05.4 OCR and Scanned Documents

RetrievalLesson 4 of 1013,606 words13 parts
Module 05 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

A surprising share of the world's documents exist only as pictures: faxed contracts, photographed receipts, scanned archives, phone photos of whiteboards, government forms, old books. No text layer means no copy-paste, no search, and nothing for a classical parser or an embedding model to work with. Optical character recognition (OCR) is the family of techniques that turn those pictures back into text — and in 2026 it sits at a genuine crossroads, because vision-language models (VLMs) can now "read" an image directly, while dedicated OCR engines, cloud document-AI services and hybrid pipelines still win on cost, determinism, confidence scores and throughput.

This lesson is about the engineering of getting text out of scans: detecting which pages need OCR, choosing between classical engines, document-AI APIs and VLMs, preprocessing images so engines read them accurately, measuring OCR quality with real numbers, recovering layout and tables, correcting post-OCR errors, and running it all at scale. By the end you will be able to design an OCR stage for an ingestion pipeline that routes each page to the cheapest engine that can read it, and to prove — with measurements, not vibes — that the output is good enough for retrieval.

What you'll learn

  • What OCR actually does (preprocess → detect regions → recognise → post-process → reconstruct layout), and why it still matters even though VLMs can read images
  • The 2026 OCR landscape: classical open-source engines (Tesseract, EasyOCR, PaddleOCR, RapidOCR, docTR, surya/marker), cloud document-AI services (Google Document AI, Azure AI Document Intelligence, AWS Textract, Mistral OCR) and VLMs-as-OCR — with verified versions, licences and pricing structure
  • How to detect scanned vs born-digital pages and route each page to the right engine
  • Image preprocessing that helps OCR (resolution, grayscale, binarization, deskew, orientation) — and the preprocessing that hurts it
  • OCR output formats (plain text, TSV, hOCR, ALTO, searchable PDFs), confidence scores, and how to measure quality with character/word error rate
  • Layout, tables, forms and handwriting from scans; multilingual and non-Latin scripts; post-OCR correction
  • VLM-based OCR as a first-class option: faithful-transcription prompts, per-page cost modelling, verification and cross-checking, plus the open-weight document VLMs (olmOCR, PaddleOCR-VL, DeepSeek-OCR, Granite-Docling, Chandra) you can run yourself, with their licences and operating traps
  • Scale: throughput, CPU vs GPU, batching, retries, caching OCR results by content hash

What you don't need

  • Any knowledge of computer vision or deep learning. Every concept is explained from zero.
  • OCR experience. You do need to have read 05.2 (or at least know that a PDF page is either text, an image, or both) and be comfortable with Python and uv.
  • API keys to learn most of this lesson. The classical-OCR parts run entirely on your machine; the provider and cloud sections are written so you can read and plan without calling anything.

Setup

Most of this lesson needs a Python project and a few packages. Create one if you haven't already:

bash
uv init scan-reader --bare --python 3.13 && cd scan-reader

Then install the libraries used in the samples (the comparison table in Part 2 explains what each is for; it also lists the versions the samples were checked against, as of November 2026, for example pillow 13.0.0, pytesseract 0.3.13 and rapidocr 3.10.0). The commands install the newest release of each package; OCR engines and their models change output between releases, so if a sample's text or confidence differs, compare versions and read the changelog before you debug your own code:

bash
# Pure-Python + imaging (needed for most samples)
uv add pillow pytesseract pypdfium2 img2pdf pdf2image

# Optional heavier engines — install only the ones you want to try:
uv add rapidocr        # ONNX-based, CPU-friendly, Apache-2.0
uv add easyocr          # PyTorch-based, GPU recommended
uv add ocrmypdf       # needs the Tesseract and Ghostscript binaries too
uv add jiwer            # optional: library CER/WER (we also write our own)

# Cloud OCR SDKs (illustrative samples only — you need accounts/keys to run them):
uv add mistralai google-cloud-documentai azure-ai-documentintelligence boto3

pytesseract, ocrmypdf and pdf2image are wrappers around external binaries — you must also install the binaries themselves:

bash
# macOS
brew install tesseract ghostscript poppler
# Debian/Ubuntu
sudo apt install tesseract-ocr ghostscript poppler-utils

Tesseract also needs language data (eng.traineddata ships with most packages; other languages are downloaded separately — see 5.5). Verify the install:

bash
tesseract --version          # Tesseract 5.x expected (5.5.4 as of late October 2026)
tesseract --list-langs       # language packs installed
python -c "import pytesseract; print(pytesseract.get_tesseract_version())"

Provider and cloud samples use the .env keys from earlier modules (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY) plus whatever your cloud account issues (MISTRAL_API_KEY, GOOGLE_APPLICATION_CREDENTIALS, AZURE_DOCUMENT_INTELLIGENCE_KEY/_ENDPOINT, AWS credentials). Never commit .env.


What you must be able to do after this lesson#

  • Explain what OCR does and when it is needed
  • Detect scanned pages and route them to the right engine
  • Preprocess an image and run OCR on it
  • Measure OCR quality with character and word error rate
  • Decide between classical OCR and a VLM for a document set

Why this matters for an AI engineer#

OCR is where "data engineering for AI" stops being optional. A retrieval system is only as good as the text it can see; a page that exists only as an image contributes nothing unless something converts it. The decisions in this lesson — which engine, which preprocessing, whether to escalate a hard page to a VLM, how to measure that the result is good enough — are the difference between a corpus that silently drops a third of its contracts and one that indexes all of them with known quality.

You'll hear... You'll understand it after...
"Half our archive is scanned PDFs — do we need OCR?" Part 1: what OCR is and why it survives the VLM era
"Tesseract keeps mangling the invoice totals." Part 3: resolution, binarization, deskew — and what preprocessing hurts
"Some pages have a text layer but the text is garbage." 4.1: bad OCR layers hiding inside PDFs
"Should we send every scan to GPT/Claude/Gemini?" Part 8 and the decision table: cost, verification, hybrid routing
"How do we know the OCR is accurate enough?" Part 6: confidence scores, CER/WER, ground-truth sets
"The receipts are handwriting / non-English / thermal-paper faded." Part 9 and Part 10
"OCR fixed 'rn' into 'm' and broke our part numbers." Part 11: common confusions and when LLM correction helps or hurts
"We need to OCR 200k pages a month." Part 12: throughput, batching, caching, cost modelling

Part 1: What OCR is, and why it still matters#

1.1 A scanned page is a picture, not text#

To a computer, a scanned contract page is an array of pixel intensities — typically grayscale or colour values between 0 (black) and 255 (white), tens of millions of them for a letter-size page at print resolution. There are no characters, no words, no paragraphs: just dots. Optical character recognition is the process of inferring which characters those dots represent, in which order, and roughly where each one sits.

This matters for AI engineering because every downstream stage — parsing, cleaning, chunking, embedding, retrieval — consumes text. A scan that never gets OCR'd is invisible to all of it. Even VLM-based ingestion pipelines typically OCR first (or send page images) and then treat the result as text.

1.2 The OCR pipeline#

Classical OCR is a pipeline, not a single model. Understanding the stages explains almost every OCR failure you'll debug:

flowchart LR
    subgraph pre ["1. Preprocessing"]
        A["Deskew<br/>orientation<br/>denoise<br/>binarize"] --> B["Text-line<br/>detection"]
    end
    subgraph rec ["2. Recognition"]
        B --> C["Character /<br/>word recognition"]
        C --> D["Language model<br/>+ dictionary"]
    end
    subgraph post ["3. Post-processing"]
        D --> E["Reading order<br/>+ layout reconstruction"]
        E --> F["Confidence scores<br/>+ outputs: text / TSV / hOCR / PDF"]
    end
  1. Preprocess the image: fix rotation and skew, remove noise and shadows, normalize contrast, sometimes binarize (reduce to black-and-white) and upscale. Done badly, this stage destroys information before recognition even starts (Part 3).
  2. Detect text regions: find where lines, words or characters are. Classical engines like Tesseract do this implicitly; modern deep models (PaddleOCR, EasyOCR, docTR, surya) run an explicit text detector.
  3. Recognise: classify each region's characters. Classical engines use trained character classifiers plus a language model; deep recognizers use CRNN/Transformer-style networks.
  4. Post-process: order the pieces into reading order, rebuild lines/columns/tables, attach confidence scores, and emit text plus structured output.

1.3 Born-digital, scanned, and the messy middle#

Before OCR can help, you need to know which pages actually need it. Three cases:

Page type What's on it What works
Born-digital Real text objects (fonts, positions, selectable text) Classical extraction — no OCR needed (05.2, 05.3)
Scanned / image-only One big image per page, no text OCR or VLM required
Hybrid / previously-OCR'd A real text layer plus images (figures, stamps, handwriting annotations, or a hidden OCR layer from an earlier scan) Extract text normally; OCR only the image regions or the pages that need it

The third case is where pipelines go wrong. A PDF can contain an invisible OCR text layer that is wrong — the page looks like a scan to a human, extracts text to a parser, and silently poisons your corpus with garbage. Detecting these is a routing problem, covered in Part 4.

1.4 The 2026 landscape: three families of "OCR"#

As of November 2026, "do OCR" is really a choice among three families:

Family Examples Strengths Weaknesses
Classical open-source engines Tesseract, EasyOCR, PaddleOCR, RapidOCR, docTR, surya Free, local, deterministic, no per-page cost, fast on CPU for Tesseract Accuracy ceiling below modern VLMs on hard scans; layout/table recovery is limited; per-engine language and script support varies
Cloud document-AI services Google Document AI, Azure AI Document Intelligence, AWS Textract, Mistral OCR Managed, per-page pricing, structured output (key-value, tables, signatures), confidence scores, SLA-backed Per-page cost adds up; data leaves your perimeter; vendor lock-in; quality varies by document type
VLMs as OCR OpenAI, Anthropic, Gemini, OpenRouter vision models Best-in-class on hard layouts, handwriting, unusual fonts, tables, figures; can return Markdown or JSON directly Highest per-page cost; probabilistic (can hallucinate or omit); slower; no word-level confidence unless the provider supplies it

A fourth group sits between the first and third: open-weight document VLMs (olmOCR, PaddleOCR-VL, DeepSeek-OCR, Granite-Docling, Chandra and others), small vision-language models trained specifically to turn a page image into Markdown that you run on your own GPU. They behave like a VLM (fluent output, can hallucinate, no per-word confidence) but cost like infrastructure and keep documents inside your perimeter. They get their own section, 2.4.1.

There is no single winner. A production pipeline typically routes: cheap classical OCR for clean scans, document-AI for structured forms, VLM escalation for pages the cheap paths fail — exactly the hybrid strategy 05.2 introduces for PDFs.

1.5 Why OCR still matters when VLMs exist#

It is tempting to conclude "just send every scan to a frontier model". Four engineering reasons say otherwise:

  • Cost. A VLM read of a dense page costs image-token pricing plus output tokens — orders of magnitude more per page than Tesseract's electricity. For bulk archives, classical OCR wins by a wide margin. (Part 12 builds the calculator.)
  • Determinism and auditability. Tesseract on the same image gives the same answer every time, with per-word confidence scores and bounding boxes you can store as provenance. A VLM can return a slightly different transcription each run.
  • Throughput and offline operation. Classical engines run on CPU in your own infrastructure — no rate limits, no data residency issues, no per-page bill. Millions of pages are an OCRmyPDF/Tesseract job, not an API budget.
  • VLMs fail differently. They can confidently invent text that isn't there, silently drop a column, or "helpfully" fix a total that was actually correct. Classical OCR fails visibly — garbage characters, low confidence — which is easier to detect and route around. Part 8 is entirely about taming these failure modes.

The mature answer in 2026 is routing and hybrid pipelines: classify each page's difficulty, send easy pages to the cheapest engine, escalate the hard tail to a VLM, and measure everything against a ground-truth set.


Part 2: The OCR toolbox#

2.1 Classical open-source engines#

All versions and licences below verified on PyPI/GitHub as of November 2026.

