heerjtdev commited on
Commit
3e756d2
Β·
verified Β·
1 Parent(s): d4b3d95

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -19
app.py CHANGED
@@ -113,8 +113,145 @@
113
 
114
 
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  import gradio as gr
117
  import fitz # PyMuPDF
 
118
  from langchain_text_splitters import RecursiveCharacterTextSplitter
119
  from langchain_community.vectorstores import FAISS
120
  from langchain_huggingface import HuggingFaceEmbeddings
@@ -123,7 +260,6 @@ class VectorSystem:
123
  def __init__(self):
124
  self.vector_store = None
125
  self.embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
126
- # NEW: We keep a copy of all chunks in a list so we can access neighbors by index
127
  self.all_chunks = []
128
 
129
  def process_file(self, file_obj):
@@ -150,14 +286,12 @@ class VectorSystem:
150
  chunk_overlap=150,
151
  separators=["\n\n", "\n", ".", " ", ""]
152
  )
153
- # Store chunks in the class so we can look them up by ID later
154
  self.all_chunks = text_splitter.split_text(text)
155
 
156
  if not self.all_chunks:
157
  return "Could not extract text. Is the file empty?"
158
 
159
  # 3. Build Vector Index with ID Metadata
160
- # We attach the index ID (0, 1, 2...) to every vector
161
  metadatas = [{"id": i} for i in range(len(self.all_chunks))]
162
 
