HemanM commited on
Commit
5b27dcb
·
verified ·
1 Parent(s): 8aefac4

Create retriever.py

Browse files
Files changed (1) hide show
  1. retriever.py +40 -0
retriever.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import faiss
2
+ import os
3
+ import numpy as np
4
+ from sentence_transformers import SentenceTransformer
5
+ import pdfplumber
6
+
7
+ model = SentenceTransformer("all-MiniLM-L6-v2") # small, fast
8
+ index = None
9
+ doc_chunks = []
10
+
11
+ def read_pdf(path):
12
+ with pdfplumber.open(path) as pdf:
13
+ return "\n".join([page.extract_text() or "" for page in pdf.pages])
14
+
15
+ def chunk_text(text, chunk_size=250):
16
+ words = text.split()
17
+ return [" ".join(words[i:i+chunk_size]) for i in range(0, len(words), chunk_size)]
18
+
19
+ def build_index_from_file(file_path):
20
+ global index, doc_chunks
21
+ ext = os.path.splitext(file_path)[-1].lower()
22
+
23
+ if ext == ".pdf":
24
+ text = read_pdf(file_path)
25
+ else:
26
+ with open(file_path, "r", encoding="utf-8") as f:
27
+ text = f.read()
28
+
29
+ doc_chunks = chunk_text(text)
30
+ embeddings = model.encode(doc_chunks, convert_to_numpy=True)
31
+ index = faiss.IndexFlatL2(embeddings.shape[1])
32
+ index.add(np.array(embeddings))
33
+
34
+ def retrieve(query, top_k=3):
35
+ if index is None:
36
+ return ""
37
+
38
+ query_vec = model.encode([query])
39
+ D, I = index.search(np.array(query_vec), top_k)
40
+ return "\n\n".join([doc_chunks[i] for i in I[0]])