File size: 6,009 Bytes
27f6252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""
BM25-based sparse vector encoder for Qdrant hybrid search.

Workflow
--------
1. fit(corpus)    — build vocab + IDF from a list of texts, persist to disk.
2. encode(text)   — per-document sparse vector (BM25 term weights).
3. encode_query(text) — per-query sparse vector (IDF weights only, standard pattern).
4. load(path)     — restore a previously fitted encoder.

Sparse vector format matches Qdrant's SparseVector:
    {"indices": [int, ...], "values": [float, ...]}
"""

from __future__ import annotations

import json
import math
import re
from collections import Counter
from pathlib import Path
from typing import Any, Dict, List, Tuple

from src.generators.rag_config import BM25_K1, BM25_B, BM25_MIN_DF, BM25_MAX_VOCAB, BM25_VOCAB_PATH


def _tokenize(text: str) -> List[str]:
    """Lowercase, split on non-alphanumeric, keep tokens ≥ 2 chars."""
    return [t for t in re.split(r"[^a-z0-9]+", text.lower()) if len(t) >= 2]


class BM25SparseEncoder:
    """
    Corpus-level BM25 sparse encoder.

    Attributes
    ----------
    vocab   : token → integer token_id
    idf     : token → IDF weight (Robertson–Spärck Jones)
    avgdl   : average document length in tokens
    """

    def __init__(self) -> None:
        self.vocab:  Dict[str, int]   = {}
        self.idf:    Dict[str, float] = {}
        self.avgdl:  float             = 0.0

    # ── fitting ──────────────────────────────────────────────────────────────

    def fit(self, corpus: List[str]) -> "BM25SparseEncoder":
        """
        Build vocab and IDF from a list of raw texts.
        Persists the fitted state to BM25_VOCAB_PATH automatically.
        """
        tokenized = [_tokenize(text) for text in corpus]
        N  = len(tokenized)
        df: Counter = Counter()

        for tokens in tokenized:
            for t in set(tokens):
                df[t] += 1

        self.avgdl = sum(len(t) for t in tokenized) / max(1, N)

        # Build vocab: filter low-df, keep top MAX_VOCAB by df desc
        filtered = [(t, f) for t, f in df.items() if f >= BM25_MIN_DF]
        filtered.sort(key=lambda x: -x[1])
        filtered = filtered[:BM25_MAX_VOCAB]

        self.vocab = {t: idx for idx, (t, _) in enumerate(filtered)}
        self.idf   = {
            t: math.log((N - f + 0.5) / (f + 0.5) + 1.0)
            for t, f in filtered
        }

        self.save()
        return self

    # ── encoding ─────────────────────────────────────────────────────────────

    def encode(self, text: str) -> Dict[str, Any]:
        """BM25 document vector — term-frequency weighted."""
        tokens = _tokenize(text)
        dl     = len(tokens)
        tf     = Counter(tokens)

        indices: List[int]   = []
        values:  List[float] = []

        for token, count in tf.items():
            tid = self.vocab.get(token)
            if tid is None:
                continue
            idf = self.idf[token]
            # BM25 TF normalisation
            tf_norm = count * (BM25_K1 + 1) / (
                count + BM25_K1 * (1 - BM25_B + BM25_B * dl / max(1, self.avgdl))
            )
            w = idf * tf_norm
            if w > 0:
                indices.append(tid)
                values.append(round(w, 6))

        return {"indices": indices, "values": values}

    def encode_query(self, text: str) -> Dict[str, Any]:
        """Query vector — IDF weights only (asymmetric BM25 pattern)."""
        tokens = set(_tokenize(text))
        indices: List[int]   = []
        values:  List[float] = []

        for token in tokens:
            tid = self.vocab.get(token)
            if tid is None:
                continue
            indices.append(tid)
            values.append(round(self.idf[token], 6))

        return {"indices": indices, "values": values}

    # ── persistence ───────────────────────────────────────────────────────────

    def save(self, path: str | Path | None = None) -> None:
        path = Path(path or BM25_VOCAB_PATH)
        path.parent.mkdir(parents=True, exist_ok=True)
        state = {
            "vocab":  self.vocab,
            "idf":    self.idf,
            "avgdl":  self.avgdl,
        }
        with open(path, "w", encoding="utf-8") as f:
            json.dump(state, f)

    @classmethod
    def load(cls, path: str | Path | None = None) -> "BM25SparseEncoder":
        path = Path(path or BM25_VOCAB_PATH)
        with open(path, encoding="utf-8") as f:
            state = json.load(f)
        enc = cls()
        enc.vocab  = state["vocab"]
        enc.idf    = state["idf"]
        enc.avgdl  = state["avgdl"]
        return enc

    @classmethod
    def load_or_none(cls, path: str | Path | None = None) -> "BM25SparseEncoder | None":
        import logging
        _logger = logging.getLogger(__name__)

        p = Path(path or BM25_VOCAB_PATH)
        if not p.exists():
            _logger.warning(
                "BM25 vocabulary not found at %s. Hybrid search will fall back to "
                "dense-only (sparse vectors empty). Run --build to create the index.",
                p,
            )
            return None

        try:
            enc = cls.load(p)
            if len(enc.vocab) < 10:
                _logger.warning(
                    "BM25 vocabulary at %s contains only %d tokens — sparse search "
                    "will be effectively disabled. Run --build to rebuild with full corpus.",
                    p, len(enc.vocab),
                )
            return enc
        except Exception as e:
            _logger.warning("Failed to load BM25 vocabulary from %s: %s", p, e)
            return None