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 +8 -0
- fieldproof/cli.py +199 -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 +107 -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.3.dist-info/METADATA +398 -0
- fieldproof-0.2.3.dist-info/RECORD +34 -0
- fieldproof-0.2.3.dist-info/WHEEL +4 -0
- fieldproof-0.2.3.dist-info/entry_points.txt +2 -0
- fieldproof-0.2.3.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
:root{--font-display: "Fraunces", Georgia, serif;--font-body: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;--font-mono: "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-bg: #f2f4f1;--color-surface: #ffffff;--color-surface-sunken: #e9ece7;--color-ink: #14181a;--color-ink-muted: #5c6670;--color-ink-faint: #8b949c;--color-border: #d7dcd6;--color-border-strong: #b7bfb9;--color-accent: #14524c;--color-accent-ink: #ffffff;--color-focus: #1c7a70;--color-verified: #0e7a5f;--color-verified-bg: #e4f3ec;--color-review: #a6650f;--color-review-bg: #fbf0dc;--color-unsupported: #b3392c;--color-unsupported-bg: #fbe7e3;--radius-sm: 4px;--radius-md: 7px;--shadow-card: 0 1px 2px rgba(20, 24, 26, .06), 0 1px 1px rgba(20, 24, 26, .04);--shadow-panel: 0 4px 16px rgba(20, 24, 26, .08);color-scheme:light}@media(prefers-color-scheme:dark){:root:not([data-theme=light]){--color-bg: #10151a;--color-surface: #171d23;--color-surface-sunken: #0d1216;--color-ink: #e8edee;--color-ink-muted: #93a1aa;--color-ink-faint: #66727c;--color-border: #2a333b;--color-border-strong: #3b4750;--color-accent: #49c9b3;--color-accent-ink: #08201c;--color-focus: #49c9b3;--color-verified: #49c9b3;--color-verified-bg: rgba(73, 201, 179, .14);--color-review: #e3ab41;--color-review-bg: rgba(227, 171, 65, .14);--color-unsupported: #e2685c;--color-unsupported-bg: rgba(226, 104, 92, .14);color-scheme:dark}}:root[data-theme=dark]{--color-bg: #10151a;--color-surface: #171d23;--color-surface-sunken: #0d1216;--color-ink: #e8edee;--color-ink-muted: #93a1aa;--color-ink-faint: #66727c;--color-border: #2a333b;--color-border-strong: #3b4750;--color-accent: #49c9b3;--color-accent-ink: #08201c;--color-focus: #49c9b3;--color-verified: #49c9b3;--color-verified-bg: rgba(73, 201, 179, .14);--color-review: #e3ab41;--color-review-bg: rgba(227, 171, 65, .14);--color-unsupported: #e2685c;--color-unsupported-bg: rgba(226, 104, 92, .14);color-scheme:dark}*{box-sizing:border-box}html,body{height:100%}body{margin:0;background:var(--color-bg);color:var(--color-ink);font-family:var(--font-body);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}button,input,select{font:inherit;color:inherit}a{color:var(--color-accent)}:focus-visible{outline:2px solid var(--color-focus);outline-offset:2px}@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation-duration:.001ms!important;transition-duration:.001ms!important}}#app{display:flex;flex-direction:column;height:100vh;height:100dvh}.topbar{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:10px 20px;border-bottom:1px solid var(--color-border);background:var(--color-surface);flex-wrap:wrap}.brand{display:flex;align-items:baseline;gap:8px}.brand-mark{font-family:var(--font-display);font-weight:560;font-size:20px;letter-spacing:-.01em;color:var(--color-ink)}.brand-tag{font-size:11px;color:var(--color-ink-faint);font-family:var(--font-mono);display:none}@media(min-width:900px){.brand-tag{display:inline}}.topbar-controls{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.sample-switch{display:flex;gap:2px;padding:2px;border:1px solid var(--color-border);border-radius:8px;background:var(--color-bg, transparent)}.sample-switch-btn{padding:5px 12px;border:0;border-radius:6px;background:transparent;color:var(--color-ink-faint);font:inherit;font-size:13px;cursor:pointer}.sample-switch-btn:hover{color:var(--color-ink)}.sample-switch-btn.is-active{background:var(--color-accent);color:var(--color-accent-ink)}.sample-switch-btn:focus-visible{outline:2px solid var(--color-accent);outline-offset:2px}@media(max-width:600px){.sample-switch{order:3;width:100%}.sample-switch-btn{flex:1}}.workbench{flex:1;display:flex;min-height:0}.start-state{margin:auto;max-width:560px;padding:48px 32px;text-align:center}.start-state h1{font-family:var(--font-display);font-weight:540;font-size:28px;margin:0 0 8px}.start-state p{color:var(--color-ink-muted);margin:0 0 28px}.proof-ticks{display:flex;justify-content:center;gap:18px;margin-bottom:32px}.proof-tick{display:flex;align-items:center;gap:6px;font-family:var(--font-mono);font-size:12px;color:var(--color-ink-muted);opacity:0;animation:tick-in .5s ease forwards}.proof-tick:nth-child(1){animation-delay:.05s}.proof-tick:nth-child(2){animation-delay:.2s}.proof-tick:nth-child(3){animation-delay:.35s}@keyframes tick-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.proof-dot{width:8px;height:8px;border-radius:50%}.sample-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px}.dropzone{border:1.5px dashed var(--color-border-strong);border-radius:var(--radius-md);padding:28px;color:var(--color-ink-muted);cursor:pointer;transition:border-color .15s ease,background .15s ease}.dropzone:hover,.dropzone.dragover{border-color:var(--color-accent);background:var(--color-surface-sunken)}.btn{display:inline-flex;align-items:center;gap:6px;padding:6px 12px;border-radius:var(--radius-sm);border:1px solid var(--color-border-strong);background:var(--color-surface);color:var(--color-ink);cursor:pointer;font-size:13px;line-height:1.3}.btn:hover{border-color:var(--color-accent)}.btn-primary{background:var(--color-accent);border-color:var(--color-accent);color:var(--color-accent-ink);font-weight:600}.btn-primary:hover{filter:brightness(1.08)}.btn:disabled{opacity:.45;cursor:not-allowed}.select,.text-input{padding:6px 10px;border-radius:var(--radius-sm);border:1px solid var(--color-border-strong);background:var(--color-surface)}.viewer-pane{flex:1 1 55%;min-width:0;min-height:0;display:flex;flex-direction:column;border-right:1px solid var(--color-border);background:var(--color-surface-sunken)}.viewer-toolbar{display:flex;align-items:center;gap:8px;padding:8px 14px;border-bottom:1px solid var(--color-border);background:var(--color-surface);font-size:12px;color:var(--color-ink-muted)}.viewer-scroll{flex:1;overflow:auto;padding:24px;display:flex;justify-content:center}.page-frame{position:relative;box-shadow:var(--shadow-panel);background:#fff;height:fit-content}.page-frame img{display:block;max-width:none}.highlight-rect{position:absolute;border-radius:2px;border:1.5px solid transparent;background:transparent;cursor:pointer;transition:background .15s ease,border-color .15s ease}.highlight-rect[data-status=verified]{border-color:color-mix(in srgb,var(--color-verified) 55%,transparent);background:color-mix(in srgb,var(--color-verified) 14%,transparent)}.highlight-rect[data-status=needs_review]{border-color:color-mix(in srgb,var(--color-review) 65%,transparent);background:color-mix(in srgb,var(--color-review) 18%,transparent)}.highlight-rect[data-status=unsupported]{border-color:color-mix(in srgb,var(--color-unsupported) 65%,transparent);background:color-mix(in srgb,var(--color-unsupported) 18%,transparent)}.highlight-rect.is-active,.highlight-rect:hover{border-width:2px;filter:brightness(.94) saturate(1.3)}.highlight-rect.is-pulsing{animation:pulse-ring .9s ease 2}@keyframes pulse-ring{0%{box-shadow:0 0 color-mix(in srgb,var(--color-accent) 55%,transparent)}70%{box-shadow:0 0 0 8px color-mix(in srgb,var(--color-accent) 0%,transparent)}to{box-shadow:0 0 0 0 transparent}}.field-pane{flex:1 1 45%;min-width:320px;min-height:0;display:flex;flex-direction:column}.field-pane-header{padding:12px 16px;border-bottom:1px solid var(--color-border);background:var(--color-surface);display:flex;flex-direction:column;gap:10px}.counts-strip{display:flex;gap:8px;flex-wrap:wrap}.count-chip{display:inline-flex;align-items:center;gap:6px;padding:3px 9px;border-radius:999px;font-size:12px;font-family:var(--font-mono);border:1px solid var(--color-border);background:var(--color-surface-sunken);cursor:pointer}.count-chip.is-active{border-color:currentColor}.count-chip[data-status=verified]{color:var(--color-verified)}.count-chip[data-status=needs_review]{color:var(--color-review)}.count-chip[data-status=unsupported]{color:var(--color-unsupported)}.filter-row{display:flex;gap:8px}.filter-row .text-input{flex:1}.field-list{flex:1;overflow:auto;list-style:none;margin:0;padding:0}.field-row{padding:10px 16px;border-bottom:1px solid var(--color-border);cursor:pointer;background:var(--color-surface)}.field-row:hover,.field-row.is-hovered{background:var(--color-surface-sunken)}.field-row.is-selected{background:var(--color-surface-sunken);box-shadow:inset 3px 0 0 var(--color-accent)}.field-row-top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}.field-path{font-family:var(--font-mono);font-size:11.5px;color:var(--color-ink-faint)}.status-chip{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;white-space:nowrap}.status-chip[data-status=verified]{color:var(--color-verified);background:var(--color-verified-bg)}.status-chip[data-status=needs_review]{color:var(--color-review);background:var(--color-review-bg)}.status-chip[data-status=unsupported]{color:var(--color-unsupported);background:var(--color-unsupported-bg)}.status-chip:before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor}.field-value{font-size:14.5px;margin-top:3px;word-break:break-word}.field-value.is-edited{text-decoration:underline dotted;text-decoration-color:var(--color-accent)}.field-reasons{margin-top:5px;font-size:12px;color:var(--color-ink-muted)}.field-reasons li{margin:2px 0 2px 16px}.field-evidence{margin-top:6px;font-family:var(--font-mono);font-size:11.5px;color:var(--color-ink-muted);background:var(--color-surface-sunken);padding:5px 8px;border-radius:var(--radius-sm);border-left:2px solid var(--color-border-strong)}.field-actions{margin-top:8px;display:flex;gap:6px;flex-wrap:wrap}.field-actions .btn{padding:4px 9px;font-size:12px}.review-badge{font-size:11px;color:var(--color-ink-faint);font-family:var(--font-mono);margin-left:6px}.edit-row{display:flex;gap:6px;margin-top:8px}.edit-row .text-input{flex:1}.empty-filtered{padding:40px 20px;text-align:center;color:var(--color-ink-faint)}.toast{position:fixed;bottom:18px;left:50%;transform:translate(-50%) translateY(8px);background:var(--color-ink);color:var(--color-bg);padding:8px 16px;border-radius:var(--radius-sm);font-size:13px;opacity:0;pointer-events:none;transition:opacity .2s ease,transform .2s ease;z-index:50}.toast.is-visible{opacity:1;transform:translate(-50%) translateY(0)}@media(max-width:860px){.workbench{flex-direction:column}.viewer-pane,.field-pane{flex:none;min-width:0}.viewer-pane{border-right:none;border-bottom:1px solid var(--color-border);max-height:42vh}.field-pane{min-height:0}}.visually-hidden{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.demo-note{margin:8px 0 0;font-size:12px;line-height:1.45;color:var(--color-ink-faint)}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<title>fieldproof · grounded document review</title>
|
|
7
|
+
<meta
|
|
8
|
+
name="description"
|
|
9
|
+
content="Review UI for fieldproof: every extracted field linked to the exact words it came from."
|
|
10
|
+
/>
|
|
11
|
+
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Crect width='24' height='24' rx='5' fill='%2314524c'/%3E%3Cpath d='M7 12.5l3 3 7-7.5' stroke='%23fff' stroke-width='2' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E" />
|
|
12
|
+
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
13
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
14
|
+
<link
|
|
15
|
+
href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,480;9..144,560&family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap"
|
|
16
|
+
rel="stylesheet"
|
|
17
|
+
/>
|
|
18
|
+
<script>
|
|
19
|
+
// Applied before paint so there's no flash of the wrong theme; the
|
|
20
|
+
// toggle in the toolbar just flips this same attribute + key.
|
|
21
|
+
(function () {
|
|
22
|
+
try {
|
|
23
|
+
var saved = localStorage.getItem("fieldproof-theme");
|
|
24
|
+
if (saved === "light" || saved === "dark") {
|
|
25
|
+
document.documentElement.setAttribute("data-theme", saved);
|
|
26
|
+
}
|
|
27
|
+
} catch (e) {
|
|
28
|
+
/* storage unavailable - system preference still applies via CSS */
|
|
29
|
+
}
|
|
30
|
+
})();
|
|
31
|
+
</script>
|
|
32
|
+
<meta property="og:type" content="website" />
|
|
33
|
+
<meta property="og:site_name" content="Officina, open-source tools by Anton Soloviev" />
|
|
34
|
+
<meta property="og:title" content="fieldproof · grounded document review" />
|
|
35
|
+
<meta property="og:description" content="Document extraction that shows its work: every LLM-extracted field grounded to its source words, verified, and reviewable." />
|
|
36
|
+
<meta property="og:url" content="https://antonsoo.github.io/fieldproof/" />
|
|
37
|
+
<meta property="og:image" content="https://raw.githubusercontent.com/antonsoo/fieldproof/main/docs/assets/og.png" />
|
|
38
|
+
<meta property="og:image:width" content="1200" />
|
|
39
|
+
<meta property="og:image:height" content="630" />
|
|
40
|
+
<meta name="twitter:card" content="summary_large_image" />
|
|
41
|
+
<meta name="twitter:title" content="fieldproof · grounded document review" />
|
|
42
|
+
<meta name="twitter:description" content="Document extraction that shows its work: every LLM-extracted field grounded to its source words, verified, and reviewable." />
|
|
43
|
+
<meta name="twitter:image" content="https://raw.githubusercontent.com/antonsoo/fieldproof/main/docs/assets/og.png" />
|
|
44
|
+
<script type="module" crossorigin src="/assets/index-BLATbujI.js"></script>
|
|
45
|
+
<link rel="stylesheet" crossorigin href="/assets/index-Bo892MpF.css">
|
|
46
|
+
</head>
|
|
47
|
+
<body>
|
|
48
|
+
<div id="app"></div>
|
|
49
|
+
</body>
|
|
50
|
+
</html>
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""In-process document store for the review server.
|
|
2
|
+
|
|
3
|
+
This is deliberately not a database: fieldproof's server is a local review
|
|
4
|
+
tool (`fieldproof serve`), not a multi-user service, and every session's
|
|
5
|
+
state - the uploaded PDF, extraction, and review decisions - lives only as
|
|
6
|
+
long as the process does. Restarting the server starts over. If you need
|
|
7
|
+
persistence across restarts, export the approved values (`/export.json`)
|
|
8
|
+
before stopping it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import uuid
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from fieldproof.document.model import Document
|
|
18
|
+
from fieldproof.extract.base import ExtractionResult
|
|
19
|
+
from fieldproof.verify.engine import VerificationReport
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ReviewState:
|
|
24
|
+
status: str = "pending" # pending | approved | edited | rejected
|
|
25
|
+
edited_value: Any = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class DocumentSession:
|
|
30
|
+
id: str
|
|
31
|
+
filename: str
|
|
32
|
+
pdf_bytes: bytes
|
|
33
|
+
document: Document
|
|
34
|
+
schema_name: str | None = None
|
|
35
|
+
extraction: ExtractionResult | None = None
|
|
36
|
+
report: VerificationReport | None = None
|
|
37
|
+
review: dict[str, ReviewState] = field(default_factory=dict)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class DocumentStore:
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self._sessions: dict[str, DocumentSession] = {}
|
|
43
|
+
|
|
44
|
+
def create(self, filename: str, pdf_bytes: bytes, document: Document) -> DocumentSession:
|
|
45
|
+
session_id = uuid.uuid4().hex
|
|
46
|
+
session = DocumentSession(
|
|
47
|
+
id=session_id, filename=filename, pdf_bytes=pdf_bytes, document=document
|
|
48
|
+
)
|
|
49
|
+
self._sessions[session_id] = session
|
|
50
|
+
return session
|
|
51
|
+
|
|
52
|
+
def get(self, session_id: str) -> DocumentSession | None:
|
|
53
|
+
return self._sessions.get(session_id)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
#: Module-level singleton - the server process has exactly one store.
|
|
57
|
+
store = DocumentStore()
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from fieldproof.verify.cross_field import CrossFieldIssue, check_cross_field
|
|
2
|
+
from fieldproof.verify.engine import FieldStatus, FieldVerification, VerificationReport, verify
|
|
3
|
+
from fieldproof.verify.value_checks import (
|
|
4
|
+
ValueCheckResult,
|
|
5
|
+
check_bool,
|
|
6
|
+
check_date,
|
|
7
|
+
check_number,
|
|
8
|
+
check_string,
|
|
9
|
+
parse_all_numbers,
|
|
10
|
+
parse_date,
|
|
11
|
+
parse_number,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"CrossFieldIssue",
|
|
16
|
+
"FieldStatus",
|
|
17
|
+
"FieldVerification",
|
|
18
|
+
"ValueCheckResult",
|
|
19
|
+
"VerificationReport",
|
|
20
|
+
"check_bool",
|
|
21
|
+
"check_cross_field",
|
|
22
|
+
"check_date",
|
|
23
|
+
"check_number",
|
|
24
|
+
"check_string",
|
|
25
|
+
"parse_all_numbers",
|
|
26
|
+
"parse_date",
|
|
27
|
+
"parse_number",
|
|
28
|
+
"verify",
|
|
29
|
+
]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Cross-field consistency rules for the built-in Invoice/Receipt schemas.
|
|
2
|
+
|
|
3
|
+
These are schema-specific by nature - "line items sum to the subtotal" only
|
|
4
|
+
means something for a schema that has line items - so unlike
|
|
5
|
+
`fieldproof.verify.value_checks` (which works on any `Evidenced[str|float|bool]`
|
|
6
|
+
leaf via `iter_evidenced_fields`), this module dispatches on the concrete
|
|
7
|
+
schema type. A custom Pydantic model gets value-vs-evidence checks and
|
|
8
|
+
grounding, but no cross-field rules, unless you extend this dispatch.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel
|
|
16
|
+
|
|
17
|
+
from fieldproof.schemas.invoice import Invoice
|
|
18
|
+
from fieldproof.schemas.receipt import Receipt
|
|
19
|
+
from fieldproof.verify.value_checks import parse_date
|
|
20
|
+
|
|
21
|
+
#: Absolute tolerance, in currency units, for "do these amounts add up".
|
|
22
|
+
#: Covers per-line-item rounding that a strict sum would flag spuriously.
|
|
23
|
+
SUM_TOLERANCE = 0.02
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class CrossFieldIssue:
|
|
28
|
+
fields: tuple[str, ...]
|
|
29
|
+
message: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def check_invoice(invoice: Invoice, *, tolerance: float = SUM_TOLERANCE) -> list[CrossFieldIssue]:
|
|
33
|
+
issues: list[CrossFieldIssue] = []
|
|
34
|
+
|
|
35
|
+
if invoice.line_items and invoice.subtotal is not None:
|
|
36
|
+
computed = sum(item.amount.value for item in invoice.line_items)
|
|
37
|
+
if abs(computed - invoice.subtotal.value) > tolerance:
|
|
38
|
+
issues.append(
|
|
39
|
+
CrossFieldIssue(
|
|
40
|
+
fields=(
|
|
41
|
+
"subtotal",
|
|
42
|
+
*(f"line_items[{i}].amount" for i in range(len(invoice.line_items))),
|
|
43
|
+
),
|
|
44
|
+
message=(
|
|
45
|
+
f"line items sum to {computed:.2f} but subtotal is "
|
|
46
|
+
f"{invoice.subtotal.value:.2f}"
|
|
47
|
+
),
|
|
48
|
+
)
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
if invoice.subtotal is not None and invoice.tax is not None:
|
|
52
|
+
computed_total = invoice.subtotal.value + invoice.tax.value
|
|
53
|
+
if abs(computed_total - invoice.total.value) > tolerance:
|
|
54
|
+
issues.append(
|
|
55
|
+
CrossFieldIssue(
|
|
56
|
+
fields=("subtotal", "tax", "total"),
|
|
57
|
+
message=(
|
|
58
|
+
f"subtotal + tax = {computed_total:.2f} but total is "
|
|
59
|
+
f"{invoice.total.value:.2f}"
|
|
60
|
+
),
|
|
61
|
+
)
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
if invoice.due_date is not None:
|
|
65
|
+
issue_d = parse_date(invoice.issue_date.value)
|
|
66
|
+
due_d = parse_date(invoice.due_date.value)
|
|
67
|
+
if issue_d and due_d and due_d < issue_d:
|
|
68
|
+
issues.append(
|
|
69
|
+
CrossFieldIssue(
|
|
70
|
+
fields=("issue_date", "due_date"),
|
|
71
|
+
message=(
|
|
72
|
+
f"due date {due_d.isoformat()} is before issue date {issue_d.isoformat()}"
|
|
73
|
+
),
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
return issues
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def check_receipt(receipt: Receipt, *, tolerance: float = SUM_TOLERANCE) -> list[CrossFieldIssue]:
|
|
81
|
+
issues: list[CrossFieldIssue] = []
|
|
82
|
+
|
|
83
|
+
if receipt.items and receipt.subtotal is not None:
|
|
84
|
+
computed = sum(item.amount.value for item in receipt.items)
|
|
85
|
+
if abs(computed - receipt.subtotal.value) > tolerance:
|
|
86
|
+
issues.append(
|
|
87
|
+
CrossFieldIssue(
|
|
88
|
+
fields=("subtotal", *(f"items[{i}].amount" for i in range(len(receipt.items)))),
|
|
89
|
+
message=(
|
|
90
|
+
f"items sum to {computed:.2f} but subtotal is {receipt.subtotal.value:.2f}"
|
|
91
|
+
),
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
if receipt.subtotal is not None and receipt.tax is not None:
|
|
96
|
+
computed_total = receipt.subtotal.value + receipt.tax.value
|
|
97
|
+
if abs(computed_total - receipt.total.value) > tolerance:
|
|
98
|
+
issues.append(
|
|
99
|
+
CrossFieldIssue(
|
|
100
|
+
fields=("subtotal", "tax", "total"),
|
|
101
|
+
message=(
|
|
102
|
+
f"subtotal + tax = {computed_total:.2f} but total is "
|
|
103
|
+
f"{receipt.total.value:.2f}"
|
|
104
|
+
),
|
|
105
|
+
)
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
return issues
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def check_cross_field(data: BaseModel) -> list[CrossFieldIssue]:
|
|
112
|
+
"""Dispatch to the right cross-field checker for `data`'s type, or
|
|
113
|
+
return no issues for a schema this module doesn't know about."""
|
|
114
|
+
if isinstance(data, Invoice):
|
|
115
|
+
return check_invoice(data)
|
|
116
|
+
if isinstance(data, Receipt):
|
|
117
|
+
return check_receipt(data)
|
|
118
|
+
return []
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""Orchestrates grounding + value checks + cross-field rules into a
|
|
2
|
+
per-field verdict.
|
|
3
|
+
|
|
4
|
+
Every extracted field ends up in exactly one of three states:
|
|
5
|
+
|
|
6
|
+
- `verified` - its evidence was found on the page, unambiguously, with a
|
|
7
|
+
strong match, and the value agrees with what the evidence actually says.
|
|
8
|
+
- `needs_review` - evidence was found but the match was weak, the value
|
|
9
|
+
disagrees with the evidence, a cross-field rule it participates in
|
|
10
|
+
failed, or the quote is genuinely ambiguous (it occurs more than once
|
|
11
|
+
and nothing nearby disambiguates it). Worth a human's attention, not
|
|
12
|
+
necessarily wrong.
|
|
13
|
+
- `unsupported` - no evidence quote was provided, or none of the quotes
|
|
14
|
+
could be located anywhere in the document. This is the strongest signal
|
|
15
|
+
of a hallucinated field.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
from collections import defaultdict
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from enum import StrEnum
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from pydantic import BaseModel
|
|
27
|
+
|
|
28
|
+
from fieldproof.document.model import Document
|
|
29
|
+
from fieldproof.ground.align import (
|
|
30
|
+
GroundingMatch,
|
|
31
|
+
find_candidates_in_document,
|
|
32
|
+
nearest_candidate,
|
|
33
|
+
rects_for_match,
|
|
34
|
+
)
|
|
35
|
+
from fieldproof.schemas.base import iter_evidenced_fields
|
|
36
|
+
from fieldproof.verify.cross_field import CrossFieldIssue, check_cross_field
|
|
37
|
+
from fieldproof.verify.value_checks import (
|
|
38
|
+
DateOrder,
|
|
39
|
+
ValueCheckResult,
|
|
40
|
+
check_bool,
|
|
41
|
+
check_date,
|
|
42
|
+
check_number,
|
|
43
|
+
check_string,
|
|
44
|
+
numeric_date_order,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
#: Matches the "row" a list-item field belongs to, e.g. "line_items[1]" out
|
|
48
|
+
#: of "line_items[1].quantity" - used to group sibling fields of the same
|
|
49
|
+
#: object so one can act as a locality hint for disambiguating another
|
|
50
|
+
#: (see `verify`).
|
|
51
|
+
_ROW_PREFIX_RE = re.compile(r"^(.*\[\d+\])\.")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class FieldStatus(StrEnum):
|
|
55
|
+
VERIFIED = "verified"
|
|
56
|
+
NEEDS_REVIEW = "needs_review"
|
|
57
|
+
UNSUPPORTED = "unsupported"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class FieldVerification:
|
|
62
|
+
path: str
|
|
63
|
+
value: str | float | bool
|
|
64
|
+
status: FieldStatus
|
|
65
|
+
reasons: list[str] = field(default_factory=list)
|
|
66
|
+
match_score: float | None = None
|
|
67
|
+
matched_text: str | None = None
|
|
68
|
+
page: int | None = None
|
|
69
|
+
rects: list[dict[str, float]] = field(default_factory=list)
|
|
70
|
+
|
|
71
|
+
def to_dict(self) -> dict[str, Any]:
|
|
72
|
+
return {
|
|
73
|
+
"path": self.path,
|
|
74
|
+
"value": self.value,
|
|
75
|
+
"status": self.status.value,
|
|
76
|
+
"reasons": self.reasons,
|
|
77
|
+
"match_score": self.match_score,
|
|
78
|
+
"matched_text": self.matched_text,
|
|
79
|
+
"page": self.page,
|
|
80
|
+
"rects": self.rects,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class VerificationReport:
|
|
86
|
+
fields: list[FieldVerification]
|
|
87
|
+
cross_field_issues: list[CrossFieldIssue]
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def counts(self) -> dict[str, int]:
|
|
91
|
+
counts = {status.value: 0 for status in FieldStatus}
|
|
92
|
+
for f in self.fields:
|
|
93
|
+
counts[f.status.value] += 1
|
|
94
|
+
return counts
|
|
95
|
+
|
|
96
|
+
def to_dict(self) -> dict[str, Any]:
|
|
97
|
+
return {
|
|
98
|
+
"fields": [f.to_dict() for f in self.fields],
|
|
99
|
+
"cross_field_issues": [
|
|
100
|
+
{"fields": list(i.fields), "message": i.message} for i in self.cross_field_issues
|
|
101
|
+
],
|
|
102
|
+
"counts": self.counts,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _row_prefix(path: str) -> str | None:
|
|
107
|
+
match = _ROW_PREFIX_RE.match(path)
|
|
108
|
+
return match.group(1) if match else None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def verify(data: BaseModel, document: Document) -> VerificationReport:
|
|
112
|
+
"""Verify every `Evidenced` field under `data` against `document`.
|
|
113
|
+
|
|
114
|
+
Fields are walked in schema-declaration order (`iter_evidenced_fields`),
|
|
115
|
+
which for a list item means its fields come in the order they're
|
|
116
|
+
declared on the model - e.g. `LineItem.description` before
|
|
117
|
+
`LineItem.quantity`. The first field of each "row" (an indexed list
|
|
118
|
+
item, e.g. `line_items[1]`) that grounds successfully becomes that
|
|
119
|
+
row's locality anchor, used to disambiguate a later sibling field whose
|
|
120
|
+
quote turns out to occur more than once on the page (see
|
|
121
|
+
`_verify_field`'s `hint_match` and `fieldproof.ground.nearest_candidate`).
|
|
122
|
+
"""
|
|
123
|
+
results: list[FieldVerification] = []
|
|
124
|
+
row_anchors: dict[str, GroundingMatch] = {}
|
|
125
|
+
# Whether this document writes numeric dates month or day first, if any of
|
|
126
|
+
# its dates settles it; see `check_date`.
|
|
127
|
+
date_order = numeric_date_order(document.full_text())
|
|
128
|
+
|
|
129
|
+
for path, evidenced in iter_evidenced_fields(data):
|
|
130
|
+
prefix = _row_prefix(path)
|
|
131
|
+
hint = row_anchors.get(prefix) if prefix else None
|
|
132
|
+
|
|
133
|
+
result, match = _verify_field(
|
|
134
|
+
path, evidenced, document, hint_match=hint, date_order=date_order
|
|
135
|
+
)
|
|
136
|
+
results.append(result)
|
|
137
|
+
|
|
138
|
+
if prefix is not None and prefix not in row_anchors and match is not None:
|
|
139
|
+
row_anchors[prefix] = match
|
|
140
|
+
|
|
141
|
+
cross_field_issues = check_cross_field(data)
|
|
142
|
+
_apply_cross_field_issues(results, cross_field_issues)
|
|
143
|
+
|
|
144
|
+
return VerificationReport(fields=results, cross_field_issues=cross_field_issues)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _verify_field(
|
|
148
|
+
path: str,
|
|
149
|
+
evidenced: Any,
|
|
150
|
+
document: Document,
|
|
151
|
+
*,
|
|
152
|
+
hint_match: GroundingMatch | None,
|
|
153
|
+
date_order: DateOrder | None = None,
|
|
154
|
+
) -> tuple[FieldVerification, GroundingMatch | None]:
|
|
155
|
+
value = evidenced.value
|
|
156
|
+
|
|
157
|
+
if not evidenced.evidence:
|
|
158
|
+
result = FieldVerification(
|
|
159
|
+
path=path,
|
|
160
|
+
value=value,
|
|
161
|
+
status=FieldStatus.UNSUPPORTED,
|
|
162
|
+
reasons=["no evidence quote was provided for this value"],
|
|
163
|
+
)
|
|
164
|
+
return result, None
|
|
165
|
+
|
|
166
|
+
candidates: list[GroundingMatch] = []
|
|
167
|
+
for quote in evidenced.evidence:
|
|
168
|
+
candidates.extend(find_candidates_in_document(quote, document, hint_page=evidenced.page))
|
|
169
|
+
|
|
170
|
+
if not candidates:
|
|
171
|
+
quoted = ", ".join(repr(q) for q in evidenced.evidence)
|
|
172
|
+
result = FieldVerification(
|
|
173
|
+
path=path,
|
|
174
|
+
value=value,
|
|
175
|
+
status=FieldStatus.UNSUPPORTED,
|
|
176
|
+
reasons=[f"none of the evidence quotes ({quoted}) could be located in the document"],
|
|
177
|
+
)
|
|
178
|
+
return result, None
|
|
179
|
+
|
|
180
|
+
reasons: list[str] = []
|
|
181
|
+
best_match: GroundingMatch | None
|
|
182
|
+
|
|
183
|
+
if len(candidates) == 1:
|
|
184
|
+
best_match = candidates[0]
|
|
185
|
+
elif hint_match is not None:
|
|
186
|
+
# Multiple occurrences of the same quote - prefer whichever is
|
|
187
|
+
# closest to another field from the same row that's already been
|
|
188
|
+
# grounded (e.g. this line item's description).
|
|
189
|
+
best_match = nearest_candidate(candidates, hint_match)
|
|
190
|
+
else:
|
|
191
|
+
# Ambiguous with nothing nearby to disambiguate it against - don't
|
|
192
|
+
# silently guess; a wrong guess here is exactly the "verified but
|
|
193
|
+
# actually wrong" failure mode this tool exists to catch.
|
|
194
|
+
best_match = None
|
|
195
|
+
reasons.append(
|
|
196
|
+
f"evidence {candidates[0].quote!r} is ambiguous (appears {len(candidates)} times); "
|
|
197
|
+
"quote more context"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
if best_match is None:
|
|
201
|
+
result = FieldVerification(
|
|
202
|
+
path=path, value=value, status=FieldStatus.NEEDS_REVIEW, reasons=reasons
|
|
203
|
+
)
|
|
204
|
+
return result, None
|
|
205
|
+
|
|
206
|
+
if not best_match.is_strong:
|
|
207
|
+
reasons.append(
|
|
208
|
+
f"evidence match quality is only {best_match.score:.0f}/100 - the quote is a loose "
|
|
209
|
+
"paraphrase or contains OCR-like noise"
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
check = _check_value(path, value, best_match.matched_text, date_order)
|
|
213
|
+
if not check.supported:
|
|
214
|
+
reasons.append(check.reason)
|
|
215
|
+
|
|
216
|
+
status = FieldStatus.NEEDS_REVIEW if reasons else FieldStatus.VERIFIED
|
|
217
|
+
|
|
218
|
+
rects = [r.to_dict() for r in rects_for_match(best_match)]
|
|
219
|
+
|
|
220
|
+
result = FieldVerification(
|
|
221
|
+
path=path,
|
|
222
|
+
value=value,
|
|
223
|
+
status=status,
|
|
224
|
+
reasons=reasons,
|
|
225
|
+
match_score=best_match.score,
|
|
226
|
+
matched_text=best_match.matched_text,
|
|
227
|
+
page=best_match.page_number,
|
|
228
|
+
rects=rects,
|
|
229
|
+
)
|
|
230
|
+
return result, best_match
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _check_value(
|
|
234
|
+
path: str,
|
|
235
|
+
value: str | float | bool,
|
|
236
|
+
evidence_text: str,
|
|
237
|
+
date_order: DateOrder | None = None,
|
|
238
|
+
) -> ValueCheckResult:
|
|
239
|
+
if isinstance(value, bool):
|
|
240
|
+
return check_bool(value, evidence_text)
|
|
241
|
+
if isinstance(value, int | float):
|
|
242
|
+
return check_number(float(value), evidence_text)
|
|
243
|
+
if isinstance(value, str):
|
|
244
|
+
if "date" in path.lower():
|
|
245
|
+
return check_date(value, evidence_text, date_order=date_order)
|
|
246
|
+
return check_string(value, evidence_text)
|
|
247
|
+
return ValueCheckResult(True)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _apply_cross_field_issues(
|
|
251
|
+
results: list[FieldVerification], issues: list[CrossFieldIssue]
|
|
252
|
+
) -> None:
|
|
253
|
+
issue_reasons: dict[str, list[str]] = defaultdict(list)
|
|
254
|
+
for issue in issues:
|
|
255
|
+
for path in issue.fields:
|
|
256
|
+
issue_reasons[path].append(issue.message)
|
|
257
|
+
|
|
258
|
+
by_path = {r.path: r for r in results}
|
|
259
|
+
for path, reasons in issue_reasons.items():
|
|
260
|
+
result = by_path.get(path)
|
|
261
|
+
if result is None:
|
|
262
|
+
continue
|
|
263
|
+
result.reasons.extend(reasons)
|
|
264
|
+
if result.status == FieldStatus.VERIFIED:
|
|
265
|
+
result.status = FieldStatus.NEEDS_REVIEW
|