Taming a Drawer Full of Scanned PDFs: A Local-First Document Intelligence Pipeline
Most "applied AI" writing jumps straight to the model: which LLM, which embedding, which vector store. In practice the model is rarely the hard part. The hard part sits upstream — the data is trapped.
I hit three flavours of trapped data at once while cleaning up my own backlog of documents:
- Image-only PDFs. Years of scans, phone photos, and "print to PDF" receipts with no text layer. You can't
Ctrl-Fany of it. - Documents that only live behind a portal. Some statements and policy copies exist only inside a provider's web dashboard — a React single-page app that returns an empty shell to a plain HTTP request.
- A privacy constraint I actually cared about. These are personal and financial documents. Uploading them to a cloud OCR service or a hosted LLM to "just extract the fields" was not something I was willing to do.
So I built a small, strictly local pipeline that takes a folder of messy scans (plus, optionally, documents pulled from my own authenticated portals) and turns them into a clean, renamed, categorised archive with a searchable JSON index. Everything — rendering, OCR, classification, extraction — runs on a single workstation. Nothing leaves the machine.
This post walks through the architecture, the actual code for each layer, and the unglamorous bugs that only showed up once I ran it over a few hundred files unattended.
The shape of the problem
The input is a folder like this — the output of a flatbed scanner and a lot of "save as PDF":
inbox/
├── scan_0001.pdf # an electricity bill, image-only
├── scan_0002.pdf # a two-year-old insurance policy
├── IMG_4471.pdf # a photographed receipt
├── doc (3).pdf # who knows
└── ... 300 more
The goal is an archive I can actually navigate:
archive/
├── utility_bill/
│ └── 2026/
│ └── TNEB-2026-04.pdf
├── insurance_policy/
│ └── 2024/
│ └── ICICI-Lombard-POL8841.pdf
├── receipt/
│ └── 2026/
│ └── Croma-INV55120.pdf
└── index.json # every document's extracted fields + where it landed
To get there, each document needs three things pulled out of it: what it is (type), who issued it, and enough of a date/reference to name and file it. On an image-only PDF, that means render → OCR → structured extraction.
Architecture: boringly sequential, on purpose
Before any code, one decision shaped everything: the pipeline is strictly linear — one document at a time, one worker.
That sounds backwards for a batch job. But look at what shares the machine:
- a local 35B-parameter LLM holding a chunk of VRAM, and
- a headless Chromium instance (for the portal step), and
- Tesseract doing CPU-bound OCR.
Throw an async crawler at that and the pieces fight each other: parallel browser contexts balloon RAM, concurrent requests to a provider portal trip rate limits, and multiple inference calls just thrash the GPU and end up slower wall-clock than doing them in order. Linear execution also makes the whole thing trivially debuggable and resumable, which matters far more than raw throughput for a few hundred documents.
So the per-document flow is a fixed 8 steps:
[one PDF in inbox/]
│
├─► 1. Render first page @160 DPI (PyMuPDF)
├─► 2. OCR the page image (Tesseract, --psm 6 --oem 1)
├─► 3. Regex pre-clean + anchor the text
├─► 4. Structured extraction (local Qwen + JSON schema)
├─► 5. Deterministic routing → type / year (plain Python, not the LLM)
├─► 6. Copy + rename into archive/ (pathlib)
├─► 7. (optional) pull official copy (Playwright, my own login)
└─► 8. Append record to index.json + log
Two layers do the heavy lifting: a fast classical OCR layer, and a local LLM layer that turns noisy OCR text into clean fields. Let's take them in order.
Layer 1: sub-second rasterisation and OCR
A tempting shortcut is to feed every page to a vision-language model and ask for the fields directly. For consistent, text-heavy documents that's overkill — it's slower, less deterministic, and (for a VLM in the cloud) exactly the privacy problem I was avoiding. Classical OCR is faster and completely reproducible.
I render only the first page at 160 DPI — high enough for crisp character edges, low enough to keep memory and OCR time down — and hand the raw bitmap straight to Tesseract. No intermediate PNG on disk.
import pymupdf as fitz
from PIL import Image
import pytesseract
RENDER_DPI = 160
ZOOM = RENDER_DPI / 72 # 72 is the PDF default
def render_and_ocr(pdf_path: str) -> str:
# 1. Render the first page to an in-memory RGB bitmap
with fitz.open(pdf_path) as doc:
page = doc[0]
pix = page.get_pixmap(matrix=fitz.Matrix(ZOOM, ZOOM), alpha=False)
img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
# 2. OCR — English, single uniform block, LSTM engine. Fast config.
text = pytesseract.image_to_string(
img,
lang="eng",
config="--psm 6 --oem 1",
)
return " ".join(text.split()) # flatten whitespace for easier matching
--psm 6 tells Tesseract to assume a single uniform block of text (correct for most single-page documents), and --oem 1 selects the LSTM engine. On my machine, render + OCR + whitespace cleanup lands at ~150–300 ms per document.
A small but useful habit: resolve the Tesseract binary from PATH with a sane fallback, so the script is portable across machines.
import shutil
pytesseract.pytesseract.tesseract_cmd = (
shutil.which("tesseract") or r"C:\Program Files\Tesseract-OCR\tesseract.exe"
)
At this point I have a flat string of OCR text — misreads and all. Now it needs structure.
Layer 2: a local LLM with constrained JSON output
OCR text is messy: broken lines, the occasional 0/O swap, headers and footers bleeding together. Writing regex to pull "issuer" and "document type" out of every vendor's layout is a losing game. This is exactly where a small local LLM shines — not for reasoning, but for turning fuzzy text into a fixed shape.
I serve Qwen 35B locally with llama-server on 127.0.0.1:8080, and hit its OpenAI-compatible /v1/chat/completions endpoint. The single most important setting is constrained decoding against a JSON schema — the server is forced to emit valid JSON in exactly my shape, so there's no free-text parsing on my side.
DOC_SCHEMA = {
"type": "object",
"properties": {
"document_type": {
"type": "string",
"enum": ["invoice", "receipt", "bank_statement", "insurance_policy",
"warranty", "utility_bill", "govt_letter", "other"],
},
"issuer": {"type": "string"}, # organisation name only
"issue_date": {"type": "string"}, # ISO 8601 if present, else ""
"reference_id": {"type": "string"}, # invoice/policy/ref number, else ""
"total_amount": {"type": "string"}, # with currency if monetary, else ""
},
"required": ["document_type", "issuer"],
}
EXTRACT_PROMPT = """You are reading the OCR text of a single scanned document.
Fill in the fields defined by the schema. Use an empty string for any field that
is not clearly present — do not guess. For document_type, choose the closest match
from the allowed values. Keep "issuer" to the organisation name only.
OCR text:
{text}"""
The request mirrors the structured-output pattern: temperature: 0 for determinism, thinking disabled to skip Qwen's <think> step (pure latency here), and response_format carrying the schema.
import json, re, urllib.request, urllib.error
QWEN_API_URL = "http://127.0.0.1:8080/v1/chat/completions"
QWEN_MODEL = "qwen3-35b-a3b"
QWEN_TIMEOUT = 60
def extract_fields(ocr_text: str) -> dict | None:
payload = {
"model": QWEN_MODEL,
"messages": [{"role": "user",
"content": EXTRACT_PROMPT.format(text=ocr_text[:4000])}],
"temperature": 0,
"max_tokens": 256,
"chat_template_kwargs": {"enable_thinking": False},
"response_format": {
"type": "json_schema",
"json_schema": {"name": "doc_fields", "schema": DOC_SCHEMA},
},
}
req = urllib.request.Request(
QWEN_API_URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=QWEN_TIMEOUT) as resp:
data = json.load(resp)
except (urllib.error.URLError, TimeoutError) as e:
print(f"Qwen server not reachable at {QWEN_API_URL} ({e}).")
return None
content = data["choices"][0]["message"].get("content") or ""
content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL)
# Schema-constrained output is already valid JSON; the slice is just belt-and-braces.
try:
return json.loads(content[content.index("{"): content.rindex("}") + 1])
except (ValueError, KeyError):
print(f"Unexpected LLM reply: {content!r}")
return None
The real lesson: let the model label, keep the logic in code
The pattern worth stealing here is the split between probabilistic labelling and deterministic logic.
The model is good at the fuzzy part — "this smudged text is an electricity bill from TNEB." It is not where I want my filing rules to live. So the LLM only ever produces labels and fields. The decision of where a document goes is plain, auditable Python:
from pathlib import Path
ARCHIVE = Path("archive")
def route(fields: dict) -> Path:
doc_type = fields.get("document_type") or "other"
# Pull a 4-digit year from issue_date if the model found one, else "undated".
m = re.search(r"(19|20)\d{2}", fields.get("issue_date", ""))
year = m.group(0) if m else "undated"
return ARCHIVE / doc_type / year
Because the schema enum constrains document_type to a fixed set, this routing never sees a surprise value — the model literally cannot invent a folder. Anything genuinely ambiguous resolves to other/ (or undated/), which I skim manually. Zero silent data loss, and the business rules stay in code where I can read and test them — not buried in a prompt.
Layer 3: getting documents out of a React SPA (Playwright)
A handful of my documents don't exist as files at all — they only live inside a provider's web portal, which I can download from my own account. The naive approach fails instantly:
import requests
html = requests.get(PORTAL_DOCS_URL).text
# -> a near-empty shell: "You need to enable JavaScript to run this app."
The portal is a client-side React app; the document list is rendered after JavaScript runs. A plain HTTP fetch sees none of it. The fix is a real browser — headless Chromium via Playwright — operating under my own logged-in session.
Two things make this clean and legitimate:
- It's my own account. I reuse a saved authenticated session (
storage_state) that I created once by logging in myself, rather than scripting a password flow. The pipeline never handles my credentials. - It's gentle. The same sequential, one-at-a-time design means I'm not hammering the portal.
from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout
DOCS_SELECTOR = "a[data-testid='document-download']" # whatever the portal uses
def fetch_portal_documents(docs_url: str, dest: Path) -> list[str]:
saved = []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# storage_state = a session I authenticated once, by hand.
context = browser.new_context(storage_state="portal_session.json")
page = context.new_page()
page.goto(docs_url, wait_until="domcontentloaded", timeout=45000)
# 1. Wait for the SPA to actually render the document list.
try:
page.wait_for_selector(DOCS_SELECTOR, timeout=45000)
except PWTimeout:
page.mouse.wheel(0, 2000) # nudge lazy-loaded rows
page.wait_for_timeout(2000)
page.wait_for_selector(DOCS_SELECTOR, timeout=15000)
# 2. Scroll so every lazy row hydrates its href.
for _ in range(4):
page.mouse.wheel(0, 2500)
page.wait_for_timeout(800)
# 3. Collect the real download links.
links = page.query_selector_all(DOCS_SELECTOR)
for a in links:
href = a.get_attribute("href") or ""
if href and not href.startswith("data:"):
saved.append(href)
browser.close()
return saved
Grab the original, not the preview
One detail from the DOM inspection generalises nicely. Many portals render a low-resolution inline preview and keep the full original behind a separate link — often distinguishable by a path segment or query flag (.../preview/... vs .../original/..., or ?size=sm vs ?size=full). If you naively download what's shown on screen, you archive the thumbnail.
So before downloading, rewrite the URL to the authoritative asset:
def to_original(url: str) -> str:
# Portal-specific: prefer the full asset over the inline preview.
return url.replace("/preview/", "/original/").replace("size=sm", "size=full")
The lesson isn't the exact string — it's inspect what the SPA actually loads and fetch the canonical version, not the first thing the grid paints.
Production hardening: the bugs that only appear on run 200
Getting the happy path working took an afternoon. Making it survive a few hundred unattended documents took fixing some deeply unglamorous things.
1. The temp file that never existed. My first OCR worker took raw PDF bytes in memory, but PyMuPDF (in the subprocess form I ran it) wanted a path on disk. The job failed in ~0.2s with "file not found" and I nearly blamed the model. The fix is a disciplined temp-file lifecycle — write before, clean up always:
tmp = ARCHIVE / f"_tmp_{doc_id}.pdf"
try:
tmp.write_bytes(pdf_bytes) # exists on disk before OCR reads it
fields = process(str(tmp))
finally:
tmp.unlink(missing_ok=True) # gone even if processing raised
2. A Unicode arrow that crashed on Windows. The classifier printed status lines with a → (U+2192). On a Windows console defaulting to cp1252, that print raised UnicodeEncodeError — after a perfectly good extraction — so the parent process couldn't read the result and the whole document looked like a failure. Two fixes: force UTF-8 on the stream, and stop using non-ASCII in machine-readable output.
import sys
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
And when the extractor runs as a child process, set the environment explicitly instead of hoping:
import os
env = os.environ.copy()
env["PYTHONIOENCODING"] = "utf-8"
env["PYTHONUTF8"] = "1"
# subprocess.run([...], env=env, encoding="utf-8", errors="replace", ...)
I also switched the status delimiters from → to a plain ASCII -> so the parser never depends on the console's codepage.
3. An audit trail, not a blind loop. Every document appends a structured record — source file, extracted fields, where it landed, and any error — to index.json, alongside rotating logs from the logging module. When document #214 hits a timeout, I don't restart from zero; I read the manifest and resume.
record = {
"source": pdf_path.name,
"fields": fields,
"archived_to": str(dest),
"errors": errors,
}
records.append(record)
(ARCHIVE / "index.json").write_text(
json.dumps(records, indent=2, ensure_ascii=False), encoding="utf-8"
)
That index.json is a bonus payoff: it's a searchable, greppable index of every document I own — the thing the scanned PDFs could never be.
The stack, and why each piece earns its place
| Layer | Tool | Why |
|---|---|---|
| HTTP / files | requests, pathlib |
fetch and organise, no ceremony |
| PDF render | PyMuPDF | fast first-page rasterisation of image-only PDFs |
| OCR | Tesseract + pytesseract |
deterministic text, far cheaper than a VLM |
| Extraction | Qwen 35B + llama-server + JSON schema |
fuzzy text → fixed fields, on-prem, no PII leaves the box |
| SPA access | Playwright (Chromium) | portals that return empty shells to plain HTTP |
| Ops | logging, index.json, linear control flow |
debuggable, resumable, auditable |
Takeaways for people building this kind of thing
- The model is the easy 20%. Rendering, OCR, SPA access, encoding, and file lifecycle are where the time actually goes. Budget accordingly.
- Constrain the output. JSON-schema decoding turned "parse the LLM's prose" from a chronic source of bugs into a non-issue. If your local server supports it, use it.
- Separate labelling from logic. Let the model produce labels; keep routing and rules in plain, testable code. Your filing logic should never live inside a prompt.
- Local-first is a feature, not a limitation. For personal and financial documents, "nothing leaves the machine" isn't a compromise — it's the whole point. A single workstation with a quantised 35B model and some classical tooling is genuinely enough.
You don't need a cluster or a cloud contract to turn a chaotic pile of scans into a clean, private, searchable archive. You need a handful of sharp tools wired together carefully — and the patience to fix the boring bugs that only show up on run number 200.
The code in this post is adapted from my own pipeline. If you build on it, point the portal step at your own accounts, respect each site's terms of use, and keep the sensitive stuff local.