Skip to main content

docling_pdf/
lib.rs

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