fieldproof 0.2.1__tar.gz

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.
Files changed (35) hide show
  1. fieldproof-0.2.1/.gitignore +39 -0
  2. fieldproof-0.2.1/CHANGELOG.md +124 -0
  3. fieldproof-0.2.1/LICENSE +21 -0
  4. fieldproof-0.2.1/PKG-INFO +394 -0
  5. fieldproof-0.2.1/README.md +354 -0
  6. fieldproof-0.2.1/pyproject.toml +119 -0
  7. fieldproof-0.2.1/src/fieldproof/__init__.py +8 -0
  8. fieldproof-0.2.1/src/fieldproof/cli.py +181 -0
  9. fieldproof-0.2.1/src/fieldproof/document/__init__.py +14 -0
  10. fieldproof-0.2.1/src/fieldproof/document/loader.py +86 -0
  11. fieldproof-0.2.1/src/fieldproof/document/model.py +99 -0
  12. fieldproof-0.2.1/src/fieldproof/document/ocr.py +115 -0
  13. fieldproof-0.2.1/src/fieldproof/document/render.py +47 -0
  14. fieldproof-0.2.1/src/fieldproof/extract/__init__.py +12 -0
  15. fieldproof-0.2.1/src/fieldproof/extract/anthropic_provider.py +141 -0
  16. fieldproof-0.2.1/src/fieldproof/extract/base.py +98 -0
  17. fieldproof-0.2.1/src/fieldproof/extract/fixture_provider.py +46 -0
  18. fieldproof-0.2.1/src/fieldproof/ground/__init__.py +26 -0
  19. fieldproof-0.2.1/src/fieldproof/ground/align.py +289 -0
  20. fieldproof-0.2.1/src/fieldproof/ground/normalize.py +80 -0
  21. fieldproof-0.2.1/src/fieldproof/schemas/__init__.py +48 -0
  22. fieldproof-0.2.1/src/fieldproof/schemas/base.py +52 -0
  23. fieldproof-0.2.1/src/fieldproof/schemas/contract.py +28 -0
  24. fieldproof-0.2.1/src/fieldproof/schemas/invoice.py +37 -0
  25. fieldproof-0.2.1/src/fieldproof/schemas/receipt.py +25 -0
  26. fieldproof-0.2.1/src/fieldproof/server/__init__.py +3 -0
  27. fieldproof-0.2.1/src/fieldproof/server/app.py +276 -0
  28. fieldproof-0.2.1/src/fieldproof/server/static/assets/index-BLATbujI.js +144 -0
  29. fieldproof-0.2.1/src/fieldproof/server/static/assets/index-Bo892MpF.css +1 -0
  30. fieldproof-0.2.1/src/fieldproof/server/static/index.html +50 -0
  31. fieldproof-0.2.1/src/fieldproof/server/store.py +57 -0
  32. fieldproof-0.2.1/src/fieldproof/verify/__init__.py +29 -0
  33. fieldproof-0.2.1/src/fieldproof/verify/cross_field.py +118 -0
  34. fieldproof-0.2.1/src/fieldproof/verify/engine.py +265 -0
  35. fieldproof-0.2.1/src/fieldproof/verify/value_checks.py +321 -0
