Dev.to AI 🤖 Ai 👁 0 📖 11 min read

PDF OCR Regression Tests for RAG: Catch Missing Text on Mixed Pages

Your PDF extractor reads “North Depot Policy,” returns a non-empty string, and marks the upload as ready. The answer users need is lower down in a scanned image: returns are allowed for 45 days. That sentence never reach

Your PDF extractor reads “North Depot Policy,” returns a non-empty string, and marks the upload as ready. The answer users need is lower down in a scanned image: returns are allowed for 45 days. That sentence never reaches your search index. When someone asks about the return window, the chatbot might quote the policy for a different depot.

Start debugging with the exact text sent to your chunker. If the sentence is missing there, swapping the model or tuning search won't bring it back. This guide builds a small PDF OCR regression test that reproduces the failure on one mixed page, recovers the missing text with partial OCR, and checks what actually reaches a retrieval-augmented generation (RAG) index. The fixture is synthetic, so it can run in CI without a real customer document.

Why a PDF can have text and still need OCR

A PDF page can contain ordinary text objects, raster images, and vector drawings. Text extraction reads characters from the document's text objects. Optical character recognition, or OCR, reads characters from rendered pixels. A common hybrid is a cover sheet or letterhead generated by one system with a scanned form pasted below it by another. Both sources can appear on the same page.

The shortcut if page.get_text(): skip_ocr() can work when the entire page comes from one source. On a mixed page, one page number or header can send the page down the native-only path. Adding a minimum length still leaves holes. A long digital footer can satisfy the threshold, while a short scanned note can contain the one field a user needs. A report of a lost digital header in a mixed-page OCR workflow illustrates the opposite failure: changing the OCR route can also drop evidence that was already readable. The two parts deserve separate checks. PyMuPDF4LLM mixed-page issue

A page counts as useful when the evidence users ask for survives extraction.

That distinction matters for manual uploads, support portals and internal document assistants. A scanned service bulletin can contain the serial number range that decides whether it applies. A signed addendum can change a date that appears elsewhere in a digital contract. Start with a single field you can verify by looking at the page. Keep the rest of the fixture simple enough that the failure has one likely cause.

Build a mixed PDF you can test in CI

Put native and scanned content on the same page

Create two pages in one file. Page one has a native North Depot header and a raster image containing a 45-day policy. Page two is entirely digital and has a different answer for South Depot. The second page acts as a control and catches a field accidentally indexed under the wrong page. Two pages with one content type each would miss the mixed-page bug.

Install PyMuPDF in a virtual environment. Make English Tesseract language data (eng.traineddata) available and point TESSDATA_PREFIX to the directory containing it. In CI, pin the package and language-data versions used by your ingestion worker. Run the script in a scratch directory because it creates mixed-policy.pdf. The assertions assume normal Python execution with optimizations disabled. PyMuPDF OCR setup

from pathlib import Path
import re

import pymupdf


def make_fixture(path):
    with pymupdf.open() as scan, pymupdf.open() as packet:
        body = scan.new_page(width=420, height=120)
        body.insert_text((24, 55), "RETURN WINDOW: 45 DAYS", fontsize=25)
        image = body.get_pixmap(dpi=220, alpha=False).tobytes("png")

        mixed = packet.new_page(width=500, height=700)
        mixed.insert_text((40, 65), "NORTH DEPOT POLICY", fontsize=23)
        mixed.insert_image(pymupdf.Rect(40, 200, 460, 320), stream=image)

        control = packet.new_page(width=500, height=700)
        control.insert_text((40, 65), "SOUTH DEPOT POLICY", fontsize=23)
        control.insert_text((40, 110), "RETURN WINDOW: 14 DAYS", fontsize=18)
        packet.save(path)


def contains(text, phrase):
    normalized = re.sub(r"[^A-Z0-9]+", " ", text.upper()).strip()
    return f" {phrase} " in f" {normalized} "


def verify_page(text, depot, days):
    assert contains(text, f"{depot} DEPOT POLICY"), "Missing digital header"
    assert contains(text, f"RETURN WINDOW {days} DAYS"), "Missing return window"


