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