OCR pipeline costs: run a local engine first

A cheaper OCR pipeline: read digital PDFs directly, run scans and screenshots through a local engine first, pay a hosted model only for pages it cannot read.

By

An OCR pipeline gets expensive quietly. If every page goes to a hosted model, you pay per page for documents that already had a perfectly good text layer, and for screenshots a small local model could have read. On a compliance platform I work on, users upload evidence: digital PDFs, scanned PDFs and screenshots of dashboards. Until this change only the digital PDFs could be read at all. This post covers how I rebuilt the reader so the common case costs nothing and never leaves the machine, and a hosted model only sees the pages the local pass could not handle.

Why a blank read is worse than an error

Before the rebuild, a scan came back empty. That sounds harmless until you look at what sits downstream. The evidence goes to an AI validation step that checks whether it supports a control. An empty read and a document that genuinely says nothing look identical to that step, so a scan of a perfectly good policy was indistinguishable from a blank page.

The data model made it worse. A null in the extracted text column was carrying three different facts: the reader was never tried, the reader could not run, or the image has no text. Only the first two should hold an artefact back from validation. So part of the fix was boring: give each of those states its own name, so the system can act on them differently.

Two more details from the same work are worth copying:

  • "Readable" means real words in a real quantity, not a character count. A scanned page's text layer is often stray header or watermark glyphs, which would pass a length check easily.
  • Page counts are kept as a pair, pages read and pages total, so a document where four of twelve pages came through says it is an excerpt.

Step one of the OCR pipeline: classify every file

The first step costs almost nothing. A local PDF inspection library classifies each file in tens of milliseconds and pulls the text layer out of anything digital. Only the pages it reports as unreadable go on to a recognition engine. For a typical upload that means no OCR at all.

This ordering is where most of the savings come from. Recognition is slow and, on a hosted model, billed. Classification is fast and free. Put the cheap check first and let it decide which pages need the expensive one.

One seam, two engines

Recognition sits behind one interface with two implementations: a small open-source OCR model running locally, and a hosted OCR model. They run as a chain, local first.

The chain has two rules that took a few attempts to get right. When the local engine flags a page as one it cannot read well, that page is dropped from its result instead of being returned as weak text, so the next engine in the chain refills it. And whatever the local pass did manage survives a hosted failure, so the user gets a partial read instead of nothing. Simplified, with neutral names:

def read_pages(pdf: bytes, pages: list[int], engines: list) -> dict[int, str]:
    text: dict[int, str] = {}
    for engine in engines:  # local first, hosted second
        missing = [p for p in pages if p not in text]
        if not missing:
            break
        try:
            for page in engine.recognise(pdf, missing):
                if not page.wants_hosted:
                    text[page.number] = page.text
        except EngineError:
            continue  # pages read so far stay: a partial read beats none
    return text

One trap cost real time here: page numbering. One library counts pages from zero in one call and from one in another, and the hosted engine counts from zero. Everything is converted at the adapter boundary, so the rest of the code only ever sees one convention.

The other rule concerns configuration. With no engine configured, a scan is recorded as ocr_not_configured instead of being reported as an outage. An engine nobody switched on and an engine that fell over need different people to do different things about them, and one shared error state would send both to the wrong person.

Screenshots, resolution and an offline container

Screenshots went straight past the local engine at first, because it only took PDFs. Each image is now wrapped in a one-page PDF with img2pdf, which embeds the original image bytes instead of re-encoding them. That matters for OCR: a second lossy pass blurs exactly the small text an engine struggles with. Transparency survives as a soft mask.

Resolution was the next lever. At the default 150 dpi, a dashboard screenshot produced a threshold cell reading "<= 8" where the source said "<= 15d", dropped one of five rows, and lost the measured value from two more. At 300 dpi every value was correct, for about 0.05 seconds a page, paid only on pages that need OCR. A sweep from 150 to 600 dpi showed the small local model is unstable across resolutions, so the value is a setting instead of a constant. A wrong figure reaching validation is worse than a missing one: a missing value cannot be assessed, a wrong one can be assessed confidently and wrongly.

Then the container. The local OCR library downloads its models on first use. In the container that failed, and behind a read-only filesystem it would have repeated on every restart. The runtime libraries and pinned models are now fetched at build time and read offline. That is about 60MB of image size, against a per-page bill for every screenshot.

On the twelve sample documents, the reader went from five files read to twelve. The four dashboard screenshots came back as markdown tables with no API key configured at all.

Inputs that were never images

While testing I found two file types that never reached OCR and still produced garbage:

  • Spreadsheets. An xlsx fell through to the plain text path. A 50KB workbook was stored as 28,137 characters starting with the zip header, and that is what validation was handed. It is now read with openpyxl in data_only and read_only mode, which streams it at the 25MB upload limit.
  • JPEGs decoded as text. Decoding image bytes with errors="ignore" yields around 38,000 characters of mojibake with NUL bytes, which Postgres will not store in a text column. Every image upload returned 503 and kept nothing.

After both fixes, a screenshot read as 850 characters, a workbook as 4,985 and a PDF as 2,916, all ready for validation. The lesson I took: route by what the file is, and never let unknown bytes fall through to a text decoder.

Move OCR off the upload request

Recognition takes seconds on a screenshot and minutes on a long scan, so it cannot live inside the upload request. OCR now runs on a worker triggered by an event published when the evidence is stored. A screenshot uploaded with nothing calling the read endpoint came back completed, with 892 characters, twelve seconds later.

Two details made the background version pleasant to use:

  • The artefact is marked running and committed before the slow download and recognition start. Sampled once a second, a screenshot moved through nothing, running and completed in six seconds. The panel in the UI polls only while a read is outstanding.
  • A no_text_found result does not notify the owner. Telling somebody their photograph contains no words trains them to ignore the notice that matters.

One local surprise: my development stack had no worker at all, which is why 420 tasks sat queued against 338 completed. If your OCR runs on a queue, run the queue locally too. I covered the job and worker setup I use in running slow AI jobs in the background with queues.

How do you reduce OCR costs?

Classify files first and extract the text layer from digital PDFs directly, since most uploads need no recognition at all. Run a local OCR engine on the pages that do, and send only the pages it cannot read well to a paid hosted model. Bundle models at build time and run recognition on a worker, so cost and latency both stay off the request.

Where I'd start

  1. Measure what share of your uploads have a usable text layer. That share needs no OCR.
  2. Give "not tried", "could not run", "not configured" and "no text found" separate states before adding any engine.
  3. Put recognition behind one interface and chain a local engine ahead of the hosted one, keeping partial reads.
  4. Raise the DPI before blaming the model, and test it on your own documents.
  5. Move recognition onto a worker and check that one runs in every environment.

The extracted text then feeds an LLM, so the same habits apply on the other side. I wrote about checking a model's answers in validating LLM output before it reaches users, about reviewing documents against a template in AI document review against a template, and about keeping per-call spend down in controlling LLM API costs in Node.js. If you are building a document pipeline like this, it is the kind of work I take on through my services.

Want this kind of work on your product?

Get in touch