Spaces:
Running on Zero
Running on Zero
Download core/rag.py from MustafaHussein/te-assistant: direct link, hf CLI and curl.
- Browser
- Download file 4.18 kB
-
https://huggingface.co/spaces/MustafaHussein/te-assistant/resolve/main/core/rag.py
- Command line
-
hf download hf://spaces/MustafaHussein/te-assistant/core/rag.py
-
curl -L -o rag.py https://huggingface.co/spaces/MustafaHussein/te-assistant/resolve/main/core/rag.py
4.18 kB
| """Embeddings, the te.eg FAISS index, and per-session indexes for uploaded documents.""" | |
| import json | |
| import threading | |
| import time | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import List, Optional | |
| import numpy as np | |
| import config | |
| class Hit: | |
| text: str | |
| title: str | |
| source: str # URL for te.eg chunks, file name for uploads | |
| page: Optional[int] | |
| kind: str # "te" | "user" | |
| score: float | |
| class Embedder: | |
| """multilingual-e5: needs 'query: ' / 'passage: ' prefixes. Arabic and English share one space, | |
| so an Arabic question can retrieve English pages and vice versa.""" | |
| def __init__(self, name: Optional[str] = None, device: str = "cpu"): | |
| from sentence_transformers import SentenceTransformer | |
| self.name = name or config.EMBED_MODEL | |
| self.model = SentenceTransformer(self.name, device=device) | |
| self._lock = threading.Lock() | |
| def _enc(self, texts: List[str], prefix: str) -> np.ndarray: | |
| with self._lock: | |
| v = self.model.encode([prefix + t for t in texts], normalize_embeddings=True, | |
| batch_size=32, show_progress_bar=False) | |
| return np.asarray(v, dtype="float32") | |
| def passages(self, texts: List[str]) -> np.ndarray: | |
| return self._enc(texts, "passage: ") | |
| def queries(self, texts: List[str]) -> np.ndarray: | |
| return self._enc(texts, "query: ") | |
| class TEIndex: | |
| """Static index over the scraped te.eg corpus (built offline, shipped with the app).""" | |
| def __init__(self, index, metas: List[dict]): | |
| self.index, self.metas = index, metas | |
| def size(self) -> int: | |
| return len(self.metas) | |
| def exists(cls, d: Path) -> bool: | |
| return (Path(d) / "te.faiss").exists() and (Path(d) / "te_meta.json").exists() | |
| def load(cls, d: Path) -> "TEIndex": | |
| import faiss | |
| d = Path(d) | |
| metas = json.loads((d / "te_meta.json").read_text(encoding="utf-8")) | |
| return cls(faiss.read_index(str(d / "te.faiss")), metas) | |
| def build(metas: List[dict], vecs: np.ndarray, out_dir: Path, model_name: str = "") -> None: | |
| import faiss | |
| out_dir = Path(out_dir) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| index = faiss.IndexFlatIP(vecs.shape[1]) # cosine, since vectors are normalized | |
| index.add(vecs.astype("float32")) | |
| faiss.write_index(index, str(out_dir / "te.faiss")) | |
| (out_dir / "te_meta.json").write_text(json.dumps(metas, ensure_ascii=False), encoding="utf-8") | |
| (out_dir / "info.json").write_text(json.dumps( | |
| {"model": model_name, "chunks": len(metas), "built": time.strftime("%Y-%m-%d %H:%M")}), encoding="utf-8") | |
| def search(self, qvec: np.ndarray, k: int) -> List[Hit]: | |
| if not self.size: | |
| return [] | |
| scores, ids = self.index.search(qvec.astype("float32"), min(k, self.size)) | |
| hits = [] | |
| for s, i in zip(scores[0], ids[0]): | |
| if i < 0: | |
| continue | |
| m = self.metas[int(i)] | |
| hits.append(Hit(m["text"], m.get("title", ""), m["source"], m.get("page"), "te", float(s))) | |
| return hits | |
| class UserIndex: | |
| """Small in-memory index for one chat session's uploaded documents.""" | |
| def __init__(self): | |
| self.chunks: list = [] | |
| self.vecs: Optional[np.ndarray] = None | |
| self.files: List[str] = [] | |
| def size(self) -> int: | |
| return len(self.chunks) | |
| def add(self, name: str, chunks: list, vecs: np.ndarray) -> None: | |
| self.chunks.extend(chunks) | |
| self.vecs = vecs if self.vecs is None else np.vstack([self.vecs, vecs]) | |
| self.files.append(name) | |
| def search(self, qvec: np.ndarray, k: int) -> List[Hit]: | |
| if self.vecs is None or not self.size: | |
| return [] | |
| scores = (self.vecs @ qvec[0]).astype("float32") | |
| top = np.argsort(-scores)[:k] | |
| return [Hit(self.chunks[i].text, self.chunks[i].title, self.chunks[i].source, | |
| self.chunks[i].page, "user", float(scores[i])) for i in top] | |