Skip to content
,
Vision, OCR, and document extraction from scratch · Part 6

How to have people check AI-extracted document data before you trust it

10 min read
oc6 cover

Do not expect software to read every document perfectly on its own. Check each result with several signals at once, and send anything doubtful to a person before it reaches the books.

Say your team is proud that almost every invoice now posts without anyone touching it. Then one misread international bank account number (IBAN), the account number used for transfers between countries, sends a payment to the wrong company. A few extra checks and a good review screen would have stopped it.

Why full automation on documents is a myth

In product demos, document AI vendors love to promise “lights-out, fully hands-off automation.” Real documents are messy. Receipts get crumpled and faded. Pages are tilted or smudged, people write in the margins, and now and then someone forges one. Even an excellent model with 99% character accuracy will still average about ten misread characters on a thousand-character tax return.

Every automated document pipeline (a chain of automated steps that moves and cleans data) has to balance two things that pull against each other:

  1. The straight-through rate. The share of incoming documents that get processed and posted straight to your systems with no human involved at all. A higher rate here means lower labor cost and faster turnaround.
  2. The error escape rate. The share of documents where a wrong or faked value slips through unnoticed and lands in your systems. A higher rate here means credit losses, compliance penalties, and customers walking away.

Figure 1 contrasts the real risk of unfiltered full automation against a modern setup that routes only the risky cases to a human.

Automating every document compared with routing only risky documents to a person
Figure 1: Unfiltered full automation compared with a setup that routes only genuinely risky documents to a human reviewer.

If every document posts with no checks, every mistake the model makes reaches your systems. A better setup sorts documents first. Clean ones, where the math adds up and the image looks normal, post on their own. The doubtful ones go to a person. How many fall into each group depends on your documents, so measure it on your own sample.

Why one confidence number isn’t enough

A common mistake is to trust one confidence number from a model. A raw model probability is notoriously unreliable: a model can be 99% “confident” even while it’s hallucinating or misreading damaged text. To build a trustworthy check, you need to combine four separate, independent signals into one composite confidence score:

1. How sure the model is about each character

A probability score for every individual character. If any single character drops below an 85% confidence threshold, like an ambiguous 8 versus B, or 0 versus O, the whole field gets flagged.

2. Whether the value sits where it should

Checking a value’s position against where similar values normally sit on this kind of document. If an extracted tax total sits eighty pixels further left than usual, that’s a red flag.

3. Whether the math actually adds up

A simple yes-or-no check. If the income lines do not add up to the reported total, to the penny, confidence drops to zero. It does not matter how sure the model claims to be.

4. Signs the image itself was tampered with

Checking the image for blur, uneven sharpness, or text that does not sit on a straight line. These can be signs of a cut-and-paste forgery.

Figure 2 shows the ongoing quality cycle that connects automated extraction, multi-signal scoring, human review, and retraining the model.

A review cycle: score with several signals, route, review flagged fields, and learn from corrections
Figure 2: A four-stage cycle: score with multiple signals, route based on risk, have a human review what’s flagged, and feed those corrections back into the model.

Look closely at that fourth stage, the feedback loop. In many setups, a reviewer fixes a number in a spreadsheet, and the fix is lost. Nothing improves. A better setup saves every correction, such as a fixed tax ID, as a labeled example. Those examples are used to improve your rules and models over time.

Designing a review screen people can actually use all day

When review fails, the reviewer is rarely the problem. It’s because the review software itself is painful to use. Switching back and forth between a PDF viewer and a cramped form wears people out. Tired reviewers miss things.

