Create hybrid_retrieval.py
Browse files- hybrid_retrieval.py +37 -0
hybrid_retrieval.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import faiss
|
| 2 |
+
import numpy as np
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
from rank_bm25 import BM25Okapi
|
| 5 |
+
|
| 6 |
+
def create_hybrid_index(pdf_texts):
|
| 7 |
+
"""Initializes BM25 and FAISS for hybrid retrieval."""
|
| 8 |
+
|
| 9 |
+
# BM25 setup
|
| 10 |
+
tokenized_corpus = [doc.split(" ") for doc in pdf_texts]
|
| 11 |
+
bm25 = BM25Okapi(tokenized_corpus)
|
| 12 |
+
|
| 13 |
+
# FAISS setup
|
| 14 |
+
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 15 |
+
document_embeddings = embed_model.encode(pdf_texts)
|
| 16 |
+
|
| 17 |
+
index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 18 |
+
index.add(np.array(document_embeddings).astype("float32"))
|
| 19 |
+
|
| 20 |
+
return bm25, index, embed_model, document_embeddings
|
| 21 |
+
|
| 22 |
+
def hybrid_search(query, bm25, index, embed_model, document_embeddings, pdf_texts, top_n=3):
|
| 23 |
+
"""Performs hybrid search using BM25 for filtering and FAISS for semantic ranking."""
|
| 24 |
+
|
| 25 |
+
# BM25 search
|
| 26 |
+
bm25_scores = bm25.get_scores(query.split(" "))
|
| 27 |
+
top_docs_indices = np.argsort(bm25_scores)[-top_n:]
|
| 28 |
+
|
| 29 |
+
# FAISS search on filtered results
|
| 30 |
+
query_embedding = embed_model.encode([query])
|
| 31 |
+
sub_index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 32 |
+
sub_index.add(np.array([document_embeddings[i] for i in top_docs_indices]).astype("float32"))
|
| 33 |
+
_, sub_ranked_indices = sub_index.search(np.array(query_embedding).astype("float32"), top_n)
|
| 34 |
+
|
| 35 |
+
# Map FAISS results back to original document indices
|
| 36 |
+
final_ranked_indices = [top_docs_indices[i] for i in sub_ranked_indices[0]]
|
| 37 |
+
return [pdf_texts[i] for i in final_ranked_indices]
|