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