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