path = Path("mixed-policy.pdf")
make_fixture(path)
with pymupdf.open(path) as packet:
    mixed = packet[0]
    native = mixed.get_text()
    assert contains(native, "NORTH DEPOT POLICY")
    assert not contains(native, "RETURN WINDOW 45 DAYS")

    layer = mixed.get_textpage_ocr(language="eng", dpi=220, full=False)
    verify_page(mixed.get_text(textpage=layer), "NORTH", 45)
    verify_page(packet[1].get_text(), "SOUTH", 14)

print("Native-only failure reproduced. Mixed and digital checks passed.")

Reproduce the failure before checking the fix

The native-only extraction should find the header and miss the scanned phrase. This gives you a known bad path. If it unexpectedly finds the full phrase, inspect the fixture first: a tool may have added a searchable layer when the PDF was saved. The repaired path should find both parts on page one and leave the different answer on page two. A failure on either page makes the fixture actionable even if the total word count for the document went up.

Notice the textpage=layer argument. The OCR call returns a text page. The second extraction needs to use it. This sample reads that result in memory and leaves the source PDF as it was. The OCR call also expects the language data to be available to the worker; treat missing data as a setup failure so the queue cannot silently fall back to incomplete text. PyMuPDF page API

The matching helper folds punctuation and case, and checks phrases with boundaries. That lets a harmless punctuation change through while keeping 45 distinct from 145. This normalization is specific to English words and an integer. For fields like -12.50, A-100, or a date, preserve the characters that carry meaning and compare a parsed value with a stated unit or format. On a sample with several policy windows, verify the label, location, and value together. A correct number next to the wrong label still gives the assistant the wrong fact.

Choose an OCR path for each kind of page

Begin with native text and a cheap inspection of the page. Image area can tell you which pages merit a closer look, especially when an image occupies a known body region. A photo on a title page can look much like a scan to that rule. A document with outlined vector text can produce no words and show no raster images at all. Treat the route as a decision you can audit. Keep an example in the test set for each common page type you decide to support. PyMuPDF page triage

What you see First route to try Check before indexing
Readable text across the page Native extraction Critical labels and values survive
Digital header and scanned body Partial OCR Header and body both survive on the same page
Full-page scan with no usable text OCR the rendered page Critical values and page location are correct
Scan with a stale or garbled OCR layer Compare rendered OCR or redo the text layer Wrong or duplicated values are excluded
Dense, multi-column form Layout-aware parser or bounded region extraction Each value stays with the right field

PyMuPDF's partial OCR is a reasonable first experiment when you want to preserve visible digital text and extract additional evidence. Its documentation warns that the additional OCR text can follow the normal text in the result. If order matters, work with words and coordinates, and test the resulting sections or table rows. Sorting from top to bottom alone can interleave two columns. On a simple policy page, the fixture's phrase checks are enough to test presence, while a two-column fixture should also test association. PyMuPDF page API

Choose OCRmyPDF when a searchable PDF is a deliverable. Its skip mode bypasses pages with text, which is the behavior this mixed-page test guards against. Its redo mode can replace an old invisible OCR layer while retaining visible text. Force mode rasterizes page content, so test any change in the document features your readers depend on. If you already need table structure or reading order, test a layout-aware pipeline such as Docling on the same fixtures. Compare the exported records and citations, since each tool is solving a slightly different problem. OCRmyPDF processing modes · Docling full-page OCR example

Test the chunks you actually publish to your index

A correct OCR string is only the first checkpoint. Your chunker might remove a short block it thinks is a footer. It might put “RETURN WINDOW” in one chunk and “45 DAYS” in the next. A later stage might carry the wrong page number through a PDF split or drop a chunk that looks too much like the previous one.

For this fixture, capture the text your indexing adapter would write, with the actual metadata it assigns. Expect the North depot and South depot passages to carry their own page references. If a chunk contains a 45-day window, it should belong to page one. If your chunker stores the depot name in a section path, exercise that path in the check too. Write the assertion against the form your retrieval step will receive, including any projection that strips fields at query time.

