Update app.py
Browse files
app.py
CHANGED
|
@@ -124,134 +124,8 @@
|
|
| 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,6 +134,7 @@ class VectorSystem:
|
|
| 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,12 +161,14 @@ class VectorSystem:
|
|
| 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,46 +185,30 @@ class VectorSystem:
|
|
| 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 |
-
#
|
| 315 |
-
# FAISS returns L2 distance (Lower is better)
|
| 316 |
results = self.vector_store.similarity_search_with_score(question, k=3)
|
| 317 |
|
| 318 |
-
|
| 319 |
-
q_vector = np.array(self.embeddings.embed_query(question))
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
for i, (doc, core_score) in enumerate(results):
|
| 324 |
chunk_id = doc.metadata['id']
|
| 325 |
|
| 326 |
-
#
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
# 3. Create the "Super Chunk" (Prev + Core + Next)
|
| 331 |
-
super_chunk_text = f"{prev_chunk} {doc.page_content} {next_chunk}"
|
| 332 |
|
| 333 |
-
|
| 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 |
-
|
| 339 |
|
| 340 |
-
|
| 341 |
-
|
| 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,8 +219,8 @@ system = VectorSystem()
|
|
| 358 |
|
| 359 |
# --- Gradio UI ---
|
| 360 |
with gr.Blocks(title="EduGenius Context Retriever") as demo:
|
| 361 |
-
gr.Markdown("# π EduGenius:
|
| 362 |
-
gr.Markdown("Upload a Chapter. This
|
| 363 |
|
| 364 |
with gr.Row():
|
| 365 |
with gr.Column(scale=1):
|
|
@@ -370,7 +231,7 @@ with gr.Blocks(title="EduGenius Context Retriever") as demo:
|
|
| 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
|
| 374 |
|
| 375 |
evidence_output = gr.Markdown(label="Relevant Text Chunks")
|
| 376 |
|
|
@@ -378,4 +239,143 @@ with gr.Blocks(title="EduGenius Context Retriever") as demo:
|
|
| 378 |
search_btn.click(fn=system.retrieve_evidence, inputs=[question_input, answer_input], outputs=[evidence_output])
|
| 379 |
|
| 380 |
if __name__ == "__main__":
|
| 381 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
|
|
|
| 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):
|
|
|
|
| 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(
|
|
|
|
| 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 |
|
|
|
|
| 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):
|
|
|
|
| 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 |
|
|
|
|
| 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
|
| 258 |
+
|
| 259 |
+
# class VectorSystem:
|
| 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):
|
| 266 |
+
# """Extracts text, preserves order, and builds the Vector Index"""
|
| 267 |
+
# if file_obj is None:
|
| 268 |
+
# return "No file uploaded."
|
| 269 |
+
|
| 270 |
+
# try:
|
| 271 |
+
# # 1. Extract Text
|
| 272 |
+
# text = ""
|
| 273 |
+
# file_path = file_obj.name
|
| 274 |
+
|
| 275 |
+
# if file_path.lower().endswith('.pdf'):
|
| 276 |
+
# doc = fitz.open(file_path)
|
| 277 |
+
# for page in doc: text += page.get_text()
|
| 278 |
+
# elif file_path.lower().endswith('.txt'):
|
| 279 |
+
# with open(file_path, 'r', encoding='utf-8') as f: text = f.read()
|
| 280 |
+
# else:
|
| 281 |
+
# return "β Error: Only .pdf and .txt files are supported."
|
| 282 |
+
|
| 283 |
+
# # 2. Split Text
|
| 284 |
+
# text_splitter = RecursiveCharacterTextSplitter(
|
| 285 |
+
# chunk_size=800,
|
| 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(
|
| 298 |
+
# self.all_chunks,
|
| 299 |
+
# self.embeddings,
|
| 300 |
+
# metadatas=metadatas
|
| 301 |
+
# )
|
| 302 |
+
|
| 303 |
+
# return f"β
Success! Indexed {len(self.all_chunks)} chunks."
|
| 304 |
+
|
| 305 |
+
# except Exception as e:
|
| 306 |
+
# return f"Error processing file: {str(e)}"
|
| 307 |
+
|
| 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 |
+
|
| 354 |
+
# return output_text
|
| 355 |
+
|
| 356 |
+
# # Initialize System
|
| 357 |
+
# system = VectorSystem()
|
| 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):
|
| 366 |
+
# pdf_input = gr.File(label="1. Upload File (PDF or TXT)", file_types=[".pdf", ".txt"])
|
| 367 |
+
# upload_btn = gr.Button("Process File", variant="primary")
|
| 368 |
+
# upload_status = gr.Textbox(label="Status", interactive=False)
|
| 369 |
+
|
| 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 |
+
|
| 377 |
+
# upload_btn.click(fn=system.process_file, inputs=[pdf_input], outputs=[upload_status])
|
| 378 |
+
# search_btn.click(fn=system.retrieve_evidence, inputs=[question_input, answer_input], outputs=[evidence_output])
|
| 379 |
+
|
| 380 |
+
# if __name__ == "__main__":
|
| 381 |
+
# demo.launch()
|