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