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