163
  self.vector_store = FAISS.from_texts(
@@ -174,30 +308,46 @@ class VectorSystem:
174
  def retrieve_evidence(self, question, student_answer):
175
  if not self.vector_store:
176
  return "⚠️ Please upload and process a file first."
177
-
178
  if not question:
179
  return "⚠️ Please enter a Question."
180
 
181
- # Lower Score = Better Match
 
182
  results = self.vector_store.similarity_search_with_score(question, k=3)
183
 
184
- output_text = "### πŸ” Expanded Context Analysis:\n"
 
 
 
185
 
186
- for i, (doc, score) in enumerate(results):
187
  chunk_id = doc.metadata['id']
188
 
189
- # Retrieve Previous and Next chunks
190
- # Logic: If it's the first chunk (ID 0), there is no 'prev', so returns empty string
191
- prev_chunk = self.all_chunks[chunk_id - 1] if chunk_id > 0 else "(Start of Text)"
192
- next_chunk = self.all_chunks[chunk_id + 1] if chunk_id < len(self.all_chunks) - 1 else "(End of Text)"
193
 
194
- output_text += f"\n#### 🎯 Match #{i+1} (Distance Score: {score:.4f})\n"
 
195
 
196
- # --- CHANGED HERE: Removed [-200:] and [:200] ---
 
 
 
197
 
198
- output_text += f"> **Preceding Context:**\n{prev_chunk}\n\n"
199
- output_text += f"> **MATCH:**\n**{doc.page_content}**\n\n"
200
- output_text += f"> **Succeeding Context:**\n{next_chunk}\n"
 
 
 
 
 
 
 
 
 
 
201
 
202
  output_text += "---\n"
203
 
@@ -208,8 +358,8 @@ system = VectorSystem()
208
 
209
  # --- Gradio UI ---
210
  with gr.Blocks(title="EduGenius Context Retriever") as demo:
211
- gr.Markdown("# πŸŽ“ EduGenius: Smart Context Retriever")
212
- gr.Markdown("Upload a Chapter. This version finds the best match AND shows you the text immediately before and after it.")
213
 
214
  with gr.Row():
215
  with gr.Column(scale=1):
@@ -220,7 +370,7 @@ with gr.Blocks(title="EduGenius Context Retriever") as demo:
220
  with gr.Column(scale=2):
221
  question_input = gr.Textbox(label="2. Question", placeholder="e.g., What causes the chemical reaction?")
222
  answer_input = gr.Textbox(label="Student Answer (Optional)", placeholder="e.g., The heat causes it...")
223
- search_btn = gr.Button("Find Context + Neighbors", variant="secondary")
224
 
225
  evidence_output = gr.Markdown(label="Relevant Text Chunks")
226
 
 
113
 
114
 
115
 
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+ # import gradio as gr
128
+ # import fitz # PyMuPDF
129
+ # from langchain_text_splitters import RecursiveCharacterTextSplitter
130
+ # from langchain_community.vectorstores import FAISS
131
+ # from langchain_huggingface import HuggingFaceEmbeddings
132
+
133
+ # class VectorSystem:
134
+ # def __init__(self):
135
+ # self.vector_store = None
136
+ # self.embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
137
+ # # NEW: We keep a copy of all chunks in a list so we can access neighbors by index
138
+ # self.all_chunks = []
139
+
140
+ # def process_file(self, file_obj):
141
+ # """Extracts text, preserves order, and builds the Vector Index"""
142
+ # if file_obj is None:
143
+ # return "No file uploaded."
144
+
145
+ # try:
146
+ # # 1. Extract Text
147
+ # text = ""
148
+ # file_path = file_obj.name
149
+
150
+ # if file_path.lower().endswith('.pdf'):
151
+ # doc = fitz.open(file_path)
152
+ # for page in doc: text += page.get_text()
153
+ # elif file_path.lower().endswith('.txt'):
154
+ # with open(file_path, 'r', encoding='utf-8') as f: text = f.read()
155
+ # else:
156
+ # return "❌ Error: Only .pdf and .txt files are supported."
157
+
158
+ # # 2. Split Text
159
+ # text_splitter = RecursiveCharacterTextSplitter(
160
+ # chunk_size=800,
161
+ # chunk_overlap=150,
162
+ # separators=["\n\n", "\n", ".", " ", ""]
163
+ # )
164
+ # # Store chunks in the class so we can look them up by ID later
165
+ # self.all_chunks = text_splitter.split_text(text)
166
+
167
+ # if not self.all_chunks:
168
+ # return "Could not extract text. Is the file empty?"
169
+
170
+ # # 3. Build Vector Index with ID Metadata
171
+ # # We attach the index ID (0, 1, 2...) to every vector
172
+ # metadatas = [{"id": i} for i in range(len(self.all_chunks))]
173
+
174
+ # self.vector_store = FAISS.from_texts(
175
+ # self.all_chunks,
176
+ # self.embeddings,
177
+ # metadatas=metadatas
178
+ # )
179
+
180
+ # return f"βœ… Success! Indexed {len(self.all_chunks)} chunks."
181
+
182
+ # except Exception as e:
183
+ # return f"Error processing file: {str(e)}"
184
+
185
+ # def retrieve_evidence(self, question, student_answer):
186
+ # if not self.vector_store:
187
+ # return "⚠️ Please upload and process a file first."
188
+
189
+ # if not question:
190
+ # return "⚠️ Please enter a Question."
191
+
192
+ # # Lower Score = Better Match
193
+ # results = self.vector_store.similarity_search_with_score(question, k=3)
194
+
195
+ # output_text = "### πŸ” Expanded Context Analysis:\n"
196
+
197
+ # for i, (doc, score) in enumerate(results):
198
+ # chunk_id = doc.metadata['id']
199
+
200
+ # # Retrieve Previous and Next chunks
201
+ # # Logic: If it's the first chunk (ID 0), there is no 'prev', so returns empty string
202
+ # prev_chunk = self.all_chunks[chunk_id - 1] if chunk_id > 0 else "(Start of Text)"
203
+ # next_chunk = self.all_chunks[chunk_id + 1] if chunk_id < len(self.all_chunks) - 1 else "(End of Text)"
204
+
205
+ # output_text += f"\n#### 🎯 Match #{i+1} (Distance Score: {score:.4f})\n"
206
+
207
+ # # --- CHANGED HERE: Removed [-200:] and [:200] ---
208
+
209
+ # output_text += f"> **Preceding Context:**\n{prev_chunk}\n\n"
210
+ # output_text += f"> **MATCH:**\n**{doc.page_content}**\n\n"
211
+ # output_text += f"> **Succeeding Context:**\n{next_chunk}\n"
212
+
213
+ # output_text += "---\n"
214
+
215
+ # return output_text
216
+
217
+ # # Initialize System
218
+ # system = VectorSystem()
219
+
220
+ # # --- Gradio UI ---
221
+ # with gr.Blocks(title="EduGenius Context Retriever") as demo:
222
+ # gr.Markdown("# πŸŽ“ EduGenius: Smart Context Retriever")
223
+ # gr.Markdown("Upload a Chapter. This version finds the best match AND shows you the text immediately before and after it.")
224
+
225
+ # with gr.Row():
226
+ # with gr.Column(scale=1):
227
+ # pdf_input = gr.File(label="1. Upload File (PDF or TXT)", file_types=[".pdf", ".txt"])
228
+ # upload_btn = gr.Button("Process File", variant="primary")
229
+ # upload_status = gr.Textbox(label="Status", interactive=False)
230
+
231
+ # with gr.Column(scale=2):
232
+ # question_input = gr.Textbox(label="2. Question", placeholder="e.g., What causes the chemical reaction?")
233
+ # answer_input = gr.Textbox(label="Student Answer (Optional)", placeholder="e.g., The heat causes it...")
234
+ # search_btn = gr.Button("Find Context + Neighbors", variant="secondary")
235
+
236
+ # evidence_output = gr.Markdown(label="Relevant Text Chunks")
237
+
238
+ # upload_btn.click(fn=system.process_file, inputs=[pdf_input], outputs=[upload_status])
239
+ # search_btn.click(fn=system.retrieve_evidence, inputs=[question_input, answer_input], outputs=[evidence_output])
240
+
241
+ # if __name__ == "__main__":
242
+ # demo.launch()
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
  import gradio as gr
253
  import fitz # PyMuPDF
254
+ import numpy as np
255
  from langchain_text_splitters import RecursiveCharacterTextSplitter
256
  from langchain_community.vectorstores import FAISS
257
  from langchain_huggingface import HuggingFaceEmbeddings
 
260
  def __init__(self):
261
  self.vector_store = None
262
  self.embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
 
263
  self.all_chunks = []
264
 
265
  def process_file(self, file_obj):
 
286
  chunk_overlap=150,
287
  separators=["\n\n", "\n", ".", " ", ""]
288
  )
 
