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