How to extract fields from scanned invoices as JSON in Python¶
Regex works until the second vendor. OCR plus patterns reads one layout. On 20 real invoices (phone photos, scans, handwriting, credit notes, six currencies) a schema-first read with a vision model found 99.8% of the values, for $0.0045 an invoice.
The steps below work with any vision model. The code uses ReadAnyDoc (open source, Apache-2.0), which does all four for you.
| Step | Why |
|---|---|
| 1. Describe the invoice as a class, not as patterns | the model maps any layout onto it; nothing to rewrite per vendor |
| 2. Read the page as an image | a scan has no text layer, and OCR text loses the columns |
| 3. Ask for the source of every value | a reviewer can see where a number came from; values with no source get flagged |
| 4. Check the arithmetic before saving | line items add up to the subtotal, or something was dropped |
1. Describe the invoice¶
from typing import Optional
from pydantic import BaseModel, Field
class LineItem(BaseModel):
description: str
quantity: Optional[float]
unit_price: Optional[float]
amount: Optional[float]
class Invoice(BaseModel):
vendor: str
invoice_number: Optional[str]
invoice_date: Optional[str] = Field(description="as printed")
currency: Optional[str]
line_items: list[LineItem]
subtotal: Optional[float]
tax: Optional[float]
total: Optional[float]
Make everything that can be missing Optional. A field the model is forced to fill is a field it will invent.
2 and 3. Read the scan, get JSON with sources¶
import readanydoc
out = readanydoc.extract("scan.pdf", schema=Invoice) # PDF, JPG, PNG, TIFF, phone photo
print(out.data.model_dump_json(indent=2)) # your JSON
print(out.citations["total"]) # the words and the box on the page it was read from
print(out.warnings) # what to check by hand
It reads each page with Claude Haiku (any vision model works), checks the result against local OCR, re-reads
doubtful strips zoomed in, and sends handwritten pages to a stronger model.
What it returns on a hard one¶
A printer's invoice from 1904, typed and handwritten, faded (the file). Three of the thirteen lines it returned, unedited:
{
"city": "Philadelphia",
"date": "May 1st",
"line_items": [
{"description": "Composition 104 pages, €", "amount": 159.12},
{"description": "Press Work, 14 forms,", "amount": 35.0},
{"description": "Binding based on 500 copies", "amount": 21.6}
],
"total": null
}
warnings:
required field 'total' was not found in the document
required field 'line_items[].amount' was not found in 1 of 13 items
Thirteen line items read, and two gaps it tells you about: the total at the bottom is not legible, so it is null
with a warning instead of a guess. Half a cent, 40 seconds. (The stray € is a misread mark; old scans are not clean.)
The full output with every citation drawn on the page.
4. Check before you save¶
def check_invoice(inv, cents=0.01):
problems = []
lines = sum(l.amount or 0 for l in inv.line_items)
if inv.subtotal is not None and abs(lines - inv.subtotal) > cents:
problems.append(f"line items add to {lines:.2f}, subtotal says {inv.subtotal:.2f}")
if None not in (inv.subtotal, inv.tax, inv.total) and abs(inv.subtotal + inv.tax - inv.total) > cents:
problems.append("subtotal + tax != total")
return problems
needs_review = check_invoice(out.data) or out.warnings or [
path for path, cites in out.citations.items()
if not cites or any(c.confidence == "low" for c in cites)]
Save automatically when needs_review is empty; send the rest to a person with the source highlighted.
More checks: how to check extracted numbers.
Measured¶
20 invoices: phone photos, scans, handwriting, credit notes, six currencies. Scored by code against an answer key.
| Values found | Cost per invoice | Median seconds | |
|---|---|---|---|
| ReadAnyDoc (Claude Haiku + engine) | 99.8% | $0.0045 | 18 |
| 99.8% | $0.027 | 5 | |
Claude Haiku alone, same schema (mode="model-only") |
99.8% | $0.0026 | not listed |
On invoices the three are level on accuracy: the model alone finds the same values. What the engine adds is the source of each value and the warnings. Where ReadAnyDoc loses: it is slower (18 seconds against 5), and it returned a citation box for 89.5% of values against Reducto's 100% (of the boxes returned, 94.9% showed the value against 87.9%). Method and every result.
Questions¶
Can I do this with Tesseract and regex? For one vendor with a clean layout, yes. Each new layout needs new patterns, tables lose their columns in OCR text, and handwriting is out of reach. A vision model with a schema handles layouts it has never seen.
Can I just send the image to Claude or GPT with a JSON schema? Yes, and on invoices it is enough for accuracy: Claude Haiku alone found the same 99.8% on our 20. What you do not get is where each value came from, a warning when something was not found, or a second look at doubtful regions.
Does it work on phone photos and handwriting?
Yes. The 20-invoice set includes both. A value it cannot read comes back as null with a warning, not a guess.
Long invoices with hundreds of lines?
Pass array_extract=True: rows are compared with the parsed table's row count and a short part is read again.
Do the invoices leave my machine? The page image goes to the model provider you choose. Point it at a vision model you host yourself if nothing may leave.