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