289
  self.all_chunks = text_splitter.split_text(text)
290
 
291
  if not self.all_chunks:
292
  return "Could not extract text. Is the file empty?"
293
 
294
  # 3. Build Vector Index with ID Metadata
 
295
  metadatas = [{"id": i} for i in range(len(self.all_chunks))]
296
 
297
  self.vector_store = FAISS.from_texts(
 
308
  def retrieve_evidence(self, question, student_answer):
309
  if not self.vector_store:
310
  return "⚠️ Please upload and process a file first."
 
311
  if not question:
312
  return "⚠️ Please enter a Question."
313
 
314
+ # 1. Get Initial Results (Core Matches)
315
+ # FAISS returns L2 distance (Lower is better)
316
  results = self.vector_store.similarity_search_with_score(question, k=3)
317
 
318
+ # We need the vector for the QUESTION to do our own math later
319
+ q_vector = np.array(self.embeddings.embed_query(question))
320
+
321
+ output_text = "### πŸ” Smart Context Analysis:\n"
322
 
323
+ for i, (doc, core_score) in enumerate(results):
324
  chunk_id = doc.metadata['id']
325
 
326
+ # 2. Identify Neighbors
327
+ prev_chunk = self.all_chunks[chunk_id - 1] if chunk_id > 0 else ""
328
+ next_chunk = self.all_chunks[chunk_id + 1] if chunk_id < len(self.all_chunks) - 1 else ""
 
329
 
330
+ # 3. Create the "Super Chunk" (Prev + Core + Next)
331
+ super_chunk_text = f"{prev_chunk} {doc.page_content} {next_chunk}"
332
 
333
+ # 4. Calculate "Super Score" (Re-embedding on the fly)
334
+ # We embed the Super Chunk and measure distance to Question
335
+ super_vector = np.array(self.embeddings.embed_query(super_chunk_text))
336
+ super_score = np.linalg.norm(q_vector - super_vector) # Euclidean Distance
337
 
338
+ output_text += f"\n#### 🎯 Match #{i+1}\n"
339
+
340
+ # 5. The Logic Test: Does Context Improve the Score?
341
+ # Remember: LOWER score is BETTER (closer distance)
342
+
343
+ if super_score < core_score:
344
+ # CASE A: Context Helps! (Distance Reduced)
345
+ output_text += f"**βœ… Context Added:** The surrounding text made the match stronger (Score improved from {core_score:.3f} to {super_score:.3f}).\n\n"
346
+ output_text += f"> {prev_chunk} **{doc.page_content}** {next_chunk}\n"
347
+ else:
348
+ # CASE B: Context Dilutes! (Distance Increased or Same)
349
+ output_text += f"**⏹️ Context Ignored:** Surrounding text was irrelevant or noisy (Score worsened from {core_score:.3f} to {super_score:.3f}). Showing Core Match only.\n\n"
350
+ output_text += f"> **{doc.page_content}**\n"
351
 
352
  output_text += "---\n"
353
 
 
358
 
359
  # --- Gradio UI ---
360
  with gr.Blocks(title="EduGenius Context Retriever") as demo:
361
+ gr.Markdown("# πŸŽ“ EduGenius: Intelligent Context Retriever")
362
+ gr.Markdown("Upload a Chapter. This system intelligently decides if it needs to read the surrounding paragraphs to answer your question.")
363
 
364
  with gr.Row():
365
  with gr.Column(scale=1):
 
370
  with gr.Column(scale=2):
371
  question_input = gr.Textbox(label="2. Question", placeholder="e.g., What causes the chemical reaction?")
372
  answer_input = gr.Textbox(label="Student Answer (Optional)", placeholder="e.g., The heat causes it...")
373
+ search_btn = gr.Button("Find Evidence", variant="secondary")
374
 
375
  evidence_output = gr.Markdown(label="Relevant Text Chunks")
376