Coverage for collectra/tasks/irn_resolvers.py: 100.00%
167 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"""IRN (Internal Reference Number) resolver tasks for Collectra workflows.
3This module provides an IRN resolver that finds candidate rows with BM25 search
4(over words and their character trigrams) plus an LLM verification step to map
5free-text query inputs to canonical IRN identifiers loaded from an xlsx
6source file.
8Public API:
9 IRNResolver: Task class that resolves a query to an IRN string.
10 normalise_column_name: Helper that normalises raw spreadsheet column names.
11 render_card: Helper that renders a per-row card from a template.
12"""
14__all__ = ["IRNResolver", "normalise_column_name", "render_card"]
16import hashlib
17import re
18from pathlib import Path
20import pandas as pd
21from dotenv import load_dotenv
23from collectra.tasks.bm25_index import BM25Index
24from collectra.tasks.canonicalisers import LLMCanonicaliser
25from collectra.types.texts import Text
27from ..logger import get_logger
29load_dotenv()
31logger = get_logger(__name__)
34NO_MATCH_INSTRUCTION = (
35 "If none of the candidates is clearly the same entity referenced in the input, "
36 'respond with empty string (""). Do NOT guess. Respond with ONLY the IRN integer, '
37 "or empty string."
38)
41class _SafeDict(dict):
42 """A dict subclass that returns "" for missing keys when used with format_map."""
44 def __missing__(self, key):
45 return ""
48def normalise_column_name(raw: str) -> str:
49 """Normalise a raw spreadsheet column name into a snake_case identifier.
51 Rules applied in order:
52 1. Strip a single trailing parenthetical ``(...)`` together with surrounding
53 whitespace.
54 2. Strip a trailing ``:``.
55 3. Lowercase.
56 4. Replace runs of whitespace and ``/`` with ``_``.
57 5. Drop any character not in ``[a-z0-9_]``.
58 6. Collapse runs of ``_`` and strip leading/trailing ``_``.
59 """
60 s = str(raw)
62 # 1. Strip a single trailing parenthetical (...) with surrounding whitespace.
63 s = re.sub(r"\s*\([^()]*\)\s*$", "", s)
65 # 2. Strip a trailing ':'.
66 s = re.sub(r":\s*$", "", s)
67 s = s.rstrip(":")
69 # 3. Lowercase.
70 s = s.lower()
72 # 4. Replace runs of whitespace AND '/' with '_'.
73 s = re.sub(r"[\s/]+", "_", s)
75 # 5. Drop any character not in [a-z0-9_].
76 s = re.sub(r"[^a-z0-9_]", "", s)
78 # 6. Collapse runs of '_' and strip leading/trailing '_'.
79 s = re.sub(r"_+", "_", s)
80 s = s.strip("_")
82 return s
85def _is_missing(value) -> bool:
86 """Return True if value is None, NaN, or pandas-NA."""
87 try:
88 return bool(pd.isna(value))
89 except (TypeError, ValueError):
90 # A list or other container: a value, even if it holds missing ones.
91 return False
94def render_card(template: str, row: dict) -> str:
95 """Render a card from a template and a row mapping.
97 Replaces None/NaN values with "", applies ``template.format(**row)``,
98 then collapses runs of separator-only segments (``|`` or ``,`` with
99 surrounding whitespace) and strips leading/trailing separators.
100 """
101 cleaned = {k: ("" if _is_missing(v) else str(v)) for k, v in row.items()}
102 rendered = template.format_map(_SafeDict(cleaned))
104 # Collapse runs of (\s*[|,]\s*){2,} into the LAST single \s*[|,]\s* in the
105 # run. We reconstruct the "last single" as: optional single leading space
106 # (if the run begins with whitespace), the last separator character, and
107 # optional single trailing space (if the run ends with whitespace). This
108 # avoids the greedy-matching artefact where earlier iterations of the
109 # capture group consume whitespace that should belong to the last match.
110 sep_chars = "|,"
112 def _collapse(match: re.Match) -> str:
113 run = match.group(0)
114 # Last separator character in the run.
115 last_sep = None
116 for ch in reversed(run):
117 if ch in sep_chars:
118 last_sep = ch
119 break
120 leading = " " if run and run[0].isspace() else ""
121 trailing = " " if run and run[-1].isspace() else ""
122 return f"{leading}{last_sep}{trailing}"
124 rendered = re.sub(r"(\s*[|,]\s*){2,}", _collapse, rendered)
126 # Strip leading/trailing whitespace and any leading/trailing | or , plus
127 # surrounding whitespace.
128 rendered = re.sub(r"^(\s*[|,]\s*)+", "", rendered)
129 rendered = re.sub(r"(\s*[|,]\s*)+$", "", rendered)
130 rendered = rendered.strip()
132 return rendered
135class IRNResolver(LLMCanonicaliser):
136 """Resolve a free-text query to an IRN identifier.
138 Builds one BM25 sub-index per entry in ``index_filters`` from rows of
139 a source xlsx file. At query time, tries each filter in order, retrieves
140 the top-``count`` candidates by BM25 score, applies acceptance rules
141 (``min_score`` and optional ``score_gap_eps``), then asks the LLM to
142 either pick a candidate IRN or return empty string.
144 Attributes:
145 source (Path): Path to the xlsx source file.
146 card_template (str): str.format template using normalised column names.
147 query_template (str): str.format template using input Text names.
148 irn_column (str): Name of the IRN column (default "IRN").
149 count (int): Number of candidates to retrieve per filter (default 20).
150 min_score (float): Lowest acceptable BM25 score for the top candidate.
151 Only candidates that share a word or trigram with the query are
152 found, so the default of 0 accepts any of them.
153 score_gap_eps (float): Minimum lead of the top score over the second.
154 index_filters (list): Pandas-query strings (or None) - one per sub-index.
155 """
157 def __init__(self, name: str, model: str, **kwargs):
158 # Required kwargs (validate before super-init since parent doesn't know
159 # about them).
160 if "source" not in kwargs:
161 raise ValueError("IRNResolver requires a 'source' kwarg (path to xlsx).")
162 if "card_template" not in kwargs:
163 raise ValueError("IRNResolver requires a 'card_template' kwarg.")
164 if "query_template" not in kwargs:
165 raise ValueError("IRNResolver requires a 'query_template' kwarg.")
166 if "score_floor" in kwargs:
167 raise ValueError(
168 "IRNResolver no longer uses 'score_floor', a maximum embedding "
169 "distance. Candidates are now found with BM25, where higher "
170 "scores are better: use 'min_score' for the lowest acceptable "
171 "score of the best candidate."
172 )
174 # The parent LLMCanonicaliser.__init__ wraps `entities` in
175 # Path(...) and then checks .exists()/.suffix. We don't use the
176 # parent's entity machinery (retrieve_entities and run are overridden),
177 # so we inject a Path-safe sentinel. Using "." makes Path(".") valid
178 # and exists() True; the parent then assigns self.entities = Path(".")
179 # without triggering file reads.
180 kwargs.setdefault("entities", ".")
181 super().__init__(name, model, **kwargs)
183 self.source: Path = Path(kwargs["source"])
184 self.card_template: str = kwargs["card_template"]
185 self.query_template: str = kwargs["query_template"]
187 self.irn_column: str = kwargs.get("irn_column", "IRN")
188 self.count: int = kwargs.get("count", 20)
189 self.min_score: float = kwargs.get("min_score", 0.0)
190 self.score_gap_eps: float = kwargs.get("score_gap_eps", 0.0)
191 self.index_filters: list = kwargs.get("index_filters", [None])
193 # Augment preamble once with the no-match instruction.
194 if self.preamble:
195 self.preamble = f"{self.preamble}\n\n{NO_MATCH_INSTRUCTION}"
196 else:
197 self.preamble = NO_MATCH_INSTRUCTION
199 # Build/load one index per filter.
200 self._indexes: list[BM25Index] = []
201 self._build_indices()
203 # ------------------------------------------------------------------
204 # Index building / caching
205 # ------------------------------------------------------------------
206 def _source_hash(self) -> str:
207 with open(self.source, "rb") as f:
208 return hashlib.sha256(f.read()).hexdigest()
210 def _index_path_for(self, i: int) -> Path:
211 return self.source.parent / f"{self.source.stem}_irn_index_{i}"
213 def _build_indices(self) -> None:
214 current_hash = self._source_hash()
215 df_raw_cache: pd.DataFrame | None = None
217 for i, filter_str in enumerate(self.index_filters):
218 index_path = self._index_path_for(i)
219 sidecar = index_path / ".source_hash"
221 reuse = (
222 BM25Index.exists(index_path)
223 and sidecar.exists()
224 and sidecar.read_text().strip() == current_hash
225 )
227 if reuse:
228 logger.info(
229 "Reusing existing IRN index at %s for filter %r",
230 index_path,
231 filter_str,
232 )
233 self._indexes.append(BM25Index.load(index_path))
234 continue
236 # Need to (re)build this index.
237 if df_raw_cache is None:
238 df_raw_cache = pd.read_excel(self.source)
239 self.df = df_raw_cache.rename(
240 columns={c: normalise_column_name(c) for c in df_raw_cache.columns}
241 )
243 # Filter against the raw spreadsheet column names so users can write
244 # filters like "Species.isna()" using the actual xlsx headers.
245 df = df_raw_cache
246 if filter_str is not None:
247 df = df.query(filter_str)
248 df = df.rename(columns={c: normalise_column_name(c) for c in df.columns})
250 normalised_irn_column = normalise_column_name(self.irn_column)
251 id_col = (
252 self.irn_column
253 if self.irn_column in df.columns
254 else normalised_irn_column
255 )
256 if id_col not in df.columns:
257 raise ValueError(
258 f"IRN column {self.irn_column!r} (normalised {normalised_irn_column!r}) "
259 f"not found in source columns: {list(df.columns)}"
260 )
262 ids: list[str] = []
263 texts: list[str] = []
264 seen: set[str] = set()
265 for _, row in df.iterrows():
266 row_dict = row.to_dict()
267 irn_value = row_dict.get(id_col)
268 if _is_missing(irn_value):
269 continue
270 # A column with blank cells is read as floats: 12.0 is IRN 12.
271 if isinstance(irn_value, float) and irn_value.is_integer():
272 irn_value = int(irn_value)
273 irn_str = str(irn_value).strip()
274 if not irn_str or irn_str in seen:
275 continue
276 card = render_card(self.card_template, row_dict)
277 if not card:
278 continue
279 ids.append(irn_str)
280 texts.append(card)
281 seen.add(irn_str)
283 index = BM25Index(ids, texts)
284 index.save(index_path)
285 sidecar.write_text(current_hash)
286 logger.info(
287 "Built IRN index at %s with %d rows for filter %r",
288 index_path,
289 len(texts),
290 filter_str,
291 )
292 self._indexes.append(index)
294 # ------------------------------------------------------------------
295 # Retrieval / run
296 # ------------------------------------------------------------------
297 def retrieve_entities(
298 self, query_data: str, filter_index: int = 0
299 ) -> list[tuple[str, str]]:
300 """Retrieve top-``count`` (id, page_content) pairs for the given filter."""
301 results = self._indexes[filter_index].search(query_data, k=self.count)
302 out: list[tuple[str, str]] = []
303 for doc, _score in results:
304 out.append((str(doc.id), doc.page_content))
305 return out
307 def _render_query(self, inputs_dict: dict) -> str:
308 return self.query_template.format_map(_SafeDict(inputs_dict))
310 def _try_filter(
311 self,
312 filter_index: int,
313 query_text: str,
314 args: tuple,
315 ) -> str | None:
316 """Try one filter; return matched IRN string or None."""
317 results = self._indexes[filter_index].search(query_text, k=self.count)
318 if not results:
319 return None
320 if results[0][1] < self.min_score:
321 return None
322 if (
323 self.score_gap_eps > 0
324 and len(results) >= 2
325 and (results[0][1] - results[1][1]) < self.score_gap_eps
326 ):
327 return None
329 candidate_ids: list[str] = [str(doc.id) for doc, _ in results]
330 candidates_string = "\n".join(
331 f"IRN {doc.id}: {doc.page_content}" for doc, _ in results
332 )
334 # Mirror LLMCanonicaliser.run for the LLM call portion.
335 prompt, pattern = self.pre_run()
336 messages = self.replace_inputs(
337 pattern, prompt, *args, entities=candidates_string
338 )
339 self.messages.append(messages)
340 self.check_inputs(*args)
341 response = self.invoke()
343 # Parse response: strip whitespace and surrounding quotes.
344 cleaned = response.strip()
345 if cleaned and cleaned[0] in ("'", '"') and cleaned[-1] == cleaned[0]:
346 cleaned = cleaned[1:-1].strip()
348 if not cleaned or cleaned.lower() in ("none", "n/a"):
349 return None
351 if cleaned in candidate_ids:
352 return cleaned
353 return None
355 def run(self, *args: Text) -> Text:
356 """Resolve the inputs to an IRN string by trying each filter in order."""
357 inputs_dict = {arg.name: str(arg.data) for arg in args}
358 query_text = self._render_query(inputs_dict)
360 for filter_index in range(len(self._indexes)):
361 matched = self._try_filter(filter_index, query_text, args)
362 if matched is not None:
363 return self.text_output(matched)
365 logger.info("IRN resolver %s returned empty (no acceptable match)", self.name)
366 return self.text_output("")