Coverage for collectra/tasks/bm25_index.py: 100.00%

74 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""BM25 search over short texts, such as entity names and spreadsheet rows. 

2 

3Each text is split into words, and each word also into its character trigrams, 

4so a misspelt or misread name (``Monograptas``) still shares most of its terms 

5with the right entry (``Monograptus``). Texts are scored with Okapi BM25: terms 

6that few texts contain count for more, and a long text needs more matches to 

7score as well as a short one. 

8 

9It needs nothing beyond NumPy, sends nothing to any service and costs nothing 

10to run. Entity lists and spreadsheets of hundreds of thousands of rows index in 

11seconds. 

12""" 

13 

14from __future__ import annotations 

15 

16__all__ = ["BM25Index", "Document", "tokenize"] 

17 

18import json 

19import math 

20import re 

21import unicodedata 

22from collections import Counter 

23from dataclasses import dataclass 

24from pathlib import Path 

25 

26import numpy as np 

27 

28DOCUMENTS_FILE = "documents.json" 

29 

30_WORD = re.compile(r"\w+") 

31 

32 

33@dataclass(frozen=True) 

34class Document: 

35 """One indexed entry: its id and its text.""" 

36 

37 id: str 

38 page_content: str 

39 

40 

41def _fold(text: str) -> str: 

42 """Lower case, without accents, so ``Müller`` and ``muller`` are the same.""" 

43 decomposed = unicodedata.normalize("NFKD", text) 

44 return "".join(c for c in decomposed if not unicodedata.combining(c)).casefold() 

45 

46 

47def tokenize(text: str) -> list[str]: 

48 """Each word of ``text``, followed by the trigrams of ``#word#``.""" 

49 tokens = [] 

50 for word in _WORD.findall(_fold(text)): 

51 tokens.append(word) 

52 padded = f"#{word}#" 

53 tokens.extend(padded[i : i + 3] for i in range(len(padded) - 2)) 

54 return tokens 

55 

56 

57class BM25Index: 

58 """Texts that can be searched by how well they match a query. 

59 

60 Scores are BM25 scores: higher is better, and only texts that share at 

61 least one term with the query score above zero. 

62 """ 

63 

64 def __init__( 

65 self, 

66 ids: list[str], 

67 texts: list[str], 

68 k1: float = 1.5, 

69 b: float = 0.75, 

70 ) -> None: 

71 if len(ids) != len(texts): 

72 raise ValueError("ids and texts must be the same length") 

73 self.ids = [str(i) for i in ids] 

74 self.texts = list(texts) 

75 

76 counts = [Counter(tokenize(text)) for text in self.texts] 

77 lengths = np.array([sum(c.values()) for c in counts], dtype=np.float64) 

78 average = lengths.mean() if lengths.size and lengths.sum() else 1.0 

79 # The part of each text's term weights that depends on its length. 

80 length_norm = k1 * (1 - b + b * lengths / average) 

81 

82 postings: dict[str, tuple[list[int], list[int]]] = {} 

83 for index, text_counts in enumerate(counts): 

84 for term, count in text_counts.items(): 

85 docs, freqs = postings.setdefault(term, ([], [])) 

86 docs.append(index) 

87 freqs.append(count) 

88 

89 # Every term's contribution to each text's score, worked out once. 

90 size = len(self.texts) 

91 self._weights: dict[str, tuple[np.ndarray, np.ndarray]] = {} 

92 for term, (docs, freqs) in postings.items(): 

93 docs_array = np.array(docs) 

94 tf = np.array(freqs, dtype=np.float64) 

95 idf = math.log(1 + (size - len(docs) + 0.5) / (len(docs) + 0.5)) 

96 weights = idf * tf * (k1 + 1) / (tf + length_norm[docs_array]) 

97 self._weights[term] = (docs_array, weights) 

98 

99 def __len__(self) -> int: 

100 return len(self.ids) 

101 

102 def search(self, query: str, k: int = 4) -> list[tuple[Document, float]]: 

103 """The ``k`` best-matching texts, best first, with their scores. 

104 

105 Texts that share no term with the query are left out, so fewer than 

106 ``k`` may come back. Equal scores keep the texts' order. 

107 """ 

108 if not len(self) or k < 1: 

109 return [] 

110 scores = np.zeros(len(self)) 

111 for term in sorted(set(tokenize(query))): 

112 if term in self._weights: 

113 docs, weights = self._weights[term] 

114 scores[docs] += weights 

115 matched = np.flatnonzero(scores > 0) 

116 best = matched[np.lexsort((matched, -scores[matched]))][:k] 

117 return [ 

118 (Document(id=self.ids[i], page_content=self.texts[i]), float(scores[i])) 

119 for i in best 

120 ] 

121 

122 @staticmethod 

123 def exists(path: str | Path) -> bool: 

124 return (Path(path) / DOCUMENTS_FILE).is_file() 

125 

126 def save(self, path: str | Path) -> None: 

127 path = Path(path) 

128 path.mkdir(parents=True, exist_ok=True) 

129 (path / DOCUMENTS_FILE).write_text( 

130 json.dumps({"ids": self.ids, "texts": self.texts}) 

131 ) 

132 

133 @classmethod 

134 def load(cls, path: str | Path) -> "BM25Index": 

135 data = json.loads((Path(path) / DOCUMENTS_FILE).read_text()) 

136 return cls(data["ids"], data["texts"])