A genuinely efficient review screen follows four rules:

  1. Show the document and the data side by side. The actual document sits on the left, and the editable fields sit on the right. Clicking into any field on the right automatically pans and zooms the document on the left to show exactly where that value came from.
  2. Highlight problems visually. Clean, high-confidence fields get a subtle green marker. Mismatches and low-confidence fields get a clear, prominent orange box with a plain-language note, like “math mismatch: subtotal is off by $120.00.”
  3. Let people work entirely from the keyboard. A skilled reviewer moves fast when their hands never leave the keyboard. Give them shortcuts: Tab jumps to the next flagged item, Enter accepts the highlighted value, and a couple of number keys trigger common rejection reasons.
  4. Only show what actually needs review. Never make a reviewer look at all sixty fields on a complex tax return. Show only the fields that failed a check. That makes each review much faster.

Figure 3 shows the full routing setup that puts these ideas into practice across a real production system.

How documents flow through review: extract, score, route, and people
Figure 3: The full routing setup, from automated extraction and multi-signal scoring through triage routing and a reviewer’s exception queue.

Comparing review strategies

Choosing a review strategy means weighing labor cost against real financial and compliance risk. Figure 4 compares four common approaches on error rate, how much gets automated, labor needed, and how defensible each one is to a regulator.

Four ways to review documents: route by risk, automate everything, random sample, and type it twice
Figure 4: Comparing four review strategies on error rate, how much gets automated, and overall risk.

Here’s how the four approaches actually compare in production:

ApproachErrors that slip throughHuman effortThe trade-off
Route by risk.Low, if the checks are good.Only for flagged fields.Effort goes where the risk is.
Automate everything.Every model error.None.Cheap until a costly mistake.
Random sample checks.Most individual errors.A small share of documents.Shows trends, misses single mistakes.
Type everything twice.Very few.All documents, twice.Accurate but slow and costly.
Table 1: Comparing review strategies in general terms. Measure error rates on your own documents.

A hands-on example: a multi-signal check in Python

Here’s how to build a production-ready verification check in Python. It takes fields read by text recognition, often called OCR (optical character recognition). It checks each character’s confidence, where each value sits, and whether the math balances. Then it approves the document, sends it for review, or rejects it.

First, install Pydantic, the one outside library (a package of ready-made code) this example needs.

pip install pydantic

The script below defines the data structures, runs the multi-signal checks, and prepares what the reviewer’s screen needs when something looks doubtful.

from decimal import Decimal
from typing import List, Dict, Optional, Any
from enum import Enum
from pydantic import BaseModel, Field

class RoutingAction(str, Enum):
    AUTO_APPROVE = "AUTO_APPROVE"
    HUMAN_REVIEW = "HUMAN_REVIEW"
    HARD_REJECT = "HARD_REJECT"

class ExtractedField(BaseModel):
    field_name: str
    value: Any
    raw_text: str
    ocr_confidence: float = Field(ge=0.0, le=1.0, description="Raw OCR character probability")
    spatial_distance_px: float = Field(description="Distance in pixels from anchor label")
    bbox: List[float] # [x0, top, x1, bottom]

class DocumentVerificationPayload(BaseModel):
    document_id: str
    document_type: str # 'W2', '1040', 'INVOICE'
    fields: Dict[str, ExtractedField]
    reported_subtotal: Decimal
    reported_tax: Decimal
    reported_total: Decimal
    calculated_subtotal: Decimal

class VerificationResult(BaseModel):
    document_id: str
    action: RoutingAction
    composite_score: float
    reasons: List[str]
    flagged_fields: List[str]
    auditor_payload: Optional[Dict[str, Any]] = None