Engine Package Version (Nov 2026) Licence Runs on Strengths Weaknesses
Tesseract pytesseract (wrapper) + tesseract binary; tesserocr (Cython bindings) pytesseract 0.3.13; engine 5.5.x Apache-2.0 (wrapper); Apache-2.0 (engine) CPU Battle-tested on hundreds of millions of PDFs; 100+ languages; hOCR/ALTO/TSV/PDF outputs; per-word confidence; free Weakest on handwriting, degraded scans, complex layouts; accuracy depends heavily on preprocessing
OCRmyPDF ocrmypdf 17.13.0 MPL-2.0 CPU (needs Tesseract + Ghostscript) Adds a searchable text layer inside a PDF, preserving layout; deskew/clean/rotate built in; parallel jobs PDF-in-PDF-out only; inherits Tesseract's accuracy ceiling; needs two external binaries
EasyOCR easyocr 1.7.2 Apache-2.0 CPU (slow) / GPU (recommended) 80+ languages incl. CJK and Arabic; simple readtext() API; returns boxes + confidence PyTorch dependency is heavy; last release Sep 2024 — stable but slow-moving; GPU strongly advised
PaddleOCR paddleocr 3.7.0 Apache-2.0 CPU/GPU (PaddlePaddle or ONNX engine) State-of-the-art open accuracy (PP-OCRv5/v6); 100+ languages; detection+recognition+orientation pipeline; predict() API Heavy install (PaddlePaddle or onnxruntime); model downloads on first run; Chinese-first ecosystem
RapidOCR rapidocr 3.10.0 Apache-2.0 CPU/GPU via ONNX Runtime, OpenVINO, TensorRT, MNN PP-OCR models repackaged for ONNX; pip install is light; no PaddlePaddle needed; configurable engines Younger project; fewer languages than PaddleOCR proper; you manage model downloads
docTR python-doctr 1.1.0 Apache-2.0 CPU/GPU (PyTorch) Modular detect+recognise architecture; many architectures (DB, CRNN, MASTER, ViTSTR); research-friendly PyTorch dependency; more assembly required; accuracy trails PaddleOCR on messy scans
surya / marker surya-ocr / marker-pdf surya 0.23.0; marker 2.1.0 Apache-2.0 GPU strongly recommended Layout-aware OCR + reading order + table recognition; marker turns PDFs into clean Markdown GPU practically required; slower; heavier models to download

2.2 OCRmyPDF: searchable PDFs, the unsung workhorse#

If your input is a scanned PDF and your goal is a searchable PDF (a text layer you can select, search and copy, invisible beneath the page image), OCRmyPDF is the default tool. It is not "OCR" in the extract-text sense — it is a PDF pipeline that rasterizes each page, runs Tesseract, and grafts the recognised text back into the PDF as an invisible layer, producing a searchable PDF (PDF/A when --output-type allows). Verified behaviour as of v17.13.0:

bash
# Basic: scanned PDF in, searchable PDF/A out
ocrmypdf --language eng+fra --deskew --rotate-pages --jobs 4 scans.pdf searchable.pdf

# Skip pages that already have a text layer (mixed born-digital + scanned)
ocrmypdf --mode skip mixed.pdf out.pdf

# Re-OCR pages, replacing a bad existing text layer
ocrmypdf --mode redo badlayer.pdf out.pdf

# Plain text sidecar of what OCR found (only pages OCR actually ran on)
ocrmypdf --sidecar output.txt --output-type none scans.pdf -

The Python API takes the same options, which makes it callable from a pipeline:

python
# s2_2_ocrmypdf_api.py — same options as the CLI; needs ocrmypdf plus tesseract and ghostscript on PATH
from ocrmypdf import ocr

ocr("scans.pdf", "searchable.pdf", language=["eng"], deskew=True, jobs=4)

Key options worth memorising: --language (Tesseract codes joined by +), --deskew and --rotate-pages (image fixes), --clean/--clean-final (unpaper cleanup), --jobs N (parallel pages), --mode skip|redo|force|strip, --sidecar (companion text), --skip-big MP (skip absurdly large pages), --tesseract-timeout SEC (default 180 s/page), --output-type auto|pdf|pdfa|pdfa-1|pdfa-2|pdfa-3|none (auto — the v17 default — is best-effort PDF/A and falls back to a plain PDF when conversion isn't safe; pdfa/pdfa-1/pdfa-2/pdfa-3 are the explicit archival targets). OCRmyPDF refuses to OCR a page that already has text unless you pass a --mode — that guard is a feature: it stops you from double-OCRing born-digital content.

2.3 Cloud document-AI services#

When you need managed OCR with structure — key-value fields, tables, signatures, IDs — the hyperscalers and Mistral sell it per page. Pricing below is the published list structure as of November 2026; always re-check the pricing page before budgeting, and note that per-page prices are volatile and tiered.

Service Engine/model Price structure (Nov 2026, USD) Structured output Notable limits/notes
Mistral OCR mistral-ocr-4-1 (July 2026; mistral-ocr-latest alias) $4 / 1,000 pages; $5 / 1,000 annotated pages; Batch API at 50% off Markdown text, tables (table_format), paragraph blocks with bboxes + block labels, confidence at page/word/block granularity, schema-driven extraction via document_annotation_format POST /v1/ocr is synchronous, whole-document; pages selects pages (0-indexed); 40+ languages; docs/PDF/PPTX/DOCX/images
Google Document AI Enterprise Document OCR; Layout Parser; Form Parser; prebuilt Invoice/Receipt/ID/etc. OCR $1.50/1k pages (first 1k free/mo); Layout $10/1k; Form/Custom $30/1k; prebuilt parsers ~$0.10 per document (≤10 pages) Full Document proto: text, pages, blocks, tables, form fields, entities, confidence per element Online (sync) and batch APIs; processor must be created in a region; failed requests not billed
Azure AI Document Intelligence prebuilt-read, prebuilt-layout, prebuilt-invoice, prebuilt-receipt, prebuilt-idDocument, custom models Read $1.50/1k pages; Layout + prebuilts $10/1k; custom $30/1k; classifier $3/1k; add-ons ~$6/1k each; query fields ~$10/1k Markdown or full AnalyzeResult: pages, lines, words, tables, selection marks (☒/☐), key-value pairs, confidence begin_analyze_document is a long-running poller; F0 free tier reads only the first 2 pages of any file — a silent truncation trap
AWS Textract DetectDocumentText, AnalyzeDocument (FORMS/TABLES/SIGNATURES/QUERIES), AnalyzeExpense, AnalyzeID, AnalyzeLending DetectText $0.0015/page; AnalyzeExpense $0.01/page; Tables $0.015, Forms $0.05, Queries $0.015, combined $0.07/page; IDs $0.025/page (first 100k) Blocks JSON: LINE/WORD/KEY_VALUE_SET/TABLE/CELL/SELECTION_ELEMENT/SIGNATURE/QUERY_RESULT, each with confidence Synchronous APIs size-limited; StartDocumentAnalysis for async; AWS states inputs may be used to improve Textract unless you opt out via AWS Organizations — check data terms

Two structural differences matter more than headline price:

  • Billing unit. Google and Azure bill per page (per 1,000 pages); AWS bills per page too but at different per-API rates; Mistral bills per page with a premium for "annotated" (block/bbox) output. Google's prebuilt parsers bill per document (a count = up to 10 pages) — a 1-page invoice costs the same as a 10-page one.
  • Where structure comes from. Textract/Azure/Document AI return field-level structure trained for forms; Mistral returns layout-level structure (blocks, tables, markdown) plus optional schema extraction. If you need "invoice total" as a field, prebuilt models or Mistral's annotation format fit; if you need faithful text + tables, Mistral or Layout-tier services fit.

2.3.1 Calling cloud OCR (verified call shapes, as of November 2026)#

Mistral OCR — the simplest dedicated OCR API: one synchronous call returns the whole document as Markdown, per-page blocks and optional confidence. mistralai 3.7.0:

python
import os
from mistralai.client import Mistral

client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])

resp = client.ocr.process(
    model="mistral-ocr-latest",            # or pin "mistral-ocr-4-1"
    document={"type": "document_url", "document_url": "https://example.com/scan.pdf"},
    table_format="markdown",               # tables as Markdown ("html" also supported)
    include_blocks=True,                   # paragraph-level bboxes + block labels
    confidence_scores_granularity="block", # page | word | block
    # pages="0,2-4",                       # optional: only these pages (0-indexed)
)
for page in resp.pages:
    print(page.markdown)                   # the page text
# page.blocks, page.images, page.confidence_score carry structure/provenance

AWS Textract — boto3 1.43.x; documents go in as Bytes or an S3Object reference:

python
import boto3

textract = boto3.client("textract")       # uses your AWS credential chain
resp = textract.analyze_document(
    Document={"S3Object": {"Bucket": "my-bucket", "Name": "scans/inv-2041.png"}},
    FeatureTypes=["TABLES", "FORMS"],     # or use analyze_expense / analyze_id
)
for block in resp["Blocks"]:
    if block["BlockType"] == "LINE":
        print(block["Text"], block.get("Confidence"))

Google Document AI (google-cloud-documentai 3.17.0) and Azure AI Document Intelligence (azure-ai-documentintelligence 1.0.2) use long-running/batch-style calls with a processor/resource you create first — their quickstarts are in Further resources. All four return per-element confidence and geometry suitable for provenance metadata.

2.4 VLMs as OCR#

Every frontier vision model can transcribe an image or PDF page. The mechanics of sending images and PDFs — content-part shapes, size limits, media token costs, the Files APIs — are owned by 03.6, which you should read first; Part 8 of this lesson covers the OCR-specific decisions on top. The one-paragraph version: you send a page image (or a PDF, which providers rasterise for you) with a prompt like "transcribe this page exactly", and get Markdown or JSON back. Cost is per-page-image tokens plus output tokens — see 03.6, Part 3 for the estimator and 03.6, 4.1 for per-provider PDF behaviour.

2.4.1 Open-weight document VLMs: the fourth family#

Between "Tesseract on CPU" and "send the page to a frontier model" there is now a well-populated middle: models of roughly 0.3 to 7 billion parameters whose only job is page-to-Markdown. They matter for three reasons: privacy (pages never leave your network), unit cost at volume (you pay for GPU time, not for a per-page or per-token API price) and control (you can pin the exact weights, so a regression test run today is comparable next year). They appeared mostly after October 2025, so expect rapid churn: the table is a map of the field as of November 2026, not a ranking.

Model Maker and size Licence (as read November 2026) What to know
olmOCR (olmocr 0.4.27 on PyPI; model olmOCR-2-7B-1025) Allen Institute for AI, 7B VLM Apache-2.0 Full pipeline (page rendering, batching, retries) plus the model. The README asks for a recent NVIDIA GPU with at least 12 GB of VRAM and serves the FP8 build through vLLM. Its own benchmark, olmOCR-Bench (over 7,000 test cases across 1,400 documents), reports 82.4 for the pipeline. No first-party hosted API: the README lists third-party providers at about $0.07-$0.10 per million input tokens and $0.15-$0.20 per million output tokens (Cirrascale, DeepInfra, Parasail)
PaddleOCR-VL (inside paddleocr 3.7.0; release 1.6) Baidu, 0.9B VLM Apache-2.0 Small enough for modest GPUs; structured Markdown and JSON output; 111 languages per the project's README (stated for PaddleOCR-VL-1.5; 1.6 keeps the same architecture). The same toolkit has PP-StructureV3, a classical-plus-layout pipeline that returns finer coordinates (table cell boxes) than the VLM, which is exactly what provenance wants
DeepSeek-OCR (and DeepSeek-OCR2, announced 27 January 2026) DeepSeek MIT (original repository) Built around "optical context compression": the page is encoded into few vision tokens (64 to 400 depending on a resolution mode, plus a dynamic mode), which keeps the decoder cheap. Research-flavoured install (specific CUDA, PyTorch and vLLM versions in its README)
Granite-Docling-258M IBM, about 0.3B Apache-2.0 Emits DocTags, Docling's structured markup, which Docling converts to a DoclingDocument; run it with docling --pipeline vlm --vlm-model granite_docling or the SDK's VlmPipeline. English is the main language; Japanese, Arabic and Chinese are marked experimental
Chandra OCR (chandra-ocr; Chandra 2, March 2026) Datalab Code Apache-2.0, weights under a modified OpenRAIL-M licence: free for research, personal use and startups under $2M in funding or revenue, no use to compete with the maker's API, separate licence for commercial self-hosting The best illustration of why you read the licence: the code is permissive, the weights are not. Self-reported benchmark results favour it, so treat them as claims to re-measure

Other names you will meet (check each model card before relying on it): dots.ocr, MinerU (whose newer versions use a VLM backend and which carries extra licence terms, 05.2, 7.1) and the OCR checkpoints in the Qwen-VL and InternVL families. Sources for the table, all opened in November 2026: the GitHub READMEs of allenai/olmocr, PaddlePaddle/PaddleOCR, deepseek-ai/DeepSeek-OCR and datalab-to/chandra, and the Hugging Face model card ibm-granite/granite-docling-258M.

How you run them. Almost all of them serve through vLLM (an inference server that exposes an OpenAI-compatible HTTP API), so your pipeline code looks the same as for a hosted VLM, with a different base_url:

python
# s2_4_1_local_vlm_ocr.py — illustrative: needs a vLLM (or similar) server you started yourself,
# e.g. `vllm serve <model> --max-model-len 16384` on a GPU machine (command from the olmOCR README).
# Client side only needs: uv add openai python-dotenv   (the OpenAI SDK just talks to your server).
import base64
import os
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI(
    base_url=os.environ.get("LOCAL_OCR_BASE_URL", "http://localhost:8000/v1"),
    api_key=os.environ.get("LOCAL_OCR_API_KEY", "not-needed-for-local"),  # a local server ignores it
)
MODEL = os.environ["LOCAL_OCR_MODEL"]       # exactly the name your server reports at /v1/models

