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