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
17// Reading-order assembly. Public under `ocr-prep` so the browser pipeline can
18// reuse the geometric table reconstruction and its reliability gate (#157).
19#[cfg(feature = "ocr-prep")]
20pub mod assemble;
21#[cfg(not(feature = "ocr-prep"))]
22mod assemble;
23mod dp_lines;
24#[cfg(feature = "ml")]
25pub mod enrich;
26// Public so sibling crates (e.g. docling-rag's ONNX embedder) can route their
27// own `ort` sessions through the same `DOCLING_RS_EP` selection. Kept as a
28// re-export after the logic moved to the shared `docling-onnx` crate —
29// `docling_pdf::ep::…` remains the stable path downstream crates code against.
30#[cfg(feature = "ml")]
31pub use docling_onnx as ep;
32// Heading-hierarchy stage (#302): PDF font-name style parsing, outline
33// extraction (pure lopdf), and the level-assignment pass. No feature gate on
34// the logic itself — only the glyph style pass needs pdfium (`ml`).
35#[cfg(feature = "ml")]
36pub mod dparse_render;
37mod font_style;
38mod heading_hierarchy;
39pub mod layout;
40#[cfg(feature = "ml")]
41mod mets;
42#[cfg(feature = "ml")]
43mod ocr;
44#[cfg(any(feature = "ml", feature = "ocr-prep"))]
45pub mod ocr_det;
46#[cfg(feature = "ocr-prep")]
47pub mod ocr_prep;
48#[cfg(feature = "ml")]
49mod orient;
50pub mod outline;
51pub mod pdfium_backend;
52#[cfg(feature = "ml")]
53pub mod quality;
54mod reading_order;
55// Pure-Rust region resampling (page→1024px box-average, crop→448 bilinear) —
56// available to the browser TableFormer path (#157 stage 3), not just `ml`.
57#[cfg(feature = "ocr-prep")]
58pub mod resample;
59#[cfg(feature = "ocr-prep")]
60pub mod scanned;
61// Built-in standard-14 font metrics for the pure-Rust text parser (#187) —
62// no feature gate: the wasm/pdf-text path needs them like the native one.
63pub mod pdf_meta;
64#[cfg(feature = "ml")]
65pub mod raster;
66#[cfg(feature = "ml")]
67pub mod render;
68mod std14;
69#[cfg(feature = "ml")]
70pub mod tableformer;
71#[cfg(feature = "ml")]
72mod tesseract;
73pub mod textparse;
74#[cfg(feature = "ocr-prep")]
75pub mod tf_core;
76// docling's TableFormer cell matcher — pure Rust, shared with the browser
77// TableFormer path (#157 stage 3).
78#[cfg(feature = "ocr-prep")]
79pub mod tf_match;
80pub mod timing;
81
82#[cfg(feature = "ml")]
83use std::collections::BTreeMap;
84use std::fmt;
85#[cfg(feature = "ml")]
86use std::sync::mpsc::{sync_channel, Receiver};
87#[cfg(feature = "ml")]
88use std::sync::{Arc, Mutex};
89
90// An execution provider only exists on its OS, and ort's prebuilt ONNX
91// Runtime binaries follow suit — requesting an impossible pairing otherwise
92// surfaces as a cryptic ort-sys linker error ("no builds available that
93// satisfy the requested feature set"). Catch it at type-check time with an
94// actionable message instead.
95#[cfg(all(feature = "coreml", not(target_vendor = "apple")))]
96compile_error!(
97    "the `coreml` execution provider exists only on Apple targets (macOS/iOS). \
98     On Linux use `--features cuda` or `--features tensorrt` (NVIDIA), on \
99     Windows also `--features directml`, or build without EP features for CPU."
100);
101#[cfg(all(feature = "directml", not(target_os = "windows")))]
102compile_error!(
103    "the `directml` execution provider exists only on Windows. On Linux use \
104     `--features cuda` or `--features tensorrt` (NVIDIA), on macOS \
105     `--features coreml`, or build without EP features for CPU."
106);
107#[cfg(all(any(feature = "cuda", feature = "tensorrt"), target_vendor = "apple"))]
108compile_error!(
109    "the `cuda`/`tensorrt` execution providers have no Apple builds (no NVIDIA \
110     support on macOS). Use `--features coreml` there, or build without EP \
111     features for CPU."
112);
113
114use docling_core::DoclingDocument;
115// The env-knob helpers only gate ML-pipeline diagnostics and tuning; the
116// pure text-layer (wasm) build has no call sites.
117#[cfg(feature = "ml")]
118use docling_core::Node;
119#[cfg(feature = "ml")]
120use docling_core::{debug_log, env};
121
122pub use heading_hierarchy::HeadingHierarchyOptions;
123#[cfg(feature = "ml")]
124pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options, convert_mets_gbs_with_pipeline};
125#[cfg(feature = "ml")]
126pub use ocr::{OcrEngine, OcrLang, OcrMode};
127#[cfg(feature = "ml")]
128pub use pdfium_backend::PdfDocument;
129pub use pdfium_backend::{PdfPage, TextCell};
130#[cfg(feature = "ml")]
131pub use tesseract::{lang_arg as tesseract_lang_arg, TesseractOptions};
132// Plain page rasterization (#243) — pdfium only, no models.
133#[cfg(feature = "ml")]
134pub use pdfium_backend::{render_pages, RenderedPage};
135
136/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
137#[derive(Debug)]
138pub enum PdfError {
139    /// pdfium failed to bind, open, or read the document (and, historically,
140    /// any pipeline error outside the models).
141    Pdfium(String),
142    /// The document itself: an object model lopdf cannot read, a page no
143    /// renderer can draw, a page range outside it.
144    Document(String),
145    /// The layout ONNX model failed to load or run.
146    Layout(String),
147    /// The OCR ONNX model failed to load or run.
148    Ocr(String),
149    /// The document budget ([`Pipeline::document_timeout`]) ran out between
150    /// two pages. Internally the sentinel that stops the page walk; a caller
151    /// never sees it from [`Pipeline::convert`] — the conversion returns the
152    /// pages it finished and reports the cut through [`Completion`].
153    Timeout(String),
154}
155
156impl fmt::Display for PdfError {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        match self {
159            PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
160            PdfError::Document(m) => write!(f, "pdf: {m}"),
161            PdfError::Layout(m) => write!(f, "pdf: {m}"),
162            PdfError::Ocr(m) => write!(f, "pdf: {m}"),
163            PdfError::Timeout(m) => write!(f, "pdf: {m}"),
164        }
165    }
166}
167
168/// How a conversion ended: every selected page, or the pages that fit the
169/// document budget (docling's `document_timeout`, `PARTIAL_SUCCESS`).
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub enum Completion {
172    /// Every selected page was processed.
173    Complete,
174    /// The budget ran out: `pages_done` of `pages_selected` pages are in the
175    /// document, the rest were never rendered (or never processed).
176    TimedOut {
177        pages_done: usize,
178        pages_selected: usize,
179        budget: std::time::Duration,
180    },
181}
182
183impl Completion {
184    pub fn timed_out(&self) -> bool {
185        matches!(self, Completion::TimedOut { .. })
186    }
187
188    /// docling's `ErrorItem.error_message` for the cut, `None` when complete.
189    pub fn message(&self) -> Option<String> {
190        match self {
191            Completion::Complete => None,
192            Completion::TimedOut {
193                pages_done,
194                pages_selected,
195                budget,
196            } => Some(format!(
197                "document timeout of {:.3}s exceeded after {pages_done} of {pages_selected} \
198                 pages; the output holds the pages processed",
199                budget.as_secs_f64()
200            )),
201        }
202    }
203}
204
205/// A converted document and how its conversion ended ([`Completion`]).
206#[derive(Debug, Clone)]
207pub struct Converted {
208    pub document: DoclingDocument,
209    pub completion: Completion,
210}
211
212/// Has the document budget run out?
213fn expired(deadline: Option<std::time::Instant>) -> bool {
214    deadline.is_some_and(|d| std::time::Instant::now() >= d)
215}
216
217/// The sentinel the page walks stop on once the budget is gone.
218fn timeout_sentinel() -> PdfError {
219    PdfError::Timeout("document timeout exceeded".into())
220}
221
222impl std::error::Error for PdfError {}
223
224#[cfg(feature = "pdfium")]
225impl From<pdfium_render::prelude::PdfiumError> for PdfError {
226    fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
227        // A failed dlopen means the library this build was asked to use
228        // (`pdfium` feature) is not there. Say what to do instead of leaking
229        // the raw loader error.
230        if matches!(e, pdfium_render::prelude::PdfiumError::LoadLibraryError(_)) {
231            // The loader error pretty-prints over several lines; compact it.
232            let detail = e
233                .to_string()
234                .split_whitespace()
235                .collect::<Vec<_>>()
236                .join(" ");
237            return PdfError::Pdfium(format!(
238                "the pdfium library is not installed. This build's `pdfium` feature \
239                 was asked for it (DOCLING_RS_RENDERER=pdfium, or a file the pure-Rust \
240                 object model cannot read): point PDFIUM_DYNAMIC_LIB_PATH at a directory \
241                 containing the pdfium library, or unset DOCLING_RS_RENDERER — the \
242                 default renderer needs no library. Declarative formats (DOCX, HTML, \
243                 Markdown, …) never need it. [{detail}]"
244            ));
245        }
246        PdfError::Pdfium(e.to_string())
247    }
248}
249
250/// Convert a PDF's **embedded text layer only** — no ONNX, no
251/// threads: the pure-Rust content-stream parser ([`textparse`]) feeds the same
252/// orphan-region assembly the `no_ocr` pipeline flag uses, so text-layer PDFs
253/// come out identical to `--no-ocr` (flat, line-grouped paragraphs in reading
254/// order; no headings/lists/tables/pictures, and no hyperlink recovery).
255///
256/// This is the only conversion entry compiled without the `ml` feature (it is
257/// what a wasm32 build runs). A scanned/image-only PDF (no embedded text
258/// layer) yields an empty document rather than an error, same as `no_ocr` —
259/// callers can detect that and fall back to an OCR-capable build.
260pub fn convert_text_layer(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
261    convert_text_layer_pages(bytes, name, None)
262}
263
264/// [`convert_text_layer`] restricted to a **1-based inclusive** page window
265/// (issue #80's `--pages`); `None` converts everything. The window is
266/// validated the same way as [`Pipeline::pages`]: `first <= last`, 1-based,
267/// and it must select at least one existing page.
268pub fn convert_text_layer_pages(
269    bytes: &[u8],
270    name: &str,
271    pages: Option<(usize, usize)>,
272) -> Result<DoclingDocument, PdfError> {
273    if let Some((first, last)) = pages {
274        if first == 0 || last < first {
275            return Err(PdfError::Pdfium(format!(
276                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
277            )));
278        }
279    }
280    let mut doc = DoclingDocument::new(name);
281    let mut total = 0usize;
282    let parsed = textparse::pdf_text_pages(bytes);
283    // A vestigial layer (a few typed-in form fields over scanned pages) is not
284    // the document's text: return the empty document, which callers already
285    // report as "no text layer" — so an OCR-capable caller falls back to OCR
286    // instead of proudly extracting thirteen characters.
287    if textparse::text_layer_is_vestigial(&parsed) {
288        return Ok(doc);
289    }
290    for (i, page) in parsed.into_iter().enumerate() {
291        total += 1;
292        if let Some((first, last)) = pages {
293            if i + 1 < first || i + 1 > last {
294                continue;
295            }
296        }
297        let mut regions = Vec::new();
298        assemble::add_orphan_regions(&mut regions, &page.cells);
299        let table_rows = vec![None; regions.len()];
300        let enrich_out = vec![None; regions.len()];
301        let (mut nodes, links) = assemble::assemble_page(&page, regions, &table_rows, &enrich_out);
302        assemble::stamp_page_no(&mut nodes, i + 1);
303        doc.nodes.extend(nodes);
304        doc.links.extend(links);
305    }
306    if let Some((first, last)) = pages {
307        if first > total {
308            return Err(PdfError::Pdfium(format!(
309                "page range {first}-{last} is outside the document ({total} page(s))"
310            )));
311        }
312    }
313    assemble::merge_continuations(&mut doc.nodes);
314    Ok(doc)
315}
316
317/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
318/// Defaults to the available parallelism (ort otherwise picks a low number).
319#[cfg(feature = "ml")]
320pub(crate) fn intra_threads() -> usize {
321    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_THREADS").filter(|&n| n > 0) {
322        return n;
323    }
324    env::cpu_budget()
325}
326
327#[cfg(feature = "ml")]
328/// TableFormer's intra-op width (#262): `DOCLING_RS_TF_INTRA` explicitly,
329/// else the shared [`intra_threads`] budget. The shared TF session used to
330/// take the raw host width on top of the already-sized worker pools —
331/// under a cgroup CPU limit that oversubscription showed up as constant
332/// throttling and ~66% higher peak memory (each intra thread carries its own
333/// arena slab); the reporter's 4-CPU/8-core case dropped from 2.2 GB to
334/// 1.3 GB peak by capping this pool.
335pub(crate) fn tf_intra() -> usize {
336    if let Some(n) = env::parse::<usize>("DOCLING_RS_TF_INTRA").filter(|&n| n > 0) {
337        return n;
338    }
339    intra_threads()
340}
341
342#[cfg(feature = "ml")]
343/// True when `DOCLING_RS_FP32` forces the full-precision models even where
344/// an INT8 variant sits next to the fp32 default.
345pub(crate) fn fp32_forced() -> bool {
346    env::flag("DOCLING_RS_FP32")
347}
348
349#[cfg(feature = "ml")]
350/// Should the int8 model defaults be skipped in favor of fp32? Either the
351/// user said so (`DOCLING_RS_FP32`), or a GPU execution provider is selected
352/// (#74) — the int8 exports are QDQ graphs calibrated for CPU kernels and
353/// only conformance-validated there. An explicit `DOCLING_*_ONNX` path
354/// override still wins over this at every call site.
355pub(crate) fn prefer_fp32() -> bool {
356    fp32_forced() || docling_onnx::prefers_fp32()
357}
358
359#[cfg(feature = "ml")]
360/// Resolve a default (CWD-relative) asset path — the shared chain in
361/// [`docling_core::assets`]: CWD, then next to the executable and one level
362/// above it (the `scripts/install/install.sh` layout).
363pub(crate) fn resolve_asset(rel: &str) -> String {
364    docling_core::assets::resolve(rel)
365}
366
367/// One resolved runtime asset — which file a stage would load right now,
368/// given the CWD, the env overrides and the int8/fp32 preference.
369#[cfg(feature = "ml")]
370#[derive(Debug, Clone)]
371pub struct ModelEntry {
372    /// Pipeline stage, e.g. `layout`, `tableformer.decoder`, `ocr.rec`.
373    pub stage: &'static str,
374    /// The resolved path (absolute or CWD-relative, as it will be opened).
375    pub path: String,
376    /// Whether the file exists right now.
377    pub found: bool,
378    /// File size in bytes (0 when missing) — enough to tell an int8 quant
379    /// from an fp32 graph, or a stale model from a re-published one, at a
380    /// glance without hashing gigabytes per request.
381    pub bytes: u64,
382}
383
384/// Resolve the whole runtime model set **without loading anything** — the
385/// exact selection each stage performs at load time (layout honors the
386/// int8/fp32 preference, TableFormer its decoder ranking, OCR the language
387/// pair), plus the pdfium library. docling-serve exposes this at
388/// `/v1/config` and logs it at startup, so "the server picked up different
389/// models" is one `curl` away instead of a mystery of dissolved tables.
390/// Resolution is CWD-relative with an exe-dir fallback, so the answer can
391/// legitimately differ between two working directories.
392#[cfg(feature = "ml")]
393pub fn model_inventory() -> Vec<ModelEntry> {
394    fn entry(stage: &'static str, path: String) -> ModelEntry {
395        let meta = std::fs::metadata(&path).ok();
396        ModelEntry {
397            stage,
398            found: meta.is_some(),
399            bytes: meta.map(|m| m.len()).unwrap_or(0),
400            path,
401        }
402    }
403    let (enc, dec, bbx) = tableformer::resolved_paths();
404    let (rec, dict) = ocr::resolve_rec_pair(ocr::OcrLang::from_env());
405    let pdfium =
406        env::nonempty("PDFIUM_DYNAMIC_LIB_PATH").unwrap_or_else(|| resolve_asset(".pdfium/lib"));
407    vec![
408        entry(
409            "layout",
410            model_path(
411                "DOCLING_LAYOUT_ONNX",
412                ".models/layout_heron.onnx",
413                ".models/layout_heron_int8.onnx",
414            ),
415        ),
416        entry("tableformer.encoder", enc),
417        entry("tableformer.decoder", dec),
418        entry("tableformer.bbox", bbx),
419        entry("ocr.rec", rec),
420        entry("ocr.dict", dict),
421        entry("pdfium", pdfium),
422    ]
423}
424
425/// Resolve a model path: an explicit env override always wins; otherwise the
426/// INT8 variant of the default path when it exists on disk (the quantized
427/// models are conformance-validated — see docs/PDF_CONFORMANCE.md — and load/run
428/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
429/// precision; else the fp32 default.
430#[cfg(feature = "ml")]
431pub(crate) fn model_path(key: &str, fp32_default: &str, int8_default: &str) -> String {
432    if let Some(p) = env::nonempty(key) {
433        return p;
434    }
435    if !prefer_fp32() {
436        let p = resolve_asset(int8_default);
437        if std::path::Path::new(&p).exists() {
438            return p;
439        }
440    }
441    resolve_asset(fp32_default)
442}
443
444/// Decode a standalone image with hard resource limits. A crafted image can
445/// declare enormous dimensions in a few-KB file; `image::load_from_memory`
446/// then tries to allocate the full pixel buffer (e.g. 60000×60000 → ~10 GB),
447/// and allocation failure aborts the whole process, bypassing the per-request
448/// panic catch. The 256 MiB alloc / 30000-px caps below turn that into a
449/// recoverable decode error instead. `DOCLING_RS_MAX_IMAGE_PIXELS` overrides
450/// the per-side pixel cap for the rare legitimately-huge scan.
451///
452/// Gated on `ml`: the only callers (`convert_image`, the METS backend) are
453/// ML-only, and the `image` crate is an `ml`-feature dependency — the
454/// text-layer wasm build has neither.
455#[cfg(feature = "ml")]
456pub(crate) fn decode_image_limited(bytes: &[u8]) -> Result<image::RgbImage, PdfError> {
457    let max_side: u32 = env::parse("DOCLING_RS_MAX_IMAGE_PIXELS").unwrap_or(30_000);
458    decode_image_with_max_side(bytes, max_side)
459}
460
461/// Whether `bytes` is an ISOBMFF HEIF/HEIC container (the `ftyp` brands
462/// iPhones write). Checked by content, not extension — HEIC regularly
463/// arrives misnamed `.jpg`.
464#[cfg(feature = "ml")]
465fn is_heif(bytes: &[u8]) -> bool {
466    bytes.len() >= 12
467        && &bytes[4..8] == b"ftyp"
468        && matches!(
469            &bytes[8..12],
470            b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"hevs" | b"mif1" | b"msf1"
471        )
472}
473
474/// Decode a HEIF/HEIC primary image via libheif (#211). Behind the opt-in
475/// `heif` feature — libheif is a native dependency the default build (and
476/// wasm) must not carry.
477#[cfg(all(feature = "ml", feature = "heif"))]
478fn decode_heif(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
479    use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
480    let err = |e: String| PdfError::Pdfium(format!("heif: {e}"));
481    let ctx = HeifContext::read_from_bytes(bytes).map_err(|e| err(e.to_string()))?;
482    let handle = ctx.primary_image_handle().map_err(|e| err(e.to_string()))?;
483    if handle.width() > max_side || handle.height() > max_side {
484        return Err(err(format!(
485            "image dimensions {}x{} exceed the {max_side}px per-side cap \
486             (DOCLING_RS_MAX_IMAGE_PIXELS overrides)",
487            handle.width(),
488            handle.height()
489        )));
490    }
491    let lib = LibHeif::new();
492    let img = lib
493        .decode(&handle, ColorSpace::Rgb(RgbChroma::Rgb), None)
494        .map_err(|e| err(e.to_string()))?;
495    let (w, h) = (img.width(), img.height());
496    let planes = img.planes();
497    let plane = planes
498        .interleaved
499        .ok_or_else(|| err("no RGB plane".into()))?;
500    let stride = plane.stride;
501    let mut out = image::RgbImage::new(w, h);
502    for (y, row) in out.rows_mut().enumerate() {
503        let src = &plane.data[y * stride..y * stride + w as usize * 3];
504        for (x, px) in row.enumerate() {
505            px.0 = [src[x * 3], src[x * 3 + 1], src[x * 3 + 2]];
506        }
507    }
508    Ok(out)
509}
510
511#[cfg(feature = "ml")]
512fn decode_image_with_max_side(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
513    use image::{ImageDecoder, ImageReader};
514    use std::io::Cursor;
515
516    if is_heif(bytes) {
517        #[cfg(feature = "heif")]
518        return decode_heif(bytes, max_side);
519        #[cfg(not(feature = "heif"))]
520        return Err(PdfError::Pdfium(
521            "HEIC/HEIF input needs a build with the `heif` cargo feature \
522             (rebuild with --features heif; links the system libheif)"
523                .into(),
524        ));
525    }
526
527    let mut limits = image::Limits::default();
528    limits.max_image_width = Some(max_side);
529    limits.max_image_height = Some(max_side);
530    limits.max_alloc = Some(256 * 1024 * 1024);
531
532    let mut reader = ImageReader::new(Cursor::new(bytes))
533        .with_guessed_format()
534        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
535    reader.limits(limits);
536    let mut decoder = reader
537        .into_decoder()
538        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
539    // docling#4247 (2.128, `ImageOps.exif_transpose`): a camera stores the
540    // sensor readout plus an orientation tag rather than rotated pixels, so
541    // a portrait photo would reach layout and OCR on its side unless the tag
542    // is honoured. An unreadable tag is no orientation, not an error.
543    let orientation = decoder
544        .orientation()
545        .unwrap_or(image::metadata::Orientation::NoTransforms);
546    let mut img = image::DynamicImage::from_decoder(decoder)
547        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
548    img.apply_orientation(orientation);
549    Ok(img.into_rgb8())
550}
551
552#[cfg(feature = "ml")]
553/// One page's assembled output: typed nodes plus the page's hyperlinks (kept
554/// separate so pages processed out of order can be stitched back in page
555/// order) and its confidence scores (#183).
556type PageOut = (
557    Vec<Node>,
558    Vec<(String, String)>,
559    docling_core::confidence::PageConfidence,
560);
561
562#[cfg(feature = "ml")]
563/// A page between region resolution and TableFormer: what `prepare_page`
564/// produced and `complete_page` still needs, so a pool worker can park the
565/// page while another worker holds the shared TableFormer (see `Staged`).
566struct Prepared {
567    regions: Vec<layout::Region>,
568    ocr_confs: Vec<f32>,
569    parse: Option<f64>,
570}
571
572#[cfg(feature = "ml")]
573/// A pool worker's per-page outcome. `NeedsTables` is a page whose only
574/// remaining stage is the shared TableFormer, which was busy when the worker
575/// got there: rather than block on the mutex — one worker idle for the
576/// whole of another worker's table decode, ~9.5 s of the 60-page .NET slice
577/// on a 2-worker pool — the worker keeps the page aside, pulls the next one
578/// off the render channel, and comes back once the slot is free. Results
579/// are reassembled by page index anyway, so completion order is free.
580enum Staged {
581    Done(PageOut),
582    NeedsTables(Prepared),
583}
584
585#[cfg(feature = "ml")]
586/// How many pages a pool worker keeps parked on the TableFormer before it
587/// falls back to waiting: each carries its ~5 MB bitmaps, so this bounds the
588/// extra residency to two pages per worker on top of the render channel.
589const MAX_DEFERRED_PAGES: usize = 2;
590
591#[cfg(feature = "ml")]
592/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
593/// lazily on the first table region any worker sees. Tables appear on a
594/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
595/// weights+arenas by the pool size for nothing; a single shared instance keeps
596/// the peak flat regardless of pool width, and a table's structure prediction
597/// is independent of which worker runs it, so output is byte-identical. The
598/// mutex serialises concurrent tables — the shared instance is loaded with the
599/// full intra-op thread budget to compensate (one wide TableFormer instead of
600/// several narrow ones).
601enum TfSlot {
602    /// Not attempted yet (no table seen so far).
603    Unloaded,
604    /// Load attempted, graphs absent — geometric fallback (warned once).
605    Missing,
606    Ready(tableformer::TableFormer),
607}
608
609#[cfg(feature = "ml")]
610type SharedTables = Arc<Mutex<TfSlot>>;
611
612#[cfg(feature = "ml")]
613/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
614/// one instance per pipeline, loaded on the first region that needs it.
615enum EnrichSlot<T> {
616    Unloaded,
617    /// Load attempted, model files absent — enrichment skipped (warned once).
618    Missing,
619    Ready(T),
620}
621
622#[cfg(feature = "ml")]
623type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
624#[cfg(feature = "ml")]
625type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
626
627#[cfg(feature = "ml")]
628/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
629/// flags (`do_picture_classification`, `do_code_enrichment`,
630/// `do_formula_enrichment`). All off by default.
631#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
632pub struct EnrichmentOptions {
633    /// Classify each picture with DocumentFigureClassifier (26 classes).
634    pub picture_classification: bool,
635    /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
636    pub code: bool,
637    /// Decode display formulas to LaTeX with CodeFormulaV2.
638    pub formula: bool,
639}
640
641#[cfg(feature = "ml")]
642impl EnrichmentOptions {
643    fn any(&self) -> bool {
644        self.picture_classification || self.code || self.formula
645    }
646}
647
648#[cfg(feature = "ml")]
649/// The layout model's input for a page: the pypdfium2-exact scale-1.0 page
650/// image (#478) when the renderer produced one, else the legacy stretch of the 2×
651/// bitmap (browser / METS paths) — see [`layout::LayoutSrc`]. Public so the
652/// diagnostic examples feed [`layout::LayoutModel::predict`] the same input
653/// the pipeline does.
654pub fn layout_src(page: &PdfPage) -> layout::LayoutSrc<'_> {
655    match &page.image_layout {
656        Some(img) => layout::LayoutSrc::PageImage(img),
657        None => layout::LayoutSrc::Raw(&page.image),
658    }
659}
660
661#[cfg(feature = "ml")]
662/// The bitmap + px/pt scale the OCR reads (#254, docling#3877's
663/// `OcrOptions.scale`): the page's own render unless `ocr_scale` asks for a
664/// different resolution, where a PIL-bicubic resample of that render is built
665/// once per page (cached in `cache`) and shared by every OCR pass. Resampling
666/// — rather than a second native pdfium render — keeps one code path across
667/// PDF, image, and hOCR inputs and leaves the layout/TableFormer pixels (and
668/// with them the conformance baseline) untouched; the 144-dpi base render is
669/// itself supersampled down from 216 dpi, so an upscaled OCR view loses
670/// little against a native render.
671fn ocr_input<'a>(
672    cache: &'a mut Option<image::RgbImage>,
673    image: &'a image::RgbImage,
674    scale: f32,
675    ocr_scale: Option<f32>,
676) -> (&'a image::RgbImage, f32) {
677    match ocr_scale {
678        Some(s) if (s - scale).abs() > 1e-3 && image.width() > 1 => {
679            let f = s / scale;
680            let img = cache.get_or_insert_with(|| {
681                let dw = ((image.width() as f32 * f).round() as u32).max(1);
682                let dh = ((image.height() as f32 * f).round() as u32).max(1);
683                resample::pil_resize(image, dw, dh, resample::PilFilter::Bicubic)
684            });
685            (img, s)
686        }
687        _ => (image, scale),
688    }
689}
690
691#[cfg(feature = "ml")]
692/// A self-contained set of the per-page models (layout, OCR). Each parallel
693/// page-worker owns its own `Worker` so inference runs concurrently without
694/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
695/// rarely-hit TableFormer is shared (see [`TfSlot`]).
696struct Worker {
697    /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
698    layout: Option<layout::LayoutModel>,
699    ocr: OcrSlot,
700    det: DetSlot,
701    /// Text-detector results computed ahead of a page's OCR pass (#429), keyed
702    /// by page index: the detector reads nothing but the page image, so it
703    /// runs on its own thread while the layout model predicts — see
704    /// [`Self::detect_alongside`] — and the OCR block collects the boxes here
705    /// instead of paying for detection serially.
706    pending_det: BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
707    /// This worker's intra-op thread budget — also the OCR lane count (see
708    /// [`ocr::OcrModel::load_with`]): a pool worker with two threads runs two
709    /// single-thread recognisers, the primary as many as its cores.
710    intra: usize,
711    /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
712    tables: Option<SharedTables>,
713    /// Shared enrichment slots; `None` unless the corresponding flag is on.
714    classifier: Option<SharedClassifier>,
715    code_formula: Option<SharedCodeFormula>,
716    enrich: EnrichmentOptions,
717    /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
718    /// embedded text layer. See [`Pipeline::no_ocr`].
719    no_ocr: bool,
720    /// Discard the embedded text layer and OCR every page. See
721    /// [`Pipeline::force_full_page_ocr`].
722    force_full_page_ocr: bool,
723    /// Keep text-panel pictures as pictures instead of demoting them to
724    /// paragraphs. See [`Pipeline::no_text_panels`].
725    no_text_panels: bool,
726    /// Never run OCR, but keep layout + TableFormer (#244) — docling's
727    /// `do_ocr=False`. See [`Pipeline::skip_ocr`].
728    skip_ocr: bool,
729    /// Which recognition model [`Self::ocr`] loads. See [`Pipeline::ocr_lang`].
730    ocr_lang: ocr::OcrLang,
731    /// Which engine [`Self::ocr`] is (#460). See [`Pipeline::ocr_engine`].
732    ocr_engine: ocr::OcrEngine,
733    /// Tesseract's `-l` argument (#460). See [`Pipeline::tesseract_lang`].
734    tesseract_lang: Option<String>,
735    /// OCR render scale override (px/pt, #254). See [`Pipeline::ocr_scale`].
736    ocr_scale: Option<f32>,
737}
738
739#[cfg(feature = "ml")]
740/// The worker's lazily-loaded OCR recognition model. `Missing` records a
741/// failed load (#244: degradation over failure — a deployment without the OCR
742/// model still gets layout + TableFormer, and OCR-dependent regions stay
743/// empty) so the load isn't retried per page.
744enum OcrSlot {
745    Unloaded,
746    Ready(Recognizer),
747    Missing,
748}
749
750#[cfg(feature = "ml")]
751/// The loaded OCR engine (#460): PP-OCRv3 via ONNX Runtime or the
752/// `tesseract` binary. Both answer the two questions the page assembly asks
753/// — line cells for text regions, word cells for table regions — in page
754/// points with a 0–1 confidence, so the call sites never know which runs.
755pub(crate) enum Recognizer {
756    PpOcr(ocr::OcrModel),
757    Tesseract(tesseract::TesseractOcr),
758}
759
760#[cfg(feature = "ml")]
761impl Recognizer {
762    /// See [`ocr::OcrModel::ocr_page`].
763    fn ocr_page(
764        &mut self,
765        img: &image::RgbImage,
766        regions: &[layout::Region],
767        scale: f32,
768    ) -> Result<Vec<(TextCell, f32)>, String> {
769        match self {
770            Self::PpOcr(m) => m.ocr_page(img, regions, scale),
771            Self::Tesseract(t) => t.ocr_page(img, regions, scale),
772        }
773    }
774
775    /// See [`ocr::OcrModel::ocr_table_words`].
776    fn ocr_table_words(
777        &mut self,
778        img: &image::RgbImage,
779        regions: &[layout::Region],
780        scale: f32,
781    ) -> Result<Vec<(TextCell, f32)>, String> {
782        match self {
783            Self::PpOcr(m) => m.ocr_table_words(img, regions, scale),
784            Self::Tesseract(t) => t.ocr_table_words(img, regions, scale),
785        }
786    }
787}
788
789#[cfg(feature = "ml")]
790/// The text detector (#429), loaded on the first OCR'd page like the
791/// recognizer; `Missing` keeps the pipeline recognition-only.
792enum DetSlot {
793    Unloaded,
794    Ready(ocr_det::DetModel),
795    Missing,
796}
797
798#[cfg(feature = "ml")]
799impl Worker {
800    #[allow(clippy::too_many_arguments)] // mirrors the Pipeline's option set
801    fn load(
802        intra: usize,
803        tables: Option<SharedTables>,
804        enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
805        enrich: EnrichmentOptions,
806        no_ocr: bool,
807        skip_ocr: bool,
808        force_full_page_ocr: bool,
809        no_text_panels: bool,
810        ocr_lang: ocr::OcrLang,
811        ocr_engine: ocr::OcrEngine,
812        tesseract_lang: Option<String>,
813        ocr_scale: Option<f32>,
814    ) -> Result<Self, PdfError> {
815        Ok(Self {
816            layout: if no_ocr {
817                None
818            } else {
819                Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
820            },
821            ocr: OcrSlot::Unloaded,
822            det: DetSlot::Unloaded,
823            pending_det: BTreeMap::new(),
824            intra,
825            tables,
826            classifier: enrich_slots.0,
827            code_formula: enrich_slots.1,
828            enrich,
829            no_ocr,
830            skip_ocr,
831            force_full_page_ocr,
832            no_text_panels,
833            ocr_lang,
834            ocr_engine,
835            tesseract_lang,
836            ocr_scale,
837        })
838    }
839
840    /// The OCR model, or `None` when this conversion must not (or cannot) OCR:
841    /// `skip_ocr` short-circuits, and a failed model load degrades to `None`
842    /// with a one-time warning instead of failing the conversion (#244) —
843    /// unless `force_full_page_ocr` demanded OCR explicitly, where a missing
844    /// model stays a hard error (the text layer was deliberately discarded, so
845    /// degrading would silently emit an empty document).
846    fn ocr_model(&mut self) -> Result<Option<&mut Recognizer>, PdfError> {
847        if self.skip_ocr {
848            return Ok(None);
849        }
850        if matches!(self.ocr, OcrSlot::Unloaded) {
851            let loaded = match self.ocr_engine {
852                ocr::OcrEngine::PpOcr => {
853                    ocr::OcrModel::load_with(self.ocr_lang, self.intra).map(Recognizer::PpOcr)
854                }
855                ocr::OcrEngine::Tesseract => tesseract::TesseractOcr::load(
856                    tesseract::TesseractOptions::from_env(self.tesseract_lang.clone()),
857                    self.intra,
858                )
859                .map(Recognizer::Tesseract),
860            };
861            match loaded {
862                Ok(model) => self.ocr = OcrSlot::Ready(model),
863                Err(e) if self.force_full_page_ocr => return Err(PdfError::Ocr(e)),
864                Err(e) => {
865                    static WARNED: std::sync::Once = std::sync::Once::new();
866                    let hint = match self.ocr_engine {
867                        ocr::OcrEngine::PpOcr => {
868                            "run scripts/install/download_dependencies.sh for the model"
869                        }
870                        ocr::OcrEngine::Tesseract => {
871                            "install tesseract-ocr with the language pack, or use --ocr-engine ppocr"
872                        }
873                    };
874                    WARNED.call_once(|| {
875                        eprintln!(
876                            "warning: OCR model unavailable ({e}); continuing without OCR — \
877                             scanned pages and text inside images will come back empty \
878                             ({hint})"
879                        );
880                    });
881                    self.ocr = OcrSlot::Missing;
882                }
883            }
884        }
885        Ok(match &mut self.ocr {
886            OcrSlot::Ready(model) => Some(model),
887            _ => None,
888        })
889    }
890
891    /// The text detector (#429): loaded on first use, `None` with `skip_ocr`
892    /// or when the model is not installed — recognition stays region-scoped
893    /// then, exactly the pre-#429 behavior, and `DOCLING_RS_DEBUG` says why.
894    fn det_model(&mut self) -> Option<&mut ocr_det::DetModel> {
895        if self.skip_ocr {
896            return None;
897        }
898        if matches!(self.det, DetSlot::Unloaded) {
899            match ocr_det::DetModel::load(self.intra) {
900                Ok(model) => self.det = DetSlot::Ready(model),
901                Err(e) => {
902                    docling_core::debug_log!(
903                        "docling-pdf: text detection unavailable ({e}); OCR stays region-scoped"
904                    );
905                    self.det = DetSlot::Missing;
906                }
907            }
908        }
909        match &mut self.det {
910            DetSlot::Ready(model) => Some(model),
911            _ => None,
912        }
913    }
914
915    /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
916    /// into its nodes and links. Pure given the page (mutates only the worker's
917    /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
918    fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
919        if self.no_ocr {
920            // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
921            // embedded text cells (if any) become flat, line-grouped paragraphs in
922            // reading order via the same orphan-region machinery that normally
923            // rescues text the detector missed — here it rescues *all* of it.
924            // Pages with no embedded text layer (scanned/image-only) yield nothing;
925            // convert those without `no_ocr`.
926            let parse = quality::parse_score(&page.cells);
927            let mut regions = Vec::new();
928            assemble::add_orphan_regions(&mut regions, &page.cells);
929            let table_rows = vec![None; regions.len()];
930            let enrich_out = vec![None; regions.len()];
931            let conf = quality::page_confidence(parse, &regions, &[]);
932            let (nodes, links) = timing::timed("assemble_page", || {
933                assemble::assemble_page(page, regions, &table_rows, &enrich_out)
934            });
935            return Ok((nodes, links, conf));
936        }
937        self.normalize_orientation(n, page)?;
938        let det_pages = self.det_candidates(std::slice::from_ref(&(n, &*page)))?;
939        let regions = {
940            let Self {
941                layout,
942                det,
943                pending_det,
944                ocr_scale,
945                ..
946            } = self;
947            let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
948            let page: &PdfPage = &*page;
949            Self::detect_alongside(det, pending_det, *ocr_scale, &det_pages, || {
950                timing::timed("layout.predict", || {
951                    layout.predict(layout_src(page), page.width, page.height)
952                })
953            })
954        }
955        .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
956        self.finish_page(n, page, regions)
957    }
958
959    /// The pages of a batch the text detector should sweep (#429): bitmap
960    /// pages (no text layer) on a run with OCR and the detector available —
961    /// loading both lazily here so the concurrent run below needs no `self`.
962    fn det_candidates<'p>(
963        &mut self,
964        pages: &[(usize, &'p PdfPage)],
965    ) -> Result<Vec<(usize, &'p PdfPage)>, PdfError> {
966        let scanned: Vec<(usize, &PdfPage)> = pages
967            .iter()
968            .filter(|(_, p)| p.cells.is_empty() && p.image.width() > 1)
969            .copied()
970            .collect();
971        if scanned.is_empty() || self.ocr_model()?.is_none() || self.det_model().is_none() {
972            return Ok(Vec::new());
973        }
974        Ok(scanned)
975    }
976
977    /// Run `layout` on the calling thread while the text detector sweeps
978    /// `det_pages` on another (#429): the detector only reads each page's
979    /// image, layout only reads the pages too, and the two sessions are
980    /// independent, so on a scanned page the ~0.7 s detection hides behind
981    /// layout instead of adding to it. Results land in `pending_det` for the
982    /// OCR block; a detector failure is recorded per page and surfaces there.
983    fn detect_alongside<T>(
984        det: &mut DetSlot,
985        pending_det: &mut BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
986        ocr_scale: Option<f32>,
987        det_pages: &[(usize, &PdfPage)],
988        layout: impl FnOnce() -> T,
989    ) -> T {
990        let DetSlot::Ready(det) = det else {
991            return layout();
992        };
993        if det_pages.is_empty() {
994            return layout();
995        }
996        std::thread::scope(|s| {
997            let handle = s.spawn(move || {
998                det_pages
999                    .iter()
1000                    .map(|&(n, page)| {
1001                        let mut view = None;
1002                        let (img, _) = ocr_input(&mut view, &page.image, page.scale, ocr_scale);
1003                        (n, timing::timed("ocr.det", || det.detect(img)))
1004                    })
1005                    .collect::<Vec<_>>()
1006            });
1007            let out = layout();
1008            match handle.join() {
1009                Ok(results) => pending_det.extend(results),
1010                Err(_) => {
1011                    for &(n, _) in det_pages {
1012                        pending_det.insert(n, Err("ocr-det: detection thread panicked".into()));
1013                    }
1014                }
1015            }
1016            out
1017        })
1018    }
1019
1020    /// Content-based orientation normalization (#225), before any inference:
1021    /// a physically rotated scan (sideways phone photo, landscape-fed sheet)
1022    /// has `/Rotate 0`, so the metadata pass in `extract_page` never fires and
1023    /// layout+OCR would read a sideways raster. Only pages with no text layer
1024    /// at all are probed (a digital page's raster is upright by construction,
1025    /// and its cells — not its pixels — carry the text); the detected angle
1026    /// composes with any `/Rotate` normalization through the same
1027    /// [`PdfPage::unrotate`] + display-space assembly mapping. Detection is
1028    /// evidence-gated and degrades to a no-op — see [`orient`].
1029    fn normalize_orientation(&mut self, n: usize, page: &mut PdfPage) -> Result<(), PdfError> {
1030        let scanned =
1031            page.cells.is_empty() && page.word_cells.is_empty() && page.code_cells.is_empty();
1032        if self.no_ocr || self.skip_ocr || !scanned || page.image.width() <= 1 || !orient::enabled()
1033        {
1034            return Ok(());
1035        }
1036        // The probe reads text through the OCR model; without one (missing —
1037        // #244 degradation) the page stays as rendered.
1038        let Some(ocr) = self.ocr_model()? else {
1039            return Ok(());
1040        };
1041        let deg = timing::timed("orient.detect", || {
1042            orient::detect(&page.image, ocr, page.scale)
1043        });
1044        if deg != 0 {
1045            debug_log!(
1046                "docling-pdf: page {}: content rotated {deg}° in the raster; \
1047                 un-rotating before layout/OCR",
1048                n + 1
1049            );
1050            page.unrotate(deg);
1051        }
1052        Ok(())
1053    }
1054
1055    /// Layout-detect a whole batch of pages with one inference call (issue #73),
1056    /// then run each page's remaining stages (OCR / TableFormer / enrichment /
1057    /// assembly) per page. Index-aligned with `items`; a layout failure fails
1058    /// every page in the batch (they shared the one inference call).
1059    fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<Staged, PdfError>> {
1060        if self.no_ocr {
1061            // No layout model to batch — the text-layer-only path is per page.
1062            return items
1063                .iter_mut()
1064                .map(|(n, page)| {
1065                    let n = *n;
1066                    self.process(n, page).map(Staged::Done)
1067                })
1068                .collect();
1069        }
1070        // Orientation-normalize every scanned page before the shared layout
1071        // call — the batched inference must see upright bitmaps too (#225).
1072        for (n, page) in items.iter_mut() {
1073            let n = *n;
1074            if let Err(e) = self.normalize_orientation(n, page) {
1075                // Model-load failure — every page in the batch needs the same
1076                // model, so they all fail alike (mirrors the layout-error arm).
1077                let msg = e.to_string();
1078                return items
1079                    .iter()
1080                    .map(|_| Err(PdfError::Ocr(msg.clone())))
1081                    .collect();
1082            }
1083        }
1084        let inputs: Vec<(layout::LayoutSrc<'_>, f32, f32)> = items
1085            .iter()
1086            .map(|(_, page)| (layout_src(page), page.width, page.height))
1087            .collect();
1088        let refs: Vec<(usize, &PdfPage)> = items.iter().map(|(n, page)| (*n, page)).collect();
1089        let det_pages = match self.det_candidates(&refs) {
1090            Ok(p) => p,
1091            Err(e) => {
1092                let msg = e.to_string();
1093                return items
1094                    .iter()
1095                    .map(|_| Err(PdfError::Ocr(msg.clone())))
1096                    .collect();
1097            }
1098        };
1099        let batched = {
1100            let Self {
1101                layout,
1102                det,
1103                pending_det,
1104                ocr_scale,
1105                ..
1106            } = self;
1107            let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
1108            Self::detect_alongside(det, pending_det, *ocr_scale, &det_pages, || {
1109                timing::timed("layout.predict", || layout.predict_batch(&inputs))
1110            })
1111        };
1112        match batched {
1113            Ok(all) => items
1114                .iter_mut()
1115                .zip(all)
1116                .map(|((n, page), regions)| self.stage_page(*n, page, regions))
1117                .collect(),
1118            Err(e) => items
1119                .iter()
1120                .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
1121                .collect(),
1122        }
1123    }
1124
1125    /// A pool worker's main loop: pull rendered pages off the shared channel
1126    /// (whatever is already there, up to the layout batch size), process them,
1127    /// and hand each finished page — or its error — to `deliver`, which returns
1128    /// `false` to stop early (the streaming consumer went away). Returns when
1129    /// the channel is closed and every page this worker took is delivered.
1130    ///
1131    /// Pages whose TableFormer turn would have to wait are parked (see
1132    /// `Staged`) and retried before every new pull; while any are parked the
1133    /// pull is non-blocking, so an empty channel means the worker waits for
1134    /// the TableFormer rather than for the renderer. The parking budget
1135    /// (`MAX_DEFERRED_PAGES`) bounds resident bitmaps; past it the worker waits
1136    /// like the serial path. Output is independent of completion order — the
1137    /// callers reassemble by page index.
1138    fn run_pool(
1139        &mut self,
1140        work_rx: &Mutex<Receiver<(usize, PdfPage)>>,
1141        layout_batch: usize,
1142        deadline: Option<std::time::Instant>,
1143        mut deliver: impl FnMut(usize, Result<PageOut, PdfError>) -> bool,
1144    ) {
1145        use std::sync::mpsc::TryRecvError;
1146        let mut deferred: std::collections::VecDeque<(usize, PdfPage, Prepared)> =
1147            std::collections::VecDeque::new();
1148        loop {
1149            // The document budget (#497), checked between pages: once it is
1150            // spent, every page still queued or parked is reported as timed
1151            // out instead of processed — the renderer stops feeding at the
1152            // same check, so the queue drains quickly.
1153            if expired(deadline) {
1154                while let Some((idx, _, _)) = deferred.pop_front() {
1155                    if !deliver(idx, Err(timeout_sentinel())) {
1156                        return;
1157                    }
1158                }
1159                let rx = work_rx.lock().unwrap();
1160                loop {
1161                    match rx.recv() {
1162                        Ok((idx, _page)) => {
1163                            if !deliver(idx, Err(timeout_sentinel())) {
1164                                return;
1165                            }
1166                        }
1167                        Err(_) => return,
1168                    }
1169                }
1170            }
1171            // Any parked page the slot has since freed up for, oldest first.
1172            let mut i = 0;
1173            while i < deferred.len() {
1174                let (_, page, prepared) = &deferred[i];
1175                match self.table_rows_try(page, &prepared.regions) {
1176                    Some(rows) => {
1177                        let (idx, mut page, prepared) = deferred.remove(i).expect("index in range");
1178                        if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1179                            return;
1180                        }
1181                    }
1182                    None => i += 1,
1183                }
1184            }
1185            // Hold the receiver lock only for the recv (plus a non-blocking drain
1186            // up to the layout batch size); release before the (long) per-page
1187            // work so other workers can pull concurrently.
1188            let mut batch: Vec<(usize, PdfPage)> = Vec::new();
1189            let mut closed = false;
1190            {
1191                let rx = work_rx.lock().unwrap();
1192                let first = if deferred.is_empty() {
1193                    rx.recv().map_err(|_| TryRecvError::Disconnected)
1194                } else {
1195                    rx.try_recv()
1196                };
1197                match first {
1198                    Ok(item) => {
1199                        batch.push(item);
1200                        while batch.len() < layout_batch {
1201                            match rx.try_recv() {
1202                                Ok(item) => batch.push(item),
1203                                Err(_) => break,
1204                            }
1205                        }
1206                    }
1207                    Err(TryRecvError::Empty) => {}
1208                    Err(TryRecvError::Disconnected) => closed = true,
1209                }
1210            }
1211            if batch.is_empty() {
1212                // Nothing new rendered (or the channel is closed): wait our turn
1213                // on the oldest parked page instead.
1214                match deferred.pop_front() {
1215                    Some((idx, mut page, prepared)) => {
1216                        let rows = self.table_rows_blocking(&page, &prepared.regions);
1217                        if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1218                            return;
1219                        }
1220                        continue;
1221                    }
1222                    None if closed => return,
1223                    None => continue,
1224                }
1225            }
1226            let outs = self.process_batch(&mut batch);
1227            for ((idx, mut page), out) in batch.into_iter().zip(outs) {
1228                let delivered = match out {
1229                    Ok(Staged::Done(out)) => deliver(idx, Ok(out)),
1230                    Ok(Staged::NeedsTables(prepared)) => {
1231                        if deferred.len() < MAX_DEFERRED_PAGES {
1232                            deferred.push_back((idx, page, prepared));
1233                            true
1234                        } else {
1235                            let rows = self.table_rows_blocking(&page, &prepared.regions);
1236                            deliver(idx, self.complete_page(idx, &mut page, prepared, rows))
1237                        }
1238                    }
1239                    Err(e) => deliver(idx, Err(e)),
1240                };
1241                if !delivered {
1242                    return;
1243                }
1244            }
1245        }
1246    }
1247
1248    /// Everything after layout detection: per-label confidence thresholds,
1249    /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
1250    /// TableFormer, enrichment, and page assembly. The serial path: waits
1251    /// for the shared TableFormer when a table needs it.
1252    fn finish_page(
1253        &mut self,
1254        n: usize,
1255        page: &mut PdfPage,
1256        regions: Vec<layout::Region>,
1257    ) -> Result<PageOut, PdfError> {
1258        let prepared = self.prepare_page(n, page, regions)?;
1259        let table_rows = self.table_rows_blocking(page, &prepared.regions);
1260        self.complete_page(n, page, prepared, table_rows)
1261    }
1262
1263    /// The pool path: like [`finish_page`](Self::finish_page), except that a
1264    /// page whose TableFormer turn would have to wait comes back as
1265    /// [`Staged::NeedsTables`] for the worker loop to park (see `Staged`).
1266    fn stage_page(
1267        &mut self,
1268        n: usize,
1269        page: &mut PdfPage,
1270        regions: Vec<layout::Region>,
1271    ) -> Result<Staged, PdfError> {
1272        let prepared = self.prepare_page(n, page, regions)?;
1273        match self.table_rows_try(page, &prepared.regions) {
1274            Some(rows) => Ok(Staged::Done(self.complete_page(n, page, prepared, rows)?)),
1275            None => Ok(Staged::NeedsTables(prepared)),
1276        }
1277    }
1278
1279    /// Does this page need the shared TableFormer at all? Table-free pages
1280    /// never touch (or load) it.
1281    fn needs_tables(&self, regions: &[layout::Region]) -> bool {
1282        self.tables.is_some() && regions.iter().any(|r| assemble::is_table_like(r.label))
1283    }
1284
1285    /// TableFormer structure for every table region of the page, on an
1286    /// already-locked slot (loading the model on first use). Tables serialise
1287    /// on this mutex, so the one instance gets the shared thread budget
1288    /// (quota-aware, #262) — DOCLING_RS_TF_INTRA narrows it further where the
1289    /// memory-per-thread tradeoff matters more than table latency.
1290    fn predict_tables(
1291        guard: &mut TfSlot,
1292        page: &PdfPage,
1293        regions: &[layout::Region],
1294    ) -> Vec<Option<tf_core::TableGrid>> {
1295        let mut table_rows: Vec<Option<tf_core::TableGrid>> = vec![None; regions.len()];
1296        if matches!(*guard, TfSlot::Unloaded) {
1297            *guard = match tableformer::TableFormer::load_with(tf_intra()) {
1298                Some(tf) => TfSlot::Ready(tf),
1299                None => TfSlot::Missing,
1300            };
1301        }
1302        if let TfSlot::Ready(tf) = guard {
1303            // One 1024-px frame per page, shared by all of its tables, and one
1304            // call for all of them: with the dynamic-batch decoder their
1305            // decode steps are shared (each step costs about the same for B
1306            // tables as for one).
1307            let page1024 = tableformer::TableFormer::page_1024(&page.image);
1308            let (idx, boxes): (Vec<usize>, Vec<[f32; 4]>) = regions
1309                .iter()
1310                .enumerate()
1311                .filter(|(_, r)| assemble::is_table_like(r.label))
1312                .map(|(i, r)| (i, [r.l, r.t, r.r, r.b]))
1313                .unzip();
1314            let rows =
1315                tf.predict_tables_on(page.image.height(), &page1024, &boxes, &page.word_cells);
1316            for (i, grid) in idx.into_iter().zip(rows) {
1317                table_rows[i] = grid;
1318            }
1319        }
1320        table_rows
1321    }
1322
1323    /// Table structure for the page, waiting for the shared slot if another
1324    /// worker holds it (else geometric fallback downstream when there is no
1325    /// TableFormer at all). The `tableformer` timing stage here includes any
1326    /// wait.
1327    fn table_rows_blocking(
1328        &self,
1329        page: &PdfPage,
1330        regions: &[layout::Region],
1331    ) -> Vec<Option<tf_core::TableGrid>> {
1332        match self.tables.as_ref().filter(|_| self.needs_tables(regions)) {
1333            Some(slot) => timing::timed("tableformer", || {
1334                Self::predict_tables(&mut slot.lock().unwrap(), page, regions)
1335            }),
1336            None => vec![None; regions.len()],
1337        }
1338    }
1339
1340    /// Non-blocking variant: `None` when the slot is held by another worker
1341    /// right now — the caller parks the page and tries again later.
1342    fn table_rows_try(
1343        &self,
1344        page: &PdfPage,
1345        regions: &[layout::Region],
1346    ) -> Option<Vec<Option<tf_core::TableGrid>>> {
1347        let Some(slot) = self.tables.as_ref().filter(|_| self.needs_tables(regions)) else {
1348            return Some(vec![None; regions.len()]);
1349        };
1350        match slot.try_lock() {
1351            Ok(mut guard) => Some(timing::timed("tableformer", || {
1352                Self::predict_tables(&mut guard, page, regions)
1353            })),
1354            Err(std::sync::TryLockError::WouldBlock) => None,
1355            Err(std::sync::TryLockError::Poisoned(e)) => panic!("TableFormer slot poisoned: {e}"),
1356        }
1357    }
1358
1359    /// The stages before TableFormer: fp32 escalation, per-label confidence
1360    /// thresholds, overlap resolution, orphan-text recovery, OCR for cell-less
1361    /// pages, in-picture text and table-word recognition.
1362    fn prepare_page(
1363        &mut self,
1364        n: usize,
1365        page: &mut PdfPage,
1366        regions: Vec<layout::Region>,
1367    ) -> Result<Prepared, PdfError> {
1368        // Force-OCR is exactly "pretend the text layer is not there": clear
1369        // every cell kind the extractors produced before anything reads them,
1370        // and the ordinary no-text-layer machinery below — full-page OCR,
1371        // OCR-fed TableFormer matching — takes over unchanged. (`no_ocr` wins
1372        // when both are set, mirroring docling, where `force_full_page_ocr`
1373        // is a sub-option of `do_ocr`; the no-ocr path never reaches here.)
1374        // Done here rather than in `process` so the batched layout path
1375        // (`process_batch` → `finish_page`) honors the flag too.
1376        // Parse quality is scored on the extracted text layer before force-OCR
1377        // discards it (docling's page-preprocessing stage runs before OCR too,
1378        // so its parse_score also reflects the original text layer).
1379        let parse = quality::parse_score(&page.cells);
1380        // Recognition confidences of every OCR'd cell on this page → ocr_score.
1381        let mut ocr_confs: Vec<f32> = Vec::new();
1382        // The bitmap the OCR reads (#254): with `ocr_scale` set, a resample of
1383        // the page render at the requested px/pt, built lazily on the first
1384        // OCR use so non-OCR pages never pay for it. Copied out of `self` up
1385        // front — the OCR sites hold `self.ocr_model()`'s mutable borrow.
1386        let ocr_scale = self.ocr_scale;
1387        let mut ocr_view: Option<image::RgbImage> = None;
1388        if self.force_full_page_ocr {
1389            page.cells.clear();
1390            page.code_cells.clear();
1391            page.word_cells.clear();
1392        }
1393        // Quant-robustness guard: the default int8 layout graph keeps its
1394        // confidences near the 0.5 label thresholds, and a different CPU's
1395        // quantized kernels can flip a whole page's detections under them —
1396        // tables and paragraphs then dissolve into orphan one-liners while the
1397        // same build converts the page perfectly elsewhere. When a dense
1398        // digital page ends up with detections covering almost none of its
1399        // text cells, re-run that one page on the fp32 graph (lazy-loaded,
1400        // auto-int8 selection only) and keep whichever detections cover more.
1401        let mut regions = regions;
1402        if !page.cells.is_empty() {
1403            let thresholded = |rs: &[layout::Region]| -> Vec<layout::Region> {
1404                rs.iter()
1405                    .filter(|r| r.score >= layout::label_threshold(r.label))
1406                    .cloned()
1407                    .collect()
1408            };
1409            let text_cells = page
1410                .cells
1411                .iter()
1412                .filter(|c| !c.text.trim().is_empty())
1413                .count();
1414            let cov = assemble::layout_cell_coverage(&thresholded(&regions), &page.cells);
1415            if text_cells >= 15 && cov < 0.5 {
1416                let retry = self
1417                    .layout
1418                    .as_mut()
1419                    .expect("layout model loaded unless no_ocr")
1420                    .predict_fp32_fallback(layout_src(page), page.width, page.height)
1421                    .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
1422                if let Some(retry) = retry {
1423                    let cov2 = assemble::layout_cell_coverage(&thresholded(&retry), &page.cells);
1424                    if cov2 > cov {
1425                        debug_log!(
1426                            "docling-pdf: page {}: int8 layout covered {:.0}% of the text \
1427                             cells; the fp32 retry covers {:.0}% — using it",
1428                            n + 1,
1429                            cov * 100.0,
1430                            cov2 * 100.0
1431                        );
1432                        regions = retry;
1433                    }
1434                }
1435            }
1436        }
1437        // docling's LayoutPostprocessor drops each detection below its label's
1438        // confidence threshold (stricter than the 0.3 base the predictor keeps),
1439        // before any overlap resolution. This removes the low-confidence tables /
1440        // pictures / list-items that otherwise double-emit or mis-classify.
1441        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1442            for r in &regions {
1443                eprintln!(
1444                    "DBG raw {} {:.2} [{:.0},{:.0},{:.0},{:.0}]",
1445                    r.label, r.score, r.l, r.t, r.r, r.b
1446                );
1447            }
1448        }
1449        regions.retain(|r| r.score >= layout::label_threshold(r.label));
1450        // docling's full-page picture filter and same-label picture dedup run
1451        // on the thresholded detections, before overlap resolution: a picture
1452        // that is the whole page goes (its text reads out as text), and a
1453        // figure proposed both whole and as sub-panels collapses to one box
1454        // (see `dedup_pictures`).
1455        assemble::drop_full_page_pictures(&mut regions, page.width, page.height);
1456        assemble::dedup_pictures(&mut regions);
1457        // Resolve overlapping detections once, before OCR.
1458        let mut regions = assemble::resolve(regions);
1459        // Emit text the detector missed as orphan text regions (docling parity).
1460        assemble::add_orphan_regions(&mut regions, &page.cells);
1461        // Drop phantom empty low-confidence picture boxes (docling parity).
1462        assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
1463        // A regular region fully inside a surviving table/index/picture is that
1464        // special's child (a cell / in-figure label), not a separate block —
1465        // remove it so it isn't emitted twice (docling parity).
1466        assemble::drop_contained_regulars(&mut regions);
1467        // A one-line paragraph in the bottom margin under a body-less heading
1468        // is that heading's text, not furniture (deliberate deviation).
1469        assemble::reclaim_heading_body_footers(&mut regions, page.width);
1470        // No text layer → recognise text from the page image via OCR.
1471        let ocred = page.cells.is_empty();
1472        // Lines the text detector found outside every layout region (#429).
1473        let mut det_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1474        if ocred {
1475            // Region-scoped OCR recognizes each region's crop, so two regular
1476            // regions over the same ink would read it twice — a low-score
1477            // paragraph box over the high-score line boxes `greedy` keeps.
1478            // Collapse such groups to one region first; a digital
1479            // page resolves the same overlap through cell ownership in
1480            // `fit_regions_to_cells` and needs nothing here.
1481            assemble::merge_overlapping_regulars(&mut regions);
1482            // `None` = `skip_ocr` or a missing model (#244): the page keeps
1483            // its layout regions (and TableFormer structure below) with no
1484            // recognized text, instead of failing the conversion.
1485            if let Some(ocr) = self.ocr_model()? {
1486                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1487                let cells = timing::timed("ocr.page", || ocr.ocr_page(img, &regions, scl))
1488                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1489                ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
1490                page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
1491                // Table interiors carry no words yet: region-scoped OCR skips
1492                // table labels, and a scanned page has no pdfium text layer — so
1493                // TableFormer's cell matcher got an empty word list and the table
1494                // dissolved (#173). Recognize the table regions' word crops
1495                // (mirroring the browser scanned path): `word_cells` feeds the
1496                // matcher, and the same cells join `cells` so the geometric
1497                // fallback and the table's region text see them too.
1498                if regions.iter().any(|r| assemble::is_table_like(r.label)) {
1499                    let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1500                    let words = timing::timed("ocr.table_words", || {
1501                        ocr.ocr_table_words(img, &regions, scl)
1502                    })
1503                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1504                    ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1505                    let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1506                    page.cells.extend(words.iter().cloned());
1507                    page.word_cells = words;
1508                }
1509            }
1510            // docling's OCR engines detect text lines over the whole bitmap
1511            // and every line becomes a cell, so text the layout model gave no
1512            // region — a diagram's labels, a stamp, a margin note — still
1513            // reads out as orphan text. Region-scoped recognition above stays
1514            // the source inside layout regions; the detector (#429) adds only
1515            // the lines no recognized cell already covers, and the orphan pass
1516            // below places them (those inside a kept picture or table become
1517            // that special's silent children, as upstream).
1518            if self.ocr_model()?.is_some() {
1519                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1520                // Usually computed already, alongside layout (see
1521                // `detect_alongside`); a page that reached OCR another way
1522                // detects here.
1523                // Degradation over failure: a detector that loaded but cannot
1524                // run (a damaged file, an allocation failure) costs the page
1525                // its detected lines, not its conversion — the region-scoped
1526                // pass above is complete on its own.
1527                let detected = match self.pending_det.remove(&n) {
1528                    Some(result) => result,
1529                    None => match self.det_model() {
1530                        Some(det) => timing::timed("ocr.det", || det.detect(img)),
1531                        None => Ok(Vec::new()),
1532                    },
1533                }
1534                .unwrap_or_else(|e| {
1535                    docling_core::debug_log!(
1536                        "docling-pdf: page {}: text detection failed ({e}); keeping the \
1537                         region-scoped OCR only",
1538                        n + 1
1539                    );
1540                    Vec::new()
1541                });
1542                docling_core::debug_log!(
1543                    "docling-pdf: page {}: text detector found {} line(s): {:?}",
1544                    n + 1,
1545                    detected.len(),
1546                    detected
1547                        .iter()
1548                        .map(|d| (
1549                            d.l.round(),
1550                            d.t.round(),
1551                            d.r.round(),
1552                            d.b.round(),
1553                            (d.score * 100.0).round() / 100.0
1554                        ))
1555                        .collect::<Vec<_>>()
1556                );
1557                let uncovered = ocr_det::uncovered_lines(&detected, scl, &regions, &page.cells);
1558                docling_core::debug_log!(
1559                    "docling-pdf: page {}: {} of {} detected line(s) not covered by the region pass",
1560                    n + 1,
1561                    uncovered.len(),
1562                    detected.len()
1563                );
1564                if let (false, Some(ocr)) = (uncovered.is_empty(), self.ocr_model()?) {
1565                    let scored =
1566                        timing::timed("ocr.det_lines", || ocr.ocr_page(img, &uncovered, scl))
1567                            .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1568                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1569                    det_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1570                    page.cells.extend(det_cells.iter().cloned());
1571                }
1572            }
1573        }
1574        // Region-scoped OCR skips `picture` interiors, and a digital page's
1575        // text layer cannot see into an embedded raster either — so a figure
1576        // that is really a text box (terms-and-conditions exported as an
1577        // image) lost its words on every page kind. Python docling OCRs the
1578        // bitmap-covered areas of *every* page — even digital ones — once they
1579        // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
1580        // already do. Recognize the big text-less crops here too; the panel
1581        // demotion / orphan recovery below place the lines.
1582        let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1583        {
1584            let page_area = (page.width * page.height).max(1.0);
1585            let has_text = |r: &layout::Region| {
1586                page.cells.iter().any(|c| {
1587                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1588                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1589                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1590                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
1591                })
1592            };
1593            // A captioned picture can never demote to a text panel (see
1594            // recover_text_panels), and on digital pages its speculative OCR
1595            // would be discarded anyway — don't pay for it.
1596            let captioned = |r: &layout::Region| {
1597                regions.iter().any(|c| {
1598                    c.label == "caption"
1599                        && c.r.min(r.r) - c.l.max(r.l) > 0.0
1600                        && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
1601                })
1602            };
1603            let bare: Vec<layout::Region> = regions
1604                .iter()
1605                .filter(|r| {
1606                    r.label == "picture"
1607                        && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
1608                        && !has_text(r)
1609                        && (ocred || !captioned(r))
1610                })
1611                .map(|r| layout::Region {
1612                    label: "text",
1613                    ..r.clone()
1614                })
1615                .collect();
1616            // Speculative OCR (#244): with `skip_ocr` or no model, big bare
1617            // pictures simply stay pictures.
1618            if let (false, Some(ocr)) = (bare.is_empty(), self.ocr_model()?) {
1619                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1620                let scored = timing::timed("ocr.pictures", || ocr.ocr_page(img, &bare, scl))
1621                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1622                // Speculative in-picture OCR counts toward ocr_score only on
1623                // OCR'd pages, where the recognized lines actually join the
1624                // output; on a digital page they may be discarded below.
1625                if ocred {
1626                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1627                }
1628                pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1629                page.cells.extend(pic_cells.iter().cloned());
1630            }
1631        }
1632        let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
1633        // A "picture" that is really a colored text panel — dense, wide,
1634        // multi-line — reads out as paragraphs instead of shipping as pixels;
1635        // sparse in-picture text (a chart's labels) keeps the crop and stays
1636        // inside it as the picture's silent children (docling parity, #200).
1637        // `no_text_panels` (#173) opts out entirely for image-extraction
1638        // workflows.
1639        if !self.no_text_panels {
1640            assemble::recover_text_panels(&mut regions, &page.cells);
1641        }
1642        // On an OCR'd page, in-picture text that did NOT demote its picture
1643        // mostly stays silent, exactly as in docling: its postprocess step
1644        // "Remove regular clusters that are included in wrappers" walks
1645        // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
1646        // >80 % contained in a kept picture becomes that picture's child and
1647        // never reaches the serializer. Only border-straddlers (≤80 %
1648        // containment) survive as text. Emitting *everything* here used to
1649        // splice a chart's OCR'd axis ticks into the body text right next to
1650        // the image chunk (#200) — so the orphan pass places the recognized
1651        // lines, the containment drop re-runs for the in-table ones, and
1652        // `assemble_page` nests the in-picture ones under their picture
1653        // (JSON-only children, `assemble::picture_parents`).
1654        if ocred && (!pic_cells.is_empty() || !det_cells.is_empty()) {
1655            // Pictures (and wrappers) no longer count as claimers (#165), so
1656            // the plain orphan pass places the recognized lines directly —
1657            // the detector's lines (#429) the same way.
1658            assemble::add_orphan_regions(&mut regions, &pic_cells);
1659            assemble::add_orphan_regions(&mut regions, &det_cells);
1660            assemble::drop_contained_regulars(&mut regions);
1661        } else if !ocred && !pic_cells.is_empty() {
1662            // Digital page, picture kept: its speculative OCR cells must not
1663            // linger in the text-cell set (they were appended at the tail).
1664            let kept: Vec<layout::Region> = regions
1665                .iter()
1666                .filter(|r| r.label == "picture")
1667                .cloned()
1668                .collect();
1669            let tail = page.cells.split_off(cells_before_pic_ocr);
1670            page.cells.extend(tail.into_iter().filter(|c| {
1671                !kept.iter().any(|r| {
1672                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1673                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1674                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1675                    ix * iy / ca > 0.5
1676                })
1677            }));
1678        }
1679        // A text-less *table* detected inside a picture on a digital page — a
1680        // screenshot of a table (2203's Figure 10) — has no text layer and no
1681        // scanned-path OCR to feed it, so its grid used to serialize empty and
1682        // the whole element vanished. docling OCRs bitmap-covered areas on
1683        // every page kind and its table cluster collects those cells; mirror
1684        // the scanned path for exactly these tables: recognize word crops and
1685        // feed them to the TableFormer matcher and the cell set.
1686        if !ocred {
1687            let has_text = |t: &layout::Region| {
1688                page.cells.iter().any(|c| {
1689                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1690                    let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
1691                    let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
1692                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
1693                })
1694            };
1695            let in_picture = |t: &layout::Region| {
1696                regions.iter().any(|r| {
1697                    r.label == "picture" && {
1698                        let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
1699                        let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
1700                        let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
1701                        ix * iy / ta > 0.5
1702                    }
1703                })
1704            };
1705            let pic_tables: Vec<layout::Region> = regions
1706                .iter()
1707                .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
1708                .cloned()
1709                .collect();
1710            // Same degradation as above: without OCR the in-picture table
1711            // keeps its structure (TableFormer is geometry-driven) minus text.
1712            if let (false, Some(ocr)) = (pic_tables.is_empty(), self.ocr_model()?) {
1713                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1714                let words = timing::timed("ocr.table_words", || {
1715                    ocr.ocr_table_words(img, &pic_tables, scl)
1716                })
1717                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1718                ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1719                let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1720                page.cells.extend(words.iter().cloned());
1721                page.word_cells.extend(words);
1722            }
1723        }
1724        // The cells are final: fit every regular region to the cells it
1725        // claims and fold the orphans it now surrounds (#419), before
1726        // TableFormer and the reading order see the boxes.
1727        assemble::fit_regions_to_cells(&mut regions, &page.cells);
1728        Ok(Prepared {
1729            regions,
1730            ocr_confs,
1731            parse,
1732        })
1733    }
1734
1735    /// The stages after TableFormer: enrichment, the page confidence report and
1736    /// assembly into typed nodes.
1737    fn complete_page(
1738        &mut self,
1739        n: usize,
1740        page: &mut PdfPage,
1741        prepared: Prepared,
1742        table_rows: Vec<Option<tf_core::TableGrid>>,
1743    ) -> Result<PageOut, PdfError> {
1744        let Prepared {
1745            regions,
1746            ocr_confs,
1747            parse,
1748        } = prepared;
1749        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1750            for (i, r) in regions.iter().enumerate() {
1751                eprintln!(
1752                    "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
1753                    r.label,
1754                    r.score,
1755                    r.l,
1756                    r.t,
1757                    r.r,
1758                    r.b,
1759                    table_rows[i]
1760                        .as_ref()
1761                        .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
1762                );
1763            }
1764            eprintln!(
1765                "DBG cells={} words={}",
1766                page.cells.len(),
1767                page.word_cells.len()
1768            );
1769        }
1770        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
1771        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
1772        // shape as TableFormer — one lazily-loaded instance per pipeline, only
1773        // ever locked when a page actually has a matching region.
1774        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
1775        if let Some(slot) = self.classifier.as_ref() {
1776            if regions.iter().any(|r| r.label == "picture") {
1777                timing::timed("picture_classifier", || {
1778                    let mut guard = slot.lock().unwrap();
1779                    if matches!(*guard, EnrichSlot::Unloaded) {
1780                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
1781                            Some(m) => EnrichSlot::Ready(m),
1782                            None => EnrichSlot::Missing,
1783                        };
1784                    }
1785                    if let EnrichSlot::Ready(model) = &mut *guard {
1786                        for (i, r) in regions.iter().enumerate() {
1787                            if r.label != "picture" {
1788                                continue;
1789                            }
1790                            let Some(crop) = assemble::crop_region_scaled(
1791                                page,
1792                                [r.l, r.t, r.r, r.b],
1793                                enrich::CLASSIFIER_SCALE,
1794                            ) else {
1795                                continue;
1796                            };
1797                            match model.classify(&crop) {
1798                                Ok(classes) => {
1799                                    enrich_out[i] =
1800                                        Some(assemble::Enrichment::PictureClasses(classes));
1801                                }
1802                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1803                            }
1804                        }
1805                    }
1806                });
1807            }
1808        }
1809        if let Some(slot) = self.code_formula.as_ref() {
1810            let wants = |label: &str| {
1811                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
1812            };
1813            if regions.iter().any(|r| wants(r.label)) {
1814                timing::timed("code_formula", || {
1815                    let mut guard = slot.lock().unwrap();
1816                    if matches!(*guard, EnrichSlot::Unloaded) {
1817                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
1818                            Some(m) => EnrichSlot::Ready(m),
1819                            None => EnrichSlot::Missing,
1820                        };
1821                    }
1822                    if let EnrichSlot::Ready(model) = &mut *guard {
1823                        for (i, r) in regions.iter().enumerate() {
1824                            if !wants(r.label) {
1825                                continue;
1826                            }
1827                            // docling crops the postprocessed cluster box — the
1828                            // union of the region's text cells, not the raw
1829                            // detector box — expanded by 18% per side, at
1830                            // ~120 dpi.
1831                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
1832                                .unwrap_or([r.l, r.t, r.r, r.b]);
1833                            let (w, h) = (br - bl, bb - bt);
1834                            let ex = enrich::CODE_FORMULA_EXPANSION;
1835                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
1836                            let Some(crop) = assemble::crop_region_scaled(
1837                                page,
1838                                bbox,
1839                                enrich::CODE_FORMULA_SCALE,
1840                            ) else {
1841                                continue;
1842                            };
1843                            let kind = if r.label == "code" {
1844                                enrich::CodeFormulaKind::Code
1845                            } else {
1846                                enrich::CodeFormulaKind::Formula
1847                            };
1848                            match model.predict(&crop, kind) {
1849                                Ok(text) => {
1850                                    enrich_out[i] = Some(match kind {
1851                                        enrich::CodeFormulaKind::Code => {
1852                                            let (code, language) =
1853                                                enrich::extract_code_language(&text);
1854                                            assemble::Enrichment::Code {
1855                                                language,
1856                                                text: code,
1857                                            }
1858                                        }
1859                                        enrich::CodeFormulaKind::Formula => {
1860                                            assemble::Enrichment::Formula { latex: text }
1861                                        }
1862                                    });
1863                                }
1864                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1865                            }
1866                        }
1867                    }
1868                });
1869            }
1870        }
1871        // Score the final region set (docling assigns layout_score over the
1872        // postprocessed clusters — the page elements assemble_page emits,
1873        // which leave out the regulars nested in a picture as its children).
1874        let parents = assemble::picture_parents(&regions);
1875        let elements: Vec<layout::Region> = regions
1876            .iter()
1877            .zip(&parents)
1878            .filter(|(_, p)| p.is_none())
1879            .map(|(r, _)| r.clone())
1880            .collect();
1881        let conf = quality::page_confidence(parse, &elements, &ocr_confs);
1882        let (nodes, links) = timing::timed("assemble_page", || {
1883            assemble::assemble_page(page, regions, &table_rows, &enrich_out)
1884        });
1885        Ok((nodes, links, conf))
1886    }
1887}
1888
1889#[cfg(feature = "ml")]
1890/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
1891/// so on a typical machine two threads per worker (sharing one in-cache copy of
1892/// the weights) extracts more throughput than one fat model or many single-thread
1893/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
1894fn pdf_intra() -> usize {
1895    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
1896        return n;
1897    }
1898    if intra_threads() >= 2 {
1899        2
1900    } else {
1901        1
1902    }
1903}
1904
1905#[cfg(feature = "ml")]
1906/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
1907/// overrides; otherwise size the pool so `workers × intra ≈ cores`.
1908///
1909/// The pool scales with the machine (#324 follow-up testing): the old hard cap
1910/// of 4 left most of a many-core box idle — on a 16-core M4 Max, 10 workers
1911/// measured ~1.2× over the capped pool (10.0 → 8.5 s on a 130-page document,
1912/// byte-identical output). The ceiling of 16 is a memory bound, not a
1913/// performance one: each worker holds its own layout/OCR sessions (~0.4 GB),
1914/// so a worst-case pool stays under ~6.5 GB even on a ≥32-core host — and
1915/// docling-serve's per-request pools sit behind its `DOCLING_RS_MAX_MEMORY_MB`
1916/// admission control besides. Machines with 4 or fewer effective threads keep
1917/// the exact old sizing (`threads / intra`, min 1).
1918fn pdf_worker_count() -> usize {
1919    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
1920        return n;
1921    }
1922    (intra_threads() / pdf_intra()).clamp(1, 16)
1923}
1924
1925#[cfg(feature = "ml")]
1926/// Max pages a worker layout-detects with one batched inference call (issue
1927/// #73). Workers drain the work channel opportunistically up to this size —
1928/// whatever is already rendered gets batched, so batching never *waits* for
1929/// pages and adds no latency when rendering is the bottleneck.
1930///
1931/// Default: per-page (1) on the CPU provider, 4 when a GPU provider is
1932/// selected (#338). The old "4 on 8+ cores" CPU default was a hypothesis —
1933/// that single-session amortization pays off with a wider thread budget —
1934/// and every actual CPU measurement lands the other way: a 4-core x86 box
1935/// runs the 9-page 2206.01062 fixture in 8.5 s/conv at batch=1 vs 9.3 s at
1936/// batch=4 (re-measured for #338; the original 8.1 vs 9.3 agrees), and the
1937/// issue-#338 report measured batch=1 ~2× faster on a 16-core M4 Max at
1938/// every worker count — batching only adds cache pressure once workers
1939/// saturate the cores. On a GPU the per-call dispatch overhead is real and
1940/// batching amortizes it, so the GPU default stays. Output is bit-identical
1941/// at every batch size, so this is purely a throughput knob.
1942/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides either way; `1` = per-page.
1943pub(crate) fn pdf_layout_batch() -> usize {
1944    env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
1945        .filter(|&n| n > 0)
1946        .unwrap_or_else(|| if docling_onnx::prefers_fp32() { 4 } else { 1 })
1947}
1948
1949#[cfg(feature = "ml")]
1950/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
1951/// the serial primary (running its model on every core) is faster than fanning out
1952/// — the helper pool's one-time model-load cost only pays off once enough pages
1953/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
1954fn pdf_parallel_min() -> usize {
1955    env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
1956        .filter(|&n| n > 0)
1957        .unwrap_or(6)
1958}
1959
1960#[cfg(feature = "ml")]
1961/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
1962/// so a single-page / small / image / METS input is converted at full intra-op
1963/// speed with no pool to load. A document with enough pages instead fans out
1964/// across a **pool** of narrower workers processed concurrently. Both load lazily
1965/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
1966pub struct Pipeline {
1967    /// Full-intra worker for the serial path; loaded on first serial use.
1968    primary: Option<Worker>,
1969    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
1970    /// path; loaded on first multi-page use and cached.
1971    pool: Vec<Worker>,
1972    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
1973    tables: SharedTables,
1974    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
1975    classifier: SharedClassifier,
1976    code_formula: SharedCodeFormula,
1977    /// Desired pool size for multi-page documents.
1978    target_workers: usize,
1979    /// Page count at/above which the parallel pool is worth its load cost.
1980    parallel_min: usize,
1981    /// Skip loading/running TableFormer; table regions fall back to geometric
1982    /// reconstruction. See [`Pipeline::no_table_former`].
1983    no_table_former: bool,
1984    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
1985    no_ocr: bool,
1986    /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
1987    skip_ocr: bool,
1988    /// OCR every page even when it carries a text layer. See
1989    /// [`Pipeline::force_full_page_ocr`].
1990    force_full_page_ocr: bool,
1991    /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
1992    no_text_panels: bool,
1993    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
1994    enrich: EnrichmentOptions,
1995    /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
1996    page_range: Option<(usize, usize)>,
1997    /// OCR recognition language. See [`Pipeline::ocr_lang`].
1998    ocr_lang: ocr::OcrLang,
1999    /// Which OCR engine runs (#460). See [`Pipeline::ocr_engine`].
2000    ocr_engine: ocr::OcrEngine,
2001    /// Tesseract's languages (#460). See [`Pipeline::tesseract_lang`].
2002    tesseract_lang: Option<String>,
2003    /// Which regions feed the OCR (#254). See [`Pipeline::ocr_mode`].
2004    ocr_mode: ocr::OcrMode,
2005    /// OCR render scale override in px/pt (#254). See [`Pipeline::ocr_scale`].
2006    ocr_scale: Option<f32>,
2007    /// Heading-level inference (#302). See [`Pipeline::heading_hierarchy`].
2008    heading_hierarchy: HeadingHierarchyOptions,
2009    /// Optional per-page progress hook `(done, selected_total)`, invoked after
2010    /// each page finishes on both the serial and parallel buffered paths. Set
2011    /// by the CLI batch mode for dot-progress; `None` costs nothing.
2012    progress: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>,
2013    /// Per-document wall-clock budget (docling's `document_timeout`, #497).
2014    /// See [`Pipeline::document_timeout`].
2015    document_timeout: Option<std::time::Duration>,
2016}
2017
2018#[cfg(feature = "ml")]
2019impl Pipeline {
2020    /// Construct the pipeline. Models load lazily on first use (full-intra primary
2021    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
2022    /// loaded that a given document doesn't need.
2023    pub fn new() -> Result<Self, PdfError> {
2024        Ok(Self {
2025            primary: None,
2026            pool: Vec::new(),
2027            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
2028            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
2029            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
2030            target_workers: pdf_worker_count(),
2031            parallel_min: pdf_parallel_min(),
2032            no_table_former: false,
2033            no_ocr: false,
2034            skip_ocr: false,
2035            force_full_page_ocr: false,
2036            no_text_panels: false,
2037            enrich: EnrichmentOptions::default(),
2038            page_range: None,
2039            ocr_lang: ocr::OcrLang::from_env(),
2040            ocr_engine: ocr::OcrEngine::from_env(),
2041            tesseract_lang: None,
2042            ocr_mode: ocr::OcrMode::from_env(),
2043            ocr_scale: ocr::scale_from_env(),
2044            heading_hierarchy: HeadingHierarchyOptions::default(),
2045            progress: None,
2046            document_timeout: None,
2047        })
2048    }
2049
2050    /// A wall-clock budget for each document (docling's
2051    /// `PipelineOptions.document_timeout`, #497; `None` = unlimited, the
2052    /// default). The budget starts when a conversion starts and is checked
2053    /// cooperatively between pages: once it is spent, no further page is
2054    /// rendered or processed, the pages already finished are assembled into
2055    /// the document, and the outcome says so (`Completion::TimedOut`, which
2056    /// the converter reports as `PartialSuccess` with a timeout error, the
2057    /// way docling does). A page in flight finishes — the check costs
2058    /// nothing inside a page, and a single-page document (an image) is never
2059    /// cut. For a long-lived pipeline use
2060    /// [`set_document_timeout`](Self::set_document_timeout) before each
2061    /// conversion.
2062    pub fn document_timeout(mut self, timeout: Option<std::time::Duration>) -> Self {
2063        self.document_timeout = timeout;
2064        self
2065    }
2066
2067    /// In-place variant of [`document_timeout`](Self::document_timeout) for a
2068    /// warm pipeline — set it before every conversion so no request inherits
2069    /// a previous one's budget.
2070    pub fn set_document_timeout(&mut self, timeout: Option<std::time::Duration>) {
2071        self.document_timeout = timeout;
2072    }
2073
2074    /// The deadline of a conversion starting now, from the configured budget.
2075    fn deadline(&self) -> Option<std::time::Instant> {
2076        self.document_timeout.map(|t| std::time::Instant::now() + t)
2077    }
2078
2079    /// The [`Completion`] of a walk that processed `done` of `selected` pages.
2080    fn completion(&self, timed_out: bool, done: usize, selected: usize) -> Completion {
2081        match (timed_out, self.document_timeout) {
2082            (true, Some(budget)) => Completion::TimedOut {
2083                pages_done: done,
2084                pages_selected: selected,
2085                budget,
2086            },
2087            _ => Completion::Complete,
2088        }
2089    }
2090
2091    /// Infer section-header levels after assembly (#302, docling's
2092    /// `HeadingHierarchyModel`): PDF bookmarks > legal/outline numbering >
2093    /// font style, off by default — see [`HeadingHierarchyOptions`]. Pure
2094    /// post-processing configuration; for a warm pipeline use
2095    /// [`set_heading_hierarchy`](Self::set_heading_hierarchy).
2096    pub fn heading_hierarchy(mut self, opts: HeadingHierarchyOptions) -> Self {
2097        self.heading_hierarchy = opts;
2098        self
2099    }
2100
2101    /// In-place variant of [`heading_hierarchy`](Self::heading_hierarchy) for
2102    /// a long-lived pipeline (docling-serve's warm instance) — like
2103    /// [`set_pages`](Self::set_pages), set it before every conversion so no
2104    /// request inherits a previous one's choice.
2105    pub fn set_heading_hierarchy(&mut self, opts: HeadingHierarchyOptions) {
2106        self.heading_hierarchy = opts;
2107    }
2108
2109    /// Run the enabled heading-hierarchy stage (#302) on an assembled
2110    /// document: gather the outline (bookmarks) and the per-page glyph styles
2111    /// on demand, then assign levels in place. `bytes` is `None` on paths
2112    /// with no PDF behind them (standalone images, METS) — those degrade to
2113    /// the numbering signal, exactly like docling without parsed pages.
2114    fn apply_heading_hierarchy(&self, nodes: &mut [Node], bytes: Option<&[u8]>) {
2115        let opts = &self.heading_hierarchy;
2116        if !opts.enabled {
2117            return;
2118        }
2119        let outline = match bytes {
2120            Some(bytes) if opts.use_bookmarks => outline::extract_outline(bytes),
2121            _ => Vec::new(),
2122        };
2123        let styles = match bytes {
2124            Some(bytes) if opts.use_style => {
2125                let pages = heading_hierarchy::heading_pages(nodes);
2126                textparse::glyph_styles(bytes, &pages)
2127            }
2128            _ => Default::default(),
2129        };
2130        heading_hierarchy::apply(nodes, &outline, &styles, opts);
2131    }
2132
2133    /// Install (or clear) the per-page progress hook: called with
2134    /// `(pages_done, pages_selected)` after each page completes during
2135    /// [`convert`](Self::convert). Shared with the parallel workers, so the
2136    /// callback must be cheap and thread-safe.
2137    pub fn set_progress(&mut self, cb: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>) {
2138        self.progress = cb;
2139    }
2140
2141    /// Convert only pages `first..=last` (**1-based**, like the page numbers a
2142    /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
2143    /// skipped before rasterization, so the cost is proportional to the window,
2144    /// not the document. `last` past the end of the document clamps; a window
2145    /// that selects no pages at all (`first` beyond the last page) is an error
2146    /// at convert time. `None` (the default) converts everything.
2147    pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
2148        self.page_range = range;
2149        self
2150    }
2151
2152    /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
2153    /// (e.g. docling-serve's warm instance) that applies a per-request window
2154    /// without rebuilding — unlike the model switches, the window is pure
2155    /// configuration. Set it before every conversion; it stays until changed.
2156    pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
2157        self.page_range = range;
2158    }
2159
2160    /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
2161    /// for the multilingual docling-conformance model. `None` keeps the
2162    /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
2163    /// first conversion; for a warm pipeline use
2164    /// [`set_ocr_lang`](Self::set_ocr_lang).
2165    pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
2166        self.set_ocr_lang(lang);
2167        self
2168    }
2169
2170    /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
2171    /// pipeline (docling-serve's warm instance). Unlike the page window this
2172    /// is a *model* switch: any worker whose cached recognition model was
2173    /// loaded for a different language drops it, to be lazily reloaded on the
2174    /// next OCR-needing page (cheap — the rec models are ~10 MB).
2175    pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
2176        let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
2177        self.ocr_lang = lang;
2178        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2179            if worker.ocr_lang != lang {
2180                worker.ocr_lang = lang;
2181                worker.ocr = OcrSlot::Unloaded;
2182            }
2183        }
2184    }
2185
2186    /// Which OCR engine recognizes text (#460, see [`OcrEngine`]): the
2187    /// built-in PP-OCRv3 recognizer by default, or the system `tesseract`
2188    /// binary (docling's `TesseractCliOcrOptions`) — same layout-region
2189    /// crops, same cells; Tesseract does its own line/word segmentation and
2190    /// reads orientation from its OSD. `None` keeps the process default
2191    /// (`DOCLING_RS_OCR_ENGINE`, else PP-OCR). Set before the first
2192    /// conversion; for a warm pipeline use
2193    /// [`set_ocr_engine`](Self::set_ocr_engine).
2194    pub fn ocr_engine(mut self, engine: Option<ocr::OcrEngine>) -> Self {
2195        self.set_ocr_engine(engine);
2196        self
2197    }
2198
2199    /// In-place variant of [`ocr_engine`](Self::ocr_engine): a model switch
2200    /// like [`set_ocr_lang`](Self::set_ocr_lang) — workers holding the other
2201    /// engine drop it, to be lazily reloaded.
2202    pub fn set_ocr_engine(&mut self, engine: Option<ocr::OcrEngine>) {
2203        let engine = engine.unwrap_or_else(ocr::OcrEngine::from_env);
2204        self.ocr_engine = engine;
2205        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2206            if worker.ocr_engine != engine {
2207                worker.ocr_engine = engine;
2208                worker.ocr = OcrSlot::Unloaded;
2209            }
2210        }
2211    }
2212
2213    /// Tesseract's languages (#460): the `-l` argument, tessdata stems joined
2214    /// with `+` — build it from an `ocr_lang` value with
2215    /// [`tesseract_lang_arg`], which also maps BCP-47 tags and the PP-OCR
2216    /// codes. `None` runs Tesseract's default (`eng`). Ignored under the
2217    /// PP-OCR engine, whose language is [`ocr_lang`](Self::ocr_lang). For a
2218    /// warm pipeline use [`set_tesseract_lang`](Self::set_tesseract_lang).
2219    pub fn tesseract_lang(mut self, lang: Option<String>) -> Self {
2220        self.set_tesseract_lang(lang);
2221        self
2222    }
2223
2224    /// In-place variant of [`tesseract_lang`](Self::tesseract_lang): a model
2225    /// switch like [`set_ocr_lang`](Self::set_ocr_lang) — a worker whose
2226    /// Tesseract was probed for other languages drops it.
2227    pub fn set_tesseract_lang(&mut self, lang: Option<String>) {
2228        self.tesseract_lang = lang.clone();
2229        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2230            if worker.tesseract_lang != lang {
2231                worker.tesseract_lang = lang.clone();
2232                if worker.ocr_engine == ocr::OcrEngine::Tesseract {
2233                    worker.ocr = OcrSlot::Unloaded;
2234                }
2235            }
2236        }
2237    }
2238
2239    /// Resolve the configured 1-based window against a page count into the
2240    /// 0-based inclusive form the backend walks, validating it selects at
2241    /// least one existing page.
2242    fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
2243        let Some((first, last)) = self.page_range else {
2244            return Ok(None);
2245        };
2246        if first == 0 || last < first {
2247            return Err(PdfError::Pdfium(format!(
2248                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
2249            )));
2250        }
2251        if first > total {
2252            return Err(PdfError::Pdfium(format!(
2253                "page range {first}-{last} is outside the document ({total} page(s))"
2254            )));
2255        }
2256        Ok(Some((first - 1, last.min(total) - 1)))
2257    }
2258
2259    /// Enable the opt-in enrichment passes (docling's
2260    /// `do_picture_classification` / `do_code_enrichment` /
2261    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
2262    /// the first matching region; a missing model warns once and is skipped.
2263    /// Set before the first conversion (no effect on already-loaded workers).
2264    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
2265        self.enrich = opts;
2266        self
2267    }
2268
2269    /// Skip loading and running the TableFormer table-structure model. Table
2270    /// regions still get emitted, but reconstructed geometrically from cell
2271    /// positions instead of via the ONNX model's predicted structure — faster
2272    /// (no model load, no per-table inference) at the cost of table fidelity.
2273    /// No effect if a worker is already loaded; set this before the first
2274    /// conversion.
2275    pub fn no_table_former(mut self, disable: bool) -> Self {
2276        self.no_table_former = disable;
2277        self
2278    }
2279
2280    /// Keep every detected `picture` region as a picture. By default an
2281    /// *uncaptioned* picture that reads like a dense, uniform text panel (a
2282    /// terms-and-conditions box exported as an image) is demoted into
2283    /// paragraphs (#157); a chart the layout mislabels can still trip that
2284    /// heuristic on scanned pages, and image-extraction workflows may simply
2285    /// want every crop — this flag disables the demotion entirely (#173).
2286    /// No effect on already-loaded workers; set before the first conversion.
2287    pub fn no_text_panels(mut self, disable: bool) -> Self {
2288        self.no_text_panels = disable;
2289        self
2290    }
2291
2292    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
2293    /// inference of any kind. The PDF's embedded text cells are grouped by line
2294    /// and emitted as plain paragraphs in reading order: no headings, lists,
2295    /// tables, code blocks, or pictures, since that structure comes from the
2296    /// layout model. The fastest possible PDF path, but pages with no embedded
2297    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
2298    /// without this flag. Implies `no_table_former`. No effect if a worker is
2299    /// already loaded; set this before the first conversion.
2300    pub fn no_ocr(mut self, disable: bool) -> Self {
2301        self.no_ocr = disable;
2302        self
2303    }
2304
2305    /// Never run OCR, but keep layout detection and TableFormer — docling's
2306    /// independent `do_ocr=False` (#244), the counterpart of
2307    /// [`no_table_former`](Self::no_table_former). Unlike
2308    /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
2309    /// output — headings, tables, pictures, reading order — is preserved;
2310    /// only text that exists solely as pixels is lost: scanned pages come
2311    /// back with their regions empty, and the speculative OCR of large
2312    /// embedded images never runs. The OCR model is never loaded. Ignored
2313    /// when `no_ocr` is set (there is no OCR to skip);
2314    /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
2315    /// mirroring docling where forcing is a sub-option of `do_ocr`.
2316    pub fn skip_ocr(mut self, disable: bool) -> Self {
2317        self.skip_ocr = disable;
2318        self
2319    }
2320
2321    /// OCR every page from its rendered image even when the page carries an
2322    /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
2323    /// for text layers that exist but lie: broken encodings, subset fonts with
2324    /// garbage mappings, a scanned form with a few typed-in fields. Ignored
2325    /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
2326    /// `force_full_page_ocr` is a sub-option of `do_ocr`).
2327    pub fn force_full_page_ocr(mut self, force: bool) -> Self {
2328        self.force_full_page_ocr = force;
2329        self
2330    }
2331
2332    /// Which document regions feed the OCR — docling's `OcrMode` (#254). The
2333    /// default (`default` = `pdf_aware_layout_regions`) is the standard
2334    /// text-layer-aware behavior; `full_page`/`layout_regions` discard the
2335    /// text layer like [`force_full_page_ocr`](Self::force_full_page_ocr)
2336    /// (see [`ocr::OcrMode`] for why both map onto it). Whichever of the flag
2337    /// and the mode demands forcing wins, mirroring docling's
2338    /// `force_full_page_ocr` → `mode=full_page` bridge. `None` keeps the
2339    /// process default (`DOCLING_RS_OCR_MODE`, else `default`).
2340    pub fn ocr_mode(mut self, mode: Option<ocr::OcrMode>) -> Self {
2341        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
2342        self
2343    }
2344
2345    /// In-place variants of [`force_full_page_ocr`](Self::force_full_page_ocr),
2346    /// [`ocr_mode`](Self::ocr_mode) and [`ocr_scale`](Self::ocr_scale) for a
2347    /// long-lived pipeline (docling-serve's warm instance): all three are pure
2348    /// per-worker configuration — no model reloads — so they apply per request
2349    /// like [`set_pages`](Self::set_pages). Set them before every conversion so
2350    /// no request inherits a previous one's choice.
2351    pub fn set_force_full_page_ocr(&mut self, force: bool) {
2352        self.force_full_page_ocr = force;
2353        self.sync_ocr_config();
2354    }
2355
2356    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
2357    pub fn set_ocr_mode(&mut self, mode: Option<ocr::OcrMode>) {
2358        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
2359        self.sync_ocr_config();
2360    }
2361
2362    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
2363    pub fn set_ocr_scale(&mut self, scale: Option<f32>) {
2364        self.ocr_scale = scale
2365            .filter(|s| s.is_finite() && *s > 0.0)
2366            .or_else(ocr::scale_from_env);
2367        self.sync_ocr_config();
2368    }
2369
2370    /// Whether page extraction should decode the text layer at all. Forced
2371    /// full-page OCR (the flag or `ocr_mode=full_page|layout_regions`) clears
2372    /// every extracted cell unread, so the decode is skipped outright —
2373    /// docling#4061's `skip_cell_extraction` (2.122). `no_ocr` wins over the
2374    /// forcing, as everywhere else: its fast path *is* the text layer.
2375    fn extract_text_layer(&self) -> bool {
2376        self.no_ocr || !(self.force_full_page_ocr || self.ocr_mode.forces_full_page())
2377    }
2378
2379    /// Push the current OCR forcing/scale choice onto already-loaded workers
2380    /// (new workers read it at [`Worker::load`]).
2381    fn sync_ocr_config(&mut self) {
2382        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2383        let scale = self.ocr_scale;
2384        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2385            worker.force_full_page_ocr = force;
2386            worker.ocr_scale = scale;
2387        }
2388    }
2389
2390    /// OCR render scale in pixels per PDF point — docling's `OcrOptions.scale`
2391    /// (#254, upstream docling#3877; their default 3 = 216 dpi). `None`
2392    /// (default: `DOCLING_RS_OCR_SCALE`, else unset) feeds the recognizer the
2393    /// pipeline's own page render (2.0 px/pt = 144 dpi); a different value
2394    /// resamples that render for the OCR input only — layout and TableFormer
2395    /// keep their pinned-resolution pixels, so the conformance baseline never
2396    /// moves. Lower it when the source raster is already high-resolution and
2397    /// upscaling degrades recognition; raise it toward docling's 216 dpi for
2398    /// parity experiments. Non-positive values are ignored.
2399    pub fn ocr_scale(mut self, scale: Option<f32>) -> Self {
2400        self.ocr_scale = scale
2401            .filter(|s| s.is_finite() && *s > 0.0)
2402            .or_else(ocr::scale_from_env);
2403        self
2404    }
2405
2406    /// The shared TableFormer slot handed to each worker, or `None` when the
2407    /// pipeline options skip TableFormer entirely.
2408    fn tables_slot(&self) -> Option<SharedTables> {
2409        if self.no_table_former || self.no_ocr {
2410            None
2411        } else {
2412            Some(Arc::clone(&self.tables))
2413        }
2414    }
2415
2416    /// The shared enrichment slots for a worker (`None` per model unless its
2417    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
2418    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
2419        if self.no_ocr || !self.enrich.any() {
2420            return (None, None);
2421        }
2422        (
2423            self.enrich
2424                .picture_classification
2425                .then(|| Arc::clone(&self.classifier)),
2426            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
2427        )
2428    }
2429
2430    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
2431    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
2432    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
2433    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
2434    /// `DocumentConverter.initialize_pipeline`.
2435    pub fn warm_up(&mut self) -> Result<(), PdfError> {
2436        self.primary()?;
2437        Ok(())
2438    }
2439
2440    /// The full-intra serial worker, loaded on first use.
2441    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
2442        if self.primary.is_none() {
2443            self.primary = Some(Worker::load(
2444                intra_threads(),
2445                self.tables_slot(),
2446                self.enrich_slots(),
2447                self.enrich,
2448                self.no_ocr,
2449                self.skip_ocr,
2450                // The mode-shaped spelling (#254) and the flag are one engine
2451                // truth: whichever demands forcing wins, mirroring docling's
2452                // `force_full_page_ocr` → `mode=full_page` bridge.
2453                self.force_full_page_ocr || self.ocr_mode.forces_full_page(),
2454                self.no_text_panels,
2455                self.ocr_lang,
2456                self.ocr_engine,
2457                self.tesseract_lang.clone(),
2458                self.ocr_scale,
2459            )?);
2460        }
2461        Ok(self.primary.as_mut().unwrap())
2462    }
2463
2464    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
2465    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
2466    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
2467    /// fans the pages out across the worker pool, reassembled in page order so the
2468    /// output is byte-identical to the serial path.
2469    pub fn convert(
2470        &mut self,
2471        bytes: &[u8],
2472        password: Option<&str>,
2473        name: &str,
2474    ) -> Result<DoclingDocument, PdfError> {
2475        self.convert_outcome(bytes, password, name)
2476            .map(|c| c.document)
2477    }
2478
2479    /// [`convert`](Self::convert) that also says how the conversion ended —
2480    /// whether the [`document_timeout`](Self::document_timeout) cut it short
2481    /// and how many pages made it (`Completion`).
2482    pub fn convert_outcome(
2483        &mut self,
2484        bytes: &[u8],
2485        password: Option<&str>,
2486        name: &str,
2487    ) -> Result<Converted, PdfError> {
2488        let deadline = self.deadline();
2489        let pages = pdfium_backend::page_count(bytes, password)?;
2490        let range = self.resolve_range(pages)?;
2491        // Serial vs parallel is decided by the pages actually converted: a
2492        // 3-page window over a 500-page PDF should not pay the pool load.
2493        let selected = range.map_or(pages, |(a, b)| b - a + 1);
2494        let (document, done, timed_out) =
2495            if self.target_workers >= 2 && selected >= self.parallel_min {
2496                self.convert_parallel(bytes, password, name, range, selected, deadline)?
2497            } else {
2498                self.convert_serial(bytes, password, name, range, selected, deadline)?
2499            };
2500        timing::report();
2501        Ok(Converted {
2502            document,
2503            completion: self.completion(timed_out, done, selected),
2504        })
2505    }
2506
2507    /// Stream pages one at a time through the primary worker — render → process →
2508    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
2509    fn convert_serial(
2510        &mut self,
2511        bytes: &[u8],
2512        password: Option<&str>,
2513        name: &str,
2514        range: Option<(usize, usize)>,
2515        selected: usize,
2516        deadline: Option<std::time::Instant>,
2517    ) -> Result<(DoclingDocument, usize, bool), PdfError> {
2518        let mut doc = DoclingDocument::new(name);
2519        let mut confs = std::collections::BTreeMap::new();
2520        let render_image = !self.no_ocr;
2521        let extract_text = self.extract_text_layer();
2522        let progress = self.progress.clone();
2523        let mut done = 0usize;
2524        let worker = self.primary()?;
2525        // The walk renders a page before handing it over, so the budget is
2526        // checked where a page *arrives*: a page the budget had already run
2527        // out on is dropped unprocessed and ends the walk through the
2528        // sentinel (`for_each_page` reads it as an error; here it is the cut).
2529        let walk = pdfium_backend::for_each_page(
2530            bytes,
2531            password,
2532            render_image,
2533            extract_text,
2534            range,
2535            |n, _total, mut page| {
2536                if expired(deadline) {
2537                    return Err(timeout_sentinel());
2538                }
2539                let (mut nodes, links, conf) = worker.process(n, &mut page)?;
2540                assemble::stamp_page_no(&mut nodes, n + 1);
2541                doc.nodes.extend(nodes);
2542                doc.links.extend(links);
2543                confs.insert(n + 1, conf);
2544                done += 1;
2545                if let Some(cb) = &progress {
2546                    cb(done, selected);
2547                }
2548                Ok::<(), PdfError>(())
2549            },
2550        );
2551        let timed_out = match walk {
2552            Ok(()) => false,
2553            Err(PdfError::Timeout(_)) => true,
2554            Err(e) => return Err(e),
2555        };
2556        assemble::merge_continuations(&mut doc.nodes);
2557        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
2558        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2559        Ok((doc, done, timed_out))
2560    }
2561
2562    /// Render pages serially on this thread (pdfium) and process them in parallel
2563    /// across the worker pool. A bounded channel applies backpressure so only a
2564    /// handful of page bitmaps are resident at once; results carry their page
2565    /// index and are reassembled in order, so the output is byte-identical to the
2566    /// serial path.
2567    fn convert_parallel(
2568        &mut self,
2569        bytes: &[u8],
2570        password: Option<&str>,
2571        name: &str,
2572        range: Option<(usize, usize)>,
2573        selected: usize,
2574        deadline: Option<std::time::Instant>,
2575    ) -> Result<(DoclingDocument, usize, bool), PdfError> {
2576        self.ensure_pool()?;
2577        let progress = self.progress.clone();
2578        let pages_done = std::sync::atomic::AtomicUsize::new(0);
2579        let timed_out = std::sync::atomic::AtomicBool::new(false);
2580        let n_workers = self.pool.len();
2581        let render_image = !self.no_ocr;
2582        let extract_text = self.extract_text_layer();
2583        let layout_batch = pdf_layout_batch();
2584        // Bound sized so every worker can accumulate a full layout batch while
2585        // rendering stays ahead (and never below the pre-#73 render-ahead of
2586        // two pages per worker); still a hard cap on resident page bitmaps.
2587        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2588        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2589        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
2590        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
2591
2592        // Move the pool into the scope so each worker gets an exclusive `&mut`.
2593        let mut workers = std::mem::take(&mut self.pool);
2594        std::thread::scope(|s| {
2595            for worker in workers.iter_mut() {
2596                let work_rx = Arc::clone(&work_rx);
2597                let results = Arc::clone(&results);
2598                let first_err = Arc::clone(&first_err);
2599                let progress = progress.clone();
2600                let pages_done = &pages_done;
2601                let timed_out = &timed_out;
2602                s.spawn(move || {
2603                    worker.run_pool(&work_rx, layout_batch, deadline, |idx, out| {
2604                        match out {
2605                            Ok(out) => {
2606                                results.lock().unwrap().push((idx, out));
2607                                let d = pages_done
2608                                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2609                                    + 1;
2610                                if let Some(cb) = &progress {
2611                                    cb(d, selected);
2612                                }
2613                            }
2614                            // The budget ran out before this page's turn: the
2615                            // page is left out, the document is partial.
2616                            Err(PdfError::Timeout(_)) => {
2617                                timed_out.store(true, std::sync::atomic::Ordering::Relaxed);
2618                            }
2619                            Err(e) => {
2620                                let mut slot = first_err.lock().unwrap();
2621                                if slot.is_none() {
2622                                    *slot = Some(e);
2623                                }
2624                            }
2625                        }
2626                        true
2627                    });
2628                });
2629            }
2630            // Render on this thread and feed the workers; backpressure blocks here
2631            // when the channel is full. Dropping `work_tx` afterwards signals the
2632            // workers (recv → Err) to finish. A spent budget ends the walk before
2633            // the next page is rendered.
2634            let render = pdfium_backend::for_each_page(
2635                bytes,
2636                password,
2637                render_image,
2638                extract_text,
2639                range,
2640                |i, _total, page| {
2641                    if expired(deadline) {
2642                        return Err(timeout_sentinel());
2643                    }
2644                    work_tx
2645                        .send((i, page))
2646                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2647                },
2648            );
2649            drop(work_tx);
2650            match render {
2651                Ok(()) => {}
2652                Err(PdfError::Timeout(_)) => {
2653                    timed_out.store(true, std::sync::atomic::Ordering::Relaxed);
2654                }
2655                Err(e) => {
2656                    let mut slot = first_err.lock().unwrap();
2657                    if slot.is_none() {
2658                        *slot = Some(e);
2659                    }
2660                }
2661            }
2662        });
2663        // Threads have joined; restore the pool for the next conversion.
2664        self.pool = workers;
2665
2666        if let Some(e) = first_err.lock().unwrap().take() {
2667            return Err(e);
2668        }
2669        let mut results = Arc::try_unwrap(results)
2670            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
2671            .into_inner()
2672            .unwrap();
2673        results.sort_by_key(|(idx, _)| *idx);
2674        let done = results.len();
2675        let mut doc = DoclingDocument::new(name);
2676        let mut confs = std::collections::BTreeMap::new();
2677        for (idx, (mut nodes, links, conf)) in results {
2678            assemble::stamp_page_no(&mut nodes, idx + 1);
2679            doc.nodes.extend(nodes);
2680            doc.links.extend(links);
2681            confs.insert(idx + 1, conf);
2682        }
2683        assemble::merge_continuations(&mut doc.nodes);
2684        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
2685        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2686        let timed_out = timed_out.load(std::sync::atomic::Ordering::Relaxed);
2687        Ok((doc, done, timed_out))
2688    }
2689
2690    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
2691    /// in-document-order batch of nodes (and that span's recovered links) as pages
2692    /// complete, so a caller can serialize Markdown page by page instead of waiting
2693    /// for the whole document. The batches are exactly the buffered [`convert`]'s
2694    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
2695    /// parallel path reorders pages back into document order before emitting, so
2696    /// the output is identical regardless of worker scheduling.
2697    ///
2698    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
2699    /// and its backpressure throttles the whole pipeline. Returning `Err` from
2700    /// `emit` aborts the conversion with that error.
2701    pub fn convert_streaming<F>(
2702        &mut self,
2703        bytes: &[u8],
2704        password: Option<&str>,
2705        name: &str,
2706        emit: F,
2707    ) -> Result<(), PdfError>
2708    where
2709        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2710    {
2711        self.convert_streaming_outcome(bytes, password, name, emit)
2712            .map(|_| ())
2713    }
2714
2715    /// [`convert_streaming`](Self::convert_streaming) that also says how the
2716    /// conversion ended ([`Completion`]): a spent
2717    /// [`document_timeout`](Self::document_timeout) stops the walk, the pages
2718    /// finished so far are emitted (the tail included) and the outcome is
2719    /// `TimedOut` — never an error.
2720    pub fn convert_streaming_outcome<F>(
2721        &mut self,
2722        bytes: &[u8],
2723        password: Option<&str>,
2724        name: &str,
2725        emit: F,
2726    ) -> Result<Completion, PdfError>
2727    where
2728        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2729    {
2730        let _ = name; // page nodes carry no name; the caller owns the document name.
2731        let deadline = self.deadline();
2732        let pages = pdfium_backend::page_count(bytes, password)?;
2733        let range = self.resolve_range(pages)?;
2734        let selected = range.map_or(pages, |(a, b)| b - a + 1);
2735        let r = if self.target_workers >= 2 && selected >= self.parallel_min {
2736            self.convert_streaming_parallel(bytes, password, range, deadline, emit)
2737        } else {
2738            self.convert_streaming_serial(bytes, password, range, deadline, emit)
2739        };
2740        timing::report();
2741        let (done, timed_out) = r?;
2742        Ok(self.completion(timed_out, done, selected))
2743    }
2744
2745    /// Serial streaming: render → process → emit, one page at a time, holding back
2746    /// only the tail that might still merge into the next page.
2747    fn convert_streaming_serial<F>(
2748        &mut self,
2749        bytes: &[u8],
2750        password: Option<&str>,
2751        range: Option<(usize, usize)>,
2752        deadline: Option<std::time::Instant>,
2753        mut emit: F,
2754    ) -> Result<(usize, bool), PdfError>
2755    where
2756        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2757    {
2758        let mut asm = assemble::StreamAssembler::new();
2759        let render_image = !self.no_ocr;
2760        let extract_text = self.extract_text_layer();
2761        let worker = self.primary()?;
2762        let mut done = 0usize;
2763        let walk = pdfium_backend::for_each_page(
2764            bytes,
2765            password,
2766            render_image,
2767            extract_text,
2768            range,
2769            |n, _total, mut page| {
2770                if expired(deadline) {
2771                    return Err(timeout_sentinel());
2772                }
2773                // Confidence is dropped on the streaming path: the report is
2774                // only complete once every page has run, which defeats
2775                // page-by-page emission — buffered `convert` carries it.
2776                let (nodes, links, _conf) = worker.process(n, &mut page)?;
2777                done += 1;
2778                emit(asm.push(nodes), links)
2779            },
2780        );
2781        let timed_out = match walk {
2782            Ok(()) => false,
2783            Err(PdfError::Timeout(_)) => true,
2784            Err(e) => return Err(e),
2785        };
2786        emit(asm.finish(), Vec::new())?;
2787        Ok((done, timed_out))
2788    }
2789
2790    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
2791    /// not thread-safe) and process across the worker pool; results carry their
2792    /// page index and are reordered on the calling thread into a
2793    /// [`assemble::StreamAssembler`], which emits each page in document order as
2794    /// soon as its predecessors have arrived. Bounded channels keep only a handful
2795    /// of pages resident and let `emit`'s backpressure reach the renderer.
2796    fn convert_streaming_parallel<F>(
2797        &mut self,
2798        bytes: &[u8],
2799        password: Option<&str>,
2800        range: Option<(usize, usize)>,
2801        deadline: Option<std::time::Instant>,
2802        mut emit: F,
2803    ) -> Result<(usize, bool), PdfError>
2804    where
2805        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2806    {
2807        self.ensure_pool()?;
2808        let n_workers = self.pool.len();
2809        let render_image = !self.no_ocr;
2810        let extract_text = self.extract_text_layer();
2811        let layout_batch = pdf_layout_batch();
2812        // Bound sized so every worker can accumulate a full layout batch while
2813        // rendering stays ahead (and never below the pre-#73 render-ahead of
2814        // two pages per worker); still a hard cap on resident page bitmaps.
2815        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2816        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2817        // Workers and the renderer report here; the calling thread drains it in
2818        // page order. Bounded so workers block (bounding resident bitmaps) when the
2819        // consumer falls behind.
2820        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
2821
2822        let mut workers = std::mem::take(&mut self.pool);
2823        let mut asm = assemble::StreamAssembler::new();
2824        let mut first_err: Option<PdfError> = None;
2825        let mut timed_out = false;
2826        let mut done = 0usize;
2827
2828        std::thread::scope(|s| {
2829            // Workers: pull a batch of pages (whatever is already rendered, up
2830            // to the layout batch size), process it, report (index-tagged)
2831            // results.
2832            for worker in workers.iter_mut() {
2833                let work_rx = Arc::clone(&work_rx);
2834                let res_tx = res_tx.clone();
2835                s.spawn(move || {
2836                    worker.run_pool(&work_rx, layout_batch, deadline, |idx, out| {
2837                        // `false` once the consumer is gone.
2838                        res_tx.send(out.map(|o| (idx, o))).is_ok()
2839                    });
2840                });
2841            }
2842            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
2843            // single thread); report a render error through the same channel. A
2844            // spent budget ends the walk before the next page is rendered.
2845            {
2846                let res_tx = res_tx.clone();
2847                s.spawn(move || {
2848                    let render = pdfium_backend::for_each_page(
2849                        bytes,
2850                        password,
2851                        render_image,
2852                        extract_text,
2853                        range,
2854                        |i, _total, page| {
2855                            if expired(deadline) {
2856                                return Err(timeout_sentinel());
2857                            }
2858                            work_tx
2859                                .send((i, page))
2860                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2861                        },
2862                    );
2863                    drop(work_tx); // signal workers to finish
2864                    if let Err(e) = render {
2865                        let _ = res_tx.send(Err(e));
2866                    }
2867                });
2868            }
2869            // Drop our own sender so the channel closes once the threads finish.
2870            drop(res_tx);
2871
2872            // Collector (this thread): reorder into document order and emit.
2873            // With a page window, indices start at the window's first page.
2874            // A timed-out page leaves a hole in the sequence: everything
2875            // before it emits in order, the pages after it stay buffered —
2876            // they are the pages the budget did not cover, and the document
2877            // ends at the cut like the buffered path's.
2878            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
2879            let mut next = range.map_or(0, |(first, _)| first);
2880            for msg in res_rx.iter() {
2881                match msg {
2882                    Err(PdfError::Timeout(_)) => timed_out = true,
2883                    Err(e) => {
2884                        if first_err.is_none() {
2885                            first_err = Some(e);
2886                        }
2887                    }
2888                    Ok((idx, out)) => {
2889                        buffer.insert(idx, out);
2890                        if first_err.is_some() {
2891                            continue; // keep draining so the threads can exit
2892                        }
2893                        while let Some((nodes, links, _conf)) = buffer.remove(&next) {
2894                            if let Err(e) = emit(asm.push(nodes), links) {
2895                                first_err = Some(e);
2896                                break;
2897                            }
2898                            next += 1;
2899                            done += 1;
2900                        }
2901                    }
2902                }
2903            }
2904            // Pages that finished after a hole (a page the budget skipped
2905            // before them) cannot follow it in document order; count them
2906            // out of the document like the skipped one.
2907            if timed_out && !buffer.is_empty() {
2908                buffer.clear();
2909            }
2910        });
2911        // Threads have joined; restore the pool for the next conversion.
2912        self.pool = workers;
2913
2914        if let Some(e) = first_err {
2915            return Err(e);
2916        }
2917        emit(asm.finish(), Vec::new())?;
2918        Ok((done, timed_out))
2919    }
2920
2921    /// Lazily grow the pool to `target_workers`, loading the new workers
2922    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
2923    /// one load's wall-time). Cached for reuse across documents.
2924    fn ensure_pool(&mut self) -> Result<(), PdfError> {
2925        let need = self.target_workers.saturating_sub(self.pool.len());
2926        if need == 0 {
2927            return Ok(());
2928        }
2929        let intra = pdf_intra();
2930        let no_ocr = self.no_ocr;
2931        let skip_ocr = self.skip_ocr;
2932        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2933        let ntp = self.no_text_panels;
2934        let ocr_lang = self.ocr_lang;
2935        let ocr_engine = self.ocr_engine;
2936        let tesseract_lang = self.tesseract_lang.clone();
2937        let ocr_scale = self.ocr_scale;
2938        let enrich = self.enrich;
2939        let tables = self.tables_slot();
2940        let enrich_slots = self.enrich_slots();
2941        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
2942            let handles: Vec<_> = (0..need)
2943                .map(|_| {
2944                    let tables = tables.clone();
2945                    let enrich_slots = enrich_slots.clone();
2946                    let tesseract_lang = tesseract_lang.clone();
2947                    s.spawn(move || {
2948                        Worker::load(
2949                            intra,
2950                            tables,
2951                            enrich_slots,
2952                            enrich,
2953                            no_ocr,
2954                            skip_ocr,
2955                            force,
2956                            ntp,
2957                            ocr_lang,
2958                            ocr_engine,
2959                            tesseract_lang,
2960                            ocr_scale,
2961                        )
2962                    })
2963                })
2964                .collect();
2965            handles.into_iter().map(|h| h.join().unwrap()).collect()
2966        });
2967        for w in loaded {
2968            self.pool.push(w?);
2969        }
2970        Ok(())
2971    }
2972
2973    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
2974    /// docling routes images through the same layout+OCR pipeline as a PDF page.
2975    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2976        let image = decode_image_limited(bytes)?;
2977        let (w, h) = image.dimensions();
2978        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
2979        // standalone image has no text layer, so OCR supplies the cells.
2980        let page = PdfPage {
2981            width: w as f32,
2982            height: h as f32,
2983            scale: 1.0,
2984            cells: Vec::new(),
2985            code_cells: Vec::new(),
2986            word_cells: Vec::new(),
2987            // A standalone image *is* its own scale-1.0 page image, so the
2988            // layout model sees it through the docling-exact PIL kernel.
2989            image_layout: Some(image.clone()),
2990            image,
2991            links: Vec::new(),
2992            rotation: 0,
2993        };
2994        self.process_pages(vec![page], name)
2995    }
2996
2997    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
2998    /// page (image / METS inputs, which are small and already materialised).
2999    /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
3000    /// caller-configured pipeline (#244).
3001    pub fn process_pages(
3002        &mut self,
3003        mut pages: Vec<PdfPage>,
3004        name: &str,
3005    ) -> Result<DoclingDocument, PdfError> {
3006        let mut doc = DoclingDocument::new(name);
3007        let mut confs = std::collections::BTreeMap::new();
3008        let worker = self.primary()?;
3009        for (n, page) in pages.iter_mut().enumerate() {
3010            let (mut nodes, links, conf) = worker.process(n, page)?;
3011            assemble::stamp_page_no(&mut nodes, n + 1);
3012            doc.nodes.extend(nodes);
3013            doc.links.extend(links);
3014            confs.insert(n + 1, conf);
3015        }
3016        assemble::merge_continuations(&mut doc.nodes);
3017        // No PDF behind these pages (images, METS): the heading-hierarchy
3018        // stage degrades to the numbering signal — exactly docling without
3019        // an outline or parsed pages.
3020        self.apply_heading_hierarchy(&mut doc.nodes, None);
3021        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
3022        Ok(doc)
3023    }
3024}
3025
3026/// Number of pages in a PDF, without converting anything — what the CLI batch
3027/// mode prints in its per-document start line.
3028#[cfg(feature = "ml")]
3029pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
3030    pdfium_backend::page_count(bytes, password)
3031}
3032
3033#[cfg(feature = "ml")]
3034/// Convenience one-shot conversion (loads the pipeline per call). Errors are
3035/// detailed and surfaced (never silently skipped).
3036pub fn convert(
3037    bytes: &[u8],
3038    password: Option<&str>,
3039    name: &str,
3040) -> Result<DoclingDocument, PdfError> {
3041    convert_with_options(
3042        bytes,
3043        password,
3044        name,
3045        false,
3046        false,
3047        false,
3048        false,
3049        EnrichmentOptions::default(),
3050        None,
3051        None,
3052    )
3053}
3054
3055#[cfg(feature = "ml")]
3056/// Like [`convert`], but optionally skips loading/running TableFormer (see
3057/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
3058/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
3059/// [`Pipeline::enrichments`]).
3060// One positional per pipeline switch mirrors the Pipeline builder; growing
3061// past clippy's arity cap is the price of keeping this one-shot signature
3062// stable-ish instead of churning callers into an options struct mid-series.
3063#[allow(clippy::too_many_arguments)]
3064pub fn convert_with_options(
3065    bytes: &[u8],
3066    password: Option<&str>,
3067    name: &str,
3068    no_table_former: bool,
3069    no_ocr: bool,
3070    force_full_page_ocr: bool,
3071    no_text_panels: bool,
3072    enrich: EnrichmentOptions,
3073    pages: Option<(usize, usize)>,
3074    ocr_lang: Option<OcrLang>,
3075) -> Result<DoclingDocument, PdfError> {
3076    Pipeline::new()?
3077        .no_table_former(no_table_former)
3078        .no_ocr(no_ocr)
3079        .force_full_page_ocr(force_full_page_ocr)
3080        .no_text_panels(no_text_panels)
3081        .enrichments(enrich)
3082        .pages(pages)
3083        .ocr_lang(ocr_lang)
3084        .convert(bytes, password, name)
3085}
3086
3087#[cfg(feature = "ml")]
3088/// Convenience one-shot image conversion (loads the pipeline per call).
3089pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
3090    convert_image_with_options(
3091        bytes,
3092        name,
3093        false,
3094        false,
3095        false,
3096        EnrichmentOptions::default(),
3097        None,
3098    )
3099}
3100
3101#[cfg(feature = "ml")]
3102/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
3103/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
3104/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
3105pub fn convert_image_with_options(
3106    bytes: &[u8],
3107    name: &str,
3108    no_table_former: bool,
3109    no_ocr: bool,
3110    no_text_panels: bool,
3111    enrich: EnrichmentOptions,
3112    ocr_lang: Option<OcrLang>,
3113) -> Result<DoclingDocument, PdfError> {
3114    Pipeline::new()?
3115        .no_table_former(no_table_former)
3116        .no_ocr(no_ocr)
3117        .no_text_panels(no_text_panels)
3118        .enrichments(enrich)
3119        .ocr_lang(ocr_lang)
3120        .convert_image(bytes, name)
3121}
3122
3123#[cfg(feature = "ml")]
3124/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
3125/// scans) through the shared layout + assembly pipeline.
3126pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
3127    convert_pages_with_options(
3128        pages,
3129        name,
3130        false,
3131        false,
3132        false,
3133        EnrichmentOptions::default(),
3134    )
3135}
3136
3137#[cfg(feature = "ml")]
3138/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
3139/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
3140/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
3141pub fn convert_pages_with_options(
3142    pages: Vec<PdfPage>,
3143    name: &str,
3144    no_table_former: bool,
3145    no_ocr: bool,
3146    no_text_panels: bool,
3147    enrich: EnrichmentOptions,
3148) -> Result<DoclingDocument, PdfError> {
3149    Pipeline::new()?
3150        .no_table_former(no_table_former)
3151        .no_text_panels(no_text_panels)
3152        .no_ocr(no_ocr)
3153        .enrichments(enrich)
3154        .process_pages(pages, name)
3155}
3156
3157#[cfg(feature = "ml")]
3158#[cfg(all(test, feature = "ml"))]
3159mod image_limit_tests {
3160    use super::decode_image_with_max_side;
3161
3162    /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
3163    /// byte literal).
3164    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
3165        use std::io::Cursor;
3166        let img = image::RgbImage::new(w, h);
3167        let mut out = Vec::new();
3168        img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
3169            .unwrap();
3170        out
3171    }
3172
3173    #[test]
3174    fn normal_image_decodes_under_the_cap() {
3175        let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
3176        assert_eq!(img.dimensions(), (8, 8));
3177    }
3178
3179    /// docling#4247 (2.128): the EXIF orientation is applied when a frame is
3180    /// loaded — a 4×2 JPEG tagged "rotate 90° CW" (orientation 6) decodes as
3181    /// 2×4, with the pixels turned.
3182    #[test]
3183    fn exif_orientation_is_applied() {
3184        use std::io::Cursor;
3185        let mut img = image::RgbImage::new(4, 2);
3186        img.put_pixel(0, 0, image::Rgb([255, 0, 0]));
3187        let mut jpeg = Vec::new();
3188        img.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
3189            .unwrap();
3190        // Splice an APP1 Exif segment (little-endian TIFF, one IFD entry:
3191        // Orientation = 6) right after the SOI marker.
3192        let mut tiff = b"II*\0".to_vec();
3193        tiff.extend(8u32.to_le_bytes());
3194        tiff.extend(1u16.to_le_bytes());
3195        tiff.extend(0x0112u16.to_le_bytes());
3196        tiff.extend(3u16.to_le_bytes());
3197        tiff.extend(1u32.to_le_bytes());
3198        tiff.extend(6u16.to_le_bytes());
3199        tiff.extend([0, 0]);
3200        tiff.extend(0u32.to_le_bytes());
3201        let mut app1 = b"Exif\0\0".to_vec();
3202        app1.extend(tiff);
3203        let mut out = jpeg[..2].to_vec();
3204        out.extend([0xff, 0xe1]);
3205        out.extend((app1.len() as u16 + 2).to_be_bytes());
3206        out.extend(app1);
3207        out.extend(&jpeg[2..]);
3208        let plain = decode_image_with_max_side(&jpeg, 30_000).unwrap();
3209        assert_eq!(plain.dimensions(), (4, 2));
3210        let turned = decode_image_with_max_side(&out, 30_000).unwrap();
3211        assert_eq!(turned.dimensions(), (2, 4), "quarter turn swaps the sides");
3212        // Rotating 90° CW moves the top-left pixel to the top-right corner.
3213        assert!(turned.get_pixel(1, 0).0[0] > 128);
3214        assert!(turned.get_pixel(0, 0).0[0] <= 128);
3215    }
3216
3217    #[test]
3218    fn dimensions_over_the_cap_are_rejected_not_aborted() {
3219        // A per-side cap below the image's declared size must yield a
3220        // recoverable Err, never an allocation-abort — the mechanism that stops
3221        // a crafted image declaring 60000×60000 from OOM-killing the process.
3222        let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
3223        assert!(
3224            r.is_err(),
3225            "decode must fail under the pixel cap, not abort"
3226        );
3227    }
3228}
3229
3230#[cfg(test)]
3231mod median_tests {
3232    #[test]
3233    fn median_of_empty_is_zero_not_a_panic() {
3234        // A crafted table can leave a row/column with zero matched cells; the
3235        // even-count branch would index values[0 - 1] and panic (→ remote crash
3236        // via docling-serve) without the empty guard.
3237        assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
3238        assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
3239        assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
3240    }
3241}
3242
3243#[cfg(test)]
3244mod send_check {
3245    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
3246    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
3247    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
3248    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
3249    fn assert_send<T: Send>() {}
3250
3251    #[test]
3252    fn pipeline_is_send() {
3253        assert_send::<super::Pipeline>();
3254    }
3255}
3256
3257#[cfg(all(test, feature = "ml"))]
3258mod ocr_input_tests {
3259    /// #254: without an `ocr_scale` (or with one equal to the render scale)
3260    /// the OCR reads the page render untouched and the cache stays cold; a
3261    /// different scale builds one resampled view, reuses it across calls, and
3262    /// reports the requested px/pt so cell geometry divides back to points.
3263    #[test]
3264    fn ocr_input_resamples_only_on_a_real_scale_change() {
3265        let img = image::RgbImage::new(200, 100);
3266        let mut cache = None;
3267        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, None);
3268        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
3269        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(2.0));
3270        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
3271
3272        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
3273        assert_eq!((v.width(), v.height(), s), (300, 150, 3.0));
3274        let first = cache.as_ref().map(|c| c as *const image::RgbImage);
3275        let (v, _) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
3276        assert_eq!(
3277            Some(v as *const image::RgbImage),
3278            first,
3279            "cached, not rebuilt"
3280        );
3281
3282        let mut down = None;
3283        let (v, s) = super::ocr_input(&mut down, &img, 2.0, Some(1.0));
3284        assert_eq!((v.width(), v.height(), s), (100, 50, 1.0));
3285    }
3286}