# Each model documents its own prompt (some expect a fixed instruction or special tokens).
# Use the model card's prompt in production; this generic one only shows the call shape.
PROMPT = "Transcribe this page to Markdown faithfully. Do not summarise. Mark illegible text [illegible]."

img_b64 = base64.b64encode(Path("page1.png").read_bytes()).decode("ascii")
resp = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}"}},
        {"type": "text", "text": PROMPT},
    ]}],
    max_tokens=4096,
    temperature=0,               # a local open-weight server accepts sampling parameters
)
choice = resp.choices[0]
print(choice.finish_reason, len(choice.message.content or ""), "characters")
print((choice.message.content or "")[:300])
Example output · illustrative5 lines
stop 2841 characters
<!-- page 1 -->
# Acme Product Handbook
Version 3.2 — January 2026
...

Engineering notes that decide whether this works in production:

  • Check finish_reason. Small OCR models sometimes fall into repetition loops (the same line or table row repeated until the token limit). A length finish on a page whose image is mostly short text is a red flag: retry once at a different resolution, then escalate the page.
  • No per-word confidence. Like frontier VLMs, they return text only. Build confidence from outside: length versus the text-layer check of Part 4, agreement with a second engine on a sample, and the review queue of 6.5.
  • GPU capacity planning. Throughput depends on page density, image resolution (the vision-token budget) and batching, so measure pages per second on your pages and GPU before you buy hardware. Compare cost per 1,000 pages using the calculator of Part 12: amortised GPU-hours versus API prices, including idle time.
  • Benchmarks are a starting list, not a verdict. OmniDocBench (OpenDataLab, accepted at CVPR 2025; 1,651 pages scored on text, tables, formulas and reading order) and olmOCR-Bench are the two public suites most model cards cite. Check the licence of the dataset as well as the model (OmniDocBench's data is stated to be for research use only), remember that vendors report their own runs, and always rank candidates on a 50 to 100 page sample of your corpus scored with the CER/WER code of 6.3.
  • Version pinning is lineage. Record the model repository, revision hash and prompt in ParseInfo.parser_version (05.2, Part 9); a silently updated checkpoint changes your corpus.

2.5 Decision table: which engine for which job#

Document type First choice Escalate to Why
Clean born-digital PDF No OCR — extract text layer (05.2) — OCR a text PDF and you lose accuracy and structure
Clean printed-English scans, bulk archive Tesseract via pytesseract/OCRmyPDF VLM on low-confidence pages Free, fast, deterministic, per-word confidence
Searchable-PDF deliverable OCRmyPDF — It's the only tool that grafts text back into the PDF properly
Scanned invoices/receipts at volume Textract AnalyzeExpense / Azure prebuilt / Document AI prebuilt LLM schema extraction for odd layouts Trained field extractors beat generic OCR for key-value data
Tables-heavy scans, complex layouts Mistral OCR / Azure Layout / Document AI Layout Parser VLM transcription + table-to-Markdown Layout-tier services recover structure classical OCR flattens
Handwriting (neat forms) VLM; Azure/Document AI form parsers Human review queue Classical engines are weakest here; VLMs are much better but not perfect
Handwriting (messy/cursive) VLM + human-in-the-loop — Expect errors; design for review, not automation
Low-quality fax / thermal receipts Preprocess hard, then Tesseract; VLM if still bad — Faded thermal paper is the classic Tesseract killer; VLMs cope better
Multilingual non-Latin (CJK, Arabic, Devanagari) PaddleOCR/RapidOCR (PP-OCRv5: 100+ langs), EasyOCR VLM Tesseract's coverage is broad but thinner for some scripts; verify per-language
IDs, passports, licences Textract AnalyzeID / Azure prebuilt-idDocument VLM cross-check MRZ and security-print need specialised handling
Screenshots, UI captures, whiteboard photos Tesseract --psm 6/11 or VLM — Sparse text suits PSM 11 or a VLM that reads context
Anything where you need an audit trail Tesseract/cloud with confidence + stored boxes — VLMs give no per-word confidence (mostly)
"Just get me text, any cost" small batches VLM transcription — Simplest correct answer for < a few thousand pages
Pages must not leave your network, high volume Open-weight document VLM on your own GPU (2.4.1) Frontier VLM for failures only if policy allows; otherwise human review Fixed GPU cost instead of per-page prices; you own the confidence and verification layer

2.6 Failure modes to expect from each family#

  • Tesseract: garbage on blur/fade/skew; column interleaving on complex layouts; weak handwriting; confident wrong answers on stylised fonts; language-pack mismatches produce plausible-looking nonsense.
  • Deep engines (EasyOCR/PaddleOCR/etc.): GPU/driver friction; model downloads on first run; occasionally worse than Tesseract on clean scans (more moving parts); detection boxes can merge or split lines on dense pages.
  • Cloud document AI: per-page cost; silent quality variation across document types; data-residency and data-use terms (Textract's improvement clause; check each provider's terms); rate limits and quotas at volume.
  • Open-weight document VLMs: the VLM failures below plus repetition loops, model-specific prompt formats, GPU/driver friction and licences that differ between code and weights.
  • VLMs: hallucinated or omitted text that looks fluent; no guaranteed verbatim fidelity unless prompted and verified; cost and latency per page; non-determinism complicates regression testing.

Part 3: Preprocessing images for OCR#

Deep-dive

Preprocessing is the highest-leverage, most-mishandled stage of classical OCR. Get it right and a mediocre engine reads cleanly; get it wrong and you destroy information before recognition starts.

3.1 Resolution: give the engine enough pixels#

OCR accuracy is dominated by effective resolution — how many pixels represent each character. The rule of thumb across the literature and vendor docs: aim for roughly 200–300 DPI for printed text (300 DPI is the standard archival scan setting; below ~150–200 DPI accuracy falls off a cliff on small fonts). A letter-size page (8.5×11 in) at 300 DPI is about 2550×3300 px ≈ 8.4 megapixels — which is why OCRmyPDF's docs illustrate --skip-big in megapixels: their example skips pages over 50 MP, and a 300 DPI letter page is 8.4 MP, comfortably under it.

Practical consequences:

  • A 72-DPI screenshot of a document (what you get from many web captures and PDFs rendered at "web" quality) is usually too low for reliable OCR. Upscale 2–4× before recognising, or send it to a VLM which downsamples internally anyway.
  • A 600-DPI scan is often too high for Tesseract: it slows OCR, can trip internal image-size limits (Tesseract caps dimensions around 32,767 px and OCRmyPDF downsamples automatically), and wastes memory. Downsample to ~300 DPI for recognition while keeping the original for the PDF output.
  • Phone photos of documents are frequently tilted, shadowed, shot at an angle (keystone distortion — 3.4) and low-contrast — the motivating case for the rest of this part.

3.2 The preprocessing toolkit#

Two libraries cover almost everything: Pillow (pillow 13.0.0, MIT-CMU) for basic transforms and OpenCV (opencv-python / opencv-python-headless 5.0.x, Apache-2.0) for the heavier vision work. Pillow is already in your Setup; install OpenCV only if you want deskew/denoise:

bash
uv add opencv-python-headless   # headless = no GUI libs, better for servers

preprocess.py — a small, composable toolkit. Each function is deliberately independent so you can A/B them on real scans:

python
"""preprocess.py: OCR-oriented image fixes with Pillow + OpenCV.

Rule of thumb: apply the *minimum* needed. Every aggressive step can remove
real content (a faint stamp, a pencil annotation, a table rule). Keep the
original; store which steps ran as metadata (05.8).
"""
from pathlib import Path

from PIL import Image, ImageOps, ImageFilter, ImageEnhance


def load_rgb(path: str | Path) -> Image.Image:
    """Open an image and normalise to RGB (OCR engines dislike palette/CMYK/grayscale surprises)."""
    img = Image.open(path)
    img.load()
    return img.convert("RGB")


def fix_orientation(img: Image.Image) -> Image.Image:
    """Apply EXIF orientation (phone photos store rotation as metadata, not pixels)."""
    return ImageOps.exif_transpose(img)


def to_grayscale(img: Image.Image) -> Image.Image:
    """OCR is about shape, not colour; grayscale also halves memory."""
    return ImageOps.grayscale(img)


def autocontrast(img: Image.Image, cutoff: int = 1) -> Image.Image:
    """Stretch histogram so faint text becomes darker. cutoff=1 clips 1% tails."""
    return ImageOps.autocontrast(img, cutoff=cutoff)


def denoise(img: Image.Image) -> Image.Image:
    """Median filter: kills salt-and-pepper scanner noise, keeps edges. Use sparingly."""
    return img.filter(ImageFilter.MedianFilter(size=3))


def sharpen(img: Image.Image) -> Image.Image:
    return ImageEnhance.Sharpness(img).enhance(1.5)


def upscale(img: Image.Image, factor: int = 2) -> Image.Image:
    """Upscale for engines that need bigger glyphs. LANCZOS smooths; NEAREST is crisper but blockier."""
    w, h = img.size
    return img.resize((w * factor, h * factor), Image.Resampling.LANCZOS)


def add_border(img: Image.Image, px: int = 50, color: int = 255) -> Image.Image:
    """White border: Tesseract docs recommend it when text is cropped tight to the edge."""
    canvas = Image.new("L", (img.width + 2 * px, img.height + 2 * px), color)
    canvas.paste(img, (px, px))
    return canvas


def binarize(img: Image.Image, threshold: int = 180) -> Image.Image:
    """Hard threshold to pure black/white. Simple; Otsu/adaptive (below) are smarter."""
    g = to_grayscale(img)
    return g.point(lambda p: 0 if p < threshold else 255, "1")


def binarize_otsu(img: Image.Image) -> Image.Image:
    """Otsu's method picks the threshold that best separates ink from paper."""
    import cv2
    import numpy as np

    gray = np.array(to_grayscale(img))
    _, bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    return Image.fromarray(bw)


def binarize_adaptive(img: Image.Image, block_size: int = 31, c: int = 15) -> Image.Image:
    """Adaptive threshold: each pixel is thresholded against its local
    neighbourhood, so shadows and lighting gradients don't erase faint text.
    block_size must be odd; c is subtracted from the local mean (higher = more
    aggressive ink detection)."""
    import cv2
    import numpy as np

    gray = np.array(to_grayscale(img))
    bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                               cv2.THRESH_BINARY, block_size, c)
    return Image.fromarray(bw)


def estimate_dpi(img: Image.Image) -> float | None:
    """DPI stored in image metadata, if any. Phone photos usually have none."""
    return img.info.get("dpi", (None, None))[0]

3.3 Deskew and orientation#

Two distinct problems people conflate:

  • Orientation (0/90/180/270°): the page is sideways or upside-down. Tesseract's image_to_osd detects it; OCRmyPDF's --rotate-pages fixes it per page. For a pipeline, run OSD once per page, cache the result, rotate, then OCR.
  • Skew (a few degrees of tilt): the page is crooked but roughly upright. Detect by finding the dominant text-line angle — OpenCV's minAreaRect on the text pixels, or projection-profile methods — then warpAffine to straighten. OCRmyPDF's --deskew and PaddleOCR's use_doc_unwarping do this internally.
python
"""deskew.py: estimate skew angle with OpenCV and rotate to correct it."""
import cv2
import numpy as np
from PIL import Image


def deskew_angle(img: Image.Image) -> float:
    """Clockwise tilt of the text baseline in degrees (0.0 = already level).

    Positive means the text slopes down to the right. Measured from the
    geometry of the minimum-area rectangle's corners rather than
    minAreaRect's `angle` field: OpenCV's angle convention has flip-flopped
    across releases ([-90, 0) before 4.5.1, (0, 90] in 4.5.1-4.12, [-90, 0)
    again from 4.13/5.x), while the corner points are stable — so we derive
    the skew ourselves and never depend on that convention.
    """
    gray = np.array(img.convert("L"))
    # Invert: ink becomes white on black
    bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
    ys, xs = np.where(bw > 0)
    if len(xs) < 100:
        return 0.0                                       # too little text to judge
    coords = np.column_stack((xs, ys))                   # minAreaRect wants (x, y)
    box = cv2.boxPoints(cv2.minAreaRect(coords))          # 4 corners of best-fit rect
    # Angle of each edge; an edge is a direction, so fold into [-90, 90)
    edges = np.roll(box, -1, axis=0) - box
    deg = np.degrees(np.arctan2(edges[:, 1], edges[:, 0]))
    folded = (deg + 90.0) % 180.0 - 90.0
    # Text baselines are the near-horizontal edges -> smallest |angle|
    return float(folded[np.argmin(np.abs(folded))])


