A lightweight Python validation and human-in-the-loop review harness for invoice and receipt extraction workflows. Built to demonstrate how deterministic business-rule checks (check() / validate()) and stateful review gates (ReviewStore) prevent silent LLM/OCR extraction errors from corrupting downstream business systems.
When engineering teams connect LLM extraction or OCR pipelines to accounting, ERP, or webhook automations, JSON Schema validity is often mistaken for data correctness.
In our held-out evaluation on 80 multi-layout, multi-line invoice documents (reports/phase2/test_cpu_20261029T062325Z/summary.json):
- A schema-constrained local model (
qwen3:0.6b) returned 80 / 80 (100.0%) schema-valid JSON objects. - It extracted 227 / 280 (
81.07%) top-level scalar fields (invoice_number,invoice_date,subtotal,tax,total, etc.) correctly. - However, it achieved only 1 / 80 (
1.25%) complete record accuracy because multi-line item tables (line_items[]) frequently suffered from line-item truncation or arithmetic drift (1 / 80exact line-item sets). - The critical reliability outcome: The deterministic validation gate (
check()inpilot_pipeline.py) flagged 79 / 79 (100.0%) of the defective model outputs, routing every incomplete or inconsistent extraction to human review instead of allowing silent data corruption.
| Evaluation Cohort | Input Complexity | Schema-Valid JSON | Scalar Field Accuracy | Complete Record Accuracy | Defective Outputs Caught by Validator |
|---|---|---|---|---|---|
Phase 1 (data/test.jsonl, n=24, qwen2.5:1.5b structured) |
Header-only UTF-8 text (clean, missing date, bad math, prompt-injection notes) | 24 / 24 (100.0%) |
155 / 168 (92.26%) |
22 / 24 (91.67% correct review decisions) |
6 / 6 (100.0% anomalies flagged, 0 false passes) |
Phase 2 (test_cpu_20261029T062325Z, n=80, qwen3:0.6b) |
Multi-item PDF/PNG/degraded scans (EN + TH) | 80 / 80 (100.0%) |
227 / 280 (81.07%) |
1 / 80 (1.25%) |
79 / 79 (100.0% defective records caught) |
This repository implements a verifiable two-stage reliability layer around candidate extractions:
- Bounded Ingestion & Candidate Extraction (
pilot_pipeline.py,invoice_demo.py):- Accepts UTF-8 text (
invoice_demo.py) or PDF/PNG/JPEG documents (pilot_pipeline.pywith10 MiBsize limit,5-page PDF ceiling,20M-pixel cap, and magic-byte header sniffing). - Runs either a fast deterministic regex/rule baseline (
rules) or a local Ollama model (structuredwith JSON Schema enforcement) and normalizes monetary and date strings (normalize_money(),normalize_date()).
- Accepts UTF-8 text (
- Deterministic Business-Rule Gate (
pilot_pipeline.py :: check(),invoice_demo.py :: validate()):- Schema & Type Contract:
jsonschema(Draft202012Validator) withadditionalProperties: falseand strict decimal formatting. - Calendar & Currency Rules: Verifies real ISO calendar dates (
YYYY-MM-DD, including Thai Buddhist year conversion) and 3-letter ISO currency codes ([A-Z]{3}). - Cross-Field Math Reconciliation: Verifies
abs(subtotal + tax - discount - total) <= 0.01on invoice headers andabs(quantity * unit_price - amount) <= 0.01on every line item. - Source-Text Grounding: Verifies that extracted supplier names, invoice numbers, dates, currencies, and monetary amounts actually appear in the recognized source text (rejecting fabricated numbers that merely balance the equation).
- OCR Confidence & Adversarial Note Detection: Flags low OCR confidence (
< 85) and detects prompt-injection strings or VAT-inclusion ambiguity inside document notes.
- Schema & Type Contract:
- Human-in-the-Loop Review & Approval Store (
pilot_store.py :: ReviewStore,pilot_server.py,pilot.html):- Persists each document in an isolated workspace with SHA-256 source-file hashing (
original_sha256), immutable revision history (history/revision_XXXX.json), and atomic JSON state writes. - Blocks approval (
approve()) whenevercheck()reports anyseverity == "error"issue, and requires explicit reviewer confirmation (confirmed=True,warnings_confirmed=True). - Automatically revokes approval (
status -> "DRAFT") and incrementsrevisionif an operator edits a field (save()). - Enforces optimistic concurrency (
require_revision()/HTTP 409) and neutralizes spreadsheet formula injection (=,+,-,@,\t,\r) prior to CSV/JSON export.
- Persists each document in an isolated workspace with SHA-256 source-file hashing (
See docs/ARCHITECTURE_AND_VALIDATION.md for detailed rule specifications and state transitions.
.
├── invoice_demo.py # Phase 1 header schema, deterministic validator (validate) & loopback HTTP demo
├── pilot_pipeline.py # Phase 2 multi-format ingestion (PDF/PNG/JPEG), OCR routing & check() validator
├── pilot_store.py # Stateful ReviewStore, SHA-256 tamper checks, revision locks & CSV/JSON export
├── pilot_server.py # Loopback HTTP server for the human-in-the-loop review queue
├── pilot.html # Single-page operator review UI (side-by-side preview, issues & approval controls)
├── benchmark.py # Phase 1 benchmark runner & metric evaluator
├── make_dataset.py # Deterministic CC0 synthetic dataset generator & SHA-256 manifest builder
├── phase2_evaluate.py # Phase 2 multi-layout evaluation harness & field/item scoring
├── phase2_analyze.py # Frozen snapshot verifier & paired failure-mode analyzer
├── src/workflow_validation/ # Clean Python package re-exporting core validation & store primitives
├── examples/run_validation_demo.py # Self-contained offline demo of check() + ReviewStore approval lifecycle
├── tests/ # 35 unit and HTTP integration tests across 8 test modules
├── data/ # CC0-1.0 synthetic dev/test datasets + sample fixtures
├── reports/ # Frozen aggregate benchmark summaries (Phase 1 & Phase 2)
└── docs/ # Architecture, validation rules, and reproducibility documentation
No external API keys, database servers, or GPU hardware are required to run the core test suite and validation demo:
# 1. Create virtual environment and install dependencies
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe -m pip install pypdf pypdfium2 Pillow
# 2. Run all 35 automated unit and HTTP integration tests
.\.venv\Scripts\python.exe -m unittest discover -s tests -v
# 3. Run the end-to-end validation & human-approval lifecycle demo
.\.venv\Scripts\python.exe examples\run_validation_demo.pyTo launch the local human-in-the-loop review web application (bound strictly to 127.0.0.1):
.\.venv\Scripts\python.exe pilot_server.py --host 127.0.0.1 --port 8766Then open http://127.0.0.1:8766 in a browser to upload a PDF/PNG/JPEG document, inspect deterministic validation flags, edit fields, approve records, and export sanitized CSV/JSON.
This repository is an engineering portfolio prototype and validation testbed, not a drop-in enterprise SaaS platform:
- Multi-Line Extraction Accuracy Requires Stronger Models or Layout Parsers: As recorded in
reports/phase2/test_cpu_20261029T062325Z/summary.json, small CPU-bound local models (0.6B–1.7Bparameters) and simple regex rules achieve only0%–1.25%exact line-item table accuracy on complex multi-item PDFs and noisy scans. The value demonstrated here is 100% defect interception (79/79) and structured human review, not unsolved zero-shot OCR accuracy. - Single-Process Local Storage:
ReviewStoreuses atomic file-per-document JSON persistence suitable for local evaluation, CLI diagnostics, or single-operator review queues. High-concurrency multi-user deployments should back the state machine with PostgreSQL or SQLite WAL transactions. - Loopback-Only HTTP Server:
pilot_server.pyandinvoice_demo.pydo not include user authentication or TLS termination and must remain bound to127.0.0.1.
- Code: Released under the MIT License.
- Synthetic Data (
data/): Dedicated to the public domain underCC0-1.0(seedata/PROVENANCE.md).