lucid.page Extract invoice data with Python, OCR + LLM: scripts and outputs
Text size
Read time1 min

# Extract invoice data with Python, OCR + LLM: scripts and outputs

Checked 2026-11-07. Every script ran as shown; the lines under # $ are what it printed, cut only where you see ....

Contents

# READ_TEXT_PY

python
import json
import sys

import pdfplumber
import pytesseract
import requests

# ...

def read_text(path):
    pages = []
    with pdfplumber.open(path) as pdf:
        for page in pdf.pages:
            text = page.extract_text() or ""
            if not text.strip():
                image = page.to_image(resolution=300).original
                text = pytesseract.image_to_string(image)
            pages.append(text)
    return "\n\n".join(pages)

# $ python -c 'from extract_invoice import read_text; print(read_text("invoice-hollins-scan.pdf"))'
# Hollins Brook Plumbing & Heating INVOICE
#
# 62 Barre St, Montpelier, VT 05602
# ...
# DESCRIPTION QTY UNIT PRICE AMOUNT
# Labor, licensed plumber, hours ahs) 95.00 332.50
# Pipe insulation, 6 ft 8 4.25 34.00
# PEX pipe 3/4 in, 10 ft 3 18.90 56.70
# Ball valve 3/4 in, brass 2 24.60 49.20
# Expansion tank fittings 4 7.35 29.40
# Service call, visits 2 45.00 90.00
# Subtotal 591.80
# Sales tax 6% on 169.30 10.16
# SSS
# Total (USD) 601.96
# Paid at booking 150.00
# Balance due (USD) 451.96
# Pay by check to Hollins Brook Plumbing & Heating
# Terms Net 30
#
# Thank you. Sales tax applies to parts only.
#
# Hollins Brook Plumbing & Heating Montpelier, Vermont VT plumbing license PL-04412
# iB 8

# EXTRACT_PY

python
# ...

NUMBER = {"type": ["number", "null"]}

SCHEMA = {
    "type": "object",
    "properties": {
        "invoice_number": {"type": "string"},
        "issue_date": {"type": "string"},
        "vendor_name": {"type": "string"},
        "currency": {"type": "string"},
        "line_items": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "description": {"type": "string"},
                    "quantity": NUMBER,
                    "unit_price": NUMBER,
                    "total": NUMBER,
                },
                "required": ["description", "quantity", "unit_price", "total"],
            },
        },
        "subtotal": NUMBER,
        "shipping": NUMBER,
        "tax_rate": NUMBER,
        "tax_base": NUMBER,
        "tax_total": NUMBER,
        "total": NUMBER,
        "amount_paid": NUMBER,
        "amount_due": NUMBER,
    },
    "required": [
        "invoice_number", "issue_date", "vendor_name", "currency", "line_items",
        "subtotal", "shipping", "tax_rate", "tax_base", "tax_total", "total", "amount_paid", "amount_due",
    ],
}

PROMPT = "Copy the values from this invoice into JSON. Use null for anything not printed. Do not calculate or correct numbers."


# ...

def extract(text):
    reply = requests.post(
        "http://localhost:11434/api/chat",
        json={
            "model": "qwen3:4b",
            "messages": [
                {"role": "system", "content": PROMPT},
                {"role": "user", "content": text},
            ],
            "format": SCHEMA,
            "think": False,
            "stream": False,
            "options": {"temperature": 0},
        },
        timeout=600,
    )
    reply.raise_for_status()
    return json.loads(reply.json()["message"]["content"])


if __name__ == "__main__":
    invoice = extract(read_text(sys.argv[1]))
    print(json.dumps(invoice, indent=2))

# $ python extract_invoice.py invoice-hollins-scan.pdf
# {
#   "invoice_number": "HB-0518",
#   "issue_date": "October 21, 2026",
#   "vendor_name": "Hollins Brook Plumbing & Heating",
#   "currency": "USD",
#   "line_items": [
#     {
#       "description": "Labor, licensed plumber, hours ahs)",
#       "quantity": 95.0,
#       "unit_price": 332.5,
#       "total": 591.8
#     },
#     {
#       "description": "Pipe insulation, 6 ft 8",
#       "quantity": 4.25,
#       "unit_price": 34.0,
#       "total": 34.0
#     },
# ...
#   ],
#   "subtotal": 591.8,
#   "shipping": null,
#   "tax_rate": 6.0,
#   "tax_base": 169.3,
#   "tax_total": 10.16,
#   "total": 601.96,
#   "amount_paid": 150.0,
#   "amount_due": 451.96
# }

# CHECK_PY

python
import json
import sys

CENT = 0.01


def off(expected, printed):
    return printed is None or abs(round(expected, 2) - printed) > CENT


def check(inv):
    problems = []

    for n, line in enumerate(inv["line_items"], start=1):
        qty, price, total = line["quantity"], line["unit_price"], line["total"]
        if None in (qty, price, total):
            problems.append(f"line {n}: quantity, unit price or total is missing")
        elif off(qty * price, total):
            problems.append(f"line {n}: {qty} x {price} = {qty * price:.2f}, printed {total:.2f}")

    lines = sum(line["total"] or 0 for line in inv["line_items"])
    if off(lines, inv["subtotal"]):
        problems.append(f"lines add up to {lines:.2f}, subtotal is {inv['subtotal']}")

    if inv["tax_base"] is not None and inv["tax_rate"] is not None:
        tax = inv["tax_base"] * inv["tax_rate"] / 100
        if off(tax, inv["tax_total"]):
            problems.append(f"tax should be {tax:.2f}, printed {inv['tax_total']}")

    total = (inv["subtotal"] or 0) + (inv["shipping"] or 0) + (inv["tax_total"] or 0)
    if off(total, inv["total"]):
        problems.append(f"subtotal + shipping + tax = {total:.2f}, total is {inv['total']}")

    if None not in (inv["total"], inv["amount_paid"]) and off(inv["total"] - inv["amount_paid"], inv["amount_due"]):
        problems.append(f"total - paid is not the amount due {inv['amount_due']}")

    return problems


if __name__ == "__main__":
    invoice = json.load(open(sys.argv[1]))
    problems = check(invoice)
    for problem in problems:
        print("FAIL", problem)
    print(f"{len(problems)} problem(s)" if problems else "OK: lines, tax and totals add up")

# $ python check_invoice.py ridgeback.json
# OK: lines, tax and totals add up
# $ python check_invoice.py hollins.json
# FAIL line 1: 95.0 x 332.5 = 31587.50, printed 591.80
# FAIL line 2: 4.25 x 34.0 = 144.50, printed 34.00
# FAIL lines add up to 851.10, subtotal is 591.8
# 3 problem(s)

# VERSIONS_PY

python
import platform
import subprocess
import sys
from importlib.metadata import version

TOOLS = {
    "tesseract": lambda: subprocess.run(["tesseract", "--version"], capture_output=True, text=True).stdout.split()[1],
    "ollama": lambda: subprocess.run(["ollama", "--version"], capture_output=True, text=True).stdout.split()[-1],
    "libreoffice": lambda: subprocess.run(["soffice", "--version"], capture_output=True, text=True).stdout.split()[1],
}

print("Python", platform.python_version())
for name in sys.argv[1:]:
    print(name, TOOLS[name]() if name in TOOLS else version(name))

# $ python versions.py pdfplumber pytesseract requests tesseract ollama
# Python 3.12.14
# pdfplumber 0.11.10
# pytesseract 0.3.13
# requests 2.34.2
# tesseract 5.5.0
# ollama 0.40.15
End