-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqa_engine.py
More file actions
424 lines (332 loc) · 10.3 KB
/
qa_engine.py
File metadata and controls
424 lines (332 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# import faiss
# import pickle
# import numpy as np
# import re
# import os
# from sentence_transformers import SentenceTransformer
# import ollama
# # -------------------------------
# # Intent keywords
# # -------------------------------
# SUMMARY_KEYWORDS = [
# "what is inside",
# "overview",
# "summary",
# "about this pdf",
# "what does this pdf contain"
# ]
# PAGE_KEYWORDS = [
# "explain page",
# "describe page",
# "what is on page"
# ]
# # -------------------------------
# # Load embedding model once
# # -------------------------------
# model = SentenceTransformer("all-MiniLM-L6-v2")
# # -------------------------------
# # Utility: Load metadata safely
# # -------------------------------
# def load_meta(pdf):
# meta_path = f"data/faiss_indexes/{pdf}.meta"
# if not os.path.exists(meta_path):
# return None
# with open(meta_path, "rb") as f:
# return pickle.load(f)
# # -------------------------------
# # PDF Summary Function
# # -------------------------------
# def summarize_pdfs(selected_pdfs):
# all_text = []
# for pdf in selected_pdfs:
# meta = load_meta(pdf)
# if not meta:
# continue
# for c in meta:
# all_text.append(c.get("text", ""))
# if not all_text:
# return "❌ No content available to summarize."
# combined_text = "\n".join(all_text[:3000])
# prompt = f"""
# Summarize the following PDF content clearly and briefly.
# Do NOT add information outside the document.
# Content:
# {combined_text}
# """
# response = ollama.chat(
# model="phi",
# messages=[{"role": "user", "content": prompt}]
# )
# return response["message"]["content"]
# # -------------------------------
# # Page-wise Explanation
# # -------------------------------
# def explain_page(page_number, selected_pdfs):
# page_text = []
# for pdf in selected_pdfs:
# meta = load_meta(pdf)
# if not meta:
# continue
# for c in meta:
# if c.get("page") == page_number:
# page_text.append(c.get("text", ""))
# if not page_text:
# return f"❌ No content found on page {page_number}."
# combined_text = "\n".join(page_text[:3000])
# prompt = f"""
# Explain the following page content clearly and in simple terms:
# {combined_text}
# """
# response = ollama.chat(
# model="phi",
# messages=[{"role": "user", "content": prompt}]
# )
# return response["message"]["content"]
# # -------------------------------
# # Main Query Function
# # -------------------------------
# def query_pdfs(question, selected_pdfs, k=4):
# q_lower = question.lower()
# # 🔹 PAGE MODE
# if any(key in q_lower for key in PAGE_KEYWORDS):
# page_nums = re.findall(r"\d+", q_lower)
# if page_nums:
# return explain_page(int(page_nums[0]), selected_pdfs)
# # 🔹 SUMMARY MODE
# if any(key in q_lower for key in SUMMARY_KEYWORDS):
# return summarize_pdfs(selected_pdfs)
# # 🔹 NORMAL QA MODE (FAISS)
# all_chunks = []
# q_emb = model.encode(
# [question],
# normalize_embeddings=True
# ).astype("float32")
# missing = []
# for pdf in selected_pdfs:
# index_path = f"data/faiss_indexes/{pdf}.index"
# meta_path = f"data/faiss_indexes/{pdf}.meta"
# if not os.path.exists(index_path) or not os.path.exists(meta_path):
# missing.append(pdf)
# continue
# index = faiss.read_index(index_path)
# meta = load_meta(pdf)
# if not meta:
# continue
# D, I = index.search(q_emb, k)
# for idx in I[0]:
# if idx < len(meta):
# all_chunks.append(meta[idx])
# if missing:
# return (
# "❌ Some selected PDFs are not indexed.\n"
# f"Missing indexes: {', '.join(missing)}\n"
# "Please re-upload them in the app."
# )
# if not all_chunks:
# return "❌ Answer not found in selected PDFs."
# # -------------------------------
# # Build context with metadata
# # -------------------------------
# context = "\n".join(
# f"(PDF: {c.get('pdf_name','Unknown')} | "
# f"Section: {c.get('section','Unknown')} | "
# f"Page {c.get('page','?')}): {c.get('text','')}"
# for c in all_chunks
# )
# prompt = f"""
# Answer ONLY using the information below.
# Do NOT add external knowledge.
# Context:
# {context}
# Question:
# {question}
# """
# response = ollama.chat(
# model="phi",
# messages=[{"role": "user", "content": prompt}]
# )
# answer = response["message"]["content"]
# # -------------------------------
# # Confidence Score
# # -------------------------------
# confidence = min(95, 50 + len(set(c["page"] for c in all_chunks)) * 8)
# # -------------------------------
# # Build citation section
# # -------------------------------
# sources = sorted({
# f"{c.get('pdf_name','Unknown')} | "
# f"{c.get('section','Unknown')} | "
# f"Page {c.get('page','?')}"
# for c in all_chunks
# })
# citation_text = "\n".join(f"• {s}" for s in sources)
# return f"""{answer}
# 📊 Confidence: {confidence}%
# 📌 Sources:
# {citation_text}
# """
# using groq instead of ollama
import faiss
import pickle
import numpy as np
import re
import os
from sentence_transformers import SentenceTransformer
from groq import Groq
from dotenv import load_dotenv
# -------------------------------
# Load environment variables
# -------------------------------
load_dotenv()
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
# -------------------------------
# Intent keywords
# -------------------------------
SUMMARY_KEYWORDS = [
"what is inside",
"overview",
"summary",
"about this pdf",
"what does this pdf contain"
]
PAGE_KEYWORDS = [
"explain page",
"describe page",
"what is on page"
]
# -------------------------------
# Load embedding model
# -------------------------------
model = SentenceTransformer("all-MiniLM-L6-v2")
# -------------------------------
# Utility: Load metadata safely
# -------------------------------
def load_meta(pdf):
path = f"data/faiss_indexes/{pdf}.meta"
if not os.path.exists(path):
return None
with open(path, "rb") as f:
return pickle.load(f)
# -------------------------------
# LLM Call (Groq-safe)
# -------------------------------
def call_llm(prompt):
if not prompt or len(prompt.strip()) < 30:
return "❌ Not enough content to answer."
response = client.chat.completions.create(
model="llama-3.1-8b-instant", # ✅ UPDATED MODEL
messages=[
{
"role": "system",
"content": "You are a helpful AI assistant. Answer strictly using the given context."
},
{
"role": "user",
"content": prompt
}
],
temperature=0.2,
max_tokens=512
)
return response.choices[0].message.content.strip()
# -------------------------------
# PDF Summary
# -------------------------------
def summarize_pdfs(selected_pdfs):
all_text = []
for pdf in selected_pdfs:
meta = load_meta(pdf)
if not meta:
continue
for c in meta:
all_text.append(c.get("text", ""))
if not all_text:
return "❌ No content available to summarize."
combined_text = "\n".join(all_text)[:4000]
prompt = f"""
Summarize the following document clearly and briefly.
Do NOT add information outside the document.
Content:
{combined_text}
"""
return call_llm(prompt)
# -------------------------------
# Page Explanation
# -------------------------------
def explain_page(page_number, selected_pdfs):
page_text = []
for pdf in selected_pdfs:
meta = load_meta(pdf)
if not meta:
continue
for c in meta:
if c.get("page") == page_number:
page_text.append(c.get("text", ""))
if not page_text:
return f"❌ No content found on page {page_number}."
combined_text = "\n".join(page_text)[:4000]
prompt = f"""
Explain the following page content in simple terms:
{combined_text}
"""
return call_llm(prompt)
# -------------------------------
# Main Query Function
# -------------------------------
def query_pdfs(question, selected_pdfs, k=4):
q_lower = question.lower()
# 🔹 Page intent
if any(key in q_lower for key in PAGE_KEYWORDS):
nums = re.findall(r"\d+", q_lower)
if nums:
return explain_page(int(nums[0]), selected_pdfs)
# 🔹 Summary intent
if any(key in q_lower for key in SUMMARY_KEYWORDS):
return summarize_pdfs(selected_pdfs)
# 🔹 FAISS QA
all_chunks = []
q_emb = model.encode(
[question],
normalize_embeddings=True
).astype("float32")
missing = []
for pdf in selected_pdfs:
index_path = f"data/faiss_indexes/{pdf}.index"
meta_path = f"data/faiss_indexes/{pdf}.meta"
if not os.path.exists(index_path) or not os.path.exists(meta_path):
missing.append(pdf)
continue
index = faiss.read_index(index_path)
meta = load_meta(pdf)
D, I = index.search(q_emb, k)
for idx in I[0]:
if idx < len(meta):
all_chunks.append(meta[idx])
if missing:
return f"❌ Missing indexes: {', '.join(missing)}"
if not all_chunks:
return "❌ Answer not found in selected PDFs."
context = "\n".join(
f"(PDF: {c.get('pdf_name','Unknown')} | "
f"Section: {c.get('section','Unknown')} | "
f"Page {c.get('page','?')}): {c.get('text','')}"
for c in all_chunks
)[:4000]
prompt = f"""
Answer ONLY using the information below.
Do NOT add external knowledge.
Context:
{context}
Question:
{question}
"""
answer = call_llm(prompt)
confidence = min(95, 50 + len(set(c["page"] for c in all_chunks)) * 8)
sources = sorted({
f"{c.get('pdf_name','Unknown')} | {c.get('section','Unknown')} | Page {c.get('page','?')}"
for c in all_chunks
})
return f"""{answer}
📊 Confidence: {confidence}%
📌 Sources:
""" + "\n".join(f"• {s}" for s in sources)