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