Guides

Build an AI Document Scanner

A scanner that reads invoices, receipts, and forms then extracts structured data automatically. Real Python code, honest failure modes, and no vendor lock-in.

16 min read July 2026 Token by Token

Why Manual Document Processing Still Eats Your Week

You've just finished a twelve-hour day on-site in Blackburn, your boots are still dusty, and there's a shoebox on the kitchen bench stuffed with receipts from Bunnings, fuel dockets from 7-Eleven, and invoices from the plasterer. Your bookkeeper needs them by Thursday. Or maybe you're a mortgage broker, and every loan application arrives as a thirty-page PDF where the client's payslip is scanned upside down, the bank statements are screenshots from a phone, and the tax notice is a blurry photograph taken through a windscreen. Someone — usually you, or someone you're paying — has to read every page, type the numbers into a spreadsheet, and hope they don't transpose a digit.

This is not a fringe problem. For Australian small businesses, document processing is the unpaid second job that arrives after the real work ends. The ATO requires records. Lenders require verification. Clients require quotes. And every one of those requirements means a human reading a piece of paper and typing what they see into a computer. It's slow, error-prone, expensive, and deeply unmotivating.

An AI document scanner changes the shape of this problem. Instead of a human reading and typing, you build a pipeline: image or PDF goes in, structured data comes out. Dates, amounts, ABNs, line items, GST totals — organised, validated, and ready for your accounting package or CRM. It won't eliminate every hour of data entry, but it can eliminate most of them. The catch is that you have to build it honestly, with your eyes open about what breaks and what it costs.

What We're Building

We're building a system, not buying a product. By the end of this guide you will have a Python pipeline that does the following:

This is not a plug-and-play app you download from an app store. It's a set of scripts you control, running on hardware you own or a cloud service you choose. The benefit is that you understand every step. The cost is that you have to assemble the steps yourself.

How It Actually Works (No Jargon)

Think of the pipeline like a two-person team in an office. The first person, OCR, is a very fast typist who can look at a photograph of a document and type out everything they see. They don't understand what they're typing. They just convert pixels into letters. If the original scan is blurry, or the handwriting looks like a doctor's prescription, the typist produces gibberish. But if the scan is clean, they produce a raw wall of text that contains all the information, just without any organisation.

The second person, the language model, is the office administrator who reads that wall of text and sorts it into columns. They don't need to be a genius. They just need clear instructions: "Find the date after the word 'Invoice' and put it in the date field. Find the ABN and put it in the ABN field. Add up the line items and confirm the total matches." They do this by understanding context — they know that "$1,250.00 inc GST" means the total is probably $1,250 and the GST is roughly $113.64.

So the process is: image → raw text → structured data. Like giving the AI an open-book exam where every answer must come from the page in front of it. The AI can't guess what isn't there, and it can't see what the OCR failed to read. But when both steps work, you get in seconds what used to take a human ten minutes of careful typing.

"AI is not magic. It's a very fast, very patient, very literal assistant that reads exactly what's on the page and tries to make sense of it. If the scan is blurry, the handwriting is illegible, or the table is crooked, the AI will fail — just like a human would. The difference is the AI won't complain. It'll just give you garbage and move on."

— The working definition

Step 1: Choose Your Tools

You need two things: an OCR engine to read the image, and a language model to understand the text.

OCR: Tesseract is free, open-source, and works well on clean printed text. For Python, install it with apt install tesseract-ocr on Ubuntu, then use the pytesseract package. If your documents are mostly clean PDFs and scans, Tesseract is enough. If you're dealing with complex tables, mixed fonts, or poor mobile photography, consider services like EasyOCR or cloud APIs from Google or Azure — but those have ongoing costs and data sovereignty implications.

Language Model: You have two realistic paths for an Australian SMB. A local model via Ollama keeps your data on your machine and costs nothing per document. A cloud API like OpenAI or Anthropic is easier to set up but sends your documents to servers overseas, which may breach client confidentiality if you're in accounting, mortgage broking, or legal. For this guide we'll use Ollama with a local model, because once it's running, the only cost is electricity.

Tools we'll use in this guide

  • Tesseract OCR — free, local, prints and typewritten text
  • PyMuPDF (fitz) — for turning PDFs into images the OCR can read
  • Ollama + Gemma 4 — local LLM that structures the extracted text
  • Python 3.10+ — the glue

Step 2: Set Up Document Ingestion

