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