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,48 @@
|
|
|
1
|
+
from pydantic import BaseModel
|
|
2
|
+
|
|
3
|
+
from fieldproof.schemas.base import Evidenced, iter_evidenced_fields
|
|
4
|
+
from fieldproof.schemas.contract import ContractKeyTerms
|
|
5
|
+
from fieldproof.schemas.invoice import Invoice, LineItem
|
|
6
|
+
from fieldproof.schemas.receipt import Receipt, ReceiptItem
|
|
7
|
+
|
|
8
|
+
#: Name -> schema, used by the CLI's `--schema` flag and the server's upload form.
|
|
9
|
+
BUILTIN_SCHEMAS: dict[str, type[BaseModel]] = {
|
|
10
|
+
"invoice": Invoice,
|
|
11
|
+
"receipt": Receipt,
|
|
12
|
+
"contract": ContractKeyTerms,
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def resolve_schema(name: object) -> type[BaseModel] | None:
|
|
17
|
+
"""Look up a built-in schema by its registry key ("invoice") or its
|
|
18
|
+
Python class name ("Invoice"), case-insensitively.
|
|
19
|
+
|
|
20
|
+
`fieldproof extract` writes the registry key into `result.json`'s
|
|
21
|
+
"schema" field, but `Extractor.extract()` (used directly by library
|
|
22
|
+
callers, or by another tool producing its own result JSON per the
|
|
23
|
+
"bring your own extractor" contract) has no registry to consult and
|
|
24
|
+
naturally reaches for the class name instead - `fieldproof verify`
|
|
25
|
+
needs to accept either.
|
|
26
|
+
"""
|
|
27
|
+
if not isinstance(name, str): # read from someone's JSON: it can be anything
|
|
28
|
+
return None
|
|
29
|
+
key = name.lower()
|
|
30
|
+
if key in BUILTIN_SCHEMAS:
|
|
31
|
+
return BUILTIN_SCHEMAS[key]
|
|
32
|
+
for schema in BUILTIN_SCHEMAS.values():
|
|
33
|
+
if schema.__name__.lower() == key:
|
|
34
|
+
return schema
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"BUILTIN_SCHEMAS",
|
|
40
|
+
"ContractKeyTerms",
|
|
41
|
+
"Evidenced",
|
|
42
|
+
"Invoice",
|
|
43
|
+
"LineItem",
|
|
44
|
+
"Receipt",
|
|
45
|
+
"ReceiptItem",
|
|
46
|
+
"iter_evidenced_fields",
|
|
47
|
+
"resolve_schema",
|
|
48
|
+
]
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""The `Evidenced[T]` wrapper and the generic walker every other stage uses.
|
|
2
|
+
|
|
3
|
+
fieldproof's trust story only works if grounding and verification can find
|
|
4
|
+
*every* extracted value in *any* schema, including one a user brings
|
|
5
|
+
themselves - so instead of hand-writing per-schema traversal, every leaf
|
|
6
|
+
value is wrapped in `Evidenced[T]` and `iter_evidenced_fields` walks an
|
|
7
|
+
arbitrary Pydantic model (nested models, lists of models) collecting them by
|
|
8
|
+
dotted path. Grounding and verification are written once, against this
|
|
9
|
+
walker, and never against Invoice/Receipt/Contract by name.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Iterator
|
|
15
|
+
from typing import Generic, TypeVar
|
|
16
|
+
|
|
17
|
+
from pydantic import BaseModel, Field
|
|
18
|
+
|
|
19
|
+
T = TypeVar("T", str, float, bool)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Evidenced(BaseModel, Generic[T]):
|
|
23
|
+
"""A single extracted value plus the verbatim quote(s) that support it.
|
|
24
|
+
|
|
25
|
+
`evidence` holds exact substrings the model claims to have read on the
|
|
26
|
+
page - grounding (`fieldproof.ground`) locates them in the real page
|
|
27
|
+
text, and verification (`fieldproof.verify`) checks they actually
|
|
28
|
+
support `value`. An empty `evidence` list means the model supplied a
|
|
29
|
+
value with no citation, which verification treats as `unsupported`.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
value: T
|
|
33
|
+
evidence: list[str] = Field(default_factory=list)
|
|
34
|
+
page: int | None = Field(default=None, description="1-indexed page the evidence was found on")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def iter_evidenced_fields(model: BaseModel, prefix: str = "") -> Iterator[tuple[str, Evidenced]]:
|
|
38
|
+
"""Yield `(dotted_path, Evidenced)` for every `Evidenced` leaf under `model`,
|
|
39
|
+
recursing into nested `BaseModel`s and lists of them (e.g. line items)."""
|
|
40
|
+
for name, value in model:
|
|
41
|
+
path = f"{prefix}.{name}" if prefix else name
|
|
42
|
+
yield from _walk_value(path, value)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _walk_value(path: str, value: object) -> Iterator[tuple[str, Evidenced]]:
|
|
46
|
+
if isinstance(value, Evidenced):
|
|
47
|
+
yield path, value
|
|
48
|
+
elif isinstance(value, BaseModel):
|
|
49
|
+
yield from iter_evidenced_fields(value, path)
|
|
50
|
+
elif isinstance(value, list):
|
|
51
|
+
for i, item in enumerate(value):
|
|
52
|
+
yield from _walk_value(f"{path}[{i}]", item)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""The built-in contract key-terms extraction template.
|
|
2
|
+
|
|
3
|
+
Contracts don't have the arithmetic structure invoices and receipts do, so
|
|
4
|
+
there are no cross-field checks for this schema in `fieldproof.verify` -
|
|
5
|
+
every field still goes through evidence grounding and value-vs-evidence
|
|
6
|
+
consistency, just no line-item sums or date-ordering rules.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, Field
|
|
12
|
+
|
|
13
|
+
from fieldproof.schemas.base import Evidenced
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ContractKeyTerms(BaseModel):
|
|
17
|
+
"""Key terms of a contract: parties, dates, and obligations."""
|
|
18
|
+
|
|
19
|
+
party_a: Evidenced[str]
|
|
20
|
+
party_b: Evidenced[str]
|
|
21
|
+
effective_date: Evidenced[str] = Field(description="ISO-8601 date")
|
|
22
|
+
term_length: Evidenced[str] | None = Field(
|
|
23
|
+
default=None, description="e.g. '12 months', 'until terminated'"
|
|
24
|
+
)
|
|
25
|
+
termination_notice_period: Evidenced[str] | None = None
|
|
26
|
+
governing_law: Evidenced[str] | None = None
|
|
27
|
+
total_contract_value: Evidenced[float] | None = None
|
|
28
|
+
key_obligations: list[Evidenced[str]] = Field(default_factory=list)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""The built-in invoice extraction template.
|
|
2
|
+
|
|
3
|
+
Dates and money are kept as `str`/`float` (not `date`/`Decimal`) so the
|
|
4
|
+
schema serializes to plain JSON Schema for the provider's structured-output
|
|
5
|
+
call - `fieldproof.verify.value_checks` is responsible for parsing
|
|
6
|
+
`issue_date`/`due_date` as ISO-8601 and comparing amounts with a tolerance,
|
|
7
|
+
not this module.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel, Field
|
|
13
|
+
|
|
14
|
+
from fieldproof.schemas.base import Evidenced
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class LineItem(BaseModel):
|
|
18
|
+
description: Evidenced[str]
|
|
19
|
+
quantity: Evidenced[float] | None = None
|
|
20
|
+
unit_price: Evidenced[float] | None = None
|
|
21
|
+
amount: Evidenced[float]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Invoice(BaseModel):
|
|
25
|
+
"""Vendor invoice: line items, totals, and payment terms."""
|
|
26
|
+
|
|
27
|
+
vendor_name: Evidenced[str]
|
|
28
|
+
invoice_number: Evidenced[str]
|
|
29
|
+
issue_date: Evidenced[str] = Field(description="ISO-8601 date, e.g. 2026-03-14")
|
|
30
|
+
due_date: Evidenced[str] | None = Field(default=None, description="ISO-8601 date")
|
|
31
|
+
currency: Evidenced[str] | None = Field(default=None, description="ISO-4217 code, e.g. USD")
|
|
32
|
+
po_number: Evidenced[str] | None = None
|
|
33
|
+
line_items: list[LineItem] = Field(default_factory=list)
|
|
34
|
+
subtotal: Evidenced[float] | None = None
|
|
35
|
+
tax: Evidenced[float] | None = None
|
|
36
|
+
total: Evidenced[float]
|
|
37
|
+
payment_terms: Evidenced[str] | None = None
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""The built-in point-of-sale receipt extraction template."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
from fieldproof.schemas.base import Evidenced
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ReceiptItem(BaseModel):
|
|
11
|
+
description: Evidenced[str]
|
|
12
|
+
quantity: Evidenced[float] | None = None
|
|
13
|
+
amount: Evidenced[float]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Receipt(BaseModel):
|
|
17
|
+
"""Point-of-sale receipt: merchant, items, tender."""
|
|
18
|
+
|
|
19
|
+
merchant_name: Evidenced[str]
|
|
20
|
+
transaction_date: Evidenced[str] = Field(description="ISO-8601 date, e.g. 2026-03-14")
|
|
21
|
+
items: list[ReceiptItem] = Field(default_factory=list)
|
|
22
|
+
subtotal: Evidenced[float] | None = None
|
|
23
|
+
tax: Evidenced[float] | None = None
|
|
24
|
+
total: Evidenced[float]
|
|
25
|
+
payment_method: Evidenced[str] | None = None
|
fieldproof/server/app.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""FastAPI app: upload a document, run extraction, serve the review UI and
|
|
2
|
+
results, export approved values.
|
|
3
|
+
|
|
4
|
+
Run with `fieldproof serve` (see `fieldproof.cli`), or directly with
|
|
5
|
+
`uvicorn fieldproof.server.app:app`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import csv
|
|
11
|
+
import io
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Annotated, Any
|
|
15
|
+
|
|
16
|
+
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
|
17
|
+
from fastapi.responses import JSONResponse, PlainTextResponse, Response
|
|
18
|
+
from fastapi.staticfiles import StaticFiles
|
|
19
|
+
from pydantic import BaseModel
|
|
20
|
+
|
|
21
|
+
from fieldproof import __version__
|
|
22
|
+
from fieldproof.document.loader import EmptyDocumentError, load_pdf
|
|
23
|
+
from fieldproof.document.render import render_page_png
|
|
24
|
+
from fieldproof.extract.anthropic_provider import AnthropicExtractor
|
|
25
|
+
from fieldproof.extract.base import (
|
|
26
|
+
ExtractionError,
|
|
27
|
+
ExtractionResult,
|
|
28
|
+
read_extraction_json,
|
|
29
|
+
validate_data,
|
|
30
|
+
)
|
|
31
|
+
from fieldproof.schemas import BUILTIN_SCHEMAS
|
|
32
|
+
from fieldproof.server.store import DocumentSession, ReviewState, store
|
|
33
|
+
from fieldproof.verify.engine import verify
|
|
34
|
+
|
|
35
|
+
app = FastAPI(title="fieldproof", version=__version__)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _find_static_dir() -> Path:
|
|
39
|
+
"""The built web UI, if present - not committed (it's build output), so
|
|
40
|
+
a fresh clone has neither candidate until `npm run build` is run in
|
|
41
|
+
web/. Checked in order: an explicit override, a copy already placed
|
|
42
|
+
next to this file (e.g. by packaging), and web/dist relative to the
|
|
43
|
+
repo checkout (the normal case for `pip install -e .` + `fieldproof
|
|
44
|
+
serve` from source)."""
|
|
45
|
+
if override := os.environ.get("FIELDPROOF_STATIC_DIR"):
|
|
46
|
+
return Path(override)
|
|
47
|
+
bundled = Path(__file__).parent / "static"
|
|
48
|
+
if (bundled / "index.html").exists():
|
|
49
|
+
return bundled
|
|
50
|
+
repo_dist = Path(__file__).resolve().parents[3] / "web" / "dist"
|
|
51
|
+
return repo_dist
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
#: When absent, "/" returns a short message instead of a 404, so a fresh
|
|
55
|
+
#: `git clone` isn't confusing to run before the UI has been built.
|
|
56
|
+
_STATIC_DIR = _find_static_dir()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _session_or_404(document_id: str) -> DocumentSession:
|
|
60
|
+
session = store.get(document_id)
|
|
61
|
+
if session is None:
|
|
62
|
+
raise HTTPException(status_code=404, detail=f"no document with id {document_id!r}")
|
|
63
|
+
return session
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@app.get("/api/schemas")
|
|
67
|
+
def list_schemas() -> dict[str, list[str]]:
|
|
68
|
+
return {"schemas": sorted(BUILTIN_SCHEMAS)}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@app.post("/api/documents")
|
|
72
|
+
async def upload_document(file: Annotated[UploadFile, File()]) -> dict[str, Any]:
|
|
73
|
+
pdf_bytes = await file.read()
|
|
74
|
+
try:
|
|
75
|
+
document = load_pdf(pdf_bytes, label=file.filename or "document.pdf")
|
|
76
|
+
except EmptyDocumentError as exc:
|
|
77
|
+
raise HTTPException(
|
|
78
|
+
status_code=422,
|
|
79
|
+
detail=f"{exc} (scanned/image-only PDFs need the optional OCR extra - see README)",
|
|
80
|
+
) from exc
|
|
81
|
+
except Exception as exc: # pdfplumber raises a variety of parse errors
|
|
82
|
+
raise HTTPException(status_code=422, detail=f"could not read PDF: {exc}") from exc
|
|
83
|
+
|
|
84
|
+
session = store.create(
|
|
85
|
+
filename=file.filename or "document.pdf", pdf_bytes=pdf_bytes, document=document
|
|
86
|
+
)
|
|
87
|
+
return _document_summary(session)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _document_summary(session: DocumentSession) -> dict[str, Any]:
|
|
91
|
+
return {
|
|
92
|
+
"id": session.id,
|
|
93
|
+
"filename": session.filename,
|
|
94
|
+
"page_count": session.document.page_count,
|
|
95
|
+
"pages": [
|
|
96
|
+
{"number": p.number, "width": p.width, "height": p.height}
|
|
97
|
+
for p in session.document.pages
|
|
98
|
+
],
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@app.get("/api/documents/{document_id}")
|
|
103
|
+
def get_document(document_id: str) -> dict[str, Any]:
|
|
104
|
+
return _document_summary(_session_or_404(document_id))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@app.get("/api/documents/{document_id}/pages/{page_number}.png")
|
|
108
|
+
def get_page_image(document_id: str, page_number: int) -> Response:
|
|
109
|
+
session = _session_or_404(document_id)
|
|
110
|
+
if not 1 <= page_number <= session.document.page_count:
|
|
111
|
+
raise HTTPException(status_code=404, detail=f"no page {page_number}")
|
|
112
|
+
png_bytes = render_page_png(session.pdf_bytes, page_number)
|
|
113
|
+
return Response(content=png_bytes, media_type="image/png")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@app.post("/api/documents/{document_id}/extract")
|
|
117
|
+
async def extract_document(
|
|
118
|
+
document_id: str,
|
|
119
|
+
schema_name: Annotated[str, Form(alias="schema")],
|
|
120
|
+
provider: Annotated[str, Form()] = "fixture",
|
|
121
|
+
fixture: Annotated[UploadFile | None, File()] = None,
|
|
122
|
+
) -> dict[str, Any]:
|
|
123
|
+
session = _session_or_404(document_id)
|
|
124
|
+
schema = BUILTIN_SCHEMAS.get(schema_name)
|
|
125
|
+
if schema is None:
|
|
126
|
+
raise HTTPException(
|
|
127
|
+
status_code=400,
|
|
128
|
+
detail=f"unknown schema {schema_name!r} - choose one of {sorted(BUILTIN_SCHEMAS)}",
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
if provider == "fixture":
|
|
132
|
+
if fixture is None:
|
|
133
|
+
raise HTTPException(status_code=400, detail="provider=fixture requires a fixture file")
|
|
134
|
+
source = fixture.filename or "the uploaded extraction"
|
|
135
|
+
try:
|
|
136
|
+
raw = read_extraction_json(await fixture.read(), source)
|
|
137
|
+
data = validate_data(raw.get("data", raw), schema, source)
|
|
138
|
+
except ExtractionError as exc:
|
|
139
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
140
|
+
model = raw.get("model")
|
|
141
|
+
extraction = ExtractionResult(
|
|
142
|
+
schema_name=schema.__name__,
|
|
143
|
+
data=data,
|
|
144
|
+
provider="fixture",
|
|
145
|
+
model=model if isinstance(model, str) else None,
|
|
146
|
+
)
|
|
147
|
+
elif provider == "anthropic":
|
|
148
|
+
if not os.environ.get("ANTHROPIC_API_KEY"):
|
|
149
|
+
raise HTTPException(
|
|
150
|
+
status_code=400,
|
|
151
|
+
detail="provider=anthropic requires ANTHROPIC_API_KEY to be set on the server",
|
|
152
|
+
)
|
|
153
|
+
try:
|
|
154
|
+
extraction = AnthropicExtractor().extract(session.document, schema)
|
|
155
|
+
except ExtractionError as exc:
|
|
156
|
+
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
|
157
|
+
else:
|
|
158
|
+
raise HTTPException(status_code=400, detail=f"unknown provider {provider!r}")
|
|
159
|
+
|
|
160
|
+
report = verify(extraction.data, session.document)
|
|
161
|
+
|
|
162
|
+
session.schema_name = schema_name
|
|
163
|
+
session.extraction = extraction
|
|
164
|
+
session.report = report
|
|
165
|
+
session.review = {f.path: ReviewState() for f in report.fields}
|
|
166
|
+
|
|
167
|
+
return _result_payload(session)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _result_payload(session: DocumentSession) -> dict[str, Any]:
|
|
171
|
+
assert session.extraction is not None and session.report is not None
|
|
172
|
+
return {
|
|
173
|
+
"schema": session.schema_name,
|
|
174
|
+
"provider": session.extraction.provider,
|
|
175
|
+
"model": session.extraction.model,
|
|
176
|
+
"data": session.extraction.data.model_dump(mode="json"),
|
|
177
|
+
"report": session.report.to_dict(),
|
|
178
|
+
"review": {
|
|
179
|
+
path: {"status": r.status, "edited_value": r.edited_value}
|
|
180
|
+
for path, r in session.review.items()
|
|
181
|
+
},
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@app.get("/api/documents/{document_id}/report")
|
|
186
|
+
def get_report(document_id: str) -> dict[str, Any]:
|
|
187
|
+
session = _session_or_404(document_id)
|
|
188
|
+
if session.report is None:
|
|
189
|
+
raise HTTPException(status_code=404, detail="no extraction has been run yet")
|
|
190
|
+
return _result_payload(session)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class ReviewRequest(BaseModel):
|
|
194
|
+
path: str
|
|
195
|
+
action: str # approve | edit | reject | reset
|
|
196
|
+
value: Any = None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@app.post("/api/documents/{document_id}/review")
|
|
200
|
+
def review_field(document_id: str, req: ReviewRequest) -> dict[str, Any]:
|
|
201
|
+
session = _session_or_404(document_id)
|
|
202
|
+
if session.report is None:
|
|
203
|
+
raise HTTPException(status_code=404, detail="no extraction has been run yet")
|
|
204
|
+
if req.path not in session.review:
|
|
205
|
+
raise HTTPException(status_code=404, detail=f"no field {req.path!r}")
|
|
206
|
+
|
|
207
|
+
if req.action == "approve":
|
|
208
|
+
session.review[req.path] = ReviewState(status="approved")
|
|
209
|
+
elif req.action == "edit":
|
|
210
|
+
session.review[req.path] = ReviewState(status="edited", edited_value=req.value)
|
|
211
|
+
elif req.action == "reject":
|
|
212
|
+
session.review[req.path] = ReviewState(status="rejected")
|
|
213
|
+
elif req.action == "reset":
|
|
214
|
+
session.review[req.path] = ReviewState(status="pending")
|
|
215
|
+
else:
|
|
216
|
+
raise HTTPException(status_code=400, detail=f"unknown action {req.action!r}")
|
|
217
|
+
|
|
218
|
+
state = session.review[req.path]
|
|
219
|
+
return {"path": req.path, "status": state.status, "edited_value": state.edited_value}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _exported_rows(session: DocumentSession) -> list[dict[str, Any]]:
|
|
223
|
+
assert session.report is not None
|
|
224
|
+
rows = []
|
|
225
|
+
for f in session.report.fields:
|
|
226
|
+
review = session.review.get(f.path, ReviewState())
|
|
227
|
+
if review.status == "rejected":
|
|
228
|
+
continue
|
|
229
|
+
value = review.edited_value if review.status == "edited" else f.value
|
|
230
|
+
rows.append(
|
|
231
|
+
{
|
|
232
|
+
"field": f.path,
|
|
233
|
+
"value": value,
|
|
234
|
+
"verification_status": f.status.value,
|
|
235
|
+
"review_status": review.status,
|
|
236
|
+
"page": f.page,
|
|
237
|
+
}
|
|
238
|
+
)
|
|
239
|
+
return rows
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@app.get("/api/documents/{document_id}/export.json")
|
|
243
|
+
def export_json(document_id: str) -> JSONResponse:
|
|
244
|
+
session = _session_or_404(document_id)
|
|
245
|
+
if session.report is None:
|
|
246
|
+
raise HTTPException(status_code=404, detail="no extraction has been run yet")
|
|
247
|
+
return JSONResponse(content=_exported_rows(session))
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@app.get("/api/documents/{document_id}/export.csv")
|
|
251
|
+
def export_csv(document_id: str) -> PlainTextResponse:
|
|
252
|
+
session = _session_or_404(document_id)
|
|
253
|
+
if session.report is None:
|
|
254
|
+
raise HTTPException(status_code=404, detail="no extraction has been run yet")
|
|
255
|
+
rows = _exported_rows(session)
|
|
256
|
+
buf = io.StringIO()
|
|
257
|
+
writer = csv.DictWriter(
|
|
258
|
+
buf, fieldnames=["field", "value", "verification_status", "review_status", "page"]
|
|
259
|
+
)
|
|
260
|
+
writer.writeheader()
|
|
261
|
+
writer.writerows(rows)
|
|
262
|
+
return PlainTextResponse(content=buf.getvalue(), media_type="text/csv")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
if _STATIC_DIR.is_dir() and (_STATIC_DIR / "index.html").exists():
|
|
266
|
+
app.mount("/", StaticFiles(directory=_STATIC_DIR, html=True), name="static")
|
|
267
|
+
else:
|
|
268
|
+
|
|
269
|
+
@app.get("/")
|
|
270
|
+
def no_ui() -> dict[str, str]:
|
|
271
|
+
return {
|
|
272
|
+
"message": (
|
|
273
|
+
"fieldproof API is running, but the review UI hasn't been built. "
|
|
274
|
+
"Run `npm ci && npm run build` in web/, or use the API directly - see /docs."
|
|
275
|
+
)
|
|
276
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&o(s)}).observe(document,{childList:!0,subtree:!0});function a(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=a(r);fetch(r.href,i)}})();async function b(e){if(!e.ok){const n=await e.json().catch(()=>({detail:e.statusText}));throw new Error(typeof n.detail=="string"?n.detail:e.statusText)}return await e.json()}class R{kind="live";async listSchemas(){return(await b(await fetch("/api/schemas"))).schemas}async uploadDocument(n){const a=new FormData;return a.append("file",n),b(await fetch("/api/documents",{method:"POST",body:a}))}pageImageUrl(n,a){return`/api/documents/${n}/pages/${a}.png`}async extract(n,a,o,r){const i=new FormData;return i.append("schema",a),i.append("provider",o),r&&i.append("fixture",r),b(await fetch(`/api/documents/${n}/extract`,{method:"POST",body:i}))}async review(n,a,o,r){return b(await fetch(`/api/documents/${n}/review`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:a,action:o,value:r??null})}))}exportUrl(n,a){return`/api/documents/${n}/export.${a}`}}function H(){return new R}function U(e){const n=[];for(const a of e.report.fields){const o=e.review[a.path]??{status:"pending",edited_value:null};o.status!=="rejected"&&n.push({field:a.path,value:o.status==="edited"?o.edited_value:a.value,verification_status:a.status,review_status:o.status,page:a.page})}return n}function B(e){const n="field,value,verification_status,review_status,page",a=r=>{const i=r==null?"":String(r);return/[",\n]/.test(i)?`"${i.replace(/"/g,'""')}"`:i},o=e.map(r=>[r.field,r.value,r.verification_status,r.review_status,r.page].map(a).join(","));return[n,...o].join(`\r
|
|
2
|
+
`)+`\r
|
|
3
|
+
`}function k(e,n,a){const o=new Blob([n],{type:a}),r=URL.createObjectURL(o),i=document.createElement("a");i.href=r,i.download=e,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}const J=["invoice","receipt","contract"],T=2,l=H(),t={document:null,extraction:null,currentPage:1,zoom:1,zoomIsAuto:!0,selectedPath:null,statusFilter:"all",searchQuery:"",editingPath:null,schemaName:"invoice",provider:"fixture",fixtureFile:null,busy:!1,samples:[]},I=document.getElementById("app");function c(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function V(e){return e==="needs_review"?"needs review":e}const Q=new Set(["amount","subtotal","tax","total","unit_price","total_contract_value"]);function W(e){const n=e.split(".").pop()??"";return Q.has(n.replace(/\[\d+\]$/,""))}function Z(e,n){if(W(e)){const a=typeof n=="number"?n:Number(n);if(Number.isFinite(a))return a.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}return String(n)}let P;function f(e){let n=document.getElementById("toast");n||(n=document.createElement("div"),n.id="toast",n.className="toast",n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),document.body.appendChild(n)),n.textContent=e,n.classList.add("is-visible"),window.clearTimeout(P),P=window.setTimeout(()=>n?.classList.remove("is-visible"),2600)}function z(){const e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function K(){const e=z()==="dark"?"light":"dark";document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem("fieldproof-theme",e)}catch{}h()}function h(){let e=document.querySelector(".topbar");e||(e=document.createElement("header"),e.className="topbar",I.prepend(e));const n=t.extraction?.report.counts,a=n?`<span class="brand-tag" aria-hidden="true">${n.verified} verified ${n.needs_review} review ${n.unsupported} unsupported</span>`:`<span class="brand-tag">${l.kind==="demo"?"static demo - fixture data":"grounded document review"}</span>`;e.innerHTML=`
|
|
4
|
+
<div class="brand">
|
|
5
|
+
<span class="brand-mark">fieldproof</span>
|
|
6
|
+
${a}
|
|
7
|
+
</div>
|
|
8
|
+
${Y()}
|
|
9
|
+
<div class="topbar-controls">
|
|
10
|
+
${l.kind==="live"&&t.document?'<button class="btn" id="new-document" type="button">New document</button>':""}
|
|
11
|
+
${t.extraction?X():""}
|
|
12
|
+
<button class="btn" id="theme-toggle" type="button" aria-label="Toggle dark mode">
|
|
13
|
+
${z()==="dark"?"☀️ Light":"☽ Dark"}
|
|
14
|
+
</button>
|
|
15
|
+
</div>
|
|
16
|
+
`,e.querySelector("#theme-toggle")?.addEventListener("click",K),e.querySelector("#export-json")?.addEventListener("click",()=>_("json")),e.querySelector("#export-csv")?.addEventListener("click",()=>_("csv")),e.querySelector("#new-document")?.addEventListener("click",G),e.querySelectorAll("[data-switch-sample]").forEach(o=>{o.addEventListener("click",()=>{window.location.hash=o.dataset.switchSample})})}function Y(){if(l.kind!=="demo"||t.samples.length===0)return"";const e=t.document?.id;return`
|
|
17
|
+
<nav class="sample-switch" aria-label="Sample documents">
|
|
18
|
+
${t.samples.map(n=>`<button class="sample-switch-btn ${n.id===e?"is-active":""}" type="button" data-switch-sample="${c(n.id)}" ${n.id===e?'aria-current="page"':""}>${c(n.label)}</button>`).join("")}
|
|
19
|
+
</nav>
|
|
20
|
+
`}function G(){t.document=null,t.extraction=null,t.selectedPath=null,t.fixtureFile=null,h(),u()}function X(){return`
|
|
21
|
+
<button class="btn" id="export-json" type="button">Export JSON</button>
|
|
22
|
+
<button class="btn" id="export-csv" type="button">Export CSV</button>
|
|
23
|
+
`}async function _(e){if(!t.document||!t.extraction)return;const n=t.document.filename.replace(/\.pdf$/i,"");if(l.kind==="live"){window.open(l.exportUrl(t.document.id,e),"_blank");return}const a=U(t.extraction);e==="json"?k(`${n}.fieldproof.json`,JSON.stringify(a,null,2),"application/json"):k(`${n}.fieldproof.csv`,B(a),"text/csv"),f(`Exported ${a.length} field${a.length===1?"":"s"}`)}async function E(){const e=w();if(l.kind==="demo"){t.samples.length===0&&(t.samples=await l.listSamples?.()??[]),e.innerHTML=`
|
|
24
|
+
<div class="start-state">
|
|
25
|
+
<div class="proof-ticks" aria-hidden="true">
|
|
26
|
+
<span class="proof-tick"><span class="proof-dot" style="background:var(--color-verified)"></span>verified</span>
|
|
27
|
+
<span class="proof-tick"><span class="proof-dot" style="background:var(--color-review)"></span>needs review</span>
|
|
28
|
+
<span class="proof-tick"><span class="proof-dot" style="background:var(--color-unsupported)"></span>unsupported</span>
|
|
29
|
+
</div>
|
|
30
|
+
<h1>Every field, traced to its source</h1>
|
|
31
|
+
<p>
|
|
32
|
+
Three synthetic sample documents, grounded and verified by fieldproof's real pipeline.
|
|
33
|
+
The candidate extractions are hand-written fixtures with planted errors, to show what the verifier catches -
|
|
34
|
+
a hallucinated PO number, a total that doesn't match its line items, and a misread date.
|
|
35
|
+
</p>
|
|
36
|
+
<div class="sample-grid">
|
|
37
|
+
${t.samples.map(o=>`<button class="btn btn-primary" type="button" data-sample="${c(o.id)}">${c(o.label)}</button>`).join("")}
|
|
38
|
+
</div>
|
|
39
|
+
</div>
|
|
40
|
+
`,e.querySelectorAll("[data-sample]").forEach(o=>{o.addEventListener("click",()=>S(o.dataset.sample))});return}e.innerHTML=`
|
|
41
|
+
<div class="start-state">
|
|
42
|
+
<h1>Upload a document</h1>
|
|
43
|
+
<p>PDF with a text layer. Extraction runs against the fixture provider or Claude, then every field is grounded and verified against the page.</p>
|
|
44
|
+
<label class="dropzone" id="dropzone" for="file-input">
|
|
45
|
+
Drop a PDF here, or click to choose one
|
|
46
|
+
</label>
|
|
47
|
+
<input type="file" id="file-input" accept="application/pdf" class="visually-hidden" />
|
|
48
|
+
</div>
|
|
49
|
+
`;const n=e.querySelector("#file-input"),a=e.querySelector("#dropzone");n.addEventListener("change",()=>{n.files?.[0]&&F(n.files[0])}),a.addEventListener("dragover",o=>{o.preventDefault(),a.classList.add("dragover")}),a.addEventListener("dragleave",()=>a.classList.remove("dragover")),a.addEventListener("drop",o=>{o.preventDefault(),a.classList.remove("dragover");const r=o.dataTransfer?.files?.[0];r&&F(r)})}async function S(e){if(!l.loadSample)return;let n;try{n=await l.loadSample(e)}catch(o){f(o instanceof Error?`Could not load ${e}: ${o.message}`:`Could not load ${e}`);return}t.document=n.document,t.extraction=n.extraction,t.currentPage=1,t.zoomIsAuto=!0,t.selectedPath=null,t.statusFilter="all",t.searchQuery="",h();const a=L().find(o=>o.status!=="verified");a?v(a.path,{scroll:!1}):u()}async function ee(){t.samples=await l.listSamples?.().catch(()=>[])??[];const e=decodeURIComponent(window.location.hash.slice(1)),n=t.samples.find(a=>a.id===e)??t.samples[0];if(!n){E();return}await S(n.id)}window.addEventListener("hashchange",()=>{if(l.kind!=="demo")return;const e=decodeURIComponent(window.location.hash.slice(1))||t.samples[0]?.id;e&&t.samples.some(n=>n.id===e)&&e!==t.document?.id&&S(e)});async function F(e){try{t.document=await l.uploadDocument(e),t.extraction=null,t.currentPage=1,t.zoomIsAuto=!0,h(),u()}catch(n){f(n instanceof Error?n.message:"Upload failed")}}function j(){const e=w();e.innerHTML=`
|
|
50
|
+
<div class="start-state">
|
|
51
|
+
<h1>${c(t.document.filename)}</h1>
|
|
52
|
+
<p>${t.document.page_count} page${t.document.page_count===1?"":"s"} loaded. Choose a schema and a provider to extract.</p>
|
|
53
|
+
<div style="display:flex; flex-direction:column; gap:12px; text-align:left; max-width:360px; margin:0 auto;">
|
|
54
|
+
<label>
|
|
55
|
+
Schema
|
|
56
|
+
<select class="select" id="schema-select" style="width:100%">
|
|
57
|
+
${J.map(i=>`<option value="${i}" ${i===t.schemaName?"selected":""}>${i}</option>`).join("")}
|
|
58
|
+
</select>
|
|
59
|
+
</label>
|
|
60
|
+
<label>
|
|
61
|
+
Provider
|
|
62
|
+
<select class="select" id="provider-select" style="width:100%">
|
|
63
|
+
<option value="fixture" ${t.provider==="fixture"?"selected":""}>fixture (replay stored JSON)</option>
|
|
64
|
+
<option value="anthropic" ${t.provider==="anthropic"?"selected":""}>anthropic (needs ANTHROPIC_API_KEY on the server)</option>
|
|
65
|
+
</select>
|
|
66
|
+
</label>
|
|
67
|
+
<label id="fixture-label" ${t.provider==="fixture"?"":"hidden"}>
|
|
68
|
+
Fixture JSON
|
|
69
|
+
<input type="file" class="text-input" id="fixture-input" accept="application/json" style="width:100%" />
|
|
70
|
+
</label>
|
|
71
|
+
<button class="btn btn-primary" id="run-extract" type="button" ${t.busy?"disabled":""}>
|
|
72
|
+
${t.busy?"Extracting…":"Run extraction"}
|
|
73
|
+
</button>
|
|
74
|
+
</div>
|
|
75
|
+
</div>
|
|
76
|
+
`;const n=e.querySelector("#schema-select"),a=e.querySelector("#provider-select"),o=e.querySelector("#fixture-label"),r=e.querySelector("#fixture-input");n.addEventListener("change",()=>{t.schemaName=n.value}),a.addEventListener("change",()=>{t.provider=a.value,o.hidden=t.provider!=="fixture"}),r.addEventListener("change",()=>{t.fixtureFile=r.files?.[0]??null}),e.querySelector("#run-extract").addEventListener("click",te)}async function te(){if(t.document){if(t.provider==="fixture"&&!t.fixtureFile){f("Choose a fixture JSON file first");return}t.busy=!0,j();try{t.extraction=await l.extract(t.document.id,t.schemaName,t.provider,t.fixtureFile),t.currentPage=1,t.zoomIsAuto=!0,h()}catch(e){f(e instanceof Error?e.message:"Extraction failed")}finally{t.busy=!1,u()}}}function w(){let e=document.querySelector(".workbench");return e||(e=document.createElement("main"),e.className="workbench",I.appendChild(e)),e}const A={unsupported:0,needs_review:1,verified:2};function L(){const e=t.extraction?.report.fields??[],n=t.searchQuery.trim().toLowerCase(),a=e.filter(o=>t.statusFilter!=="all"&&o.status!==t.statusFilter?!1:n?o.path.toLowerCase().includes(n)||String(o.value).toLowerCase().includes(n):!0);return t.statusFilter!=="all"?a:[...a].sort((o,r)=>A[o.status]-A[r.status])}function u(){if(!t.document){E();return}if(!t.extraction){j();return}const e=w();e.innerHTML=`
|
|
77
|
+
<section class="viewer-pane" aria-label="Document page">
|
|
78
|
+
<div class="viewer-toolbar">
|
|
79
|
+
<button class="btn" id="prev-page" type="button" ${t.currentPage<=1?"disabled":""}>←</button>
|
|
80
|
+
<span>Page ${t.currentPage} / ${t.document.page_count}</span>
|
|
81
|
+
<button class="btn" id="next-page" type="button" ${t.currentPage>=t.document.page_count?"disabled":""}>→</button>
|
|
82
|
+
<span style="flex:1"></span>
|
|
83
|
+
<button class="btn" id="zoom-out" type="button" aria-label="Zoom out">−</button>
|
|
84
|
+
<span id="zoom-label">${Math.round(t.zoom*100)}%</span>
|
|
85
|
+
<button class="btn" id="zoom-in" type="button" aria-label="Zoom in">+</button>
|
|
86
|
+
</div>
|
|
87
|
+
<div class="viewer-scroll" id="viewer-scroll">
|
|
88
|
+
${N()}
|
|
89
|
+
</div>
|
|
90
|
+
</section>
|
|
91
|
+
<section class="field-pane" aria-label="Extracted fields">
|
|
92
|
+
${ne()}
|
|
93
|
+
<ul class="field-list" id="field-list" tabindex="0" aria-label="Fields (arrow keys to navigate, a to approve, r to reject)">
|
|
94
|
+
${C()}
|
|
95
|
+
</ul>
|
|
96
|
+
</section>
|
|
97
|
+
`,oe(),t.zoomIsAuto&&q()}function q(){const e=document.getElementById("viewer-scroll"),n=t.document?.pages.find(d=>d.number===t.currentPage);if(!e||!n)return;const a=n.width*T,o=e.clientWidth-48,r=Math.min(1,Math.max(.35,o/a)),i=Math.round(r*100)/100;if(i===t.zoom)return;t.zoom=i,e.innerHTML=N(),e.scrollLeft=0,e.scrollTop=0,O();const s=document.getElementById("zoom-label");s&&(s.textContent=`${Math.round(t.zoom*100)}%`)}window.addEventListener("resize",()=>{t.zoomIsAuto&&q()});function N(){const e=t.document.pages.find(s=>s.number===t.currentPage),n=T*t.zoom,a=Math.round(e.width*n),o=Math.round(e.height*n),i=(t.extraction?.report.fields??[]).filter(s=>s.page===t.currentPage).flatMap(s=>s.rects.map(d=>({rect:d,field:s}))).map(({rect:s,field:d})=>{const p=s.x0*n,g=s.top*n,$=(s.x1-s.x0)*n,D=(s.bottom-s.top)*n;return`<div class="highlight-rect ${d.path===t.selectedPath?"is-active":""}" data-status="${d.status}" data-path="${c(d.path)}"
|
|
98
|
+
style="left:${p}px; top:${g}px; width:${$}px; height:${D}px"
|
|
99
|
+
title="${c(d.path)}"></div>`}).join("");return`
|
|
100
|
+
<div class="page-frame" id="page-frame" style="width:${a}px; height:${o}px;">
|
|
101
|
+
<img src="${l.pageImageUrl(t.document.id,t.currentPage)}" width="${a}" height="${o}" alt="Page ${t.currentPage} of ${c(t.document.filename)}" />
|
|
102
|
+
${i}
|
|
103
|
+
</div>
|
|
104
|
+
`}function ne(){const e=t.extraction.report.counts,n=(a,o,r)=>`
|
|
105
|
+
<button class="count-chip ${t.statusFilter===a?"is-active":""}" data-status-filter="${a}"
|
|
106
|
+
data-status="${a==="all"?"":a}" type="button">
|
|
107
|
+
${c(o)} ${r}
|
|
108
|
+
</button>
|
|
109
|
+
`;return`
|
|
110
|
+
<div class="field-pane-header">
|
|
111
|
+
<div class="counts-strip">
|
|
112
|
+
${n("all","All",t.extraction.report.fields.length)}
|
|
113
|
+
${n("verified","Verified",e.verified)}
|
|
114
|
+
${n("needs_review","Needs review",e.needs_review)}
|
|
115
|
+
${n("unsupported","Unsupported",e.unsupported)}
|
|
116
|
+
</div>
|
|
117
|
+
<div class="filter-row">
|
|
118
|
+
<input class="text-input" id="search-input" type="search" placeholder="Search fields…" value="${c(t.searchQuery)}" />
|
|
119
|
+
</div>
|
|
120
|
+
${l.kind==="demo"?'<p class="demo-note">Synthetic document. The extraction is a hand-written fixture with planted errors, grounded and verified by the real pipeline. Flagged fields come first; select one to see its evidence on the page.</p>':""}
|
|
121
|
+
</div>
|
|
122
|
+
`}function C(){const e=L();return e.length===0?'<li class="empty-filtered">No fields match this filter.</li>':e.map(n=>ae(n)).join("")}function ae(e){const n=t.extraction.review[e.path]??{status:"pending",edited_value:null},a=e.path===t.selectedPath,o=n.status==="edited"?n.edited_value:e.value,r=t.editingPath===e.path,i=e.reasons.length>0?`<ul class="field-reasons">${e.reasons.map(p=>`<li>${c(p)}</li>`).join("")}</ul>`:"",s=e.matched_text?`<div class="field-evidence">“${c(e.matched_text)}”${e.match_score!==null&&e.match_score<100?` <span style="opacity:.7">(${Math.round(e.match_score)}% match)</span>`:""}</div>`:"",d=r?`<div class="edit-row">
|
|
123
|
+
<input class="text-input" id="edit-input-${c(e.path)}" value="${c(o)}" />
|
|
124
|
+
<button class="btn btn-primary" type="button" data-save="${c(e.path)}">Save</button>
|
|
125
|
+
<button class="btn" type="button" data-cancel-edit>Cancel</button>
|
|
126
|
+
</div>`:"";return`
|
|
127
|
+
<li class="field-row ${a?"is-selected":""}" data-path="${c(e.path)}" aria-current="${a?"true":"false"}">
|
|
128
|
+
<div class="field-row-top">
|
|
129
|
+
<span class="field-path">${c(e.path)}</span>
|
|
130
|
+
<span class="status-chip" data-status="${e.status}">${V(e.status)}</span>
|
|
131
|
+
</div>
|
|
132
|
+
<div class="field-value ${n.status==="edited"?"is-edited":""}">${c(Z(e.path,o))}</div>
|
|
133
|
+
${n.status!=="pending"?`<span class="review-badge">${n.status}</span>`:""}
|
|
134
|
+
${i}
|
|
135
|
+
${s}
|
|
136
|
+
${r?d:`<div class="field-actions">
|
|
137
|
+
<button class="btn" type="button" data-approve="${c(e.path)}">Approve</button>
|
|
138
|
+
<button class="btn" type="button" data-edit="${c(e.path)}">Edit</button>
|
|
139
|
+
<button class="btn" type="button" data-reject="${c(e.path)}">Reject</button>
|
|
140
|
+
${n.status!=="pending"?`<button class="btn" type="button" data-reset="${c(e.path)}">Reset</button>`:""}
|
|
141
|
+
</div>`}
|
|
142
|
+
</li>
|
|
143
|
+
`}function O(){document.querySelectorAll(".highlight-rect").forEach(e=>{e.addEventListener("click",()=>v(e.dataset.path,{pulse:!0})),e.addEventListener("mouseenter",()=>M(e.dataset.path,!0)),e.addEventListener("mouseleave",()=>M(e.dataset.path,!1))})}function oe(){const e=w();e.querySelector("#prev-page")?.addEventListener("click",()=>{t.currentPage=Math.max(1,t.currentPage-1),u()}),e.querySelector("#next-page")?.addEventListener("click",()=>{t.currentPage=Math.min(t.document.page_count,t.currentPage+1),u()}),e.querySelector("#zoom-in")?.addEventListener("click",()=>{t.zoomIsAuto=!1,t.zoom=Math.min(3,Math.round((t.zoom+.25)*100)/100),u()}),e.querySelector("#zoom-out")?.addEventListener("click",()=>{t.zoomIsAuto=!1,t.zoom=Math.max(.35,Math.round((t.zoom-.25)*100)/100),u()}),O(),e.querySelectorAll(".count-chip").forEach(o=>{o.addEventListener("click",()=>{t.statusFilter=o.dataset.statusFilter??"all",u()})});const n=e.querySelector("#search-input");n?.addEventListener("input",()=>{t.searchQuery=n.value,y()});const a=e.querySelector("#field-list");a.addEventListener("click",o=>re(o)),a.addEventListener("keydown",o=>se(o))}function re(e){const n=e.target,a=n.closest("[data-approve]"),o=n.closest("[data-edit]"),r=n.closest("[data-reject]"),i=n.closest("[data-reset]"),s=n.closest("[data-save]"),d=n.closest("[data-cancel-edit]"),p=n.closest(".field-row");if(a)return void m(a.dataset.approve,"approve");if(r)return void m(r.dataset.reject,"reject");if(i)return void m(i.dataset.reset,"reset");if(o){t.editingPath=o.dataset.edit,y();return}if(d){t.editingPath=null,y();return}if(s){const g=s.dataset.save,$=document.getElementById(`edit-input-${ie(g)}`);m(g,"edit",$?.value??""),t.editingPath=null;return}p&&v(p.dataset.path,{pulse:!0})}function ie(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function se(e){if(e.target.tagName==="INPUT")return;const a=L();if(a.length===0)return;const o=a.findIndex(r=>r.path===t.selectedPath);if(e.key==="ArrowDown"||e.key==="j"){e.preventDefault();const r=a[Math.min(a.length-1,o+1)]??a[0];v(r.path,{pulse:!0})}else if(e.key==="ArrowUp"||e.key==="k"){e.preventDefault();const r=a[Math.max(0,o-1)]??a[0];v(r.path,{pulse:!0})}else e.key==="a"&&t.selectedPath?m(t.selectedPath,"approve"):e.key==="r"&&t.selectedPath&&m(t.selectedPath,"reject")}function v(e,n={}){const a=t.extraction.report.fields.find(r=>r.path===e);if(t.selectedPath=e,a?.page&&(t.currentPage=a.page),u(),n.scroll===!1)return;const o=document.querySelector(`.highlight-rect[data-path="${x(e)}"]`);o?.scrollIntoView({block:"center",inline:"center",behavior:"smooth"}),n.pulse&&o&&(window.matchMedia("(prefers-reduced-motion: reduce)").matches||(o.classList.add("is-pulsing"),window.setTimeout(()=>o.classList.remove("is-pulsing"),1900))),document.querySelector(`.field-row[data-path="${x(e)}"]`)?.scrollIntoView({block:"nearest"})}function x(e){return e.replace(/"/g,'\\"')}function M(e,n){document.querySelector(`.field-row[data-path="${x(e)}"]`)?.classList.toggle("is-hovered",n)}async function m(e,n,a){if(t.document)try{const o=await l.review(t.document.id,e,n,a);t.extraction.review[e]=o,y()}catch(o){f(o instanceof Error?o.message:"Couldn't update review status")}}function y(){const e=document.getElementById("field-list");e&&(e.innerHTML=C())}h();l.kind==="demo"?ee():E();
|
|
144
|
+
//# sourceMappingURL=index-BLATbujI.js.map
|