Skip to main content

docling_pdf/
lib.rs

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