def evaluate_document_gate(payload: DocumentVerificationPayload) -> VerificationResult:
    reasons = []
    flagged_fields = []

    # Signal 1: Token OCR Confidence Threshold
    min_ocr_threshold = 0.90
    for fname, f in payload.fields.items():
        if f.ocr_confidence < min_ocr_threshold:
            flagged_fields.append(fname)
            reasons.append(f"Low OCR confidence on field '{fname}' ({f.ocr_confidence * 100:.1f}%)")

    # Signal 2: Spatial Proximity & Alignment Check
    max_spatial_distance = 220.0
    for fname, f in payload.fields.items():
        if f.spatial_distance_px > max_spatial_distance:
            flagged_fields.append(fname)
            reasons.append(f"Excessive spatial distance for field '{fname}' ({f.spatial_distance_px:.1f}px from anchor)")

    # Signal 3: Deterministic Arithmetic Gauntlet
    math_passed = True
    subtotal_delta = abs(payload.reported_subtotal - payload.calculated_subtotal)
    if subtotal_delta > Decimal("0.02"):
        math_passed = False
        reasons.append(f"Subtotal arithmetic mismatch: Calculated {payload.calculated_subtotal}, reported {payload.reported_subtotal}")
        flagged_fields.extend(["reported_subtotal", "calculated_subtotal"])

    expected_total = payload.reported_subtotal + payload.reported_tax
    total_delta = abs(expected_total - payload.reported_total)
    if total_delta > Decimal("0.02"):
        math_passed = False
        reasons.append(f"Grand total balance failure: {payload.reported_subtotal} + {payload.reported_tax} != {payload.reported_total}")
        flagged_fields.append("reported_total")

    # Calculate Composite Confidence Score
    avg_ocr = sum(f.ocr_confidence for f in payload.fields.values()) / max(1, len(payload.fields))
    math_multiplier = 1.0 if math_passed else 0.40 # Heavy penalty for math failures
    composite_score = round(avg_ocr * math_multiplier, 3)

    # Step 4: Routing Decision Gate
    if composite_score >= 0.95 and math_passed and len(flagged_fields) == 0:
        action = RoutingAction.AUTO_APPROVE
    elif composite_score < 0.60 or len(flagged_fields) > 5:
        action = RoutingAction.HARD_REJECT
        reasons.append("Document quality severely degraded or corrupted")
    else:
        action = RoutingAction.HUMAN_REVIEW

    # Step 5: Construct Ergonomic Auditor Payload if Review Required
    auditor_payload = None
    if action == RoutingAction.HUMAN_REVIEW:
        auditor_payload = {
            "document_id": payload.document_id,
            "total_fields": len(payload.fields),
            "exceptions_to_review": [
                {
                    "field_name": fn,
                    "extracted_value": payload.fields[fn].value,
                    "confidence": payload.fields[fn].ocr_confidence,
                    "crop_coordinates": payload.fields[fn].bbox,
                    "problem_tag": [r for r in reasons if fn in r]
                }
                for fn in set(flagged_fields) if fn in payload.fields
            ],
            "keyboard_shortcuts": {
                "accept": "Enter",
                "edit": "Tab",
                "reject": "Shift+Delete"
            }
        }

    return VerificationResult(
        document_id=payload.document_id,
        action=action,
        composite_score=composite_score,
        reasons=reasons,
        flagged_fields=list(set(flagged_fields)),
        auditor_payload=auditor_payload
    )

# Example Execution:
sample_payload = DocumentVerificationPayload(
    document_id="W2-2026-88412",
    document_type="W2",
    fields={
        "wages_tips": ExtractedField(
            field_name="wages_tips",
            value=Decimal("84500.00"),
            raw_text="$84,500.00",
            ocr_confidence=0.98,
            spatial_distance_px=45.0,
            bbox=[120.0, 240.0, 260.0, 265.0]
        ),
        "federal_tax_withheld": ExtractedField(
            field_name="federal_tax_withheld",
            value=Decimal("14200.00"),
            raw_text="$14,200.00",
            ocr_confidence=0.82, # Low confidence!
            spatial_distance_px=52.0,
            bbox=[120.0, 280.0, 260.0, 305.0]
        )
    },
    reported_subtotal=Decimal("84500.00"),
    reported_tax=Decimal("14200.00"),
    reported_total=Decimal("98700.00"),
    calculated_subtotal=Decimal("84500.00")
)

