Download src/retrieval/semantic.py from Estarcode/campusdesk-ai: direct link, hf CLI and curl.
- Browser
- Download file 2.16 kB
-
https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/src/retrieval/semantic.py
- Command line
-
hf download hf://Estarcode/campusdesk-ai/src/retrieval/semantic.py
-
curl -L -o semantic.py https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/src/retrieval/semantic.py
2.16 kB
| """Multilingual semantic vector index backed by intfloat/multilingual-e5-small.""" | |
| from pathlib import Path | |
| from typing import List | |
| import numpy as np | |
| from sentence_transformers import SentenceTransformer | |
| from src.config import EMBEDDING_MODEL_ID, EMBEDDINGS_INDEX_PATH | |
| from src.schemas import PassageRecord | |
| def format_passage_for_search(p: PassageRecord) -> str: | |
| amend_ctx = f" Amends {p.amends_doc_id}: {p.amends_scope}." if p.amends_doc_id else "" | |
| return f"{p.doc_id} {p.title} ({p.section_or_row}, {p.date}): {p.text}{amend_ctx}" | |
| class SemanticIndex: | |
| """Dense vector index using normalized multilingual E5 embeddings.""" | |
| def __init__( | |
| self, | |
| passages: List[PassageRecord], | |
| index_path: Path = EMBEDDINGS_INDEX_PATH, | |
| model_id: str = EMBEDDING_MODEL_ID, | |
| rebuild: bool = False, | |
| ): | |
| self.passages = passages | |
| self.index_path = index_path | |
| self.model_id = model_id | |
| self.embedder = SentenceTransformer(model_id) | |
| self.embeddings = self._load_or_build(rebuild=rebuild) | |
| def _load_or_build(self, rebuild: bool) -> np.ndarray: | |
| passage_ids = [p.passage_id for p in self.passages] | |
| if not rebuild and self.index_path.exists(): | |
| cached = np.load(self.index_path, allow_pickle=False) | |
| if list(cached["passage_ids"]) == passage_ids: | |
| return cached["embeddings"] | |
| texts = [f"passage: {format_passage_for_search(p)}" for p in self.passages] | |
| emb = self.embedder.encode(texts, normalize_embeddings=True, show_progress_bar=False) | |
| emb = np.asarray(emb, dtype=np.float32) | |
| self.index_path.parent.mkdir(parents=True, exist_ok=True) | |
| np.savez(self.index_path, passage_ids=np.array(passage_ids), embeddings=emb) | |
| return emb | |
| def score_normalized(self, query: str) -> np.ndarray: | |
| q_emb = self.embedder.encode( | |
| [f"query: {query}"], normalize_embeddings=True, show_progress_bar=False | |
| )[0] | |
| raw = np.dot(self.embeddings, q_emb) | |
| d_min, d_max = float(raw.min()), float(raw.max()) | |
| return (raw - d_min) / (d_max - d_min + 1e-8) | |