EvidenceGuard-AI / src /vector_store.py
leeshal's picture
Upload 55 files
a805048 verified
Raw History Blame Contribute Delete
4.03 kB
"""FAISS vector store plus the KnowledgeBase that owns documents, chunks, dense and BM25 indexes."""
from __future__ import annotations
import math
from collections import Counter
from pathlib import Path
import faiss
import numpy as np
from src.document_processor import Chunk, DocumentInfo, process_pdf
from src.text_utils import content_tokens
class FaissStore:
"""Exact inner-product search over L2-normalised vectors (= cosine similarity)."""
def __init__(self, dim: int):
self.index = faiss.IndexFlatIP(dim)
def add(self, vectors: np.ndarray):
self.index.add(np.ascontiguousarray(vectors, dtype="float32"))
def search(self, query_vec: np.ndarray, k: int):
k = min(k, self.index.ntotal)
if k == 0:
return [], []
scores, ids = self.index.search(np.ascontiguousarray(query_vec, dtype="float32"), k)
return scores[0].tolist(), ids[0].tolist()
@property
def size(self):
return self.index.ntotal
class KnowledgeBase:
"""Holds the chunk collection and every index built over it."""
def __init__(self, embedder):
from rank_bm25 import BM25Okapi # noqa: F401 (import check)
self.embedder = embedder
self.docs: dict[str, DocumentInfo] = {}
self.chunks: list[Chunk] = []
self.store: FaissStore | None = None
self.bm25 = None
self.idf: dict[str, float] = {}
self.max_idf = 1.0
# ---------------------------------------------------------------- ingestion
def add_pdfs(self, paths, doc_ids=None) -> list[DocumentInfo]:
infos = []
for i, p in enumerate(paths):
did = doc_ids[i] if doc_ids else None
info, chunks = process_pdf(p, did)
if info.doc_id in self.docs: # re-upload replaces the old version
self.chunks = [c for c in self.chunks if c.doc_id != info.doc_id]
if info.status != "error":
self.docs[info.doc_id] = info
self.chunks.extend(chunks)
infos.append(info)
self.rebuild()
return infos
def remove_doc(self, doc_id: str):
self.docs.pop(doc_id, None)
self.chunks = [c for c in self.chunks if c.doc_id != doc_id]
self.rebuild()
def rebuild(self):
from rank_bm25 import BM25Okapi
texts = [self._index_text(c) for c in self.chunks]
if not texts:
self.store, self.bm25 = None, None
return
if getattr(self.embedder, "needs_fit", False):
self.embedder.fit(texts)
vecs = self.embedder.encode(texts)
self.store = FaissStore(vecs.shape[1])
self.store.add(vecs)
toks = [content_tokens(t) for t in texts]
self.bm25 = BM25Okapi(toks)
df = Counter(t for doc in toks for t in set(doc))
n = len(toks)
self.idf = {t: math.log(1 + (n - d + 0.5) / (d + 0.5)) for t, d in df.items()}
self.max_idf = max(self.idf.values()) if self.idf else 1.0
@staticmethod
def _index_text(c: Chunk) -> str:
return f"{c.title}. {c.text}"
# ---------------------------------------------------------------- helpers
def term_idf(self, term: str) -> float:
"""IDF of a term; terms never seen in the corpus get the highest weight (+1)."""
return self.idf.get(term, self.max_idf + 1.0)
def in_vocab(self, term: str) -> bool:
return term in self.idf
@property
def ready(self) -> bool:
return self.store is not None and self.store.size > 0
def load_folder(self, folder: Path, use_manifest_ids: bool = True):
import json
folder = Path(folder)
pdfs = sorted(folder.glob("*.pdf"))
ids = None
mf = folder / "corpus_manifest.json"
if use_manifest_ids and mf.exists():
m = {d["filename"]: d["id"] for d in json.loads(mf.read_text())}
ids = [m.get(p.name) for p in pdfs]
return self.add_pdfs(pdfs, ids)