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