Spaces:
Sleeping
Sleeping
Create semantic.py
Browse files- semantic.py +29 -15
semantic.py
CHANGED
|
@@ -1,18 +1,32 @@
|
|
| 1 |
-
|
| 2 |
-
import numpy as np
|
| 3 |
-
from sentence_transformers import SentenceTransformer
|
| 4 |
-
from typing import List, Dict
|
| 5 |
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
index.add(np.array(embeddings))
|
| 13 |
-
return index, embeddings
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FAISS_AVAILABLE = False
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
try:
|
| 4 |
+
import faiss
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
+
FAISS_AVAILABLE = True
|
| 7 |
+
except Exception:
|
| 8 |
+
FAISS_AVAILABLE = False
|
| 9 |
|
| 10 |
+
class SemanticIndex:
|
| 11 |
+
def __init__(self):
|
| 12 |
+
if not FAISS_AVAILABLE:
|
| 13 |
+
raise RuntimeError("FAISS unavailable")
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
self.model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 16 |
+
self.index = None
|
| 17 |
+
self.texts = []
|
| 18 |
+
|
| 19 |
+
def build(self, texts):
|
| 20 |
+
embeddings = self.model.encode(texts)
|
| 21 |
+
dim = embeddings.shape[1]
|
| 22 |
+
self.index = faiss.IndexFlatL2(dim)
|
| 23 |
+
self.index.add(embeddings)
|
| 24 |
+
self.texts = texts
|
| 25 |
+
|
| 26 |
+
def search(self, query, k=5):
|
| 27 |
+
if not self.index:
|
| 28 |
+
return []
|
| 29 |
+
|
| 30 |
+
q = self.model.encode([query])
|
| 31 |
+
_, idxs = self.index.search(q, k)
|
| 32 |
+
return [self.texts[i] for i in idxs[0]]
|