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