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