Skip to content

About

Deterministic Python validation (check()) and human-in-the-loop review store (ReviewStore) for AI/OCR invoice workflows — 35 unit/HTTP tests, SHA-256 tamper locks, CSV formula-injection guards, and reproducible synthetic benchmarks.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Making AI-Assisted Document Workflows Safer Through Validation and Human Review

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.


1. The Workflow Problem

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 / 80 exact line-item sets).
  • The critical reliability outcome: The deterministic validation gate (check() in pilot_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)

2. System Architecture

This repository implements a verifiable two-stage reliability layer around candidate extractions:

  1. Bounded Ingestion & Candidate Extraction (pilot_pipeline.py, invoice_demo.py):
    • Accepts UTF-8 text (invoice_demo.py) or PDF/PNG/JPEG documents (pilot_pipeline.py with 10 MiB size 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 (structured with JSON Schema enforcement) and normalizes monetary and date strings (normalize_money(), normalize_date()).
  2. Deterministic Business-Rule Gate (pilot_pipeline.py :: check(), invoice_demo.py :: validate()):
    • Schema & Type Contract: jsonschema (Draft202012Validator) with additionalProperties: false and 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.01 on invoice headers and abs(quantity * unit_price - amount) <= 0.01 on 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.
  3. 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()) whenever check() reports any severity == "error" issue, and requires explicit reviewer confirmation (confirmed=True, warnings_confirmed=True).
    • Automatically revokes approval (status -> "DRAFT") and increments revision if 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.

See docs/ARCHITECTURE_AND_VALIDATION.md for detailed rule specifications and state transitions.


3. Repository Structure

.
├── 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

4. Quick Start (Windows PowerShell)

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.py

To 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 8766

Then 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.


5. Honest Limitations & Prototype Scope

This repository is an engineering portfolio prototype and validation testbed, not a drop-in enterprise SaaS platform:

  1. 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.7B parameters) and simple regex rules achieve only 0%–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.
  2. Single-Process Local Storage: ReviewStore uses 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.
  3. Loopback-Only HTTP Server: pilot_server.py and invoice_demo.py do not include user authentication or TLS termination and must remain bound to 127.0.0.1.

6. License

About

Deterministic Python validation (check()) and human-in-the-loop review store (ReviewStore) for AI/OCR invoice workflows — 35 unit/HTTP tests, SHA-256 tamper locks, CSV formula-injection guards, and reproducible synthetic benchmarks.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages