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