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