Skip to main content

docling_pdf/
lib.rs

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