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