fieldproof 0.2.1__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.
@@ -0,0 +1,141 @@
1
+ """Anthropic-backed extractor using structured outputs.
2
+
3
+ The request carries the schema as `output_config.format` (a JSON Schema the
4
+ SDK derives from the Pydantic model with `anthropic.transform_schema`), so
5
+ Claude's reply is constrained to it. The reply is streamed and collected:
6
+ a long extraction can run past the time a plain request is allowed, and the
7
+ SDK refuses a non-streaming call it expects to.
8
+
9
+ A constrained reply can still fail to be the schema in two ways, and both
10
+ are told from the reply's `stop_reason` rather than from a JSON error: it
11
+ was cut off at `max_tokens` (an invoice with hundreds of line items), or the
12
+ model declined (`refusal`).
13
+
14
+ No live network calls happen anywhere in this repository - this machine has
15
+ no `ANTHROPIC_API_KEY` configured, and CI never sets one.
16
+ `tests/test_extract_anthropic.py` runs the real `anthropic` SDK over a mocked
17
+ HTTP transport that answers in the Messages API's wire format, so the
18
+ request it checks is the one the SDK really sends and the replies are parsed
19
+ by the SDK's own code; no completion in those tests came from a model.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ from dataclasses import dataclass
26
+ from typing import Any, TypeVar
27
+
28
+ import anthropic
29
+ from pydantic import BaseModel
30
+
31
+ from fieldproof.document.model import Document
32
+ from fieldproof.extract.base import ExtractionError, ExtractionResult, validate_data
33
+
34
+ #: Claude Opus 5.5, the current Opus model. Override via the `model`
35
+ #: constructor argument (or the CLI's `--model` flag), e.g. with
36
+ #: `claude-sonnet-5-5` for a cheaper and faster one.
37
+ DEFAULT_MODEL = "claude-opus-5-5"
38
+
39
+ _SYSTEM_PROMPT = """You are a meticulous document-extraction assistant. You will be given \
40
+ the full text of a document, page by page, with each page's exact wording preserved below.
41
+
42
+ Extract the requested fields. For every field, you MUST provide:
43
+ - `value`: the extracted value, normalized to the requested type (ISO-8601 dates; plain \
44
+ numbers for money, with no currency symbol or thousands separator).
45
+ - `evidence`: one or more VERBATIM quotes copied character-for-character from the document \
46
+ text below that support this value. Never paraphrase, translate, reformat, or correct the \
47
+ quote - copy the exact substring as it appears, including its original punctuation and \
48
+ casing. If you cannot find text that supports a value, leave `evidence` empty rather than \
49
+ inventing a quote.
50
+ - A short value (a bare number, a single word) can appear more than once in a document - a \
51
+ quantity of "1" in a line-item table, for instance, is often not unique. If the value you're \
52
+ quoting could plausibly appear elsewhere too, quote enough surrounding context to make it \
53
+ unambiguous - for a table row, that usually means the whole row, e.g. "Fuel surcharge 1 \
54
+ 210.50 210.50" rather than just "1". If the value is already unique in the document (most \
55
+ names, dates, and totals are), a short precise quote is fine.
56
+ - `page`: the 1-indexed page number the evidence came from.
57
+
58
+ If a field is genuinely absent from the document, use an empty string/list or omit it where \
59
+ the schema allows one - never guess a plausible-looking value that has no evidence on the \
60
+ page."""
61
+
62
+ T = TypeVar("T", bound=BaseModel)
63
+
64
+
65
+ @dataclass
66
+ class AnthropicExtractor:
67
+ """Extracts a Pydantic schema from a `Document` via Claude's structured
68
+ outputs. `client` is injectable for testing; when omitted, a default
69
+ `anthropic.Anthropic()` is constructed lazily (so importing this module
70
+ never requires credentials)."""
71
+
72
+ model: str = DEFAULT_MODEL
73
+ client: anthropic.Anthropic | None = None
74
+ max_tokens: int = 16000
75
+
76
+ def _get_client(self) -> anthropic.Anthropic:
77
+ return self.client if self.client is not None else anthropic.Anthropic()
78
+
79
+ def extract(self, document: Document, schema: type[T]) -> ExtractionResult:
80
+ # Typed loosely: the SDK's TypedDicts for this parameter have changed names between
81
+ # the releases this works with.
82
+ output_config: Any = {
83
+ "format": {"type": "json_schema", "schema": anthropic.transform_schema(schema)}
84
+ }
85
+ try:
86
+ with self._get_client().messages.stream(
87
+ model=self.model,
88
+ max_tokens=self.max_tokens,
89
+ system=_SYSTEM_PROMPT,
90
+ messages=[{"role": "user", "content": _build_prompt(document)}],
91
+ output_config=output_config,
92
+ ) as stream:
93
+ message = stream.get_final_message()
94
+ except anthropic.AnthropicError as exc:
95
+ raise ExtractionError(f"the Anthropic API request failed: {exc}") from exc
96
+ except TypeError as exc:
97
+ # How the SDK reports that it found no API key or token to send.
98
+ if "authentication method" not in str(exc):
99
+ raise
100
+ raise ExtractionError("no Anthropic credentials found: set ANTHROPIC_API_KEY") from exc
101
+ return ExtractionResult(
102
+ schema_name=schema.__name__,
103
+ data=_parse_reply(message, schema, self.max_tokens),
104
+ provider="anthropic",
105
+ model=self.model,
106
+ )
107
+
108
+
109
+ def _parse_reply(message: Any, schema: type[T], max_tokens: int) -> T:
110
+ """Claude's reply as an instance of `schema`, or an `ExtractionError` that says why it
111
+ isn't one."""
112
+ stop_reason = getattr(message, "stop_reason", None)
113
+ if stop_reason == "max_tokens":
114
+ raise ExtractionError(
115
+ f"Claude's reply was cut off at {max_tokens} output tokens, before the "
116
+ f"{schema.__name__} was complete; raise the limit (--max-tokens) or extract a "
117
+ "shorter document"
118
+ )
119
+ if stop_reason == "refusal":
120
+ raise ExtractionError(
121
+ "Claude declined to extract from this document (stop_reason 'refusal')"
122
+ )
123
+ text = "".join(
124
+ block.text
125
+ for block in getattr(message, "content", [])
126
+ if getattr(block, "type", "") == "text"
127
+ )
128
+ try:
129
+ payload = json.loads(text)
130
+ except ValueError as exc:
131
+ raise ExtractionError(
132
+ f"Claude did not return a {schema.__name__} as JSON (stop_reason={stop_reason!r})"
133
+ ) from exc
134
+ return validate_data(payload, schema, "Claude's reply")
135
+
136
+
137
+ def _build_prompt(document: Document) -> str:
138
+ parts = [f"Document: {document.source}\n"]
139
+ for page in document.pages:
140
+ parts.append(f"=== Page {page.number} ===\n{page.text}\n")
141
+ return "\n".join(parts)
@@ -0,0 +1,98 @@
1
+ """The provider-agnostic extractor interface and result envelope."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from typing import Any, Protocol, TypeVar
8
+
9
+ from pydantic import BaseModel, ValidationError
10
+
11
+ from fieldproof.document.model import Document
12
+
13
+ T = TypeVar("T", bound=BaseModel)
14
+
15
+
16
+ class ExtractionError(RuntimeError):
17
+ """Raised when an extraction can't be turned into the schema: a provider's
18
+ response, or a stored result that isn't JSON or doesn't have the schema's
19
+ shape. The message is written for the person who supplied the file."""
20
+
21
+
22
+ def read_extraction_json(content: str | bytes, source: str) -> dict[str, Any]:
23
+ """Parse a stored extraction (a fixture, or another tool's `result.json`).
24
+ `source` names the file in the error."""
25
+ try:
26
+ text = content.decode("utf-8") if isinstance(content, bytes) else content
27
+ raw = json.loads(text)
28
+ except UnicodeDecodeError as exc:
29
+ raise ExtractionError(f"{source} is not UTF-8 text") from exc
30
+ except json.JSONDecodeError as exc:
31
+ raise ExtractionError(
32
+ f"{source} is not valid JSON (line {exc.lineno}, column {exc.colno}: {exc.msg})"
33
+ ) from exc
34
+ if not isinstance(raw, dict):
35
+ raise ExtractionError(f"{source} must hold a JSON object, not {type(raw).__name__}")
36
+ return raw
37
+
38
+
39
+ def validate_data(payload: Any, schema: type[T], source: str) -> T:
40
+ """`payload` as an instance of `schema`, or an `ExtractionError` that
41
+ lists what doesn't fit, field by field, instead of pydantic's full report."""
42
+ try:
43
+ return schema.model_validate(payload)
44
+ except ValidationError as exc:
45
+ problems = [
46
+ f"{'.'.join(str(part) for part in error['loc']) or 'data'}: {error['msg']}"
47
+ for error in exc.errors()
48
+ ]
49
+ shown = "; ".join(problems[:3])
50
+ more = f" (and {len(problems) - 3} more)" if len(problems) > 3 else ""
51
+ raise ExtractionError(
52
+ f"{source} does not match the {schema.__name__} schema: {shown}{more}"
53
+ ) from exc
54
+
55
+
56
+ def _text_or(value: Any, default: str | None) -> str | None:
57
+ return value if isinstance(value, str) else default
58
+
59
+
60
+ @dataclass
61
+ class ExtractionResult:
62
+ """A schema instance plus provenance - which provider/model produced it,
63
+ so `result.json` is self-describing when it's re-verified later."""
64
+
65
+ schema_name: str
66
+ data: BaseModel
67
+ provider: str
68
+ model: str | None = None
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ return {
72
+ "schema": self.schema_name,
73
+ "provider": self.provider,
74
+ "model": self.model,
75
+ "data": self.data.model_dump(mode="json"),
76
+ }
77
+
78
+ @classmethod
79
+ def from_dict(
80
+ cls, raw: dict[str, Any], schema: type[T], *, source: str = "the result"
81
+ ) -> ExtractionResult:
82
+ if "data" not in raw:
83
+ raise ExtractionError(f'{source} has no "data" object')
84
+ return cls(
85
+ schema_name=_text_or(raw.get("schema"), None) or schema.__name__,
86
+ data=validate_data(raw["data"], schema, source),
87
+ provider=_text_or(raw.get("provider"), None) or "unknown",
88
+ model=_text_or(raw.get("model"), None),
89
+ )
90
+
91
+
92
+ class Extractor(Protocol):
93
+ """Anything that can turn a `Document` into a schema instance. Both
94
+ `AnthropicExtractor` and `FixtureExtractor` implement this without a
95
+ shared base class - it's a structural protocol so a third-party
96
+ extractor doesn't need to import fieldproof internals to conform."""
97
+
98
+ def extract(self, document: Document, schema: type[T]) -> ExtractionResult: ...
@@ -0,0 +1,46 @@
1
+ """Fixture extractor: replays a stored JSON extraction instead of calling a
2
+ live provider.
3
+
4
+ This is what the test suite, the CI pipeline, and the static Pages demo all
5
+ use - none of them have an API key or network access, and none of them
6
+ should need one to exercise grounding, verification, or the review UI. A
7
+ fixture is exactly the `ExtractionResult.to_dict()` shape a real provider
8
+ would have produced.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import TypeVar
16
+
17
+ from pydantic import BaseModel
18
+
19
+ from fieldproof.document.model import Document
20
+ from fieldproof.extract.base import ExtractionResult, read_extraction_json, validate_data
21
+
22
+ T = TypeVar("T", bound=BaseModel)
23
+
24
+
25
+ @dataclass
26
+ class FixtureExtractor:
27
+ """Loads `fixture_path` (JSON) and validates it against the requested
28
+ schema. The document argument is accepted (to satisfy the `Extractor`
29
+ protocol) but not read - the fixture is expected to already match the
30
+ document it stands in for. If it doesn't, grounding will simply report
31
+ the mismatched fields as unsupported, which is a legitimate way to
32
+ exercise that path in tests."""
33
+
34
+ fixture_path: str | Path
35
+
36
+ def extract(self, document: Document, schema: type[T]) -> ExtractionResult:
37
+ del document # unused: part of the Extractor protocol
38
+ source = Path(self.fixture_path).name
39
+ raw = read_extraction_json(Path(self.fixture_path).read_bytes(), source)
40
+ model = raw.get("model")
41
+ return ExtractionResult(
42
+ schema_name=schema.__name__,
43
+ data=validate_data(raw.get("data", raw), schema, source),
44
+ provider="fixture",
45
+ model=model if isinstance(model, str) else str(self.fixture_path),
46
+ )
@@ -0,0 +1,26 @@
1
+ from fieldproof.ground.align import (
2
+ MIN_MATCH_SCORE,
3
+ STRONG_MATCH_SCORE,
4
+ GroundingMatch,
5
+ find_candidates,
6
+ find_candidates_in_document,
7
+ find_quote,
8
+ ground_quote,
9
+ nearest_candidate,
10
+ rects_for_match,
11
+ )
12
+ from fieldproof.ground.normalize import normalize, normalize_with_map
13
+
14
+ __all__ = [
15
+ "MIN_MATCH_SCORE",
16
+ "STRONG_MATCH_SCORE",
17
+ "GroundingMatch",
18
+ "find_candidates",
19
+ "find_candidates_in_document",
20
+ "find_quote",
21
+ "ground_quote",
22
+ "nearest_candidate",
23
+ "normalize",
24
+ "normalize_with_map",
25
+ "rects_for_match",
26
+ ]
@@ -0,0 +1,289 @@
1
+ """Locate a quoted string on a page: exact match first, fuzzy fallback.
2
+
3
+ This is the core of "showing its work": a field's evidence is worthless if
4
+ we can't point at where on the page it actually is - and worse than
5
+ worthless if it points at the *wrong* place while still reporting
6
+ "verified". A short quote like "1" must never be allowed to match the
7
+ trailing digit of a street address like "4821": every exact match is
8
+ required to cover whole words (`_word_aligned_occurrences`; punctuation
9
+ attached to a word, like the comma in "1," or the "$" in "$2,458.00", may be
10
+ left out, letters and digits may not), and a fuzzy match that cuts a word is
11
+ scored against the whole words it touches (`_fuzzy_match`), so "wind" does
12
+ not count as found in "Northwind". When a quote genuinely occurs more than
13
+ once, `find_candidates` returns every occurrence rather than silently
14
+ picking the first one, so a caller (`fieldproof.verify.engine`) can
15
+ disambiguate by context or admit it can't.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass
21
+
22
+ from rapidfuzz import fuzz
23
+
24
+ from fieldproof.document.model import BBox, Document, Page, Word
25
+ from fieldproof.ground.normalize import normalize, normalize_with_map
26
+
27
+ #: Below this fuzzy score (0-100), we consider the quote not found on the
28
+ #: page rather than report a misleading low-confidence match.
29
+ MIN_MATCH_SCORE = 70.0
30
+
31
+ #: At or above this score, a match is "strong" evidence; below it (but
32
+ #: above MIN_MATCH_SCORE) it's "weak" - used by fieldproof.verify to decide
33
+ #: needs_review vs. verified.
34
+ STRONG_MATCH_SCORE = 92.0
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class GroundingMatch:
39
+ """Where a quote was found: its span in `Page.text`, the words it
40
+ covers, and how good the match was (100 = exact)."""
41
+
42
+ quote: str
43
+ page_number: int
44
+ start: int
45
+ end: int
46
+ score: float
47
+ matched_text: str
48
+ words: tuple[Word, ...]
49
+
50
+ @property
51
+ def is_exact(self) -> bool:
52
+ return self.score >= 100.0
53
+
54
+ @property
55
+ def is_strong(self) -> bool:
56
+ return self.score >= STRONG_MATCH_SCORE
57
+
58
+ @property
59
+ def top(self) -> float:
60
+ """Vertical position (PDF points from the page top) used to judge
61
+ which of several ambiguous matches is "on the same row" as another
62
+ field's evidence - the average of its words' tops, so a match is
63
+ represented by a single comparable y-coordinate."""
64
+ if not self.words:
65
+ return 0.0
66
+ return sum(w.bbox.top for w in self.words) / len(self.words)
67
+
68
+
69
+ def _covers_whole_words(page: Page, start: int, end: int, words: list[Word]) -> bool:
70
+ """Does the span `[start, end)` cover every letter and digit of the words
71
+ it touches? Punctuation glued to a word may be left outside: the page's
72
+ words are split on whitespace, so "1," and "$2,458.00" are one word each,
73
+ and a quote of "1" or "2,458.00" still names the whole of what is there.
74
+ "458.00" does not: the "2," it leaves out is part of the number."""
75
+ left_out = page.text[words[0].start : start] + page.text[end : words[-1].end]
76
+ return not any(ch.isalnum() for ch in left_out)
77
+
78
+
79
+ def _splits_a_character(index_map: list[int], first: int, last: int) -> bool:
80
+ """One page character can normalize to several (the ligature "\ufb01" to
81
+ "fi"). Does the normalized span `first..last` begin or end between them?
82
+ Its page span would then cover a character the quote only half matches."""
83
+ begins_inside = first > 0 and index_map[first - 1] == index_map[first]
84
+ ends_inside = last + 1 < len(index_map) and index_map[last + 1] == index_map[last]
85
+ return begins_inside or ends_inside
86
+
87
+
88
+ def _word_aligned_occurrences(quote: str, page: Page) -> list[GroundingMatch]:
89
+ """Every exact (normalized) occurrence of `quote` in `page` that covers
90
+ whole words - i.e. never starts or ends mid-token. Without this check, a
91
+ one-character quote like "1" would happily match the trailing digit of
92
+ "4821"; pdfplumber never splits "4821" into separate word tokens, so
93
+ requiring the match to leave no letter or digit of a touched word
94
+ uncovered rules that out entirely, while still allowing a quote that
95
+ spans several whole words (e.g. a full line-item row)."""
96
+ normalized_quote = normalize(quote)
97
+ if not normalized_quote or not page.words:
98
+ return []
99
+
100
+ norm_page_text, index_map = normalize_with_map(page.text)
101
+ if not norm_page_text:
102
+ return []
103
+
104
+ matches: list[GroundingMatch] = []
105
+ qlen = len(normalized_quote)
106
+ search_from = 0
107
+ while True:
108
+ idx = norm_page_text.find(normalized_quote, search_from)
109
+ if idx == -1:
110
+ break
111
+ search_from = idx + 1
112
+
113
+ last = idx + qlen - 1
114
+ if _splits_a_character(index_map, idx, last):
115
+ continue
116
+
117
+ start = index_map[idx]
118
+ end = index_map[last] + 1
119
+ words = _words_overlapping(page.words, start, end)
120
+ if not words or not _covers_whole_words(page, start, end, words):
121
+ continue
122
+ matches.append(
123
+ GroundingMatch(
124
+ quote=quote,
125
+ page_number=page.number,
126
+ start=start,
127
+ end=end,
128
+ score=100.0,
129
+ matched_text=page.text[start:end],
130
+ words=tuple(words),
131
+ )
132
+ )
133
+ return matches
134
+
135
+
136
+ def _fuzzy_match(quote: str, page: Page) -> GroundingMatch | None:
137
+ normalized_quote = normalize(quote)
138
+ if not normalized_quote or not page.words:
139
+ return None
140
+
141
+ norm_page_text, index_map = normalize_with_map(page.text)
142
+ if not norm_page_text:
143
+ return None
144
+
145
+ alignment = fuzz.partial_ratio_alignment(normalized_quote, norm_page_text)
146
+ if alignment is None or alignment.dest_end <= alignment.dest_start:
147
+ return None
148
+ if alignment.score < MIN_MATCH_SCORE:
149
+ return None
150
+
151
+ start = index_map[alignment.dest_start]
152
+ end = index_map[alignment.dest_end - 1] + 1
153
+ words = _words_overlapping(page.words, start, end)
154
+ if not words:
155
+ return None
156
+
157
+ score = alignment.score
158
+ cut = _splits_a_character(index_map, alignment.dest_start, alignment.dest_end - 1)
159
+ if cut or not _covers_whole_words(page, start, end, words):
160
+ # The best window cuts a word: the quote is a fragment of something
161
+ # longer on the page ("wind" in "Northwind", "0214" in "NW-20260214").
162
+ # A fragment is a perfect *partial* match, which is exactly the
163
+ # misleading 100 this module exists to refuse. Judge the quote against
164
+ # the whole words instead.
165
+ start, end = words[0].start, words[-1].end
166
+ score = fuzz.ratio(normalized_quote, normalize(page.text[start:end]))
167
+ if score < MIN_MATCH_SCORE:
168
+ return None
169
+
170
+ return GroundingMatch(
171
+ quote=quote,
172
+ page_number=page.number,
173
+ start=start,
174
+ end=end,
175
+ score=score,
176
+ matched_text=page.text[start:end],
177
+ words=tuple(words),
178
+ )
179
+
180
+
181
+ def find_candidates(quote: str, page: Page) -> list[GroundingMatch]:
182
+ """All plausible locations for `quote` on `page`: every word-aligned
183
+ exact occurrence if there is at least one, otherwise the single best
184
+ fuzzy match (fuzzy scoring across many candidates isn't meaningful, so
185
+ fuzzy only ever contributes one). An empty list means not found."""
186
+ exact = _word_aligned_occurrences(quote, page)
187
+ if exact:
188
+ return exact
189
+ fuzzy = _fuzzy_match(quote, page)
190
+ return [fuzzy] if fuzzy is not None else []
191
+
192
+
193
+ def find_quote(quote: str, page: Page) -> GroundingMatch | None:
194
+ """Find `quote` on a single page, or return None if it isn't there.
195
+
196
+ A low-level convenience for simple/unambiguous lookups: if `quote`
197
+ occurs more than once, this returns the first occurrence without
198
+ trying to disambiguate - callers that need to handle ambiguity
199
+ correctly (as `fieldproof.verify.engine` does) should use
200
+ `find_candidates` directly instead.
201
+ """
202
+ candidates = find_candidates(quote, page)
203
+ return candidates[0] if candidates else None
204
+
205
+
206
+ def ground_quote(
207
+ quote: str, document: Document, *, hint_page: int | None = None
208
+ ) -> GroundingMatch | None:
209
+ """Find `quote` anywhere in `document`, preferring `hint_page` (the page
210
+ the extractor claimed) when scores tie, and returning the best-scoring
211
+ match across all pages otherwise - a provider's page number is often
212
+ right but not authoritative. Like `find_quote`, does not disambiguate
213
+ multiple occurrences - see `find_candidates_in_document`."""
214
+ best: GroundingMatch | None = None
215
+ pages = sorted(document.pages, key=lambda p: p.number != hint_page)
216
+ for page in pages:
217
+ match = find_quote(quote, page)
218
+ if match is None:
219
+ continue
220
+ if best is None or match.score > best.score:
221
+ best = match
222
+ if best is not None and best.is_exact and page.number == hint_page:
223
+ break
224
+ return best
225
+
226
+
227
+ def find_candidates_in_document(
228
+ quote: str, document: Document, *, hint_page: int | None = None
229
+ ) -> list[GroundingMatch]:
230
+ """Every plausible location for `quote` anywhere in `document`. If any
231
+ page has word-aligned exact occurrences, only exact occurrences (from
232
+ all pages, `hint_page` first) are returned - fuzzy matches from other
233
+ pages are never mixed in as "maybe this instead" once an exact hit
234
+ exists anywhere. If none do, falls back to the single best fuzzy match
235
+ across pages."""
236
+ pages = sorted(document.pages, key=lambda p: p.number != hint_page)
237
+
238
+ exact: list[GroundingMatch] = []
239
+ for page in pages:
240
+ exact.extend(_word_aligned_occurrences(quote, page))
241
+ if exact:
242
+ return exact
243
+
244
+ best_fuzzy: GroundingMatch | None = None
245
+ for page in pages:
246
+ match = _fuzzy_match(quote, page)
247
+ if match is not None and (best_fuzzy is None or match.score > best_fuzzy.score):
248
+ best_fuzzy = match
249
+ return [best_fuzzy] if best_fuzzy is not None else []
250
+
251
+
252
+ def nearest_candidate(candidates: list[GroundingMatch], hint: GroundingMatch) -> GroundingMatch:
253
+ """Pick whichever of several ambiguous `candidates` is closest to
254
+ `hint` - same page first, then smallest vertical distance between
255
+ their word tops. Used to resolve "the quote appears N times" by
256
+ preferring the occurrence on the same row as another field from the
257
+ same object that's already been grounded (e.g. a line item's
258
+ description) - see `fieldproof.verify.engine`."""
259
+
260
+ def distance(candidate: GroundingMatch) -> tuple[int, float]:
261
+ same_page = 0 if candidate.page_number == hint.page_number else 1
262
+ return (same_page, abs(candidate.top - hint.top))
263
+
264
+ return min(candidates, key=distance)
265
+
266
+
267
+ def _words_overlapping(words: list[Word], start: int, end: int) -> list[Word]:
268
+ return [w for w in words if w.start < end and w.end > start]
269
+
270
+
271
+ def rects_for_match(match: GroundingMatch, line_tolerance: float = 3.0) -> list[BBox]:
272
+ """Merge a match's words into one highlight rectangle per line, so a
273
+ quote spanning several lines renders as several boxes instead of one box
274
+ covering the full width between the first and last line."""
275
+ if not match.words:
276
+ return []
277
+ ordered = sorted(match.words, key=lambda w: (w.bbox.top, w.bbox.x0))
278
+ rects: list[BBox] = []
279
+ current = ordered[0].bbox
280
+ current_top = ordered[0].bbox.top
281
+ for w in ordered[1:]:
282
+ if abs(w.bbox.top - current_top) <= line_tolerance:
283
+ current = current.union(w.bbox)
284
+ else:
285
+ rects.append(current)
286
+ current = w.bbox
287
+ current_top = w.bbox.top
288
+ rects.append(current)
289
+ return rects
@@ -0,0 +1,80 @@
1
+ """Text normalization for grounding.
2
+
3
+ The model's evidence quotes and the page's own text layer rarely agree on
4
+ byte-for-byte punctuation: curly vs. straight quotes, ligatures a PDF font
5
+ substitutes for "fi"/"fl", and runs of whitespace where the original had a
6
+ line break or a tab. `normalize_with_map` normalizes while keeping a
7
+ character-by-character map back to the original string, so a match found in
8
+ normalized text can still be located in the original page text (and from
9
+ there, in `Page.words`).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import unicodedata
15
+
16
+ _QUOTE_MAP = {
17
+ "‘": "'",
18
+ "’": "'",
19
+ "‚": "'",
20
+ "‛": "'",
21
+ "“": '"',
22
+ "”": '"',
23
+ "„": '"',
24
+ "‟": '"',
25
+ "«": '"',
26
+ "»": '"',
27
+ "‐": "-",
28
+ "‑": "-",
29
+ "‒": "-",
30
+ "–": "-",
31
+ "—": "-",
32
+ "−": "-",
33
+ }
34
+
35
+
36
+ def _map_char(ch: str) -> str:
37
+ if ch in _QUOTE_MAP:
38
+ return _QUOTE_MAP[ch]
39
+ return unicodedata.normalize("NFKC", ch)
40
+
41
+
42
+ def normalize(text: str) -> str:
43
+ """Normalize text for comparison: NFKC, ligature expansion, straight
44
+ quotes/dashes, collapsed whitespace. Loses position information - use
45
+ `normalize_with_map` when you need to locate the result in `text`."""
46
+ return normalize_with_map(text)[0]
47
+
48
+
49
+ def normalize_with_map(text: str) -> tuple[str, list[int]]:
50
+ """Like `normalize`, but also returns `index_map` where
51
+ `index_map[i]` is the offset in `text` that normalized character `i`
52
+ came from. `len(normalized) == len(index_map)`, always."""
53
+ out: list[str] = []
54
+ index_map: list[int] = []
55
+ in_whitespace_run = False
56
+
57
+ for i, ch in enumerate(text):
58
+ mapped = _map_char(ch)
59
+ if not mapped:
60
+ continue
61
+ if mapped.isspace():
62
+ if in_whitespace_run:
63
+ continue
64
+ out.append(" ")
65
+ index_map.append(i)
66
+ in_whitespace_run = True
67
+ continue
68
+ in_whitespace_run = False
69
+ for c in mapped:
70
+ out.append(c)
71
+ index_map.append(i)
72
+
73
+ start = 0
74
+ end = len(out)
75
+ while start < end and out[start] == " ":
76
+ start += 1
77
+ while end > start and out[end - 1] == " ":
78
+ end -= 1
79
+
80
+ return "".join(out[start:end]), index_map[start:end]