Skip to main content

docling_pdf/
lib.rs

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