A small set of assertions can tell you which layer broke:

  1. Extraction. Page one contains “North Depot Policy” and the 45-day span. Page two contains the 14-day span.
  2. Chunk construction. The policy label and value are available together with their depot identifier. Checks fail if the wrong value is attached to a depot.
  3. Index write. Records retain the source document version and the PDF page index. If your UI displays one-based page numbers, test that conversion.
  4. Retrieval. A query for the North depot returns the page-one evidence in the expected result window. A separate query does the same for the South depot.

Run the first checks with no model call. They give you fast feedback whenever a dependency or a chunking rule changes. Run the retrieval check against the same indexing and filtering logic used by the app. If you want to score the generated answer, do that after you know the right evidence reached retrieval. The broader checklist covers that layer and the permissions the search results must respect. RAG evaluation checklist

Roll out OCR changes with field-level results

Before switching libraries or settings, run your current path and the candidate on the same permitted sample. Label the expected fields independently from both outputs by reading the rendered pages. A small team can start with a handful of examples of each common input type, including documents where the assistant has already missed a field. Use synthetic lookalikes in CI if the source PDFs contain data your build environment shouldn't store.

Count how many expected fields survived with the correct value and page. Keep the counts by input type. An all-digital majority can hide a drop in mixed-page results. Also record duplicate fields, wrong page associations, pages sent to OCR, and processing time per document. That last measurement helps you decide how to handle a queue when many users upload scans at once. Compare numbers from your own workload before generalizing the result. Research on OCR and RAG evaluates errors across several document classes, which is a good reason to include your own hard cases. OCR Hinders RAG evaluation

Record the extraction route, parser build, language, and document version with the ingestion attempt. If OCR times out or returns suspiciously little text for a known form, save a usable error state for that page. An app can label the rest of the document as partially indexed or hold the entire document until review, depending on what it promises users. Either choice gives support something more specific to investigate than “the chatbot gave the wrong policy.”

Process the candidate output in a staging index or a small cohort. Keep earlier chunks available until the replacement set clears the checks, then switch the active version of the document so retrieval sees one set. Test this behavior with a document that once had a wrong value. If the assistant can still retrieve both versions, a better OCR engine alone won't fix the answer.

FAQ

How can I tell if a PDF page has a text layer?

Extract words from the page and see whether meaningful text comes back. Then compare that result with the rendered regions that matter to your workflow. A text layer can cover a header while leaving the body as pixels. It can also contain text from an earlier OCR pass with errors in numbers or names. The presence of selectable text is an initial signal. Coverage of important fields is the stronger check.

Should I run full-page OCR on every PDF?

Measure it on the documents your app receives. Full-page OCR can make sense for image-only inputs or a text layer that consistently disagrees with the rendered page. For digital text, native extraction often gives you a simpler path to the original characters. Try partial OCR on the hybrid pages in your fixture set and compare field recovery, layout, and runtime against full-page OCR.

What should a PDF OCR regression test assert?

Start with one important value, its label, and its expected page. Add a check that preserves an adjacent digital field on the same page. Include a test where native-only extraction misses the scanned evidence so you know the fixture exercises the behavior you care about. For numeric or identifier fields, check exact values after normalization that preserves signs, units, and meaningful punctuation.

Can a scanned PDF already contain OCR text?

Yes. Many scanned PDFs carry searchable text under the visible image. A line of that text can be incomplete or inaccurate while the scan looks fine. Include an example with a stale or low-quality text layer if you accept previously processed scans. Compare the old layer against the visible page before choosing to redo OCR, especially when a digit changes the meaning.

When should I reindex PDFs after an OCR change?

Reindex affected documents when the extractor change alters evidence you expect users to retrieve. Tag runs with the parser and settings version so you can find documents routed through the changed path. Validate the new chunks and keep their citation references intact before you switch to the replacement version. That avoids leaving stale and corrected passages active for the same source.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.