Spaces:
Sleeping
Sleeping
Rajan Sharma
commited on
Update retriever.py
Browse files- retriever.py +43 -47
retriever.py
CHANGED
|
@@ -1,49 +1,45 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
import faiss
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from sentence_transformers import SentenceTransformer
|
| 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 |
-
if
|
| 42 |
-
_retriever = Retriever(index_path, meta_path)
|
| 43 |
-
return _retriever
|
| 44 |
-
|
| 45 |
-
def retrieve_context(query: str, k: int = 6) -> str:
|
| 46 |
-
r = init_retriever()
|
| 47 |
-
if not r.ready():
|
| 48 |
-
return "(No policy index found. Run build_policy_index.py to enable RAG.)"
|
| 49 |
-
return "\n---\n".join(r.retrieve(query, k=k))
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
try:
|
| 4 |
+
import faiss
|
| 5 |
+
_HAS_FAISS = True
|
| 6 |
+
except ImportError:
|
| 7 |
+
logging.warning("FAISS not installed — retrieval will be disabled. Install faiss-cpu or faiss-gpu for full functionality.")
|
| 8 |
+
_HAS_FAISS = False
|
| 9 |
+
|
| 10 |
from sentence_transformers import SentenceTransformer
|
| 11 |
|
| 12 |
+
# load embedding model (still works even if FAISS missing)
|
| 13 |
+
_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 14 |
+
|
| 15 |
+
_index = None
|
| 16 |
+
_docs = []
|
| 17 |
+
|
| 18 |
+
def init_retriever(docs=None):
|
| 19 |
+
"""
|
| 20 |
+
Initialize FAISS index if FAISS is available.
|
| 21 |
+
docs: list[str] to index
|
| 22 |
+
"""
|
| 23 |
+
global _index, _docs
|
| 24 |
+
if not _HAS_FAISS:
|
| 25 |
+
_docs = docs or []
|
| 26 |
+
return
|
| 27 |
+
|
| 28 |
+
if docs:
|
| 29 |
+
_docs = docs
|
| 30 |
+
embeddings = _model.encode(docs, convert_to_numpy=True)
|
| 31 |
+
d = embeddings.shape[1]
|
| 32 |
+
_index = faiss.IndexFlatL2(d)
|
| 33 |
+
_index.add(embeddings)
|
| 34 |
+
|
| 35 |
+
def retrieve_context(query: str, k: int = 5):
|
| 36 |
+
"""
|
| 37 |
+
Retrieve top-k docs matching query.
|
| 38 |
+
Falls back to empty list if FAISS unavailable.
|
| 39 |
+
"""
|
| 40 |
+
if not _HAS_FAISS or _index is None or not _docs:
|
| 41 |
+
return []
|
| 42 |
+
|
| 43 |
+
q_emb = _model.encode([query], convert_to_numpy=True)
|
| 44 |
+
D, I = _index.search(q_emb, k)
|
| 45 |
+
return [_docs[i] for i in I[0] if i < len(_docs)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|