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