Create semantic_index.py
Browse files- semantic_index.py +19 -0
semantic_index.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import faiss
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class FaissSemanticIndex:
|
| 7 |
+
def __init__(self, dim: int):
|
| 8 |
+
self.index = faiss.IndexFlatIP(dim)
|
| 9 |
+
self.texts = []
|
| 10 |
+
|
| 11 |
+
def add(self, embeddings: torch.Tensor, texts: list[str]):
|
| 12 |
+
normalized = torch.nn.functional.normalize(embeddings, p=2, dim=1).cpu().numpy()
|
| 13 |
+
self.index.add(normalized)
|
| 14 |
+
self.texts.extend(texts)
|
| 15 |
+
|
| 16 |
+
def search(self, query: torch.Tensor, k: int = 1):
|
| 17 |
+
query = torch.nn.functional.normalize(query, p=2, dim=1).cpu().numpy()
|
| 18 |
+
scores, indices = self.index.search(query, k)
|
| 19 |
+
return [(self.texts[i], float(scores[0][j])) for j, i in enumerate(indices[0])]
|