result = evaluate_document_gate(sample_payload)
print(f"Document [{result.document_id}] Action: {result.action.value}")
print(f"Composite Confidence: {result.composite_score}")
print(f"Reasons: {result.reasons}")
if result.auditor_payload:
    print(f"Dispatched {len(result.auditor_payload['exceptions_to_review'])} exception(s) to Auditor Workstation.")

Notice exactly how precise this check is. The document doesn’t get dumped into a generic pile for someone to sort through. The system immediately pinpoints that the federal_tax_withheld field had a confidence dip, down to 0.82. It stops the document, packages up the exact coordinates of that one field, and sends only that single field to a reviewer’s screen. The reviewer checks the actual box on the page with one tap of Enter, and the transaction clears for posting.

Key takeaways

  • Give up on 100% automation as a goal. Route by risk instead. Let clean files post on their own, and send doubtful ones to a person.
  • Combine several signals, never just one. Never trust a raw model confidence number by itself. Combine character-level confidence, position checks, and simple arithmetic checks.
  • Treat a math mismatch as an automatic red flag. If an invoice subtotal or tax calculation doesn’t balance exactly, drop the confidence immediately and force a human review.
  • Design the review screen around real humans. Show reviewers the exact spot on the document right next to the editable field. Support full keyboard use so reviews stay quick.
  • Capture every human correction. Log each fix as a training example to keep improving your local models and rules week over week.

A later post covers finding and removing secrets and personal details, and processing documents securely without the internet.

← All series & guides

Series

Vision, OCR, and document extraction from scratch

6 parts

This path is for you if a photo of a receipt or a scanned contract needs to become text you can check, not a guess in a chat. It is the vision and document path: what the model can read, and where a human still has to look. No part is live on this page yet. Start with Practical AI for what not to paste, and come back when part 1 is up.

Start with part 1 →

  1. 1 How OCR and AI turn photos of paper documents into useful text Build document capture as a pipeline: correct the image, detect text, then extract structure. Classic OCR still matters before any LLM reasons.
  2. 2 AI vision models vs classic OCR: which to use for reading documents Hybrid document AI: OCR for precise text and numbers, vision LLMs for semantic layout and messy handwriting. Do not let fluent models invent totals.
  3. 3 How to get clean text out of PDFs and scanned documents with AI Detect PDF type, preserve reading order, and chunk on layout before you embed. Columns and tables break if you slice by character count alone.
  4. 4 How to extract text from PDFs on your own computer with Docling Run open document tools like Docling on CPU or GPU for private, batch extraction. Keep cloud APIs for spikes that need managed scale.
  5. 5 How to extract tables, invoices, and form fields from documents with AI Extract structured documents with table geometry plus schema validation. Plain text dumps are not invoice systems.
  6. 6 How to have people check AI-extracted document data before you trust it Design document AI with confidence scoring and human review queues. High softmax alone is not a payment authorization.
  7. 7 How to remove private data from documents before an AI tool reads them Sanitize document AI inputs at the byte layer before OCR or LLM vision. Overlays and cloud defaults are not enough for PHI, PII, and regulated filings. Scheduled · December 14, 2026
  8. 8 When a phone scanner app is enough to turn paper forms into data Use good lighting and a scanner app when field capture quality matters more than fancy models. Save heavy document AI for pages that still fail after clean scans. Scheduled · December 23, 2026

Series notes

This is Part 6 of Vision OCR extraction from scratch. Previous: tables and invoices. Next: privacy and compliance.

Sources

Written by

Jose S

Founder & Lead Analyst · Analytics Made Simple

Hands-on data strategist, analytics engineering lead, and educator. Writing practical, no-fluff guides to help everyday teams, analysts, and engineers master SQL, AI systems, and modern data architectures.

Keep going

Same lessons in your feed

Short diagrams, hooks, and weekly tutorials on Substack, Instagram, X, and Facebook.

Google Search Prefer our practical guides in Google Search & Top Stories: