Repository navigation
Expand file tree
/
Copy pathRAG_multi_pdf.py
More file actions
1009 lines (743 loc) · 22 KB
/
Copy pathRAG_multi_pdf.py
File metadata and controls
1009 lines (743 loc) · 22 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# //RETRIEVLAL CODE //
# PDF LOADER DATA
import os
import fitz
import requests
documents = []
folder_path = r"C:\Users\Madhav\OneDrive\PROJECTS\Python_Project1\RAG_Implementation\pdfs"
for filename in os.listdir(folder_path):
if filename.endswith(".pdf"):
pdf_path = os.path.join(folder_path ,filename)
pdf = fitz.open(pdf_path)
for page_num,page in enumerate(pdf):
documents.append({
"text" : page.get_text(),
"page" : page_num + 1,
"source" : filename
})
pdf.close()
# document retrieval
document_texts = {}
for doc in documents:
source = doc["source"]
if source not in document_texts:
document_texts[source] = ""
document_texts[source] += "\n" + doc["text"]
# # create document name list
doc_names =sorted(
document_texts.keys()
)
#################################################
# DOCUMENT SUMMARIES
#################################################
def generate_document_summary(text):
prompt = f"""
You are a document understanding assistant.
Summarize the following document in about 100-150 words.
Focus on:
- What type of document it is
- Main topics
- Important entities (people, projects, organizations, technologies)
- Purpose of the document
Do NOT copy large sections.
Document:
{text[:5000]}
"""
try:
response = requests.post(
"http://localhost:11434/api/generate",
json={
"model": "llama3",
"prompt": prompt,
"stream": False
},
timeout = 120
)
response.raise_for_status()
result = response.json()
except Exception as e:
print(f"Error generating summary : {e}")
return text[:1500]
if "response" not in result:
print(result)
return text[:1500]
return result["response"].strip()
document_summaries = {}
for source, text in document_texts.items():
print(f"\nGenerating summary for {source}...")
summary = generate_document_summary(text)
document_summaries[source] = summary
#FOR DEBUGGING PURPOSES ONLY
print("\nDOCUMENT SUMMARIES\n")
for source, summary in document_summaries.items():
print("-" * 50)
print(source)
print(summary)
# pages = []
# OLD and basic method of chunking
# CREATING CHUNKS
# fixed chunking method
# def chunk_text(text,chunk_size =400,overlap = 100):
# return [
# text[i:i+chunk_size]
# for i in range(0,len(text),chunk_size - overlap)
# ]
# RECURSIVE CHUNKING
from langchain_text_splitters import RecursiveCharacterTextSplitter
parent_splitter = RecursiveCharacterTextSplitter(
chunk_size =2000,
chunk_overlap =200)
child_splitter = RecursiveCharacterTextSplitter(
chunk_size = 500,
chunk_overlap =100)
parent_chunks =[]
parent_id = 0
# generate parent chunks
for doc in documents:
parents = parent_splitter.split_text(doc["text"])
for parent in parents:
parent_chunks.append({
"id" : parent_id,
"text": parent,
"page": doc["page"],
"source" : doc["source"]
})
parent_id += 1
child_chunks = []
for parent in parent_chunks:
children =child_splitter.split_text(parent["text"])
for child in children:
child_chunks.append({
"text" : child,
"parent_id" : parent["id"],
"source" : parent["source"],
"page":parent["page"]
})
# generate emebddings
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
# only child chunks go to FAISS
embeddings = model.encode(
[chunk["text"] for chunk in child_chunks]
)
# # document embeddings
doc_embeddings = model.encode(
list(document_summaries.values())
)
import numpy as np
import faiss
# convert to numpy
embeddings = np.array(embeddings , dtype=np.float32)
doc_embeddings = np.array(doc_embeddings,
dtype = np.float32)
# # build BM25 index
from rank_bm25 import BM25Okapi
tokenized_chunks = [
item["text"].lower().split()
for item in child_chunks
]
#keyword search index
bm25 =BM25Okapi(tokenized_chunks)
# BRUTE FORCE METHOD
# storing the chunks and embeddings
# vector_store = {
# "chunks" : chunks,
# "embeddings" : embeddings
# }
faiss.normalize_L2(embeddings)
faiss.normalize_L2(doc_embeddings)
dimension = embeddings.shape[1]
# this FAISS returns cosine similarity scores
index= faiss.IndexFlatIP(dimension)
index.add(embeddings)
# document FAISS Index
doc_dimension = doc_embeddings.shape[1]
doc_index = faiss.IndexFlatIP(doc_dimension)
doc_index.add(doc_embeddings)
# debugging code
print(f"Total PDFs indexed: {len(doc_names)}")
print(f"Total chunks indexed: {len(child_chunks)}")
# lets generate query
def generate_queries(question):
prompt = f"""
You are a search query generator.
The user's question belongs to a Retrieval-Augmented Generation system.
Generate exactly FOUR alternative search queries.
Rules:
- Preserve the original meaning.
- Do NOT answer the question.
- Do NOT explain anything.
- Do NOT invent new topics.
- Do NOT output numbering.
- Do NOT output headings.
- One query per line.
- Keep each query under 12 words.
Question:
{question}
"""
try:
response = requests.post(
"http://localhost:11434/api/generate",
json={
"model":"llama3",
"prompt":prompt,
"stream":False
},
timeout = 120
)
response.raise_for_status()
result = response.json()
except Exception as e:
print(f"Error generating queries: {e}")
return [question]
if "response" not in result:
print(result)
return [question]
generated_text = result["response"]
raw_queries = generated_text.split("\n")
queries = []
for q in raw_queries:
q = q.strip()
if not q:
continue
if q.lower().startswith("here are"):
continue
if q.lower().startswith("sure"):
continue
if q.lower().startswith("certainly"):
continue
for i in range(1, 10):
if q.startswith(f"{i}."):
q = q[len(f"{i}."):].strip()
if q not in queries:
queries.append(q)
queries.insert(0, question)
queries = list(dict.fromkeys(queries))
print("\nGenerated Queries:")
for q in queries:
print("-", q)
return queries
# HyDE generator
def generate_hyde(query):
prompt = f"""
You are generating a hypothetical document for semantic retrieval.
Write ONE short paragraph (50–80 words) that could plausibly appear inside a document containing the answer.
Rules:
- Do NOT answer with certainty.
- Use generic wording whenever information is unknown.
- Do NOT invent names, numbers, dates, organizations, or locations.
- Do NOT include explanations or opinions.
- Write only the hypothetical document.
Question:
{query}
Hypothetical Answer:
"""
try:
response = requests.post(
"http://localhost:11434/api/generate",
json={
"model":"llama3",
"prompt":prompt,
"stream":False
},
timeout =120
)
response.raise_for_status()
result = response.json()
except Exception as e:
print(f"error generating HyDE for query: {e}")
return query
if "response" not in result:
print(result)
return query
return result["response"].strip()
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
def route_query(query):
q=query.lower()
# resume related questions
if any(word in q for word in [
"cgpa",
"percentage",
"certification",
"skill",
"certificate",
"experience",
"education",
"madhav",
"resume"
]):
return ["resume (4).pdf"]
# pdl report questions
elif any(word in q for word in[
"pdl",
"project",
"group member",
"esp32"
]):
return ["PDL_REPORT.pdf"]
# Python Lab questions
elif any(word in q for word in [
"experiment",
"python",
"grade program"
]):
return ["Python 3rd Semester Continued.pdf"]
# Curriculum / syllabus questions
elif any(word in q for word in [
"ece",
"semester",
"subject",
"curriculum",
"syllabus"
]):
return ["z.pdf"]
# search all docs
return None
def retrieve_documents(
query,
top_docs=3
):
hyde_document = generate_hyde(query)
query_embedding = model.encode([hyde_document])
query_embedding = np.array(
query_embedding,
dtype = np.float32
)
faiss.normalize_L2(query_embedding)
scores,indices = doc_index.search(query_embedding ,
top_docs)
print("\nTop Documents: ")
for score,idx in zip(scores[0],
indices[0]):
print(
f"{doc_names[idx]} (score={score:.4f})"
)
return [
doc_names[i]
for i in indices[0]
]
from collections import defaultdict
#Retrieval part of bm25
def bm25_retrieve(
query,
top_k = 20
):
query_tokens=(
query.lower().split()
)
scores = bm25.get_scores(
query_tokens
)
top_indices = (
np.argsort(scores)
[-top_k:]
[::-1]
)
return top_indices
# retrieval part of Hybrid Search ( bm25 + faiss)
def retrieve_single_query(semantic_query,
lexical_query,
top_k = 20,
sources = None):
query_embedding = model.encode([
semantic_query])
query_embedding = np.array(
query_embedding,
dtype=np.float32
)
faiss.normalize_L2(query_embedding)
# document filtering
candidate_chunk_indices = {
i
for i, chunk in enumerate(child_chunks)
if sources is None or chunk["source"] in sources
}
# faiss retrieval
faiss_scores, faiss_indices = index.search(
query_embedding,
100
)
filtered_faiss = []
for idx in faiss_indices[0]:
if idx in candidate_chunk_indices:
filtered_faiss.append(idx)
filtered_faiss = filtered_faiss[:top_k]
# BM25 retrieval
bm_indices = [
idx
for idx in bm25_retrieve(lexical_query, top_k * 3)
if idx in candidate_chunk_indices
][:top_k]
# hybrid merge
# reciprocal rank fusion
# rrf_scores = defaultdict(float)
# k=60
# for rank,idx in enumerate(filtered_faiss):
# rrf_scores[idx] += (
# 1/(k+rank+1)
# )
# for rank,idx in enumerate(bm_indices):
# rrf_scores[idx] += (
# 1/(k+rank+1)
# )
# candidate_indices = sorted(
# rrf_scores.keys(),
# key =lambda x : rrf_scores[x],
# reverse=True
# )
# candidate_indices =candidate_indices[:20]
# if len(candidate_indices) == 0:
# return None
# print("\nRRF Ranking: ")
# for idx in candidate_indices[:10]:
# print(
# chunk_data[idx]['source'],
# chunk_data[idx]["page"],
# f"{rrf_scores[idx]:.5f}"
# )
return {
"faiss": filtered_faiss,
"bm25": bm_indices
}
# multi query retrieval
def multi_query_retrieve(
question,
top_k = 10,
sources = None
):
queries= generate_queries(question)
hyde_document = generate_hyde(question)
print("\nHyDE Document:\n")
print(hyde_document)
# all_chunks=[]
# for q in queries:
# chunks = retrieve_single_query(q,
# top_k=top_k,
# sources = sources)
# if chunks :
# all_chunks.extend(chunks)
# all_chunks = remove_duplicates(all_chunks)
# return all_chunks
rrf_scores = defaultdict(float)
k = 60
for q in queries:
result = retrieve_single_query(
semantic_query=hyde_document,
lexical_query=q,
top_k=top_k,
sources=sources
)
if not result:
continue
for rank, idx in enumerate(result["faiss"]):
rrf_scores[idx] += 1/(k+rank+1)
for rank, idx in enumerate(result["bm25"]):
rrf_scores[idx] += 1/(k+rank+1)
if len(rrf_scores) == 0:
return None
candidate_indices = sorted(rrf_scores.keys(),
key =lambda x :rrf_scores[x],
reverse = True)
candidate_indices = candidate_indices[:30]
print("\nFinal Multi Query RRF Ranking:")
for idx in candidate_indices[:10]:
print(
child_chunks[idx]["source"],
child_chunks[idx]["page"],
rrf_scores[idx]
)
retrieved_children = [
child_chunks[idx]
for idx in candidate_indices
]
retrieved_children = remove_duplicates(retrieved_children)
return retrieved_children
# remove duplicate chunks
def remove_duplicates(chunks):
seen =set()
unique_chunks =[]
for chunk in chunks:
key =(
chunk["source"],
chunk["page"],
chunk["text"]
)
if key not in seen:
seen.add(key)
unique_chunks.append(chunk)
return unique_chunks
# Contextual Compression of Chunks
from langchain_text_splitters import RecursiveCharacterTextSplitter
compression_splitter = RecursiveCharacterTextSplitter(
chunk_size=300,
chunk_overlap=50
)
def split_parent_chunks(parent_chunks):
mini_chunks = []
for chunk in parent_chunks:
parts = compression_splitter.split_text(
chunk["text"]
)
for part in parts:
mini_chunks.append({
"text": part,
"source": chunk["source"],
"page": chunk["page"]
})
return mini_chunks
def compress_context(question, mini_chunks, top_k=5):
# Encode the question
question_embedding = model.encode([question])
question_embedding = np.array(
question_embedding,
dtype=np.float32
)
faiss.normalize_L2(question_embedding)
# Encode every mini chunk
mini_embeddings = model.encode(
[chunk["text"] for chunk in mini_chunks]
)
mini_embeddings = np.array(
mini_embeddings,
dtype=np.float32
)
faiss.normalize_L2(mini_embeddings)
# Cosine similarity
scores = np.dot(
mini_embeddings,
question_embedding.T
).flatten()
# Sort by similarity
top_indices = np.argsort(scores)[::-1][:top_k]
compressed_chunks = [
mini_chunks[i]
for i in top_indices
]
return compressed_chunks
# llm based context filtering
def llm_context_filter(question, compressed_chunks):
context = "\n\n".join(
chunk["text"]
for chunk in compressed_chunks
)
prompt = f"""
You are an information filtering system used inside a Retrieval-Augmented Generation (RAG) pipeline.
Question:
{question}
Context:
{context}
Your job is to FILTER the retrieved context.
You are NOT writing a summary.
You are NOT answering the question.
Imagine you are editing a document with a red pen.
Delete irrelevant lines.
Keep relevant lines exactly as they appear.
Rules:
- Copy useful sentences exactly.
- Delete irrelevant sentences.
- Never rewrite sentences.
- Never paraphrase.
- Never summarize.
- Never merge two sentences.
- Never invent headings.
- Never add explanations.
- Never add introductory text.
- Never output phrases like:
"Here is the filtered context"
"Summary"
"Relevant Context"
"Compressed Context"
Return ONLY the remaining original sentences.
Filtered Context:
"""
try:
response = requests.post(
"http://localhost:11434/api/generate",
json={
"model": "llama3",
"prompt": prompt,
"stream": False
},timeout =120
)
response.raise_for_status()
result = response.json()
except Exception as e:
print(f"Error during context filtering: {e}")
return compressed_chunks
if "response" not in result:
print(result)
return compressed_chunks
page = compressed_chunks[0]["page"]
source = compressed_chunks[0]["source"]
filtered_text = result["response"].strip()
bad_prefixes = [
"Filtered Context:",
"Compressed Context:",
"Relevant Context:",
"Summary:",
"Here is the filtered context:"
]
for prefix in bad_prefixes:
if filtered_text.startswith(prefix):
filtered_text = filtered_text[len(prefix):].strip()
if not filtered_text.strip():
return compressed_chunks
mini_texts = compression_splitter.split_text(filtered_text)
llm_chunks = []
for chunk in mini_texts:
llm_chunks.append({
"text": chunk,
"page": page,
"source": source
})
return llm_chunks
# // GENERATION CODE //
import requests
while True:
question = input("\nAsk a question: ")
if question.lower() == "exit":
break
# context = "\n".join(retrieved_chunks)
# won't work because now retrieved chunks are dictionaries.
top_docs = route_query(question)
if not top_docs:
top_docs = retrieve_documents(question,
top_docs = 2)
print("/Routed Documents : ")
print(top_docs)
retrieved_children = multi_query_retrieve(question,
top_k =10,
sources = top_docs
)
if not retrieved_children:
print("I couldn't find relevant information in the PDF.")
continue
pairs =[
(question,
chunk["text"]
)
for chunk in retrieved_children
]
rerank_scores= reranker.predict(pairs)
ranked_results = sorted(zip(rerank_scores,retrieved_children),
reverse =True,
key=lambda x:x[0]
)
top_children = [
chunk
for score, chunk in ranked_results[:5]
]
parent_ids = {
child["parent_id"]
for child in top_children
}
parent_scores = {}
for score, child in ranked_results[:10]:
pid = child["parent_id"]
if pid not in parent_scores:
parent_scores[pid] = score
else:
parent_scores[pid] = max(
parent_scores[pid],
score
)
retrieved_parents = sorted(
[
parent
for parent in parent_chunks
if parent["id"] in parent_scores
],
key=lambda x: parent_scores[x["id"]],
reverse=True
)[:3]
if not retrieved_parents:
print("No parent chunks found.")
continue
print("\nTop Reranked Chunks:")
for score, chunk in ranked_results[:10]:
print(
score,
chunk["source"],
chunk["page"]
)
mini_chunks = split_parent_chunks(retrieved_parents)
print("\nMini Chunks Created:")
for i, chunk in enumerate(mini_chunks):
print("\n------------------")
print(i)
print(chunk["source"])
print(chunk["page"])
print(chunk["text"][:200])
compressed_chunks = compress_context(
question,
mini_chunks,
top_k=5
)
if not compressed_chunks:
print("Context compression returned nothing.")
continue
filtered_chunks = llm_context_filter(
question,
compressed_chunks
)
if not filtered_chunks:
filtered_chunks = compressed_chunks
print("\nCompressed Chunks:\n")
context = "\n".join(
chunk["text"]
for chunk in filtered_chunks
)
# for degugging purpose only
print("\nLLM Filtered Chunks:\n")
for chunk in filtered_chunks:
print("-" * 40)
print(chunk["source"])
print(chunk["page"])
print(chunk["text"])
prompt = f"""
You are a Retrieval-Augmented Generation assistant.
Answer ONLY using information explicitly present in the context.
Do not make assumptions.
Use the strongest evidence from the context.
If multiple pieces of evidence exist,
prefer the most directly relevant one.
If the answer is not present in the context, reply:
"I could not find that information in the PDF."
Context:
{context}
Question:
{question}
Answer:
"""
print("\nRetrieved Context:")
print(context)
try:
response = requests.post(
"http://localhost:11434/api/generate",
json={
"model": "llama3",
"prompt": prompt,
"stream": False
},timeout =120
)
response.raise_for_status()
result = response.json()
except Exception as e:
print(f"Error generating answer: {e}")
continue
if "response" in result :
print("\nAnswer:")
print(result["response"])
else:
print(result)
print("\n Selected Parents: ")
for parent in retrieved_parents:
print(parent["source"],