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