Skip to main content

docling_pdf/
lib.rs

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