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