def deskew(img: Image.Image, max_angle: float = 10.0) -> Image.Image:
    """Rotate to correct skew, but only for small angles — big 'skew' is probably a rotated page."""
    angle = deskew_angle(img)
    if abs(angle) < 0.1 or abs(angle) > max_angle:
        return img
    # For cardinal orientation errors (0/90/180/270), use pytesseract.image_to_osd
    # or OCRmyPDF --rotate-pages instead — this function only fixes small skew.
    # `angle` is the clockwise tilt; PIL's positive angle rotates counter-clockwise,
    # which is exactly the correction needed.
    return img.rotate(angle, expand=True, fillcolor="white")
Aggressive step What it destroys
Hard binarization on a photo with shadows/gradients Faint text disappears into "background"; stamps and pencil marks vanish
Denoising/upscaling before a deep engine (PaddleOCR, EasyOCR) These models were trained on natural images; over-cleaned input can fall outside their training distribution and get worse
Deskewing a page that's actually a two-page spread or has a rotated stamp The "skew" is content, not error; you shear real structure
Cropping tight to detected text bounds Loses margin context that helps layout reconstruction; Tesseract docs explicitly warn tight crops hurt
JPEG re-encode at low quality before OCR Compression artefacts around glyph edges are exactly what recognizers are sensitive to

Rule: preprocess the minimum needed for the engine you're using. Tesseract wants clean, high-contrast, deskewed input; modern deep engines and VLMs prefer near-original images. Keep the raw scan and record every transform as metadata (05.8).

3.4 Perspective correction: photos of documents#

Deskew fixes rotation; a phone photo held at an angle also suffers keystone distortion — the page becomes a trapezoid, text lines converge toward a vanishing point, and one edge of the page is physically closer to the camera (and thus larger) than the other. The single most impactful fix for phone photos is a four-point perspective transform: find the page's four corners, then warp them onto a rectangle.

python
"""rectify.py: detect a document's four corners and warp it flat."""
import cv2
import numpy as np
from PIL import Image


def _order_points(pts: np.ndarray) -> np.ndarray:
    """Order 4 points as top-left, top-right, bottom-right, bottom-left."""
    rect = np.zeros((4, 2), dtype="float32")
    s = pts.sum(axis=1)
    rect[0] = pts[np.argmin(s)]          # smallest x+y -> top-left
    rect[2] = pts[np.argmax(s)]          # largest  x+y -> bottom-right
    diff = np.diff(pts, axis=1)          # y - x per point
    rect[1] = pts[np.argmin(diff)]       # smallest y-x -> top-right
    rect[3] = pts[np.argmax(diff)]       # largest  y-x -> bottom-left
    return rect


def rectify_document(img: Image.Image) -> Image.Image:
    """Perspective-correct a photo of a document. Returns the original image
    unchanged if no clean quadrilateral is found — never guess."""
    rgb = np.array(img.convert("RGB"))
    gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
    edges = cv2.Canny(cv2.GaussianBlur(gray, (5, 5), 0), 50, 150)
    contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return img
    # The page is usually the largest quadrilateral-ish contour
    page = max(contours, key=cv2.contourArea)
    approx = cv2.approxPolyDP(page, 0.02 * cv2.arcLength(page, True), True)
    if len(approx) != 4:
        return img                        # not a clean quad -> leave it alone

    rect = _order_points(approx.reshape(4, 2).astype("float32"))
    (tl, tr, br, bl) = rect
    # Output size: the longer of the two pairs of opposite edges
    width = int(max(np.linalg.norm(br - bl), np.linalg.norm(tr - tl)))
    height = int(max(np.linalg.norm(tr - br), np.linalg.norm(tl - bl)))
    dst = np.array([[0, 0], [width - 1, 0],
                    [width - 1, height - 1], [0, height - 1]], dtype="float32")
    M = cv2.getPerspectiveTransform(rect, dst)
    return Image.fromarray(cv2.warpPerspective(rgb, M, (width, height)))

3.5 A before/after reference table#

Input problem Symptom in output Fix that usually works Fix that often makes it worse
72-DPI web screenshot Missed small text, broken words Upscale 2–4× or use a VLM Binarizing before upscaling
Phone photo, tilted Garbled lines, wrong reading order exif_transpose + deskew; perspective warp (3.4) if shot at an angle Aggressive denoise
Shadow across page One side reads, other side garbage autocontrast or adaptive threshold; VLM Global hard threshold
Faded thermal receipt Numbers wrong or dropped Contrast stretch; --psm 6; VLM fallback Sharpen (amplifies noise too)
Two-page book spread Columns interleave Crop to single page or --psm 3 with layout model; VLM Deskew assuming one text block
Skewed fax Characters clipped at line edges Deskew ± few degrees Rotate assuming orientation error
Coloured logo/stamp over text Recognition noise in stamp area Crop region of interest or mask Binarize (stamp becomes "text")

Part 4: Detecting scanned pages and routing#

A PDF page can be: all text, all image, or a mix — and it can carry a hidden OCR layer that's wrong. You can't decide "this document needs OCR" at the file level; you route per page.

4.1 Signals that a page needs OCR#

