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