@@ -0,0 +1,39 @@
1
+ # Python
2
+ __pycache__/
3
+ *.pyc
4
+ .venv/
5
+ *.egg-info/
6
+ .pytest_cache/
7
+ .ruff_cache/
8
+ .mypy_cache/
9
+ .coverage
10
+ htmlcov/
11
+ dist/
12
+ build/
13
+
14
+ # Node / web
15
+ web/node_modules/
16
+ web/dist/
17
+ web/dist-demo/
18
+ npm-debug.log*
19
+
20
+ # web/public/demo-data/ is intentionally COMMITTED (not ignored): the Pages
21
+ # deploy is a plain Node build (no Python/uv step - see
22
+ # .github/workflows/pages.yml), so the data scripts/build_demo_data.py
23
+ # precomputes has to already be on disk for `npm run build:demo` alone to
24
+ # produce a complete demo. Regenerate it with that script after changing
25
+ # examples/ or its fixtures, and commit the result.
26
+
27
+ # Generated (built by scripts/build_demo_data.py or the web build - never
28
+ # hand-edited, so committing them would just be stale binary diffs)
29
+ src/fieldproof/server/static/
30
+
31
+ # Editors / OS
32
+ .DS_Store
33
+ .vscode/
34
+ .idea/
35
+ *.swp
36
+
37
+ # Local scratch
38
+ *.local.json
39
+ .venv-minimums/
@@ -0,0 +1,124 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ ## [0.2.1] - 2026-10-02
6
+
7
+ ### Added
8
+
9
+ - Published to PyPI: `pip install fieldproof`. The package includes the built
10
+ review UI, so `fieldproof serve` works without a Node toolchain
11
+ (`scripts/bundle_ui.py` builds it into the package before a release).
12
+ - `fieldproof --version`.
13
+
14
+ ### Fixed
15
+
16
+ - A value quoted from inside a longer word could be marked `verified`. The
17
+ exact matcher refused a quote that cuts a word, and the fuzzy fallback then
18
+ scored the same fragment 100/100 as a perfect partial match. On the example
19
+ invoice, a vendor name of `wind` (inside "Northwind") and an invoice number
20
+ of `0214` (inside "NW-20260214") both verified. A match now has to cover
21
+ whole words; when the best fuzzy window cuts one, the quote is scored
22
+ against the whole words, so those two are `unsupported` and `458.00` is a
23
+ weak match for `$2,458.00`. Punctuation glued to a word may be left out of
24
+ a quote (`1` for `1,`, `2,458.00` for `$2,458.00`), and every such
25
+ occurrence counts when deciding whether a quote is ambiguous.
26
+ - A string value one digit off verified: `NW-20260215` for a document reading
27
+ `NW-20260214` is 96% similar, which passed both the grounding and the value
28
+ check. Every run of digits in a string value now has to appear in the
29
+ evidence as written.
30
+ - `--provider anthropic` against the real SDK. The provider had only met a
31
+ mocked client, which returned `parsed_output=None` for a reply that isn't
32
+ the schema. The SDK's `messages.parse` raises instead: an extraction cut
33
+ off at `max_tokens` (a long invoice) or refused came out as a pydantic
34
+ traceback, `Invalid JSON: EOF while parsing a string`. The provider now
35
+ streams the reply, reads its `stop_reason` and says which it was in one
36
+ line: `error: Claude's reply was cut off at 16000 output tokens, before the
37
+ Invoice was complete; raise the limit (--max-tokens) or extract a shorter
38
+ document`. New `--max-tokens` option. The tests run the real SDK over a
39
+ mocked HTTP transport.
40
+ - The declared minimum `anthropic>=0.40` had no `messages.parse`:
41
+ `AttributeError: 'Messages' object has no attribute 'parse'`. The minimum
42
+ is 0.77, the first release with structured outputs on the Messages API,
43
+ and the provider tests pass on it.
44
+ - Two more declared minimums did not work. With `typer` below 0.15.4 every
45
+ command stopped (`Type not yet supported: pathlib.Path | None` on 0.12.0;
46
+ `make_metavar() takes 1 positional argument` on `--help` with a current
47
+ click), and with `pydantic` below 2.10 a typed result could not be built
48
+ from `Evidenced` values. The minimums are `typer>=0.15.4` and
49
+ `pydantic>=2.10`, and CI has a job that installs the oldest allowed version
50
+ of every direct dependency on the oldest supported Python and runs the
51
+ tests there.
52
+ - A match could begin or end inside a ligature (`inal` matched "final").
53
+ - A result or fixture file that isn't valid JSON, isn't an object, or doesn't
54
+ fit the schema printed a traceback from `extract` and `verify`, and was an
55
+ unexplained 500 in the review UI. The CLI prints one line (`error:
56
+ result.json does not match the Invoice schema: total.value: Input should be
57
+ a valid number, unable to parse string as a number`) and the server answers
58
+ 422 with the same message. A file
59
+ that isn't a PDF, a missing API key and a failed API request are one line
60
+ too.
61
+
62
+ ### Added
63
+
64
+ - Seeded fuzz tests for the promise above: an exact match always covers whole
65
+ words, a piece of a longer word never verifies, a value with a number the
66
+ document lacks never verifies, and a damaged result file ends in a report or
67
+ a one-line error.
68
+
69
+ ## [0.2.0] - 2026-09-30
70
+
71
+ ### Fixed
72
+
73
+ - A numeric date with both parts 12 or under (`03/04/2026`) was always read
74
+ month first, so a day-first document's correctly extracted date was flagged
75
+ and a month-first misreading of it was marked verified. Such a date is now
76
+ read in the order another date on the same document settles, and goes to
77
+ review when none does.
78
+ - Boolean checks matched substrings: "no" inside "notice", "November" or
79
+ "none" counted as a negation. They match whole words now.
80
+
81
+ ### Changed
82
+
83
+ - The live demo opens on the invoice with its first flagged field selected,
84
+ instead of a landing page with three buttons. A sample switcher in the top
85
+ bar changes documents without a reload, and `#invoice` / `#receipt` /
86
+ `#contract` link straight to one.
87
+ - `fieldproof serve`: a "New document" button returns to the upload screen.
88
+ - A short note in the demo's field pane says the documents are synthetic
89
+ and the extractions are fixtures with planted errors.
90
+
91
+ ### Fixed
92
+
93
+ - Opening a sample on a narrow screen no longer scrolls the top bar out of
94
+ view.
95
+ - The Anthropic provider's docs no longer call Claude Opus 5.5 Anthropic's
96
+ most capable model.
97
+
98
+ ## [0.1.0] - 2026-09-24
99
+
100
+ Initial release.
101
+
102
+ ### Added
103
+
104
+ - `fieldproof.document`: PDF text-layer loading (pdfplumber), page image
105
+ rendering (pypdfium2), and an optional Tesseract OCR fallback for scanned
106
+ documents.
107
+ - `fieldproof.schemas`: `Evidenced[T]` value wrapper, a generic
108
+ `iter_evidenced_fields` walker, and built-in Invoice, Receipt, and
109
+ ContractKeyTerms templates.
110
+ - `fieldproof.extract`: a provider-agnostic `Extractor` protocol, an
111
+ Anthropic structured-output implementation, and a fixture provider for
112
+ tests/offline use.
113
+ - `fieldproof.ground`: Unicode-aware text normalization and exact/fuzzy
114
+ quote alignment (rapidfuzz) mapping evidence to page word bounding boxes.
115
+ - `fieldproof.verify`: value-vs-evidence consistency checks (numbers,
116
+ dates, strings, booleans), cross-field rules for invoices and receipts,
117
+ and the `verified` / `needs_review` / `unsupported` verdict engine.
118
+ - `fieldproof.server`: a FastAPI app for upload, extraction, review, and
119
+ JSON/CSV export.
120
+ - `fieldproof` CLI: `extract`, `verify`, `serve`.
121
+ - A TypeScript review UI (Vite, no framework) with grounded highlight
122
+ overlays, keyboard navigation, and a static demo mode for GitHub Pages.
123
+ - Synthetic sample documents (invoice, receipt, contract) and fixture
124
+ extractions with planted errors for the test suite and the Pages demo.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anton Soloviev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,394 @@
1
+ Metadata-Version: 2.5
2
+ Name: fieldproof
3
+ Version: 0.2.1
4
+ Summary: Document extraction that shows its work: every field linked to the exact words it came from.
5
+ Project-URL: Homepage, https://antonsoo.github.io/fieldproof/
6
+ Project-URL: Repository, https://github.com/antonsoo/fieldproof
7
+ Project-URL: Issues, https://github.com/antonsoo/fieldproof/issues
8
+ Author-email: Anton Soloviev <anton@praviel.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: document-ai,extraction,grounding,invoice-processing,llm,ocr,pdf,structured-output
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Text Processing :: Linguistic
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: anthropic>=0.77
21
+ Requires-Dist: fastapi>=0.115
22
+ Requires-Dist: pdfplumber>=0.11
23
+ Requires-Dist: pydantic>=2.10
24
+ Requires-Dist: pypdfium2>=4.30
25
+ Requires-Dist: python-multipart>=0.0.9
26
+ Requires-Dist: rapidfuzz>=3.9
27
+ Requires-Dist: typer>=0.15.4
28
+ Requires-Dist: uvicorn[standard]>=0.30
29
+ Provides-Extra: dev
30
+ Requires-Dist: httpx>=0.27; extra == 'dev'
31
+ Requires-Dist: mypy>=1.11; extra == 'dev'
32
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
33
+ Requires-Dist: pytest>=8.3; extra == 'dev'
34
+ Requires-Dist: reportlab>=4.2; extra == 'dev'
35
+ Requires-Dist: ruff>=0.6; extra == 'dev'
36
+ Provides-Extra: ocr
37
+ Requires-Dist: pillow>=10.4; extra == 'ocr'
38
+ Requires-Dist: pytesseract>=0.3.10; extra == 'ocr'
39
+ Description-Content-Type: text/markdown
40
+
41
+ # fieldproof
42
+
43
+ **Document extraction that shows its work: every field linked to the exact words it came from.**
44
+
45
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/antonsoo/fieldproof/blob/main/LICENSE)
46
+ [![Live demo](https://img.shields.io/badge/demo-antonsoo.github.io%2Ffieldproof-14524c)](https://antonsoo.github.io/fieldproof/)
47
+
48
+ LLMs are good at pulling structured data out of invoices, contracts, and forms.
49
+ In production the question is never "can it extract a total" - it's "can I trust
50
+ *this* total, on *this* document, without a human re-reading the whole page."
51
+ Most extraction pipelines give you a JSON blob and a confidence number pulled
52
+ out of nowhere. fieldproof instead makes the model cite a verbatim quote for
53
+ every field, locates that quote on the page with word-level bounding boxes,
54
+ checks that the quote actually supports the value it's attached to, runs
55
+ cross-field arithmetic and date-ordering checks, and gives a human a review UI
56
+ to confirm or fix whatever's left. Every field ends up `verified`,
57
+ `needs_review`, or `unsupported` - never a bare number with no way to check it.
58
+
59
+ ![The review UI catching a hallucinated PO number and a total that doesn't match its line items](https://raw.githubusercontent.com/antonsoo/fieldproof/main/docs/assets/hero-review.png)
60
+
61
+ <details>
62
+ <summary>Dark mode</summary>
63
+
64
+ ![The same review, in dark mode](https://raw.githubusercontent.com/antonsoo/fieldproof/main/docs/assets/review-dark.png)
65
+
66
+ </details>
67
+
68
+ ## Live demo
69
+
70
+ **[antonsoo.github.io/fieldproof](https://antonsoo.github.io/fieldproof/)** - three
71
+ synthetic sample documents (invoice, receipt, contract), grounded and
72
+ verified ahead of time by the real Python pipeline. It opens on the invoice
73
+ with its first flagged field selected; switch documents from the top bar, or
74
+ link straight to one (`#receipt`, `#contract`). The candidate extractions
75
+ are hand-written fixtures in the shape an LLM returns, with deliberately
76
+ planted errors - a hallucinated PO number, a total
77
+ that doesn't match its line items, and a misread date - so you can see exactly
78
+ what the verifier catches. No backend: the demo runs entirely on precomputed
79
+ JSON and static page images.
80
+
81
+ ## Quickstart
82
+
83
+ ```bash
84
+ pip install fieldproof
85
+ ```
86
+
87
+ The sample documents used below live in the repo (`examples/`), so clone it
88
+ to try them:
89
+
90
+ ```bash
91
+ git clone --depth 1 https://github.com/antonsoo/fieldproof && cd fieldproof
92
+ fieldproof extract examples/invoice.pdf --schema invoice --provider fixture \
93
+ --fixture examples/fixtures/invoice.json --out result.json
94
+ ```
95
+
96
+ `--provider fixture` replays a stored JSON extraction (no API key needed,
97
+ useful for CI/offline). To extract with Claude instead, set
98
+ `ANTHROPIC_API_KEY` and pass `--provider anthropic` (`--model` picks the
99
+ model; `--max-tokens` raises the output limit for a document whose
100
+ extraction is cut off at the default 16,000). To review the result in
101
+ the browser instead: `fieldproof serve`. The PyPI package includes the built
102
+ UI; from a source checkout, build it first (see [Development](#development)).
103
+
104
+ ## Features
105
+
106
+ - **Grounded extraction** - every field is `{value, evidence, page}`, not a
107
+ bare value. Built-in Pydantic templates for invoices, receipts, and
108
+ contract key terms; bring your own schema and it works the same way.
109
+ - **Provider-agnostic** - an `Extractor` protocol with an Anthropic
110
+ (Claude) implementation using structured outputs, and a fixture provider
111
+ for tests, CI, and offline demos.
112
+ - **Real grounding, not string search** - exact match first, rapidfuzz-based
113
+ fuzzy alignment as a fallback, tolerant of curly quotes, ligatures,
114
+ hyphenated line-wraps, and OCR noise. Exact matches are required to land
115
+ on whole word boundaries (a quote never matches mid-token), and a quote
116
+ that occurs more than once is disambiguated by locality rather than
117
+ silently taking the first hit. Maps back to word bounding boxes and
118
+ merges them into per-line highlight rectangles.
119
+ - **Verification, not just a confidence score** - numbers, dates, currency,
120
+ and strings are independently re-derived from the matched evidence and
121
+ compared to the claimed value; line items are checked against subtotal,
122
+ subtotal + tax against total, and due date against issue date.
123
+ - **A review UI that shows the reasoning** - flagged fields sort to the top;
124
+ click a field to jump to its evidence on the page; hover a highlight to
125
+ see which field it supports; currency fields display formatted (`312.50`,
126
+ `2,458.00`) while the underlying value and export stay machine numbers;
127
+ approve, edit, or reject; export approved values as JSON or CSV.
128
+ - **Optional OCR** - scanned PDFs fall back to Tesseract if it's installed;
129
+ documented as a degraded mode, not silently pretended to be as reliable as
130
+ a native text layer.
131
+
132
+ ## Usage
133
+
134
+ ### CLI
135
+
136
+ ```bash
137
+ fieldproof extract doc.pdf --schema invoice --provider anthropic --out result.json
138
+ fieldproof verify result.json doc.pdf # re-ground/re-verify an existing extraction
139
+ fieldproof serve --port 8000 # API + review UI
140
+ ```
141
+
142
+ `--provider anthropic` defaults to `claude-opus-5-5` (Claude Opus 5.5); pass
143
+ `--model claude-sonnet-5-5` or any other model id to override it.
144
+
145
+ Real output, captured from this repo's sample documents:
146
+
147
+ ![fieldproof extract and verify, real terminal output](https://raw.githubusercontent.com/antonsoo/fieldproof/main/docs/assets/cli-extract-verify.png)
148
+
149
+ ### As a library
150
+
151
+ ```python
152
+ from fieldproof.document import load_pdf
153
+ from fieldproof.schemas import Invoice
154
+ from fieldproof.extract import FixtureExtractor
155
+ from fieldproof.verify import verify
156
+
157
+ document = load_pdf("examples/invoice.pdf")
158
+ result = FixtureExtractor(fixture_path="examples/fixtures/invoice.json").extract(document, Invoice)
159
+ report = verify(result.data, document)
160
+
161
+ for field in report.fields:
162
+ if field.status != "verified":
163
+ print(field.path, field.status, field.reasons)
164
+ # po_number unsupported ["none of the evidence quotes (...) could be located in the document"]
165
+ # subtotal needs_review ['subtotal + tax = 2666.93 but total is 2600.00']
166
+ # tax needs_review ['subtotal + tax = 2666.93 but total is 2600.00']
167
+ # total needs_review ['value 2600 does not match 2666.93 parsed from the evidence', ...]
168
+ ```
169
+
170
+ ### Bring your own schema
171
+
172
+ Any Pydantic model built from `Evidenced[T]` leaves works - `fieldproof.ground`
173
+ and `fieldproof.verify` walk it generically (`iter_evidenced_fields`), they
174
+ never reference `Invoice`/`Receipt`/`ContractKeyTerms` by name:
175
+
176
+ ```python
177
+ from pydantic import BaseModel
178
+ from fieldproof.schemas import Evidenced
179
+
180
+ class PurchaseOrder(BaseModel):
181
+ po_number: Evidenced[str]
182
+ approved: Evidenced[bool]
183
+ amount: Evidenced[float]
184
+ ```
185
+
186
+ Cross-field rules (line-item sums, date ordering) are schema-specific and
187
+ currently only implemented for the built-in Invoice/Receipt templates - see
188
+ [Limitations](#accuracy-and-limitations).
189
+
190
+ ### Bring your own extractor
191
+
192
+ `Extractor` is a structural protocol (`def extract(self, document, schema) ->
193
+ ExtractionResult`) - implement it against any provider and
194
+ `fieldproof.ground` / `fieldproof.verify` work unchanged, since they only
195
+ depend on the `Evidenced` shape, not on Anthropic.
196
+
197
+ ## How it works
198
+
199
+ ```mermaid
200
+ flowchart LR
201
+ PDF["PDF"] --> DOC["document<br/>words + bboxes + page images"]
202
+ DOC --> EXT["extract<br/>Anthropic / fixture provider"]
203
+ EXT -->|"schema instance:<br/>value + evidence quotes"| GRD["ground<br/>normalize + align quotes to words"]
204
+ DOC --> GRD
205
+ GRD --> VER["verify<br/>value-vs-evidence + cross-field rules"]
206
+ VER --> REP["verified / needs_review / unsupported"]
207
+ REP --> UI["review UI<br/>approve, edit, export"]
208
+ ```
209
+
210
+ **Trust is established in four steps**, and a field is only `verified` if all
211
+ four hold:
212
+
213
+ 1. **Quote.** The model must produce a verbatim substring for every value
214
+ (`fieldproof.extract.anthropic_provider` instructs this explicitly and
215
+ uses structured outputs so it's enforced by the schema, not just asked
216
+ nicely). No quote -> `unsupported` immediately; no need to even look at
217
+ the page.
218
+ 2. **Alignment.** `fieldproof.ground` normalizes both the quote and the
219
+ page text (NFKC, straight quotes/dashes, collapsed whitespace) and tries
220
+ an exact substring match first, falling back to
221
+ [rapidfuzz](https://github.com/rapidfuzz/RapidFuzz)'s partial-ratio
222
+ alignment (`fuzz.partial_ratio_alignment`) for the best-scoring substring
223
+ of the page. Below a 70/100 score, the quote is treated as not found; a
224
+ match under 92/100 is flagged as weak evidence even if it's found. A
225
+ match has to cover whole words - a quote like `"1"` can never match the
226
+ trailing digit of a street number like `"4821"`, though it may leave out
227
+ punctuation glued to a word (the comma in `"1,"`, the `$` in
228
+ `"$2,458.00"`). When the best fuzzy window cuts a word, the quote is
229
+ scored against the whole words instead, so `"wind"` is not found in
230
+ `"Northwind"` and `"458.00"` is only a weak match for `"$2,458.00"`.
231
+ When a quote genuinely occurs more than once,
232
+ `fieldproof.verify.engine` disambiguates it by preferring whichever
233
+ occurrence is on the same row as another field from the same object
234
+ that's already been grounded (e.g. a line item's `quantity` next to its
235
+ already-grounded `description`); with nothing nearby to disambiguate
236
+ against, the field becomes `needs_review` with an "ambiguous, appears N
237
+ times" reason rather than silently guessing. The matched span is mapped
238
+ back through an index map to the exact words it covers (via each word's
239
+ character offset into the page's flattened text), and those words'
240
+ bounding boxes are merged into per-line highlight rectangles.
241
+ 3. **Value check.** The claimed value is independently re-derived from the
242
+ *matched* evidence text - not trusted just because a quote was found
243
+ nearby - and compared: numbers are parsed with currency/thousands-
244
+ separator handling and checked against every plain number in the
245
+ evidence, not just the last one (evidence for a row-level field is often
246
+ the whole row, e.g. a quantity of `1` is checked against `"Fuel
247
+ surcharge 1 210.50 210.50"`), excluding percentages so `"Tax (8.5%)
248
+ $208.93"` can't be misread as `8.5`; dates are parsed from either
249
+ ISO-8601 or a handful of common formats and compared as calendar dates,
250
+ and a numeric date whose first two parts are both 12 or under
251
+ (`03/04/2026`) is read in whichever order another date on the same
252
+ document settles (`03/14/2026` means month first) - with no such date it
253
+ goes to review rather than being verified under a guessed convention;
254
+ strings use fuzzy partial-ratio (a short value inside a longer quote
255
+ should still match), except that every run of digits in the value must
256
+ be in the evidence as written - `NW-20260215` is 96% similar to
257
+ `NW-20260214` and a different invoice; booleans look for whole words like
258
+ yes/no/not/confirmed/denied (so "notice" isn't a "no"). Any mismatch ->
259
+ `needs_review`.
260
+ 4. **Cross-field rules.** For invoices and receipts: line items must sum to
261
+ the subtotal, subtotal + tax must equal the total (both within a $0.02
262
+ tolerance), and the due date must not precede the issue date. A failed
263
+ rule marks every field it involves as `needs_review` and records why.
264
+
265
+ ### Grounding quality, checked against ground truth
266
+
267
+ `tests/test_ground.py` and `tests/test_e2e.py` don't just assert "no
268
+ exception" - they assert exact match scores and exact reasons against
269
+ documents with known content: an exact quote must score 100, a quote with a
270
+ dropped colon and a curly apostrophe must score ≥85 but not be flagged
271
+ `is_exact`, a quote spanning a hyphenated line-wrap must still ground at
272
+ ≥80, a quote that's genuinely absent must return no match at all rather
273
+ than a low-quality one, and - the concrete regression this repo shipped
274
+ with - a bare `"1"` on `examples/invoice.pdf` must ground to one of its two
275
+ line-item quantities, never to the trailing digit of the "4821" street
276
+ address, and must resolve to the *correct* line item by row locality when
277
+ both are plausible. `tests/test_e2e.py` runs the full pipeline against the
278
+ checked-in sample documents and pins down exactly which field each planted
279
+ error is expected to surface as - a regression that stops catching the
280
+ hallucinated PO number or the misread date fails a test, not just a manual
281
+ look at the demo.
282
+
283
+ ### Performance
284
+
285
+ Measured on this machine (14 vCPU, 48 GB RAM, WSL2 Linux), 200-iteration
286
+ average, on `examples/invoice.pdf` (25 leaf fields across 4 line items):
287
+
288
+ | Stage | Time |
289
+ |---|---|
290
+ | PDF text-layer load (pdfplumber) | 22.6 ms |
291
+ | Grounding + verification, all 25 fields | 4.3 ms |
292
+
293
+ Extraction time is dominated by the provider's network round trip, not
294
+ anything in this repo.
295
+
296
+ ## Accuracy and limitations
297
+
298
+ - **OCR is a degraded mode, not equivalent to a text layer.** Scanned PDFs
299
+ are supported only if the optional `ocr` extra (`pytesseract` + a system
300
+ Tesseract install) is present; grounding still fuzzy-matches against
301
+ whatever text Tesseract produced, but OCR accuracy drops sharply on
302
+ skewed scans, low contrast, or unusual fonts, and word boxes are
303
+ per-word pixel boxes with no sub-word offsets. Treat an OCR'd document's
304
+ results as "Tesseract thinks this is what's there," not ground truth.
305
+ - **Tables aren't structurally parsed.** Line items are extracted by the
306
+ LLM reading the page text in reading order, not by detecting table
307
+ cells/columns - a table with an unusual layout (merged cells, multi-line
308
+ cells, columns that don't read top-to-bottom-then-left-to-right) can
309
+ confuse the model's reading of which number belongs to which row, even
310
+ though each individual value's grounding is still checked independently.
311
+ - **No handwriting support.** Neither the text-layer path nor the OCR
312
+ fallback is designed for handwritten text.
313
+ - **Cross-field rules are schema-specific.** They're implemented for the
314
+ built-in Invoice and Receipt templates only
315
+ (`fieldproof.verify.cross_field`); a custom schema gets grounding and
316
+ value-vs-evidence checks but no arithmetic/date-ordering rules unless you
317
+ add your own.
318
+ - **String matching is fuzzy by design**, which means a sufficiently short
319
+ or generic value can occasionally find a spurious match inside unrelated
320
+ evidence text. The 92/100 "strong match" threshold and the independent
321
+ value check are there to catch most of this, but neither is a proof.
322
+ - **Ambiguous quotes are resolved by row locality, not proven correct.**
323
+ When a short quote occurs more than once, fieldproof prefers the
324
+ occurrence nearest another already-grounded field from the same row
325
+ (see [How it works](#how-it-works)) rather than flagging every such
326
+ field `needs_review` - a reasonable heuristic, not a guarantee. Two
327
+ identical amounts in the same row (a line item where `unit_price` and
328
+ `amount` happen to be equal) can still ground to either one; the *value*
329
+ check still passes either way, but the highlighted box may point at the
330
+ wrong column of an otherwise-correct row.
331
+ - **The Anthropic adapter is tested against the real SDK, not a live
332
+ model** - there's no API key configured in this repo's CI. The tests run
333
+ the `anthropic` SDK over a mocked HTTP transport that answers in the
334
+ Messages API's wire format, so the request (the schema as structured-output
335
+ JSON Schema, the prompt, `max_tokens`) and the handling of replies (a
336
+ complete one, one cut off at `max_tokens`, a refusal, an API error, a
337
+ missing key) are the real thing. What no such test can check is whether a
338
+ model follows the evidence-quoting instructions in the system prompt; that
339
+ is what grounding and verification are for.
340
+
341
+ ## Architecture
342
+
343
+ ```
344
+ src/fieldproof/
345
+ document/ PDF loading (pdfplumber), page rendering (pypdfium2), optional OCR (pytesseract)
346
+ schemas/ Evidenced[T], the generic field walker, Invoice/Receipt/ContractKeyTerms
347
+ extract/ Extractor protocol, Anthropic provider, fixture provider
348
+ ground/ text normalization, exact/fuzzy quote alignment, bbox merging
349
+ verify/ value-vs-evidence checks, cross-field rules, the verdict engine
350
+ server/ FastAPI app (upload, extract, review, export)
351
+ cli.py extract / verify / serve
352
+ web/ Vite + TypeScript review UI (no framework)
353
+ scripts/ synthetic sample-document generator, static-demo data precomputation
354
+ examples/ synthetic sample PDFs + fixture extractions (planted errors, for the demo/tests)
355
+ ```
356
+
357
+ Python ≥3.11, [uv](https://docs.astral.sh/uv/) for dependency management,
358
+ src layout, fully typed (`mypy --strict`-adjacent; see `pyproject.toml`).
359
+
360
+ ## Development
361
+
362
+ ```bash
363
+ uv sync --extra dev --extra ocr
364
+ uv run pytest
365
+ uv run ruff check src tests
366
+ uv run mypy src
367
+
368
+ cd web && npm ci && npm run typecheck && npm run lint && npm run build
369
+ ```
370
+
371
+ `fieldproof serve` from a checkout serves `web/dist`. For a release,
372
+ `uv run python scripts/bundle_ui.py && uv build` builds the UI into the
373
+ package first, so the wheel carries it.
374
+
375
+ Regenerate the sample documents and demo data after changing them - the
376
+ output (`web/public/demo-data/`) is committed, since the Pages deploy is a
377
+ plain `npm ci && npm run build:demo` with no Python step:
378
+
379
+ ```bash
380
+ uv run python scripts/generate_samples.py
381
+ uv run python scripts/build_demo_data.py # writes + commit web/public/demo-data/
382
+ ```
383
+
384
+ ## Contributing
385
+
386
+ See [CONTRIBUTING.md](https://github.com/antonsoo/fieldproof/blob/main/CONTRIBUTING.md). Issues and pull requests welcome.
387
+
388
+ ## License
389
+
390
+ [MIT](https://github.com/antonsoo/fieldproof/blob/main/LICENSE) © 2026 Anton Soloviev
391
+
392
+ ---
393
+
394
+ <sub>Part of [Officina](https://antonsoo.github.io/officina/), a set of small open-source tools by [Anton Soloviev](https://github.com/antonsoo).</sub>