fieldproof 0.2.3__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,321 @@
1
+ """Value-vs-evidence consistency: does the extracted value actually say what
2
+ the cited quote says?
3
+
4
+ Grounding only proves a quote exists on the page - it says nothing about
5
+ whether the *value* the model attached to it is correct. A model can (and
6
+ occasionally does) quote a real sentence and then attach the wrong number to
7
+ it. This module re-derives a value from the matched evidence text
8
+ independently - parsing a number, a date, or fuzzy-comparing a string - and
9
+ flags a mismatch.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from dataclasses import dataclass
16
+ from datetime import date, datetime
17
+ from typing import Literal
18
+
19
+ from rapidfuzz import fuzz
20
+
21
+ from fieldproof.ground.normalize import normalize
22
+
23
+ #: Absolute tolerance (in the field's own units, e.g. dollars) for numeric
24
+ #: value-vs-evidence comparisons - covers rounding in how the model or the
25
+ #: document itself formats cents.
26
+ NUMBER_TOLERANCE = 0.01
27
+
28
+ #: Below this rapidfuzz ratio (0-100), a string value is not considered
29
+ #: supported by its evidence text.
30
+ STRING_MATCH_THRESHOLD = 82.0
31
+
32
+ _MONEY_STRIP = re.compile(r"[^0-9.\-]")
33
+
34
+ #: A currency/plain-number token, optionally wrapped in parens (accounting
35
+ #: negative) or followed by "%" (so a rate like "8.5%" can be told apart
36
+ #: from the dollar amount next to it, e.g. "Tax (8.5%) $208.93").
37
+ _NUMBER_TOKEN = re.compile(r"\(?-?\$?\d[\d,]*(?:\.\d+)?\)?%?")
38
+
39
+ _DATE_FORMATS = (
40
+ "%Y-%m-%d",
41
+ "%m/%d/%Y",
42
+ "%m/%d/%y",
43
+ "%d/%m/%Y",
44
+ "%B %d, %Y",
45
+ "%b %d, %Y",
46
+ "%d %B %Y",
47
+ "%d %b %Y",
48
+ "%Y/%m/%d",
49
+ )
50
+
51
+ #: Date-shaped substrings to search for inside free text (e.g. "Issue Date:
52
+ #: January 1, 2026") - evidence is a verbatim quote, so it often carries a
53
+ #: label or surrounding words the schema's ISO-8601 value never does; a full
54
+ #: strptime match would reject that and never find the date at all.
55
+ _DATE_SEARCH_PATTERNS = (
56
+ re.compile(r"\d{4}-\d{2}-\d{2}"),
57
+ re.compile(r"\d{1,2}/\d{1,2}/\d{2,4}"),
58
+ re.compile(r"[A-Za-z]{3,9}\.?\s+\d{1,2},?\s+\d{4}"),
59
+ re.compile(r"\d{1,2}\s+[A-Za-z]{3,9}\.?\s+\d{4}"),
60
+ )
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class ValueCheckResult:
65
+ supported: bool
66
+ reason: str = ""
67
+
68
+
69
+ def _token_to_float(token: str) -> float | None:
70
+ negative = token.startswith("(") or token.endswith(")")
71
+ cleaned = _MONEY_STRIP.sub("", token.replace(",", ""))
72
+ if not cleaned or cleaned in {"-", "."}:
73
+ return None
74
+ try:
75
+ value = float(cleaned)
76
+ except ValueError:
77
+ return None
78
+ return -abs(value) if negative else value
79
+
80
+
81
+ def parse_all_numbers(text: str) -> list[float]:
82
+ """Every plain (non-percentage) number in `text`, in reading order -
83
+ strips currency symbols and thousands separators, and excludes rate-like
84
+ tokens such as the "8.5" in "Tax (8.5%) $208.93". Evidence for a
85
+ row-level field is often the whole row (e.g. "Fuel surcharge 1 210.50
86
+ 210.50" for a quantity of 1), so a value check needs to ask "does this
87
+ number appear anywhere in the evidence", not just "is it the last
88
+ number" - see `check_number`."""
89
+ text = text.strip()
90
+ if not text:
91
+ return []
92
+
93
+ if text.startswith("(") and text.endswith(")"):
94
+ inner = _MONEY_STRIP.sub("", text[1:-1].replace(",", ""))
95
+ if inner and inner not in {"-", "."}:
96
+ try:
97
+ return [-abs(float(inner))]
98
+ except ValueError:
99
+ pass
100
+
101
+ matches = list(_NUMBER_TOKEN.finditer(text))
102
+ non_percent = [m for m in matches if not m.group(0).endswith("%")]
103
+ candidates = non_percent or matches
104
+ values = [_token_to_float(m.group(0)) for m in candidates]
105
+ return [v for v in values if v is not None]
106
+
107
+
108
+ def parse_number(text: str) -> float | None:
109
+ """Best-effort extraction of a single number from free text - the last
110
+ non-percentage number token, e.g. "208.93" from "Tax (8.5%) $208.93".
111
+ For evidence that may contain several numbers where any one of them
112
+ could be the value being checked (a whole line-item row, say), use
113
+ `parse_all_numbers` / `check_number` instead."""
114
+ values = parse_all_numbers(text)
115
+ return values[-1] if values else None
116
+
117
+
118
+ def parse_date(text: str) -> date | None:
119
+ """Parse a date from either ISO-8601 (what the schema asks the model
120
+ for) or a handful of common document formats (what evidence text, taken
121
+ verbatim from the page, is more likely to contain). Tries a full-string
122
+ match first; if that fails, searches for a date-shaped substring within
123
+ surrounding text like "Issue Date: January 1, 2026"."""
124
+ stripped = text.strip()
125
+ candidate = _try_formats(stripped)
126
+ if candidate is not None:
127
+ return candidate
128
+
129
+ for pattern in _DATE_SEARCH_PATTERNS:
130
+ match = pattern.search(stripped)
131
+ if match is None:
132
+ continue
133
+ candidate = _try_formats(match.group(0))
134
+ if candidate is not None:
135
+ return candidate
136
+ return None
137
+
138
+
139
+ def _try_formats(text: str) -> date | None:
140
+ for fmt in _DATE_FORMATS:
141
+ try:
142
+ return datetime.strptime(text, fmt).date()
143
+ except ValueError:
144
+ continue
145
+ return None
146
+
147
+
148
+ def check_number(value: float, evidence_text: str) -> ValueCheckResult:
149
+ """Does `value` appear anywhere among the numbers in `evidence_text`?
150
+ Evidence for a row-level field can be the whole row (several numbers,
151
+ one of which is the value), not just the value on its own - so this
152
+ checks membership, not just "is it the last number parsed"."""
153
+ candidates = parse_all_numbers(evidence_text)
154
+ if not candidates:
155
+ return ValueCheckResult(False, f"could not parse a number from evidence {evidence_text!r}")
156
+ if any(abs(c - value) <= NUMBER_TOLERANCE for c in candidates):
157
+ return ValueCheckResult(True)
158
+ closest = min(candidates, key=lambda c: abs(c - value))
159
+ return ValueCheckResult(
160
+ False, f"value {value:g} does not match {closest:g} parsed from the evidence"
161
+ )
162
+
163
+
164
+ _NUMERIC_DATE = re.compile(r"(?<!\d)(\d{1,2})/(\d{1,2})/(\d{4}|\d{2})(?!\d)")
165
+
166
+ DateOrder = Literal["mdy", "dmy"]
167
+
168
+
169
+ def numeric_date_order(text: str) -> DateOrder | None:
170
+ """The day/month order a document's numeric dates settle between them:
171
+ "mdy" if some date's second part is over 12 (03/14/2026), "dmy" if some
172
+ date's first part is (14/03/2026), None if no date settles it or the
173
+ document mixes both."""
174
+ month_first = day_first = False
175
+ for m in _NUMERIC_DATE.finditer(text):
176
+ first, second = int(m.group(1)), int(m.group(2))
177
+ if second > 12 >= first:
178
+ month_first = True
179
+ elif first > 12 >= second:
180
+ day_first = True
181
+ if month_first == day_first:
182
+ return None
183
+ return "mdy" if month_first else "dmy"
184
+
185
+
186
+ def _numeric_readings(match: re.Match[str]) -> dict[DateOrder, date]:
187
+ first, second, year = match.group(1), match.group(2), match.group(3)
188
+ year_fmt = "%Y" if len(year) == 4 else "%y"
189
+ readings: dict[DateOrder, date] = {}
190
+ orders: tuple[tuple[DateOrder, str], ...] = (
191
+ ("mdy", f"%m/%d/{year_fmt}"),
192
+ ("dmy", f"%d/%m/{year_fmt}"),
193
+ )
194
+ for order, fmt in orders:
195
+ try:
196
+ readings[order] = datetime.strptime(f"{first}/{second}/{year}", fmt).date()
197
+ except ValueError:
198
+ continue
199
+ return readings
200
+
201
+
202
+ def check_date(
203
+ value: str, evidence_text: str, *, date_order: DateOrder | None = None
204
+ ) -> ValueCheckResult:
205
+ """Does the evidence show the claimed date? A numeric date whose first two
206
+ parts are both 12 or under (03/04/2026) reads as 4 March or 3 April; it is
207
+ read in `date_order` (see `numeric_date_order`) when the document settles
208
+ that, and otherwise can't verify a value on its own."""
209
+ claimed = parse_date(value)
210
+ if claimed is None:
211
+ return ValueCheckResult(False, f"value {value!r} is not a parseable ISO-8601 date")
212
+
213
+ numeric = _numeric_date_in(evidence_text.strip())
214
+ if numeric is not None:
215
+ readings = _numeric_readings(numeric)
216
+ if len(set(readings.values())) == 2:
217
+ if date_order is not None:
218
+ found = readings[date_order]
219
+ elif claimed in readings.values():
220
+ return ValueCheckResult(
221
+ False,
222
+ f"the evidence date {numeric.group(0)!r} reads as "
223
+ f"{readings['mdy'].isoformat()} (month first) or "
224
+ f"{readings['dmy'].isoformat()} (day first), and no other date on the "
225
+ "document settles which",
226
+ )
227
+ else:
228
+ return ValueCheckResult(
229
+ False,
230
+ f"value {claimed.isoformat()} matches neither reading of "
231
+ f"{numeric.group(0)!r} ({readings['mdy'].isoformat()} or "
232
+ f"{readings['dmy'].isoformat()})",
233
+ )
234
+ if claimed == found:
235
+ return ValueCheckResult(True)
236
+ return ValueCheckResult(
237
+ False,
238
+ f"value {claimed.isoformat()} does not match {found.isoformat()} parsed from "
239
+ f"the evidence (this document writes dates "
240
+ f"{'month' if date_order == 'mdy' else 'day'} first)",
241
+ )
242
+
243
+ parsed = parse_date(evidence_text)
244
+ if parsed is None:
245
+ return ValueCheckResult(False, f"could not parse a date from evidence {evidence_text!r}")
246
+ if claimed == parsed:
247
+ return ValueCheckResult(True)
248
+ return ValueCheckResult(
249
+ False,
250
+ f"value {claimed.isoformat()} does not match {parsed.isoformat()} parsed from the evidence",
251
+ )
252
+
253
+
254
+ #: Formats in `_DATE_FORMATS` where day and month can't be confused.
255
+ _UNAMBIGUOUS_FORMATS = tuple(f for f in _DATE_FORMATS if not f.startswith(("%m/", "%d/")))
256
+
257
+
258
+ def _numeric_date_in(text: str) -> re.Match[str] | None:
259
+ """The day/month/year date `parse_date` would read from `text`, when that is
260
+ a numeric one (it prefers a whole-string ISO or written-month date, then an
261
+ ISO date inside the text, before a numeric one)."""
262
+ for fmt in _UNAMBIGUOUS_FORMATS:
263
+ try:
264
+ datetime.strptime(text, fmt)
265
+ return None
266
+ except ValueError:
267
+ continue
268
+ if _DATE_SEARCH_PATTERNS[0].search(text):
269
+ return None
270
+ return _NUMERIC_DATE.search(text)
271
+
272
+
273
+ _DIGIT_RUN = re.compile(r"\d+")
274
+
275
+
276
+ def check_string(
277
+ value: str, evidence_text: str, *, threshold: float = STRING_MATCH_THRESHOLD
278
+ ) -> ValueCheckResult:
279
+ """Is `value` actually present in `evidence_text`? Evidence is a
280
+ verbatim quote and is often longer than the value it supports (e.g. the
281
+ quote "Invoice Number: INV-1001" for the value "INV-1001"), so this uses
282
+ partial-ratio (best-matching substring) rather than whole-string
283
+ similarity - a short value inside a longer quote should still verify."""
284
+ normalized_value, normalized_evidence = normalize(value), normalize(evidence_text)
285
+ # Wording can differ a little and still be the same name. A number can't:
286
+ # "NW-20260215" against a page that reads "NW-20260214" is 96% similar and
287
+ # a different invoice. Every run of digits in the value has to be in the
288
+ # evidence as written.
289
+ evidence_numbers = set(_DIGIT_RUN.findall(normalized_evidence))
290
+ for number in _DIGIT_RUN.findall(normalized_value):
291
+ if number not in evidence_numbers:
292
+ return ValueCheckResult(
293
+ False,
294
+ f"value {value!r} contains {number!r}, "
295
+ f"which the evidence {evidence_text!r} does not",
296
+ )
297
+ score = fuzz.partial_ratio(normalized_value, normalized_evidence)
298
+ if score >= threshold:
299
+ return ValueCheckResult(True)
300
+ return ValueCheckResult(
301
+ False, f"value {value!r} is only {score:.0f}% similar to evidence {evidence_text!r}"
302
+ )
303
+
304
+
305
+ _POSITIVE_WORDS = frozenset({"yes", "true", "confirmed", "agreed", "approved"})
306
+ _NEGATIVE_WORDS = frozenset({"no", "not", "false", "denied", "declined"})
307
+ _WORD = re.compile(r"[a-z]+")
308
+
309
+
310
+ def check_bool(value: bool, evidence_text: str) -> ValueCheckResult:
311
+ # Whole words: "no" inside "notice" or "November" is not a negation.
312
+ words = set(_WORD.findall(normalize(evidence_text).lower()))
313
+ positive = bool(words & _POSITIVE_WORDS)
314
+ negative = bool(words & _NEGATIVE_WORDS)
315
+ if value and positive and not negative:
316
+ return ValueCheckResult(True)
317
+ if not value and negative:
318
+ return ValueCheckResult(True)
319
+ return ValueCheckResult(
320
+ False, f"boolean value {value} is not clearly supported by evidence {evidence_text!r}"
321
+ )