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