Document Processing with AI
Invoices, contracts and forms are not text â they are geometry, and the pipeline must respect both.
ExtractionPrerequisites
- !How OCR engines recognize text lines
- !JSON schemas and typed validation
- !Batch versus streaming data pipelines
What You'll Learn
- 1Explain why plain-text OCR loses the information documents rely on
- 2Design a layout-aware parsing stage that preserves reading order
- 3Drive extraction from a schema instead of free-form prompting
- 4Route low-confidence fields to humans instead of trusting them
Why document data resists naive pipelines
A spreadsheet has one row per record and one column per field. A business document has none of that structure â and yet the downstream system expects exactly that shape. The gap between the two is where document automation projects live or die.
Three properties make documents hard. Layout carries meaning: a number placed under a column header means something different from the same number in a footnote, and flattening to text discards the distinction. Formatting is inconsistent by design â two vendors will format the same invoice differently, sometimes within the same mailbox. And the cost of errors is asymmetric: a wrong total in an accounting system is worse than a missed document, so a pipeline that is ninety-nine percent right needs a story about the remaining one percent.
The practical consequence is that quality lives in the pipeline design, not in the model choice. Teams that bolt an LLM onto raw text and hope for the best get demo-grade results; teams that treat layout preservation, schema design and confidence routing as first-class components get systems that survive contact with real inboxes.
Scope matters as much as technique. A pipeline tuned for one vendor's invoices rarely generalizes to shipping manifests, and teams that chase a single universal extractor usually end up with a system that handles the common case and fails the expensive one. Narrow the document types deliberately, instrument accuracy per type, and extend the set only when volume justifies the engineering.
Layout-aware reading is more than OCR
OCR answers the question "what characters are on this page". Document understanding asks "what is this element, and how does it relate to the others". The difference is structural: a table is a grid of cells with spanning headers, a line item is a tuple that must stay together across a page break, and a signature block is a region whose presence changes the meaning of the page.
Modern layout models detect these regions as objects, then read each region with a recognizer tuned for its type. Table detection followed by cell-level recognition preserves row and column relationships that a plain text dump flattens into an unreadable string. Reading-order models handle multi-column layouts where a naive top-to-bottom scan interleaves two independent stories.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Element:
kind: str # text | table | key_value | signature
bbox: tuple
text: str = ""
confidence: float = 0.0
rows: List[List[str]] = field(default_factory=list)
def parse_page(ocr_page):
"""Convert a page of OCR output into ordered, typed elements."""
regions = ocr_page.detect_regions() # layout model
elements = []
for region in regions:
el = Element(kind=region.type, bbox=region.bbox, confidence=region.conf)
if region.type == "table":
el.rows = ocr_page.recognize_table(region)
else:
el.text = ocr_page.recognize_text(region)
elements.append(el)
return sorted(elements, key=lambda e: reading_order_key(e.bbox))
def reading_order_key(bbox):
"""Column-aware sort so multi-column pages stay coherent."""
x, y, w, _ = bbox
column = int(x // 300)
return (column, y, x)
def flatten(elements):
"""Render elements into a text block that keeps table structure."""
parts = []
for el in elements:
if el.kind == "table":
rows = [" | ".join(r) for r in el.rows]
parts.append("TABLE:\n" + "\n".join(rows))
else:
parts.append(el.text)
return "\n\n".join(parts)
Keeping tables in a pipe-delimited rendering rather than a word soup is a small change that measurably improves extraction accuracy, because the model can follow the same row-and-column logic a human reader uses.
Reading order, tables and page breaks
Layout handling is where otherwise solid pipelines quietly lose data. A two-column report read left-to-right across both columns interleaves two unrelated narratives and produces text that no extractor can make sense of. A spanning table header â a merged cell that labels three sub-columns â flattens into a repeated word or, worse, vanishes, orphaning every value beneath it.
Page breaks create a different class of bug. A line-item table that continues onto page two is one logical structure split across two parsing results; extracting each page independently yields two incomplete invoices instead of one complete one. The reliable fix is to detect continuation markers â a repeated header row, a footer that says the next page belongs to the same document, or simply the absence of a new invoice number â and stitch pages before extraction rather than trying to reconcile records afterward.
Confidence scores from the OCR engine are worth preserving through every stage. A character-level recognition score is a useful input to the routing decision later, and systems that discard it during parsing lose the ability to distinguish "this field was hard to read" from "this field was easy to read and wrong".
Schema-driven extraction
Free-form prompting asks the model to invent both the structure and the values, which produces inconsistent output across documents even when each response looks reasonable. Fixing the schema turns extraction into a constrained task: the model fills in a form you designed, and every downstream consumer knows what to expect.
import json
from pydantic import BaseModel, Field
from openai import OpenAI
class LineItem(BaseModel):
description: str
quantity: int = Field(ge=1)
unit_price: float = Field(gt=0)
total: float = Field(gt=0)
class Invoice(BaseModel):
vendor: str
invoice_number: str
issue_date: str
currency: str
line_items: list[LineItem]
subtotal: float
tax: float
grand_total: float
client = OpenAI()
def extract_invoice(page_text, page_number):
"""Fill a typed schema from one parsed page."""
response = client.chat.completions.create(
model="gpt-4o-mini",
temperature=0,
messages=[
{
"role": "system",
"content": "Extract the invoice fields. Use null when a field "
"is genuinely absent. Never estimate a numeric value.",
},
{"role": "user", "content": f"Page {page_number}:\n{page_text}"},
],
response_format={"type": "json_object"},
)
payload = json.loads(response.choices[0].message.content)
return Invoice.model_validate(payload)
Two details in that prompt matter more than they look. Instructing the model to return null rather than guess keeps unknowns visible so they can be routed to review. Forbidding estimates prevents the single most damaging failure mode in financial extraction: a plausible-looking number that no one checks because it arrived with high confidence.
Arithmetic checks and confidence routing
A typed schema validates shape, not truth. The cheapest high-yield validation is arithmetic: line item totals should sum to the subtotal, subtotal plus tax should equal the grand total, and any disagreement is either an extraction error or a document the business genuinely needs a human to interpret.
def validate_invoice(inv, tol=0.02):
"""Cross-field checks that catch extraction errors cheaply."""
issues = []
items_sum = sum(i.total for i in inv.line_items)
if abs(items_sum - inv.subtotal) > tol:
issues.append(("subtotal_mismatch", items_sum, inv.subtotal))
if abs(inv.subtotal + inv.tax - inv.grand_total) > tol:
issues.append(("total_mismatch", inv.subtotal + inv.tax, inv.grand_total))
for idx, item in enumerate(inv.line_items):
expected = item.quantity * item.unit_price
if abs(expected - item.total) > tol:
issues.append((f"line_{idx}_mismatch", expected, item.total))
return issues
def route(inv, issues, confidence):
"""Send only ambiguous documents to human review."""
if not issues and confidence >= 0.92:
return "auto_accept"
if not issues and confidence >= 0.75:
return "spot_check"
if len(issues) <= 2 and confidence >= 0.55:
return "human_review"
return "escalate"
Confidence itself needs calibration against real outcomes, not a theoretical probability. Track the auto-accept rate against the measured error rate monthly; when a document type starts drifting, the first signal appears in that gap before customers complain.
Assembling a pipeline that keeps up
Throughput requirements decide the architecture more than accuracy requirements do. A team processing two hundred invoices a day can afford synchronous calls and a spreadsheet-based review queue. A team processing two hundred thousand needs a queue-backed pipeline with retries, dead-letter handling and parallel page workers.
| Component | Responsibility | Failure mode to design for |
|---|---|---|
| Ingestion | Accept files, deduplicate | Same document submitted twice |
| Parser | Layout and OCR | Scanned pages with no text layer |
| Extractor | Schema fill | Multi-page records split incorrectly |
| Validator | Cross-field checks | Legitimate exceptions flagged as errors |
| Review UI | Human confirmation | Reviewers rubber-stamping |
Batch documents that span multiple pages need particular care: the correct record is assembled across pages before extraction, and a line item cut by a page break is stitched back together rather than extracted twice. Measure the pipeline with end-to-end metrics â straight-through processing rate, fields per minute, review time per document â because optimizing model accuracy in isolation often moves the real bottleneck somewhere else entirely.
â ī¸Silent truncation is the most expensive bug
When a page exceeds the context budget or an OCR region fails, the extractor still returns a valid-looking schema with fields missing. Detect incomplete inputs explicitly and fail loudly instead of accepting a partial record.
Common Mistakes
Feeding raw OCR text and asking for JSON without a schema
Fix: Define a typed schema and constrain the model to fill it, returning null rather than guessing.
Trusting extraction confidence as if it were calibrated
Fix: Measure auto-accept rate against audited error rate and recalibrate whenever document mix changes.
Optimizing model accuracy while ignoring the review queue
Fix: Track straight-through rate and review time â a 2% accuracy gain that doubles review volume is a net loss.
Best Practices
- Preserve layout and table structure before any language model sees the page
- Validate with arithmetic cross-checks that catch most extraction errors for free
- Route by confidence with a documented threshold per document type
- Stitch multi-page records before extraction, not after
- Version schemas so downstream consumers can migrate deliberately
Key Takeaways
- Documents encode meaning in layout, so structure-preserving parsing is a prerequisite for extraction
- Schema-driven extraction beats free-form prompting on consistency and downstream compatibility
- Null-not-guess instructions and arithmetic checks catch the costliest errors
- Confidence must be calibrated against audited outcomes, not assumed
- Straight-through rate and review time are the metrics that decide whether automation pays off