Your documents will arrive as photos, scanned PDFs, or email attachments. The first job is to normalise them into a format the OCR can handle. Tesseract reads images, not PDFs, so PDFs need to be converted to images first.

Install the Python dependencies:

pip install pytesseract pymupdf pillow requests

Then write a small ingestion script that watches a folder, converts PDFs to PNGs, and keeps the originals:

import fitz  # PyMuPDF
from pathlib import Path

def pdf_to_images(pdf_path, output_folder):
    doc = fitz.open(pdf_path)
    for i, page in enumerate(doc):
        pix = page.get_pixmap(dpi=300)
        out = Path(output_folder) / f"{Path(pdf_path).stem}_page{i+1}.png"
        pix.save(out)
    doc.close()

# Example: dump every PDF in ./inbox to ./images/
for pdf in Path("./inbox").glob("*.pdf"):
    pdf_to_images(pdf, "./images")

Use 300 DPI. Lower resolution saves space but produces worse OCR. For phone photos, you'll also want to handle rotation and cropping, but start simple.

Step 3: Extract Text with OCR

Now that you have images, feed them to Tesseract. The Python wrapper is straightforward:

import pytesseract
from PIL import Image

def ocr_image(image_path):
    img = Image.open(image_path)
    text = pytesseract.image_to_string(img)
    return text

raw = ocr_image("./images/invoice_001.png")
print(raw)

The output is raw, unformatted text. It might look like this:

ABC Plumbing Pty Ltd
Invoice #2047
Date: 14/06/2026

Description          Qty    Rate    Amount
Leak repair            1    $120    $120.00
Replacement tap        1    $85     $85.00

Subtotal: $205.00
GST: $20.50
Total: $225.50

That raw text is what the LLM will read. The OCR step is doing nothing except transcription. All the intelligence — understanding that "GST: $20.50" is tax, that "Invoice #2047" is the identifier — happens in the next step.

Step 4: Structure the Data with an LLM

This is where the pipeline gets smart. You send the raw OCR text to a local language model with a very specific prompt, and ask it to return structured JSON. The prompt is the most important piece of code in this entire system. A vague prompt gives vague results. A tight prompt gives reliable results.

Here's an example prompt and the Python code to send it:

import json, requests

SYSTEM_PROMPT = """You are a document data extraction assistant.
Read the invoice text below and return ONLY a JSON object.
Do not add commentary, markdown, or explanations.
Use null if a field is missing.

Required fields:
- invoice_number (string)
- date (string, DD/MM/YYYY)
- supplier_name (string)
- supplier_abn (string, 11 digits with optional spaces)
- line_items (list of {description, quantity, unit_price, amount})
- subtotal (number)
- gst (number or null)
- total (number)

Invoice text:
{ocr_text}
"""

def extract_invoice(ocr_text):
    payload = {
        "model": "gemma4:31b",
        "prompt": SYSTEM_PROMPT.format(ocr_text=ocr_text),
        "stream": False,
        "options": {"temperature": 0.1}
    }
    r = requests.post("http://localhost:11434/api/generate", json=payload)
    data = r.json()
    # Clean up: sometimes models wrap JSON in markdown code blocks
    raw = data["response"].strip()
    if raw.startswith("```json"):
        raw = raw.split("\n", 1)[1]
    if raw.endswith("```"):
        raw = raw.rsplit("\n", 1)[0]
    return json.loads(raw)

result = extract_invoice(raw)
print(json.dumps(result, indent=2))

The temperature is set low (0.1) because you want consistency, not creativity. This is not a chatbot. It's a data extraction tool. The prompt explicitly forbids markdown wrapping because some models love to decorate their JSON with code blocks, which breaks parsing.

Australian field you should not forget

Always ask for the ABN. It's the most reliable identifier for matching invoices to suppliers in Australian accounting systems. If the invoice doesn't show one, flag it. The ATO requires tax invoices over $82.50 to include an ABN, so its absence is either an error or a compliance issue.

Step 5: Validate and Store Results

The LLM will occasionally hallucinate. It might invent an invoice number, misread a date, or claim the total is $2,250.50 when the subtotal is clearly $205.00. You need validation logic before you trust anything.

def validate_invoice(data):
    errors = []
    if data.get("total") and data.get("subtotal"):
        if abs(data["total"] - (data["subtotal"] + (data.get("gst") or 0))) > 0.01:
            errors.append("Total does not match subtotal + GST")
    if data.get("date"):
        try:
            datetime.strptime(data["date"], "%d/%m/%Y")
        except ValueError:
            errors.append("Date format invalid")
    if data.get("supplier_abn"):
        abn = data["supplier_abn"].replace(" ", "")
        if len(abn) != 11 or not abn.isdigit():
            errors.append("ABN format invalid")
    return errors

