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