Repository navigation
Conversation
|
✅ DCO Check Passed Thanks @wittjeff, all your commits are properly signed off. 🎉 |
Merge Protections🟢 Merge protection satisfied — ready to merge. Show 1 satisfied protection🟢 Enforce conventional commitMake sure that we follow https://www.conventionalcommits.org/en/v1.0.0/
|
There was a problem hiding this comment.
Pull request overview
This PR adjusts Docling’s PDFium-based get_page_image() rendering to avoid a lossy supersample-then-downsample path on raster-only (scanned) PDF pages, while keeping the sharpening supersample behavior for vector/text pages by default. It also introduces a configurable supersample_factor backend option and consolidates rendering logic into the shared managed PDFium page backend.
Changes:
- Detect raster-only pages (including form-wrapped scans) and render them directly at the requested scale to avoid degrading OCR quality.
- Add
PdfBackendOptions.supersample_factor(default1.5;1.0disables supersampling globally) and propagate it through PDFium-rendering backends. - Add/extend tests and docs to validate behavior (including fractional page sizes and option honoring by the default backend).
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
docling/backend/managed_pdfium_backend.py |
Adds shared raster-only detection and unified get_page_image() with direct-render/cropping logic and configurable supersampling. |
docling/backend/pypdfium2_backend.py |
Routes page rendering through the managed base and passes supersample_factor from backend options. |
docling/backend/docling_parse_backend.py |
Routes page rendering through the managed base and passes supersample_factor into page backends. |
docling/datamodel/backend_options.py |
Introduces PdfBackendOptions.supersample_factor with validation and documentation. |
tests/test_backend_pdfium.py |
Adds deterministic raster-only and vector-page rendering tests plus option coverage. |
tests/test_backend_docling_parse.py |
Adds a test asserting the default backend honors supersample_factor=1.0. |
docs/usage/advanced_options.md |
Documents how to control PDF page image supersampling via backend options. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
411b8d3 to
4759c96
Compare
|
@wittjeff I ran this branch against the corpus behind my #3587 comment — 796 scanned Chinese book PDFs, 1,590 pages sampled, RapidOCR (ONNX) on Apple silicon. Three findings: the detector holds up, one gap worth closing, and one claim that does not reproduce on this corpus. First, a validity check on my harness: on pages the detector rejects, 1. Detection works well, but a blank background rect excludes genuine scansClassification over 1,590 pages:
Of the 68 PATH-blocked pages, 21 (across 14 documents) are blocked by nothing but a full-page opaque blank fill: a 5-segment closed rect, RGBA That page is as raster-only as it gets — no text layer, no annotations — but it takes the supersample round-trip. Some scanner/producer toolchains emit this background rect and some don't, so two otherwise identical scans get different render paths. If you want to relax the detector, the z-order caveat matters: across those pages the draw order is 2. The OCR improvement does not reproduce on this corpusThis is the part that cuts against the PR's headline, so I want to be precise: I am not disputing the CER 0.184 vs 0.05 measurement in #3587. But on my scans the round-trip costs nothing measurable. 21 raster-only pages, old vs new arm, same OCR engine and settings:
A wash in both directions, well inside run-to-run noise. I initially assumed this was because I mention it because it affects how the fix should be argued — "recovers lost text" is true for degraded scans but overclaims for the common case, and a reviewer testing on a clean scan will see nothing and may conclude the PR does nothing. 3. There is a large unclaimed benefit: render costThe stronger general argument may be the one the PR doesn't make. Same 21 raster-only pages, That follows directly from dropping a 2.25× oversized bitmap plus a full-page Lanczos resize, and it holds regardless of whether OCR quality moves. For anyone processing scanned books in bulk it is the difference that shows up in wall-clock, and it makes the change worth taking on correctness-plus-cost grounds even where OCR is unaffected. Happy to share the harness scripts if useful. |
|
@faithpricejp-source — thank you for the thorough corpus analysis. The breakdown by classification outcome is exactly the kind of data needed to evaluate the detector, and the white-background-rect finding is actionable (I'll look at a follow-up that handles the Your point #2 is the more interesting finding for me. The round-trip degradation in #3587 was dramatic (entire line lost, CER 0.184 → 0.05), but your corpus shows no measurable OCR difference — which suggests the effect is conditional on scan quality, not universal. That's useful calibration for how to argue for the fix. Your analysis also surfaced a question I've been circling: what's the right rendering strategy when we don't know the input characteristics? The PR optimizes within a fixed-scale request (skip the 1.5× round-trip for raster-only pages), but it doesn't address the upstream question of what scale to request in the first place. For a scanned page, the embedded image has a fixed pixel resolution. Rendering at a scale that upsamples it invents pixels; rendering at a scale that downsamples it discards real data. The "optimal" scale depends on:
For my use case (yra-doc-pipeline, a multi-engine document processing pipeline where Docling is one adapter among many), this matters because different engines have different optimal inputs, and the intelligent choice would be per-page and per-engine. The cleanest path for raster-only pages might be to extract the embedded image directly and let each engine handle its own scaling — but that's a larger architectural question than this PR should carry. I've reached out to Christoph Auer to discuss where Docling's scope ends and where orchestration-layer concerns begin. Depending on that conversation, the right home for "inspect embedded image metadata → choose rendering strategy" might be upstream in Docling, downstream in callers, or some combination. For now, the PATH-blocked-pages fix you identified seems like a clean follow-up to this PR regardless of how the bigger question resolves. The scenarios you've surfaced also suggest there's value in a systematic factorial analysis across the input variables — embedded image resolution, effective pixels-per-stroke, noise/degradation level, contrast, presence of other page content — with generated test images under controlled conditions, measured against multiple OCR engines. The outcome would be empirical guidance on rendering strategy when we don't know the inputs up front: when does upsampling help vs. hurt, where are the engine-specific thresholds, what's the interaction between scan quality and model training. I haven't audited whether Docling's existing test corpus covers this parameter space, but if there are gaps, I'd be glad to contribute generated fixtures or run the matrix as part of work we're already doing on multi-engine benchmarking. Happy to coordinate with the Docling team on coverage if that's useful. Happy to take your harness scripts if you want to share them — useful for validating the background-rect predicate. |
4759c96 to
fd4148d
Compare
|
@faithpricejp-source Sorry for the long gap — and re-reading your review, I owe you a You were right that the render-cost argument is the stronger one, and I didn't engage That is unconditional, it falls straight out of dropping a 2.25× oversized bitmap plus For the record, my A/B through the backend on 9 raster-only pages at Your section 2 conclusion is the one I'd now put in the description verbatim in spirit: On the background-rect gap: yes please, send the follow-up PR. 21 of 68 PATH-blocked Some API details I checked while confirming this is implementable, which may save you a
Two fixtures would make it reviewable on its own: one page with the blank fill under the One thing changed under the PR while it sat. #4244 refactored the docling-parse And yes, I'd still like the harness scripts, mostly to validate the background-rect To be explicit about what I am not asking you to wait for: the optimal-scale question 🤖 Generated with Claude Code |
Merge Protections🟢 Merge protection satisfied — ready to merge. Show 1 satisfied protection🟢 Enforce conventional commitMake sure that we follow https://www.conventionalcommits.org/en/v1.0.0/
|
fd4148d to
12efbc1
Compare
Merge Protections🟢 Merge protection satisfied — ready to merge. Show 1 satisfied protection🟢 Enforce conventional commitMake sure that we follow https://www.conventionalcommits.org/en/v1.0.0/
|
AI triage (advisory)Checked commit The pypdfium2 backend now renders raster-only (scanned) pages directly at the requested scale. Pages with text or vector content still use 1.5x supersampling. The PR adds a CI safety: no concern found. A maintainer must still approve CI. 2 related pull request(s) in the same code
The |
There was a problem hiding this comment.
AI first review (advisory): no blocker found
This review covers the full diff at 12efbc1213. It read the code and did not run it.
The raster-only fast path in PyPdfiumPageBackend looks correct, and the raster-only test compares against a direct render. The risk is the new public option supersample_factor: the default PDF backend ignores it, and the description does not say so. Decide whether to add the option now or limit it to the pypdfium path.
A maintainer makes the merge decision. This review never approves the pull request.
PyPdfiumPageBackend.get_page_image() renders every page at 1.5x the requested scale and PIL-resizes down. For vector content this sharpens the output, but for image-only (scanned) pages it is a lossy resample round-trip of already-rasterized pixels that can destroy borderline OCR text detections (issue docling-project#3587). - Render pages whose content is raster-only (image objects only, the common scanned-document case) directly at the requested scale. - Add PdfBackendOptions.supersample_factor (default 1.5, preserving current behavior for pages with text/vector content); 1.0 disables supersampling entirely. - Skip the PIL resize when the rendered bitmap already has the target pixel dimensions. Resolves docling-project#3587 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Signed-off-by: Jeff Witt <152964771+witt3rd@users.noreply.github.com>
The option lived on the shared PdfBackendOptions, but only the pypdfium2 backend reads it: the docling-parse backends render through their own renderer and never supersampled. Move it to a PyPdfiumBackendOptions subclass with kind "pypdfium", mirroring ThreadedDoclingParseBackendOptions, and fall back to the default factor when a plain PdfBackendOptions is passed. This keeps the shared options schema unchanged and makes the backend scope explicit in the field description. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Jeff Witt <1848307+wittjeff@users.noreply.github.com>
12efbc1 to
1a04409
Compare
There was a problem hiding this comment.
AI first review (advisory): no blocker found
This review covers the full diff at 1a04409b7b. It read the code and did not run it.
No important defect found. The raster-only detection falls back to the old supersampling path on any non-image object or pdfium error. The new PyPdfiumBackendOptions is registered in the BackendOptions union, and the earlier question about a no-op option on the docling-parse backends is fixed by moving the field. I checked the get_objects recursion and render sizing in the installed pypdfium2, and I checked the test assertions against the old behavior. The raster-only test compares bytes with a direct render, so it fails on the old resample path.
Earlier findings
- fixed (question): New
supersample_factoroption has no effect on the default PDF backend
A maintainer makes the merge decision. This review never approves the pull request.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
What this changes
PyPdfiumPageBackend.get_page_image()renders every page atscale * 1.5and then downsizes to the requested scale. Supersampling that way sharpens vector content, but on a raster-only page — a scanned page whose content is a single full-page image with no text or vector objects — there is no vector detail to sharpen. The round trip just resamples already-rasterised pixels twice, at 2.25× the pixel cost.This renders raster-only pages directly at the requested scale. Pages with any text or vector content keep supersampling exactly as before.
Detection walks the page object list once (
get_objects(max_depth=16)) and treats the page as raster-only only if it contains at least one image object and nothing but image and form objects. The result is cached per page, and any pdfium error falls back to the existing supersampling path.Why
Render cost, unconditionally. Dropping a 2.25× oversized bitmap plus a full-page Lanczos resize is pure saving on every raster-only page, whatever happens to OCR quality:
scale=3.0, best of 5)@faithpricejp-source measured the same comparison independently on 21 raster-only pages from a corpus of scanned Chinese books (RapidOCR, Apple silicon) and saw 4.68× (92 → 20 ms/page) with the identical 2.25× pixel reduction. The pixel factor is structural — it is just 1.5² — while the time saving depends on machine and page content, so 2.7×–4.7× is the range to expect.
OCR recovery, conditionally. The round trip can destroy borderline text detections: #3587 reports an entire line lost, with CER 0.184 → 0.05 once the resample is skipped.
This benefit is not universal, and it is worth being precise about. @faithpricejp-source's 1,590-page corpus shows no measurable OCR difference from the change — a wash in both directions, at
scale=3.0and again atscale=1.0, which rules out "the render was already upsampling past native resolution" as the explanation. The honest summary of the two results together is that the round trip bites on scans that are already borderline for the engine, not on legible scans generally. A reviewer testing this on a clean scan should expect to see no OCR change at all.So the case for the change is cost plus correctness-on-degraded-input, not a general OCR win.
Scope
Only the pypdfium2 backend. An earlier revision of this PR also carried the same fix for the docling-parse backend, but #4244 refactored that backend to remove pypdfium entirely, deleting the
DoclingParsePageBackendclass those commits modified. They are obsolete and have been dropped in the rebase onto current main; the pypdfium2 render path is the only pdfium-rendering path left.supersample_factoris exposed on a newPyPdfiumBackendOptions(kind="pypdfium", a subclass ofPdfBackendOptionsin the same wayThreadedDoclingParseBackendOptionsis) so the behaviour remains configurable, including setting it to1.0to disable supersampling entirely. It is scoped to the pypdfium2 backend on purpose: the docling-parse backends render through docling-parse's own renderer and never supersampled, so the option would be a no-op there. Passing a plainPdfBackendOptionsto the pypdfium2 backend keeps the default factor.Tests
tests/test_backend_pdfium.pycovers the detector and the render path: a raster-only page renders byte-identically to a direct pdfium render at the requested scale, a page with text keeps the supersampled path, and thesupersample_factoroption is honoured end to end.Known gap, follow-up offered
On @faithpricejp-source's corpus, 21 of 68 pages that the detector rejects are blocked by nothing but a full-page opaque blank fill drawn underneath the scan image — a 5-segment closed rect, RGBA (255,255,255,255), covering >98% of the page. Those pages are as raster-only as it gets and should take the fast path. The predicate has to respect draw order, though: across those pages the path precedes the image in 20 of 22 cases, but in 2 of 22 it is drawn over the image, where it could legitimately obscure content and must keep blocking the fast path. @faithpricejp-source has offered a follow-up PR for this, which is the right place for it.