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