From the parsed representation (05.2's ParsedDocument), these signals identify image-only or bad-text pages:

  • Text coverage ratio: extracted characters (or words) per unit page area. A born-digital page yields hundreds–thousands of characters; a pure scan yields ~0.
  • Image coverage: one image covering ~the whole page = scanned page. Several images = figures/regions to OCR selectively.
  • Font/glyph sanity: real text has real font encodings; OCR layers often produce suspicious symbol runs, broken ligatures, or characters outside the expected script.
  • Text-layer quality score: run a cheap heuristic — dictionary hit-rate, alphabetic ratio, vowel ratio for Latin text — on the extracted text. A layer that scores like noise is a bad OCR layer, not real text.
  • Per-page OCR confidence (if a previous OCR pass exists): mean word confidence below threshold = re-OCR or escalate.

4.2 A routing function#

route_page() turns page metadata into an engine decision. Pure Python — you can run it on real parsed data:

python
"""route_page.py: decide which OCR path a PDF page should take.

Input is a dict of signals you compute during parsing (05.2). Output is one
of: 'skip' (has good text), 'ocr_classical', 'ocr_cloud', 'vlm', 'review'.
Thresholds are starting points — tune them on YOUR corpus (Part 6).
"""
from dataclasses import dataclass


@dataclass
class PageSignals:
    char_count: int          # characters extracted from the text layer
    image_coverage: float    # fraction of page area covered by images (0..1)
    text_quality: float      # 0..1 heuristic: looks like real language
    ocr_confidence: float | None = None  # mean word confidence if a prior OCR layer exists
    has_handwriting_hint: bool = False
    page_area_pt2: float = 0.0


def route_page(s: PageSignals) -> str:
    # 1. Real, good text -> nothing to do
    if s.char_count > 200 and s.text_quality > 0.6:
        if s.ocr_confidence is not None and s.ocr_confidence < 55:
            return "ocr_classical"      # text exists but prior OCR was shaky
        return "skip"

    # 2. Essentially no text and mostly one big image -> a scan
    if s.image_coverage > 0.5 and s.char_count < 50:
        if s.has_handwriting_hint:
            return "vlm"                 # handwriting: go straight to the strong model
        return "ocr_classical"           # try cheap first; escalate on failure

    # 3. Sparse text + images -> selective OCR of image regions, or VLM for the page
    if s.image_coverage > 0.15 and s.char_count < 400:
        return "vlm" if s.text_quality < 0.4 else "ocr_classical"

    # 4. Text exists but looks like noise -> bad OCR layer; redo it
    if s.char_count > 50 and s.text_quality < 0.4:
        return "ocr_classical"

    # 5. Almost nothing at all -> probably a figure/blank page; flag for review
    return "review"

Example run (real output — this is pure Python on hand-built signals):

python
cases = {
    "born_digital_page":   PageSignals(char_count=3200, image_coverage=0.05, text_quality=0.95),
    "clean_scan":          PageSignals(char_count=12,  image_coverage=0.98, text_quality=0.1),
    "bad_ocr_layer":       PageSignals(char_count=900,  image_coverage=0.9,  text_quality=0.25,
                                       ocr_confidence=41.0),
    "mixed_text_and_fig":  PageSignals(char_count=150,  image_coverage=0.3,  text_quality=0.7),
    "handwritten_form":    PageSignals(char_count=20,   image_coverage=0.95, text_quality=0.1,
                                       has_handwriting_hint=True),
    "figure_page":         PageSignals(char_count=5,    image_coverage=0.10, text_quality=0.0),
}
for name, sig in cases.items():
    print(f"{name:20} -> {route_page(sig)}")
Output6 lines
born_digital_page    -> skip
clean_scan           -> ocr_classical
bad_ocr_layer        -> ocr_classical
mixed_text_and_fig   -> ocr_classical
handwritten_form     -> vlm
figure_page          -> review

4.3 The routing pipeline#

flowchart TD
    A["PDF page"] --> B["Extract text layer<br/>(05.2 parser)"]
    B --> C{"text_quality<br/>+ char_count<br/>good?"}
    C -- "yes" --> D["skip: use text layer"]
    C -- "no / sparse" --> E{"image_coverage<br/>> 0.5?"}
    E -- "yes, clean print" --> F["Classical OCR<br/>Tesseract / PaddleOCR"]
    E -- "yes, handwriting" --> G["VLM transcription"]
    E -- "partial / mixed" --> H{"confidence<br/>good enough?"}
    F --> H
    H -- "yes" --> I["store text + boxes + conf"]
    H -- "no" --> J{"escalate?"}
    J -- "VLM budget ok" --> G
    J -- "else" --> K["review queue"]
    G --> I
    K --> L["human review"]

The escalation decision (H → J) is the heart of a cost-controlled pipeline: run the cheap engine, measure its confidence, and only spend VLM money on the pages that need it. Part 12 quantifies when escalation pays.


Part 5: Running classical OCR#

5.1 The Tesseract mental model#

Tesseract 5.x is the reference classical engine: a C++ binary (tesseract) plus pytesseract as its Python wrapper. Three concepts organise everything:

  • Language packs (eng, fra, deu, chi_sim, ara, …): each is a *.traineddata file in tesseract-ocr/tessdata containing character classifiers and language statistics. The tessdata repo ships ~128 language packs (plus osd.traineddata for orientation/script detection — 129 .traineddata files in total) and 37 script-level models (Latin, Cyrillic, HanS/HanT incl. vertical variants, Arabic, Devanagari, etc.) — verified against the repo as of November 2026. Script models cover scripts that have no single "language" (e.g. HanS for any Simplified-Chinese text).
  • OEM (OCR Engine Mode): --oem 1 = LSTM/neural nets only (what you want); --oem 0 = legacy engine (only in tessdata repo packs); --oem 3 = default/auto.
  • PSM (Page Segmentation Mode): tells Tesseract what kind of image it's looking at. The ones you'll actually use:
PSM Meaning Use for
3 Fully automatic page segmentation (default) Normal multi-column pages
4 Single column of variable-size text Tables, forms
6 Single uniform block of text Receipts, labels, cropped regions
7 Single text line One-line fields
11 Sparse text, find as much as possible Screenshots, scattered labels, stamps
12 Sparse text + OSD Sparse text needing orientation detection
13 Raw line Bypass Tesseract's layout hacks entirely

The wrong PSM never errors — it just silently produces worse text. That's why you test PSMs on representative scans.

5.2 pytesseract: the API#

pytesseract wraps the binary; every call shells out to tesseract. Key functions (all verified against the pytesseract README/source as of 0.3.13):

python
"""ocr_tesseract.py: the core pytesseract calls, with the options that matter."""
import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = "tesseract"   # or full path if not on PATH

img = Image.open("data/scans/invoice-2041.png")

# 1. Simplest: image -> plain text
text = pytesseract.image_to_string(img, lang="eng")

# 2. Verbose TSV: per-word boxes + confidences (needs Tesseract >= 3.05)
data = pytesseract.image_to_data(img, lang="eng", output_type=pytesseract.Output.DICT)
# data keys: level, page_num, block_num, par_num, line_num, word_num,
#            left, top, width, height, conf, text

# 3. Word boxes as characters (' ' separated x0,y0,x1,y1 per char)
boxes = pytesseract.image_to_boxes(img)

# 4. Orientation + script detection (needs osd.traineddata)
osd = pytesseract.image_to_osd(img)
# -> "Orientation in degrees: 0\nRotate: 0\nOrientation confidence: ...\nScript: Latin\n..."

# 5. Searchable PDF or hOCR directly from the image (both return bytes)
pdf_bytes  = pytesseract.image_to_pdf_or_hocr(img, extension="pdf")
hocr_bytes = pytesseract.image_to_pdf_or_hocr(img, extension="hocr")  # .decode() for text
alto_bytes = pytesseract.image_to_alto_xml(img)                       # .decode() for XML text

# 6. Multiple outputs in ONE tesseract call (saves compute — one OCR pass)
#    'txt' and 'tsv' are tesseract config names; tsv_out is a TSV *string*
#    (same shape as image_to_data's STRING output). This function has no
#    `config` parameter — for --psm/--oem use image_to_string/image_to_data
#    with config="--psm 6", each of which runs its own tesseract call.
text_out, tsv_out = pytesseract.run_and_get_multiple_output(
    img, extensions=["txt", "tsv"]
)

# 7. Timeout so a pathological page can't hang the pipeline
try:
    text = pytesseract.image_to_string(img, timeout=30)
except RuntimeError as e:
    print("OCR timed out:", e)

# Custom config string for OEM/PSM/params you can't pass as kwargs
custom = r"--oem 1 --psm 6 -c preserve_interword_spaces=1"
text = pytesseract.image_to_string(img, config=custom)

Example TSV row shape (illustrative — your coordinates differ):

text
5  1  1  1  1  3  120  240  36  18  96.4  Invoice
5  1  1  1  1  4  162  240  30  18  88.1  #
5  1  1  1  1  5  196  240  44  18  72.3  2041

(columns: level, page_num, block_num, par_num, line_num, word_num, left, top, width, height, conf, text)

5.3 PSM/OEM in practice#

The highest-value tuning knob is --psm. On a corpus audit, run each candidate PSM on ~20 representative pages and compare mean word confidence and spot-check outputs — confidence correlates with accuracy but isn't proof. Common recipes:

  • Normal page → --psm 3 (default) or --psm 1 (with OSD for rotated pages)
  • Receipt / label / cropped block → --psm 6
  • Single field (amount, date, signature line) → --psm 7 or --psm 8 (word) / --psm 13 (raw line)
  • Screenshot / scattered stamps → --psm 11

--oem 1 (LSTM) is right for essentially everything in Tesseract 5; --oem 3 is the safe default. Add -c preserve_interword_spaces=1 when spaces carry meaning (tables-as-text, aligned columns) and -c tessedit_char_whitelist=... for constrained fields like digit-only amounts.

5.4 The other classical engines, briefly#

Each is a real alternative when Tesseract's ceiling isn't enough. Install only what you need; outputs below are illustrative.

EasyOCR (PyTorch, GPU recommended):

python
import easyocr

reader = easyocr.Reader(["en"], gpu=True)          # load once; model weights download on first use
results = reader.readtext("data/scans/menu.png")   # [(bbox4pts, text, conf0to1), ...]
for box, text, conf in results:
    print(f"{conf:.2f}  {text}")

plain = reader.readtext("data/scans/menu.png", detail=0)   # just strings

PaddleOCR 3.x (PP-OCRv5/v6, best open accuracy, 100+ languages):

python
from paddleocr import PaddleOCR

# use_doc_* flags turn OFF the optional layout/orientation models for plain OCR
ocr = PaddleOCR(
    use_doc_orientation_classify=False,
    use_doc_unwarping=False,
    use_textline_orientation=False,
)
result = ocr.predict("data/scans/contract-page.png")
for res in result:
    res.print()                 # text + boxes + scores to stdout
    res.save_to_json("out.json")
    res.save_to_img("out.jpg")  # visualised boxes

Requires paddlepaddle (or the onnxruntime/transformers inference engine); models download on first run.

RapidOCR (ONNX repackaging of PP-OCR models — light install, CPU-friendly):

python
from rapidocr import RapidOCR

engine = RapidOCR()                     # ONNX Runtime backend by default
result = engine("data/scans/sign.png")
print(result.txts)                      # ['MERIDIAN', 'HEALTH', '...']
print(result.scores)                    # [0.98, 0.91, ...]
result.vis("vis.jpg")                   # draw boxes

docTR (modular detect+recognise, research-friendly):

python
from doctr.io import DocumentFile
from doctr.models import ocr_predictor

predictor = ocr_predictor(det_arch="db_resnet50", reco_arch="crnn_vgg16_bn", pretrained=True)
result = predictor(DocumentFile.from_images("data/scans/form.png"))
result.show()

surya / marker (layout-aware, GPU recommended): surya does OCR + reading order + table structure; marker converts whole PDFs to Markdown. These are the closest open-source things to "classical OCR that understands layout" — worth it when PaddleOCR/RapidOCR flatten your tables.

5.5 Multilingual packs and non-Latin scripts#

  • Tesseract: language codes are 3-letter ISO 639-2 (eng, fra, deu, spa, jpn, chi_sim, ara, heb, kor, …). Combine with +: lang="eng+fra". For scripts without a language pack, use the script/ models (Latin, HanS, HanT, Arabic, Cyrillic, Devanagari, Hangul, …) — note vertical CJK needs HanS_vert/HanT_vert/Japanese_vert/Hangul_vert. Install packs into tessdata/ or point TESSDATA_PREFIX/--tessdata-dir at them. RTL languages (Arabic, Hebrew, Persian) work but Tesseract's line ordering and shaping have known quirks — verify on real samples.
  • Deep engines: EasyOCR takes language codes like en, fr, ch_sim, ja, ko, ar, hi; PaddleOCR's PP-OCRv5 recognises 100+ languages via lang=; RapidOCR exposes PP-OCRv4/v5 language routes.
  • VLMs: handle multilingual and mixed-language pages far more gracefully — often the right answer for a corpus that's genuinely multi-script.

5.6 OCRmyPDF end-to-end#

For the common case "scanned PDF → searchable PDF + extracted text", OCRmyPDF is the pipeline:

bash
# 1. Detect which pages lack a text layer (your router, Part 4)
# 2. OCR only those pages, deskewed, parallel, searchable PDF out
ocrmypdf --mode skip --language eng --deskew --rotate-pages \
         --jobs 8 --output-type pdfa --sidecar page-text.txt \
         contracts-scan.pdf contracts-searchable.pdf

# 3. Extract the text layer for downstream chunking (poppler)
pdftotext -layout contracts-searchable.pdf contracts.txt

--sidecar writes the OCR-found text to a plain file; --mode skip leaves born-digital pages untouched; --jobs parallelises across cores. For the extracted-text-for-RAG path, pdftotext (poppler) or PyMuPDF then reads the new text layer — the searchable PDF becomes your canonical artefact, giving you both a human-readable PDF and machine-readable text with page provenance.


Part 6: OCR output, confidence and measuring quality#

6.1 Output formats: pick the right one for the job#

Format What it gives you Best for
Plain text (image_to_string, --sidecar) Reading-order text, no positions Quick extraction, feeding a chunker
TSV (image_to_data, Tesseract tsv config) Word-level text + bounding box + confidence Per-word confidence filtering, highlighting, table reconstruction
hOCR HTML with word/line boxes + confidence, per page Web-friendly structured output, downstream layout tools
ALTO XML XML with detailed layout regions + confidence Archival/GLAM pipelines, precise region queries
Searchable PDF (image_to_pdf_or_hocr, OCRmyPDF) Text layer grafted onto the page image Delivering a PDF humans can read and search
Engine JSON (res.save_to_json, Mistral pages, Azure AnalyzeResult, Textract Blocks) Boxes, confidences, structure, fields Structured ingestion with provenance

For an AI pipeline you usually want two artefacts: the plain/Markdown text for chunking, and the structured output (TSV/JSON/Blocks) for confidence-based quality gating and provenance metadata (page, bbox → 05.8).

6.2 Confidence scores: what they mean and how to use them#

Every serious OCR engine emits a per-word or per-region confidence (0–100 for Tesseract/cloud, 0–1 for EasyOCR/some APIs). It is the recogniser's self-assessed probability that the characters are right — useful but imperfect:

  • Low confidence correlates with errors but isn't a guarantee: Tesseract can be confidently wrong on stylised fonts, and right-but-unsure on unusual-but-valid words.
  • Confidence is not comparable across engines — a Tesseract 85 and a PaddleOCR 0.85 are different scales.
  • Use it as a routing signal, not a truth signal. Flag words/regions below a threshold for review or VLM escalation; don't silently drop them.
python
"""confidence.py: filter image_to_data output to usable word records."""
import pytesseract
from PIL import Image


def words_with_confidence(img: Image.Image, min_conf: float = 0.0) -> list[dict]:
    """Word-level records (level 5) with boxes and confidence.

    min_conf keeps only words at or above that confidence; the default 0.0
    returns every recognised word — filter further in the caller if needed.
    """
    data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)
    words = []
    n = len(data["text"])
    for i in range(n):
        text = data["text"][i].strip()
        conf = float(data["conf"][i])
        if data["level"][i] != 5 or not text or conf < min_conf:
            continue                      # level 5 = word; skip structure rows (conf=-1)
        words.append({
            "text": text,
            "conf": conf,
            "left": data["left"][i], "top": data["top"][i],
            "width": data["width"][i], "height": data["height"][i],
            "line_num": data["line_num"][i], "block_num": data["block_num"][i],
        })
    return words


def low_confidence_regions(img: Image.Image, threshold: float = 60.0) -> list[dict]:
    """Group consecutive low-confidence words on the same line into review regions."""
    ws = [w for w in words_with_confidence(img) if w["conf"] < threshold]
    return ws   # production: cluster by (block_num, line_num) proximity

A pragmatic threshold for Tesseract is ~60: below it, error rates rise steeply on typical scans (tune on your data — Part 6.4). Store the raw confidence alongside each chunk's provenance so you can filter or re-route later.

6.3 Measuring quality: CER and WER in plain English#

The two standard OCR metrics are Character Error Rate (CER) and Word Error Rate (WER) — both are edit distance normalised by length:

  • CER = (insertions + deletions + substitutions of characters) ÷ (number of characters in the reference). "3 wrong characters in a 300-char line" → CER ≈ 0.01.
  • WER = the same but counted in words. One wrong word in a 50-word line → WER = 0.02. WER is harsher: a single character error inside a word counts the whole word wrong.

Both are computed against a reference (ground truth) you trust. Lower is better; CER < ~1–2% and WER < ~5% is generally "good" for clean printed scans, but the acceptable threshold depends on your use (a wrong digit in an invoice total is worse than a wrong letter in prose).

Here's a correct, dependency-free implementation — Levenshtein distance by dynamic programming, then CER/WER on top. This is pure stdlib, so the output below is real:

python
"""metrics.py: CER and WER from scratch (no jiwer needed for the core idea)."""

def levenshtein(a: str, b: str) -> int:
    """Minimum single-character edits (insert/delete/substitute) to turn a into b."""
    if a == b:
        return 0
    if not a:
        return len(b)
    if not b:
        return len(a)
    # previous row of the DP table; iterate over b's characters
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(
                prev[j] + 1,                    # deletion
                cur[j - 1] + 1,                # insertion
                prev[j - 1] + (ca != cb),      # substitution (0 if same)
            ))
        prev = cur
    return prev[-1]


def cer(reference: str, hypothesis: str) -> float:
    """Character error rate: edits / len(reference)."""
    ref = reference.replace("\n", " ")
    hyp = hypothesis.replace("\n", " ")
    if not ref:
        return 0.0 if not hyp else float("inf")
    return levenshtein(ref, hyp) / len(ref)


def _normalise_words(text: str) -> list[str]:
    return text.split()


def wer(reference: str, hypothesis: str) -> float:
    """Word error rate: word-level edit distance / word count.

    Note: we reuse levenshtein on the *word sequences* by treating each word as a
    symbol — implement via list edit distance (same DP, on tokens).
    """
    ref, hyp = _normalise_words(reference), _normalise_words(hypothesis)
    if not ref:
        return 0.0 if not hyp else float("inf")
    # token-level Levenshtein
    prev = list(range(len(hyp) + 1))
    for i, rw in enumerate(ref, 1):
        cur = [i]
        for j, hw in enumerate(hyp, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (rw != hw)))
        prev = cur
    return prev[-1] / len(ref)

Demo on real-ish OCR mistakes (output below is real — pure stdlib):

python
ref  = "Invoice total: $1,240.00 due on 2026-11-30"
hyp1 = "Invoice total: $1,240.00 due on 2026-11-3O"   # O vs 0
hyp2 = "Invoice Iotal: $1,240.00 due on 2026-11-30"   # t vs I
for name, h in [("one char wrong (O/0)", hyp1), ("one word wrong (t/I)", hyp2)]:
    print(f"{name:24} CER={cer(ref, h):.4f}  WER={wer(ref, h):.4f}")
Output2 lines
one char wrong (O/0)     CER=0.0238  WER=0.1667
one word wrong (t/I)     CER=0.0238  WER=0.1667

Both single-character confusions cost the same: one character edit (CER ≈ 2.4% of 42 chars) corrupting one of six words (WER = 1/6 ≈ 16.7%). That's exactly why WER is so much harsher — a single wrong letter inside a word counts the whole word as wrong. For the library version, jiwer (4.0.0, Apache-2.0) computes CER/WER plus more (MER, WIL) with standard normalisation.

6.4 Building a tiny ground-truth set#

