structurerag 0.1.0__py3-none-any.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.
- structurerag/__init__.py +56 -0
- structurerag/core/__init__.py +16 -0
- structurerag/core/builder.py +309 -0
- structurerag/core/hsf.py +249 -0
- structurerag/core/reasoner.py +305 -0
- structurerag/grounding/__init__.py +20 -0
- structurerag/grounding/citation.py +173 -0
- structurerag/grounding/reranker.py +160 -0
- structurerag/grounding/retriever.py +980 -0
- structurerag/grounding/verifier.py +774 -0
- structurerag/loaders/__init__.py +6 -0
- structurerag/loaders/pdf.py +36 -0
- structurerag/loaders/text.py +16 -0
- structurerag/semantic.py +307 -0
- structurerag/structurerag.py +455 -0
- structurerag-0.1.0.dist-info/METADATA +186 -0
- structurerag-0.1.0.dist-info/RECORD +20 -0
- structurerag-0.1.0.dist-info/WHEEL +5 -0
- structurerag-0.1.0.dist-info/licenses/LICENSE +21 -0
- structurerag-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,980 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Structure-based retrieval.
|
|
3
|
+
|
|
4
|
+
Deterministic retrieval using an inverted index, BM25 scoring, semantic
|
|
5
|
+
expansion, and phrase normalization, with optional post-retrieval reranking.
|
|
6
|
+
|
|
7
|
+
The index is corpus-level. One retriever holds every document, and all BM25
|
|
8
|
+
statistics (collection size, document frequency, average length) are computed
|
|
9
|
+
across the whole collection, so scores from different documents sit on the same
|
|
10
|
+
scale and can be ranked against each other.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
import re
|
|
15
|
+
from typing import List, Dict, Optional, Tuple, Any, Set, Iterable, Mapping, Union
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from collections import defaultdict
|
|
18
|
+
|
|
19
|
+
try: # optional fast path; the library stays fully functional without it
|
|
20
|
+
import numpy as np
|
|
21
|
+
except ImportError: # pragma: no cover
|
|
22
|
+
np = None
|
|
23
|
+
|
|
24
|
+
from ..core.hsf import HolisticStructuralForm, CompositeFeature, ElementaryFeature
|
|
25
|
+
from ..semantic import SemanticExpander, PhraseMatcher, create_default_expander, create_default_phrase_matcher
|
|
26
|
+
|
|
27
|
+
# Internal identity for one feature: (document_id, feature_id).
|
|
28
|
+
DocKey = Tuple[str, str]
|
|
29
|
+
|
|
30
|
+
DocumentInput = Union[HolisticStructuralForm,
|
|
31
|
+
Mapping[str, HolisticStructuralForm],
|
|
32
|
+
Iterable[HolisticStructuralForm]]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _as_document_map(documents: DocumentInput) -> Dict[str, HolisticStructuralForm]:
|
|
36
|
+
"""Normalize the accepted document shapes into {document_id: HSF}."""
|
|
37
|
+
if isinstance(documents, HolisticStructuralForm):
|
|
38
|
+
return {documents.document_id: documents}
|
|
39
|
+
if isinstance(documents, Mapping):
|
|
40
|
+
return dict(documents)
|
|
41
|
+
return {hsf.document_id: hsf for hsf in documents}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _is_word_token(token: str) -> bool:
|
|
45
|
+
"""True for word tokens; excludes punctuation-only tokens ('.', '--', ...).
|
|
46
|
+
|
|
47
|
+
The builder stores punctuation as word features. Sentence-level scoring is
|
|
48
|
+
indifferent (queries never contain bare punctuation), but document-level
|
|
49
|
+
tf maps and lengths must exclude them to stay comparable to textbook BM25.
|
|
50
|
+
"""
|
|
51
|
+
return re.fullmatch(r'\w+|\d[\d,]*(?:\.\d+)?', token) is not None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# ─── Inverted Index ──────────────────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class InvertedIndex:
|
|
59
|
+
"""
|
|
60
|
+
Maps words to (doc_key, position) tuples over a whole corpus.
|
|
61
|
+
|
|
62
|
+
Only sentence features are indexed. Those are the only units retrieval can
|
|
63
|
+
return, so indexing document- and paragraph-level composites would both
|
|
64
|
+
waste work and inflate ``avg_feature_length``, which BM25 uses to normalize
|
|
65
|
+
result length.
|
|
66
|
+
"""
|
|
67
|
+
index: Dict[str, List[Tuple[DocKey, int]]] = field(default_factory=lambda: defaultdict(list))
|
|
68
|
+
feature_lengths: Dict[DocKey, int] = field(default_factory=dict)
|
|
69
|
+
doc_freq: Dict[str, int] = field(default_factory=dict)
|
|
70
|
+
# Query-time caches, populated at build: per-sentence text and term
|
|
71
|
+
# frequencies (so scoring never re-flattens a sentence), and per-word idf
|
|
72
|
+
# (static per index build — N and df do not change between queries).
|
|
73
|
+
feature_texts: Dict[DocKey, str] = field(default_factory=dict)
|
|
74
|
+
feature_tf: Dict[DocKey, Dict[str, int]] = field(default_factory=dict)
|
|
75
|
+
idf: Dict[str, float] = field(default_factory=dict)
|
|
76
|
+
# Document-level aggregates for search_documents(): per-doc term
|
|
77
|
+
# frequencies (the sum of the doc's sentence tfs) and lengths, the number
|
|
78
|
+
# of documents containing each word, and doc-count/avg-length.
|
|
79
|
+
doc_tf: Dict[str, Dict[str, int]] = field(default_factory=dict)
|
|
80
|
+
doc_lengths: Dict[str, int] = field(default_factory=dict)
|
|
81
|
+
doc_df: Dict[str, int] = field(default_factory=dict)
|
|
82
|
+
num_docs: int = 0
|
|
83
|
+
doc_avg_length: float = 0.0
|
|
84
|
+
# Canonical lowercase vocabulary: every tf dict and posting references one
|
|
85
|
+
# shared string object per word (megabytes saved on large corpora).
|
|
86
|
+
_vocab: Dict[str, str] = field(default_factory=dict)
|
|
87
|
+
# Optional numpy fast path (built lazily, only when numpy is importable):
|
|
88
|
+
# row tables mapping row index -> DocKey, per-row length arrays, and
|
|
89
|
+
# per-word (row_ids, tfs) arrays. Same math as the Python scorer.
|
|
90
|
+
rows: List[DocKey] = field(default_factory=list)
|
|
91
|
+
row_of: Dict[DocKey, int] = field(default_factory=dict)
|
|
92
|
+
dl_arr: Any = None
|
|
93
|
+
np_postings: Dict[str, Any] = field(default_factory=dict)
|
|
94
|
+
doc_rows: List[str] = field(default_factory=list)
|
|
95
|
+
doc_row_of: Dict[str, int] = field(default_factory=dict)
|
|
96
|
+
doc_dl_arr: Any = None
|
|
97
|
+
doc_np_postings: Dict[str, Any] = field(default_factory=dict)
|
|
98
|
+
num_features: int = 0
|
|
99
|
+
avg_feature_length: float = 0.0
|
|
100
|
+
_built: bool = False
|
|
101
|
+
_total_length: int = 0
|
|
102
|
+
_idf_dirty: bool = True
|
|
103
|
+
_doc_stats_dirty: bool = True
|
|
104
|
+
_np_dirty: bool = True
|
|
105
|
+
_dnp_dirty: bool = True
|
|
106
|
+
_indexed_docs: Set[str] = field(default_factory=set)
|
|
107
|
+
|
|
108
|
+
def build(self, documents: DocumentInput) -> None:
|
|
109
|
+
"""Rebuild the index from scratch across the whole collection."""
|
|
110
|
+
self.index.clear()
|
|
111
|
+
self.feature_lengths.clear()
|
|
112
|
+
self.doc_freq.clear()
|
|
113
|
+
self.feature_texts.clear()
|
|
114
|
+
self.feature_tf.clear()
|
|
115
|
+
self.idf.clear()
|
|
116
|
+
self._idf_dirty = True
|
|
117
|
+
self.doc_tf.clear()
|
|
118
|
+
self.doc_lengths.clear()
|
|
119
|
+
self.doc_df.clear()
|
|
120
|
+
self.num_docs = 0
|
|
121
|
+
self.doc_avg_length = 0.0
|
|
122
|
+
self._doc_stats_dirty = True
|
|
123
|
+
self._vocab.clear()
|
|
124
|
+
self.rows.clear()
|
|
125
|
+
self.row_of.clear()
|
|
126
|
+
self.dl_arr = None
|
|
127
|
+
self.np_postings.clear()
|
|
128
|
+
self.doc_rows.clear()
|
|
129
|
+
self.doc_row_of.clear()
|
|
130
|
+
self.doc_dl_arr = None
|
|
131
|
+
self.doc_np_postings.clear()
|
|
132
|
+
self._np_dirty = True
|
|
133
|
+
self._dnp_dirty = True
|
|
134
|
+
self.num_features = 0
|
|
135
|
+
self._total_length = 0
|
|
136
|
+
self._indexed_docs.clear()
|
|
137
|
+
|
|
138
|
+
for doc_id, hsf in _as_document_map(documents).items():
|
|
139
|
+
self.add_document(doc_id, hsf)
|
|
140
|
+
|
|
141
|
+
self._finalize()
|
|
142
|
+
|
|
143
|
+
def add_document(self, doc_id: str, hsf: HolisticStructuralForm) -> None:
|
|
144
|
+
"""Index one document. Documents already indexed are skipped."""
|
|
145
|
+
if doc_id in self._indexed_docs:
|
|
146
|
+
return
|
|
147
|
+
self._indexed_docs.add(doc_id)
|
|
148
|
+
|
|
149
|
+
doc_tf_acc: Dict[str, int] = {}
|
|
150
|
+
doc_tokens: List[str] = []
|
|
151
|
+
|
|
152
|
+
for feat_id, feature in hsf.composite_features.items():
|
|
153
|
+
if feature.feature_type != 'sentence':
|
|
154
|
+
continue
|
|
155
|
+
|
|
156
|
+
key = (doc_id, feat_id)
|
|
157
|
+
words = self._extract_words(feature, hsf)
|
|
158
|
+
self.feature_lengths[key] = len(words)
|
|
159
|
+
self.feature_texts[key] = " ".join(words)
|
|
160
|
+
self._total_length += len(words)
|
|
161
|
+
self.num_features += 1
|
|
162
|
+
|
|
163
|
+
tf: Dict[str, int] = defaultdict(int)
|
|
164
|
+
seen: Set[str] = set()
|
|
165
|
+
for pos, word in enumerate(words):
|
|
166
|
+
lw = word.lower()
|
|
167
|
+
# Canonical string: all dicts share one object per word.
|
|
168
|
+
w = self._vocab.setdefault(lw, lw)
|
|
169
|
+
tf[w] += 1
|
|
170
|
+
doc_tokens.append(w)
|
|
171
|
+
self.index[w].append((key, pos))
|
|
172
|
+
if w not in seen:
|
|
173
|
+
self.doc_freq[w] = self.doc_freq.get(w, 0) + 1
|
|
174
|
+
seen.add(w)
|
|
175
|
+
self.feature_tf[key] = dict(tf)
|
|
176
|
+
for w, count in tf.items():
|
|
177
|
+
doc_tf_acc[w] = doc_tf_acc.get(w, 0) + count
|
|
178
|
+
|
|
179
|
+
# Document-level aggregates: a doc's tf is the sum of its sentences'
|
|
180
|
+
# tfs, and doc_df counts DOCUMENTS containing a word (not sentences).
|
|
181
|
+
# Punctuation-only tokens (the builder stores '.' etc. as word
|
|
182
|
+
# features) are excluded: they can never match a query term and would
|
|
183
|
+
# only inflate tf maps and lengths away from textbook BM25.
|
|
184
|
+
doc_tf_acc = {w: c for w, c in doc_tf_acc.items()
|
|
185
|
+
if _is_word_token(w)}
|
|
186
|
+
self.doc_tf[doc_id] = doc_tf_acc
|
|
187
|
+
self.doc_lengths[doc_id] = sum(1 for w in doc_tokens
|
|
188
|
+
if _is_word_token(w))
|
|
189
|
+
for w in doc_tf_acc:
|
|
190
|
+
self.doc_df[w] = self.doc_df.get(w, 0) + 1
|
|
191
|
+
self.num_docs += 1
|
|
192
|
+
self._doc_stats_dirty = True
|
|
193
|
+
self._np_dirty = True
|
|
194
|
+
self._dnp_dirty = True
|
|
195
|
+
|
|
196
|
+
self._finalize()
|
|
197
|
+
|
|
198
|
+
def _finalize(self) -> None:
|
|
199
|
+
self.avg_feature_length = self._total_length / max(1, self.num_features)
|
|
200
|
+
# idf is NOT recomputed here: _finalize runs per document, and an
|
|
201
|
+
# O(vocab) pass per document made indexing O(docs x vocab). Mark dirty
|
|
202
|
+
# instead; _ensure_idf() recomputes it once before the first search.
|
|
203
|
+
self._idf_dirty = True
|
|
204
|
+
self._built = True
|
|
205
|
+
|
|
206
|
+
def _ensure_idf(self) -> None:
|
|
207
|
+
if not self._idf_dirty:
|
|
208
|
+
return
|
|
209
|
+
self.idf = {
|
|
210
|
+
w: max(0.1, math.log((self.num_features - df + 0.5) / (df + 0.5) + 1))
|
|
211
|
+
for w, df in self.doc_freq.items()
|
|
212
|
+
}
|
|
213
|
+
self._idf_dirty = False
|
|
214
|
+
|
|
215
|
+
def _ensure_doc_stats(self) -> None:
|
|
216
|
+
if not self._doc_stats_dirty:
|
|
217
|
+
return
|
|
218
|
+
self.doc_avg_length = sum(self.doc_lengths.values()) / max(1, self.num_docs)
|
|
219
|
+
self._doc_stats_dirty = False
|
|
220
|
+
|
|
221
|
+
def _ensure_np(self) -> None:
|
|
222
|
+
"""Build row tables and per-word (row_ids, tfs) arrays for the
|
|
223
|
+
sentence-level numpy scorer. No-op when numpy is unavailable."""
|
|
224
|
+
if np is None or not self._np_dirty:
|
|
225
|
+
return
|
|
226
|
+
self.rows = list(self.feature_lengths.keys())
|
|
227
|
+
self.row_of = {k: i for i, k in enumerate(self.rows)}
|
|
228
|
+
self.dl_arr = np.array([self.feature_lengths[k] for k in self.rows],
|
|
229
|
+
dtype=np.float64)
|
|
230
|
+
self.np_postings = {}
|
|
231
|
+
for word, entries in self.index.items():
|
|
232
|
+
counts: Dict[DocKey, int] = {}
|
|
233
|
+
for key, _ in entries:
|
|
234
|
+
counts[key] = counts.get(key, 0) + 1
|
|
235
|
+
n = len(counts)
|
|
236
|
+
ids = np.fromiter((self.row_of[k] for k in counts),
|
|
237
|
+
dtype=np.int64, count=n)
|
|
238
|
+
tfs = np.fromiter(counts.values(), dtype=np.float64, count=n)
|
|
239
|
+
self.np_postings[word] = (ids, tfs)
|
|
240
|
+
self._np_dirty = False
|
|
241
|
+
|
|
242
|
+
def _ensure_doc_np(self) -> None:
|
|
243
|
+
"""Row tables + arrays for the document-level numpy scorer."""
|
|
244
|
+
if np is None or not self._dnp_dirty:
|
|
245
|
+
return
|
|
246
|
+
self.doc_rows = list(self.doc_lengths.keys())
|
|
247
|
+
self.doc_row_of = {d: i for i, d in enumerate(self.doc_rows)}
|
|
248
|
+
self.doc_dl_arr = np.array([self.doc_lengths[d] for d in self.doc_rows],
|
|
249
|
+
dtype=np.float64)
|
|
250
|
+
self.doc_np_postings = {}
|
|
251
|
+
per_word: Dict[str, Tuple[List[int], List[float]]] = {}
|
|
252
|
+
for doc_id, tf_map in self.doc_tf.items():
|
|
253
|
+
row = self.doc_row_of[doc_id]
|
|
254
|
+
for word, tf in tf_map.items():
|
|
255
|
+
ids, tfs = per_word.setdefault(word, ([], []))
|
|
256
|
+
ids.append(row)
|
|
257
|
+
tfs.append(float(tf))
|
|
258
|
+
self.doc_np_postings = {
|
|
259
|
+
w: (np.array(ids, dtype=np.int64), np.array(tfs))
|
|
260
|
+
for w, (ids, tfs) in per_word.items()
|
|
261
|
+
}
|
|
262
|
+
self._dnp_dirty = False
|
|
263
|
+
|
|
264
|
+
def _extract_words(self, feature: CompositeFeature,
|
|
265
|
+
hsf: HolisticStructuralForm) -> List[str]:
|
|
266
|
+
"""Flatten a composite feature into its word values, in source order."""
|
|
267
|
+
words = []
|
|
268
|
+
if feature.feature_type == 'sentence':
|
|
269
|
+
for child in sorted(feature.children, key=lambda c: c.position):
|
|
270
|
+
words.append(child.value)
|
|
271
|
+
else:
|
|
272
|
+
for child_id in feature.child_ids:
|
|
273
|
+
child = hsf.get_feature(child_id)
|
|
274
|
+
if isinstance(child, CompositeFeature):
|
|
275
|
+
words.extend(self._extract_words(child, hsf))
|
|
276
|
+
elif isinstance(child, ElementaryFeature):
|
|
277
|
+
words.append(child.value)
|
|
278
|
+
return words
|
|
279
|
+
|
|
280
|
+
def lookup(self, word: str) -> List[Tuple[DocKey, int]]:
|
|
281
|
+
return self.index.get(word.lower(), [])
|
|
282
|
+
|
|
283
|
+
def get_features_containing(self, word: str) -> Set[DocKey]:
|
|
284
|
+
return set(loc[0] for loc in self.lookup(word))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
# ─── Search Results ──────────────────────────────────────────────────────────
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@dataclass
|
|
291
|
+
class SearchResult:
|
|
292
|
+
"""Result of a structure-based search."""
|
|
293
|
+
feature_id: str
|
|
294
|
+
feature_type: str
|
|
295
|
+
content: str
|
|
296
|
+
score: float
|
|
297
|
+
path: List[str]
|
|
298
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
299
|
+
|
|
300
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
301
|
+
return {
|
|
302
|
+
'feature_id': self.feature_id, 'feature_type': self.feature_type,
|
|
303
|
+
'content': self.content, 'score': self.score,
|
|
304
|
+
'path': self.path, 'metadata': self.metadata
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# ─── Retriever ────────────────────────────────────────────────────────────────
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class StructureRetriever:
|
|
312
|
+
"""
|
|
313
|
+
Structure-based retriever: lexical matching only, with deterministic
|
|
314
|
+
ordering and no model dependencies.
|
|
315
|
+
|
|
316
|
+
Features:
|
|
317
|
+
- Corpus-level inverted index for O(1) word lookups
|
|
318
|
+
- BM25 scoring over corpus-wide statistics
|
|
319
|
+
- Semantic expansion (synonyms, morphology) and phrase normalization
|
|
320
|
+
- Multi-term query support
|
|
321
|
+
- Optional reranker for post-retrieval precision
|
|
322
|
+
"""
|
|
323
|
+
|
|
324
|
+
def __init__(self, documents: DocumentInput,
|
|
325
|
+
semantic_expander: Optional[SemanticExpander] = None,
|
|
326
|
+
phrase_matcher: Optional[PhraseMatcher] = None,
|
|
327
|
+
reranker: Optional[Any] = None):
|
|
328
|
+
self.documents = _as_document_map(documents)
|
|
329
|
+
self.semantic_expander = semantic_expander or create_default_expander()
|
|
330
|
+
self.phrase_matcher = phrase_matcher or create_default_phrase_matcher()
|
|
331
|
+
self.inverted_index = InvertedIndex()
|
|
332
|
+
self.reranker = reranker
|
|
333
|
+
|
|
334
|
+
# Populated incrementally as documents are registered.
|
|
335
|
+
self._sentences: Dict[DocKey, CompositeFeature] = {}
|
|
336
|
+
self._key_of: Dict[str, DocKey] = {}
|
|
337
|
+
self._parent_of: Dict[DocKey, DocKey] = {}
|
|
338
|
+
self._new_docs: List[str] = [d for d in self.documents]
|
|
339
|
+
self._index_built = False
|
|
340
|
+
|
|
341
|
+
for doc_id, hsf in self.documents.items():
|
|
342
|
+
self._register(doc_id, hsf)
|
|
343
|
+
|
|
344
|
+
self.build_index()
|
|
345
|
+
|
|
346
|
+
# ── Registration ─────────────────────────────────────────────────────
|
|
347
|
+
|
|
348
|
+
def _register(self, doc_id: str, hsf: HolisticStructuralForm) -> None:
|
|
349
|
+
"""Index the ID maps of one document. Cheap; safe to call per document."""
|
|
350
|
+
for feat_id, feature in hsf.composite_features.items():
|
|
351
|
+
key = (doc_id, feat_id)
|
|
352
|
+
# An ID collision would silently reroute get_by_id to the wrong
|
|
353
|
+
# document. Fail loudly instead of overwriting.
|
|
354
|
+
existing = self._key_of.get(feat_id)
|
|
355
|
+
if existing is not None and existing != key:
|
|
356
|
+
raise ValueError(
|
|
357
|
+
f"Feature ID '{feat_id}' is already registered for "
|
|
358
|
+
f"document '{existing[0]}'"
|
|
359
|
+
)
|
|
360
|
+
self._key_of[feat_id] = key
|
|
361
|
+
if feature.feature_type == 'sentence':
|
|
362
|
+
self._sentences[key] = feature
|
|
363
|
+
|
|
364
|
+
# Sentence children are inline; composite children are by ID.
|
|
365
|
+
for child in feature.children:
|
|
366
|
+
self._key_of.setdefault(child.id, (doc_id, child.id))
|
|
367
|
+
self._parent_of[(doc_id, child.id)] = key
|
|
368
|
+
for child_id in feature.child_ids:
|
|
369
|
+
self._key_of.setdefault(child_id, (doc_id, child_id))
|
|
370
|
+
self._parent_of.setdefault((doc_id, child_id), key)
|
|
371
|
+
|
|
372
|
+
# hierarchy is authoritative for parentage; it also covers the document
|
|
373
|
+
# composite, whose children are stored as IDs only.
|
|
374
|
+
for parent_id, child_ids in hsf.hierarchy.items():
|
|
375
|
+
for child_id in child_ids:
|
|
376
|
+
self._parent_of[(doc_id, child_id)] = (doc_id, parent_id)
|
|
377
|
+
|
|
378
|
+
if doc_id not in self._new_docs:
|
|
379
|
+
self._new_docs.append(doc_id)
|
|
380
|
+
self._index_built = False
|
|
381
|
+
|
|
382
|
+
def add_document(self, hsf: HolisticStructuralForm,
|
|
383
|
+
doc_id: Optional[str] = None) -> str:
|
|
384
|
+
"""
|
|
385
|
+
Add one document to the collection.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
hsf: The document's structure.
|
|
389
|
+
doc_id: Overrides ``hsf.document_id`` as the registry key, which
|
|
390
|
+
lets a caller import the same HSF twice without a collision.
|
|
391
|
+
The HSF is never mutated.
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
The key the document was registered under.
|
|
395
|
+
|
|
396
|
+
Raises:
|
|
397
|
+
ValueError: If ``doc_id`` is already taken.
|
|
398
|
+
"""
|
|
399
|
+
doc_id = doc_id or hsf.document_id
|
|
400
|
+
if doc_id in self.documents:
|
|
401
|
+
raise ValueError(
|
|
402
|
+
f"Document '{doc_id}' is already indexed. Remove it first or "
|
|
403
|
+
f"pass a distinct doc_id."
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
self.documents[doc_id] = hsf
|
|
407
|
+
self._register(doc_id, hsf)
|
|
408
|
+
self.build_index()
|
|
409
|
+
return doc_id
|
|
410
|
+
|
|
411
|
+
def remove_document(self, doc_id: str) -> bool:
|
|
412
|
+
"""Remove one document from the collection and rebuild the index."""
|
|
413
|
+
if doc_id not in self.documents:
|
|
414
|
+
return False
|
|
415
|
+
|
|
416
|
+
del self.documents[doc_id]
|
|
417
|
+
for key in [k for k in self._sentences if k[0] == doc_id]:
|
|
418
|
+
self._sentences.pop(key)
|
|
419
|
+
self._key_of = {fid: k for fid, k in self._key_of.items() if k[0] != doc_id}
|
|
420
|
+
self._parent_of = {k: v for k, v in self._parent_of.items()
|
|
421
|
+
if k[0] != doc_id and v[0] != doc_id}
|
|
422
|
+
|
|
423
|
+
# BM25 document frequency cannot be corrected by subtraction, so every
|
|
424
|
+
# surviving document is re-queued and the index is rebuilt from scratch.
|
|
425
|
+
self.inverted_index = InvertedIndex()
|
|
426
|
+
self._new_docs = list(self.documents)
|
|
427
|
+
self._index_built = False
|
|
428
|
+
self.build_index()
|
|
429
|
+
return True
|
|
430
|
+
|
|
431
|
+
def build_index(self) -> None:
|
|
432
|
+
"""
|
|
433
|
+
Index pending documents into the inverted index.
|
|
434
|
+
|
|
435
|
+
Called by :meth:`add_document` and :meth:`remove_document`, so the
|
|
436
|
+
inverted index always reflects the collection. Call it directly only
|
|
437
|
+
after mutating ``documents`` by hand.
|
|
438
|
+
"""
|
|
439
|
+
if self._index_built:
|
|
440
|
+
return
|
|
441
|
+
|
|
442
|
+
for doc_id in self._new_docs:
|
|
443
|
+
hsf = self.documents.get(doc_id)
|
|
444
|
+
if hsf is not None:
|
|
445
|
+
self.inverted_index.add_document(doc_id, hsf)
|
|
446
|
+
|
|
447
|
+
self._new_docs.clear()
|
|
448
|
+
self._index_built = True
|
|
449
|
+
|
|
450
|
+
# ── Search ───────────────────────────────────────────────────────────
|
|
451
|
+
|
|
452
|
+
def search(self, query: str, top_k: int = 5,
|
|
453
|
+
fuzzy_threshold: float = 0.20,
|
|
454
|
+
use_semantic_expansion: bool = True,
|
|
455
|
+
document_ids: Optional[Iterable[str]] = None) -> List[SearchResult]:
|
|
456
|
+
"""
|
|
457
|
+
Rank sentences in the collection against ``query``.
|
|
458
|
+
|
|
459
|
+
Args:
|
|
460
|
+
query: Natural language or keyword query.
|
|
461
|
+
top_k: Maximum results.
|
|
462
|
+
fuzzy_threshold: Minimum score to keep a result.
|
|
463
|
+
use_semantic_expansion: Widen candidates with synonyms.
|
|
464
|
+
document_ids: Restrict the search to these documents. All of them
|
|
465
|
+
are still scored against one set of corpus statistics, so the
|
|
466
|
+
ranking stays comparable across documents.
|
|
467
|
+
"""
|
|
468
|
+
self.build_index()
|
|
469
|
+
|
|
470
|
+
# Over-retrieve when reranking so the reranker has more candidates
|
|
471
|
+
retrieval_k = top_k * 3 if self.reranker else top_k
|
|
472
|
+
|
|
473
|
+
normalized_query, _ = self.phrase_matcher.normalize_query(query)
|
|
474
|
+
original_terms = self._tokenize(normalized_query)
|
|
475
|
+
|
|
476
|
+
# Synonyms widen the candidate net; scoring only ever looks at the
|
|
477
|
+
# original terms, so a synonym hit is counted once, not twice.
|
|
478
|
+
if use_semantic_expansion:
|
|
479
|
+
candidate_terms, _ = self.semantic_expander.expand_query(normalized_query)
|
|
480
|
+
else:
|
|
481
|
+
candidate_terms = original_terms
|
|
482
|
+
|
|
483
|
+
# An empty query has nothing to match, so it has no results.
|
|
484
|
+
if not candidate_terms:
|
|
485
|
+
return []
|
|
486
|
+
|
|
487
|
+
self.inverted_index._ensure_idf()
|
|
488
|
+
candidates = self._find_candidates(candidate_terms)
|
|
489
|
+
if document_ids is not None:
|
|
490
|
+
allowed = set(document_ids)
|
|
491
|
+
candidates = {key for key in candidates if key[0] in allowed}
|
|
492
|
+
|
|
493
|
+
# Alternatives and the length normalizer depend only on the query, not
|
|
494
|
+
# on the candidate, so resolve them once per query.
|
|
495
|
+
alternatives = {term: self._alternatives_of(term)
|
|
496
|
+
for term in set(original_terms)}
|
|
497
|
+
avgdl_safe = max(1, self.inverted_index.avg_feature_length)
|
|
498
|
+
|
|
499
|
+
# Fast path: vectorized scoring (identical math and summation order).
|
|
500
|
+
np_scores = self._score_candidates_numpy(candidates, original_terms,
|
|
501
|
+
alternatives, avgdl_safe)
|
|
502
|
+
# Keys travel alongside results so identity is never re-derived from a
|
|
503
|
+
# raw feature id, which would be ambiguous if ids ever collided.
|
|
504
|
+
# rank_score is the raw BM25 sum: unbounded, order-exact. score is the
|
|
505
|
+
# reported 0..1 value, squashed monotonically so rank order survives.
|
|
506
|
+
# Score first, construct SearchResult only for survivors: most
|
|
507
|
+
# candidates die at the threshold, and content/path/metadata are pure
|
|
508
|
+
# overhead for them. Stored negated so plain tuple sort = rank order.
|
|
509
|
+
scored: List[Tuple[float, DocKey]] = []
|
|
510
|
+
if np_scores is not None:
|
|
511
|
+
for key, rank_score in np_scores.items():
|
|
512
|
+
if key not in self._sentences:
|
|
513
|
+
continue
|
|
514
|
+
score = rank_score / (rank_score + 1.0)
|
|
515
|
+
if score < fuzzy_threshold:
|
|
516
|
+
continue
|
|
517
|
+
scored.append((-rank_score, key))
|
|
518
|
+
else:
|
|
519
|
+
for key in candidates:
|
|
520
|
+
if key not in self._sentences:
|
|
521
|
+
continue
|
|
522
|
+
|
|
523
|
+
rank_score = self._score_feature(original_terms, key, alternatives,
|
|
524
|
+
avgdl_safe)
|
|
525
|
+
score = rank_score / (rank_score + 1.0) # monotonic, 0..1, order-preserving
|
|
526
|
+
if score < fuzzy_threshold:
|
|
527
|
+
continue
|
|
528
|
+
scored.append((-rank_score, key))
|
|
529
|
+
|
|
530
|
+
scored.sort()
|
|
531
|
+
scored = scored[:retrieval_k]
|
|
532
|
+
|
|
533
|
+
results = []
|
|
534
|
+
for neg_score, key in scored:
|
|
535
|
+
rank_score = -neg_score
|
|
536
|
+
feature = self._sentences[key]
|
|
537
|
+
# Do NOT write feature_texts.get(key, self._sentence_text(feature)):
|
|
538
|
+
# the default is evaluated eagerly, which re-sorted every survivor
|
|
539
|
+
# sentence 966 times per query for a cache that always hits.
|
|
540
|
+
content = self.inverted_index.feature_texts.get(key)
|
|
541
|
+
if content is None:
|
|
542
|
+
content = self._sentence_text(feature)
|
|
543
|
+
results.append(SearchResult(
|
|
544
|
+
feature_id=key[1], feature_type=feature.feature_type,
|
|
545
|
+
content=content,
|
|
546
|
+
score=rank_score / (rank_score + 1.0),
|
|
547
|
+
path=self._get_feature_path(key),
|
|
548
|
+
metadata={**feature.metadata, 'document_id': key[0]},
|
|
549
|
+
))
|
|
550
|
+
|
|
551
|
+
if self.reranker:
|
|
552
|
+
results = self.reranker.rerank(query, results, top_k=top_k)
|
|
553
|
+
|
|
554
|
+
return results[:top_k]
|
|
555
|
+
|
|
556
|
+
# ── Document-level retrieval ─────────────────────────────────────────
|
|
557
|
+
|
|
558
|
+
def search_documents(self, query: str, top_k: int = 5,
|
|
559
|
+
use_semantic_expansion: bool = True,
|
|
560
|
+
document_ids: Optional[Iterable[str]] = None) -> List[SearchResult]:
|
|
561
|
+
"""
|
|
562
|
+
Rank whole DOCUMENTS with textbook Okapi BM25.
|
|
563
|
+
|
|
564
|
+
The sentence index stays the source of truth: a document's term
|
|
565
|
+
frequencies are the sum of its sentences' cached tfs and its length is
|
|
566
|
+
the sum of sentence lengths, so no second tokenization pass can drift
|
|
567
|
+
from the sentence path. Statistics are document-level (N = number of
|
|
568
|
+
documents, df = documents containing a term), which is what makes the
|
|
569
|
+
score comparable to textbook BM25: the sentence path's
|
|
570
|
+
max-aggregation to documents loses the term frequency a document
|
|
571
|
+
accumulates across sentences, and that is exactly the ranking gap
|
|
572
|
+
measured on BEIR.
|
|
573
|
+
|
|
574
|
+
Candidates may be widened by synonyms (same policy as search()), but
|
|
575
|
+
scoring uses only the original query terms, one contribution per term,
|
|
576
|
+
in term order — the score sum is deterministic. Scores are squashed
|
|
577
|
+
with the same monotonic raw/(raw+1) mapping as search().
|
|
578
|
+
|
|
579
|
+
Returns:
|
|
580
|
+
SearchResult per document (feature_type 'document'), ranked best
|
|
581
|
+
first, ties broken by document ID. Only documents with a positive
|
|
582
|
+
score are returned.
|
|
583
|
+
"""
|
|
584
|
+
self.build_index()
|
|
585
|
+
idx = self.inverted_index
|
|
586
|
+
idx._ensure_doc_stats()
|
|
587
|
+
|
|
588
|
+
normalized_query, _ = self.phrase_matcher.normalize_query(query)
|
|
589
|
+
original_terms = self._tokenize(normalized_query)
|
|
590
|
+
if not original_terms:
|
|
591
|
+
return []
|
|
592
|
+
|
|
593
|
+
candidate_terms = original_terms
|
|
594
|
+
if use_semantic_expansion:
|
|
595
|
+
candidate_terms, _ = self.semantic_expander.expand_query(normalized_query)
|
|
596
|
+
|
|
597
|
+
# Docs reachable from any candidate term, via the sentence postings.
|
|
598
|
+
candidates: Set[str] = set()
|
|
599
|
+
for term in candidate_terms:
|
|
600
|
+
for key, _ in idx.index.get(term, ()):
|
|
601
|
+
candidates.add(key[0])
|
|
602
|
+
if document_ids is not None:
|
|
603
|
+
allowed = set(document_ids)
|
|
604
|
+
candidates &= allowed
|
|
605
|
+
|
|
606
|
+
k1 = 1.5 # term frequency saturation
|
|
607
|
+
b = 0.75 # length normalization
|
|
608
|
+
N = idx.num_docs
|
|
609
|
+
avgdl = max(1, idx.doc_avg_length)
|
|
610
|
+
idf_of = {}
|
|
611
|
+
for term in set(original_terms):
|
|
612
|
+
df = idx.doc_df.get(term, 0)
|
|
613
|
+
if df:
|
|
614
|
+
idf_of[term] = max(0.1, math.log((N - df + 0.5) / (df + 0.5) + 1))
|
|
615
|
+
|
|
616
|
+
# Over-retrieve when reranking so the reranker has more candidates.
|
|
617
|
+
retrieval_k = top_k * 3 if self.reranker else top_k
|
|
618
|
+
|
|
619
|
+
np_scores = self._score_docs_numpy(candidates, original_terms,
|
|
620
|
+
idf_of, max(1, avgdl))
|
|
621
|
+
scored: List[Tuple[float, str]] = []
|
|
622
|
+
if np_scores is not None:
|
|
623
|
+
for doc_id, score in np_scores.items():
|
|
624
|
+
if score <= 0.0 or not idx.doc_tf.get(doc_id):
|
|
625
|
+
continue
|
|
626
|
+
scored.append((-score, doc_id))
|
|
627
|
+
else:
|
|
628
|
+
for doc_id in candidates:
|
|
629
|
+
tf_map = idx.doc_tf.get(doc_id)
|
|
630
|
+
if not tf_map:
|
|
631
|
+
continue
|
|
632
|
+
doc_len = idx.doc_lengths.get(doc_id, 0)
|
|
633
|
+
score = 0.0
|
|
634
|
+
for term in original_terms:
|
|
635
|
+
idf = idf_of.get(term)
|
|
636
|
+
if idf is None: # term absent from every document
|
|
637
|
+
continue
|
|
638
|
+
tf = tf_map.get(term, 0)
|
|
639
|
+
if not tf:
|
|
640
|
+
continue
|
|
641
|
+
den = tf + k1 * (1 - b + b * doc_len / avgdl)
|
|
642
|
+
score += idf * (tf * (k1 + 1) / den)
|
|
643
|
+
if score <= 0.0:
|
|
644
|
+
continue
|
|
645
|
+
scored.append((-score, doc_id))
|
|
646
|
+
|
|
647
|
+
scored.sort()
|
|
648
|
+
|
|
649
|
+
results = []
|
|
650
|
+
for neg_score, doc_id in scored[:retrieval_k]:
|
|
651
|
+
score = -neg_score
|
|
652
|
+
hsf = self.documents.get(doc_id)
|
|
653
|
+
results.append(SearchResult(
|
|
654
|
+
feature_id=doc_id, feature_type='document',
|
|
655
|
+
content=self._document_text(doc_id, hsf) if hsf else "",
|
|
656
|
+
score=score / (score + 1.0),
|
|
657
|
+
path=[doc_id],
|
|
658
|
+
metadata={'document_id': doc_id},
|
|
659
|
+
))
|
|
660
|
+
|
|
661
|
+
if self.reranker:
|
|
662
|
+
results = self.reranker.rerank(query, results, top_k=top_k)
|
|
663
|
+
|
|
664
|
+
return results[:top_k]
|
|
665
|
+
|
|
666
|
+
def _document_text(self, doc_id: str,
|
|
667
|
+
hsf: Optional[HolisticStructuralForm]) -> str:
|
|
668
|
+
"""The document composite's text; cached sentence texts as fallback."""
|
|
669
|
+
if hsf is not None:
|
|
670
|
+
for feature in hsf.composite_features.values():
|
|
671
|
+
if feature.feature_type == 'document':
|
|
672
|
+
return self._get_feature_text(feature, hsf)
|
|
673
|
+
keys = sorted(k for k in self.inverted_index.feature_texts
|
|
674
|
+
if k[0] == doc_id)
|
|
675
|
+
return " ".join(self.inverted_index.feature_texts[k] for k in keys)
|
|
676
|
+
|
|
677
|
+
# ── Candidate selection ──────────────────────────────────────────────
|
|
678
|
+
|
|
679
|
+
def _tokenize(self, text: str) -> List[str]:
|
|
680
|
+
# Number-aware: '3.5' and '1,000' stay single tokens, matching the
|
|
681
|
+
# builder's word tokens.
|
|
682
|
+
return [w.lower() for w in re.findall(r'\b\d[\d,]*(?:\.\d+)?\b|\b\w+\b', text)]
|
|
683
|
+
|
|
684
|
+
def _find_candidates(self, query_terms: List[str]) -> Set[DocKey]:
|
|
685
|
+
"""
|
|
686
|
+
Collect sentences reachable from any query term.
|
|
687
|
+
|
|
688
|
+
A term here may be an original token or one of its synonyms, so the
|
|
689
|
+
sets are unioned rather than intersected: any term may earn a match.
|
|
690
|
+
Only keys matter downstream (scoring re-derives what matched from the
|
|
691
|
+
original terms), so no per-sentence term bookkeeping is kept.
|
|
692
|
+
"""
|
|
693
|
+
index = self.inverted_index.index
|
|
694
|
+
hits: Set[DocKey] = set()
|
|
695
|
+
for term in query_terms:
|
|
696
|
+
postings = index.get(term)
|
|
697
|
+
if postings:
|
|
698
|
+
hits.update(key for key, _ in postings)
|
|
699
|
+
return hits
|
|
700
|
+
|
|
701
|
+
# ── Scoring ──────────────────────────────────────────────────────────
|
|
702
|
+
|
|
703
|
+
def _score_candidates_numpy(self, candidates: Set[DocKey],
|
|
704
|
+
original_terms: List[str],
|
|
705
|
+
alternatives: Dict[str, List[str]],
|
|
706
|
+
avgdl_safe: float) -> Optional[Dict[DocKey, float]]:
|
|
707
|
+
"""
|
|
708
|
+
Vectorized equivalent of the per-candidate loop in search().
|
|
709
|
+
|
|
710
|
+
Accumulates per-term contributions in query-term order, exactly like
|
|
711
|
+
the scalar scorer, so raw scores are bit-identical. Returns None when
|
|
712
|
+
numpy is unavailable (caller falls back to the Python loop).
|
|
713
|
+
"""
|
|
714
|
+
if np is None:
|
|
715
|
+
return None
|
|
716
|
+
idx = self.inverted_index
|
|
717
|
+
idx._ensure_np()
|
|
718
|
+
n = len(idx.rows)
|
|
719
|
+
if n == 0:
|
|
720
|
+
return {}
|
|
721
|
+
|
|
722
|
+
k1 = 1.5
|
|
723
|
+
b = 0.75
|
|
724
|
+
# Elementwise identical to the scalar den's k1*(1 - b + b*dl/avgdl).
|
|
725
|
+
norm = k1 * ((1.0 - b) + (b * idx.dl_arr) / avgdl_safe)
|
|
726
|
+
score = np.zeros(n)
|
|
727
|
+
matched = np.zeros(n, dtype=bool)
|
|
728
|
+
empty = (np.empty(0, dtype=np.int64), np.empty(0))
|
|
729
|
+
|
|
730
|
+
for term in original_terms:
|
|
731
|
+
matched[:] = False
|
|
732
|
+
ids, tfs = idx.np_postings.get(term, empty)
|
|
733
|
+
if ids.size:
|
|
734
|
+
score[ids] += idx.idf.get(term, 0.1) * (
|
|
735
|
+
(tfs * (k1 + 1.0)) / (tfs + norm[ids]))
|
|
736
|
+
matched[ids] = True
|
|
737
|
+
for alt in alternatives.get(term, ()):
|
|
738
|
+
ids, tfs = idx.np_postings.get(alt, empty)
|
|
739
|
+
if not ids.size:
|
|
740
|
+
continue
|
|
741
|
+
sel = ~matched[ids]
|
|
742
|
+
if not sel.any():
|
|
743
|
+
continue
|
|
744
|
+
ids, tfs = ids[sel], tfs[sel]
|
|
745
|
+
score[ids] += idx.idf.get(alt, 0.1) * (
|
|
746
|
+
(tfs * (k1 + 1.0)) / (tfs + norm[ids])) * 0.9
|
|
747
|
+
matched[ids] = True
|
|
748
|
+
|
|
749
|
+
row_of = idx.row_of
|
|
750
|
+
return {key: float(score[row_of[key]])
|
|
751
|
+
for key in candidates if key in row_of}
|
|
752
|
+
|
|
753
|
+
def _score_docs_numpy(self, candidates: Set[str],
|
|
754
|
+
original_terms: List[str],
|
|
755
|
+
idf_of: Dict[str, float],
|
|
756
|
+
avgdl_safe: float) -> Optional[Dict[str, float]]:
|
|
757
|
+
"""Vectorized equivalent of the per-doc loop in search_documents()."""
|
|
758
|
+
if np is None:
|
|
759
|
+
return None
|
|
760
|
+
idx = self.inverted_index
|
|
761
|
+
idx._ensure_doc_np()
|
|
762
|
+
n = len(idx.doc_rows)
|
|
763
|
+
if n == 0:
|
|
764
|
+
return {}
|
|
765
|
+
|
|
766
|
+
k1 = 1.5
|
|
767
|
+
b = 0.75
|
|
768
|
+
norm = k1 * ((1.0 - b) + (b * idx.doc_dl_arr) / avgdl_safe)
|
|
769
|
+
score = np.zeros(n)
|
|
770
|
+
empty = (np.empty(0, dtype=np.int64), np.empty(0))
|
|
771
|
+
|
|
772
|
+
for term in original_terms: # term order preserved: sum is exact
|
|
773
|
+
idf = idf_of.get(term)
|
|
774
|
+
if idf is None:
|
|
775
|
+
continue
|
|
776
|
+
ids, tfs = idx.doc_np_postings.get(term, empty)
|
|
777
|
+
if not ids.size:
|
|
778
|
+
continue
|
|
779
|
+
score[ids] += idf * ((tfs * (k1 + 1.0)) / (tfs + norm[ids]))
|
|
780
|
+
|
|
781
|
+
row_of = idx.doc_row_of
|
|
782
|
+
return {doc_id: float(score[row_of[doc_id]])
|
|
783
|
+
for doc_id in candidates if doc_id in row_of}
|
|
784
|
+
|
|
785
|
+
def _score_feature(self, query_terms: List[str], key: DocKey,
|
|
786
|
+
alternatives: Optional[Dict[str, List[str]]] = None,
|
|
787
|
+
avgdl_safe: Optional[float] = None) -> float:
|
|
788
|
+
"""
|
|
789
|
+
BM25 over the original query terms, plus a coverage bonus.
|
|
790
|
+
|
|
791
|
+
Statistics come from the corpus-level index, so a result from one
|
|
792
|
+
document is directly comparable to a result from another. Term
|
|
793
|
+
frequencies, sentence text, and idf are read from build-time caches;
|
|
794
|
+
the math is identical to the uncached form. ``avgdl_safe`` is
|
|
795
|
+
``max(1, avg_feature_length)``, hoisted by the caller: it is constant
|
|
796
|
+
per query and per-candidate ``max`` calls showed up in profiles.
|
|
797
|
+
"""
|
|
798
|
+
if not query_terms:
|
|
799
|
+
return 0.0
|
|
800
|
+
|
|
801
|
+
tf_counts = self.inverted_index.feature_tf.get(key)
|
|
802
|
+
if tf_counts is None: # un-cached feature; rebuild on the fly
|
|
803
|
+
tf_counts = defaultdict(int)
|
|
804
|
+
for w in self._sentence_text(self._sentences[key]).lower().split():
|
|
805
|
+
tf_counts[w] += 1
|
|
806
|
+
if not tf_counts:
|
|
807
|
+
return 0.0
|
|
808
|
+
|
|
809
|
+
k1 = 1.5 # term frequency saturation
|
|
810
|
+
b = 0.75 # length normalization
|
|
811
|
+
avgdl = avgdl_safe if avgdl_safe is not None else max(
|
|
812
|
+
1, self.inverted_index.avg_feature_length)
|
|
813
|
+
doc_len = self.inverted_index.feature_lengths.get(key, len(tf_counts))
|
|
814
|
+
|
|
815
|
+
score = 0.0
|
|
816
|
+
alts_by_term = alternatives or {}
|
|
817
|
+
|
|
818
|
+
for term in query_terms:
|
|
819
|
+
# Exact match wins; otherwise take the first alternative that is
|
|
820
|
+
# present. One contribution per query term, never one per synonym
|
|
821
|
+
# that happens to appear. Explicit loop rather than next(genexpr):
|
|
822
|
+
# identical result, no generator-frame overhead per candidate.
|
|
823
|
+
if term in tf_counts:
|
|
824
|
+
matched = term
|
|
825
|
+
else:
|
|
826
|
+
matched = None
|
|
827
|
+
for alt in alts_by_term.get(term, ()):
|
|
828
|
+
if alt in tf_counts:
|
|
829
|
+
matched = alt
|
|
830
|
+
break
|
|
831
|
+
if matched is None:
|
|
832
|
+
continue
|
|
833
|
+
|
|
834
|
+
tf = tf_counts[matched]
|
|
835
|
+
idf = self.inverted_index.idf.get(matched, 0.1)
|
|
836
|
+
num = tf * (k1 + 1)
|
|
837
|
+
den = tf + k1 * (1 - b + b * doc_len / max(1, avgdl))
|
|
838
|
+
contribution = idf * (num / den)
|
|
839
|
+
if matched != term:
|
|
840
|
+
contribution *= 0.9 # penalty for anything that is not an exact hit
|
|
841
|
+
|
|
842
|
+
score += contribution
|
|
843
|
+
|
|
844
|
+
# No averaging and no coverage blend: BM25's sum over query terms is
|
|
845
|
+
# the textbook formula and the ranking signal. Averaging by query-term
|
|
846
|
+
# count and blending with coverage flattened it until BEIR-scale
|
|
847
|
+
# ranking collapsed (24% vs 69% nDCG@10 on the same sentence pool).
|
|
848
|
+
# The reported score is squashed in search(), not here: this value
|
|
849
|
+
# ranks, and a cap here would flatten exactly the top of the ranking.
|
|
850
|
+
return score
|
|
851
|
+
|
|
852
|
+
def _alternatives_of(self, term: str) -> List[str]:
|
|
853
|
+
"""
|
|
854
|
+
Non-exact forms a query term may match, in a fixed order.
|
|
855
|
+
|
|
856
|
+
Synonyms come before morphological variants, so a real synonym is
|
|
857
|
+
preferred over a suffix-stripped stem. Ordering is explicit because
|
|
858
|
+
results must be reproducible.
|
|
859
|
+
"""
|
|
860
|
+
group = self.semantic_expander.synonym_groups.get(term)
|
|
861
|
+
synonyms = sorted(group.all_terms() - {term}) if group else []
|
|
862
|
+
morphology = sorted(self.semantic_expander.morphological_variants(term))
|
|
863
|
+
|
|
864
|
+
ordered: List[str] = []
|
|
865
|
+
for alt in (*synonyms, *morphology):
|
|
866
|
+
if alt not in ordered:
|
|
867
|
+
ordered.append(alt)
|
|
868
|
+
return ordered
|
|
869
|
+
|
|
870
|
+
# ── Text and structure accessors ─────────────────────────────────────
|
|
871
|
+
|
|
872
|
+
@staticmethod
|
|
873
|
+
def _sentence_text(feature: CompositeFeature) -> str:
|
|
874
|
+
return " ".join(c.value for c in sorted(feature.children, key=lambda c: c.position))
|
|
875
|
+
|
|
876
|
+
def _get_feature_text(self, feature: CompositeFeature, hsf: HolisticStructuralForm) -> str:
|
|
877
|
+
"""Read a composite feature's text, descending into children by ID."""
|
|
878
|
+
if feature.feature_type == 'sentence':
|
|
879
|
+
return self._sentence_text(feature)
|
|
880
|
+
|
|
881
|
+
parts = []
|
|
882
|
+
for cid in feature.child_ids:
|
|
883
|
+
child = hsf.get_feature(cid)
|
|
884
|
+
if isinstance(child, CompositeFeature):
|
|
885
|
+
parts.append(self._get_feature_text(child, hsf))
|
|
886
|
+
elif isinstance(child, ElementaryFeature):
|
|
887
|
+
parts.append(child.value)
|
|
888
|
+
return " ".join(parts)
|
|
889
|
+
|
|
890
|
+
def _get_feature_path(self, key: DocKey) -> List[str]:
|
|
891
|
+
"""Walk the precomputed parent map. O(depth), no scanning."""
|
|
892
|
+
path = [key[1]]
|
|
893
|
+
current = key
|
|
894
|
+
seen = {current}
|
|
895
|
+
while True:
|
|
896
|
+
parent = self._parent_of.get(current)
|
|
897
|
+
if parent is None or parent in seen:
|
|
898
|
+
break
|
|
899
|
+
path.insert(0, parent[1])
|
|
900
|
+
seen.add(parent)
|
|
901
|
+
current = parent
|
|
902
|
+
return path
|
|
903
|
+
|
|
904
|
+
def _resolve(self, feature_id: str) -> Optional[Tuple[DocKey, Any]]:
|
|
905
|
+
"""Find a feature by its raw ID across the collection."""
|
|
906
|
+
key = self._key_of.get(feature_id)
|
|
907
|
+
if key is None:
|
|
908
|
+
return None
|
|
909
|
+
hsf = self.documents.get(key[0])
|
|
910
|
+
if hsf is None:
|
|
911
|
+
return None
|
|
912
|
+
feature = hsf.get_feature(key[1])
|
|
913
|
+
return (key, feature) if feature is not None else None
|
|
914
|
+
|
|
915
|
+
# ── Non-text retrieval paths ─────────────────────────────────────────
|
|
916
|
+
|
|
917
|
+
def get_by_id(self, feature_id: str) -> Optional[SearchResult]:
|
|
918
|
+
resolved = self._resolve(feature_id)
|
|
919
|
+
if resolved is None:
|
|
920
|
+
return None
|
|
921
|
+
|
|
922
|
+
key, feature = resolved
|
|
923
|
+
if isinstance(feature, ElementaryFeature):
|
|
924
|
+
return SearchResult(feature_id, feature.feature_type, feature.value,
|
|
925
|
+
1.0, self._get_feature_path(key), feature.metadata)
|
|
926
|
+
|
|
927
|
+
hsf = self.documents[key[0]]
|
|
928
|
+
return SearchResult(feature_id, feature.feature_type,
|
|
929
|
+
self._get_feature_text(feature, hsf), 1.0,
|
|
930
|
+
self._get_feature_path(key), feature.metadata)
|
|
931
|
+
|
|
932
|
+
def search_by_structure(self, pattern_type: str) -> List[SearchResult]:
|
|
933
|
+
"""Return every feature of a given structural type. Ignores query text."""
|
|
934
|
+
results = []
|
|
935
|
+
for doc_id, hsf in self.documents.items():
|
|
936
|
+
for feat_id, feat in hsf.composite_features.items():
|
|
937
|
+
if feat.feature_type != pattern_type:
|
|
938
|
+
continue
|
|
939
|
+
key = (doc_id, feat_id)
|
|
940
|
+
results.append(SearchResult(
|
|
941
|
+
feat_id, feat.feature_type,
|
|
942
|
+
self._get_feature_text(feat, hsf), 1.0,
|
|
943
|
+
self._get_feature_path(key), feat.metadata,
|
|
944
|
+
))
|
|
945
|
+
return results
|
|
946
|
+
|
|
947
|
+
def find_similar_structures(self, feature_id: str,
|
|
948
|
+
threshold: float = 0.8) -> List[SearchResult]:
|
|
949
|
+
resolved = self._resolve(feature_id)
|
|
950
|
+
if resolved is None:
|
|
951
|
+
return []
|
|
952
|
+
|
|
953
|
+
target_key, target = resolved
|
|
954
|
+
if not isinstance(target, CompositeFeature):
|
|
955
|
+
return []
|
|
956
|
+
|
|
957
|
+
results = []
|
|
958
|
+
for doc_id, hsf in self.documents.items():
|
|
959
|
+
for feat_id, feat in hsf.composite_features.items():
|
|
960
|
+
key = (doc_id, feat_id)
|
|
961
|
+
if key == target_key or feat.feature_type != target.feature_type:
|
|
962
|
+
continue
|
|
963
|
+
sim = self._compare_structures(target, feat)
|
|
964
|
+
if sim >= threshold:
|
|
965
|
+
results.append(SearchResult(
|
|
966
|
+
feat_id, feat.feature_type,
|
|
967
|
+
self._get_feature_text(feat, hsf), sim,
|
|
968
|
+
self._get_feature_path(key), feat.metadata,
|
|
969
|
+
))
|
|
970
|
+
return results
|
|
971
|
+
|
|
972
|
+
@staticmethod
|
|
973
|
+
def _compare_structures(f1: CompositeFeature, f2: CompositeFeature) -> float:
|
|
974
|
+
sig_match = 1.0 if f1.structural_signature == f2.structural_signature else 0.0
|
|
975
|
+
size_ratio = min(len(f1.children), len(f2.children)) / max(len(f1.children), len(f2.children), 1)
|
|
976
|
+
return 0.4 * sig_match + 0.3 * size_ratio + 0.3
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
# Backwards compat alias
|
|
980
|
+
EnhancedStructureRetriever = StructureRetriever
|