File size: 4,028 Bytes
a805048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""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)