You can't improve what you don't measure. A minimal eval set for OCR:

  1. Sample ~30–100 pages stratified by document type, quality, language, and engine path (the pages your router sends to each engine).
  2. Transcribe a reference for each — ideally by a human, or by a strong VLM then human-verified. For a quick start, use the best engine's output on your cleanest scans as pseudo-reference, then hand-correct.
  3. Score each engine on the same pages: CER/WER per page and per corpus, plus task-specific checks (did the invoice total come out right? did the table have the right number of rows?).
  4. Record provenance: engine + version + preprocessing config + PSM, so a regression is attributable.

Store references as reference.txt next to each page.png in eval/; the CER/WER functions above score open("page.ocr.txt") vs open("page.reference.txt"). 05.10 generalises this into a full quality suite.

6.5 The low-confidence review queue#

Pages or regions below your confidence threshold shouldn't silently enter the corpus. Route them to:

  • VLM escalation (Part 8) — cheapest fix for a handful of hard pages.
  • A human review queue — for handwriting, IDs, or pages where even the VLM is unsure. Record the reviewer's correction as new ground truth (your eval set grows itself).
  • Flag-and-keep — store the low-confidence text with ocr_confidence metadata so retrieval can down-weight or filter it, rather than dropping content entirely.

Part 7: Layout, tables and structure from scans#

Deep-dive

Plain OCR gives you words in reading order — it does not tell you "this was a two-column article", "these words formed a table", or "this box was checked". Recovering structure is where classical OCR is weakest and where you lean on layout-aware tools.

7.1 Reading order and columns#

Tesseract's TSV gives you block_num/par_num/line_num plus bounding boxes — enough to reconstruct its idea of reading order, but it interleaves multi-column pages because it doesn't truly understand columns. Options, cheapest first:

  • XY-cut / column detection: cluster word boxes into columns by x-coordinate gaps, then sort columns then rows. Works for clean two-column scans; fragile on irregular layouts.
  • Layout models: PaddleOCR's PP-StructureV3, docTR, surya, and cloud Layout-tier services (Azure prebuilt-layout, Document AI Layout Parser, Mistral include_blocks) return regions with types (title, text, table, figure) already ordered.
  • VLM transcription: ask for Markdown and the model infers structure — good but probabilistic (Part 8).

7.2 Tables from scans#

Tables are the hardest structure to recover: ruled tables (lines) differ from borderless ones, merged cells break naive grids, and a flattened table attaches values to the wrong labels — the exact failure 05.1 warns poisons retrieval.

Approach When it works Cost/complexity
Tesseract TSV + your own grid inference Simple ruled tables, clean scans Free; you write the geometry code
PaddleOCR PP-StructureV3 / docTR table models Complex tables, borderless Free; GPU helps
Azure Layout / Document AI Layout / Mistral table_format Production tables at volume Per-page cost; best structure out-of-box
VLM → Markdown/HTML table Irregular tables, small batches Highest per-page cost; verify cell-by-cell

Whatever the source, the representation decision is downstream: emit tables as Markdown (readable, chunk-friendly), HTML (preserves merged cells), or CSV/JSON (for schema extraction). Keep the header row attached to every chunk that contains table rows — a chunk of bare numbers is meaningless (05.6 covers table chunking).

7.3 Forms, checkboxes, stamps, signatures#

  • Key-value forms: cloud prebuilt models (Textract AnalyzeDocument FORMS, Azure layout keyValuePairs, Document AI Form Parser) and Mistral's annotation format return field→value pairs directly. Classical path: detect labelled regions by position, OCR each cell.
  • Checkboxes / selection marks: Azure Layout returns selection marks as ☒/☐; Textract returns SELECTION_ELEMENT blocks with SelectionStatus. Tesseract sees them as noise or small glyphs — don't rely on it for checkbox state.
  • Stamps and signatures: these are images, often overlapping text. Classical OCR reads the stamp text as if it were content (polluting your text); VLMs may describe or ignore them. Decide deliberately: mask stamp regions before OCR, or extract them as separate image artefacts with their own metadata.
  • IDs / passports / licences: MRZ lines (the <<< machine-readable zone) are deliberately OCR-friendly — Tesseract with a constrained charset (-c tessedit_char_whitelist=...) does well; dedicated prebuilt ID models (Textract AnalyzeID, Azure prebuilt-idDocument) handle the security-print and hologram cases better.

7.4 Receipts and invoices: from OCR to fields#

A receipt is a table plus a total plus dates — exactly what schema-constrained extraction is for. The pipeline: OCR/layout → get text+boxes → extract fields. You can extract fields with a classical route (regex on the OCR text for totals/dates, table parsing for line items) or an LLM route (send the OCR text or page image to a model with a JSON schema — 03.4 owns the mechanics; 05.8 owns the metadata). The LLM route is far more robust to layout variation; the classical route is free and deterministic for clean templates. Numeric validation (totals add up, dates parse, check digits) is your safety net either way — Part 11 covers it.


Part 8: VLM-based OCR in depth#

Deep-dive

8.1 When a VLM beats classical OCR — and when it doesn't#

A VLM "reads" an image the way a person does: it sees layout, handwriting, stamps, tables and figures in context. That makes it the right tool for the hard tail — but the wrong default for bulk clean scans. The trade-off table:

Factor Classical/cloud OCR VLM OCR
Cost per page ~$0.000–0.05 ~$0.001–0.05+ (image tokens + output; model-dependent — measure)
Accuracy on clean print Good–excellent Excellent
Accuracy on handwriting/degraded/layout Poor–fair Good–very good (still imperfect)
Output structure Text + boxes/confidence Markdown/JSON you prompt for
Confidence scores Per-word Rarely (some providers give none)
Determinism Deterministic Probabilistic — same page can differ run to run
Throughput High (CPU batches) API-rate-limited
Data leaves perimeter Only if cloud OCR Always (unless self-hosted open VLM)

8.2 The faithful-transcription prompt#

The single most important VLM-OCR prompt rule: transcribe, don't interpret. Models default to "helpfully" summarising, fixing or explaining; for OCR you want verbatim text with explicit markers for what couldn't be read.

text
Transcribe the text in this document image/page exactly as it appears.
Rules:
- Output plain text/Markdown preserving the reading order and headings.
- Do NOT summarise, paraphrase, correct spelling, or add commentary.
- If a word or region is illegible, write [illegible] in its place.
- Preserve numbers, punctuation, currency symbols and dates exactly.
- For tables, output a Markdown table. For forms, keep label: value pairs.
- Do not invent text that is not visible.

Variations per need:

  • Verbatim plain text (for chunking): the prompt above minus the Markdown-table line.
  • Structured fields (invoice extraction): replace the output rules with a JSON schema via structured output (03.4) — e.g. {vendor, invoice_number, date, total, currency, line_items[]}.
  • Layout-faithful (when structure matters): "Return the document as Markdown with headings, lists, tables and code blocks preserved; include a brief note for each figure describing what it shows."
  • Field spot-check: "Read only the 'Total' and 'Date' fields; return JSON {total, date}."

8.3 Page-by-page processing, stitching and batching#

For multi-page documents:

  • Page-by-page gives you per-page provenance, lets you retry only failed pages, and bounds context — but loses cross-page context (a table spanning pages, a sentence continuing). Stitch pages with a page marker (\n\n<!-- page 3 -->\n\n) so chunking can respect boundaries.
  • Whole-document (send the PDF or many page images in one request) preserves cross-page context but costs more tokens and risks hitting request limits (03.6, 4.1: Anthropic 600 pages/128 MB, OpenAI 50 MB, Gemini 50 MB/1000 pages). For long documents, page-batches of ~5–20 pages balance context and cost.
  • Batch APIs (03.9) cut cost ~50% on OpenAI/Anthropic/Gemini for non-urgent bulk OCR — ideal for backfilling an archive.

Provider mechanics (which content part, size limits, media token costs) are in 03.6 — don't re-implement them here. The OCR-specific decision is which pages go to the VLM at all: your router (Part 4) should send only pages classical OCR couldn't read confidently.

8.4 A VLM-OCR call, provider by provider#

The wire shapes live in 03.6; here's the OCR-relevant essence. All outputs illustrative.

OpenAI (Responses API) — image as input_image, or PDF as input_file:

python
from openai import OpenAI

client = OpenAI()  # OPENAI_API_KEY from .env

resp = client.responses.create(
    model="gpt-6-luna",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_image", "image_url": "data:image/png;base64,<...>"},
            {"type": "input_text", "text": TRANSCRIBE_PROMPT},
        ],
    }],
    max_output_tokens=4000,
)
print(resp.output_text)

Anthropic (Messages API) — image as a base64 image block:

python
import anthropic, base64

client = anthropic.Anthropic()
img_b64 = base64.standard_b64encode(open("page.png", "rb").read()).decode()

msg = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=4000,
    messages=[{"role": "user", "content": [
        {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": img_b64}},
        {"type": "text", "text": TRANSCRIBE_PROMPT},
    ]}],
)
text = "".join(b.text for b in msg.content if b.type == "text")

Gemini (generate_content) — image bytes as a Part:

python
from google import genai
from google.genai import types

client = genai.Client()  # GEMINI_API_KEY
resp = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[
        types.Part.from_bytes(data=open("page.png", "rb").read(), mime_type="image/png"),
        TRANSCRIBE_PROMPT,
    ],
)
print(resp.text)

OpenRouter — Chat Completions image_url part:

python
import os
from openai import OpenAI

client = OpenAI(base_url="https://openrouter.ai/api/v1",
                api_key=os.environ["OPENROUTER_API_KEY"])
resp = client.chat.completions.create(
    model="openai/gpt-6-luna",
    messages=[{"role": "user", "content": [
        {"type": "text", "text": TRANSCRIBE_PROMPT},
        {"type": "image_url", "image_url": {"url": "data:image/png;base64,<...>"}},
    ]}],
    max_tokens=4000,
)
print(resp.choices[0].message.content)

8.5 Cost model: pages × tokens × price#

You don't need exact prices to decide whether VLM OCR is viable — you need the formula and where to plug live numbers. ocr_cost.py is a pure-Python calculator with prices as parameters (no hard-coded prices — they change; pull them from the providers' pricing pages or the price-table pattern in 03.7):

python
"""ocr_cost.py: estimate OCR cost for a corpus. Prices are parameters, not constants."""
from dataclasses import dataclass


@dataclass
class EnginePrice:
    """USD cost model for one engine path."""
    name: str
    usd_per_page: float | None = None        # flat per-page (cloud OCR, Mistral)
    image_tokens_per_page: int | None = None # VLM: media tokens per page image
    input_usd_per_mtok: float | None = None  # VLM: input price per 1M tokens
    output_usd_per_mtok: float | None = None # VLM: output price per 1M tokens
    output_tokens_per_page: int = 800        # typical transcription length; measure yours


def cost_per_page(e: EnginePrice) -> float:
    if e.usd_per_page is not None:
        return e.usd_per_page
    img_cost = (e.image_tokens_per_page or 0) * (e.input_usd_per_mtok or 0) / 1e6
    out_cost = e.output_tokens_per_page * (e.output_usd_per_mtok or 0) / 1e6
    return img_cost + out_cost


def corpus_cost(e: EnginePrice, n_pages: int, fraction_needing_it: float = 1.0) -> float:
    """Only `fraction_needing_it` of pages go to this engine (routing!)."""
    return cost_per_page(e) * n_pages * fraction_needing_it


# --- Example shapes (prices illustrative — plug in live numbers) ---
TESSERACT = EnginePrice(name="tesseract", usd_per_page=0.0)          # electricity only
MISTRAL   = EnginePrice(name="mistral-ocr", usd_per_page=0.004)      # $4/1k pages
VLM_CHEAP = EnginePrice(name="vlm-cheap", image_tokens_per_page=1500,
                        input_usd_per_mtok=1.0, output_usd_per_mtok=6.0,
                        output_tokens_per_page=800)

if __name__ == "__main__":
    N = 100_000
    for e in (TESSERACT, MISTRAL, VLM_CHEAP):
        print(f"{e.name:12} all pages : ${corpus_cost(e, N):,.2f}")
    # routing: only 10% of pages escalate to the VLM
    print(f"{'vlm-cheap (10%)':12} routed    : ${corpus_cost(VLM_CHEAP, N, 0.10):,.2f}")
Output4 lines
tesseract    all pages : $0.00
mistral-ocr  all pages : $400.00
vlm-cheap    all pages : $630.00
vlm-cheap (10%) routed    : $63.00

Two takeaways: (1) at 100k pages, classical OCR is effectively free and a VLM-everything approach is hundreds of dollars — routing the hard 10% is the difference between $63 and $630; (2) image tokens per page dominate the VLM cost, so a lower media_resolution/detail where quality allows is a real lever (03.6, 3.4).

8.6 Verification, cross-checking and hallucination risk#

