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.
- fieldproof/__init__.py +8 -0
- fieldproof/cli.py +181 -0
- fieldproof/document/__init__.py +14 -0
- fieldproof/document/loader.py +86 -0
- fieldproof/document/model.py +99 -0
- fieldproof/document/ocr.py +115 -0
- fieldproof/document/render.py +47 -0
- fieldproof/extract/__init__.py +12 -0
- fieldproof/extract/anthropic_provider.py +141 -0
- fieldproof/extract/base.py +98 -0
- fieldproof/extract/fixture_provider.py +46 -0
- fieldproof/ground/__init__.py +26 -0
- fieldproof/ground/align.py +289 -0
- fieldproof/ground/normalize.py +80 -0
- fieldproof/schemas/__init__.py +48 -0
- fieldproof/schemas/base.py +52 -0
- fieldproof/schemas/contract.py +28 -0
- fieldproof/schemas/invoice.py +37 -0
- fieldproof/schemas/receipt.py +25 -0
- fieldproof/server/__init__.py +3 -0
- fieldproof/server/app.py +276 -0
- fieldproof/server/static/assets/index-BLATbujI.js +144 -0
- fieldproof/server/static/assets/index-Bo892MpF.css +1 -0
- fieldproof/server/static/index.html +50 -0
- fieldproof/server/store.py +57 -0
- fieldproof/verify/__init__.py +29 -0
- fieldproof/verify/cross_field.py +118 -0
- fieldproof/verify/engine.py +265 -0
- fieldproof/verify/value_checks.py +321 -0
- fieldproof-0.2.1.dist-info/METADATA +394 -0
- fieldproof-0.2.1.dist-info/RECORD +34 -0
- fieldproof-0.2.1.dist-info/WHEEL +4 -0
- fieldproof-0.2.1.dist-info/entry_points.txt +2 -0
- fieldproof-0.2.1.dist-info/licenses/LICENSE +21 -0
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.1"
|
fieldproof/cli.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""fieldproof CLI: extract, verify, serve."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import NoReturn
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
import uvicorn
|
|
11
|
+
|
|
12
|
+
from fieldproof import __version__
|
|
13
|
+
from fieldproof.document.loader import EmptyDocumentError, load_pdf
|
|
14
|
+
from fieldproof.document.model import Document
|
|
15
|
+
from fieldproof.extract.anthropic_provider import DEFAULT_MODEL, AnthropicExtractor
|
|
16
|
+
from fieldproof.extract.base import ExtractionError, ExtractionResult, read_extraction_json
|
|
17
|
+
from fieldproof.extract.fixture_provider import FixtureExtractor
|
|
18
|
+
from fieldproof.schemas import BUILTIN_SCHEMAS, resolve_schema
|
|
19
|
+
from fieldproof.verify.engine import verify as run_verify
|
|
20
|
+
|
|
21
|
+
app = typer.Typer(
|
|
22
|
+
name="fieldproof",
|
|
23
|
+
help="Document extraction that shows its work: every field linked to the words it came from.",
|
|
24
|
+
no_args_is_help=True,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _print_version(value: bool) -> None:
|
|
29
|
+
if value:
|
|
30
|
+
typer.echo(f"fieldproof {__version__}")
|
|
31
|
+
raise typer.Exit
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@app.callback()
|
|
35
|
+
def _options(
|
|
36
|
+
version: bool = typer.Option(
|
|
37
|
+
False, "--version", callback=_print_version, is_eager=True, help="show the version and exit"
|
|
38
|
+
),
|
|
39
|
+
) -> None:
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _fail(message: str, code: int = 1) -> NoReturn:
|
|
44
|
+
typer.echo(f"error: {message}", err=True)
|
|
45
|
+
raise typer.Exit(code=code)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _load_document(path: Path) -> Document:
|
|
49
|
+
"""The PDF, or a one-line error: a file that isn't a PDF is the caller's to
|
|
50
|
+
fix, and pdfplumber's own exception for it is a page of traceback."""
|
|
51
|
+
try:
|
|
52
|
+
return load_pdf(path)
|
|
53
|
+
except EmptyDocumentError as exc:
|
|
54
|
+
_fail(str(exc))
|
|
55
|
+
except Exception as exc: # pdfplumber raises a variety of parse errors
|
|
56
|
+
_fail(f"could not read {path} as a PDF: {exc}")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@app.command()
|
|
60
|
+
def extract(
|
|
61
|
+
document: Path = typer.Argument(..., exists=True, readable=True, help="PDF to extract from"),
|
|
62
|
+
schema: str = typer.Option(
|
|
63
|
+
"invoice", "--schema", help=f"one of: {', '.join(sorted(BUILTIN_SCHEMAS))}"
|
|
64
|
+
),
|
|
65
|
+
provider: str = typer.Option(
|
|
66
|
+
"fixture", "--provider", help="anthropic (needs ANTHROPIC_API_KEY) or fixture"
|
|
67
|
+
),
|
|
68
|
+
fixture: Path | None = typer.Option(
|
|
69
|
+
None, "--fixture", help="stored JSON extraction to replay (required for --provider fixture)"
|
|
70
|
+
),
|
|
71
|
+
model: str = typer.Option(
|
|
72
|
+
DEFAULT_MODEL, "--model", help="Anthropic model id (only used with --provider anthropic)"
|
|
73
|
+
),
|
|
74
|
+
max_tokens: int = typer.Option(
|
|
75
|
+
16000,
|
|
76
|
+
"--max-tokens",
|
|
77
|
+
min=1,
|
|
78
|
+
help="most output tokens Claude may use for the extraction (--provider anthropic)",
|
|
79
|
+
),
|
|
80
|
+
out: Path = typer.Option(..., "--out", help="where to write the verified result JSON"),
|
|
81
|
+
) -> None:
|
|
82
|
+
"""Extract a schema from DOCUMENT, ground and verify it, write the result to --out."""
|
|
83
|
+
schema_cls = BUILTIN_SCHEMAS.get(schema)
|
|
84
|
+
if schema_cls is None:
|
|
85
|
+
typer.echo(
|
|
86
|
+
f"error: unknown schema {schema!r}; choose one of {sorted(BUILTIN_SCHEMAS)}", err=True
|
|
87
|
+
)
|
|
88
|
+
raise typer.Exit(code=2)
|
|
89
|
+
|
|
90
|
+
if provider not in ("fixture", "anthropic"):
|
|
91
|
+
_fail(f"unknown provider {provider!r}", code=2)
|
|
92
|
+
if provider == "fixture" and fixture is None:
|
|
93
|
+
_fail("--provider fixture requires --fixture <path>", code=2)
|
|
94
|
+
|
|
95
|
+
doc = _load_document(document)
|
|
96
|
+
try:
|
|
97
|
+
if fixture is not None and provider == "fixture":
|
|
98
|
+
result = FixtureExtractor(fixture_path=fixture).extract(doc, schema_cls)
|
|
99
|
+
else:
|
|
100
|
+
result = AnthropicExtractor(model=model, max_tokens=max_tokens).extract(doc, schema_cls)
|
|
101
|
+
except (ExtractionError, OSError) as exc:
|
|
102
|
+
_fail(str(exc))
|
|
103
|
+
|
|
104
|
+
report = run_verify(result.data, doc)
|
|
105
|
+
# Write the registry key ("invoice"), not result.schema_name (the class
|
|
106
|
+
# name, "Invoice") - so `fieldproof verify result.json doc.pdf` on our
|
|
107
|
+
# own output resolves the schema without needing resolve_schema's
|
|
108
|
+
# class-name fallback below.
|
|
109
|
+
payload = {**result.to_dict(), "schema": schema, "report": report.to_dict()}
|
|
110
|
+
out.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
|
111
|
+
|
|
112
|
+
counts = report.counts
|
|
113
|
+
typer.echo(
|
|
114
|
+
f"wrote {out} - {counts['verified']} verified, {counts['needs_review']} needs review, "
|
|
115
|
+
f"{counts['unsupported']} unsupported"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@app.command()
|
|
120
|
+
def verify(
|
|
121
|
+
result: Path = typer.Argument(..., exists=True, readable=True, help="extraction result JSON"),
|
|
122
|
+
document: Path = typer.Argument(
|
|
123
|
+
..., exists=True, readable=True, help="the PDF it was extracted from"
|
|
124
|
+
),
|
|
125
|
+
out: Path | None = typer.Option(
|
|
126
|
+
None, "--out", help="write the re-verified result here (default: overwrite RESULT)"
|
|
127
|
+
),
|
|
128
|
+
) -> None:
|
|
129
|
+
"""Re-ground and re-verify an extraction JSON against DOCUMENT.
|
|
130
|
+
|
|
131
|
+
Useful for extractions produced by other tools: RESULT just needs a
|
|
132
|
+
`schema` name (one of fieldproof's built-ins) and a `data` object shaped
|
|
133
|
+
like that schema, with `{value, evidence, page}` at every leaf.
|
|
134
|
+
"""
|
|
135
|
+
try:
|
|
136
|
+
raw = read_extraction_json(result.read_bytes(), result.name)
|
|
137
|
+
schema_name = raw.get("schema", "")
|
|
138
|
+
schema_cls = resolve_schema(schema_name)
|
|
139
|
+
if schema_cls is None:
|
|
140
|
+
_fail(
|
|
141
|
+
f'{result.name}\'s "schema" is {schema_name!r}; must name one of '
|
|
142
|
+
f"{sorted(BUILTIN_SCHEMAS)} (by registry key or class name) "
|
|
143
|
+
"to re-verify from the CLI",
|
|
144
|
+
code=2,
|
|
145
|
+
)
|
|
146
|
+
extraction = ExtractionResult.from_dict(raw, schema_cls, source=result.name)
|
|
147
|
+
except ExtractionError as exc:
|
|
148
|
+
_fail(str(exc), code=2)
|
|
149
|
+
doc = _load_document(document)
|
|
150
|
+
report = run_verify(extraction.data, doc)
|
|
151
|
+
|
|
152
|
+
destination = out or result
|
|
153
|
+
destination.write_text(
|
|
154
|
+
json.dumps({**extraction.to_dict(), "report": report.to_dict()}, indent=2), encoding="utf-8"
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
counts = report.counts
|
|
158
|
+
typer.echo(
|
|
159
|
+
f"wrote {destination} - {counts['verified']} verified, "
|
|
160
|
+
f"{counts['needs_review']} needs review, {counts['unsupported']} unsupported"
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@app.command()
|
|
165
|
+
def serve(
|
|
166
|
+
host: str = typer.Option("127.0.0.1", "--host"),
|
|
167
|
+
port: int = typer.Option(8000, "--port"),
|
|
168
|
+
reload: bool = typer.Option(
|
|
169
|
+
False, "--reload", help="auto-reload on source changes (development)"
|
|
170
|
+
),
|
|
171
|
+
) -> None:
|
|
172
|
+
"""Run the review server (API + UI) at http://HOST:PORT."""
|
|
173
|
+
uvicorn.run("fieldproof.server.app:app", host=host, port=port, reload=reload)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def main() -> None:
|
|
177
|
+
app()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
if __name__ == "__main__":
|
|
181
|
+
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
|
+
]
|