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.
fieldproof/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """fieldproof: document extraction that shows its work.
2
+
3
+ Every extracted field is linked to the exact words it came from, so a human
4
+ reviewer (or a downstream system) can tell a verified value from a
5
+ hallucinated one before it reaches a database.
6
+ """
7
+
8
+ __version__ = "0.2.3"
fieldproof/cli.py ADDED
@@ -0,0 +1,199 @@
1
+ """fieldproof CLI: extract, verify, serve."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import NoReturn
9
+
10
+ import typer
11
+ import uvicorn
12
+
13
+ from fieldproof import __version__
14
+ from fieldproof.document.loader import EmptyDocumentError, load_pdf
15
+ from fieldproof.document.model import Document
16
+ from fieldproof.extract.anthropic_provider import DEFAULT_MODEL, AnthropicExtractor
17
+ from fieldproof.extract.base import ExtractionError, ExtractionResult, read_extraction_json
18
+ from fieldproof.extract.fixture_provider import FixtureExtractor
19
+ from fieldproof.schemas import BUILTIN_SCHEMAS, resolve_schema
20
+ from fieldproof.verify.engine import verify as run_verify
21
+
22
+ app = typer.Typer(
23
+ name="fieldproof",
24
+ help="Document extraction that shows its work: every field linked to the words it came from.",
25
+ no_args_is_help=True,
26
+ )
27
+
28
+
29
+ def _print_version(value: bool) -> None:
30
+ if value:
31
+ typer.echo(f"fieldproof {__version__}")
32
+ raise typer.Exit
33
+
34
+
35
+ def _text_streams() -> None:
36
+ """Make stdout and stderr able to carry any text.
37
+
38
+ A pipe or a file gets UTF-8: before 3.15, Python on Windows gives it the system's code
39
+ page, where a file name outside it raised ``UnicodeEncodeError``. A terminal keeps its
40
+ own encoding and shows a character it cannot encode as an escape.
41
+ """
42
+ for stream in (sys.stdout, sys.stderr):
43
+ reconfigure = getattr(stream, "reconfigure", None)
44
+ if reconfigure is None: # replaced by something that isn't a text file
45
+ continue
46
+ if stream.isatty():
47
+ reconfigure(errors="backslashreplace")
48
+ else:
49
+ reconfigure(encoding="utf-8")
50
+
51
+
52
+ @app.callback()
53
+ def _options(
54
+ version: bool = typer.Option(
55
+ False, "--version", callback=_print_version, is_eager=True, help="show the version and exit"
56
+ ),
57
+ ) -> None:
58
+ _text_streams()
59
+
60
+
61
+ def _fail(message: str, code: int = 1) -> NoReturn:
62
+ typer.echo(f"error: {message}", err=True)
63
+ raise typer.Exit(code=code)
64
+
65
+
66
+ def _load_document(path: Path) -> Document:
67
+ """The PDF, or a one-line error: a file that isn't a PDF is the caller's to
68
+ fix, and pdfplumber's own exception for it is a page of traceback."""
69
+ try:
70
+ return load_pdf(path)
71
+ except EmptyDocumentError as exc:
72
+ _fail(str(exc))
73
+ except Exception as exc: # pdfplumber raises a variety of parse errors
74
+ _fail(f"could not read {path} as a PDF: {exc}")
75
+
76
+
77
+ @app.command()
78
+ def extract(
79
+ document: Path = typer.Argument(..., exists=True, readable=True, help="PDF to extract from"),
80
+ schema: str = typer.Option(
81
+ "invoice", "--schema", help=f"one of: {', '.join(sorted(BUILTIN_SCHEMAS))}"
82
+ ),
83
+ provider: str = typer.Option(
84
+ "fixture", "--provider", help="anthropic (needs ANTHROPIC_API_KEY) or fixture"
85
+ ),
86
+ fixture: Path | None = typer.Option(
87
+ None, "--fixture", help="stored JSON extraction to replay (required for --provider fixture)"
88
+ ),
89
+ model: str = typer.Option(
90
+ DEFAULT_MODEL, "--model", help="Anthropic model id (only used with --provider anthropic)"
91
+ ),
92
+ max_tokens: int = typer.Option(
93
+ 16000,
94
+ "--max-tokens",
95
+ min=1,
96
+ help="most output tokens Claude may use for the extraction (--provider anthropic)",
97
+ ),
98
+ out: Path = typer.Option(..., "--out", help="where to write the verified result JSON"),
99
+ ) -> None:
100
+ """Extract a schema from DOCUMENT, ground and verify it, write the result to --out."""
101
+ schema_cls = BUILTIN_SCHEMAS.get(schema)
102
+ if schema_cls is None:
103
+ typer.echo(
104
+ f"error: unknown schema {schema!r}; choose one of {sorted(BUILTIN_SCHEMAS)}", err=True
105
+ )
106
+ raise typer.Exit(code=2)
107
+
108
+ if provider not in ("fixture", "anthropic"):
109
+ _fail(f"unknown provider {provider!r}", code=2)
110
+ if provider == "fixture" and fixture is None:
111
+ _fail("--provider fixture requires --fixture <path>", code=2)
112
+
113
+ doc = _load_document(document)
114
+ try:
115
+ if fixture is not None and provider == "fixture":
116
+ result = FixtureExtractor(fixture_path=fixture).extract(doc, schema_cls)
117
+ else:
118
+ result = AnthropicExtractor(model=model, max_tokens=max_tokens).extract(doc, schema_cls)
119
+ except (ExtractionError, OSError) as exc:
120
+ _fail(str(exc))
121
+
122
+ report = run_verify(result.data, doc)
123
+ # Write the registry key ("invoice"), not result.schema_name (the class
124
+ # name, "Invoice") - so `fieldproof verify result.json doc.pdf` on our
125
+ # own output resolves the schema without needing resolve_schema's
126
+ # class-name fallback below.
127
+ payload = {**result.to_dict(), "schema": schema, "report": report.to_dict()}
128
+ out.write_text(json.dumps(payload, indent=2), encoding="utf-8")
129
+
130
+ counts = report.counts
131
+ typer.echo(
132
+ f"wrote {out} - {counts['verified']} verified, {counts['needs_review']} needs review, "
133
+ f"{counts['unsupported']} unsupported"
134
+ )
135
+
136
+
137
+ @app.command()
138
+ def verify(
139
+ result: Path = typer.Argument(..., exists=True, readable=True, help="extraction result JSON"),
140
+ document: Path = typer.Argument(
141
+ ..., exists=True, readable=True, help="the PDF it was extracted from"
142
+ ),
143
+ out: Path | None = typer.Option(
144
+ None, "--out", help="write the re-verified result here (default: overwrite RESULT)"
145
+ ),
146
+ ) -> None:
147
+ """Re-ground and re-verify an extraction JSON against DOCUMENT.
148
+
149
+ Useful for extractions produced by other tools: RESULT just needs a
150
+ `schema` name (one of fieldproof's built-ins) and a `data` object shaped
151
+ like that schema, with `{value, evidence, page}` at every leaf.
152
+ """
153
+ try:
154
+ raw = read_extraction_json(result.read_bytes(), result.name)
155
+ schema_name = raw.get("schema", "")
156
+ schema_cls = resolve_schema(schema_name)
157
+ if schema_cls is None:
158
+ _fail(
159
+ f'{result.name}\'s "schema" is {schema_name!r}; must name one of '
160
+ f"{sorted(BUILTIN_SCHEMAS)} (by registry key or class name) "
161
+ "to re-verify from the CLI",
162
+ code=2,
163
+ )
164
+ extraction = ExtractionResult.from_dict(raw, schema_cls, source=result.name)
165
+ except ExtractionError as exc:
166
+ _fail(str(exc), code=2)
167
+ doc = _load_document(document)
168
+ report = run_verify(extraction.data, doc)
169
+
170
+ destination = out or result
171
+ destination.write_text(
172
+ json.dumps({**extraction.to_dict(), "report": report.to_dict()}, indent=2), encoding="utf-8"
173
+ )
174
+
175
+ counts = report.counts
176
+ typer.echo(
177
+ f"wrote {destination} - {counts['verified']} verified, "
178
+ f"{counts['needs_review']} needs review, {counts['unsupported']} unsupported"
179
+ )
180
+
181
+
182
+ @app.command()
183
+ def serve(
184
+ host: str = typer.Option("127.0.0.1", "--host"),
185
+ port: int = typer.Option(8000, "--port"),
186
+ reload: bool = typer.Option(
187
+ False, "--reload", help="auto-reload on source changes (development)"
188
+ ),
189
+ ) -> None:
190
+ """Run the review server (API + UI) at http://HOST:PORT."""
191
+ uvicorn.run("fieldproof.server.app:app", host=host, port=port, reload=reload)
192
+
193
+
194
+ def main() -> None:
195
+ app()
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()
@@ -0,0 +1,14 @@
1
+ from fieldproof.document.loader import EmptyDocumentError, load_pdf
2
+ from fieldproof.document.model import BBox, Document, Page, Word
3
+ from fieldproof.document.render import page_pixel_size, render_page_png
4
+
5
+ __all__ = [
6
+ "BBox",
7
+ "Document",
8
+ "EmptyDocumentError",
9
+ "Page",
10
+ "Word",
11
+ "load_pdf",
12
+ "page_pixel_size",
13
+ "render_page_png",
14
+ ]
@@ -0,0 +1,86 @@
1
+ """Load PDFs with a text layer into the `Document` model.
2
+
3
+ Uses pdfplumber for word-level extraction (text + bounding boxes) because its
4
+ `extract_words` gives us exactly the granularity grounding needs: individual
5
+ words with boxes, in reading order. pypdfium2 is used separately for page
6
+ rendering (see `render.py`) since pdfplumber's rendering path is slower and
7
+ we only need pixels there, not text.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import io
13
+ from pathlib import Path
14
+
15
+ import pdfplumber
16
+
17
+ from fieldproof.document.model import BBox, Document, Page, Word
18
+
19
+
20
+ class EmptyDocumentError(ValueError):
21
+ """Raised when a PDF has no extractable text on any page."""
22
+
23
+
24
+ def load_pdf(source: str | Path | bytes, *, label: str | None = None) -> Document:
25
+ """Load a PDF that has a text layer (not a scanned image).
26
+
27
+ `source` may be a path or raw PDF bytes. Raises `EmptyDocumentError` if
28
+ no page yields any words - that's the signal callers should use to fall
29
+ back to OCR (see `fieldproof.document.ocr`).
30
+ """
31
+ if isinstance(source, bytes):
32
+ stream: str | Path | io.BytesIO = io.BytesIO(source)
33
+ name = label or "<bytes>"
34
+ else:
35
+ stream = source
36
+ name = label or str(source)
37
+
38
+ pages: list[Page] = []
39
+ with pdfplumber.open(stream) as pdf:
40
+ for page_number, page in enumerate(pdf.pages, start=1):
41
+ pages.append(_load_page(page, page_number))
42
+
43
+ if not any(p.words for p in pages):
44
+ raise EmptyDocumentError(
45
+ f"{name!r} has no extractable text on any page - "
46
+ "it may be a scanned image; see fieldproof.document.ocr"
47
+ )
48
+ return Document(source=name, pages=pages)
49
+
50
+
51
+ def _load_page(page: pdfplumber.page.Page, page_number: int) -> Page:
52
+ raw_words = page.extract_words(
53
+ keep_blank_chars=False,
54
+ use_text_flow=False,
55
+ extra_attrs=["size"],
56
+ )
57
+
58
+ text_parts: list[str] = []
59
+ words: list[Word] = []
60
+ cursor = 0
61
+ for raw in raw_words:
62
+ token = raw["text"]
63
+ if not token:
64
+ continue
65
+ if text_parts:
66
+ text_parts.append(" ")
67
+ cursor += 1
68
+ start = cursor
69
+ text_parts.append(token)
70
+ cursor += len(token)
71
+ words.append(
72
+ Word(
73
+ text=token,
74
+ bbox=BBox(x0=raw["x0"], top=raw["top"], x1=raw["x1"], bottom=raw["bottom"]),
75
+ start=start,
76
+ end=cursor,
77
+ )
78
+ )
79
+
80
+ return Page(
81
+ number=page_number,
82
+ width=float(page.width),
83
+ height=float(page.height),
84
+ text="".join(text_parts),
85
+ words=words,
86
+ )
@@ -0,0 +1,99 @@
1
+ """Core document model: pages, words, and character-offset text.
2
+
3
+ Every downstream stage (grounding, verification, the review UI) refers back
4
+ to a document by page number and character offset, so this is the one place
5
+ that owns the coordinate system. A `Document` is deliberately dumb data: no
6
+ provider calls, no rendering, just what was actually on the page.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class BBox:
16
+ """A rectangle in PDF points, origin top-left, y growing downward.
17
+
18
+ This matches pdfplumber's convention (not the PDF spec's bottom-left
19
+ origin) so bounding boxes can be drawn directly onto a top-left-origin
20
+ page image without a flip.
21
+ """
22
+
23
+ x0: float
24
+ top: float
25
+ x1: float
26
+ bottom: float
27
+
28
+ def union(self, other: BBox) -> BBox:
29
+ return BBox(
30
+ x0=min(self.x0, other.x0),
31
+ top=min(self.top, other.top),
32
+ x1=max(self.x1, other.x1),
33
+ bottom=max(self.bottom, other.bottom),
34
+ )
35
+
36
+ @property
37
+ def width(self) -> float:
38
+ return self.x1 - self.x0
39
+
40
+ @property
41
+ def height(self) -> float:
42
+ return self.bottom - self.top
43
+
44
+ def to_dict(self) -> dict[str, float]:
45
+ return {"x0": self.x0, "top": self.top, "x1": self.x1, "bottom": self.bottom}
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class Word:
50
+ """A single word on a page, with its bounding box and offset into the
51
+ page's flattened text (`Page.text`)."""
52
+
53
+ text: str
54
+ bbox: BBox
55
+ start: int
56
+ end: int
57
+
58
+
59
+ @dataclass(frozen=True, slots=True)
60
+ class Page:
61
+ """One page of a document.
62
+
63
+ `text` is the words joined by single spaces, in reading order; `words[i]`
64
+ corresponds to the exact span `text[words[i].start:words[i].end]`. This
65
+ is the text that grounding aligns quotes against.
66
+ """
67
+
68
+ number: int
69
+ width: float
70
+ height: float
71
+ text: str
72
+ words: list[Word] = field(default_factory=list)
73
+
74
+
75
+ @dataclass(slots=True)
76
+ class Document:
77
+ """A loaded document: one or more pages with extracted text layers.
78
+
79
+ `source` is a human-readable label for provenance (filename), not a
80
+ filesystem path guarantee - callers may load from bytes.
81
+ """
82
+
83
+ source: str
84
+ pages: list[Page] = field(default_factory=list)
85
+
86
+ @property
87
+ def page_count(self) -> int:
88
+ return len(self.pages)
89
+
90
+ def page(self, number: int) -> Page:
91
+ for p in self.pages:
92
+ if p.number == number:
93
+ return p
94
+ raise IndexError(f"document {self.source!r} has no page {number}")
95
+
96
+ def full_text(self) -> str:
97
+ """All pages concatenated, one page per line - used only for
98
+ provider prompts, never for grounding (which is per-page)."""
99
+ return "\n".join(p.text for p in self.pages)
@@ -0,0 +1,115 @@
1
+ """Optional OCR fallback for scanned (image-only) documents.
2
+
3
+ This module is only reached when `load_pdf` raises `EmptyDocumentError` -
4
+ i.e. the PDF has no text layer at all. It requires the `pytesseract` Python
5
+ package *and* the Tesseract binary on PATH; neither is a hard dependency of
6
+ fieldproof (see the `ocr` extra in pyproject.toml). Import this module
7
+ lazily and call `is_available()` before using it - do not add it to the
8
+ default install, since Tesseract is a system package with its own install
9
+ story per OS and pulling it in unconditionally would break `pip install
10
+ fieldproof` on machines without it.
11
+
12
+ OCR word boxes are visibly lower-precision than a native text layer:
13
+ Tesseract gives per-word pixel boxes at whatever DPI you render at, with no
14
+ sub-word offsets, and accuracy drops sharply on skewed scans, low contrast,
15
+ or unusual fonts. Treat OCR'd documents as a degraded mode - grounding still
16
+ works (it fuzzy-matches against whatever text OCR produced) but confidence
17
+ should be read as "OCR thinks this is what's there," not ground truth.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import importlib.util
23
+ import io
24
+ from pathlib import Path
25
+
26
+ from fieldproof.document.model import BBox, Document, Page, Word
27
+ from fieldproof.document.render import render_page_png
28
+
29
+ #: Checked without importing either package, so `import fieldproof.document.ocr`
30
+ #: never fails on a machine that only has fieldproof's required dependencies.
31
+ _HAS_OCR_PACKAGES = (
32
+ importlib.util.find_spec("pytesseract") is not None
33
+ and importlib.util.find_spec("PIL") is not None
34
+ )
35
+
36
+
37
+ def is_available() -> bool:
38
+ """True only if both the `pytesseract` package is importable and the
39
+ Tesseract binary itself can be found on PATH."""
40
+ if not _HAS_OCR_PACKAGES:
41
+ return False
42
+ import pytesseract
43
+
44
+ try:
45
+ pytesseract.get_tesseract_version()
46
+ except Exception:
47
+ return False
48
+ return True
49
+
50
+
51
+ def load_scanned_pdf(
52
+ source: str | Path | bytes, page_count: int, *, label: str | None = None
53
+ ) -> Document:
54
+ """OCR every page of a PDF that has no text layer.
55
+
56
+ Raises `RuntimeError` if OCR isn't available - callers should check
57
+ `is_available()` first and give the user a clear message rather than
58
+ let this raise from deep in a pipeline.
59
+ """
60
+ if not is_available():
61
+ raise RuntimeError(
62
+ "OCR is not available: install the 'ocr' extra (pytesseract, Pillow) "
63
+ "and the Tesseract binary (e.g. `apt install tesseract-ocr`)."
64
+ )
65
+
66
+ import pytesseract
67
+ from PIL import Image
68
+
69
+ pages: list[Page] = []
70
+ for page_number in range(1, page_count + 1):
71
+ png_bytes = render_page_png(source, page_number, scale=2.0)
72
+ image = Image.open(io.BytesIO(png_bytes))
73
+ data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
74
+ pages.append(_page_from_ocr(page_number, image.width, image.height, data))
75
+
76
+ return Document(
77
+ source=label or (source if isinstance(source, str) else "<scanned>"), pages=pages
78
+ )
79
+
80
+
81
+ def _page_from_ocr(page_number: int, width_px: int, height_px: int, data: dict) -> Page:
82
+ # OCR renders at scale=2.0 (144 DPI); convert pixel boxes back to PDF
83
+ # points (72 DPI) so they share the coordinate system with native pages.
84
+ scale = 2.0
85
+ text_parts: list[str] = []
86
+ words: list[Word] = []
87
+ cursor = 0
88
+ n = len(data["text"])
89
+ for i in range(n):
90
+ token = data["text"][i].strip()
91
+ if not token:
92
+ continue
93
+ x, y, w, h = data["left"][i], data["top"][i], data["width"][i], data["height"][i]
94
+ if text_parts:
95
+ text_parts.append(" ")
96
+ cursor += 1
97
+ start = cursor
98
+ text_parts.append(token)
99
+ cursor += len(token)
100
+ words.append(
101
+ Word(
102
+ text=token,
103
+ bbox=BBox(x0=x / scale, top=y / scale, x1=(x + w) / scale, bottom=(y + h) / scale),
104
+ start=start,
105
+ end=cursor,
106
+ )
107
+ )
108
+
109
+ return Page(
110
+ number=page_number,
111
+ width=width_px / scale,
112
+ height=height_px / scale,
113
+ text="".join(text_parts),
114
+ words=words,
115
+ )
@@ -0,0 +1,47 @@
1
+ """Render PDF pages to PNG images for the review UI.
2
+
3
+ Uses pypdfium2 (a Python binding to PDFium, the rendering engine behind
4
+ Chrome's PDF viewer) rather than pdfplumber's rendering path, which shells
5
+ out to Poppler's `pdftoppm` and is both slower and an extra system
6
+ dependency. pypdfium2 ships prebuilt wheels with the renderer statically
7
+ linked, so `pip install` is enough - no system PDF tooling required.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import io
13
+ from pathlib import Path
14
+
15
+ import pypdfium2 as pdfium
16
+
17
+
18
+ def render_page_png(source: str | Path | bytes, page_number: int, *, scale: float = 2.0) -> bytes:
19
+ """Render one page (1-indexed) to PNG bytes at `scale` * 72 DPI.
20
+
21
+ `scale=2.0` (the default) gives 144 DPI, which is sharp enough to read
22
+ small print on screen without producing huge files.
23
+ """
24
+ pdf = pdfium.PdfDocument(source)
25
+ try:
26
+ page = pdf[page_number - 1]
27
+ bitmap = page.render(scale=scale)
28
+ pil_image = bitmap.to_pil()
29
+ buf = io.BytesIO()
30
+ pil_image.save(buf, format="PNG")
31
+ return buf.getvalue()
32
+ finally:
33
+ pdf.close()
34
+
35
+
36
+ def page_pixel_size(
37
+ source: str | Path | bytes, page_number: int, *, scale: float = 2.0
38
+ ) -> tuple[int, int]:
39
+ """Return the (width, height) in pixels the rendered PNG will have,
40
+ without re-rendering - used by the UI to map PDF points to pixels."""
41
+ pdf = pdfium.PdfDocument(source)
42
+ try:
43
+ page = pdf[page_number - 1]
44
+ width_pt, height_pt = page.get_size()
45
+ return round(width_pt * scale), round(height_pt * scale)
46
+ finally:
47
+ pdf.close()
@@ -0,0 +1,12 @@
1
+ from fieldproof.extract.anthropic_provider import DEFAULT_MODEL, AnthropicExtractor
2
+ from fieldproof.extract.base import ExtractionError, ExtractionResult, Extractor
3
+ from fieldproof.extract.fixture_provider import FixtureExtractor
4
+
5
+ __all__ = [
6
+ "DEFAULT_MODEL",
7
+ "AnthropicExtractor",
8
+ "ExtractionError",
9
+ "ExtractionResult",
10
+ "Extractor",
11
+ "FixtureExtractor",
12
+ ]