Spaces:
Sleeping
Sleeping
Update helpers/live_sources.py
Browse files- helpers/live_sources.py +42 -41
helpers/live_sources.py
CHANGED
|
@@ -1,42 +1,43 @@
|
|
| 1 |
-
# Retrieves links for all modules
|
| 2 |
-
import json
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
import faiss
|
| 5 |
-
from sentence_transformers import SentenceTransformer
|
| 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 |
return results
|
|
|
|
| 1 |
+
# Retrieves links for all modules
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import faiss
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 7 |
+
DATA_DIR = BASE_DIR / "data"
|
| 8 |
+
VECTOR_DIR = DATA_DIR / "vector_store"
|
| 9 |
+
LIVE_FAISS_INDEX_PATH = VECTOR_DIR / "live_faiss.index"
|
| 10 |
+
LIVE_METADATA_PATH = VECTOR_DIR / "live_metadata.json"
|
| 11 |
+
index = faiss.read_index(str(LIVE_FAISS_INDEX_PATH))
|
| 12 |
+
with open(LIVE_METADATA_PATH, "r", encoding="utf-8") as f:
|
| 13 |
+
METADATA = json.load(f)
|
| 14 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 15 |
+
def retrieve_live_sources(
|
| 16 |
+
query: str,
|
| 17 |
+
*,
|
| 18 |
+
top_k: int = 2,
|
| 19 |
+
search_k: int = 2000
|
| 20 |
+
):
|
| 21 |
+
query_embedding = model.encode(
|
| 22 |
+
[query],
|
| 23 |
+
normalize_embeddings=True,
|
| 24 |
+
convert_to_numpy=True
|
| 25 |
+
)
|
| 26 |
+
scores, indices = index.search(query_embedding, search_k)
|
| 27 |
+
results = []
|
| 28 |
+
seen_urls = set()
|
| 29 |
+
for score, idx in zip(scores[0], indices[0]):
|
| 30 |
+
meta = METADATA[idx]
|
| 31 |
+
url = meta.get("document_path")
|
| 32 |
+
if not url or url in seen_urls:
|
| 33 |
+
continue
|
| 34 |
+
seen_urls.add(url)
|
| 35 |
+
results.append({
|
| 36 |
+
"url": url,
|
| 37 |
+
"authority": meta.get("authority"),
|
| 38 |
+
"description": meta.get("text"),
|
| 39 |
+
"similarity": float(score)
|
| 40 |
+
})
|
| 41 |
+
if len(results) >= top_k:
|
| 42 |
+
break
|
| 43 |
return results
|