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