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 // docling's LayoutPostprocessor drops each detection below its label's
256 // confidence threshold (stricter than the 0.3 base the predictor keeps),
257 // before any overlap resolution. This removes the low-confidence tables /
258 // pictures / list-items that otherwise double-emit or mis-classify.
259 let mut regions = regions;
260 regions.retain(|r| r.score >= layout::label_threshold(r.label));
261 // Resolve overlapping detections once, before OCR.
262 let mut regions = assemble::resolve(regions);
263 // Emit text the detector missed as orphan text regions (docling parity).
264 assemble::add_orphan_regions(&mut regions, &page.cells);
265 // Drop phantom empty low-confidence picture boxes (docling parity).
266 assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
267 // A regular region fully inside a surviving table/index/picture is that
268 // special's child (a cell / in-figure label), not a separate block —
269 // remove it so it isn't emitted twice (docling parity).
270 assemble::drop_contained_regulars(&mut regions);
271 // No text layer → recognise text from the page image via OCR.
272 if page.cells.is_empty() {
273 if self.ocr.is_none() {
274 self.ocr = Some(ocr::OcrModel::load().map_err(PdfError::Ocr)?);
275 }
276 let cells = timing::timed("ocr.page", || {
277 self.ocr
278 .as_mut()
279 .unwrap()
280 .ocr_page(&page.image, ®ions, page.scale)
281 })
282 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
283 page.cells = cells;
284 }
285 // TableFormer structure per table region (else geometric fallback). The
286 // shared slot is only locked (and lazily loaded) when the page actually
287 // has a table, so table-free documents never pay for TableFormer at all.
288 let mut table_rows: Vec<Option<Vec<Vec<String>>>> = vec![None; regions.len()];
289 if let Some(slot) = self.tables.as_ref() {
290 if regions.iter().any(|r| assemble::is_table_like(r.label)) {
291 timing::timed("tableformer", || {
292 let mut guard = slot.lock().unwrap();
293 if matches!(*guard, TfSlot::Unloaded) {
294 // Full intra-op width: tables serialise on this mutex, so
295 // the one instance gets the whole thread budget.
296 *guard = match tableformer::TableFormer::load_with(intra_threads()) {
297 Some(tf) => TfSlot::Ready(tf),
298 None => TfSlot::Missing,
299 };
300 }
301 if let TfSlot::Ready(tf) = &mut *guard {
302 for (i, r) in regions.iter().enumerate() {
303 if assemble::is_table_like(r.label) {
304 table_rows[i] = tf.predict_table_rows(
305 &page.image,
306 [r.l, r.t, r.r, r.b],
307 &page.word_cells,
308 );
309 }
310 }
311 }
312 });
313 }
314 }
315 // Enrichment passes (opt-in): DocumentPictureClassifier over picture
316 // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
317 // shape as TableFormer — one lazily-loaded instance per pipeline, only
318 // ever locked when a page actually has a matching region.
319 let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
320 if let Some(slot) = self.classifier.as_ref() {
321 if regions.iter().any(|r| r.label == "picture") {
322 timing::timed("picture_classifier", || {
323 let mut guard = slot.lock().unwrap();
324 if matches!(*guard, EnrichSlot::Unloaded) {
325 *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
326 Some(m) => EnrichSlot::Ready(m),
327 None => EnrichSlot::Missing,
328 };
329 }
330 if let EnrichSlot::Ready(model) = &mut *guard {
331 for (i, r) in regions.iter().enumerate() {
332 if r.label != "picture" {
333 continue;
334 }
335 let Some(crop) = assemble::crop_region_scaled(
336 page,
337 [r.l, r.t, r.r, r.b],
338 enrich::CLASSIFIER_SCALE,
339 ) else {
340 continue;
341 };
342 match model.classify(&crop) {
343 Ok(classes) => {
344 enrich_out[i] =
345 Some(assemble::Enrichment::PictureClasses(classes));
346 }
347 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
348 }
349 }
350 }
351 });
352 }
353 }
354 if let Some(slot) = self.code_formula.as_ref() {
355 let wants = |label: &str| {
356 (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
357 };
358 if regions.iter().any(|r| wants(r.label)) {
359 timing::timed("code_formula", || {
360 let mut guard = slot.lock().unwrap();
361 if matches!(*guard, EnrichSlot::Unloaded) {
362 *guard = match enrich::CodeFormula::load_with(intra_threads()) {
363 Some(m) => EnrichSlot::Ready(m),
364 None => EnrichSlot::Missing,
365 };
366 }
367 if let EnrichSlot::Ready(model) = &mut *guard {
368 for (i, r) in regions.iter().enumerate() {
369 if !wants(r.label) {
370 continue;
371 }
372 // docling crops the postprocessed cluster box — the
373 // union of the region's text cells, not the raw
374 // detector box — expanded by 18% per side, at
375 // ~120 dpi.
376 let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
377 .unwrap_or([r.l, r.t, r.r, r.b]);
378 let (w, h) = (br - bl, bb - bt);
379 let ex = enrich::CODE_FORMULA_EXPANSION;
380 let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
381 let Some(crop) = assemble::crop_region_scaled(
382 page,
383 bbox,
384 enrich::CODE_FORMULA_SCALE,
385 ) else {
386 continue;
387 };
388 let kind = if r.label == "code" {
389 enrich::CodeFormulaKind::Code
390 } else {
391 enrich::CodeFormulaKind::Formula
392 };
393 match model.predict(&crop, kind) {
394 Ok(text) => {
395 enrich_out[i] = Some(match kind {
396 enrich::CodeFormulaKind::Code => {
397 let (code, language) =
398 enrich::extract_code_language(&text);
399 assemble::Enrichment::Code {
400 language,
401 text: code,
402 }
403 }
404 enrich::CodeFormulaKind::Formula => {
405 assemble::Enrichment::Formula { latex: text }
406 }
407 });
408 }
409 Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
410 }
411 }
412 }
413 });
414 }
415 }
416 Ok(timing::timed("assemble_page", || {
417 assemble::assemble_page(page, regions, &table_rows, &enrich_out)
418 }))
419 }
420}
421
422/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
423/// so on a typical machine two threads per worker (sharing one in-cache copy of
424/// the weights) extracts more throughput than one fat model or many single-thread
425/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
426fn pdf_intra() -> usize {
427 if let Some(n) = std::env::var("DOCLING_RS_PDF_INTRA")
428 .ok()
429 .and_then(|v| v.parse::<usize>().ok())
430 .filter(|&n| n > 0)
431 {
432 return n;
433 }
434 if intra_threads() >= 2 {
435 2
436 } else {
437 1
438 }
439}
440
441/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
442/// overrides; otherwise size the pool so `workers × intra ≈ cores`, capped at 4 so
443/// a worst-case pool holds a bounded amount of model memory (~0.4 GB per worker)
444/// and does not oversaturate the memory bus with model-weight traffic.
445fn pdf_worker_count() -> usize {
446 if let Some(n) = std::env::var("DOCLING_RS_PDF_WORKERS")
447 .ok()
448 .and_then(|v| v.parse::<usize>().ok())
449 .filter(|&n| n > 0)
450 {
451 return n;
452 }
453 (intra_threads() / pdf_intra()).clamp(1, 4)
454}
455
456/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
457/// the serial primary (running its model on every core) is faster than fanning out
458/// — the helper pool's one-time model-load cost only pays off once enough pages
459/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
460fn pdf_parallel_min() -> usize {
461 std::env::var("DOCLING_RS_PDF_PARALLEL_MIN")
462 .ok()
463 .and_then(|v| v.parse::<usize>().ok())
464 .filter(|&n| n > 0)
465 .unwrap_or(6)
466}
467
468/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
469/// so a single-page / small / image / METS input is converted at full intra-op
470/// speed with no pool to load. A document with enough pages instead fans out
471/// across a **pool** of narrower workers processed concurrently. Both load lazily
472/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
473pub struct Pipeline {
474 /// Full-intra worker for the serial path; loaded on first serial use.
475 primary: Option<Worker>,
476 /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
477 /// path; loaded on first multi-page use and cached.
478 pool: Vec<Worker>,
479 /// The single TableFormer instance every worker shares (see [`TfSlot`]).
480 tables: SharedTables,
481 /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
482 classifier: SharedClassifier,
483 code_formula: SharedCodeFormula,
484 /// Desired pool size for multi-page documents.
485 target_workers: usize,
486 /// Page count at/above which the parallel pool is worth its load cost.
487 parallel_min: usize,
488 /// Skip loading/running TableFormer; table regions fall back to geometric
489 /// reconstruction. See [`Pipeline::no_table_former`].
490 no_table_former: bool,
491 /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
492 no_ocr: bool,
493 /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
494 enrich: EnrichmentOptions,
495}
496
497impl Pipeline {
498 /// Construct the pipeline. Models load lazily on first use (full-intra primary
499 /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
500 /// loaded that a given document doesn't need.
501 pub fn new() -> Result<Self, PdfError> {
502 Ok(Self {
503 primary: None,
504 pool: Vec::new(),
505 tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
506 classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
507 code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
508 target_workers: pdf_worker_count(),
509 parallel_min: pdf_parallel_min(),
510 no_table_former: false,
511 no_ocr: false,
512 enrich: EnrichmentOptions::default(),
513 })
514 }
515
516 /// Enable the opt-in enrichment passes (docling's
517 /// `do_picture_classification` / `do_code_enrichment` /
518 /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
519 /// the first matching region; a missing model warns once and is skipped.
520 /// Set before the first conversion (no effect on already-loaded workers).
521 pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
522 self.enrich = opts;
523 self
524 }
525
526 /// Skip loading and running the TableFormer table-structure model. Table
527 /// regions still get emitted, but reconstructed geometrically from cell
528 /// positions instead of via the ONNX model's predicted structure — faster
529 /// (no model load, no per-table inference) at the cost of table fidelity.
530 /// No effect if a worker is already loaded; set this before the first
531 /// conversion.
532 pub fn no_table_former(mut self, disable: bool) -> Self {
533 self.no_table_former = disable;
534 self
535 }
536
537 /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
538 /// inference of any kind. The PDF's embedded text cells are grouped by line
539 /// and emitted as plain paragraphs in reading order: no headings, lists,
540 /// tables, code blocks, or pictures, since that structure comes from the
541 /// layout model. The fastest possible PDF path, but pages with no embedded
542 /// text layer (scanned/image-only PDFs) yield no text at all — convert those
543 /// without this flag. Implies `no_table_former`. No effect if a worker is
544 /// already loaded; set this before the first conversion.
545 pub fn no_ocr(mut self, disable: bool) -> Self {
546 self.no_ocr = disable;
547 self
548 }
549
550 /// The shared TableFormer slot handed to each worker, or `None` when the
551 /// pipeline options skip TableFormer entirely.
552 fn tables_slot(&self) -> Option<SharedTables> {
553 if self.no_table_former || self.no_ocr {
554 None
555 } else {
556 Some(Arc::clone(&self.tables))
557 }
558 }
559
560 /// The shared enrichment slots for a worker (`None` per model unless its
561 /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
562 fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
563 if self.no_ocr || !self.enrich.any() {
564 return (None, None);
565 }
566 (
567 self.enrich
568 .picture_classification
569 .then(|| Arc::clone(&self.classifier)),
570 (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
571 )
572 }
573
574 /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
575 /// the shared TableFormer unless disabled) so the first conversion doesn't pay
576 /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
577 /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
578 /// `DocumentConverter.initialize_pipeline`.
579 pub fn warm_up(&mut self) -> Result<(), PdfError> {
580 self.primary()?;
581 Ok(())
582 }
583
584 /// The full-intra serial worker, loaded on first use.
585 fn primary(&mut self) -> Result<&mut Worker, PdfError> {
586 if self.primary.is_none() {
587 self.primary = Some(Worker::load(
588 intra_threads(),
589 self.tables_slot(),
590 self.enrich_slots(),
591 self.enrich,
592 self.no_ocr,
593 )?);
594 }
595 Ok(self.primary.as_mut().unwrap())
596 }
597
598 /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
599 /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
600 /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
601 /// fans the pages out across the worker pool, reassembled in page order so the
602 /// output is byte-identical to the serial path.
603 pub fn convert(
604 &mut self,
605 bytes: &[u8],
606 password: Option<&str>,
607 name: &str,
608 ) -> Result<DoclingDocument, PdfError> {
609 let pages = pdfium_backend::page_count(bytes, password)?;
610 let doc = if self.target_workers >= 2 && pages >= self.parallel_min {
611 self.convert_parallel(bytes, password, name)?
612 } else {
613 self.convert_serial(bytes, password, name)?
614 };
615 timing::report();
616 Ok(doc)
617 }
618
619 /// Stream pages one at a time through the primary worker — render → process →
620 /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
621 fn convert_serial(
622 &mut self,
623 bytes: &[u8],
624 password: Option<&str>,
625 name: &str,
626 ) -> Result<DoclingDocument, PdfError> {
627 let mut doc = DoclingDocument::new(name);
628 let render_image = !self.no_ocr;
629 let worker = self.primary()?;
630 pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
631 let (nodes, links) = worker.process(n, &mut page)?;
632 doc.nodes.extend(nodes);
633 doc.links.extend(links);
634 Ok::<(), PdfError>(())
635 })?;
636 assemble::merge_continuations(&mut doc.nodes);
637 Ok(doc)
638 }
639
640 /// Render pages serially on this thread (pdfium) and process them in parallel
641 /// across the worker pool. A bounded channel applies backpressure so only a
642 /// handful of page bitmaps are resident at once; results carry their page
643 /// index and are reassembled in order, so the output is byte-identical to the
644 /// serial path.
645 fn convert_parallel(
646 &mut self,
647 bytes: &[u8],
648 password: Option<&str>,
649 name: &str,
650 ) -> Result<DoclingDocument, PdfError> {
651 self.ensure_pool()?;
652 let n_workers = self.pool.len();
653 let render_image = !self.no_ocr;
654 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * 2);
655 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
656 let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
657 let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
658
659 // Move the pool into the scope so each worker gets an exclusive `&mut`.
660 let mut workers = std::mem::take(&mut self.pool);
661 std::thread::scope(|s| {
662 for worker in workers.iter_mut() {
663 let work_rx = Arc::clone(&work_rx);
664 let results = Arc::clone(&results);
665 let first_err = Arc::clone(&first_err);
666 s.spawn(move || loop {
667 // Hold the receiver lock only for the recv; release before the
668 // (long) per-page work so other workers can pull concurrently.
669 let item = work_rx.lock().unwrap().recv();
670 let Ok((idx, mut page)) = item else { break };
671 match worker.process(idx, &mut page) {
672 Ok(out) => results.lock().unwrap().push((idx, out)),
673 Err(e) => {
674 let mut slot = first_err.lock().unwrap();
675 if slot.is_none() {
676 *slot = Some(e);
677 }
678 }
679 }
680 });
681 }
682 // Render on this thread and feed the workers; backpressure blocks here
683 // when the channel is full. Dropping `work_tx` afterwards signals the
684 // workers (recv → Err) to finish.
685 let render =
686 pdfium_backend::for_each_page(bytes, password, render_image, |i, _total, page| {
687 work_tx
688 .send((i, page))
689 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
690 });
691 drop(work_tx);
692 if let Err(e) = render {
693 let mut slot = first_err.lock().unwrap();
694 if slot.is_none() {
695 *slot = Some(e);
696 }
697 }
698 });
699 // Threads have joined; restore the pool for the next conversion.
700 self.pool = workers;
701
702 if let Some(e) = first_err.lock().unwrap().take() {
703 return Err(e);
704 }
705 let mut results = Arc::try_unwrap(results)
706 .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
707 .into_inner()
708 .unwrap();
709 results.sort_by_key(|(idx, _)| *idx);
710 let mut doc = DoclingDocument::new(name);
711 for (_, (nodes, links)) in results {
712 doc.nodes.extend(nodes);
713 doc.links.extend(links);
714 }
715 assemble::merge_continuations(&mut doc.nodes);
716 Ok(doc)
717 }
718
719 /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
720 /// in-document-order batch of nodes (and that span's recovered links) as pages
721 /// complete, so a caller can serialize Markdown page by page instead of waiting
722 /// for the whole document. The batches are exactly the buffered [`convert`]'s
723 /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
724 /// parallel path reorders pages back into document order before emitting, so
725 /// the output is identical regardless of worker scheduling.
726 ///
727 /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
728 /// and its backpressure throttles the whole pipeline. Returning `Err` from
729 /// `emit` aborts the conversion with that error.
730 pub fn convert_streaming<F>(
731 &mut self,
732 bytes: &[u8],
733 password: Option<&str>,
734 name: &str,
735 emit: F,
736 ) -> Result<(), PdfError>
737 where
738 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
739 {
740 let _ = name; // page nodes carry no name; the caller owns the document name.
741 let pages = pdfium_backend::page_count(bytes, password)?;
742 let r = if self.target_workers >= 2 && pages >= self.parallel_min {
743 self.convert_streaming_parallel(bytes, password, emit)
744 } else {
745 self.convert_streaming_serial(bytes, password, emit)
746 };
747 timing::report();
748 r
749 }
750
751 /// Serial streaming: render → process → emit, one page at a time, holding back
752 /// only the tail that might still merge into the next page.
753 fn convert_streaming_serial<F>(
754 &mut self,
755 bytes: &[u8],
756 password: Option<&str>,
757 mut emit: F,
758 ) -> Result<(), PdfError>
759 where
760 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
761 {
762 let mut asm = assemble::StreamAssembler::new();
763 let render_image = !self.no_ocr;
764 let worker = self.primary()?;
765 pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
766 let (nodes, links) = worker.process(n, &mut page)?;
767 emit(asm.push(nodes), links)
768 })?;
769 emit(asm.finish(), Vec::new())
770 }
771
772 /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
773 /// not thread-safe) and process across the worker pool; results carry their
774 /// page index and are reordered on the calling thread into a
775 /// [`assemble::StreamAssembler`], which emits each page in document order as
776 /// soon as its predecessors have arrived. Bounded channels keep only a handful
777 /// of pages resident and let `emit`'s backpressure reach the renderer.
778 fn convert_streaming_parallel<F>(
779 &mut self,
780 bytes: &[u8],
781 password: Option<&str>,
782 mut emit: F,
783 ) -> Result<(), PdfError>
784 where
785 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
786 {
787 self.ensure_pool()?;
788 let n_workers = self.pool.len();
789 let render_image = !self.no_ocr;
790 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * 2);
791 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
792 // Workers and the renderer report here; the calling thread drains it in
793 // page order. Bounded so workers block (bounding resident bitmaps) when the
794 // consumer falls behind.
795 let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
796
797 let mut workers = std::mem::take(&mut self.pool);
798 let mut asm = assemble::StreamAssembler::new();
799 let mut first_err: Option<PdfError> = None;
800
801 std::thread::scope(|s| {
802 // Workers: pull a page, process it, report (index-tagged) result.
803 for worker in workers.iter_mut() {
804 let work_rx = Arc::clone(&work_rx);
805 let res_tx = res_tx.clone();
806 s.spawn(move || loop {
807 let item = work_rx.lock().unwrap().recv();
808 let Ok((idx, mut page)) = item else { break };
809 let out = worker.process(idx, &mut page).map(|o| (idx, o));
810 if res_tx.send(out).is_err() {
811 break; // consumer gone
812 }
813 });
814 }
815 // Renderer: feed pages to the pool on its own thread (pdfium stays on a
816 // single thread); report a render error through the same channel.
817 {
818 let res_tx = res_tx.clone();
819 s.spawn(move || {
820 let render = pdfium_backend::for_each_page(
821 bytes,
822 password,
823 render_image,
824 |i, _total, page| {
825 work_tx
826 .send((i, page))
827 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
828 },
829 );
830 drop(work_tx); // signal workers to finish
831 if let Err(e) = render {
832 let _ = res_tx.send(Err(e));
833 }
834 });
835 }
836 // Drop our own sender so the channel closes once the threads finish.
837 drop(res_tx);
838
839 // Collector (this thread): reorder into document order and emit.
840 let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
841 let mut next = 0usize;
842 for msg in res_rx.iter() {
843 match msg {
844 Err(e) => {
845 if first_err.is_none() {
846 first_err = Some(e);
847 }
848 }
849 Ok((idx, out)) => {
850 buffer.insert(idx, out);
851 if first_err.is_some() {
852 continue; // keep draining so the threads can exit
853 }
854 while let Some((nodes, links)) = buffer.remove(&next) {
855 if let Err(e) = emit(asm.push(nodes), links) {
856 first_err = Some(e);
857 break;
858 }
859 next += 1;
860 }
861 }
862 }
863 }
864 });
865 // Threads have joined; restore the pool for the next conversion.
866 self.pool = workers;
867
868 if let Some(e) = first_err {
869 return Err(e);
870 }
871 emit(asm.finish(), Vec::new())
872 }
873
874 /// Lazily grow the pool to `target_workers`, loading the new workers
875 /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
876 /// one load's wall-time). Cached for reuse across documents.
877 fn ensure_pool(&mut self) -> Result<(), PdfError> {
878 let need = self.target_workers.saturating_sub(self.pool.len());
879 if need == 0 {
880 return Ok(());
881 }
882 let intra = pdf_intra();
883 let no_ocr = self.no_ocr;
884 let enrich = self.enrich;
885 let tables = self.tables_slot();
886 let enrich_slots = self.enrich_slots();
887 let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
888 let handles: Vec<_> = (0..need)
889 .map(|_| {
890 let tables = tables.clone();
891 let enrich_slots = enrich_slots.clone();
892 s.spawn(move || Worker::load(intra, tables, enrich_slots, enrich, no_ocr))
893 })
894 .collect();
895 handles.into_iter().map(|h| h.join().unwrap()).collect()
896 });
897 for w in loaded {
898 self.pool.push(w?);
899 }
900 Ok(())
901 }
902
903 /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
904 /// docling routes images through the same layout+OCR pipeline as a PDF page.
905 pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
906 let image = image::load_from_memory(bytes)
907 .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?
908 .into_rgb8();
909 let (w, h) = image.dimensions();
910 // The image is its own page rendered at 1 px per "point" (scale 1.0); a
911 // standalone image has no text layer, so OCR supplies the cells.
912 let page = PdfPage {
913 width: w as f32,
914 height: h as f32,
915 scale: 1.0,
916 cells: Vec::new(),
917 code_cells: Vec::new(),
918 word_cells: Vec::new(),
919 image,
920 links: Vec::new(),
921 };
922 self.process_pages(vec![page], name)
923 }
924
925 /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
926 /// page (image / METS inputs, which are small and already materialised).
927 fn process_pages(
928 &mut self,
929 mut pages: Vec<PdfPage>,
930 name: &str,
931 ) -> Result<DoclingDocument, PdfError> {
932 let mut doc = DoclingDocument::new(name);
933 let worker = self.primary()?;
934 for (n, page) in pages.iter_mut().enumerate() {
935 let (nodes, links) = worker.process(n, page)?;
936 doc.nodes.extend(nodes);
937 doc.links.extend(links);
938 }
939 assemble::merge_continuations(&mut doc.nodes);
940 Ok(doc)
941 }
942}
943
944/// Convenience one-shot conversion (loads the pipeline per call). Errors are
945/// detailed and surfaced (never silently skipped).
946pub fn convert(
947 bytes: &[u8],
948 password: Option<&str>,
949 name: &str,
950) -> Result<DoclingDocument, PdfError> {
951 convert_with_options(
952 bytes,
953 password,
954 name,
955 false,
956 false,
957 EnrichmentOptions::default(),
958 )
959}
960
961/// Like [`convert`], but optionally skips loading/running TableFormer (see
962/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
963/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
964/// [`Pipeline::enrichments`]).
965pub fn convert_with_options(
966 bytes: &[u8],
967 password: Option<&str>,
968 name: &str,
969 no_table_former: bool,
970 no_ocr: bool,
971 enrich: EnrichmentOptions,
972) -> Result<DoclingDocument, PdfError> {
973 Pipeline::new()?
974 .no_table_former(no_table_former)
975 .no_ocr(no_ocr)
976 .enrichments(enrich)
977 .convert(bytes, password, name)
978}
979
980/// Convenience one-shot image conversion (loads the pipeline per call).
981pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
982 convert_image_with_options(bytes, name, false, false, EnrichmentOptions::default())
983}
984
985/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
986/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
987/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
988pub fn convert_image_with_options(
989 bytes: &[u8],
990 name: &str,
991 no_table_former: bool,
992 no_ocr: bool,
993 enrich: EnrichmentOptions,
994) -> Result<DoclingDocument, PdfError> {
995 Pipeline::new()?
996 .no_table_former(no_table_former)
997 .no_ocr(no_ocr)
998 .enrichments(enrich)
999 .convert_image(bytes, name)
1000}
1001
1002/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
1003/// scans) through the shared layout + assembly pipeline.
1004pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
1005 convert_pages_with_options(pages, name, false, false, EnrichmentOptions::default())
1006}
1007
1008/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
1009/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
1010/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
1011pub fn convert_pages_with_options(
1012 pages: Vec<PdfPage>,
1013 name: &str,
1014 no_table_former: bool,
1015 no_ocr: bool,
1016 enrich: EnrichmentOptions,
1017) -> Result<DoclingDocument, PdfError> {
1018 Pipeline::new()?
1019 .no_table_former(no_table_former)
1020 .no_ocr(no_ocr)
1021 .enrichments(enrich)
1022 .process_pages(pages, name)
1023}
1024
1025#[cfg(test)]
1026mod send_check {
1027 /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
1028 /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
1029 /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
1030 /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
1031 fn assert_send<T: Send>() {}
1032
1033 #[test]
1034 fn pipeline_is_send() {
1035 assert_send::<super::Pipeline>();
1036 }
1037}