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#[cfg(feature = "ml")]
197/// One page's assembled output: typed nodes plus the page's hyperlinks, kept
198/// separate so pages processed out of order can be stitched back in page order.
199type PageOut = (Vec<Node>, Vec<(String, String)>);
200
201#[cfg(feature = "ml")]
202/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
203/// lazily on the first table region any worker sees. Tables appear on a
204/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
205/// weights+arenas by the pool size for nothing; a single shared instance keeps
206/// the peak flat regardless of pool width, and a table's structure prediction
207/// is independent of which worker runs it, so output is byte-identical. The
208/// mutex serialises concurrent tables — the shared instance is loaded with the
209/// full intra-op thread budget to compensate (one wide TableFormer instead of
210/// several narrow ones).
211enum TfSlot {
212    /// Not attempted yet (no table seen so far).
213    Unloaded,
214    /// Load attempted, graphs absent — geometric fallback (warned once).
215    Missing,
216    Ready(tableformer::TableFormer),
217}
218
219#[cfg(feature = "ml")]
220type SharedTables = Arc<Mutex<TfSlot>>;
221
222#[cfg(feature = "ml")]
223/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
224/// one instance per pipeline, loaded on the first region that needs it.
225enum EnrichSlot<T> {
226    Unloaded,
227    /// Load attempted, model files absent — enrichment skipped (warned once).
228    Missing,
229    Ready(T),
230}
231
232#[cfg(feature = "ml")]
233type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
234#[cfg(feature = "ml")]
235type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
236
237#[cfg(feature = "ml")]
238/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
239/// flags (`do_picture_classification`, `do_code_enrichment`,
240/// `do_formula_enrichment`). All off by default.
241#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
242pub struct EnrichmentOptions {
243    /// Classify each picture with DocumentFigureClassifier (26 classes).
244    pub picture_classification: bool,
245    /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
246    pub code: bool,
247    /// Decode display formulas to LaTeX with CodeFormulaV2.
248    pub formula: bool,
249}
250
251#[cfg(feature = "ml")]
252impl EnrichmentOptions {
253    fn any(&self) -> bool {
254        self.picture_classification || self.code || self.formula
255    }
256}
257
258#[cfg(feature = "ml")]
259/// A self-contained set of the per-page models (layout, OCR). Each parallel
260/// page-worker owns its own `Worker` so inference runs concurrently without
261/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
262/// rarely-hit TableFormer is shared (see [`TfSlot`]).
263struct Worker {
264    /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
265    layout: Option<layout::LayoutModel>,
266    ocr: Option<ocr::OcrModel>,
267    /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
268    tables: Option<SharedTables>,
269    /// Shared enrichment slots; `None` unless the corresponding flag is on.
270    classifier: Option<SharedClassifier>,
271    code_formula: Option<SharedCodeFormula>,
272    enrich: EnrichmentOptions,
273    /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
274    /// embedded text layer. See [`Pipeline::no_ocr`].
275    no_ocr: bool,
276}
277
278#[cfg(feature = "ml")]
279impl Worker {
280    fn load(
281        intra: usize,
282        tables: Option<SharedTables>,
283        enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
284        enrich: EnrichmentOptions,
285        no_ocr: bool,
286    ) -> Result<Self, PdfError> {
287        Ok(Self {
288            layout: if no_ocr {
289                None
290            } else {
291                Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
292            },
293            ocr: None,
294            tables,
295            classifier: enrich_slots.0,
296            code_formula: enrich_slots.1,
297            enrich,
298            no_ocr,
299        })
300    }
301
302    /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
303    /// into its nodes and links. Pure given the page (mutates only the worker's
304    /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
305    fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
306        if self.no_ocr {
307            // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
308            // embedded text cells (if any) become flat, line-grouped paragraphs in
309            // reading order via the same orphan-region machinery that normally
310            // rescues text the detector missed — here it rescues *all* of it.
311            // Pages with no embedded text layer (scanned/image-only) yield nothing;
312            // convert those without `no_ocr`.
313            let mut regions = Vec::new();
314            assemble::add_orphan_regions(&mut regions, &page.cells);
315            let table_rows = vec![None; regions.len()];
316            let enrich_out = vec![None; regions.len()];
317            return Ok(timing::timed("assemble_page", || {
318                assemble::assemble_page(page, regions, &table_rows, &enrich_out)
319            }));
320        }
321        let regions = timing::timed("layout.predict", || {
322            self.layout
323                .as_mut()
324                .expect("layout model loaded unless no_ocr")
325                .predict(&page.image, page.width, page.height)
326        })
327        .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
328        self.finish_page(n, page, regions)
329    }
330
331    /// Layout-detect a whole batch of pages with one inference call (issue #73),
332    /// then run each page's remaining stages (OCR / TableFormer / enrichment /
333    /// assembly) per page. Index-aligned with `items`; a layout failure fails
334    /// every page in the batch (they shared the one inference call).
335    fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<PageOut, PdfError>> {
336        if self.no_ocr {
337            // No layout model to batch — the text-layer-only path is per page.
338            return items
339                .iter_mut()
340                .map(|(n, page)| {
341                    let n = *n;
342                    self.process(n, page)
343                })
344                .collect();
345        }
346        let inputs: Vec<(&image::RgbImage, f32, f32)> = items
347            .iter()
348            .map(|(_, page)| (&page.image, page.width, page.height))
349            .collect();
350        let batched = timing::timed("layout.predict", || {
351            self.layout
352                .as_mut()
353                .expect("layout model loaded unless no_ocr")
354                .predict_batch(&inputs)
355        });
356        match batched {
357            Ok(all) => items
358                .iter_mut()
359                .zip(all)
360                .map(|((n, page), regions)| self.finish_page(*n, page, regions))
361                .collect(),
362            Err(e) => items
363                .iter()
364                .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
365                .collect(),
366        }
367    }
368
369    /// Everything after layout detection: per-label confidence thresholds,
370    /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
371    /// TableFormer, enrichment, and page assembly.
372    fn finish_page(
373        &mut self,
374        n: usize,
375        page: &mut PdfPage,
376        regions: Vec<layout::Region>,
377    ) -> Result<PageOut, PdfError> {
378        // docling's LayoutPostprocessor drops each detection below its label's
379        // confidence threshold (stricter than the 0.3 base the predictor keeps),
380        // before any overlap resolution. This removes the low-confidence tables /
381        // pictures / list-items that otherwise double-emit or mis-classify.
382        let mut regions = regions;
383        regions.retain(|r| r.score >= layout::label_threshold(r.label));
384        // Resolve overlapping detections once, before OCR.
385        let mut regions = assemble::resolve(regions);
386        // Emit text the detector missed as orphan text regions (docling parity).
387        assemble::add_orphan_regions(&mut regions, &page.cells);
388        // Drop phantom empty low-confidence picture boxes (docling parity).
389        assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
390        // A regular region fully inside a surviving table/index/picture is that
391        // special's child (a cell / in-figure label), not a separate block —
392        // remove it so it isn't emitted twice (docling parity).
393        assemble::drop_contained_regulars(&mut regions);
394        // No text layer → recognise text from the page image via OCR.
395        if page.cells.is_empty() {
396            if self.ocr.is_none() {
397                self.ocr = Some(ocr::OcrModel::load().map_err(PdfError::Ocr)?);
398            }
399            let cells = timing::timed("ocr.page", || {
400                self.ocr
401                    .as_mut()
402                    .unwrap()
403                    .ocr_page(&page.image, &regions, page.scale)
404            })
405            .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
406            page.cells = cells;
407        }
408        // TableFormer structure per table region (else geometric fallback). The
409        // shared slot is only locked (and lazily loaded) when the page actually
410        // has a table, so table-free documents never pay for TableFormer at all.
411        let mut table_rows: Vec<Option<Vec<Vec<String>>>> = vec![None; regions.len()];
412        if let Some(slot) = self.tables.as_ref() {
413            if regions.iter().any(|r| assemble::is_table_like(r.label)) {
414                timing::timed("tableformer", || {
415                    let mut guard = slot.lock().unwrap();
416                    if matches!(*guard, TfSlot::Unloaded) {
417                        // Full intra-op width: tables serialise on this mutex, so
418                        // the one instance gets the whole thread budget.
419                        *guard = match tableformer::TableFormer::load_with(intra_threads()) {
420                            Some(tf) => TfSlot::Ready(tf),
421                            None => TfSlot::Missing,
422                        };
423                    }
424                    if let TfSlot::Ready(tf) = &mut *guard {
425                        for (i, r) in regions.iter().enumerate() {
426                            if assemble::is_table_like(r.label) {
427                                table_rows[i] = tf.predict_table_rows(
428                                    &page.image,
429                                    [r.l, r.t, r.r, r.b],
430                                    &page.word_cells,
431                                );
432                            }
433                        }
434                    }
435                });
436            }
437        }
438        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
439        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
440        // shape as TableFormer — one lazily-loaded instance per pipeline, only
441        // ever locked when a page actually has a matching region.
442        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
443        if let Some(slot) = self.classifier.as_ref() {
444            if regions.iter().any(|r| r.label == "picture") {
445                timing::timed("picture_classifier", || {
446                    let mut guard = slot.lock().unwrap();
447                    if matches!(*guard, EnrichSlot::Unloaded) {
448                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
449                            Some(m) => EnrichSlot::Ready(m),
450                            None => EnrichSlot::Missing,
451                        };
452                    }
453                    if let EnrichSlot::Ready(model) = &mut *guard {
454                        for (i, r) in regions.iter().enumerate() {
455                            if r.label != "picture" {
456                                continue;
457                            }
458                            let Some(crop) = assemble::crop_region_scaled(
459                                page,
460                                [r.l, r.t, r.r, r.b],
461                                enrich::CLASSIFIER_SCALE,
462                            ) else {
463                                continue;
464                            };
465                            match model.classify(&crop) {
466                                Ok(classes) => {
467                                    enrich_out[i] =
468                                        Some(assemble::Enrichment::PictureClasses(classes));
469                                }
470                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
471                            }
472                        }
473                    }
474                });
475            }
476        }
477        if let Some(slot) = self.code_formula.as_ref() {
478            let wants = |label: &str| {
479                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
480            };
481            if regions.iter().any(|r| wants(r.label)) {
482                timing::timed("code_formula", || {
483                    let mut guard = slot.lock().unwrap();
484                    if matches!(*guard, EnrichSlot::Unloaded) {
485                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
486                            Some(m) => EnrichSlot::Ready(m),
487                            None => EnrichSlot::Missing,
488                        };
489                    }
490                    if let EnrichSlot::Ready(model) = &mut *guard {
491                        for (i, r) in regions.iter().enumerate() {
492                            if !wants(r.label) {
493                                continue;
494                            }
495                            // docling crops the postprocessed cluster box — the
496                            // union of the region's text cells, not the raw
497                            // detector box — expanded by 18% per side, at
498                            // ~120 dpi.
499                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
500                                .unwrap_or([r.l, r.t, r.r, r.b]);
501                            let (w, h) = (br - bl, bb - bt);
502                            let ex = enrich::CODE_FORMULA_EXPANSION;
503                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
504                            let Some(crop) = assemble::crop_region_scaled(
505                                page,
506                                bbox,
507                                enrich::CODE_FORMULA_SCALE,
508                            ) else {
509                                continue;
510                            };
511                            let kind = if r.label == "code" {
512                                enrich::CodeFormulaKind::Code
513                            } else {
514                                enrich::CodeFormulaKind::Formula
515                            };
516                            match model.predict(&crop, kind) {
517                                Ok(text) => {
518                                    enrich_out[i] = Some(match kind {
519                                        enrich::CodeFormulaKind::Code => {
520                                            let (code, language) =
521                                                enrich::extract_code_language(&text);
522                                            assemble::Enrichment::Code {
523                                                language,
524                                                text: code,
525                                            }
526                                        }
527                                        enrich::CodeFormulaKind::Formula => {
528                                            assemble::Enrichment::Formula { latex: text }
529                                        }
530                                    });
531                                }
532                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
533                            }
534                        }
535                    }
536                });
537            }
538        }
539        Ok(timing::timed("assemble_page", || {
540            assemble::assemble_page(page, regions, &table_rows, &enrich_out)
541        }))
542    }
543}
544
545#[cfg(feature = "ml")]
546/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
547/// so on a typical machine two threads per worker (sharing one in-cache copy of
548/// the weights) extracts more throughput than one fat model or many single-thread
549/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
550fn pdf_intra() -> usize {
551    if let Some(n) = std::env::var("DOCLING_RS_PDF_INTRA")
552        .ok()
553        .and_then(|v| v.parse::<usize>().ok())
554        .filter(|&n| n > 0)
555    {
556        return n;
557    }
558    if intra_threads() >= 2 {
559        2
560    } else {
561        1
562    }
563}
564
565#[cfg(feature = "ml")]
566/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
567/// overrides; otherwise size the pool so `workers × intra ≈ cores`, capped at 4 so
568/// a worst-case pool holds a bounded amount of model memory (~0.4 GB per worker)
569/// and does not oversaturate the memory bus with model-weight traffic.
570fn pdf_worker_count() -> usize {
571    if let Some(n) = std::env::var("DOCLING_RS_PDF_WORKERS")
572        .ok()
573        .and_then(|v| v.parse::<usize>().ok())
574        .filter(|&n| n > 0)
575    {
576        return n;
577    }
578    (intra_threads() / pdf_intra()).clamp(1, 4)
579}
580
581#[cfg(feature = "ml")]
582/// Max pages a worker layout-detects with one batched inference call (issue
583/// #73). Workers drain the work channel opportunistically up to this size —
584/// whatever is already rendered gets batched, so batching never *waits* for
585/// pages and adds no latency when rendering is the bottleneck.
586///
587/// Default: 4 on 8+ cores, 1 (per-page) below. Measured on a 4-core box the
588/// batch only adds cache pressure and costs pipeline overlap (2 workers × 2
589/// threads: 8.1 s/conv at batch=1 vs 9.3 s at batch=4 on the 9-page
590/// 2206.01062 fixture); the single-session amortization it buys needs the
591/// wider thread budget of a many-core machine. Output is bit-identical at
592/// every batch size, so this is purely a throughput knob.
593/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides; `1` restores per-page inference.
594fn pdf_layout_batch() -> usize {
595    std::env::var("DOCLING_RS_PDF_LAYOUT_BATCH")
596        .ok()
597        .and_then(|v| v.parse::<usize>().ok())
598        .filter(|&n| n > 0)
599        .unwrap_or_else(|| if intra_threads() >= 8 { 4 } else { 1 })
600}
601
602#[cfg(feature = "ml")]
603/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
604/// the serial primary (running its model on every core) is faster than fanning out
605/// — the helper pool's one-time model-load cost only pays off once enough pages
606/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
607fn pdf_parallel_min() -> usize {
608    std::env::var("DOCLING_RS_PDF_PARALLEL_MIN")
609        .ok()
610        .and_then(|v| v.parse::<usize>().ok())
611        .filter(|&n| n > 0)
612        .unwrap_or(6)
613}
614
615#[cfg(feature = "ml")]
616/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
617/// so a single-page / small / image / METS input is converted at full intra-op
618/// speed with no pool to load. A document with enough pages instead fans out
619/// across a **pool** of narrower workers processed concurrently. Both load lazily
620/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
621pub struct Pipeline {
622    /// Full-intra worker for the serial path; loaded on first serial use.
623    primary: Option<Worker>,
624    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
625    /// path; loaded on first multi-page use and cached.
626    pool: Vec<Worker>,
627    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
628    tables: SharedTables,
629    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
630    classifier: SharedClassifier,
631    code_formula: SharedCodeFormula,
632    /// Desired pool size for multi-page documents.
633    target_workers: usize,
634    /// Page count at/above which the parallel pool is worth its load cost.
635    parallel_min: usize,
636    /// Skip loading/running TableFormer; table regions fall back to geometric
637    /// reconstruction. See [`Pipeline::no_table_former`].
638    no_table_former: bool,
639    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
640    no_ocr: bool,
641    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
642    enrich: EnrichmentOptions,
643}
644
645#[cfg(feature = "ml")]
646impl Pipeline {
647    /// Construct the pipeline. Models load lazily on first use (full-intra primary
648    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
649    /// loaded that a given document doesn't need.
650    pub fn new() -> Result<Self, PdfError> {
651        Ok(Self {
652            primary: None,
653            pool: Vec::new(),
654            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
655            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
656            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
657            target_workers: pdf_worker_count(),
658            parallel_min: pdf_parallel_min(),
659            no_table_former: false,
660            no_ocr: false,
661            enrich: EnrichmentOptions::default(),
662        })
663    }
664
665    /// Enable the opt-in enrichment passes (docling's
666    /// `do_picture_classification` / `do_code_enrichment` /
667    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
668    /// the first matching region; a missing model warns once and is skipped.
669    /// Set before the first conversion (no effect on already-loaded workers).
670    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
671        self.enrich = opts;
672        self
673    }
674
675    /// Skip loading and running the TableFormer table-structure model. Table
676    /// regions still get emitted, but reconstructed geometrically from cell
677    /// positions instead of via the ONNX model's predicted structure — faster
678    /// (no model load, no per-table inference) at the cost of table fidelity.
679    /// No effect if a worker is already loaded; set this before the first
680    /// conversion.
681    pub fn no_table_former(mut self, disable: bool) -> Self {
682        self.no_table_former = disable;
683        self
684    }
685
686    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
687    /// inference of any kind. The PDF's embedded text cells are grouped by line
688    /// and emitted as plain paragraphs in reading order: no headings, lists,
689    /// tables, code blocks, or pictures, since that structure comes from the
690    /// layout model. The fastest possible PDF path, but pages with no embedded
691    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
692    /// without this flag. Implies `no_table_former`. No effect if a worker is
693    /// already loaded; set this before the first conversion.
694    pub fn no_ocr(mut self, disable: bool) -> Self {
695        self.no_ocr = disable;
696        self
697    }
698
699    /// The shared TableFormer slot handed to each worker, or `None` when the
700    /// pipeline options skip TableFormer entirely.
701    fn tables_slot(&self) -> Option<SharedTables> {
702        if self.no_table_former || self.no_ocr {
703            None
704        } else {
705            Some(Arc::clone(&self.tables))
706        }
707    }
708
709    /// The shared enrichment slots for a worker (`None` per model unless its
710    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
711    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
712        if self.no_ocr || !self.enrich.any() {
713            return (None, None);
714        }
715        (
716            self.enrich
717                .picture_classification
718                .then(|| Arc::clone(&self.classifier)),
719            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
720        )
721    }
722
723    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
724    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
725    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
726    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
727    /// `DocumentConverter.initialize_pipeline`.
728    pub fn warm_up(&mut self) -> Result<(), PdfError> {
729        self.primary()?;
730        Ok(())
731    }
732
733    /// The full-intra serial worker, loaded on first use.
734    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
735        if self.primary.is_none() {
736            self.primary = Some(Worker::load(
737                intra_threads(),
738                self.tables_slot(),
739                self.enrich_slots(),
740                self.enrich,
741                self.no_ocr,
742            )?);
743        }
744        Ok(self.primary.as_mut().unwrap())
745    }
746
747    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
748    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
749    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
750    /// fans the pages out across the worker pool, reassembled in page order so the
751    /// output is byte-identical to the serial path.
752    pub fn convert(
753        &mut self,
754        bytes: &[u8],
755        password: Option<&str>,
756        name: &str,
757    ) -> Result<DoclingDocument, PdfError> {
758        let pages = pdfium_backend::page_count(bytes, password)?;
759        let doc = if self.target_workers >= 2 && pages >= self.parallel_min {
760            self.convert_parallel(bytes, password, name)?
761        } else {
762            self.convert_serial(bytes, password, name)?
763        };
764        timing::report();
765        Ok(doc)
766    }
767
768    /// Stream pages one at a time through the primary worker — render → process →
769    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
770    fn convert_serial(
771        &mut self,
772        bytes: &[u8],
773        password: Option<&str>,
774        name: &str,
775    ) -> Result<DoclingDocument, PdfError> {
776        let mut doc = DoclingDocument::new(name);
777        let render_image = !self.no_ocr;
778        let worker = self.primary()?;
779        pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
780            let (nodes, links) = worker.process(n, &mut page)?;
781            doc.nodes.extend(nodes);
782            doc.links.extend(links);
783            Ok::<(), PdfError>(())
784        })?;
785        assemble::merge_continuations(&mut doc.nodes);
786        Ok(doc)
787    }
788
789    /// Render pages serially on this thread (pdfium) and process them in parallel
790    /// across the worker pool. A bounded channel applies backpressure so only a
791    /// handful of page bitmaps are resident at once; results carry their page
792    /// index and are reassembled in order, so the output is byte-identical to the
793    /// serial path.
794    fn convert_parallel(
795        &mut self,
796        bytes: &[u8],
797        password: Option<&str>,
798        name: &str,
799    ) -> Result<DoclingDocument, PdfError> {
800        self.ensure_pool()?;
801        let n_workers = self.pool.len();
802        let render_image = !self.no_ocr;
803        let layout_batch = pdf_layout_batch();
804        // Bound sized so every worker can accumulate a full layout batch while
805        // rendering stays ahead (and never below the pre-#73 render-ahead of
806        // two pages per worker); still a hard cap on resident page bitmaps.
807        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
808        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
809        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
810        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
811
812        // Move the pool into the scope so each worker gets an exclusive `&mut`.
813        let mut workers = std::mem::take(&mut self.pool);
814        std::thread::scope(|s| {
815            for worker in workers.iter_mut() {
816                let work_rx = Arc::clone(&work_rx);
817                let results = Arc::clone(&results);
818                let first_err = Arc::clone(&first_err);
819                s.spawn(move || loop {
820                    // Hold the receiver lock only for the recv (plus a non-blocking
821                    // drain up to the layout batch size); release before the (long)
822                    // per-page work so other workers can pull concurrently.
823                    let mut batch = Vec::new();
824                    {
825                        let rx = work_rx.lock().unwrap();
826                        match rx.recv() {
827                            Ok(item) => {
828                                batch.push(item);
829                                while batch.len() < layout_batch {
830                                    match rx.try_recv() {
831                                        Ok(item) => batch.push(item),
832                                        Err(_) => break,
833                                    }
834                                }
835                            }
836                            Err(_) => break,
837                        }
838                    }
839                    let outs = worker.process_batch(&mut batch);
840                    for ((idx, _), out) in batch.iter().zip(outs) {
841                        match out {
842                            Ok(out) => results.lock().unwrap().push((*idx, out)),
843                            Err(e) => {
844                                let mut slot = first_err.lock().unwrap();
845                                if slot.is_none() {
846                                    *slot = Some(e);
847                                }
848                            }
849                        }
850                    }
851                });
852            }
853            // Render on this thread and feed the workers; backpressure blocks here
854            // when the channel is full. Dropping `work_tx` afterwards signals the
855            // workers (recv → Err) to finish.
856            let render =
857                pdfium_backend::for_each_page(bytes, password, render_image, |i, _total, page| {
858                    work_tx
859                        .send((i, page))
860                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
861                });
862            drop(work_tx);
863            if let Err(e) = render {
864                let mut slot = first_err.lock().unwrap();
865                if slot.is_none() {
866                    *slot = Some(e);
867                }
868            }
869        });
870        // Threads have joined; restore the pool for the next conversion.
871        self.pool = workers;
872
873        if let Some(e) = first_err.lock().unwrap().take() {
874            return Err(e);
875        }
876        let mut results = Arc::try_unwrap(results)
877            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
878            .into_inner()
879            .unwrap();
880        results.sort_by_key(|(idx, _)| *idx);
881        let mut doc = DoclingDocument::new(name);
882        for (_, (nodes, links)) in results {
883            doc.nodes.extend(nodes);
884            doc.links.extend(links);
885        }
886        assemble::merge_continuations(&mut doc.nodes);
887        Ok(doc)
888    }
889
890    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
891    /// in-document-order batch of nodes (and that span's recovered links) as pages
892    /// complete, so a caller can serialize Markdown page by page instead of waiting
893    /// for the whole document. The batches are exactly the buffered [`convert`]'s
894    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
895    /// parallel path reorders pages back into document order before emitting, so
896    /// the output is identical regardless of worker scheduling.
897    ///
898    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
899    /// and its backpressure throttles the whole pipeline. Returning `Err` from
900    /// `emit` aborts the conversion with that error.
901    pub fn convert_streaming<F>(
902        &mut self,
903        bytes: &[u8],
904        password: Option<&str>,
905        name: &str,
906        emit: F,
907    ) -> Result<(), PdfError>
908    where
909        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
910    {
911        let _ = name; // page nodes carry no name; the caller owns the document name.
912        let pages = pdfium_backend::page_count(bytes, password)?;
913        let r = if self.target_workers >= 2 && pages >= self.parallel_min {
914            self.convert_streaming_parallel(bytes, password, emit)
915        } else {
916            self.convert_streaming_serial(bytes, password, emit)
917        };
918        timing::report();
919        r
920    }
921
922    /// Serial streaming: render → process → emit, one page at a time, holding back
923    /// only the tail that might still merge into the next page.
924    fn convert_streaming_serial<F>(
925        &mut self,
926        bytes: &[u8],
927        password: Option<&str>,
928        mut emit: F,
929    ) -> Result<(), PdfError>
930    where
931        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
932    {
933        let mut asm = assemble::StreamAssembler::new();
934        let render_image = !self.no_ocr;
935        let worker = self.primary()?;
936        pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
937            let (nodes, links) = worker.process(n, &mut page)?;
938            emit(asm.push(nodes), links)
939        })?;
940        emit(asm.finish(), Vec::new())
941    }
942
943    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
944    /// not thread-safe) and process across the worker pool; results carry their
945    /// page index and are reordered on the calling thread into a
946    /// [`assemble::StreamAssembler`], which emits each page in document order as
947    /// soon as its predecessors have arrived. Bounded channels keep only a handful
948    /// of pages resident and let `emit`'s backpressure reach the renderer.
949    fn convert_streaming_parallel<F>(
950        &mut self,
951        bytes: &[u8],
952        password: Option<&str>,
953        mut emit: F,
954    ) -> Result<(), PdfError>
955    where
956        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
957    {
958        self.ensure_pool()?;
959        let n_workers = self.pool.len();
960        let render_image = !self.no_ocr;
961        let layout_batch = pdf_layout_batch();
962        // Bound sized so every worker can accumulate a full layout batch while
963        // rendering stays ahead (and never below the pre-#73 render-ahead of
964        // two pages per worker); still a hard cap on resident page bitmaps.
965        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
966        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
967        // Workers and the renderer report here; the calling thread drains it in
968        // page order. Bounded so workers block (bounding resident bitmaps) when the
969        // consumer falls behind.
970        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
971
972        let mut workers = std::mem::take(&mut self.pool);
973        let mut asm = assemble::StreamAssembler::new();
974        let mut first_err: Option<PdfError> = None;
975
976        std::thread::scope(|s| {
977            // Workers: pull a batch of pages (whatever is already rendered, up
978            // to the layout batch size), process it, report (index-tagged)
979            // results.
980            for worker in workers.iter_mut() {
981                let work_rx = Arc::clone(&work_rx);
982                let res_tx = res_tx.clone();
983                s.spawn(move || 'outer: loop {
984                    let mut batch = Vec::new();
985                    {
986                        let rx = work_rx.lock().unwrap();
987                        match rx.recv() {
988                            Ok(item) => {
989                                batch.push(item);
990                                while batch.len() < layout_batch {
991                                    match rx.try_recv() {
992                                        Ok(item) => batch.push(item),
993                                        Err(_) => break,
994                                    }
995                                }
996                            }
997                            Err(_) => break,
998                        }
999                    }
1000                    let outs = worker.process_batch(&mut batch);
1001                    for ((idx, _), out) in batch.iter().zip(outs) {
1002                        if res_tx.send(out.map(|o| (*idx, o))).is_err() {
1003                            break 'outer; // consumer gone
1004                        }
1005                    }
1006                });
1007            }
1008            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
1009            // single thread); report a render error through the same channel.
1010            {
1011                let res_tx = res_tx.clone();
1012                s.spawn(move || {
1013                    let render = pdfium_backend::for_each_page(
1014                        bytes,
1015                        password,
1016                        render_image,
1017                        |i, _total, page| {
1018                            work_tx
1019                                .send((i, page))
1020                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
1021                        },
1022                    );
1023                    drop(work_tx); // signal workers to finish
1024                    if let Err(e) = render {
1025                        let _ = res_tx.send(Err(e));
1026                    }
1027                });
1028            }
1029            // Drop our own sender so the channel closes once the threads finish.
1030            drop(res_tx);
1031
1032            // Collector (this thread): reorder into document order and emit.
1033            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
1034            let mut next = 0usize;
1035            for msg in res_rx.iter() {
1036                match msg {
1037                    Err(e) => {
1038                        if first_err.is_none() {
1039                            first_err = Some(e);
1040                        }
1041                    }
1042                    Ok((idx, out)) => {
1043                        buffer.insert(idx, out);
1044                        if first_err.is_some() {
1045                            continue; // keep draining so the threads can exit
1046                        }
1047                        while let Some((nodes, links)) = buffer.remove(&next) {
1048                            if let Err(e) = emit(asm.push(nodes), links) {
1049                                first_err = Some(e);
1050                                break;
1051                            }
1052                            next += 1;
1053                        }
1054                    }
1055                }
1056            }
1057        });
1058        // Threads have joined; restore the pool for the next conversion.
1059        self.pool = workers;
1060
1061        if let Some(e) = first_err {
1062            return Err(e);
1063        }
1064        emit(asm.finish(), Vec::new())
1065    }
1066
1067    /// Lazily grow the pool to `target_workers`, loading the new workers
1068    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
1069    /// one load's wall-time). Cached for reuse across documents.
1070    fn ensure_pool(&mut self) -> Result<(), PdfError> {
1071        let need = self.target_workers.saturating_sub(self.pool.len());
1072        if need == 0 {
1073            return Ok(());
1074        }
1075        let intra = pdf_intra();
1076        let no_ocr = self.no_ocr;
1077        let enrich = self.enrich;
1078        let tables = self.tables_slot();
1079        let enrich_slots = self.enrich_slots();
1080        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
1081            let handles: Vec<_> = (0..need)
1082                .map(|_| {
1083                    let tables = tables.clone();
1084                    let enrich_slots = enrich_slots.clone();
1085                    s.spawn(move || Worker::load(intra, tables, enrich_slots, enrich, no_ocr))
1086                })
1087                .collect();
1088            handles.into_iter().map(|h| h.join().unwrap()).collect()
1089        });
1090        for w in loaded {
1091            self.pool.push(w?);
1092        }
1093        Ok(())
1094    }
1095
1096    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
1097    /// docling routes images through the same layout+OCR pipeline as a PDF page.
1098    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1099        let image = image::load_from_memory(bytes)
1100            .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?
1101            .into_rgb8();
1102        let (w, h) = image.dimensions();
1103        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
1104        // standalone image has no text layer, so OCR supplies the cells.
1105        let page = PdfPage {
1106            width: w as f32,
1107            height: h as f32,
1108            scale: 1.0,
1109            cells: Vec::new(),
1110            code_cells: Vec::new(),
1111            word_cells: Vec::new(),
1112            image,
1113            links: Vec::new(),
1114        };
1115        self.process_pages(vec![page], name)
1116    }
1117
1118    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
1119    /// page (image / METS inputs, which are small and already materialised).
1120    fn process_pages(
1121        &mut self,
1122        mut pages: Vec<PdfPage>,
1123        name: &str,
1124    ) -> Result<DoclingDocument, PdfError> {
1125        let mut doc = DoclingDocument::new(name);
1126        let worker = self.primary()?;
1127        for (n, page) in pages.iter_mut().enumerate() {
1128            let (nodes, links) = worker.process(n, page)?;
1129            doc.nodes.extend(nodes);
1130            doc.links.extend(links);
1131        }
1132        assemble::merge_continuations(&mut doc.nodes);
1133        Ok(doc)
1134    }
1135}
1136
1137#[cfg(feature = "ml")]
1138/// Convenience one-shot conversion (loads the pipeline per call). Errors are
1139/// detailed and surfaced (never silently skipped).
1140pub fn convert(
1141    bytes: &[u8],
1142    password: Option<&str>,
1143    name: &str,
1144) -> Result<DoclingDocument, PdfError> {
1145    convert_with_options(
1146        bytes,
1147        password,
1148        name,
1149        false,
1150        false,
1151        EnrichmentOptions::default(),
1152    )
1153}
1154
1155#[cfg(feature = "ml")]
1156/// Like [`convert`], but optionally skips loading/running TableFormer (see
1157/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1158/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
1159/// [`Pipeline::enrichments`]).
1160pub fn convert_with_options(
1161    bytes: &[u8],
1162    password: Option<&str>,
1163    name: &str,
1164    no_table_former: bool,
1165    no_ocr: bool,
1166    enrich: EnrichmentOptions,
1167) -> Result<DoclingDocument, PdfError> {
1168    Pipeline::new()?
1169        .no_table_former(no_table_former)
1170        .no_ocr(no_ocr)
1171        .enrichments(enrich)
1172        .convert(bytes, password, name)
1173}
1174
1175#[cfg(feature = "ml")]
1176/// Convenience one-shot image conversion (loads the pipeline per call).
1177pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1178    convert_image_with_options(bytes, name, false, false, EnrichmentOptions::default())
1179}
1180
1181#[cfg(feature = "ml")]
1182/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
1183/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1184/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
1185pub fn convert_image_with_options(
1186    bytes: &[u8],
1187    name: &str,
1188    no_table_former: bool,
1189    no_ocr: bool,
1190    enrich: EnrichmentOptions,
1191) -> Result<DoclingDocument, PdfError> {
1192    Pipeline::new()?
1193        .no_table_former(no_table_former)
1194        .no_ocr(no_ocr)
1195        .enrichments(enrich)
1196        .convert_image(bytes, name)
1197}
1198
1199#[cfg(feature = "ml")]
1200/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
1201/// scans) through the shared layout + assembly pipeline.
1202pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
1203    convert_pages_with_options(pages, name, false, false, EnrichmentOptions::default())
1204}
1205
1206#[cfg(feature = "ml")]
1207/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
1208/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1209/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
1210pub fn convert_pages_with_options(
1211    pages: Vec<PdfPage>,
1212    name: &str,
1213    no_table_former: bool,
1214    no_ocr: bool,
1215    enrich: EnrichmentOptions,
1216) -> Result<DoclingDocument, PdfError> {
1217    Pipeline::new()?
1218        .no_table_former(no_table_former)
1219        .no_ocr(no_ocr)
1220        .enrichments(enrich)
1221        .process_pages(pages, name)
1222}
1223
1224#[cfg(feature = "ml")]
1225#[cfg(test)]
1226mod send_check {
1227    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
1228    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
1229    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
1230    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
1231    fn assert_send<T: Send>() {}
1232
1233    #[test]
1234    fn pipeline_is_send() {
1235        assert_send::<super::Pipeline>();
1236    }
1237}