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
12mod assemble;
13mod dp_lines;
14pub mod enrich;
15pub(crate) mod ep;
16pub mod layout;
17mod mets;
18mod ocr;
19pub mod pdfium_backend;
20mod reading_order;
21pub mod resample;
22pub mod tableformer;
23pub mod textparse;
24mod tf_match;
25pub mod timing;
26
27use std::collections::BTreeMap;
28use std::fmt;
29use std::sync::mpsc::{sync_channel, Receiver};
30use std::sync::{Arc, Mutex};
31
32use docling_core::{DoclingDocument, Node};
33
34pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options};
35pub use pdfium_backend::{PdfDocument, PdfPage, TextCell};
36
37/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
38#[derive(Debug)]
39pub enum PdfError {
40 /// pdfium failed to bind, open, or read the document.
41 Pdfium(String),
42 /// The layout ONNX model failed to load or run.
43 Layout(String),
44 /// The OCR ONNX model failed to load or run.
45 Ocr(String),
46}
47
48impl fmt::Display for PdfError {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 match self {
51 PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
52 PdfError::Layout(m) => write!(f, "pdf: {m}"),
53 PdfError::Ocr(m) => write!(f, "pdf: {m}"),
54 }
55 }
56}
57
58impl std::error::Error for PdfError {}
59
60impl From<pdfium_render::prelude::PdfiumError> for PdfError {
61 fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
62 PdfError::Pdfium(e.to_string())
63 }
64}
65
66/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
67/// Defaults to the available parallelism (ort otherwise picks a low number).
68pub(crate) fn intra_threads() -> usize {
69 if let Some(n) = std::env::var("DOCLING_RS_PDF_THREADS")
70 .ok()
71 .and_then(|v| v.parse::<usize>().ok())
72 .filter(|&n| n > 0)
73 {
74 return n;
75 }
76 std::thread::available_parallelism()
77 .map(|n| n.get())
78 .unwrap_or(1)
79}
80
81/// True when `DOCLING_RS_FP32` (any value but `0`) forces the full-precision
82/// models even where an INT8 variant sits next to the fp32 default.
83pub(crate) fn fp32_forced() -> bool {
84 std::env::var("DOCLING_RS_FP32")
85 .map(|v| v != "0")
86 .unwrap_or(false)
87}
88
89/// Should the int8 model defaults be skipped in favor of fp32? Either the
90/// user said so (`DOCLING_RS_FP32`), or a GPU execution provider is selected
91/// (#74) — the int8 exports are QDQ graphs calibrated for CPU kernels and
92/// only conformance-validated there. An explicit `DOCLING_*_ONNX` path
93/// override still wins over this at every call site.
94pub(crate) fn prefer_fp32() -> bool {
95 fp32_forced() || ep::prefers_fp32()
96}
97
98/// Resolve a default (CWD-relative) asset path. If it doesn't exist relative
99/// to the current directory, try next to the executable and one level above
100/// it (following symlinks — the layout `scripts/install/install.sh` produces:
101/// `/usr/local/bin/docling-rs` → `/usr/local/docling.rs/bin/docling-rs`
102/// with `models/` and `.pdfium/` in `/usr/local/docling.rs`). Lets an
103/// installed binary run from any working directory with no env vars; explicit
104/// env overrides never reach this. Returns `rel` unchanged when nothing
105/// exists anywhere, so callers' error messages keep the familiar path.
106pub(crate) fn resolve_asset(rel: &str) -> String {
107 if std::path::Path::new(rel).exists() {
108 return rel.to_string();
109 }
110 if let Some(dir) = std::env::current_exe()
111 .ok()
112 .and_then(|p| p.canonicalize().ok())
113 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
114 {
115 for base in [Some(dir.as_path()), dir.parent()].into_iter().flatten() {
116 let p = base.join(rel);
117 if p.exists() {
118 return p.to_string_lossy().into_owned();
119 }
120 }
121 }
122 rel.to_string()
123}
124
125/// Resolve a model path: an explicit env override always wins; otherwise the
126/// INT8 variant of the default path when it exists on disk (the quantized
127/// models are conformance-validated — see docs/PDF_CONFORMANCE.md — and load/run
128/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
129/// precision; else the fp32 default.
130pub(crate) fn model_path(env: &str, fp32_default: &str, int8_default: &str) -> String {
131 if let Ok(p) = std::env::var(env) {
132 return p;
133 }
134 if !prefer_fp32() {
135 let p = resolve_asset(int8_default);
136 if std::path::Path::new(&p).exists() {
137 return p;
138 }
139 }
140 resolve_asset(fp32_default)
141}
142
143/// One page's assembled output: typed nodes plus the page's hyperlinks, kept
144/// separate so pages processed out of order can be stitched back in page order.
145type PageOut = (Vec<Node>, Vec<(String, String)>);
146
147/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
148/// lazily on the first table region any worker sees. Tables appear on a
149/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
150/// weights+arenas by the pool size for nothing; a single shared instance keeps
151/// the peak flat regardless of pool width, and a table's structure prediction
152/// is independent of which worker runs it, so output is byte-identical. The
153/// mutex serialises concurrent tables — the shared instance is loaded with the
154/// full intra-op thread budget to compensate (one wide TableFormer instead of
155/// several narrow ones).
156enum TfSlot {
157 /// Not attempted yet (no table seen so far).
158 Unloaded,
159 /// Load attempted, graphs absent — geometric fallback (warned once).
160 Missing,
161 Ready(tableformer::TableFormer),
162}
163
164type SharedTables = Arc<Mutex<TfSlot>>;
165
166/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
167/// one instance per pipeline, loaded on the first region that needs it.
168enum EnrichSlot<T> {
169 Unloaded,
170 /// Load attempted, model files absent — enrichment skipped (warned once).
171 Missing,
172 Ready(T),
173}
174
175type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
176type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
177
178/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
179/// flags (`do_picture_classification`, `do_code_enrichment`,
180/// `do_formula_enrichment`). All off by default.
181#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
182pub struct EnrichmentOptions {
183 /// Classify each picture with DocumentFigureClassifier (26 classes).
184 pub picture_classification: bool,
185 /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
186 pub code: bool,
187 /// Decode display formulas to LaTeX with CodeFormulaV2.
188 pub formula: bool,
189}
190
191impl EnrichmentOptions {
192 fn any(&self) -> bool {
193 self.picture_classification || self.code || self.formula
194 }
195}
196
197/// A self-contained set of the per-page models (layout, OCR). Each parallel
198/// page-worker owns its own `Worker` so inference runs concurrently without
199/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
200/// rarely-hit TableFormer is shared (see [`TfSlot`]).
201struct Worker {
202 /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
203 layout: Option<layout::LayoutModel>,
204 ocr: Option<ocr::OcrModel>,
205 /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
206 tables: Option<SharedTables>,
207 /// Shared enrichment slots; `None` unless the corresponding flag is on.
208 classifier: Option<SharedClassifier>,
209 code_formula: Option<SharedCodeFormula>,
210 enrich: EnrichmentOptions,
211 /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
212 /// embedded text layer. See [`Pipeline::no_ocr`].
213 no_ocr: bool,
214}
215
216impl Worker {
217 fn load(
218 intra: usize,
219 tables: Option<SharedTables>,
220 enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
221 enrich: EnrichmentOptions,
222 no_ocr: bool,
223 ) -> Result<Self, PdfError> {
224 Ok(Self {
225 layout: if no_ocr {
226 None
227 } else {
228 Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
229 },
230 ocr: None,
231 tables,
232 classifier: enrich_slots.0,
233 code_formula: enrich_slots.1,
234 enrich,
235 no_ocr,
236 })
237 }
238
239 /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
240 /// into its nodes and links. Pure given the page (mutates only the worker's
241 /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
242 fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
243 if self.no_ocr {
244 // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
245 // embedded text cells (if any) become flat, line-grouped paragraphs in
246 // reading order via the same orphan-region machinery that normally
247 // rescues text the detector missed — here it rescues *all* of it.
248 // Pages with no embedded text layer (scanned/image-only) yield nothing;
249 // convert those without `no_ocr`.
250 let mut regions = Vec::new();
251 assemble::add_orphan_regions(&mut regions, &page.cells);
252 let table_rows = vec![None; regions.len()];
253 let enrich_out = vec![None; regions.len()];
254 return Ok(timing::timed("assemble_page", || {
255 assemble::assemble_page(page, regions, &table_rows, &enrich_out)
256 }));
257 }
258 let regions = timing::timed("layout.predict", || {
259 self.layout
260 .as_mut()
261 .expect("layout model loaded unless no_ocr")
262 .predict(&page.image, page.width, page.height)
263 })
264 .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
265 self.finish_page(n, page, regions)
266 }
267
268 /// Layout-detect a whole batch of pages with one inference call (issue #73),
269 /// then run each page's remaining stages (OCR / TableFormer / enrichment /
270 /// assembly) per page. Index-aligned with `items`; a layout failure fails
271 /// every page in the batch (they shared the one inference call).
272 fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<PageOut, PdfError>> {
273 if self.no_ocr {
274 // No layout model to batch — the text-layer-only path is per page.
275 return items
276 .iter_mut()
277 .map(|(n, page)| {
278 let n = *n;
279 self.process(n, page)
280 })
281 .collect();
282 }
283 let inputs: Vec<(&image::RgbImage, f32, f32)> = items
284 .iter()
285 .map(|(_, page)| (&page.image, page.width, page.height))
286 .collect();
287 let batched = timing::timed("layout.predict", || {
288 self.layout
289 .as_mut()
290 .expect("layout model loaded unless no_ocr")
291 .predict_batch(&inputs)
292 });
293 match batched {
294 Ok(all) => items
295 .iter_mut()
296 .zip(all)
297 .map(|((n, page), regions)| self.finish_page(*n, page, regions))
298 .collect(),
299 Err(e) => items
300 .iter()
301 .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
302 .collect(),
303 }
304 }
305
306 /// Everything after layout detection: per-label confidence thresholds,
307 /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
308 /// TableFormer, enrichment, and page assembly.
309 fn finish_page(
310 &mut self,
311 n: usize,
312 page: &mut PdfPage,
313 regions: Vec<layout::Region>,
314 ) -> Result<PageOut, PdfError> {
315 // docling's LayoutPostprocessor drops each detection below its label's
316 // confidence threshold (stricter than the 0.3 base the predictor keeps),
317 // before any overlap resolution. This removes the low-confidence tables /
318 // pictures / list-items that otherwise double-emit or mis-classify.
319 let mut regions = regions;
320 regions.retain(|r| r.score >= layout::label_threshold(r.label));
321 // Resolve overlapping detections once, before OCR.
322 let mut regions = assemble::resolve(regions);
323 // Emit text the detector missed as orphan text regions (docling parity).
324 assemble::add_orphan_regions(&mut regions, &page.cells);
325 // Drop phantom empty low-confidence picture boxes (docling parity).
326 assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
327 // A regular region fully inside a surviving table/index/picture is that
328 // special's child (a cell / in-figure label), not a separate block —
329 // remove it so it isn't emitted twice (docling parity).
330 assemble::drop_contained_regulars(&mut regions);
331 // No text layer → recognise text from the page image via OCR.
332 if page.cells.is_empty() {
333 if self.ocr.is_none() {
334 self.ocr = Some(ocr::OcrModel::load().map_err(PdfError::Ocr)?);
335 }
336 let cells = timing::timed("ocr.page", || {
337 self.ocr
338 .as_mut()
339 .unwrap()
340 .ocr_page(&page.image, ®ions, page.scale)
341 })
342 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
343 page.cells = cells;
344 }
345 // TableFormer structure per table region (else geometric fallback). The
346 // shared slot is only locked (and lazily loaded) when the page actually
347 // has a table, so table-free documents never pay for TableFormer at all.
348 let mut table_rows: Vec<Option<Vec<Vec<String>>>> = vec![None; regions.len()];
349 if let Some(slot) = self.tables.as_ref() {
350 if regions.iter().any(|r| assemble::is_table_like(r.label)) {
351 timing::timed("tableformer", || {
352 let mut guard = slot.lock().unwrap();
353 if matches!(*guard, TfSlot::Unloaded) {
354 // Full intra-op width: tables serialise on this mutex, so
355 // the one instance gets the whole thread budget.
356 *guard = match tableformer::TableFormer::load_with(intra_threads()) {
357 Some(tf) => TfSlot::Ready(tf),
358 None => TfSlot::Missing,
359 };
360 }
361 if let TfSlot::Ready(tf) = &mut *guard {
362 for (i, r) in regions.iter().enumerate() {
363 if assemble::is_table_like(r.label) {
364 table_rows[i] = tf.predict_table_rows(
365 &page.image,
366 [r.l, r.t, r.r, r.b],
367 &page.word_cells,
368 );
369 }
370 }
371 }
372 });
373 }
374 }
375 // Enrichment passes (opt-in): DocumentPictureClassifier over picture
376 // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
377 // shape as TableFormer — one lazily-loaded instance per pipeline, only
378 // ever locked when a page actually has a matching region.
379 let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
380 if let Some(slot) = self.classifier.as_ref() {
381 if regions.iter().any(|r| r.label == "picture") {
382 timing::timed("picture_classifier", || {
383 let mut guard = slot.lock().unwrap();
384 if matches!(*guard, EnrichSlot::Unloaded) {
385 *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
386 Some(m) => EnrichSlot::Ready(m),
387 None => EnrichSlot::Missing,
388 };
389 }
390 if let EnrichSlot::Ready(model) = &mut *guard {
391 for (i, r) in regions.iter().enumerate() {
392 if r.label != "picture" {
393 continue;
394 }
395 let Some(crop) = assemble::crop_region_scaled(
396 page,
397 [r.l, r.t, r.r, r.b],
398 enrich::CLASSIFIER_SCALE,
399 ) else {
400 continue;
401 };
402 match model.classify(&crop) {
403 Ok(classes) => {
404 enrich_out[i] =
405 Some(assemble::Enrichment::PictureClasses(classes));
406 }
407 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
408 }
409 }
410 }
411 });
412 }
413 }
414 if let Some(slot) = self.code_formula.as_ref() {
415 let wants = |label: &str| {
416 (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
417 };
418 if regions.iter().any(|r| wants(r.label)) {
419 timing::timed("code_formula", || {
420 let mut guard = slot.lock().unwrap();
421 if matches!(*guard, EnrichSlot::Unloaded) {
422 *guard = match enrich::CodeFormula::load_with(intra_threads()) {
423 Some(m) => EnrichSlot::Ready(m),
424 None => EnrichSlot::Missing,
425 };
426 }
427 if let EnrichSlot::Ready(model) = &mut *guard {
428 for (i, r) in regions.iter().enumerate() {
429 if !wants(r.label) {
430 continue;
431 }
432 // docling crops the postprocessed cluster box — the
433 // union of the region's text cells, not the raw
434 // detector box — expanded by 18% per side, at
435 // ~120 dpi.
436 let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
437 .unwrap_or([r.l, r.t, r.r, r.b]);
438 let (w, h) = (br - bl, bb - bt);
439 let ex = enrich::CODE_FORMULA_EXPANSION;
440 let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
441 let Some(crop) = assemble::crop_region_scaled(
442 page,
443 bbox,
444 enrich::CODE_FORMULA_SCALE,
445 ) else {
446 continue;
447 };
448 let kind = if r.label == "code" {
449 enrich::CodeFormulaKind::Code
450 } else {
451 enrich::CodeFormulaKind::Formula
452 };
453 match model.predict(&crop, kind) {
454 Ok(text) => {
455 enrich_out[i] = Some(match kind {
456 enrich::CodeFormulaKind::Code => {
457 let (code, language) =
458 enrich::extract_code_language(&text);
459 assemble::Enrichment::Code {
460 language,
461 text: code,
462 }
463 }
464 enrich::CodeFormulaKind::Formula => {
465 assemble::Enrichment::Formula { latex: text }
466 }
467 });
468 }
469 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
470 }
471 }
472 }
473 });
474 }
475 }
476 Ok(timing::timed("assemble_page", || {
477 assemble::assemble_page(page, regions, &table_rows, &enrich_out)
478 }))
479 }
480}
481
482/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
483/// so on a typical machine two threads per worker (sharing one in-cache copy of
484/// the weights) extracts more throughput than one fat model or many single-thread
485/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
486fn pdf_intra() -> usize {
487 if let Some(n) = std::env::var("DOCLING_RS_PDF_INTRA")
488 .ok()
489 .and_then(|v| v.parse::<usize>().ok())
490 .filter(|&n| n > 0)
491 {
492 return n;
493 }
494 if intra_threads() >= 2 {
495 2
496 } else {
497 1
498 }
499}
500
501/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
502/// overrides; otherwise size the pool so `workers × intra ≈ cores`, capped at 4 so
503/// a worst-case pool holds a bounded amount of model memory (~0.4 GB per worker)
504/// and does not oversaturate the memory bus with model-weight traffic.
505fn pdf_worker_count() -> usize {
506 if let Some(n) = std::env::var("DOCLING_RS_PDF_WORKERS")
507 .ok()
508 .and_then(|v| v.parse::<usize>().ok())
509 .filter(|&n| n > 0)
510 {
511 return n;
512 }
513 (intra_threads() / pdf_intra()).clamp(1, 4)
514}
515
516/// Max pages a worker layout-detects with one batched inference call (issue
517/// #73). Workers drain the work channel opportunistically up to this size —
518/// whatever is already rendered gets batched, so batching never *waits* for
519/// pages and adds no latency when rendering is the bottleneck.
520///
521/// Default: 4 on 8+ cores, 1 (per-page) below. Measured on a 4-core box the
522/// batch only adds cache pressure and costs pipeline overlap (2 workers × 2
523/// threads: 8.1 s/conv at batch=1 vs 9.3 s at batch=4 on the 9-page
524/// 2206.01062 fixture); the single-session amortization it buys needs the
525/// wider thread budget of a many-core machine. Output is bit-identical at
526/// every batch size, so this is purely a throughput knob.
527/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides; `1` restores per-page inference.
528fn pdf_layout_batch() -> usize {
529 std::env::var("DOCLING_RS_PDF_LAYOUT_BATCH")
530 .ok()
531 .and_then(|v| v.parse::<usize>().ok())
532 .filter(|&n| n > 0)
533 .unwrap_or_else(|| if intra_threads() >= 8 { 4 } else { 1 })
534}
535
536/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
537/// the serial primary (running its model on every core) is faster than fanning out
538/// — the helper pool's one-time model-load cost only pays off once enough pages
539/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
540fn pdf_parallel_min() -> usize {
541 std::env::var("DOCLING_RS_PDF_PARALLEL_MIN")
542 .ok()
543 .and_then(|v| v.parse::<usize>().ok())
544 .filter(|&n| n > 0)
545 .unwrap_or(6)
546}
547
548/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
549/// so a single-page / small / image / METS input is converted at full intra-op
550/// speed with no pool to load. A document with enough pages instead fans out
551/// across a **pool** of narrower workers processed concurrently. Both load lazily
552/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
553pub struct Pipeline {
554 /// Full-intra worker for the serial path; loaded on first serial use.
555 primary: Option<Worker>,
556 /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
557 /// path; loaded on first multi-page use and cached.
558 pool: Vec<Worker>,
559 /// The single TableFormer instance every worker shares (see [`TfSlot`]).
560 tables: SharedTables,
561 /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
562 classifier: SharedClassifier,
563 code_formula: SharedCodeFormula,
564 /// Desired pool size for multi-page documents.
565 target_workers: usize,
566 /// Page count at/above which the parallel pool is worth its load cost.
567 parallel_min: usize,
568 /// Skip loading/running TableFormer; table regions fall back to geometric
569 /// reconstruction. See [`Pipeline::no_table_former`].
570 no_table_former: bool,
571 /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
572 no_ocr: bool,
573 /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
574 enrich: EnrichmentOptions,
575}
576
577impl Pipeline {
578 /// Construct the pipeline. Models load lazily on first use (full-intra primary
579 /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
580 /// loaded that a given document doesn't need.
581 pub fn new() -> Result<Self, PdfError> {
582 Ok(Self {
583 primary: None,
584 pool: Vec::new(),
585 tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
586 classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
587 code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
588 target_workers: pdf_worker_count(),
589 parallel_min: pdf_parallel_min(),
590 no_table_former: false,
591 no_ocr: false,
592 enrich: EnrichmentOptions::default(),
593 })
594 }
595
596 /// Enable the opt-in enrichment passes (docling's
597 /// `do_picture_classification` / `do_code_enrichment` /
598 /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
599 /// the first matching region; a missing model warns once and is skipped.
600 /// Set before the first conversion (no effect on already-loaded workers).
601 pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
602 self.enrich = opts;
603 self
604 }
605
606 /// Skip loading and running the TableFormer table-structure model. Table
607 /// regions still get emitted, but reconstructed geometrically from cell
608 /// positions instead of via the ONNX model's predicted structure — faster
609 /// (no model load, no per-table inference) at the cost of table fidelity.
610 /// No effect if a worker is already loaded; set this before the first
611 /// conversion.
612 pub fn no_table_former(mut self, disable: bool) -> Self {
613 self.no_table_former = disable;
614 self
615 }
616
617 /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
618 /// inference of any kind. The PDF's embedded text cells are grouped by line
619 /// and emitted as plain paragraphs in reading order: no headings, lists,
620 /// tables, code blocks, or pictures, since that structure comes from the
621 /// layout model. The fastest possible PDF path, but pages with no embedded
622 /// text layer (scanned/image-only PDFs) yield no text at all — convert those
623 /// without this flag. Implies `no_table_former`. No effect if a worker is
624 /// already loaded; set this before the first conversion.
625 pub fn no_ocr(mut self, disable: bool) -> Self {
626 self.no_ocr = disable;
627 self
628 }
629
630 /// The shared TableFormer slot handed to each worker, or `None` when the
631 /// pipeline options skip TableFormer entirely.
632 fn tables_slot(&self) -> Option<SharedTables> {
633 if self.no_table_former || self.no_ocr {
634 None
635 } else {
636 Some(Arc::clone(&self.tables))
637 }
638 }
639
640 /// The shared enrichment slots for a worker (`None` per model unless its
641 /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
642 fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
643 if self.no_ocr || !self.enrich.any() {
644 return (None, None);
645 }
646 (
647 self.enrich
648 .picture_classification
649 .then(|| Arc::clone(&self.classifier)),
650 (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
651 )
652 }
653
654 /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
655 /// the shared TableFormer unless disabled) so the first conversion doesn't pay
656 /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
657 /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
658 /// `DocumentConverter.initialize_pipeline`.
659 pub fn warm_up(&mut self) -> Result<(), PdfError> {
660 self.primary()?;
661 Ok(())
662 }
663
664 /// The full-intra serial worker, loaded on first use.
665 fn primary(&mut self) -> Result<&mut Worker, PdfError> {
666 if self.primary.is_none() {
667 self.primary = Some(Worker::load(
668 intra_threads(),
669 self.tables_slot(),
670 self.enrich_slots(),
671 self.enrich,
672 self.no_ocr,
673 )?);
674 }
675 Ok(self.primary.as_mut().unwrap())
676 }
677
678 /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
679 /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
680 /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
681 /// fans the pages out across the worker pool, reassembled in page order so the
682 /// output is byte-identical to the serial path.
683 pub fn convert(
684 &mut self,
685 bytes: &[u8],
686 password: Option<&str>,
687 name: &str,
688 ) -> Result<DoclingDocument, PdfError> {
689 let pages = pdfium_backend::page_count(bytes, password)?;
690 let doc = if self.target_workers >= 2 && pages >= self.parallel_min {
691 self.convert_parallel(bytes, password, name)?
692 } else {
693 self.convert_serial(bytes, password, name)?
694 };
695 timing::report();
696 Ok(doc)
697 }
698
699 /// Stream pages one at a time through the primary worker — render → process →
700 /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
701 fn convert_serial(
702 &mut self,
703 bytes: &[u8],
704 password: Option<&str>,
705 name: &str,
706 ) -> Result<DoclingDocument, PdfError> {
707 let mut doc = DoclingDocument::new(name);
708 let render_image = !self.no_ocr;
709 let worker = self.primary()?;
710 pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
711 let (nodes, links) = worker.process(n, &mut page)?;
712 doc.nodes.extend(nodes);
713 doc.links.extend(links);
714 Ok::<(), PdfError>(())
715 })?;
716 assemble::merge_continuations(&mut doc.nodes);
717 Ok(doc)
718 }
719
720 /// Render pages serially on this thread (pdfium) and process them in parallel
721 /// across the worker pool. A bounded channel applies backpressure so only a
722 /// handful of page bitmaps are resident at once; results carry their page
723 /// index and are reassembled in order, so the output is byte-identical to the
724 /// serial path.
725 fn convert_parallel(
726 &mut self,
727 bytes: &[u8],
728 password: Option<&str>,
729 name: &str,
730 ) -> Result<DoclingDocument, PdfError> {
731 self.ensure_pool()?;
732 let n_workers = self.pool.len();
733 let render_image = !self.no_ocr;
734 let layout_batch = pdf_layout_batch();
735 // Bound sized so every worker can accumulate a full layout batch while
736 // rendering stays ahead (and never below the pre-#73 render-ahead of
737 // two pages per worker); still a hard cap on resident page bitmaps.
738 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
739 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
740 let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
741 let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
742
743 // Move the pool into the scope so each worker gets an exclusive `&mut`.
744 let mut workers = std::mem::take(&mut self.pool);
745 std::thread::scope(|s| {
746 for worker in workers.iter_mut() {
747 let work_rx = Arc::clone(&work_rx);
748 let results = Arc::clone(&results);
749 let first_err = Arc::clone(&first_err);
750 s.spawn(move || loop {
751 // Hold the receiver lock only for the recv (plus a non-blocking
752 // drain up to the layout batch size); release before the (long)
753 // per-page work so other workers can pull concurrently.
754 let mut batch = Vec::new();
755 {
756 let rx = work_rx.lock().unwrap();
757 match rx.recv() {
758 Ok(item) => {
759 batch.push(item);
760 while batch.len() < layout_batch {
761 match rx.try_recv() {
762 Ok(item) => batch.push(item),
763 Err(_) => break,
764 }
765 }
766 }
767 Err(_) => break,
768 }
769 }
770 let outs = worker.process_batch(&mut batch);
771 for ((idx, _), out) in batch.iter().zip(outs) {
772 match out {
773 Ok(out) => results.lock().unwrap().push((*idx, out)),
774 Err(e) => {
775 let mut slot = first_err.lock().unwrap();
776 if slot.is_none() {
777 *slot = Some(e);
778 }
779 }
780 }
781 }
782 });
783 }
784 // Render on this thread and feed the workers; backpressure blocks here
785 // when the channel is full. Dropping `work_tx` afterwards signals the
786 // workers (recv → Err) to finish.
787 let render =
788 pdfium_backend::for_each_page(bytes, password, render_image, |i, _total, page| {
789 work_tx
790 .send((i, page))
791 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
792 });
793 drop(work_tx);
794 if let Err(e) = render {
795 let mut slot = first_err.lock().unwrap();
796 if slot.is_none() {
797 *slot = Some(e);
798 }
799 }
800 });
801 // Threads have joined; restore the pool for the next conversion.
802 self.pool = workers;
803
804 if let Some(e) = first_err.lock().unwrap().take() {
805 return Err(e);
806 }
807 let mut results = Arc::try_unwrap(results)
808 .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
809 .into_inner()
810 .unwrap();
811 results.sort_by_key(|(idx, _)| *idx);
812 let mut doc = DoclingDocument::new(name);
813 for (_, (nodes, links)) in results {
814 doc.nodes.extend(nodes);
815 doc.links.extend(links);
816 }
817 assemble::merge_continuations(&mut doc.nodes);
818 Ok(doc)
819 }
820
821 /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
822 /// in-document-order batch of nodes (and that span's recovered links) as pages
823 /// complete, so a caller can serialize Markdown page by page instead of waiting
824 /// for the whole document. The batches are exactly the buffered [`convert`]'s
825 /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
826 /// parallel path reorders pages back into document order before emitting, so
827 /// the output is identical regardless of worker scheduling.
828 ///
829 /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
830 /// and its backpressure throttles the whole pipeline. Returning `Err` from
831 /// `emit` aborts the conversion with that error.
832 pub fn convert_streaming<F>(
833 &mut self,
834 bytes: &[u8],
835 password: Option<&str>,
836 name: &str,
837 emit: F,
838 ) -> Result<(), PdfError>
839 where
840 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
841 {
842 let _ = name; // page nodes carry no name; the caller owns the document name.
843 let pages = pdfium_backend::page_count(bytes, password)?;
844 let r = if self.target_workers >= 2 && pages >= self.parallel_min {
845 self.convert_streaming_parallel(bytes, password, emit)
846 } else {
847 self.convert_streaming_serial(bytes, password, emit)
848 };
849 timing::report();
850 r
851 }
852
853 /// Serial streaming: render → process → emit, one page at a time, holding back
854 /// only the tail that might still merge into the next page.
855 fn convert_streaming_serial<F>(
856 &mut self,
857 bytes: &[u8],
858 password: Option<&str>,
859 mut emit: F,
860 ) -> Result<(), PdfError>
861 where
862 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
863 {
864 let mut asm = assemble::StreamAssembler::new();
865 let render_image = !self.no_ocr;
866 let worker = self.primary()?;
867 pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
868 let (nodes, links) = worker.process(n, &mut page)?;
869 emit(asm.push(nodes), links)
870 })?;
871 emit(asm.finish(), Vec::new())
872 }
873
874 /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
875 /// not thread-safe) and process across the worker pool; results carry their
876 /// page index and are reordered on the calling thread into a
877 /// [`assemble::StreamAssembler`], which emits each page in document order as
878 /// soon as its predecessors have arrived. Bounded channels keep only a handful
879 /// of pages resident and let `emit`'s backpressure reach the renderer.
880 fn convert_streaming_parallel<F>(
881 &mut self,
882 bytes: &[u8],
883 password: Option<&str>,
884 mut emit: F,
885 ) -> Result<(), PdfError>
886 where
887 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
888 {
889 self.ensure_pool()?;
890 let n_workers = self.pool.len();
891 let render_image = !self.no_ocr;
892 let layout_batch = pdf_layout_batch();
893 // Bound sized so every worker can accumulate a full layout batch while
894 // rendering stays ahead (and never below the pre-#73 render-ahead of
895 // two pages per worker); still a hard cap on resident page bitmaps.
896 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
897 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
898 // Workers and the renderer report here; the calling thread drains it in
899 // page order. Bounded so workers block (bounding resident bitmaps) when the
900 // consumer falls behind.
901 let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
902
903 let mut workers = std::mem::take(&mut self.pool);
904 let mut asm = assemble::StreamAssembler::new();
905 let mut first_err: Option<PdfError> = None;
906
907 std::thread::scope(|s| {
908 // Workers: pull a batch of pages (whatever is already rendered, up
909 // to the layout batch size), process it, report (index-tagged)
910 // results.
911 for worker in workers.iter_mut() {
912 let work_rx = Arc::clone(&work_rx);
913 let res_tx = res_tx.clone();
914 s.spawn(move || 'outer: loop {
915 let mut batch = Vec::new();
916 {
917 let rx = work_rx.lock().unwrap();
918 match rx.recv() {
919 Ok(item) => {
920 batch.push(item);
921 while batch.len() < layout_batch {
922 match rx.try_recv() {
923 Ok(item) => batch.push(item),
924 Err(_) => break,
925 }
926 }
927 }
928 Err(_) => break,
929 }
930 }
931 let outs = worker.process_batch(&mut batch);
932 for ((idx, _), out) in batch.iter().zip(outs) {
933 if res_tx.send(out.map(|o| (*idx, o))).is_err() {
934 break 'outer; // consumer gone
935 }
936 }
937 });
938 }
939 // Renderer: feed pages to the pool on its own thread (pdfium stays on a
940 // single thread); report a render error through the same channel.
941 {
942 let res_tx = res_tx.clone();
943 s.spawn(move || {
944 let render = pdfium_backend::for_each_page(
945 bytes,
946 password,
947 render_image,
948 |i, _total, page| {
949 work_tx
950 .send((i, page))
951 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
952 },
953 );
954 drop(work_tx); // signal workers to finish
955 if let Err(e) = render {
956 let _ = res_tx.send(Err(e));
957 }
958 });
959 }
960 // Drop our own sender so the channel closes once the threads finish.
961 drop(res_tx);
962
963 // Collector (this thread): reorder into document order and emit.
964 let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
965 let mut next = 0usize;
966 for msg in res_rx.iter() {
967 match msg {
968 Err(e) => {
969 if first_err.is_none() {
970 first_err = Some(e);
971 }
972 }
973 Ok((idx, out)) => {
974 buffer.insert(idx, out);
975 if first_err.is_some() {
976 continue; // keep draining so the threads can exit
977 }
978 while let Some((nodes, links)) = buffer.remove(&next) {
979 if let Err(e) = emit(asm.push(nodes), links) {
980 first_err = Some(e);
981 break;
982 }
983 next += 1;
984 }
985 }
986 }
987 }
988 });
989 // Threads have joined; restore the pool for the next conversion.
990 self.pool = workers;
991
992 if let Some(e) = first_err {
993 return Err(e);
994 }
995 emit(asm.finish(), Vec::new())
996 }
997
998 /// Lazily grow the pool to `target_workers`, loading the new workers
999 /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
1000 /// one load's wall-time). Cached for reuse across documents.
1001 fn ensure_pool(&mut self) -> Result<(), PdfError> {
1002 let need = self.target_workers.saturating_sub(self.pool.len());
1003 if need == 0 {
1004 return Ok(());
1005 }
1006 let intra = pdf_intra();
1007 let no_ocr = self.no_ocr;
1008 let enrich = self.enrich;
1009 let tables = self.tables_slot();
1010 let enrich_slots = self.enrich_slots();
1011 let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
1012 let handles: Vec<_> = (0..need)
1013 .map(|_| {
1014 let tables = tables.clone();
1015 let enrich_slots = enrich_slots.clone();
1016 s.spawn(move || Worker::load(intra, tables, enrich_slots, enrich, no_ocr))
1017 })
1018 .collect();
1019 handles.into_iter().map(|h| h.join().unwrap()).collect()
1020 });
1021 for w in loaded {
1022 self.pool.push(w?);
1023 }
1024 Ok(())
1025 }
1026
1027 /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
1028 /// docling routes images through the same layout+OCR pipeline as a PDF page.
1029 pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1030 let image = image::load_from_memory(bytes)
1031 .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?
1032 .into_rgb8();
1033 let (w, h) = image.dimensions();
1034 // The image is its own page rendered at 1 px per "point" (scale 1.0); a
1035 // standalone image has no text layer, so OCR supplies the cells.
1036 let page = PdfPage {
1037 width: w as f32,
1038 height: h as f32,
1039 scale: 1.0,
1040 cells: Vec::new(),
1041 code_cells: Vec::new(),
1042 word_cells: Vec::new(),
1043 image,
1044 links: Vec::new(),
1045 };
1046 self.process_pages(vec![page], name)
1047 }
1048
1049 /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
1050 /// page (image / METS inputs, which are small and already materialised).
1051 fn process_pages(
1052 &mut self,
1053 mut pages: Vec<PdfPage>,
1054 name: &str,
1055 ) -> Result<DoclingDocument, PdfError> {
1056 let mut doc = DoclingDocument::new(name);
1057 let worker = self.primary()?;
1058 for (n, page) in pages.iter_mut().enumerate() {
1059 let (nodes, links) = worker.process(n, page)?;
1060 doc.nodes.extend(nodes);
1061 doc.links.extend(links);
1062 }
1063 assemble::merge_continuations(&mut doc.nodes);
1064 Ok(doc)
1065 }
1066}
1067
1068/// Convenience one-shot conversion (loads the pipeline per call). Errors are
1069/// detailed and surfaced (never silently skipped).
1070pub fn convert(
1071 bytes: &[u8],
1072 password: Option<&str>,
1073 name: &str,
1074) -> Result<DoclingDocument, PdfError> {
1075 convert_with_options(
1076 bytes,
1077 password,
1078 name,
1079 false,
1080 false,
1081 EnrichmentOptions::default(),
1082 )
1083}
1084
1085/// Like [`convert`], but optionally skips loading/running TableFormer (see
1086/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1087/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
1088/// [`Pipeline::enrichments`]).
1089pub fn convert_with_options(
1090 bytes: &[u8],
1091 password: Option<&str>,
1092 name: &str,
1093 no_table_former: bool,
1094 no_ocr: bool,
1095 enrich: EnrichmentOptions,
1096) -> Result<DoclingDocument, PdfError> {
1097 Pipeline::new()?
1098 .no_table_former(no_table_former)
1099 .no_ocr(no_ocr)
1100 .enrichments(enrich)
1101 .convert(bytes, password, name)
1102}
1103
1104/// Convenience one-shot image conversion (loads the pipeline per call).
1105pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
1106 convert_image_with_options(bytes, name, false, false, EnrichmentOptions::default())
1107}
1108
1109/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
1110/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1111/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
1112pub fn convert_image_with_options(
1113 bytes: &[u8],
1114 name: &str,
1115 no_table_former: bool,
1116 no_ocr: bool,
1117 enrich: EnrichmentOptions,
1118) -> Result<DoclingDocument, PdfError> {
1119 Pipeline::new()?
1120 .no_table_former(no_table_former)
1121 .no_ocr(no_ocr)
1122 .enrichments(enrich)
1123 .convert_image(bytes, name)
1124}
1125
1126/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
1127/// scans) through the shared layout + assembly pipeline.
1128pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
1129 convert_pages_with_options(pages, name, false, false, EnrichmentOptions::default())
1130}
1131
1132/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
1133/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1134/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
1135pub fn convert_pages_with_options(
1136 pages: Vec<PdfPage>,
1137 name: &str,
1138 no_table_former: bool,
1139 no_ocr: bool,
1140 enrich: EnrichmentOptions,
1141) -> Result<DoclingDocument, PdfError> {
1142 Pipeline::new()?
1143 .no_table_former(no_table_former)
1144 .no_ocr(no_ocr)
1145 .enrichments(enrich)
1146 .process_pages(pages, name)
1147}
1148
1149#[cfg(test)]
1150mod send_check {
1151 /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
1152 /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
1153 /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
1154 /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
1155 fn assert_send<T: Send>() {}
1156
1157 #[test]
1158 fn pipeline_is_send() {
1159 assert_send::<super::Pipeline>();
1160 }
1161}