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.
28#[cfg(feature = "ml")]
29pub mod ep;
30pub mod layout;
31#[cfg(feature = "ml")]
32mod mets;
33#[cfg(feature = "ml")]
34mod ocr;
35#[cfg(feature = "ocr-prep")]
36pub mod ocr_prep;
37#[cfg(feature = "ml")]
38mod orient;
39pub mod pdfium_backend;
40#[cfg(feature = "ml")]
41pub mod quality;
42mod reading_order;
43// Pure-Rust region resampling (page→1024px box-average, crop→448 bilinear) —
44// available to the browser TableFormer path (#157 stage 3), not just `ml`.
45#[cfg(feature = "ocr-prep")]
46pub mod resample;
47#[cfg(feature = "ocr-prep")]
48pub mod scanned;
49// Built-in standard-14 font metrics for the pure-Rust text parser (#187) —
50// no feature gate: the wasm/pdf-text path needs them like the native one.
51mod std14;
52#[cfg(feature = "ml")]
53pub mod tableformer;
54pub mod textparse;
55#[cfg(feature = "ocr-prep")]
56pub mod tf_core;
57// docling's TableFormer cell matcher — pure Rust, shared with the browser
58// TableFormer path (#157 stage 3).
59#[cfg(feature = "ocr-prep")]
60pub mod tf_match;
61pub mod timing;
62
63#[cfg(feature = "ml")]
64use std::collections::BTreeMap;
65use std::fmt;
66#[cfg(feature = "ml")]
67use std::sync::mpsc::{sync_channel, Receiver};
68#[cfg(feature = "ml")]
69use std::sync::{Arc, Mutex};
70
71use docling_core::DoclingDocument;
72// The env-knob helpers only gate ML-pipeline diagnostics and tuning; the
73// pure text-layer (wasm) build has no call sites.
74#[cfg(feature = "ml")]
75use docling_core::Node;
76#[cfg(feature = "ml")]
77use docling_core::{debug_log, env};
78
79#[cfg(feature = "ml")]
80pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options};
81#[cfg(feature = "ml")]
82pub use ocr::OcrLang;
83#[cfg(feature = "ml")]
84pub use pdfium_backend::PdfDocument;
85pub use pdfium_backend::{PdfPage, TextCell};
86
87/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
88#[derive(Debug)]
89pub enum PdfError {
90    /// pdfium failed to bind, open, or read the document.
91    Pdfium(String),
92    /// The layout ONNX model failed to load or run.
93    Layout(String),
94    /// The OCR ONNX model failed to load or run.
95    Ocr(String),
96}
97
98impl fmt::Display for PdfError {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        match self {
101            PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
102            PdfError::Layout(m) => write!(f, "pdf: {m}"),
103            PdfError::Ocr(m) => write!(f, "pdf: {m}"),
104        }
105    }
106}
107
108impl std::error::Error for PdfError {}
109
110#[cfg(feature = "ml")]
111impl From<pdfium_render::prelude::PdfiumError> for PdfError {
112    fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
113        // A failed dlopen means pdfium was never installed — the #1 first-run
114        // failure after a bare `cargo install` (which ships no runtime
115        // assets). Say what to do instead of leaking the raw loader error.
116        if matches!(e, pdfium_render::prelude::PdfiumError::LoadLibraryError(_)) {
117            // The loader error pretty-prints over several lines; compact it.
118            let detail = e
119                .to_string()
120                .split_whitespace()
121                .collect::<Vec<_>>()
122                .join(" ");
123            return PdfError::Pdfium(format!(
124                "the pdfium library is not installed. PDF/image conversion needs \
125                 pdfium + the ONNX models: fetch both with \
126                 scripts/install/download_dependencies.sh from a docling.rs \
127                 checkout (https://github.com/docling-project/docling.rs), or \
128                 point PDFIUM_DYNAMIC_LIB_PATH at a directory containing the \
129                 pdfium library. A digital PDF's embedded text layer converts \
130                 without either in no-OCR mode (CLI: --no-ocr). Declarative \
131                 formats (DOCX, HTML, Markdown, …) never need them. [{detail}]"
132            ));
133        }
134        PdfError::Pdfium(e.to_string())
135    }
136}
137
138/// Convert a PDF's **embedded text layer only** — no pdfium, no ONNX, no
139/// threads: the pure-Rust content-stream parser ([`textparse`]) feeds the same
140/// orphan-region assembly the `no_ocr` pipeline flag uses, so text-layer PDFs
141/// come out identical to `--no-ocr` (flat, line-grouped paragraphs in reading
142/// order; no headings/lists/tables/pictures, and no hyperlink recovery).
143///
144/// This is the only conversion entry compiled without the `ml` feature (it is
145/// what a wasm32 build runs). A scanned/image-only PDF (no embedded text
146/// layer) yields an empty document rather than an error, same as `no_ocr` —
147/// callers can detect that and fall back to an OCR-capable build.
148pub fn convert_text_layer(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
149    convert_text_layer_pages(bytes, name, None)
150}
151
152/// [`convert_text_layer`] restricted to a **1-based inclusive** page window
153/// (issue #80's `--pages`); `None` converts everything. The window is
154/// validated the same way as [`Pipeline::pages`]: `first <= last`, 1-based,
155/// and it must select at least one existing page.
156pub fn convert_text_layer_pages(
157    bytes: &[u8],
158    name: &str,
159    pages: Option<(usize, usize)>,
160) -> Result<DoclingDocument, PdfError> {
161    if let Some((first, last)) = pages {
162        if first == 0 || last < first {
163            return Err(PdfError::Pdfium(format!(
164                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
165            )));
166        }
167    }
168    let mut doc = DoclingDocument::new(name);
169    let mut total = 0usize;
170    let parsed = textparse::pdf_text_pages(bytes);
171    // A vestigial layer (a few typed-in form fields over scanned pages) is not
172    // the document's text: return the empty document, which callers already
173    // report as "no text layer" — so an OCR-capable caller falls back to OCR
174    // instead of proudly extracting thirteen characters.
175    if textparse::text_layer_is_vestigial(&parsed) {
176        return Ok(doc);
177    }
178    for (i, page) in parsed.into_iter().enumerate() {
179        total += 1;
180        if let Some((first, last)) = pages {
181            if i + 1 < first || i + 1 > last {
182                continue;
183            }
184        }
185        let mut regions = Vec::new();
186        assemble::add_orphan_regions(&mut regions, &page.cells);
187        let table_rows = vec![None; regions.len()];
188        let enrich_out = vec![None; regions.len()];
189        let (mut nodes, links) = assemble::assemble_page(&page, regions, &table_rows, &enrich_out);
190        assemble::stamp_page_no(&mut nodes, i + 1);
191        doc.nodes.extend(nodes);
192        doc.links.extend(links);
193    }
194    if let Some((first, last)) = pages {
195        if first > total {
196            return Err(PdfError::Pdfium(format!(
197                "page range {first}-{last} is outside the document ({total} page(s))"
198            )));
199        }
200    }
201    assemble::merge_continuations(&mut doc.nodes);
202    Ok(doc)
203}
204
205/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
206/// Defaults to the available parallelism (ort otherwise picks a low number).
207#[cfg(feature = "ml")]
208pub(crate) fn intra_threads() -> usize {
209    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_THREADS").filter(|&n| n > 0) {
210        return n;
211    }
212    std::thread::available_parallelism()
213        .map(|n| n.get())
214        .unwrap_or(1)
215}
216
217#[cfg(feature = "ml")]
218/// True when `DOCLING_RS_FP32` forces the full-precision models even where
219/// an INT8 variant sits next to the fp32 default.
220pub(crate) fn fp32_forced() -> bool {
221    env::flag("DOCLING_RS_FP32")
222}
223
224#[cfg(feature = "ml")]
225/// Should the int8 model defaults be skipped in favor of fp32? Either the
226/// user said so (`DOCLING_RS_FP32`), or a GPU execution provider is selected
227/// (#74) — the int8 exports are QDQ graphs calibrated for CPU kernels and
228/// only conformance-validated there. An explicit `DOCLING_*_ONNX` path
229/// override still wins over this at every call site.
230pub(crate) fn prefer_fp32() -> bool {
231    fp32_forced() || ep::prefers_fp32()
232}
233
234#[cfg(feature = "ml")]
235/// Resolve a default (CWD-relative) asset path — the shared chain in
236/// [`docling_core::assets`]: CWD, then next to the executable and one level
237/// above it (the `scripts/install/install.sh` layout).
238pub(crate) fn resolve_asset(rel: &str) -> String {
239    docling_core::assets::resolve(rel)
240}
241
242/// One resolved runtime asset — which file a stage would load right now,
243/// given the CWD, the env overrides and the int8/fp32 preference.
244#[cfg(feature = "ml")]
245#[derive(Debug, Clone)]
246pub struct ModelEntry {
247    /// Pipeline stage, e.g. `layout`, `tableformer.decoder`, `ocr.rec`.
248    pub stage: &'static str,
249    /// The resolved path (absolute or CWD-relative, as it will be opened).
250    pub path: String,
251    /// Whether the file exists right now.
252    pub found: bool,
253    /// File size in bytes (0 when missing) — enough to tell an int8 quant
254    /// from an fp32 graph, or a stale model from a re-published one, at a
255    /// glance without hashing gigabytes per request.
256    pub bytes: u64,
257}
258
259/// Resolve the whole runtime model set **without loading anything** — the
260/// exact selection each stage performs at load time (layout honors the
261/// int8/fp32 preference, TableFormer its decoder ranking, OCR the language
262/// pair), plus the pdfium library. docling-serve exposes this at
263/// `/v1/config` and logs it at startup, so "the server picked up different
264/// models" is one `curl` away instead of a mystery of dissolved tables.
265/// Resolution is CWD-relative with an exe-dir fallback, so the answer can
266/// legitimately differ between two working directories.
267#[cfg(feature = "ml")]
268pub fn model_inventory() -> Vec<ModelEntry> {
269    fn entry(stage: &'static str, path: String) -> ModelEntry {
270        let meta = std::fs::metadata(&path).ok();
271        ModelEntry {
272            stage,
273            found: meta.is_some(),
274            bytes: meta.map(|m| m.len()).unwrap_or(0),
275            path,
276        }
277    }
278    let (enc, dec, bbx) = tableformer::resolved_paths();
279    let (rec, dict) = ocr::resolve_rec_pair(ocr::OcrLang::from_env());
280    let pdfium =
281        env::nonempty("PDFIUM_DYNAMIC_LIB_PATH").unwrap_or_else(|| resolve_asset(".pdfium/lib"));
282    vec![
283        entry(
284            "layout",
285            model_path(
286                "DOCLING_LAYOUT_ONNX",
287                ".models/layout_heron.onnx",
288                ".models/layout_heron_int8.onnx",
289            ),
290        ),
291        entry("tableformer.encoder", enc),
292        entry("tableformer.decoder", dec),
293        entry("tableformer.bbox", bbx),
294        entry("ocr.rec", rec),
295        entry("ocr.dict", dict),
296        entry("pdfium", pdfium),
297    ]
298}
299
300/// Resolve a model path: an explicit env override always wins; otherwise the
301/// INT8 variant of the default path when it exists on disk (the quantized
302/// models are conformance-validated — see docs/PDF_CONFORMANCE.md — and load/run
303/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
304/// precision; else the fp32 default.
305#[cfg(feature = "ml")]
306pub(crate) fn model_path(key: &str, fp32_default: &str, int8_default: &str) -> String {
307    if let Some(p) = env::nonempty(key) {
308        return p;
309    }
310    if !prefer_fp32() {
311        let p = resolve_asset(int8_default);
312        if std::path::Path::new(&p).exists() {
313            return p;
314        }
315    }
316    resolve_asset(fp32_default)
317}
318
319/// Decode a standalone image with hard resource limits. A crafted image can
320/// declare enormous dimensions in a few-KB file; `image::load_from_memory`
321/// then tries to allocate the full pixel buffer (e.g. 60000×60000 → ~10 GB),
322/// and allocation failure aborts the whole process, bypassing the per-request
323/// panic catch. The 256 MiB alloc / 30000-px caps below turn that into a
324/// recoverable decode error instead. `DOCLING_RS_MAX_IMAGE_PIXELS` overrides
325/// the per-side pixel cap for the rare legitimately-huge scan.
326///
327/// Gated on `ml`: the only callers (`convert_image`, the METS backend) are
328/// ML-only, and the `image` crate is an `ml`-feature dependency — the
329/// text-layer wasm build has neither.
330#[cfg(feature = "ml")]
331pub(crate) fn decode_image_limited(bytes: &[u8]) -> Result<image::RgbImage, PdfError> {
332    let max_side: u32 = env::parse("DOCLING_RS_MAX_IMAGE_PIXELS").unwrap_or(30_000);
333    decode_image_with_max_side(bytes, max_side)
334}
335
336/// Whether `bytes` is an ISOBMFF HEIF/HEIC container (the `ftyp` brands
337/// iPhones write). Checked by content, not extension — HEIC regularly
338/// arrives misnamed `.jpg`.
339#[cfg(feature = "ml")]
340fn is_heif(bytes: &[u8]) -> bool {
341    bytes.len() >= 12
342        && &bytes[4..8] == b"ftyp"
343        && matches!(
344            &bytes[8..12],
345            b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"hevs" | b"mif1" | b"msf1"
346        )
347}
348
349/// Decode a HEIF/HEIC primary image via libheif (#211). Behind the opt-in
350/// `heif` feature — libheif is a native dependency the default build (and
351/// wasm) must not carry.
352#[cfg(all(feature = "ml", feature = "heif"))]
353fn decode_heif(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
354    use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
355    let err = |e: String| PdfError::Pdfium(format!("heif: {e}"));
356    let ctx = HeifContext::read_from_bytes(bytes).map_err(|e| err(e.to_string()))?;
357    let handle = ctx.primary_image_handle().map_err(|e| err(e.to_string()))?;
358    if handle.width() > max_side || handle.height() > max_side {
359        return Err(err(format!(
360            "image dimensions {}x{} exceed the {max_side}px per-side cap \
361             (DOCLING_RS_MAX_IMAGE_PIXELS overrides)",
362            handle.width(),
363            handle.height()
364        )));
365    }
366    let lib = LibHeif::new();
367    let img = lib
368        .decode(&handle, ColorSpace::Rgb(RgbChroma::Rgb), None)
369        .map_err(|e| err(e.to_string()))?;
370    let (w, h) = (img.width(), img.height());
371    let planes = img.planes();
372    let plane = planes
373        .interleaved
374        .ok_or_else(|| err("no RGB plane".into()))?;
375    let stride = plane.stride;
376    let mut out = image::RgbImage::new(w, h);
377    for (y, row) in out.rows_mut().enumerate() {
378        let src = &plane.data[y * stride..y * stride + w as usize * 3];
379        for (x, px) in row.enumerate() {
380            px.0 = [src[x * 3], src[x * 3 + 1], src[x * 3 + 2]];
381        }
382    }
383    Ok(out)
384}
385
386#[cfg(feature = "ml")]
387fn decode_image_with_max_side(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
388    use image::ImageReader;
389    use std::io::Cursor;
390
391    if is_heif(bytes) {
392        #[cfg(feature = "heif")]
393        return decode_heif(bytes, max_side);
394        #[cfg(not(feature = "heif"))]
395        return Err(PdfError::Pdfium(
396            "HEIC/HEIF input needs a build with the `heif` cargo feature \
397             (rebuild with --features heif; links the system libheif)"
398                .into(),
399        ));
400    }
401
402    let mut limits = image::Limits::default();
403    limits.max_image_width = Some(max_side);
404    limits.max_image_height = Some(max_side);
405    limits.max_alloc = Some(256 * 1024 * 1024);
406
407    let mut reader = ImageReader::new(Cursor::new(bytes))
408        .with_guessed_format()
409        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
410    reader.limits(limits);
411    Ok(reader
412        .decode()
413        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?
414        .into_rgb8())
415}
416
417#[cfg(feature = "ml")]
418/// One page's assembled output: typed nodes plus the page's hyperlinks (kept
419/// separate so pages processed out of order can be stitched back in page
420/// order) and its confidence scores (#183).
421type PageOut = (
422    Vec<Node>,
423    Vec<(String, String)>,
424    docling_core::confidence::PageConfidence,
425);
426
427#[cfg(feature = "ml")]
428/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
429/// lazily on the first table region any worker sees. Tables appear on a
430/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
431/// weights+arenas by the pool size for nothing; a single shared instance keeps
432/// the peak flat regardless of pool width, and a table's structure prediction
433/// is independent of which worker runs it, so output is byte-identical. The
434/// mutex serialises concurrent tables — the shared instance is loaded with the
435/// full intra-op thread budget to compensate (one wide TableFormer instead of
436/// several narrow ones).
437enum TfSlot {
438    /// Not attempted yet (no table seen so far).
439    Unloaded,
440    /// Load attempted, graphs absent — geometric fallback (warned once).
441    Missing,
442    Ready(tableformer::TableFormer),
443}
444
445#[cfg(feature = "ml")]
446type SharedTables = Arc<Mutex<TfSlot>>;
447
448#[cfg(feature = "ml")]
449/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
450/// one instance per pipeline, loaded on the first region that needs it.
451enum EnrichSlot<T> {
452    Unloaded,
453    /// Load attempted, model files absent — enrichment skipped (warned once).
454    Missing,
455    Ready(T),
456}
457
458#[cfg(feature = "ml")]
459type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
460#[cfg(feature = "ml")]
461type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
462
463#[cfg(feature = "ml")]
464/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
465/// flags (`do_picture_classification`, `do_code_enrichment`,
466/// `do_formula_enrichment`). All off by default.
467#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
468pub struct EnrichmentOptions {
469    /// Classify each picture with DocumentFigureClassifier (26 classes).
470    pub picture_classification: bool,
471    /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
472    pub code: bool,
473    /// Decode display formulas to LaTeX with CodeFormulaV2.
474    pub formula: bool,
475}
476
477#[cfg(feature = "ml")]
478impl EnrichmentOptions {
479    fn any(&self) -> bool {
480        self.picture_classification || self.code || self.formula
481    }
482}
483
484#[cfg(feature = "ml")]
485/// The layout model's input for a page: the docling-exact scale-1.0 page
486/// image when the renderer produced one, else the legacy stretch of the 2×
487/// bitmap (browser / METS paths) — see [`layout::LayoutSrc`]. Public so the
488/// diagnostic examples feed [`layout::LayoutModel::predict`] the same input
489/// the pipeline does.
490pub fn layout_src(page: &PdfPage) -> layout::LayoutSrc<'_> {
491    match &page.image_layout {
492        Some(img) => layout::LayoutSrc::PageImage(img),
493        None => layout::LayoutSrc::Raw(&page.image),
494    }
495}
496
497#[cfg(feature = "ml")]
498/// A self-contained set of the per-page models (layout, OCR). Each parallel
499/// page-worker owns its own `Worker` so inference runs concurrently without
500/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
501/// rarely-hit TableFormer is shared (see [`TfSlot`]).
502struct Worker {
503    /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
504    layout: Option<layout::LayoutModel>,
505    ocr: Option<ocr::OcrModel>,
506    /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
507    tables: Option<SharedTables>,
508    /// Shared enrichment slots; `None` unless the corresponding flag is on.
509    classifier: Option<SharedClassifier>,
510    code_formula: Option<SharedCodeFormula>,
511    enrich: EnrichmentOptions,
512    /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
513    /// embedded text layer. See [`Pipeline::no_ocr`].
514    no_ocr: bool,
515    /// Discard the embedded text layer and OCR every page. See
516    /// [`Pipeline::force_full_page_ocr`].
517    force_full_page_ocr: bool,
518    /// Keep text-panel pictures as pictures instead of demoting them to
519    /// paragraphs. See [`Pipeline::no_text_panels`].
520    no_text_panels: bool,
521    /// Which recognition model [`Self::ocr`] loads. See [`Pipeline::ocr_lang`].
522    ocr_lang: ocr::OcrLang,
523}
524
525#[cfg(feature = "ml")]
526impl Worker {
527    #[allow(clippy::too_many_arguments)] // mirrors the Pipeline's option set
528    fn load(
529        intra: usize,
530        tables: Option<SharedTables>,
531        enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
532        enrich: EnrichmentOptions,
533        no_ocr: bool,
534        force_full_page_ocr: bool,
535        no_text_panels: bool,
536        ocr_lang: ocr::OcrLang,
537    ) -> Result<Self, PdfError> {
538        Ok(Self {
539            layout: if no_ocr {
540                None
541            } else {
542                Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
543            },
544            ocr: None,
545            tables,
546            classifier: enrich_slots.0,
547            code_formula: enrich_slots.1,
548            enrich,
549            no_ocr,
550            force_full_page_ocr,
551            no_text_panels,
552            ocr_lang,
553        })
554    }
555
556    /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
557    /// into its nodes and links. Pure given the page (mutates only the worker's
558    /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
559    fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
560        if self.no_ocr {
561            // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
562            // embedded text cells (if any) become flat, line-grouped paragraphs in
563            // reading order via the same orphan-region machinery that normally
564            // rescues text the detector missed — here it rescues *all* of it.
565            // Pages with no embedded text layer (scanned/image-only) yield nothing;
566            // convert those without `no_ocr`.
567            let parse = quality::parse_score(&page.cells);
568            let mut regions = Vec::new();
569            assemble::add_orphan_regions(&mut regions, &page.cells);
570            let table_rows = vec![None; regions.len()];
571            let enrich_out = vec![None; regions.len()];
572            let conf = quality::page_confidence(parse, &regions, &[]);
573            let (nodes, links) = timing::timed("assemble_page", || {
574                assemble::assemble_page(page, regions, &table_rows, &enrich_out)
575            });
576            return Ok((nodes, links, conf));
577        }
578        self.normalize_orientation(n, page)?;
579        let regions = timing::timed("layout.predict", || {
580            self.layout
581                .as_mut()
582                .expect("layout model loaded unless no_ocr")
583                .predict(layout_src(page), page.width, page.height)
584        })
585        .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
586        self.finish_page(n, page, regions)
587    }
588
589    /// Content-based orientation normalization (#225), before any inference:
590    /// a physically rotated scan (sideways phone photo, landscape-fed sheet)
591    /// has `/Rotate 0`, so the metadata pass in `extract_page` never fires and
592    /// layout+OCR would read a sideways raster. Only pages with no text layer
593    /// at all are probed (a digital page's raster is upright by construction,
594    /// and its cells — not its pixels — carry the text); the detected angle
595    /// composes with any `/Rotate` normalization through the same
596    /// [`PdfPage::unrotate`] + display-space assembly mapping. Detection is
597    /// evidence-gated and degrades to a no-op — see [`orient`].
598    fn normalize_orientation(&mut self, n: usize, page: &mut PdfPage) -> Result<(), PdfError> {
599        let scanned =
600            page.cells.is_empty() && page.word_cells.is_empty() && page.code_cells.is_empty();
601        if self.no_ocr || !scanned || page.image.width() <= 1 || !orient::enabled() {
602            return Ok(());
603        }
604        if self.ocr.is_none() {
605            self.ocr = Some(ocr::OcrModel::load(self.ocr_lang).map_err(PdfError::Ocr)?);
606        }
607        let deg = timing::timed("orient.detect", || {
608            orient::detect(&page.image, self.ocr.as_mut().unwrap())
609        });
610        if deg != 0 {
611            debug_log!(
612                "docling-pdf: page {}: content rotated {deg}° in the raster; \
613                 un-rotating before layout/OCR",
614                n + 1
615            );
616            page.unrotate(deg);
617        }
618        Ok(())
619    }
620
621    /// Layout-detect a whole batch of pages with one inference call (issue #73),
622    /// then run each page's remaining stages (OCR / TableFormer / enrichment /
623    /// assembly) per page. Index-aligned with `items`; a layout failure fails
624    /// every page in the batch (they shared the one inference call).
625    fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<PageOut, PdfError>> {
626        if self.no_ocr {
627            // No layout model to batch — the text-layer-only path is per page.
628            return items
629                .iter_mut()
630                .map(|(n, page)| {
631                    let n = *n;
632                    self.process(n, page)
633                })
634                .collect();
635        }
636        // Orientation-normalize every scanned page before the shared layout
637        // call — the batched inference must see upright bitmaps too (#225).
638        for (n, page) in items.iter_mut() {
639            let n = *n;
640            if let Err(e) = self.normalize_orientation(n, page) {
641                // Model-load failure — every page in the batch needs the same
642                // model, so they all fail alike (mirrors the layout-error arm).
643                let msg = e.to_string();
644                return items
645                    .iter()
646                    .map(|_| Err(PdfError::Ocr(msg.clone())))
647                    .collect();
648            }
649        }
650        let inputs: Vec<(layout::LayoutSrc<'_>, f32, f32)> = items
651            .iter()
652            .map(|(_, page)| (layout_src(page), page.width, page.height))
653            .collect();
654        let batched = timing::timed("layout.predict", || {
655            self.layout
656                .as_mut()
657                .expect("layout model loaded unless no_ocr")
658                .predict_batch(&inputs)
659        });
660        match batched {
661            Ok(all) => items
662                .iter_mut()
663                .zip(all)
664                .map(|((n, page), regions)| self.finish_page(*n, page, regions))
665                .collect(),
666            Err(e) => items
667                .iter()
668                .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
669                .collect(),
670        }
671    }
672
673    /// Everything after layout detection: per-label confidence thresholds,
674    /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
675    /// TableFormer, enrichment, and page assembly.
676    fn finish_page(
677        &mut self,
678        n: usize,
679        page: &mut PdfPage,
680        regions: Vec<layout::Region>,
681    ) -> Result<PageOut, PdfError> {
682        // Force-OCR is exactly "pretend the text layer is not there": clear
683        // every cell kind the extractors produced before anything reads them,
684        // and the ordinary no-text-layer machinery below — full-page OCR,
685        // OCR-fed TableFormer matching — takes over unchanged. (`no_ocr` wins
686        // when both are set, mirroring docling, where `force_full_page_ocr`
687        // is a sub-option of `do_ocr`; the no-ocr path never reaches here.)
688        // Done here rather than in `process` so the batched layout path
689        // (`process_batch` → `finish_page`) honors the flag too.
690        // Parse quality is scored on the extracted text layer before force-OCR
691        // discards it (docling's page-preprocessing stage runs before OCR too,
692        // so its parse_score also reflects the original text layer).
693        let parse = quality::parse_score(&page.cells);
694        // Recognition confidences of every OCR'd cell on this page → ocr_score.
695        let mut ocr_confs: Vec<f32> = Vec::new();
696        if self.force_full_page_ocr {
697            page.cells.clear();
698            page.code_cells.clear();
699            page.word_cells.clear();
700        }
701        // Quant-robustness guard: the default int8 layout graph keeps its
702        // confidences near the 0.5 label thresholds, and a different CPU's
703        // quantized kernels can flip a whole page's detections under them —
704        // tables and paragraphs then dissolve into orphan one-liners while the
705        // same build converts the page perfectly elsewhere. When a dense
706        // digital page ends up with detections covering almost none of its
707        // text cells, re-run that one page on the fp32 graph (lazy-loaded,
708        // auto-int8 selection only) and keep whichever detections cover more.
709        let mut regions = regions;
710        if !page.cells.is_empty() {
711            let thresholded = |rs: &[layout::Region]| -> Vec<layout::Region> {
712                rs.iter()
713                    .filter(|r| r.score >= layout::label_threshold(r.label))
714                    .cloned()
715                    .collect()
716            };
717            let text_cells = page
718                .cells
719                .iter()
720                .filter(|c| !c.text.trim().is_empty())
721                .count();
722            let cov = assemble::layout_cell_coverage(&thresholded(&regions), &page.cells);
723            if text_cells >= 15 && cov < 0.5 {
724                let retry = self
725                    .layout
726                    .as_mut()
727                    .expect("layout model loaded unless no_ocr")
728                    .predict_fp32_fallback(layout_src(page), page.width, page.height)
729                    .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
730                if let Some(retry) = retry {
731                    let cov2 = assemble::layout_cell_coverage(&thresholded(&retry), &page.cells);
732                    if cov2 > cov {
733                        debug_log!(
734                            "docling-pdf: page {}: int8 layout covered {:.0}% of the text \
735                             cells; the fp32 retry covers {:.0}% — using it",
736                            n + 1,
737                            cov * 100.0,
738                            cov2 * 100.0
739                        );
740                        regions = retry;
741                    }
742                }
743            }
744        }
745        // docling's LayoutPostprocessor drops each detection below its label's
746        // confidence threshold (stricter than the 0.3 base the predictor keeps),
747        // before any overlap resolution. This removes the low-confidence tables /
748        // pictures / list-items that otherwise double-emit or mis-classify.
749        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
750            for r in &regions {
751                eprintln!(
752                    "DBG raw {} {:.2} [{:.0},{:.0},{:.0},{:.0}]",
753                    r.label, r.score, r.l, r.t, r.r, r.b
754                );
755            }
756        }
757        regions.retain(|r| r.score >= layout::label_threshold(r.label));
758        // docling's same-label picture dedup runs on the thresholded
759        // detections, before overlap resolution: a figure proposed both whole
760        // and as sub-panels collapses to one box (see `dedup_pictures`).
761        assemble::dedup_pictures(&mut regions);
762        // Resolve overlapping detections once, before OCR.
763        let mut regions = assemble::resolve(regions);
764        // Emit text the detector missed as orphan text regions (docling parity).
765        assemble::add_orphan_regions(&mut regions, &page.cells);
766        // Drop phantom empty low-confidence picture boxes (docling parity).
767        assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
768        // A regular region fully inside a surviving table/index/picture is that
769        // special's child (a cell / in-figure label), not a separate block —
770        // remove it so it isn't emitted twice (docling parity).
771        assemble::drop_contained_regulars(&mut regions);
772        // No text layer → recognise text from the page image via OCR.
773        let ocred = page.cells.is_empty();
774        if ocred {
775            if self.ocr.is_none() {
776                self.ocr = Some(ocr::OcrModel::load(self.ocr_lang).map_err(PdfError::Ocr)?);
777            }
778            let cells = timing::timed("ocr.page", || {
779                self.ocr
780                    .as_mut()
781                    .unwrap()
782                    .ocr_page(&page.image, &regions, page.scale)
783            })
784            .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
785            ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
786            page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
787            // Table interiors carry no words yet: region-scoped OCR skips
788            // table labels, and a scanned page has no pdfium text layer — so
789            // TableFormer's cell matcher got an empty word list and the table
790            // dissolved (#173). Recognize the table regions' word crops
791            // (mirroring the browser scanned path): `word_cells` feeds the
792            // matcher, and the same cells join `cells` so the geometric
793            // fallback and the table's region text see them too.
794            if regions.iter().any(|r| assemble::is_table_like(r.label)) {
795                let words = timing::timed("ocr.table_words", || {
796                    self.ocr
797                        .as_mut()
798                        .unwrap()
799                        .ocr_table_words(&page.image, &regions, page.scale)
800                })
801                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
802                ocr_confs.extend(words.iter().map(|(_, conf)| conf));
803                let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
804                page.cells.extend(words.iter().cloned());
805                page.word_cells = words;
806            }
807        }
808        // Region-scoped OCR skips `picture` interiors, and a digital page's
809        // text layer cannot see into an embedded raster either — so a figure
810        // that is really a text box (terms-and-conditions exported as an
811        // image) lost its words on every page kind. Python docling OCRs the
812        // bitmap-covered areas of *every* page — even digital ones — once they
813        // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
814        // already do. Recognize the big text-less crops here too; the panel
815        // demotion / orphan recovery below place the lines.
816        let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
817        {
818            let page_area = (page.width * page.height).max(1.0);
819            let has_text = |r: &layout::Region| {
820                page.cells.iter().any(|c| {
821                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
822                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
823                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
824                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
825                })
826            };
827            // A captioned picture can never demote to a text panel (see
828            // recover_text_panels), and on digital pages its speculative OCR
829            // would be discarded anyway — don't pay for it.
830            let captioned = |r: &layout::Region| {
831                regions.iter().any(|c| {
832                    c.label == "caption"
833                        && c.r.min(r.r) - c.l.max(r.l) > 0.0
834                        && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
835                })
836            };
837            let bare: Vec<layout::Region> = regions
838                .iter()
839                .filter(|r| {
840                    r.label == "picture"
841                        && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
842                        && !has_text(r)
843                        && (ocred || !captioned(r))
844                })
845                .map(|r| layout::Region {
846                    label: "text",
847                    ..r.clone()
848                })
849                .collect();
850            if !bare.is_empty() {
851                if self.ocr.is_none() {
852                    self.ocr = Some(ocr::OcrModel::load(self.ocr_lang).map_err(PdfError::Ocr)?);
853                }
854                let scored = timing::timed("ocr.pictures", || {
855                    self.ocr
856                        .as_mut()
857                        .unwrap()
858                        .ocr_page(&page.image, &bare, page.scale)
859                })
860                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
861                // Speculative in-picture OCR counts toward ocr_score only on
862                // OCR'd pages, where the recognized lines actually join the
863                // output; on a digital page they may be discarded below.
864                if ocred {
865                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
866                }
867                pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
868                page.cells.extend(pic_cells.iter().cloned());
869            }
870        }
871        let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
872        // A "picture" that is really a colored text panel — dense, wide,
873        // multi-line — reads out as paragraphs instead of shipping as pixels;
874        // sparse in-picture text (a chart's labels) keeps the crop and stays
875        // inside it as the picture's silent children (docling parity, #200).
876        // `no_text_panels` (#173) opts out entirely for image-extraction
877        // workflows.
878        if !self.no_text_panels {
879            assemble::recover_text_panels(&mut regions, &page.cells);
880        }
881        // On an OCR'd page, in-picture text that did NOT demote its picture
882        // mostly stays silent, exactly as in docling: its postprocess step
883        // "Remove regular clusters that are included in wrappers" walks
884        // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
885        // >80 % contained in a kept picture becomes that picture's child and
886        // never reaches the serializer. Only border-straddlers (≤80 %
887        // containment) survive as text. Emitting *everything* here used to
888        // splice a chart's OCR'd axis ticks into the body text right next to
889        // the image chunk (#200) — so the orphan pass places the recognized
890        // lines, then the same containment drop that handled the first wave
891        // re-runs to swallow the in-picture ones.
892        if ocred && !pic_cells.is_empty() {
893            // Pictures (and wrappers) no longer count as claimers (#165), so
894            // the plain orphan pass places the recognized lines directly.
895            assemble::add_orphan_regions(&mut regions, &pic_cells);
896            assemble::drop_contained_regulars(&mut regions);
897        } else if !ocred && !pic_cells.is_empty() {
898            // Digital page, picture kept: its speculative OCR cells must not
899            // linger in the text-cell set (they were appended at the tail).
900            let kept: Vec<layout::Region> = regions
901                .iter()
902                .filter(|r| r.label == "picture")
903                .cloned()
904                .collect();
905            let tail = page.cells.split_off(cells_before_pic_ocr);
906            page.cells.extend(tail.into_iter().filter(|c| {
907                !kept.iter().any(|r| {
908                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
909                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
910                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
911                    ix * iy / ca > 0.5
912                })
913            }));
914        }
915        // A text-less *table* detected inside a picture on a digital page — a
916        // screenshot of a table (2203's Figure 10) — has no text layer and no
917        // scanned-path OCR to feed it, so its grid used to serialize empty and
918        // the whole element vanished. docling OCRs bitmap-covered areas on
919        // every page kind and its table cluster collects those cells; mirror
920        // the scanned path for exactly these tables: recognize word crops and
921        // feed them to the TableFormer matcher and the cell set.
922        if !ocred {
923            let has_text = |t: &layout::Region| {
924                page.cells.iter().any(|c| {
925                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
926                    let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
927                    let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
928                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
929                })
930            };
931            let in_picture = |t: &layout::Region| {
932                regions.iter().any(|r| {
933                    r.label == "picture" && {
934                        let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
935                        let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
936                        let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
937                        ix * iy / ta > 0.5
938                    }
939                })
940            };
941            let pic_tables: Vec<layout::Region> = regions
942                .iter()
943                .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
944                .cloned()
945                .collect();
946            if !pic_tables.is_empty() {
947                if self.ocr.is_none() {
948                    self.ocr = Some(ocr::OcrModel::load(self.ocr_lang).map_err(PdfError::Ocr)?);
949                }
950                let words = timing::timed("ocr.table_words", || {
951                    self.ocr
952                        .as_mut()
953                        .unwrap()
954                        .ocr_table_words(&page.image, &pic_tables, page.scale)
955                })
956                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
957                ocr_confs.extend(words.iter().map(|(_, conf)| conf));
958                let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
959                page.cells.extend(words.iter().cloned());
960                page.word_cells.extend(words);
961            }
962        }
963        // TableFormer structure per table region (else geometric fallback). The
964        // shared slot is only locked (and lazily loaded) when the page actually
965        // has a table, so table-free documents never pay for TableFormer at all.
966        let mut table_rows: Vec<Option<Vec<Vec<String>>>> = vec![None; regions.len()];
967        if let Some(slot) = self.tables.as_ref() {
968            if regions.iter().any(|r| assemble::is_table_like(r.label)) {
969                timing::timed("tableformer", || {
970                    let mut guard = slot.lock().unwrap();
971                    if matches!(*guard, TfSlot::Unloaded) {
972                        // Full intra-op width: tables serialise on this mutex, so
973                        // the one instance gets the whole thread budget.
974                        *guard = match tableformer::TableFormer::load_with(intra_threads()) {
975                            Some(tf) => TfSlot::Ready(tf),
976                            None => TfSlot::Missing,
977                        };
978                    }
979                    if let TfSlot::Ready(tf) = &mut *guard {
980                        for (i, r) in regions.iter().enumerate() {
981                            if assemble::is_table_like(r.label) {
982                                table_rows[i] = tf.predict_table_rows(
983                                    &page.image,
984                                    [r.l, r.t, r.r, r.b],
985                                    &page.word_cells,
986                                );
987                            }
988                        }
989                    }
990                });
991            }
992        }
993        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
994            for (i, r) in regions.iter().enumerate() {
995                eprintln!(
996                    "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
997                    r.label,
998                    r.score,
999                    r.l,
1000                    r.t,
1001                    r.r,
1002                    r.b,
1003                    table_rows[i]
1004                        .as_ref()
1005                        .map(|t| (t.len(), t.first().map(|r| r.len())))
1006                );
1007            }
1008            eprintln!(
1009                "DBG cells={} words={}",
1010                page.cells.len(),
1011                page.word_cells.len()
1012            );
1013        }
1014        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
1015        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
1016        // shape as TableFormer — one lazily-loaded instance per pipeline, only
1017        // ever locked when a page actually has a matching region.
1018        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
1019        if let Some(slot) = self.classifier.as_ref() {
1020            if regions.iter().any(|r| r.label == "picture") {
1021                timing::timed("picture_classifier", || {
1022                    let mut guard = slot.lock().unwrap();
1023                    if matches!(*guard, EnrichSlot::Unloaded) {
1024                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
1025                            Some(m) => EnrichSlot::Ready(m),
1026                            None => EnrichSlot::Missing,
1027                        };
1028                    }
1029                    if let EnrichSlot::Ready(model) = &mut *guard {
1030                        for (i, r) in regions.iter().enumerate() {
1031                            if r.label != "picture" {
1032                                continue;
1033                            }
1034                            let Some(crop) = assemble::crop_region_scaled(
1035                                page,
1036                                [r.l, r.t, r.r, r.b],
1037                                enrich::CLASSIFIER_SCALE,
1038                            ) else {
1039                                continue;
1040                            };
1041                            match model.classify(&crop) {
1042                                Ok(classes) => {
1043                                    enrich_out[i] =
1044                                        Some(assemble::Enrichment::PictureClasses(classes));
1045                                }
1046                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1047                            }
1048                        }
1049                    }
1050                });
1051            }
1052        }
1053        if let Some(slot) = self.code_formula.as_ref() {
1054            let wants = |label: &str| {
1055                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
1056            };
1057            if regions.iter().any(|r| wants(r.label)) {
1058                timing::timed("code_formula", || {
1059                    let mut guard = slot.lock().unwrap();
1060                    if matches!(*guard, EnrichSlot::Unloaded) {
1061                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
1062                            Some(m) => EnrichSlot::Ready(m),
1063                            None => EnrichSlot::Missing,
1064                        };
1065                    }
1066                    if let EnrichSlot::Ready(model) = &mut *guard {
1067                        for (i, r) in regions.iter().enumerate() {
1068                            if !wants(r.label) {
1069                                continue;
1070                            }
1071                            // docling crops the postprocessed cluster box — the
1072                            // union of the region's text cells, not the raw
1073                            // detector box — expanded by 18% per side, at
1074                            // ~120 dpi.
1075                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
1076                                .unwrap_or([r.l, r.t, r.r, r.b]);
1077                            let (w, h) = (br - bl, bb - bt);
1078                            let ex = enrich::CODE_FORMULA_EXPANSION;
1079                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
1080                            let Some(crop) = assemble::crop_region_scaled(
1081                                page,
1082                                bbox,
1083                                enrich::CODE_FORMULA_SCALE,
1084                            ) else {
1085                                continue;
1086                            };
1087                            let kind = if r.label == "code" {
1088                                enrich::CodeFormulaKind::Code
1089                            } else {
1090                                enrich::CodeFormulaKind::Formula
1091                            };
1092                            match model.predict(&crop, kind) {
1093                                Ok(text) => {
1094                                    enrich_out[i] = Some(match kind {
1095                                        enrich::CodeFormulaKind::Code => {
1096                                            let (code, language) =
1097                                                enrich::extract_code_language(&text);
1098                                            assemble::Enrichment::Code {
1099                                                language,
1100                                                text: code,
1101                                            }
1102                                        }
1103                                        enrich::CodeFormulaKind::Formula => {
1104                                            assemble::Enrichment::Formula { latex: text }
1105                                        }
1106                                    });
1107                                }
1108                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1109                            }
1110                        }
1111                    }
1112                });
1113            }
1114        }
1115        // Score the final region set (docling assigns layout_score over the
1116        // postprocessed clusters — the same set assemble_page consumes).
1117        let conf = quality::page_confidence(parse, &regions, &ocr_confs);
1118        let (nodes, links) = timing::timed("assemble_page", || {
1119            assemble::assemble_page(page, regions, &table_rows, &enrich_out)
1120        });
1121        Ok((nodes, links, conf))
1122    }
1123}
1124
1125#[cfg(feature = "ml")]
1126/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
1127/// so on a typical machine two threads per worker (sharing one in-cache copy of
1128/// the weights) extracts more throughput than one fat model or many single-thread
1129/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
1130fn pdf_intra() -> usize {
1131    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
1132        return n;
1133    }
1134    if intra_threads() >= 2 {
1135        2
1136    } else {
1137        1
1138    }
1139}
1140
1141#[cfg(feature = "ml")]
1142/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
1143/// overrides; otherwise size the pool so `workers × intra ≈ cores`, capped at 4 so
1144/// a worst-case pool holds a bounded amount of model memory (~0.4 GB per worker)
1145/// and does not oversaturate the memory bus with model-weight traffic.
1146fn pdf_worker_count() -> usize {
1147    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
1148        return n;
1149    }
1150    (intra_threads() / pdf_intra()).clamp(1, 4)
1151}
1152
1153#[cfg(feature = "ml")]
1154/// Max pages a worker layout-detects with one batched inference call (issue
1155/// #73). Workers drain the work channel opportunistically up to this size —
1156/// whatever is already rendered gets batched, so batching never *waits* for
1157/// pages and adds no latency when rendering is the bottleneck.
1158///
1159/// Default: 4 on 8+ cores, 1 (per-page) below. Measured on a 4-core box the
1160/// batch only adds cache pressure and costs pipeline overlap (2 workers × 2
1161/// threads: 8.1 s/conv at batch=1 vs 9.3 s at batch=4 on the 9-page
1162/// 2206.01062 fixture); the single-session amortization it buys needs the
1163/// wider thread budget of a many-core machine. Output is bit-identical at
1164/// every batch size, so this is purely a throughput knob.
1165/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides; `1` restores per-page inference.
1166fn pdf_layout_batch() -> usize {
1167    env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
1168        .filter(|&n| n > 0)
1169        .unwrap_or_else(|| if intra_threads() >= 8 { 4 } else { 1 })
1170}
1171
1172#[cfg(feature = "ml")]
1173/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
1174/// the serial primary (running its model on every core) is faster than fanning out
1175/// — the helper pool's one-time model-load cost only pays off once enough pages
1176/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
1177fn pdf_parallel_min() -> usize {
1178    env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
1179        .filter(|&n| n > 0)
1180        .unwrap_or(6)
1181}
1182
1183#[cfg(feature = "ml")]
1184/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
1185/// so a single-page / small / image / METS input is converted at full intra-op
1186/// speed with no pool to load. A document with enough pages instead fans out
1187/// across a **pool** of narrower workers processed concurrently. Both load lazily
1188/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
1189pub struct Pipeline {
1190    /// Full-intra worker for the serial path; loaded on first serial use.
1191    primary: Option<Worker>,
1192    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
1193    /// path; loaded on first multi-page use and cached.
1194    pool: Vec<Worker>,
1195    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
1196    tables: SharedTables,
1197    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
1198    classifier: SharedClassifier,
1199    code_formula: SharedCodeFormula,
1200    /// Desired pool size for multi-page documents.
1201    target_workers: usize,
1202    /// Page count at/above which the parallel pool is worth its load cost.
1203    parallel_min: usize,
1204    /// Skip loading/running TableFormer; table regions fall back to geometric
1205    /// reconstruction. See [`Pipeline::no_table_former`].
1206    no_table_former: bool,
1207    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
1208    no_ocr: bool,
1209    /// OCR every page even when it carries a text layer. See
1210    /// [`Pipeline::force_full_page_ocr`].
1211    force_full_page_ocr: bool,
1212    /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
1213    no_text_panels: bool,
1214    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
1215    enrich: EnrichmentOptions,
1216    /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
1217    page_range: Option<(usize, usize)>,
1218    /// OCR recognition language. See [`Pipeline::ocr_lang`].
1219    ocr_lang: ocr::OcrLang,
1220    /// Optional per-page progress hook `(done, selected_total)`, invoked after
1221    /// each page finishes on both the serial and parallel buffered paths. Set
1222    /// by the CLI batch mode for dot-progress; `None` costs nothing.
1223    progress: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>,
1224}
1225
1226#[cfg(feature = "ml")]
1227impl Pipeline {
1228    /// Construct the pipeline. Models load lazily on first use (full-intra primary
1229    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
1230    /// loaded that a given document doesn't need.
1231    pub fn new() -> Result<Self, PdfError> {
1232        Ok(Self {
1233            primary: None,
1234            pool: Vec::new(),
1235            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
1236            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1237            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1238            target_workers: pdf_worker_count(),
1239            parallel_min: pdf_parallel_min(),
1240            no_table_former: false,
1241            no_ocr: false,
1242            force_full_page_ocr: false,
1243            no_text_panels: false,
1244            enrich: EnrichmentOptions::default(),
1245            page_range: None,
1246            ocr_lang: ocr::OcrLang::from_env(),
1247            progress: None,
1248        })
1249    }
1250
1251    /// Install (or clear) the per-page progress hook: called with
1252    /// `(pages_done, pages_selected)` after each page completes during
1253    /// [`convert`](Self::convert). Shared with the parallel workers, so the
1254    /// callback must be cheap and thread-safe.
1255    pub fn set_progress(&mut self, cb: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>) {
1256        self.progress = cb;
1257    }
1258
1259    /// Convert only pages `first..=last` (**1-based**, like the page numbers a
1260    /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
1261    /// skipped before rasterization, so the cost is proportional to the window,
1262    /// not the document. `last` past the end of the document clamps; a window
1263    /// that selects no pages at all (`first` beyond the last page) is an error
1264    /// at convert time. `None` (the default) converts everything.
1265    pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
1266        self.page_range = range;
1267        self
1268    }
1269
1270    /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
1271    /// (e.g. docling-serve's warm instance) that applies a per-request window
1272    /// without rebuilding — unlike the model switches, the window is pure
1273    /// configuration. Set it before every conversion; it stays until changed.
1274    pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
1275        self.page_range = range;
1276    }
1277
1278    /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
1279    /// for the multilingual docling-conformance model. `None` keeps the
1280    /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
1281    /// first conversion; for a warm pipeline use
1282    /// [`set_ocr_lang`](Self::set_ocr_lang).
1283    pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
1284        self.set_ocr_lang(lang);
1285        self
1286    }
1287
1288    /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
1289    /// pipeline (docling-serve's warm instance). Unlike the page window this
1290    /// is a *model* switch: any worker whose cached recognition model was
1291    /// loaded for a different language drops it, to be lazily reloaded on the
1292    /// next OCR-needing page (cheap — the rec models are ~10 MB).
1293    pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
1294        let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
1295        self.ocr_lang = lang;
1296        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
1297            if worker.ocr_lang != lang {
1298                worker.ocr_lang = lang;
1299                worker.ocr = None;
1300            }
1301        }
1302    }
1303
1304    /// Resolve the configured 1-based window against a page count into the
1305    /// 0-based inclusive form the backend walks, validating it selects at
1306    /// least one existing page.
1307    fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
1308        let Some((first, last)) = self.page_range else {
1309            return Ok(None);
1310        };
1311        if first == 0 || last < first {
1312            return Err(PdfError::Pdfium(format!(
1313                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
1314            )));
1315        }
1316        if first > total {
1317            return Err(PdfError::Pdfium(format!(
1318                "page range {first}-{last} is outside the document ({total} page(s))"
1319            )));
1320        }
1321        Ok(Some((first - 1, last.min(total) - 1)))
1322    }
1323
1324    /// Enable the opt-in enrichment passes (docling's
1325    /// `do_picture_classification` / `do_code_enrichment` /
1326    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
1327    /// the first matching region; a missing model warns once and is skipped.
1328    /// Set before the first conversion (no effect on already-loaded workers).
1329    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
1330        self.enrich = opts;
1331        self
1332    }
1333
1334    /// Skip loading and running the TableFormer table-structure model. Table
1335    /// regions still get emitted, but reconstructed geometrically from cell
1336    /// positions instead of via the ONNX model's predicted structure — faster
1337    /// (no model load, no per-table inference) at the cost of table fidelity.
1338    /// No effect if a worker is already loaded; set this before the first
1339    /// conversion.
1340    pub fn no_table_former(mut self, disable: bool) -> Self {
1341        self.no_table_former = disable;
1342        self
1343    }
1344
1345    /// Keep every detected `picture` region as a picture. By default an
1346    /// *uncaptioned* picture that reads like a dense, uniform text panel (a
1347    /// terms-and-conditions box exported as an image) is demoted into
1348    /// paragraphs (#157); a chart the layout mislabels can still trip that
1349    /// heuristic on scanned pages, and image-extraction workflows may simply
1350    /// want every crop — this flag disables the demotion entirely (#173).
1351    /// No effect on already-loaded workers; set before the first conversion.
1352    pub fn no_text_panels(mut self, disable: bool) -> Self {
1353        self.no_text_panels = disable;
1354        self
1355    }
1356
1357    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
1358    /// inference of any kind. The PDF's embedded text cells are grouped by line
1359    /// and emitted as plain paragraphs in reading order: no headings, lists,
1360    /// tables, code blocks, or pictures, since that structure comes from the
1361    /// layout model. The fastest possible PDF path, but pages with no embedded
1362    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
1363    /// without this flag. Implies `no_table_former`. No effect if a worker is
1364    /// already loaded; set this before the first conversion.
1365    pub fn no_ocr(mut self, disable: bool) -> Self {
1366        self.no_ocr = disable;
1367        self
1368    }
1369
1370    /// OCR every page from its rendered image even when the page carries an
1371    /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
1372    /// for text layers that exist but lie: broken encodings, subset fonts with
1373    /// garbage mappings, a scanned form with a few typed-in fields. Ignored
1374    /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
1375    /// `force_full_page_ocr` is a sub-option of `do_ocr`).
1376    pub fn force_full_page_ocr(mut self, force: bool) -> Self {
1377        self.force_full_page_ocr = force;
1378        self
1379    }
1380
1381    /// The shared TableFormer slot handed to each worker, or `None` when the
1382    /// pipeline options skip TableFormer entirely.
1383    fn tables_slot(&self) -> Option<SharedTables> {
1384        if self.no_table_former || self.no_ocr {
1385            None
1386        } else {
1387            Some(Arc::clone(&self.tables))
1388        }
1389    }
1390
1391    /// The shared enrichment slots for a worker (`None` per model unless its
1392    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
1393    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
1394        if self.no_ocr || !self.enrich.any() {
1395            return (None, None);
1396        }
1397        (
1398            self.enrich
1399                .picture_classification
1400                .then(|| Arc::clone(&self.classifier)),
1401            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
1402        )
1403    }
1404
1405    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
1406    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
1407    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
1408    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
1409    /// `DocumentConverter.initialize_pipeline`.
1410    pub fn warm_up(&mut self) -> Result<(), PdfError> {
1411        self.primary()?;
1412        Ok(())
1413    }
1414
1415    /// The full-intra serial worker, loaded on first use.
1416    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
1417        if self.primary.is_none() {
1418            self.primary = Some(Worker::load(
1419                intra_threads(),
1420                self.tables_slot(),
1421                self.enrich_slots(),
1422                self.enrich,
1423                self.no_ocr,
1424                self.force_full_page_ocr,
1425                self.no_text_panels,
1426                self.ocr_lang,
1427            )?);
1428        }
1429        Ok(self.primary.as_mut().unwrap())
1430    }
1431
1432    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
1433    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
1434    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
1435    /// fans the pages out across the worker pool, reassembled in page order so the
1436    /// output is byte-identical to the serial path.
1437    pub fn convert(
1438        &mut self,
1439        bytes: &[u8],
1440        password: Option<&str>,
1441        name: &str,
1442    ) -> Result<DoclingDocument, PdfError> {
1443        let pages = pdfium_backend::page_count(bytes, password)?;
1444        let range = self.resolve_range(pages)?;
1445        // Serial vs parallel is decided by the pages actually converted: a
1446        // 3-page window over a 500-page PDF should not pay the pool load.
1447        let selected = range.map_or(pages, |(a, b)| b - a + 1);
1448        let doc = if self.target_workers >= 2 && selected >= self.parallel_min {
1449            self.convert_parallel(bytes, password, name, range, selected)?
1450        } else {
1451            self.convert_serial(bytes, password, name, range, selected)?
1452        };
1453        timing::report();
1454        Ok(doc)
1455    }
1456
1457    /// Stream pages one at a time through the primary worker — render → process →
1458    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
1459    fn convert_serial(
1460        &mut self,
1461        bytes: &[u8],
1462        password: Option<&str>,
1463        name: &str,
1464        range: Option<(usize, usize)>,
1465        selected: usize,
1466    ) -> Result<DoclingDocument, PdfError> {
1467        let mut doc = DoclingDocument::new(name);
1468        let mut confs = std::collections::BTreeMap::new();
1469        let render_image = !self.no_ocr;
1470        let progress = self.progress.clone();
1471        let mut done = 0usize;
1472        let worker = self.primary()?;
1473        pdfium_backend::for_each_page(
1474            bytes,
1475            password,
1476            render_image,
1477            range,
1478            |n, _total, mut page| {
1479                let (mut nodes, links, conf) = worker.process(n, &mut page)?;
1480                assemble::stamp_page_no(&mut nodes, n + 1);
1481                doc.nodes.extend(nodes);
1482                doc.links.extend(links);
1483                confs.insert(n + 1, conf);
1484                if let Some(cb) = &progress {
1485                    done += 1;
1486                    cb(done, selected);
1487                }
1488                Ok::<(), PdfError>(())
1489            },
1490        )?;
1491        assemble::merge_continuations(&mut doc.nodes);
1492        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
1493        Ok(doc)
1494    }
1495
1496    /// Render pages serially on this thread (pdfium) and process them in parallel
1497    /// across the worker pool. A bounded channel applies backpressure so only a
1498    /// handful of page bitmaps are resident at once; results carry their page
1499    /// index and are reassembled in order, so the output is byte-identical to the
1500    /// serial path.
1501    fn convert_parallel(
1502        &mut self,
1503        bytes: &[u8],
1504        password: Option<&str>,
1505        name: &str,
1506        range: Option<(usize, usize)>,
1507        selected: usize,
1508    ) -> Result<DoclingDocument, PdfError> {
1509        self.ensure_pool()?;
1510        let progress = self.progress.clone();
1511        let pages_done = std::sync::atomic::AtomicUsize::new(0);
1512        let n_workers = self.pool.len();
1513        let render_image = !self.no_ocr;
1514        let layout_batch = pdf_layout_batch();
1515        // Bound sized so every worker can accumulate a full layout batch while
1516        // rendering stays ahead (and never below the pre-#73 render-ahead of
1517        // two pages per worker); still a hard cap on resident page bitmaps.
1518        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
1519        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
1520        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
1521        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
1522
1523        // Move the pool into the scope so each worker gets an exclusive `&mut`.
1524        let mut workers = std::mem::take(&mut self.pool);
1525        std::thread::scope(|s| {
1526            for worker in workers.iter_mut() {
1527                let work_rx = Arc::clone(&work_rx);
1528                let results = Arc::clone(&results);
1529                let first_err = Arc::clone(&first_err);
1530                let progress = progress.clone();
1531                let pages_done = &pages_done;
1532                s.spawn(move || loop {
1533                    // Hold the receiver lock only for the recv (plus a non-blocking
1534                    // drain up to the layout batch size); release before the (long)
1535                    // per-page work so other workers can pull concurrently.
1536                    let mut batch = Vec::new();
1537                    {
1538                        let rx = work_rx.lock().unwrap();
1539                        match rx.recv() {
1540                            Ok(item) => {
1541                                batch.push(item);
1542                                while batch.len() < layout_batch {
1543                                    match rx.try_recv() {
1544                                        Ok(item) => batch.push(item),
1545                                        Err(_) => break,
1546                                    }
1547                                }
1548                            }
1549                            Err(_) => break,
1550                        }
1551                    }
1552                    let outs = worker.process_batch(&mut batch);
1553                    for ((idx, _), out) in batch.iter().zip(outs) {
1554                        match out {
1555                            Ok(out) => {
1556                                results.lock().unwrap().push((*idx, out));
1557                                if let Some(cb) = &progress {
1558                                    let d = pages_done
1559                                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1560                                        + 1;
1561                                    cb(d, selected);
1562                                }
1563                            }
1564                            Err(e) => {
1565                                let mut slot = first_err.lock().unwrap();
1566                                if slot.is_none() {
1567                                    *slot = Some(e);
1568                                }
1569                            }
1570                        }
1571                    }
1572                });
1573            }
1574            // Render on this thread and feed the workers; backpressure blocks here
1575            // when the channel is full. Dropping `work_tx` afterwards signals the
1576            // workers (recv → Err) to finish.
1577            let render = pdfium_backend::for_each_page(
1578                bytes,
1579                password,
1580                render_image,
1581                range,
1582                |i, _total, page| {
1583                    work_tx
1584                        .send((i, page))
1585                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
1586                },
1587            );
1588            drop(work_tx);
1589            if let Err(e) = render {
1590                let mut slot = first_err.lock().unwrap();
1591                if slot.is_none() {
1592                    *slot = Some(e);
1593                }
1594            }
1595        });
1596        // Threads have joined; restore the pool for the next conversion.
1597        self.pool = workers;
1598
1599        if let Some(e) = first_err.lock().unwrap().take() {
1600            return Err(e);
1601        }
1602        let mut results = Arc::try_unwrap(results)
1603            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
1604            .into_inner()
1605            .unwrap();
1606        results.sort_by_key(|(idx, _)| *idx);
1607        let mut doc = DoclingDocument::new(name);
1608        let mut confs = std::collections::BTreeMap::new();
1609        for (idx, (mut nodes, links, conf)) in results {
1610            assemble::stamp_page_no(&mut nodes, idx + 1);
1611            doc.nodes.extend(nodes);
1612            doc.links.extend(links);
1613            confs.insert(idx + 1, conf);
1614        }
1615        assemble::merge_continuations(&mut doc.nodes);
1616        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
1617        Ok(doc)
1618    }
1619
1620    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
1621    /// in-document-order batch of nodes (and that span's recovered links) as pages
1622    /// complete, so a caller can serialize Markdown page by page instead of waiting
1623    /// for the whole document. The batches are exactly the buffered [`convert`]'s
1624    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
1625    /// parallel path reorders pages back into document order before emitting, so
1626    /// the output is identical regardless of worker scheduling.
1627    ///
1628    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
1629    /// and its backpressure throttles the whole pipeline. Returning `Err` from
1630    /// `emit` aborts the conversion with that error.
1631    pub fn convert_streaming<F>(
1632        &mut self,
1633        bytes: &[u8],
1634        password: Option<&str>,
1635        name: &str,
1636        emit: F,
1637    ) -> Result<(), PdfError>
1638    where
1639        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
1640    {
1641        let _ = name; // page nodes carry no name; the caller owns the document name.
1642        let pages = pdfium_backend::page_count(bytes, password)?;
1643        let range = self.resolve_range(pages)?;
1644        let selected = range.map_or(pages, |(a, b)| b - a + 1);
1645        let r = if self.target_workers >= 2 && selected >= self.parallel_min {
1646            self.convert_streaming_parallel(bytes, password, range, emit)
1647        } else {
1648            self.convert_streaming_serial(bytes, password, range, emit)
1649        };
1650        timing::report();
1651        r
1652    }
1653
1654    /// Serial streaming: render → process → emit, one page at a time, holding back
1655    /// only the tail that might still merge into the next page.
1656    fn convert_streaming_serial<F>(
1657        &mut self,
1658        bytes: &[u8],
1659        password: Option<&str>,
1660        range: Option<(usize, usize)>,
1661        mut emit: F,
1662    ) -> Result<(), PdfError>
1663    where
1664        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
1665    {
1666        let mut asm = assemble::StreamAssembler::new();
1667        let render_image = !self.no_ocr;
1668        let worker = self.primary()?;
1669        pdfium_backend::for_each_page(
1670            bytes,
1671            password,
1672            render_image,
1673            range,
1674            |n, _total, mut page| {
1675                // Confidence is dropped on the streaming path: the report is
1676                // only complete once every page has run, which defeats
1677                // page-by-page emission — buffered `convert` carries it.
1678                let (nodes, links, _conf) = worker.process(n, &mut page)?;
1679                emit(asm.push(nodes), links)
1680            },
1681        )?;
1682        emit(asm.finish(), Vec::new())
1683    }
1684
1685    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
1686    /// not thread-safe) and process across the worker pool; results carry their
1687    /// page index and are reordered on the calling thread into a
1688    /// [`assemble::StreamAssembler`], which emits each page in document order as
1689    /// soon as its predecessors have arrived. Bounded channels keep only a handful
1690    /// of pages resident and let `emit`'s backpressure reach the renderer.
1691    fn convert_streaming_parallel<F>(
1692        &mut self,
1693        bytes: &[u8],
1694        password: Option<&str>,
1695        range: Option<(usize, usize)>,
1696        mut emit: F,
1697    ) -> Result<(), PdfError>
1698    where
1699        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
1700    {
1701        self.ensure_pool()?;
1702        let n_workers = self.pool.len();
1703        let render_image = !self.no_ocr;
1704        let layout_batch = pdf_layout_batch();
1705        // Bound sized so every worker can accumulate a full layout batch while
1706        // rendering stays ahead (and never below the pre-#73 render-ahead of
1707        // two pages per worker); still a hard cap on resident page bitmaps.
1708        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
1709        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
1710        // Workers and the renderer report here; the calling thread drains it in
1711        // page order. Bounded so workers block (bounding resident bitmaps) when the
1712        // consumer falls behind.
1713        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
1714
1715        let mut workers = std::mem::take(&mut self.pool);
1716        let mut asm = assemble::StreamAssembler::new();
1717        let mut first_err: Option<PdfError> = None;
1718
1719        std::thread::scope(|s| {
1720            // Workers: pull a batch of pages (whatever is already rendered, up
1721            // to the layout batch size), process it, report (index-tagged)
1722            // results.
1723            for worker in workers.iter_mut() {
1724                let work_rx = Arc::clone(&work_rx);
1725                let res_tx = res_tx.clone();
1726                s.spawn(move || 'outer: loop {
1727                    let mut batch = Vec::new();
1728                    {
1729                        let rx = work_rx.lock().unwrap();
1730                        match rx.recv() {
1731                            Ok(item) => {
1732                                batch.push(item);
1733                                while batch.len() < layout_batch {
1734                                    match rx.try_recv() {
1735                                        Ok(item) => batch.push(item),
1736                                        Err(_) => break,
1737                                    }
1738                                }
1739                            }
1740                            Err(_) => break,
1741                        }
1742                    }
1743                    let outs = worker.process_batch(&mut batch);
1744                    for ((idx, _), out) in batch.iter().zip(outs) {
1745                        if res_tx.send(out.map(|o| (*idx, o))).is_err() {
1746                            break 'outer; // consumer gone
1747                        }
1748                    }
1749                });
1750            }
1751            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
1752            // single thread); report a render error through the same channel.
1753            {
1754                let res_tx = res_tx.clone();
1755                s.spawn(move || {
1756                    let render = pdfium_backend::for_each_page(
1757                        bytes,
1758                        password,
1759                        render_image,
1760                        range,
1761                        |i, _total, page| {
1762                            work_tx
1763                                .send((i, page))
1764                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
1765                        },
1766                    );
1767                    drop(work_tx); // signal workers to finish
1768                    if let Err(e) = render {
1769                        let _ = res_tx.send(Err(e));
1770                    }
1771                });
1772            }
1773            // Drop our own sender so the channel closes once the threads finish.
1774            drop(res_tx);
1775
1776            // Collector (this thread): reorder into document order and emit.
1777            // With a page window, indices start at the window's first page.
1778            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
1779            let mut next = range.map_or(0, |(first, _)| first);
1780            for msg in res_rx.iter() {
1781                match msg {
1782                    Err(e) => {
1783                        if first_err.is_none() {
1784                            first_err = Some(e);
1785                        }
1786                    }
1787                    Ok((idx, out)) => {
1788                        buffer.insert(idx, out);
1789                        if first_err.is_some() {
1790                            continue; // keep draining so the threads can exit
1791                        }
1792                        while let Some((nodes, links, _conf)) = buffer.remove(&next) {
1793                            if let Err(e) = emit(asm.push(nodes), links) {
1794                                first_err = Some(e);
1795                                break;
1796                            }
1797                            next += 1;
1798                        }
1799                    }
1800                }
1801            }
1802        });
1803        // Threads have joined; restore the pool for the next conversion.
1804        self.pool = workers;
1805
1806        if let Some(e) = first_err {
1807            return Err(e);
1808        }
1809        emit(asm.finish(), Vec::new())
1810    }
1811
1812    /// Lazily grow the pool to `target_workers`, loading the new workers
1813    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
1814    /// one load's wall-time). Cached for reuse across documents.
1815    fn ensure_pool(&mut self) -> Result<(), PdfError> {
1816        let need = self.target_workers.saturating_sub(self.pool.len());
1817        if need == 0 {
1818            return Ok(());
1819        }
1820        let intra = pdf_intra();
1821        let no_ocr = self.no_ocr;
1822        let force = self.force_full_page_ocr;
1823        let ntp = self.no_text_panels;
1824        let ocr_lang = self.ocr_lang;
1825        let enrich = self.enrich;
1826        let tables = self.tables_slot();
1827        let enrich_slots = self.enrich_slots();
1828        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
1829            let handles: Vec<_> = (0..need)
1830                .map(|_| {
1831                    let tables = tables.clone();
1832                    let enrich_slots = enrich_slots.clone();
1833                    s.spawn(move || {
1834                        Worker::load(
1835                            intra,
1836                            tables,
1837                            enrich_slots,
1838                            enrich,
1839                            no_ocr,
1840                            force,
1841                            ntp,
1842                            ocr_lang,
1843                        )
1844                    })
1845                })
1846                .collect();
1847            handles.into_iter().map(|h| h.join().unwrap()).collect()
1848        });
1849        for w in loaded {
1850            self.pool.push(w?);
1851        }
1852        Ok(())
1853    }
1854
1855    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
1856    /// docling routes images through the same layout+OCR pipeline as a PDF page.
1857    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1858        let image = decode_image_limited(bytes)?;
1859        let (w, h) = image.dimensions();
1860        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
1861        // standalone image has no text layer, so OCR supplies the cells.
1862        let page = PdfPage {
1863            width: w as f32,
1864            height: h as f32,
1865            scale: 1.0,
1866            cells: Vec::new(),
1867            code_cells: Vec::new(),
1868            word_cells: Vec::new(),
1869            // A standalone image *is* its own scale-1.0 page image, so the
1870            // layout model sees it through the docling-exact PIL kernel.
1871            image_layout: Some(image.clone()),
1872            image,
1873            links: Vec::new(),
1874            rotation: 0,
1875        };
1876        self.process_pages(vec![page], name)
1877    }
1878
1879    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
1880    /// page (image / METS inputs, which are small and already materialised).
1881    fn process_pages(
1882        &mut self,
1883        mut pages: Vec<PdfPage>,
1884        name: &str,
1885    ) -> Result<DoclingDocument, PdfError> {
1886        let mut doc = DoclingDocument::new(name);
1887        let mut confs = std::collections::BTreeMap::new();
1888        let worker = self.primary()?;
1889        for (n, page) in pages.iter_mut().enumerate() {
1890            let (mut nodes, links, conf) = worker.process(n, page)?;
1891            assemble::stamp_page_no(&mut nodes, n + 1);
1892            doc.nodes.extend(nodes);
1893            doc.links.extend(links);
1894            confs.insert(n + 1, conf);
1895        }
1896        assemble::merge_continuations(&mut doc.nodes);
1897        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
1898        Ok(doc)
1899    }
1900}
1901
1902/// Number of pages in a PDF, without converting anything — what the CLI batch
1903/// mode prints in its per-document start line.
1904#[cfg(feature = "ml")]
1905pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
1906    Ok(pdfium_backend::page_count(bytes, password)?)
1907}
1908
1909#[cfg(feature = "ml")]
1910/// Convenience one-shot conversion (loads the pipeline per call). Errors are
1911/// detailed and surfaced (never silently skipped).
1912pub fn convert(
1913    bytes: &[u8],
1914    password: Option<&str>,
1915    name: &str,
1916) -> Result<DoclingDocument, PdfError> {
1917    convert_with_options(
1918        bytes,
1919        password,
1920        name,
1921        false,
1922        false,
1923        false,
1924        false,
1925        EnrichmentOptions::default(),
1926        None,
1927        None,
1928    )
1929}
1930
1931#[cfg(feature = "ml")]
1932/// Like [`convert`], but optionally skips loading/running TableFormer (see
1933/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1934/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
1935/// [`Pipeline::enrichments`]).
1936// One positional per pipeline switch mirrors the Pipeline builder; growing
1937// past clippy's arity cap is the price of keeping this one-shot signature
1938// stable-ish instead of churning callers into an options struct mid-series.
1939#[allow(clippy::too_many_arguments)]
1940pub fn convert_with_options(
1941    bytes: &[u8],
1942    password: Option<&str>,
1943    name: &str,
1944    no_table_former: bool,
1945    no_ocr: bool,
1946    force_full_page_ocr: bool,
1947    no_text_panels: bool,
1948    enrich: EnrichmentOptions,
1949    pages: Option<(usize, usize)>,
1950    ocr_lang: Option<OcrLang>,
1951) -> Result<DoclingDocument, PdfError> {
1952    Pipeline::new()?
1953        .no_table_former(no_table_former)
1954        .no_ocr(no_ocr)
1955        .force_full_page_ocr(force_full_page_ocr)
1956        .no_text_panels(no_text_panels)
1957        .enrichments(enrich)
1958        .pages(pages)
1959        .ocr_lang(ocr_lang)
1960        .convert(bytes, password, name)
1961}
1962
1963#[cfg(feature = "ml")]
1964/// Convenience one-shot image conversion (loads the pipeline per call).
1965pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1966    convert_image_with_options(
1967        bytes,
1968        name,
1969        false,
1970        false,
1971        false,
1972        EnrichmentOptions::default(),
1973        None,
1974    )
1975}
1976
1977#[cfg(feature = "ml")]
1978/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
1979/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1980/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
1981pub fn convert_image_with_options(
1982    bytes: &[u8],
1983    name: &str,
1984    no_table_former: bool,
1985    no_ocr: bool,
1986    no_text_panels: bool,
1987    enrich: EnrichmentOptions,
1988    ocr_lang: Option<OcrLang>,
1989) -> Result<DoclingDocument, PdfError> {
1990    Pipeline::new()?
1991        .no_table_former(no_table_former)
1992        .no_ocr(no_ocr)
1993        .no_text_panels(no_text_panels)
1994        .enrichments(enrich)
1995        .ocr_lang(ocr_lang)
1996        .convert_image(bytes, name)
1997}
1998
1999#[cfg(feature = "ml")]
2000/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
2001/// scans) through the shared layout + assembly pipeline.
2002pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
2003    convert_pages_with_options(
2004        pages,
2005        name,
2006        false,
2007        false,
2008        false,
2009        EnrichmentOptions::default(),
2010    )
2011}
2012
2013#[cfg(feature = "ml")]
2014/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
2015/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2016/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2017pub fn convert_pages_with_options(
2018    pages: Vec<PdfPage>,
2019    name: &str,
2020    no_table_former: bool,
2021    no_ocr: bool,
2022    no_text_panels: bool,
2023    enrich: EnrichmentOptions,
2024) -> Result<DoclingDocument, PdfError> {
2025    Pipeline::new()?
2026        .no_table_former(no_table_former)
2027        .no_text_panels(no_text_panels)
2028        .no_ocr(no_ocr)
2029        .enrichments(enrich)
2030        .process_pages(pages, name)
2031}
2032
2033#[cfg(feature = "ml")]
2034#[cfg(all(test, feature = "ml"))]
2035mod image_limit_tests {
2036    use super::decode_image_with_max_side;
2037
2038    /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
2039    /// byte literal).
2040    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
2041        use std::io::Cursor;
2042        let img = image::RgbImage::new(w, h);
2043        let mut out = Vec::new();
2044        img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
2045            .unwrap();
2046        out
2047    }
2048
2049    #[test]
2050    fn normal_image_decodes_under_the_cap() {
2051        let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
2052        assert_eq!(img.dimensions(), (8, 8));
2053    }
2054
2055    #[test]
2056    fn dimensions_over_the_cap_are_rejected_not_aborted() {
2057        // A per-side cap below the image's declared size must yield a
2058        // recoverable Err, never an allocation-abort — the mechanism that stops
2059        // a crafted image declaring 60000×60000 from OOM-killing the process.
2060        let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
2061        assert!(
2062            r.is_err(),
2063            "decode must fail under the pixel cap, not abort"
2064        );
2065    }
2066}
2067
2068#[cfg(test)]
2069mod median_tests {
2070    #[test]
2071    fn median_of_empty_is_zero_not_a_panic() {
2072        // A crafted table can leave a row/column with zero matched cells; the
2073        // even-count branch would index values[0 - 1] and panic (→ remote crash
2074        // via docling-serve) without the empty guard.
2075        assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
2076        assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
2077        assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
2078    }
2079}
2080
2081#[cfg(test)]
2082mod send_check {
2083    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
2084    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
2085    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
2086    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
2087    fn assert_send<T: Send>() {}
2088
2089    #[test]
2090    fn pipeline_is_send() {
2091        assert_send::<super::Pipeline>();
2092    }
2093}