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