kci-vec 0.2.16__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kci_vec/text.py ADDED
@@ -0,0 +1,617 @@
1
+ """kci_vec.text — search your texts by handing over the texts.
2
+
3
+ from kci_vec.text import TextIndex
4
+
5
+ ix = TextIndex("ja") # "ja" Japanese, "en" English
6
+ ix.add(["有給休暇は入社半年後に10日付与されます。", "経費の精算は月末締めです。", ...])
7
+ for hit in ix.search("有給は何日もらえる?", k=3):
8
+ print(hit.id, round(hit.score, 3), hit.text)
9
+ ix.save("my_index") # later: ix = TextIndex.load("my_index")
10
+
11
+ What happens inside: every text is turned into two vectors by two language models that run on this machine
12
+ (nothing is sent anywhere after the models have been downloaded once): a dense one (the meaning as a whole)
13
+ and a sparse one (which words matter, including related words). A question is searched in both indexes (KciVec
14
+ and KciSparse) and the two result lists are merged by score (hybrid.mix).
15
+
16
+ Needs, besides kci_vec: torch and transformers (pip install torch transformers); for "ja" also fugashi and
17
+ unidic-lite (the sparse model's word splitter). The first use downloads the models (a few hundred MB). Turning
18
+ texts into vectors is the slow part: on a laptop CPU 4 to 8 texts a second, so 10,000 texts take 20 to 40
19
+ minutes; a question takes about 0.07 s. add() can be called again later; it prints its progress.
20
+
21
+ Long texts: a text longer than the models read at once is cut into overlapping parts at sentence ends
22
+ (TextIndex(chunk=) characters; "ja" 350, "en" 1000; 0 = never cut) and every part is indexed. The dense model
23
+ reads further, so its parts are longer (dense_chunk=; "ja" 900, "en" 2000). A search still answers with texts:
24
+ each text once, with the part that matched best as hit.text and its place in the text as hit.span; the whole
25
+ text is ix.texts[hit.id]. With your own models nothing is cut unless you give chunk=.
26
+
27
+ Without a second model: TextIndex("ja", sparse="bm25") uses character-pair BM25 for the word side (CharBM25)
28
+ instead of the sparse language model: nothing to download for that side, and names, codes and terms no model
29
+ has seen are matched as written. dedup=True keeps texts that repeat once on the dense side.
30
+
31
+ Your own models: TextIndex(dense=f, sparse=g, sparse_dim=n) with f(texts, is_query) -> array [len(texts), dim]
32
+ and g(texts, is_query) -> [(indices, values), ...]; mode="dense" or mode="sparse" uses one side only.
33
+
34
+ Saving: save(dir) writes the two indexes, the texts and a small meta.json. Without a key everything is
35
+ readable (the texts as texts.json). With a key (a passphrase) the two indexes and the texts are encrypted
36
+ (texts.kct; AES-256-CTR + CMAC with a key from PBKDF2, all in the C library) and a wrong key or a changed file
37
+ is refused. meta.json stays readable either way: it holds the ids, the model names and the settings, no text.
38
+
39
+ Licences of the built-in models (as their model pages on the Hugging Face hub state; check again before you
40
+ rely on it): "ja": cl-nagoya/ruri-v3-30m Apache-2.0, hotchpotch/japanese-splade-v2 MIT.
41
+ "en": intfloat/multilingual-e5-small MIT, opensearch-project/opensearch-neural-sparse-encoding-v2-distill
42
+ Apache-2.0."""
43
+ import io, json, math, os, re, sys, time, unicodedata, zlib
44
+ from collections import namedtuple, Counter
45
+ import numpy as np
46
+
47
+ from . import KciVec
48
+ from .sparse import KciSparse, seal, unseal
49
+ from .hybrid import mix, choose_weight, tokenize
50
+
51
+ Hit = namedtuple("Hit", "id score text dense_rank sparse_rank span")
52
+ Cand = namedtuple("Cand", "id text span dense_rank dense_score sparse_rank sparse_score")
53
+ # the words of a question that count for the phrase match: runs of kanji, of katakana, or of Latin letters / digits, 2 or longer
54
+ _TERMS = re.compile("[\u4e00-\u9fff\u3005]{2,}|[\u30a1-\u30fa\u30fc]{2,}|[0-9A-Za-z][0-9A-Za-z_.\\-]+")
55
+
56
+
57
+ PRESETS = {
58
+ "ja": dict(dense="cl-nagoya/ruri-v3-30m", q_prefix="検索クエリ: ", d_prefix="検索文書: ",
59
+ sparse="hotchpotch/japanese-splade-v2", w_dense=0.4, chunk=350, dense_chunk=900),
60
+ "en": dict(dense="intfloat/multilingual-e5-small", q_prefix="query: ", d_prefix="passage: ",
61
+ sparse="opensearch-project/opensearch-neural-sparse-encoding-v2-distill", zero_special=True, w_dense=0.4, chunk=1000, dense_chunk=2000),
62
+ }
63
+ BLOCKS_FROM = 50000 # from this many texts on the sparse side uses the approximate (block) search
64
+
65
+
66
+ _ENDS = "\u3002\uff01\uff1f!?\n" # a part may end after these (Japanese full stop, ! ?, a line break)
67
+
68
+
69
+ def split_text(text, size, overlap=None):
70
+ """Cut a long text into parts of at most `size` characters: [(start, end), ...], text[start:end] is a part."""
71
+ n = len(text); size = int(size)
72
+ if size <= 0 or n <= size: return [(0, n)]
73
+ overlap = size // 8 if overlap is None else max(0, min(int(overlap), size // 2))
74
+ def is_end(i):
75
+ c = text[i - 1]
76
+ return c in _ENDS or (c in ".;:" and text[i:i + 1].isspace())
77
+ out, start = [], 0
78
+ while n - start > size:
79
+ rem = n - start; lim = start + size
80
+ if rem < 2 * size - overlap: # the last two parts: about equal, not a full one and a scrap
81
+ lim = start + min(size, (rem + overlap + 1) // 2 + size // 8)
82
+ half, end = start + (lim - start) // 2, 0
83
+ for i in range(lim, half, -1):
84
+ if is_end(i): end = i; break
85
+ if not end:
86
+ for i in range(lim, half, -1):
87
+ if text[i - 1].isspace(): end = i; break
88
+ if not end: end = lim
89
+ out.append((start, end))
90
+ nxt = end
91
+ for i in range(max(end - overlap, start + 1), end):
92
+ if is_end(i): nxt = i; break
93
+ start = nxt
94
+ out.append((start, n))
95
+ return out
96
+
97
+
98
+ def _torch():
99
+ try:
100
+ import torch, transformers # noqa: F401
101
+ except ImportError as e:
102
+ raise ImportError("kci_vec.text needs torch and transformers for its built-in models: "
103
+ "pip install torch transformers (or pass your own dense= / sparse= functions)") from e
104
+ return torch
105
+
106
+
107
+ def _device(torch, device):
108
+ """"cuda" / "mps" / "auto" (a GPU when torch sees one): NOT tried by the author, who has no such machine at hand;
109
+ the code path is the usual .to(device)."""
110
+ if device in (None, "cpu"): return "cpu"
111
+ if device == "auto":
112
+ if torch.cuda.is_available(): return "cuda"
113
+ mps = getattr(torch.backends, "mps", None)
114
+ return "mps" if mps is not None and mps.is_available() else "cpu"
115
+ return device
116
+
117
+
118
+ class CharBM25:
119
+ """The sparse side without a model: BM25 over words (Latin, digits) and character pairs (Japanese, Chinese,
120
+ Korean), the tokens of kci_vec.hybrid.tokenize, hashed into `dim` slots. For names, codes and terms a language
121
+ model has never seen (drug names, abbreviations, part numbers), and for when no second model should run. A
122
+ text becomes (slot, tf part of BM25); a question becomes (slot, idf), so their inner product is the BM25 score
123
+ and the same KciSparse index (and its encryption) serves. The counts it keeps (how many texts hold each slot,
124
+ the mean length) are saved with the index. Deleting a text does not take its counts back; they follow the
125
+ texts added. TextIndex(lang, sparse="bm25") uses it."""
126
+ name = "char-bm25"
127
+
128
+ def __init__(self, dim=1 << 18, k1=1.5, b=0.75):
129
+ self.dim, self.k1, self.b = int(dim), float(k1), float(b)
130
+ self.df = np.zeros(self.dim, dtype=np.uint32); self.n = 0; self.sum_len = 0
131
+
132
+ def _slots(self, text):
133
+ return [zlib.crc32(tok.encode("utf-8")) % self.dim for tok in tokenize(text)]
134
+
135
+ def __call__(self, texts, is_query):
136
+ rows = []
137
+ for tx in texts:
138
+ sl = self._slots(tx)
139
+ if is_query:
140
+ u = sorted(set(sl)); n = max(self.n, 1)
141
+ rows.append((np.array(u, dtype=np.uint32),
142
+ np.array([math.log(1.0 + (n - float(self.df[s]) + 0.5) / (float(self.df[s]) + 0.5)) for s in u], dtype=np.float32)))
143
+ continue
144
+ c = Counter(sl); L = len(sl)
145
+ self.n += 1; self.sum_len += L
146
+ u = sorted(c); avg = self.sum_len / self.n if self.n else 1.0
147
+ for s in u: self.df[s] += 1
148
+ norm = self.k1 * (1.0 - self.b + self.b * (L / avg if avg > 0 else 1.0))
149
+ rows.append((np.array(u, dtype=np.uint32), np.array([c[s] * (self.k1 + 1.0) / (c[s] + norm) for s in u], dtype=np.float32)))
150
+ return rows
151
+
152
+ def state(self):
153
+ buf = io.BytesIO(); nz = np.nonzero(self.df)[0].astype(np.uint32)
154
+ np.savez(buf, slots=nz, df=self.df[nz], head=np.array([self.dim, self.n, self.sum_len], dtype=np.int64), kb=np.array([self.k1, self.b]))
155
+ return buf.getvalue()
156
+
157
+ def load_state(self, raw):
158
+ z = np.load(io.BytesIO(raw)); head = z["head"]
159
+ if int(head[0]) != self.dim: raise RuntimeError("CharBM25: the saved counts are for another number of slots")
160
+ self.df[:] = 0; self.df[z["slots"]] = z["df"]; self.n = int(head[1]); self.sum_len = int(head[2])
161
+ self.k1, self.b = float(z["kb"][0]), float(z["kb"][1])
162
+
163
+
164
+ def _batches(texts, batch):
165
+ order = sorted(range(len(texts)), key=lambda i: -len(texts[i])) # similar lengths share a batch
166
+ for b in range(0, len(order), batch):
167
+ yield order[b:b + batch]
168
+
169
+
170
+ class HFDense:
171
+ """A sentence-embedding model from the Hugging Face hub: mean of the token vectors, length 1."""
172
+ def __init__(self, name, q_prefix="", d_prefix="", max_tokens=512, batch=16, device=None):
173
+ torch = _torch()
174
+ from transformers import AutoModel, AutoTokenizer
175
+ self.name, self.qp, self.dp, self.max_tokens, self.batch = name, q_prefix, d_prefix, max_tokens, batch
176
+ self.tok = AutoTokenizer.from_pretrained(name); self.model = AutoModel.from_pretrained(name).eval()
177
+ self.dim = int(self.model.config.hidden_size); self.torch = torch
178
+ self.device = _device(torch, device); self.model.to(self.device)
179
+
180
+ def __call__(self, texts, is_query):
181
+ torch = self.torch; out = np.zeros((len(texts), self.dim), dtype=np.float32)
182
+ pre = self.qp if is_query else self.dp
183
+ with torch.inference_mode():
184
+ for ids in _batches(texts, self.batch):
185
+ enc = self.tok([pre + texts[i] for i in ids], padding=True, truncation=True, max_length=self.max_tokens, return_tensors="pt").to(self.device)
186
+ h = self.model(**enc).last_hidden_state
187
+ m = enc["attention_mask"].unsqueeze(-1).to(h.dtype)
188
+ v = (h * m).sum(1) / m.sum(1).clamp(min=1)
189
+ out[ids] = torch.nn.functional.normalize(v, dim=1).cpu().numpy()
190
+ return out
191
+
192
+
193
+ class HFSplade:
194
+ """A SPLADE-type model: per text, log(1 + relu(.)) of the word scores, the largest over the tokens."""
195
+ def __init__(self, name, max_tokens=256, max_query_tokens=64, batch=16, zero_special=False, device=None):
196
+ torch = _torch()
197
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
198
+ self.name, self.max_tokens, self.max_query_tokens, self.batch = name, max_tokens, max_query_tokens, batch
199
+ try:
200
+ self.tok = AutoTokenizer.from_pretrained(name)
201
+ except (ImportError, ModuleNotFoundError) as e:
202
+ raise ImportError(f"the tokenizer of {name} needs more packages ({e}); for Japanese: pip install fugashi unidic-lite") from e
203
+ self.model = AutoModelForMaskedLM.from_pretrained(name).eval().float() # some models are stored in 16 bits
204
+ self.dim = int(self.model.config.vocab_size); self.torch = torch
205
+ # zero_special: the weights of [CLS], [SEP], ... are set to 0 (what the opensearch models' cards ask for)
206
+ self.special = list(self.tok.all_special_ids) if zero_special else []
207
+ self.device = _device(torch, device); self.model.to(self.device)
208
+
209
+ def __call__(self, texts, is_query):
210
+ torch = self.torch; rows = [None] * len(texts)
211
+ with torch.inference_mode():
212
+ for ids in _batches(texts, self.batch):
213
+ enc = self.tok([texts[i] for i in ids], padding=True, truncation=True,
214
+ max_length=self.max_query_tokens if is_query else self.max_tokens, return_tensors="pt").to(self.device)
215
+ logits = self.model(**enc).logits
216
+ logits.masked_fill_(enc["attention_mask"].unsqueeze(-1) == 0, float("-inf"))
217
+ w = torch.log1p(torch.relu(logits.max(dim=1).values))
218
+ if self.special: w[:, self.special] = 0
219
+ w = w.cpu()
220
+ for j, i in enumerate(ids):
221
+ nz = torch.nonzero(w[j]).squeeze(1)
222
+ rows[i] = (nz.numpy().astype(np.uint32), w[j, nz].numpy().astype(np.float32))
223
+ return rows
224
+
225
+
226
+ class TextIndex:
227
+ """Texts in, the best matching texts out. See the module text for an example.
228
+
229
+ lang: "ja" or "en" — which built-in models to use (PRESETS). mode: "hybrid" (both, merged), "dense", "sparse".
230
+ dense / sparse: your own functions instead of the built-in models (see the module text); sparse_dim: the size
231
+ of your sparse function's vocabulary. w_dense: the dense side's weight in the merge, 0..1 (the sparse side gets
232
+ the rest); None = the preset's. tune() picks it from questions whose answers you know. chunk: texts longer
233
+ than this many characters are cut into parts (split_text; None = the preset's, 0 = never), overlap: how many
234
+ characters two neighbouring parts may share (None = chunk // 8)."""
235
+
236
+ def __init__(self, lang="ja", mode="hybrid", dense=None, sparse=None, sparse_dim=None, w_dense=None, keep_text=True, verbose=True,
237
+ chunk=None, overlap=None, dense_chunk=None, dedup=False, device=None, phrase=False, phrase_depth=1000,
238
+ phrase_stop=None, phrase_common=None):
239
+ if mode not in ("hybrid", "dense", "sparse"):
240
+ raise ValueError("mode must be 'hybrid', 'dense' or 'sparse'")
241
+ # dedup=True: texts that repeat (boilerplate, empty fields) are kept once on the dense side (kci_vec_set_dedup).
242
+ # device: where the built-in models run (None = CPU; "auto" / "cuda" / "mps": see _device, not tried by the author).
243
+ if isinstance(sparse, str):
244
+ if sparse != "bm25": raise ValueError("sparse= as a word can only be 'bm25'")
245
+ sparse = CharBM25()
246
+ self.dedup, self.device = bool(dedup), device
247
+ # in which the question's own words stand as written come first (_phrase_order). Needs the texts (keep_text).
248
+ self.phrase, self.phrase_depth = bool(phrase), int(phrase_depth)
249
+ # phrase_common = a share 0..1: a word whose character pairs all occur in more than this share of the texts is
250
+ # left out (counted from CharBM25's own counts, so only with sparse="bm25").
251
+ self.phrase_stop = set(unicodedata.normalize("NFKC", w).lower() for w in (phrase_stop or []))
252
+ self.phrase_common = None if phrase_common is None else float(phrase_common)
253
+ if lang not in PRESETS and (dense is None or sparse is None) and not (mode == "dense" and dense) and not (mode == "sparse" and sparse):
254
+ raise ValueError(f"lang must be one of {sorted(PRESETS)} (or pass your own dense= and sparse= functions)")
255
+ self.lang, self.mode, self.keep_text, self.verbose = lang, mode, keep_text, verbose
256
+ self._preset = PRESETS.get(lang, {})
257
+ self._dense_fn, self._sparse_fn, self._sparse_dim = dense, sparse, sparse_dim
258
+ if sparse is not None and sparse_dim is None and not hasattr(sparse, "dim"):
259
+ raise ValueError("with your own sparse= function give sparse_dim= (the size of its vocabulary)")
260
+ self.w_dense = float(w_dense if w_dense is not None else self._preset.get("w_dense", 0.4))
261
+ if not 0.0 <= self.w_dense <= 1.0:
262
+ raise ValueError("w_dense must be between 0 and 1")
263
+ self.chunk = int(chunk if chunk is not None else self._preset.get("chunk", 0)); self.overlap = overlap
264
+ # of 1000 characters. So the dense side has its own, longer part size. With chunk= given and dense_chunk= not,
265
+ self.dense_chunk = int(dense_chunk if dense_chunk is not None else (self._preset.get("dense_chunk", self.chunk) if chunk is None else self.chunk))
266
+ if self.chunk < 0 or self.dense_chunk < 0 or (overlap is not None and int(overlap) < 0): raise ValueError("chunk, dense_chunk and overlap must be >= 0")
267
+ self._side = {}; self._nside = {"d": 0, "s": 0} # row -> "b" both sides, "d" dense only, "s" sparse only; rows per side
268
+ self.vec = None; self.sps = None
269
+ self.texts = {}; self._ids = set(); self._next = 0
270
+ self._rows = {}; self._doc_rows = {}; self._row_next = 0 # row -> (text id, start, end); text id -> rows
271
+ self._built = False; self._blocks = False; self._added_since = 0
272
+
273
+ # ---- the two models, loaded when first needed
274
+ def _dense(self):
275
+ if self._dense_fn is None:
276
+ p = self._preset; self._say(f"loading the dense model {p['dense']} ...")
277
+ self._dense_fn = HFDense(p["dense"], p["q_prefix"], p["d_prefix"], device=self.device)
278
+ return self._dense_fn
279
+
280
+ def _sparse(self):
281
+ if self._sparse_fn is None:
282
+ p = self._preset; self._say(f"loading the sparse model {p['sparse']} ...")
283
+ self._sparse_fn = HFSplade(p["sparse"], zero_special=p.get("zero_special", False), device=self.device)
284
+ if self._sparse_dim is None:
285
+ self._sparse_dim = int(self._sparse_fn.dim)
286
+ return self._sparse_fn
287
+
288
+ def _say(self, s):
289
+ if self.verbose:
290
+ print(s, file=sys.stderr, flush=True)
291
+
292
+ def __len__(self): return len(self._ids)
293
+
294
+ # ---- adding
295
+ def add(self, texts, ids=None, batch=256):
296
+ """Add texts (a list of strings, or one string). ids: your own whole numbers (>= 0), one per text; without
297
+ them the texts are numbered 0, 1, 2, ... in the order they come. Returns the ids. Can be called again at any
298
+ time, also after searching. An id that is already in the index is refused (delete it first)."""
299
+ if isinstance(texts, str): texts = [texts]
300
+ texts = list(texts)
301
+ if any(not isinstance(t, str) for t in texts):
302
+ raise TypeError("add: every text must be a string")
303
+ if ids is None:
304
+ ids = list(range(self._next, self._next + len(texts)))
305
+ else:
306
+ ids = [int(i) for i in ids]
307
+ if len(ids) != len(texts): raise ValueError("add: one id per text")
308
+ if any(i < 0 for i in ids) or len(set(ids)) != len(ids): raise ValueError("add: ids must be distinct whole numbers >= 0")
309
+ clash = [i for i in ids if i in self._ids]
310
+ if clash:
311
+ raise ValueError(f"add: id {clash[0]} is already in the index" + (f" (and {len(clash) - 1} more)" if len(clash) > 1 else ""))
312
+ flat = [] # (row, text id, start, end, the part, side)
313
+ two = self.mode == "hybrid" and self.dense_chunk != self.chunk
314
+ for d, tx in zip(ids, texts):
315
+ sp = split_text(tx, self.dense_chunk if self.mode == "dense" else self.chunk, self.overlap)
316
+ dn = split_text(tx, self.dense_chunk, self.overlap) if two else sp
317
+ parts = [(a, e, "b") for a, e in sp] if dn == sp else [(a, e, "d") for a, e in dn] + [(a, e, "s") for a, e in sp]
318
+ for a, e, side in parts:
319
+ flat.append((self._row_next + len(flat), d, a, e, tx if (a, e) == (0, len(tx)) else tx[a:e], side))
320
+ whole = dict(zip(ids, texts)); t0 = time.time()
321
+ for b in range(0, len(flat), batch):
322
+ fb = flat[b:b + batch]
323
+ fd = [f for f in fb if f[5] != "s"] if self.mode != "sparse" else []
324
+ fs = [f for f in fb if f[5] != "d"] if self.mode != "dense" else []
325
+ if fd:
326
+ tb = [f[4] for f in fd]; ib = [f[0] for f in fd]
327
+ dv = np.ascontiguousarray(self._dense()(tb, False), dtype=np.float32)
328
+ if dv.ndim != 2 or len(dv) != len(tb): raise ValueError("the dense function must return one row per text")
329
+ if self.vec is None: self.vec = KciVec(dv.shape[1], M=16, efc=200, rerank=200, dedup=self.dedup)
330
+ if self._built:
331
+ for i, v in zip(ib, dv): self.vec.insert(i, v)
332
+ else:
333
+ self.vec.add_many(ib, dv)
334
+ if fs:
335
+ tb = [f[4] for f in fs]; ib = [f[0] for f in fs]
336
+ rows = self._sparse()(tb, False)
337
+ if len(rows) != len(tb): raise ValueError("the sparse function must return one (indices, values) per text")
338
+ if self.sps is None: self.sps = KciSparse(self._sparse_dim)
339
+ for i, (ix, val) in zip(ib, rows):
340
+ if len(ix) == 0: continue # nothing to match on: the dense side still has it
341
+ (self.sps.insert if self._built else self.sps.add)(i, ix, val)
342
+ for r, d, a, e, _, side in fb:
343
+ self._rows[r] = (d, a, e); self._doc_rows.setdefault(d, []).append(r); self._row_next = max(self._row_next, r + 1)
344
+ self._side[r] = side
345
+ if side != "s": self._nside["d"] += 1
346
+ if side != "d": self._nside["s"] += 1
347
+ if d not in self._ids:
348
+ self._ids.add(d)
349
+ if self.keep_text: self.texts[d] = whole[d]
350
+ if len(flat) > batch:
351
+ done = b + len(fb); el = time.time() - t0
352
+ self._say(f" added {done} / {len(flat)}" + (" parts" if len(flat) > len(texts) else "") + f" ({el:.0f} s, about {(len(flat) - done) * el / done:.0f} s to go)")
353
+ if ids: self._next = max(self._next, max(ids) + 1)
354
+ self._added_since += len(ids)
355
+ return ids
356
+
357
+ def delete(self, id):
358
+ """Remove one text. Returns True when it was there."""
359
+ id = int(id)
360
+ if id not in self._ids: return False
361
+ if not self._built: self.build()
362
+ for r in self._doc_rows.pop(id, []):
363
+ side = self._side.pop(r, "b")
364
+ if self.vec is not None and side != "s":
365
+ if not self.vec.delete(r): raise RuntimeError(f"delete: the dense index did not take row {r} of text {id}")
366
+ self._nside["d"] -= 1
367
+ if self.sps is not None and side != "d":
368
+ self.sps.delete(r) # False for a part that had no words to index: nothing to remove
369
+ self._nside["s"] -= 1
370
+ self._rows.pop(r, None)
371
+ self._ids.discard(id); self.texts.pop(id, None)
372
+ return True
373
+
374
+ def build(self):
375
+ """Make the indexes searchable. search() calls this by itself the first time; call it yourself to choose when
376
+ the waiting happens (a second or two per 10,000 texts)."""
377
+ if not self._ids: return
378
+ if self.vec is not None: self.vec.build()
379
+ if self.sps is not None:
380
+ self.sps.build()
381
+ if len(self._ids) >= BLOCKS_FROM:
382
+ self.sps.build_blocks(); self.sps.build_neighbours(20); self._blocks = True
383
+ self._built = True; self._added_since = 0
384
+
385
+ # ---- searching
386
+ def _row_filter(self, filter):
387
+ if filter is None: return None
388
+ rows = self._rows
389
+ if callable(filter): return lambda r: bool(filter(rows[r][0]))
390
+ return [r for d in filter for r in self._doc_rows.get(int(d), ())]
391
+
392
+ def _texts_of(self, lst, depth):
393
+ """a list of parts, best first -> (the list of texts, each once at its best part; text id -> that part)"""
394
+ out, part = [], {}
395
+ for r, s in lst:
396
+ d = self._rows[r][0]
397
+ if d not in part:
398
+ part[d] = r
399
+ if len(out) < depth: out.append((d, s))
400
+ return out, part
401
+
402
+ def _lists(self, query, depth, filter=None):
403
+ """the two result lists as texts: (dense list, sparse list, dense parts, sparse parts); None = side not used"""
404
+ dl = sl = None; dp = sp = {}
405
+ getd = depth * 2 if self._nside["d"] > len(self._ids) else depth # some texts are in parts on that side: look deeper
406
+ gets = depth * 2 if self._nside["s"] > len(self._ids) else depth
407
+ filter = self._row_filter(filter)
408
+ if filter is not None and not callable(filter) and len(filter) == 0:
409
+ return ([] if self.mode != "sparse" and self.vec is not None else None), ([] if self.mode != "dense" and self.sps is not None else None), {}, {}
410
+ if self.mode != "sparse" and self.vec is not None:
411
+ qv = np.ascontiguousarray(self._dense()([query], True), dtype=np.float32)[0]
412
+ dl, dp = self._texts_of(self.vec.search(qv, k=getd, ef=max(200, getd), filter=filter), depth)
413
+ if self.mode != "dense" and self.sps is not None:
414
+ ix, val = self._sparse()([query], True)[0]
415
+ use_phrase = self.phrase and self.keep_text and bool(self.texts)
416
+ if use_phrase: gets = max(gets, self.phrase_depth)
417
+ if len(ix) == 0: sl = []
418
+ elif self._blocks: sl = self.sps.search_blocks(ix, val, k=gets, query_terms=8, heap_factor=1.15, neighbours=20, filter=filter)
419
+ else: sl = self.sps.search(ix, val, k=gets, filter=filter)
420
+ if use_phrase and sl: sl = self._phrase_order(query, sl)
421
+ sl, sp = self._texts_of(sl, depth)
422
+ return dl, sl, dp, sp
423
+
424
+ def _phrase_order(self, query, lst):
425
+ """the word side's parts, those first in which the question's words stand as written. A word = a run of kanji, of
426
+ katakana, or of Latin letters / digits, 2 characters or longer. A part's phrase score = the sum, over the
427
+ question's words it contains verbatim, of log(1 + parts looked at / (1 + parts that contain the word)): a word
428
+ few parts contain counts more. Words in phrase_stop, and with phrase_common the words that are common in the
429
+ whole index, are not counted at all. Order: phrase score, then the BM25 score. The scores given on are phrase
430
+ score + BM25 / (largest BM25 + 1), so that the merge with the dense side keeps this order. Why: character-pair
431
+ BM25 ranks by pairs, and a part can collect many of a question's pairs without holding any of its words."""
432
+ terms = sorted(set(m.group(0).lower() for m in _TERMS.finditer(unicodedata.normalize("NFKC", query))) - self.phrase_stop)
433
+ fn = self._sparse_fn
434
+ if self.phrase_common is not None and isinstance(fn, CharBM25) and fn.n:
435
+ terms = [tm for tm in terms if min((int(fn.df[s]) for s in fn._slots(tm)), default=0) <= self.phrase_common * fn.n]
436
+ if not terms: return lst
437
+ parts = []
438
+ for r, s in lst:
439
+ d, a, e = self._rows[r]; tx = self.texts.get(d)
440
+ parts.append(unicodedata.normalize("NFKC", tx[a:e]).lower() if tx is not None else "")
441
+ has = [[tm in px for px in parts] for tm in terms]
442
+ n = len(lst); w = [math.log(1.0 + n / (1.0 + c)) if c else 0.0 for c in (sum(h) for h in has)]
443
+ top = max(s for _, s in lst) + 1.0
444
+ scored = [(sum(w[j] for j in range(len(terms)) if has[j][i]) + lst[i][1] / top, lst[i][0]) for i in range(n)]
445
+ scored.sort(key=lambda x: -x[0])
446
+ return [(r, s) for s, r in scored]
447
+
448
+ def candidates(self, query, depth_dense=50, depth_sparse=100, filter=None):
449
+ """Everything either side found, unmerged, for a re-ranker of your own: [Cand(id, text, span, dense_rank,
450
+ dense_score, sparse_rank, sparse_score)], the word side's texts first (in its order), then those only the
451
+ dense side found. A side that did not find a text gives None for its rank and score. text / span: the part
452
+ that side matched (the word side's when both did). Nothing is cut off and no weight is applied: which
453
+ candidates are worth keeping is for the re-ranker to say."""
454
+ if not isinstance(query, str): raise TypeError("candidates: the question must be a string")
455
+ if not self._ids: return []
456
+ if not self._built: self.build()
457
+ dl, sl, dp, sp = self._lists(query, max(int(depth_dense), int(depth_sparse), 1), filter)
458
+ dl = (dl or [])[:max(int(depth_dense), 0)]; sl = (sl or [])[:max(int(depth_sparse), 0)]
459
+ dpos = {i: (r + 1, s) for r, (i, s) in enumerate(dl)}; spos = {i: (r + 1, s) for r, (i, s) in enumerate(sl)}
460
+ out = []
461
+ for i in [i for i, _ in sl] + [i for i, _ in dl if i not in spos]:
462
+ row = sp[i] if i in spos else dp[i]
463
+ _, a, e = self._rows[row]; tx = self.texts.get(i)
464
+ if e is None: e = len(tx) if tx is not None else None
465
+ dr, ds = dpos.get(i, (None, None)); sr, ss = spos.get(i, (None, None))
466
+ out.append(Cand(i, None if tx is None else tx[a:e], (a, e), dr, ds, sr, ss))
467
+ return out
468
+
469
+ def _hit(self, d, score, dr, sr, dp, sp):
470
+ r = dp[d] if dr is not None and (sr is None or dr <= sr) else sp[d] # the part from the side that ranks it higher
471
+ _, a, e = self._rows[r]; tx = self.texts.get(d)
472
+ if e is None: e = len(tx) if tx is not None else None
473
+ return Hit(d, score, None if tx is None else tx[a:e], dr, sr, (a, e))
474
+
475
+ def search(self, query, k=5, depth=100, filter=None, rerank=None, depth_dense=50, depth_sparse=100, select=None, select_from=18):
476
+ """The k best texts for a question: [Hit(id, score, text, dense_rank, sparse_rank, span)], best first. rerank: a
477
+ function (question, [texts]) -> one score per text, larger = better (a cross-encoder of your own). select: a
478
+ function (question, [texts]) -> positions; it is shown
479
+ the best select_from texts (after rerank, or of the merged order), the ones it names go first in its order,
480
+ the rest follow as they were. Positions out of range or named twice are ignored."""
481
+ if not isinstance(query, str): raise TypeError("search: the question must be a string")
482
+ if not self._ids: return []
483
+ if not self._built: self.build()
484
+ if rerank is not None:
485
+ if not self.keep_text: raise RuntimeError("search: rerank= needs the texts (keep_text=True)")
486
+ cs = self.candidates(query, depth_dense, depth_sparse, filter)
487
+ if not cs: return []
488
+ sc = [float(x) for x in rerank(query, [c.text for c in cs])]
489
+ if len(sc) != len(cs): raise ValueError("the rerank function must return one score per text")
490
+ order = sorted(range(len(cs)), key=lambda j: -sc[j])
491
+ hits = [Hit(cs[j].id, sc[j], cs[j].text, cs[j].dense_rank, cs[j].sparse_rank, cs[j].span) for j in order[:max(int(k), int(select_from)) if select else int(k)]]
492
+ return self._select(query, hits, select, select_from)[:k] if select else hits
493
+ if select is not None:
494
+ if not self.keep_text: raise RuntimeError("search: select= needs the texts (keep_text=True)")
495
+ hits = self.search(query, k=max(int(k), int(select_from)), depth=depth, filter=filter)
496
+ return self._select(query, hits, select, select_from)[:k]
497
+ depth = max(int(depth), int(k))
498
+ dl, sl, dp, sp = self._lists(query, depth, filter)
499
+ if dl is None or sl is None:
500
+ one = dl if sl is None else sl
501
+ return [self._hit(i, s, r + 1 if sl is None else None, r + 1 if dl is None else None, dp, sp) for r, (i, s) in enumerate((one or [])[:k])]
502
+ if self.w_dense >= 1.0: merged = [(i, s, [r + 1, None]) for r, (i, s) in enumerate(dl[:k])]
503
+ elif self.w_dense <= 0.0: merged = [(i, s, [None, r + 1]) for r, (i, s) in enumerate(sl[:k])]
504
+ else: merged = mix([dl, sl], k=k, weights=[self.w_dense, 1.0 - self.w_dense])
505
+ return [self._hit(i, s, r[0], r[1], dp, sp) for i, s, r in merged]
506
+
507
+ @staticmethod
508
+ def _select(query, hits, select, select_from):
509
+ shown = hits[:max(int(select_from), 0)]
510
+ if not shown: return hits
511
+ picked, seen = [], set()
512
+ for pos in select(query, [h.text for h in shown]):
513
+ try: pos = int(pos)
514
+ except (TypeError, ValueError): continue
515
+ if 0 <= pos < len(shown) and pos not in seen: seen.add(pos); picked.append(pos)
516
+ return [shown[j] for j in picked] + [h for j, h in enumerate(hits) if j not in seen]
517
+
518
+ def tune(self, questions, answers, k=10, depth=100):
519
+ """Check the dense side's weight against questions whose right answers you know, and move it when another weight
520
+ is clearly better for your texts. answers[i]: the ids of the right texts for questions[i] (a set / list, or
521
+ {id: grade}). 50 questions or more; with few, the present weight is kept unless it clearly loses
522
+ (hybrid.choose_weight, prefer=). Look at the table: if one end is far above the other, the weak side's model
523
+ does not suit your texts, and a better model for that side helps more than any weight."""
524
+ if self.mode != "hybrid": raise RuntimeError("tune: only for mode='hybrid'")
525
+ if not self._built: self.build()
526
+ la, lb = [], []
527
+ for q in questions:
528
+ dl, sl, _, _ = self._lists(q, depth); la.append(dl or []); lb.append(sl or [])
529
+ w, table = choose_weight(la, lb, list(answers), k=k, method="mix", prefer=round(self.w_dense, 1))
530
+ self.w_dense = float(w)
531
+ return self.w_dense, table
532
+
533
+ # ---- saving
534
+ def save(self, path, key=None):
535
+ """Write the index into the folder `path`. key (a passphrase, str or bytes): the two index files and the texts
536
+ are encrypted. Without a key the texts go to texts.json as they are. Returns True when the texts were written
537
+ (False with keep_text=False)."""
538
+ if not self._ids: raise RuntimeError("save: the index is empty")
539
+ if not self._built: self.build()
540
+ kb = key.encode("utf-8") if isinstance(key, str) else key
541
+ os.makedirs(path, exist_ok=True)
542
+ if self.vec is not None and not self.vec.save(os.path.join(path, "dense.kvec"), kb): raise RuntimeError("save: writing dense.kvec failed")
543
+ if self.sps is not None: self.sps.save(os.path.join(path, "sparse.kcs"), kb) # raises when it fails
544
+ sp_state = os.path.join(path, "sparse_state.bin") # what the sparse function has counted (CharBM25): with the key, encrypted
545
+ if os.path.exists(sp_state): os.remove(sp_state)
546
+ has_state = self._sparse_fn is not None and hasattr(self._sparse_fn, "state")
547
+ if has_state:
548
+ raw_state = self._sparse_fn.state()
549
+ with open(sp_state, "wb") as f: f.write(raw_state if kb is None else seal(raw_state, kb))
550
+ tp, cp = os.path.join(path, "texts.json"), os.path.join(path, "texts.kct")
551
+ with_text = bool(self.keep_text)
552
+ for old in (tp, cp): # never leave an older copy (a plain one least of all)
553
+ if os.path.exists(old): os.remove(old)
554
+ if with_text:
555
+ raw = json.dumps({str(i): t for i, t in self.texts.items()}, ensure_ascii=False).encode("utf-8")
556
+ if kb is None:
557
+ with open(tp, "wb") as f: f.write(raw)
558
+ else:
559
+ with open(cp, "wb") as f: f.write(seal(raw, kb))
560
+ meta = dict(format=3, lang=self.lang, mode=self.mode, w_dense=self.w_dense, blocks=self._blocks, next=self._next,
561
+ ids=sorted(self._ids), texts=with_text, encrypted=kb is not None,
562
+ dense=getattr(self._dense_fn, "name", None) or self._preset.get("dense"),
563
+ sparse=getattr(self._sparse_fn, "name", None) or self._preset.get("sparse"), sparse_dim=self._sparse_dim,
564
+ chunk=self.chunk, dense_chunk=self.dense_chunk, overlap=self.overlap, row_next=self._row_next,
565
+ sparse_state=has_state, dedup=self.dedup, phrase=self.phrase, phrase_depth=self.phrase_depth,
566
+ phrase_stop=sorted(self.phrase_stop), phrase_common=self.phrase_common,
567
+ rows=[[r, d, a, e, self._side.get(r, "b")] for r, (d, a, e) in sorted(self._rows.items())])
568
+ with open(os.path.join(path, "meta.json"), "w", encoding="utf-8") as f: json.dump(meta, f)
569
+ return with_text
570
+
571
+ @classmethod
572
+ def load(cls, path, key=None, texts=None, dense=None, sparse=None, verbose=True, device=None):
573
+ """Open a saved index. key: the passphrase it was saved with (a wrong one is refused). texts: {id: text} to use
574
+ instead of the saved ones (or when none were saved). dense / sparse: your own functions, when the index was
575
+ made with them."""
576
+ try:
577
+ with open(os.path.join(path, "meta.json"), encoding="utf-8") as f: meta = json.load(f)
578
+ except (OSError, ValueError) as e:
579
+ raise RuntimeError(f"load: {path} is not a saved TextIndex ({e})") from e
580
+ if meta.get("format") not in (1, 2, 3): raise RuntimeError("load: made by a newer version")
581
+ kb = key.encode("utf-8") if isinstance(key, str) else key
582
+ if meta.get("encrypted") and kb is None: raise RuntimeError("load: this index was saved with a key; pass key=")
583
+ if sparse is None and meta.get("sparse") == CharBM25.name: sparse = CharBM25(dim=int(meta.get("sparse_dim") or (1 << 18)))
584
+ ix = cls(meta["lang"], mode=meta["mode"], dense=dense, sparse=sparse, sparse_dim=meta.get("sparse_dim"),
585
+ w_dense=meta["w_dense"], verbose=verbose, chunk=meta.get("chunk", 0), overlap=meta.get("overlap"),
586
+ dense_chunk=meta.get("dense_chunk", meta.get("chunk", 0)), dedup=bool(meta.get("dedup", False)), device=device,
587
+ phrase=bool(meta.get("phrase", False)), phrase_depth=int(meta.get("phrase_depth", 1000)),
588
+ phrase_stop=meta.get("phrase_stop"), phrase_common=meta.get("phrase_common"))
589
+ if meta.get("sparse_state"):
590
+ if not hasattr(ix._sparse_fn, "load_state"): raise RuntimeError("load: this index needs the sparse function it was made with (its counts were saved)")
591
+ try:
592
+ with open(os.path.join(path, "sparse_state.bin"), "rb") as f: raw_state = f.read()
593
+ except OSError as e:
594
+ raise RuntimeError(f"load: sparse_state.bin is missing ({e})") from e
595
+ ix._sparse_fn.load_state(raw_state if kb is None else unseal(raw_state, kb))
596
+ if meta["mode"] != "sparse": ix.vec = KciVec.load(os.path.join(path, "dense.kvec"), key=kb, rerank=200)
597
+ if meta["mode"] != "dense": ix.sps = KciSparse.load(os.path.join(path, "sparse.kcs"), key=kb)
598
+ ix._ids = set(int(i) for i in meta["ids"]); ix._next = int(meta["next"]); ix._blocks = bool(meta["blocks"]); ix._built = True
599
+ for ent in (meta["rows"] if "rows" in meta else [[i, i, 0, None] for i in ix._ids]):
600
+ r, d, a, e = ent[:4]; side = ent[4] if len(ent) > 4 else "b"
601
+ ix._rows[int(r)] = (int(d), int(a), e if e is None else int(e)); ix._doc_rows.setdefault(int(d), []).append(int(r))
602
+ ix._side[int(r)] = side
603
+ if side != "s" and meta["mode"] != "sparse": ix._nside["d"] += 1
604
+ if side != "d" and meta["mode"] != "dense": ix._nside["s"] += 1
605
+ ix._row_next = int(meta.get("row_next", ix._next))
606
+ if texts is not None:
607
+ ix.texts = {int(i): t for i, t in dict(texts).items()}
608
+ elif meta.get("texts") and kb is not None:
609
+ with open(os.path.join(path, "texts.kct"), "rb") as f: ix.texts = {int(i): t for i, t in json.loads(unseal(f.read(), kb).decode("utf-8")).items()}
610
+ elif meta.get("texts"):
611
+ with open(os.path.join(path, "texts.json"), encoding="utf-8") as f: ix.texts = {int(i): t for i, t in json.load(f).items()}
612
+ else:
613
+ ix.keep_text = False
614
+ return ix
615
+
616
+ def __repr__(self):
617
+ return f"TextIndex({self.lang!r}, mode={self.mode!r}, {len(self)} texts, w_dense={self.w_dense})"