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/// A page between region resolution and TableFormer: what `prepare_page`
478/// produced and `complete_page` still needs, so a pool worker can park the
479/// page while another worker holds the shared TableFormer (see `Staged`).
480struct Prepared {
481 regions: Vec<layout::Region>,
482 ocr_confs: Vec<f32>,
483 parse: Option<f64>,
484}
485
486#[cfg(feature = "ml")]
487/// A pool worker's per-page outcome. `NeedsTables` is a page whose only
488/// remaining stage is the shared TableFormer, which was busy when the worker
489/// got there: rather than block on the mutex — one worker idle for the
490/// whole of another worker's table decode, ~9.5 s of the 60-page .NET slice
491/// on a 2-worker pool — the worker keeps the page aside, pulls the next one
492/// off the render channel, and comes back once the slot is free. Results
493/// are reassembled by page index anyway, so completion order is free.
494enum Staged {
495 Done(PageOut),
496 NeedsTables(Prepared),
497}
498
499#[cfg(feature = "ml")]
500/// How many pages a pool worker keeps parked on the TableFormer before it
501/// falls back to waiting: each carries its ~5 MB bitmaps, so this bounds the
502/// extra residency to two pages per worker on top of the render channel.
503const MAX_DEFERRED_PAGES: usize = 2;
504
505#[cfg(feature = "ml")]
506/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
507/// lazily on the first table region any worker sees. Tables appear on a
508/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
509/// weights+arenas by the pool size for nothing; a single shared instance keeps
510/// the peak flat regardless of pool width, and a table's structure prediction
511/// is independent of which worker runs it, so output is byte-identical. The
512/// mutex serialises concurrent tables — the shared instance is loaded with the
513/// full intra-op thread budget to compensate (one wide TableFormer instead of
514/// several narrow ones).
515enum TfSlot {
516 /// Not attempted yet (no table seen so far).
517 Unloaded,
518 /// Load attempted, graphs absent — geometric fallback (warned once).
519 Missing,
520 Ready(tableformer::TableFormer),
521}
522
523#[cfg(feature = "ml")]
524type SharedTables = Arc<Mutex<TfSlot>>;
525
526#[cfg(feature = "ml")]
527/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
528/// one instance per pipeline, loaded on the first region that needs it.
529enum EnrichSlot<T> {
530 Unloaded,
531 /// Load attempted, model files absent — enrichment skipped (warned once).
532 Missing,
533 Ready(T),
534}
535
536#[cfg(feature = "ml")]
537type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
538#[cfg(feature = "ml")]
539type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
540
541#[cfg(feature = "ml")]
542/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
543/// flags (`do_picture_classification`, `do_code_enrichment`,
544/// `do_formula_enrichment`). All off by default.
545#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
546pub struct EnrichmentOptions {
547 /// Classify each picture with DocumentFigureClassifier (26 classes).
548 pub picture_classification: bool,
549 /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
550 pub code: bool,
551 /// Decode display formulas to LaTeX with CodeFormulaV2.
552 pub formula: bool,
553}
554
555#[cfg(feature = "ml")]
556impl EnrichmentOptions {
557 fn any(&self) -> bool {
558 self.picture_classification || self.code || self.formula
559 }
560}
561
562#[cfg(feature = "ml")]
563/// The layout model's input for a page: the docling-exact scale-1.0 page
564/// image when the renderer produced one, else the legacy stretch of the 2×
565/// bitmap (browser / METS paths) — see [`layout::LayoutSrc`]. Public so the
566/// diagnostic examples feed [`layout::LayoutModel::predict`] the same input
567/// the pipeline does.
568pub fn layout_src(page: &PdfPage) -> layout::LayoutSrc<'_> {
569 match &page.image_layout {
570 Some(img) => layout::LayoutSrc::PageImage(img),
571 None => layout::LayoutSrc::Raw(&page.image),
572 }
573}
574
575#[cfg(feature = "ml")]
576/// The bitmap + px/pt scale the OCR reads (#254, docling#3877's
577/// `OcrOptions.scale`): the page's own render unless `ocr_scale` asks for a
578/// different resolution, where a PIL-bicubic resample of that render is built
579/// once per page (cached in `cache`) and shared by every OCR pass. Resampling
580/// — rather than a second native pdfium render — keeps one code path across
581/// PDF, image, and hOCR inputs and leaves the layout/TableFormer pixels (and
582/// with them the conformance baseline) untouched; the 144-dpi base render is
583/// itself supersampled down from 216 dpi, so an upscaled OCR view loses
584/// little against a native render.
585fn ocr_input<'a>(
586 cache: &'a mut Option<image::RgbImage>,
587 image: &'a image::RgbImage,
588 scale: f32,
589 ocr_scale: Option<f32>,
590) -> (&'a image::RgbImage, f32) {
591 match ocr_scale {
592 Some(s) if (s - scale).abs() > 1e-3 && image.width() > 1 => {
593 let f = s / scale;
594 let img = cache.get_or_insert_with(|| {
595 let dw = ((image.width() as f32 * f).round() as u32).max(1);
596 let dh = ((image.height() as f32 * f).round() as u32).max(1);
597 resample::pil_resize(image, dw, dh, resample::PilFilter::Bicubic)
598 });
599 (img, s)
600 }
601 _ => (image, scale),
602 }
603}
604
605#[cfg(feature = "ml")]
606/// A self-contained set of the per-page models (layout, OCR). Each parallel
607/// page-worker owns its own `Worker` so inference runs concurrently without
608/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
609/// rarely-hit TableFormer is shared (see [`TfSlot`]).
610struct Worker {
611 /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
612 layout: Option<layout::LayoutModel>,
613 ocr: OcrSlot,
614 /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
615 tables: Option<SharedTables>,
616 /// Shared enrichment slots; `None` unless the corresponding flag is on.
617 classifier: Option<SharedClassifier>,
618 code_formula: Option<SharedCodeFormula>,
619 enrich: EnrichmentOptions,
620 /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
621 /// embedded text layer. See [`Pipeline::no_ocr`].
622 no_ocr: bool,
623 /// Discard the embedded text layer and OCR every page. See
624 /// [`Pipeline::force_full_page_ocr`].
625 force_full_page_ocr: bool,
626 /// Keep text-panel pictures as pictures instead of demoting them to
627 /// paragraphs. See [`Pipeline::no_text_panels`].
628 no_text_panels: bool,
629 /// Never run OCR, but keep layout + TableFormer (#244) — docling's
630 /// `do_ocr=False`. See [`Pipeline::skip_ocr`].
631 skip_ocr: bool,
632 /// Which recognition model [`Self::ocr`] loads. See [`Pipeline::ocr_lang`].
633 ocr_lang: ocr::OcrLang,
634 /// OCR render scale override (px/pt, #254). See [`Pipeline::ocr_scale`].
635 ocr_scale: Option<f32>,
636}
637
638#[cfg(feature = "ml")]
639/// The worker's lazily-loaded OCR recognition model. `Missing` records a
640/// failed load (#244: degradation over failure — a deployment without the OCR
641/// model still gets layout + TableFormer, and OCR-dependent regions stay
642/// empty) so the load isn't retried per page.
643enum OcrSlot {
644 Unloaded,
645 Ready(ocr::OcrModel),
646 Missing,
647}
648
649#[cfg(feature = "ml")]
650impl Worker {
651 #[allow(clippy::too_many_arguments)] // mirrors the Pipeline's option set
652 fn load(
653 intra: usize,
654 tables: Option<SharedTables>,
655 enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
656 enrich: EnrichmentOptions,
657 no_ocr: bool,
658 skip_ocr: bool,
659 force_full_page_ocr: bool,
660 no_text_panels: bool,
661 ocr_lang: ocr::OcrLang,
662 ocr_scale: Option<f32>,
663 ) -> Result<Self, PdfError> {
664 Ok(Self {
665 layout: if no_ocr {
666 None
667 } else {
668 Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
669 },
670 ocr: OcrSlot::Unloaded,
671 tables,
672 classifier: enrich_slots.0,
673 code_formula: enrich_slots.1,
674 enrich,
675 no_ocr,
676 skip_ocr,
677 force_full_page_ocr,
678 no_text_panels,
679 ocr_lang,
680 ocr_scale,
681 })
682 }
683
684 /// The OCR model, or `None` when this conversion must not (or cannot) OCR:
685 /// `skip_ocr` short-circuits, and a failed model load degrades to `None`
686 /// with a one-time warning instead of failing the conversion (#244) —
687 /// unless `force_full_page_ocr` demanded OCR explicitly, where a missing
688 /// model stays a hard error (the text layer was deliberately discarded, so
689 /// degrading would silently emit an empty document).
690 fn ocr_model(&mut self) -> Result<Option<&mut ocr::OcrModel>, PdfError> {
691 if self.skip_ocr {
692 return Ok(None);
693 }
694 if matches!(self.ocr, OcrSlot::Unloaded) {
695 match ocr::OcrModel::load(self.ocr_lang) {
696 Ok(model) => self.ocr = OcrSlot::Ready(model),
697 Err(e) if self.force_full_page_ocr => return Err(PdfError::Ocr(e)),
698 Err(e) => {
699 static WARNED: std::sync::Once = std::sync::Once::new();
700 WARNED.call_once(|| {
701 eprintln!(
702 "warning: OCR model unavailable ({e}); continuing without OCR — \
703 scanned pages and text inside images will come back empty \
704 (run scripts/install/download_dependencies.sh for the model)"
705 );
706 });
707 self.ocr = OcrSlot::Missing;
708 }
709 }
710 }
711 Ok(match &mut self.ocr {
712 OcrSlot::Ready(model) => Some(model),
713 _ => None,
714 })
715 }
716
717 /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
718 /// into its nodes and links. Pure given the page (mutates only the worker's
719 /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
720 fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
721 if self.no_ocr {
722 // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
723 // embedded text cells (if any) become flat, line-grouped paragraphs in
724 // reading order via the same orphan-region machinery that normally
725 // rescues text the detector missed — here it rescues *all* of it.
726 // Pages with no embedded text layer (scanned/image-only) yield nothing;
727 // convert those without `no_ocr`.
728 let parse = quality::parse_score(&page.cells);
729 let mut regions = Vec::new();
730 assemble::add_orphan_regions(&mut regions, &page.cells);
731 let table_rows = vec![None; regions.len()];
732 let enrich_out = vec![None; regions.len()];
733 let conf = quality::page_confidence(parse, ®ions, &[]);
734 let (nodes, links) = timing::timed("assemble_page", || {
735 assemble::assemble_page(page, regions, &table_rows, &enrich_out)
736 });
737 return Ok((nodes, links, conf));
738 }
739 self.normalize_orientation(n, page)?;
740 let regions = timing::timed("layout.predict", || {
741 self.layout
742 .as_mut()
743 .expect("layout model loaded unless no_ocr")
744 .predict(layout_src(page), page.width, page.height)
745 })
746 .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
747 self.finish_page(n, page, regions)
748 }
749
750 /// Content-based orientation normalization (#225), before any inference:
751 /// a physically rotated scan (sideways phone photo, landscape-fed sheet)
752 /// has `/Rotate 0`, so the metadata pass in `extract_page` never fires and
753 /// layout+OCR would read a sideways raster. Only pages with no text layer
754 /// at all are probed (a digital page's raster is upright by construction,
755 /// and its cells — not its pixels — carry the text); the detected angle
756 /// composes with any `/Rotate` normalization through the same
757 /// [`PdfPage::unrotate`] + display-space assembly mapping. Detection is
758 /// evidence-gated and degrades to a no-op — see [`orient`].
759 fn normalize_orientation(&mut self, n: usize, page: &mut PdfPage) -> Result<(), PdfError> {
760 let scanned =
761 page.cells.is_empty() && page.word_cells.is_empty() && page.code_cells.is_empty();
762 if self.no_ocr || self.skip_ocr || !scanned || page.image.width() <= 1 || !orient::enabled()
763 {
764 return Ok(());
765 }
766 // The probe reads text through the OCR model; without one (missing —
767 // #244 degradation) the page stays as rendered.
768 let Some(ocr) = self.ocr_model()? else {
769 return Ok(());
770 };
771 let deg = timing::timed("orient.detect", || orient::detect(&page.image, ocr));
772 if deg != 0 {
773 debug_log!(
774 "docling-pdf: page {}: content rotated {deg}° in the raster; \
775 un-rotating before layout/OCR",
776 n + 1
777 );
778 page.unrotate(deg);
779 }
780 Ok(())
781 }
782
783 /// Layout-detect a whole batch of pages with one inference call (issue #73),
784 /// then run each page's remaining stages (OCR / TableFormer / enrichment /
785 /// assembly) per page. Index-aligned with `items`; a layout failure fails
786 /// every page in the batch (they shared the one inference call).
787 fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<Staged, PdfError>> {
788 if self.no_ocr {
789 // No layout model to batch — the text-layer-only path is per page.
790 return items
791 .iter_mut()
792 .map(|(n, page)| {
793 let n = *n;
794 self.process(n, page).map(Staged::Done)
795 })
796 .collect();
797 }
798 // Orientation-normalize every scanned page before the shared layout
799 // call — the batched inference must see upright bitmaps too (#225).
800 for (n, page) in items.iter_mut() {
801 let n = *n;
802 if let Err(e) = self.normalize_orientation(n, page) {
803 // Model-load failure — every page in the batch needs the same
804 // model, so they all fail alike (mirrors the layout-error arm).
805 let msg = e.to_string();
806 return items
807 .iter()
808 .map(|_| Err(PdfError::Ocr(msg.clone())))
809 .collect();
810 }
811 }
812 let inputs: Vec<(layout::LayoutSrc<'_>, f32, f32)> = items
813 .iter()
814 .map(|(_, page)| (layout_src(page), page.width, page.height))
815 .collect();
816 let batched = timing::timed("layout.predict", || {
817 self.layout
818 .as_mut()
819 .expect("layout model loaded unless no_ocr")
820 .predict_batch(&inputs)
821 });
822 match batched {
823 Ok(all) => items
824 .iter_mut()
825 .zip(all)
826 .map(|((n, page), regions)| self.stage_page(*n, page, regions))
827 .collect(),
828 Err(e) => items
829 .iter()
830 .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
831 .collect(),
832 }
833 }
834
835 /// A pool worker's main loop: pull rendered pages off the shared channel
836 /// (whatever is already there, up to the layout batch size), process them,
837 /// and hand each finished page — or its error — to `deliver`, which returns
838 /// `false` to stop early (the streaming consumer went away). Returns when
839 /// the channel is closed and every page this worker took is delivered.
840 ///
841 /// Pages whose TableFormer turn would have to wait are parked (see
842 /// `Staged`) and retried before every new pull; while any are parked the
843 /// pull is non-blocking, so an empty channel means the worker waits for
844 /// the TableFormer rather than for the renderer. The parking budget
845 /// (`MAX_DEFERRED_PAGES`) bounds resident bitmaps; past it the worker waits
846 /// like the serial path. Output is independent of completion order — the
847 /// callers reassemble by page index.
848 fn run_pool(
849 &mut self,
850 work_rx: &Mutex<Receiver<(usize, PdfPage)>>,
851 layout_batch: usize,
852 mut deliver: impl FnMut(usize, Result<PageOut, PdfError>) -> bool,
853 ) {
854 use std::sync::mpsc::TryRecvError;
855 let mut deferred: std::collections::VecDeque<(usize, PdfPage, Prepared)> =
856 std::collections::VecDeque::new();
857 loop {
858 // Any parked page the slot has since freed up for, oldest first.
859 let mut i = 0;
860 while i < deferred.len() {
861 let (_, page, prepared) = &deferred[i];
862 match self.table_rows_try(page, &prepared.regions) {
863 Some(rows) => {
864 let (idx, mut page, prepared) = deferred.remove(i).expect("index in range");
865 if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
866 return;
867 }
868 }
869 None => i += 1,
870 }
871 }
872 // Hold the receiver lock only for the recv (plus a non-blocking drain
873 // up to the layout batch size); release before the (long) per-page
874 // work so other workers can pull concurrently.
875 let mut batch: Vec<(usize, PdfPage)> = Vec::new();
876 let mut closed = false;
877 {
878 let rx = work_rx.lock().unwrap();
879 let first = if deferred.is_empty() {
880 rx.recv().map_err(|_| TryRecvError::Disconnected)
881 } else {
882 rx.try_recv()
883 };
884 match first {
885 Ok(item) => {
886 batch.push(item);
887 while batch.len() < layout_batch {
888 match rx.try_recv() {
889 Ok(item) => batch.push(item),
890 Err(_) => break,
891 }
892 }
893 }
894 Err(TryRecvError::Empty) => {}
895 Err(TryRecvError::Disconnected) => closed = true,
896 }
897 }
898 if batch.is_empty() {
899 // Nothing new rendered (or the channel is closed): wait our turn
900 // on the oldest parked page instead.
901 match deferred.pop_front() {
902 Some((idx, mut page, prepared)) => {
903 let rows = self.table_rows_blocking(&page, &prepared.regions);
904 if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
905 return;
906 }
907 continue;
908 }
909 None if closed => return,
910 None => continue,
911 }
912 }
913 let outs = self.process_batch(&mut batch);
914 for ((idx, mut page), out) in batch.into_iter().zip(outs) {
915 let delivered = match out {
916 Ok(Staged::Done(out)) => deliver(idx, Ok(out)),
917 Ok(Staged::NeedsTables(prepared)) => {
918 if deferred.len() < MAX_DEFERRED_PAGES {
919 deferred.push_back((idx, page, prepared));
920 true
921 } else {
922 let rows = self.table_rows_blocking(&page, &prepared.regions);
923 deliver(idx, self.complete_page(idx, &mut page, prepared, rows))
924 }
925 }
926 Err(e) => deliver(idx, Err(e)),
927 };
928 if !delivered {
929 return;
930 }
931 }
932 }
933 }
934
935 /// Everything after layout detection: per-label confidence thresholds,
936 /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
937 /// TableFormer, enrichment, and page assembly. The serial path: waits
938 /// for the shared TableFormer when a table needs it.
939 fn finish_page(
940 &mut self,
941 n: usize,
942 page: &mut PdfPage,
943 regions: Vec<layout::Region>,
944 ) -> Result<PageOut, PdfError> {
945 let prepared = self.prepare_page(n, page, regions)?;
946 let table_rows = self.table_rows_blocking(page, &prepared.regions);
947 self.complete_page(n, page, prepared, table_rows)
948 }
949
950 /// The pool path: like [`finish_page`](Self::finish_page), except that a
951 /// page whose TableFormer turn would have to wait comes back as
952 /// [`Staged::NeedsTables`] for the worker loop to park (see `Staged`).
953 fn stage_page(
954 &mut self,
955 n: usize,
956 page: &mut PdfPage,
957 regions: Vec<layout::Region>,
958 ) -> Result<Staged, PdfError> {
959 let prepared = self.prepare_page(n, page, regions)?;
960 match self.table_rows_try(page, &prepared.regions) {
961 Some(rows) => Ok(Staged::Done(self.complete_page(n, page, prepared, rows)?)),
962 None => Ok(Staged::NeedsTables(prepared)),
963 }
964 }
965
966 /// Does this page need the shared TableFormer at all? Table-free pages
967 /// never touch (or load) it.
968 fn needs_tables(&self, regions: &[layout::Region]) -> bool {
969 self.tables.is_some() && regions.iter().any(|r| assemble::is_table_like(r.label))
970 }
971
972 /// TableFormer structure for every table region of the page, on an
973 /// already-locked slot (loading the model on first use). Tables serialise
974 /// on this mutex, so the one instance gets the shared thread budget
975 /// (quota-aware, #262) — DOCLING_RS_TF_INTRA narrows it further where the
976 /// memory-per-thread tradeoff matters more than table latency.
977 fn predict_tables(
978 guard: &mut TfSlot,
979 page: &PdfPage,
980 regions: &[layout::Region],
981 ) -> Vec<Option<tf_core::TableGrid>> {
982 let mut table_rows: Vec<Option<tf_core::TableGrid>> = vec![None; regions.len()];
983 if matches!(*guard, TfSlot::Unloaded) {
984 *guard = match tableformer::TableFormer::load_with(tf_intra()) {
985 Some(tf) => TfSlot::Ready(tf),
986 None => TfSlot::Missing,
987 };
988 }
989 if let TfSlot::Ready(tf) = guard {
990 for (i, r) in regions.iter().enumerate() {
991 if assemble::is_table_like(r.label) {
992 table_rows[i] =
993 tf.predict_table_rows(&page.image, [r.l, r.t, r.r, r.b], &page.word_cells);
994 }
995 }
996 }
997 table_rows
998 }
999
1000 /// Table structure for the page, waiting for the shared slot if another
1001 /// worker holds it (else geometric fallback downstream when there is no
1002 /// TableFormer at all). The `tableformer` timing stage here includes any
1003 /// wait.
1004 fn table_rows_blocking(
1005 &self,
1006 page: &PdfPage,
1007 regions: &[layout::Region],
1008 ) -> Vec<Option<tf_core::TableGrid>> {
1009 match self.tables.as_ref().filter(|_| self.needs_tables(regions)) {
1010 Some(slot) => timing::timed("tableformer", || {
1011 Self::predict_tables(&mut slot.lock().unwrap(), page, regions)
1012 }),
1013 None => vec![None; regions.len()],
1014 }
1015 }
1016
1017 /// Non-blocking variant: `None` when the slot is held by another worker
1018 /// right now — the caller parks the page and tries again later.
1019 fn table_rows_try(
1020 &self,
1021 page: &PdfPage,
1022 regions: &[layout::Region],
1023 ) -> Option<Vec<Option<tf_core::TableGrid>>> {
1024 let Some(slot) = self.tables.as_ref().filter(|_| self.needs_tables(regions)) else {
1025 return Some(vec![None; regions.len()]);
1026 };
1027 match slot.try_lock() {
1028 Ok(mut guard) => Some(timing::timed("tableformer", || {
1029 Self::predict_tables(&mut guard, page, regions)
1030 })),
1031 Err(std::sync::TryLockError::WouldBlock) => None,
1032 Err(std::sync::TryLockError::Poisoned(e)) => panic!("TableFormer slot poisoned: {e}"),
1033 }
1034 }
1035
1036 /// The stages before TableFormer: fp32 escalation, per-label confidence
1037 /// thresholds, overlap resolution, orphan-text recovery, OCR for cell-less
1038 /// pages, in-picture text and table-word recognition.
1039 fn prepare_page(
1040 &mut self,
1041 n: usize,
1042 page: &mut PdfPage,
1043 regions: Vec<layout::Region>,
1044 ) -> Result<Prepared, PdfError> {
1045 // Force-OCR is exactly "pretend the text layer is not there": clear
1046 // every cell kind the extractors produced before anything reads them,
1047 // and the ordinary no-text-layer machinery below — full-page OCR,
1048 // OCR-fed TableFormer matching — takes over unchanged. (`no_ocr` wins
1049 // when both are set, mirroring docling, where `force_full_page_ocr`
1050 // is a sub-option of `do_ocr`; the no-ocr path never reaches here.)
1051 // Done here rather than in `process` so the batched layout path
1052 // (`process_batch` → `finish_page`) honors the flag too.
1053 // Parse quality is scored on the extracted text layer before force-OCR
1054 // discards it (docling's page-preprocessing stage runs before OCR too,
1055 // so its parse_score also reflects the original text layer).
1056 let parse = quality::parse_score(&page.cells);
1057 // Recognition confidences of every OCR'd cell on this page → ocr_score.
1058 let mut ocr_confs: Vec<f32> = Vec::new();
1059 // The bitmap the OCR reads (#254): with `ocr_scale` set, a resample of
1060 // the page render at the requested px/pt, built lazily on the first
1061 // OCR use so non-OCR pages never pay for it. Copied out of `self` up
1062 // front — the OCR sites hold `self.ocr_model()`'s mutable borrow.
1063 let ocr_scale = self.ocr_scale;
1064 let mut ocr_view: Option<image::RgbImage> = None;
1065 if self.force_full_page_ocr {
1066 page.cells.clear();
1067 page.code_cells.clear();
1068 page.word_cells.clear();
1069 }
1070 // Quant-robustness guard: the default int8 layout graph keeps its
1071 // confidences near the 0.5 label thresholds, and a different CPU's
1072 // quantized kernels can flip a whole page's detections under them —
1073 // tables and paragraphs then dissolve into orphan one-liners while the
1074 // same build converts the page perfectly elsewhere. When a dense
1075 // digital page ends up with detections covering almost none of its
1076 // text cells, re-run that one page on the fp32 graph (lazy-loaded,
1077 // auto-int8 selection only) and keep whichever detections cover more.
1078 let mut regions = regions;
1079 if !page.cells.is_empty() {
1080 let thresholded = |rs: &[layout::Region]| -> Vec<layout::Region> {
1081 rs.iter()
1082 .filter(|r| r.score >= layout::label_threshold(r.label))
1083 .cloned()
1084 .collect()
1085 };
1086 let text_cells = page
1087 .cells
1088 .iter()
1089 .filter(|c| !c.text.trim().is_empty())
1090 .count();
1091 let cov = assemble::layout_cell_coverage(&thresholded(®ions), &page.cells);
1092 if text_cells >= 15 && cov < 0.5 {
1093 let retry = self
1094 .layout
1095 .as_mut()
1096 .expect("layout model loaded unless no_ocr")
1097 .predict_fp32_fallback(layout_src(page), page.width, page.height)
1098 .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
1099 if let Some(retry) = retry {
1100 let cov2 = assemble::layout_cell_coverage(&thresholded(&retry), &page.cells);
1101 if cov2 > cov {
1102 debug_log!(
1103 "docling-pdf: page {}: int8 layout covered {:.0}% of the text \
1104 cells; the fp32 retry covers {:.0}% — using it",
1105 n + 1,
1106 cov * 100.0,
1107 cov2 * 100.0
1108 );
1109 regions = retry;
1110 }
1111 }
1112 }
1113 }
1114 // docling's LayoutPostprocessor drops each detection below its label's
1115 // confidence threshold (stricter than the 0.3 base the predictor keeps),
1116 // before any overlap resolution. This removes the low-confidence tables /
1117 // pictures / list-items that otherwise double-emit or mis-classify.
1118 if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1119 for r in ®ions {
1120 eprintln!(
1121 "DBG raw {} {:.2} [{:.0},{:.0},{:.0},{:.0}]",
1122 r.label, r.score, r.l, r.t, r.r, r.b
1123 );
1124 }
1125 }
1126 regions.retain(|r| r.score >= layout::label_threshold(r.label));
1127 // docling's same-label picture dedup runs on the thresholded
1128 // detections, before overlap resolution: a figure proposed both whole
1129 // and as sub-panels collapses to one box (see `dedup_pictures`).
1130 assemble::dedup_pictures(&mut regions);
1131 // Resolve overlapping detections once, before OCR.
1132 let mut regions = assemble::resolve(regions);
1133 // Emit text the detector missed as orphan text regions (docling parity).
1134 assemble::add_orphan_regions(&mut regions, &page.cells);
1135 // Drop phantom empty low-confidence picture boxes (docling parity).
1136 assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
1137 // A regular region fully inside a surviving table/index/picture is that
1138 // special's child (a cell / in-figure label), not a separate block —
1139 // remove it so it isn't emitted twice (docling parity).
1140 assemble::drop_contained_regulars(&mut regions);
1141 // No text layer → recognise text from the page image via OCR.
1142 let ocred = page.cells.is_empty();
1143 if ocred {
1144 // `None` = `skip_ocr` or a missing model (#244): the page keeps
1145 // its layout regions (and TableFormer structure below) with no
1146 // recognized text, instead of failing the conversion.
1147 if let Some(ocr) = self.ocr_model()? {
1148 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1149 let cells = timing::timed("ocr.page", || ocr.ocr_page(img, ®ions, scl))
1150 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1151 ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
1152 page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
1153 // Table interiors carry no words yet: region-scoped OCR skips
1154 // table labels, and a scanned page has no pdfium text layer — so
1155 // TableFormer's cell matcher got an empty word list and the table
1156 // dissolved (#173). Recognize the table regions' word crops
1157 // (mirroring the browser scanned path): `word_cells` feeds the
1158 // matcher, and the same cells join `cells` so the geometric
1159 // fallback and the table's region text see them too.
1160 if regions.iter().any(|r| assemble::is_table_like(r.label)) {
1161 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1162 let words = timing::timed("ocr.table_words", || {
1163 ocr.ocr_table_words(img, ®ions, scl)
1164 })
1165 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1166 ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1167 let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1168 page.cells.extend(words.iter().cloned());
1169 page.word_cells = words;
1170 }
1171 }
1172 }
1173 // Region-scoped OCR skips `picture` interiors, and a digital page's
1174 // text layer cannot see into an embedded raster either — so a figure
1175 // that is really a text box (terms-and-conditions exported as an
1176 // image) lost its words on every page kind. Python docling OCRs the
1177 // bitmap-covered areas of *every* page — even digital ones — once they
1178 // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
1179 // already do. Recognize the big text-less crops here too; the panel
1180 // demotion / orphan recovery below place the lines.
1181 let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1182 {
1183 let page_area = (page.width * page.height).max(1.0);
1184 let has_text = |r: &layout::Region| {
1185 page.cells.iter().any(|c| {
1186 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1187 let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1188 let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1189 !c.text.trim().is_empty() && ix * iy / ca > 0.5
1190 })
1191 };
1192 // A captioned picture can never demote to a text panel (see
1193 // recover_text_panels), and on digital pages its speculative OCR
1194 // would be discarded anyway — don't pay for it.
1195 let captioned = |r: &layout::Region| {
1196 regions.iter().any(|c| {
1197 c.label == "caption"
1198 && c.r.min(r.r) - c.l.max(r.l) > 0.0
1199 && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
1200 })
1201 };
1202 let bare: Vec<layout::Region> = regions
1203 .iter()
1204 .filter(|r| {
1205 r.label == "picture"
1206 && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
1207 && !has_text(r)
1208 && (ocred || !captioned(r))
1209 })
1210 .map(|r| layout::Region {
1211 label: "text",
1212 ..r.clone()
1213 })
1214 .collect();
1215 // Speculative OCR (#244): with `skip_ocr` or no model, big bare
1216 // pictures simply stay pictures.
1217 if let (false, Some(ocr)) = (bare.is_empty(), self.ocr_model()?) {
1218 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1219 let scored = timing::timed("ocr.pictures", || ocr.ocr_page(img, &bare, scl))
1220 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1221 // Speculative in-picture OCR counts toward ocr_score only on
1222 // OCR'd pages, where the recognized lines actually join the
1223 // output; on a digital page they may be discarded below.
1224 if ocred {
1225 ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1226 }
1227 pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1228 page.cells.extend(pic_cells.iter().cloned());
1229 }
1230 }
1231 let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
1232 // A "picture" that is really a colored text panel — dense, wide,
1233 // multi-line — reads out as paragraphs instead of shipping as pixels;
1234 // sparse in-picture text (a chart's labels) keeps the crop and stays
1235 // inside it as the picture's silent children (docling parity, #200).
1236 // `no_text_panels` (#173) opts out entirely for image-extraction
1237 // workflows.
1238 if !self.no_text_panels {
1239 assemble::recover_text_panels(&mut regions, &page.cells);
1240 }
1241 // On an OCR'd page, in-picture text that did NOT demote its picture
1242 // mostly stays silent, exactly as in docling: its postprocess step
1243 // "Remove regular clusters that are included in wrappers" walks
1244 // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
1245 // >80 % contained in a kept picture becomes that picture's child and
1246 // never reaches the serializer. Only border-straddlers (≤80 %
1247 // containment) survive as text. Emitting *everything* here used to
1248 // splice a chart's OCR'd axis ticks into the body text right next to
1249 // the image chunk (#200) — so the orphan pass places the recognized
1250 // lines, then the same containment drop that handled the first wave
1251 // re-runs to swallow the in-picture ones.
1252 if ocred && !pic_cells.is_empty() {
1253 // Pictures (and wrappers) no longer count as claimers (#165), so
1254 // the plain orphan pass places the recognized lines directly.
1255 assemble::add_orphan_regions(&mut regions, &pic_cells);
1256 assemble::drop_contained_regulars(&mut regions);
1257 } else if !ocred && !pic_cells.is_empty() {
1258 // Digital page, picture kept: its speculative OCR cells must not
1259 // linger in the text-cell set (they were appended at the tail).
1260 let kept: Vec<layout::Region> = regions
1261 .iter()
1262 .filter(|r| r.label == "picture")
1263 .cloned()
1264 .collect();
1265 let tail = page.cells.split_off(cells_before_pic_ocr);
1266 page.cells.extend(tail.into_iter().filter(|c| {
1267 !kept.iter().any(|r| {
1268 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1269 let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1270 let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1271 ix * iy / ca > 0.5
1272 })
1273 }));
1274 }
1275 // A text-less *table* detected inside a picture on a digital page — a
1276 // screenshot of a table (2203's Figure 10) — has no text layer and no
1277 // scanned-path OCR to feed it, so its grid used to serialize empty and
1278 // the whole element vanished. docling OCRs bitmap-covered areas on
1279 // every page kind and its table cluster collects those cells; mirror
1280 // the scanned path for exactly these tables: recognize word crops and
1281 // feed them to the TableFormer matcher and the cell set.
1282 if !ocred {
1283 let has_text = |t: &layout::Region| {
1284 page.cells.iter().any(|c| {
1285 let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1286 let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
1287 let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
1288 !c.text.trim().is_empty() && ix * iy / ca > 0.5
1289 })
1290 };
1291 let in_picture = |t: &layout::Region| {
1292 regions.iter().any(|r| {
1293 r.label == "picture" && {
1294 let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
1295 let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
1296 let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
1297 ix * iy / ta > 0.5
1298 }
1299 })
1300 };
1301 let pic_tables: Vec<layout::Region> = regions
1302 .iter()
1303 .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
1304 .cloned()
1305 .collect();
1306 // Same degradation as above: without OCR the in-picture table
1307 // keeps its structure (TableFormer is geometry-driven) minus text.
1308 if let (false, Some(ocr)) = (pic_tables.is_empty(), self.ocr_model()?) {
1309 let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1310 let words = timing::timed("ocr.table_words", || {
1311 ocr.ocr_table_words(img, &pic_tables, scl)
1312 })
1313 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1314 ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1315 let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1316 page.cells.extend(words.iter().cloned());
1317 page.word_cells.extend(words);
1318 }
1319 }
1320 Ok(Prepared {
1321 regions,
1322 ocr_confs,
1323 parse,
1324 })
1325 }
1326
1327 /// The stages after TableFormer: enrichment, the page confidence report and
1328 /// assembly into typed nodes.
1329 fn complete_page(
1330 &mut self,
1331 n: usize,
1332 page: &mut PdfPage,
1333 prepared: Prepared,
1334 table_rows: Vec<Option<tf_core::TableGrid>>,
1335 ) -> Result<PageOut, PdfError> {
1336 let Prepared {
1337 regions,
1338 ocr_confs,
1339 parse,
1340 } = prepared;
1341 if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1342 for (i, r) in regions.iter().enumerate() {
1343 eprintln!(
1344 "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
1345 r.label,
1346 r.score,
1347 r.l,
1348 r.t,
1349 r.r,
1350 r.b,
1351 table_rows[i]
1352 .as_ref()
1353 .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
1354 );
1355 }
1356 eprintln!(
1357 "DBG cells={} words={}",
1358 page.cells.len(),
1359 page.word_cells.len()
1360 );
1361 }
1362 // Enrichment passes (opt-in): DocumentPictureClassifier over picture
1363 // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
1364 // shape as TableFormer — one lazily-loaded instance per pipeline, only
1365 // ever locked when a page actually has a matching region.
1366 let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
1367 if let Some(slot) = self.classifier.as_ref() {
1368 if regions.iter().any(|r| r.label == "picture") {
1369 timing::timed("picture_classifier", || {
1370 let mut guard = slot.lock().unwrap();
1371 if matches!(*guard, EnrichSlot::Unloaded) {
1372 *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
1373 Some(m) => EnrichSlot::Ready(m),
1374 None => EnrichSlot::Missing,
1375 };
1376 }
1377 if let EnrichSlot::Ready(model) = &mut *guard {
1378 for (i, r) in regions.iter().enumerate() {
1379 if r.label != "picture" {
1380 continue;
1381 }
1382 let Some(crop) = assemble::crop_region_scaled(
1383 page,
1384 [r.l, r.t, r.r, r.b],
1385 enrich::CLASSIFIER_SCALE,
1386 ) else {
1387 continue;
1388 };
1389 match model.classify(&crop) {
1390 Ok(classes) => {
1391 enrich_out[i] =
1392 Some(assemble::Enrichment::PictureClasses(classes));
1393 }
1394 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1395 }
1396 }
1397 }
1398 });
1399 }
1400 }
1401 if let Some(slot) = self.code_formula.as_ref() {
1402 let wants = |label: &str| {
1403 (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
1404 };
1405 if regions.iter().any(|r| wants(r.label)) {
1406 timing::timed("code_formula", || {
1407 let mut guard = slot.lock().unwrap();
1408 if matches!(*guard, EnrichSlot::Unloaded) {
1409 *guard = match enrich::CodeFormula::load_with(intra_threads()) {
1410 Some(m) => EnrichSlot::Ready(m),
1411 None => EnrichSlot::Missing,
1412 };
1413 }
1414 if let EnrichSlot::Ready(model) = &mut *guard {
1415 for (i, r) in regions.iter().enumerate() {
1416 if !wants(r.label) {
1417 continue;
1418 }
1419 // docling crops the postprocessed cluster box — the
1420 // union of the region's text cells, not the raw
1421 // detector box — expanded by 18% per side, at
1422 // ~120 dpi.
1423 let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
1424 .unwrap_or([r.l, r.t, r.r, r.b]);
1425 let (w, h) = (br - bl, bb - bt);
1426 let ex = enrich::CODE_FORMULA_EXPANSION;
1427 let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
1428 let Some(crop) = assemble::crop_region_scaled(
1429 page,
1430 bbox,
1431 enrich::CODE_FORMULA_SCALE,
1432 ) else {
1433 continue;
1434 };
1435 let kind = if r.label == "code" {
1436 enrich::CodeFormulaKind::Code
1437 } else {
1438 enrich::CodeFormulaKind::Formula
1439 };
1440 match model.predict(&crop, kind) {
1441 Ok(text) => {
1442 enrich_out[i] = Some(match kind {
1443 enrich::CodeFormulaKind::Code => {
1444 let (code, language) =
1445 enrich::extract_code_language(&text);
1446 assemble::Enrichment::Code {
1447 language,
1448 text: code,
1449 }
1450 }
1451 enrich::CodeFormulaKind::Formula => {
1452 assemble::Enrichment::Formula { latex: text }
1453 }
1454 });
1455 }
1456 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1457 }
1458 }
1459 }
1460 });
1461 }
1462 }
1463 // Score the final region set (docling assigns layout_score over the
1464 // postprocessed clusters — the same set assemble_page consumes).
1465 let conf = quality::page_confidence(parse, ®ions, &ocr_confs);
1466 let (nodes, links) = timing::timed("assemble_page", || {
1467 assemble::assemble_page(page, regions, &table_rows, &enrich_out)
1468 });
1469 Ok((nodes, links, conf))
1470 }
1471}
1472
1473#[cfg(feature = "ml")]
1474/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
1475/// so on a typical machine two threads per worker (sharing one in-cache copy of
1476/// the weights) extracts more throughput than one fat model or many single-thread
1477/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
1478fn pdf_intra() -> usize {
1479 if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
1480 return n;
1481 }
1482 if intra_threads() >= 2 {
1483 2
1484 } else {
1485 1
1486 }
1487}
1488
1489#[cfg(feature = "ml")]
1490/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
1491/// overrides; otherwise size the pool so `workers × intra ≈ cores`.
1492///
1493/// The pool scales with the machine (#324 follow-up testing): the old hard cap
1494/// of 4 left most of a many-core box idle — on a 16-core M4 Max, 10 workers
1495/// measured ~1.2× over the capped pool (10.0 → 8.5 s on a 130-page document,
1496/// byte-identical output). The ceiling of 16 is a memory bound, not a
1497/// performance one: each worker holds its own layout/OCR sessions (~0.4 GB),
1498/// so a worst-case pool stays under ~6.5 GB even on a ≥32-core host — and
1499/// docling-serve's per-request pools sit behind its `DOCLING_RS_MAX_MEMORY_MB`
1500/// admission control besides. Machines with 4 or fewer effective threads keep
1501/// the exact old sizing (`threads / intra`, min 1).
1502fn pdf_worker_count() -> usize {
1503 if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
1504 return n;
1505 }
1506 (intra_threads() / pdf_intra()).clamp(1, 16)
1507}
1508
1509#[cfg(feature = "ml")]
1510/// Max pages a worker layout-detects with one batched inference call (issue
1511/// #73). Workers drain the work channel opportunistically up to this size —
1512/// whatever is already rendered gets batched, so batching never *waits* for
1513/// pages and adds no latency when rendering is the bottleneck.
1514///
1515/// Default: per-page (1) on the CPU provider, 4 when a GPU provider is
1516/// selected (#338). The old "4 on 8+ cores" CPU default was a hypothesis —
1517/// that single-session amortization pays off with a wider thread budget —
1518/// and every actual CPU measurement lands the other way: a 4-core x86 box
1519/// runs the 9-page 2206.01062 fixture in 8.5 s/conv at batch=1 vs 9.3 s at
1520/// batch=4 (re-measured for #338; the original 8.1 vs 9.3 agrees), and the
1521/// issue-#338 report measured batch=1 ~2× faster on a 16-core M4 Max at
1522/// every worker count — batching only adds cache pressure once workers
1523/// saturate the cores. On a GPU the per-call dispatch overhead is real and
1524/// batching amortizes it, so the GPU default stays. Output is bit-identical
1525/// at every batch size, so this is purely a throughput knob.
1526/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides either way; `1` = per-page.
1527pub(crate) fn pdf_layout_batch() -> usize {
1528 env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
1529 .filter(|&n| n > 0)
1530 .unwrap_or_else(|| if docling_onnx::prefers_fp32() { 4 } else { 1 })
1531}
1532
1533#[cfg(feature = "ml")]
1534/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
1535/// the serial primary (running its model on every core) is faster than fanning out
1536/// — the helper pool's one-time model-load cost only pays off once enough pages
1537/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
1538fn pdf_parallel_min() -> usize {
1539 env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
1540 .filter(|&n| n > 0)
1541 .unwrap_or(6)
1542}
1543
1544#[cfg(feature = "ml")]
1545/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
1546/// so a single-page / small / image / METS input is converted at full intra-op
1547/// speed with no pool to load. A document with enough pages instead fans out
1548/// across a **pool** of narrower workers processed concurrently. Both load lazily
1549/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
1550pub struct Pipeline {
1551 /// Full-intra worker for the serial path; loaded on first serial use.
1552 primary: Option<Worker>,
1553 /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
1554 /// path; loaded on first multi-page use and cached.
1555 pool: Vec<Worker>,
1556 /// The single TableFormer instance every worker shares (see [`TfSlot`]).
1557 tables: SharedTables,
1558 /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
1559 classifier: SharedClassifier,
1560 code_formula: SharedCodeFormula,
1561 /// Desired pool size for multi-page documents.
1562 target_workers: usize,
1563 /// Page count at/above which the parallel pool is worth its load cost.
1564 parallel_min: usize,
1565 /// Skip loading/running TableFormer; table regions fall back to geometric
1566 /// reconstruction. See [`Pipeline::no_table_former`].
1567 no_table_former: bool,
1568 /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
1569 no_ocr: bool,
1570 /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
1571 skip_ocr: bool,
1572 /// OCR every page even when it carries a text layer. See
1573 /// [`Pipeline::force_full_page_ocr`].
1574 force_full_page_ocr: bool,
1575 /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
1576 no_text_panels: bool,
1577 /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
1578 enrich: EnrichmentOptions,
1579 /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
1580 page_range: Option<(usize, usize)>,
1581 /// OCR recognition language. See [`Pipeline::ocr_lang`].
1582 ocr_lang: ocr::OcrLang,
1583 /// Which regions feed the OCR (#254). See [`Pipeline::ocr_mode`].
1584 ocr_mode: ocr::OcrMode,
1585 /// OCR render scale override in px/pt (#254). See [`Pipeline::ocr_scale`].
1586 ocr_scale: Option<f32>,
1587 /// Heading-level inference (#302). See [`Pipeline::heading_hierarchy`].
1588 heading_hierarchy: HeadingHierarchyOptions,
1589 /// Optional per-page progress hook `(done, selected_total)`, invoked after
1590 /// each page finishes on both the serial and parallel buffered paths. Set
1591 /// by the CLI batch mode for dot-progress; `None` costs nothing.
1592 progress: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>,
1593}
1594
1595#[cfg(feature = "ml")]
1596impl Pipeline {
1597 /// Construct the pipeline. Models load lazily on first use (full-intra primary
1598 /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
1599 /// loaded that a given document doesn't need.
1600 pub fn new() -> Result<Self, PdfError> {
1601 Ok(Self {
1602 primary: None,
1603 pool: Vec::new(),
1604 tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
1605 classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1606 code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1607 target_workers: pdf_worker_count(),
1608 parallel_min: pdf_parallel_min(),
1609 no_table_former: false,
1610 no_ocr: false,
1611 skip_ocr: false,
1612 force_full_page_ocr: false,
1613 no_text_panels: false,
1614 enrich: EnrichmentOptions::default(),
1615 page_range: None,
1616 ocr_lang: ocr::OcrLang::from_env(),
1617 ocr_mode: ocr::OcrMode::from_env(),
1618 ocr_scale: ocr::scale_from_env(),
1619 heading_hierarchy: HeadingHierarchyOptions::default(),
1620 progress: None,
1621 })
1622 }
1623
1624 /// Infer section-header levels after assembly (#302, docling's
1625 /// `HeadingHierarchyModel`): PDF bookmarks > legal/outline numbering >
1626 /// font style, off by default — see [`HeadingHierarchyOptions`]. Pure
1627 /// post-processing configuration; for a warm pipeline use
1628 /// [`set_heading_hierarchy`](Self::set_heading_hierarchy).
1629 pub fn heading_hierarchy(mut self, opts: HeadingHierarchyOptions) -> Self {
1630 self.heading_hierarchy = opts;
1631 self
1632 }
1633
1634 /// In-place variant of [`heading_hierarchy`](Self::heading_hierarchy) for
1635 /// a long-lived pipeline (docling-serve's warm instance) — like
1636 /// [`set_pages`](Self::set_pages), set it before every conversion so no
1637 /// request inherits a previous one's choice.
1638 pub fn set_heading_hierarchy(&mut self, opts: HeadingHierarchyOptions) {
1639 self.heading_hierarchy = opts;
1640 }
1641
1642 /// Run the enabled heading-hierarchy stage (#302) on an assembled
1643 /// document: gather the outline (bookmarks) and the per-page glyph styles
1644 /// on demand, then assign levels in place. `bytes` is `None` on paths
1645 /// with no PDF behind them (standalone images, METS) — those degrade to
1646 /// the numbering signal, exactly like docling without parsed pages.
1647 fn apply_heading_hierarchy(
1648 &self,
1649 nodes: &mut [Node],
1650 bytes: Option<&[u8]>,
1651 password: Option<&str>,
1652 ) {
1653 let opts = &self.heading_hierarchy;
1654 if !opts.enabled {
1655 return;
1656 }
1657 let outline = match bytes {
1658 Some(bytes) if opts.use_bookmarks => outline::extract_outline(bytes),
1659 _ => Vec::new(),
1660 };
1661 let styles = match bytes {
1662 Some(bytes) if opts.use_style => {
1663 let pages = heading_hierarchy::heading_pages(nodes);
1664 pdfium_backend::glyph_styles(bytes, password, &pages)
1665 }
1666 _ => Default::default(),
1667 };
1668 heading_hierarchy::apply(nodes, &outline, &styles, opts);
1669 }
1670
1671 /// Install (or clear) the per-page progress hook: called with
1672 /// `(pages_done, pages_selected)` after each page completes during
1673 /// [`convert`](Self::convert). Shared with the parallel workers, so the
1674 /// callback must be cheap and thread-safe.
1675 pub fn set_progress(&mut self, cb: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>) {
1676 self.progress = cb;
1677 }
1678
1679 /// Convert only pages `first..=last` (**1-based**, like the page numbers a
1680 /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
1681 /// skipped before rasterization, so the cost is proportional to the window,
1682 /// not the document. `last` past the end of the document clamps; a window
1683 /// that selects no pages at all (`first` beyond the last page) is an error
1684 /// at convert time. `None` (the default) converts everything.
1685 pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
1686 self.page_range = range;
1687 self
1688 }
1689
1690 /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
1691 /// (e.g. docling-serve's warm instance) that applies a per-request window
1692 /// without rebuilding — unlike the model switches, the window is pure
1693 /// configuration. Set it before every conversion; it stays until changed.
1694 pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
1695 self.page_range = range;
1696 }
1697
1698 /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
1699 /// for the multilingual docling-conformance model. `None` keeps the
1700 /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
1701 /// first conversion; for a warm pipeline use
1702 /// [`set_ocr_lang`](Self::set_ocr_lang).
1703 pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
1704 self.set_ocr_lang(lang);
1705 self
1706 }
1707
1708 /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
1709 /// pipeline (docling-serve's warm instance). Unlike the page window this
1710 /// is a *model* switch: any worker whose cached recognition model was
1711 /// loaded for a different language drops it, to be lazily reloaded on the
1712 /// next OCR-needing page (cheap — the rec models are ~10 MB).
1713 pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
1714 let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
1715 self.ocr_lang = lang;
1716 for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
1717 if worker.ocr_lang != lang {
1718 worker.ocr_lang = lang;
1719 worker.ocr = OcrSlot::Unloaded;
1720 }
1721 }
1722 }
1723
1724 /// Resolve the configured 1-based window against a page count into the
1725 /// 0-based inclusive form the backend walks, validating it selects at
1726 /// least one existing page.
1727 fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
1728 let Some((first, last)) = self.page_range else {
1729 return Ok(None);
1730 };
1731 if first == 0 || last < first {
1732 return Err(PdfError::Pdfium(format!(
1733 "invalid page range {first}-{last} (pages are 1-based, first <= last)"
1734 )));
1735 }
1736 if first > total {
1737 return Err(PdfError::Pdfium(format!(
1738 "page range {first}-{last} is outside the document ({total} page(s))"
1739 )));
1740 }
1741 Ok(Some((first - 1, last.min(total) - 1)))
1742 }
1743
1744 /// Enable the opt-in enrichment passes (docling's
1745 /// `do_picture_classification` / `do_code_enrichment` /
1746 /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
1747 /// the first matching region; a missing model warns once and is skipped.
1748 /// Set before the first conversion (no effect on already-loaded workers).
1749 pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
1750 self.enrich = opts;
1751 self
1752 }
1753
1754 /// Skip loading and running the TableFormer table-structure model. Table
1755 /// regions still get emitted, but reconstructed geometrically from cell
1756 /// positions instead of via the ONNX model's predicted structure — faster
1757 /// (no model load, no per-table inference) at the cost of table fidelity.
1758 /// No effect if a worker is already loaded; set this before the first
1759 /// conversion.
1760 pub fn no_table_former(mut self, disable: bool) -> Self {
1761 self.no_table_former = disable;
1762 self
1763 }
1764
1765 /// Keep every detected `picture` region as a picture. By default an
1766 /// *uncaptioned* picture that reads like a dense, uniform text panel (a
1767 /// terms-and-conditions box exported as an image) is demoted into
1768 /// paragraphs (#157); a chart the layout mislabels can still trip that
1769 /// heuristic on scanned pages, and image-extraction workflows may simply
1770 /// want every crop — this flag disables the demotion entirely (#173).
1771 /// No effect on already-loaded workers; set before the first conversion.
1772 pub fn no_text_panels(mut self, disable: bool) -> Self {
1773 self.no_text_panels = disable;
1774 self
1775 }
1776
1777 /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
1778 /// inference of any kind. The PDF's embedded text cells are grouped by line
1779 /// and emitted as plain paragraphs in reading order: no headings, lists,
1780 /// tables, code blocks, or pictures, since that structure comes from the
1781 /// layout model. The fastest possible PDF path, but pages with no embedded
1782 /// text layer (scanned/image-only PDFs) yield no text at all — convert those
1783 /// without this flag. Implies `no_table_former`. No effect if a worker is
1784 /// already loaded; set this before the first conversion.
1785 pub fn no_ocr(mut self, disable: bool) -> Self {
1786 self.no_ocr = disable;
1787 self
1788 }
1789
1790 /// Never run OCR, but keep layout detection and TableFormer — docling's
1791 /// independent `do_ocr=False` (#244), the counterpart of
1792 /// [`no_table_former`](Self::no_table_former). Unlike
1793 /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
1794 /// output — headings, tables, pictures, reading order — is preserved;
1795 /// only text that exists solely as pixels is lost: scanned pages come
1796 /// back with their regions empty, and the speculative OCR of large
1797 /// embedded images never runs. The OCR model is never loaded. Ignored
1798 /// when `no_ocr` is set (there is no OCR to skip);
1799 /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
1800 /// mirroring docling where forcing is a sub-option of `do_ocr`.
1801 pub fn skip_ocr(mut self, disable: bool) -> Self {
1802 self.skip_ocr = disable;
1803 self
1804 }
1805
1806 /// OCR every page from its rendered image even when the page carries an
1807 /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
1808 /// for text layers that exist but lie: broken encodings, subset fonts with
1809 /// garbage mappings, a scanned form with a few typed-in fields. Ignored
1810 /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
1811 /// `force_full_page_ocr` is a sub-option of `do_ocr`).
1812 pub fn force_full_page_ocr(mut self, force: bool) -> Self {
1813 self.force_full_page_ocr = force;
1814 self
1815 }
1816
1817 /// Which document regions feed the OCR — docling's `OcrMode` (#254). The
1818 /// default (`default` = `pdf_aware_layout_regions`) is the standard
1819 /// text-layer-aware behavior; `full_page`/`layout_regions` discard the
1820 /// text layer like [`force_full_page_ocr`](Self::force_full_page_ocr)
1821 /// (see [`ocr::OcrMode`] for why both map onto it). Whichever of the flag
1822 /// and the mode demands forcing wins, mirroring docling's
1823 /// `force_full_page_ocr` → `mode=full_page` bridge. `None` keeps the
1824 /// process default (`DOCLING_RS_OCR_MODE`, else `default`).
1825 pub fn ocr_mode(mut self, mode: Option<ocr::OcrMode>) -> Self {
1826 self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
1827 self
1828 }
1829
1830 /// In-place variants of [`force_full_page_ocr`](Self::force_full_page_ocr),
1831 /// [`ocr_mode`](Self::ocr_mode) and [`ocr_scale`](Self::ocr_scale) for a
1832 /// long-lived pipeline (docling-serve's warm instance): all three are pure
1833 /// per-worker configuration — no model reloads — so they apply per request
1834 /// like [`set_pages`](Self::set_pages). Set them before every conversion so
1835 /// no request inherits a previous one's choice.
1836 pub fn set_force_full_page_ocr(&mut self, force: bool) {
1837 self.force_full_page_ocr = force;
1838 self.sync_ocr_config();
1839 }
1840
1841 /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
1842 pub fn set_ocr_mode(&mut self, mode: Option<ocr::OcrMode>) {
1843 self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
1844 self.sync_ocr_config();
1845 }
1846
1847 /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
1848 pub fn set_ocr_scale(&mut self, scale: Option<f32>) {
1849 self.ocr_scale = scale
1850 .filter(|s| s.is_finite() && *s > 0.0)
1851 .or_else(ocr::scale_from_env);
1852 self.sync_ocr_config();
1853 }
1854
1855 /// Whether page extraction should decode the text layer at all. Forced
1856 /// full-page OCR (the flag or `ocr_mode=full_page|layout_regions`) clears
1857 /// every extracted cell unread, so the decode is skipped outright —
1858 /// docling#4061's `skip_cell_extraction` (2.122). `no_ocr` wins over the
1859 /// forcing, as everywhere else: its fast path *is* the text layer.
1860 fn extract_text_layer(&self) -> bool {
1861 self.no_ocr || !(self.force_full_page_ocr || self.ocr_mode.forces_full_page())
1862 }
1863
1864 /// Push the current OCR forcing/scale choice onto already-loaded workers
1865 /// (new workers read it at [`Worker::load`]).
1866 fn sync_ocr_config(&mut self) {
1867 let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
1868 let scale = self.ocr_scale;
1869 for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
1870 worker.force_full_page_ocr = force;
1871 worker.ocr_scale = scale;
1872 }
1873 }
1874
1875 /// OCR render scale in pixels per PDF point — docling's `OcrOptions.scale`
1876 /// (#254, upstream docling#3877; their default 3 = 216 dpi). `None`
1877 /// (default: `DOCLING_RS_OCR_SCALE`, else unset) feeds the recognizer the
1878 /// pipeline's own page render (2.0 px/pt = 144 dpi); a different value
1879 /// resamples that render for the OCR input only — layout and TableFormer
1880 /// keep their pinned-resolution pixels, so the conformance baseline never
1881 /// moves. Lower it when the source raster is already high-resolution and
1882 /// upscaling degrades recognition; raise it toward docling's 216 dpi for
1883 /// parity experiments. Non-positive values are ignored.
1884 pub fn ocr_scale(mut self, scale: Option<f32>) -> Self {
1885 self.ocr_scale = scale
1886 .filter(|s| s.is_finite() && *s > 0.0)
1887 .or_else(ocr::scale_from_env);
1888 self
1889 }
1890
1891 /// The shared TableFormer slot handed to each worker, or `None` when the
1892 /// pipeline options skip TableFormer entirely.
1893 fn tables_slot(&self) -> Option<SharedTables> {
1894 if self.no_table_former || self.no_ocr {
1895 None
1896 } else {
1897 Some(Arc::clone(&self.tables))
1898 }
1899 }
1900
1901 /// The shared enrichment slots for a worker (`None` per model unless its
1902 /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
1903 fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
1904 if self.no_ocr || !self.enrich.any() {
1905 return (None, None);
1906 }
1907 (
1908 self.enrich
1909 .picture_classification
1910 .then(|| Arc::clone(&self.classifier)),
1911 (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
1912 )
1913 }
1914
1915 /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
1916 /// the shared TableFormer unless disabled) so the first conversion doesn't pay
1917 /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
1918 /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
1919 /// `DocumentConverter.initialize_pipeline`.
1920 pub fn warm_up(&mut self) -> Result<(), PdfError> {
1921 self.primary()?;
1922 Ok(())
1923 }
1924
1925 /// The full-intra serial worker, loaded on first use.
1926 fn primary(&mut self) -> Result<&mut Worker, PdfError> {
1927 if self.primary.is_none() {
1928 self.primary = Some(Worker::load(
1929 intra_threads(),
1930 self.tables_slot(),
1931 self.enrich_slots(),
1932 self.enrich,
1933 self.no_ocr,
1934 self.skip_ocr,
1935 // The mode-shaped spelling (#254) and the flag are one engine
1936 // truth: whichever demands forcing wins, mirroring docling's
1937 // `force_full_page_ocr` → `mode=full_page` bridge.
1938 self.force_full_page_ocr || self.ocr_mode.forces_full_page(),
1939 self.no_text_panels,
1940 self.ocr_lang,
1941 self.ocr_scale,
1942 )?);
1943 }
1944 Ok(self.primary.as_mut().unwrap())
1945 }
1946
1947 /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
1948 /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
1949 /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
1950 /// fans the pages out across the worker pool, reassembled in page order so the
1951 /// output is byte-identical to the serial path.
1952 pub fn convert(
1953 &mut self,
1954 bytes: &[u8],
1955 password: Option<&str>,
1956 name: &str,
1957 ) -> Result<DoclingDocument, PdfError> {
1958 let pages = pdfium_backend::page_count(bytes, password)?;
1959 let range = self.resolve_range(pages)?;
1960 // Serial vs parallel is decided by the pages actually converted: a
1961 // 3-page window over a 500-page PDF should not pay the pool load.
1962 let selected = range.map_or(pages, |(a, b)| b - a + 1);
1963 let doc = if self.target_workers >= 2 && selected >= self.parallel_min {
1964 self.convert_parallel(bytes, password, name, range, selected)?
1965 } else {
1966 self.convert_serial(bytes, password, name, range, selected)?
1967 };
1968 timing::report();
1969 Ok(doc)
1970 }
1971
1972 /// Stream pages one at a time through the primary worker — render → process →
1973 /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
1974 fn convert_serial(
1975 &mut self,
1976 bytes: &[u8],
1977 password: Option<&str>,
1978 name: &str,
1979 range: Option<(usize, usize)>,
1980 selected: usize,
1981 ) -> Result<DoclingDocument, PdfError> {
1982 let mut doc = DoclingDocument::new(name);
1983 let mut confs = std::collections::BTreeMap::new();
1984 let render_image = !self.no_ocr;
1985 let extract_text = self.extract_text_layer();
1986 let progress = self.progress.clone();
1987 let mut done = 0usize;
1988 let worker = self.primary()?;
1989 pdfium_backend::for_each_page(
1990 bytes,
1991 password,
1992 render_image,
1993 extract_text,
1994 range,
1995 |n, _total, mut page| {
1996 let (mut nodes, links, conf) = worker.process(n, &mut page)?;
1997 assemble::stamp_page_no(&mut nodes, n + 1);
1998 doc.nodes.extend(nodes);
1999 doc.links.extend(links);
2000 confs.insert(n + 1, conf);
2001 if let Some(cb) = &progress {
2002 done += 1;
2003 cb(done, selected);
2004 }
2005 Ok::<(), PdfError>(())
2006 },
2007 )?;
2008 assemble::merge_continuations(&mut doc.nodes);
2009 self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes), password);
2010 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2011 Ok(doc)
2012 }
2013
2014 /// Render pages serially on this thread (pdfium) and process them in parallel
2015 /// across the worker pool. A bounded channel applies backpressure so only a
2016 /// handful of page bitmaps are resident at once; results carry their page
2017 /// index and are reassembled in order, so the output is byte-identical to the
2018 /// serial path.
2019 fn convert_parallel(
2020 &mut self,
2021 bytes: &[u8],
2022 password: Option<&str>,
2023 name: &str,
2024 range: Option<(usize, usize)>,
2025 selected: usize,
2026 ) -> Result<DoclingDocument, PdfError> {
2027 self.ensure_pool()?;
2028 let progress = self.progress.clone();
2029 let pages_done = std::sync::atomic::AtomicUsize::new(0);
2030 let n_workers = self.pool.len();
2031 let render_image = !self.no_ocr;
2032 let extract_text = self.extract_text_layer();
2033 let layout_batch = pdf_layout_batch();
2034 // Bound sized so every worker can accumulate a full layout batch while
2035 // rendering stays ahead (and never below the pre-#73 render-ahead of
2036 // two pages per worker); still a hard cap on resident page bitmaps.
2037 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2038 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2039 let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
2040 let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
2041
2042 // Move the pool into the scope so each worker gets an exclusive `&mut`.
2043 let mut workers = std::mem::take(&mut self.pool);
2044 std::thread::scope(|s| {
2045 for worker in workers.iter_mut() {
2046 let work_rx = Arc::clone(&work_rx);
2047 let results = Arc::clone(&results);
2048 let first_err = Arc::clone(&first_err);
2049 let progress = progress.clone();
2050 let pages_done = &pages_done;
2051 s.spawn(move || {
2052 worker.run_pool(&work_rx, layout_batch, |idx, out| {
2053 match out {
2054 Ok(out) => {
2055 results.lock().unwrap().push((idx, out));
2056 if let Some(cb) = &progress {
2057 let d = pages_done
2058 .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2059 + 1;
2060 cb(d, selected);
2061 }
2062 }
2063 Err(e) => {
2064 let mut slot = first_err.lock().unwrap();
2065 if slot.is_none() {
2066 *slot = Some(e);
2067 }
2068 }
2069 }
2070 true
2071 });
2072 });
2073 }
2074 // Render on this thread and feed the workers; backpressure blocks here
2075 // when the channel is full. Dropping `work_tx` afterwards signals the
2076 // workers (recv → Err) to finish.
2077 let render = pdfium_backend::for_each_page(
2078 bytes,
2079 password,
2080 render_image,
2081 extract_text,
2082 range,
2083 |i, _total, page| {
2084 work_tx
2085 .send((i, page))
2086 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2087 },
2088 );
2089 drop(work_tx);
2090 if let Err(e) = render {
2091 let mut slot = first_err.lock().unwrap();
2092 if slot.is_none() {
2093 *slot = Some(e);
2094 }
2095 }
2096 });
2097 // Threads have joined; restore the pool for the next conversion.
2098 self.pool = workers;
2099
2100 if let Some(e) = first_err.lock().unwrap().take() {
2101 return Err(e);
2102 }
2103 let mut results = Arc::try_unwrap(results)
2104 .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
2105 .into_inner()
2106 .unwrap();
2107 results.sort_by_key(|(idx, _)| *idx);
2108 let mut doc = DoclingDocument::new(name);
2109 let mut confs = std::collections::BTreeMap::new();
2110 for (idx, (mut nodes, links, conf)) in results {
2111 assemble::stamp_page_no(&mut nodes, idx + 1);
2112 doc.nodes.extend(nodes);
2113 doc.links.extend(links);
2114 confs.insert(idx + 1, conf);
2115 }
2116 assemble::merge_continuations(&mut doc.nodes);
2117 self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes), password);
2118 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2119 Ok(doc)
2120 }
2121
2122 /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
2123 /// in-document-order batch of nodes (and that span's recovered links) as pages
2124 /// complete, so a caller can serialize Markdown page by page instead of waiting
2125 /// for the whole document. The batches are exactly the buffered [`convert`]'s
2126 /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
2127 /// parallel path reorders pages back into document order before emitting, so
2128 /// the output is identical regardless of worker scheduling.
2129 ///
2130 /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
2131 /// and its backpressure throttles the whole pipeline. Returning `Err` from
2132 /// `emit` aborts the conversion with that error.
2133 pub fn convert_streaming<F>(
2134 &mut self,
2135 bytes: &[u8],
2136 password: Option<&str>,
2137 name: &str,
2138 emit: F,
2139 ) -> Result<(), PdfError>
2140 where
2141 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2142 {
2143 let _ = name; // page nodes carry no name; the caller owns the document name.
2144 let pages = pdfium_backend::page_count(bytes, password)?;
2145 let range = self.resolve_range(pages)?;
2146 let selected = range.map_or(pages, |(a, b)| b - a + 1);
2147 let r = if self.target_workers >= 2 && selected >= self.parallel_min {
2148 self.convert_streaming_parallel(bytes, password, range, emit)
2149 } else {
2150 self.convert_streaming_serial(bytes, password, range, emit)
2151 };
2152 timing::report();
2153 r
2154 }
2155
2156 /// Serial streaming: render → process → emit, one page at a time, holding back
2157 /// only the tail that might still merge into the next page.
2158 fn convert_streaming_serial<F>(
2159 &mut self,
2160 bytes: &[u8],
2161 password: Option<&str>,
2162 range: Option<(usize, usize)>,
2163 mut emit: F,
2164 ) -> Result<(), PdfError>
2165 where
2166 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2167 {
2168 let mut asm = assemble::StreamAssembler::new();
2169 let render_image = !self.no_ocr;
2170 let extract_text = self.extract_text_layer();
2171 let worker = self.primary()?;
2172 pdfium_backend::for_each_page(
2173 bytes,
2174 password,
2175 render_image,
2176 extract_text,
2177 range,
2178 |n, _total, mut page| {
2179 // Confidence is dropped on the streaming path: the report is
2180 // only complete once every page has run, which defeats
2181 // page-by-page emission — buffered `convert` carries it.
2182 let (nodes, links, _conf) = worker.process(n, &mut page)?;
2183 emit(asm.push(nodes), links)
2184 },
2185 )?;
2186 emit(asm.finish(), Vec::new())
2187 }
2188
2189 /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
2190 /// not thread-safe) and process across the worker pool; results carry their
2191 /// page index and are reordered on the calling thread into a
2192 /// [`assemble::StreamAssembler`], which emits each page in document order as
2193 /// soon as its predecessors have arrived. Bounded channels keep only a handful
2194 /// of pages resident and let `emit`'s backpressure reach the renderer.
2195 fn convert_streaming_parallel<F>(
2196 &mut self,
2197 bytes: &[u8],
2198 password: Option<&str>,
2199 range: Option<(usize, usize)>,
2200 mut emit: F,
2201 ) -> Result<(), PdfError>
2202 where
2203 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2204 {
2205 self.ensure_pool()?;
2206 let n_workers = self.pool.len();
2207 let render_image = !self.no_ocr;
2208 let extract_text = self.extract_text_layer();
2209 let layout_batch = pdf_layout_batch();
2210 // Bound sized so every worker can accumulate a full layout batch while
2211 // rendering stays ahead (and never below the pre-#73 render-ahead of
2212 // two pages per worker); still a hard cap on resident page bitmaps.
2213 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2214 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2215 // Workers and the renderer report here; the calling thread drains it in
2216 // page order. Bounded so workers block (bounding resident bitmaps) when the
2217 // consumer falls behind.
2218 let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
2219
2220 let mut workers = std::mem::take(&mut self.pool);
2221 let mut asm = assemble::StreamAssembler::new();
2222 let mut first_err: Option<PdfError> = None;
2223
2224 std::thread::scope(|s| {
2225 // Workers: pull a batch of pages (whatever is already rendered, up
2226 // to the layout batch size), process it, report (index-tagged)
2227 // results.
2228 for worker in workers.iter_mut() {
2229 let work_rx = Arc::clone(&work_rx);
2230 let res_tx = res_tx.clone();
2231 s.spawn(move || {
2232 worker.run_pool(&work_rx, layout_batch, |idx, out| {
2233 // `false` once the consumer is gone.
2234 res_tx.send(out.map(|o| (idx, o))).is_ok()
2235 });
2236 });
2237 }
2238 // Renderer: feed pages to the pool on its own thread (pdfium stays on a
2239 // single thread); report a render error through the same channel.
2240 {
2241 let res_tx = res_tx.clone();
2242 s.spawn(move || {
2243 let render = pdfium_backend::for_each_page(
2244 bytes,
2245 password,
2246 render_image,
2247 extract_text,
2248 range,
2249 |i, _total, page| {
2250 work_tx
2251 .send((i, page))
2252 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2253 },
2254 );
2255 drop(work_tx); // signal workers to finish
2256 if let Err(e) = render {
2257 let _ = res_tx.send(Err(e));
2258 }
2259 });
2260 }
2261 // Drop our own sender so the channel closes once the threads finish.
2262 drop(res_tx);
2263
2264 // Collector (this thread): reorder into document order and emit.
2265 // With a page window, indices start at the window's first page.
2266 let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
2267 let mut next = range.map_or(0, |(first, _)| first);
2268 for msg in res_rx.iter() {
2269 match msg {
2270 Err(e) => {
2271 if first_err.is_none() {
2272 first_err = Some(e);
2273 }
2274 }
2275 Ok((idx, out)) => {
2276 buffer.insert(idx, out);
2277 if first_err.is_some() {
2278 continue; // keep draining so the threads can exit
2279 }
2280 while let Some((nodes, links, _conf)) = buffer.remove(&next) {
2281 if let Err(e) = emit(asm.push(nodes), links) {
2282 first_err = Some(e);
2283 break;
2284 }
2285 next += 1;
2286 }
2287 }
2288 }
2289 }
2290 });
2291 // Threads have joined; restore the pool for the next conversion.
2292 self.pool = workers;
2293
2294 if let Some(e) = first_err {
2295 return Err(e);
2296 }
2297 emit(asm.finish(), Vec::new())
2298 }
2299
2300 /// Lazily grow the pool to `target_workers`, loading the new workers
2301 /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
2302 /// one load's wall-time). Cached for reuse across documents.
2303 fn ensure_pool(&mut self) -> Result<(), PdfError> {
2304 let need = self.target_workers.saturating_sub(self.pool.len());
2305 if need == 0 {
2306 return Ok(());
2307 }
2308 let intra = pdf_intra();
2309 let no_ocr = self.no_ocr;
2310 let skip_ocr = self.skip_ocr;
2311 let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2312 let ntp = self.no_text_panels;
2313 let ocr_lang = self.ocr_lang;
2314 let ocr_scale = self.ocr_scale;
2315 let enrich = self.enrich;
2316 let tables = self.tables_slot();
2317 let enrich_slots = self.enrich_slots();
2318 let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
2319 let handles: Vec<_> = (0..need)
2320 .map(|_| {
2321 let tables = tables.clone();
2322 let enrich_slots = enrich_slots.clone();
2323 s.spawn(move || {
2324 Worker::load(
2325 intra,
2326 tables,
2327 enrich_slots,
2328 enrich,
2329 no_ocr,
2330 skip_ocr,
2331 force,
2332 ntp,
2333 ocr_lang,
2334 ocr_scale,
2335 )
2336 })
2337 })
2338 .collect();
2339 handles.into_iter().map(|h| h.join().unwrap()).collect()
2340 });
2341 for w in loaded {
2342 self.pool.push(w?);
2343 }
2344 Ok(())
2345 }
2346
2347 /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
2348 /// docling routes images through the same layout+OCR pipeline as a PDF page.
2349 pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2350 let image = decode_image_limited(bytes)?;
2351 let (w, h) = image.dimensions();
2352 // The image is its own page rendered at 1 px per "point" (scale 1.0); a
2353 // standalone image has no text layer, so OCR supplies the cells.
2354 let page = PdfPage {
2355 width: w as f32,
2356 height: h as f32,
2357 scale: 1.0,
2358 cells: Vec::new(),
2359 code_cells: Vec::new(),
2360 word_cells: Vec::new(),
2361 // A standalone image *is* its own scale-1.0 page image, so the
2362 // layout model sees it through the docling-exact PIL kernel.
2363 image_layout: Some(image.clone()),
2364 image,
2365 links: Vec::new(),
2366 rotation: 0,
2367 };
2368 self.process_pages(vec![page], name)
2369 }
2370
2371 /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
2372 /// page (image / METS inputs, which are small and already materialised).
2373 /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
2374 /// caller-configured pipeline (#244).
2375 pub fn process_pages(
2376 &mut self,
2377 mut pages: Vec<PdfPage>,
2378 name: &str,
2379 ) -> Result<DoclingDocument, PdfError> {
2380 let mut doc = DoclingDocument::new(name);
2381 let mut confs = std::collections::BTreeMap::new();
2382 let worker = self.primary()?;
2383 for (n, page) in pages.iter_mut().enumerate() {
2384 let (mut nodes, links, conf) = worker.process(n, page)?;
2385 assemble::stamp_page_no(&mut nodes, n + 1);
2386 doc.nodes.extend(nodes);
2387 doc.links.extend(links);
2388 confs.insert(n + 1, conf);
2389 }
2390 assemble::merge_continuations(&mut doc.nodes);
2391 // No PDF behind these pages (images, METS): the heading-hierarchy
2392 // stage degrades to the numbering signal — exactly docling without
2393 // an outline or parsed pages.
2394 self.apply_heading_hierarchy(&mut doc.nodes, None, None);
2395 doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2396 Ok(doc)
2397 }
2398}
2399
2400/// Number of pages in a PDF, without converting anything — what the CLI batch
2401/// mode prints in its per-document start line.
2402#[cfg(feature = "ml")]
2403pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
2404 Ok(pdfium_backend::page_count(bytes, password)?)
2405}
2406
2407#[cfg(feature = "ml")]
2408/// Convenience one-shot conversion (loads the pipeline per call). Errors are
2409/// detailed and surfaced (never silently skipped).
2410pub fn convert(
2411 bytes: &[u8],
2412 password: Option<&str>,
2413 name: &str,
2414) -> Result<DoclingDocument, PdfError> {
2415 convert_with_options(
2416 bytes,
2417 password,
2418 name,
2419 false,
2420 false,
2421 false,
2422 false,
2423 EnrichmentOptions::default(),
2424 None,
2425 None,
2426 )
2427}
2428
2429#[cfg(feature = "ml")]
2430/// Like [`convert`], but optionally skips loading/running TableFormer (see
2431/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2432/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
2433/// [`Pipeline::enrichments`]).
2434// One positional per pipeline switch mirrors the Pipeline builder; growing
2435// past clippy's arity cap is the price of keeping this one-shot signature
2436// stable-ish instead of churning callers into an options struct mid-series.
2437#[allow(clippy::too_many_arguments)]
2438pub fn convert_with_options(
2439 bytes: &[u8],
2440 password: Option<&str>,
2441 name: &str,
2442 no_table_former: bool,
2443 no_ocr: bool,
2444 force_full_page_ocr: bool,
2445 no_text_panels: bool,
2446 enrich: EnrichmentOptions,
2447 pages: Option<(usize, usize)>,
2448 ocr_lang: Option<OcrLang>,
2449) -> Result<DoclingDocument, PdfError> {
2450 Pipeline::new()?
2451 .no_table_former(no_table_former)
2452 .no_ocr(no_ocr)
2453 .force_full_page_ocr(force_full_page_ocr)
2454 .no_text_panels(no_text_panels)
2455 .enrichments(enrich)
2456 .pages(pages)
2457 .ocr_lang(ocr_lang)
2458 .convert(bytes, password, name)
2459}
2460
2461#[cfg(feature = "ml")]
2462/// Convenience one-shot image conversion (loads the pipeline per call).
2463pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2464 convert_image_with_options(
2465 bytes,
2466 name,
2467 false,
2468 false,
2469 false,
2470 EnrichmentOptions::default(),
2471 None,
2472 )
2473}
2474
2475#[cfg(feature = "ml")]
2476/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
2477/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2478/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2479pub fn convert_image_with_options(
2480 bytes: &[u8],
2481 name: &str,
2482 no_table_former: bool,
2483 no_ocr: bool,
2484 no_text_panels: bool,
2485 enrich: EnrichmentOptions,
2486 ocr_lang: Option<OcrLang>,
2487) -> Result<DoclingDocument, PdfError> {
2488 Pipeline::new()?
2489 .no_table_former(no_table_former)
2490 .no_ocr(no_ocr)
2491 .no_text_panels(no_text_panels)
2492 .enrichments(enrich)
2493 .ocr_lang(ocr_lang)
2494 .convert_image(bytes, name)
2495}
2496
2497#[cfg(feature = "ml")]
2498/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
2499/// scans) through the shared layout + assembly pipeline.
2500pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
2501 convert_pages_with_options(
2502 pages,
2503 name,
2504 false,
2505 false,
2506 false,
2507 EnrichmentOptions::default(),
2508 )
2509}
2510
2511#[cfg(feature = "ml")]
2512/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
2513/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2514/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2515pub fn convert_pages_with_options(
2516 pages: Vec<PdfPage>,
2517 name: &str,
2518 no_table_former: bool,
2519 no_ocr: bool,
2520 no_text_panels: bool,
2521 enrich: EnrichmentOptions,
2522) -> Result<DoclingDocument, PdfError> {
2523 Pipeline::new()?
2524 .no_table_former(no_table_former)
2525 .no_text_panels(no_text_panels)
2526 .no_ocr(no_ocr)
2527 .enrichments(enrich)
2528 .process_pages(pages, name)
2529}
2530
2531#[cfg(feature = "ml")]
2532#[cfg(all(test, feature = "ml"))]
2533mod image_limit_tests {
2534 use super::decode_image_with_max_side;
2535
2536 /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
2537 /// byte literal).
2538 fn png_bytes(w: u32, h: u32) -> Vec<u8> {
2539 use std::io::Cursor;
2540 let img = image::RgbImage::new(w, h);
2541 let mut out = Vec::new();
2542 img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
2543 .unwrap();
2544 out
2545 }
2546
2547 #[test]
2548 fn normal_image_decodes_under_the_cap() {
2549 let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
2550 assert_eq!(img.dimensions(), (8, 8));
2551 }
2552
2553 #[test]
2554 fn dimensions_over_the_cap_are_rejected_not_aborted() {
2555 // A per-side cap below the image's declared size must yield a
2556 // recoverable Err, never an allocation-abort — the mechanism that stops
2557 // a crafted image declaring 60000×60000 from OOM-killing the process.
2558 let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
2559 assert!(
2560 r.is_err(),
2561 "decode must fail under the pixel cap, not abort"
2562 );
2563 }
2564}
2565
2566#[cfg(test)]
2567mod median_tests {
2568 #[test]
2569 fn median_of_empty_is_zero_not_a_panic() {
2570 // A crafted table can leave a row/column with zero matched cells; the
2571 // even-count branch would index values[0 - 1] and panic (→ remote crash
2572 // via docling-serve) without the empty guard.
2573 assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
2574 assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
2575 assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
2576 }
2577}
2578
2579#[cfg(test)]
2580mod send_check {
2581 /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
2582 /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
2583 /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
2584 /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
2585 fn assert_send<T: Send>() {}
2586
2587 #[test]
2588 fn pipeline_is_send() {
2589 assert_send::<super::Pipeline>();
2590 }
2591}
2592
2593#[cfg(all(test, feature = "ml"))]
2594mod ocr_input_tests {
2595 /// #254: without an `ocr_scale` (or with one equal to the render scale)
2596 /// the OCR reads the page render untouched and the cache stays cold; a
2597 /// different scale builds one resampled view, reuses it across calls, and
2598 /// reports the requested px/pt so cell geometry divides back to points.
2599 #[test]
2600 fn ocr_input_resamples_only_on_a_real_scale_change() {
2601 let img = image::RgbImage::new(200, 100);
2602 let mut cache = None;
2603 let (v, s) = super::ocr_input(&mut cache, &img, 2.0, None);
2604 assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
2605 let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(2.0));
2606 assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
2607
2608 let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
2609 assert_eq!((v.width(), v.height(), s), (300, 150, 3.0));
2610 let first = cache.as_ref().map(|c| c as *const image::RgbImage);
2611 let (v, _) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
2612 assert_eq!(
2613 Some(v as *const image::RgbImage),
2614 first,
2615 "cached, not rebuilt"
2616 );
2617
2618 let mut down = None;
2619 let (v, s) = super::ocr_input(&mut down, &img, 2.0, Some(1.0));
2620 assert_eq!((v.width(), v.height(), s), (100, 50, 1.0));
2621 }
2622}