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