Skip to main content

docling_pdf/
lib.rs

1//! PDF backend for docling.rs.
2//!
3//! A port of docling's standard PDF pipeline: pdfium extracts the text layer
4//! (cells with bounding boxes) and renders page images; a discriminative ONNX
5//! stack (layout detection, table structure, OCR) classifies regions; the cells
6//! are assembled in reading order into a [`DoclingDocument`].
7//!
8//! Current stages: pdfium text-cell extraction + page rendering ([`pdfium_backend`])
9//! and the deterministic text/reading-order assembly ([`assemble`]). The layout,
10//! table-structure and OCR ONNX stages land behind [`Pipeline`] next.
11
12// Without `ml` only the text-layer path runs; the shared assembly/label
13// helpers it doesn't exercise stay compiled for API stability (the full
14// build still flags genuinely dead code).
15#![cfg_attr(not(feature = "ml"), allow(dead_code))]
16
17mod adobe_glyph_list;
18// Reading-order assembly. Public under `ocr-prep` so the browser pipeline can
19// reuse the geometric table reconstruction and its reliability gate (#157).
20#[cfg(feature = "ocr-prep")]
21pub mod assemble;
22#[cfg(not(feature = "ocr-prep"))]
23mod assemble;
24// Vector checkbox squares from the text parser's path walk (#609).
25pub mod checkbox;
26mod dp_lines;
27#[cfg(feature = "ml")]
28pub mod enrich;
29// Public so sibling crates (e.g. docling-rag's ONNX embedder) can route their
30// own `ort` sessions through the same `DOCLING_RS_EP` selection. Kept as a
31// re-export after the logic moved to the shared `docling-onnx` crate —
32// `docling_pdf::ep::…` remains the stable path downstream crates code against.
33#[cfg(feature = "ml")]
34pub use docling_onnx as ep;
35// Heading-hierarchy stage (#302): PDF font-name style parsing, outline
36// extraction (pure lopdf), and the level-assignment pass. No feature gate on
37// the logic itself — only the glyph style pass needs pdfium (`ml`).
38#[cfg(feature = "render")]
39pub mod dparse_render;
40mod font_style;
41mod heading_hierarchy;
42pub mod layout;
43#[cfg(feature = "ml")]
44mod mets;
45#[cfg(feature = "ner")]
46pub mod ner;
47mod numbering_lexicon;
48#[cfg(feature = "ml")]
49mod ocr;
50#[cfg(feature = "ml")]
51mod ocr_cls;
52#[cfg(any(feature = "ml", feature = "ocr-prep"))]
53pub mod ocr_det;
54#[cfg(feature = "ocr-prep")]
55pub mod ocr_prep;
56#[cfg(feature = "ml")]
57mod orient;
58pub mod outline;
59pub mod pdfium_backend;
60#[cfg(feature = "ml")]
61pub mod picture;
62#[cfg(feature = "ml")]
63pub mod quality;
64mod reading_order;
65#[cfg(feature = "ml")]
66mod redact_ocr;
67// Pure-Rust region resampling (page→1024px box-average, crop→448 bilinear) —
68// available to the browser TableFormer path (#157 stage 3), not just `ml`.
69#[cfg(feature = "ocr-prep")]
70pub mod resample;
71#[cfg(feature = "ocr-prep")]
72pub mod scanned;
73// Built-in standard-14 font metrics for the pure-Rust text parser (#187) —
74// no feature gate: the wasm/pdf-text path needs them like the native one.
75pub mod info;
76pub mod pdf_meta;
77// What the reader repaired to read a file (#934) — typed provenance, on
78// demand; pure Rust like `pdf_meta`.
79pub mod repairs;
80pub use repairs::{pdf_repairs, try_pdf_repairs, PdfRepair, RepairInspectError};
81// Embedded images as picture images (#1007, `use_embedded_picture_images`).
82#[cfg(feature = "render")]
83pub mod embedded;
84mod encodings;
85mod glyph_names;
86#[cfg(feature = "render")]
87pub mod raster;
88#[cfg(feature = "render")]
89pub mod render;
90mod script_position;
91mod std14;
92mod symbol_fonts;
93#[cfg(feature = "ml")]
94mod table_tokens;
95#[cfg(feature = "ml")]
96pub mod tableformer;
97#[cfg(feature = "ml")]
98mod tesseract;
99pub mod textparse;
100#[cfg(feature = "ocr-prep")]
101pub mod tf_core;
102// docling's TableFormer cell matcher — pure Rust, shared with the browser
103// TableFormer path (#157 stage 3).
104#[cfg(feature = "ocr-prep")]
105pub mod tf_match;
106pub mod timing;
107mod tounicode;
108
109#[cfg(feature = "ml")]
110use std::collections::BTreeMap;
111use std::fmt;
112#[cfg(feature = "ml")]
113use std::sync::mpsc::{sync_channel, Receiver};
114#[cfg(feature = "ml")]
115use std::sync::{Arc, Mutex};
116
117// An execution provider only exists on its OS, and ort's prebuilt ONNX
118// Runtime binaries follow suit — requesting an impossible pairing otherwise
119// surfaces as a cryptic ort-sys linker error ("no builds available that
120// satisfy the requested feature set"). Catch it at type-check time with an
121// actionable message instead.
122#[cfg(all(feature = "coreml", not(target_vendor = "apple")))]
123compile_error!(
124    "the `coreml` execution provider exists only on Apple targets (macOS/iOS). \
125     On Linux use `--features cuda` or `--features tensorrt` (NVIDIA), on \
126     Windows also `--features directml`, or build without EP features for CPU."
127);
128#[cfg(all(feature = "directml", not(target_os = "windows")))]
129compile_error!(
130    "the `directml` execution provider exists only on Windows. On Linux use \
131     `--features cuda` or `--features tensorrt` (NVIDIA), on macOS \
132     `--features coreml`, or build without EP features for CPU."
133);
134#[cfg(all(any(feature = "cuda", feature = "tensorrt"), target_vendor = "apple"))]
135compile_error!(
136    "the `cuda`/`tensorrt` execution providers have no Apple builds (no NVIDIA \
137     support on macOS). Use `--features coreml` there, or build without EP \
138     features for CPU."
139);
140
141use docling_core::DoclingDocument;
142pub use docling_core::EncryptionError;
143// The env-knob helpers only gate ML-pipeline diagnostics and tuning; the
144// pure text-layer (wasm) build has no call sites.
145#[cfg(feature = "ml")]
146use docling_core::Node;
147#[cfg(feature = "ml")]
148use docling_core::{debug_log, env};
149
150pub use dp_lines::WordGap;
151pub use heading_hierarchy::HeadingHierarchyOptions;
152#[cfg(feature = "ml")]
153pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options, convert_mets_gbs_with_pipeline};
154#[cfg(feature = "ml")]
155pub use ocr::{OcrEngine, OcrLang, OcrMode, OcrModel, RecognizedLine};
156#[cfg(feature = "render")]
157pub use pdfium_backend::PdfDocument;
158pub use pdfium_backend::TextOptions;
159pub use pdfium_backend::{PdfPage, TextCell};
160#[cfg(feature = "ml")]
161pub use tesseract::{
162    installed_languages as tesseract_languages, lang_arg as tesseract_lang_arg, TesseractOptions,
163};
164// Plain page rasterization (#243) — pdfium only, no models.
165#[cfg(feature = "render")]
166pub use pdfium_backend::{render_pages, RenderedPage};
167#[cfg(feature = "ml")]
168pub use render::Omission;
169
170/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
171#[derive(Debug)]
172pub enum PdfError {
173    /// pdfium failed to bind, open, or read the document (and, historically,
174    /// any pipeline error outside the models).
175    Pdfium(String),
176    /// The document itself: an object model lopdf cannot read, a page no
177    /// renderer can draw, a page range outside it.
178    Document(String),
179    /// The layout ONNX model failed to load or run.
180    Layout(String),
181    /// The OCR ONNX model failed to load or run.
182    Ocr(String),
183    /// The document budget ([`Pipeline::document_timeout`]) ran out between
184    /// two pages. Internally the sentinel that stops the page walk; a caller
185    /// never sees it from [`Pipeline::convert`] — the conversion returns the
186    /// pages it finished and reports the cut through [`Completion`].
187    Timeout(String),
188    /// The document is encrypted and the password given (or none) does not
189    /// open it (#636) — the typed value a caller prompts for a password on,
190    /// reachable through [`std::error::Error::source`] too. Its text is the
191    /// one docling raises.
192    Encrypted(EncryptionError),
193}
194
195impl fmt::Display for PdfError {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        match self {
198            PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
199            PdfError::Document(m) => write!(f, "pdf: {m}"),
200            PdfError::Layout(m) => write!(f, "pdf: {m}"),
201            PdfError::Ocr(m) => write!(f, "pdf: {m}"),
202            PdfError::Timeout(m) => write!(f, "pdf: {m}"),
203            PdfError::Encrypted(EncryptionError::WrongPassword) => {
204                f.write_str("pdf: the PDF is encrypted and the password is wrong")
205            }
206            PdfError::Encrypted(EncryptionError::NeedPassword) => {
207                f.write_str("pdf: the PDF is encrypted: a password is required")
208            }
209            PdfError::Encrypted(e) => write!(f, "pdf: the PDF is encrypted: {e}"),
210        }
211    }
212}
213
214/// How a conversion ended: every selected page, or the pages that fit the
215/// document budget (docling's `document_timeout`, `PARTIAL_SUCCESS`).
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum Completion {
218    /// Every selected page was processed.
219    Complete,
220    /// The budget ran out: `pages_done` of `pages_selected` pages are in the
221    /// document, the rest were never rendered (or never processed).
222    TimedOut {
223        pages_done: usize,
224        pages_selected: usize,
225        budget: std::time::Duration,
226    },
227}
228
229/// One finished page, as the per-page progress hook
230/// ([`Pipeline::set_progress`]) reports it — docling's `PageCompletedProgress`
231/// minus the document fields the caller adds (#783).
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub struct PageProgress {
234    /// The page's 1-based number in the document: a page window keeps the
235    /// source numbering, so a `2-3` window reports pages 2 and 3.
236    pub page_no: usize,
237    /// Pages finished so far in this conversion, this one included. On the
238    /// parallel walks pages finish out of order, so this — not `page_no` —
239    /// drives a progress bar.
240    pub pages_done: usize,
241    /// Pages the conversion selected: the window's size, else the whole
242    /// document.
243    pub pages_selected: usize,
244}
245
246/// The per-page progress hook: shared with the parallel workers, so it must
247/// be cheap and thread-safe.
248pub type PageProgressHook = std::sync::Arc<dyn Fn(PageProgress) + Send + Sync>;
249
250impl Completion {
251    pub fn timed_out(&self) -> bool {
252        matches!(self, Completion::TimedOut { .. })
253    }
254
255    /// docling's `ErrorItem.error_message` for the cut, `None` when complete.
256    pub fn message(&self) -> Option<String> {
257        match self {
258            Completion::Complete => None,
259            Completion::TimedOut {
260                pages_done,
261                pages_selected,
262                budget,
263            } => Some(format!(
264                "document timeout of {:.3}s exceeded after {pages_done} of {pages_selected} \
265                 pages; the output holds the pages processed",
266                budget.as_secs_f64()
267            )),
268        }
269    }
270}
271
272/// A converted document and how its conversion ended ([`Completion`]).
273#[derive(Debug, Clone)]
274pub struct Converted {
275    pub document: DoclingDocument,
276    pub completion: Completion,
277}
278
279/// Has the document budget run out?
280fn expired(deadline: Option<std::time::Instant>) -> bool {
281    deadline.is_some_and(|d| std::time::Instant::now() >= d)
282}
283
284/// The sentinel the page walks stop on once the budget is gone.
285fn timeout_sentinel() -> PdfError {
286    PdfError::Timeout("document timeout exceeded".into())
287}
288
289impl std::error::Error for PdfError {
290    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
291        match self {
292            PdfError::Encrypted(e) => Some(e),
293            _ => None,
294        }
295    }
296}
297
298#[cfg(feature = "pdfium")]
299impl From<pdfium_render::prelude::PdfiumError> for PdfError {
300    fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
301        // A failed dlopen means the library this build was asked to use
302        // (`pdfium` feature) is not there. Say what to do instead of leaking
303        // the raw loader error.
304        if matches!(e, pdfium_render::prelude::PdfiumError::LoadLibraryError(_)) {
305            // The loader error pretty-prints over several lines; compact it.
306            let detail = e
307                .to_string()
308                .split_whitespace()
309                .collect::<Vec<_>>()
310                .join(" ");
311            return PdfError::Pdfium(format!(
312                "the pdfium library is not installed. This build's `pdfium` feature \
313                 was asked for it (DOCLING_RS_RENDERER=pdfium, or a file the pure-Rust \
314                 object model cannot read): point PDFIUM_DYNAMIC_LIB_PATH at a directory \
315                 containing the pdfium library, or unset DOCLING_RS_RENDERER — the \
316                 default renderer needs no library. Declarative formats (DOCX, HTML, \
317                 Markdown, …) never need it. [{detail}]"
318            ));
319        }
320        PdfError::Pdfium(e.to_string())
321    }
322}
323
324/// Convert a PDF's **embedded text layer only** — no ONNX, no
325/// threads: the pure-Rust content-stream parser ([`textparse`]) feeds the same
326/// orphan-region assembly the `no_ocr` pipeline flag uses, so text-layer PDFs
327/// come out identical to `--text-layer-only` (flat, line-grouped paragraphs in reading
328/// order; no headings/lists/tables/pictures, and no hyperlink recovery).
329///
330/// This is the only conversion entry compiled without the `ml` feature (it is
331/// what a wasm32 build runs). A scanned/image-only PDF (no embedded text
332/// layer) yields an empty document rather than an error, same as `no_ocr` —
333/// callers can detect that and fall back to an OCR-capable build.
334pub fn convert_text_layer(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
335    convert_text_layer_pages(bytes, name, None)
336}
337
338/// The error for bytes no reader here can parse as a PDF — not a PDF at
339/// all, or one damaged past the parser's repairs. Said about the file, not
340/// about a missing renderer or text layer: no library would read it either.
341pub(crate) const UNREADABLE: &str =
342    "not a readable PDF: the file is damaged or not a PDF (its structure could not be parsed)";
343
344/// [`convert_text_layer`] restricted to a **1-based inclusive** page window
345/// (issue #80's `--pages`); `None` converts everything. The window is
346/// validated the same way as [`Pipeline::pages`]: `first <= last`, 1-based,
347/// and it must select at least one existing page.
348pub fn convert_text_layer_pages(
349    bytes: &[u8],
350    name: &str,
351    pages: Option<(usize, usize)>,
352) -> Result<DoclingDocument, PdfError> {
353    convert_text_layer_pages_with(bytes, name, pages, None)
354}
355
356/// [`convert_text_layer_pages`] with the word-gap rule of the text layer's
357/// line and word contraction (#921, [`WordGap`]); `None` = the process
358/// default (`DOCLING_RS_PDF_WORD_GAP`, else [`WordGap::Adaptive`]).
359pub fn convert_text_layer_pages_with(
360    bytes: &[u8],
361    name: &str,
362    pages: Option<(usize, usize)>,
363    word_gap: Option<WordGap>,
364) -> Result<DoclingDocument, PdfError> {
365    convert_text_layer_pages_opts(
366        bytes,
367        name,
368        pages,
369        TextOptions {
370            word_gap,
371            ..TextOptions::from_env()
372        },
373    )
374}
375
376/// [`convert_text_layer_pages`] with every text-layer setting (#921): the
377/// word-gap rule and whether typographic punctuation is kept as drawn.
378pub fn convert_text_layer_pages_opts(
379    bytes: &[u8],
380    name: &str,
381    pages: Option<(usize, usize)>,
382    text: TextOptions,
383) -> Result<DoclingDocument, PdfError> {
384    if let Some((first, last)) = pages {
385        if first == 0 || last < first {
386            return Err(PdfError::Pdfium(format!(
387                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
388            )));
389        }
390    }
391    let mut doc = DoclingDocument::new(name);
392    // A file nothing can open is an error, not a PDF that merely has no
393    // text layer (the caller's "scanned? needs OCR" hint).
394    let Some(mut parser) = textparse::PageTextParser::open(bytes) else {
395        return Err(PdfError::Document(UNREADABLE.into()));
396    };
397    parser.set_word_gap(text.word_gap);
398    parser.set_keep_typography(Some(text.keep_typography));
399    // Pages are parsed, assembled and dropped one at a time: holding every
400    // page's cells until the end made the peak scale with the whole file —
401    // and a page window still paid for every page outside it.
402    let total = parser.page_count();
403    let mut tally = textparse::TextLayerTally::default();
404    for i in 0..total {
405        let selected = pages.is_none_or(|(first, last)| (first..=last).contains(&(i + 1)));
406        // A page outside the window only feeds the vestigial verdict below,
407        // so it is parsed only until that verdict is settled (on any real
408        // text layer, by the first page or two).
409        if !selected && tally.proves_text(total) {
410            continue;
411        }
412        let page = parser.text_page(i);
413        tally.add(&page);
414        if !selected {
415            continue;
416        }
417        let mut regions = Vec::new();
418        assemble::add_orphan_regions(&mut regions, &page.cells);
419        let table_rows = vec![None; regions.len()];
420        let enrich_out = vec![None; regions.len()];
421        let (mut nodes, links) =
422            assemble::assemble_page(&page, regions, &table_rows, &enrich_out, None);
423        assemble::float_running_head(&mut nodes, &page.cells);
424        assemble::stamp_page_no(&mut nodes, i + 1);
425        doc.nodes.extend(nodes);
426        doc.links.extend(links);
427    }
428    // A vestigial layer (a few typed-in form fields over scanned pages) is not
429    // the document's text: return the empty document, which callers already
430    // report as "no text layer" — so an OCR-capable caller falls back to OCR
431    // instead of proudly extracting thirteen characters.
432    if tally.is_vestigial() {
433        return Ok(DoclingDocument::new(name));
434    }
435    if let Some((first, last)) = pages {
436        if first > total {
437            return Err(PdfError::Pdfium(format!(
438                "page range {first}-{last} is outside the document ({total} page(s))"
439            )));
440        }
441    }
442    assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::Lines);
443    // Grown a page at a time, the node vector can be up to half spare
444    // capacity — hundreds of MB on a long document, held for its lifetime.
445    doc.nodes.shrink_to_fit();
446    Ok(doc)
447}
448
449/// Whether a PDF's embedded text layer is the document's text — the verdict
450/// behind [`Pipeline::text_layer_auto`]: `true` when the pages carry real
451/// text, `false` for a scanned / image-only file or a vestigial layer (a few
452/// typed-in form fields over scans; [`textparse::TextLayerTally`]'s rule,
453/// the one [`convert_text_layer`] answers with an empty document). Pure
454/// Rust, no render, no model: the pages are parsed only until the verdict
455/// is settled — on a digital document, by the first page or two; a scanned
456/// one is walked to the end, which is cheap (its content streams hold no
457/// text). Every page counts, not just a page window: the window is the
458/// caller's output selection, the document's nature is the whole file's.
459/// An unreadable file is an error, as on every other path.
460pub fn text_layer_has_text(bytes: &[u8], password: Option<&str>) -> Result<bool, PdfError> {
461    let Some(mut parser) = textparse::PageTextParser::open_with_password(bytes, password) else {
462        return Err(PdfError::Document(UNREADABLE.into()));
463    };
464    let total = parser.page_count();
465    let mut tally = textparse::TextLayerTally::default();
466    for i in 0..total {
467        if tally.proves_text(total) {
468            return Ok(true);
469        }
470        tally.add(&parser.text_page(i));
471    }
472    Ok(!tally.is_vestigial())
473}
474
475/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
476/// Defaults to the available parallelism (ort otherwise picks a low number).
477#[cfg(feature = "ml")]
478pub(crate) fn intra_threads() -> usize {
479    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_THREADS").filter(|&n| n > 0) {
480        return n;
481    }
482    env::cpu_budget()
483}
484
485#[cfg(feature = "ml")]
486/// TableFormer's intra-op width (#262): `DOCLING_RS_TF_INTRA` explicitly,
487/// else the shared [`intra_threads`] budget. The shared TF session used to
488/// take the raw host width on top of the already-sized worker pools —
489/// under a cgroup CPU limit that oversubscription showed up as constant
490/// throttling and ~66% higher peak memory (each intra thread carries its own
491/// arena slab); the reporter's 4-CPU/8-core case dropped from 2.2 GB to
492/// 1.3 GB peak by capping this pool.
493pub(crate) fn tf_intra() -> usize {
494    if let Some(n) = env::parse::<usize>("DOCLING_RS_TF_INTRA").filter(|&n| n > 0) {
495        return n;
496    }
497    intra_threads()
498}
499
500#[cfg(feature = "ml")]
501/// True when `DOCLING_RS_FP32` forces the full-precision models even where
502/// an INT8 variant sits next to the fp32 default.
503pub(crate) fn fp32_forced() -> bool {
504    env::flag("DOCLING_RS_FP32")
505}
506
507#[cfg(feature = "ml")]
508/// Should the int8 model defaults be skipped in favor of fp32? Either the
509/// user said so (`DOCLING_RS_FP32`), or a GPU execution provider is selected
510/// (#74) — the int8 exports are QDQ graphs calibrated for CPU kernels and
511/// only conformance-validated there. An explicit `DOCLING_*_ONNX` path
512/// override still wins over this at every call site.
513pub(crate) fn prefer_fp32() -> bool {
514    fp32_forced() || docling_onnx::prefers_fp32()
515}
516
517#[cfg(feature = "render")]
518/// Resolve a default (CWD-relative) asset path — the shared chain in
519/// [`docling_core::assets`]: CWD, then next to the executable and one level
520/// above it (the `scripts/install/install.sh` layout).
521pub(crate) fn resolve_asset(rel: &str) -> String {
522    docling_core::assets::resolve(rel)
523}
524
525/// One resolved runtime asset — which file a stage would load right now,
526/// given the CWD, the env overrides and the int8/fp32 preference.
527#[cfg(feature = "ml")]
528#[derive(Debug, Clone)]
529pub struct ModelEntry {
530    /// Pipeline stage, e.g. `layout`, `tableformer.decoder`, `ocr.rec`.
531    pub stage: &'static str,
532    /// The resolved path (absolute or CWD-relative, as it will be opened).
533    pub path: String,
534    /// Whether the file exists right now.
535    pub found: bool,
536    /// File size in bytes (0 when missing) — enough to tell an int8 quant
537    /// from an fp32 graph, or a stale model from a re-published one, at a
538    /// glance without hashing gigabytes per request.
539    pub bytes: u64,
540}
541
542/// Resolve the whole runtime model set **without loading anything** — the
543/// exact selection each stage performs at load time (layout honors the
544/// int8/fp32 preference, TableFormer its decoder ranking, OCR the language
545/// pair), plus the pdfium library. docling-serve exposes this at
546/// `/v1/config` and logs it at startup, so "the server picked up different
547/// models" is one `curl` away instead of a mystery of dissolved tables.
548/// Resolution is CWD-relative with an exe-dir fallback, so the answer can
549/// legitimately differ between two working directories.
550#[cfg(feature = "ml")]
551pub fn model_inventory() -> Vec<ModelEntry> {
552    fn entry(stage: &'static str, path: String) -> ModelEntry {
553        let meta = std::fs::metadata(&path).ok();
554        ModelEntry {
555            stage,
556            found: meta.is_some(),
557            bytes: meta.map(|m| m.len()).unwrap_or(0),
558            path,
559        }
560    }
561    let (enc, dec, bbx) = tableformer::resolved_paths();
562    let (rec, dict) = ocr::resolve_rec_pair(ocr::OcrLang::from_env());
563    let pdfium =
564        env::nonempty("PDFIUM_DYNAMIC_LIB_PATH").unwrap_or_else(|| resolve_asset(".pdfium/lib"));
565    vec![
566        entry(
567            "layout",
568            model_path(
569                "DOCLING_LAYOUT_ONNX",
570                ".models/layout_heron.onnx",
571                ".models/layout_heron_int8.onnx",
572            ),
573        ),
574        entry("tableformer.encoder", enc),
575        entry("tableformer.decoder", dec),
576        entry("tableformer.bbox", bbx),
577        entry("ocr.rec", rec),
578        entry("ocr.dict", dict),
579        entry("ocr.textline_ori", ocr_cls::resolve_cls_path()),
580        entry("pdfium", pdfium),
581    ]
582}
583
584/// Resolve a model path: an explicit env override always wins; otherwise the
585/// INT8 variant of the default path when it exists on disk (the quantized
586/// models are conformance-validated — see docs/PDF_CONFORMANCE.md — and load/run
587/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
588/// precision; else the fp32 default.
589#[cfg(feature = "ml")]
590pub(crate) fn model_path(key: &str, fp32_default: &str, int8_default: &str) -> String {
591    if let Some(p) = env::nonempty(key) {
592        return p;
593    }
594    if !prefer_fp32() {
595        let p = resolve_asset(int8_default);
596        if std::path::Path::new(&p).exists() {
597            return p;
598        }
599    }
600    resolve_asset(fp32_default)
601}
602
603/// Decode a standalone image with hard resource limits. A crafted image can
604/// declare enormous dimensions in a few-KB file; `image::load_from_memory`
605/// then tries to allocate the full pixel buffer (e.g. 60000×60000 → ~10 GB),
606/// and allocation failure aborts the whole process, bypassing the per-request
607/// panic catch. The 256 MiB alloc / 30000-px caps below turn that into a
608/// recoverable decode error instead. `DOCLING_RS_MAX_IMAGE_PIXELS` overrides
609/// the per-side pixel cap for the rare legitimately-huge scan.
610///
611/// Gated on `ml`: the only callers (`convert_image`, the METS backend) are
612/// ML-only, and the `image` crate is an `ml`-feature dependency — the
613/// text-layer wasm build has neither.
614#[cfg(feature = "ml")]
615pub(crate) fn decode_image_limited(bytes: &[u8]) -> Result<image::RgbImage, PdfError> {
616    decode_image_with_max_side(bytes, max_image_side())
617}
618
619/// `DOCLING_RS_MAX_IMAGE_PIXELS`: the per-side pixel cap of an image input
620/// (30000).
621#[cfg(feature = "ml")]
622pub(crate) fn max_image_side() -> u32 {
623    env::parse("DOCLING_RS_MAX_IMAGE_PIXELS").unwrap_or(30_000)
624}
625
626/// The `(horizontal, vertical)` resolution an image input's page is sized by,
627/// as docling's `ImageDocumentBackend` reads it (#1093): Pillow's
628/// `info["dpi"]` ([`docling_core::image_dpi::resolution`]), 72 when the file
629/// records none or the `(1, 1)` / `(0, 0)` placeholders, the axes swapped when
630/// the EXIF orientation turned the frame a quarter (`decoded` is the size
631/// after [`decode_image_limited`] applied it; docling's `_oriented_frame`
632/// compares the sizes the same way). A resolution docling rejects — not
633/// finite, zero or negative on one axis — fails its conversion; here it reads
634/// as 72, degradation over failure.
635#[cfg(feature = "ml")]
636fn image_page_dpi(bytes: &[u8], decoded: (u32, u32)) -> (f64, f64) {
637    const DEFAULT: (f64, f64) = (72.0, 72.0);
638    let dpi = match docling_core::image_dpi::resolution(bytes) {
639        None => return DEFAULT,
640        Some(d) if d == (1.0, 1.0) || d == (0.0, 0.0) => return DEFAULT,
641        Some((x, y)) if !(x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0) => return DEFAULT,
642        Some(d) => d,
643    };
644    let stored = image::ImageReader::new(std::io::Cursor::new(bytes))
645        .with_guessed_format()
646        .ok()
647        .and_then(|r| r.into_dimensions().ok());
648    match stored {
649        Some(size) if size != decoded => (dpi.1, dpi.0),
650        _ => dpi,
651    }
652}
653
654/// Whether `bytes` is an ISOBMFF HEIF/HEIC container (the `ftyp` brands
655/// iPhones write). Checked by content, not extension — HEIC regularly
656/// arrives misnamed `.jpg`.
657#[cfg(feature = "ml")]
658fn is_heif(bytes: &[u8]) -> bool {
659    bytes.len() >= 12
660        && &bytes[4..8] == b"ftyp"
661        && matches!(
662            &bytes[8..12],
663            b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"hevs" | b"mif1" | b"msf1"
664        )
665}
666
667/// Decode a HEIF/HEIC primary image via libheif (#211). Behind the opt-in
668/// `heif` feature — libheif is a native dependency the default build (and
669/// wasm) must not carry.
670#[cfg(all(feature = "ml", feature = "heif"))]
671fn decode_heif(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
672    use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
673    let err = |e: String| PdfError::Pdfium(format!("heif: {e}"));
674    let ctx = HeifContext::read_from_bytes(bytes).map_err(|e| err(e.to_string()))?;
675    let handle = ctx.primary_image_handle().map_err(|e| err(e.to_string()))?;
676    if handle.width() > max_side || handle.height() > max_side {
677        return Err(err(format!(
678            "image dimensions {}x{} exceed the {max_side}px per-side cap \
679             (DOCLING_RS_MAX_IMAGE_PIXELS overrides)",
680            handle.width(),
681            handle.height()
682        )));
683    }
684    let lib = LibHeif::new();
685    let img = lib
686        .decode(&handle, ColorSpace::Rgb(RgbChroma::Rgb), None)
687        .map_err(|e| err(e.to_string()))?;
688    let (w, h) = (img.width(), img.height());
689    let planes = img.planes();
690    let plane = planes
691        .interleaved
692        .ok_or_else(|| err("no RGB plane".into()))?;
693    let stride = plane.stride;
694    let mut out = image::RgbImage::new(w, h);
695    for (y, row) in out.rows_mut().enumerate() {
696        let src = &plane.data[y * stride..y * stride + w as usize * 3];
697        for (x, px) in row.enumerate() {
698            px.0 = [src[x * 3], src[x * 3 + 1], src[x * 3 + 2]];
699        }
700    }
701    Ok(out)
702}
703
704#[cfg(feature = "ml")]
705fn decode_image_with_max_side(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
706    use image::{ImageDecoder, ImageReader};
707    use std::io::Cursor;
708
709    if is_heif(bytes) {
710        #[cfg(feature = "heif")]
711        return decode_heif(bytes, max_side);
712        #[cfg(not(feature = "heif"))]
713        return Err(PdfError::Pdfium(
714            "HEIC/HEIF input needs a build with the `heif` cargo feature \
715             (rebuild with --features heif; links the system libheif)"
716                .into(),
717        ));
718    }
719
720    let mut limits = image::Limits::default();
721    limits.max_image_width = Some(max_side);
722    limits.max_image_height = Some(max_side);
723    limits.max_alloc = Some(256 * 1024 * 1024);
724
725    let mut reader = ImageReader::new(Cursor::new(bytes))
726        .with_guessed_format()
727        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
728    reader.limits(limits);
729    let mut decoder = reader
730        .into_decoder()
731        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
732    // docling#4247 (2.128, `ImageOps.exif_transpose`): a camera stores the
733    // sensor readout plus an orientation tag rather than rotated pixels, so
734    // a portrait photo would reach layout and OCR on its side unless the tag
735    // is honoured. An unreadable tag is no orientation, not an error.
736    let orientation = decoder
737        .orientation()
738        .unwrap_or(image::metadata::Orientation::NoTransforms);
739    let mut img = image::DynamicImage::from_decoder(decoder)
740        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
741    img.apply_orientation(orientation);
742    // Transparency onto white, 16-bit samples truncated — docling's
743    // `to_rgb` (#1149).
744    Ok(ocr_prep::flatten_onto_white(img))
745}
746
747/// Image outputs of the PDF/image pipeline (#519/#520): the scale picture
748/// crops are delivered at and whether each page's render is kept as the
749/// document's page image. See [`Pipeline::images_scale`] /
750/// [`Pipeline::generate_page_images`].
751#[derive(Debug, Clone, Copy, Default, PartialEq)]
752pub struct ImageOutput {
753    /// Pixels per PDF point for picture crops and page images — docling's
754    /// `images_scale`. `None` keeps the pipeline's own page render (2.0
755    /// px/pt), resampling nothing.
756    pub scale: Option<f32>,
757    /// Keep every page's render as the document's page image — docling's
758    /// `generate_page_images`.
759    pub page_images: bool,
760    /// A picture region holding exactly one safe embedded image gets that
761    /// bitmap at native resolution (`dpi` 72) instead of a render crop —
762    /// docling's `use_embedded_picture_images` (#1007, docling#5143; see
763    /// [`embedded`]). Anything uncertain keeps the crop.
764    pub embedded_pictures: bool,
765}
766
767#[cfg(feature = "ml")]
768/// Whether a page's text layer is furniture rather than its text (#936): a
769/// page number, a running header — at most [`SPARSE_LAYER_WORDS`] non-blank
770/// words covering under 2 % of the page — beside text drawn as outlines. A
771/// digital page's body text covers far more, so it never pays for the
772/// orientation probe. The area test alone was not enough: a figure page with
773/// a one-line caption (1–2 % covered, 20–30 words — three of the sixteen
774/// pages of `2203.01017v2.pdf`) passed it and paid the full-page text
775/// detector on every such page, +44 % on the document; the word cap keeps
776/// the probe for the layer a sideways outline page keeps (the reporter's
777/// `Page 1`: 2 words, 0.05 %).
778fn sparse_text_layer(page: &PdfPage) -> bool {
779    let (mut covered, mut words) = (0.0f32, 0usize);
780    for c in page.cells.iter().filter(|c| !c.text.trim().is_empty()) {
781        covered += (c.r - c.l).max(0.0) * (c.b - c.t).max(0.0);
782        words += c.text.split_whitespace().count();
783    }
784    words <= SPARSE_LAYER_WORDS && covered < 0.02 * page.width * page.height
785}
786
787#[cfg(feature = "ml")]
788/// The detector's longer-side cap for the orientation probe of a page that
789/// has a text layer (#945): the pre-#570 budget, enough for the few wide
790/// lines the probe scores.
791const PROBE_DET_MAX_SIDE: u32 = 960;
792
793#[cfg(feature = "ml")]
794/// [`sparse_text_layer`]'s word cap: a page number plus a running header of
795/// a few words, not a caption.
796const SPARSE_LAYER_WORDS: usize = 12;
797
798#[cfg(feature = "ml")]
799/// The layout regions of a page with a text layer that no programmatic text
800/// touches — docling's "clusters without any visible programmatic text"
801/// (`_find_pdf_aware_layout_ocr_rects`: any text cell intersecting the
802/// cluster counts), so their text, if any, is drawn as outlines (#931).
803/// Text, furniture and table regions only: pictures have their own pass.
804/// Furniture is relabeled `text`, the label region OCR reads.
805fn text_less_regions(regions: &[layout::Region], cells: &[TextCell]) -> Vec<layout::Region> {
806    regions
807        .iter()
808        .filter(|r| {
809            ocr_prep::is_text_label(r.label)
810                || assemble::is_table_like(r.label)
811                || matches!(r.label, "page_header" | "page_footer")
812        })
813        .filter(|r| {
814            !cells.iter().any(|c| {
815                !c.text.trim().is_empty()
816                    && c.r.min(r.r) > c.l.max(r.l)
817                    && c.b.min(r.b) > c.t.max(r.t)
818            })
819        })
820        .map(|r| layout::Region {
821            label: match r.label {
822                "page_header" | "page_footer" => "text",
823                l => l,
824            },
825            ..r.clone()
826        })
827        .collect()
828}
829
830#[cfg(feature = "ml")]
831/// docling's `THIN_SHAPE_LINE_HEIGHTS`: a band no thicker than this many
832/// text lines is accounted for by any text on it.
833const THIN_BAND_LINES: f32 = 2.0;
834#[cfg(feature = "ml")]
835/// docling's `TEXT_BACKED_MIN_COVERAGE`: a thicker area is accounted for
836/// when text covers this share of it.
837const TEXT_BACKED_MIN_COVERAGE: f32 = 0.1;
838#[cfg(feature = "ml")]
839/// The share of a region a bitmap must cover for [`bitmap_regions`] to OCR
840/// it.
841const BITMAP_REGION_COVER: f32 = 0.5;
842
843#[cfg(feature = "ml")]
844/// The layout regions of a page with a text layer that lie on a bitmap the
845/// text layer does not account for (#999) — docling's other
846/// `_find_pdf_aware_layout_ocr_rects` trigger, "clusters overlapping a
847/// bitmap": a scanned form with one typed-in value has text in its table
848/// region, so [`text_less_regions`] skipped it and the table read the one
849/// native word. The same labels as there; regions [`text_less_regions`]
850/// already takes are left to it.
851///
852/// Narrower than docling, on purpose: docling OCRs every cluster that
853/// touches a bitmap. Here the bitmap must cover at least
854/// [`BITMAP_REGION_COVER`] of the region, and its part inside the region
855/// must not be accounted for by the text layer, judged with docling's own
856/// rule for shapes (`_text_accounts_for`: a band no thicker than two text
857/// lines is explained by any text on it, a thicker one by text over a
858/// tenth of it). A searchable scan — an invisible text layer over the
859/// page image — and a digital page's logo or figure beside its text are
860/// left to their text layer instead of being OCR'd a second time.
861fn bitmap_regions(
862    regions: &[layout::Region],
863    cells: &[TextCell],
864    bitmaps: &[[f32; 4]],
865) -> Vec<layout::Region> {
866    if bitmaps.is_empty() {
867        return Vec::new();
868    }
869    let ink = |c: &&TextCell| !c.text.trim().is_empty();
870    regions
871        .iter()
872        .filter(|r| {
873            ocr_prep::is_text_label(r.label)
874                || assemble::is_table_like(r.label)
875                || matches!(r.label, "page_header" | "page_footer")
876        })
877        .filter(|r| {
878            // Regions with no text at all are `text_less_regions`'.
879            cells
880                .iter()
881                .filter(ink)
882                .any(|c| c.r.min(r.r) > c.l.max(r.l) && c.b.min(r.b) > c.t.max(r.t))
883        })
884        .filter(|r| {
885            let area = ((r.r - r.l) * (r.b - r.t)).max(1.0);
886            bitmaps.iter().any(|&[bl, bt, br, bb]| {
887                let (l, t, rr, b) = (bl.max(r.l), bt.max(r.t), br.min(r.r), bb.min(r.b));
888                let (w, h) = (rr - l, b - t);
889                if w <= 0.0 || h <= 0.0 || w * h < BITMAP_REGION_COVER * area {
890                    return false;
891                }
892                let under: Vec<(f32, f32)> = cells
893                    .iter()
894                    .filter(ink)
895                    .filter_map(|c| {
896                        let iw = c.r.min(rr) - c.l.max(l);
897                        let ih = c.b.min(b) - c.t.max(t);
898                        (iw > 0.0 && ih > 0.0).then_some((c.b - c.t, iw * ih))
899                    })
900                    .collect();
901                if under.is_empty() {
902                    return true;
903                }
904                let mut heights: Vec<f32> = under.iter().map(|u| u.0).collect();
905                heights.sort_by(f32::total_cmp);
906                let line = heights[heights.len() / 2];
907                if w.min(h) <= THIN_BAND_LINES * line {
908                    return false;
909                }
910                let covered: f32 = under.iter().map(|u| u.1).sum();
911                covered / (w * h) < TEXT_BACKED_MIN_COVERAGE
912            })
913        })
914        .map(|r| layout::Region {
915            label: match r.label {
916                "page_header" | "page_footer" => "text",
917                l => l,
918            },
919            ..r.clone()
920        })
921        .collect()
922}
923
924#[cfg(feature = "ml")]
925/// The OCR'd cells with their recognition confidence, for the per-cell report
926/// (#915): a copy of what feeds the page `ocr_score`, kept beside it.
927fn cell_confs(scored: &[(TextCell, f32)]) -> Vec<docling_core::OcrCellConfidence> {
928    scored
929        .iter()
930        .map(|(c, conf)| docling_core::OcrCellConfidence {
931            text: c.text.clone(),
932            l: c.l,
933            t: c.t,
934            r: c.r,
935            b: c.b,
936            confidence: *conf,
937        })
938        .collect()
939}
940
941#[cfg(feature = "ml")]
942/// The document's report: page scores plus the per-cell OCR confidences (#915).
943fn confidence_report(
944    confs: std::collections::BTreeMap<usize, docling_core::confidence::PageConfidence>,
945    cells: std::collections::BTreeMap<usize, Vec<docling_core::OcrCellConfidence>>,
946) -> docling_core::ConfidenceReport {
947    cells.into_iter().fold(
948        docling_core::ConfidenceReport::from_pages(confs),
949        |report, (n, cells)| report.with_ocr_cells(n, cells),
950    )
951}
952
953#[cfg(feature = "ml")]
954/// One page's assembled output: typed nodes plus the page's hyperlinks (kept
955/// separate so pages processed out of order can be stitched back in page
956/// order) and its confidence scores (#183).
957type PageOut = (
958    Vec<Node>,
959    Vec<(String, String)>,
960    docling_core::confidence::PageConfidence,
961    // The page image, when page images are requested (#520).
962    Option<docling_core::PictureImage>,
963    // The page's OCR cells with their recognition confidence (#915).
964    Vec<docling_core::OcrCellConfidence>,
965);
966
967/// One page from its text layer alone — the fastest path: no layout, OCR
968/// or TableFormer inference at all. The embedded text cells (if any) become
969/// flat, line-grouped paragraphs in reading order via the same
970/// orphan-region machinery that normally rescues text the detector missed —
971/// here it rescues *all* of it. A page with no text layer (scanned /
972/// image-only) yields nothing. Shared by the `no_ocr` worker branch
973/// (images, METS) and the worker-less PDF loop of
974/// [`Pipeline::convert_text_only`], so `text_layer_only=true` and an
975/// `auto` document with text come out byte-identical.
976#[cfg(feature = "ml")]
977fn text_only_page(
978    page: &PdfPage,
979    images_scale: Option<f32>,
980) -> (
981    Vec<Node>,
982    Vec<(String, String)>,
983    docling_core::confidence::PageConfidence,
984) {
985    let parse = quality::parse_score(&page.cells);
986    let mut regions = Vec::new();
987    assemble::add_orphan_regions(&mut regions, &page.cells);
988    let table_rows = vec![None; regions.len()];
989    let enrich_out = vec![None; regions.len()];
990    let conf = quality::page_confidence(parse, &regions, &[]);
991    let (nodes, links) = timing::timed("assemble_page", || {
992        assemble::assemble_page(page, regions, &table_rows, &enrich_out, images_scale)
993    });
994    (nodes, links, conf)
995}
996
997/// The page's image for the document's page images (#520) under `images`:
998/// `None` unless page images were requested, or when the page has no bitmap
999/// (the text-layer-only paths never render one).
1000#[cfg(feature = "ml")]
1001fn page_image_under(
1002    images: ImageOutput,
1003    n: usize,
1004    page: &PdfPage,
1005) -> Option<docling_core::PictureImage> {
1006    if !images.page_images {
1007        return None;
1008    }
1009    let image = assemble::page_image(page, images.scale);
1010    if image.is_none() {
1011        docling_core::debug_log!("page {}: no page bitmap for the page image", n + 1);
1012    }
1013    image
1014}
1015
1016#[cfg(feature = "ml")]
1017/// A page between region resolution and TableFormer: what `prepare_page`
1018/// produced and `complete_page` still needs, so a pool worker can park the
1019/// page while another worker holds the shared TableFormer (see `Staged`).
1020struct Prepared {
1021    regions: Vec<layout::Region>,
1022    ocr_confs: Vec<f32>,
1023    ocr_cells: Vec<docling_core::OcrCellConfidence>,
1024    parse: Option<f64>,
1025    /// The OCR lines read inside the pictures of a text-layer page under
1026    /// `picture_ocr` (#1219), hung on the assembled pictures.
1027    picture_text: Vec<pdfium_backend::TextCell>,
1028}
1029
1030#[cfg(feature = "ml")]
1031/// A pool worker's per-page outcome. `NeedsTables` is a page whose only
1032/// remaining stage is the shared TableFormer, which was busy when the worker
1033/// got there: rather than block on the mutex — one worker idle for the
1034/// whole of another worker's table decode, ~9.5 s of the 60-page .NET slice
1035/// on a 2-worker pool — the worker keeps the page aside, pulls the next one
1036/// off the render channel, and comes back once the slot is free. Results
1037/// are reassembled by page index anyway, so completion order is free.
1038enum Staged {
1039    Done(PageOut),
1040    NeedsTables(Prepared),
1041}
1042
1043#[cfg(feature = "ml")]
1044/// How many pages a pool worker keeps parked on the TableFormer before it
1045/// falls back to waiting: each carries its ~5 MB bitmaps, so this bounds the
1046/// extra residency to two pages per worker on top of the render channel.
1047const MAX_DEFERRED_PAGES: usize = 2;
1048
1049#[cfg(feature = "ml")]
1050/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
1051/// lazily on the first table region any worker sees. Tables appear on a
1052/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
1053/// weights+arenas by the pool size for nothing; a single shared instance keeps
1054/// the peak flat regardless of pool width, and a table's structure prediction
1055/// is independent of which worker runs it, so output is byte-identical. The
1056/// mutex serialises concurrent tables — the shared instance is loaded with the
1057/// full intra-op thread budget to compensate (one wide TableFormer instead of
1058/// several narrow ones).
1059enum TfSlot {
1060    /// Not attempted yet (no table seen so far).
1061    Unloaded,
1062    /// Load attempted, graphs absent — geometric fallback (warned once).
1063    Missing,
1064    Ready(tableformer::TableFormer),
1065}
1066
1067#[cfg(feature = "ml")]
1068impl TfSlot {
1069    /// Load TableFormer on the first call: `Ready`, or `Missing` when its
1070    /// graphs are absent (the geometric fallback — degradation, not an
1071    /// error). Later calls are no-ops either way.
1072    fn load(&mut self) {
1073        if matches!(self, TfSlot::Unloaded) {
1074            *self = match tableformer::TableFormer::load_with(tf_intra()) {
1075                Some(tf) => TfSlot::Ready(tf),
1076                None => TfSlot::Missing,
1077            };
1078        }
1079    }
1080}
1081
1082#[cfg(feature = "ml")]
1083type SharedTables = Arc<Mutex<TfSlot>>;
1084
1085#[cfg(feature = "ml")]
1086/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
1087/// one instance per pipeline, loaded on the first region that needs it.
1088enum EnrichSlot<T> {
1089    Unloaded,
1090    /// Load attempted, model files absent — enrichment skipped (warned once).
1091    Missing,
1092    Ready(T),
1093}
1094
1095#[cfg(feature = "ml")]
1096type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
1097#[cfg(feature = "ml")]
1098type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
1099
1100#[cfg(feature = "ml")]
1101/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
1102/// flags (`do_picture_classification`, `do_code_enrichment`,
1103/// `do_formula_enrichment`). All off by default.
1104#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1105pub struct EnrichmentOptions {
1106    /// Classify each picture with DocumentFigureClassifier (26 classes).
1107    pub picture_classification: bool,
1108    /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
1109    pub code: bool,
1110    /// Decode display formulas to LaTeX with CodeFormulaV2.
1111    pub formula: bool,
1112}
1113
1114#[cfg(feature = "ml")]
1115impl EnrichmentOptions {
1116    fn any(&self) -> bool {
1117        self.picture_classification || self.code || self.formula
1118    }
1119}
1120
1121#[cfg(feature = "ml")]
1122/// The layout model's input for a page: the pypdfium2-exact scale-1.0 page
1123/// image (#478) when the renderer produced one, else the legacy stretch of the 2×
1124/// bitmap (browser / METS paths) — see [`layout::LayoutSrc`]. Public so the
1125/// diagnostic examples feed [`layout::LayoutModel::predict`] the same input
1126/// the pipeline does.
1127pub fn layout_src(page: &PdfPage) -> layout::LayoutSrc<'_> {
1128    match &page.image_layout {
1129        Some(img) => layout::LayoutSrc::PageImage(img),
1130        None => layout::LayoutSrc::Raw(&page.image),
1131    }
1132}
1133
1134#[cfg(feature = "ml")]
1135/// RapidOCR's longest side (`Global.max_side_len`, 2000): docling renders the
1136/// OCR input at `OcrOptions.scale` = 3 and RapidOCR then shrinks what exceeds
1137/// this before detecting and recognizing, so that is the resolution its
1138/// models actually see.
1139pub(crate) const RAPIDOCR_MAX_SIDE: f32 = 2000.0;
1140
1141#[cfg(feature = "ml")]
1142/// The px/pt the OCR reads a page at: the caller's `ocr_scale` when set; else,
1143/// for a standalone bitmap input — its own scale-1.0 page, a resolution the
1144/// pipeline did not choose — docling's rule (#570): three pixels per point
1145/// (`OcrOptions.scale`), shrunk so the longer side stays within RapidOCR's
1146/// 2000 px (a 754 × 1000 scanned form reads at 2.0; a 3000 px photo at 0.67,
1147/// as RapidOCR would downsample it). `None` for a rendered page (PDF, hOCR),
1148/// which keeps its own render — the 2.0 px/pt the conformance baselines are
1149/// pinned to. Measured on FUNSD at 1.0 / 2.0 / 3.0 px/pt: 0.825 / 0.856 /
1150/// 0.836 word recall — the recognizer likes its crops at the resolution
1151/// RapidOCR hands it, no more.
1152fn page_ocr_scale(ocr_scale: Option<f32>, width: f32, height: f32, scale: f32) -> Option<f32> {
1153    if ocr_scale.is_some() || scale != 1.0 {
1154        return ocr_scale;
1155    }
1156    let longest = width.max(height);
1157    if longest <= 0.0 {
1158        return None;
1159    }
1160    let s = 3.0f32.min(RAPIDOCR_MAX_SIDE / longest);
1161    ((s - 1.0).abs() > 1e-3).then_some(s)
1162}
1163
1164#[cfg(feature = "ml")]
1165/// The bitmap + px/pt scale the OCR reads (#254, docling#3877's
1166/// `OcrOptions.scale`): the page's own render unless `ocr_scale` asks for a
1167/// different resolution, where a PIL-bicubic resample of that render is built
1168/// once per page (cached in `cache`) and shared by every OCR pass. Resampling
1169/// — rather than a second native pdfium render — keeps one code path across
1170/// PDF, image, and hOCR inputs and leaves the layout/TableFormer pixels (and
1171/// with them the conformance baseline) untouched; the 144-dpi base render is
1172/// itself supersampled down from 216 dpi, so an upscaled OCR view loses
1173/// little against a native render.
1174fn ocr_input<'a>(
1175    cache: &'a mut Option<image::RgbImage>,
1176    image: &'a image::RgbImage,
1177    scale: f32,
1178    ocr_scale: Option<f32>,
1179) -> (&'a image::RgbImage, f32) {
1180    match ocr_scale {
1181        Some(s) if (s - scale).abs() > 1e-3 && image.width() > 1 => {
1182            let f = s / scale;
1183            let img = cache.get_or_insert_with(|| {
1184                let dw = ((image.width() as f32 * f).round() as u32).max(1);
1185                let dh = ((image.height() as f32 * f).round() as u32).max(1);
1186                resample::pil_resize(image, dw, dh, resample::PilFilter::Bicubic)
1187            });
1188            (img, s)
1189        }
1190        _ => (image, scale),
1191    }
1192}
1193
1194#[cfg(feature = "ml")]
1195/// A self-contained set of the per-page models (layout, OCR). Each parallel
1196/// page-worker owns its own `Worker` so inference runs concurrently without
1197/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
1198/// rarely-hit TableFormer is shared (see [`TfSlot`]).
1199struct Worker {
1200    /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
1201    layout: Option<layout::LayoutModel>,
1202    ocr: OcrSlot,
1203    /// What this worker's OCR requests met since the pipeline last asked
1204    /// (#1210): set by [`Self::ocr_model`] whenever a page wants OCR, read
1205    /// and cleared by [`Pipeline::take_ocr_status`]. `None` = no request.
1206    ocr_status: Option<docling_core::OcrStatus>,
1207    det: SharedDet,
1208    /// Text-detector results computed ahead of a page's OCR pass (#429), keyed
1209    /// by page index: the detector reads nothing but the page image, so it
1210    /// runs on its own thread while the layout model predicts — see
1211    /// [`Self::detect_alongside`] — and the OCR block collects the boxes here
1212    /// instead of paying for detection serially.
1213    pending_det: BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
1214    /// This worker's intra-op thread budget — also the OCR lane count (see
1215    /// [`ocr::OcrModel::load_with`]): a pool worker with two threads runs two
1216    /// single-thread recognisers, the primary as many as its cores.
1217    intra: usize,
1218    /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
1219    tables: Option<SharedTables>,
1220    /// Shared enrichment slots; `None` unless the corresponding flag is on.
1221    classifier: Option<SharedClassifier>,
1222    code_formula: Option<SharedCodeFormula>,
1223    enrich: EnrichmentOptions,
1224    /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
1225    /// embedded text layer. See [`Pipeline::no_ocr`].
1226    no_ocr: bool,
1227    /// Discard the embedded text layer and OCR every page. See
1228    /// [`Pipeline::force_full_page_ocr`].
1229    force_full_page_ocr: bool,
1230    /// OCR a page whose text layer [`quality::is_broken_text_layer`] judges
1231    /// broken, that page only (#1006). See
1232    /// [`Pipeline::replace_broken_text_layer`].
1233    replace_broken_text_layer: bool,
1234    /// Read the pictures of a text-layer page (#1219). See
1235    /// [`Pipeline::picture_ocr`].
1236    picture_ocr: bool,
1237    /// Keep text-panel pictures as pictures instead of demoting them to
1238    /// paragraphs. See [`Pipeline::no_text_panels`].
1239    no_text_panels: bool,
1240    /// Never run OCR, but keep layout + TableFormer (#244) — docling's
1241    /// `do_ocr=False`. See [`Pipeline::skip_ocr`].
1242    skip_ocr: bool,
1243    /// Which recognition model [`Self::ocr`] loads. See [`Pipeline::ocr_lang`].
1244    ocr_lang: ocr::OcrLang,
1245    /// Which engine [`Self::ocr`] is (#460). See [`Pipeline::ocr_engine`].
1246    ocr_engine: ocr::OcrEngine,
1247    /// Tesseract's `-l` argument (#460). See [`Pipeline::tesseract_lang`].
1248    tesseract_lang: Option<String>,
1249    /// OCR render scale override (px/pt, #254). See [`Pipeline::ocr_scale`].
1250    ocr_scale: Option<f32>,
1251    /// RapidOCR's line orientation handling (#666), handed to the PP-OCR
1252    /// recognizer. See [`Pipeline::ocr_textline_orientation`].
1253    textline_orientation: bool,
1254    /// Picture-crop scale and page images (#519/#520). See [`ImageOutput`].
1255    images: ImageOutput,
1256}
1257
1258#[cfg(feature = "ml")]
1259/// The worker's lazily-loaded OCR recognition model. `Missing` records a
1260/// failed load (#244: degradation over failure — a deployment without the OCR
1261/// model still gets layout + TableFormer, and OCR-dependent regions stay
1262/// empty) so the load isn't retried per page. It keeps the load error: every
1263/// later conversion that wants OCR reports it on its result (#1210), not
1264/// only the first one the one-time warning reached.
1265enum OcrSlot {
1266    Unloaded,
1267    Ready(Recognizer),
1268    Missing(String),
1269}
1270
1271#[cfg(feature = "ml")]
1272/// The loaded OCR engine (#460): PP-OCRv3 via ONNX Runtime or the
1273/// `tesseract` binary. Both answer the two questions the page assembly asks
1274/// — line cells for text regions, word cells for table regions — in page
1275/// points with a 0–1 confidence, so the call sites never know which runs.
1276pub(crate) enum Recognizer {
1277    PpOcr(ocr::OcrModel),
1278    Tesseract(tesseract::TesseractOcr),
1279}
1280
1281#[cfg(feature = "ml")]
1282impl Recognizer {
1283    /// See [`ocr::OcrModel::ocr_page_with`].
1284    fn ocr_page(
1285        &mut self,
1286        img: &image::RgbImage,
1287        regions: &[layout::Region],
1288        scale: f32,
1289    ) -> Result<Vec<(TextCell, f32)>, String> {
1290        self.ocr_page_with(img, regions, scale, None)
1291    }
1292
1293    /// [`Self::ocr_page`] with the detector's boxes (#570). Tesseract segments its
1294    /// own lines and ignores the detector's boxes.
1295    fn ocr_page_with(
1296        &mut self,
1297        img: &image::RgbImage,
1298        regions: &[layout::Region],
1299        scale: f32,
1300        detected: Option<&[ocr_det::DetBox]>,
1301    ) -> Result<Vec<(TextCell, f32)>, String> {
1302        match self {
1303            Self::PpOcr(m) => m.ocr_page_with(img, regions, scale, detected),
1304            Self::Tesseract(t) => t.ocr_page(img, regions, scale),
1305        }
1306    }
1307
1308    /// See [`ocr::OcrModel::ocr_table_words`].
1309    fn ocr_table_words(
1310        &mut self,
1311        img: &image::RgbImage,
1312        regions: &[layout::Region],
1313        scale: f32,
1314        detected: Option<&[ocr_det::DetBox]>,
1315    ) -> Result<Vec<(TextCell, f32)>, String> {
1316        match self {
1317            Self::PpOcr(m) => m.ocr_table_words(img, regions, scale, detected),
1318            Self::Tesseract(t) => t.ocr_table_words(img, regions, scale),
1319        }
1320    }
1321}
1322
1323#[cfg(feature = "ml")]
1324/// The text detector (#429), loaded on the first OCR'd page like the
1325/// recognizer; `Missing` keeps the pipeline recognition-only. One instance
1326/// is shared by every worker ([`SharedDet`], #945, as TableFormer is): the
1327/// DB net's activation arena at the 2000 px input (#570) is ~250 MB, the
1328/// largest of any OCR model, and per-worker copies multiplied it by the
1329/// pool width for a model that runs once per page. The mutex serializes
1330/// concurrent detections; each worker's layout still runs alongside its
1331/// own, so the wall time is unchanged, and a page's boxes do not depend on
1332/// which worker detected them, so the output is byte-identical.
1333enum DetSlot {
1334    Unloaded,
1335    Ready(ocr_det::DetModel),
1336    Missing,
1337}
1338
1339#[cfg(feature = "ml")]
1340impl DetSlot {
1341    /// Load the detector on the first call — with the full intra-op budget,
1342    /// one wide session for the pool — `Missing` (said once under
1343    /// `DOCLING_RS_DEBUG`) when the model is not installed.
1344    fn load(&mut self) {
1345        if matches!(self, DetSlot::Unloaded) {
1346            *self = match ocr_det::DetModel::load(intra_threads()) {
1347                Ok(model) => DetSlot::Ready(model),
1348                Err(e) => {
1349                    docling_core::debug_log!(
1350                        "docling-pdf: text detection unavailable ({e}); OCR stays region-scoped"
1351                    );
1352                    DetSlot::Missing
1353                }
1354            };
1355        }
1356    }
1357}
1358
1359#[cfg(feature = "ml")]
1360type SharedDet = Arc<Mutex<DetSlot>>;
1361
1362#[cfg(feature = "ml")]
1363impl Worker {
1364    #[allow(clippy::too_many_arguments)] // mirrors the Pipeline's option set
1365    fn load(
1366        intra: usize,
1367        tables: Option<SharedTables>,
1368        det: SharedDet,
1369        enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
1370        enrich: EnrichmentOptions,
1371        no_ocr: bool,
1372        skip_ocr: bool,
1373        force_full_page_ocr: bool,
1374        no_text_panels: bool,
1375        ocr_lang: ocr::OcrLang,
1376        ocr_engine: ocr::OcrEngine,
1377        tesseract_lang: Option<String>,
1378        ocr_scale: Option<f32>,
1379        textline_orientation: bool,
1380        images: ImageOutput,
1381    ) -> Result<Self, PdfError> {
1382        Ok(Self {
1383            images,
1384            layout: if no_ocr {
1385                None
1386            } else {
1387                Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
1388            },
1389            ocr: OcrSlot::Unloaded,
1390            ocr_status: None,
1391            det,
1392            pending_det: BTreeMap::new(),
1393            intra,
1394            tables,
1395            classifier: enrich_slots.0,
1396            code_formula: enrich_slots.1,
1397            enrich,
1398            no_ocr,
1399            skip_ocr,
1400            force_full_page_ocr,
1401            // Set by the pipeline after loading (`sync_ocr_config`).
1402            replace_broken_text_layer: false,
1403            picture_ocr: false,
1404            no_text_panels,
1405            ocr_lang,
1406            ocr_engine,
1407            tesseract_lang,
1408            ocr_scale,
1409            textline_orientation,
1410        })
1411    }
1412
1413    /// Set [`Pipeline::ocr_textline_orientation`] here and on a loaded
1414    /// PP-OCR recognizer.
1415    fn set_textline_orientation(&mut self, enable: bool) {
1416        self.textline_orientation = enable;
1417        if let OcrSlot::Ready(Recognizer::PpOcr(m)) = &mut self.ocr {
1418            m.set_textline_orientation(enable);
1419        }
1420    }
1421
1422    /// The OCR model, or `None` when this conversion must not (or cannot) OCR:
1423    /// `skip_ocr` short-circuits, and a failed model load degrades to `None`
1424    /// with a one-time warning instead of failing the conversion (#244) —
1425    /// unless `force_full_page_ocr` demanded OCR explicitly, where a missing
1426    /// model stays a hard error (the text layer was deliberately discarded, so
1427    /// degrading would silently emit an empty document).
1428    fn ocr_model(&mut self) -> Result<Option<&mut Recognizer>, PdfError> {
1429        if self.skip_ocr {
1430            return Ok(None);
1431        }
1432        if matches!(self.ocr, OcrSlot::Unloaded) {
1433            let loaded = match self.ocr_engine {
1434                ocr::OcrEngine::PpOcr => {
1435                    ocr::OcrModel::load_with(self.ocr_lang, self.intra).map(|mut m| {
1436                        m.set_textline_orientation(self.textline_orientation);
1437                        Recognizer::PpOcr(m)
1438                    })
1439                }
1440                ocr::OcrEngine::Tesseract => tesseract::TesseractOcr::load(
1441                    tesseract::TesseractOptions::from_env(self.tesseract_lang.clone()),
1442                    self.intra,
1443                )
1444                .map(Recognizer::Tesseract),
1445            };
1446            match loaded {
1447                Ok(model) => self.ocr = OcrSlot::Ready(model),
1448                Err(e) if self.force_full_page_ocr => return Err(PdfError::Ocr(e)),
1449                Err(e) => {
1450                    static WARNED: std::sync::Once = std::sync::Once::new();
1451                    let hint = match self.ocr_engine {
1452                        ocr::OcrEngine::PpOcr => {
1453                            "install the models with scripts/install/download_dependencies.sh, \
1454                             or docling_rs.download_models() from Python"
1455                        }
1456                        ocr::OcrEngine::Tesseract => {
1457                            "install tesseract-ocr with the language pack, or use --ocr-engine ppocr"
1458                        }
1459                    };
1460                    WARNED.call_once(|| {
1461                        eprintln!(
1462                            "warning: OCR model unavailable ({e}); continuing without OCR — \
1463                             scanned pages and text inside images will come back empty \
1464                             ({hint})"
1465                        );
1466                    });
1467                    self.ocr = OcrSlot::Missing(e.to_string());
1468                }
1469            }
1470        }
1471        // Every call is a page (or picture) asking for OCR — the callers
1472        // reach here only once a text-less region needs reading — so the
1473        // slot's state is what that request met (#1210).
1474        let met = match &self.ocr {
1475            OcrSlot::Ready(_) => docling_core::OcrStatus::Available,
1476            OcrSlot::Missing(reason) => docling_core::OcrStatus::Unavailable {
1477                reason: reason.clone(),
1478            },
1479            OcrSlot::Unloaded => unreachable!("loaded above"),
1480        };
1481        self.ocr_status = docling_core::OcrStatus::merge_opt(self.ocr_status.take(), Some(met));
1482        Ok(match &mut self.ocr {
1483            OcrSlot::Ready(model) => Some(model),
1484            _ => None,
1485        })
1486    }
1487
1488    /// [`Self::ocr_model`] when `wanted`, else `None` without touching the
1489    /// slot: the call sites that only *may* need OCR (a region left without
1490    /// text, a picture-table) ask through here, so a page with nothing to
1491    /// read neither loads the model nor counts as an OCR request on the
1492    /// result's status (#1210) — a born-digital page needs no OCR, whatever
1493    /// the engine's state.
1494    fn ocr_model_if(&mut self, wanted: bool) -> Result<Option<&mut Recognizer>, PdfError> {
1495        if wanted {
1496            self.ocr_model()
1497        } else {
1498            Ok(None)
1499        }
1500    }
1501
1502    /// Run `f` on the shared text detector (#429/#945), loading it on first
1503    /// use; `None` with `skip_ocr` or when the model is not installed —
1504    /// recognition stays region-scoped then, exactly the pre-#429 behavior.
1505    /// The slot's lock is held for the call, which serializes detections
1506    /// across the pool.
1507    fn with_det<R>(&mut self, f: impl FnOnce(&mut ocr_det::DetModel) -> R) -> Option<R> {
1508        if self.skip_ocr {
1509            return None;
1510        }
1511        let mut slot = self.det.lock().unwrap_or_else(|p| p.into_inner());
1512        slot.load();
1513        match &mut *slot {
1514            DetSlot::Ready(model) => Some(f(model)),
1515            _ => None,
1516        }
1517    }
1518
1519    /// Whether the text detector is there to run (loading it on first use).
1520    fn det_available(&mut self) -> bool {
1521        self.with_det(|_| ()).is_some()
1522    }
1523
1524    /// OCR one picture of a text-layer page (#1219, `picture_ocr`) the way
1525    /// the picture OCR of the other formats reads an embedded image
1526    /// (`Pipeline::ocr_picture`): the region's own crop of the page render,
1527    /// the text detector's boxes on that crop as the line crops when the
1528    /// detector is installed — a photo's label or a seal's ring of text is
1529    /// no stack of horizontal strips, which is all the ink projection can
1530    /// cut — and the recognizer's lines mapped back to page points. Empty
1531    /// without the recognizer (its one-time warning says why) or `skip_ocr`.
1532    fn read_picture_region(
1533        &mut self,
1534        page: &PdfPage,
1535        r: &layout::Region,
1536        ocr_scale: Option<f32>,
1537    ) -> Result<Vec<pdfium_backend::TextCell>, String> {
1538        let s = page.scale;
1539        let (iw, ih) = (page.image.width(), page.image.height());
1540        let x0 = ((r.l * s).floor().max(0.0) as u32).min(iw);
1541        let y0 = ((r.t * s).floor().max(0.0) as u32).min(ih);
1542        let x1 = ((r.r * s).ceil().max(0.0) as u32).min(iw);
1543        let y1 = ((r.b * s).ceil().max(0.0) as u32).min(ih);
1544        if x1 <= x0 + 1 || y1 <= y0 + 1 {
1545            return Ok(Vec::new());
1546        }
1547        let crop = image::imageops::crop_imm(&page.image, x0, y0, x1 - x0, y1 - y0).to_image();
1548        let mut cache = None;
1549        let (view, scale) = ocr_input(&mut cache, &crop, s, ocr_scale);
1550        let (ox, oy) = (x0 as f32 / s, y0 as f32 / s);
1551        let region = layout::Region {
1552            label: "text",
1553            score: 1.0,
1554            l: 0.0,
1555            t: 0.0,
1556            r: (x1 - x0) as f32 / s,
1557            b: (y1 - y0) as f32 / s,
1558        };
1559        // A detector that cannot run costs the picture its detected lines,
1560        // not the conversion: the projection strips read it instead.
1561        let detected = self
1562            .with_det(|det| det.detect(view))
1563            .and_then(Result::ok)
1564            .filter(|d| ocr::det_lines() && !d.is_empty());
1565        let Some(model) = self.ocr_model().map_err(|e| e.to_string())? else {
1566            return Ok(Vec::new());
1567        };
1568        let cells = model.ocr_page_with(
1569            view,
1570            std::slice::from_ref(&region),
1571            scale,
1572            detected.as_deref(),
1573        )?;
1574        Ok(cells
1575            .into_iter()
1576            .map(|(mut c, _)| {
1577                c.l += ox;
1578                c.r += ox;
1579                c.t += oy;
1580                c.b += oy;
1581                c
1582            })
1583            .collect())
1584    }
1585
1586    /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
1587    /// into its nodes and links. Pure given the page (mutates only the worker's
1588    /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
1589    fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
1590        if self.no_ocr {
1591            // Fastest path (`text_only_page`): the text layer alone, nothing
1592            // inferred. Pages with no embedded text layer yield nothing;
1593            // convert those without `no_ocr`.
1594            let (nodes, links, conf) = text_only_page(page, self.images.scale);
1595            return Ok((nodes, links, conf, self.page_image(n, page), Vec::new()));
1596        }
1597        self.normalize_orientation(n, page)?;
1598        let det_pages = self.det_candidates(std::slice::from_ref(&(n, &*page)))?;
1599        let regions = {
1600            let Self {
1601                layout,
1602                det,
1603                pending_det,
1604                ocr_scale,
1605                ..
1606            } = self;
1607            let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
1608            let page: &PdfPage = &*page;
1609            Self::detect_alongside(&*det, pending_det, *ocr_scale, &det_pages, || {
1610                timing::timed("layout.predict", || {
1611                    layout.predict(layout_src(page), page.width, page.height)
1612                })
1613            })
1614        }
1615        .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
1616        // The 2x bitmap (#682), when the detections read it (#897).
1617        self.ensure_bitmap(page, &regions)?;
1618        self.finish_page(n, page, regions)
1619    }
1620
1621    /// The page's render as docling's `PageItem.image` (#520), at
1622    /// [`ImageOutput::scale`] — `None` unless page images were requested, or
1623    /// when the page has no bitmap (the text-layer-only `no_ocr` path never
1624    /// renders one).
1625    fn page_image(&self, n: usize, page: &PdfPage) -> Option<docling_core::PictureImage> {
1626        page_image_under(self.images, n, page)
1627    }
1628
1629    /// The pages of a batch the text detector should sweep (#429): bitmap
1630    /// pages (no text layer) on a run with OCR and the detector available —
1631    /// loading both lazily here so the concurrent run below needs no `self`.
1632    fn det_candidates<'p>(
1633        &mut self,
1634        pages: &[(usize, &'p PdfPage)],
1635    ) -> Result<Vec<(usize, &'p PdfPage)>, PdfError> {
1636        // Pages the orientation pass already detected (#571) are skipped:
1637        // their boxes wait in `pending_det`.
1638        let scanned: Vec<(usize, &PdfPage)> = pages
1639            .iter()
1640            .filter(|(n, p)| {
1641                p.cells.is_empty() && p.image.width() > 1 && !self.pending_det.contains_key(n)
1642            })
1643            .copied()
1644            .collect();
1645        if scanned.is_empty() || self.ocr_model()?.is_none() || !self.det_available() {
1646            return Ok(Vec::new());
1647        }
1648        Ok(scanned)
1649    }
1650
1651    /// Run `layout` on the calling thread while the text detector sweeps
1652    /// `det_pages` on another (#429): the detector only reads each page's
1653    /// image, layout only reads the pages too, and the two sessions are
1654    /// independent, so on a scanned page the ~0.7 s detection hides behind
1655    /// layout instead of adding to it. Results land in `pending_det` for the
1656    /// OCR block; a detector failure is recorded per page and surfaces there.
1657    fn detect_alongside<T>(
1658        det: &SharedDet,
1659        pending_det: &mut BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
1660        ocr_scale: Option<f32>,
1661        det_pages: &[(usize, &PdfPage)],
1662        layout: impl FnOnce() -> T,
1663    ) -> T {
1664        if det_pages.is_empty() {
1665            return layout();
1666        }
1667        // Loaded by `det_candidates` (which produced a non-empty list); the
1668        // lock is held while this worker's layout runs, so another worker's
1669        // detection waits for this one — its layout does not.
1670        let mut slot = det.lock().unwrap_or_else(|p| p.into_inner());
1671        let DetSlot::Ready(det) = &mut *slot else {
1672            return layout();
1673        };
1674        std::thread::scope(|s| {
1675            let handle = s.spawn(move || {
1676                det_pages
1677                    .iter()
1678                    .map(|&(n, page)| {
1679                        let mut view = None;
1680                        let (img, _) = ocr_input(
1681                            &mut view,
1682                            &page.image,
1683                            page.scale,
1684                            page_ocr_scale(ocr_scale, page.width, page.height, page.scale),
1685                        );
1686                        (
1687                            n,
1688                            timing::timed("ocr.det", || {
1689                                det.detect_scan(img, ocr_scale.is_none() && page.scale != 1.0)
1690                            }),
1691                        )
1692                    })
1693                    .collect::<Vec<_>>()
1694            });
1695            let out = layout();
1696            match handle.join() {
1697                Ok(results) => pending_det.extend(results),
1698                Err(_) => {
1699                    for &(n, _) in det_pages {
1700                        pending_det.insert(n, Err("ocr-det: detection thread panicked".into()));
1701                    }
1702                }
1703            }
1704            out
1705        })
1706    }
1707
1708    /// Content-based orientation normalization (#225), before any inference:
1709    /// a physically rotated scan (sideways phone photo, landscape-fed sheet)
1710    /// has `/Rotate 0`, so the metadata pass in `extract_page` never fires and
1711    /// layout+OCR would read a sideways raster. Only pages with no text layer
1712    /// at all are probed (a digital page's raster is upright by construction,
1713    /// and its cells — not its pixels — carry the text); the detected angle
1714    /// composes with any `/Rotate` normalization through the same
1715    /// [`PdfPage::unrotate`] + display-space assembly mapping. Detection is
1716    /// evidence-gated and degrades to a no-op — see [`orient`].
1717    fn normalize_orientation(&mut self, n: usize, page: &mut PdfPage) -> Result<(), PdfError> {
1718        let scanned =
1719            page.cells.is_empty() && page.word_cells.is_empty() && page.code_cells.is_empty();
1720        if self.no_ocr || self.skip_ocr || !orient::enabled() {
1721            return Ok(());
1722        }
1723        // A sideways page drawn as vector outlines keeps a small upright text
1724        // layer (a page number, a running header, #936): the layer is too thin
1725        // to be the page's text, so the raster is probed like a scan's. The
1726        // render may still be deferred for a page that needed no bitmap.
1727        if !scanned {
1728            if !sparse_text_layer(page) {
1729                return Ok(());
1730            }
1731            page.resolve_image()?;
1732        }
1733        if page.image.width() <= 1 {
1734            return Ok(());
1735        }
1736        // The probe reads text through the OCR model; without one (missing —
1737        // #244 degradation) the page stays as rendered.
1738        if self.ocr_model()?.is_none() {
1739            return Ok(());
1740        }
1741        // The text detector's lines are the probe's crops (#571). Detected on
1742        // the page image as rendered; an upright scan keeps them for the OCR
1743        // pass (`pending_det`) when that pass reads the same bitmap, so the
1744        // detector runs once per page as before — a rotated page detects
1745        // again on the un-rotated image, alongside layout. A page with a
1746        // (thin) text layer only needs the probe's few wide lines and its
1747        // OCR pass detects on region crops (#931), so it pays the pre-#570
1748        // 960 px budget here instead of the full one (#945).
1749        let ocr_scale = page_ocr_scale(self.ocr_scale, page.width, page.height, page.scale);
1750        let image = &page.image;
1751        let boxes: Vec<ocr_det::DetBox> = self
1752            .with_det(|det| {
1753                timing::timed("orient.det", || {
1754                    if scanned {
1755                        det.detect_scan(image, ocr_scale.is_none() && page.scale != 1.0)
1756                    } else {
1757                        det.detect_capped(image, PROBE_DET_MAX_SIDE)
1758                    }
1759                })
1760            })
1761            .unwrap_or(Ok(Vec::new()))
1762            .unwrap_or_else(|e| {
1763                debug_log!(
1764                    "docling-pdf: page {}: text detection failed ({e}); probing projection strips",
1765                    n + 1
1766                );
1767                Vec::new()
1768            });
1769        let Some(ocr) = self.ocr_model()? else {
1770            return Ok(());
1771        };
1772        let deg = timing::timed("orient.detect", || {
1773            orient::detect(&page.image, ocr, page.scale, &boxes)
1774        });
1775        if deg != 0 {
1776            debug_log!(
1777                "docling-pdf: page {}: content rotated {deg}° in the raster; \
1778                 un-rotating before layout/OCR",
1779                n + 1
1780            );
1781            page.unrotate(deg);
1782        } else if scanned
1783            && !boxes.is_empty()
1784            && ocr_scale.is_none_or(|s| (s - page.scale).abs() <= 1e-3)
1785        {
1786            self.pending_det.insert(n, Ok(boxes));
1787        }
1788        Ok(())
1789    }
1790
1791    /// Layout-detect a whole batch of pages with one inference call (issue #73),
1792    /// then run each page's remaining stages (OCR / TableFormer / enrichment /
1793    /// assembly) per page. Index-aligned with `items`; a layout failure fails
1794    /// every page in the batch (they shared the one inference call).
1795    fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<Staged, PdfError>> {
1796        if self.no_ocr {
1797            // No layout model to batch — the text-layer-only path is per page.
1798            return items
1799                .iter_mut()
1800                .map(|(n, page)| {
1801                    let n = *n;
1802                    self.process(n, page).map(Staged::Done)
1803                })
1804                .collect();
1805        }
1806        // Orientation-normalize every scanned page before the shared layout
1807        // call — the batched inference must see upright bitmaps too (#225).
1808        for (n, page) in items.iter_mut() {
1809            let n = *n;
1810            if let Err(e) = self.normalize_orientation(n, page) {
1811                // Model-load failure — every page in the batch needs the same
1812                // model, so they all fail alike (mirrors the layout-error arm).
1813                let msg = e.to_string();
1814                return items
1815                    .iter()
1816                    .map(|_| Err(PdfError::Ocr(msg.clone())))
1817                    .collect();
1818            }
1819        }
1820        let inputs: Vec<(layout::LayoutSrc<'_>, f32, f32)> = items
1821            .iter()
1822            .map(|(_, page)| (layout_src(page), page.width, page.height))
1823            .collect();
1824        let refs: Vec<(usize, &PdfPage)> = items.iter().map(|(n, page)| (*n, page)).collect();
1825        let det_pages = match self.det_candidates(&refs) {
1826            Ok(p) => p,
1827            Err(e) => {
1828                let msg = e.to_string();
1829                return items
1830                    .iter()
1831                    .map(|_| Err(PdfError::Ocr(msg.clone())))
1832                    .collect();
1833            }
1834        };
1835        let batched = {
1836            let Self {
1837                layout,
1838                det,
1839                pending_det,
1840                ocr_scale,
1841                ..
1842            } = self;
1843            let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
1844            Self::detect_alongside(&*det, pending_det, *ocr_scale, &det_pages, || {
1845                timing::timed("layout.predict", || layout.predict_batch(&inputs))
1846            })
1847        };
1848        match batched {
1849            Ok(all) => items
1850                .iter_mut()
1851                .zip(all)
1852                .map(|((n, page), regions)| {
1853                    // The 2x bitmap (#682), when the detections read it (#897).
1854                    self.ensure_bitmap(page, &regions)?;
1855                    self.stage_page(*n, page, regions)
1856                })
1857                .collect(),
1858            Err(e) => items
1859                .iter()
1860                .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
1861                .collect(),
1862        }
1863    }
1864
1865    /// A pool worker's main loop: pull rendered pages off the shared channel
1866    /// (whatever is already there, up to the layout batch size), process them,
1867    /// and hand each finished page — or its error — to `deliver`, which returns
1868    /// `false` to stop early (the streaming consumer went away). Returns when
1869    /// the channel is closed and every page this worker took is delivered.
1870    ///
1871    /// Pages whose TableFormer turn would have to wait are parked (see
1872    /// `Staged`) and retried before every new pull; while any are parked the
1873    /// pull is non-blocking, so an empty channel means the worker waits for
1874    /// the TableFormer rather than for the renderer. The parking budget
1875    /// (`MAX_DEFERRED_PAGES`) bounds resident bitmaps; past it the worker waits
1876    /// like the serial path. Output is independent of completion order — the
1877    /// callers reassemble by page index.
1878    fn run_pool(
1879        &mut self,
1880        work_rx: &Mutex<Receiver<(usize, PdfPage)>>,
1881        layout_batch: usize,
1882        deadline: Option<std::time::Instant>,
1883        mut deliver: impl FnMut(usize, Result<PageOut, PdfError>) -> bool,
1884    ) {
1885        use std::sync::mpsc::TryRecvError;
1886        let mut deferred: std::collections::VecDeque<(usize, PdfPage, Prepared)> =
1887            std::collections::VecDeque::new();
1888        loop {
1889            // The document budget (#497), checked between pages: once it is
1890            // spent, every page still queued or parked is reported as timed
1891            // out instead of processed — the renderer stops feeding at the
1892            // same check, so the queue drains quickly.
1893            if expired(deadline) {
1894                while let Some((idx, _, _)) = deferred.pop_front() {
1895                    if !deliver(idx, Err(timeout_sentinel())) {
1896                        return;
1897                    }
1898                }
1899                let rx = work_rx.lock().unwrap();
1900                loop {
1901                    match rx.recv() {
1902                        Ok((idx, _page)) => {
1903                            if !deliver(idx, Err(timeout_sentinel())) {
1904                                return;
1905                            }
1906                        }
1907                        Err(_) => return,
1908                    }
1909                }
1910            }
1911            // Any parked page the slot has since freed up for, oldest first.
1912            let mut i = 0;
1913            while i < deferred.len() {
1914                let (_, page, prepared) = &deferred[i];
1915                match self.table_rows_try(page, &prepared.regions) {
1916                    Some(rows) => {
1917                        let (idx, mut page, prepared) = deferred.remove(i).expect("index in range");
1918                        if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1919                            return;
1920                        }
1921                    }
1922                    None => i += 1,
1923                }
1924            }
1925            // Hold the receiver lock only for the recv (plus a non-blocking drain
1926            // up to the layout batch size); release before the (long) per-page
1927            // work so other workers can pull concurrently.
1928            let mut batch: Vec<(usize, PdfPage)> = Vec::new();
1929            let mut closed = false;
1930            {
1931                let rx = work_rx.lock().unwrap();
1932                let first = if deferred.is_empty() {
1933                    rx.recv().map_err(|_| TryRecvError::Disconnected)
1934                } else {
1935                    rx.try_recv()
1936                };
1937                match first {
1938                    Ok(item) => {
1939                        batch.push(item);
1940                        while batch.len() < layout_batch {
1941                            match rx.try_recv() {
1942                                Ok(item) => batch.push(item),
1943                                Err(_) => break,
1944                            }
1945                        }
1946                    }
1947                    Err(TryRecvError::Empty) => {}
1948                    Err(TryRecvError::Disconnected) => closed = true,
1949                }
1950            }
1951            if batch.is_empty() {
1952                // Nothing new rendered (or the channel is closed): wait our turn
1953                // on the oldest parked page instead.
1954                match deferred.pop_front() {
1955                    Some((idx, mut page, prepared)) => {
1956                        let rows = self.table_rows_blocking(&page, &prepared.regions);
1957                        if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1958                            return;
1959                        }
1960                        continue;
1961                    }
1962                    None if closed => return,
1963                    None => continue,
1964                }
1965            }
1966            let outs = self.process_batch(&mut batch);
1967            for ((idx, mut page), out) in batch.into_iter().zip(outs) {
1968                let delivered = match out {
1969                    Ok(Staged::Done(out)) => deliver(idx, Ok(out)),
1970                    Ok(Staged::NeedsTables(prepared)) => {
1971                        if deferred.len() < MAX_DEFERRED_PAGES {
1972                            deferred.push_back((idx, page, prepared));
1973                            true
1974                        } else {
1975                            let rows = self.table_rows_blocking(&page, &prepared.regions);
1976                            deliver(idx, self.complete_page(idx, &mut page, prepared, rows))
1977                        }
1978                    }
1979                    Err(e) => deliver(idx, Err(e)),
1980                };
1981                if !delivered {
1982                    return;
1983                }
1984            }
1985        }
1986    }
1987
1988    /// Everything after layout detection: per-label confidence thresholds,
1989    /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
1990    /// TableFormer, enrichment, and page assembly. The serial path: waits
1991    /// for the shared TableFormer when a table needs it.
1992    fn finish_page(
1993        &mut self,
1994        n: usize,
1995        page: &mut PdfPage,
1996        regions: Vec<layout::Region>,
1997    ) -> Result<PageOut, PdfError> {
1998        let prepared = self.prepare_page(n, page, regions)?;
1999        self.ensure_bitmap(page, &prepared.regions)?;
2000        let table_rows = self.table_rows_blocking(page, &prepared.regions);
2001        self.complete_page(n, page, prepared, table_rows)
2002    }
2003
2004    /// The pool path: like [`finish_page`](Self::finish_page), except that a
2005    /// page whose TableFormer turn would have to wait comes back as
2006    /// [`Staged::NeedsTables`] for the worker loop to park (see `Staged`).
2007    fn stage_page(
2008        &mut self,
2009        n: usize,
2010        page: &mut PdfPage,
2011        regions: Vec<layout::Region>,
2012    ) -> Result<Staged, PdfError> {
2013        let prepared = self.prepare_page(n, page, regions)?;
2014        self.ensure_bitmap(page, &prepared.regions)?;
2015        match self.table_rows_try(page, &prepared.regions) {
2016            Some(rows) => Ok(Staged::Done(self.complete_page(n, page, prepared, rows)?)),
2017            None => Ok(Staged::NeedsTables(prepared)),
2018        }
2019    }
2020
2021    /// Does this page read its 2x bitmap (#897)? Layout reads the separate
2022    /// 1x render; after it, the bitmap feeds TableFormer, picture crops (and
2023    /// the picture classifier, in-picture OCR and the image outputs on
2024    /// them), the code/formula enrichment crops, page images and OCR. A
2025    /// page without any of those — on a text-heavy document most pages —
2026    /// never renders it. Decided on the detections as they stand (a
2027    /// superset of what survives postprocessing, which only drops or
2028    /// demotes pictures and tables), and asked again wherever the regions
2029    /// change.
2030    fn needs_bitmap(&self, page: &PdfPage, regions: &[layout::Region]) -> bool {
2031        self.images.page_images
2032            || self.force_full_page_ocr
2033            || page.cells.is_empty()
2034            || regions.iter().any(|r| {
2035                r.label == "picture"
2036                    || assemble::is_table_like(r.label)
2037                    || (r.label == "code" && self.enrich.code)
2038                    || (r.label == "formula" && self.enrich.formula)
2039            })
2040    }
2041
2042    /// Install the page's deferred 2x bitmap (#682) if [`Self::needs_bitmap`]
2043    /// says it is read — rendering it now when it was not rendered already —
2044    /// and otherwise decline it, so the render helper skips it when it has
2045    /// not got to it yet (#897). Idempotent, and a declined page can still
2046    /// be resolved later (an fp32 layout retry with new detections).
2047    fn ensure_bitmap(
2048        &self,
2049        page: &mut PdfPage,
2050        regions: &[layout::Region],
2051    ) -> Result<(), PdfError> {
2052        if page.image_pending() {
2053            if self.needs_bitmap(page, regions) {
2054                page.resolve_image()?;
2055            } else {
2056                page.decline_image();
2057            }
2058        }
2059        Ok(())
2060    }
2061
2062    /// Does this page need the shared TableFormer at all? Table-free pages
2063    /// never touch (or load) it.
2064    fn needs_tables(&self, regions: &[layout::Region]) -> bool {
2065        self.tables.is_some() && regions.iter().any(|r| assemble::is_table_like(r.label))
2066    }
2067
2068    /// TableFormer structure for every table region of the page, on an
2069    /// already-locked slot (loading the model on first use). Tables serialise
2070    /// on this mutex, so the one instance gets the shared thread budget
2071    /// (quota-aware, #262) — DOCLING_RS_TF_INTRA narrows it further where the
2072    /// memory-per-thread tradeoff matters more than table latency.
2073    fn predict_tables(
2074        guard: &mut TfSlot,
2075        page: &PdfPage,
2076        regions: &[layout::Region],
2077    ) -> Vec<Option<tf_core::TableGrid>> {
2078        let mut table_rows: Vec<Option<tf_core::TableGrid>> = vec![None; regions.len()];
2079        debug_assert!(
2080            !page.image_pending(),
2081            "TableFormer reached an unrendered page bitmap"
2082        );
2083        guard.load();
2084        if let TfSlot::Ready(tf) = guard {
2085            // One 1024-px frame per page, shared by all of its tables, and one
2086            // call for all of them: with the dynamic-batch decoder their
2087            // decode steps are shared (each step costs about the same for B
2088            // tables as for one).
2089            let page1024 = tableformer::TableFormer::page_1024(&page.image);
2090            let (idx, boxes): (Vec<usize>, Vec<[f32; 4]>) = regions
2091                .iter()
2092                .enumerate()
2093                .filter(|(_, r)| assemble::is_table_like(r.label))
2094                .map(|(i, r)| (i, [r.l, r.t, r.r, r.b]))
2095                .unzip();
2096            let rows =
2097                tf.predict_tables_on(page.image.height(), &page1024, &boxes, &page.word_cells);
2098            for (i, grid) in idx.into_iter().zip(rows) {
2099                table_rows[i] = grid;
2100            }
2101        }
2102        table_rows
2103    }
2104
2105    /// Table structure for the page, waiting for the shared slot if another
2106    /// worker holds it (else geometric fallback downstream when there is no
2107    /// TableFormer at all). The `tableformer` timing stage here includes any
2108    /// wait.
2109    fn table_rows_blocking(
2110        &self,
2111        page: &PdfPage,
2112        regions: &[layout::Region],
2113    ) -> Vec<Option<tf_core::TableGrid>> {
2114        match self.tables.as_ref().filter(|_| self.needs_tables(regions)) {
2115            Some(slot) => timing::timed("tableformer", || {
2116                Self::predict_tables(&mut slot.lock().unwrap(), page, regions)
2117            }),
2118            None => vec![None; regions.len()],
2119        }
2120    }
2121
2122    /// Non-blocking variant: `None` when the slot is held by another worker
2123    /// right now — the caller parks the page and tries again later.
2124    fn table_rows_try(
2125        &self,
2126        page: &PdfPage,
2127        regions: &[layout::Region],
2128    ) -> Option<Vec<Option<tf_core::TableGrid>>> {
2129        let Some(slot) = self.tables.as_ref().filter(|_| self.needs_tables(regions)) else {
2130            return Some(vec![None; regions.len()]);
2131        };
2132        match slot.try_lock() {
2133            Ok(mut guard) => Some(timing::timed("tableformer", || {
2134                Self::predict_tables(&mut guard, page, regions)
2135            })),
2136            Err(std::sync::TryLockError::WouldBlock) => None,
2137            Err(std::sync::TryLockError::Poisoned(e)) => panic!("TableFormer slot poisoned: {e}"),
2138        }
2139    }
2140
2141    /// The stages before TableFormer: fp32 escalation, per-label confidence
2142    /// thresholds, overlap resolution, orphan-text recovery, OCR for cell-less
2143    /// pages, in-picture text and table-word recognition.
2144    fn prepare_page(
2145        &mut self,
2146        n: usize,
2147        page: &mut PdfPage,
2148        regions: Vec<layout::Region>,
2149    ) -> Result<Prepared, PdfError> {
2150        // Force-OCR is exactly "pretend the text layer is not there": clear
2151        // every cell kind the extractors produced before anything reads them,
2152        // and the ordinary no-text-layer machinery below — full-page OCR,
2153        // OCR-fed TableFormer matching — takes over unchanged. (`no_ocr` wins
2154        // when both are set, mirroring docling, where `force_full_page_ocr`
2155        // is a sub-option of `do_ocr`; the no-ocr path never reaches here.)
2156        // Done here rather than in `process` so the batched layout path
2157        // (`process_batch` → `finish_page`) honors the flag too.
2158        // Parse quality is scored on the extracted text layer before force-OCR
2159        // discards it (docling's page-preprocessing stage runs before OCR too,
2160        // so its parse_score also reflects the original text layer).
2161        let mut parse = quality::parse_score(&page.cells);
2162        // docling#4654 (#1006): a text layer a broken font mapping produced
2163        // (`quality::is_broken_text_layer`) is replaced by full-page OCR on
2164        // this page only, its `parse_score` zeroed — it keeps describing the
2165        // PDF layer. Judged only with OCR available: a page whose layer is
2166        // discarded with no recognizer to read it would lose its text, so a
2167        // missing model keeps the (broken) layer, degradation over failure.
2168        let replace_broken = !self.force_full_page_ocr
2169            && self.replace_broken_text_layer
2170            && parse.is_some()
2171            && quality::is_broken_text_layer(
2172                &page
2173                    .cells
2174                    .iter()
2175                    .map(|c| c.text.as_str())
2176                    .collect::<Vec<_>>()
2177                    .join("\n"),
2178            )
2179            && self.ocr_model()?.is_some();
2180        if replace_broken {
2181            debug_log!(
2182                "docling-pdf: page {}: broken text layer — replaced by full-page OCR",
2183                n + 1
2184            );
2185            parse = Some(0.0);
2186        }
2187        // Recognition confidences of every OCR'd cell on this page → ocr_score.
2188        let mut ocr_confs: Vec<f32> = Vec::new();
2189        let mut ocr_cells: Vec<docling_core::OcrCellConfidence> = Vec::new();
2190        // The bitmap the OCR reads (#254): with `ocr_scale` set, a resample of
2191        // the page render at the requested px/pt, built lazily on the first
2192        // OCR use so non-OCR pages never pay for it. Copied out of `self` up
2193        // front — the OCR sites hold `self.ocr_model()`'s mutable borrow.
2194        let ocr_scale = page_ocr_scale(self.ocr_scale, page.width, page.height, page.scale);
2195        let mut ocr_view: Option<image::RgbImage> = None;
2196        if self.force_full_page_ocr || replace_broken {
2197            page.cells.clear();
2198            page.code_cells.clear();
2199            page.word_cells.clear();
2200        }
2201        if replace_broken {
2202            // The bitmap was judged on the text layer just discarded (a prose
2203            // page declines it, #897); the OCR reads it now.
2204            self.ensure_bitmap(page, &regions)?;
2205        }
2206        // Quant-robustness guard: the default int8 layout graph keeps its
2207        // confidences near the 0.5 label thresholds, and a different CPU's
2208        // quantized kernels can flip a whole page's detections under them —
2209        // tables and paragraphs then dissolve into orphan one-liners while the
2210        // same build converts the page perfectly elsewhere. When a dense
2211        // digital page ends up with detections covering almost none of its
2212        // text cells, re-run that one page on the fp32 graph (lazy-loaded,
2213        // auto-int8 selection only) and keep whichever detections cover more.
2214        let mut regions = regions;
2215        if !page.cells.is_empty() {
2216            let thresholded = |rs: &[layout::Region]| -> Vec<layout::Region> {
2217                rs.iter()
2218                    .filter(|r| r.score >= layout::label_threshold(r.label))
2219                    .cloned()
2220                    .collect()
2221            };
2222            let text_cells = page
2223                .cells
2224                .iter()
2225                .filter(|c| !c.text.trim().is_empty())
2226                .count();
2227            let cov = assemble::layout_cell_coverage(&thresholded(&regions), &page.cells);
2228            if text_cells >= 15 && cov < 0.5 {
2229                let retry = self
2230                    .layout
2231                    .as_mut()
2232                    .expect("layout model loaded unless no_ocr")
2233                    .predict_fp32_fallback(layout_src(page), page.width, page.height)
2234                    .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
2235                if let Some(retry) = retry {
2236                    let cov2 = assemble::layout_cell_coverage(&thresholded(&retry), &page.cells);
2237                    if cov2 > cov {
2238                        debug_log!(
2239                            "docling-pdf: page {}: int8 layout covered {:.0}% of the text \
2240                             cells; the fp32 retry covers {:.0}% — using it",
2241                            n + 1,
2242                            cov * 100.0,
2243                            cov2 * 100.0
2244                        );
2245                        regions = retry;
2246                        // New detections may read the bitmap the first ones
2247                        // did not (#897).
2248                        self.ensure_bitmap(page, &regions)?;
2249                    }
2250                }
2251            }
2252        }
2253        // docling's LayoutPostprocessor drops each detection below its label's
2254        // confidence threshold (stricter than the 0.3 base the predictor keeps),
2255        // before any overlap resolution. This removes the low-confidence tables /
2256        // pictures / list-items that otherwise double-emit or mis-classify.
2257        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
2258            for r in &regions {
2259                eprintln!(
2260                    "DBG raw {} {:.2} [{:.2},{:.2},{:.2},{:.2}]",
2261                    r.label, r.score, r.l, r.t, r.r, r.b
2262                );
2263            }
2264        }
2265        regions.retain(|r| r.score >= layout::label_threshold(r.label));
2266        // docling's full-page picture filter and same-label picture dedup run
2267        // on the thresholded detections, before overlap resolution: a picture
2268        // that is the whole page goes (its text reads out as text), and a
2269        // figure proposed both whole and as sub-panels collapses to one box
2270        // (see `dedup_pictures`).
2271        assemble::drop_full_page_pictures(&mut regions, page.width, page.height);
2272        assemble::dedup_pictures(&mut regions);
2273        // Resolve overlapping detections once, before OCR.
2274        let mut regions = assemble::resolve(regions);
2275        // Emit text the detector missed as orphan text regions (docling parity).
2276        assemble::add_orphan_regions(&mut regions, &page.cells);
2277        // Drop phantom empty low-confidence picture boxes (docling parity).
2278        assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
2279        // A regular region fully inside a surviving table/index/picture is that
2280        // special's child (a cell / in-figure label), not a separate block —
2281        // remove it so it isn't emitted twice (docling parity).
2282        assemble::drop_contained_regulars(&mut regions);
2283        // A one-line paragraph in the bottom margin under a body-less heading
2284        // is that heading's text, not furniture (deliberate deviation).
2285        assemble::reclaim_heading_body_footers(&mut regions, page.width);
2286        // No text layer → recognise text from the page image via OCR.
2287        let ocred = page.cells.is_empty();
2288        // Lines the text detector found outside every layout region (#429).
2289        let mut det_cells: Vec<pdfium_backend::TextCell> = Vec::new();
2290        if ocred {
2291            // Region-scoped OCR recognizes each region's crop, so two regular
2292            // regions over the same ink would read it twice — a low-score
2293            // paragraph box over the high-score line boxes `greedy` keeps.
2294            // Collapse such groups to one region first; a digital
2295            // page resolves the same overlap through cell ownership in
2296            // `fit_regions_to_cells` and needs nothing here.
2297            assemble::merge_overlapping_regulars(&mut regions);
2298            // The text detector's lines (#429), fetched before the region
2299            // pass: with `det` line mode (#570, the default) they are the
2300            // recognizer's crops inside the regions too — RapidOCR's own line
2301            // source — not only the supplement outside them. Usually computed
2302            // already, alongside layout (see `detect_alongside`); a page that
2303            // reached OCR another way detects here. Degradation over failure:
2304            // a detector that loaded but cannot run (a damaged file, an
2305            // allocation failure) costs the page its detected lines, not its
2306            // conversion — the projection segmentation is complete on its own.
2307            let detected: Vec<ocr_det::DetBox> = if self.ocr_model()?.is_some() {
2308                let (img, _) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2309                match self.pending_det.remove(&n) {
2310                    Some(result) => result,
2311                    None => self
2312                        .with_det(|det| {
2313                            timing::timed("ocr.det", || {
2314                                det.detect_scan(img, ocr_scale.is_none() && page.scale != 1.0)
2315                            })
2316                        })
2317                        .unwrap_or(Ok(Vec::new())),
2318                }
2319                .unwrap_or_else(|e| {
2320                    docling_core::debug_log!(
2321                        "docling-pdf: page {}: text detection failed ({e}); keeping the \
2322                         region-scoped OCR only",
2323                        n + 1
2324                    );
2325                    Vec::new()
2326                })
2327            } else {
2328                Vec::new()
2329            };
2330            docling_core::debug_log!(
2331                "docling-pdf: page {}: text detector found {} line(s): {:?}",
2332                n + 1,
2333                detected.len(),
2334                detected
2335                    .iter()
2336                    .map(|d| (
2337                        d.l.round(),
2338                        d.t.round(),
2339                        d.r.round(),
2340                        d.b.round(),
2341                        (d.score * 100.0).round() / 100.0
2342                    ))
2343                    .collect::<Vec<_>>()
2344            );
2345            let det_lines =
2346                (ocr::det_lines() && !detected.is_empty()).then_some(detected.as_slice());
2347            // `None` = `skip_ocr` or a missing model (#244): the page keeps
2348            // its layout regions (and TableFormer structure below) with no
2349            // recognized text, instead of failing the conversion.
2350            if let Some(ocr) = self.ocr_model()? {
2351                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2352                let cells = timing::timed("ocr.page", || {
2353                    ocr.ocr_page_with(img, &regions, scl, det_lines)
2354                })
2355                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2356                ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
2357                ocr_cells.extend(cell_confs(&cells));
2358                page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
2359                // Table interiors carry no words yet: region-scoped OCR skips
2360                // table labels, and a scanned page has no pdfium text layer — so
2361                // TableFormer's cell matcher got an empty word list and the table
2362                // dissolved (#173). Recognize the table regions' word crops
2363                // (mirroring the browser scanned path): `word_cells` feeds the
2364                // matcher, and the same cells join `cells` so the geometric
2365                // fallback and the table's region text see them too.
2366                if regions.iter().any(|r| assemble::is_table_like(r.label)) {
2367                    let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2368                    let words = timing::timed("ocr.table_words", || {
2369                        ocr.ocr_table_words(img, &regions, scl, det_lines)
2370                    })
2371                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2372                    ocr_confs.extend(words.iter().map(|(_, conf)| conf));
2373                    ocr_cells.extend(cell_confs(&words));
2374                    let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
2375                    page.cells.extend(words.iter().cloned());
2376                    page.word_cells = words;
2377                }
2378            }
2379            // docling's OCR engines detect text lines over the whole bitmap
2380            // and every line becomes a cell, so text the layout model gave no
2381            // region — a diagram's labels, a stamp, a margin note — still
2382            // reads out as orphan text. Region-scoped recognition above stays
2383            // the source inside layout regions; the detector (#429) adds only
2384            // the lines no recognized cell already covers, and the orphan pass
2385            // below places them (those inside a kept picture or table become
2386            // that special's silent children, as upstream).
2387            if self.ocr_model()?.is_some() {
2388                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2389                let uncovered = ocr_det::uncovered_lines(&detected, scl, &regions, &page.cells);
2390                docling_core::debug_log!(
2391                    "docling-pdf: page {}: {} of {} detected line(s) not covered by the region pass",
2392                    n + 1,
2393                    uncovered.len(),
2394                    detected.len()
2395                );
2396                if let Some(ocr) = self.ocr_model_if(!uncovered.is_empty())? {
2397                    let scored =
2398                        timing::timed("ocr.det_lines", || ocr.ocr_page(img, &uncovered, scl))
2399                            .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2400                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
2401                    ocr_cells.extend(cell_confs(&scored));
2402                    det_cells = scored.into_iter().map(|(cell, _)| cell).collect();
2403                    page.cells.extend(det_cells.iter().cloned());
2404                }
2405            }
2406        } else {
2407            // A page with a text layer can still draw part of its text as
2408            // vector outlines (`gs -dNoOutputFonts`, flattened print PDFs):
2409            // the layout model finds the paragraph, the text layer holds
2410            // nothing there, and the region dropped empty — one native `Page
2411            // 1` footer was enough to switch the page's OCR off (#931).
2412            // docling's default `pdf_aware_layout_regions` OCRs every layout
2413            // cluster without any programmatic text in it
2414            // (`_find_pdf_aware_layout_ocr_rects`); do the same for the text,
2415            // furniture and table regions (pictures go through the bare-
2416            // picture pass below). Its other trigger, a cluster over a
2417            // bitmap, takes the regions a scan's image covers past a thin
2418            // text layer (#999, `bitmap_regions`).
2419            let mut empty = text_less_regions(&regions, &page.cells);
2420            empty.extend(bitmap_regions(&regions, &page.cells, &page.bitmaps));
2421            if !empty.is_empty() && self.ocr_model()?.is_some() {
2422                // A page with a text layer and no picture or table had its
2423                // bitmap declined (#897); render it now — rare, and only
2424                // for the page that needs it.
2425                page.resolve_image()?;
2426                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2427                // Detected on the empty regions' crops, not the page (#945):
2428                // the page at the 2000 px budget cost ~2.3 s and ~250 MB per
2429                // such page for a caption's worth of lines; a crop reads at
2430                // full render resolution for a fraction of it. A margin of
2431                // half a line keeps the DB net's context at the edges.
2432                let rects: Vec<(u32, u32, u32, u32)> = empty
2433                    .iter()
2434                    .map(|r| {
2435                        let m = (0.5 * (r.b - r.t)).clamp(4.0, 24.0) * scl;
2436                        (
2437                            ((r.l * scl - m).max(0.0)) as u32,
2438                            ((r.t * scl - m).max(0.0)) as u32,
2439                            (r.r * scl + m).ceil() as u32,
2440                            (r.b * scl + m).ceil() as u32,
2441                        )
2442                    })
2443                    .collect();
2444                let detected = self
2445                    .with_det(|det| timing::timed("ocr.det", || det.detect_regions(img, &rects)))
2446                    .unwrap_or(Ok(Vec::new()))
2447                    .unwrap_or_else(|e| {
2448                        docling_core::debug_log!(
2449                            "docling-pdf: page {}: text detection failed ({e}); keeping the \
2450                             region-scoped OCR only",
2451                            n + 1
2452                        );
2453                        Vec::new()
2454                    });
2455                let det_lines =
2456                    (ocr::det_lines() && !detected.is_empty()).then_some(detected.as_slice());
2457                let ocr = self.ocr_model()?.expect("checked above");
2458                // docling's merge for this mode (`PDF_FIRST`): every native
2459                // cell is kept, and an OCR cell only where it touches none —
2460                // a typed-in value over its own scanned pixels is read once.
2461                let native = page.cells.clone();
2462                let pdf_first = |cells: &mut Vec<(TextCell, f32)>| {
2463                    cells.retain(|(c, _)| table_tokens::uncovered([c], &native).len() == 1)
2464                };
2465                let mut scored = timing::timed("ocr.page", || {
2466                    ocr.ocr_page_with(img, &empty, scl, det_lines)
2467                })
2468                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2469                pdf_first(&mut scored);
2470                docling_core::debug_log!(
2471                    "docling-pdf: page {}: {} text-less layout region(s) OCR'd, {} line(s)",
2472                    n + 1,
2473                    empty.len(),
2474                    scored.len()
2475                );
2476                ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
2477                ocr_cells.extend(cell_confs(&scored));
2478                page.cells.extend(scored.into_iter().map(|(cell, _)| cell));
2479                if empty.iter().any(|r| assemble::is_table_like(r.label)) {
2480                    let mut words = timing::timed("ocr.table_words", || {
2481                        ocr.ocr_table_words(img, &empty, scl, det_lines)
2482                    })
2483                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2484                    pdf_first(&mut words);
2485                    ocr_confs.extend(words.iter().map(|(_, conf)| conf));
2486                    ocr_cells.extend(cell_confs(&words));
2487                    let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
2488                    page.cells.extend(words.iter().cloned());
2489                    // TableFormer's tokens (#999, docling's
2490                    // `_words_and_ocr_cells`): the native words beside the
2491                    // surviving OCR lines — the matcher saw the natives
2492                    // alone, and one typed-in value made the whole table.
2493                    page.word_cells =
2494                        table_tokens::words_and_ocr_cells(&page.word_cells, &[], &words);
2495                }
2496            }
2497        }
2498        // Region-scoped OCR skips `picture` interiors, and a digital page's
2499        // text layer cannot see into an embedded raster either — so a figure
2500        // that is really a text box (terms-and-conditions exported as an
2501        // image) lost its words on every page kind. Python docling OCRs the
2502        // bitmap-covered areas of *every* page — even digital ones — once they
2503        // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
2504        // already do. Recognize the big text-less crops here too; the panel
2505        // demotion / orphan recovery below place the lines.
2506        let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
2507        {
2508            let page_area = (page.width * page.height).max(1.0);
2509            let has_text = |r: &layout::Region| {
2510                page.cells.iter().any(|c| {
2511                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
2512                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
2513                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
2514                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
2515                })
2516            };
2517            // A captioned picture can never demote to a text panel (see
2518            // recover_text_panels), and on digital pages its speculative OCR
2519            // would be discarded anyway — don't pay for it.
2520            let captioned = |r: &layout::Region| {
2521                regions.iter().any(|c| {
2522                    c.label == "caption"
2523                        && c.r.min(r.r) - c.l.max(r.l) > 0.0
2524                        && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
2525                })
2526            };
2527            let bare: Vec<layout::Region> = regions
2528                .iter()
2529                .filter(|r| {
2530                    r.label == "picture"
2531                        && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
2532                        && !has_text(r)
2533                        && (ocred || !captioned(r))
2534                })
2535                .map(|r| layout::Region {
2536                    label: "text",
2537                    ..r.clone()
2538                })
2539                .collect();
2540            // Speculative OCR (#244): with `skip_ocr` or no model, big bare
2541            // pictures simply stay pictures.
2542            if let Some(ocr) = self.ocr_model_if(!bare.is_empty())? {
2543                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2544                let scored = timing::timed("ocr.pictures", || ocr.ocr_page(img, &bare, scl))
2545                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2546                // Speculative in-picture OCR counts toward ocr_score only on
2547                // OCR'd pages, where the recognized lines actually join the
2548                // output; on a digital page they may be discarded below.
2549                if ocred {
2550                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
2551                    ocr_cells.extend(cell_confs(&scored));
2552                }
2553                pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
2554                page.cells.extend(pic_cells.iter().cloned());
2555            }
2556        }
2557        let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
2558        // A "picture" that is really a colored text panel — dense, wide,
2559        // multi-line — reads out as paragraphs instead of shipping as pixels;
2560        // sparse in-picture text (a chart's labels) keeps the crop and stays
2561        // inside it as the picture's silent children (docling parity, #200).
2562        // `no_text_panels` (#173) opts out entirely for image-extraction
2563        // workflows.
2564        if !self.no_text_panels {
2565            assemble::recover_text_panels(&mut regions, &page.cells);
2566        }
2567        // On an OCR'd page, in-picture text that did NOT demote its picture
2568        // mostly stays silent, exactly as in docling: its postprocess step
2569        // "Remove regular clusters that are included in wrappers" walks
2570        // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
2571        // >80 % contained in a kept picture becomes that picture's child and
2572        // never reaches the serializer. Only border-straddlers (≤80 %
2573        // containment) survive as text. Emitting *everything* here used to
2574        // splice a chart's OCR'd axis ticks into the body text right next to
2575        // the image chunk (#200) — so the orphan pass places the recognized
2576        // lines, the containment drop re-runs for the in-table ones, and
2577        // `assemble_page` nests the in-picture ones under their picture
2578        // (JSON-only children, `assemble::picture_parents`).
2579        if ocred && (!pic_cells.is_empty() || !det_cells.is_empty()) {
2580            // Pictures (and wrappers) no longer count as claimers (#165), so
2581            // the plain orphan pass places the recognized lines directly —
2582            // the detector's lines (#429) the same way.
2583            assemble::add_orphan_regions(&mut regions, &pic_cells);
2584            assemble::add_orphan_regions(&mut regions, &det_cells);
2585            assemble::drop_contained_regulars(&mut regions);
2586        } else if !ocred && !pic_cells.is_empty() {
2587            // Digital page, picture kept: its speculative OCR cells must not
2588            // linger in the text-cell set (they were appended at the tail).
2589            let kept: Vec<layout::Region> = regions
2590                .iter()
2591                .filter(|r| r.label == "picture")
2592                .cloned()
2593                .collect();
2594            let tail = page.cells.split_off(cells_before_pic_ocr);
2595            page.cells.extend(tail.into_iter().filter(|c| {
2596                !kept.iter().any(|r| {
2597                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
2598                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
2599                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
2600                    ix * iy / ca > 0.5
2601                })
2602            }));
2603        }
2604        // `picture_ocr` (#1219): on a text-layer page, every picture that
2605        // stayed a picture is read — the small ones the 5 % threshold skips
2606        // (a seal, a stamp) and the big ones whose speculative lines were just
2607        // discarded (a photo's rating label) — and its lines become the
2608        // picture's description after assembly. Each is read on its own crop
2609        // with the detector's line boxes (`read_picture_region`), not reusing
2610        // the speculative pass's lines: those are the ink-projection strips a
2611        // text panel splits into, which read a label inside a photo as
2612        // nothing. The lines never join `page.cells`: the text layer and the
2613        // layout stay exactly as without the option, only the pictures gain
2614        // an annotation.
2615        let mut picture_text: Vec<pdfium_backend::TextCell> = Vec::new();
2616        if self.picture_ocr && !ocred {
2617            let todo: Vec<layout::Region> = regions
2618                .iter()
2619                .filter(|r| r.label == "picture")
2620                .cloned()
2621                .collect();
2622            for r in &todo {
2623                let cells = timing::timed("ocr.picture_text", || {
2624                    self.read_picture_region(page, r, ocr_scale)
2625                })
2626                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2627                picture_text.extend(cells);
2628            }
2629        }
2630        // A text-less *table* detected inside a picture on a digital page — a
2631        // screenshot of a table (2203's Figure 10) — has no text layer and no
2632        // scanned-path OCR to feed it, so its grid used to serialize empty and
2633        // the whole element vanished. docling OCRs bitmap-covered areas on
2634        // every page kind and its table cluster collects those cells; mirror
2635        // the scanned path for exactly these tables: recognize word crops and
2636        // feed them to the TableFormer matcher and the cell set.
2637        if !ocred {
2638            let has_text = |t: &layout::Region| {
2639                page.cells.iter().any(|c| {
2640                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
2641                    let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
2642                    let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
2643                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
2644                })
2645            };
2646            let in_picture = |t: &layout::Region| {
2647                regions.iter().any(|r| {
2648                    r.label == "picture" && {
2649                        let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
2650                        let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
2651                        let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
2652                        ix * iy / ta > 0.5
2653                    }
2654                })
2655            };
2656            let pic_tables: Vec<layout::Region> = regions
2657                .iter()
2658                .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
2659                .cloned()
2660                .collect();
2661            // Same degradation as above: without OCR the in-picture table
2662            // keeps its structure (TableFormer is geometry-driven) minus text.
2663            if let Some(ocr) = self.ocr_model_if(!pic_tables.is_empty())? {
2664                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2665                let words = timing::timed("ocr.table_words", || {
2666                    ocr.ocr_table_words(img, &pic_tables, scl, None)
2667                })
2668                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2669                ocr_confs.extend(words.iter().map(|(_, conf)| conf));
2670                ocr_cells.extend(cell_confs(&words));
2671                let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
2672                page.cells.extend(words.iter().cloned());
2673                page.word_cells.extend(words);
2674            }
2675        }
2676        // `do_table_structure=False`: OCR has already read any table crops.
2677        // `tables` is `None` only then on this path (`no_ocr` returns before
2678        // layout). A scan has no text layer, so dropping the region earlier
2679        // loses those words when the text detector is absent. docling emits
2680        // an empty table here; the words stay text. A missing TableFormer
2681        // model keeps `tables` as `Some` and still reconstructs.
2682        if self.tables.is_none() {
2683            assemble::release_unstructured_tables_after_ocr(&mut regions, &page.cells);
2684        }
2685        // The cells are final: fit every regular region to the cells it
2686        // claims and fold the orphans it now surrounds (#419), before
2687        // TableFormer and the reading order see the boxes.
2688        assemble::fit_regions_to_cells(&mut regions, &page.cells);
2689        Ok(Prepared {
2690            regions,
2691            ocr_confs,
2692            ocr_cells,
2693            parse,
2694            picture_text,
2695        })
2696    }
2697
2698    /// The stages after TableFormer: enrichment, the page confidence report and
2699    /// assembly into typed nodes.
2700    fn complete_page(
2701        &mut self,
2702        n: usize,
2703        page: &mut PdfPage,
2704        prepared: Prepared,
2705        table_rows: Vec<Option<tf_core::TableGrid>>,
2706    ) -> Result<PageOut, PdfError> {
2707        let Prepared {
2708            regions,
2709            ocr_confs,
2710            ocr_cells,
2711            parse,
2712            picture_text,
2713        } = prepared;
2714        // The crops and the page image below read the bitmap (#897).
2715        self.ensure_bitmap(page, &regions)?;
2716        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
2717            for (i, r) in regions.iter().enumerate() {
2718                eprintln!(
2719                    "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
2720                    r.label,
2721                    r.score,
2722                    r.l,
2723                    r.t,
2724                    r.r,
2725                    r.b,
2726                    table_rows[i]
2727                        .as_ref()
2728                        .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
2729                );
2730            }
2731            eprintln!(
2732                "DBG cells={} words={}",
2733                page.cells.len(),
2734                page.word_cells.len()
2735            );
2736        }
2737        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
2738        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
2739        // shape as TableFormer — one lazily-loaded instance per pipeline, only
2740        // ever locked when a page actually has a matching region.
2741        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
2742        if let Some(slot) = self.classifier.as_ref() {
2743            if regions.iter().any(|r| r.label == "picture") {
2744                timing::timed("picture_classifier", || {
2745                    let mut guard = slot.lock().unwrap();
2746                    if matches!(*guard, EnrichSlot::Unloaded) {
2747                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
2748                            Some(m) => EnrichSlot::Ready(m),
2749                            None => EnrichSlot::Missing,
2750                        };
2751                    }
2752                    if let EnrichSlot::Ready(model) = &mut *guard {
2753                        for (i, r) in regions.iter().enumerate() {
2754                            if r.label != "picture" {
2755                                continue;
2756                            }
2757                            let Some(crop) = assemble::crop_region_scaled(
2758                                page,
2759                                [r.l, r.t, r.r, r.b],
2760                                enrich::CLASSIFIER_SCALE,
2761                            ) else {
2762                                continue;
2763                            };
2764                            match model.classify(&crop) {
2765                                Ok(classes) => {
2766                                    enrich_out[i] =
2767                                        Some(assemble::Enrichment::PictureClasses(classes));
2768                                }
2769                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
2770                            }
2771                        }
2772                    }
2773                });
2774            }
2775        }
2776        if let Some(slot) = self.code_formula.as_ref() {
2777            let wants = |label: &str| {
2778                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
2779            };
2780            if regions.iter().any(|r| wants(r.label)) {
2781                timing::timed("code_formula", || {
2782                    let mut guard = slot.lock().unwrap();
2783                    if matches!(*guard, EnrichSlot::Unloaded) {
2784                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
2785                            Some(m) => EnrichSlot::Ready(m),
2786                            None => EnrichSlot::Missing,
2787                        };
2788                    }
2789                    if let EnrichSlot::Ready(model) = &mut *guard {
2790                        for (i, r) in regions.iter().enumerate() {
2791                            if !wants(r.label) {
2792                                continue;
2793                            }
2794                            // docling crops the postprocessed cluster box — the
2795                            // union of the region's text cells, not the raw
2796                            // detector box — expanded by 18% per side, at
2797                            // ~120 dpi.
2798                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
2799                                .unwrap_or([r.l, r.t, r.r, r.b]);
2800                            let (w, h) = (br - bl, bb - bt);
2801                            let ex = enrich::CODE_FORMULA_EXPANSION;
2802                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
2803                            let Some(crop) = assemble::crop_region_scaled(
2804                                page,
2805                                bbox,
2806                                enrich::CODE_FORMULA_SCALE,
2807                            ) else {
2808                                continue;
2809                            };
2810                            let kind = if r.label == "code" {
2811                                enrich::CodeFormulaKind::Code
2812                            } else {
2813                                enrich::CodeFormulaKind::Formula
2814                            };
2815                            match model.predict(&crop, kind) {
2816                                Ok(text) => {
2817                                    enrich_out[i] = Some(match kind {
2818                                        enrich::CodeFormulaKind::Code => {
2819                                            let (code, language) =
2820                                                enrich::extract_code_language(&text);
2821                                            assemble::Enrichment::Code {
2822                                                language,
2823                                                text: code,
2824                                            }
2825                                        }
2826                                        enrich::CodeFormulaKind::Formula => {
2827                                            assemble::Enrichment::Formula { latex: text }
2828                                        }
2829                                    });
2830                                }
2831                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
2832                            }
2833                        }
2834                    }
2835                });
2836            }
2837        }
2838        // Score the final region set (docling assigns layout_score over the
2839        // postprocessed clusters — the page elements assemble_page emits,
2840        // which leave out the regulars nested in a picture as its children).
2841        let parents = assemble::picture_parents(&regions);
2842        let elements: Vec<layout::Region> = regions
2843            .iter()
2844            .zip(&parents)
2845            .filter(|(_, p)| p.is_none())
2846            .map(|(r, _)| r.clone())
2847            .collect();
2848        let conf = quality::page_confidence(parse, &elements, &ocr_confs);
2849        let (mut nodes, links) = timing::timed("assemble_page", || {
2850            assemble::assemble_page(page, regions, &table_rows, &enrich_out, self.images.scale)
2851        });
2852        if !picture_text.is_empty() {
2853            let provenance = match self.ocr_engine {
2854                ocr::OcrEngine::PpOcr => "ppocr",
2855                ocr::OcrEngine::Tesseract => "tesseract",
2856            };
2857            picture::describe_pictures(&mut nodes, page, &picture_text, provenance);
2858        }
2859        Ok((nodes, links, conf, self.page_image(n, page), ocr_cells))
2860    }
2861}
2862
2863#[cfg(feature = "ml")]
2864/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
2865/// so on a typical machine two threads per worker (sharing one in-cache copy of
2866/// the weights) extracts more throughput than one fat model or many single-thread
2867/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
2868fn pdf_intra() -> usize {
2869    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
2870        return n;
2871    }
2872    if intra_threads() >= 2 {
2873        2
2874    } else {
2875        1
2876    }
2877}
2878
2879#[cfg(feature = "ml")]
2880/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
2881/// overrides; otherwise size the pool so `workers × intra ≈ cores`.
2882///
2883/// The pool scales with the machine (#324 follow-up testing): the old hard cap
2884/// of 4 left most of a many-core box idle — on a 16-core M4 Max, 10 workers
2885/// measured ~1.2× over the capped pool (10.0 → 8.5 s on a 130-page document,
2886/// byte-identical output). The ceiling of 16 is a memory bound, not a
2887/// performance one: each worker holds its own layout/OCR sessions (~0.4 GB),
2888/// so a worst-case pool stays under ~6.5 GB even on a ≥32-core host — and
2889/// docling-serve's per-request pools sit behind its `DOCLING_RS_MAX_MEMORY_MB`
2890/// admission control besides. Machines with 4 or fewer effective threads keep
2891/// the exact old sizing (`threads / intra`, min 1).
2892fn pdf_worker_count() -> usize {
2893    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
2894        return n;
2895    }
2896    // One GPU behind every worker (#842): the pool multiplies the sessions,
2897    // and on the device that is memory, not speed — the serial primary's
2898    // render-ahead already overlaps rasterization with inference.
2899    if docling_onnx::prefers_single_worker() {
2900        return 1;
2901    }
2902    (intra_threads() / pdf_intra()).clamp(1, 16)
2903}
2904
2905#[cfg(feature = "ml")]
2906/// Max pages a worker layout-detects with one batched inference call (issue
2907/// #73). Workers drain the work channel opportunistically up to this size —
2908/// whatever is already rendered gets batched, so batching never *waits* for
2909/// pages and adds no latency when rendering is the bottleneck.
2910///
2911/// Default: per-page (1) on the CPU provider, 4 when a CUDA-class GPU
2912/// provider is selected (#338) — CoreML stays per-page (#602,
2913/// [`docling_onnx::prefers_batching`]): only the pinned batch=1 graph is
2914/// static, and static partitions are all CoreML is allowed to take. The old
2915/// "4 on 8+ cores" CPU default was a hypothesis — that single-session
2916/// amortization pays off with a wider thread budget —
2917/// and every actual CPU measurement lands the other way: a 4-core x86 box
2918/// runs the 9-page 2206.01062 fixture in 8.5 s/conv at batch=1 vs 9.3 s at
2919/// batch=4 (re-measured for #338; the original 8.1 vs 9.3 agrees), and the
2920/// issue-#338 report measured batch=1 ~2× faster on a 16-core M4 Max at
2921/// every worker count — batching only adds cache pressure once workers
2922/// saturate the cores. On a GPU the per-call dispatch overhead is real and
2923/// batching amortizes it, so the GPU default stays. Output is bit-identical
2924/// at every batch size, so this is purely a throughput knob.
2925/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides either way; `1` = per-page.
2926pub(crate) fn pdf_layout_batch() -> usize {
2927    env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
2928        .filter(|&n| n > 0)
2929        .unwrap_or_else(|| {
2930            if docling_onnx::prefers_batching() {
2931                4
2932            } else {
2933                1
2934            }
2935        })
2936}
2937
2938#[cfg(feature = "ml")]
2939/// Pages the serial path renders ahead of the one being processed
2940/// ([`Pipeline::render_ahead`], #682): one in flight on the worker, two
2941/// rendered and waiting — a bound on resident page bitmaps, like the
2942/// pool's channel.
2943const RENDER_AHEAD: usize = 2;
2944
2945#[cfg(feature = "ml")]
2946/// Minimum page count before a PDF goes to the parallel worker pool; below
2947/// it the serial primary runs its model on every core. Four since #682 (was
2948/// six, from the days of the pool's uncached model load): the layout model's
2949/// intra-op scaling is weak (on a 4-core x86 box 4 threads run a page 2.35×
2950/// faster than one, 2 threads 1.6×), so two workers of two threads convert
2951/// pages faster than one worker of four converts them in turn — 4–5-page
2952/// digital documents measured 18% faster than the serial path with its
2953/// render-ahead, the pool's load included (the pool is sized to the page
2954/// count, [`Pipeline::ensure_pool_for`]). Not lower: the text detector a
2955/// scanned page needs scales well with threads, so a 2–3-page scan runs
2956/// 15–20% *slower* split across two-thread workers than on the four-thread
2957/// primary. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
2958fn pdf_parallel_min() -> usize {
2959    env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
2960        .filter(|&n| n > 0)
2961        .unwrap_or(4)
2962}
2963
2964#[cfg(feature = "ml")]
2965/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
2966/// so a single-page / small / image / METS input is converted at full intra-op
2967/// speed with no pool to load. A document with enough pages instead fans out
2968/// across a **pool** of narrower workers processed concurrently. Both load lazily
2969/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
2970pub struct Pipeline {
2971    /// Full-intra worker for the serial path; loaded on first serial use.
2972    primary: Option<Worker>,
2973    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
2974    /// path; loaded on first multi-page use and cached.
2975    pool: Vec<Worker>,
2976    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
2977    tables: SharedTables,
2978    /// The pool-wide text detector slot (#945), see [`DetSlot`].
2979    det: SharedDet,
2980    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
2981    classifier: SharedClassifier,
2982    code_formula: SharedCodeFormula,
2983    /// Desired pool size for multi-page documents.
2984    target_workers: usize,
2985    /// Page count at/above which the parallel pool is worth its load cost.
2986    parallel_min: usize,
2987    /// Skip loading/running TableFormer; table regions fall back to geometric
2988    /// reconstruction. See [`Pipeline::no_table_former`].
2989    no_table_former: bool,
2990    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
2991    no_ocr: bool,
2992    /// Per document: the text layer alone when it carries the text, the
2993    /// full pipeline otherwise. See [`Pipeline::text_layer_auto`].
2994    text_layer_auto: bool,
2995    /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
2996    skip_ocr: bool,
2997    /// OCR every page even when it carries a text layer. See
2998    /// [`Pipeline::force_full_page_ocr`].
2999    force_full_page_ocr: bool,
3000    /// OCR only the pages whose text layer is broken (#1006). See
3001    /// [`Pipeline::replace_broken_text_layer`].
3002    replace_broken_text_layer: bool,
3003    /// Read the pictures of a text-layer page (#1219). See
3004    /// [`Pipeline::picture_ocr`].
3005    picture_ocr: bool,
3006    /// Mark superscripts and subscripts (#1005). See
3007    /// [`Pipeline::script_positions`].
3008    script_positions: bool,
3009    /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
3010    no_text_panels: bool,
3011    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
3012    enrich: EnrichmentOptions,
3013    /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
3014    page_range: Option<(usize, usize)>,
3015    /// OCR recognition language. See [`Pipeline::ocr_lang`].
3016    ocr_lang: ocr::OcrLang,
3017    /// Which OCR engine runs (#460). See [`Pipeline::ocr_engine`].
3018    ocr_engine: ocr::OcrEngine,
3019    /// Tesseract's languages (#460). See [`Pipeline::tesseract_lang`].
3020    tesseract_lang: Option<String>,
3021    /// Which regions feed the OCR (#254). See [`Pipeline::ocr_mode`].
3022    ocr_mode: ocr::OcrMode,
3023    /// OCR render scale override in px/pt (#254). See [`Pipeline::ocr_scale`].
3024    ocr_scale: Option<f32>,
3025    /// Picture OCR scale (#666). See [`Pipeline::picture_ocr_scale`].
3026    picture_ocr_scale: Option<f32>,
3027    /// The text layer's word-gap rule (#921); `None` = the environment's
3028    /// (`DOCLING_RS_PDF_WORD_GAP`), else [`WordGap::Adaptive`].
3029    word_gap: Option<WordGap>,
3030    /// Keep typographic punctuation as drawn (#921); `None` = the
3031    /// environment's (`DOCLING_RS_PDF_KEEP_TYPOGRAPHY`), else folding.
3032    keep_typography: Option<bool>,
3033    /// RapidOCR's line orientation handling (#666). See
3034    /// [`Pipeline::ocr_textline_orientation`].
3035    textline_orientation: bool,
3036    /// Picture-crop scale and page images (#519/#520). See
3037    /// [`Pipeline::images_scale`] / [`Pipeline::generate_page_images`].
3038    images: ImageOutput,
3039    /// Heading-level inference (#302). See [`Pipeline::heading_hierarchy`].
3040    heading_hierarchy: HeadingHierarchyOptions,
3041    /// Optional per-page progress hook, invoked after each page finishes on
3042    /// every walk — the serial and parallel buffered paths, both streaming
3043    /// paths and the pre-rendered page path (images, METS). The converter
3044    /// turns it into its progress events (#783); `None` costs nothing.
3045    progress: Option<PageProgressHook>,
3046    /// Per-document wall-clock budget (docling's `document_timeout`, #497).
3047    /// See [`Pipeline::document_timeout`].
3048    document_timeout: Option<std::time::Duration>,
3049}
3050
3051#[cfg(feature = "ml")]
3052impl Pipeline {
3053    /// Construct the pipeline. Models load lazily on first use (full-intra primary
3054    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
3055    /// loaded that a given document doesn't need.
3056    pub fn new() -> Result<Self, PdfError> {
3057        Ok(Self {
3058            primary: None,
3059            pool: Vec::new(),
3060            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
3061            det: Arc::new(Mutex::new(DetSlot::Unloaded)),
3062            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
3063            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
3064            target_workers: pdf_worker_count(),
3065            parallel_min: pdf_parallel_min(),
3066            no_table_former: false,
3067            no_ocr: false,
3068            text_layer_auto: false,
3069            skip_ocr: false,
3070            force_full_page_ocr: false,
3071            replace_broken_text_layer: false,
3072            picture_ocr: false,
3073            script_positions: false,
3074            no_text_panels: false,
3075            enrich: EnrichmentOptions::default(),
3076            page_range: None,
3077            ocr_lang: ocr::OcrLang::from_env(),
3078            ocr_engine: ocr::OcrEngine::from_env(),
3079            tesseract_lang: None,
3080            ocr_mode: ocr::OcrMode::from_env(),
3081            ocr_scale: ocr::scale_from_env(),
3082            picture_ocr_scale: ocr::picture_scale_from_env(),
3083            word_gap: None,
3084            keep_typography: None,
3085            textline_orientation: ocr::textline_orientation_from_env(),
3086            images: ImageOutput::default(),
3087            heading_hierarchy: HeadingHierarchyOptions::default(),
3088            progress: None,
3089            document_timeout: None,
3090        })
3091    }
3092
3093    /// A wall-clock budget for each document (docling's
3094    /// `PipelineOptions.document_timeout`, #497; `None` = unlimited, the
3095    /// default). The budget starts when a conversion starts and is checked
3096    /// cooperatively between pages: once it is spent, no further page is
3097    /// rendered or processed, the pages already finished are assembled into
3098    /// the document, and the outcome says so (`Completion::TimedOut`, which
3099    /// the converter reports as `PartialSuccess` with a timeout error, the
3100    /// way docling does). A page in flight finishes — the check costs
3101    /// nothing inside a page, and a single-page document (an image) is never
3102    /// cut. For a long-lived pipeline use
3103    /// [`set_document_timeout`](Self::set_document_timeout) before each
3104    /// conversion.
3105    pub fn document_timeout(mut self, timeout: Option<std::time::Duration>) -> Self {
3106        self.document_timeout = timeout;
3107        self
3108    }
3109
3110    /// In-place variant of [`document_timeout`](Self::document_timeout) for a
3111    /// warm pipeline — set it before every conversion so no request inherits
3112    /// a previous one's budget.
3113    pub fn set_document_timeout(&mut self, timeout: Option<std::time::Duration>) {
3114        self.document_timeout = timeout;
3115    }
3116
3117    /// The deadline of a conversion starting now, from the configured budget.
3118    fn deadline(&self) -> Option<std::time::Instant> {
3119        self.document_timeout.map(|t| std::time::Instant::now() + t)
3120    }
3121
3122    /// The [`Completion`] of a walk that processed `done` of `selected` pages.
3123    fn completion(&self, timed_out: bool, done: usize, selected: usize) -> Completion {
3124        match (timed_out, self.document_timeout) {
3125            (true, Some(budget)) => Completion::TimedOut {
3126                pages_done: done,
3127                pages_selected: selected,
3128                budget,
3129            },
3130            _ => Completion::Complete,
3131        }
3132    }
3133
3134    /// Infer section-header levels after assembly (#302, docling's
3135    /// `HeadingHierarchyModel`): PDF bookmarks > legal/outline numbering >
3136    /// font style, off by default — see [`HeadingHierarchyOptions`]. Pure
3137    /// post-processing configuration; for a warm pipeline use
3138    /// [`set_heading_hierarchy`](Self::set_heading_hierarchy).
3139    pub fn heading_hierarchy(mut self, opts: HeadingHierarchyOptions) -> Self {
3140        self.heading_hierarchy = opts;
3141        self
3142    }
3143
3144    /// In-place variant of [`heading_hierarchy`](Self::heading_hierarchy) for
3145    /// a long-lived pipeline (docling-serve's warm instance) — like
3146    /// [`set_pages`](Self::set_pages), set it before every conversion so no
3147    /// request inherits a previous one's choice.
3148    pub fn set_heading_hierarchy(&mut self, opts: HeadingHierarchyOptions) {
3149        self.heading_hierarchy = opts;
3150    }
3151
3152    /// Run the enabled heading-hierarchy stage (#302) on an assembled
3153    /// document: gather the outline (bookmarks) and the per-page glyph styles
3154    /// on demand, then assign levels in place. `bytes` is `None` on paths
3155    /// with no PDF behind them (standalone images, METS) — those degrade to
3156    /// the numbering signal, exactly like docling without parsed pages.
3157    fn apply_heading_hierarchy(&self, nodes: &mut [Node], bytes: Option<&[u8]>) {
3158        let opts = &self.heading_hierarchy;
3159        if !opts.enabled {
3160            return;
3161        }
3162        let outline = match bytes {
3163            Some(bytes) if opts.use_bookmarks => outline::extract_outline(bytes),
3164            _ => Vec::new(),
3165        };
3166        let styles = match bytes {
3167            Some(bytes) if opts.use_style => {
3168                let pages = heading_hierarchy::heading_pages(nodes);
3169                textparse::glyph_styles(bytes, &pages)
3170            }
3171            _ => Default::default(),
3172        };
3173        heading_hierarchy::apply(nodes, &outline, &styles, opts);
3174    }
3175
3176    /// Run the opt-in script-position stage (#1005) on an assembled
3177    /// document, after the heading hierarchy as docling runs it.
3178    fn apply_script_positions(&self, nodes: &mut [Node], bytes: &[u8]) {
3179        if self.script_positions {
3180            timing::timed("script_position", || script_position::apply(nodes, bytes));
3181        }
3182    }
3183
3184    /// Mark superscript and subscript text — docling's
3185    /// `script_position_options.enabled` (docling#4815, #1005). Characters
3186    /// drawn smaller than their line and raised or lowered against it
3187    /// (footnote markers, `1st`, `mc²`, `H₂O`) become runs with
3188    /// `formatting.script`: a paragraph or footnote holding them keeps its
3189    /// place, and its text moves into an inline group of the runs in the
3190    /// JSON (HTML `<sup>`/`<sub>`, DocLang `<superscript>`/`<subscript>`);
3191    /// Markdown joins the runs as docling does (`E = mc2 in 1905.`, where the
3192    /// plain text layer reads `E = mc 2 in 1905.`). Headings, captions,
3193    /// tables, code, formulas, list items, OCR'd and invisible text are left
3194    /// alone. Off by default: the output is unchanged.
3195    pub fn script_positions(mut self, enable: bool) -> Self {
3196        self.set_script_positions(enable);
3197        self
3198    }
3199
3200    /// In-place variant of [`script_positions`](Self::script_positions).
3201    pub fn set_script_positions(&mut self, enable: bool) {
3202        self.script_positions = enable;
3203    }
3204
3205    /// Install (or clear) the per-page progress hook: called with a
3206    /// [`PageProgress`] after each page completes, on every conversion entry
3207    /// point ([`convert`](Self::convert), the streaming variants,
3208    /// [`convert_image`](Self::convert_image), [`process_pages`](Self::process_pages)).
3209    /// Shared with the parallel workers, so the callback must be cheap and
3210    /// thread-safe. A page the budget cut off is never reported here — the
3211    /// walk's [`Completion`] says how many were; the converter reports those
3212    /// as failed pages (#783).
3213    pub fn set_progress(&mut self, cb: Option<PageProgressHook>) {
3214        self.progress = cb;
3215    }
3216
3217    /// Convert only pages `first..=last` (**1-based**, like the page numbers a
3218    /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
3219    /// skipped before rasterization, so the cost is proportional to the window,
3220    /// not the document. `last` past the end of the document clamps; a window
3221    /// that selects no pages at all (`first` beyond the last page) is an error
3222    /// at convert time. `None` (the default) converts everything.
3223    pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
3224        self.page_range = range;
3225        self
3226    }
3227
3228    /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
3229    /// (e.g. docling-serve's warm instance) that applies a per-request window
3230    /// without rebuilding — unlike the model switches, the window is pure
3231    /// configuration. Set it before every conversion; it stays until changed.
3232    pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
3233        self.page_range = range;
3234    }
3235
3236    /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
3237    /// for the multilingual docling-conformance model. `None` keeps the
3238    /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
3239    /// first conversion; for a warm pipeline use
3240    /// [`set_ocr_lang`](Self::set_ocr_lang).
3241    pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
3242        self.set_ocr_lang(lang);
3243        self
3244    }
3245
3246    /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
3247    /// pipeline (docling-serve's warm instance). Unlike the page window this
3248    /// is a *model* switch: any worker whose cached recognition model was
3249    /// loaded for a different language drops it, to be lazily reloaded on the
3250    /// next OCR-needing page (cheap — the rec models are ~10 MB).
3251    pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
3252        let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
3253        self.ocr_lang = lang;
3254        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3255            if worker.ocr_lang != lang {
3256                worker.ocr_lang = lang;
3257                worker.ocr = OcrSlot::Unloaded;
3258            }
3259        }
3260    }
3261
3262    /// Which OCR engine recognizes text (#460, see [`OcrEngine`]): the
3263    /// built-in PP-OCRv3 recognizer by default, or the system `tesseract`
3264    /// binary (docling's `TesseractCliOcrOptions`) — same layout-region
3265    /// crops, same cells; Tesseract does its own line/word segmentation and
3266    /// reads orientation from its OSD. `None` keeps the process default
3267    /// (`DOCLING_RS_OCR_ENGINE`, else PP-OCR). Set before the first
3268    /// conversion; for a warm pipeline use
3269    /// [`set_ocr_engine`](Self::set_ocr_engine).
3270    pub fn ocr_engine(mut self, engine: Option<ocr::OcrEngine>) -> Self {
3271        self.set_ocr_engine(engine);
3272        self
3273    }
3274
3275    /// In-place variant of [`ocr_engine`](Self::ocr_engine): a model switch
3276    /// like [`set_ocr_lang`](Self::set_ocr_lang) — workers holding the other
3277    /// engine drop it, to be lazily reloaded.
3278    pub fn set_ocr_engine(&mut self, engine: Option<ocr::OcrEngine>) {
3279        let engine = engine.unwrap_or_else(ocr::OcrEngine::from_env);
3280        self.ocr_engine = engine;
3281        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3282            if worker.ocr_engine != engine {
3283                worker.ocr_engine = engine;
3284                worker.ocr = OcrSlot::Unloaded;
3285            }
3286        }
3287    }
3288
3289    /// What the OCR requests of the conversions since the last call met
3290    /// (#1210), and clear it: `None` when nothing asked for OCR (a digital
3291    /// PDF, `skip_ocr`, `no_ocr`), [`OcrStatus::Available`] when the engine
3292    /// read every request, [`OcrStatus::Unavailable`] — with the load error
3293    /// — when one went without it because the engine could not load (the
3294    /// #244 degradation: the conversion succeeds, the text OCR would have
3295    /// read is missing). A caller reads it after each conversion; a warm
3296    /// pipeline's caller also once before, to drop what an earlier
3297    /// conversion that failed half-way left behind.
3298    ///
3299    /// [`OcrStatus::Available`]: docling_core::OcrStatus::Available
3300    /// [`OcrStatus::Unavailable`]: docling_core::OcrStatus::Unavailable
3301    pub fn take_ocr_status(&mut self) -> Option<docling_core::OcrStatus> {
3302        self.primary
3303            .iter_mut()
3304            .chain(self.pool.iter_mut())
3305            .fold(None, |acc, worker| {
3306                docling_core::OcrStatus::merge_opt(acc, worker.ocr_status.take())
3307            })
3308    }
3309
3310    /// Tesseract's languages (#460): the `-l` argument, tessdata stems joined
3311    /// with `+` — build it from an `ocr_lang` value with
3312    /// [`tesseract_lang_arg`], which also maps BCP-47 tags and the PP-OCR
3313    /// codes. `None` runs Tesseract's default (`eng`). Ignored under the
3314    /// PP-OCR engine, whose language is [`ocr_lang`](Self::ocr_lang). For a
3315    /// warm pipeline use [`set_tesseract_lang`](Self::set_tesseract_lang).
3316    pub fn tesseract_lang(mut self, lang: Option<String>) -> Self {
3317        self.set_tesseract_lang(lang);
3318        self
3319    }
3320
3321    /// In-place variant of [`tesseract_lang`](Self::tesseract_lang): a model
3322    /// switch like [`set_ocr_lang`](Self::set_ocr_lang) — a worker whose
3323    /// Tesseract was probed for other languages drops it.
3324    pub fn set_tesseract_lang(&mut self, lang: Option<String>) {
3325        self.tesseract_lang = lang.clone();
3326        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3327            if worker.tesseract_lang != lang {
3328                worker.tesseract_lang = lang.clone();
3329                if worker.ocr_engine == ocr::OcrEngine::Tesseract {
3330                    worker.ocr = OcrSlot::Unloaded;
3331                }
3332            }
3333        }
3334    }
3335
3336    /// Resolve the configured 1-based window against a page count into the
3337    /// 0-based inclusive form the backend walks, validating it selects at
3338    /// least one existing page.
3339    fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
3340        let Some((first, last)) = self.page_range else {
3341            return Ok(None);
3342        };
3343        if first == 0 || last < first {
3344            return Err(PdfError::Pdfium(format!(
3345                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
3346            )));
3347        }
3348        if first > total {
3349            return Err(PdfError::Pdfium(format!(
3350                "page range {first}-{last} is outside the document ({total} page(s))"
3351            )));
3352        }
3353        Ok(Some((first - 1, last.min(total) - 1)))
3354    }
3355
3356    /// Enable the opt-in enrichment passes (docling's
3357    /// `do_picture_classification` / `do_code_enrichment` /
3358    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
3359    /// the first matching region; a missing model warns once and is skipped.
3360    /// Set before the first conversion (no effect on already-loaded workers).
3361    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
3362        self.enrich = opts;
3363        self
3364    }
3365
3366    /// Skip table structure — docling's `do_table_structure=False`
3367    /// (`--no-tables`). Layout still runs. docling 2.150 still emits an
3368    /// empty table for that region (`text=""`, no cells). This port drops
3369    /// it after OCR and keeps the words as text items, each with its own
3370    /// box. The geometric grid is the other case, when TableFormer was
3371    /// requested and its model files are missing.
3372    /// No effect if a worker is already loaded; set this before the first
3373    /// conversion.
3374    pub fn no_table_former(mut self, disable: bool) -> Self {
3375        self.no_table_former = disable;
3376        self
3377    }
3378
3379    /// Keep every detected `picture` region as a picture. By default an
3380    /// *uncaptioned* picture that reads like a dense, uniform text panel (a
3381    /// terms-and-conditions box exported as an image) is demoted into
3382    /// paragraphs (#157); a chart the layout mislabels can still trip that
3383    /// heuristic on scanned pages, and image-extraction workflows may simply
3384    /// want every crop — this flag disables the demotion entirely (#173).
3385    /// No effect on already-loaded workers; set before the first conversion.
3386    pub fn no_text_panels(mut self, disable: bool) -> Self {
3387        self.no_text_panels = disable;
3388        self
3389    }
3390
3391    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
3392    /// inference of any kind. The PDF's embedded text cells are grouped by line
3393    /// and emitted as plain paragraphs in reading order: no headings, lists,
3394    /// tables, code blocks, or pictures, since that structure comes from the
3395    /// layout model. The fastest possible PDF path, but pages with no embedded
3396    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
3397    /// without this flag. Implies `no_table_former`. A PDF conversion reads
3398    /// the flag per call (its pages never touch a worker); image and METS
3399    /// pages read the flag the workers were loaded with, so set it before
3400    /// the first conversion for those.
3401    pub fn no_ocr(mut self, disable: bool) -> Self {
3402        self.no_ocr = disable;
3403        self
3404    }
3405
3406    /// Decide per document between the two: a PDF whose embedded text layer
3407    /// carries its text converts as under [`no_ocr`](Self::no_ocr) — the
3408    /// text layer alone, flat paragraphs, no model loaded, no inference —
3409    /// and one without a usable layer (scanned / image-only, or a vestigial
3410    /// layer of a few typed-in form fields; [`text_layer_has_text`]) runs the
3411    /// full pipeline, which OCRs its pages. The verdict is the document's,
3412    /// not a page's: a digital file with a few scanned pages inserted keeps
3413    /// the text path, and those pages come back empty as under `no_ocr`.
3414    /// `no_ocr` wins when both are set; forcing (`force_full_page_ocr`,
3415    /// `ocr_mode`) is read only on the pipeline side of the verdict, as
3416    /// under `no_ocr`. A per-conversion setting: the workers and their
3417    /// models are untouched, so a warm pipeline serving digital and scanned
3418    /// documents in turn reloads nothing.
3419    pub fn text_layer_auto(mut self, enable: bool) -> Self {
3420        self.text_layer_auto = enable;
3421        self
3422    }
3423
3424    /// Set [`text_layer_auto`](Self::text_layer_auto) on a built pipeline.
3425    pub fn set_text_layer_auto(&mut self, enable: bool) {
3426        self.text_layer_auto = enable;
3427    }
3428
3429    /// Never run OCR, but keep layout detection and TableFormer — docling's
3430    /// independent `do_ocr=False` (#244), the counterpart of
3431    /// [`no_table_former`](Self::no_table_former). Unlike
3432    /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
3433    /// output — headings, tables, pictures, reading order — is preserved;
3434    /// only text that exists solely as pixels is lost: scanned pages come
3435    /// back with their regions empty, and the speculative OCR of large
3436    /// embedded images never runs. The OCR model is never loaded. Ignored
3437    /// when `no_ocr` is set (there is no OCR to skip);
3438    /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
3439    /// mirroring docling where forcing is a sub-option of `do_ocr`.
3440    pub fn skip_ocr(mut self, disable: bool) -> Self {
3441        self.skip_ocr = disable;
3442        self
3443    }
3444
3445    /// OCR every page from its rendered image even when the page carries an
3446    /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
3447    /// for text layers that exist but lie: broken encodings, subset fonts with
3448    /// garbage mappings, a scanned form with a few typed-in fields. Ignored
3449    /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
3450    /// `force_full_page_ocr` is a sub-option of `do_ocr`).
3451    pub fn force_full_page_ocr(mut self, force: bool) -> Self {
3452        self.force_full_page_ocr = force;
3453        self
3454    }
3455
3456    /// Which document regions feed the OCR — docling's `OcrMode` (#254). The
3457    /// default (`default` = `pdf_aware_layout_regions`) is the standard
3458    /// text-layer-aware behavior; `full_page`/`layout_regions` discard the
3459    /// text layer like [`force_full_page_ocr`](Self::force_full_page_ocr)
3460    /// (see [`ocr::OcrMode`] for why both map onto it). Whichever of the flag
3461    /// and the mode demands forcing wins, mirroring docling's
3462    /// `force_full_page_ocr` → `mode=full_page` bridge. `None` keeps the
3463    /// process default (`DOCLING_RS_OCR_MODE`, else `default`).
3464    pub fn ocr_mode(mut self, mode: Option<ocr::OcrMode>) -> Self {
3465        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
3466        self
3467    }
3468
3469    /// In-place variants of [`force_full_page_ocr`](Self::force_full_page_ocr),
3470    /// [`ocr_mode`](Self::ocr_mode) and [`ocr_scale`](Self::ocr_scale) for a
3471    /// long-lived pipeline (docling-serve's warm instance): all three are pure
3472    /// per-worker configuration — no model reloads — so they apply per request
3473    /// like [`set_pages`](Self::set_pages). Set them before every conversion so
3474    /// no request inherits a previous one's choice.
3475    pub fn set_force_full_page_ocr(&mut self, force: bool) {
3476        self.force_full_page_ocr = force;
3477        self.sync_ocr_config();
3478    }
3479
3480    /// Replace a broken PDF text layer with OCR, page by page — docling's
3481    /// `replace_broken_text_layer` (docling#4654, #1006). A page whose text
3482    /// layer [`quality::is_broken_text_layer`] judges broken — control,
3483    /// U+FFFD or private-use characters on the page or in many of its
3484    /// lines, Latin letters that stand for another script, too few vowels —
3485    /// is read with full-page OCR, its `parse_score` set to 0; every other
3486    /// page, and a page without a text layer, keeps the usual behavior. A
3487    /// low `parse_score` alone never replaces a page. Off by default;
3488    /// ignored under [`no_ocr`](Self::no_ocr) / [`skip_ocr`](Self::skip_ocr)
3489    /// (a sub-option of docling's `do_ocr`) and moot under
3490    /// [`force_full_page_ocr`](Self::force_full_page_ocr). Pure per-worker
3491    /// configuration, like the forcing flag.
3492    pub fn replace_broken_text_layer(mut self, replace: bool) -> Self {
3493        self.set_replace_broken_text_layer(replace);
3494        self
3495    }
3496
3497    /// In-place variant of
3498    /// [`replace_broken_text_layer`](Self::replace_broken_text_layer).
3499    pub fn set_replace_broken_text_layer(&mut self, replace: bool) {
3500        self.replace_broken_text_layer = replace;
3501        self.sync_ocr_config();
3502    }
3503
3504    /// Read the text inside the pictures of a page that has a text layer
3505    /// (#1219) — the PDF side of `do_picture_ocr`. By default such a page
3506    /// OCRs only the bare pictures that cover ≥ 5 % of it (docling's
3507    /// `bitmap_area_threshold`) and keeps their lines only when the
3508    /// picture demotes to a text panel; a seal, a stamp or a photo's
3509    /// rating label keeps no text at all. With this on, every picture that
3510    /// stays a picture is OCR'd on its own crop, with the text detector's
3511    /// line boxes when `ocr_det.onnx` is installed, and its lines land on it as docling's `description`
3512    /// annotation (`provenance` = the OCR engine), where the picture OCR of
3513    /// the other formats puts them — Markdown prints it under the caption,
3514    /// JSON writes `meta.description`. Docling instead nests the OCR cells
3515    /// under the picture as children, which Markdown prints only with
3516    /// `traverse_pictures`; the annotation keeps one shape for every
3517    /// format. Scanned pages are unchanged — the page OCR reads their
3518    /// pictures already. Off by default: same output, same time. Ignored
3519    /// under [`no_ocr`](Self::no_ocr) / [`skip_ocr`](Self::skip_ocr).
3520    pub fn picture_ocr(mut self, enable: bool) -> Self {
3521        self.set_picture_ocr(enable);
3522        self
3523    }
3524
3525    /// In-place variant of [`picture_ocr`](Self::picture_ocr).
3526    pub fn set_picture_ocr(&mut self, enable: bool) {
3527        self.picture_ocr = enable;
3528        self.sync_ocr_config();
3529    }
3530
3531    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
3532    pub fn set_ocr_mode(&mut self, mode: Option<ocr::OcrMode>) {
3533        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
3534        self.sync_ocr_config();
3535    }
3536
3537    /// How the text layer splits words where the PDF draws no space glyph
3538    /// (#921): docling-parse ≥ 7's line-local [`WordGap::Adaptive`]
3539    /// threshold (the default), a fixed [`WordGap::Factor`] of the two
3540    /// flanking glyphs' mean advance, or [`WordGap::Legacy`] (docling-parse
3541    /// ≤ 6's running-mean rule). `None` keeps `DOCLING_RS_PDF_WORD_GAP`,
3542    /// else the default.
3543    pub fn set_word_gap(&mut self, gap: Option<WordGap>) {
3544        self.word_gap = gap;
3545    }
3546
3547    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
3548    pub fn set_ocr_scale(&mut self, scale: Option<f32>) {
3549        self.ocr_scale = scale
3550            .filter(|s| s.is_finite() && *s > 0.0)
3551            .or_else(ocr::scale_from_env);
3552        self.sync_ocr_config();
3553    }
3554
3555    /// Resolution of the picture-OCR enrichment (#645) in pixels per
3556    /// picture pixel, before RapidOCR's 2000 px longer-side cap (#666) —
3557    /// RapidOCR reads a picture at its native pixels (`1.0`) and only
3558    /// shrinks what exceeds 2000 px. `None` (default:
3559    /// `DOCLING_RS_PICTURE_OCR_SCALE`, else unset) keeps the image-input
3560    /// rule pictures shared with scanned images: [`ocr_scale`](Self::ocr_scale)
3561    /// when set, else 3 px/pt shrunk to the 2000 px cap — which upscales a
3562    /// 720 × 180 screenshot to 2000 × 500. Pages and image inputs are
3563    /// unaffected. Non-positive values are ignored.
3564    pub fn picture_ocr_scale(mut self, scale: Option<f32>) -> Self {
3565        self.set_picture_ocr_scale(scale);
3566        self
3567    }
3568
3569    /// In-place [`picture_ocr_scale`](Self::picture_ocr_scale) for a warm
3570    /// pipeline.
3571    pub fn set_picture_ocr_scale(&mut self, scale: Option<f32>) {
3572        self.picture_ocr_scale = scale
3573            .filter(|s| s.is_finite() && *s > 0.0)
3574            .or_else(ocr::picture_scale_from_env);
3575    }
3576
3577    /// RapidOCR's handling of text-line orientation (#666), off by default
3578    /// (`DOCLING_RS_OCR_TEXTLINE_ORIENTATION` sets the process default): each
3579    /// detected line is cropped along the detector's rotated rectangle (a
3580    /// perspective warp, `get_rotate_crop_image`) instead of its axis-aligned
3581    /// box, a crop at least 1.5× taller than wide is turned 90°
3582    /// counter-clockwise, and the PP-LCNet text-line orientation classifier
3583    /// (`.models/ocr_textline_ori.onnx`, `DOCLING_OCR_TEXTLINE_ORI_ONNX`)
3584    /// turns lines it reads as upside down (`180` above 0.9). Vertical axis
3585    /// titles, rotated headers, skewed and upside-down lines then read as
3586    /// text. Applies to every PP-OCR line read off the detector — pages and
3587    /// pictures alike — but not to table words or the projection fallback;
3588    /// the reported boxes stay axis-aligned. A missing classifier warns once
3589    /// and keeps the crop and the 90° turn. Tesseract orients on its own.
3590    pub fn ocr_textline_orientation(mut self, enable: bool) -> Self {
3591        self.set_ocr_textline_orientation(Some(enable));
3592        self
3593    }
3594
3595    /// In-place [`ocr_textline_orientation`](Self::ocr_textline_orientation)
3596    /// for a warm pipeline (serve, the bindings' `Pipeline`), applied to
3597    /// loaded workers too; `None` restores the process default
3598    /// (`DOCLING_RS_OCR_TEXTLINE_ORIENTATION`), like
3599    /// [`set_ocr_scale`](Self::set_ocr_scale).
3600    pub fn set_ocr_textline_orientation(&mut self, enable: Option<bool>) {
3601        self.textline_orientation = enable.unwrap_or_else(ocr::textline_orientation_from_env);
3602        self.sync_ocr_config();
3603    }
3604
3605    /// Whether page extraction should decode the text layer at all. Forced
3606    /// full-page OCR (the flag or `ocr_mode=full_page|layout_regions`) clears
3607    /// every extracted cell unread, so the decode is skipped outright —
3608    /// docling#4061's `skip_cell_extraction` (2.122). `no_ocr` wins over the
3609    /// forcing, as everywhere else: its fast path *is* the text layer.
3610    fn extract_text_layer(&self) -> bool {
3611        self.no_ocr || !(self.force_full_page_ocr || self.ocr_mode.forces_full_page())
3612    }
3613
3614    /// When the walk renders the 2x bitmaps of pages with a text layer
3615    /// (#897). Adaptively by default: while the document's recent pages read
3616    /// theirs, each starts on the helper thread as the page leaves the walk,
3617    /// overlapping layout (#682); while they do not (prose), only a page that
3618    /// reads it renders it, after layout. Page images read every bitmap, so
3619    /// they keep the #682 schedule. `DOCLING_RS_PAGE_BITMAP` picks one
3620    /// explicitly: `eager` (every bitmap, during layout), `adaptive`,
3621    /// `on-demand` (only the bitmaps read — the least CPU, with every render
3622    /// after layout).
3623    fn bitmap_render(&self) -> pdfium_backend::BitmapRender {
3624        use pdfium_backend::BitmapRender;
3625        match env::nonempty("DOCLING_RS_PAGE_BITMAP")
3626            .map(|v| v.to_ascii_lowercase())
3627            .as_deref()
3628        {
3629            Some("eager") => BitmapRender::Eager,
3630            Some("on-demand" | "ondemand" | "lazy") => BitmapRender::OnDemand,
3631            _ if self.images.page_images => BitmapRender::Eager,
3632            _ => BitmapRender::Adaptive,
3633        }
3634    }
3635
3636    /// Push the current OCR forcing/scale choice onto already-loaded workers
3637    /// (new workers read it at [`Worker::load`]).
3638    fn sync_ocr_config(&mut self) {
3639        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
3640        let scale = self.ocr_scale;
3641        let orient = self.textline_orientation;
3642        let replace = self.replace_broken_text_layer;
3643        let pictures = self.picture_ocr;
3644        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3645            worker.force_full_page_ocr = force;
3646            worker.replace_broken_text_layer = replace;
3647            worker.picture_ocr = pictures;
3648            worker.ocr_scale = scale;
3649            worker.set_textline_orientation(orient);
3650        }
3651    }
3652
3653    /// Pixels per PDF point for picture crops and page images — docling's
3654    /// `images_scale` (#519/#520). `None` (the default) delivers crops at the
3655    /// pipeline's own page render, 2.0 px/pt (144 dpi), untouched. Another
3656    /// value resamples that render (CatmullRom, docling's PIL BICUBIC), so
3657    /// values above 2.0 upsample rather than re-render. Each picture's
3658    /// `dpi` (docling-core's `ImageRef.dpi`) is 72·scale, so consumers mapping
3659    /// pixels back to points stay exact. Layout, OCR and TableFormer inputs
3660    /// are unaffected. Non-positive values are ignored.
3661    pub fn images_scale(mut self, scale: Option<f32>) -> Self {
3662        self.set_images(ImageOutput {
3663            scale,
3664            ..self.images
3665        });
3666        self
3667    }
3668
3669    /// Keep each page's render as the document's page image — docling's
3670    /// `generate_page_images` (#520): the JSON export writes it as the page's
3671    /// `image` (docling-core's `PageItem.image`, at [`Self::images_scale`],
3672    /// `dpi` = 72·scale), which is what docling-core's
3673    /// `TableItem.get_image` / `FormulaItem.get_image` crop from. Off by
3674    /// default: a page image is a full-page PNG per page held in memory.
3675    /// Pages converted with `no_ocr` (text layer only) are never rendered and
3676    /// get none; streaming conversions carry no page map and drop them.
3677    pub fn generate_page_images(mut self, enabled: bool) -> Self {
3678        self.set_images(ImageOutput {
3679            page_images: enabled,
3680            ..self.images
3681        });
3682        self
3683    }
3684
3685    /// Use a picture's embedded image instead of the render crop when its
3686    /// region holds exactly one image XObject with nothing painted over it —
3687    /// docling's `use_embedded_picture_images` (#1007, docling#5143). The
3688    /// bitmap keeps its native pixel size and the picture's `dpi` is 72; a
3689    /// masked, transparent, clipped, rotated or overlapped image, a second
3690    /// image or text in the box, a `/Rotate`d page or an image that does not
3691    /// decode keep the crop. Off by default; layout, OCR and page images are
3692    /// unaffected.
3693    pub fn use_embedded_picture_images(mut self, enabled: bool) -> Self {
3694        self.set_images(ImageOutput {
3695            embedded_pictures: enabled,
3696            ..self.images
3697        });
3698        self
3699    }
3700
3701    /// Both image outputs at once, also on already-loaded workers — the
3702    /// per-request form a warm pipeline (serve, the Node `Pipeline`) uses,
3703    /// like [`set_ocr_scale`](Self::set_ocr_scale). A non-finite or
3704    /// non-positive scale reads as unset.
3705    pub fn set_images(&mut self, images: ImageOutput) {
3706        self.images = ImageOutput {
3707            scale: images.scale.filter(|s| s.is_finite() && *s > 0.0),
3708            ..images
3709        };
3710        let images = self.images;
3711        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3712            worker.images = images;
3713        }
3714    }
3715
3716    /// OCR render scale in pixels per PDF point — docling's `OcrOptions.scale`
3717    /// (#254, upstream docling#3877; their default 3 = 216 dpi). `None`
3718    /// (default: `DOCLING_RS_OCR_SCALE`, else unset) feeds the recognizer the
3719    /// pipeline's own page render (2.0 px/pt = 144 dpi) for a rendered page,
3720    /// and for a standalone image input docling's own resolution (#570): 3
3721    /// px/pt shrunk so the longer side stays within RapidOCR's 2000 px — what
3722    /// its models see after RapidOCR's `max_side_len` pass (a 754 × 1000 scan
3723    /// reads at 2.0). A set value resamples the render / image for the OCR
3724    /// input only — layout and TableFormer keep their pinned-resolution
3725    /// pixels, so the conformance baseline never moves. Lower it when the
3726    /// source raster is already high-resolution and upscaling degrades
3727    /// recognition; raise it toward docling's 216 dpi for parity experiments.
3728    /// Non-positive values are ignored.
3729    pub fn ocr_scale(mut self, scale: Option<f32>) -> Self {
3730        self.ocr_scale = scale
3731            .filter(|s| s.is_finite() && *s > 0.0)
3732            .or_else(ocr::scale_from_env);
3733        self
3734    }
3735
3736    /// Keep typographic punctuation as drawn — `„ “ ‚ ‘`, dashes, `…` —
3737    /// instead of folding it to ASCII as docling-parse's sanitizer does
3738    /// (`pdf_keep_typography`, #921). `None` keeps
3739    /// `DOCLING_RS_PDF_KEEP_TYPOGRAPHY`, else folding.
3740    pub fn set_keep_typography(&mut self, keep: Option<bool>) {
3741        self.keep_typography = keep;
3742    }
3743
3744    /// See [`set_keep_typography`](Self::set_keep_typography).
3745    pub fn keep_typography(mut self, keep: Option<bool>) -> Self {
3746        self.keep_typography = keep;
3747        self
3748    }
3749
3750    /// The text-layer settings the page walk applies.
3751    fn text_options(&self) -> pdfium_backend::TextOptions {
3752        pdfium_backend::TextOptions {
3753            word_gap: self.word_gap,
3754            keep_typography: self
3755                .keep_typography
3756                .unwrap_or_else(assemble::keep_typography_from_env),
3757            embedded_pictures: self.images.embedded_pictures,
3758        }
3759    }
3760
3761    /// See [`set_word_gap`](Self::set_word_gap).
3762    pub fn word_gap(mut self, gap: Option<WordGap>) -> Self {
3763        self.word_gap = gap;
3764        self
3765    }
3766
3767    /// The shared TableFormer slot handed to each worker, or `None` when the
3768    /// pipeline options skip TableFormer entirely.
3769    fn tables_slot(&self) -> Option<SharedTables> {
3770        if self.no_table_former || self.no_ocr {
3771            None
3772        } else {
3773            Some(Arc::clone(&self.tables))
3774        }
3775    }
3776
3777    /// The shared enrichment slots for a worker (`None` per model unless its
3778    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
3779    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
3780        if self.no_ocr || !self.enrich.any() {
3781            return (None, None);
3782        }
3783        (
3784            self.enrich
3785                .picture_classification
3786                .then(|| Arc::clone(&self.classifier)),
3787            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
3788        )
3789    }
3790
3791    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
3792    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
3793    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
3794    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
3795    /// `DocumentConverter.initialize_pipeline`.
3796    pub fn warm_up(&mut self) -> Result<(), PdfError> {
3797        self.primary()?;
3798        // The shared TableFormer loads on the first table otherwise — a
3799        // document with one would still pay for it (#548).
3800        if let Some(tables) = self.tables_slot() {
3801            tables.lock().unwrap_or_else(|p| p.into_inner()).load();
3802        }
3803        Ok(())
3804    }
3805
3806    /// [`warm_up`](Self::warm_up) plus the parallel page-worker pool, so the
3807    /// first *multi-page* conversion is no slower than later ones either: a
3808    /// document of `DOCLING_RS_PDF_PARALLEL_MIN` pages (6) or more fans out across the pool,
3809    /// whose workers each load their own layout/OCR sessions on first use
3810    /// (#548 — docling-serve's `--warmup` left a 9-page PDF paying that load).
3811    /// Costs the pool's memory up front (~0.4 GB a worker); with a pool of one
3812    /// worker it is exactly `warm_up`.
3813    pub fn warm_up_all(&mut self) -> Result<(), PdfError> {
3814        self.warm_up()?;
3815        if self.target_workers >= 2 {
3816            self.ensure_pool()?;
3817        }
3818        Ok(())
3819    }
3820
3821    /// The full-intra serial worker, loaded on first use.
3822    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
3823        if self.primary.is_none() {
3824            self.primary = Some(Worker::load(
3825                intra_threads(),
3826                self.tables_slot(),
3827                Arc::clone(&self.det),
3828                self.enrich_slots(),
3829                self.enrich,
3830                self.no_ocr,
3831                self.skip_ocr,
3832                // The mode-shaped spelling (#254) and the flag are one engine
3833                // truth: whichever demands forcing wins, mirroring docling's
3834                // `force_full_page_ocr` → `mode=full_page` bridge.
3835                self.force_full_page_ocr || self.ocr_mode.forces_full_page(),
3836                self.no_text_panels,
3837                self.ocr_lang,
3838                self.ocr_engine,
3839                self.tesseract_lang.clone(),
3840                self.ocr_scale,
3841                self.textline_orientation,
3842                self.images,
3843            )?);
3844            if let Some(w) = self.primary.as_mut() {
3845                w.replace_broken_text_layer = self.replace_broken_text_layer;
3846                w.picture_ocr = self.picture_ocr;
3847            }
3848        }
3849        Ok(self.primary.as_mut().unwrap())
3850    }
3851
3852    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
3853    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
3854    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
3855    /// fans the pages out across the worker pool, reassembled in page order so the
3856    /// output is byte-identical to the serial path.
3857    pub fn convert(
3858        &mut self,
3859        bytes: &[u8],
3860        password: Option<&str>,
3861        name: &str,
3862    ) -> Result<DoclingDocument, PdfError> {
3863        self.convert_outcome(bytes, password, name)
3864            .map(|c| c.document)
3865    }
3866
3867    /// [`convert`](Self::convert) that also says how the conversion ended —
3868    /// whether the [`document_timeout`](Self::document_timeout) cut it short
3869    /// and how many pages made it (`Completion`).
3870    pub fn convert_outcome(
3871        &mut self,
3872        bytes: &[u8],
3873        password: Option<&str>,
3874        name: &str,
3875    ) -> Result<Converted, PdfError> {
3876        let deadline = self.deadline();
3877        let pages = pdfium_backend::page_count(bytes, password)?;
3878        let range = self.resolve_range(pages)?;
3879        // Serial vs parallel is decided by the pages actually converted: a
3880        // 3-page window over a 500-page PDF should not pay the pool load.
3881        let selected = range.map_or(pages, |(a, b)| b - a + 1);
3882        let (document, done, timed_out) = if self.text_only_for(bytes, password)? {
3883            self.convert_text_only(bytes, password, name, range, selected, deadline)?
3884        } else if self.target_workers >= 2 && selected >= self.parallel_min {
3885            self.convert_parallel(bytes, password, name, range, selected, deadline)?
3886        } else {
3887            self.convert_serial(bytes, password, name, range, selected, deadline)?
3888        };
3889        timing::report();
3890        Ok(Converted {
3891            document,
3892            completion: self.completion(timed_out, done, selected),
3893        })
3894    }
3895
3896    /// Whether this document converts from its text layer alone: always
3897    /// under [`no_ocr`](Self::no_ocr); under
3898    /// [`text_layer_auto`](Self::text_layer_auto), when the layer carries
3899    /// the text ([`text_layer_has_text`]). Decided before any worker — and
3900    /// so any model — is touched.
3901    fn text_only_for(&self, bytes: &[u8], password: Option<&str>) -> Result<bool, PdfError> {
3902        if self.no_ocr {
3903            return Ok(true);
3904        }
3905        if !self.text_layer_auto {
3906            return Ok(false);
3907        }
3908        let has_text = text_layer_has_text(bytes, password)?;
3909        docling_core::debug_log!(
3910            "text_layer_only=auto: {}",
3911            if has_text {
3912                "the text layer carries the document, converting it alone"
3913            } else {
3914                "no usable text layer, running the full pipeline"
3915            }
3916        );
3917        Ok(has_text)
3918    }
3919
3920    /// The text layer alone, page by page — no worker, no model, no page
3921    /// bitmap: [`text_only_page`] on each extracted page, in order. The path
3922    /// of [`no_ocr`](Self::no_ocr) and of an [`auto`](Self::text_layer_auto)
3923    /// document with text; byte-identical to the serial walk, since the
3924    /// worker's `no_ocr` branch is the same function.
3925    fn convert_text_only(
3926        &mut self,
3927        bytes: &[u8],
3928        password: Option<&str>,
3929        name: &str,
3930        range: Option<(usize, usize)>,
3931        selected: usize,
3932        deadline: Option<std::time::Instant>,
3933    ) -> Result<(DoclingDocument, usize, bool), PdfError> {
3934        let mut doc = DoclingDocument::new(name);
3935        let mut confs = std::collections::BTreeMap::new();
3936        let images = self.images;
3937        let progress = self.progress.clone();
3938        let mut done = 0usize;
3939        let timed_out = Self::render_ahead(
3940            bytes,
3941            password,
3942            false,
3943            pdfium_backend::BitmapRender::Eager,
3944            true,
3945            range,
3946            deadline,
3947            self.text_options(),
3948            |n, page| {
3949                let (mut nodes, links, conf) = text_only_page(&page, images.scale);
3950                assemble::stamp_page_no(&mut nodes, n + 1);
3951                if let Some(img) = page_image_under(images, n, &page) {
3952                    doc.page_images.insert(n + 1, img);
3953                }
3954                doc.nodes.extend(nodes);
3955                doc.links.extend(links);
3956                confs.insert(n + 1, conf);
3957                done += 1;
3958                if let Some(cb) = &progress {
3959                    cb(PageProgress {
3960                        page_no: n + 1,
3961                        pages_done: done,
3962                        pages_selected: selected,
3963                    });
3964                }
3965                Ok(())
3966            },
3967        )?;
3968        assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::Lines);
3969        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
3970        self.apply_script_positions(&mut doc.nodes, bytes);
3971        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
3972        Ok((doc, done, timed_out))
3973    }
3974
3975    /// Stream pages one at a time through the primary worker — render → process →
3976    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
3977    fn convert_serial(
3978        &mut self,
3979        bytes: &[u8],
3980        password: Option<&str>,
3981        name: &str,
3982        range: Option<(usize, usize)>,
3983        selected: usize,
3984        deadline: Option<std::time::Instant>,
3985    ) -> Result<(DoclingDocument, usize, bool), PdfError> {
3986        let mut doc = DoclingDocument::new(name);
3987        let mut confs = std::collections::BTreeMap::new();
3988        let mut ocr_cells_by_page = std::collections::BTreeMap::new();
3989        let render_image = !self.no_ocr;
3990        let bitmap = self.bitmap_render();
3991        let extract_text = self.extract_text_layer();
3992        let progress = self.progress.clone();
3993        let mut done = 0usize;
3994        let text = self.text_options();
3995        let worker = self.primary()?;
3996        let timed_out = Self::render_ahead(
3997            bytes,
3998            password,
3999            render_image,
4000            bitmap,
4001            extract_text,
4002            range,
4003            deadline,
4004            text,
4005            |n, mut page| {
4006                let (mut nodes, links, conf, page_image, ocr_cells) =
4007                    worker.process(n, &mut page)?;
4008                assemble::stamp_page_no(&mut nodes, n + 1);
4009                if let Some(img) = page_image {
4010                    doc.page_images.insert(n + 1, img);
4011                }
4012                doc.nodes.extend(nodes);
4013                doc.links.extend(links);
4014                confs.insert(n + 1, conf);
4015                ocr_cells_by_page.insert(n + 1, ocr_cells);
4016                done += 1;
4017                if let Some(cb) = &progress {
4018                    cb(PageProgress {
4019                        page_no: n + 1,
4020                        pages_done: done,
4021                        pages_selected: selected,
4022                    });
4023                }
4024                Ok(())
4025            },
4026        )?;
4027        assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::AcrossPages);
4028        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
4029        self.apply_script_positions(&mut doc.nodes, bytes);
4030        doc.confidence = Some(confidence_report(confs, ocr_cells_by_page));
4031        Ok((doc, done, timed_out))
4032    }
4033
4034    /// The serial path's schedule (#682): pages render on a scoped thread
4035    /// and queue through a [`RENDER_AHEAD`]-page channel while the primary
4036    /// worker processes the previous one on the calling thread, so a page's
4037    /// two rasters (about a third of a digital page's cost) hide behind
4038    /// layout and TableFormer instead of preceding them — the render-ahead
4039    /// the worker pool always had, for documents too small for the pool.
4040    /// One consumer, pages in order: the output is byte-identical to the
4041    /// sequential walk. `consume` runs on the calling thread (a streaming
4042    /// `emit` need not be `Send`). A spent budget (#497) ends the walk at
4043    /// the renderer and the consumer alike; a consumer error closes the
4044    /// channel, which stops the renderer, and is the one reported.
4045    #[allow(clippy::too_many_arguments)]
4046    fn render_ahead<F>(
4047        bytes: &[u8],
4048        password: Option<&str>,
4049        render_image: bool,
4050        bitmap: pdfium_backend::BitmapRender,
4051        extract_text: bool,
4052        range: Option<(usize, usize)>,
4053        deadline: Option<std::time::Instant>,
4054        text: pdfium_backend::TextOptions,
4055        mut consume: F,
4056    ) -> Result<bool, PdfError>
4057    where
4058        F: FnMut(usize, PdfPage) -> Result<(), PdfError>,
4059    {
4060        let (tx, rx) = sync_channel::<(usize, PdfPage)>(RENDER_AHEAD);
4061        std::thread::scope(|s| {
4062            let render = s.spawn(move || {
4063                pdfium_backend::walk_pages(
4064                    bytes,
4065                    password,
4066                    render_image,
4067                    extract_text,
4068                    range,
4069                    bitmap,
4070                    text,
4071                    |n, _total, page| {
4072                        if expired(deadline) {
4073                            return Err(timeout_sentinel());
4074                        }
4075                        tx.send((n, page))
4076                            .map_err(|_| PdfError::Pdfium("page channel closed".into()))
4077                    },
4078                )
4079            });
4080            let mut timed_out = false;
4081            let mut failed = None;
4082            for (n, page) in rx.iter() {
4083                if expired(deadline) {
4084                    timed_out = true;
4085                    break;
4086                }
4087                if let Err(e) = consume(n, page) {
4088                    failed = Some(e);
4089                    break;
4090                }
4091            }
4092            // Closing the channel ends a walk still rendering.
4093            drop(rx);
4094            let walk = render
4095                .join()
4096                .map_err(|_| PdfError::Pdfium("page render thread panicked".into()))?;
4097            if let Some(e) = failed {
4098                return Err(e);
4099            }
4100            match walk {
4101                Ok(()) => Ok(timed_out),
4102                Err(PdfError::Timeout(_)) => Ok(true),
4103                Err(_) if timed_out => Ok(true),
4104                Err(e) => Err(e),
4105            }
4106        })
4107    }
4108
4109    /// Render pages serially on this thread (pdfium) and process them in parallel
4110    /// across the worker pool. A bounded channel applies backpressure so only a
4111    /// handful of page bitmaps are resident at once; results carry their page
4112    /// index and are reassembled in order, so the output is byte-identical to the
4113    /// serial path.
4114    fn convert_parallel(
4115        &mut self,
4116        bytes: &[u8],
4117        password: Option<&str>,
4118        name: &str,
4119        range: Option<(usize, usize)>,
4120        selected: usize,
4121        deadline: Option<std::time::Instant>,
4122    ) -> Result<(DoclingDocument, usize, bool), PdfError> {
4123        let text = self.text_options();
4124        self.ensure_pool_for(selected)?;
4125        let progress = self.progress.clone();
4126        let pages_done = std::sync::atomic::AtomicUsize::new(0);
4127        let timed_out = std::sync::atomic::AtomicBool::new(false);
4128        let n_workers = self.pool.len();
4129        let render_image = !self.no_ocr;
4130        let bitmap = self.bitmap_render();
4131        let extract_text = self.extract_text_layer();
4132        let layout_batch = pdf_layout_batch();
4133        // Bound sized so every worker can accumulate a full layout batch while
4134        // rendering stays ahead (and never below the pre-#73 render-ahead of
4135        // two pages per worker); still a hard cap on resident page bitmaps.
4136        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
4137        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
4138        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
4139        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
4140
4141        // Move the pool into the scope so each worker gets an exclusive `&mut`.
4142        let mut workers = std::mem::take(&mut self.pool);
4143        std::thread::scope(|s| {
4144            for worker in workers.iter_mut() {
4145                let work_rx = Arc::clone(&work_rx);
4146                let results = Arc::clone(&results);
4147                let first_err = Arc::clone(&first_err);
4148                let progress = progress.clone();
4149                let pages_done = &pages_done;
4150                let timed_out = &timed_out;
4151                s.spawn(move || {
4152                    worker.run_pool(&work_rx, layout_batch, deadline, |idx, out| {
4153                        match out {
4154                            Ok(out) => {
4155                                results.lock().unwrap().push((idx, out));
4156                                let d = pages_done
4157                                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
4158                                    + 1;
4159                                if let Some(cb) = &progress {
4160                                    cb(PageProgress {
4161                                        page_no: idx + 1,
4162                                        pages_done: d,
4163                                        pages_selected: selected,
4164                                    });
4165                                }
4166                            }
4167                            // The budget ran out before this page's turn: the
4168                            // page is left out, the document is partial.
4169                            Err(PdfError::Timeout(_)) => {
4170                                timed_out.store(true, std::sync::atomic::Ordering::Relaxed);
4171                            }
4172                            Err(e) => {
4173                                let mut slot = first_err.lock().unwrap();
4174                                if slot.is_none() {
4175                                    *slot = Some(e);
4176                                }
4177                            }
4178                        }
4179                        true
4180                    });
4181                });
4182            }
4183            // Render on this thread and feed the workers; backpressure blocks here
4184            // when the channel is full. Dropping `work_tx` afterwards signals the
4185            // workers (recv → Err) to finish. A spent budget ends the walk before
4186            // the next page is rendered.
4187            let render = pdfium_backend::walk_pages(
4188                bytes,
4189                password,
4190                render_image,
4191                extract_text,
4192                range,
4193                bitmap,
4194                text,
4195                |i, _total, page| {
4196                    if expired(deadline) {
4197                        return Err(timeout_sentinel());
4198                    }
4199                    work_tx
4200                        .send((i, page))
4201                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
4202                },
4203            );
4204            drop(work_tx);
4205            match render {
4206                Ok(()) => {}
4207                Err(PdfError::Timeout(_)) => {
4208                    timed_out.store(true, std::sync::atomic::Ordering::Relaxed);
4209                }
4210                Err(e) => {
4211                    let mut slot = first_err.lock().unwrap();
4212                    if slot.is_none() {
4213                        *slot = Some(e);
4214                    }
4215                }
4216            }
4217        });
4218        // Threads have joined; restore the pool for the next conversion.
4219        self.pool = workers;
4220
4221        if let Some(e) = first_err.lock().unwrap().take() {
4222            return Err(e);
4223        }
4224        let mut results = Arc::try_unwrap(results)
4225            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
4226            .into_inner()
4227            .unwrap();
4228        results.sort_by_key(|(idx, _)| *idx);
4229        let done = results.len();
4230        let mut doc = DoclingDocument::new(name);
4231        let mut confs = std::collections::BTreeMap::new();
4232        let mut ocr_cells_by_page = std::collections::BTreeMap::new();
4233        for (idx, (mut nodes, links, conf, page_image, ocr_cells)) in results {
4234            assemble::stamp_page_no(&mut nodes, idx + 1);
4235            if let Some(img) = page_image {
4236                doc.page_images.insert(idx + 1, img);
4237            }
4238            doc.nodes.extend(nodes);
4239            doc.links.extend(links);
4240            confs.insert(idx + 1, conf);
4241            ocr_cells_by_page.insert(idx + 1, ocr_cells);
4242        }
4243        assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::AcrossPages);
4244        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
4245        self.apply_script_positions(&mut doc.nodes, bytes);
4246        doc.confidence = Some(confidence_report(confs, ocr_cells_by_page));
4247        let timed_out = timed_out.load(std::sync::atomic::Ordering::Relaxed);
4248        Ok((doc, done, timed_out))
4249    }
4250
4251    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
4252    /// in-document-order batch of nodes (and that span's recovered links) as pages
4253    /// complete, so a caller can serialize Markdown page by page instead of waiting
4254    /// for the whole document. The batches are exactly the buffered [`convert`]'s
4255    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
4256    /// parallel path reorders pages back into document order before emitting, so
4257    /// the output is identical regardless of worker scheduling.
4258    ///
4259    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
4260    /// and its backpressure throttles the whole pipeline. Returning `Err` from
4261    /// `emit` aborts the conversion with that error.
4262    pub fn convert_streaming<F>(
4263        &mut self,
4264        bytes: &[u8],
4265        password: Option<&str>,
4266        name: &str,
4267        emit: F,
4268    ) -> Result<(), PdfError>
4269    where
4270        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4271    {
4272        self.convert_streaming_outcome(bytes, password, name, emit)
4273            .map(|_| ())
4274    }
4275
4276    /// [`convert_streaming`](Self::convert_streaming) that also says how the
4277    /// conversion ended ([`Completion`]): a spent
4278    /// [`document_timeout`](Self::document_timeout) stops the walk, the pages
4279    /// finished so far are emitted (the tail included) and the outcome is
4280    /// `TimedOut` — never an error.
4281    pub fn convert_streaming_outcome<F>(
4282        &mut self,
4283        bytes: &[u8],
4284        password: Option<&str>,
4285        name: &str,
4286        emit: F,
4287    ) -> Result<Completion, PdfError>
4288    where
4289        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4290    {
4291        let _ = name; // page nodes carry no name; the caller owns the document name.
4292        let deadline = self.deadline();
4293        let pages = pdfium_backend::page_count(bytes, password)?;
4294        let range = self.resolve_range(pages)?;
4295        let selected = range.map_or(pages, |(a, b)| b - a + 1);
4296        let r = if self.text_only_for(bytes, password)? {
4297            self.convert_streaming_text_only(bytes, password, range, deadline, selected, emit)
4298        } else if self.target_workers >= 2 && selected >= self.parallel_min {
4299            self.convert_streaming_parallel(bytes, password, range, deadline, selected, emit)
4300        } else {
4301            self.convert_streaming_serial(bytes, password, range, deadline, selected, emit)
4302        };
4303        timing::report();
4304        let (done, timed_out) = r?;
4305        Ok(self.completion(timed_out, done, selected))
4306    }
4307
4308    /// Streaming from the text layer alone ([`convert_text_only`](Self::convert_text_only)'s
4309    /// emitting twin): extract → [`text_only_page`] → emit, one page at a
4310    /// time, holding back only the tail that might still merge into the next
4311    /// page. No worker, no model, no bitmap.
4312    fn convert_streaming_text_only<F>(
4313        &mut self,
4314        bytes: &[u8],
4315        password: Option<&str>,
4316        range: Option<(usize, usize)>,
4317        deadline: Option<std::time::Instant>,
4318        selected: usize,
4319        mut emit: F,
4320    ) -> Result<(usize, bool), PdfError>
4321    where
4322        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4323    {
4324        let mut asm = assemble::StreamAssembler::new(assemble::Continuations::Lines);
4325        let images = self.images;
4326        let progress = self.progress.clone();
4327        let mut done = 0usize;
4328        let timed_out = Self::render_ahead(
4329            bytes,
4330            password,
4331            false,
4332            pdfium_backend::BitmapRender::Eager,
4333            true,
4334            range,
4335            deadline,
4336            self.text_options(),
4337            |n, page| {
4338                let (nodes, links, _conf) = text_only_page(&page, images.scale);
4339                done += 1;
4340                if let Some(cb) = &progress {
4341                    cb(PageProgress {
4342                        page_no: n + 1,
4343                        pages_done: done,
4344                        pages_selected: selected,
4345                    });
4346                }
4347                emit(asm.push(nodes), links)
4348            },
4349        )?;
4350        emit(asm.finish(), Vec::new())?;
4351        Ok((done, timed_out))
4352    }
4353
4354    /// Serial streaming: render → process → emit, one page at a time, holding back
4355    /// only the tail that might still merge into the next page.
4356    fn convert_streaming_serial<F>(
4357        &mut self,
4358        bytes: &[u8],
4359        password: Option<&str>,
4360        range: Option<(usize, usize)>,
4361        deadline: Option<std::time::Instant>,
4362        selected: usize,
4363        mut emit: F,
4364    ) -> Result<(usize, bool), PdfError>
4365    where
4366        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4367    {
4368        let mut asm = assemble::StreamAssembler::new(assemble::Continuations::AcrossPages);
4369        let render_image = !self.no_ocr;
4370        let bitmap = self.bitmap_render();
4371        let extract_text = self.extract_text_layer();
4372        let progress = self.progress.clone();
4373        let text = self.text_options();
4374        let worker = self.primary()?;
4375        let mut done = 0usize;
4376        let timed_out = Self::render_ahead(
4377            bytes,
4378            password,
4379            render_image,
4380            bitmap,
4381            extract_text,
4382            range,
4383            deadline,
4384            text,
4385            |n, mut page| {
4386                // Confidence is dropped on the streaming path: the report is
4387                // only complete once every page has run, which defeats
4388                // page-by-page emission — buffered `convert` carries it.
4389                let (nodes, links, _conf, _page_image, _cells) = worker.process(n, &mut page)?;
4390                done += 1;
4391                if let Some(cb) = &progress {
4392                    cb(PageProgress {
4393                        page_no: n + 1,
4394                        pages_done: done,
4395                        pages_selected: selected,
4396                    });
4397                }
4398                emit(asm.push(nodes), links)
4399            },
4400        )?;
4401        emit(asm.finish(), Vec::new())?;
4402        Ok((done, timed_out))
4403    }
4404
4405    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
4406    /// not thread-safe) and process across the worker pool; results carry their
4407    /// page index and are reordered on the calling thread into a
4408    /// [`assemble::StreamAssembler`], which emits each page in document order as
4409    /// soon as its predecessors have arrived. Bounded channels keep only a handful
4410    /// of pages resident and let `emit`'s backpressure reach the renderer.
4411    fn convert_streaming_parallel<F>(
4412        &mut self,
4413        bytes: &[u8],
4414        password: Option<&str>,
4415        range: Option<(usize, usize)>,
4416        deadline: Option<std::time::Instant>,
4417        selected: usize,
4418        mut emit: F,
4419    ) -> Result<(usize, bool), PdfError>
4420    where
4421        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4422    {
4423        let text = self.text_options();
4424        self.ensure_pool_for(selected)?;
4425        let n_workers = self.pool.len();
4426        let render_image = !self.no_ocr;
4427        let bitmap = self.bitmap_render();
4428        let extract_text = self.extract_text_layer();
4429        let progress = self.progress.clone();
4430        let layout_batch = pdf_layout_batch();
4431        // Bound sized so every worker can accumulate a full layout batch while
4432        // rendering stays ahead (and never below the pre-#73 render-ahead of
4433        // two pages per worker); still a hard cap on resident page bitmaps.
4434        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
4435        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
4436        // Workers and the renderer report here; the calling thread drains it in
4437        // page order. Bounded so workers block (bounding resident bitmaps) when the
4438        // consumer falls behind.
4439        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
4440
4441        let mut workers = std::mem::take(&mut self.pool);
4442        let mut asm = assemble::StreamAssembler::new(assemble::Continuations::AcrossPages);
4443        let mut first_err: Option<PdfError> = None;
4444        let mut timed_out = false;
4445        let mut done = 0usize;
4446
4447        std::thread::scope(|s| {
4448            // Workers: pull a batch of pages (whatever is already rendered, up
4449            // to the layout batch size), process it, report (index-tagged)
4450            // results.
4451            for worker in workers.iter_mut() {
4452                let work_rx = Arc::clone(&work_rx);
4453                let res_tx = res_tx.clone();
4454                s.spawn(move || {
4455                    worker.run_pool(&work_rx, layout_batch, deadline, |idx, out| {
4456                        // `false` once the consumer is gone.
4457                        res_tx.send(out.map(|o| (idx, o))).is_ok()
4458                    });
4459                });
4460            }
4461            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
4462            // single thread); report a render error through the same channel. A
4463            // spent budget ends the walk before the next page is rendered.
4464            {
4465                let res_tx = res_tx.clone();
4466                s.spawn(move || {
4467                    let render = pdfium_backend::walk_pages(
4468                        bytes,
4469                        password,
4470                        render_image,
4471                        extract_text,
4472                        range,
4473                        bitmap,
4474                        text,
4475                        |i, _total, page| {
4476                            if expired(deadline) {
4477                                return Err(timeout_sentinel());
4478                            }
4479                            work_tx
4480                                .send((i, page))
4481                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
4482                        },
4483                    );
4484                    drop(work_tx); // signal workers to finish
4485                    if let Err(e) = render {
4486                        let _ = res_tx.send(Err(e));
4487                    }
4488                });
4489            }
4490            // Drop our own sender so the channel closes once the threads finish.
4491            drop(res_tx);
4492
4493            // Collector (this thread): reorder into document order and emit.
4494            // With a page window, indices start at the window's first page.
4495            // A timed-out page leaves a hole in the sequence: everything
4496            // before it emits in order, the pages after it stay buffered —
4497            // they are the pages the budget did not cover, and the document
4498            // ends at the cut like the buffered path's.
4499            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
4500            let mut next = range.map_or(0, |(first, _)| first);
4501            for msg in res_rx.iter() {
4502                match msg {
4503                    Err(PdfError::Timeout(_)) => timed_out = true,
4504                    Err(e) => {
4505                        if first_err.is_none() {
4506                            first_err = Some(e);
4507                        }
4508                    }
4509                    Ok((idx, out)) => {
4510                        buffer.insert(idx, out);
4511                        if first_err.is_some() {
4512                            continue; // keep draining so the threads can exit
4513                        }
4514                        // A stream carries Markdown, not the page map: page
4515                        // images (#520) have nowhere to go and are dropped.
4516                        while let Some((nodes, links, _conf, _page_image, _cells)) =
4517                            buffer.remove(&next)
4518                        {
4519                            if let Err(e) = emit(asm.push(nodes), links) {
4520                                first_err = Some(e);
4521                                break;
4522                            }
4523                            next += 1;
4524                            done += 1;
4525                            // Reported in document order, as emitted: a page
4526                            // that finished early counts once it is emitted.
4527                            if let Some(cb) = &progress {
4528                                cb(PageProgress {
4529                                    page_no: next,
4530                                    pages_done: done,
4531                                    pages_selected: selected,
4532                                });
4533                            }
4534                        }
4535                    }
4536                }
4537            }
4538            // Pages that finished after a hole (a page the budget skipped
4539            // before them) cannot follow it in document order; count them
4540            // out of the document like the skipped one.
4541            if timed_out && !buffer.is_empty() {
4542                buffer.clear();
4543            }
4544        });
4545        // Threads have joined; restore the pool for the next conversion.
4546        self.pool = workers;
4547
4548        if let Some(e) = first_err {
4549            return Err(e);
4550        }
4551        emit(asm.finish(), Vec::new())?;
4552        Ok((done, timed_out))
4553    }
4554
4555    /// Lazily grow the pool to `target_workers`, loading the new workers
4556    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
4557    /// one load's wall-time). Cached for reuse across documents.
4558    fn ensure_pool(&mut self) -> Result<(), PdfError> {
4559        self.ensure_pool_for(self.target_workers)
4560    }
4561
4562    /// [`ensure_pool`](Self::ensure_pool) for a document of `pages` pages:
4563    /// no more workers than pages (#682 — a two-page document on a 16-core
4564    /// host loads two workers, not eight), never fewer than two, and never
4565    /// more than `target_workers`; a later, longer document grows the pool.
4566    fn ensure_pool_for(&mut self, pages: usize) -> Result<(), PdfError> {
4567        let want = pages.max(2).min(self.target_workers);
4568        let need = want.saturating_sub(self.pool.len());
4569        if need == 0 {
4570            return Ok(());
4571        }
4572        let intra = pdf_intra();
4573        let no_ocr = self.no_ocr;
4574        let skip_ocr = self.skip_ocr;
4575        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
4576        let ntp = self.no_text_panels;
4577        let ocr_lang = self.ocr_lang;
4578        let ocr_engine = self.ocr_engine;
4579        let tesseract_lang = self.tesseract_lang.clone();
4580        let ocr_scale = self.ocr_scale;
4581        let textline_orientation = self.textline_orientation;
4582        let images = self.images;
4583        let enrich = self.enrich;
4584        let tables = self.tables_slot();
4585        let det = Arc::clone(&self.det);
4586        let enrich_slots = self.enrich_slots();
4587        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
4588            let handles: Vec<_> = (0..need)
4589                .map(|_| {
4590                    let tables = tables.clone();
4591                    let det = Arc::clone(&det);
4592                    let enrich_slots = enrich_slots.clone();
4593                    let tesseract_lang = tesseract_lang.clone();
4594                    s.spawn(move || {
4595                        Worker::load(
4596                            intra,
4597                            tables,
4598                            det,
4599                            enrich_slots,
4600                            enrich,
4601                            no_ocr,
4602                            skip_ocr,
4603                            force,
4604                            ntp,
4605                            ocr_lang,
4606                            ocr_engine,
4607                            tesseract_lang,
4608                            ocr_scale,
4609                            textline_orientation,
4610                            images,
4611                        )
4612                    })
4613                })
4614                .collect();
4615            handles.into_iter().map(|h| h.join().unwrap()).collect()
4616        });
4617        for w in loaded {
4618            let mut w = w?;
4619            w.replace_broken_text_layer = self.replace_broken_text_layer;
4620            w.picture_ocr = self.picture_ocr;
4621            self.pool.push(w);
4622        }
4623        Ok(())
4624    }
4625
4626    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
4627    /// docling routes images through the same layout+OCR pipeline as a PDF page.
4628    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
4629        let image = decode_image_limited(bytes)?;
4630        let (w, h) = image.dimensions();
4631        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
4632        // standalone image has no text layer, so OCR supplies the cells.
4633        let page = PdfPage {
4634            width: w as f32,
4635            height: h as f32,
4636            scale: 1.0,
4637            cells: Vec::new(),
4638            code_cells: Vec::new(),
4639            checkboxes: Vec::new(),
4640            bitmaps: Vec::new(),
4641            shapes: Default::default(),
4642            word_cells: Vec::new(),
4643            // A standalone image *is* its own scale-1.0 page image, so the
4644            // layout model sees it through the docling-exact PIL kernel.
4645            image_layout: Some(image.clone()),
4646            image,
4647            links: Vec::new(),
4648            rotation: 0,
4649            keep_typography: false,
4650            #[cfg(feature = "render")]
4651            embedded_images: Vec::new(),
4652            pending_image: None,
4653        };
4654        let mut doc = self.process_pages(vec![page], name)?;
4655        // docling sizes the page from the file's resolution (#1093); the
4656        // models above ran on the file's own pixels, which only the page unit
4657        // changes, so the text and the reading order cannot move.
4658        let (dpi_x, dpi_y) = image_page_dpi(bytes, (w, h));
4659        if (dpi_x, dpi_y) != (72.0, 72.0) {
4660            doc.rescale_page_units((72.0 / dpi_x) as f32, (72.0 / dpi_y) as f32);
4661        }
4662        Ok(doc)
4663    }
4664
4665    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
4666    /// page (image / METS inputs, which are small and already materialised).
4667    /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
4668    /// caller-configured pipeline (#244).
4669    pub fn process_pages(
4670        &mut self,
4671        pages: Vec<PdfPage>,
4672        name: &str,
4673    ) -> Result<DoclingDocument, PdfError> {
4674        let numbered = pages
4675            .into_iter()
4676            .enumerate()
4677            .map(|(n, p)| (n + 1, p))
4678            .collect();
4679        self.process_numbered_pages(numbered, name)
4680    }
4681
4682    /// [`Pipeline::process_pages`] with each page's 1-based number given —
4683    /// a METS archive that left a page out keeps the numbers of the pages
4684    /// after it (#1147).
4685    pub fn process_numbered_pages(
4686        &mut self,
4687        mut pages: Vec<(usize, PdfPage)>,
4688        name: &str,
4689    ) -> Result<DoclingDocument, PdfError> {
4690        let mut doc = DoclingDocument::new(name);
4691        let mut confs = std::collections::BTreeMap::new();
4692        let mut ocr_cells_by_page = std::collections::BTreeMap::new();
4693        let progress = self.progress.clone();
4694        let total = pages.len();
4695        let worker = self.primary()?;
4696        for (done, (page_no, page)) in pages.iter_mut().enumerate() {
4697            let page_no = *page_no;
4698            let (mut nodes, links, conf, page_image, ocr_cells) =
4699                worker.process(page_no - 1, page)?;
4700            assemble::stamp_page_no(&mut nodes, page_no);
4701            if let Some(img) = page_image {
4702                doc.page_images.insert(page_no, img);
4703            }
4704            doc.nodes.extend(nodes);
4705            doc.links.extend(links);
4706            confs.insert(page_no, conf);
4707            ocr_cells_by_page.insert(page_no, ocr_cells);
4708            if let Some(cb) = &progress {
4709                cb(PageProgress {
4710                    page_no,
4711                    pages_done: done + 1,
4712                    pages_selected: total,
4713                });
4714            }
4715        }
4716        assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::AcrossPages);
4717        // No PDF behind these pages (images, METS): the heading-hierarchy
4718        // stage degrades to the numbering signal — exactly docling without
4719        // an outline or parsed pages.
4720        self.apply_heading_hierarchy(&mut doc.nodes, None);
4721        doc.confidence = Some(confidence_report(confs, ocr_cells_by_page));
4722        Ok(doc)
4723    }
4724}
4725
4726/// Number of pages in a PDF, without converting anything — what the CLI batch
4727/// mode prints in its per-document start line.
4728#[cfg(feature = "ml")]
4729pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
4730    pdfium_backend::page_count(bytes, password)
4731}
4732
4733#[cfg(feature = "ml")]
4734/// Convenience one-shot conversion (loads the pipeline per call). Errors are
4735/// detailed and surfaced (never silently skipped).
4736pub fn convert(
4737    bytes: &[u8],
4738    password: Option<&str>,
4739    name: &str,
4740) -> Result<DoclingDocument, PdfError> {
4741    convert_with_options(
4742        bytes,
4743        password,
4744        name,
4745        false,
4746        false,
4747        false,
4748        false,
4749        EnrichmentOptions::default(),
4750        None,
4751        None,
4752    )
4753}
4754
4755#[cfg(feature = "ml")]
4756/// Like [`convert`], but optionally skips loading/running TableFormer (see
4757/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
4758/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
4759/// [`Pipeline::enrichments`]).
4760// One positional per pipeline switch mirrors the Pipeline builder; growing
4761// past clippy's arity cap is the price of keeping this one-shot signature
4762// stable-ish instead of churning callers into an options struct mid-series.
4763#[allow(clippy::too_many_arguments)]
4764pub fn convert_with_options(
4765    bytes: &[u8],
4766    password: Option<&str>,
4767    name: &str,
4768    no_table_former: bool,
4769    no_ocr: bool,
4770    force_full_page_ocr: bool,
4771    no_text_panels: bool,
4772    enrich: EnrichmentOptions,
4773    pages: Option<(usize, usize)>,
4774    ocr_lang: Option<OcrLang>,
4775) -> Result<DoclingDocument, PdfError> {
4776    Pipeline::new()?
4777        .no_table_former(no_table_former)
4778        .no_ocr(no_ocr)
4779        .force_full_page_ocr(force_full_page_ocr)
4780        .no_text_panels(no_text_panels)
4781        .enrichments(enrich)
4782        .pages(pages)
4783        .ocr_lang(ocr_lang)
4784        .convert(bytes, password, name)
4785}
4786
4787#[cfg(feature = "ml")]
4788/// Convenience one-shot image conversion (loads the pipeline per call).
4789pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
4790    convert_image_with_options(
4791        bytes,
4792        name,
4793        false,
4794        false,
4795        false,
4796        EnrichmentOptions::default(),
4797        None,
4798    )
4799}
4800
4801#[cfg(feature = "ml")]
4802/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
4803/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
4804/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
4805pub fn convert_image_with_options(
4806    bytes: &[u8],
4807    name: &str,
4808    no_table_former: bool,
4809    no_ocr: bool,
4810    no_text_panels: bool,
4811    enrich: EnrichmentOptions,
4812    ocr_lang: Option<OcrLang>,
4813) -> Result<DoclingDocument, PdfError> {
4814    Pipeline::new()?
4815        .no_table_former(no_table_former)
4816        .no_ocr(no_ocr)
4817        .no_text_panels(no_text_panels)
4818        .enrichments(enrich)
4819        .ocr_lang(ocr_lang)
4820        .convert_image(bytes, name)
4821}
4822
4823#[cfg(feature = "ml")]
4824/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
4825/// scans) through the shared layout + assembly pipeline.
4826pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
4827    convert_pages_with_options(
4828        pages,
4829        name,
4830        false,
4831        false,
4832        false,
4833        EnrichmentOptions::default(),
4834    )
4835}
4836
4837#[cfg(feature = "ml")]
4838/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
4839/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
4840/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
4841pub fn convert_pages_with_options(
4842    pages: Vec<PdfPage>,
4843    name: &str,
4844    no_table_former: bool,
4845    no_ocr: bool,
4846    no_text_panels: bool,
4847    enrich: EnrichmentOptions,
4848) -> Result<DoclingDocument, PdfError> {
4849    Pipeline::new()?
4850        .no_table_former(no_table_former)
4851        .no_text_panels(no_text_panels)
4852        .no_ocr(no_ocr)
4853        .enrichments(enrich)
4854        .process_pages(pages, name)
4855}
4856
4857#[cfg(feature = "ml")]
4858#[cfg(all(test, feature = "ml"))]
4859mod image_limit_tests {
4860    use super::decode_image_with_max_side;
4861
4862    /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
4863    /// byte literal).
4864    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
4865        use std::io::Cursor;
4866        let img = image::RgbImage::new(w, h);
4867        let mut out = Vec::new();
4868        img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
4869            .unwrap();
4870        out
4871    }
4872
4873    #[test]
4874    fn normal_image_decodes_under_the_cap() {
4875        let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
4876        assert_eq!(img.dimensions(), (8, 8));
4877    }
4878
4879    /// docling#4247 (2.128): the EXIF orientation is applied when a frame is
4880    /// loaded — a 4×2 JPEG tagged "rotate 90° CW" (orientation 6) decodes as
4881    /// 2×4, with the pixels turned.
4882    #[test]
4883    fn exif_orientation_is_applied() {
4884        use std::io::Cursor;
4885        let mut img = image::RgbImage::new(4, 2);
4886        img.put_pixel(0, 0, image::Rgb([255, 0, 0]));
4887        let mut jpeg = Vec::new();
4888        img.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
4889            .unwrap();
4890        // Splice an APP1 Exif segment (little-endian TIFF, one IFD entry:
4891        // Orientation = 6) right after the SOI marker.
4892        let mut tiff = b"II*\0".to_vec();
4893        tiff.extend(8u32.to_le_bytes());
4894        tiff.extend(1u16.to_le_bytes());
4895        tiff.extend(0x0112u16.to_le_bytes());
4896        tiff.extend(3u16.to_le_bytes());
4897        tiff.extend(1u32.to_le_bytes());
4898        tiff.extend(6u16.to_le_bytes());
4899        tiff.extend([0, 0]);
4900        tiff.extend(0u32.to_le_bytes());
4901        let mut app1 = b"Exif\0\0".to_vec();
4902        app1.extend(tiff);
4903        let mut out = jpeg[..2].to_vec();
4904        out.extend([0xff, 0xe1]);
4905        out.extend((app1.len() as u16 + 2).to_be_bytes());
4906        out.extend(app1);
4907        out.extend(&jpeg[2..]);
4908        let plain = decode_image_with_max_side(&jpeg, 30_000).unwrap();
4909        assert_eq!(plain.dimensions(), (4, 2));
4910        let turned = decode_image_with_max_side(&out, 30_000).unwrap();
4911        assert_eq!(turned.dimensions(), (2, 4), "quarter turn swaps the sides");
4912        // Rotating 90° CW moves the top-left pixel to the top-right corner.
4913        assert!(turned.get_pixel(1, 0).0[0] > 128);
4914        assert!(turned.get_pixel(0, 0).0[0] <= 128);
4915    }
4916
4917    #[test]
4918    fn dimensions_over_the_cap_are_rejected_not_aborted() {
4919        // A per-side cap below the image's declared size must yield a
4920        // recoverable Err, never an allocation-abort — the mechanism that stops
4921        // a crafted image declaring 60000×60000 from OOM-killing the process.
4922        let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
4923        assert!(
4924            r.is_err(),
4925            "decode must fail under the pixel cap, not abort"
4926        );
4927    }
4928}
4929
4930#[cfg(all(test, feature = "ml"))]
4931mod image_page_dpi_tests {
4932    use super::{decode_image_with_max_side, image_page_dpi};
4933    use image::codecs::jpeg::{JpegEncoder, PixelDensity, PixelDensityUnit};
4934
4935    /// A 4 × 2 JPEG whose JFIF records `density`, tagged with EXIF
4936    /// `orientation` when given.
4937    fn jpeg(density: PixelDensity, orientation: Option<u16>) -> Vec<u8> {
4938        let img = image::RgbImage::new(4, 2);
4939        let mut out = Vec::new();
4940        let mut enc = JpegEncoder::new(&mut out);
4941        enc.set_pixel_density(density);
4942        enc.encode_image(&img).unwrap();
4943        let Some(o) = orientation else {
4944            return out;
4945        };
4946        // An APP1 Exif segment (little-endian TIFF, one IFD entry:
4947        // Orientation) right after SOI; the JFIF density stays authoritative.
4948        let mut app1 = b"Exif\0\0II*\0".to_vec();
4949        app1.extend(8u32.to_le_bytes());
4950        app1.extend(1u16.to_le_bytes());
4951        app1.extend(0x0112u16.to_le_bytes());
4952        app1.extend(3u16.to_le_bytes());
4953        app1.extend(1u32.to_le_bytes());
4954        app1.extend(o.to_le_bytes());
4955        app1.extend([0, 0, 0, 0, 0, 0]);
4956        let mut spliced = out[..2].to_vec();
4957        spliced.extend([0xff, 0xe1]);
4958        spliced.extend((app1.len() as u16 + 2).to_be_bytes());
4959        spliced.extend(app1);
4960        spliced.extend(&out[2..]);
4961        spliced
4962    }
4963
4964    fn dpi_of(bytes: &[u8]) -> (f64, f64) {
4965        let decoded = decode_image_with_max_side(bytes, 30_000).unwrap();
4966        image_page_dpi(bytes, decoded.dimensions())
4967    }
4968
4969    /// docling's `_get_frame_dpi`: each axis's resolution as Pillow reads it;
4970    /// none, `(1, 1)` and `(0, 0)` read as 72.
4971    #[test]
4972    fn the_page_takes_the_files_resolution() {
4973        let anisotropic = PixelDensity {
4974            density: (300, 150),
4975            unit: PixelDensityUnit::Inches,
4976        };
4977        assert_eq!(dpi_of(&jpeg(anisotropic, None)), (300.0, 150.0));
4978        assert_eq!(dpi_of(&jpeg(PixelDensity::default(), None)), (72.0, 72.0));
4979        assert_eq!(dpi_of(&jpeg(PixelDensity::dpi(1), None)), (72.0, 72.0));
4980        assert_eq!(dpi_of(&jpeg(PixelDensity::dpi(0), None)), (72.0, 72.0));
4981    }
4982
4983    /// docling's `_oriented_frame`: a quarter-turn EXIF orientation swaps the
4984    /// frame's sides, and the resolution's axes with them; a half turn does
4985    /// not.
4986    #[test]
4987    fn a_quarter_turn_swaps_the_axes() {
4988        let anisotropic = PixelDensity {
4989            density: (300, 150),
4990            unit: PixelDensityUnit::Inches,
4991        };
4992        assert_eq!(dpi_of(&jpeg(anisotropic, Some(6))), (150.0, 300.0));
4993        assert_eq!(dpi_of(&jpeg(anisotropic, Some(3))), (300.0, 150.0));
4994    }
4995}
4996
4997#[cfg(all(test, feature = "ml"))]
4998mod ocr_scale_tests {
4999    use super::*;
5000
5001    /// #570: an explicit scale wins everywhere; a rendered page keeps its
5002    /// render; a scale-1.0 image page reads at docling's 3 px/pt, shrunk to
5003    /// RapidOCR's 2000 px longer side (a FUNSD scan at 2.0, a 3000 px photo
5004    /// downsampled to 0.67), and an image that lands at 1.0 is not resampled.
5005    #[test]
5006    fn image_inputs_follow_rapidocrs_resolution() {
5007        assert_eq!(page_ocr_scale(Some(1.5), 754.0, 1000.0, 1.0), Some(1.5));
5008        assert_eq!(page_ocr_scale(None, 612.0, 792.0, 2.0), None);
5009        assert_eq!(page_ocr_scale(None, 754.0, 1000.0, 1.0), Some(2.0));
5010        assert_eq!(page_ocr_scale(None, 400.0, 600.0, 1.0), Some(3.0));
5011        let s = page_ocr_scale(None, 3000.0, 2000.0, 1.0).unwrap();
5012        assert!((s - 2.0 / 3.0).abs() < 1e-6, "{s}");
5013        assert_eq!(page_ocr_scale(None, 2000.0, 1500.0, 1.0), None);
5014    }
5015}
5016
5017#[cfg(test)]
5018mod median_tests {
5019    #[test]
5020    fn median_of_empty_is_zero_not_a_panic() {
5021        // A crafted table can leave a row/column with zero matched cells; the
5022        // even-count branch would index values[0 - 1] and panic (→ remote crash
5023        // via docling-serve) without the empty guard.
5024        assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
5025        assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
5026        assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
5027    }
5028}
5029
5030#[cfg(test)]
5031mod unreadable_tests {
5032    /// The text-layer path (the wasm build's only one) tells a file nothing
5033    /// can open apart from a PDF that merely has no text layer: garbage is
5034    /// an error about the file, a real PDF converts.
5035    #[test]
5036    fn text_layer_path_reports_an_unreadable_file() {
5037        for bytes in [b"garbage".as_slice(), b"", b"%PDF-1.7\n%%EOF\n"] {
5038            let err = super::convert_text_layer(bytes, "x.pdf").unwrap_err();
5039            assert!(err.to_string().contains("not a readable PDF"), "{err}");
5040        }
5041        let real = std::fs::read(
5042            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5043                .join("../../tests/data/pdf/sources/multi_page.pdf"),
5044        )
5045        .unwrap();
5046        assert!(!super::convert_text_layer(&real, "multi_page.pdf")
5047            .unwrap()
5048            .nodes
5049            .is_empty());
5050    }
5051}
5052
5053#[cfg(test)]
5054mod send_check {
5055    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
5056    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
5057    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
5058    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
5059    fn assert_send<T: Send>() {}
5060
5061    #[test]
5062    fn pipeline_is_send() {
5063        assert_send::<super::Pipeline>();
5064    }
5065}
5066
5067#[cfg(all(test, feature = "ml"))]
5068mod ocr_input_tests {
5069    /// #254: without an `ocr_scale` (or with one equal to the render scale)
5070    /// the OCR reads the page render untouched and the cache stays cold; a
5071    /// different scale builds one resampled view, reuses it across calls, and
5072    /// reports the requested px/pt so cell geometry divides back to points.
5073    #[test]
5074    fn ocr_input_resamples_only_on_a_real_scale_change() {
5075        let img = image::RgbImage::new(200, 100);
5076        let mut cache = None;
5077        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, None);
5078        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
5079        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(2.0));
5080        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
5081
5082        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
5083        assert_eq!((v.width(), v.height(), s), (300, 150, 3.0));
5084        let first = cache.as_ref().map(|c| c as *const image::RgbImage);
5085        let (v, _) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
5086        assert_eq!(
5087            Some(v as *const image::RgbImage),
5088            first,
5089            "cached, not rebuilt"
5090        );
5091
5092        let mut down = None;
5093        let (v, s) = super::ocr_input(&mut down, &img, 2.0, Some(1.0));
5094        assert_eq!((v.width(), v.height(), s), (100, 50, 1.0));
5095    }
5096}
5097
5098#[cfg(all(test, feature = "ml"))]
5099mod text_layer_auto_tests {
5100    use std::path::Path;
5101
5102    fn fixture(rel: &str) -> Vec<u8> {
5103        std::fs::read(
5104            Path::new(env!("CARGO_MANIFEST_DIR"))
5105                .join("../..")
5106                .join(rel),
5107        )
5108        .unwrap()
5109    }
5110
5111    /// The verdict behind `text_layer_only=auto`: a digital PDF's layer
5112    /// carries it, a scan's does not, and garbage is the file's error.
5113    #[test]
5114    fn text_layer_verdict_tells_digital_from_scanned() {
5115        let digital = fixture("tests/data/pdf/sources/multi_page.pdf");
5116        assert!(super::text_layer_has_text(&digital, None).unwrap());
5117        let scanned = fixture("tests/data/scanned/sources/ocr_test_raster.pdf");
5118        assert!(!super::text_layer_has_text(&scanned, None).unwrap());
5119        let err = super::text_layer_has_text(b"garbage", None).unwrap_err();
5120        assert!(err.to_string().contains("not a readable PDF"), "{err}");
5121    }
5122
5123    /// On a digital PDF `auto` is the `no_ocr` path byte for byte — the
5124    /// buffered and the streaming conversion alike — and touches no model:
5125    /// the pipeline below has none to load (`Pipeline::new` loads lazily),
5126    /// so a conversion that reached a worker would fail.
5127    #[test]
5128    fn auto_on_a_digital_pdf_is_the_text_layer_path() {
5129        let bytes = fixture("tests/data/pdf/sources/multi_page.pdf");
5130        let mut only = super::Pipeline::new().unwrap().no_ocr(true);
5131        let mut auto = super::Pipeline::new().unwrap().text_layer_auto(true);
5132        let a = only.convert(&bytes, None, "multi_page.pdf").unwrap();
5133        let b = auto.convert(&bytes, None, "multi_page.pdf").unwrap();
5134        assert!(!a.nodes.is_empty());
5135        assert_eq!(a.export_to_markdown(), b.export_to_markdown());
5136        assert_eq!(a.confidence, b.confidence);
5137        let streamed = |p: &mut super::Pipeline| {
5138            let mut nodes = Vec::new();
5139            p.convert_streaming(&bytes, None, "multi_page.pdf", |page, _| {
5140                nodes.extend(page);
5141                Ok(())
5142            })
5143            .unwrap();
5144            nodes
5145        };
5146        assert_eq!(streamed(&mut only), streamed(&mut auto));
5147    }
5148}
5149
5150#[cfg(all(test, feature = "ml"))]
5151mod bitmap_region_tests {
5152    use super::{bitmap_regions, layout::Region, TextCell};
5153
5154    fn region(label: &'static str, l: f32, t: f32, r: f32, b: f32) -> Region {
5155        Region {
5156            label,
5157            score: 1.0,
5158            l,
5159            t,
5160            r,
5161            b,
5162        }
5163    }
5164
5165    fn cell(text: &str, l: f32, t: f32, r: f32, b: f32) -> TextCell {
5166        TextCell {
5167            text: text.into(),
5168            l,
5169            t,
5170            r,
5171            b,
5172        }
5173    }
5174
5175    const PAGE: [f32; 4] = [0.0, 0.0, 612.0, 792.0];
5176
5177    /// #999: a scanned table with one typed-in value is OCR'd; a text-less
5178    /// region is left to `text_less_regions`; a page without a bitmap, or a
5179    /// region the scan barely touches, is not.
5180    #[test]
5181    fn a_scan_under_a_thin_layer_is_read() {
5182        let table = region("table", 100.0, 300.0, 500.0, 500.0);
5183        let blank = region("text", 100.0, 100.0, 500.0, 120.0);
5184        let cells = [cell("420", 226.0, 444.0, 251.0, 458.0)];
5185        let got = bitmap_regions(&[table.clone(), blank], &cells, &[PAGE]);
5186        assert_eq!(got.len(), 1);
5187        assert_eq!((got[0].label, got[0].t), ("table", 300.0));
5188        assert!(bitmap_regions(std::slice::from_ref(&table), &cells, &[]).is_empty());
5189        // A logo over a corner of the region: not half of it.
5190        let logo = [450.0, 290.0, 520.0, 340.0];
5191        assert!(bitmap_regions(&[table], &cells, &[logo]).is_empty());
5192    }
5193
5194    /// A searchable scan — an invisible layer over the page image — keeps
5195    /// its text layer: a one-line region is a thin band any text explains,
5196    /// a paragraph is covered well past a tenth of its area.
5197    #[test]
5198    fn a_searchable_scan_keeps_its_text_layer() {
5199        let line = region("text", 72.0, 100.0, 540.0, 114.0);
5200        let para = region("text", 72.0, 200.0, 540.0, 260.0);
5201        let cells: Vec<TextCell> = std::iter::once(cell("Heading", 72.0, 100.0, 300.0, 114.0))
5202            .chain((0..4).map(|i| {
5203                let t = 200.0 + 15.0 * i as f32;
5204                cell("body text", 72.0, t, 540.0, t + 12.0)
5205            }))
5206            .collect();
5207        assert!(bitmap_regions(&[line, para], &cells, &[PAGE]).is_empty());
5208    }
5209}
5210
5211/// The worker decides tables-off from an empty TableFormer slot. A missing
5212/// model is a present slot whose load came back empty, and that path keeps
5213/// the table region for the geometric grid.
5214#[cfg(all(test, feature = "ml"))]
5215mod tables_off_gate {
5216    use std::sync::{Arc, Mutex};
5217
5218    use super::{
5219        assemble, layout::Region, pdfium_backend::PdfPage, pdfium_backend::TextCell, DetSlot,
5220        EnrichmentOptions, ImageOutput, OcrSlot, TfSlot, Worker,
5221    };
5222
5223    fn worker(tables: Option<super::SharedTables>) -> Worker {
5224        Worker {
5225            layout: None,
5226            ocr: OcrSlot::Unloaded,
5227            ocr_status: None,
5228            det: Arc::new(Mutex::new(DetSlot::Missing)),
5229            pending_det: Default::default(),
5230            intra: 1,
5231            tables,
5232            classifier: None,
5233            code_formula: None,
5234            enrich: EnrichmentOptions::default(),
5235            no_ocr: false,
5236            force_full_page_ocr: false,
5237            replace_broken_text_layer: false,
5238            picture_ocr: false,
5239            no_text_panels: true,
5240            // No recognizer in the test. The scanned-page test covers the
5241            // cells `ocr_table_words` would have appended before the release.
5242            skip_ocr: true,
5243            ocr_lang: Default::default(),
5244            ocr_engine: Default::default(),
5245            tesseract_lang: None,
5246            ocr_scale: None,
5247            textline_orientation: false,
5248            images: ImageOutput::default(),
5249        }
5250    }
5251
5252    /// #1210: a failed OCR load is reported for every request, and only for
5253    /// a request — a page that may need OCR but has nothing to read does not
5254    /// count, nor touch the slot.
5255    #[test]
5256    fn a_missing_ocr_model_is_recorded_per_request() {
5257        let mut w = worker(None);
5258        w.skip_ocr = false;
5259        w.ocr = OcrSlot::Missing("no model".into());
5260        assert!(w.ocr_model_if(false).unwrap().is_none());
5261        assert_eq!(w.ocr_status, None, "nothing asked for OCR");
5262        assert!(w.ocr_model().unwrap().is_none(), "degrades, not fails");
5263        let unavailable = docling_core::OcrStatus::Unavailable {
5264            reason: "no model".into(),
5265        };
5266        assert_eq!(w.ocr_status, Some(unavailable.clone()));
5267        // The pipeline folds its workers' state and clears it.
5268        let Ok(mut p) = super::Pipeline::new() else {
5269            return;
5270        };
5271        p.primary = Some(w);
5272        assert_eq!(p.take_ocr_status(), Some(unavailable));
5273        assert_eq!(p.take_ocr_status(), None, "taken");
5274        // `skip_ocr` never asks.
5275        let mut skipped = worker(None);
5276        skipped.ocr = OcrSlot::Missing("no model".into());
5277        assert!(skipped.ocr_model().unwrap().is_none());
5278        assert_eq!(skipped.ocr_status, None);
5279    }
5280
5281    fn axle_page() -> (PdfPage, Vec<Region>) {
5282        let cells = vec![TextCell {
5283            text: "Axle:".into(),
5284            l: 40.0,
5285            t: 100.0,
5286            r: 90.0,
5287            b: 112.0,
5288        }];
5289        let regions = vec![Region {
5290            label: "table",
5291            score: 0.9,
5292            l: 30.0,
5293            t: 90.0,
5294            r: 220.0,
5295            b: 180.0,
5296        }];
5297        (PdfPage::from_cells(600.0, 800.0, 1.0, cells), regions)
5298    }
5299
5300    #[test]
5301    fn tables_off_drops_the_table_region() {
5302        let (mut page, regions) = axle_page();
5303        let prepared = worker(None).prepare_page(0, &mut page, regions).unwrap();
5304        assert!(prepared
5305            .regions
5306            .iter()
5307            .all(|r| !assemble::is_table_like(r.label)));
5308        assert!(prepared.regions.iter().any(|r| r.label == "text"));
5309    }
5310
5311    #[test]
5312    fn missing_tableformer_keeps_the_table_region() {
5313        let (mut page, regions) = axle_page();
5314        let tables = Arc::new(Mutex::new(TfSlot::Missing));
5315        let prepared = worker(Some(tables))
5316            .prepare_page(0, &mut page, regions)
5317            .unwrap();
5318        assert!(prepared.regions.iter().any(|r| r.label == "table"));
5319    }
5320}
5321
5322/// #1149: an image input decodes to the page docling reads — transparency
5323/// on white, a 16-bit `tRNS` key included, 16-bit samples truncated.
5324/// docling's `test_transparent_background_is_flattened_onto_white`,
5325/// `test_to_rgb_scales_the_transparency_key_of_16_bit_images` and
5326/// `test_16_bit_grayscale_is_scaled_to_8_bits[PNG]`.
5327#[cfg(all(test, feature = "ml"))]
5328mod image_input_tests {
5329    use super::decode_image_with_max_side;
5330
5331    fn png(img: image::DynamicImage) -> Vec<u8> {
5332        let mut out = Vec::new();
5333        img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
5334            .unwrap();
5335        out
5336    }
5337
5338    /// A PNG chunk inserted before `IDAT`.
5339    fn with_chunk(png: &[u8], kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
5340        let crc = |bytes: &[u8]| {
5341            let mut c = 0xFFFF_FFFFu32;
5342            for &b in bytes {
5343                c ^= u32::from(b);
5344                for _ in 0..8 {
5345                    c = if c & 1 != 0 {
5346                        0xEDB8_8320 ^ (c >> 1)
5347                    } else {
5348                        c >> 1
5349                    };
5350                }
5351            }
5352            !c
5353        };
5354        let idat = png.windows(4).position(|w| w == b"IDAT").unwrap() - 4;
5355        let mut chunk = (data.len() as u32).to_be_bytes().to_vec();
5356        let body = [kind.as_slice(), data].concat();
5357        chunk.extend_from_slice(&body);
5358        chunk.extend_from_slice(&crc(&body).to_be_bytes());
5359        [&png[..idat], &chunk, &png[idat..]].concat()
5360    }
5361
5362    #[test]
5363    fn transparent_inputs_are_flattened_onto_white() {
5364        let mut rgba = image::RgbaImage::from_pixel(8, 8, image::Rgba([0, 0, 0, 0]));
5365        rgba.put_pixel(0, 0, image::Rgba([0, 0, 0, 255]));
5366        let page = decode_image_with_max_side(&png(rgba.into()), 1000).unwrap();
5367        assert_eq!(page.get_pixel(0, 0).0, [0, 0, 0]);
5368        assert_eq!(page.get_pixel(4, 4).0, [255, 255, 255]);
5369
5370        // 16-bit gray, 4000 and 60000, the 60000 key transparent.
5371        let g: image::ImageBuffer<image::Luma<u16>, Vec<u16>> =
5372            image::ImageBuffer::from_fn(2, 1, |x, _| image::Luma([[4000u16, 60000][x as usize]]));
5373        let plain = png(image::DynamicImage::ImageLuma16(g));
5374        let page = decode_image_with_max_side(&plain, 1000).unwrap();
5375        assert_eq!(
5376            (page.get_pixel(0, 0).0, page.get_pixel(1, 0).0),
5377            ([15; 3], [234; 3])
5378        );
5379        let keyed = with_chunk(&plain, b"tRNS", &60000u16.to_be_bytes());
5380        let page = decode_image_with_max_side(&keyed, 1000).unwrap();
5381        assert_eq!(
5382            (page.get_pixel(0, 0).0, page.get_pixel(1, 0).0),
5383            ([15; 3], [255; 3])
5384        );
5385    }
5386}