Because VLM output is fluent-but-unverified, treat it as a hypothesis to check:

  • Prompt for fidelity (8.2) and forbid summarising/correcting.
  • Cross-check with a classical engine: run Tesseract and the VLM on the same page; where they agree, confidence is high; where they disagree, flag for review. Agreement between two independent systems is strong evidence.
  • Sample-and-audit: human-verify a random ~5–10% of VLM pages (more for high-stakes docs) and measure CER/WER against your ground truth — the same eval harness as 6.4.
  • Watch for omission: VLMs drop content (a whole column, a footer, a signature). Check page text length against expectation (chars/page distribution per doc type) — a page that returns suspiciously little text is a red flag.
  • Numbers get extra scrutiny: totals, dates, IDs are where hallucination hurts most. Validate numerics with rules (Part 11) regardless of engine.

8.7 Privacy when documents go to a provider#

Sending scans to OpenAI/Anthropic/Gemini/OpenRouter/Mistral/cloud-OCR means the document bytes leave your perimeter. Check each provider's data-use terms (retention, training opt-out, region) — 02.9, Part 9 covers the framework; Module 12 covers security. For sensitive corpora (contracts, IDs, medical-adjacent), prefer local engines or a provider with a documented no-training/zero-retention tier, and record the data-flow decision in your pipeline metadata. This is not legal advice.


Part 9: Handwriting#

Deep-dive

Handwriting is OCR's hardest case and the one where engine choice matters most.

