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