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