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