Skip to main content

docling_pdf/
lib.rs

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