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, convert_mets_gbs_with_pipeline};
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: OcrSlot,
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 /// Never run OCR, but keep layout + TableFormer (#244) — docling's
549 /// `do_ocr=False`. See [`Pipeline::skip_ocr`].
550 skip_ocr: bool,
551 /// Which recognition model [`Self::ocr`] loads. See [`Pipeline::ocr_lang`].
552 ocr_lang: ocr::OcrLang,
553}
554
555#[cfg(feature = "ml")]
556/// The worker's lazily-loaded OCR recognition model. `Missing` records a
557/// failed load (#244: degradation over failure — a deployment without the OCR
558/// model still gets layout + TableFormer, and OCR-dependent regions stay
559/// empty) so the load isn't retried per page.
560enum OcrSlot {
561 Unloaded,
562 Ready(ocr::OcrModel),
563 Missing,
564}
565
566#[cfg(feature = "ml")]
567impl Worker {
568 #[allow(clippy::too_many_arguments)] // mirrors the Pipeline's option set
569 fn load(
570 intra: usize,
571 tables: Option<SharedTables>,
572 enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
573 enrich: EnrichmentOptions,
574 no_ocr: bool,
575 skip_ocr: bool,
576 force_full_page_ocr: bool,
577 no_text_panels: bool,
578 ocr_lang: ocr::OcrLang,
579 ) -> Result<Self, PdfError> {
580 Ok(Self {
581 layout: if no_ocr {
582 None
583 } else {
584 Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
585 },
586 ocr: OcrSlot::Unloaded,
587 tables,
588 classifier: enrich_slots.0,
589 code_formula: enrich_slots.1,
590 enrich,
591 no_ocr,
592 skip_ocr,
593 force_full_page_ocr,
594 no_text_panels,
595 ocr_lang,
596 })
597 }
598
599 /// The OCR model, or `None` when this conversion must not (or cannot) OCR:
600 /// `skip_ocr` short-circuits, and a failed model load degrades to `None`
601 /// with a one-time warning instead of failing the conversion (#244) —
602 /// unless `force_full_page_ocr` demanded OCR explicitly, where a missing
603 /// model stays a hard error (the text layer was deliberately discarded, so
604 /// degrading would silently emit an empty document).
605 fn ocr_model(&mut self) -> Result<Option<&mut ocr::OcrModel>, PdfError> {
606 if self.skip_ocr {
607 return Ok(None);
608 }
609 if matches!(self.ocr, OcrSlot::Unloaded) {
610 match ocr::OcrModel::load(self.ocr_lang) {
611 Ok(model) => self.ocr = OcrSlot::Ready(model),
612 Err(e) if self.force_full_page_ocr => return Err(PdfError::Ocr(e)),
613 Err(e) => {
614 static WARNED: std::sync::Once = std::sync::Once::new();
615 WARNED.call_once(|| {
616 eprintln!(
617 "warning: OCR model unavailable ({e}); continuing without OCR — \
618 scanned pages and text inside images will come back empty \
619 (run scripts/install/download_dependencies.sh for the model)"
620 );
621 });
622 self.ocr = OcrSlot::Missing;
623 }
624 }
625 }
626 Ok(match &mut self.ocr {
627 OcrSlot::Ready(model) => Some(model),
628 _ => None,
629 })
630 }
631
632 /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
633 /// into its nodes and links. Pure given the page (mutates only the worker's
634 /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
635 fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
636 if self.no_ocr {
637 // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
638 // embedded text cells (if any) become flat, line-grouped paragraphs in
639 // reading order via the same orphan-region machinery that normally
640 // rescues text the detector missed — here it rescues *all* of it.
641 // Pages with no embedded text layer (scanned/image-only) yield nothing;
642 // convert those without `no_ocr`.
643 let parse = quality::parse_score(&page.cells);
644 let mut regions = Vec::new();
645 assemble::add_orphan_regions(&mut regions, &page.cells);
646 let table_rows = vec![None; regions.len()];
647 let enrich_out = vec![None; regions.len()];
648 let conf = quality::page_confidence(parse, ®ions, &[]);
649 let (nodes, links) = timing::timed("assemble_page", || {
650 assemble::assemble_page(page, regions, &table_rows, &enrich_out)
651 });
652 return Ok((nodes, links, conf));
653 }
654 self.normalize_orientation(n, page)?;
655 let regions = timing::timed("layout.predict", || {
656 self.layout
657 .as_mut()
658 .expect("layout model loaded unless no_ocr")
659 .predict(layout_src(page), page.width, page.height)
660 })
661 .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
662 self.finish_page(n, page, regions)
663 }
664
665 /// Content-based orientation normalization (#225), before any inference:
666 /// a physically rotated scan (sideways phone photo, landscape-fed sheet)
667 /// has `/Rotate 0`, so the metadata pass in `extract_page` never fires and
668 /// layout+OCR would read a sideways raster. Only pages with no text layer
669 /// at all are probed (a digital page's raster is upright by construction,
670 /// and its cells — not its pixels — carry the text); the detected angle
671 /// composes with any `/Rotate` normalization through the same
672 /// [`PdfPage::unrotate`] + display-space assembly mapping. Detection is
673 /// evidence-gated and degrades to a no-op — see [`orient`].
674 fn normalize_orientation(&mut self, n: usize, page: &mut PdfPage) -> Result<(), PdfError> {
675 let scanned =
676 page.cells.is_empty() && page.word_cells.is_empty() && page.code_cells.is_empty();
677 if self.no_ocr || self.skip_ocr || !scanned || page.image.width() <= 1 || !orient::enabled()
678 {
679 return Ok(());
680 }
681 // The probe reads text through the OCR model; without one (missing —
682 // #244 degradation) the page stays as rendered.
683 let Some(ocr) = self.ocr_model()? else {
684 return Ok(());
685 };
686 let deg = timing::timed("orient.detect", || orient::detect(&page.image, ocr));
687 if deg != 0 {
688 debug_log!(
689 "docling-pdf: page {}: content rotated {deg}° in the raster; \
690 un-rotating before layout/OCR",
691 n + 1
692 );
693 page.unrotate(deg);
694 }
695 Ok(())
696 }
697
698 /// Layout-detect a whole batch of pages with one inference call (issue #73),
699 /// then run each page's remaining stages (OCR / TableFormer / enrichment /
700 /// assembly) per page. Index-aligned with `items`; a layout failure fails
701 /// every page in the batch (they shared the one inference call).
702 fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<PageOut, PdfError>> {
703 if self.no_ocr {
704 // No layout model to batch — the text-layer-only path is per page.
705 return items
706 .iter_mut()
707 .map(|(n, page)| {
708 let n = *n;
709 self.process(n, page)
710 })
711 .collect();
712 }
713 // Orientation-normalize every scanned page before the shared layout
714 // call — the batched inference must see upright bitmaps too (#225).
715 for (n, page) in items.iter_mut() {
716 let n = *n;
717 if let Err(e) = self.normalize_orientation(n, page) {
718 // Model-load failure — every page in the batch needs the same
719 // model, so they all fail alike (mirrors the layout-error arm).
720 let msg = e.to_string();
721 return items
722 .iter()
723 .map(|_| Err(PdfError::Ocr(msg.clone())))
724 .collect();
725 }
726 }
727 let inputs: Vec<(layout::LayoutSrc<'_>, f32, f32)> = items
728 .iter()
729 .map(|(_, page)| (layout_src(page), page.width, page.height))
730 .collect();
731 let batched = timing::timed("layout.predict", || {
732 self.layout
733 .as_mut()
734 .expect("layout model loaded unless no_ocr")
735 .predict_batch(&inputs)
736 });
737 match batched {
738 Ok(all) => items
739 .iter_mut()
740 .zip(all)
741 .map(|((n, page), regions)| self.finish_page(*n, page, regions))
742 .collect(),
743 Err(e) => items
744 .iter()
745 .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
746 .collect(),
747 }
748 }
749
750 /// Everything after layout detection: per-label confidence thresholds,
751 /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
752 /// TableFormer, enrichment, and page assembly.
753 fn finish_page(
754 &mut self,
755 n: usize,
756 page: &mut PdfPage,
757 regions: Vec<layout::Region>,
758 ) -> Result<PageOut, PdfError> {
759 // Force-OCR is exactly "pretend the text layer is not there": clear
760 // every cell kind the extractors produced before anything reads them,
761 // and the ordinary no-text-layer machinery below — full-page OCR,
762 // OCR-fed TableFormer matching — takes over unchanged. (`no_ocr` wins
763 // when both are set, mirroring docling, where `force_full_page_ocr`
764 // is a sub-option of `do_ocr`; the no-ocr path never reaches here.)
765 // Done here rather than in `process` so the batched layout path
766 // (`process_batch` → `finish_page`) honors the flag too.
767 // Parse quality is scored on the extracted text layer before force-OCR
768 // discards it (docling's page-preprocessing stage runs before OCR too,
769 // so its parse_score also reflects the original text layer).
770 let parse = quality::parse_score(&page.cells);
771 // Recognition confidences of every OCR'd cell on this page → ocr_score.
772 let mut ocr_confs: Vec<f32> = Vec::new();
773 if self.force_full_page_ocr {
774 page.cells.clear();
775 page.code_cells.clear();
776 page.word_cells.clear();
777 }
778 // Quant-robustness guard: the default int8 layout graph keeps its
779 // confidences near the 0.5 label thresholds, and a different CPU's
780 // quantized kernels can flip a whole page's detections under them —
781 // tables and paragraphs then dissolve into orphan one-liners while the
782 // same build converts the page perfectly elsewhere. When a dense
783 // digital page ends up with detections covering almost none of its
784 // text cells, re-run that one page on the fp32 graph (lazy-loaded,
785 // auto-int8 selection only) and keep whichever detections cover more.
786 let mut regions = regions;
787 if !page.cells.is_empty() {
788 let thresholded = |rs: &[layout::Region]| -> Vec<layout::Region> {
789 rs.iter()
790 .filter(|r| r.score >= layout::label_threshold(r.label))
791 .cloned()
792 .collect()
793 };
794 let text_cells = page
795 .cells
796 .iter()
797 .filter(|c| !c.text.trim().is_empty())
798 .count();
799 let cov = assemble::layout_cell_coverage(&thresholded(®ions), &page.cells);
800 if text_cells >= 15 && cov < 0.5 {
801 let retry = self
802 .layout
803 .as_mut()
804 .expect("layout model loaded unless no_ocr")
805 .predict_fp32_fallback(layout_src(page), page.width, page.height)
806 .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
807 if let Some(retry) = retry {
808 let cov2 = assemble::layout_cell_coverage(&thresholded(&retry), &page.cells);
809 if cov2 > cov {
810 debug_log!(
811 "docling-pdf: page {}: int8 layout covered {:.0}% of the text \
812 cells; the fp32 retry covers {:.0}% — using it",
813 n + 1,
814 cov * 100.0,
815 cov2 * 100.0
816 );
817 regions = retry;
818 }
819 }
820 }
821 }
822 // docling's LayoutPostprocessor drops each detection below its label's
823 // confidence threshold (stricter than the 0.3 base the predictor keeps),
824 // before any overlap resolution. This removes the low-confidence tables /
825 // pictures / list-items that otherwise double-emit or mis-classify.
826 if env::flag("DOCLING_RS_DEBUG_REGIONS") {
827 for r in ®ions {
828 eprintln!(
829 "DBG raw {} {:.2} [{:.0},{:.0},{:.0},{:.0}]",
830 r.label, r.score, r.l, r.t, r.r, r.b
831 );
832 }
833 }
834 regions.retain(|r| r.score >= layout::label_threshold(r.label));
835 // docling's same-label picture dedup runs on the thresholded
836 // detections, before overlap resolution: a figure proposed both whole
837 // and as sub-panels collapses to one box (see `dedup_pictures`).
838 assemble::dedup_pictures(&mut regions);
839 // Resolve overlapping detections once, before OCR.
840 let mut regions = assemble::resolve(regions);
841 // Emit text the detector missed as orphan text regions (docling parity).
842 assemble::add_orphan_regions(&mut regions, &page.cells);
843 // Drop phantom empty low-confidence picture boxes (docling parity).
844 assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
845 // A regular region fully inside a surviving table/index/picture is that
846 // special's child (a cell / in-figure label), not a separate block —
847 // remove it so it isn't emitted twice (docling parity).
848 assemble::drop_contained_regulars(&mut regions);
849 // No text layer → recognise text from the page image via OCR.
850 let ocred = page.cells.is_empty();
851 if ocred {
852 // `None` = `skip_ocr` or a missing model (#244): the page keeps
853 // its layout regions (and TableFormer structure below) with no
854 // recognized text, instead of failing the conversion.
855 if let Some(ocr) = self.ocr_model()? {
856 let cells = timing::timed("ocr.page", || {
857 ocr.ocr_page(&page.image, ®ions, page.scale)
858 })
859 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
860 ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
861 page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
862 // Table interiors carry no words yet: region-scoped OCR skips
863 // table labels, and a scanned page has no pdfium text layer — so
864 // TableFormer's cell matcher got an empty word list and the table
865 // dissolved (#173). Recognize the table regions' word crops
866 // (mirroring the browser scanned path): `word_cells` feeds the
867 // matcher, and the same cells join `cells` so the geometric
868 // fallback and the table's region text see them too.
869 if regions.iter().any(|r| assemble::is_table_like(r.label)) {
870 let words = timing::timed("ocr.table_words", || {
871 ocr.ocr_table_words(&page.image, ®ions, page.scale)
872 })
873 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
874 ocr_confs.extend(words.iter().map(|(_, conf)| conf));
875 let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
876 page.cells.extend(words.iter().cloned());
877 page.word_cells = words;
878 }
879 }
880 }
881 // Region-scoped OCR skips `picture` interiors, and a digital page's
882 // text layer cannot see into an embedded raster either — so a figure
883 // that is really a text box (terms-and-conditions exported as an
884 // image) lost its words on every page kind. Python docling OCRs the
885 // bitmap-covered areas of *every* page — even digital ones — once they
886 // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
887 // already do. Recognize the big text-less crops here too; the panel
888 // demotion / orphan recovery below place the lines.
889 let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
890 {
891 let page_area = (page.width * page.height).max(1.0);
892 let has_text = |r: &layout::Region| {
893 page.cells.iter().any(|c| {
894 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
895 let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
896 let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
897 !c.text.trim().is_empty() && ix * iy / ca > 0.5
898 })
899 };
900 // A captioned picture can never demote to a text panel (see
901 // recover_text_panels), and on digital pages its speculative OCR
902 // would be discarded anyway — don't pay for it.
903 let captioned = |r: &layout::Region| {
904 regions.iter().any(|c| {
905 c.label == "caption"
906 && c.r.min(r.r) - c.l.max(r.l) > 0.0
907 && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
908 })
909 };
910 let bare: Vec<layout::Region> = regions
911 .iter()
912 .filter(|r| {
913 r.label == "picture"
914 && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
915 && !has_text(r)
916 && (ocred || !captioned(r))
917 })
918 .map(|r| layout::Region {
919 label: "text",
920 ..r.clone()
921 })
922 .collect();
923 // Speculative OCR (#244): with `skip_ocr` or no model, big bare
924 // pictures simply stay pictures.
925 if let (false, Some(ocr)) = (bare.is_empty(), self.ocr_model()?) {
926 let scored = timing::timed("ocr.pictures", || {
927 ocr.ocr_page(&page.image, &bare, page.scale)
928 })
929 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
930 // Speculative in-picture OCR counts toward ocr_score only on
931 // OCR'd pages, where the recognized lines actually join the
932 // output; on a digital page they may be discarded below.
933 if ocred {
934 ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
935 }
936 pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
937 page.cells.extend(pic_cells.iter().cloned());
938 }
939 }
940 let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
941 // A "picture" that is really a colored text panel — dense, wide,
942 // multi-line — reads out as paragraphs instead of shipping as pixels;
943 // sparse in-picture text (a chart's labels) keeps the crop and stays
944 // inside it as the picture's silent children (docling parity, #200).
945 // `no_text_panels` (#173) opts out entirely for image-extraction
946 // workflows.
947 if !self.no_text_panels {
948 assemble::recover_text_panels(&mut regions, &page.cells);
949 }
950 // On an OCR'd page, in-picture text that did NOT demote its picture
951 // mostly stays silent, exactly as in docling: its postprocess step
952 // "Remove regular clusters that are included in wrappers" walks
953 // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
954 // >80 % contained in a kept picture becomes that picture's child and
955 // never reaches the serializer. Only border-straddlers (≤80 %
956 // containment) survive as text. Emitting *everything* here used to
957 // splice a chart's OCR'd axis ticks into the body text right next to
958 // the image chunk (#200) — so the orphan pass places the recognized
959 // lines, then the same containment drop that handled the first wave
960 // re-runs to swallow the in-picture ones.
961 if ocred && !pic_cells.is_empty() {
962 // Pictures (and wrappers) no longer count as claimers (#165), so
963 // the plain orphan pass places the recognized lines directly.
964 assemble::add_orphan_regions(&mut regions, &pic_cells);
965 assemble::drop_contained_regulars(&mut regions);
966 } else if !ocred && !pic_cells.is_empty() {
967 // Digital page, picture kept: its speculative OCR cells must not
968 // linger in the text-cell set (they were appended at the tail).
969 let kept: Vec<layout::Region> = regions
970 .iter()
971 .filter(|r| r.label == "picture")
972 .cloned()
973 .collect();
974 let tail = page.cells.split_off(cells_before_pic_ocr);
975 page.cells.extend(tail.into_iter().filter(|c| {
976 !kept.iter().any(|r| {
977 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
978 let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
979 let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
980 ix * iy / ca > 0.5
981 })
982 }));
983 }
984 // A text-less *table* detected inside a picture on a digital page — a
985 // screenshot of a table (2203's Figure 10) — has no text layer and no
986 // scanned-path OCR to feed it, so its grid used to serialize empty and
987 // the whole element vanished. docling OCRs bitmap-covered areas on
988 // every page kind and its table cluster collects those cells; mirror
989 // the scanned path for exactly these tables: recognize word crops and
990 // feed them to the TableFormer matcher and the cell set.
991 if !ocred {
992 let has_text = |t: &layout::Region| {
993 page.cells.iter().any(|c| {
994 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
995 let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
996 let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
997 !c.text.trim().is_empty() && ix * iy / ca > 0.5
998 })
999 };
1000 let in_picture = |t: &layout::Region| {
1001 regions.iter().any(|r| {
1002 r.label == "picture" && {
1003 let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
1004 let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
1005 let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
1006 ix * iy / ta > 0.5
1007 }
1008 })
1009 };
1010 let pic_tables: Vec<layout::Region> = regions
1011 .iter()
1012 .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
1013 .cloned()
1014 .collect();
1015 // Same degradation as above: without OCR the in-picture table
1016 // keeps its structure (TableFormer is geometry-driven) minus text.
1017 if let (false, Some(ocr)) = (pic_tables.is_empty(), self.ocr_model()?) {
1018 let words = timing::timed("ocr.table_words", || {
1019 ocr.ocr_table_words(&page.image, &pic_tables, page.scale)
1020 })
1021 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1022 ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1023 let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1024 page.cells.extend(words.iter().cloned());
1025 page.word_cells.extend(words);
1026 }
1027 }
1028 // TableFormer structure per table region (else geometric fallback). The
1029 // shared slot is only locked (and lazily loaded) when the page actually
1030 // has a table, so table-free documents never pay for TableFormer at all.
1031 let mut table_rows: Vec<Option<tf_core::TableGrid>> = vec![None; regions.len()];
1032 if let Some(slot) = self.tables.as_ref() {
1033 if regions.iter().any(|r| assemble::is_table_like(r.label)) {
1034 timing::timed("tableformer", || {
1035 let mut guard = slot.lock().unwrap();
1036 if matches!(*guard, TfSlot::Unloaded) {
1037 // Full intra-op width: tables serialise on this mutex, so
1038 // the one instance gets the whole thread budget.
1039 *guard = match tableformer::TableFormer::load_with(intra_threads()) {
1040 Some(tf) => TfSlot::Ready(tf),
1041 None => TfSlot::Missing,
1042 };
1043 }
1044 if let TfSlot::Ready(tf) = &mut *guard {
1045 for (i, r) in regions.iter().enumerate() {
1046 if assemble::is_table_like(r.label) {
1047 table_rows[i] = tf.predict_table_rows(
1048 &page.image,
1049 [r.l, r.t, r.r, r.b],
1050 &page.word_cells,
1051 );
1052 }
1053 }
1054 }
1055 });
1056 }
1057 }
1058 if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1059 for (i, r) in regions.iter().enumerate() {
1060 eprintln!(
1061 "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
1062 r.label,
1063 r.score,
1064 r.l,
1065 r.t,
1066 r.r,
1067 r.b,
1068 table_rows[i]
1069 .as_ref()
1070 .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
1071 );
1072 }
1073 eprintln!(
1074 "DBG cells={} words={}",
1075 page.cells.len(),
1076 page.word_cells.len()
1077 );
1078 }
1079 // Enrichment passes (opt-in): DocumentPictureClassifier over picture
1080 // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
1081 // shape as TableFormer — one lazily-loaded instance per pipeline, only
1082 // ever locked when a page actually has a matching region.
1083 let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
1084 if let Some(slot) = self.classifier.as_ref() {
1085 if regions.iter().any(|r| r.label == "picture") {
1086 timing::timed("picture_classifier", || {
1087 let mut guard = slot.lock().unwrap();
1088 if matches!(*guard, EnrichSlot::Unloaded) {
1089 *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
1090 Some(m) => EnrichSlot::Ready(m),
1091 None => EnrichSlot::Missing,
1092 };
1093 }
1094 if let EnrichSlot::Ready(model) = &mut *guard {
1095 for (i, r) in regions.iter().enumerate() {
1096 if r.label != "picture" {
1097 continue;
1098 }
1099 let Some(crop) = assemble::crop_region_scaled(
1100 page,
1101 [r.l, r.t, r.r, r.b],
1102 enrich::CLASSIFIER_SCALE,
1103 ) else {
1104 continue;
1105 };
1106 match model.classify(&crop) {
1107 Ok(classes) => {
1108 enrich_out[i] =
1109 Some(assemble::Enrichment::PictureClasses(classes));
1110 }
1111 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1112 }
1113 }
1114 }
1115 });
1116 }
1117 }
1118 if let Some(slot) = self.code_formula.as_ref() {
1119 let wants = |label: &str| {
1120 (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
1121 };
1122 if regions.iter().any(|r| wants(r.label)) {
1123 timing::timed("code_formula", || {
1124 let mut guard = slot.lock().unwrap();
1125 if matches!(*guard, EnrichSlot::Unloaded) {
1126 *guard = match enrich::CodeFormula::load_with(intra_threads()) {
1127 Some(m) => EnrichSlot::Ready(m),
1128 None => EnrichSlot::Missing,
1129 };
1130 }
1131 if let EnrichSlot::Ready(model) = &mut *guard {
1132 for (i, r) in regions.iter().enumerate() {
1133 if !wants(r.label) {
1134 continue;
1135 }
1136 // docling crops the postprocessed cluster box — the
1137 // union of the region's text cells, not the raw
1138 // detector box — expanded by 18% per side, at
1139 // ~120 dpi.
1140 let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
1141 .unwrap_or([r.l, r.t, r.r, r.b]);
1142 let (w, h) = (br - bl, bb - bt);
1143 let ex = enrich::CODE_FORMULA_EXPANSION;
1144 let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
1145 let Some(crop) = assemble::crop_region_scaled(
1146 page,
1147 bbox,
1148 enrich::CODE_FORMULA_SCALE,
1149 ) else {
1150 continue;
1151 };
1152 let kind = if r.label == "code" {
1153 enrich::CodeFormulaKind::Code
1154 } else {
1155 enrich::CodeFormulaKind::Formula
1156 };
1157 match model.predict(&crop, kind) {
1158 Ok(text) => {
1159 enrich_out[i] = Some(match kind {
1160 enrich::CodeFormulaKind::Code => {
1161 let (code, language) =
1162 enrich::extract_code_language(&text);
1163 assemble::Enrichment::Code {
1164 language,
1165 text: code,
1166 }
1167 }
1168 enrich::CodeFormulaKind::Formula => {
1169 assemble::Enrichment::Formula { latex: text }
1170 }
1171 });
1172 }
1173 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1174 }
1175 }
1176 }
1177 });
1178 }
1179 }
1180 // Score the final region set (docling assigns layout_score over the
1181 // postprocessed clusters — the same set assemble_page consumes).
1182 let conf = quality::page_confidence(parse, ®ions, &ocr_confs);
1183 let (nodes, links) = timing::timed("assemble_page", || {
1184 assemble::assemble_page(page, regions, &table_rows, &enrich_out)
1185 });
1186 Ok((nodes, links, conf))
1187 }
1188}
1189
1190#[cfg(feature = "ml")]
1191/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
1192/// so on a typical machine two threads per worker (sharing one in-cache copy of
1193/// the weights) extracts more throughput than one fat model or many single-thread
1194/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
1195fn pdf_intra() -> usize {
1196 if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
1197 return n;
1198 }
1199 if intra_threads() >= 2 {
1200 2
1201 } else {
1202 1
1203 }
1204}
1205
1206#[cfg(feature = "ml")]
1207/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
1208/// overrides; otherwise size the pool so `workers × intra ≈ cores`, capped at 4 so
1209/// a worst-case pool holds a bounded amount of model memory (~0.4 GB per worker)
1210/// and does not oversaturate the memory bus with model-weight traffic.
1211fn pdf_worker_count() -> usize {
1212 if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
1213 return n;
1214 }
1215 (intra_threads() / pdf_intra()).clamp(1, 4)
1216}
1217
1218#[cfg(feature = "ml")]
1219/// Max pages a worker layout-detects with one batched inference call (issue
1220/// #73). Workers drain the work channel opportunistically up to this size —
1221/// whatever is already rendered gets batched, so batching never *waits* for
1222/// pages and adds no latency when rendering is the bottleneck.
1223///
1224/// Default: 4 on 8+ cores, 1 (per-page) below. Measured on a 4-core box the
1225/// batch only adds cache pressure and costs pipeline overlap (2 workers × 2
1226/// threads: 8.1 s/conv at batch=1 vs 9.3 s at batch=4 on the 9-page
1227/// 2206.01062 fixture); the single-session amortization it buys needs the
1228/// wider thread budget of a many-core machine. Output is bit-identical at
1229/// every batch size, so this is purely a throughput knob.
1230/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides; `1` restores per-page inference.
1231fn pdf_layout_batch() -> usize {
1232 env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
1233 .filter(|&n| n > 0)
1234 .unwrap_or_else(|| if intra_threads() >= 8 { 4 } else { 1 })
1235}
1236
1237#[cfg(feature = "ml")]
1238/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
1239/// the serial primary (running its model on every core) is faster than fanning out
1240/// — the helper pool's one-time model-load cost only pays off once enough pages
1241/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
1242fn pdf_parallel_min() -> usize {
1243 env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
1244 .filter(|&n| n > 0)
1245 .unwrap_or(6)
1246}
1247
1248#[cfg(feature = "ml")]
1249/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
1250/// so a single-page / small / image / METS input is converted at full intra-op
1251/// speed with no pool to load. A document with enough pages instead fans out
1252/// across a **pool** of narrower workers processed concurrently. Both load lazily
1253/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
1254pub struct Pipeline {
1255 /// Full-intra worker for the serial path; loaded on first serial use.
1256 primary: Option<Worker>,
1257 /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
1258 /// path; loaded on first multi-page use and cached.
1259 pool: Vec<Worker>,
1260 /// The single TableFormer instance every worker shares (see [`TfSlot`]).
1261 tables: SharedTables,
1262 /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
1263 classifier: SharedClassifier,
1264 code_formula: SharedCodeFormula,
1265 /// Desired pool size for multi-page documents.
1266 target_workers: usize,
1267 /// Page count at/above which the parallel pool is worth its load cost.
1268 parallel_min: usize,
1269 /// Skip loading/running TableFormer; table regions fall back to geometric
1270 /// reconstruction. See [`Pipeline::no_table_former`].
1271 no_table_former: bool,
1272 /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
1273 no_ocr: bool,
1274 /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
1275 skip_ocr: bool,
1276 /// OCR every page even when it carries a text layer. See
1277 /// [`Pipeline::force_full_page_ocr`].
1278 force_full_page_ocr: bool,
1279 /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
1280 no_text_panels: bool,
1281 /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
1282 enrich: EnrichmentOptions,
1283 /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
1284 page_range: Option<(usize, usize)>,
1285 /// OCR recognition language. See [`Pipeline::ocr_lang`].
1286 ocr_lang: ocr::OcrLang,
1287 /// Optional per-page progress hook `(done, selected_total)`, invoked after
1288 /// each page finishes on both the serial and parallel buffered paths. Set
1289 /// by the CLI batch mode for dot-progress; `None` costs nothing.
1290 progress: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>,
1291}
1292
1293#[cfg(feature = "ml")]
1294impl Pipeline {
1295 /// Construct the pipeline. Models load lazily on first use (full-intra primary
1296 /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
1297 /// loaded that a given document doesn't need.
1298 pub fn new() -> Result<Self, PdfError> {
1299 Ok(Self {
1300 primary: None,
1301 pool: Vec::new(),
1302 tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
1303 classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1304 code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1305 target_workers: pdf_worker_count(),
1306 parallel_min: pdf_parallel_min(),
1307 no_table_former: false,
1308 no_ocr: false,
1309 skip_ocr: false,
1310 force_full_page_ocr: false,
1311 no_text_panels: false,
1312 enrich: EnrichmentOptions::default(),
1313 page_range: None,
1314 ocr_lang: ocr::OcrLang::from_env(),
1315 progress: None,
1316 })
1317 }
1318
1319 /// Install (or clear) the per-page progress hook: called with
1320 /// `(pages_done, pages_selected)` after each page completes during
1321 /// [`convert`](Self::convert). Shared with the parallel workers, so the
1322 /// callback must be cheap and thread-safe.
1323 pub fn set_progress(&mut self, cb: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>) {
1324 self.progress = cb;
1325 }
1326
1327 /// Convert only pages `first..=last` (**1-based**, like the page numbers a
1328 /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
1329 /// skipped before rasterization, so the cost is proportional to the window,
1330 /// not the document. `last` past the end of the document clamps; a window
1331 /// that selects no pages at all (`first` beyond the last page) is an error
1332 /// at convert time. `None` (the default) converts everything.
1333 pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
1334 self.page_range = range;
1335 self
1336 }
1337
1338 /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
1339 /// (e.g. docling-serve's warm instance) that applies a per-request window
1340 /// without rebuilding — unlike the model switches, the window is pure
1341 /// configuration. Set it before every conversion; it stays until changed.
1342 pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
1343 self.page_range = range;
1344 }
1345
1346 /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
1347 /// for the multilingual docling-conformance model. `None` keeps the
1348 /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
1349 /// first conversion; for a warm pipeline use
1350 /// [`set_ocr_lang`](Self::set_ocr_lang).
1351 pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
1352 self.set_ocr_lang(lang);
1353 self
1354 }
1355
1356 /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
1357 /// pipeline (docling-serve's warm instance). Unlike the page window this
1358 /// is a *model* switch: any worker whose cached recognition model was
1359 /// loaded for a different language drops it, to be lazily reloaded on the
1360 /// next OCR-needing page (cheap — the rec models are ~10 MB).
1361 pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
1362 let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
1363 self.ocr_lang = lang;
1364 for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
1365 if worker.ocr_lang != lang {
1366 worker.ocr_lang = lang;
1367 worker.ocr = OcrSlot::Unloaded;
1368 }
1369 }
1370 }
1371
1372 /// Resolve the configured 1-based window against a page count into the
1373 /// 0-based inclusive form the backend walks, validating it selects at
1374 /// least one existing page.
1375 fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
1376 let Some((first, last)) = self.page_range else {
1377 return Ok(None);
1378 };
1379 if first == 0 || last < first {
1380 return Err(PdfError::Pdfium(format!(
1381 "invalid page range {first}-{last} (pages are 1-based, first <= last)"
1382 )));
1383 }
1384 if first > total {
1385 return Err(PdfError::Pdfium(format!(
1386 "page range {first}-{last} is outside the document ({total} page(s))"
1387 )));
1388 }
1389 Ok(Some((first - 1, last.min(total) - 1)))
1390 }
1391
1392 /// Enable the opt-in enrichment passes (docling's
1393 /// `do_picture_classification` / `do_code_enrichment` /
1394 /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
1395 /// the first matching region; a missing model warns once and is skipped.
1396 /// Set before the first conversion (no effect on already-loaded workers).
1397 pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
1398 self.enrich = opts;
1399 self
1400 }
1401
1402 /// Skip loading and running the TableFormer table-structure model. Table
1403 /// regions still get emitted, but reconstructed geometrically from cell
1404 /// positions instead of via the ONNX model's predicted structure — faster
1405 /// (no model load, no per-table inference) at the cost of table fidelity.
1406 /// No effect if a worker is already loaded; set this before the first
1407 /// conversion.
1408 pub fn no_table_former(mut self, disable: bool) -> Self {
1409 self.no_table_former = disable;
1410 self
1411 }
1412
1413 /// Keep every detected `picture` region as a picture. By default an
1414 /// *uncaptioned* picture that reads like a dense, uniform text panel (a
1415 /// terms-and-conditions box exported as an image) is demoted into
1416 /// paragraphs (#157); a chart the layout mislabels can still trip that
1417 /// heuristic on scanned pages, and image-extraction workflows may simply
1418 /// want every crop — this flag disables the demotion entirely (#173).
1419 /// No effect on already-loaded workers; set before the first conversion.
1420 pub fn no_text_panels(mut self, disable: bool) -> Self {
1421 self.no_text_panels = disable;
1422 self
1423 }
1424
1425 /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
1426 /// inference of any kind. The PDF's embedded text cells are grouped by line
1427 /// and emitted as plain paragraphs in reading order: no headings, lists,
1428 /// tables, code blocks, or pictures, since that structure comes from the
1429 /// layout model. The fastest possible PDF path, but pages with no embedded
1430 /// text layer (scanned/image-only PDFs) yield no text at all — convert those
1431 /// without this flag. Implies `no_table_former`. No effect if a worker is
1432 /// already loaded; set this before the first conversion.
1433 pub fn no_ocr(mut self, disable: bool) -> Self {
1434 self.no_ocr = disable;
1435 self
1436 }
1437
1438 /// Never run OCR, but keep layout detection and TableFormer — docling's
1439 /// independent `do_ocr=False` (#244), the counterpart of
1440 /// [`no_table_former`](Self::no_table_former). Unlike
1441 /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
1442 /// output — headings, tables, pictures, reading order — is preserved;
1443 /// only text that exists solely as pixels is lost: scanned pages come
1444 /// back with their regions empty, and the speculative OCR of large
1445 /// embedded images never runs. The OCR model is never loaded. Ignored
1446 /// when `no_ocr` is set (there is no OCR to skip);
1447 /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
1448 /// mirroring docling where forcing is a sub-option of `do_ocr`.
1449 pub fn skip_ocr(mut self, disable: bool) -> Self {
1450 self.skip_ocr = disable;
1451 self
1452 }
1453
1454 /// OCR every page from its rendered image even when the page carries an
1455 /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
1456 /// for text layers that exist but lie: broken encodings, subset fonts with
1457 /// garbage mappings, a scanned form with a few typed-in fields. Ignored
1458 /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
1459 /// `force_full_page_ocr` is a sub-option of `do_ocr`).
1460 pub fn force_full_page_ocr(mut self, force: bool) -> Self {
1461 self.force_full_page_ocr = force;
1462 self
1463 }
1464
1465 /// The shared TableFormer slot handed to each worker, or `None` when the
1466 /// pipeline options skip TableFormer entirely.
1467 fn tables_slot(&self) -> Option<SharedTables> {
1468 if self.no_table_former || self.no_ocr {
1469 None
1470 } else {
1471 Some(Arc::clone(&self.tables))
1472 }
1473 }
1474
1475 /// The shared enrichment slots for a worker (`None` per model unless its
1476 /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
1477 fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
1478 if self.no_ocr || !self.enrich.any() {
1479 return (None, None);
1480 }
1481 (
1482 self.enrich
1483 .picture_classification
1484 .then(|| Arc::clone(&self.classifier)),
1485 (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
1486 )
1487 }
1488
1489 /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
1490 /// the shared TableFormer unless disabled) so the first conversion doesn't pay
1491 /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
1492 /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
1493 /// `DocumentConverter.initialize_pipeline`.
1494 pub fn warm_up(&mut self) -> Result<(), PdfError> {
1495 self.primary()?;
1496 Ok(())
1497 }
1498
1499 /// The full-intra serial worker, loaded on first use.
1500 fn primary(&mut self) -> Result<&mut Worker, PdfError> {
1501 if self.primary.is_none() {
1502 self.primary = Some(Worker::load(
1503 intra_threads(),
1504 self.tables_slot(),
1505 self.enrich_slots(),
1506 self.enrich,
1507 self.no_ocr,
1508 self.skip_ocr,
1509 self.force_full_page_ocr,
1510 self.no_text_panels,
1511 self.ocr_lang,
1512 )?);
1513 }
1514 Ok(self.primary.as_mut().unwrap())
1515 }
1516
1517 /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
1518 /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
1519 /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
1520 /// fans the pages out across the worker pool, reassembled in page order so the
1521 /// output is byte-identical to the serial path.
1522 pub fn convert(
1523 &mut self,
1524 bytes: &[u8],
1525 password: Option<&str>,
1526 name: &str,
1527 ) -> Result<DoclingDocument, PdfError> {
1528 let pages = pdfium_backend::page_count(bytes, password)?;
1529 let range = self.resolve_range(pages)?;
1530 // Serial vs parallel is decided by the pages actually converted: a
1531 // 3-page window over a 500-page PDF should not pay the pool load.
1532 let selected = range.map_or(pages, |(a, b)| b - a + 1);
1533 let doc = if self.target_workers >= 2 && selected >= self.parallel_min {
1534 self.convert_parallel(bytes, password, name, range, selected)?
1535 } else {
1536 self.convert_serial(bytes, password, name, range, selected)?
1537 };
1538 timing::report();
1539 Ok(doc)
1540 }
1541
1542 /// Stream pages one at a time through the primary worker — render → process →
1543 /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
1544 fn convert_serial(
1545 &mut self,
1546 bytes: &[u8],
1547 password: Option<&str>,
1548 name: &str,
1549 range: Option<(usize, usize)>,
1550 selected: usize,
1551 ) -> Result<DoclingDocument, PdfError> {
1552 let mut doc = DoclingDocument::new(name);
1553 let mut confs = std::collections::BTreeMap::new();
1554 let render_image = !self.no_ocr;
1555 let progress = self.progress.clone();
1556 let mut done = 0usize;
1557 let worker = self.primary()?;
1558 pdfium_backend::for_each_page(
1559 bytes,
1560 password,
1561 render_image,
1562 range,
1563 |n, _total, mut page| {
1564 let (mut nodes, links, conf) = worker.process(n, &mut page)?;
1565 assemble::stamp_page_no(&mut nodes, n + 1);
1566 doc.nodes.extend(nodes);
1567 doc.links.extend(links);
1568 confs.insert(n + 1, conf);
1569 if let Some(cb) = &progress {
1570 done += 1;
1571 cb(done, selected);
1572 }
1573 Ok::<(), PdfError>(())
1574 },
1575 )?;
1576 assemble::merge_continuations(&mut doc.nodes);
1577 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
1578 Ok(doc)
1579 }
1580
1581 /// Render pages serially on this thread (pdfium) and process them in parallel
1582 /// across the worker pool. A bounded channel applies backpressure so only a
1583 /// handful of page bitmaps are resident at once; results carry their page
1584 /// index and are reassembled in order, so the output is byte-identical to the
1585 /// serial path.
1586 fn convert_parallel(
1587 &mut self,
1588 bytes: &[u8],
1589 password: Option<&str>,
1590 name: &str,
1591 range: Option<(usize, usize)>,
1592 selected: usize,
1593 ) -> Result<DoclingDocument, PdfError> {
1594 self.ensure_pool()?;
1595 let progress = self.progress.clone();
1596 let pages_done = std::sync::atomic::AtomicUsize::new(0);
1597 let n_workers = self.pool.len();
1598 let render_image = !self.no_ocr;
1599 let layout_batch = pdf_layout_batch();
1600 // Bound sized so every worker can accumulate a full layout batch while
1601 // rendering stays ahead (and never below the pre-#73 render-ahead of
1602 // two pages per worker); still a hard cap on resident page bitmaps.
1603 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
1604 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
1605 let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
1606 let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
1607
1608 // Move the pool into the scope so each worker gets an exclusive `&mut`.
1609 let mut workers = std::mem::take(&mut self.pool);
1610 std::thread::scope(|s| {
1611 for worker in workers.iter_mut() {
1612 let work_rx = Arc::clone(&work_rx);
1613 let results = Arc::clone(&results);
1614 let first_err = Arc::clone(&first_err);
1615 let progress = progress.clone();
1616 let pages_done = &pages_done;
1617 s.spawn(move || loop {
1618 // Hold the receiver lock only for the recv (plus a non-blocking
1619 // drain up to the layout batch size); release before the (long)
1620 // per-page work so other workers can pull concurrently.
1621 let mut batch = Vec::new();
1622 {
1623 let rx = work_rx.lock().unwrap();
1624 match rx.recv() {
1625 Ok(item) => {
1626 batch.push(item);
1627 while batch.len() < layout_batch {
1628 match rx.try_recv() {
1629 Ok(item) => batch.push(item),
1630 Err(_) => break,
1631 }
1632 }
1633 }
1634 Err(_) => break,
1635 }
1636 }
1637 let outs = worker.process_batch(&mut batch);
1638 for ((idx, _), out) in batch.iter().zip(outs) {
1639 match out {
1640 Ok(out) => {
1641 results.lock().unwrap().push((*idx, out));
1642 if let Some(cb) = &progress {
1643 let d = pages_done
1644 .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1645 + 1;
1646 cb(d, selected);
1647 }
1648 }
1649 Err(e) => {
1650 let mut slot = first_err.lock().unwrap();
1651 if slot.is_none() {
1652 *slot = Some(e);
1653 }
1654 }
1655 }
1656 }
1657 });
1658 }
1659 // Render on this thread and feed the workers; backpressure blocks here
1660 // when the channel is full. Dropping `work_tx` afterwards signals the
1661 // workers (recv → Err) to finish.
1662 let render = pdfium_backend::for_each_page(
1663 bytes,
1664 password,
1665 render_image,
1666 range,
1667 |i, _total, page| {
1668 work_tx
1669 .send((i, page))
1670 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
1671 },
1672 );
1673 drop(work_tx);
1674 if let Err(e) = render {
1675 let mut slot = first_err.lock().unwrap();
1676 if slot.is_none() {
1677 *slot = Some(e);
1678 }
1679 }
1680 });
1681 // Threads have joined; restore the pool for the next conversion.
1682 self.pool = workers;
1683
1684 if let Some(e) = first_err.lock().unwrap().take() {
1685 return Err(e);
1686 }
1687 let mut results = Arc::try_unwrap(results)
1688 .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
1689 .into_inner()
1690 .unwrap();
1691 results.sort_by_key(|(idx, _)| *idx);
1692 let mut doc = DoclingDocument::new(name);
1693 let mut confs = std::collections::BTreeMap::new();
1694 for (idx, (mut nodes, links, conf)) in results {
1695 assemble::stamp_page_no(&mut nodes, idx + 1);
1696 doc.nodes.extend(nodes);
1697 doc.links.extend(links);
1698 confs.insert(idx + 1, conf);
1699 }
1700 assemble::merge_continuations(&mut doc.nodes);
1701 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
1702 Ok(doc)
1703 }
1704
1705 /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
1706 /// in-document-order batch of nodes (and that span's recovered links) as pages
1707 /// complete, so a caller can serialize Markdown page by page instead of waiting
1708 /// for the whole document. The batches are exactly the buffered [`convert`]'s
1709 /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
1710 /// parallel path reorders pages back into document order before emitting, so
1711 /// the output is identical regardless of worker scheduling.
1712 ///
1713 /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
1714 /// and its backpressure throttles the whole pipeline. Returning `Err` from
1715 /// `emit` aborts the conversion with that error.
1716 pub fn convert_streaming<F>(
1717 &mut self,
1718 bytes: &[u8],
1719 password: Option<&str>,
1720 name: &str,
1721 emit: F,
1722 ) -> Result<(), PdfError>
1723 where
1724 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
1725 {
1726 let _ = name; // page nodes carry no name; the caller owns the document name.
1727 let pages = pdfium_backend::page_count(bytes, password)?;
1728 let range = self.resolve_range(pages)?;
1729 let selected = range.map_or(pages, |(a, b)| b - a + 1);
1730 let r = if self.target_workers >= 2 && selected >= self.parallel_min {
1731 self.convert_streaming_parallel(bytes, password, range, emit)
1732 } else {
1733 self.convert_streaming_serial(bytes, password, range, emit)
1734 };
1735 timing::report();
1736 r
1737 }
1738
1739 /// Serial streaming: render → process → emit, one page at a time, holding back
1740 /// only the tail that might still merge into the next page.
1741 fn convert_streaming_serial<F>(
1742 &mut self,
1743 bytes: &[u8],
1744 password: Option<&str>,
1745 range: Option<(usize, usize)>,
1746 mut emit: F,
1747 ) -> Result<(), PdfError>
1748 where
1749 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
1750 {
1751 let mut asm = assemble::StreamAssembler::new();
1752 let render_image = !self.no_ocr;
1753 let worker = self.primary()?;
1754 pdfium_backend::for_each_page(
1755 bytes,
1756 password,
1757 render_image,
1758 range,
1759 |n, _total, mut page| {
1760 // Confidence is dropped on the streaming path: the report is
1761 // only complete once every page has run, which defeats
1762 // page-by-page emission — buffered `convert` carries it.
1763 let (nodes, links, _conf) = worker.process(n, &mut page)?;
1764 emit(asm.push(nodes), links)
1765 },
1766 )?;
1767 emit(asm.finish(), Vec::new())
1768 }
1769
1770 /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
1771 /// not thread-safe) and process across the worker pool; results carry their
1772 /// page index and are reordered on the calling thread into a
1773 /// [`assemble::StreamAssembler`], which emits each page in document order as
1774 /// soon as its predecessors have arrived. Bounded channels keep only a handful
1775 /// of pages resident and let `emit`'s backpressure reach the renderer.
1776 fn convert_streaming_parallel<F>(
1777 &mut self,
1778 bytes: &[u8],
1779 password: Option<&str>,
1780 range: Option<(usize, usize)>,
1781 mut emit: F,
1782 ) -> Result<(), PdfError>
1783 where
1784 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
1785 {
1786 self.ensure_pool()?;
1787 let n_workers = self.pool.len();
1788 let render_image = !self.no_ocr;
1789 let layout_batch = pdf_layout_batch();
1790 // Bound sized so every worker can accumulate a full layout batch while
1791 // rendering stays ahead (and never below the pre-#73 render-ahead of
1792 // two pages per worker); still a hard cap on resident page bitmaps.
1793 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
1794 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
1795 // Workers and the renderer report here; the calling thread drains it in
1796 // page order. Bounded so workers block (bounding resident bitmaps) when the
1797 // consumer falls behind.
1798 let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
1799
1800 let mut workers = std::mem::take(&mut self.pool);
1801 let mut asm = assemble::StreamAssembler::new();
1802 let mut first_err: Option<PdfError> = None;
1803
1804 std::thread::scope(|s| {
1805 // Workers: pull a batch of pages (whatever is already rendered, up
1806 // to the layout batch size), process it, report (index-tagged)
1807 // results.
1808 for worker in workers.iter_mut() {
1809 let work_rx = Arc::clone(&work_rx);
1810 let res_tx = res_tx.clone();
1811 s.spawn(move || 'outer: loop {
1812 let mut batch = Vec::new();
1813 {
1814 let rx = work_rx.lock().unwrap();
1815 match rx.recv() {
1816 Ok(item) => {
1817 batch.push(item);
1818 while batch.len() < layout_batch {
1819 match rx.try_recv() {
1820 Ok(item) => batch.push(item),
1821 Err(_) => break,
1822 }
1823 }
1824 }
1825 Err(_) => break,
1826 }
1827 }
1828 let outs = worker.process_batch(&mut batch);
1829 for ((idx, _), out) in batch.iter().zip(outs) {
1830 if res_tx.send(out.map(|o| (*idx, o))).is_err() {
1831 break 'outer; // consumer gone
1832 }
1833 }
1834 });
1835 }
1836 // Renderer: feed pages to the pool on its own thread (pdfium stays on a
1837 // single thread); report a render error through the same channel.
1838 {
1839 let res_tx = res_tx.clone();
1840 s.spawn(move || {
1841 let render = pdfium_backend::for_each_page(
1842 bytes,
1843 password,
1844 render_image,
1845 range,
1846 |i, _total, page| {
1847 work_tx
1848 .send((i, page))
1849 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
1850 },
1851 );
1852 drop(work_tx); // signal workers to finish
1853 if let Err(e) = render {
1854 let _ = res_tx.send(Err(e));
1855 }
1856 });
1857 }
1858 // Drop our own sender so the channel closes once the threads finish.
1859 drop(res_tx);
1860
1861 // Collector (this thread): reorder into document order and emit.
1862 // With a page window, indices start at the window's first page.
1863 let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
1864 let mut next = range.map_or(0, |(first, _)| first);
1865 for msg in res_rx.iter() {
1866 match msg {
1867 Err(e) => {
1868 if first_err.is_none() {
1869 first_err = Some(e);
1870 }
1871 }
1872 Ok((idx, out)) => {
1873 buffer.insert(idx, out);
1874 if first_err.is_some() {
1875 continue; // keep draining so the threads can exit
1876 }
1877 while let Some((nodes, links, _conf)) = buffer.remove(&next) {
1878 if let Err(e) = emit(asm.push(nodes), links) {
1879 first_err = Some(e);
1880 break;
1881 }
1882 next += 1;
1883 }
1884 }
1885 }
1886 }
1887 });
1888 // Threads have joined; restore the pool for the next conversion.
1889 self.pool = workers;
1890
1891 if let Some(e) = first_err {
1892 return Err(e);
1893 }
1894 emit(asm.finish(), Vec::new())
1895 }
1896
1897 /// Lazily grow the pool to `target_workers`, loading the new workers
1898 /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
1899 /// one load's wall-time). Cached for reuse across documents.
1900 fn ensure_pool(&mut self) -> Result<(), PdfError> {
1901 let need = self.target_workers.saturating_sub(self.pool.len());
1902 if need == 0 {
1903 return Ok(());
1904 }
1905 let intra = pdf_intra();
1906 let no_ocr = self.no_ocr;
1907 let skip_ocr = self.skip_ocr;
1908 let force = self.force_full_page_ocr;
1909 let ntp = self.no_text_panels;
1910 let ocr_lang = self.ocr_lang;
1911 let enrich = self.enrich;
1912 let tables = self.tables_slot();
1913 let enrich_slots = self.enrich_slots();
1914 let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
1915 let handles: Vec<_> = (0..need)
1916 .map(|_| {
1917 let tables = tables.clone();
1918 let enrich_slots = enrich_slots.clone();
1919 s.spawn(move || {
1920 Worker::load(
1921 intra,
1922 tables,
1923 enrich_slots,
1924 enrich,
1925 no_ocr,
1926 skip_ocr,
1927 force,
1928 ntp,
1929 ocr_lang,
1930 )
1931 })
1932 })
1933 .collect();
1934 handles.into_iter().map(|h| h.join().unwrap()).collect()
1935 });
1936 for w in loaded {
1937 self.pool.push(w?);
1938 }
1939 Ok(())
1940 }
1941
1942 /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
1943 /// docling routes images through the same layout+OCR pipeline as a PDF page.
1944 pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1945 let image = decode_image_limited(bytes)?;
1946 let (w, h) = image.dimensions();
1947 // The image is its own page rendered at 1 px per "point" (scale 1.0); a
1948 // standalone image has no text layer, so OCR supplies the cells.
1949 let page = PdfPage {
1950 width: w as f32,
1951 height: h as f32,
1952 scale: 1.0,
1953 cells: Vec::new(),
1954 code_cells: Vec::new(),
1955 word_cells: Vec::new(),
1956 // A standalone image *is* its own scale-1.0 page image, so the
1957 // layout model sees it through the docling-exact PIL kernel.
1958 image_layout: Some(image.clone()),
1959 image,
1960 links: Vec::new(),
1961 rotation: 0,
1962 };
1963 self.process_pages(vec![page], name)
1964 }
1965
1966 /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
1967 /// page (image / METS inputs, which are small and already materialised).
1968 /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
1969 /// caller-configured pipeline (#244).
1970 pub fn process_pages(
1971 &mut self,
1972 mut pages: Vec<PdfPage>,
1973 name: &str,
1974 ) -> Result<DoclingDocument, PdfError> {
1975 let mut doc = DoclingDocument::new(name);
1976 let mut confs = std::collections::BTreeMap::new();
1977 let worker = self.primary()?;
1978 for (n, page) in pages.iter_mut().enumerate() {
1979 let (mut nodes, links, conf) = worker.process(n, page)?;
1980 assemble::stamp_page_no(&mut nodes, n + 1);
1981 doc.nodes.extend(nodes);
1982 doc.links.extend(links);
1983 confs.insert(n + 1, conf);
1984 }
1985 assemble::merge_continuations(&mut doc.nodes);
1986 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
1987 Ok(doc)
1988 }
1989}
1990
1991/// Number of pages in a PDF, without converting anything — what the CLI batch
1992/// mode prints in its per-document start line.
1993#[cfg(feature = "ml")]
1994pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
1995 Ok(pdfium_backend::page_count(bytes, password)?)
1996}
1997
1998#[cfg(feature = "ml")]
1999/// Convenience one-shot conversion (loads the pipeline per call). Errors are
2000/// detailed and surfaced (never silently skipped).
2001pub fn convert(
2002 bytes: &[u8],
2003 password: Option<&str>,
2004 name: &str,
2005) -> Result<DoclingDocument, PdfError> {
2006 convert_with_options(
2007 bytes,
2008 password,
2009 name,
2010 false,
2011 false,
2012 false,
2013 false,
2014 EnrichmentOptions::default(),
2015 None,
2016 None,
2017 )
2018}
2019
2020#[cfg(feature = "ml")]
2021/// Like [`convert`], but optionally skips loading/running TableFormer (see
2022/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2023/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
2024/// [`Pipeline::enrichments`]).
2025// One positional per pipeline switch mirrors the Pipeline builder; growing
2026// past clippy's arity cap is the price of keeping this one-shot signature
2027// stable-ish instead of churning callers into an options struct mid-series.
2028#[allow(clippy::too_many_arguments)]
2029pub fn convert_with_options(
2030 bytes: &[u8],
2031 password: Option<&str>,
2032 name: &str,
2033 no_table_former: bool,
2034 no_ocr: bool,
2035 force_full_page_ocr: bool,
2036 no_text_panels: bool,
2037 enrich: EnrichmentOptions,
2038 pages: Option<(usize, usize)>,
2039 ocr_lang: Option<OcrLang>,
2040) -> Result<DoclingDocument, PdfError> {
2041 Pipeline::new()?
2042 .no_table_former(no_table_former)
2043 .no_ocr(no_ocr)
2044 .force_full_page_ocr(force_full_page_ocr)
2045 .no_text_panels(no_text_panels)
2046 .enrichments(enrich)
2047 .pages(pages)
2048 .ocr_lang(ocr_lang)
2049 .convert(bytes, password, name)
2050}
2051
2052#[cfg(feature = "ml")]
2053/// Convenience one-shot image conversion (loads the pipeline per call).
2054pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2055 convert_image_with_options(
2056 bytes,
2057 name,
2058 false,
2059 false,
2060 false,
2061 EnrichmentOptions::default(),
2062 None,
2063 )
2064}
2065
2066#[cfg(feature = "ml")]
2067/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
2068/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2069/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2070pub fn convert_image_with_options(
2071 bytes: &[u8],
2072 name: &str,
2073 no_table_former: bool,
2074 no_ocr: bool,
2075 no_text_panels: bool,
2076 enrich: EnrichmentOptions,
2077 ocr_lang: Option<OcrLang>,
2078) -> Result<DoclingDocument, PdfError> {
2079 Pipeline::new()?
2080 .no_table_former(no_table_former)
2081 .no_ocr(no_ocr)
2082 .no_text_panels(no_text_panels)
2083 .enrichments(enrich)
2084 .ocr_lang(ocr_lang)
2085 .convert_image(bytes, name)
2086}
2087
2088#[cfg(feature = "ml")]
2089/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
2090/// scans) through the shared layout + assembly pipeline.
2091pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
2092 convert_pages_with_options(
2093 pages,
2094 name,
2095 false,
2096 false,
2097 false,
2098 EnrichmentOptions::default(),
2099 )
2100}
2101
2102#[cfg(feature = "ml")]
2103/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
2104/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2105/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2106pub fn convert_pages_with_options(
2107 pages: Vec<PdfPage>,
2108 name: &str,
2109 no_table_former: bool,
2110 no_ocr: bool,
2111 no_text_panels: bool,
2112 enrich: EnrichmentOptions,
2113) -> Result<DoclingDocument, PdfError> {
2114 Pipeline::new()?
2115 .no_table_former(no_table_former)
2116 .no_text_panels(no_text_panels)
2117 .no_ocr(no_ocr)
2118 .enrichments(enrich)
2119 .process_pages(pages, name)
2120}
2121
2122#[cfg(feature = "ml")]
2123#[cfg(all(test, feature = "ml"))]
2124mod image_limit_tests {
2125 use super::decode_image_with_max_side;
2126
2127 /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
2128 /// byte literal).
2129 fn png_bytes(w: u32, h: u32) -> Vec<u8> {
2130 use std::io::Cursor;
2131 let img = image::RgbImage::new(w, h);
2132 let mut out = Vec::new();
2133 img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
2134 .unwrap();
2135 out
2136 }
2137
2138 #[test]
2139 fn normal_image_decodes_under_the_cap() {
2140 let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
2141 assert_eq!(img.dimensions(), (8, 8));
2142 }
2143
2144 #[test]
2145 fn dimensions_over_the_cap_are_rejected_not_aborted() {
2146 // A per-side cap below the image's declared size must yield a
2147 // recoverable Err, never an allocation-abort — the mechanism that stops
2148 // a crafted image declaring 60000×60000 from OOM-killing the process.
2149 let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
2150 assert!(
2151 r.is_err(),
2152 "decode must fail under the pixel cap, not abort"
2153 );
2154 }
2155}
2156
2157#[cfg(test)]
2158mod median_tests {
2159 #[test]
2160 fn median_of_empty_is_zero_not_a_panic() {
2161 // A crafted table can leave a row/column with zero matched cells; the
2162 // even-count branch would index values[0 - 1] and panic (→ remote crash
2163 // via docling-serve) without the empty guard.
2164 assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
2165 assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
2166 assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
2167 }
2168}
2169
2170#[cfg(test)]
2171mod send_check {
2172 /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
2173 /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
2174 /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
2175 /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
2176 fn assert_send<T: Send>() {}
2177
2178 #[test]
2179 fn pipeline_is_send() {
2180 assert_send::<super::Pipeline>();
2181 }
2182}