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