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