dnzblgn commited on
Commit
2f9174e
Β·
verified Β·
1 Parent(s): 777f21e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -0
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import docx
4
+ import numpy as np
5
+ from sentence_transformers import SentenceTransformer
6
+ from sklearn.metrics.pairwise import cosine_similarity
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import FAISS
9
+ from langchain.chains import ConversationalRetrievalChain
10
+ from langchain.memory import ConversationBufferMemory
11
+ from langchain_community.llms import HuggingFaceEndpoint
12
+ from langchain_huggingface import HuggingFaceEmbeddings
13
+
14
+ # βœ… Use a strong sentence embedding model
15
+ semantic_model = SentenceTransformer("all-MiniLM-L6-v2")
16
+
17
+
18
+ def extract_text_from_docx(file_path):
19
+ """ βœ… Extracts normal text & tables from a .docx file for better retrieval. """
20
+ doc = docx.Document(file_path)
21
+ extracted_text = []
22
+
23
+ for para in doc.paragraphs:
24
+ if para.text.strip():
25
+ extracted_text.append(para.text.strip())
26
+
27
+ for table in doc.tables:
28
+ extracted_text.append("πŸ“Œ Table Detected:")
29
+ for row in table.rows:
30
+ row_text = [cell.text.strip() for cell in row.cells]
31
+ if any(row_text):
32
+ extracted_text.append(" | ".join(row_text))
33
+
34
+ return "\n".join(extracted_text)
35
+
36
+
37
+ def load_documents():
38
+ """ βœ… Loads & processes documents, ensuring table data is properly extracted. """
39
+ file_paths = {
40
+ "Fastener_Types_Manual": "Fastener_Types_Manual.docx",
41
+ "Manufacturing_Expert_Manual": "Manufacturing Expert Manual.docx"
42
+ }
43
+
44
+ all_splits = []
45
+
46
+ for doc_name, file_path in file_paths.items():
47
+ if not os.path.exists(file_path):
48
+ raise FileNotFoundError(f"Document not found: {file_path}")
49
+
50
+ print(f"Extracting text from {file_path}...")
51
+ full_text = extract_text_from_docx(file_path)
52
+
53
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=200)
54
+ doc_splits = text_splitter.create_documents([full_text])
55
+
56
+ for chunk in doc_splits:
57
+ chunk.metadata = {"source": doc_name}
58
+
59
+ all_splits.extend(doc_splits)
60
+
61
+ return all_splits
62
+
63
+
64
+ def create_db(splits):
65
+ """ βœ… Creates a FAISS vector database from document splits. """
66
+ embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
67
+ vectordb = FAISS.from_documents(splits, embeddings)
68
+ return vectordb
69
+
70
+
71
+ def retrieve_documents(query, retriever, embeddings):
72
+ """ βœ… Retrieves the most relevant documents & filters out low-relevance ones. """
73
+ query_embedding = np.array(embeddings.embed_query(query)).reshape(1, -1)
74
+ results = retriever.invoke(query)
75
+
76
+ if not results:
77
+ return []
78
+
79
+ doc_embeddings = np.array([embeddings.embed_query(doc.page_content) for doc in results])
80
+ similarity_scores = cosine_similarity(query_embedding, doc_embeddings)[0] # βœ… Proper cosine similarity
81
+
82
+ MIN_SIMILARITY = 0.5 # πŸ”₯ Increased threshold to improve relevance
83
+ filtered_results = [(doc, sim) for doc, sim in zip(results, similarity_scores) if sim >= MIN_SIMILARITY]
84
+
85
+ # βœ… Debugging log
86
+ print(f"πŸ” Query: {query}")
87
+ print(f"πŸ“„ Retrieved Docs (before filtering): {[(doc.metadata.get('source', 'Unknown'), sim) for doc, sim in zip(results, similarity_scores)]}")
88
+ print(f"βœ… Filtered Docs (after threshold {MIN_SIMILARITY}): {[(doc.metadata.get('source', 'Unknown'), sim) for doc, sim in filtered_results]}")
89
+
90
+ return [doc for doc, _ in filtered_results] if filtered_results else []
91
+
92
+
93
+ def validate_query_semantically(query, retrieved_docs):
94
+ """ βœ… Ensures the query meaning is covered in the retrieved documents. """
95
+ if not retrieved_docs:
96
+ return False
97
+
98
+ combined_text = " ".join([doc.page_content for doc in retrieved_docs])
99
+ query_embedding = semantic_model.encode(query, normalize_embeddings=True)
100
+ doc_embedding = semantic_model.encode(combined_text, normalize_embeddings=True)
101
+
102
+ similarity_score = np.dot(query_embedding, doc_embedding) # βœ… Cosine similarity already normalized
103
+
104
+ print(f"πŸ” Semantic Similarity Score: {similarity_score}")
105
+
106
+ return similarity_score >= 0.4 # πŸ”₯ Stricter threshold to ensure correctness
107
+
108
+
109
+ def handle_query(query, history, retriever, qa_chain, embeddings):
110
+ """ βœ… Handles user queries & prevents hallucination. """
111
+ retrieved_docs = retrieve_documents(query, retriever, embeddings)
112
+
113
+ if not retrieved_docs or not validate_query_semantically(query, retrieved_docs):
114
+ return history + [(query, "I couldn't find any relevant information.")], ""
115
+
116
+ response = qa_chain.invoke({"question": query, "chat_history": history})
117
+ assistant_response = response['answer'].strip()
118
+
119
+ # βœ… Final hallucination check
120
+ if not validate_query_semantically(query, retrieved_docs):
121
+ assistant_response = "I couldn't find any relevant information."
122
+
123
+ assistant_response += f"\n\nπŸ“„ **Source:** {', '.join(set(doc.metadata.get('source', 'Unknown') for doc in retrieved_docs))}"
124
+
125
+ # βœ… Debugging logs
126
+ print(f"πŸ€– LLM Response: {assistant_response[:300]}") # βœ… Limit output for debugging
127
+
128
+ history.append((query, assistant_response))
129
+ return history, ""
130
+
131
+
132
+ def initialize_chatbot(vector_db):
133
+ """ βœ… Initializes chatbot with improved retrieval & processing. """
134
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True, output_key='answer')
135
+
136
+ embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
137
+
138
+ retriever = vector_db.as_retriever(search_kwargs={"k": 5, "search_type": "similarity"})
139
+
140
+ system_prompt = """You are an AI assistant that answers questions **ONLY based on the provided documents**.
141
+ - **If no relevant documents are retrieved, respond with: "I couldn't find any relevant information."**
142
+ - **If the meaning of the query does not match the retrieved documents, say "I couldn't find any relevant information."**
143
+ - **Do NOT attempt to answer from general knowledge.**
144
+ """
145
+
146
+ llm = HuggingFaceEndpoint(
147
+ repo_id="mistralai/Mistral-7B-Instruct-v0.2",
148
+ huggingfacehub_api_token=os.environ.get("Another"),
149
+ temperature=0.1,
150
+ max_new_tokens=400,
151
+ task="text-generation",
152
+ system_prompt=system_prompt
153
+ )
154
+
155
+ qa_chain = ConversationalRetrievalChain.from_llm(
156
+ llm=llm,
157
+ retriever=retriever,
158
+ memory=memory,
159
+ return_source_documents=True,
160
+ verbose=False
161
+ )
162
+
163
+ return retriever, qa_chain, embeddings
164
+
165
+
166
+ def demo():
167
+ """ βœ… Starts the chatbot application using Gradio. """
168
+ retriever, qa_chain, embeddings = initialize_chatbot(create_db(load_documents()))
169
+
170
+ with gr.Blocks() as app:
171
+ gr.Markdown("### πŸ€– **Fastener Agent** πŸ“š")
172
+ chatbot = gr.Chatbot()
173
+ query_input = gr.Textbox(label="Ask me a question")
174
+ query_btn = gr.Button("Ask")
175
+
176
+ def user_query_handler(query, history):
177
+ return handle_query(query, history, retriever, qa_chain, embeddings)
178
+
179
+ query_btn.click(user_query_handler, inputs=[query_input, chatbot], outputs=[chatbot, query_input])
180
+ query_input.submit(user_query_handler, inputs=[query_input, chatbot], outputs=[chatbot, query_input])
181
+
182
+ app.launch()
183
+
184
+
185
+ if __name__ == "__main__":
186
+ demo()