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