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