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;
23// Vector checkbox squares from the text parser's path walk (#609).
24pub mod checkbox;
25mod dp_lines;
26#[cfg(feature = "ml")]
27pub mod enrich;
28// Public so sibling crates (e.g. docling-rag's ONNX embedder) can route their
29// own `ort` sessions through the same `DOCLING_RS_EP` selection. Kept as a
30// re-export after the logic moved to the shared `docling-onnx` crate —
31// `docling_pdf::ep::…` remains the stable path downstream crates code against.
32#[cfg(feature = "ml")]
33pub use docling_onnx as ep;
34// Heading-hierarchy stage (#302): PDF font-name style parsing, outline
35// extraction (pure lopdf), and the level-assignment pass. No feature gate on
36// the logic itself — only the glyph style pass needs pdfium (`ml`).
37#[cfg(feature = "ml")]
38pub mod dparse_render;
39mod font_style;
40mod heading_hierarchy;
41pub mod layout;
42#[cfg(feature = "ml")]
43mod mets;
44#[cfg(feature = "ner")]
45pub mod ner;
46#[cfg(feature = "ml")]
47mod ocr;
48#[cfg(any(feature = "ml", feature = "ocr-prep"))]
49pub mod ocr_det;
50#[cfg(feature = "ocr-prep")]
51pub mod ocr_prep;
52#[cfg(feature = "ml")]
53mod orient;
54pub mod outline;
55pub mod pdfium_backend;
56#[cfg(feature = "ml")]
57pub mod picture;
58#[cfg(feature = "ml")]
59pub mod quality;
60mod reading_order;
61#[cfg(feature = "ml")]
62mod redact_ocr;
63// Pure-Rust region resampling (page→1024px box-average, crop→448 bilinear) —
64// available to the browser TableFormer path (#157 stage 3), not just `ml`.
65#[cfg(feature = "ocr-prep")]
66pub mod resample;
67#[cfg(feature = "ocr-prep")]
68pub mod scanned;
69// Built-in standard-14 font metrics for the pure-Rust text parser (#187) —
70// no feature gate: the wasm/pdf-text path needs them like the native one.
71pub mod pdf_meta;
72#[cfg(feature = "ml")]
73pub mod raster;
74#[cfg(feature = "ml")]
75pub mod render;
76mod std14;
77#[cfg(feature = "ml")]
78pub mod tableformer;
79#[cfg(feature = "ml")]
80mod tesseract;
81pub mod textparse;
82#[cfg(feature = "ocr-prep")]
83pub mod tf_core;
84// docling's TableFormer cell matcher — pure Rust, shared with the browser
85// TableFormer path (#157 stage 3).
86#[cfg(feature = "ocr-prep")]
87pub mod tf_match;
88pub mod timing;
89
90#[cfg(feature = "ml")]
91use std::collections::BTreeMap;
92use std::fmt;
93#[cfg(feature = "ml")]
94use std::sync::mpsc::{sync_channel, Receiver};
95#[cfg(feature = "ml")]
96use std::sync::{Arc, Mutex};
97
98// An execution provider only exists on its OS, and ort's prebuilt ONNX
99// Runtime binaries follow suit — requesting an impossible pairing otherwise
100// surfaces as a cryptic ort-sys linker error ("no builds available that
101// satisfy the requested feature set"). Catch it at type-check time with an
102// actionable message instead.
103#[cfg(all(feature = "coreml", not(target_vendor = "apple")))]
104compile_error!(
105 "the `coreml` execution provider exists only on Apple targets (macOS/iOS). \
106 On Linux use `--features cuda` or `--features tensorrt` (NVIDIA), on \
107 Windows also `--features directml`, or build without EP features for CPU."
108);
109#[cfg(all(feature = "directml", not(target_os = "windows")))]
110compile_error!(
111 "the `directml` execution provider exists only on Windows. On Linux use \
112 `--features cuda` or `--features tensorrt` (NVIDIA), on macOS \
113 `--features coreml`, or build without EP features for CPU."
114);
115#[cfg(all(any(feature = "cuda", feature = "tensorrt"), target_vendor = "apple"))]
116compile_error!(
117 "the `cuda`/`tensorrt` execution providers have no Apple builds (no NVIDIA \
118 support on macOS). Use `--features coreml` there, or build without EP \
119 features for CPU."
120);
121
122use docling_core::DoclingDocument;
123pub use docling_core::EncryptionError;
124// The env-knob helpers only gate ML-pipeline diagnostics and tuning; the
125// pure text-layer (wasm) build has no call sites.
126#[cfg(feature = "ml")]
127use docling_core::Node;
128#[cfg(feature = "ml")]
129use docling_core::{debug_log, env};
130
131pub use heading_hierarchy::HeadingHierarchyOptions;
132#[cfg(feature = "ml")]
133pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options, convert_mets_gbs_with_pipeline};
134#[cfg(feature = "ml")]
135pub use ocr::{OcrEngine, OcrLang, OcrMode};
136#[cfg(feature = "ml")]
137pub use pdfium_backend::PdfDocument;
138pub use pdfium_backend::{PdfPage, TextCell};
139#[cfg(feature = "ml")]
140pub use tesseract::{lang_arg as tesseract_lang_arg, TesseractOptions};
141// Plain page rasterization (#243) — pdfium only, no models.
142#[cfg(feature = "ml")]
143pub use pdfium_backend::{render_pages, RenderedPage};
144
145/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
146#[derive(Debug)]
147pub enum PdfError {
148 /// pdfium failed to bind, open, or read the document (and, historically,
149 /// any pipeline error outside the models).
150 Pdfium(String),
151 /// The document itself: an object model lopdf cannot read, a page no
152 /// renderer can draw, a page range outside it.
153 Document(String),
154 /// The layout ONNX model failed to load or run.
155 Layout(String),
156 /// The OCR ONNX model failed to load or run.
157 Ocr(String),
158 /// The document budget ([`Pipeline::document_timeout`]) ran out between
159 /// two pages. Internally the sentinel that stops the page walk; a caller
160 /// never sees it from [`Pipeline::convert`] — the conversion returns the
161 /// pages it finished and reports the cut through [`Completion`].
162 Timeout(String),
163 /// The document is encrypted and the password given (or none) does not
164 /// open it (#636) — the typed value a caller prompts for a password on,
165 /// reachable through [`std::error::Error::source`] too. Its text is the
166 /// one docling raises.
167 Encrypted(EncryptionError),
168}
169
170impl fmt::Display for PdfError {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 match self {
173 PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
174 PdfError::Document(m) => write!(f, "pdf: {m}"),
175 PdfError::Layout(m) => write!(f, "pdf: {m}"),
176 PdfError::Ocr(m) => write!(f, "pdf: {m}"),
177 PdfError::Timeout(m) => write!(f, "pdf: {m}"),
178 PdfError::Encrypted(EncryptionError::WrongPassword) => {
179 f.write_str("pdf: the PDF is encrypted and the password is wrong")
180 }
181 PdfError::Encrypted(EncryptionError::NeedPassword) => {
182 f.write_str("pdf: the PDF is encrypted: a password is required")
183 }
184 PdfError::Encrypted(e) => write!(f, "pdf: the PDF is encrypted: {e}"),
185 }
186 }
187}
188
189/// How a conversion ended: every selected page, or the pages that fit the
190/// document budget (docling's `document_timeout`, `PARTIAL_SUCCESS`).
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub enum Completion {
193 /// Every selected page was processed.
194 Complete,
195 /// The budget ran out: `pages_done` of `pages_selected` pages are in the
196 /// document, the rest were never rendered (or never processed).
197 TimedOut {
198 pages_done: usize,
199 pages_selected: usize,
200 budget: std::time::Duration,
201 },
202}
203
204impl Completion {
205 pub fn timed_out(&self) -> bool {
206 matches!(self, Completion::TimedOut { .. })
207 }
208
209 /// docling's `ErrorItem.error_message` for the cut, `None` when complete.
210 pub fn message(&self) -> Option<String> {
211 match self {
212 Completion::Complete => None,
213 Completion::TimedOut {
214 pages_done,
215 pages_selected,
216 budget,
217 } => Some(format!(
218 "document timeout of {:.3}s exceeded after {pages_done} of {pages_selected} \
219 pages; the output holds the pages processed",
220 budget.as_secs_f64()
221 )),
222 }
223 }
224}
225
226/// A converted document and how its conversion ended ([`Completion`]).
227#[derive(Debug, Clone)]
228pub struct Converted {
229 pub document: DoclingDocument,
230 pub completion: Completion,
231}
232
233/// Has the document budget run out?
234fn expired(deadline: Option<std::time::Instant>) -> bool {
235 deadline.is_some_and(|d| std::time::Instant::now() >= d)
236}
237
238/// The sentinel the page walks stop on once the budget is gone.
239fn timeout_sentinel() -> PdfError {
240 PdfError::Timeout("document timeout exceeded".into())
241}
242
243impl std::error::Error for PdfError {
244 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
245 match self {
246 PdfError::Encrypted(e) => Some(e),
247 _ => None,
248 }
249 }
250}
251
252#[cfg(feature = "pdfium")]
253impl From<pdfium_render::prelude::PdfiumError> for PdfError {
254 fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
255 // A failed dlopen means the library this build was asked to use
256 // (`pdfium` feature) is not there. Say what to do instead of leaking
257 // the raw loader error.
258 if matches!(e, pdfium_render::prelude::PdfiumError::LoadLibraryError(_)) {
259 // The loader error pretty-prints over several lines; compact it.
260 let detail = e
261 .to_string()
262 .split_whitespace()
263 .collect::<Vec<_>>()
264 .join(" ");
265 return PdfError::Pdfium(format!(
266 "the pdfium library is not installed. This build's `pdfium` feature \
267 was asked for it (DOCLING_RS_RENDERER=pdfium, or a file the pure-Rust \
268 object model cannot read): point PDFIUM_DYNAMIC_LIB_PATH at a directory \
269 containing the pdfium library, or unset DOCLING_RS_RENDERER — the \
270 default renderer needs no library. Declarative formats (DOCX, HTML, \
271 Markdown, …) never need it. [{detail}]"
272 ));
273 }
274 PdfError::Pdfium(e.to_string())
275 }
276}
277
278/// Convert a PDF's **embedded text layer only** — no ONNX, no
279/// threads: the pure-Rust content-stream parser ([`textparse`]) feeds the same
280/// orphan-region assembly the `no_ocr` pipeline flag uses, so text-layer PDFs
281/// come out identical to `--text-layer-only` (flat, line-grouped paragraphs in reading
282/// order; no headings/lists/tables/pictures, and no hyperlink recovery).
283///
284/// This is the only conversion entry compiled without the `ml` feature (it is
285/// what a wasm32 build runs). A scanned/image-only PDF (no embedded text
286/// layer) yields an empty document rather than an error, same as `no_ocr` —
287/// callers can detect that and fall back to an OCR-capable build.
288pub fn convert_text_layer(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
289 convert_text_layer_pages(bytes, name, None)
290}
291
292/// The error for bytes no reader here can parse as a PDF — not a PDF at
293/// all, or one damaged past the parser's repairs. Said about the file, not
294/// about a missing renderer or text layer: no library would read it either.
295pub(crate) const UNREADABLE: &str =
296 "not a readable PDF: the file is damaged or not a PDF (its structure could not be parsed)";
297
298/// [`convert_text_layer`] restricted to a **1-based inclusive** page window
299/// (issue #80's `--pages`); `None` converts everything. The window is
300/// validated the same way as [`Pipeline::pages`]: `first <= last`, 1-based,
301/// and it must select at least one existing page.
302pub fn convert_text_layer_pages(
303 bytes: &[u8],
304 name: &str,
305 pages: Option<(usize, usize)>,
306) -> Result<DoclingDocument, PdfError> {
307 if let Some((first, last)) = pages {
308 if first == 0 || last < first {
309 return Err(PdfError::Pdfium(format!(
310 "invalid page range {first}-{last} (pages are 1-based, first <= last)"
311 )));
312 }
313 }
314 let mut doc = DoclingDocument::new(name);
315 // A file nothing can open is an error, not a PDF that merely has no
316 // text layer (the caller's "scanned? needs OCR" hint).
317 let Some(mut parser) = textparse::PageTextParser::open(bytes) else {
318 return Err(PdfError::Document(UNREADABLE.into()));
319 };
320 // Pages are parsed, assembled and dropped one at a time: holding every
321 // page's cells until the end made the peak scale with the whole file —
322 // and a page window still paid for every page outside it.
323 let total = parser.page_count();
324 let mut tally = textparse::TextLayerTally::default();
325 for i in 0..total {
326 let selected = pages.is_none_or(|(first, last)| (first..=last).contains(&(i + 1)));
327 // A page outside the window only feeds the vestigial verdict below,
328 // so it is parsed only until that verdict is settled (on any real
329 // text layer, by the first page or two).
330 if !selected && tally.proves_text(total) {
331 continue;
332 }
333 let page = parser.text_page(i);
334 tally.add(&page);
335 if !selected {
336 continue;
337 }
338 let mut regions = Vec::new();
339 assemble::add_orphan_regions(&mut regions, &page.cells);
340 let table_rows = vec![None; regions.len()];
341 let enrich_out = vec![None; regions.len()];
342 let (mut nodes, links) =
343 assemble::assemble_page(&page, regions, &table_rows, &enrich_out, None);
344 assemble::stamp_page_no(&mut nodes, i + 1);
345 doc.nodes.extend(nodes);
346 doc.links.extend(links);
347 }
348 // A vestigial layer (a few typed-in form fields over scanned pages) is not
349 // the document's text: return the empty document, which callers already
350 // report as "no text layer" — so an OCR-capable caller falls back to OCR
351 // instead of proudly extracting thirteen characters.
352 if tally.is_vestigial() {
353 return Ok(DoclingDocument::new(name));
354 }
355 if let Some((first, last)) = pages {
356 if first > total {
357 return Err(PdfError::Pdfium(format!(
358 "page range {first}-{last} is outside the document ({total} page(s))"
359 )));
360 }
361 }
362 assemble::merge_continuations(&mut doc.nodes);
363 // Grown a page at a time, the node vector can be up to half spare
364 // capacity — hundreds of MB on a long document, held for its lifetime.
365 doc.nodes.shrink_to_fit();
366 Ok(doc)
367}
368
369/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
370/// Defaults to the available parallelism (ort otherwise picks a low number).
371#[cfg(feature = "ml")]
372pub(crate) fn intra_threads() -> usize {
373 if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_THREADS").filter(|&n| n > 0) {
374 return n;
375 }
376 env::cpu_budget()
377}
378
379#[cfg(feature = "ml")]
380/// TableFormer's intra-op width (#262): `DOCLING_RS_TF_INTRA` explicitly,
381/// else the shared [`intra_threads`] budget. The shared TF session used to
382/// take the raw host width on top of the already-sized worker pools —
383/// under a cgroup CPU limit that oversubscription showed up as constant
384/// throttling and ~66% higher peak memory (each intra thread carries its own
385/// arena slab); the reporter's 4-CPU/8-core case dropped from 2.2 GB to
386/// 1.3 GB peak by capping this pool.
387pub(crate) fn tf_intra() -> usize {
388 if let Some(n) = env::parse::<usize>("DOCLING_RS_TF_INTRA").filter(|&n| n > 0) {
389 return n;
390 }
391 intra_threads()
392}
393
394#[cfg(feature = "ml")]
395/// True when `DOCLING_RS_FP32` forces the full-precision models even where
396/// an INT8 variant sits next to the fp32 default.
397pub(crate) fn fp32_forced() -> bool {
398 env::flag("DOCLING_RS_FP32")
399}
400
401#[cfg(feature = "ml")]
402/// Should the int8 model defaults be skipped in favor of fp32? Either the
403/// user said so (`DOCLING_RS_FP32`), or a GPU execution provider is selected
404/// (#74) — the int8 exports are QDQ graphs calibrated for CPU kernels and
405/// only conformance-validated there. An explicit `DOCLING_*_ONNX` path
406/// override still wins over this at every call site.
407pub(crate) fn prefer_fp32() -> bool {
408 fp32_forced() || docling_onnx::prefers_fp32()
409}
410
411#[cfg(feature = "ml")]
412/// Resolve a default (CWD-relative) asset path — the shared chain in
413/// [`docling_core::assets`]: CWD, then next to the executable and one level
414/// above it (the `scripts/install/install.sh` layout).
415pub(crate) fn resolve_asset(rel: &str) -> String {
416 docling_core::assets::resolve(rel)
417}
418
419/// One resolved runtime asset — which file a stage would load right now,
420/// given the CWD, the env overrides and the int8/fp32 preference.
421#[cfg(feature = "ml")]
422#[derive(Debug, Clone)]
423pub struct ModelEntry {
424 /// Pipeline stage, e.g. `layout`, `tableformer.decoder`, `ocr.rec`.
425 pub stage: &'static str,
426 /// The resolved path (absolute or CWD-relative, as it will be opened).
427 pub path: String,
428 /// Whether the file exists right now.
429 pub found: bool,
430 /// File size in bytes (0 when missing) — enough to tell an int8 quant
431 /// from an fp32 graph, or a stale model from a re-published one, at a
432 /// glance without hashing gigabytes per request.
433 pub bytes: u64,
434}
435
436/// Resolve the whole runtime model set **without loading anything** — the
437/// exact selection each stage performs at load time (layout honors the
438/// int8/fp32 preference, TableFormer its decoder ranking, OCR the language
439/// pair), plus the pdfium library. docling-serve exposes this at
440/// `/v1/config` and logs it at startup, so "the server picked up different
441/// models" is one `curl` away instead of a mystery of dissolved tables.
442/// Resolution is CWD-relative with an exe-dir fallback, so the answer can
443/// legitimately differ between two working directories.
444#[cfg(feature = "ml")]
445pub fn model_inventory() -> Vec<ModelEntry> {
446 fn entry(stage: &'static str, path: String) -> ModelEntry {
447 let meta = std::fs::metadata(&path).ok();
448 ModelEntry {
449 stage,
450 found: meta.is_some(),
451 bytes: meta.map(|m| m.len()).unwrap_or(0),
452 path,
453 }
454 }
455 let (enc, dec, bbx) = tableformer::resolved_paths();
456 let (rec, dict) = ocr::resolve_rec_pair(ocr::OcrLang::from_env());
457 let pdfium =
458 env::nonempty("PDFIUM_DYNAMIC_LIB_PATH").unwrap_or_else(|| resolve_asset(".pdfium/lib"));
459 vec![
460 entry(
461 "layout",
462 model_path(
463 "DOCLING_LAYOUT_ONNX",
464 ".models/layout_heron.onnx",
465 ".models/layout_heron_int8.onnx",
466 ),
467 ),
468 entry("tableformer.encoder", enc),
469 entry("tableformer.decoder", dec),
470 entry("tableformer.bbox", bbx),
471 entry("ocr.rec", rec),
472 entry("ocr.dict", dict),
473 entry("pdfium", pdfium),
474 ]
475}
476
477/// Resolve a model path: an explicit env override always wins; otherwise the
478/// INT8 variant of the default path when it exists on disk (the quantized
479/// models are conformance-validated — see docs/PDF_CONFORMANCE.md — and load/run
480/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
481/// precision; else the fp32 default.
482#[cfg(feature = "ml")]
483pub(crate) fn model_path(key: &str, fp32_default: &str, int8_default: &str) -> String {
484 if let Some(p) = env::nonempty(key) {
485 return p;
486 }
487 if !prefer_fp32() {
488 let p = resolve_asset(int8_default);
489 if std::path::Path::new(&p).exists() {
490 return p;
491 }
492 }
493 resolve_asset(fp32_default)
494}
495
496/// Decode a standalone image with hard resource limits. A crafted image can
497/// declare enormous dimensions in a few-KB file; `image::load_from_memory`
498/// then tries to allocate the full pixel buffer (e.g. 60000×60000 → ~10 GB),
499/// and allocation failure aborts the whole process, bypassing the per-request
500/// panic catch. The 256 MiB alloc / 30000-px caps below turn that into a
501/// recoverable decode error instead. `DOCLING_RS_MAX_IMAGE_PIXELS` overrides
502/// the per-side pixel cap for the rare legitimately-huge scan.
503///
504/// Gated on `ml`: the only callers (`convert_image`, the METS backend) are
505/// ML-only, and the `image` crate is an `ml`-feature dependency — the
506/// text-layer wasm build has neither.
507#[cfg(feature = "ml")]
508pub(crate) fn decode_image_limited(bytes: &[u8]) -> Result<image::RgbImage, PdfError> {
509 let max_side: u32 = env::parse("DOCLING_RS_MAX_IMAGE_PIXELS").unwrap_or(30_000);
510 decode_image_with_max_side(bytes, max_side)
511}
512
513/// Whether `bytes` is an ISOBMFF HEIF/HEIC container (the `ftyp` brands
514/// iPhones write). Checked by content, not extension — HEIC regularly
515/// arrives misnamed `.jpg`.
516#[cfg(feature = "ml")]
517fn is_heif(bytes: &[u8]) -> bool {
518 bytes.len() >= 12
519 && &bytes[4..8] == b"ftyp"
520 && matches!(
521 &bytes[8..12],
522 b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"hevs" | b"mif1" | b"msf1"
523 )
524}
525
526/// Decode a HEIF/HEIC primary image via libheif (#211). Behind the opt-in
527/// `heif` feature — libheif is a native dependency the default build (and
528/// wasm) must not carry.
529#[cfg(all(feature = "ml", feature = "heif"))]
530fn decode_heif(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
531 use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
532 let err = |e: String| PdfError::Pdfium(format!("heif: {e}"));
533 let ctx = HeifContext::read_from_bytes(bytes).map_err(|e| err(e.to_string()))?;
534 let handle = ctx.primary_image_handle().map_err(|e| err(e.to_string()))?;
535 if handle.width() > max_side || handle.height() > max_side {
536 return Err(err(format!(
537 "image dimensions {}x{} exceed the {max_side}px per-side cap \
538 (DOCLING_RS_MAX_IMAGE_PIXELS overrides)",
539 handle.width(),
540 handle.height()
541 )));
542 }
543 let lib = LibHeif::new();
544 let img = lib
545 .decode(&handle, ColorSpace::Rgb(RgbChroma::Rgb), None)
546 .map_err(|e| err(e.to_string()))?;
547 let (w, h) = (img.width(), img.height());
548 let planes = img.planes();
549 let plane = planes
550 .interleaved
551 .ok_or_else(|| err("no RGB plane".into()))?;
552 let stride = plane.stride;
553 let mut out = image::RgbImage::new(w, h);
554 for (y, row) in out.rows_mut().enumerate() {
555 let src = &plane.data[y * stride..y * stride + w as usize * 3];
556 for (x, px) in row.enumerate() {
557 px.0 = [src[x * 3], src[x * 3 + 1], src[x * 3 + 2]];
558 }
559 }
560 Ok(out)
561}
562
563#[cfg(feature = "ml")]
564fn decode_image_with_max_side(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
565 use image::{ImageDecoder, ImageReader};
566 use std::io::Cursor;
567
568 if is_heif(bytes) {
569 #[cfg(feature = "heif")]
570 return decode_heif(bytes, max_side);
571 #[cfg(not(feature = "heif"))]
572 return Err(PdfError::Pdfium(
573 "HEIC/HEIF input needs a build with the `heif` cargo feature \
574 (rebuild with --features heif; links the system libheif)"
575 .into(),
576 ));
577 }
578
579 let mut limits = image::Limits::default();
580 limits.max_image_width = Some(max_side);
581 limits.max_image_height = Some(max_side);
582 limits.max_alloc = Some(256 * 1024 * 1024);
583
584 let mut reader = ImageReader::new(Cursor::new(bytes))
585 .with_guessed_format()
586 .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
587 reader.limits(limits);
588 let mut decoder = reader
589 .into_decoder()
590 .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
591 // docling#4247 (2.128, `ImageOps.exif_transpose`): a camera stores the
592 // sensor readout plus an orientation tag rather than rotated pixels, so
593 // a portrait photo would reach layout and OCR on its side unless the tag
594 // is honoured. An unreadable tag is no orientation, not an error.
595 let orientation = decoder
596 .orientation()
597 .unwrap_or(image::metadata::Orientation::NoTransforms);
598 let mut img = image::DynamicImage::from_decoder(decoder)
599 .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
600 img.apply_orientation(orientation);
601 Ok(img.into_rgb8())
602}
603
604/// Image outputs of the PDF/image pipeline (#519/#520): the scale picture
605/// crops are delivered at and whether each page's render is kept as the
606/// document's page image. See [`Pipeline::images_scale`] /
607/// [`Pipeline::generate_page_images`].
608#[derive(Debug, Clone, Copy, Default, PartialEq)]
609pub struct ImageOutput {
610 /// Pixels per PDF point for picture crops and page images — docling's
611 /// `images_scale`. `None` keeps the pipeline's own page render (2.0
612 /// px/pt), resampling nothing.
613 pub scale: Option<f32>,
614 /// Keep every page's render as the document's page image — docling's
615 /// `generate_page_images`.
616 pub page_images: bool,
617}
618
619#[cfg(feature = "ml")]
620/// One page's assembled output: typed nodes plus the page's hyperlinks (kept
621/// separate so pages processed out of order can be stitched back in page
622/// order) and its confidence scores (#183).
623type PageOut = (
624 Vec<Node>,
625 Vec<(String, String)>,
626 docling_core::confidence::PageConfidence,
627 // The page image, when page images are requested (#520).
628 Option<docling_core::PictureImage>,
629);
630
631#[cfg(feature = "ml")]
632/// A page between region resolution and TableFormer: what `prepare_page`
633/// produced and `complete_page` still needs, so a pool worker can park the
634/// page while another worker holds the shared TableFormer (see `Staged`).
635struct Prepared {
636 regions: Vec<layout::Region>,
637 ocr_confs: Vec<f32>,
638 parse: Option<f64>,
639}
640
641#[cfg(feature = "ml")]
642/// A pool worker's per-page outcome. `NeedsTables` is a page whose only
643/// remaining stage is the shared TableFormer, which was busy when the worker
644/// got there: rather than block on the mutex — one worker idle for the
645/// whole of another worker's table decode, ~9.5 s of the 60-page .NET slice
646/// on a 2-worker pool — the worker keeps the page aside, pulls the next one
647/// off the render channel, and comes back once the slot is free. Results
648/// are reassembled by page index anyway, so completion order is free.
649enum Staged {
650 Done(PageOut),
651 NeedsTables(Prepared),
652}
653
654#[cfg(feature = "ml")]
655/// How many pages a pool worker keeps parked on the TableFormer before it
656/// falls back to waiting: each carries its ~5 MB bitmaps, so this bounds the
657/// extra residency to two pages per worker on top of the render channel.
658const MAX_DEFERRED_PAGES: usize = 2;
659
660#[cfg(feature = "ml")]
661/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
662/// lazily on the first table region any worker sees. Tables appear on a
663/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
664/// weights+arenas by the pool size for nothing; a single shared instance keeps
665/// the peak flat regardless of pool width, and a table's structure prediction
666/// is independent of which worker runs it, so output is byte-identical. The
667/// mutex serialises concurrent tables — the shared instance is loaded with the
668/// full intra-op thread budget to compensate (one wide TableFormer instead of
669/// several narrow ones).
670enum TfSlot {
671 /// Not attempted yet (no table seen so far).
672 Unloaded,
673 /// Load attempted, graphs absent — geometric fallback (warned once).
674 Missing,
675 Ready(tableformer::TableFormer),
676}
677
678#[cfg(feature = "ml")]
679impl TfSlot {
680 /// Load TableFormer on the first call: `Ready`, or `Missing` when its
681 /// graphs are absent (the geometric fallback — degradation, not an
682 /// error). Later calls are no-ops either way.
683 fn load(&mut self) {
684 if matches!(self, TfSlot::Unloaded) {
685 *self = match tableformer::TableFormer::load_with(tf_intra()) {
686 Some(tf) => TfSlot::Ready(tf),
687 None => TfSlot::Missing,
688 };
689 }
690 }
691}
692
693#[cfg(feature = "ml")]
694type SharedTables = Arc<Mutex<TfSlot>>;
695
696#[cfg(feature = "ml")]
697/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
698/// one instance per pipeline, loaded on the first region that needs it.
699enum EnrichSlot<T> {
700 Unloaded,
701 /// Load attempted, model files absent — enrichment skipped (warned once).
702 Missing,
703 Ready(T),
704}
705
706#[cfg(feature = "ml")]
707type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
708#[cfg(feature = "ml")]
709type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
710
711#[cfg(feature = "ml")]
712/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
713/// flags (`do_picture_classification`, `do_code_enrichment`,
714/// `do_formula_enrichment`). All off by default.
715#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
716pub struct EnrichmentOptions {
717 /// Classify each picture with DocumentFigureClassifier (26 classes).
718 pub picture_classification: bool,
719 /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
720 pub code: bool,
721 /// Decode display formulas to LaTeX with CodeFormulaV2.
722 pub formula: bool,
723}
724
725#[cfg(feature = "ml")]
726impl EnrichmentOptions {
727 fn any(&self) -> bool {
728 self.picture_classification || self.code || self.formula
729 }
730}
731
732#[cfg(feature = "ml")]
733/// The layout model's input for a page: the pypdfium2-exact scale-1.0 page
734/// image (#478) when the renderer produced one, else the legacy stretch of the 2×
735/// bitmap (browser / METS paths) — see [`layout::LayoutSrc`]. Public so the
736/// diagnostic examples feed [`layout::LayoutModel::predict`] the same input
737/// the pipeline does.
738pub fn layout_src(page: &PdfPage) -> layout::LayoutSrc<'_> {
739 match &page.image_layout {
740 Some(img) => layout::LayoutSrc::PageImage(img),
741 None => layout::LayoutSrc::Raw(&page.image),
742 }
743}
744
745#[cfg(feature = "ml")]
746/// RapidOCR's longest side (`Global.max_side_len`, 2000): docling renders the
747/// OCR input at `OcrOptions.scale` = 3 and RapidOCR then shrinks what exceeds
748/// this before detecting and recognizing, so that is the resolution its
749/// models actually see.
750const RAPIDOCR_MAX_SIDE: f32 = 2000.0;
751
752#[cfg(feature = "ml")]
753/// The px/pt the OCR reads a page at: the caller's `ocr_scale` when set; else,
754/// for a standalone bitmap input — its own scale-1.0 page, a resolution the
755/// pipeline did not choose — docling's rule (#570): three pixels per point
756/// (`OcrOptions.scale`), shrunk so the longer side stays within RapidOCR's
757/// 2000 px (a 754 × 1000 scanned form reads at 2.0; a 3000 px photo at 0.67,
758/// as RapidOCR would downsample it). `None` for a rendered page (PDF, hOCR),
759/// which keeps its own render — the 2.0 px/pt the conformance baselines are
760/// pinned to. Measured on FUNSD at 1.0 / 2.0 / 3.0 px/pt: 0.825 / 0.856 /
761/// 0.836 word recall — the recognizer likes its crops at the resolution
762/// RapidOCR hands it, no more.
763fn page_ocr_scale(ocr_scale: Option<f32>, width: f32, height: f32, scale: f32) -> Option<f32> {
764 if ocr_scale.is_some() || scale != 1.0 {
765 return ocr_scale;
766 }
767 let longest = width.max(height);
768 if longest <= 0.0 {
769 return None;
770 }
771 let s = 3.0f32.min(RAPIDOCR_MAX_SIDE / longest);
772 ((s - 1.0).abs() > 1e-3).then_some(s)
773}
774
775#[cfg(feature = "ml")]
776/// The bitmap + px/pt scale the OCR reads (#254, docling#3877's
777/// `OcrOptions.scale`): the page's own render unless `ocr_scale` asks for a
778/// different resolution, where a PIL-bicubic resample of that render is built
779/// once per page (cached in `cache`) and shared by every OCR pass. Resampling
780/// — rather than a second native pdfium render — keeps one code path across
781/// PDF, image, and hOCR inputs and leaves the layout/TableFormer pixels (and
782/// with them the conformance baseline) untouched; the 144-dpi base render is
783/// itself supersampled down from 216 dpi, so an upscaled OCR view loses
784/// little against a native render.
785fn ocr_input<'a>(
786 cache: &'a mut Option<image::RgbImage>,
787 image: &'a image::RgbImage,
788 scale: f32,
789 ocr_scale: Option<f32>,
790) -> (&'a image::RgbImage, f32) {
791 match ocr_scale {
792 Some(s) if (s - scale).abs() > 1e-3 && image.width() > 1 => {
793 let f = s / scale;
794 let img = cache.get_or_insert_with(|| {
795 let dw = ((image.width() as f32 * f).round() as u32).max(1);
796 let dh = ((image.height() as f32 * f).round() as u32).max(1);
797 resample::pil_resize(image, dw, dh, resample::PilFilter::Bicubic)
798 });
799 (img, s)
800 }
801 _ => (image, scale),
802 }
803}
804
805#[cfg(feature = "ml")]
806/// A self-contained set of the per-page models (layout, OCR). Each parallel
807/// page-worker owns its own `Worker` so inference runs concurrently without
808/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
809/// rarely-hit TableFormer is shared (see [`TfSlot`]).
810struct Worker {
811 /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
812 layout: Option<layout::LayoutModel>,
813 ocr: OcrSlot,
814 det: DetSlot,
815 /// Text-detector results computed ahead of a page's OCR pass (#429), keyed
816 /// by page index: the detector reads nothing but the page image, so it
817 /// runs on its own thread while the layout model predicts — see
818 /// [`Self::detect_alongside`] — and the OCR block collects the boxes here
819 /// instead of paying for detection serially.
820 pending_det: BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
821 /// This worker's intra-op thread budget — also the OCR lane count (see
822 /// [`ocr::OcrModel::load_with`]): a pool worker with two threads runs two
823 /// single-thread recognisers, the primary as many as its cores.
824 intra: usize,
825 /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
826 tables: Option<SharedTables>,
827 /// Shared enrichment slots; `None` unless the corresponding flag is on.
828 classifier: Option<SharedClassifier>,
829 code_formula: Option<SharedCodeFormula>,
830 enrich: EnrichmentOptions,
831 /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
832 /// embedded text layer. See [`Pipeline::no_ocr`].
833 no_ocr: bool,
834 /// Discard the embedded text layer and OCR every page. See
835 /// [`Pipeline::force_full_page_ocr`].
836 force_full_page_ocr: bool,
837 /// Keep text-panel pictures as pictures instead of demoting them to
838 /// paragraphs. See [`Pipeline::no_text_panels`].
839 no_text_panels: bool,
840 /// Never run OCR, but keep layout + TableFormer (#244) — docling's
841 /// `do_ocr=False`. See [`Pipeline::skip_ocr`].
842 skip_ocr: bool,
843 /// Which recognition model [`Self::ocr`] loads. See [`Pipeline::ocr_lang`].
844 ocr_lang: ocr::OcrLang,
845 /// Which engine [`Self::ocr`] is (#460). See [`Pipeline::ocr_engine`].
846 ocr_engine: ocr::OcrEngine,
847 /// Tesseract's `-l` argument (#460). See [`Pipeline::tesseract_lang`].
848 tesseract_lang: Option<String>,
849 /// OCR render scale override (px/pt, #254). See [`Pipeline::ocr_scale`].
850 ocr_scale: Option<f32>,
851 /// Picture-crop scale and page images (#519/#520). See [`ImageOutput`].
852 images: ImageOutput,
853}
854
855#[cfg(feature = "ml")]
856/// The worker's lazily-loaded OCR recognition model. `Missing` records a
857/// failed load (#244: degradation over failure — a deployment without the OCR
858/// model still gets layout + TableFormer, and OCR-dependent regions stay
859/// empty) so the load isn't retried per page.
860enum OcrSlot {
861 Unloaded,
862 Ready(Recognizer),
863 Missing,
864}
865
866#[cfg(feature = "ml")]
867/// The loaded OCR engine (#460): PP-OCRv3 via ONNX Runtime or the
868/// `tesseract` binary. Both answer the two questions the page assembly asks
869/// — line cells for text regions, word cells for table regions — in page
870/// points with a 0–1 confidence, so the call sites never know which runs.
871pub(crate) enum Recognizer {
872 PpOcr(ocr::OcrModel),
873 Tesseract(tesseract::TesseractOcr),
874}
875
876#[cfg(feature = "ml")]
877impl Recognizer {
878 /// See [`ocr::OcrModel::ocr_page_with`].
879 fn ocr_page(
880 &mut self,
881 img: &image::RgbImage,
882 regions: &[layout::Region],
883 scale: f32,
884 ) -> Result<Vec<(TextCell, f32)>, String> {
885 self.ocr_page_with(img, regions, scale, None)
886 }
887
888 /// [`Self::ocr_page`] with the detector's boxes (#570). Tesseract segments its
889 /// own lines and ignores the detector's boxes.
890 fn ocr_page_with(
891 &mut self,
892 img: &image::RgbImage,
893 regions: &[layout::Region],
894 scale: f32,
895 detected: Option<&[ocr_det::DetBox]>,
896 ) -> Result<Vec<(TextCell, f32)>, String> {
897 match self {
898 Self::PpOcr(m) => m.ocr_page_with(img, regions, scale, detected),
899 Self::Tesseract(t) => t.ocr_page(img, regions, scale),
900 }
901 }
902
903 /// See [`ocr::OcrModel::ocr_table_words`].
904 fn ocr_table_words(
905 &mut self,
906 img: &image::RgbImage,
907 regions: &[layout::Region],
908 scale: f32,
909 detected: Option<&[ocr_det::DetBox]>,
910 ) -> Result<Vec<(TextCell, f32)>, String> {
911 match self {
912 Self::PpOcr(m) => m.ocr_table_words(img, regions, scale, detected),
913 Self::Tesseract(t) => t.ocr_table_words(img, regions, scale),
914 }
915 }
916}
917
918#[cfg(feature = "ml")]
919/// The text detector (#429), loaded on the first OCR'd page like the
920/// recognizer; `Missing` keeps the pipeline recognition-only.
921enum DetSlot {
922 Unloaded,
923 Ready(ocr_det::DetModel),
924 Missing,
925}
926
927#[cfg(feature = "ml")]
928impl Worker {
929 #[allow(clippy::too_many_arguments)] // mirrors the Pipeline's option set
930 fn load(
931 intra: usize,
932 tables: Option<SharedTables>,
933 enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
934 enrich: EnrichmentOptions,
935 no_ocr: bool,
936 skip_ocr: bool,
937 force_full_page_ocr: bool,
938 no_text_panels: bool,
939 ocr_lang: ocr::OcrLang,
940 ocr_engine: ocr::OcrEngine,
941 tesseract_lang: Option<String>,
942 ocr_scale: Option<f32>,
943 images: ImageOutput,
944 ) -> Result<Self, PdfError> {
945 Ok(Self {
946 images,
947 layout: if no_ocr {
948 None
949 } else {
950 Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
951 },
952 ocr: OcrSlot::Unloaded,
953 det: DetSlot::Unloaded,
954 pending_det: BTreeMap::new(),
955 intra,
956 tables,
957 classifier: enrich_slots.0,
958 code_formula: enrich_slots.1,
959 enrich,
960 no_ocr,
961 skip_ocr,
962 force_full_page_ocr,
963 no_text_panels,
964 ocr_lang,
965 ocr_engine,
966 tesseract_lang,
967 ocr_scale,
968 })
969 }
970
971 /// The OCR model, or `None` when this conversion must not (or cannot) OCR:
972 /// `skip_ocr` short-circuits, and a failed model load degrades to `None`
973 /// with a one-time warning instead of failing the conversion (#244) —
974 /// unless `force_full_page_ocr` demanded OCR explicitly, where a missing
975 /// model stays a hard error (the text layer was deliberately discarded, so
976 /// degrading would silently emit an empty document).
977 fn ocr_model(&mut self) -> Result<Option<&mut Recognizer>, PdfError> {
978 if self.skip_ocr {
979 return Ok(None);
980 }
981 if matches!(self.ocr, OcrSlot::Unloaded) {
982 let loaded = match self.ocr_engine {
983 ocr::OcrEngine::PpOcr => {
984 ocr::OcrModel::load_with(self.ocr_lang, self.intra).map(Recognizer::PpOcr)
985 }
986 ocr::OcrEngine::Tesseract => tesseract::TesseractOcr::load(
987 tesseract::TesseractOptions::from_env(self.tesseract_lang.clone()),
988 self.intra,
989 )
990 .map(Recognizer::Tesseract),
991 };
992 match loaded {
993 Ok(model) => self.ocr = OcrSlot::Ready(model),
994 Err(e) if self.force_full_page_ocr => return Err(PdfError::Ocr(e)),
995 Err(e) => {
996 static WARNED: std::sync::Once = std::sync::Once::new();
997 let hint = match self.ocr_engine {
998 ocr::OcrEngine::PpOcr => {
999 "run scripts/install/download_dependencies.sh for the model"
1000 }
1001 ocr::OcrEngine::Tesseract => {
1002 "install tesseract-ocr with the language pack, or use --ocr-engine ppocr"
1003 }
1004 };
1005 WARNED.call_once(|| {
1006 eprintln!(
1007 "warning: OCR model unavailable ({e}); continuing without OCR — \
1008 scanned pages and text inside images will come back empty \
1009 ({hint})"
1010 );
1011 });
1012 self.ocr = OcrSlot::Missing;
1013 }
1014 }
1015 }
1016 Ok(match &mut self.ocr {
1017 OcrSlot::Ready(model) => Some(model),
1018 _ => None,
1019 })
1020 }
1021
1022 /// The text detector (#429): loaded on first use, `None` with `skip_ocr`
1023 /// or when the model is not installed — recognition stays region-scoped
1024 /// then, exactly the pre-#429 behavior, and `DOCLING_RS_DEBUG` says why.
1025 fn det_model(&mut self) -> Option<&mut ocr_det::DetModel> {
1026 if self.skip_ocr {
1027 return None;
1028 }
1029 if matches!(self.det, DetSlot::Unloaded) {
1030 match ocr_det::DetModel::load(self.intra) {
1031 Ok(model) => self.det = DetSlot::Ready(model),
1032 Err(e) => {
1033 docling_core::debug_log!(
1034 "docling-pdf: text detection unavailable ({e}); OCR stays region-scoped"
1035 );
1036 self.det = DetSlot::Missing;
1037 }
1038 }
1039 }
1040 match &mut self.det {
1041 DetSlot::Ready(model) => Some(model),
1042 _ => None,
1043 }
1044 }
1045
1046 /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
1047 /// into its nodes and links. Pure given the page (mutates only the worker's
1048 /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
1049 fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
1050 if self.no_ocr {
1051 // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
1052 // embedded text cells (if any) become flat, line-grouped paragraphs in
1053 // reading order via the same orphan-region machinery that normally
1054 // rescues text the detector missed — here it rescues *all* of it.
1055 // Pages with no embedded text layer (scanned/image-only) yield nothing;
1056 // convert those without `no_ocr`.
1057 let parse = quality::parse_score(&page.cells);
1058 let mut regions = Vec::new();
1059 assemble::add_orphan_regions(&mut regions, &page.cells);
1060 let table_rows = vec![None; regions.len()];
1061 let enrich_out = vec![None; regions.len()];
1062 let conf = quality::page_confidence(parse, ®ions, &[]);
1063 let (nodes, links) = timing::timed("assemble_page", || {
1064 assemble::assemble_page(page, regions, &table_rows, &enrich_out, self.images.scale)
1065 });
1066 return Ok((nodes, links, conf, self.page_image(n, page)));
1067 }
1068 self.normalize_orientation(n, page)?;
1069 let det_pages = self.det_candidates(std::slice::from_ref(&(n, &*page)))?;
1070 let regions = {
1071 let Self {
1072 layout,
1073 det,
1074 pending_det,
1075 ocr_scale,
1076 ..
1077 } = self;
1078 let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
1079 let page: &PdfPage = &*page;
1080 Self::detect_alongside(det, pending_det, *ocr_scale, &det_pages, || {
1081 timing::timed("layout.predict", || {
1082 layout.predict(layout_src(page), page.width, page.height)
1083 })
1084 })
1085 }
1086 .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
1087 self.finish_page(n, page, regions)
1088 }
1089
1090 /// The page's render as docling's `PageItem.image` (#520), at
1091 /// [`ImageOutput::scale`] — `None` unless page images were requested, or
1092 /// when the page has no bitmap (the text-layer-only `no_ocr` path never
1093 /// renders one).
1094 fn page_image(&self, n: usize, page: &PdfPage) -> Option<docling_core::PictureImage> {
1095 if !self.images.page_images {
1096 return None;
1097 }
1098 let image = assemble::page_image(page, self.images.scale);
1099 if image.is_none() {
1100 docling_core::debug_log!("page {}: no page bitmap for the page image", n + 1);
1101 }
1102 image
1103 }
1104
1105 /// The pages of a batch the text detector should sweep (#429): bitmap
1106 /// pages (no text layer) on a run with OCR and the detector available —
1107 /// loading both lazily here so the concurrent run below needs no `self`.
1108 fn det_candidates<'p>(
1109 &mut self,
1110 pages: &[(usize, &'p PdfPage)],
1111 ) -> Result<Vec<(usize, &'p PdfPage)>, PdfError> {
1112 // Pages the orientation pass already detected (#571) are skipped:
1113 // their boxes wait in `pending_det`.
1114 let scanned: Vec<(usize, &PdfPage)> = pages
1115 .iter()
1116 .filter(|(n, p)| {
1117 p.cells.is_empty() && p.image.width() > 1 && !self.pending_det.contains_key(n)
1118 })
1119 .copied()
1120 .collect();
1121 if scanned.is_empty() || self.ocr_model()?.is_none() || self.det_model().is_none() {
1122 return Ok(Vec::new());
1123 }
1124 Ok(scanned)
1125 }
1126
1127 /// Run `layout` on the calling thread while the text detector sweeps
1128 /// `det_pages` on another (#429): the detector only reads each page's
1129 /// image, layout only reads the pages too, and the two sessions are
1130 /// independent, so on a scanned page the ~0.7 s detection hides behind
1131 /// layout instead of adding to it. Results land in `pending_det` for the
1132 /// OCR block; a detector failure is recorded per page and surfaces there.
1133 fn detect_alongside<T>(
1134 det: &mut DetSlot,
1135 pending_det: &mut BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
1136 ocr_scale: Option<f32>,
1137 det_pages: &[(usize, &PdfPage)],
1138 layout: impl FnOnce() -> T,
1139 ) -> T {
1140 let DetSlot::Ready(det) = det else {
1141 return layout();
1142 };
1143 if det_pages.is_empty() {
1144 return layout();
1145 }
1146 std::thread::scope(|s| {
1147 let handle = s.spawn(move || {
1148 det_pages
1149 .iter()
1150 .map(|&(n, page)| {
1151 let mut view = None;
1152 let (img, _) = ocr_input(
1153 &mut view,
1154 &page.image,
1155 page.scale,
1156 page_ocr_scale(ocr_scale, page.width, page.height, page.scale),
1157 );
1158 (n, timing::timed("ocr.det", || det.detect(img)))
1159 })
1160 .collect::<Vec<_>>()
1161 });
1162 let out = layout();
1163 match handle.join() {
1164 Ok(results) => pending_det.extend(results),
1165 Err(_) => {
1166 for &(n, _) in det_pages {
1167 pending_det.insert(n, Err("ocr-det: detection thread panicked".into()));
1168 }
1169 }
1170 }
1171 out
1172 })
1173 }
1174
1175 /// Content-based orientation normalization (#225), before any inference:
1176 /// a physically rotated scan (sideways phone photo, landscape-fed sheet)
1177 /// has `/Rotate 0`, so the metadata pass in `extract_page` never fires and
1178 /// layout+OCR would read a sideways raster. Only pages with no text layer
1179 /// at all are probed (a digital page's raster is upright by construction,
1180 /// and its cells — not its pixels — carry the text); the detected angle
1181 /// composes with any `/Rotate` normalization through the same
1182 /// [`PdfPage::unrotate`] + display-space assembly mapping. Detection is
1183 /// evidence-gated and degrades to a no-op — see [`orient`].
1184 fn normalize_orientation(&mut self, n: usize, page: &mut PdfPage) -> Result<(), PdfError> {
1185 let scanned =
1186 page.cells.is_empty() && page.word_cells.is_empty() && page.code_cells.is_empty();
1187 if self.no_ocr || self.skip_ocr || !scanned || page.image.width() <= 1 || !orient::enabled()
1188 {
1189 return Ok(());
1190 }
1191 // The probe reads text through the OCR model; without one (missing —
1192 // #244 degradation) the page stays as rendered.
1193 if self.ocr_model()?.is_none() {
1194 return Ok(());
1195 }
1196 // The text detector's lines are the probe's crops (#571). Detected on
1197 // the page image as rendered; an upright page keeps them for the OCR
1198 // pass (`pending_det`) when that pass reads the same bitmap, so the
1199 // detector runs once per page as before — a rotated page detects
1200 // again on the un-rotated image, alongside layout.
1201 let boxes: Vec<ocr_det::DetBox> = match self.det_model() {
1202 Some(det) => timing::timed("orient.det", || det.detect(&page.image)).unwrap_or_else(|e| {
1203 debug_log!("docling-pdf: page {}: text detection failed ({e}); probing projection strips", n + 1);
1204 Vec::new()
1205 }),
1206 None => Vec::new(),
1207 };
1208 let ocr_scale = page_ocr_scale(self.ocr_scale, page.width, page.height, page.scale);
1209 let Some(ocr) = self.ocr_model()? else {
1210 return Ok(());
1211 };
1212 let deg = timing::timed("orient.detect", || {
1213 orient::detect(&page.image, ocr, page.scale, &boxes)
1214 });
1215 if deg != 0 {
1216 debug_log!(
1217 "docling-pdf: page {}: content rotated {deg}° in the raster; \
1218 un-rotating before layout/OCR",
1219 n + 1
1220 );
1221 page.unrotate(deg);
1222 } else if !boxes.is_empty() && ocr_scale.is_none_or(|s| (s - page.scale).abs() <= 1e-3) {
1223 self.pending_det.insert(n, Ok(boxes));
1224 }
1225 Ok(())
1226 }
1227
1228 /// Layout-detect a whole batch of pages with one inference call (issue #73),
1229 /// then run each page's remaining stages (OCR / TableFormer / enrichment /
1230 /// assembly) per page. Index-aligned with `items`; a layout failure fails
1231 /// every page in the batch (they shared the one inference call).
1232 fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<Staged, PdfError>> {
1233 if self.no_ocr {
1234 // No layout model to batch — the text-layer-only path is per page.
1235 return items
1236 .iter_mut()
1237 .map(|(n, page)| {
1238 let n = *n;
1239 self.process(n, page).map(Staged::Done)
1240 })
1241 .collect();
1242 }
1243 // Orientation-normalize every scanned page before the shared layout
1244 // call — the batched inference must see upright bitmaps too (#225).
1245 for (n, page) in items.iter_mut() {
1246 let n = *n;
1247 if let Err(e) = self.normalize_orientation(n, page) {
1248 // Model-load failure — every page in the batch needs the same
1249 // model, so they all fail alike (mirrors the layout-error arm).
1250 let msg = e.to_string();
1251 return items
1252 .iter()
1253 .map(|_| Err(PdfError::Ocr(msg.clone())))
1254 .collect();
1255 }
1256 }
1257 let inputs: Vec<(layout::LayoutSrc<'_>, f32, f32)> = items
1258 .iter()
1259 .map(|(_, page)| (layout_src(page), page.width, page.height))
1260 .collect();
1261 let refs: Vec<(usize, &PdfPage)> = items.iter().map(|(n, page)| (*n, page)).collect();
1262 let det_pages = match self.det_candidates(&refs) {
1263 Ok(p) => p,
1264 Err(e) => {
1265 let msg = e.to_string();
1266 return items
1267 .iter()
1268 .map(|_| Err(PdfError::Ocr(msg.clone())))
1269 .collect();
1270 }
1271 };
1272 let batched = {
1273 let Self {
1274 layout,
1275 det,
1276 pending_det,
1277 ocr_scale,
1278 ..
1279 } = self;
1280 let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
1281 Self::detect_alongside(det, pending_det, *ocr_scale, &det_pages, || {
1282 timing::timed("layout.predict", || layout.predict_batch(&inputs))
1283 })
1284 };
1285 match batched {
1286 Ok(all) => items
1287 .iter_mut()
1288 .zip(all)
1289 .map(|((n, page), regions)| self.stage_page(*n, page, regions))
1290 .collect(),
1291 Err(e) => items
1292 .iter()
1293 .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
1294 .collect(),
1295 }
1296 }
1297
1298 /// A pool worker's main loop: pull rendered pages off the shared channel
1299 /// (whatever is already there, up to the layout batch size), process them,
1300 /// and hand each finished page — or its error — to `deliver`, which returns
1301 /// `false` to stop early (the streaming consumer went away). Returns when
1302 /// the channel is closed and every page this worker took is delivered.
1303 ///
1304 /// Pages whose TableFormer turn would have to wait are parked (see
1305 /// `Staged`) and retried before every new pull; while any are parked the
1306 /// pull is non-blocking, so an empty channel means the worker waits for
1307 /// the TableFormer rather than for the renderer. The parking budget
1308 /// (`MAX_DEFERRED_PAGES`) bounds resident bitmaps; past it the worker waits
1309 /// like the serial path. Output is independent of completion order — the
1310 /// callers reassemble by page index.
1311 fn run_pool(
1312 &mut self,
1313 work_rx: &Mutex<Receiver<(usize, PdfPage)>>,
1314 layout_batch: usize,
1315 deadline: Option<std::time::Instant>,
1316 mut deliver: impl FnMut(usize, Result<PageOut, PdfError>) -> bool,
1317 ) {
1318 use std::sync::mpsc::TryRecvError;
1319 let mut deferred: std::collections::VecDeque<(usize, PdfPage, Prepared)> =
1320 std::collections::VecDeque::new();
1321 loop {
1322 // The document budget (#497), checked between pages: once it is
1323 // spent, every page still queued or parked is reported as timed
1324 // out instead of processed — the renderer stops feeding at the
1325 // same check, so the queue drains quickly.
1326 if expired(deadline) {
1327 while let Some((idx, _, _)) = deferred.pop_front() {
1328 if !deliver(idx, Err(timeout_sentinel())) {
1329 return;
1330 }
1331 }
1332 let rx = work_rx.lock().unwrap();
1333 loop {
1334 match rx.recv() {
1335 Ok((idx, _page)) => {
1336 if !deliver(idx, Err(timeout_sentinel())) {
1337 return;
1338 }
1339 }
1340 Err(_) => return,
1341 }
1342 }
1343 }
1344 // Any parked page the slot has since freed up for, oldest first.
1345 let mut i = 0;
1346 while i < deferred.len() {
1347 let (_, page, prepared) = &deferred[i];
1348 match self.table_rows_try(page, &prepared.regions) {
1349 Some(rows) => {
1350 let (idx, mut page, prepared) = deferred.remove(i).expect("index in range");
1351 if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1352 return;
1353 }
1354 }
1355 None => i += 1,
1356 }
1357 }
1358 // Hold the receiver lock only for the recv (plus a non-blocking drain
1359 // up to the layout batch size); release before the (long) per-page
1360 // work so other workers can pull concurrently.
1361 let mut batch: Vec<(usize, PdfPage)> = Vec::new();
1362 let mut closed = false;
1363 {
1364 let rx = work_rx.lock().unwrap();
1365 let first = if deferred.is_empty() {
1366 rx.recv().map_err(|_| TryRecvError::Disconnected)
1367 } else {
1368 rx.try_recv()
1369 };
1370 match first {
1371 Ok(item) => {
1372 batch.push(item);
1373 while batch.len() < layout_batch {
1374 match rx.try_recv() {
1375 Ok(item) => batch.push(item),
1376 Err(_) => break,
1377 }
1378 }
1379 }
1380 Err(TryRecvError::Empty) => {}
1381 Err(TryRecvError::Disconnected) => closed = true,
1382 }
1383 }
1384 if batch.is_empty() {
1385 // Nothing new rendered (or the channel is closed): wait our turn
1386 // on the oldest parked page instead.
1387 match deferred.pop_front() {
1388 Some((idx, mut page, prepared)) => {
1389 let rows = self.table_rows_blocking(&page, &prepared.regions);
1390 if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1391 return;
1392 }
1393 continue;
1394 }
1395 None if closed => return,
1396 None => continue,
1397 }
1398 }
1399 let outs = self.process_batch(&mut batch);
1400 for ((idx, mut page), out) in batch.into_iter().zip(outs) {
1401 let delivered = match out {
1402 Ok(Staged::Done(out)) => deliver(idx, Ok(out)),
1403 Ok(Staged::NeedsTables(prepared)) => {
1404 if deferred.len() < MAX_DEFERRED_PAGES {
1405 deferred.push_back((idx, page, prepared));
1406 true
1407 } else {
1408 let rows = self.table_rows_blocking(&page, &prepared.regions);
1409 deliver(idx, self.complete_page(idx, &mut page, prepared, rows))
1410 }
1411 }
1412 Err(e) => deliver(idx, Err(e)),
1413 };
1414 if !delivered {
1415 return;
1416 }
1417 }
1418 }
1419 }
1420
1421 /// Everything after layout detection: per-label confidence thresholds,
1422 /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
1423 /// TableFormer, enrichment, and page assembly. The serial path: waits
1424 /// for the shared TableFormer when a table needs it.
1425 fn finish_page(
1426 &mut self,
1427 n: usize,
1428 page: &mut PdfPage,
1429 regions: Vec<layout::Region>,
1430 ) -> Result<PageOut, PdfError> {
1431 let prepared = self.prepare_page(n, page, regions)?;
1432 let table_rows = self.table_rows_blocking(page, &prepared.regions);
1433 self.complete_page(n, page, prepared, table_rows)
1434 }
1435
1436 /// The pool path: like [`finish_page`](Self::finish_page), except that a
1437 /// page whose TableFormer turn would have to wait comes back as
1438 /// [`Staged::NeedsTables`] for the worker loop to park (see `Staged`).
1439 fn stage_page(
1440 &mut self,
1441 n: usize,
1442 page: &mut PdfPage,
1443 regions: Vec<layout::Region>,
1444 ) -> Result<Staged, PdfError> {
1445 let prepared = self.prepare_page(n, page, regions)?;
1446 match self.table_rows_try(page, &prepared.regions) {
1447 Some(rows) => Ok(Staged::Done(self.complete_page(n, page, prepared, rows)?)),
1448 None => Ok(Staged::NeedsTables(prepared)),
1449 }
1450 }
1451
1452 /// Does this page need the shared TableFormer at all? Table-free pages
1453 /// never touch (or load) it.
1454 fn needs_tables(&self, regions: &[layout::Region]) -> bool {
1455 self.tables.is_some() && regions.iter().any(|r| assemble::is_table_like(r.label))
1456 }
1457
1458 /// TableFormer structure for every table region of the page, on an
1459 /// already-locked slot (loading the model on first use). Tables serialise
1460 /// on this mutex, so the one instance gets the shared thread budget
1461 /// (quota-aware, #262) — DOCLING_RS_TF_INTRA narrows it further where the
1462 /// memory-per-thread tradeoff matters more than table latency.
1463 fn predict_tables(
1464 guard: &mut TfSlot,
1465 page: &PdfPage,
1466 regions: &[layout::Region],
1467 ) -> Vec<Option<tf_core::TableGrid>> {
1468 let mut table_rows: Vec<Option<tf_core::TableGrid>> = vec![None; regions.len()];
1469 guard.load();
1470 if let TfSlot::Ready(tf) = guard {
1471 // One 1024-px frame per page, shared by all of its tables, and one
1472 // call for all of them: with the dynamic-batch decoder their
1473 // decode steps are shared (each step costs about the same for B
1474 // tables as for one).
1475 let page1024 = tableformer::TableFormer::page_1024(&page.image);
1476 let (idx, boxes): (Vec<usize>, Vec<[f32; 4]>) = regions
1477 .iter()
1478 .enumerate()
1479 .filter(|(_, r)| assemble::is_table_like(r.label))
1480 .map(|(i, r)| (i, [r.l, r.t, r.r, r.b]))
1481 .unzip();
1482 let rows =
1483 tf.predict_tables_on(page.image.height(), &page1024, &boxes, &page.word_cells);
1484 for (i, grid) in idx.into_iter().zip(rows) {
1485 table_rows[i] = grid;
1486 }
1487 }
1488 table_rows
1489 }
1490
1491 /// Table structure for the page, waiting for the shared slot if another
1492 /// worker holds it (else geometric fallback downstream when there is no
1493 /// TableFormer at all). The `tableformer` timing stage here includes any
1494 /// wait.
1495 fn table_rows_blocking(
1496 &self,
1497 page: &PdfPage,
1498 regions: &[layout::Region],
1499 ) -> Vec<Option<tf_core::TableGrid>> {
1500 match self.tables.as_ref().filter(|_| self.needs_tables(regions)) {
1501 Some(slot) => timing::timed("tableformer", || {
1502 Self::predict_tables(&mut slot.lock().unwrap(), page, regions)
1503 }),
1504 None => vec![None; regions.len()],
1505 }
1506 }
1507
1508 /// Non-blocking variant: `None` when the slot is held by another worker
1509 /// right now — the caller parks the page and tries again later.
1510 fn table_rows_try(
1511 &self,
1512 page: &PdfPage,
1513 regions: &[layout::Region],
1514 ) -> Option<Vec<Option<tf_core::TableGrid>>> {
1515 let Some(slot) = self.tables.as_ref().filter(|_| self.needs_tables(regions)) else {
1516 return Some(vec![None; regions.len()]);
1517 };
1518 match slot.try_lock() {
1519 Ok(mut guard) => Some(timing::timed("tableformer", || {
1520 Self::predict_tables(&mut guard, page, regions)
1521 })),
1522 Err(std::sync::TryLockError::WouldBlock) => None,
1523 Err(std::sync::TryLockError::Poisoned(e)) => panic!("TableFormer slot poisoned: {e}"),
1524 }
1525 }
1526
1527 /// The stages before TableFormer: fp32 escalation, per-label confidence
1528 /// thresholds, overlap resolution, orphan-text recovery, OCR for cell-less
1529 /// pages, in-picture text and table-word recognition.
1530 fn prepare_page(
1531 &mut self,
1532 n: usize,
1533 page: &mut PdfPage,
1534 regions: Vec<layout::Region>,
1535 ) -> Result<Prepared, PdfError> {
1536 // Force-OCR is exactly "pretend the text layer is not there": clear
1537 // every cell kind the extractors produced before anything reads them,
1538 // and the ordinary no-text-layer machinery below — full-page OCR,
1539 // OCR-fed TableFormer matching — takes over unchanged. (`no_ocr` wins
1540 // when both are set, mirroring docling, where `force_full_page_ocr`
1541 // is a sub-option of `do_ocr`; the no-ocr path never reaches here.)
1542 // Done here rather than in `process` so the batched layout path
1543 // (`process_batch` → `finish_page`) honors the flag too.
1544 // Parse quality is scored on the extracted text layer before force-OCR
1545 // discards it (docling's page-preprocessing stage runs before OCR too,
1546 // so its parse_score also reflects the original text layer).
1547 let parse = quality::parse_score(&page.cells);
1548 // Recognition confidences of every OCR'd cell on this page → ocr_score.
1549 let mut ocr_confs: Vec<f32> = Vec::new();
1550 // The bitmap the OCR reads (#254): with `ocr_scale` set, a resample of
1551 // the page render at the requested px/pt, built lazily on the first
1552 // OCR use so non-OCR pages never pay for it. Copied out of `self` up
1553 // front — the OCR sites hold `self.ocr_model()`'s mutable borrow.
1554 let ocr_scale = page_ocr_scale(self.ocr_scale, page.width, page.height, page.scale);
1555 let mut ocr_view: Option<image::RgbImage> = None;
1556 if self.force_full_page_ocr {
1557 page.cells.clear();
1558 page.code_cells.clear();
1559 page.word_cells.clear();
1560 }
1561 // Quant-robustness guard: the default int8 layout graph keeps its
1562 // confidences near the 0.5 label thresholds, and a different CPU's
1563 // quantized kernels can flip a whole page's detections under them —
1564 // tables and paragraphs then dissolve into orphan one-liners while the
1565 // same build converts the page perfectly elsewhere. When a dense
1566 // digital page ends up with detections covering almost none of its
1567 // text cells, re-run that one page on the fp32 graph (lazy-loaded,
1568 // auto-int8 selection only) and keep whichever detections cover more.
1569 let mut regions = regions;
1570 if !page.cells.is_empty() {
1571 let thresholded = |rs: &[layout::Region]| -> Vec<layout::Region> {
1572 rs.iter()
1573 .filter(|r| r.score >= layout::label_threshold(r.label))
1574 .cloned()
1575 .collect()
1576 };
1577 let text_cells = page
1578 .cells
1579 .iter()
1580 .filter(|c| !c.text.trim().is_empty())
1581 .count();
1582 let cov = assemble::layout_cell_coverage(&thresholded(®ions), &page.cells);
1583 if text_cells >= 15 && cov < 0.5 {
1584 let retry = self
1585 .layout
1586 .as_mut()
1587 .expect("layout model loaded unless no_ocr")
1588 .predict_fp32_fallback(layout_src(page), page.width, page.height)
1589 .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
1590 if let Some(retry) = retry {
1591 let cov2 = assemble::layout_cell_coverage(&thresholded(&retry), &page.cells);
1592 if cov2 > cov {
1593 debug_log!(
1594 "docling-pdf: page {}: int8 layout covered {:.0}% of the text \
1595 cells; the fp32 retry covers {:.0}% — using it",
1596 n + 1,
1597 cov * 100.0,
1598 cov2 * 100.0
1599 );
1600 regions = retry;
1601 }
1602 }
1603 }
1604 }
1605 // docling's LayoutPostprocessor drops each detection below its label's
1606 // confidence threshold (stricter than the 0.3 base the predictor keeps),
1607 // before any overlap resolution. This removes the low-confidence tables /
1608 // pictures / list-items that otherwise double-emit or mis-classify.
1609 if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1610 for r in ®ions {
1611 eprintln!(
1612 "DBG raw {} {:.2} [{:.0},{:.0},{:.0},{:.0}]",
1613 r.label, r.score, r.l, r.t, r.r, r.b
1614 );
1615 }
1616 }
1617 regions.retain(|r| r.score >= layout::label_threshold(r.label));
1618 // docling's full-page picture filter and same-label picture dedup run
1619 // on the thresholded detections, before overlap resolution: a picture
1620 // that is the whole page goes (its text reads out as text), and a
1621 // figure proposed both whole and as sub-panels collapses to one box
1622 // (see `dedup_pictures`).
1623 assemble::drop_full_page_pictures(&mut regions, page.width, page.height);
1624 assemble::dedup_pictures(&mut regions);
1625 // Resolve overlapping detections once, before OCR.
1626 let mut regions = assemble::resolve(regions);
1627 // Emit text the detector missed as orphan text regions (docling parity).
1628 assemble::add_orphan_regions(&mut regions, &page.cells);
1629 // Drop phantom empty low-confidence picture boxes (docling parity).
1630 assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
1631 // A regular region fully inside a surviving table/index/picture is that
1632 // special's child (a cell / in-figure label), not a separate block —
1633 // remove it so it isn't emitted twice (docling parity).
1634 assemble::drop_contained_regulars(&mut regions);
1635 // A one-line paragraph in the bottom margin under a body-less heading
1636 // is that heading's text, not furniture (deliberate deviation).
1637 assemble::reclaim_heading_body_footers(&mut regions, page.width);
1638 // No text layer → recognise text from the page image via OCR.
1639 let ocred = page.cells.is_empty();
1640 // Lines the text detector found outside every layout region (#429).
1641 let mut det_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1642 if ocred {
1643 // Region-scoped OCR recognizes each region's crop, so two regular
1644 // regions over the same ink would read it twice — a low-score
1645 // paragraph box over the high-score line boxes `greedy` keeps.
1646 // Collapse such groups to one region first; a digital
1647 // page resolves the same overlap through cell ownership in
1648 // `fit_regions_to_cells` and needs nothing here.
1649 assemble::merge_overlapping_regulars(&mut regions);
1650 // The text detector's lines (#429), fetched before the region
1651 // pass: with `det` line mode (#570, the default) they are the
1652 // recognizer's crops inside the regions too — RapidOCR's own line
1653 // source — not only the supplement outside them. Usually computed
1654 // already, alongside layout (see `detect_alongside`); a page that
1655 // reached OCR another way detects here. Degradation over failure:
1656 // a detector that loaded but cannot run (a damaged file, an
1657 // allocation failure) costs the page its detected lines, not its
1658 // conversion — the projection segmentation is complete on its own.
1659 let detected: Vec<ocr_det::DetBox> = if self.ocr_model()?.is_some() {
1660 let (img, _) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1661 match self.pending_det.remove(&n) {
1662 Some(result) => result,
1663 None => match self.det_model() {
1664 Some(det) => timing::timed("ocr.det", || det.detect(img)),
1665 None => Ok(Vec::new()),
1666 },
1667 }
1668 .unwrap_or_else(|e| {
1669 docling_core::debug_log!(
1670 "docling-pdf: page {}: text detection failed ({e}); keeping the \
1671 region-scoped OCR only",
1672 n + 1
1673 );
1674 Vec::new()
1675 })
1676 } else {
1677 Vec::new()
1678 };
1679 docling_core::debug_log!(
1680 "docling-pdf: page {}: text detector found {} line(s): {:?}",
1681 n + 1,
1682 detected.len(),
1683 detected
1684 .iter()
1685 .map(|d| (
1686 d.l.round(),
1687 d.t.round(),
1688 d.r.round(),
1689 d.b.round(),
1690 (d.score * 100.0).round() / 100.0
1691 ))
1692 .collect::<Vec<_>>()
1693 );
1694 let det_lines =
1695 (ocr::det_lines() && !detected.is_empty()).then_some(detected.as_slice());
1696 // `None` = `skip_ocr` or a missing model (#244): the page keeps
1697 // its layout regions (and TableFormer structure below) with no
1698 // recognized text, instead of failing the conversion.
1699 if let Some(ocr) = self.ocr_model()? {
1700 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1701 let cells = timing::timed("ocr.page", || {
1702 ocr.ocr_page_with(img, ®ions, scl, det_lines)
1703 })
1704 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1705 ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
1706 page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
1707 // Table interiors carry no words yet: region-scoped OCR skips
1708 // table labels, and a scanned page has no pdfium text layer — so
1709 // TableFormer's cell matcher got an empty word list and the table
1710 // dissolved (#173). Recognize the table regions' word crops
1711 // (mirroring the browser scanned path): `word_cells` feeds the
1712 // matcher, and the same cells join `cells` so the geometric
1713 // fallback and the table's region text see them too.
1714 if regions.iter().any(|r| assemble::is_table_like(r.label)) {
1715 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1716 let words = timing::timed("ocr.table_words", || {
1717 ocr.ocr_table_words(img, ®ions, scl, det_lines)
1718 })
1719 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1720 ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1721 let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1722 page.cells.extend(words.iter().cloned());
1723 page.word_cells = words;
1724 }
1725 }
1726 // docling's OCR engines detect text lines over the whole bitmap
1727 // and every line becomes a cell, so text the layout model gave no
1728 // region — a diagram's labels, a stamp, a margin note — still
1729 // reads out as orphan text. Region-scoped recognition above stays
1730 // the source inside layout regions; the detector (#429) adds only
1731 // the lines no recognized cell already covers, and the orphan pass
1732 // below places them (those inside a kept picture or table become
1733 // that special's silent children, as upstream).
1734 if self.ocr_model()?.is_some() {
1735 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1736 let uncovered = ocr_det::uncovered_lines(&detected, scl, ®ions, &page.cells);
1737 docling_core::debug_log!(
1738 "docling-pdf: page {}: {} of {} detected line(s) not covered by the region pass",
1739 n + 1,
1740 uncovered.len(),
1741 detected.len()
1742 );
1743 if let (false, Some(ocr)) = (uncovered.is_empty(), self.ocr_model()?) {
1744 let scored =
1745 timing::timed("ocr.det_lines", || ocr.ocr_page(img, &uncovered, scl))
1746 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1747 ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1748 det_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1749 page.cells.extend(det_cells.iter().cloned());
1750 }
1751 }
1752 }
1753 // Region-scoped OCR skips `picture` interiors, and a digital page's
1754 // text layer cannot see into an embedded raster either — so a figure
1755 // that is really a text box (terms-and-conditions exported as an
1756 // image) lost its words on every page kind. Python docling OCRs the
1757 // bitmap-covered areas of *every* page — even digital ones — once they
1758 // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
1759 // already do. Recognize the big text-less crops here too; the panel
1760 // demotion / orphan recovery below place the lines.
1761 let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1762 {
1763 let page_area = (page.width * page.height).max(1.0);
1764 let has_text = |r: &layout::Region| {
1765 page.cells.iter().any(|c| {
1766 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1767 let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1768 let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1769 !c.text.trim().is_empty() && ix * iy / ca > 0.5
1770 })
1771 };
1772 // A captioned picture can never demote to a text panel (see
1773 // recover_text_panels), and on digital pages its speculative OCR
1774 // would be discarded anyway — don't pay for it.
1775 let captioned = |r: &layout::Region| {
1776 regions.iter().any(|c| {
1777 c.label == "caption"
1778 && c.r.min(r.r) - c.l.max(r.l) > 0.0
1779 && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
1780 })
1781 };
1782 let bare: Vec<layout::Region> = regions
1783 .iter()
1784 .filter(|r| {
1785 r.label == "picture"
1786 && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
1787 && !has_text(r)
1788 && (ocred || !captioned(r))
1789 })
1790 .map(|r| layout::Region {
1791 label: "text",
1792 ..r.clone()
1793 })
1794 .collect();
1795 // Speculative OCR (#244): with `skip_ocr` or no model, big bare
1796 // pictures simply stay pictures.
1797 if let (false, Some(ocr)) = (bare.is_empty(), self.ocr_model()?) {
1798 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1799 let scored = timing::timed("ocr.pictures", || ocr.ocr_page(img, &bare, scl))
1800 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1801 // Speculative in-picture OCR counts toward ocr_score only on
1802 // OCR'd pages, where the recognized lines actually join the
1803 // output; on a digital page they may be discarded below.
1804 if ocred {
1805 ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1806 }
1807 pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1808 page.cells.extend(pic_cells.iter().cloned());
1809 }
1810 }
1811 let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
1812 // A "picture" that is really a colored text panel — dense, wide,
1813 // multi-line — reads out as paragraphs instead of shipping as pixels;
1814 // sparse in-picture text (a chart's labels) keeps the crop and stays
1815 // inside it as the picture's silent children (docling parity, #200).
1816 // `no_text_panels` (#173) opts out entirely for image-extraction
1817 // workflows.
1818 if !self.no_text_panels {
1819 assemble::recover_text_panels(&mut regions, &page.cells);
1820 }
1821 // On an OCR'd page, in-picture text that did NOT demote its picture
1822 // mostly stays silent, exactly as in docling: its postprocess step
1823 // "Remove regular clusters that are included in wrappers" walks
1824 // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
1825 // >80 % contained in a kept picture becomes that picture's child and
1826 // never reaches the serializer. Only border-straddlers (≤80 %
1827 // containment) survive as text. Emitting *everything* here used to
1828 // splice a chart's OCR'd axis ticks into the body text right next to
1829 // the image chunk (#200) — so the orphan pass places the recognized
1830 // lines, the containment drop re-runs for the in-table ones, and
1831 // `assemble_page` nests the in-picture ones under their picture
1832 // (JSON-only children, `assemble::picture_parents`).
1833 if ocred && (!pic_cells.is_empty() || !det_cells.is_empty()) {
1834 // Pictures (and wrappers) no longer count as claimers (#165), so
1835 // the plain orphan pass places the recognized lines directly —
1836 // the detector's lines (#429) the same way.
1837 assemble::add_orphan_regions(&mut regions, &pic_cells);
1838 assemble::add_orphan_regions(&mut regions, &det_cells);
1839 assemble::drop_contained_regulars(&mut regions);
1840 } else if !ocred && !pic_cells.is_empty() {
1841 // Digital page, picture kept: its speculative OCR cells must not
1842 // linger in the text-cell set (they were appended at the tail).
1843 let kept: Vec<layout::Region> = regions
1844 .iter()
1845 .filter(|r| r.label == "picture")
1846 .cloned()
1847 .collect();
1848 let tail = page.cells.split_off(cells_before_pic_ocr);
1849 page.cells.extend(tail.into_iter().filter(|c| {
1850 !kept.iter().any(|r| {
1851 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1852 let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1853 let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1854 ix * iy / ca > 0.5
1855 })
1856 }));
1857 }
1858 // A text-less *table* detected inside a picture on a digital page — a
1859 // screenshot of a table (2203's Figure 10) — has no text layer and no
1860 // scanned-path OCR to feed it, so its grid used to serialize empty and
1861 // the whole element vanished. docling OCRs bitmap-covered areas on
1862 // every page kind and its table cluster collects those cells; mirror
1863 // the scanned path for exactly these tables: recognize word crops and
1864 // feed them to the TableFormer matcher and the cell set.
1865 if !ocred {
1866 let has_text = |t: &layout::Region| {
1867 page.cells.iter().any(|c| {
1868 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1869 let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
1870 let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
1871 !c.text.trim().is_empty() && ix * iy / ca > 0.5
1872 })
1873 };
1874 let in_picture = |t: &layout::Region| {
1875 regions.iter().any(|r| {
1876 r.label == "picture" && {
1877 let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
1878 let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
1879 let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
1880 ix * iy / ta > 0.5
1881 }
1882 })
1883 };
1884 let pic_tables: Vec<layout::Region> = regions
1885 .iter()
1886 .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
1887 .cloned()
1888 .collect();
1889 // Same degradation as above: without OCR the in-picture table
1890 // keeps its structure (TableFormer is geometry-driven) minus text.
1891 if let (false, Some(ocr)) = (pic_tables.is_empty(), self.ocr_model()?) {
1892 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1893 let words = timing::timed("ocr.table_words", || {
1894 ocr.ocr_table_words(img, &pic_tables, scl, None)
1895 })
1896 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1897 ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1898 let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1899 page.cells.extend(words.iter().cloned());
1900 page.word_cells.extend(words);
1901 }
1902 }
1903 // The cells are final: fit every regular region to the cells it
1904 // claims and fold the orphans it now surrounds (#419), before
1905 // TableFormer and the reading order see the boxes.
1906 assemble::fit_regions_to_cells(&mut regions, &page.cells);
1907 Ok(Prepared {
1908 regions,
1909 ocr_confs,
1910 parse,
1911 })
1912 }
1913
1914 /// The stages after TableFormer: enrichment, the page confidence report and
1915 /// assembly into typed nodes.
1916 fn complete_page(
1917 &mut self,
1918 n: usize,
1919 page: &mut PdfPage,
1920 prepared: Prepared,
1921 table_rows: Vec<Option<tf_core::TableGrid>>,
1922 ) -> Result<PageOut, PdfError> {
1923 let Prepared {
1924 regions,
1925 ocr_confs,
1926 parse,
1927 } = prepared;
1928 if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1929 for (i, r) in regions.iter().enumerate() {
1930 eprintln!(
1931 "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
1932 r.label,
1933 r.score,
1934 r.l,
1935 r.t,
1936 r.r,
1937 r.b,
1938 table_rows[i]
1939 .as_ref()
1940 .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
1941 );
1942 }
1943 eprintln!(
1944 "DBG cells={} words={}",
1945 page.cells.len(),
1946 page.word_cells.len()
1947 );
1948 }
1949 // Enrichment passes (opt-in): DocumentPictureClassifier over picture
1950 // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
1951 // shape as TableFormer — one lazily-loaded instance per pipeline, only
1952 // ever locked when a page actually has a matching region.
1953 let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
1954 if let Some(slot) = self.classifier.as_ref() {
1955 if regions.iter().any(|r| r.label == "picture") {
1956 timing::timed("picture_classifier", || {
1957 let mut guard = slot.lock().unwrap();
1958 if matches!(*guard, EnrichSlot::Unloaded) {
1959 *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
1960 Some(m) => EnrichSlot::Ready(m),
1961 None => EnrichSlot::Missing,
1962 };
1963 }
1964 if let EnrichSlot::Ready(model) = &mut *guard {
1965 for (i, r) in regions.iter().enumerate() {
1966 if r.label != "picture" {
1967 continue;
1968 }
1969 let Some(crop) = assemble::crop_region_scaled(
1970 page,
1971 [r.l, r.t, r.r, r.b],
1972 enrich::CLASSIFIER_SCALE,
1973 ) else {
1974 continue;
1975 };
1976 match model.classify(&crop) {
1977 Ok(classes) => {
1978 enrich_out[i] =
1979 Some(assemble::Enrichment::PictureClasses(classes));
1980 }
1981 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1982 }
1983 }
1984 }
1985 });
1986 }
1987 }
1988 if let Some(slot) = self.code_formula.as_ref() {
1989 let wants = |label: &str| {
1990 (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
1991 };
1992 if regions.iter().any(|r| wants(r.label)) {
1993 timing::timed("code_formula", || {
1994 let mut guard = slot.lock().unwrap();
1995 if matches!(*guard, EnrichSlot::Unloaded) {
1996 *guard = match enrich::CodeFormula::load_with(intra_threads()) {
1997 Some(m) => EnrichSlot::Ready(m),
1998 None => EnrichSlot::Missing,
1999 };
2000 }
2001 if let EnrichSlot::Ready(model) = &mut *guard {
2002 for (i, r) in regions.iter().enumerate() {
2003 if !wants(r.label) {
2004 continue;
2005 }
2006 // docling crops the postprocessed cluster box — the
2007 // union of the region's text cells, not the raw
2008 // detector box — expanded by 18% per side, at
2009 // ~120 dpi.
2010 let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
2011 .unwrap_or([r.l, r.t, r.r, r.b]);
2012 let (w, h) = (br - bl, bb - bt);
2013 let ex = enrich::CODE_FORMULA_EXPANSION;
2014 let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
2015 let Some(crop) = assemble::crop_region_scaled(
2016 page,
2017 bbox,
2018 enrich::CODE_FORMULA_SCALE,
2019 ) else {
2020 continue;
2021 };
2022 let kind = if r.label == "code" {
2023 enrich::CodeFormulaKind::Code
2024 } else {
2025 enrich::CodeFormulaKind::Formula
2026 };
2027 match model.predict(&crop, kind) {
2028 Ok(text) => {
2029 enrich_out[i] = Some(match kind {
2030 enrich::CodeFormulaKind::Code => {
2031 let (code, language) =
2032 enrich::extract_code_language(&text);
2033 assemble::Enrichment::Code {
2034 language,
2035 text: code,
2036 }
2037 }
2038 enrich::CodeFormulaKind::Formula => {
2039 assemble::Enrichment::Formula { latex: text }
2040 }
2041 });
2042 }
2043 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
2044 }
2045 }
2046 }
2047 });
2048 }
2049 }
2050 // Score the final region set (docling assigns layout_score over the
2051 // postprocessed clusters — the page elements assemble_page emits,
2052 // which leave out the regulars nested in a picture as its children).
2053 let parents = assemble::picture_parents(®ions);
2054 let elements: Vec<layout::Region> = regions
2055 .iter()
2056 .zip(&parents)
2057 .filter(|(_, p)| p.is_none())
2058 .map(|(r, _)| r.clone())
2059 .collect();
2060 let conf = quality::page_confidence(parse, &elements, &ocr_confs);
2061 let (nodes, links) = timing::timed("assemble_page", || {
2062 assemble::assemble_page(page, regions, &table_rows, &enrich_out, self.images.scale)
2063 });
2064 Ok((nodes, links, conf, self.page_image(n, page)))
2065 }
2066}
2067
2068#[cfg(feature = "ml")]
2069/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
2070/// so on a typical machine two threads per worker (sharing one in-cache copy of
2071/// the weights) extracts more throughput than one fat model or many single-thread
2072/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
2073fn pdf_intra() -> usize {
2074 if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
2075 return n;
2076 }
2077 if intra_threads() >= 2 {
2078 2
2079 } else {
2080 1
2081 }
2082}
2083
2084#[cfg(feature = "ml")]
2085/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
2086/// overrides; otherwise size the pool so `workers × intra ≈ cores`.
2087///
2088/// The pool scales with the machine (#324 follow-up testing): the old hard cap
2089/// of 4 left most of a many-core box idle — on a 16-core M4 Max, 10 workers
2090/// measured ~1.2× over the capped pool (10.0 → 8.5 s on a 130-page document,
2091/// byte-identical output). The ceiling of 16 is a memory bound, not a
2092/// performance one: each worker holds its own layout/OCR sessions (~0.4 GB),
2093/// so a worst-case pool stays under ~6.5 GB even on a ≥32-core host — and
2094/// docling-serve's per-request pools sit behind its `DOCLING_RS_MAX_MEMORY_MB`
2095/// admission control besides. Machines with 4 or fewer effective threads keep
2096/// the exact old sizing (`threads / intra`, min 1).
2097fn pdf_worker_count() -> usize {
2098 if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
2099 return n;
2100 }
2101 (intra_threads() / pdf_intra()).clamp(1, 16)
2102}
2103
2104#[cfg(feature = "ml")]
2105/// Max pages a worker layout-detects with one batched inference call (issue
2106/// #73). Workers drain the work channel opportunistically up to this size —
2107/// whatever is already rendered gets batched, so batching never *waits* for
2108/// pages and adds no latency when rendering is the bottleneck.
2109///
2110/// Default: per-page (1) on the CPU provider, 4 when a CUDA-class GPU
2111/// provider is selected (#338) — CoreML stays per-page (#602,
2112/// [`docling_onnx::prefers_batching`]): only the pinned batch=1 graph is
2113/// static, and static partitions are all CoreML is allowed to take. The old
2114/// "4 on 8+ cores" CPU default was a hypothesis — that single-session
2115/// amortization pays off with a wider thread budget —
2116/// and every actual CPU measurement lands the other way: a 4-core x86 box
2117/// runs the 9-page 2206.01062 fixture in 8.5 s/conv at batch=1 vs 9.3 s at
2118/// batch=4 (re-measured for #338; the original 8.1 vs 9.3 agrees), and the
2119/// issue-#338 report measured batch=1 ~2× faster on a 16-core M4 Max at
2120/// every worker count — batching only adds cache pressure once workers
2121/// saturate the cores. On a GPU the per-call dispatch overhead is real and
2122/// batching amortizes it, so the GPU default stays. Output is bit-identical
2123/// at every batch size, so this is purely a throughput knob.
2124/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides either way; `1` = per-page.
2125pub(crate) fn pdf_layout_batch() -> usize {
2126 env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
2127 .filter(|&n| n > 0)
2128 .unwrap_or_else(|| {
2129 if docling_onnx::prefers_batching() {
2130 4
2131 } else {
2132 1
2133 }
2134 })
2135}
2136
2137#[cfg(feature = "ml")]
2138/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
2139/// the serial primary (running its model on every core) is faster than fanning out
2140/// — the helper pool's one-time model-load cost only pays off once enough pages
2141/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
2142fn pdf_parallel_min() -> usize {
2143 env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
2144 .filter(|&n| n > 0)
2145 .unwrap_or(6)
2146}
2147
2148#[cfg(feature = "ml")]
2149/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
2150/// so a single-page / small / image / METS input is converted at full intra-op
2151/// speed with no pool to load. A document with enough pages instead fans out
2152/// across a **pool** of narrower workers processed concurrently. Both load lazily
2153/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
2154pub struct Pipeline {
2155 /// Full-intra worker for the serial path; loaded on first serial use.
2156 primary: Option<Worker>,
2157 /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
2158 /// path; loaded on first multi-page use and cached.
2159 pool: Vec<Worker>,
2160 /// The single TableFormer instance every worker shares (see [`TfSlot`]).
2161 tables: SharedTables,
2162 /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
2163 classifier: SharedClassifier,
2164 code_formula: SharedCodeFormula,
2165 /// Desired pool size for multi-page documents.
2166 target_workers: usize,
2167 /// Page count at/above which the parallel pool is worth its load cost.
2168 parallel_min: usize,
2169 /// Skip loading/running TableFormer; table regions fall back to geometric
2170 /// reconstruction. See [`Pipeline::no_table_former`].
2171 no_table_former: bool,
2172 /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
2173 no_ocr: bool,
2174 /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
2175 skip_ocr: bool,
2176 /// OCR every page even when it carries a text layer. See
2177 /// [`Pipeline::force_full_page_ocr`].
2178 force_full_page_ocr: bool,
2179 /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
2180 no_text_panels: bool,
2181 /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
2182 enrich: EnrichmentOptions,
2183 /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
2184 page_range: Option<(usize, usize)>,
2185 /// OCR recognition language. See [`Pipeline::ocr_lang`].
2186 ocr_lang: ocr::OcrLang,
2187 /// Which OCR engine runs (#460). See [`Pipeline::ocr_engine`].
2188 ocr_engine: ocr::OcrEngine,
2189 /// Tesseract's languages (#460). See [`Pipeline::tesseract_lang`].
2190 tesseract_lang: Option<String>,
2191 /// Which regions feed the OCR (#254). See [`Pipeline::ocr_mode`].
2192 ocr_mode: ocr::OcrMode,
2193 /// OCR render scale override in px/pt (#254). See [`Pipeline::ocr_scale`].
2194 ocr_scale: Option<f32>,
2195 /// Picture-crop scale and page images (#519/#520). See
2196 /// [`Pipeline::images_scale`] / [`Pipeline::generate_page_images`].
2197 images: ImageOutput,
2198 /// Heading-level inference (#302). See [`Pipeline::heading_hierarchy`].
2199 heading_hierarchy: HeadingHierarchyOptions,
2200 /// Optional per-page progress hook `(done, selected_total)`, invoked after
2201 /// each page finishes on both the serial and parallel buffered paths. Set
2202 /// by the CLI batch mode for dot-progress; `None` costs nothing.
2203 progress: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>,
2204 /// Per-document wall-clock budget (docling's `document_timeout`, #497).
2205 /// See [`Pipeline::document_timeout`].
2206 document_timeout: Option<std::time::Duration>,
2207}
2208
2209#[cfg(feature = "ml")]
2210impl Pipeline {
2211 /// Construct the pipeline. Models load lazily on first use (full-intra primary
2212 /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
2213 /// loaded that a given document doesn't need.
2214 pub fn new() -> Result<Self, PdfError> {
2215 Ok(Self {
2216 primary: None,
2217 pool: Vec::new(),
2218 tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
2219 classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
2220 code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
2221 target_workers: pdf_worker_count(),
2222 parallel_min: pdf_parallel_min(),
2223 no_table_former: false,
2224 no_ocr: false,
2225 skip_ocr: false,
2226 force_full_page_ocr: false,
2227 no_text_panels: false,
2228 enrich: EnrichmentOptions::default(),
2229 page_range: None,
2230 ocr_lang: ocr::OcrLang::from_env(),
2231 ocr_engine: ocr::OcrEngine::from_env(),
2232 tesseract_lang: None,
2233 ocr_mode: ocr::OcrMode::from_env(),
2234 ocr_scale: ocr::scale_from_env(),
2235 images: ImageOutput::default(),
2236 heading_hierarchy: HeadingHierarchyOptions::default(),
2237 progress: None,
2238 document_timeout: None,
2239 })
2240 }
2241
2242 /// A wall-clock budget for each document (docling's
2243 /// `PipelineOptions.document_timeout`, #497; `None` = unlimited, the
2244 /// default). The budget starts when a conversion starts and is checked
2245 /// cooperatively between pages: once it is spent, no further page is
2246 /// rendered or processed, the pages already finished are assembled into
2247 /// the document, and the outcome says so (`Completion::TimedOut`, which
2248 /// the converter reports as `PartialSuccess` with a timeout error, the
2249 /// way docling does). A page in flight finishes — the check costs
2250 /// nothing inside a page, and a single-page document (an image) is never
2251 /// cut. For a long-lived pipeline use
2252 /// [`set_document_timeout`](Self::set_document_timeout) before each
2253 /// conversion.
2254 pub fn document_timeout(mut self, timeout: Option<std::time::Duration>) -> Self {
2255 self.document_timeout = timeout;
2256 self
2257 }
2258
2259 /// In-place variant of [`document_timeout`](Self::document_timeout) for a
2260 /// warm pipeline — set it before every conversion so no request inherits
2261 /// a previous one's budget.
2262 pub fn set_document_timeout(&mut self, timeout: Option<std::time::Duration>) {
2263 self.document_timeout = timeout;
2264 }
2265
2266 /// The deadline of a conversion starting now, from the configured budget.
2267 fn deadline(&self) -> Option<std::time::Instant> {
2268 self.document_timeout.map(|t| std::time::Instant::now() + t)
2269 }
2270
2271 /// The [`Completion`] of a walk that processed `done` of `selected` pages.
2272 fn completion(&self, timed_out: bool, done: usize, selected: usize) -> Completion {
2273 match (timed_out, self.document_timeout) {
2274 (true, Some(budget)) => Completion::TimedOut {
2275 pages_done: done,
2276 pages_selected: selected,
2277 budget,
2278 },
2279 _ => Completion::Complete,
2280 }
2281 }
2282
2283 /// Infer section-header levels after assembly (#302, docling's
2284 /// `HeadingHierarchyModel`): PDF bookmarks > legal/outline numbering >
2285 /// font style, off by default — see [`HeadingHierarchyOptions`]. Pure
2286 /// post-processing configuration; for a warm pipeline use
2287 /// [`set_heading_hierarchy`](Self::set_heading_hierarchy).
2288 pub fn heading_hierarchy(mut self, opts: HeadingHierarchyOptions) -> Self {
2289 self.heading_hierarchy = opts;
2290 self
2291 }
2292
2293 /// In-place variant of [`heading_hierarchy`](Self::heading_hierarchy) for
2294 /// a long-lived pipeline (docling-serve's warm instance) — like
2295 /// [`set_pages`](Self::set_pages), set it before every conversion so no
2296 /// request inherits a previous one's choice.
2297 pub fn set_heading_hierarchy(&mut self, opts: HeadingHierarchyOptions) {
2298 self.heading_hierarchy = opts;
2299 }
2300
2301 /// Run the enabled heading-hierarchy stage (#302) on an assembled
2302 /// document: gather the outline (bookmarks) and the per-page glyph styles
2303 /// on demand, then assign levels in place. `bytes` is `None` on paths
2304 /// with no PDF behind them (standalone images, METS) — those degrade to
2305 /// the numbering signal, exactly like docling without parsed pages.
2306 fn apply_heading_hierarchy(&self, nodes: &mut [Node], bytes: Option<&[u8]>) {
2307 let opts = &self.heading_hierarchy;
2308 if !opts.enabled {
2309 return;
2310 }
2311 let outline = match bytes {
2312 Some(bytes) if opts.use_bookmarks => outline::extract_outline(bytes),
2313 _ => Vec::new(),
2314 };
2315 let styles = match bytes {
2316 Some(bytes) if opts.use_style => {
2317 let pages = heading_hierarchy::heading_pages(nodes);
2318 textparse::glyph_styles(bytes, &pages)
2319 }
2320 _ => Default::default(),
2321 };
2322 heading_hierarchy::apply(nodes, &outline, &styles, opts);
2323 }
2324
2325 /// Install (or clear) the per-page progress hook: called with
2326 /// `(pages_done, pages_selected)` after each page completes during
2327 /// [`convert`](Self::convert). Shared with the parallel workers, so the
2328 /// callback must be cheap and thread-safe.
2329 pub fn set_progress(&mut self, cb: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>) {
2330 self.progress = cb;
2331 }
2332
2333 /// Convert only pages `first..=last` (**1-based**, like the page numbers a
2334 /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
2335 /// skipped before rasterization, so the cost is proportional to the window,
2336 /// not the document. `last` past the end of the document clamps; a window
2337 /// that selects no pages at all (`first` beyond the last page) is an error
2338 /// at convert time. `None` (the default) converts everything.
2339 pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
2340 self.page_range = range;
2341 self
2342 }
2343
2344 /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
2345 /// (e.g. docling-serve's warm instance) that applies a per-request window
2346 /// without rebuilding — unlike the model switches, the window is pure
2347 /// configuration. Set it before every conversion; it stays until changed.
2348 pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
2349 self.page_range = range;
2350 }
2351
2352 /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
2353 /// for the multilingual docling-conformance model. `None` keeps the
2354 /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
2355 /// first conversion; for a warm pipeline use
2356 /// [`set_ocr_lang`](Self::set_ocr_lang).
2357 pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
2358 self.set_ocr_lang(lang);
2359 self
2360 }
2361
2362 /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
2363 /// pipeline (docling-serve's warm instance). Unlike the page window this
2364 /// is a *model* switch: any worker whose cached recognition model was
2365 /// loaded for a different language drops it, to be lazily reloaded on the
2366 /// next OCR-needing page (cheap — the rec models are ~10 MB).
2367 pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
2368 let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
2369 self.ocr_lang = lang;
2370 for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2371 if worker.ocr_lang != lang {
2372 worker.ocr_lang = lang;
2373 worker.ocr = OcrSlot::Unloaded;
2374 }
2375 }
2376 }
2377
2378 /// Which OCR engine recognizes text (#460, see [`OcrEngine`]): the
2379 /// built-in PP-OCRv3 recognizer by default, or the system `tesseract`
2380 /// binary (docling's `TesseractCliOcrOptions`) — same layout-region
2381 /// crops, same cells; Tesseract does its own line/word segmentation and
2382 /// reads orientation from its OSD. `None` keeps the process default
2383 /// (`DOCLING_RS_OCR_ENGINE`, else PP-OCR). Set before the first
2384 /// conversion; for a warm pipeline use
2385 /// [`set_ocr_engine`](Self::set_ocr_engine).
2386 pub fn ocr_engine(mut self, engine: Option<ocr::OcrEngine>) -> Self {
2387 self.set_ocr_engine(engine);
2388 self
2389 }
2390
2391 /// In-place variant of [`ocr_engine`](Self::ocr_engine): a model switch
2392 /// like [`set_ocr_lang`](Self::set_ocr_lang) — workers holding the other
2393 /// engine drop it, to be lazily reloaded.
2394 pub fn set_ocr_engine(&mut self, engine: Option<ocr::OcrEngine>) {
2395 let engine = engine.unwrap_or_else(ocr::OcrEngine::from_env);
2396 self.ocr_engine = engine;
2397 for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2398 if worker.ocr_engine != engine {
2399 worker.ocr_engine = engine;
2400 worker.ocr = OcrSlot::Unloaded;
2401 }
2402 }
2403 }
2404
2405 /// Tesseract's languages (#460): the `-l` argument, tessdata stems joined
2406 /// with `+` — build it from an `ocr_lang` value with
2407 /// [`tesseract_lang_arg`], which also maps BCP-47 tags and the PP-OCR
2408 /// codes. `None` runs Tesseract's default (`eng`). Ignored under the
2409 /// PP-OCR engine, whose language is [`ocr_lang`](Self::ocr_lang). For a
2410 /// warm pipeline use [`set_tesseract_lang`](Self::set_tesseract_lang).
2411 pub fn tesseract_lang(mut self, lang: Option<String>) -> Self {
2412 self.set_tesseract_lang(lang);
2413 self
2414 }
2415
2416 /// In-place variant of [`tesseract_lang`](Self::tesseract_lang): a model
2417 /// switch like [`set_ocr_lang`](Self::set_ocr_lang) — a worker whose
2418 /// Tesseract was probed for other languages drops it.
2419 pub fn set_tesseract_lang(&mut self, lang: Option<String>) {
2420 self.tesseract_lang = lang.clone();
2421 for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2422 if worker.tesseract_lang != lang {
2423 worker.tesseract_lang = lang.clone();
2424 if worker.ocr_engine == ocr::OcrEngine::Tesseract {
2425 worker.ocr = OcrSlot::Unloaded;
2426 }
2427 }
2428 }
2429 }
2430
2431 /// Resolve the configured 1-based window against a page count into the
2432 /// 0-based inclusive form the backend walks, validating it selects at
2433 /// least one existing page.
2434 fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
2435 let Some((first, last)) = self.page_range else {
2436 return Ok(None);
2437 };
2438 if first == 0 || last < first {
2439 return Err(PdfError::Pdfium(format!(
2440 "invalid page range {first}-{last} (pages are 1-based, first <= last)"
2441 )));
2442 }
2443 if first > total {
2444 return Err(PdfError::Pdfium(format!(
2445 "page range {first}-{last} is outside the document ({total} page(s))"
2446 )));
2447 }
2448 Ok(Some((first - 1, last.min(total) - 1)))
2449 }
2450
2451 /// Enable the opt-in enrichment passes (docling's
2452 /// `do_picture_classification` / `do_code_enrichment` /
2453 /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
2454 /// the first matching region; a missing model warns once and is skipped.
2455 /// Set before the first conversion (no effect on already-loaded workers).
2456 pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
2457 self.enrich = opts;
2458 self
2459 }
2460
2461 /// Skip loading and running the TableFormer table-structure model. Table
2462 /// regions still get emitted, but reconstructed geometrically from cell
2463 /// positions instead of via the ONNX model's predicted structure — faster
2464 /// (no model load, no per-table inference) at the cost of table fidelity.
2465 /// No effect if a worker is already loaded; set this before the first
2466 /// conversion.
2467 pub fn no_table_former(mut self, disable: bool) -> Self {
2468 self.no_table_former = disable;
2469 self
2470 }
2471
2472 /// Keep every detected `picture` region as a picture. By default an
2473 /// *uncaptioned* picture that reads like a dense, uniform text panel (a
2474 /// terms-and-conditions box exported as an image) is demoted into
2475 /// paragraphs (#157); a chart the layout mislabels can still trip that
2476 /// heuristic on scanned pages, and image-extraction workflows may simply
2477 /// want every crop — this flag disables the demotion entirely (#173).
2478 /// No effect on already-loaded workers; set before the first conversion.
2479 pub fn no_text_panels(mut self, disable: bool) -> Self {
2480 self.no_text_panels = disable;
2481 self
2482 }
2483
2484 /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
2485 /// inference of any kind. The PDF's embedded text cells are grouped by line
2486 /// and emitted as plain paragraphs in reading order: no headings, lists,
2487 /// tables, code blocks, or pictures, since that structure comes from the
2488 /// layout model. The fastest possible PDF path, but pages with no embedded
2489 /// text layer (scanned/image-only PDFs) yield no text at all — convert those
2490 /// without this flag. Implies `no_table_former`. No effect if a worker is
2491 /// already loaded; set this before the first conversion.
2492 pub fn no_ocr(mut self, disable: bool) -> Self {
2493 self.no_ocr = disable;
2494 self
2495 }
2496
2497 /// Never run OCR, but keep layout detection and TableFormer — docling's
2498 /// independent `do_ocr=False` (#244), the counterpart of
2499 /// [`no_table_former`](Self::no_table_former). Unlike
2500 /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
2501 /// output — headings, tables, pictures, reading order — is preserved;
2502 /// only text that exists solely as pixels is lost: scanned pages come
2503 /// back with their regions empty, and the speculative OCR of large
2504 /// embedded images never runs. The OCR model is never loaded. Ignored
2505 /// when `no_ocr` is set (there is no OCR to skip);
2506 /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
2507 /// mirroring docling where forcing is a sub-option of `do_ocr`.
2508 pub fn skip_ocr(mut self, disable: bool) -> Self {
2509 self.skip_ocr = disable;
2510 self
2511 }
2512
2513 /// OCR every page from its rendered image even when the page carries an
2514 /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
2515 /// for text layers that exist but lie: broken encodings, subset fonts with
2516 /// garbage mappings, a scanned form with a few typed-in fields. Ignored
2517 /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
2518 /// `force_full_page_ocr` is a sub-option of `do_ocr`).
2519 pub fn force_full_page_ocr(mut self, force: bool) -> Self {
2520 self.force_full_page_ocr = force;
2521 self
2522 }
2523
2524 /// Which document regions feed the OCR — docling's `OcrMode` (#254). The
2525 /// default (`default` = `pdf_aware_layout_regions`) is the standard
2526 /// text-layer-aware behavior; `full_page`/`layout_regions` discard the
2527 /// text layer like [`force_full_page_ocr`](Self::force_full_page_ocr)
2528 /// (see [`ocr::OcrMode`] for why both map onto it). Whichever of the flag
2529 /// and the mode demands forcing wins, mirroring docling's
2530 /// `force_full_page_ocr` → `mode=full_page` bridge. `None` keeps the
2531 /// process default (`DOCLING_RS_OCR_MODE`, else `default`).
2532 pub fn ocr_mode(mut self, mode: Option<ocr::OcrMode>) -> Self {
2533 self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
2534 self
2535 }
2536
2537 /// In-place variants of [`force_full_page_ocr`](Self::force_full_page_ocr),
2538 /// [`ocr_mode`](Self::ocr_mode) and [`ocr_scale`](Self::ocr_scale) for a
2539 /// long-lived pipeline (docling-serve's warm instance): all three are pure
2540 /// per-worker configuration — no model reloads — so they apply per request
2541 /// like [`set_pages`](Self::set_pages). Set them before every conversion so
2542 /// no request inherits a previous one's choice.
2543 pub fn set_force_full_page_ocr(&mut self, force: bool) {
2544 self.force_full_page_ocr = force;
2545 self.sync_ocr_config();
2546 }
2547
2548 /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
2549 pub fn set_ocr_mode(&mut self, mode: Option<ocr::OcrMode>) {
2550 self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
2551 self.sync_ocr_config();
2552 }
2553
2554 /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
2555 pub fn set_ocr_scale(&mut self, scale: Option<f32>) {
2556 self.ocr_scale = scale
2557 .filter(|s| s.is_finite() && *s > 0.0)
2558 .or_else(ocr::scale_from_env);
2559 self.sync_ocr_config();
2560 }
2561
2562 /// Whether page extraction should decode the text layer at all. Forced
2563 /// full-page OCR (the flag or `ocr_mode=full_page|layout_regions`) clears
2564 /// every extracted cell unread, so the decode is skipped outright —
2565 /// docling#4061's `skip_cell_extraction` (2.122). `no_ocr` wins over the
2566 /// forcing, as everywhere else: its fast path *is* the text layer.
2567 fn extract_text_layer(&self) -> bool {
2568 self.no_ocr || !(self.force_full_page_ocr || self.ocr_mode.forces_full_page())
2569 }
2570
2571 /// Push the current OCR forcing/scale choice onto already-loaded workers
2572 /// (new workers read it at [`Worker::load`]).
2573 fn sync_ocr_config(&mut self) {
2574 let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2575 let scale = self.ocr_scale;
2576 for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2577 worker.force_full_page_ocr = force;
2578 worker.ocr_scale = scale;
2579 }
2580 }
2581
2582 /// Pixels per PDF point for picture crops and page images — docling's
2583 /// `images_scale` (#519/#520). `None` (the default) delivers crops at the
2584 /// pipeline's own page render, 2.0 px/pt (144 dpi), untouched. Another
2585 /// value resamples that render (CatmullRom, docling's PIL BICUBIC), so
2586 /// values above 2.0 upsample rather than re-render. Each picture's
2587 /// `dpi` (docling-core's `ImageRef.dpi`) is 72·scale, so consumers mapping
2588 /// pixels back to points stay exact. Layout, OCR and TableFormer inputs
2589 /// are unaffected. Non-positive values are ignored.
2590 pub fn images_scale(mut self, scale: Option<f32>) -> Self {
2591 self.set_images(ImageOutput {
2592 scale,
2593 ..self.images
2594 });
2595 self
2596 }
2597
2598 /// Keep each page's render as the document's page image — docling's
2599 /// `generate_page_images` (#520): the JSON export writes it as the page's
2600 /// `image` (docling-core's `PageItem.image`, at [`Self::images_scale`],
2601 /// `dpi` = 72·scale), which is what docling-core's
2602 /// `TableItem.get_image` / `FormulaItem.get_image` crop from. Off by
2603 /// default: a page image is a full-page PNG per page held in memory.
2604 /// Pages converted with `no_ocr` (text layer only) are never rendered and
2605 /// get none; streaming conversions carry no page map and drop them.
2606 pub fn generate_page_images(mut self, enabled: bool) -> Self {
2607 self.set_images(ImageOutput {
2608 page_images: enabled,
2609 ..self.images
2610 });
2611 self
2612 }
2613
2614 /// Both image outputs at once, also on already-loaded workers — the
2615 /// per-request form a warm pipeline (serve, the Node `Pipeline`) uses,
2616 /// like [`set_ocr_scale`](Self::set_ocr_scale). A non-finite or
2617 /// non-positive scale reads as unset.
2618 pub fn set_images(&mut self, images: ImageOutput) {
2619 self.images = ImageOutput {
2620 scale: images.scale.filter(|s| s.is_finite() && *s > 0.0),
2621 ..images
2622 };
2623 let images = self.images;
2624 for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2625 worker.images = images;
2626 }
2627 }
2628
2629 /// OCR render scale in pixels per PDF point — docling's `OcrOptions.scale`
2630 /// (#254, upstream docling#3877; their default 3 = 216 dpi). `None`
2631 /// (default: `DOCLING_RS_OCR_SCALE`, else unset) feeds the recognizer the
2632 /// pipeline's own page render (2.0 px/pt = 144 dpi) for a rendered page,
2633 /// and for a standalone image input docling's own resolution (#570): 3
2634 /// px/pt shrunk so the longer side stays within RapidOCR's 2000 px — what
2635 /// its models see after RapidOCR's `max_side_len` pass (a 754 × 1000 scan
2636 /// reads at 2.0). A set value resamples the render / image for the OCR
2637 /// input only — layout and TableFormer keep their pinned-resolution
2638 /// pixels, so the conformance baseline never moves. Lower it when the
2639 /// source raster is already high-resolution and upscaling degrades
2640 /// recognition; raise it toward docling's 216 dpi for parity experiments.
2641 /// Non-positive values are ignored.
2642 pub fn ocr_scale(mut self, scale: Option<f32>) -> Self {
2643 self.ocr_scale = scale
2644 .filter(|s| s.is_finite() && *s > 0.0)
2645 .or_else(ocr::scale_from_env);
2646 self
2647 }
2648
2649 /// The shared TableFormer slot handed to each worker, or `None` when the
2650 /// pipeline options skip TableFormer entirely.
2651 fn tables_slot(&self) -> Option<SharedTables> {
2652 if self.no_table_former || self.no_ocr {
2653 None
2654 } else {
2655 Some(Arc::clone(&self.tables))
2656 }
2657 }
2658
2659 /// The shared enrichment slots for a worker (`None` per model unless its
2660 /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
2661 fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
2662 if self.no_ocr || !self.enrich.any() {
2663 return (None, None);
2664 }
2665 (
2666 self.enrich
2667 .picture_classification
2668 .then(|| Arc::clone(&self.classifier)),
2669 (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
2670 )
2671 }
2672
2673 /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
2674 /// the shared TableFormer unless disabled) so the first conversion doesn't pay
2675 /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
2676 /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
2677 /// `DocumentConverter.initialize_pipeline`.
2678 pub fn warm_up(&mut self) -> Result<(), PdfError> {
2679 self.primary()?;
2680 // The shared TableFormer loads on the first table otherwise — a
2681 // document with one would still pay for it (#548).
2682 if let Some(tables) = self.tables_slot() {
2683 tables.lock().unwrap_or_else(|p| p.into_inner()).load();
2684 }
2685 Ok(())
2686 }
2687
2688 /// [`warm_up`](Self::warm_up) plus the parallel page-worker pool, so the
2689 /// first *multi-page* conversion is no slower than later ones either: a
2690 /// document of `DOCLING_RS_PDF_PARALLEL_MIN` pages (6) or more fans out across the pool,
2691 /// whose workers each load their own layout/OCR sessions on first use
2692 /// (#548 — docling-serve's `--warmup` left a 9-page PDF paying that load).
2693 /// Costs the pool's memory up front (~0.4 GB a worker); with a pool of one
2694 /// worker it is exactly `warm_up`.
2695 pub fn warm_up_all(&mut self) -> Result<(), PdfError> {
2696 self.warm_up()?;
2697 if self.target_workers >= 2 {
2698 self.ensure_pool()?;
2699 }
2700 Ok(())
2701 }
2702
2703 /// The full-intra serial worker, loaded on first use.
2704 fn primary(&mut self) -> Result<&mut Worker, PdfError> {
2705 if self.primary.is_none() {
2706 self.primary = Some(Worker::load(
2707 intra_threads(),
2708 self.tables_slot(),
2709 self.enrich_slots(),
2710 self.enrich,
2711 self.no_ocr,
2712 self.skip_ocr,
2713 // The mode-shaped spelling (#254) and the flag are one engine
2714 // truth: whichever demands forcing wins, mirroring docling's
2715 // `force_full_page_ocr` → `mode=full_page` bridge.
2716 self.force_full_page_ocr || self.ocr_mode.forces_full_page(),
2717 self.no_text_panels,
2718 self.ocr_lang,
2719 self.ocr_engine,
2720 self.tesseract_lang.clone(),
2721 self.ocr_scale,
2722 self.images,
2723 )?);
2724 }
2725 Ok(self.primary.as_mut().unwrap())
2726 }
2727
2728 /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
2729 /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
2730 /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
2731 /// fans the pages out across the worker pool, reassembled in page order so the
2732 /// output is byte-identical to the serial path.
2733 pub fn convert(
2734 &mut self,
2735 bytes: &[u8],
2736 password: Option<&str>,
2737 name: &str,
2738 ) -> Result<DoclingDocument, PdfError> {
2739 self.convert_outcome(bytes, password, name)
2740 .map(|c| c.document)
2741 }
2742
2743 /// [`convert`](Self::convert) that also says how the conversion ended —
2744 /// whether the [`document_timeout`](Self::document_timeout) cut it short
2745 /// and how many pages made it (`Completion`).
2746 pub fn convert_outcome(
2747 &mut self,
2748 bytes: &[u8],
2749 password: Option<&str>,
2750 name: &str,
2751 ) -> Result<Converted, PdfError> {
2752 let deadline = self.deadline();
2753 let pages = pdfium_backend::page_count(bytes, password)?;
2754 let range = self.resolve_range(pages)?;
2755 // Serial vs parallel is decided by the pages actually converted: a
2756 // 3-page window over a 500-page PDF should not pay the pool load.
2757 let selected = range.map_or(pages, |(a, b)| b - a + 1);
2758 let (document, done, timed_out) =
2759 if self.target_workers >= 2 && selected >= self.parallel_min {
2760 self.convert_parallel(bytes, password, name, range, selected, deadline)?
2761 } else {
2762 self.convert_serial(bytes, password, name, range, selected, deadline)?
2763 };
2764 timing::report();
2765 Ok(Converted {
2766 document,
2767 completion: self.completion(timed_out, done, selected),
2768 })
2769 }
2770
2771 /// Stream pages one at a time through the primary worker — render → process →
2772 /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
2773 fn convert_serial(
2774 &mut self,
2775 bytes: &[u8],
2776 password: Option<&str>,
2777 name: &str,
2778 range: Option<(usize, usize)>,
2779 selected: usize,
2780 deadline: Option<std::time::Instant>,
2781 ) -> Result<(DoclingDocument, usize, bool), PdfError> {
2782 let mut doc = DoclingDocument::new(name);
2783 let mut confs = std::collections::BTreeMap::new();
2784 let render_image = !self.no_ocr;
2785 let extract_text = self.extract_text_layer();
2786 let progress = self.progress.clone();
2787 let mut done = 0usize;
2788 let worker = self.primary()?;
2789 // The walk renders a page before handing it over, so the budget is
2790 // checked where a page *arrives*: a page the budget had already run
2791 // out on is dropped unprocessed and ends the walk through the
2792 // sentinel (`for_each_page` reads it as an error; here it is the cut).
2793 let walk = pdfium_backend::for_each_page(
2794 bytes,
2795 password,
2796 render_image,
2797 extract_text,
2798 range,
2799 |n, _total, mut page| {
2800 if expired(deadline) {
2801 return Err(timeout_sentinel());
2802 }
2803 let (mut nodes, links, conf, page_image) = worker.process(n, &mut page)?;
2804 assemble::stamp_page_no(&mut nodes, n + 1);
2805 if let Some(img) = page_image {
2806 doc.page_images.insert(n + 1, img);
2807 }
2808 doc.nodes.extend(nodes);
2809 doc.links.extend(links);
2810 confs.insert(n + 1, conf);
2811 done += 1;
2812 if let Some(cb) = &progress {
2813 cb(done, selected);
2814 }
2815 Ok::<(), PdfError>(())
2816 },
2817 );
2818 let timed_out = match walk {
2819 Ok(()) => false,
2820 Err(PdfError::Timeout(_)) => true,
2821 Err(e) => return Err(e),
2822 };
2823 assemble::merge_continuations(&mut doc.nodes);
2824 self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
2825 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2826 Ok((doc, done, timed_out))
2827 }
2828
2829 /// Render pages serially on this thread (pdfium) and process them in parallel
2830 /// across the worker pool. A bounded channel applies backpressure so only a
2831 /// handful of page bitmaps are resident at once; results carry their page
2832 /// index and are reassembled in order, so the output is byte-identical to the
2833 /// serial path.
2834 fn convert_parallel(
2835 &mut self,
2836 bytes: &[u8],
2837 password: Option<&str>,
2838 name: &str,
2839 range: Option<(usize, usize)>,
2840 selected: usize,
2841 deadline: Option<std::time::Instant>,
2842 ) -> Result<(DoclingDocument, usize, bool), PdfError> {
2843 self.ensure_pool()?;
2844 let progress = self.progress.clone();
2845 let pages_done = std::sync::atomic::AtomicUsize::new(0);
2846 let timed_out = std::sync::atomic::AtomicBool::new(false);
2847 let n_workers = self.pool.len();
2848 let render_image = !self.no_ocr;
2849 let extract_text = self.extract_text_layer();
2850 let layout_batch = pdf_layout_batch();
2851 // Bound sized so every worker can accumulate a full layout batch while
2852 // rendering stays ahead (and never below the pre-#73 render-ahead of
2853 // two pages per worker); still a hard cap on resident page bitmaps.
2854 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2855 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2856 let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
2857 let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
2858
2859 // Move the pool into the scope so each worker gets an exclusive `&mut`.
2860 let mut workers = std::mem::take(&mut self.pool);
2861 std::thread::scope(|s| {
2862 for worker in workers.iter_mut() {
2863 let work_rx = Arc::clone(&work_rx);
2864 let results = Arc::clone(&results);
2865 let first_err = Arc::clone(&first_err);
2866 let progress = progress.clone();
2867 let pages_done = &pages_done;
2868 let timed_out = &timed_out;
2869 s.spawn(move || {
2870 worker.run_pool(&work_rx, layout_batch, deadline, |idx, out| {
2871 match out {
2872 Ok(out) => {
2873 results.lock().unwrap().push((idx, out));
2874 let d = pages_done
2875 .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2876 + 1;
2877 if let Some(cb) = &progress {
2878 cb(d, selected);
2879 }
2880 }
2881 // The budget ran out before this page's turn: the
2882 // page is left out, the document is partial.
2883 Err(PdfError::Timeout(_)) => {
2884 timed_out.store(true, std::sync::atomic::Ordering::Relaxed);
2885 }
2886 Err(e) => {
2887 let mut slot = first_err.lock().unwrap();
2888 if slot.is_none() {
2889 *slot = Some(e);
2890 }
2891 }
2892 }
2893 true
2894 });
2895 });
2896 }
2897 // Render on this thread and feed the workers; backpressure blocks here
2898 // when the channel is full. Dropping `work_tx` afterwards signals the
2899 // workers (recv → Err) to finish. A spent budget ends the walk before
2900 // the next page is rendered.
2901 let render = pdfium_backend::for_each_page(
2902 bytes,
2903 password,
2904 render_image,
2905 extract_text,
2906 range,
2907 |i, _total, page| {
2908 if expired(deadline) {
2909 return Err(timeout_sentinel());
2910 }
2911 work_tx
2912 .send((i, page))
2913 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2914 },
2915 );
2916 drop(work_tx);
2917 match render {
2918 Ok(()) => {}
2919 Err(PdfError::Timeout(_)) => {
2920 timed_out.store(true, std::sync::atomic::Ordering::Relaxed);
2921 }
2922 Err(e) => {
2923 let mut slot = first_err.lock().unwrap();
2924 if slot.is_none() {
2925 *slot = Some(e);
2926 }
2927 }
2928 }
2929 });
2930 // Threads have joined; restore the pool for the next conversion.
2931 self.pool = workers;
2932
2933 if let Some(e) = first_err.lock().unwrap().take() {
2934 return Err(e);
2935 }
2936 let mut results = Arc::try_unwrap(results)
2937 .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
2938 .into_inner()
2939 .unwrap();
2940 results.sort_by_key(|(idx, _)| *idx);
2941 let done = results.len();
2942 let mut doc = DoclingDocument::new(name);
2943 let mut confs = std::collections::BTreeMap::new();
2944 for (idx, (mut nodes, links, conf, page_image)) in results {
2945 assemble::stamp_page_no(&mut nodes, idx + 1);
2946 if let Some(img) = page_image {
2947 doc.page_images.insert(idx + 1, img);
2948 }
2949 doc.nodes.extend(nodes);
2950 doc.links.extend(links);
2951 confs.insert(idx + 1, conf);
2952 }
2953 assemble::merge_continuations(&mut doc.nodes);
2954 self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
2955 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2956 let timed_out = timed_out.load(std::sync::atomic::Ordering::Relaxed);
2957 Ok((doc, done, timed_out))
2958 }
2959
2960 /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
2961 /// in-document-order batch of nodes (and that span's recovered links) as pages
2962 /// complete, so a caller can serialize Markdown page by page instead of waiting
2963 /// for the whole document. The batches are exactly the buffered [`convert`]'s
2964 /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
2965 /// parallel path reorders pages back into document order before emitting, so
2966 /// the output is identical regardless of worker scheduling.
2967 ///
2968 /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
2969 /// and its backpressure throttles the whole pipeline. Returning `Err` from
2970 /// `emit` aborts the conversion with that error.
2971 pub fn convert_streaming<F>(
2972 &mut self,
2973 bytes: &[u8],
2974 password: Option<&str>,
2975 name: &str,
2976 emit: F,
2977 ) -> Result<(), PdfError>
2978 where
2979 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2980 {
2981 self.convert_streaming_outcome(bytes, password, name, emit)
2982 .map(|_| ())
2983 }
2984
2985 /// [`convert_streaming`](Self::convert_streaming) that also says how the
2986 /// conversion ended ([`Completion`]): a spent
2987 /// [`document_timeout`](Self::document_timeout) stops the walk, the pages
2988 /// finished so far are emitted (the tail included) and the outcome is
2989 /// `TimedOut` — never an error.
2990 pub fn convert_streaming_outcome<F>(
2991 &mut self,
2992 bytes: &[u8],
2993 password: Option<&str>,
2994 name: &str,
2995 emit: F,
2996 ) -> Result<Completion, PdfError>
2997 where
2998 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2999 {
3000 let _ = name; // page nodes carry no name; the caller owns the document name.
3001 let deadline = self.deadline();
3002 let pages = pdfium_backend::page_count(bytes, password)?;
3003 let range = self.resolve_range(pages)?;
3004 let selected = range.map_or(pages, |(a, b)| b - a + 1);
3005 let r = if self.target_workers >= 2 && selected >= self.parallel_min {
3006 self.convert_streaming_parallel(bytes, password, range, deadline, emit)
3007 } else {
3008 self.convert_streaming_serial(bytes, password, range, deadline, emit)
3009 };
3010 timing::report();
3011 let (done, timed_out) = r?;
3012 Ok(self.completion(timed_out, done, selected))
3013 }
3014
3015 /// Serial streaming: render → process → emit, one page at a time, holding back
3016 /// only the tail that might still merge into the next page.
3017 fn convert_streaming_serial<F>(
3018 &mut self,
3019 bytes: &[u8],
3020 password: Option<&str>,
3021 range: Option<(usize, usize)>,
3022 deadline: Option<std::time::Instant>,
3023 mut emit: F,
3024 ) -> Result<(usize, bool), PdfError>
3025 where
3026 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
3027 {
3028 let mut asm = assemble::StreamAssembler::new();
3029 let render_image = !self.no_ocr;
3030 let extract_text = self.extract_text_layer();
3031 let worker = self.primary()?;
3032 let mut done = 0usize;
3033 let walk = pdfium_backend::for_each_page(
3034 bytes,
3035 password,
3036 render_image,
3037 extract_text,
3038 range,
3039 |n, _total, mut page| {
3040 if expired(deadline) {
3041 return Err(timeout_sentinel());
3042 }
3043 // Confidence is dropped on the streaming path: the report is
3044 // only complete once every page has run, which defeats
3045 // page-by-page emission — buffered `convert` carries it.
3046 let (nodes, links, _conf, _page_image) = worker.process(n, &mut page)?;
3047 done += 1;
3048 emit(asm.push(nodes), links)
3049 },
3050 );
3051 let timed_out = match walk {
3052 Ok(()) => false,
3053 Err(PdfError::Timeout(_)) => true,
3054 Err(e) => return Err(e),
3055 };
3056 emit(asm.finish(), Vec::new())?;
3057 Ok((done, timed_out))
3058 }
3059
3060 /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
3061 /// not thread-safe) and process across the worker pool; results carry their
3062 /// page index and are reordered on the calling thread into a
3063 /// [`assemble::StreamAssembler`], which emits each page in document order as
3064 /// soon as its predecessors have arrived. Bounded channels keep only a handful
3065 /// of pages resident and let `emit`'s backpressure reach the renderer.
3066 fn convert_streaming_parallel<F>(
3067 &mut self,
3068 bytes: &[u8],
3069 password: Option<&str>,
3070 range: Option<(usize, usize)>,
3071 deadline: Option<std::time::Instant>,
3072 mut emit: F,
3073 ) -> Result<(usize, bool), PdfError>
3074 where
3075 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
3076 {
3077 self.ensure_pool()?;
3078 let n_workers = self.pool.len();
3079 let render_image = !self.no_ocr;
3080 let extract_text = self.extract_text_layer();
3081 let layout_batch = pdf_layout_batch();
3082 // Bound sized so every worker can accumulate a full layout batch while
3083 // rendering stays ahead (and never below the pre-#73 render-ahead of
3084 // two pages per worker); still a hard cap on resident page bitmaps.
3085 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
3086 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
3087 // Workers and the renderer report here; the calling thread drains it in
3088 // page order. Bounded so workers block (bounding resident bitmaps) when the
3089 // consumer falls behind.
3090 let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
3091
3092 let mut workers = std::mem::take(&mut self.pool);
3093 let mut asm = assemble::StreamAssembler::new();
3094 let mut first_err: Option<PdfError> = None;
3095 let mut timed_out = false;
3096 let mut done = 0usize;
3097
3098 std::thread::scope(|s| {
3099 // Workers: pull a batch of pages (whatever is already rendered, up
3100 // to the layout batch size), process it, report (index-tagged)
3101 // results.
3102 for worker in workers.iter_mut() {
3103 let work_rx = Arc::clone(&work_rx);
3104 let res_tx = res_tx.clone();
3105 s.spawn(move || {
3106 worker.run_pool(&work_rx, layout_batch, deadline, |idx, out| {
3107 // `false` once the consumer is gone.
3108 res_tx.send(out.map(|o| (idx, o))).is_ok()
3109 });
3110 });
3111 }
3112 // Renderer: feed pages to the pool on its own thread (pdfium stays on a
3113 // single thread); report a render error through the same channel. A
3114 // spent budget ends the walk before the next page is rendered.
3115 {
3116 let res_tx = res_tx.clone();
3117 s.spawn(move || {
3118 let render = pdfium_backend::for_each_page(
3119 bytes,
3120 password,
3121 render_image,
3122 extract_text,
3123 range,
3124 |i, _total, page| {
3125 if expired(deadline) {
3126 return Err(timeout_sentinel());
3127 }
3128 work_tx
3129 .send((i, page))
3130 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
3131 },
3132 );
3133 drop(work_tx); // signal workers to finish
3134 if let Err(e) = render {
3135 let _ = res_tx.send(Err(e));
3136 }
3137 });
3138 }
3139 // Drop our own sender so the channel closes once the threads finish.
3140 drop(res_tx);
3141
3142 // Collector (this thread): reorder into document order and emit.
3143 // With a page window, indices start at the window's first page.
3144 // A timed-out page leaves a hole in the sequence: everything
3145 // before it emits in order, the pages after it stay buffered —
3146 // they are the pages the budget did not cover, and the document
3147 // ends at the cut like the buffered path's.
3148 let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
3149 let mut next = range.map_or(0, |(first, _)| first);
3150 for msg in res_rx.iter() {
3151 match msg {
3152 Err(PdfError::Timeout(_)) => timed_out = true,
3153 Err(e) => {
3154 if first_err.is_none() {
3155 first_err = Some(e);
3156 }
3157 }
3158 Ok((idx, out)) => {
3159 buffer.insert(idx, out);
3160 if first_err.is_some() {
3161 continue; // keep draining so the threads can exit
3162 }
3163 // A stream carries Markdown, not the page map: page
3164 // images (#520) have nowhere to go and are dropped.
3165 while let Some((nodes, links, _conf, _page_image)) = buffer.remove(&next) {
3166 if let Err(e) = emit(asm.push(nodes), links) {
3167 first_err = Some(e);
3168 break;
3169 }
3170 next += 1;
3171 done += 1;
3172 }
3173 }
3174 }
3175 }
3176 // Pages that finished after a hole (a page the budget skipped
3177 // before them) cannot follow it in document order; count them
3178 // out of the document like the skipped one.
3179 if timed_out && !buffer.is_empty() {
3180 buffer.clear();
3181 }
3182 });
3183 // Threads have joined; restore the pool for the next conversion.
3184 self.pool = workers;
3185
3186 if let Some(e) = first_err {
3187 return Err(e);
3188 }
3189 emit(asm.finish(), Vec::new())?;
3190 Ok((done, timed_out))
3191 }
3192
3193 /// Lazily grow the pool to `target_workers`, loading the new workers
3194 /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
3195 /// one load's wall-time). Cached for reuse across documents.
3196 fn ensure_pool(&mut self) -> Result<(), PdfError> {
3197 let need = self.target_workers.saturating_sub(self.pool.len());
3198 if need == 0 {
3199 return Ok(());
3200 }
3201 let intra = pdf_intra();
3202 let no_ocr = self.no_ocr;
3203 let skip_ocr = self.skip_ocr;
3204 let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
3205 let ntp = self.no_text_panels;
3206 let ocr_lang = self.ocr_lang;
3207 let ocr_engine = self.ocr_engine;
3208 let tesseract_lang = self.tesseract_lang.clone();
3209 let ocr_scale = self.ocr_scale;
3210 let images = self.images;
3211 let enrich = self.enrich;
3212 let tables = self.tables_slot();
3213 let enrich_slots = self.enrich_slots();
3214 let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
3215 let handles: Vec<_> = (0..need)
3216 .map(|_| {
3217 let tables = tables.clone();
3218 let enrich_slots = enrich_slots.clone();
3219 let tesseract_lang = tesseract_lang.clone();
3220 s.spawn(move || {
3221 Worker::load(
3222 intra,
3223 tables,
3224 enrich_slots,
3225 enrich,
3226 no_ocr,
3227 skip_ocr,
3228 force,
3229 ntp,
3230 ocr_lang,
3231 ocr_engine,
3232 tesseract_lang,
3233 ocr_scale,
3234 images,
3235 )
3236 })
3237 })
3238 .collect();
3239 handles.into_iter().map(|h| h.join().unwrap()).collect()
3240 });
3241 for w in loaded {
3242 self.pool.push(w?);
3243 }
3244 Ok(())
3245 }
3246
3247 /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
3248 /// docling routes images through the same layout+OCR pipeline as a PDF page.
3249 pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
3250 let image = decode_image_limited(bytes)?;
3251 let (w, h) = image.dimensions();
3252 // The image is its own page rendered at 1 px per "point" (scale 1.0); a
3253 // standalone image has no text layer, so OCR supplies the cells.
3254 let page = PdfPage {
3255 width: w as f32,
3256 height: h as f32,
3257 scale: 1.0,
3258 cells: Vec::new(),
3259 code_cells: Vec::new(),
3260 checkboxes: Vec::new(),
3261 word_cells: Vec::new(),
3262 // A standalone image *is* its own scale-1.0 page image, so the
3263 // layout model sees it through the docling-exact PIL kernel.
3264 image_layout: Some(image.clone()),
3265 image,
3266 links: Vec::new(),
3267 rotation: 0,
3268 };
3269 self.process_pages(vec![page], name)
3270 }
3271
3272 /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
3273 /// page (image / METS inputs, which are small and already materialised).
3274 /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
3275 /// caller-configured pipeline (#244).
3276 pub fn process_pages(
3277 &mut self,
3278 mut pages: Vec<PdfPage>,
3279 name: &str,
3280 ) -> Result<DoclingDocument, PdfError> {
3281 let mut doc = DoclingDocument::new(name);
3282 let mut confs = std::collections::BTreeMap::new();
3283 let worker = self.primary()?;
3284 for (n, page) in pages.iter_mut().enumerate() {
3285 let (mut nodes, links, conf, page_image) = worker.process(n, page)?;
3286 assemble::stamp_page_no(&mut nodes, n + 1);
3287 if let Some(img) = page_image {
3288 doc.page_images.insert(n + 1, img);
3289 }
3290 doc.nodes.extend(nodes);
3291 doc.links.extend(links);
3292 confs.insert(n + 1, conf);
3293 }
3294 assemble::merge_continuations(&mut doc.nodes);
3295 // No PDF behind these pages (images, METS): the heading-hierarchy
3296 // stage degrades to the numbering signal — exactly docling without
3297 // an outline or parsed pages.
3298 self.apply_heading_hierarchy(&mut doc.nodes, None);
3299 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
3300 Ok(doc)
3301 }
3302}
3303
3304/// Number of pages in a PDF, without converting anything — what the CLI batch
3305/// mode prints in its per-document start line.
3306#[cfg(feature = "ml")]
3307pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
3308 pdfium_backend::page_count(bytes, password)
3309}
3310
3311#[cfg(feature = "ml")]
3312/// Convenience one-shot conversion (loads the pipeline per call). Errors are
3313/// detailed and surfaced (never silently skipped).
3314pub fn convert(
3315 bytes: &[u8],
3316 password: Option<&str>,
3317 name: &str,
3318) -> Result<DoclingDocument, PdfError> {
3319 convert_with_options(
3320 bytes,
3321 password,
3322 name,
3323 false,
3324 false,
3325 false,
3326 false,
3327 EnrichmentOptions::default(),
3328 None,
3329 None,
3330 )
3331}
3332
3333#[cfg(feature = "ml")]
3334/// Like [`convert`], but optionally skips loading/running TableFormer (see
3335/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
3336/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
3337/// [`Pipeline::enrichments`]).
3338// One positional per pipeline switch mirrors the Pipeline builder; growing
3339// past clippy's arity cap is the price of keeping this one-shot signature
3340// stable-ish instead of churning callers into an options struct mid-series.
3341#[allow(clippy::too_many_arguments)]
3342pub fn convert_with_options(
3343 bytes: &[u8],
3344 password: Option<&str>,
3345 name: &str,
3346 no_table_former: bool,
3347 no_ocr: bool,
3348 force_full_page_ocr: bool,
3349 no_text_panels: bool,
3350 enrich: EnrichmentOptions,
3351 pages: Option<(usize, usize)>,
3352 ocr_lang: Option<OcrLang>,
3353) -> Result<DoclingDocument, PdfError> {
3354 Pipeline::new()?
3355 .no_table_former(no_table_former)
3356 .no_ocr(no_ocr)
3357 .force_full_page_ocr(force_full_page_ocr)
3358 .no_text_panels(no_text_panels)
3359 .enrichments(enrich)
3360 .pages(pages)
3361 .ocr_lang(ocr_lang)
3362 .convert(bytes, password, name)
3363}
3364
3365#[cfg(feature = "ml")]
3366/// Convenience one-shot image conversion (loads the pipeline per call).
3367pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
3368 convert_image_with_options(
3369 bytes,
3370 name,
3371 false,
3372 false,
3373 false,
3374 EnrichmentOptions::default(),
3375 None,
3376 )
3377}
3378
3379#[cfg(feature = "ml")]
3380/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
3381/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
3382/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
3383pub fn convert_image_with_options(
3384 bytes: &[u8],
3385 name: &str,
3386 no_table_former: bool,
3387 no_ocr: bool,
3388 no_text_panels: bool,
3389 enrich: EnrichmentOptions,
3390 ocr_lang: Option<OcrLang>,
3391) -> Result<DoclingDocument, PdfError> {
3392 Pipeline::new()?
3393 .no_table_former(no_table_former)
3394 .no_ocr(no_ocr)
3395 .no_text_panels(no_text_panels)
3396 .enrichments(enrich)
3397 .ocr_lang(ocr_lang)
3398 .convert_image(bytes, name)
3399}
3400
3401#[cfg(feature = "ml")]
3402/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
3403/// scans) through the shared layout + assembly pipeline.
3404pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
3405 convert_pages_with_options(
3406 pages,
3407 name,
3408 false,
3409 false,
3410 false,
3411 EnrichmentOptions::default(),
3412 )
3413}
3414
3415#[cfg(feature = "ml")]
3416/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
3417/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
3418/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
3419pub fn convert_pages_with_options(
3420 pages: Vec<PdfPage>,
3421 name: &str,
3422 no_table_former: bool,
3423 no_ocr: bool,
3424 no_text_panels: bool,
3425 enrich: EnrichmentOptions,
3426) -> Result<DoclingDocument, PdfError> {
3427 Pipeline::new()?
3428 .no_table_former(no_table_former)
3429 .no_text_panels(no_text_panels)
3430 .no_ocr(no_ocr)
3431 .enrichments(enrich)
3432 .process_pages(pages, name)
3433}
3434
3435#[cfg(feature = "ml")]
3436#[cfg(all(test, feature = "ml"))]
3437mod image_limit_tests {
3438 use super::decode_image_with_max_side;
3439
3440 /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
3441 /// byte literal).
3442 fn png_bytes(w: u32, h: u32) -> Vec<u8> {
3443 use std::io::Cursor;
3444 let img = image::RgbImage::new(w, h);
3445 let mut out = Vec::new();
3446 img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
3447 .unwrap();
3448 out
3449 }
3450
3451 #[test]
3452 fn normal_image_decodes_under_the_cap() {
3453 let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
3454 assert_eq!(img.dimensions(), (8, 8));
3455 }
3456
3457 /// docling#4247 (2.128): the EXIF orientation is applied when a frame is
3458 /// loaded — a 4×2 JPEG tagged "rotate 90° CW" (orientation 6) decodes as
3459 /// 2×4, with the pixels turned.
3460 #[test]
3461 fn exif_orientation_is_applied() {
3462 use std::io::Cursor;
3463 let mut img = image::RgbImage::new(4, 2);
3464 img.put_pixel(0, 0, image::Rgb([255, 0, 0]));
3465 let mut jpeg = Vec::new();
3466 img.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
3467 .unwrap();
3468 // Splice an APP1 Exif segment (little-endian TIFF, one IFD entry:
3469 // Orientation = 6) right after the SOI marker.
3470 let mut tiff = b"II*\0".to_vec();
3471 tiff.extend(8u32.to_le_bytes());
3472 tiff.extend(1u16.to_le_bytes());
3473 tiff.extend(0x0112u16.to_le_bytes());
3474 tiff.extend(3u16.to_le_bytes());
3475 tiff.extend(1u32.to_le_bytes());
3476 tiff.extend(6u16.to_le_bytes());
3477 tiff.extend([0, 0]);
3478 tiff.extend(0u32.to_le_bytes());
3479 let mut app1 = b"Exif\0\0".to_vec();
3480 app1.extend(tiff);
3481 let mut out = jpeg[..2].to_vec();
3482 out.extend([0xff, 0xe1]);
3483 out.extend((app1.len() as u16 + 2).to_be_bytes());
3484 out.extend(app1);
3485 out.extend(&jpeg[2..]);
3486 let plain = decode_image_with_max_side(&jpeg, 30_000).unwrap();
3487 assert_eq!(plain.dimensions(), (4, 2));
3488 let turned = decode_image_with_max_side(&out, 30_000).unwrap();
3489 assert_eq!(turned.dimensions(), (2, 4), "quarter turn swaps the sides");
3490 // Rotating 90° CW moves the top-left pixel to the top-right corner.
3491 assert!(turned.get_pixel(1, 0).0[0] > 128);
3492 assert!(turned.get_pixel(0, 0).0[0] <= 128);
3493 }
3494
3495 #[test]
3496 fn dimensions_over_the_cap_are_rejected_not_aborted() {
3497 // A per-side cap below the image's declared size must yield a
3498 // recoverable Err, never an allocation-abort — the mechanism that stops
3499 // a crafted image declaring 60000×60000 from OOM-killing the process.
3500 let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
3501 assert!(
3502 r.is_err(),
3503 "decode must fail under the pixel cap, not abort"
3504 );
3505 }
3506}
3507
3508#[cfg(all(test, feature = "ml"))]
3509mod ocr_scale_tests {
3510 use super::*;
3511
3512 /// #570: an explicit scale wins everywhere; a rendered page keeps its
3513 /// render; a scale-1.0 image page reads at docling's 3 px/pt, shrunk to
3514 /// RapidOCR's 2000 px longer side (a FUNSD scan at 2.0, a 3000 px photo
3515 /// downsampled to 0.67), and an image that lands at 1.0 is not resampled.
3516 #[test]
3517 fn image_inputs_follow_rapidocrs_resolution() {
3518 assert_eq!(page_ocr_scale(Some(1.5), 754.0, 1000.0, 1.0), Some(1.5));
3519 assert_eq!(page_ocr_scale(None, 612.0, 792.0, 2.0), None);
3520 assert_eq!(page_ocr_scale(None, 754.0, 1000.0, 1.0), Some(2.0));
3521 assert_eq!(page_ocr_scale(None, 400.0, 600.0, 1.0), Some(3.0));
3522 let s = page_ocr_scale(None, 3000.0, 2000.0, 1.0).unwrap();
3523 assert!((s - 2.0 / 3.0).abs() < 1e-6, "{s}");
3524 assert_eq!(page_ocr_scale(None, 2000.0, 1500.0, 1.0), None);
3525 }
3526}
3527
3528#[cfg(test)]
3529mod median_tests {
3530 #[test]
3531 fn median_of_empty_is_zero_not_a_panic() {
3532 // A crafted table can leave a row/column with zero matched cells; the
3533 // even-count branch would index values[0 - 1] and panic (→ remote crash
3534 // via docling-serve) without the empty guard.
3535 assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
3536 assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
3537 assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
3538 }
3539}
3540
3541#[cfg(test)]
3542mod unreadable_tests {
3543 /// The text-layer path (the wasm build's only one) tells a file nothing
3544 /// can open apart from a PDF that merely has no text layer: garbage is
3545 /// an error about the file, a real PDF converts.
3546 #[test]
3547 fn text_layer_path_reports_an_unreadable_file() {
3548 for bytes in [b"garbage".as_slice(), b"", b"%PDF-1.7\n%%EOF\n"] {
3549 let err = super::convert_text_layer(bytes, "x.pdf").unwrap_err();
3550 assert!(err.to_string().contains("not a readable PDF"), "{err}");
3551 }
3552 let real = std::fs::read(
3553 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3554 .join("../../tests/data/pdf/sources/multi_page.pdf"),
3555 )
3556 .unwrap();
3557 assert!(!super::convert_text_layer(&real, "multi_page.pdf")
3558 .unwrap()
3559 .nodes
3560 .is_empty());
3561 }
3562}
3563
3564#[cfg(test)]
3565mod send_check {
3566 /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
3567 /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
3568 /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
3569 /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
3570 fn assert_send<T: Send>() {}
3571
3572 #[test]
3573 fn pipeline_is_send() {
3574 assert_send::<super::Pipeline>();
3575 }
3576}
3577
3578#[cfg(all(test, feature = "ml"))]
3579mod ocr_input_tests {
3580 /// #254: without an `ocr_scale` (or with one equal to the render scale)
3581 /// the OCR reads the page render untouched and the cache stays cold; a
3582 /// different scale builds one resampled view, reuses it across calls, and
3583 /// reports the requested px/pt so cell geometry divides back to points.
3584 #[test]
3585 fn ocr_input_resamples_only_on_a_real_scale_change() {
3586 let img = image::RgbImage::new(200, 100);
3587 let mut cache = None;
3588 let (v, s) = super::ocr_input(&mut cache, &img, 2.0, None);
3589 assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
3590 let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(2.0));
3591 assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
3592
3593 let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
3594 assert_eq!((v.width(), v.height(), s), (300, 150, 3.0));
3595 let first = cache.as_ref().map(|c| c as *const image::RgbImage);
3596 let (v, _) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
3597 assert_eq!(
3598 Some(v as *const image::RgbImage),
3599 first,
3600 "cached, not rebuilt"
3601 );
3602
3603 let mut down = None;
3604 let (v, s) = super::ocr_input(&mut down, &img, 2.0, Some(1.0));
3605 assert_eq!((v.width(), v.height(), s), (100, 50, 1.0));
3606 }
3607}