Coverage for collectra/resources/entity_lookup.py: 100.00%
96 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Look up likely entries in a list of known names, with BM25."""
3import math
4import re
5import unicodedata
6from collections import Counter
7from pathlib import Path
8from typing import Any
10from pydantic import BaseModel, Field, PrivateAttr
12from collectra.resources.base import Resource
14__all__ = ["EntityLookup", "LookupHit"]
17class LookupHit(BaseModel):
18 """One candidate from a lookup."""
20 entity: str
21 score: float # relative to the best candidate, 0-1
22 exact: bool # the query equals this entry apart from case, accents, punctuation
25def _normalise(text: str) -> str:
26 """Lower-case, strip accents, and reduce punctuation to single spaces."""
27 decomposed = unicodedata.normalize("NFKD", text)
28 plain = "".join(c for c in decomposed if not unicodedata.combining(c))
29 return re.sub(r"[\W_]+", " ", plain.casefold()).strip()
32class EntityLookup(Resource):
33 """A list of known entities that can be searched by approximate text.
35 Entries are indexed with BM25 over whole words and over character n-grams,
36 so a query matches a word of a longer entry (``Axedale`` finds ``Parish of
37 Axedale, allot 6``) and still finds an entry despite a misspelling
38 (``Didymograpus`` finds ``Didymograptus``). The index is built in memory
39 when the lookup is created: there are no index files to keep up to date.
41 ``file`` holds one entity per line. ``limit`` is the default number of
42 candidates returned.
43 """
45 file: Path
46 limit: int = Field(default=10, ge=1)
47 ngram: int = Field(default=3, ge=2)
48 k1: float = 1.5
49 b: float = 0.75
51 _entities: list[str] = PrivateAttr(default_factory=list)
52 _normalised: list[str] = PrivateAttr(default_factory=list)
53 _postings: dict[str, list[tuple[int, int]]] = PrivateAttr(default_factory=dict)
54 _lengths: list[int] = PrivateAttr(default_factory=list)
55 _idf: dict[str, float] = PrivateAttr(default_factory=dict)
56 _average: float = PrivateAttr(default=1.0)
58 def model_post_init(self, __context: Any) -> None:
59 path = Path(self.file).expanduser().resolve()
60 if not path.is_file():
61 raise FileNotFoundError(
62 f"EntityLookup {self.name!r}: entity file not found: {self.file}"
63 )
64 self.file = path
65 seen: set[str] = set()
66 for line in path.read_text(encoding="utf-8").splitlines():
67 entity = line.strip()
68 if entity and entity not in seen:
69 seen.add(entity)
70 self._entities.append(entity)
71 self._build()
73 @property
74 def entities(self) -> list[str]:
75 return list(self._entities)
77 # --- the index ---------------------------------------------------------------
79 def _tokens(self, normalised: str) -> list[str]:
80 tokens = []
81 for word in normalised.split():
82 tokens.append(f"w:{word}")
83 padded = f"^{word}$"
84 if len(padded) <= self.ngram:
85 tokens.append(f"n:{padded}")
86 else:
87 tokens.extend(
88 f"n:{padded[i : i + self.ngram]}"
89 for i in range(len(padded) - self.ngram + 1)
90 )
91 return tokens
93 def _build(self) -> None:
94 self._normalised = [_normalise(entity) for entity in self._entities]
95 documents = [self._tokens(text) for text in self._normalised]
96 self._lengths = [len(tokens) for tokens in documents]
97 self._average = (sum(self._lengths) / len(documents)) if documents else 1.0
98 for index, tokens in enumerate(documents):
99 for token, frequency in Counter(tokens).items():
100 self._postings.setdefault(token, []).append((index, frequency))
101 total = len(documents)
102 self._idf = {
103 token: math.log(1 + (total - len(posts) + 0.5) / (len(posts) + 0.5))
104 for token, posts in self._postings.items()
105 }
107 # --- searching ---------------------------------------------------------------
109 def search(self, query: str, limit: int | None = None) -> list[LookupHit]:
110 """Candidates for ``query``, an exact match first, then best score first."""
111 normalised = _normalise(query)
112 if not normalised or not self._entities:
113 return []
114 scores: dict[int, float] = {}
115 for token in set(self._tokens(normalised)):
116 for index, frequency in self._postings.get(token, ()):
117 length = self._lengths[index] / self._average
118 weight = (
119 frequency
120 * (self.k1 + 1)
121 / (frequency + self.k1 * (1 - self.b + self.b * length))
122 )
123 scores[index] = scores.get(index, 0.0) + self._idf[token] * weight
124 if not scores:
125 return []
126 best = max(scores.values())
127 ranked = sorted(scores, key=lambda i: (-scores[i], i))
128 exact = [i for i in ranked if self._normalised[i] == normalised]
129 order = exact + [i for i in ranked if i not in set(exact)]
130 count = limit if limit is not None else self.limit
131 return [
132 LookupHit(
133 entity=self._entities[i],
134 score=1.0 if i in exact else round(scores[i] / best, 3),
135 exact=i in exact,
136 )
137 for i in order[:count]
138 ]
140 # --- the tool an LLM can call ---------------------------------------------------
142 def as_tool(self):
143 """This lookup as a tool the model can call with a ``query``."""
144 from pydantic_ai import Tool
146 def lookup(query: str) -> str:
147 if not query.strip():
148 return "Give a non-empty query: the text to look up."
149 hits = self.search(query)
150 if not hits:
151 return (
152 f"No candidates for {query!r}. This list is not exhaustive: "
153 "if you are confident of your reading, keep it."
154 )
155 lines = [f"Candidates for {query!r} (best first):"]
156 for position, hit in enumerate(hits, start=1):
157 note = ", exact match" if hit.exact else ""
158 lines.append(f"{position}. {hit.entity} [score {hit.score:.2f}{note}]")
159 return "\n".join(lines)
161 about = self.description.strip().rstrip(".")
162 return Tool(
163 lookup,
164 name=self.name,
165 description=(
166 f"Look up known entries{f' ({about})' if about else ''}. Pass the "
167 "text you read, or a spelling variant of it. Returns up to "
168 f"{self.limit} candidates, best first, each with a relative score; "
169 "an exact match is marked. The list is not necessarily complete, "
170 "so no match does not mean your reading is wrong."
171 ),
172 )