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
17mod assemble;
18mod dp_lines;
19#[cfg(feature = "ml")]
20pub mod enrich;
21// Public so sibling crates (e.g. docling-rag's ONNX embedder) can route their
22// own `ort` sessions through the same `DOCLING_RS_EP` selection.
23#[cfg(feature = "ml")]
24pub mod ep;
25pub mod layout;
26#[cfg(feature = "ml")]
27mod mets;
28#[cfg(feature = "ml")]
29mod ocr;
30pub mod pdfium_backend;
31mod reading_order;
32#[cfg(feature = "ml")]
33pub mod resample;
34#[cfg(feature = "ml")]
35pub mod tableformer;
36pub mod textparse;
37#[cfg(feature = "ml")]
38mod tf_match;
39pub mod timing;
40
41#[cfg(feature = "ml")]
42use std::collections::BTreeMap;
43use std::fmt;
44#[cfg(feature = "ml")]
45use std::sync::mpsc::{sync_channel, Receiver};
46#[cfg(feature = "ml")]
47use std::sync::{Arc, Mutex};
48
49use docling_core::DoclingDocument;
50#[cfg(feature = "ml")]
51use docling_core::Node;
52
53#[cfg(feature = "ml")]
54pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options};
55#[cfg(feature = "ml")]
56pub use pdfium_backend::PdfDocument;
57pub use pdfium_backend::{PdfPage, TextCell};
58
59/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
60#[derive(Debug)]
61pub enum PdfError {
62    /// pdfium failed to bind, open, or read the document.
63    Pdfium(String),
64    /// The layout ONNX model failed to load or run.
65    Layout(String),
66    /// The OCR ONNX model failed to load or run.
67    Ocr(String),
68}
69
70impl fmt::Display for PdfError {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
74            PdfError::Layout(m) => write!(f, "pdf: {m}"),
75            PdfError::Ocr(m) => write!(f, "pdf: {m}"),
76        }
77    }
78}
79
80impl std::error::Error for PdfError {}
81
82#[cfg(feature = "ml")]
83impl From<pdfium_render::prelude::PdfiumError> for PdfError {
84    fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
85        PdfError::Pdfium(e.to_string())
86    }
87}
88
89/// Convert a PDF's **embedded text layer only** — no pdfium, no ONNX, no
90/// threads: the pure-Rust content-stream parser ([`textparse`]) feeds the same
91/// orphan-region assembly the `no_ocr` pipeline flag uses, so text-layer PDFs
92/// come out identical to `--no-ocr` (flat, line-grouped paragraphs in reading
93/// order; no headings/lists/tables/pictures, and no hyperlink recovery).
94///
95/// This is the only conversion entry compiled without the `ml` feature (it is
96/// what a wasm32 build runs). A scanned/image-only PDF (no embedded text
97/// layer) yields an empty document rather than an error, same as `no_ocr` —
98/// callers can detect that and fall back to an OCR-capable build.
99pub fn convert_text_layer(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
100    let mut doc = DoclingDocument::new(name);
101    for page in textparse::pdf_text_pages(bytes) {
102        let mut regions = Vec::new();
103        assemble::add_orphan_regions(&mut regions, &page.cells);
104        let table_rows = vec![None; regions.len()];
105        let enrich_out = vec![None; regions.len()];
106        let (nodes, links) = assemble::assemble_page(&page, regions, &table_rows, &enrich_out);
107        doc.nodes.extend(nodes);
108        doc.links.extend(links);
109    }
110    assemble::merge_continuations(&mut doc.nodes);
111    Ok(doc)
112}
113
114/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
115/// Defaults to the available parallelism (ort otherwise picks a low number).
116#[cfg(feature = "ml")]
117pub(crate) fn intra_threads() -> usize {
118    if let Some(n) = std::env::var("DOCLING_RS_PDF_THREADS")
119        .ok()
120        .and_then(|v| v.parse::<usize>().ok())
121        .filter(|&n| n > 0)
122    {
123        return n;
124    }
125    std::thread::available_parallelism()
126        .map(|n| n.get())
127        .unwrap_or(1)
128}
129
130#[cfg(feature = "ml")]
131/// True when `DOCLING_RS_FP32` (any value but `0`) forces the full-precision
132/// models even where an INT8 variant sits next to the fp32 default.
133pub(crate) fn fp32_forced() -> bool {
134    std::env::var("DOCLING_RS_FP32")
135        .map(|v| v != "0")
136        .unwrap_or(false)
137}
138
139#[cfg(feature = "ml")]
140/// Should the int8 model defaults be skipped in favor of fp32? Either the
141/// user said so (`DOCLING_RS_FP32`), or a GPU execution provider is selected
142/// (#74) — the int8 exports are QDQ graphs calibrated for CPU kernels and
143/// only conformance-validated there. An explicit `DOCLING_*_ONNX` path
144/// override still wins over this at every call site.
145pub(crate) fn prefer_fp32() -> bool {
146    fp32_forced() || ep::prefers_fp32()
147}
148
149#[cfg(feature = "ml")]
150/// Resolve a default (CWD-relative) asset path. If it doesn't exist relative
151/// to the current directory, try next to the executable and one level above
152/// it (following symlinks — the layout `scripts/install/install.sh` produces:
153/// `/usr/local/bin/docling-rs` → `/usr/local/docling.rs/bin/docling-rs`
154/// with `models/` and `.pdfium/` in `/usr/local/docling.rs`). Lets an
155/// installed binary run from any working directory with no env vars; explicit
156/// env overrides never reach this. Returns `rel` unchanged when nothing
157/// exists anywhere, so callers' error messages keep the familiar path.
158pub(crate) fn resolve_asset(rel: &str) -> String {
159    if std::path::Path::new(rel).exists() {
160        return rel.to_string();
161    }
162    if let Some(dir) = std::env::current_exe()
163        .ok()
164        .and_then(|p| p.canonicalize().ok())
165        .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
166    {
167        for base in [Some(dir.as_path()), dir.parent()].into_iter().flatten() {
168            let p = base.join(rel);
169            if p.exists() {
170                return p.to_string_lossy().into_owned();
171            }
172        }
173    }
174    rel.to_string()
175}
176
177#[cfg(feature = "ml")]
178/// Resolve a model path: an explicit env override always wins; otherwise the
179/// INT8 variant of the default path when it exists on disk (the quantized
180/// models are conformance-validated — see docs/PDF_CONFORMANCE.md — and load/run
181/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
182/// precision; else the fp32 default.
183pub(crate) fn model_path(env: &str, fp32_default: &str, int8_default: &str) -> String {
184    if let Ok(p) = std::env::var(env) {
185        return p;
186    }
187    if !prefer_fp32() {
188        let p = resolve_asset(int8_default);
189        if std::path::Path::new(&p).exists() {
190            return p;
191        }
192    }
193    resolve_asset(fp32_default)
194}
195
196/// Decode a standalone image with hard resource limits. A crafted image can
197/// declare enormous dimensions in a few-KB file; `image::load_from_memory`
198/// then tries to allocate the full pixel buffer (e.g. 60000×60000 → ~10 GB),
199/// and allocation failure aborts the whole process, bypassing the per-request
200/// panic catch. The 256 MiB alloc / 30000-px caps below turn that into a
201/// recoverable decode error instead. `DOCLING_RS_MAX_IMAGE_PIXELS` overrides
202/// the per-side pixel cap for the rare legitimately-huge scan.
203///
204/// Gated on `ml`: the only callers (`convert_image`, the METS backend) are
205/// ML-only, and the `image` crate is an `ml`-feature dependency — the
206/// text-layer wasm build has neither.
207#[cfg(feature = "ml")]
208pub(crate) fn decode_image_limited(bytes: &[u8]) -> Result<image::RgbImage, PdfError> {
209    let max_side: u32 = std::env::var("DOCLING_RS_MAX_IMAGE_PIXELS")
210        .ok()
211        .and_then(|v| v.parse().ok())
212        .unwrap_or(30_000);
213    decode_image_with_max_side(bytes, max_side)
214}
215
216#[cfg(feature = "ml")]
217fn decode_image_with_max_side(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
218    use image::ImageReader;
219    use std::io::Cursor;
220
221    let mut limits = image::Limits::default();
222    limits.max_image_width = Some(max_side);
223    limits.max_image_height = Some(max_side);
224    limits.max_alloc = Some(256 * 1024 * 1024);
225
226    let mut reader = ImageReader::new(Cursor::new(bytes))
227        .with_guessed_format()
228        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
229    reader.limits(limits);
230    Ok(reader
231        .decode()
232        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?
233        .into_rgb8())
234}
235
236#[cfg(feature = "ml")]
237/// One page's assembled output: typed nodes plus the page's hyperlinks, kept
238/// separate so pages processed out of order can be stitched back in page order.
239type PageOut = (Vec<Node>, Vec<(String, String)>);
240
241#[cfg(feature = "ml")]
242/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
243/// lazily on the first table region any worker sees. Tables appear on a
244/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
245/// weights+arenas by the pool size for nothing; a single shared instance keeps
246/// the peak flat regardless of pool width, and a table's structure prediction
247/// is independent of which worker runs it, so output is byte-identical. The
248/// mutex serialises concurrent tables — the shared instance is loaded with the
249/// full intra-op thread budget to compensate (one wide TableFormer instead of
250/// several narrow ones).
251enum TfSlot {
252    /// Not attempted yet (no table seen so far).
253    Unloaded,
254    /// Load attempted, graphs absent — geometric fallback (warned once).
255    Missing,
256    Ready(tableformer::TableFormer),
257}
258
259#[cfg(feature = "ml")]
260type SharedTables = Arc<Mutex<TfSlot>>;
261
262#[cfg(feature = "ml")]
263/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
264/// one instance per pipeline, loaded on the first region that needs it.
265enum EnrichSlot<T> {
266    Unloaded,
267    /// Load attempted, model files absent — enrichment skipped (warned once).
268    Missing,
269    Ready(T),
270}
271
272#[cfg(feature = "ml")]
273type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
274#[cfg(feature = "ml")]
275type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
276
277#[cfg(feature = "ml")]
278/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
279/// flags (`do_picture_classification`, `do_code_enrichment`,
280/// `do_formula_enrichment`). All off by default.
281#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
282pub struct EnrichmentOptions {
283    /// Classify each picture with DocumentFigureClassifier (26 classes).
284    pub picture_classification: bool,
285    /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
286    pub code: bool,
287    /// Decode display formulas to LaTeX with CodeFormulaV2.
288    pub formula: bool,
289}
290
291#[cfg(feature = "ml")]
292impl EnrichmentOptions {
293    fn any(&self) -> bool {
294        self.picture_classification || self.code || self.formula
295    }
296}
297
298#[cfg(feature = "ml")]
299/// A self-contained set of the per-page models (layout, OCR). Each parallel
300/// page-worker owns its own `Worker` so inference runs concurrently without
301/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
302/// rarely-hit TableFormer is shared (see [`TfSlot`]).
303struct Worker {
304    /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
305    layout: Option<layout::LayoutModel>,
306    ocr: Option<ocr::OcrModel>,
307    /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
308    tables: Option<SharedTables>,
309    /// Shared enrichment slots; `None` unless the corresponding flag is on.
310    classifier: Option<SharedClassifier>,
311    code_formula: Option<SharedCodeFormula>,
312    enrich: EnrichmentOptions,
313    /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
314    /// embedded text layer. See [`Pipeline::no_ocr`].
315    no_ocr: bool,
316}
317
318#[cfg(feature = "ml")]
319impl Worker {
320    fn load(
321        intra: usize,
322        tables: Option<SharedTables>,
323        enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
324        enrich: EnrichmentOptions,
325        no_ocr: bool,
326    ) -> Result<Self, PdfError> {
327        Ok(Self {
328            layout: if no_ocr {
329                None
330            } else {
331                Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
332            },
333            ocr: None,
334            tables,
335            classifier: enrich_slots.0,
336            code_formula: enrich_slots.1,
337            enrich,
338            no_ocr,
339        })
340    }
341
342    /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
343    /// into its nodes and links. Pure given the page (mutates only the worker's
344    /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
345    fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
346        if self.no_ocr {
347            // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
348            // embedded text cells (if any) become flat, line-grouped paragraphs in
349            // reading order via the same orphan-region machinery that normally
350            // rescues text the detector missed — here it rescues *all* of it.
351            // Pages with no embedded text layer (scanned/image-only) yield nothing;
352            // convert those without `no_ocr`.
353            let mut regions = Vec::new();
354            assemble::add_orphan_regions(&mut regions, &page.cells);
355            let table_rows = vec![None; regions.len()];
356            let enrich_out = vec![None; regions.len()];
357            return Ok(timing::timed("assemble_page", || {
358                assemble::assemble_page(page, regions, &table_rows, &enrich_out)
359            }));
360        }
361        let regions = timing::timed("layout.predict", || {
362            self.layout
363                .as_mut()
364                .expect("layout model loaded unless no_ocr")
365                .predict(&page.image, page.width, page.height)
366        })
367        .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
368        self.finish_page(n, page, regions)
369    }
370
371    /// Layout-detect a whole batch of pages with one inference call (issue #73),
372    /// then run each page's remaining stages (OCR / TableFormer / enrichment /
373    /// assembly) per page. Index-aligned with `items`; a layout failure fails
374    /// every page in the batch (they shared the one inference call).
375    fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<PageOut, PdfError>> {
376        if self.no_ocr {
377            // No layout model to batch — the text-layer-only path is per page.
378            return items
379                .iter_mut()
380                .map(|(n, page)| {
381                    let n = *n;
382                    self.process(n, page)
383                })
384                .collect();
385        }
386        let inputs: Vec<(&image::RgbImage, f32, f32)> = items
387            .iter()
388            .map(|(_, page)| (&page.image, page.width, page.height))
389            .collect();
390        let batched = timing::timed("layout.predict", || {
391            self.layout
392                .as_mut()
393                .expect("layout model loaded unless no_ocr")
394                .predict_batch(&inputs)
395        });
396        match batched {
397            Ok(all) => items
398                .iter_mut()
399                .zip(all)
400                .map(|((n, page), regions)| self.finish_page(*n, page, regions))
401                .collect(),
402            Err(e) => items
403                .iter()
404                .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
405                .collect(),
406        }
407    }
408
409    /// Everything after layout detection: per-label confidence thresholds,
410    /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
411    /// TableFormer, enrichment, and page assembly.
412    fn finish_page(
413        &mut self,
414        n: usize,
415        page: &mut PdfPage,
416        regions: Vec<layout::Region>,
417    ) -> Result<PageOut, PdfError> {
418        // docling's LayoutPostprocessor drops each detection below its label's
419        // confidence threshold (stricter than the 0.3 base the predictor keeps),
420        // before any overlap resolution. This removes the low-confidence tables /
421        // pictures / list-items that otherwise double-emit or mis-classify.
422        let mut regions = regions;
423        regions.retain(|r| r.score >= layout::label_threshold(r.label));
424        // Resolve overlapping detections once, before OCR.
425        let mut regions = assemble::resolve(regions);
426        // Emit text the detector missed as orphan text regions (docling parity).
427        assemble::add_orphan_regions(&mut regions, &page.cells);
428        // Drop phantom empty low-confidence picture boxes (docling parity).
429        assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
430        // A regular region fully inside a surviving table/index/picture is that
431        // special's child (a cell / in-figure label), not a separate block —
432        // remove it so it isn't emitted twice (docling parity).
433        assemble::drop_contained_regulars(&mut regions);
434        // No text layer → recognise text from the page image via OCR.
435        if page.cells.is_empty() {
436            if self.ocr.is_none() {
437                self.ocr = Some(ocr::OcrModel::load().map_err(PdfError::Ocr)?);
438            }
439            let cells = timing::timed("ocr.page", || {
440                self.ocr
441                    .as_mut()
442                    .unwrap()
443                    .ocr_page(&page.image, &regions, page.scale)
444            })
445            .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
446            page.cells = cells;
447        }
448        // TableFormer structure per table region (else geometric fallback). The
449        // shared slot is only locked (and lazily loaded) when the page actually
450        // has a table, so table-free documents never pay for TableFormer at all.
451        let mut table_rows: Vec<Option<Vec<Vec<String>>>> = vec![None; regions.len()];
452        if let Some(slot) = self.tables.as_ref() {
453            if regions.iter().any(|r| assemble::is_table_like(r.label)) {
454                timing::timed("tableformer", || {
455                    let mut guard = slot.lock().unwrap();
456                    if matches!(*guard, TfSlot::Unloaded) {
457                        // Full intra-op width: tables serialise on this mutex, so
458                        // the one instance gets the whole thread budget.
459                        *guard = match tableformer::TableFormer::load_with(intra_threads()) {
460                            Some(tf) => TfSlot::Ready(tf),
461                            None => TfSlot::Missing,
462                        };
463                    }
464                    if let TfSlot::Ready(tf) = &mut *guard {
465                        for (i, r) in regions.iter().enumerate() {
466                            if assemble::is_table_like(r.label) {
467                                table_rows[i] = tf.predict_table_rows(
468                                    &page.image,
469                                    [r.l, r.t, r.r, r.b],
470                                    &page.word_cells,
471                                );
472                            }
473                        }
474                    }
475                });
476            }
477        }
478        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
479        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
480        // shape as TableFormer — one lazily-loaded instance per pipeline, only
481        // ever locked when a page actually has a matching region.
482        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
483        if let Some(slot) = self.classifier.as_ref() {
484            if regions.iter().any(|r| r.label == "picture") {
485                timing::timed("picture_classifier", || {
486                    let mut guard = slot.lock().unwrap();
487                    if matches!(*guard, EnrichSlot::Unloaded) {
488                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
489                            Some(m) => EnrichSlot::Ready(m),
490                            None => EnrichSlot::Missing,
491                        };
492                    }
493                    if let EnrichSlot::Ready(model) = &mut *guard {
494                        for (i, r) in regions.iter().enumerate() {
495                            if r.label != "picture" {
496                                continue;
497                            }
498                            let Some(crop) = assemble::crop_region_scaled(
499                                page,
500                                [r.l, r.t, r.r, r.b],
501                                enrich::CLASSIFIER_SCALE,
502                            ) else {
503                                continue;
504                            };
505                            match model.classify(&crop) {
506                                Ok(classes) => {
507                                    enrich_out[i] =
508                                        Some(assemble::Enrichment::PictureClasses(classes));
509                                }
510                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
511                            }
512                        }
513                    }
514                });
515            }
516        }
517        if let Some(slot) = self.code_formula.as_ref() {
518            let wants = |label: &str| {
519                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
520            };
521            if regions.iter().any(|r| wants(r.label)) {
522                timing::timed("code_formula", || {
523                    let mut guard = slot.lock().unwrap();
524                    if matches!(*guard, EnrichSlot::Unloaded) {
525                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
526                            Some(m) => EnrichSlot::Ready(m),
527                            None => EnrichSlot::Missing,
528                        };
529                    }
530                    if let EnrichSlot::Ready(model) = &mut *guard {
531                        for (i, r) in regions.iter().enumerate() {
532                            if !wants(r.label) {
533                                continue;
534                            }
535                            // docling crops the postprocessed cluster box — the
536                            // union of the region's text cells, not the raw
537                            // detector box — expanded by 18% per side, at
538                            // ~120 dpi.
539                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
540                                .unwrap_or([r.l, r.t, r.r, r.b]);
541                            let (w, h) = (br - bl, bb - bt);
542                            let ex = enrich::CODE_FORMULA_EXPANSION;
543                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
544                            let Some(crop) = assemble::crop_region_scaled(
545                                page,
546                                bbox,
547                                enrich::CODE_FORMULA_SCALE,
548                            ) else {
549                                continue;
550                            };
551                            let kind = if r.label == "code" {
552                                enrich::CodeFormulaKind::Code
553                            } else {
554                                enrich::CodeFormulaKind::Formula
555                            };
556                            match model.predict(&crop, kind) {
557                                Ok(text) => {
558                                    enrich_out[i] = Some(match kind {
559                                        enrich::CodeFormulaKind::Code => {
560                                            let (code, language) =
561                                                enrich::extract_code_language(&text);
562                                            assemble::Enrichment::Code {
563                                                language,
564                                                text: code,
565                                            }
566                                        }
567                                        enrich::CodeFormulaKind::Formula => {
568                                            assemble::Enrichment::Formula { latex: text }
569                                        }
570                                    });
571                                }
572                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
573                            }
574                        }
575                    }
576                });
577            }
578        }
579        Ok(timing::timed("assemble_page", || {
580            assemble::assemble_page(page, regions, &table_rows, &enrich_out)
581        }))
582    }
583}
584
585#[cfg(feature = "ml")]
586/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
587/// so on a typical machine two threads per worker (sharing one in-cache copy of
588/// the weights) extracts more throughput than one fat model or many single-thread
589/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
590fn pdf_intra() -> usize {
591    if let Some(n) = std::env::var("DOCLING_RS_PDF_INTRA")
592        .ok()
593        .and_then(|v| v.parse::<usize>().ok())
594        .filter(|&n| n > 0)
595    {
596        return n;
597    }
598    if intra_threads() >= 2 {
599        2
600    } else {
601        1
602    }
603}
604
605#[cfg(feature = "ml")]
606/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
607/// overrides; otherwise size the pool so `workers × intra ≈ cores`, capped at 4 so
608/// a worst-case pool holds a bounded amount of model memory (~0.4 GB per worker)
609/// and does not oversaturate the memory bus with model-weight traffic.
610fn pdf_worker_count() -> usize {
611    if let Some(n) = std::env::var("DOCLING_RS_PDF_WORKERS")
612        .ok()
613        .and_then(|v| v.parse::<usize>().ok())
614        .filter(|&n| n > 0)
615    {
616        return n;
617    }
618    (intra_threads() / pdf_intra()).clamp(1, 4)
619}
620
621#[cfg(feature = "ml")]
622/// Max pages a worker layout-detects with one batched inference call (issue
623/// #73). Workers drain the work channel opportunistically up to this size —
624/// whatever is already rendered gets batched, so batching never *waits* for
625/// pages and adds no latency when rendering is the bottleneck.
626///
627/// Default: 4 on 8+ cores, 1 (per-page) below. Measured on a 4-core box the
628/// batch only adds cache pressure and costs pipeline overlap (2 workers × 2
629/// threads: 8.1 s/conv at batch=1 vs 9.3 s at batch=4 on the 9-page
630/// 2206.01062 fixture); the single-session amortization it buys needs the
631/// wider thread budget of a many-core machine. Output is bit-identical at
632/// every batch size, so this is purely a throughput knob.
633/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides; `1` restores per-page inference.
634fn pdf_layout_batch() -> usize {
635    std::env::var("DOCLING_RS_PDF_LAYOUT_BATCH")
636        .ok()
637        .and_then(|v| v.parse::<usize>().ok())
638        .filter(|&n| n > 0)
639        .unwrap_or_else(|| if intra_threads() >= 8 { 4 } else { 1 })
640}
641
642#[cfg(feature = "ml")]
643/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
644/// the serial primary (running its model on every core) is faster than fanning out
645/// — the helper pool's one-time model-load cost only pays off once enough pages
646/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
647fn pdf_parallel_min() -> usize {
648    std::env::var("DOCLING_RS_PDF_PARALLEL_MIN")
649        .ok()
650        .and_then(|v| v.parse::<usize>().ok())
651        .filter(|&n| n > 0)
652        .unwrap_or(6)
653}
654
655#[cfg(feature = "ml")]
656/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
657/// so a single-page / small / image / METS input is converted at full intra-op
658/// speed with no pool to load. A document with enough pages instead fans out
659/// across a **pool** of narrower workers processed concurrently. Both load lazily
660/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
661pub struct Pipeline {
662    /// Full-intra worker for the serial path; loaded on first serial use.
663    primary: Option<Worker>,
664    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
665    /// path; loaded on first multi-page use and cached.
666    pool: Vec<Worker>,
667    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
668    tables: SharedTables,
669    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
670    classifier: SharedClassifier,
671    code_formula: SharedCodeFormula,
672    /// Desired pool size for multi-page documents.
673    target_workers: usize,
674    /// Page count at/above which the parallel pool is worth its load cost.
675    parallel_min: usize,
676    /// Skip loading/running TableFormer; table regions fall back to geometric
677    /// reconstruction. See [`Pipeline::no_table_former`].
678    no_table_former: bool,
679    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
680    no_ocr: bool,
681    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
682    enrich: EnrichmentOptions,
683}
684
685#[cfg(feature = "ml")]
686impl Pipeline {
687    /// Construct the pipeline. Models load lazily on first use (full-intra primary
688    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
689    /// loaded that a given document doesn't need.
690    pub fn new() -> Result<Self, PdfError> {
691        Ok(Self {
692            primary: None,
693            pool: Vec::new(),
694            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
695            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
696            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
697            target_workers: pdf_worker_count(),
698            parallel_min: pdf_parallel_min(),
699            no_table_former: false,
700            no_ocr: false,
701            enrich: EnrichmentOptions::default(),
702        })
703    }
704
705    /// Enable the opt-in enrichment passes (docling's
706    /// `do_picture_classification` / `do_code_enrichment` /
707    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
708    /// the first matching region; a missing model warns once and is skipped.
709    /// Set before the first conversion (no effect on already-loaded workers).
710    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
711        self.enrich = opts;
712        self
713    }
714
715    /// Skip loading and running the TableFormer table-structure model. Table
716    /// regions still get emitted, but reconstructed geometrically from cell
717    /// positions instead of via the ONNX model's predicted structure — faster
718    /// (no model load, no per-table inference) at the cost of table fidelity.
719    /// No effect if a worker is already loaded; set this before the first
720    /// conversion.
721    pub fn no_table_former(mut self, disable: bool) -> Self {
722        self.no_table_former = disable;
723        self
724    }
725
726    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
727    /// inference of any kind. The PDF's embedded text cells are grouped by line
728    /// and emitted as plain paragraphs in reading order: no headings, lists,
729    /// tables, code blocks, or pictures, since that structure comes from the
730    /// layout model. The fastest possible PDF path, but pages with no embedded
731    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
732    /// without this flag. Implies `no_table_former`. No effect if a worker is
733    /// already loaded; set this before the first conversion.
734    pub fn no_ocr(mut self, disable: bool) -> Self {
735        self.no_ocr = disable;
736        self
737    }
738
739    /// The shared TableFormer slot handed to each worker, or `None` when the
740    /// pipeline options skip TableFormer entirely.
741    fn tables_slot(&self) -> Option<SharedTables> {
742        if self.no_table_former || self.no_ocr {
743            None
744        } else {
745            Some(Arc::clone(&self.tables))
746        }
747    }
748
749    /// The shared enrichment slots for a worker (`None` per model unless its
750    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
751    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
752        if self.no_ocr || !self.enrich.any() {
753            return (None, None);
754        }
755        (
756            self.enrich
757                .picture_classification
758                .then(|| Arc::clone(&self.classifier)),
759            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
760        )
761    }
762
763    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
764    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
765    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
766    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
767    /// `DocumentConverter.initialize_pipeline`.
768    pub fn warm_up(&mut self) -> Result<(), PdfError> {
769        self.primary()?;
770        Ok(())
771    }
772
773    /// The full-intra serial worker, loaded on first use.
774    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
775        if self.primary.is_none() {
776            self.primary = Some(Worker::load(
777                intra_threads(),
778                self.tables_slot(),
779                self.enrich_slots(),
780                self.enrich,
781                self.no_ocr,
782            )?);
783        }
784        Ok(self.primary.as_mut().unwrap())
785    }
786
787    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
788    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
789    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
790    /// fans the pages out across the worker pool, reassembled in page order so the
791    /// output is byte-identical to the serial path.
792    pub fn convert(
793        &mut self,
794        bytes: &[u8],
795        password: Option<&str>,
796        name: &str,
797    ) -> Result<DoclingDocument, PdfError> {
798        let pages = pdfium_backend::page_count(bytes, password)?;
799        let doc = if self.target_workers >= 2 && pages >= self.parallel_min {
800            self.convert_parallel(bytes, password, name)?
801        } else {
802            self.convert_serial(bytes, password, name)?
803        };
804        timing::report();
805        Ok(doc)
806    }
807
808    /// Stream pages one at a time through the primary worker — render → process →
809    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
810    fn convert_serial(
811        &mut self,
812        bytes: &[u8],
813        password: Option<&str>,
814        name: &str,
815    ) -> Result<DoclingDocument, PdfError> {
816        let mut doc = DoclingDocument::new(name);
817        let render_image = !self.no_ocr;
818        let worker = self.primary()?;
819        pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
820            let (nodes, links) = worker.process(n, &mut page)?;
821            doc.nodes.extend(nodes);
822            doc.links.extend(links);
823            Ok::<(), PdfError>(())
824        })?;
825        assemble::merge_continuations(&mut doc.nodes);
826        Ok(doc)
827    }
828
829    /// Render pages serially on this thread (pdfium) and process them in parallel
830    /// across the worker pool. A bounded channel applies backpressure so only a
831    /// handful of page bitmaps are resident at once; results carry their page
832    /// index and are reassembled in order, so the output is byte-identical to the
833    /// serial path.
834    fn convert_parallel(
835        &mut self,
836        bytes: &[u8],
837        password: Option<&str>,
838        name: &str,
839    ) -> Result<DoclingDocument, PdfError> {
840        self.ensure_pool()?;
841        let n_workers = self.pool.len();
842        let render_image = !self.no_ocr;
843        let layout_batch = pdf_layout_batch();
844        // Bound sized so every worker can accumulate a full layout batch while
845        // rendering stays ahead (and never below the pre-#73 render-ahead of
846        // two pages per worker); still a hard cap on resident page bitmaps.
847        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
848        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
849        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
850        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
851
852        // Move the pool into the scope so each worker gets an exclusive `&mut`.
853        let mut workers = std::mem::take(&mut self.pool);
854        std::thread::scope(|s| {
855            for worker in workers.iter_mut() {
856                let work_rx = Arc::clone(&work_rx);
857                let results = Arc::clone(&results);
858                let first_err = Arc::clone(&first_err);
859                s.spawn(move || loop {
860                    // Hold the receiver lock only for the recv (plus a non-blocking
861                    // drain up to the layout batch size); release before the (long)
862                    // per-page work so other workers can pull concurrently.
863                    let mut batch = Vec::new();
864                    {
865                        let rx = work_rx.lock().unwrap();
866                        match rx.recv() {
867                            Ok(item) => {
868                                batch.push(item);
869                                while batch.len() < layout_batch {
870                                    match rx.try_recv() {
871                                        Ok(item) => batch.push(item),
872                                        Err(_) => break,
873                                    }
874                                }
875                            }
876                            Err(_) => break,
877                        }
878                    }
879                    let outs = worker.process_batch(&mut batch);
880                    for ((idx, _), out) in batch.iter().zip(outs) {
881                        match out {
882                            Ok(out) => results.lock().unwrap().push((*idx, out)),
883                            Err(e) => {
884                                let mut slot = first_err.lock().unwrap();
885                                if slot.is_none() {
886                                    *slot = Some(e);
887                                }
888                            }
889                        }
890                    }
891                });
892            }
893            // Render on this thread and feed the workers; backpressure blocks here
894            // when the channel is full. Dropping `work_tx` afterwards signals the
895            // workers (recv → Err) to finish.
896            let render =
897                pdfium_backend::for_each_page(bytes, password, render_image, |i, _total, page| {
898                    work_tx
899                        .send((i, page))
900                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
901                });
902            drop(work_tx);
903            if let Err(e) = render {
904                let mut slot = first_err.lock().unwrap();
905                if slot.is_none() {
906                    *slot = Some(e);
907                }
908            }
909        });
910        // Threads have joined; restore the pool for the next conversion.
911        self.pool = workers;
912
913        if let Some(e) = first_err.lock().unwrap().take() {
914            return Err(e);
915        }
916        let mut results = Arc::try_unwrap(results)
917            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
918            .into_inner()
919            .unwrap();
920        results.sort_by_key(|(idx, _)| *idx);
921        let mut doc = DoclingDocument::new(name);
922        for (_, (nodes, links)) in results {
923            doc.nodes.extend(nodes);
924            doc.links.extend(links);
925        }
926        assemble::merge_continuations(&mut doc.nodes);
927        Ok(doc)
928    }
929
930    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
931    /// in-document-order batch of nodes (and that span's recovered links) as pages
932    /// complete, so a caller can serialize Markdown page by page instead of waiting
933    /// for the whole document. The batches are exactly the buffered [`convert`]'s
934    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
935    /// parallel path reorders pages back into document order before emitting, so
936    /// the output is identical regardless of worker scheduling.
937    ///
938    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
939    /// and its backpressure throttles the whole pipeline. Returning `Err` from
940    /// `emit` aborts the conversion with that error.
941    pub fn convert_streaming<F>(
942        &mut self,
943        bytes: &[u8],
944        password: Option<&str>,
945        name: &str,
946        emit: F,
947    ) -> Result<(), PdfError>
948    where
949        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
950    {
951        let _ = name; // page nodes carry no name; the caller owns the document name.
952        let pages = pdfium_backend::page_count(bytes, password)?;
953        let r = if self.target_workers >= 2 && pages >= self.parallel_min {
954            self.convert_streaming_parallel(bytes, password, emit)
955        } else {
956            self.convert_streaming_serial(bytes, password, emit)
957        };
958        timing::report();
959        r
960    }
961
962    /// Serial streaming: render → process → emit, one page at a time, holding back
963    /// only the tail that might still merge into the next page.
964    fn convert_streaming_serial<F>(
965        &mut self,
966        bytes: &[u8],
967        password: Option<&str>,
968        mut emit: F,
969    ) -> Result<(), PdfError>
970    where
971        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
972    {
973        let mut asm = assemble::StreamAssembler::new();
974        let render_image = !self.no_ocr;
975        let worker = self.primary()?;
976        pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
977            let (nodes, links) = worker.process(n, &mut page)?;
978            emit(asm.push(nodes), links)
979        })?;
980        emit(asm.finish(), Vec::new())
981    }
982
983    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
984    /// not thread-safe) and process across the worker pool; results carry their
985    /// page index and are reordered on the calling thread into a
986    /// [`assemble::StreamAssembler`], which emits each page in document order as
987    /// soon as its predecessors have arrived. Bounded channels keep only a handful
988    /// of pages resident and let `emit`'s backpressure reach the renderer.
989    fn convert_streaming_parallel<F>(
990        &mut self,
991        bytes: &[u8],
992        password: Option<&str>,
993        mut emit: F,
994    ) -> Result<(), PdfError>
995    where
996        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
997    {
998        self.ensure_pool()?;
999        let n_workers = self.pool.len();
1000        let render_image = !self.no_ocr;
1001        let layout_batch = pdf_layout_batch();
1002        // Bound sized so every worker can accumulate a full layout batch while
1003        // rendering stays ahead (and never below the pre-#73 render-ahead of
1004        // two pages per worker); still a hard cap on resident page bitmaps.
1005        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
1006        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
1007        // Workers and the renderer report here; the calling thread drains it in
1008        // page order. Bounded so workers block (bounding resident bitmaps) when the
1009        // consumer falls behind.
1010        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
1011
1012        let mut workers = std::mem::take(&mut self.pool);
1013        let mut asm = assemble::StreamAssembler::new();
1014        let mut first_err: Option<PdfError> = None;
1015
1016        std::thread::scope(|s| {
1017            // Workers: pull a batch of pages (whatever is already rendered, up
1018            // to the layout batch size), process it, report (index-tagged)
1019            // results.
1020            for worker in workers.iter_mut() {
1021                let work_rx = Arc::clone(&work_rx);
1022                let res_tx = res_tx.clone();
1023                s.spawn(move || 'outer: loop {
1024                    let mut batch = Vec::new();
1025                    {
1026                        let rx = work_rx.lock().unwrap();
1027                        match rx.recv() {
1028                            Ok(item) => {
1029                                batch.push(item);
1030                                while batch.len() < layout_batch {
1031                                    match rx.try_recv() {
1032                                        Ok(item) => batch.push(item),
1033                                        Err(_) => break,
1034                                    }
1035                                }
1036                            }
1037                            Err(_) => break,
1038                        }
1039                    }
1040                    let outs = worker.process_batch(&mut batch);
1041                    for ((idx, _), out) in batch.iter().zip(outs) {
1042                        if res_tx.send(out.map(|o| (*idx, o))).is_err() {
1043                            break 'outer; // consumer gone
1044                        }
1045                    }
1046                });
1047            }
1048            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
1049            // single thread); report a render error through the same channel.
1050            {
1051                let res_tx = res_tx.clone();
1052                s.spawn(move || {
1053                    let render = pdfium_backend::for_each_page(
1054                        bytes,
1055                        password,
1056                        render_image,
1057                        |i, _total, page| {
1058                            work_tx
1059                                .send((i, page))
1060                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
1061                        },
1062                    );
1063                    drop(work_tx); // signal workers to finish
1064                    if let Err(e) = render {
1065                        let _ = res_tx.send(Err(e));
1066                    }
1067                });
1068            }
1069            // Drop our own sender so the channel closes once the threads finish.
1070            drop(res_tx);
1071
1072            // Collector (this thread): reorder into document order and emit.
1073            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
1074            let mut next = 0usize;
1075            for msg in res_rx.iter() {
1076                match msg {
1077                    Err(e) => {
1078                        if first_err.is_none() {
1079                            first_err = Some(e);
1080                        }
1081                    }
1082                    Ok((idx, out)) => {
1083                        buffer.insert(idx, out);
1084                        if first_err.is_some() {
1085                            continue; // keep draining so the threads can exit
1086                        }
1087                        while let Some((nodes, links)) = buffer.remove(&next) {
1088                            if let Err(e) = emit(asm.push(nodes), links) {
1089                                first_err = Some(e);
1090                                break;
1091                            }
1092                            next += 1;
1093                        }
1094                    }
1095                }
1096            }
1097        });
1098        // Threads have joined; restore the pool for the next conversion.
1099        self.pool = workers;
1100
1101        if let Some(e) = first_err {
1102            return Err(e);
1103        }
1104        emit(asm.finish(), Vec::new())
1105    }
1106
1107    /// Lazily grow the pool to `target_workers`, loading the new workers
1108    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
1109    /// one load's wall-time). Cached for reuse across documents.
1110    fn ensure_pool(&mut self) -> Result<(), PdfError> {
1111        let need = self.target_workers.saturating_sub(self.pool.len());
1112        if need == 0 {
1113            return Ok(());
1114        }
1115        let intra = pdf_intra();
1116        let no_ocr = self.no_ocr;
1117        let enrich = self.enrich;
1118        let tables = self.tables_slot();
1119        let enrich_slots = self.enrich_slots();
1120        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
1121            let handles: Vec<_> = (0..need)
1122                .map(|_| {
1123                    let tables = tables.clone();
1124                    let enrich_slots = enrich_slots.clone();
1125                    s.spawn(move || Worker::load(intra, tables, enrich_slots, enrich, no_ocr))
1126                })
1127                .collect();
1128            handles.into_iter().map(|h| h.join().unwrap()).collect()
1129        });
1130        for w in loaded {
1131            self.pool.push(w?);
1132        }
1133        Ok(())
1134    }
1135
1136    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
1137    /// docling routes images through the same layout+OCR pipeline as a PDF page.
1138    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1139        let image = decode_image_limited(bytes)?;
1140        let (w, h) = image.dimensions();
1141        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
1142        // standalone image has no text layer, so OCR supplies the cells.
1143        let page = PdfPage {
1144            width: w as f32,
1145            height: h as f32,
1146            scale: 1.0,
1147            cells: Vec::new(),
1148            code_cells: Vec::new(),
1149            word_cells: Vec::new(),
1150            image,
1151            links: Vec::new(),
1152        };
1153        self.process_pages(vec![page], name)
1154    }
1155
1156    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
1157    /// page (image / METS inputs, which are small and already materialised).
1158    fn process_pages(
1159        &mut self,
1160        mut pages: Vec<PdfPage>,
1161        name: &str,
1162    ) -> Result<DoclingDocument, PdfError> {
1163        let mut doc = DoclingDocument::new(name);
1164        let worker = self.primary()?;
1165        for (n, page) in pages.iter_mut().enumerate() {
1166            let (nodes, links) = worker.process(n, page)?;
1167            doc.nodes.extend(nodes);
1168            doc.links.extend(links);
1169        }
1170        assemble::merge_continuations(&mut doc.nodes);
1171        Ok(doc)
1172    }
1173}
1174
1175#[cfg(feature = "ml")]
1176/// Convenience one-shot conversion (loads the pipeline per call). Errors are
1177/// detailed and surfaced (never silently skipped).
1178pub fn convert(
1179    bytes: &[u8],
1180    password: Option<&str>,
1181    name: &str,
1182) -> Result<DoclingDocument, PdfError> {
1183    convert_with_options(
1184        bytes,
1185        password,
1186        name,
1187        false,
1188        false,
1189        EnrichmentOptions::default(),
1190    )
1191}
1192
1193#[cfg(feature = "ml")]
1194/// Like [`convert`], but optionally skips loading/running TableFormer (see
1195/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1196/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
1197/// [`Pipeline::enrichments`]).
1198pub fn convert_with_options(
1199    bytes: &[u8],
1200    password: Option<&str>,
1201    name: &str,
1202    no_table_former: bool,
1203    no_ocr: bool,
1204    enrich: EnrichmentOptions,
1205) -> Result<DoclingDocument, PdfError> {
1206    Pipeline::new()?
1207        .no_table_former(no_table_former)
1208        .no_ocr(no_ocr)
1209        .enrichments(enrich)
1210        .convert(bytes, password, name)
1211}
1212
1213#[cfg(feature = "ml")]
1214/// Convenience one-shot image conversion (loads the pipeline per call).
1215pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1216    convert_image_with_options(bytes, name, false, false, EnrichmentOptions::default())
1217}
1218
1219#[cfg(feature = "ml")]
1220/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
1221/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1222/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
1223pub fn convert_image_with_options(
1224    bytes: &[u8],
1225    name: &str,
1226    no_table_former: bool,
1227    no_ocr: bool,
1228    enrich: EnrichmentOptions,
1229) -> Result<DoclingDocument, PdfError> {
1230    Pipeline::new()?
1231        .no_table_former(no_table_former)
1232        .no_ocr(no_ocr)
1233        .enrichments(enrich)
1234        .convert_image(bytes, name)
1235}
1236
1237#[cfg(feature = "ml")]
1238/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
1239/// scans) through the shared layout + assembly pipeline.
1240pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
1241    convert_pages_with_options(pages, name, false, false, EnrichmentOptions::default())
1242}
1243
1244#[cfg(feature = "ml")]
1245/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
1246/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1247/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
1248pub fn convert_pages_with_options(
1249    pages: Vec<PdfPage>,
1250    name: &str,
1251    no_table_former: bool,
1252    no_ocr: bool,
1253    enrich: EnrichmentOptions,
1254) -> Result<DoclingDocument, PdfError> {
1255    Pipeline::new()?
1256        .no_table_former(no_table_former)
1257        .no_ocr(no_ocr)
1258        .enrichments(enrich)
1259        .process_pages(pages, name)
1260}
1261
1262#[cfg(feature = "ml")]
1263#[cfg(all(test, feature = "ml"))]
1264mod image_limit_tests {
1265    use super::decode_image_with_max_side;
1266
1267    /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
1268    /// byte literal).
1269    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
1270        use std::io::Cursor;
1271        let img = image::RgbImage::new(w, h);
1272        let mut out = Vec::new();
1273        img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
1274            .unwrap();
1275        out
1276    }
1277
1278    #[test]
1279    fn normal_image_decodes_under_the_cap() {
1280        let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
1281        assert_eq!(img.dimensions(), (8, 8));
1282    }
1283
1284    #[test]
1285    fn dimensions_over_the_cap_are_rejected_not_aborted() {
1286        // A per-side cap below the image's declared size must yield a
1287        // recoverable Err, never an allocation-abort — the mechanism that stops
1288        // a crafted image declaring 60000×60000 from OOM-killing the process.
1289        let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
1290        assert!(
1291            r.is_err(),
1292            "decode must fail under the pixel cap, not abort"
1293        );
1294    }
1295}
1296
1297#[cfg(test)]
1298mod median_tests {
1299    #[test]
1300    fn median_of_empty_is_zero_not_a_panic() {
1301        // A crafted table can leave a row/column with zero matched cells; the
1302        // even-count branch would index values[0 - 1] and panic (→ remote crash
1303        // via docling-serve) without the empty guard.
1304        assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
1305        assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
1306        assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
1307    }
1308}
1309
1310#[cfg(test)]
1311mod send_check {
1312    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
1313    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
1314    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
1315    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
1316    fn assert_send<T: Send>() {}
1317
1318    #[test]
1319    fn pipeline_is_send() {
1320        assert_send::<super::Pipeline>();
1321    }
1322}