What works, roughly in order of reliability:

  1. Neat, printed-style handwriting on forms (clear letters, consistent baseline): modern VLMs read this well; some cloud form parsers (Azure/Document AI prebuilt forms) handle it. Tesseract is unreliable here — its character models were trained mostly on print.
  2. Messy cursive / mixed case: VLMs still beat classical engines but expect real error rates. There is no production-grade open engine that reliably reads arbitrary cursive; specialised models exist (e.g. Microsoft's TrOCR on Hugging Face) but they target constrained domains (a line of text, a word image), not full pages.
  3. Historical manuscripts, degraded ink, unusual scripts: expect human-in-the-loop regardless.

Engineering guidance:

  • Route handwriting-heavy pages straight to a VLM (has_handwriting_hint in Part 4) — don't waste a classical pass.
  • For forms, prefer field-level extraction (crop each answer box, OCR the small region with --psm 7/8 or a VLM field prompt) over whole-page transcription — handwriting recognition improves dramatically on tight crops.
  • Always keep the page image alongside the extracted text so a human can verify against the original.
  • Design for human-in-the-loop: low-confidence or low-agreement pages go to a review queue; store the corrected text as ground truth for your eval set.

Part 10: Multilingual and non-Latin scripts#

Deep-dive

OCR is not "English with accents" — script support is per-engine and per-language-pack, and the failure mode is plausible-looking nonsense, not an error.

Tesseract: ~128 language packs plus osd.traineddata (orientation/script detection) and 37 script-level models (verified against tessdata as of November 2026), including vertical CJK (HanS_vert, HanT_vert, Japanese_vert, Hangul_vert) and RTL scripts (Arabic, Hebrew). Combine languages with + (lang="eng+fra"). Gaps: some low-resource languages have thin packs; RTL text ordering and ligature shaping have known quirks — test on real samples, don't assume.

Deep engines: EasyOCR covers 80+ languages; PaddleOCR's PP-OCRv5 multilingual recogniser covers 109 languages per the PaddleOCR README (including Chinese, Japanese, Korean, and many Latin, Cyrillic and Indic scripts), and the PP-OCRv6 release notes describe a single unified model for 50 languages, so check which model generation you load; RapidOCR exposes PP-OCRv4/v5 language routes. For a mostly-CJK corpus, PaddleOCR/RapidOCR are the strong open choice.

VLMs: the most robust answer for genuinely mixed-language or multi-script pages — they read context, not just glyphs. Cost is the trade-off; use them for the pages classical engines fail.

Mixed-language pages: a page that's half English contract, half German annex defeats a single -l eng run. Detect language per page/region (Part 4 signals, or a language-ID step in cleaning — 05.5 owns language ID), then route: monolingual pages to that language's pack, mixed pages to a multilingual pack or VLM.

Non-whitespace languages: Chinese/Japanese/Thai have no spaces between words, so "word" confidence and WER behave differently — tokenise by the language's own rules before computing WER, or use CER which is script-agnostic. (Tokenization effects are covered in 02.2.)


Part 11: Post-OCR correction#

Deep-dive

OCR output is never clean. A correction stage fixes recognisable errors without inventing content — and, critically, keeps the raw text so corrections are auditable.

11.1 The correction ladder (cheapest first)#

  1. Encoding/normalisation — mojibake, ligatures, smart quotes, zero-width chars (05.5 owns the general case; apply it after OCR).
  2. Dictionary/regex fixes — known confusions and domain vocabulary:
    • Character confusions: O↔0, l↔1↔I, rn↔m, cl↔d, vv↔w, 5↔S, 8↔B.
    • Domain terms: expand abbreviations, fix part-number patterns, normalise dates/currencies.
    • These are safe only when context disambiguates — l→1 inside a word is usually wrong.
  3. Numeric validation — the highest-value checks because numbers are where OCR hurts most:
    • Dates parse and are plausible; totals = sum of line items; invoice numbers match a pattern; check digits (IBAN, ISBN, credit-card-style) verify.
    • A failed check flags the field for review or VLM re-read — it does not auto-correct.
  4. LLM-based correction — last resort, for messy free text. Send the raw OCR text with a strict prompt ("fix only obvious OCR errors; preserve every word, number and name; output the corrected text"). Risks: the model may "fix" content that was actually correct, normalise names it shouldn't, or hallucinate. Mitigations: keep raw text, diff-check that corrections are small/local, prefer field-level correction over whole-document rewrites, and never let the LLM touch numeric fields without rule validation.

11.2 A conservative corrector#

python
"""post_ocr.py: safe, auditable post-OCR fixes. Keeps raw; returns (text, log)."""
import re

# Safer: fix specific known-bad tokens via a dictionary built from YOUR corpus.
# Only whole-word matches fire, and IGNORECASE keeps "Invo1ce" -> "invoice" style fixes working.
DOMAIN_FIXES = {
    "invo1ce": "invoice",   # digit 1 inside a known word
    "t0tal":   "total",
    "arnount": "amount",
}


def fix_domain_terms(text: str) -> tuple[str, list[str]]:
    """Replace whole-word OCR confusions that your dictionary knows are wrong."""
    log = []
    out = text
    for bad, good in DOMAIN_FIXES.items():
        new = re.sub(rf"\b{re.escape(bad)}\b", good, out, flags=re.IGNORECASE)
        if new != out:
            log.append(f"{bad!r} -> {good!r}")
            out = new
    return out, log


def validate_amounts(text: str) -> list[str]:
    """Flag suspicious numbers: totals with too many/few decimals, dates out of range."""
    issues = []
    for m in re.finditer(r"\$\s*(\d[\d,]*\.\d{1,2})", text):
        val = float(m.group(1).replace(",", ""))
        if val <= 0 or val > 10_000_000:
            issues.append(f"suspicious amount ${m.group(1)}")
    return issues

The log is the point: every correction is recorded so you can audit why the text changed, and the raw OCR stays in storage untouched. For the LLM-correction variant, see the diff-guard pattern in 05.5 — the principle is identical.


Part 12: Scale, cost and operations#

Deep-dive

12.1 Throughput: CPU vs GPU, and how work parallelises#

  • Tesseract is CPU-bound and embarrassingly parallel — one process per page. OCRmyPDF's --jobs N does this; pytesseract calls can go through a process pool. Expect seconds-per-page on CPU for dense pages (varies hugely with DPI and content).
  • Deep engines (EasyOCR, PaddleOCR, docTR, surya) want a GPU for throughput; on CPU they're 5–20× slower. Batch images to amortise model load.
  • Open-weight document VLMs are GPU-bound: throughput depends on page density, image resolution and batching in the serving engine (vLLM), so measure pages per second on your own pages and size the GPU pool from that, with a queue in front and a retry-then-escalate rule for length finishes (2.4.1).
  • Cloud OCR / VLMs are API-bound: throughput = your rate-limit budget, not CPU. Use bounded concurrency (03.9) and the Batch APIs for backfills.

A pragmatic architecture: a queue of pages → worker pool sized to CPU cores (classical) or GPU memory (deep) or rate limits (API) → per-page results with status → dead-letter for failures. 05.9 owns pipeline orchestration; this is the OCR-specific worker shape.

12.2 Cost modelling at scale#

Extend 8.5: total cost = Σ over engines of (pages routed to engine) × (per-page cost). The routing fraction is your biggest lever — every page you keep off the VLM saves its full per-page cost. Build the calculator with your measured per-page costs (time × hardware, or API spend), not list prices.

12.3 Retries, caching and idempotency#

  • Retries: OCR engines fail on corrupt images, timeouts, OOM. Retry transient failures with backoff (03.8); quarantine poison pages after N attempts rather than blocking the batch.
  • Caching by content hash: OCR is deterministic-ish and expensive — cache results keyed by sha256(image_bytes) + engine + version + preprocessing_config. A re-run of the pipeline then only OCRs new or changed pages (05.9 owns the manifest/change-detection machinery; the OCR stage just consumes it).
  • Idempotency: the OCR stage should be a pure function page → (text, boxes, conf); running it twice on the same input must produce the same stored result.
python
"""ocr_cache.py: content-addressed OCR result cache (stdlib only)."""
import hashlib, json, sqlite3
from pathlib import Path


def content_key(image_path: str | Path, engine: str, version: str, config: dict) -> str:
    h = hashlib.sha256()
    h.update(Path(image_path).read_bytes())
    h.update(engine.encode()); h.update(version.encode())
    h.update(json.dumps(config, sort_keys=True).encode())
    return h.hexdigest()


class OcrCache:
    def __init__(self, db_path: str = "ocr_cache.db"):
        self.db = sqlite3.connect(db_path)
        self.db.execute("CREATE TABLE IF NOT EXISTS results (key TEXT PRIMARY KEY, text TEXT, meta TEXT)")

    def get(self, key: str) -> dict | None:
        row = self.db.execute("SELECT text, meta FROM results WHERE key=?", (key,)).fetchone()
        return {"text": row[0], "meta": json.loads(row[1])} if row else None

    def put(self, key: str, text: str, meta: dict) -> None:
        self.db.execute("INSERT OR REPLACE INTO results VALUES (?,?,?)",
                        (key, text, json.dumps(meta)))
        self.db.commit()

Real output (stdlib only):

python
# demo: needs a file called scan.png in the working directory (any bytes work) —
# shows the key is stable and config-sensitive
k1 = content_key("scan.png", "tesseract", "5.5.4", {"psm": 3})
k2 = content_key("scan.png", "tesseract", "5.5.4", {"psm": 6})
print("same image+engine, psm 3 vs 6 -> different keys:", k1 != k2)
Output1 line
same image+engine, psm 3 vs 6 -> different keys: True

Reference

What actually goes wrong in production OCR, and the fix that usually works:

Failure What you see Likely cause Fix
Empty text from a real scan image_to_string returns "" Wrong PSM, too-low DPI, or image is actually blank/figure Check DPI, try --psm 6/11, inspect the image
Garbled but fluent-looking text Real words, wrong ones Bad language pack, stylised font, or a bad hidden OCR layer Switch -l, escalate to VLM, --mode redo
Columns interleaved Sentence jumps between columns Multi-column page with wrong PSM/layout --psm 3, column detection, or layout/VLM
Numbers all wrong l/1, O/0 in amounts Low-res digits, thermal fade Crop+upscale the amount region, --psm 7/8, numeric validation
Handwriting as noise Random characters Classical engine on cursive Route to VLM
Table flattened, values misattached Rows lose alignment No table structure recovery Layout-tier engine or VLM→Markdown
Rotated page read sideways Vertical text garbled Orientation not corrected image_to_osd / --rotate-pages
Everything shifted 3° Characters clipped at edges Residual skew Deskew before OCR
VLM invents a table Plausible but wrong cells VLM hallucination on structure Cross-check with classical; verify cell count
Duplicate text in searchable PDF Text appears twice on copy Page had a visible OCR layer + new invisible one --mode redo or strip
Pipeline hangs on one page One image never finishes Huge image / pathological page --skip-big, --tesseract-timeout, per-page timeout
"It worked on my machine" Different output elsewhere Missing tessdata/osd pack, Tesseract version drift Pin Tesseract version + pack list in config

Common misconceptions#

Misconception Reality
"VLMs made OCR obsolete." VLMs are the best single tool for hard pages, but classical OCR is cheaper, deterministic, faster, gives per-word confidence, and runs offline. Production pipelines route between them.
"Higher DPI is always better." Past ~300 DPI you mostly add cost and can trip engine limits; too-low DPI (<150–200) is the real killer. Match resolution to the engine.
"Preprocessing always helps." Over-binarizing, over-denoising and over-deskewing destroy information — especially for deep engines and VLMs trained on natural images. Preprocess the minimum.
"Confidence score = accuracy." It's a self-assessment, not ground truth; engines can be confidently wrong. Use it for routing and flagging, and measure real CER/WER on a ground-truth set.
"OCR gives you the document's structure." It gives words + boxes. Columns, tables, forms and reading order are inferred — use layout-aware tools or a VLM for structure.
"A text layer means no OCR needed." A hidden OCR layer can be wrong. Check text quality, not just presence, before skipping OCR.
"WER and CER measure the same thing." CER counts character edits; WER counts word edits and is far harsher — one wrong letter fails the whole word. Report both.
"Send the whole archive to the expensive model." At scale, cost is pages × per-page price; routing only the hard fraction to a VLM is routinely 5–10× cheaper for the same quality.

Key takeaways#

  • OCR is a pipeline — preprocess → detect → recognise → post-process → reconstruct — and most failures live in preprocessing and layout reconstruction, not recognition.
  • Three engine families coexist in 2026: classical open-source (Tesseract/OCRmyPDF/EasyOCR/PaddleOCR/RapidOCR/docTR/surya), cloud document-AI (Document AI, Azure DI, Textract, Mistral OCR), and VLMs-as-OCR, with a fourth, self-hosted group of open-weight document VLMs (olmOCR, PaddleOCR-VL, DeepSeek-OCR, Granite-Docling, Chandra) in between, whose licences and GPU needs you must check. Choose per page, not per corpus.
  • Detect scanned vs born-digital vs bad-OCR-layer per page and route accordingly; escalate only low-confidence or handwriting pages to a VLM.
  • Preprocess the minimum: ~300 DPI, fix orientation/EXIF, light deskew, gentle contrast — and keep the raw scan.
  • Measure quality with CER/WER against a ground-truth set; use confidence scores for routing, not truth.
  • Structure (tables, forms, columns, checkboxes) needs layout-aware engines or VLMs; plain OCR flattens it.
  • Post-OCR correction is conservative and auditable: dictionary/numeric fixes first, LLM correction last and always diff-checked, raw text always kept.
  • At scale: parallelise classical OCR across cores, use Batch APIs for VLM/cloud backfills, cache results by content hash, and model cost as routed pages × per-page price.

Terms introduced in this lesson#

Term Meaning
OCR (optical character recognition) Inferring text characters from an image of text
OCR engine The recogniser itself (Tesseract, PaddleOCR, a VLM)
Text layer Invisible/searchable text embedded in a PDF, separate from the visible page image
Born-digital A document created as text (real fonts), not scanned
Scanned / image-only page A page that is just a picture, with no text layer
Hidden/bad OCR layer An invisible text layer from a previous OCR pass that may contain errors
PSM (page segmentation mode) Tesseract's --psm setting describing the image layout (page/column/line/word)
OEM (OCR engine mode) Tesseract's --oem selector: legacy vs LSTM/neural engine
Language pack / traineddata Tesseract's per-language *.traineddata model files
Script model Tesseract script-level traineddata (Latin, HanS, Arabic…) for scripts without a single language
OSD (orientation and script detection) Tesseract's page-rotation/script detection (image_to_osd, osd.traineddata)
Deskew Correcting small rotational tilt of a scanned page
Perspective correction / keystone Warping a photographed page's trapezoid back to a rectangle via a four-point transform
Binarization / Otsu / adaptive Reducing an image to black-and-white; Otsu picks one global threshold, adaptive thresholds each pixel locally
hOCR / ALTO / TSV Structured OCR output formats carrying word boxes and confidences
Searchable PDF A PDF with an invisible OCR text layer over the page image
Confidence score Per-word/region self-assessed accuracy (0–100 or 0–1)
CER / WER Character/Word Error Rate: normalised edit distance vs a reference
Ground-truth set Human-verified reference transcriptions used to measure OCR accuracy
Document AI / document intelligence Cloud services returning structured fields/tables from documents
VLM-as-OCR Using a vision-language model to transcribe an image/page
Faithful transcription Prompting a VLM to output verbatim text, not summaries or corrections
Open-weight document VLM A small vision-language model you can download and self-host (olmOCR, PaddleOCR-VL, DeepSeek-OCR, Granite-Docling, Chandra) that converts a page image to Markdown or structured markup
vLLM An inference server that serves open-weight models behind an OpenAI-compatible HTTP API, so pipeline code only changes base_url
OmniDocBench / olmOCR-Bench Public benchmark suites for document parsing (text, tables, formulas, reading order); a shortlist aid, never a substitute for scoring your own pages
Hybrid OCR pipeline Routing pages across cheap and expensive engines by difficulty
Post-OCR correction Auditable fixes applied after recognition (confusions, numerics, LLM)

All terms are also collected in the glossary.


Exercises#

  1. Routing (Part 4): Extend route_page() with a prior_ocr_cer signal so pages whose stored OCR has CER > 5% route to ocr_classical even when text_quality looks OK. Test it on the six existing cases plus a new "good text, bad prior OCR" case.
  2. Preprocessing A/B (Part 3): Take one clean scan and one phone photo. Run Tesseract with (a) raw, (b) grayscale+autocontrast, (c) +deskew, (d) +binarize. Compare mean word confidence and eyeball the outputs. Which step helped which image — and which hurt?
  3. PSM sweep (5.3): On a receipt image and a two-column article image, run image_to_string with --psm 3, 4, 6, 11. Which wins for each, and does mean word confidence predict it?
  4. CER/WER harness (6.3–6.4): Build eval/ with 5 pages: page.png, page.ocr.txt, page.reference.txt. Write score_eval.py that prints CER and WER per page and corpus means. Then corrupt one reference on purpose and confirm the metric moves.
  5. Confidence routing (6.2): Using image_to_data, compute the fraction of words below conf 60 on a clean vs degraded scan. Propose a threshold that would send <10% of clean-page words to review.
  6. Searchable PDF (5.6): Run OCRmyPDF on a scanned PDF with --mode skip --deskew --sidecar. Verify pdftotext now extracts the text, and confirm a born-digital page in the same file was left untouched.
  7. VLM transcription (8.2–8.4): Pick one hard page (handwriting or complex table). Transcribe it with your cheapest vision model using the faithful-transcription prompt, then with a classical engine. Compare CER against a hand-written reference and decide which you'd route this page type to.
  8. Cost model (8.5, 12.2): Fill ocr_cost.py with your real per-page numbers (measure Tesseract pages/sec on your machine; pull current VLM image-token rules from 03.6). At what fraction of hard pages does VLM-everything become cheaper than classical+escalation?
  9. Post-OCR (11): Feed fix_domain_terms a paragraph containing invo1ce, t0tal, and a legitimate 1o in a part number. Which fixes fire, and how does the log keep it auditable?
  10. Failure gallery (13): Pick two failures from the table, reproduce them on a synthetic image (Pillow text + rotation/blur), and confirm the fix resolves them.
  11. Open-weight model dossier (2.4.1): Pick one model from the table and write a one-page dossier from its own model card and repository: licence for the weights (not only the code), minimum GPU memory, the prompt it expects, its output format, and how you would record its revision in lineage. Would your organisation be allowed to use it commercially? What evidence would you collect on 50 of your own pages before adopting it?
Hints and worked answers
  1. Add prior_ocr_cer: float | None = None to PageSignals and check it before the return "skip" branch — e.g. if s.prior_ocr_cer is not None and s.prior_ocr_cer > 0.05: return "ocr_classical". New case: PageSignals(char_count=3200, image_coverage=0.05, text_quality=0.95, prior_ocr_cer=0.08) must return "ocr_classical", not "skip".
  2. Expected shape: preprocess with PIL — ImageOps.grayscale + ImageOps.autocontrast almost always helps the phone photo; deskew (rotate by the minAreaRect angle, or --psm 0 OSD) helps only if the photo is actually tilted; hard binarization (point(lambda p: 255 if p > 128 else 0)) often hurts photos by destroying grey-level anti-aliasing. Score each variant by mean level-5 word confidence and eyeball — confidence alone won't catch a confidently-wrong result.
  3. Receipt → --psm 6 (uniform block) or 11 (sparse) usually wins; two-column article → --psm 3 (auto) or 4 (single column — forces one reading order). Mean word confidence roughly tracks the winner but isn't proof — verify against a reference with cer()/wer() where you have one.
  4. score_eval.py: for d in Path("eval").iterdir() pairing page.ocr.txt/page.reference.txt, call the lesson's cer()/wer(), print per-page rows then corpus means (sum(errors)/sum(lengths), not mean of ratios). Corrupting one character inside a word moves CER by ~1/len(ref) and WER by 1/n_words — both should rise.
  5. Filter image_to_data to level == 5 rows with non-empty text, cast conf to int. Compute frac_below = mean(conf < T). On a clean scan nearly all words sit above ~60–70; pick the threshold where clean-page frac_below < 0.10 (typically T≈50) — then check the degraded scan flags a much larger fraction, which is exactly the routing signal you want.
  6. ocrmypdf --mode skip --deskew --sidecar in.pdf out.pdf produces out.pdf plus out.txt. pdftotext out.pdf - should now emit the OCR text; --mode skip is why born-digital pages are untouched (they already have a text layer). Confirm with ocrmypdf --pdf-info out.pdf or by diffing pdftotext output on a mixed file.
  7. Cheapest vision model per the 03.6 conventions + the faithful-transcription prompt from Part 8; classical = pytesseract.image_to_string at ~300 DPI. Score both against your hand reference with cer()/wer(); handwriting/complex tables usually favour the VLM, clean printed pages don't.
  8. TESSERACT = EnginePrice("tesseract", usd_per_page=0.0) understates it — add your measured pages/sec → wall-clock/energy cost as a comment; MISTRAL/cloud use usd_per_page from the live pricing page; VLM uses image_tokens_per_page + in/out *_per_mtok. Crossover: per page, VLM-everything costs vlm_cost; classical-plus-escalation costs classical_cost + f × vlm_cost, where f is the fraction escalated. VLM-everything is cheaper when vlm_cost < classical_cost + f × vlm_cost, i.e. when f > 1 - classical_cost / vlm_cost. With classical_cost near zero that is f close to 1: escalation pays almost always, unless your measured classical cost (hardware, review time for its errors) is large.
  9. fix_domain_terms fires on invo1ce→invoice and t0tal→total (whole-word, case-insensitive); a 1o inside a part number is untouched — 1o isn't a dictionary key and \b boundaries stop partial-word hits anyway. The returned log lists every bad -> good replacement: that's the audit trail.
  10. Draw text with ImageDraw.text using a bundled TTF (ImageFont.truetype), then img.rotate(3, expand=True) for skew or GaussianBlur/ImageFilter for degradation; run the engine + the documented fix (deskew/preprocess) on both versions and compare CER.
  11. There is no single right answer; check for the same things a reviewer would. Weights licence: Chandra's modified OpenRAIL-M differs from its Apache-2.0 code, olmOCR and Granite-Docling are Apache-2.0 per their pages (re-read when you do the exercise). GPU: the olmOCR README states at least 12 GB of VRAM; small models such as Granite-Docling and PaddleOCR-VL run on much less, which you should confirm in their docs. Evidence: CER/WER (6.3) on 50 pages stratified by document type, a count of repetition-loop or length finishes, and a cost-per-1,000-pages comparison against your current engine. Record the repository, revision hash and prompt in ParseInfo.parser_version.

Check yourself#

  1. What are the five stages of the classical OCR pipeline, and which stage causes most production failures?
  2. Why does a scanned PDF need OCR before it can feed a text-based RAG pipeline?
  3. Name the three engine families and one strength/weakness of each.
  4. What does --mode skip do in OCRmyPDF, and why is it the safe default for mixed PDFs?
  5. What is the difference between orientation (0/90/180/270°) and skew, and which tool fixes each?
  6. Why is ~300 DPI the rule of thumb, and what goes wrong below ~150 DPI and above ~600 DPI?
  7. In image_to_data output, which level carries real word confidence, and what is conf for structural levels?
  8. What are CER and WER, and why is WER harsher than CER for the same single-character error?
  9. Why can't you trust an OCR confidence score as a measure of accuracy?
  10. What does a "bad hidden OCR layer" look like, and how do you detect it?
  11. When should a page route to a VLM instead of classical OCR? Give three cases.
  12. What are the two biggest VLM-OCR risks, and what verification mitigates each?
  13. Why does post-OCR correction keep the raw text and a change log?
  14. At 100k pages, why does routing only ~10% of pages to a VLM matter for cost?
  15. What does caching OCR results by content hash + engine + version + config buy you on a pipeline re-run?
  16. Your security team forbids sending scans to any third party, and you have 2 million pages. Which engine family fits, what must you check before adopting a specific model, and what do you lose compared with Tesseract?

Further resources#


← 05.3 — Parsing HTML, Web Pages and Office Files | Module 05 overview | 05.5 — Cleaning and Normalization →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close