Skip to main content

docling_pdf/
lib.rs

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