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        // The cells are final: fit every regular region to the cells it
1336        // claims and fold the orphans it now surrounds (#419), before
1337        // TableFormer and the reading order see the boxes.
1338        assemble::fit_regions_to_cells(&mut regions, &page.cells);
1339        Ok(Prepared {
1340            regions,
1341            ocr_confs,
1342            parse,
1343        })
1344    }
1345
1346    /// The stages after TableFormer: enrichment, the page confidence report and
1347    /// assembly into typed nodes.
1348    fn complete_page(
1349        &mut self,
1350        n: usize,
1351        page: &mut PdfPage,
1352        prepared: Prepared,
1353        table_rows: Vec<Option<tf_core::TableGrid>>,
1354    ) -> Result<PageOut, PdfError> {
1355        let Prepared {
1356            regions,
1357            ocr_confs,
1358            parse,
1359        } = prepared;
1360        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1361            for (i, r) in regions.iter().enumerate() {
1362                eprintln!(
1363                    "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
1364                    r.label,
1365                    r.score,
1366                    r.l,
1367                    r.t,
1368                    r.r,
1369                    r.b,
1370                    table_rows[i]
1371                        .as_ref()
1372                        .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
1373                );
1374            }
1375            eprintln!(
1376                "DBG cells={} words={}",
1377                page.cells.len(),
1378                page.word_cells.len()
1379            );
1380        }
1381        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
1382        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
1383        // shape as TableFormer — one lazily-loaded instance per pipeline, only
1384        // ever locked when a page actually has a matching region.
1385        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
1386        if let Some(slot) = self.classifier.as_ref() {
1387            if regions.iter().any(|r| r.label == "picture") {
1388                timing::timed("picture_classifier", || {
1389                    let mut guard = slot.lock().unwrap();
1390                    if matches!(*guard, EnrichSlot::Unloaded) {
1391                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
1392                            Some(m) => EnrichSlot::Ready(m),
1393                            None => EnrichSlot::Missing,
1394                        };
1395                    }
1396                    if let EnrichSlot::Ready(model) = &mut *guard {
1397                        for (i, r) in regions.iter().enumerate() {
1398                            if r.label != "picture" {
1399                                continue;
1400                            }
1401                            let Some(crop) = assemble::crop_region_scaled(
1402                                page,
1403                                [r.l, r.t, r.r, r.b],
1404                                enrich::CLASSIFIER_SCALE,
1405                            ) else {
1406                                continue;
1407                            };
1408                            match model.classify(&crop) {
1409                                Ok(classes) => {
1410                                    enrich_out[i] =
1411                                        Some(assemble::Enrichment::PictureClasses(classes));
1412                                }
1413                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1414                            }
1415                        }
1416                    }
1417                });
1418            }
1419        }
1420        if let Some(slot) = self.code_formula.as_ref() {
1421            let wants = |label: &str| {
1422                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
1423            };
1424            if regions.iter().any(|r| wants(r.label)) {
1425                timing::timed("code_formula", || {
1426                    let mut guard = slot.lock().unwrap();
1427                    if matches!(*guard, EnrichSlot::Unloaded) {
1428                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
1429                            Some(m) => EnrichSlot::Ready(m),
1430                            None => EnrichSlot::Missing,
1431                        };
1432                    }
1433                    if let EnrichSlot::Ready(model) = &mut *guard {
1434                        for (i, r) in regions.iter().enumerate() {
1435                            if !wants(r.label) {
1436                                continue;
1437                            }
1438                            // docling crops the postprocessed cluster box — the
1439                            // union of the region's text cells, not the raw
1440                            // detector box — expanded by 18% per side, at
1441                            // ~120 dpi.
1442                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
1443                                .unwrap_or([r.l, r.t, r.r, r.b]);
1444                            let (w, h) = (br - bl, bb - bt);
1445                            let ex = enrich::CODE_FORMULA_EXPANSION;
1446                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
1447                            let Some(crop) = assemble::crop_region_scaled(
1448                                page,
1449                                bbox,
1450                                enrich::CODE_FORMULA_SCALE,
1451                            ) else {
1452                                continue;
1453                            };
1454                            let kind = if r.label == "code" {
1455                                enrich::CodeFormulaKind::Code
1456                            } else {
1457                                enrich::CodeFormulaKind::Formula
1458                            };
1459                            match model.predict(&crop, kind) {
1460                                Ok(text) => {
1461                                    enrich_out[i] = Some(match kind {
1462                                        enrich::CodeFormulaKind::Code => {
1463                                            let (code, language) =
1464                                                enrich::extract_code_language(&text);
1465                                            assemble::Enrichment::Code {
1466                                                language,
1467                                                text: code,
1468                                            }
1469                                        }
1470                                        enrich::CodeFormulaKind::Formula => {
1471                                            assemble::Enrichment::Formula { latex: text }
1472                                        }
1473                                    });
1474                                }
1475                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1476                            }
1477                        }
1478                    }
1479                });
1480            }
1481        }
1482        // Score the final region set (docling assigns layout_score over the
1483        // postprocessed clusters — the same set assemble_page consumes).
1484        let conf = quality::page_confidence(parse, &regions, &ocr_confs);
1485        let (nodes, links) = timing::timed("assemble_page", || {
1486            assemble::assemble_page(page, regions, &table_rows, &enrich_out)
1487        });
1488        Ok((nodes, links, conf))
1489    }
1490}
1491
1492#[cfg(feature = "ml")]
1493/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
1494/// so on a typical machine two threads per worker (sharing one in-cache copy of
1495/// the weights) extracts more throughput than one fat model or many single-thread
1496/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
1497fn pdf_intra() -> usize {
1498    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
1499        return n;
1500    }
1501    if intra_threads() >= 2 {
1502        2
1503    } else {
1504        1
1505    }
1506}
1507
1508#[cfg(feature = "ml")]
1509/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
1510/// overrides; otherwise size the pool so `workers × intra ≈ cores`.
1511///
1512/// The pool scales with the machine (#324 follow-up testing): the old hard cap
1513/// of 4 left most of a many-core box idle — on a 16-core M4 Max, 10 workers
1514/// measured ~1.2× over the capped pool (10.0 → 8.5 s on a 130-page document,
1515/// byte-identical output). The ceiling of 16 is a memory bound, not a
1516/// performance one: each worker holds its own layout/OCR sessions (~0.4 GB),
1517/// so a worst-case pool stays under ~6.5 GB even on a ≥32-core host — and
1518/// docling-serve's per-request pools sit behind its `DOCLING_RS_MAX_MEMORY_MB`
1519/// admission control besides. Machines with 4 or fewer effective threads keep
1520/// the exact old sizing (`threads / intra`, min 1).
1521fn pdf_worker_count() -> usize {
1522    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
1523        return n;
1524    }
1525    (intra_threads() / pdf_intra()).clamp(1, 16)
1526}
1527
1528#[cfg(feature = "ml")]
1529/// Max pages a worker layout-detects with one batched inference call (issue
1530/// #73). Workers drain the work channel opportunistically up to this size —
1531/// whatever is already rendered gets batched, so batching never *waits* for
1532/// pages and adds no latency when rendering is the bottleneck.
1533///
1534/// Default: per-page (1) on the CPU provider, 4 when a GPU provider is
1535/// selected (#338). The old "4 on 8+ cores" CPU default was a hypothesis —
1536/// that single-session amortization pays off with a wider thread budget —
1537/// and every actual CPU measurement lands the other way: a 4-core x86 box
1538/// runs the 9-page 2206.01062 fixture in 8.5 s/conv at batch=1 vs 9.3 s at
1539/// batch=4 (re-measured for #338; the original 8.1 vs 9.3 agrees), and the
1540/// issue-#338 report measured batch=1 ~2× faster on a 16-core M4 Max at
1541/// every worker count — batching only adds cache pressure once workers
1542/// saturate the cores. On a GPU the per-call dispatch overhead is real and
1543/// batching amortizes it, so the GPU default stays. Output is bit-identical
1544/// at every batch size, so this is purely a throughput knob.
1545/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides either way; `1` = per-page.
1546pub(crate) fn pdf_layout_batch() -> usize {
1547    env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
1548        .filter(|&n| n > 0)
1549        .unwrap_or_else(|| if docling_onnx::prefers_fp32() { 4 } else { 1 })
1550}
1551
1552#[cfg(feature = "ml")]
1553/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
1554/// the serial primary (running its model on every core) is faster than fanning out
1555/// — the helper pool's one-time model-load cost only pays off once enough pages
1556/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
1557fn pdf_parallel_min() -> usize {
1558    env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
1559        .filter(|&n| n > 0)
1560        .unwrap_or(6)
1561}
1562
1563#[cfg(feature = "ml")]
1564/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
1565/// so a single-page / small / image / METS input is converted at full intra-op
1566/// speed with no pool to load. A document with enough pages instead fans out
1567/// across a **pool** of narrower workers processed concurrently. Both load lazily
1568/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
1569pub struct Pipeline {
1570    /// Full-intra worker for the serial path; loaded on first serial use.
1571    primary: Option<Worker>,
1572    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
1573    /// path; loaded on first multi-page use and cached.
1574    pool: Vec<Worker>,
1575    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
1576    tables: SharedTables,
1577    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
1578    classifier: SharedClassifier,
1579    code_formula: SharedCodeFormula,
1580    /// Desired pool size for multi-page documents.
1581    target_workers: usize,
1582    /// Page count at/above which the parallel pool is worth its load cost.
1583    parallel_min: usize,
1584    /// Skip loading/running TableFormer; table regions fall back to geometric
1585    /// reconstruction. See [`Pipeline::no_table_former`].
1586    no_table_former: bool,
1587    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
1588    no_ocr: bool,
1589    /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
1590    skip_ocr: bool,
1591    /// OCR every page even when it carries a text layer. See
1592    /// [`Pipeline::force_full_page_ocr`].
1593    force_full_page_ocr: bool,
1594    /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
1595    no_text_panels: bool,
1596    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
1597    enrich: EnrichmentOptions,
1598    /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
1599    page_range: Option<(usize, usize)>,
1600    /// OCR recognition language. See [`Pipeline::ocr_lang`].
1601    ocr_lang: ocr::OcrLang,
1602    /// Which regions feed the OCR (#254). See [`Pipeline::ocr_mode`].
1603    ocr_mode: ocr::OcrMode,
1604    /// OCR render scale override in px/pt (#254). See [`Pipeline::ocr_scale`].
1605    ocr_scale: Option<f32>,
1606    /// Heading-level inference (#302). See [`Pipeline::heading_hierarchy`].
1607    heading_hierarchy: HeadingHierarchyOptions,
1608    /// Optional per-page progress hook `(done, selected_total)`, invoked after
1609    /// each page finishes on both the serial and parallel buffered paths. Set
1610    /// by the CLI batch mode for dot-progress; `None` costs nothing.
1611    progress: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>,
1612}
1613
1614#[cfg(feature = "ml")]
1615impl Pipeline {
1616    /// Construct the pipeline. Models load lazily on first use (full-intra primary
1617    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
1618    /// loaded that a given document doesn't need.
1619    pub fn new() -> Result<Self, PdfError> {
1620        Ok(Self {
1621            primary: None,
1622            pool: Vec::new(),
1623            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
1624            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1625            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1626            target_workers: pdf_worker_count(),
1627            parallel_min: pdf_parallel_min(),
1628            no_table_former: false,
1629            no_ocr: false,
1630            skip_ocr: false,
1631            force_full_page_ocr: false,
1632            no_text_panels: false,
1633            enrich: EnrichmentOptions::default(),
1634            page_range: None,
1635            ocr_lang: ocr::OcrLang::from_env(),
1636            ocr_mode: ocr::OcrMode::from_env(),
1637            ocr_scale: ocr::scale_from_env(),
1638            heading_hierarchy: HeadingHierarchyOptions::default(),
1639            progress: None,
1640        })
1641    }
1642
1643    /// Infer section-header levels after assembly (#302, docling's
1644    /// `HeadingHierarchyModel`): PDF bookmarks > legal/outline numbering >
1645    /// font style, off by default — see [`HeadingHierarchyOptions`]. Pure
1646    /// post-processing configuration; for a warm pipeline use
1647    /// [`set_heading_hierarchy`](Self::set_heading_hierarchy).
1648    pub fn heading_hierarchy(mut self, opts: HeadingHierarchyOptions) -> Self {
1649        self.heading_hierarchy = opts;
1650        self
1651    }
1652
1653    /// In-place variant of [`heading_hierarchy`](Self::heading_hierarchy) for
1654    /// a long-lived pipeline (docling-serve's warm instance) — like
1655    /// [`set_pages`](Self::set_pages), set it before every conversion so no
1656    /// request inherits a previous one's choice.
1657    pub fn set_heading_hierarchy(&mut self, opts: HeadingHierarchyOptions) {
1658        self.heading_hierarchy = opts;
1659    }
1660
1661    /// Run the enabled heading-hierarchy stage (#302) on an assembled
1662    /// document: gather the outline (bookmarks) and the per-page glyph styles
1663    /// on demand, then assign levels in place. `bytes` is `None` on paths
1664    /// with no PDF behind them (standalone images, METS) — those degrade to
1665    /// the numbering signal, exactly like docling without parsed pages.
1666    fn apply_heading_hierarchy(
1667        &self,
1668        nodes: &mut [Node],
1669        bytes: Option<&[u8]>,
1670        password: Option<&str>,
1671    ) {
1672        let opts = &self.heading_hierarchy;
1673        if !opts.enabled {
1674            return;
1675        }
1676        let outline = match bytes {
1677            Some(bytes) if opts.use_bookmarks => outline::extract_outline(bytes),
1678            _ => Vec::new(),
1679        };
1680        let styles = match bytes {
1681            Some(bytes) if opts.use_style => {
1682                let pages = heading_hierarchy::heading_pages(nodes);
1683                pdfium_backend::glyph_styles(bytes, password, &pages)
1684            }
1685            _ => Default::default(),
1686        };
1687        heading_hierarchy::apply(nodes, &outline, &styles, opts);
1688    }
1689
1690    /// Install (or clear) the per-page progress hook: called with
1691    /// `(pages_done, pages_selected)` after each page completes during
1692    /// [`convert`](Self::convert). Shared with the parallel workers, so the
1693    /// callback must be cheap and thread-safe.
1694    pub fn set_progress(&mut self, cb: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>) {
1695        self.progress = cb;
1696    }
1697
1698    /// Convert only pages `first..=last` (**1-based**, like the page numbers a
1699    /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
1700    /// skipped before rasterization, so the cost is proportional to the window,
1701    /// not the document. `last` past the end of the document clamps; a window
1702    /// that selects no pages at all (`first` beyond the last page) is an error
1703    /// at convert time. `None` (the default) converts everything.
1704    pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
1705        self.page_range = range;
1706        self
1707    }
1708
1709    /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
1710    /// (e.g. docling-serve's warm instance) that applies a per-request window
1711    /// without rebuilding — unlike the model switches, the window is pure
1712    /// configuration. Set it before every conversion; it stays until changed.
1713    pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
1714        self.page_range = range;
1715    }
1716
1717    /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
1718    /// for the multilingual docling-conformance model. `None` keeps the
1719    /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
1720    /// first conversion; for a warm pipeline use
1721    /// [`set_ocr_lang`](Self::set_ocr_lang).
1722    pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
1723        self.set_ocr_lang(lang);
1724        self
1725    }
1726
1727    /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
1728    /// pipeline (docling-serve's warm instance). Unlike the page window this
1729    /// is a *model* switch: any worker whose cached recognition model was
1730    /// loaded for a different language drops it, to be lazily reloaded on the
1731    /// next OCR-needing page (cheap — the rec models are ~10 MB).
1732    pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
1733        let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
1734        self.ocr_lang = lang;
1735        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
1736            if worker.ocr_lang != lang {
1737                worker.ocr_lang = lang;
1738                worker.ocr = OcrSlot::Unloaded;
1739            }
1740        }
1741    }
1742
1743    /// Resolve the configured 1-based window against a page count into the
1744    /// 0-based inclusive form the backend walks, validating it selects at
1745    /// least one existing page.
1746    fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
1747        let Some((first, last)) = self.page_range else {
1748            return Ok(None);
1749        };
1750        if first == 0 || last < first {
1751            return Err(PdfError::Pdfium(format!(
1752                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
1753            )));
1754        }
1755        if first > total {
1756            return Err(PdfError::Pdfium(format!(
1757                "page range {first}-{last} is outside the document ({total} page(s))"
1758            )));
1759        }
1760        Ok(Some((first - 1, last.min(total) - 1)))
1761    }
1762
1763    /// Enable the opt-in enrichment passes (docling's
1764    /// `do_picture_classification` / `do_code_enrichment` /
1765    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
1766    /// the first matching region; a missing model warns once and is skipped.
1767    /// Set before the first conversion (no effect on already-loaded workers).
1768    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
1769        self.enrich = opts;
1770        self
1771    }
1772
1773    /// Skip loading and running the TableFormer table-structure model. Table
1774    /// regions still get emitted, but reconstructed geometrically from cell
1775    /// positions instead of via the ONNX model's predicted structure — faster
1776    /// (no model load, no per-table inference) at the cost of table fidelity.
1777    /// No effect if a worker is already loaded; set this before the first
1778    /// conversion.
1779    pub fn no_table_former(mut self, disable: bool) -> Self {
1780        self.no_table_former = disable;
1781        self
1782    }
1783
1784    /// Keep every detected `picture` region as a picture. By default an
1785    /// *uncaptioned* picture that reads like a dense, uniform text panel (a
1786    /// terms-and-conditions box exported as an image) is demoted into
1787    /// paragraphs (#157); a chart the layout mislabels can still trip that
1788    /// heuristic on scanned pages, and image-extraction workflows may simply
1789    /// want every crop — this flag disables the demotion entirely (#173).
1790    /// No effect on already-loaded workers; set before the first conversion.
1791    pub fn no_text_panels(mut self, disable: bool) -> Self {
1792        self.no_text_panels = disable;
1793        self
1794    }
1795
1796    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
1797    /// inference of any kind. The PDF's embedded text cells are grouped by line
1798    /// and emitted as plain paragraphs in reading order: no headings, lists,
1799    /// tables, code blocks, or pictures, since that structure comes from the
1800    /// layout model. The fastest possible PDF path, but pages with no embedded
1801    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
1802    /// without this flag. Implies `no_table_former`. No effect if a worker is
1803    /// already loaded; set this before the first conversion.
1804    pub fn no_ocr(mut self, disable: bool) -> Self {
1805        self.no_ocr = disable;
1806        self
1807    }
1808
1809    /// Never run OCR, but keep layout detection and TableFormer — docling's
1810    /// independent `do_ocr=False` (#244), the counterpart of
1811    /// [`no_table_former`](Self::no_table_former). Unlike
1812    /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
1813    /// output — headings, tables, pictures, reading order — is preserved;
1814    /// only text that exists solely as pixels is lost: scanned pages come
1815    /// back with their regions empty, and the speculative OCR of large
1816    /// embedded images never runs. The OCR model is never loaded. Ignored
1817    /// when `no_ocr` is set (there is no OCR to skip);
1818    /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
1819    /// mirroring docling where forcing is a sub-option of `do_ocr`.
1820    pub fn skip_ocr(mut self, disable: bool) -> Self {
1821        self.skip_ocr = disable;
1822        self
1823    }
1824
1825    /// OCR every page from its rendered image even when the page carries an
1826    /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
1827    /// for text layers that exist but lie: broken encodings, subset fonts with
1828    /// garbage mappings, a scanned form with a few typed-in fields. Ignored
1829    /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
1830    /// `force_full_page_ocr` is a sub-option of `do_ocr`).
1831    pub fn force_full_page_ocr(mut self, force: bool) -> Self {
1832        self.force_full_page_ocr = force;
1833        self
1834    }
1835
1836    /// Which document regions feed the OCR — docling's `OcrMode` (#254). The
1837    /// default (`default` = `pdf_aware_layout_regions`) is the standard
1838    /// text-layer-aware behavior; `full_page`/`layout_regions` discard the
1839    /// text layer like [`force_full_page_ocr`](Self::force_full_page_ocr)
1840    /// (see [`ocr::OcrMode`] for why both map onto it). Whichever of the flag
1841    /// and the mode demands forcing wins, mirroring docling's
1842    /// `force_full_page_ocr` → `mode=full_page` bridge. `None` keeps the
1843    /// process default (`DOCLING_RS_OCR_MODE`, else `default`).
1844    pub fn ocr_mode(mut self, mode: Option<ocr::OcrMode>) -> Self {
1845        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
1846        self
1847    }
1848
1849    /// In-place variants of [`force_full_page_ocr`](Self::force_full_page_ocr),
1850    /// [`ocr_mode`](Self::ocr_mode) and [`ocr_scale`](Self::ocr_scale) for a
1851    /// long-lived pipeline (docling-serve's warm instance): all three are pure
1852    /// per-worker configuration — no model reloads — so they apply per request
1853    /// like [`set_pages`](Self::set_pages). Set them before every conversion so
1854    /// no request inherits a previous one's choice.
1855    pub fn set_force_full_page_ocr(&mut self, force: bool) {
1856        self.force_full_page_ocr = force;
1857        self.sync_ocr_config();
1858    }
1859
1860    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
1861    pub fn set_ocr_mode(&mut self, mode: Option<ocr::OcrMode>) {
1862        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
1863        self.sync_ocr_config();
1864    }
1865
1866    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
1867    pub fn set_ocr_scale(&mut self, scale: Option<f32>) {
1868        self.ocr_scale = scale
1869            .filter(|s| s.is_finite() && *s > 0.0)
1870            .or_else(ocr::scale_from_env);
1871        self.sync_ocr_config();
1872    }
1873
1874    /// Whether page extraction should decode the text layer at all. Forced
1875    /// full-page OCR (the flag or `ocr_mode=full_page|layout_regions`) clears
1876    /// every extracted cell unread, so the decode is skipped outright —
1877    /// docling#4061's `skip_cell_extraction` (2.122). `no_ocr` wins over the
1878    /// forcing, as everywhere else: its fast path *is* the text layer.
1879    fn extract_text_layer(&self) -> bool {
1880        self.no_ocr || !(self.force_full_page_ocr || self.ocr_mode.forces_full_page())
1881    }
1882
1883    /// Push the current OCR forcing/scale choice onto already-loaded workers
1884    /// (new workers read it at [`Worker::load`]).
1885    fn sync_ocr_config(&mut self) {
1886        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
1887        let scale = self.ocr_scale;
1888        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
1889            worker.force_full_page_ocr = force;
1890            worker.ocr_scale = scale;
1891        }
1892    }
1893
1894    /// OCR render scale in pixels per PDF point — docling's `OcrOptions.scale`
1895    /// (#254, upstream docling#3877; their default 3 = 216 dpi). `None`
1896    /// (default: `DOCLING_RS_OCR_SCALE`, else unset) feeds the recognizer the
1897    /// pipeline's own page render (2.0 px/pt = 144 dpi); a different value
1898    /// resamples that render for the OCR input only — layout and TableFormer
1899    /// keep their pinned-resolution pixels, so the conformance baseline never
1900    /// moves. Lower it when the source raster is already high-resolution and
1901    /// upscaling degrades recognition; raise it toward docling's 216 dpi for
1902    /// parity experiments. Non-positive values are ignored.
1903    pub fn ocr_scale(mut self, scale: Option<f32>) -> Self {
1904        self.ocr_scale = scale
1905            .filter(|s| s.is_finite() && *s > 0.0)
1906            .or_else(ocr::scale_from_env);
1907        self
1908    }
1909
1910    /// The shared TableFormer slot handed to each worker, or `None` when the
1911    /// pipeline options skip TableFormer entirely.
1912    fn tables_slot(&self) -> Option<SharedTables> {
1913        if self.no_table_former || self.no_ocr {
1914            None
1915        } else {
1916            Some(Arc::clone(&self.tables))
1917        }
1918    }
1919
1920    /// The shared enrichment slots for a worker (`None` per model unless its
1921    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
1922    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
1923        if self.no_ocr || !self.enrich.any() {
1924            return (None, None);
1925        }
1926        (
1927            self.enrich
1928                .picture_classification
1929                .then(|| Arc::clone(&self.classifier)),
1930            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
1931        )
1932    }
1933
1934    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
1935    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
1936    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
1937    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
1938    /// `DocumentConverter.initialize_pipeline`.
1939    pub fn warm_up(&mut self) -> Result<(), PdfError> {
1940        self.primary()?;
1941        Ok(())
1942    }
1943
1944    /// The full-intra serial worker, loaded on first use.
1945    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
1946        if self.primary.is_none() {
1947            self.primary = Some(Worker::load(
1948                intra_threads(),
1949                self.tables_slot(),
1950                self.enrich_slots(),
1951                self.enrich,
1952                self.no_ocr,
1953                self.skip_ocr,
1954                // The mode-shaped spelling (#254) and the flag are one engine
1955                // truth: whichever demands forcing wins, mirroring docling's
1956                // `force_full_page_ocr` → `mode=full_page` bridge.
1957                self.force_full_page_ocr || self.ocr_mode.forces_full_page(),
1958                self.no_text_panels,
1959                self.ocr_lang,
1960                self.ocr_scale,
1961            )?);
1962        }
1963        Ok(self.primary.as_mut().unwrap())
1964    }
1965
1966    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
1967    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
1968    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
1969    /// fans the pages out across the worker pool, reassembled in page order so the
1970    /// output is byte-identical to the serial path.
1971    pub fn convert(
1972        &mut self,
1973        bytes: &[u8],
1974        password: Option<&str>,
1975        name: &str,
1976    ) -> Result<DoclingDocument, PdfError> {
1977        let pages = pdfium_backend::page_count(bytes, password)?;
1978        let range = self.resolve_range(pages)?;
1979        // Serial vs parallel is decided by the pages actually converted: a
1980        // 3-page window over a 500-page PDF should not pay the pool load.
1981        let selected = range.map_or(pages, |(a, b)| b - a + 1);
1982        let doc = if self.target_workers >= 2 && selected >= self.parallel_min {
1983            self.convert_parallel(bytes, password, name, range, selected)?
1984        } else {
1985            self.convert_serial(bytes, password, name, range, selected)?
1986        };
1987        timing::report();
1988        Ok(doc)
1989    }
1990
1991    /// Stream pages one at a time through the primary worker — render → process →
1992    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
1993    fn convert_serial(
1994        &mut self,
1995        bytes: &[u8],
1996        password: Option<&str>,
1997        name: &str,
1998        range: Option<(usize, usize)>,
1999        selected: usize,
2000    ) -> Result<DoclingDocument, PdfError> {
2001        let mut doc = DoclingDocument::new(name);
2002        let mut confs = std::collections::BTreeMap::new();
2003        let render_image = !self.no_ocr;
2004        let extract_text = self.extract_text_layer();
2005        let progress = self.progress.clone();
2006        let mut done = 0usize;
2007        let worker = self.primary()?;
2008        pdfium_backend::for_each_page(
2009            bytes,
2010            password,
2011            render_image,
2012            extract_text,
2013            range,
2014            |n, _total, mut page| {
2015                let (mut nodes, links, conf) = worker.process(n, &mut page)?;
2016                assemble::stamp_page_no(&mut nodes, n + 1);
2017                doc.nodes.extend(nodes);
2018                doc.links.extend(links);
2019                confs.insert(n + 1, conf);
2020                if let Some(cb) = &progress {
2021                    done += 1;
2022                    cb(done, selected);
2023                }
2024                Ok::<(), PdfError>(())
2025            },
2026        )?;
2027        assemble::merge_continuations(&mut doc.nodes);
2028        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes), password);
2029        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2030        Ok(doc)
2031    }
2032
2033    /// Render pages serially on this thread (pdfium) and process them in parallel
2034    /// across the worker pool. A bounded channel applies backpressure so only a
2035    /// handful of page bitmaps are resident at once; results carry their page
2036    /// index and are reassembled in order, so the output is byte-identical to the
2037    /// serial path.
2038    fn convert_parallel(
2039        &mut self,
2040        bytes: &[u8],
2041        password: Option<&str>,
2042        name: &str,
2043        range: Option<(usize, usize)>,
2044        selected: usize,
2045    ) -> Result<DoclingDocument, PdfError> {
2046        self.ensure_pool()?;
2047        let progress = self.progress.clone();
2048        let pages_done = std::sync::atomic::AtomicUsize::new(0);
2049        let n_workers = self.pool.len();
2050        let render_image = !self.no_ocr;
2051        let extract_text = self.extract_text_layer();
2052        let layout_batch = pdf_layout_batch();
2053        // Bound sized so every worker can accumulate a full layout batch while
2054        // rendering stays ahead (and never below the pre-#73 render-ahead of
2055        // two pages per worker); still a hard cap on resident page bitmaps.
2056        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2057        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2058        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
2059        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
2060
2061        // Move the pool into the scope so each worker gets an exclusive `&mut`.
2062        let mut workers = std::mem::take(&mut self.pool);
2063        std::thread::scope(|s| {
2064            for worker in workers.iter_mut() {
2065                let work_rx = Arc::clone(&work_rx);
2066                let results = Arc::clone(&results);
2067                let first_err = Arc::clone(&first_err);
2068                let progress = progress.clone();
2069                let pages_done = &pages_done;
2070                s.spawn(move || {
2071                    worker.run_pool(&work_rx, layout_batch, |idx, out| {
2072                        match out {
2073                            Ok(out) => {
2074                                results.lock().unwrap().push((idx, out));
2075                                if let Some(cb) = &progress {
2076                                    let d = pages_done
2077                                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2078                                        + 1;
2079                                    cb(d, selected);
2080                                }
2081                            }
2082                            Err(e) => {
2083                                let mut slot = first_err.lock().unwrap();
2084                                if slot.is_none() {
2085                                    *slot = Some(e);
2086                                }
2087                            }
2088                        }
2089                        true
2090                    });
2091                });
2092            }
2093            // Render on this thread and feed the workers; backpressure blocks here
2094            // when the channel is full. Dropping `work_tx` afterwards signals the
2095            // workers (recv → Err) to finish.
2096            let render = pdfium_backend::for_each_page(
2097                bytes,
2098                password,
2099                render_image,
2100                extract_text,
2101                range,
2102                |i, _total, page| {
2103                    work_tx
2104                        .send((i, page))
2105                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2106                },
2107            );
2108            drop(work_tx);
2109            if let Err(e) = render {
2110                let mut slot = first_err.lock().unwrap();
2111                if slot.is_none() {
2112                    *slot = Some(e);
2113                }
2114            }
2115        });
2116        // Threads have joined; restore the pool for the next conversion.
2117        self.pool = workers;
2118
2119        if let Some(e) = first_err.lock().unwrap().take() {
2120            return Err(e);
2121        }
2122        let mut results = Arc::try_unwrap(results)
2123            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
2124            .into_inner()
2125            .unwrap();
2126        results.sort_by_key(|(idx, _)| *idx);
2127        let mut doc = DoclingDocument::new(name);
2128        let mut confs = std::collections::BTreeMap::new();
2129        for (idx, (mut nodes, links, conf)) in results {
2130            assemble::stamp_page_no(&mut nodes, idx + 1);
2131            doc.nodes.extend(nodes);
2132            doc.links.extend(links);
2133            confs.insert(idx + 1, conf);
2134        }
2135        assemble::merge_continuations(&mut doc.nodes);
2136        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes), password);
2137        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2138        Ok(doc)
2139    }
2140
2141    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
2142    /// in-document-order batch of nodes (and that span's recovered links) as pages
2143    /// complete, so a caller can serialize Markdown page by page instead of waiting
2144    /// for the whole document. The batches are exactly the buffered [`convert`]'s
2145    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
2146    /// parallel path reorders pages back into document order before emitting, so
2147    /// the output is identical regardless of worker scheduling.
2148    ///
2149    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
2150    /// and its backpressure throttles the whole pipeline. Returning `Err` from
2151    /// `emit` aborts the conversion with that error.
2152    pub fn convert_streaming<F>(
2153        &mut self,
2154        bytes: &[u8],
2155        password: Option<&str>,
2156        name: &str,
2157        emit: F,
2158    ) -> Result<(), PdfError>
2159    where
2160        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2161    {
2162        let _ = name; // page nodes carry no name; the caller owns the document name.
2163        let pages = pdfium_backend::page_count(bytes, password)?;
2164        let range = self.resolve_range(pages)?;
2165        let selected = range.map_or(pages, |(a, b)| b - a + 1);
2166        let r = if self.target_workers >= 2 && selected >= self.parallel_min {
2167            self.convert_streaming_parallel(bytes, password, range, emit)
2168        } else {
2169            self.convert_streaming_serial(bytes, password, range, emit)
2170        };
2171        timing::report();
2172        r
2173    }
2174
2175    /// Serial streaming: render → process → emit, one page at a time, holding back
2176    /// only the tail that might still merge into the next page.
2177    fn convert_streaming_serial<F>(
2178        &mut self,
2179        bytes: &[u8],
2180        password: Option<&str>,
2181        range: Option<(usize, usize)>,
2182        mut emit: F,
2183    ) -> Result<(), PdfError>
2184    where
2185        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2186    {
2187        let mut asm = assemble::StreamAssembler::new();
2188        let render_image = !self.no_ocr;
2189        let extract_text = self.extract_text_layer();
2190        let worker = self.primary()?;
2191        pdfium_backend::for_each_page(
2192            bytes,
2193            password,
2194            render_image,
2195            extract_text,
2196            range,
2197            |n, _total, mut page| {
2198                // Confidence is dropped on the streaming path: the report is
2199                // only complete once every page has run, which defeats
2200                // page-by-page emission — buffered `convert` carries it.
2201                let (nodes, links, _conf) = worker.process(n, &mut page)?;
2202                emit(asm.push(nodes), links)
2203            },
2204        )?;
2205        emit(asm.finish(), Vec::new())
2206    }
2207
2208    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
2209    /// not thread-safe) and process across the worker pool; results carry their
2210    /// page index and are reordered on the calling thread into a
2211    /// [`assemble::StreamAssembler`], which emits each page in document order as
2212    /// soon as its predecessors have arrived. Bounded channels keep only a handful
2213    /// of pages resident and let `emit`'s backpressure reach the renderer.
2214    fn convert_streaming_parallel<F>(
2215        &mut self,
2216        bytes: &[u8],
2217        password: Option<&str>,
2218        range: Option<(usize, usize)>,
2219        mut emit: F,
2220    ) -> Result<(), PdfError>
2221    where
2222        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2223    {
2224        self.ensure_pool()?;
2225        let n_workers = self.pool.len();
2226        let render_image = !self.no_ocr;
2227        let extract_text = self.extract_text_layer();
2228        let layout_batch = pdf_layout_batch();
2229        // Bound sized so every worker can accumulate a full layout batch while
2230        // rendering stays ahead (and never below the pre-#73 render-ahead of
2231        // two pages per worker); still a hard cap on resident page bitmaps.
2232        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2233        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2234        // Workers and the renderer report here; the calling thread drains it in
2235        // page order. Bounded so workers block (bounding resident bitmaps) when the
2236        // consumer falls behind.
2237        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
2238
2239        let mut workers = std::mem::take(&mut self.pool);
2240        let mut asm = assemble::StreamAssembler::new();
2241        let mut first_err: Option<PdfError> = None;
2242
2243        std::thread::scope(|s| {
2244            // Workers: pull a batch of pages (whatever is already rendered, up
2245            // to the layout batch size), process it, report (index-tagged)
2246            // results.
2247            for worker in workers.iter_mut() {
2248                let work_rx = Arc::clone(&work_rx);
2249                let res_tx = res_tx.clone();
2250                s.spawn(move || {
2251                    worker.run_pool(&work_rx, layout_batch, |idx, out| {
2252                        // `false` once the consumer is gone.
2253                        res_tx.send(out.map(|o| (idx, o))).is_ok()
2254                    });
2255                });
2256            }
2257            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
2258            // single thread); report a render error through the same channel.
2259            {
2260                let res_tx = res_tx.clone();
2261                s.spawn(move || {
2262                    let render = pdfium_backend::for_each_page(
2263                        bytes,
2264                        password,
2265                        render_image,
2266                        extract_text,
2267                        range,
2268                        |i, _total, page| {
2269                            work_tx
2270                                .send((i, page))
2271                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2272                        },
2273                    );
2274                    drop(work_tx); // signal workers to finish
2275                    if let Err(e) = render {
2276                        let _ = res_tx.send(Err(e));
2277                    }
2278                });
2279            }
2280            // Drop our own sender so the channel closes once the threads finish.
2281            drop(res_tx);
2282
2283            // Collector (this thread): reorder into document order and emit.
2284            // With a page window, indices start at the window's first page.
2285            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
2286            let mut next = range.map_or(0, |(first, _)| first);
2287            for msg in res_rx.iter() {
2288                match msg {
2289                    Err(e) => {
2290                        if first_err.is_none() {
2291                            first_err = Some(e);
2292                        }
2293                    }
2294                    Ok((idx, out)) => {
2295                        buffer.insert(idx, out);
2296                        if first_err.is_some() {
2297                            continue; // keep draining so the threads can exit
2298                        }
2299                        while let Some((nodes, links, _conf)) = buffer.remove(&next) {
2300                            if let Err(e) = emit(asm.push(nodes), links) {
2301                                first_err = Some(e);
2302                                break;
2303                            }
2304                            next += 1;
2305                        }
2306                    }
2307                }
2308            }
2309        });
2310        // Threads have joined; restore the pool for the next conversion.
2311        self.pool = workers;
2312
2313        if let Some(e) = first_err {
2314            return Err(e);
2315        }
2316        emit(asm.finish(), Vec::new())
2317    }
2318
2319    /// Lazily grow the pool to `target_workers`, loading the new workers
2320    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
2321    /// one load's wall-time). Cached for reuse across documents.
2322    fn ensure_pool(&mut self) -> Result<(), PdfError> {
2323        let need = self.target_workers.saturating_sub(self.pool.len());
2324        if need == 0 {
2325            return Ok(());
2326        }
2327        let intra = pdf_intra();
2328        let no_ocr = self.no_ocr;
2329        let skip_ocr = self.skip_ocr;
2330        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2331        let ntp = self.no_text_panels;
2332        let ocr_lang = self.ocr_lang;
2333        let ocr_scale = self.ocr_scale;
2334        let enrich = self.enrich;
2335        let tables = self.tables_slot();
2336        let enrich_slots = self.enrich_slots();
2337        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
2338            let handles: Vec<_> = (0..need)
2339                .map(|_| {
2340                    let tables = tables.clone();
2341                    let enrich_slots = enrich_slots.clone();
2342                    s.spawn(move || {
2343                        Worker::load(
2344                            intra,
2345                            tables,
2346                            enrich_slots,
2347                            enrich,
2348                            no_ocr,
2349                            skip_ocr,
2350                            force,
2351                            ntp,
2352                            ocr_lang,
2353                            ocr_scale,
2354                        )
2355                    })
2356                })
2357                .collect();
2358            handles.into_iter().map(|h| h.join().unwrap()).collect()
2359        });
2360        for w in loaded {
2361            self.pool.push(w?);
2362        }
2363        Ok(())
2364    }
2365
2366    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
2367    /// docling routes images through the same layout+OCR pipeline as a PDF page.
2368    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2369        let image = decode_image_limited(bytes)?;
2370        let (w, h) = image.dimensions();
2371        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
2372        // standalone image has no text layer, so OCR supplies the cells.
2373        let page = PdfPage {
2374            width: w as f32,
2375            height: h as f32,
2376            scale: 1.0,
2377            cells: Vec::new(),
2378            code_cells: Vec::new(),
2379            word_cells: Vec::new(),
2380            // A standalone image *is* its own scale-1.0 page image, so the
2381            // layout model sees it through the docling-exact PIL kernel.
2382            image_layout: Some(image.clone()),
2383            image,
2384            links: Vec::new(),
2385            rotation: 0,
2386        };
2387        self.process_pages(vec![page], name)
2388    }
2389
2390    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
2391    /// page (image / METS inputs, which are small and already materialised).
2392    /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
2393    /// caller-configured pipeline (#244).
2394    pub fn process_pages(
2395        &mut self,
2396        mut pages: Vec<PdfPage>,
2397        name: &str,
2398    ) -> Result<DoclingDocument, PdfError> {
2399        let mut doc = DoclingDocument::new(name);
2400        let mut confs = std::collections::BTreeMap::new();
2401        let worker = self.primary()?;
2402        for (n, page) in pages.iter_mut().enumerate() {
2403            let (mut nodes, links, conf) = worker.process(n, page)?;
2404            assemble::stamp_page_no(&mut nodes, n + 1);
2405            doc.nodes.extend(nodes);
2406            doc.links.extend(links);
2407            confs.insert(n + 1, conf);
2408        }
2409        assemble::merge_continuations(&mut doc.nodes);
2410        // No PDF behind these pages (images, METS): the heading-hierarchy
2411        // stage degrades to the numbering signal — exactly docling without
2412        // an outline or parsed pages.
2413        self.apply_heading_hierarchy(&mut doc.nodes, None, None);
2414        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2415        Ok(doc)
2416    }
2417}
2418
2419/// Number of pages in a PDF, without converting anything — what the CLI batch
2420/// mode prints in its per-document start line.
2421#[cfg(feature = "ml")]
2422pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
2423    Ok(pdfium_backend::page_count(bytes, password)?)
2424}
2425
2426#[cfg(feature = "ml")]
2427/// Convenience one-shot conversion (loads the pipeline per call). Errors are
2428/// detailed and surfaced (never silently skipped).
2429pub fn convert(
2430    bytes: &[u8],
2431    password: Option<&str>,
2432    name: &str,
2433) -> Result<DoclingDocument, PdfError> {
2434    convert_with_options(
2435        bytes,
2436        password,
2437        name,
2438        false,
2439        false,
2440        false,
2441        false,
2442        EnrichmentOptions::default(),
2443        None,
2444        None,
2445    )
2446}
2447
2448#[cfg(feature = "ml")]
2449/// Like [`convert`], but optionally skips loading/running TableFormer (see
2450/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2451/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
2452/// [`Pipeline::enrichments`]).
2453// One positional per pipeline switch mirrors the Pipeline builder; growing
2454// past clippy's arity cap is the price of keeping this one-shot signature
2455// stable-ish instead of churning callers into an options struct mid-series.
2456#[allow(clippy::too_many_arguments)]
2457pub fn convert_with_options(
2458    bytes: &[u8],
2459    password: Option<&str>,
2460    name: &str,
2461    no_table_former: bool,
2462    no_ocr: bool,
2463    force_full_page_ocr: bool,
2464    no_text_panels: bool,
2465    enrich: EnrichmentOptions,
2466    pages: Option<(usize, usize)>,
2467    ocr_lang: Option<OcrLang>,
2468) -> Result<DoclingDocument, PdfError> {
2469    Pipeline::new()?
2470        .no_table_former(no_table_former)
2471        .no_ocr(no_ocr)
2472        .force_full_page_ocr(force_full_page_ocr)
2473        .no_text_panels(no_text_panels)
2474        .enrichments(enrich)
2475        .pages(pages)
2476        .ocr_lang(ocr_lang)
2477        .convert(bytes, password, name)
2478}
2479
2480#[cfg(feature = "ml")]
2481/// Convenience one-shot image conversion (loads the pipeline per call).
2482pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2483    convert_image_with_options(
2484        bytes,
2485        name,
2486        false,
2487        false,
2488        false,
2489        EnrichmentOptions::default(),
2490        None,
2491    )
2492}
2493
2494#[cfg(feature = "ml")]
2495/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
2496/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2497/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2498pub fn convert_image_with_options(
2499    bytes: &[u8],
2500    name: &str,
2501    no_table_former: bool,
2502    no_ocr: bool,
2503    no_text_panels: bool,
2504    enrich: EnrichmentOptions,
2505    ocr_lang: Option<OcrLang>,
2506) -> Result<DoclingDocument, PdfError> {
2507    Pipeline::new()?
2508        .no_table_former(no_table_former)
2509        .no_ocr(no_ocr)
2510        .no_text_panels(no_text_panels)
2511        .enrichments(enrich)
2512        .ocr_lang(ocr_lang)
2513        .convert_image(bytes, name)
2514}
2515
2516#[cfg(feature = "ml")]
2517/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
2518/// scans) through the shared layout + assembly pipeline.
2519pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
2520    convert_pages_with_options(
2521        pages,
2522        name,
2523        false,
2524        false,
2525        false,
2526        EnrichmentOptions::default(),
2527    )
2528}
2529
2530#[cfg(feature = "ml")]
2531/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
2532/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2533/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2534pub fn convert_pages_with_options(
2535    pages: Vec<PdfPage>,
2536    name: &str,
2537    no_table_former: bool,
2538    no_ocr: bool,
2539    no_text_panels: bool,
2540    enrich: EnrichmentOptions,
2541) -> Result<DoclingDocument, PdfError> {
2542    Pipeline::new()?
2543        .no_table_former(no_table_former)
2544        .no_text_panels(no_text_panels)
2545        .no_ocr(no_ocr)
2546        .enrichments(enrich)
2547        .process_pages(pages, name)
2548}
2549
2550#[cfg(feature = "ml")]
2551#[cfg(all(test, feature = "ml"))]
2552mod image_limit_tests {
2553    use super::decode_image_with_max_side;
2554
2555    /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
2556    /// byte literal).
2557    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
2558        use std::io::Cursor;
2559        let img = image::RgbImage::new(w, h);
2560        let mut out = Vec::new();
2561        img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
2562            .unwrap();
2563        out
2564    }
2565
2566    #[test]
2567    fn normal_image_decodes_under_the_cap() {
2568        let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
2569        assert_eq!(img.dimensions(), (8, 8));
2570    }
2571
2572    #[test]
2573    fn dimensions_over_the_cap_are_rejected_not_aborted() {
2574        // A per-side cap below the image's declared size must yield a
2575        // recoverable Err, never an allocation-abort — the mechanism that stops
2576        // a crafted image declaring 60000×60000 from OOM-killing the process.
2577        let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
2578        assert!(
2579            r.is_err(),
2580            "decode must fail under the pixel cap, not abort"
2581        );
2582    }
2583}
2584
2585#[cfg(test)]
2586mod median_tests {
2587    #[test]
2588    fn median_of_empty_is_zero_not_a_panic() {
2589        // A crafted table can leave a row/column with zero matched cells; the
2590        // even-count branch would index values[0 - 1] and panic (→ remote crash
2591        // via docling-serve) without the empty guard.
2592        assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
2593        assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
2594        assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
2595    }
2596}
2597
2598#[cfg(test)]
2599mod send_check {
2600    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
2601    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
2602    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
2603    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
2604    fn assert_send<T: Send>() {}
2605
2606    #[test]
2607    fn pipeline_is_send() {
2608        assert_send::<super::Pipeline>();
2609    }
2610}
2611
2612#[cfg(all(test, feature = "ml"))]
2613mod ocr_input_tests {
2614    /// #254: without an `ocr_scale` (or with one equal to the render scale)
2615    /// the OCR reads the page render untouched and the cache stays cold; a
2616    /// different scale builds one resampled view, reuses it across calls, and
2617    /// reports the requested px/pt so cell geometry divides back to points.
2618    #[test]
2619    fn ocr_input_resamples_only_on_a_real_scale_change() {
2620        let img = image::RgbImage::new(200, 100);
2621        let mut cache = None;
2622        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, None);
2623        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
2624        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(2.0));
2625        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
2626
2627        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
2628        assert_eq!((v.width(), v.height(), s), (300, 150, 3.0));
2629        let first = cache.as_ref().map(|c| c as *const image::RgbImage);
2630        let (v, _) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
2631        assert_eq!(
2632            Some(v as *const image::RgbImage),
2633            first,
2634            "cached, not rebuilt"
2635        );
2636
2637        let mut down = None;
2638        let (v, s) = super::ocr_input(&mut down, &img, 2.0, Some(1.0));
2639        assert_eq!((v.width(), v.height(), s), (100, 50, 1.0));
2640    }
2641}