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