errors = validate_invoice(result)
if errors:
    print("VALIDATION FAILED:", errors)
    # Write to a review queue instead of the clean database
else:
    # Safe to store
    with open("./output/invoices.jsonl", "a") as f:
        f.write(json.dumps(result) + "\n")

Never trust the LLM output blindly. Always validate totals, date formats, and ABN structures. Anything that fails validation goes to a human review queue. This queue is your safety net. It's also where you'll learn what the model gets wrong most often, which tells you where the prompt needs tightening.

Step 6: Handle Errors and Edge Cases

Real documents are messy. The best pipeline is one that expects failure and routes around it.

Multi-page invoices: Run OCR on every page, concatenate the text with page separators, and send the whole block to the LLM. If the invoice is ten pages, the prompt needs to say "This invoice spans multiple pages."

Handwritten notes: Tesseract struggles with handwriting. If your workflow involves signed delivery dockets or handwritten amendments, consider training a custom OCR model or accepting that those documents need human review.

Crooked scans and phone photos: Use image preprocessing — deskewing, contrast enhancement, binarisation — before sending to OCR. The opencv-python library can do this in a few lines.

Tables: The LLM is better at reading tables than Tesseract is at preserving their structure. If your document has complex tables, experiment with sending the image directly to a multimodal model (one that can see images, not just text) rather than relying on OCR transcription.

What Goes Wrong — The Reality Check

I've seen enough document scanning pipelines to know where they die. Here is the honest inventory.

Bad scans produce confident garbage: A blurry photo of a fuel receipt looks fine to the human eye but produces OCR text like "7-Eleven Pty Ltd Total $B7.40". The LLM will happily parse $B7.40 as a number and return garbage. If your input quality is poor, your output quality will be poor. No AI can see through a smudge.

Handwritten text is a brick wall: A plumber writes "Job done rear tap" on the bottom of an invoice. Tesseract reads it as "Job done rear tap" on a good day and "Jnb dnnn rar tap" on a bad day. The LLM cannot reconstruct meaning from characters that don't form words. Handwriting is still a human job unless you're using specialised handwriting models.

Multi-page documents with headers and footers: The OCR spits out repeated headers on every page. The LLM sees "Invoice #2047" five times and might extract the footer page number as the invoice number. You need to clean page artifacts before extraction, or instruct the model to ignore headers.

Currency and GST confusion: An invoice from a New Zealand supplier shows NZD. The LLM assumes AUD because that's what it's seen most often. Now your GST calculation is wrong and your accounting import fails. Explicitly ask for currency in the prompt, and validate that the ABN matches an Australian entity.

Privacy and client data: If you're a mortgage broker scanning payslips and bank statements, that data is protected under the Privacy Act. Sending it to a cloud API may breach your obligations, especially if the provider stores logs offshore. Local models via Ollama keep everything in-house. The trade-off is hardware cost and setup complexity.

Real Cost and Time Numbers

Let's be specific, because the word "AI" makes people think it's either free or fifty thousand dollars.

Local-only route (Ollama + Tesseract):

Cloud OCR + Cloud LLM route (Azure Document Intelligence + OpenAI):

The comparison: A data entry contractor in Australia charges $30–$45 per hour. If this pipeline saves you five hours per month, it pays for the hardware in three months or the cloud service immediately. But the real saving is not money — it's time returned to you, and the elimination of the Sunday-night receipt-sorting ritual.

What It Actually Takes

Here is the honest day-by-day breakdown for a working system:

The total investment is roughly one focused weekend plus an hour per week of maintenance. The return is the disappearance of most manual data entry from your workflow. But be honest: if you only process five documents a month, this is not worth building. The pipeline shines when volume is high enough that the time saved compounds.

Stuck on the prompt or validation logic?

I've built document extraction pipelines for accountants, mortgage brokers, and trades businesses across Australia. If you're wrestling with OCR quality, prompt engineering, or keeping client data local — get in touch.

What to Build Next

Once your scanner reliably extracts invoices and receipts, the natural extensions are:

None of these require rebuilding from scratch. They're layers on top of the same foundation: image → text → structured data → validation. Start with one document type. Get it working. Then expand. The businesses that succeed with AI are the ones that treat it as a compounding advantage, not a magic wand.