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 layout;
15mod mets;
16mod ocr;
17pub mod pdfium_backend;
18mod reading_order;
19pub mod resample;
20pub mod tableformer;
21pub mod textparse;
22mod tf_match;
23pub mod timing;
24
25use std::collections::BTreeMap;
26use std::fmt;
27use std::sync::mpsc::{sync_channel, Receiver};
28use std::sync::{Arc, Mutex};
29
30use docling_core::{DoclingDocument, Node};
31
32pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options};
33pub use pdfium_backend::{PdfDocument, PdfPage, TextCell};
34
35/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
36#[derive(Debug)]
37pub enum PdfError {
38 /// pdfium failed to bind, open, or read the document.
39 Pdfium(String),
40 /// The layout ONNX model failed to load or run.
41 Layout(String),
42 /// The OCR ONNX model failed to load or run.
43 Ocr(String),
44}
45
46impl fmt::Display for PdfError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 match self {
49 PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
50 PdfError::Layout(m) => write!(f, "pdf: {m}"),
51 PdfError::Ocr(m) => write!(f, "pdf: {m}"),
52 }
53 }
54}
55
56impl std::error::Error for PdfError {}
57
58impl From<pdfium_render::prelude::PdfiumError> for PdfError {
59 fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
60 PdfError::Pdfium(e.to_string())
61 }
62}
63
64/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
65/// Defaults to the available parallelism (ort otherwise picks a low number).
66pub(crate) fn intra_threads() -> usize {
67 if let Some(n) = std::env::var("DOCLING_RS_PDF_THREADS")
68 .ok()
69 .and_then(|v| v.parse::<usize>().ok())
70 .filter(|&n| n > 0)
71 {
72 return n;
73 }
74 std::thread::available_parallelism()
75 .map(|n| n.get())
76 .unwrap_or(1)
77}
78
79/// True when `DOCLING_RS_FP32` (any value but `0`) forces the full-precision
80/// models even where an INT8 variant sits next to the fp32 default.
81pub(crate) fn fp32_forced() -> bool {
82 std::env::var("DOCLING_RS_FP32")
83 .map(|v| v != "0")
84 .unwrap_or(false)
85}
86
87/// Resolve a default (CWD-relative) asset path. If it doesn't exist relative
88/// to the current directory, try next to the executable and one level above
89/// it (following symlinks — the layout `scripts/install/install.sh` produces:
90/// `/usr/local/bin/docling-rs` → `/usr/local/docling.rs/bin/docling-rs`
91/// with `models/` and `.pdfium/` in `/usr/local/docling.rs`). Lets an
92/// installed binary run from any working directory with no env vars; explicit
93/// env overrides never reach this. Returns `rel` unchanged when nothing
94/// exists anywhere, so callers' error messages keep the familiar path.
95pub(crate) fn resolve_asset(rel: &str) -> String {
96 if std::path::Path::new(rel).exists() {
97 return rel.to_string();
98 }
99 if let Some(dir) = std::env::current_exe()
100 .ok()
101 .and_then(|p| p.canonicalize().ok())
102 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
103 {
104 for base in [Some(dir.as_path()), dir.parent()].into_iter().flatten() {
105 let p = base.join(rel);
106 if p.exists() {
107 return p.to_string_lossy().into_owned();
108 }
109 }
110 }
111 rel.to_string()
112}
113
114/// Resolve a model path: an explicit env override always wins; otherwise the
115/// INT8 variant of the default path when it exists on disk (the quantized
116/// models are conformance-validated — see PDF_CONFORMANCE.md — and load/run
117/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
118/// precision; else the fp32 default.
119pub(crate) fn model_path(env: &str, fp32_default: &str, int8_default: &str) -> String {
120 if let Ok(p) = std::env::var(env) {
121 return p;
122 }
123 if !fp32_forced() {
124 let p = resolve_asset(int8_default);
125 if std::path::Path::new(&p).exists() {
126 return p;
127 }
128 }
129 resolve_asset(fp32_default)
130}
131
132/// One page's assembled output: typed nodes plus the page's hyperlinks, kept
133/// separate so pages processed out of order can be stitched back in page order.
134type PageOut = (Vec<Node>, Vec<(String, String)>);
135
136/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
137/// lazily on the first table region any worker sees. Tables appear on a
138/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
139/// weights+arenas by the pool size for nothing; a single shared instance keeps
140/// the peak flat regardless of pool width, and a table's structure prediction
141/// is independent of which worker runs it, so output is byte-identical. The
142/// mutex serialises concurrent tables — the shared instance is loaded with the
143/// full intra-op thread budget to compensate (one wide TableFormer instead of
144/// several narrow ones).
145enum TfSlot {
146 /// Not attempted yet (no table seen so far).
147 Unloaded,
148 /// Load attempted, graphs absent — geometric fallback (warned once).
149 Missing,
150 Ready(tableformer::TableFormer),
151}
152
153type SharedTables = Arc<Mutex<TfSlot>>;
154
155/// A self-contained set of the per-page models (layout, OCR). Each parallel
156/// page-worker owns its own `Worker` so inference runs concurrently without
157/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
158/// rarely-hit TableFormer is shared (see [`TfSlot`]).
159struct Worker {
160 /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
161 layout: Option<layout::LayoutModel>,
162 ocr: Option<ocr::OcrModel>,
163 /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
164 tables: Option<SharedTables>,
165 /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
166 /// embedded text layer. See [`Pipeline::no_ocr`].
167 no_ocr: bool,
168}
169
170impl Worker {
171 fn load(intra: usize, tables: Option<SharedTables>, no_ocr: bool) -> Result<Self, PdfError> {
172 Ok(Self {
173 layout: if no_ocr {
174 None
175 } else {
176 Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
177 },
178 ocr: None,
179 tables,
180 no_ocr,
181 })
182 }
183
184 /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
185 /// into its nodes and links. Pure given the page (mutates only the worker's
186 /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
187 fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
188 if self.no_ocr {
189 // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
190 // embedded text cells (if any) become flat, line-grouped paragraphs in
191 // reading order via the same orphan-region machinery that normally
192 // rescues text the detector missed — here it rescues *all* of it.
193 // Pages with no embedded text layer (scanned/image-only) yield nothing;
194 // convert those without `no_ocr`.
195 let mut regions = Vec::new();
196 assemble::add_orphan_regions(&mut regions, &page.cells);
197 let table_rows = vec![None; regions.len()];
198 return Ok(timing::timed("assemble_page", || {
199 assemble::assemble_page(page, regions, &table_rows)
200 }));
201 }
202 let regions = timing::timed("layout.predict", || {
203 self.layout
204 .as_mut()
205 .expect("layout model loaded unless no_ocr")
206 .predict(&page.image, page.width, page.height)
207 })
208 .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
209 // docling's LayoutPostprocessor drops each detection below its label's
210 // confidence threshold (stricter than the 0.3 base the predictor keeps),
211 // before any overlap resolution. This removes the low-confidence tables /
212 // pictures / list-items that otherwise double-emit or mis-classify.
213 let mut regions = regions;
214 regions.retain(|r| r.score >= layout::label_threshold(r.label));
215 // Resolve overlapping detections once, before OCR.
216 let mut regions = assemble::resolve(regions);
217 // Emit text the detector missed as orphan text regions (docling parity).
218 assemble::add_orphan_regions(&mut regions, &page.cells);
219 // Drop phantom empty low-confidence picture boxes (docling parity).
220 assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
221 // A regular region fully inside a surviving table/index/picture is that
222 // special's child (a cell / in-figure label), not a separate block —
223 // remove it so it isn't emitted twice (docling parity).
224 assemble::drop_contained_regulars(&mut regions);
225 // No text layer → recognise text from the page image via OCR.
226 if page.cells.is_empty() {
227 if self.ocr.is_none() {
228 self.ocr = Some(ocr::OcrModel::load().map_err(PdfError::Ocr)?);
229 }
230 let cells = timing::timed("ocr.page", || {
231 self.ocr
232 .as_mut()
233 .unwrap()
234 .ocr_page(&page.image, ®ions, page.scale)
235 })
236 .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
237 page.cells = cells;
238 }
239 // TableFormer structure per table region (else geometric fallback). The
240 // shared slot is only locked (and lazily loaded) when the page actually
241 // has a table, so table-free documents never pay for TableFormer at all.
242 let mut table_rows: Vec<Option<Vec<Vec<String>>>> = vec![None; regions.len()];
243 if let Some(slot) = self.tables.as_ref() {
244 if regions.iter().any(|r| assemble::is_table_like(r.label)) {
245 timing::timed("tableformer", || {
246 let mut guard = slot.lock().unwrap();
247 if matches!(*guard, TfSlot::Unloaded) {
248 // Full intra-op width: tables serialise on this mutex, so
249 // the one instance gets the whole thread budget.
250 *guard = match tableformer::TableFormer::load_with(intra_threads()) {
251 Some(tf) => TfSlot::Ready(tf),
252 None => TfSlot::Missing,
253 };
254 }
255 if let TfSlot::Ready(tf) = &mut *guard {
256 for (i, r) in regions.iter().enumerate() {
257 if assemble::is_table_like(r.label) {
258 table_rows[i] = tf.predict_table_rows(
259 &page.image,
260 [r.l, r.t, r.r, r.b],
261 &page.word_cells,
262 );
263 }
264 }
265 }
266 });
267 }
268 }
269 Ok(timing::timed("assemble_page", || {
270 assemble::assemble_page(page, regions, &table_rows)
271 }))
272 }
273}
274
275/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
276/// so on a typical machine two threads per worker (sharing one in-cache copy of
277/// the weights) extracts more throughput than one fat model or many single-thread
278/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
279fn pdf_intra() -> usize {
280 if let Some(n) = std::env::var("DOCLING_RS_PDF_INTRA")
281 .ok()
282 .and_then(|v| v.parse::<usize>().ok())
283 .filter(|&n| n > 0)
284 {
285 return n;
286 }
287 if intra_threads() >= 2 {
288 2
289 } else {
290 1
291 }
292}
293
294/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
295/// overrides; otherwise size the pool so `workers × intra ≈ cores`, capped at 4 so
296/// a worst-case pool holds a bounded amount of model memory (~0.4 GB per worker)
297/// and does not oversaturate the memory bus with model-weight traffic.
298fn pdf_worker_count() -> usize {
299 if let Some(n) = std::env::var("DOCLING_RS_PDF_WORKERS")
300 .ok()
301 .and_then(|v| v.parse::<usize>().ok())
302 .filter(|&n| n > 0)
303 {
304 return n;
305 }
306 (intra_threads() / pdf_intra()).clamp(1, 4)
307}
308
309/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
310/// the serial primary (running its model on every core) is faster than fanning out
311/// — the helper pool's one-time model-load cost only pays off once enough pages
312/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
313fn pdf_parallel_min() -> usize {
314 std::env::var("DOCLING_RS_PDF_PARALLEL_MIN")
315 .ok()
316 .and_then(|v| v.parse::<usize>().ok())
317 .filter(|&n| n > 0)
318 .unwrap_or(6)
319}
320
321/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
322/// so a single-page / small / image / METS input is converted at full intra-op
323/// speed with no pool to load. A document with enough pages instead fans out
324/// across a **pool** of narrower workers processed concurrently. Both load lazily
325/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
326pub struct Pipeline {
327 /// Full-intra worker for the serial path; loaded on first serial use.
328 primary: Option<Worker>,
329 /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
330 /// path; loaded on first multi-page use and cached.
331 pool: Vec<Worker>,
332 /// The single TableFormer instance every worker shares (see [`TfSlot`]).
333 tables: SharedTables,
334 /// Desired pool size for multi-page documents.
335 target_workers: usize,
336 /// Page count at/above which the parallel pool is worth its load cost.
337 parallel_min: usize,
338 /// Skip loading/running TableFormer; table regions fall back to geometric
339 /// reconstruction. See [`Pipeline::no_table_former`].
340 no_table_former: bool,
341 /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
342 no_ocr: bool,
343}
344
345impl Pipeline {
346 /// Construct the pipeline. Models load lazily on first use (full-intra primary
347 /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
348 /// loaded that a given document doesn't need.
349 pub fn new() -> Result<Self, PdfError> {
350 Ok(Self {
351 primary: None,
352 pool: Vec::new(),
353 tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
354 target_workers: pdf_worker_count(),
355 parallel_min: pdf_parallel_min(),
356 no_table_former: false,
357 no_ocr: false,
358 })
359 }
360
361 /// Skip loading and running the TableFormer table-structure model. Table
362 /// regions still get emitted, but reconstructed geometrically from cell
363 /// positions instead of via the ONNX model's predicted structure — faster
364 /// (no model load, no per-table inference) at the cost of table fidelity.
365 /// No effect if a worker is already loaded; set this before the first
366 /// conversion.
367 pub fn no_table_former(mut self, disable: bool) -> Self {
368 self.no_table_former = disable;
369 self
370 }
371
372 /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
373 /// inference of any kind. The PDF's embedded text cells are grouped by line
374 /// and emitted as plain paragraphs in reading order: no headings, lists,
375 /// tables, code blocks, or pictures, since that structure comes from the
376 /// layout model. The fastest possible PDF path, but pages with no embedded
377 /// text layer (scanned/image-only PDFs) yield no text at all — convert those
378 /// without this flag. Implies `no_table_former`. No effect if a worker is
379 /// already loaded; set this before the first conversion.
380 pub fn no_ocr(mut self, disable: bool) -> Self {
381 self.no_ocr = disable;
382 self
383 }
384
385 /// The shared TableFormer slot handed to each worker, or `None` when the
386 /// pipeline options skip TableFormer entirely.
387 fn tables_slot(&self) -> Option<SharedTables> {
388 if self.no_table_former || self.no_ocr {
389 None
390 } else {
391 Some(Arc::clone(&self.tables))
392 }
393 }
394
395 /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
396 /// the shared TableFormer unless disabled) so the first conversion doesn't pay
397 /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
398 /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
399 /// `DocumentConverter.initialize_pipeline`.
400 pub fn warm_up(&mut self) -> Result<(), PdfError> {
401 self.primary()?;
402 Ok(())
403 }
404
405 /// The full-intra serial worker, loaded on first use.
406 fn primary(&mut self) -> Result<&mut Worker, PdfError> {
407 if self.primary.is_none() {
408 self.primary = Some(Worker::load(
409 intra_threads(),
410 self.tables_slot(),
411 self.no_ocr,
412 )?);
413 }
414 Ok(self.primary.as_mut().unwrap())
415 }
416
417 /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
418 /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
419 /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
420 /// fans the pages out across the worker pool, reassembled in page order so the
421 /// output is byte-identical to the serial path.
422 pub fn convert(
423 &mut self,
424 bytes: &[u8],
425 password: Option<&str>,
426 name: &str,
427 ) -> Result<DoclingDocument, PdfError> {
428 let pages = pdfium_backend::page_count(bytes, password)?;
429 let doc = if self.target_workers >= 2 && pages >= self.parallel_min {
430 self.convert_parallel(bytes, password, name)?
431 } else {
432 self.convert_serial(bytes, password, name)?
433 };
434 timing::report();
435 Ok(doc)
436 }
437
438 /// Stream pages one at a time through the primary worker — render → process →
439 /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
440 fn convert_serial(
441 &mut self,
442 bytes: &[u8],
443 password: Option<&str>,
444 name: &str,
445 ) -> Result<DoclingDocument, PdfError> {
446 let mut doc = DoclingDocument::new(name);
447 let render_image = !self.no_ocr;
448 let worker = self.primary()?;
449 pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
450 let (nodes, links) = worker.process(n, &mut page)?;
451 doc.nodes.extend(nodes);
452 doc.links.extend(links);
453 Ok::<(), PdfError>(())
454 })?;
455 assemble::merge_continuations(&mut doc.nodes);
456 Ok(doc)
457 }
458
459 /// Render pages serially on this thread (pdfium) and process them in parallel
460 /// across the worker pool. A bounded channel applies backpressure so only a
461 /// handful of page bitmaps are resident at once; results carry their page
462 /// index and are reassembled in order, so the output is byte-identical to the
463 /// serial path.
464 fn convert_parallel(
465 &mut self,
466 bytes: &[u8],
467 password: Option<&str>,
468 name: &str,
469 ) -> Result<DoclingDocument, PdfError> {
470 self.ensure_pool()?;
471 let n_workers = self.pool.len();
472 let render_image = !self.no_ocr;
473 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * 2);
474 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
475 let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
476 let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
477
478 // Move the pool into the scope so each worker gets an exclusive `&mut`.
479 let mut workers = std::mem::take(&mut self.pool);
480 std::thread::scope(|s| {
481 for worker in workers.iter_mut() {
482 let work_rx = Arc::clone(&work_rx);
483 let results = Arc::clone(&results);
484 let first_err = Arc::clone(&first_err);
485 s.spawn(move || loop {
486 // Hold the receiver lock only for the recv; release before the
487 // (long) per-page work so other workers can pull concurrently.
488 let item = work_rx.lock().unwrap().recv();
489 let Ok((idx, mut page)) = item else { break };
490 match worker.process(idx, &mut page) {
491 Ok(out) => results.lock().unwrap().push((idx, out)),
492 Err(e) => {
493 let mut slot = first_err.lock().unwrap();
494 if slot.is_none() {
495 *slot = Some(e);
496 }
497 }
498 }
499 });
500 }
501 // Render on this thread and feed the workers; backpressure blocks here
502 // when the channel is full. Dropping `work_tx` afterwards signals the
503 // workers (recv → Err) to finish.
504 let render =
505 pdfium_backend::for_each_page(bytes, password, render_image, |i, _total, page| {
506 work_tx
507 .send((i, page))
508 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
509 });
510 drop(work_tx);
511 if let Err(e) = render {
512 let mut slot = first_err.lock().unwrap();
513 if slot.is_none() {
514 *slot = Some(e);
515 }
516 }
517 });
518 // Threads have joined; restore the pool for the next conversion.
519 self.pool = workers;
520
521 if let Some(e) = first_err.lock().unwrap().take() {
522 return Err(e);
523 }
524 let mut results = Arc::try_unwrap(results)
525 .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
526 .into_inner()
527 .unwrap();
528 results.sort_by_key(|(idx, _)| *idx);
529 let mut doc = DoclingDocument::new(name);
530 for (_, (nodes, links)) in results {
531 doc.nodes.extend(nodes);
532 doc.links.extend(links);
533 }
534 assemble::merge_continuations(&mut doc.nodes);
535 Ok(doc)
536 }
537
538 /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
539 /// in-document-order batch of nodes (and that span's recovered links) as pages
540 /// complete, so a caller can serialize Markdown page by page instead of waiting
541 /// for the whole document. The batches are exactly the buffered [`convert`]'s
542 /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
543 /// parallel path reorders pages back into document order before emitting, so
544 /// the output is identical regardless of worker scheduling.
545 ///
546 /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
547 /// and its backpressure throttles the whole pipeline. Returning `Err` from
548 /// `emit` aborts the conversion with that error.
549 pub fn convert_streaming<F>(
550 &mut self,
551 bytes: &[u8],
552 password: Option<&str>,
553 name: &str,
554 emit: F,
555 ) -> Result<(), PdfError>
556 where
557 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
558 {
559 let _ = name; // page nodes carry no name; the caller owns the document name.
560 let pages = pdfium_backend::page_count(bytes, password)?;
561 let r = if self.target_workers >= 2 && pages >= self.parallel_min {
562 self.convert_streaming_parallel(bytes, password, emit)
563 } else {
564 self.convert_streaming_serial(bytes, password, emit)
565 };
566 timing::report();
567 r
568 }
569
570 /// Serial streaming: render → process → emit, one page at a time, holding back
571 /// only the tail that might still merge into the next page.
572 fn convert_streaming_serial<F>(
573 &mut self,
574 bytes: &[u8],
575 password: Option<&str>,
576 mut emit: F,
577 ) -> Result<(), PdfError>
578 where
579 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
580 {
581 let mut asm = assemble::StreamAssembler::new();
582 let render_image = !self.no_ocr;
583 let worker = self.primary()?;
584 pdfium_backend::for_each_page(bytes, password, render_image, |n, _total, mut page| {
585 let (nodes, links) = worker.process(n, &mut page)?;
586 emit(asm.push(nodes), links)
587 })?;
588 emit(asm.finish(), Vec::new())
589 }
590
591 /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
592 /// not thread-safe) and process across the worker pool; results carry their
593 /// page index and are reordered on the calling thread into a
594 /// [`assemble::StreamAssembler`], which emits each page in document order as
595 /// soon as its predecessors have arrived. Bounded channels keep only a handful
596 /// of pages resident and let `emit`'s backpressure reach the renderer.
597 fn convert_streaming_parallel<F>(
598 &mut self,
599 bytes: &[u8],
600 password: Option<&str>,
601 mut emit: F,
602 ) -> Result<(), PdfError>
603 where
604 F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
605 {
606 self.ensure_pool()?;
607 let n_workers = self.pool.len();
608 let render_image = !self.no_ocr;
609 let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * 2);
610 let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
611 // Workers and the renderer report here; the calling thread drains it in
612 // page order. Bounded so workers block (bounding resident bitmaps) when the
613 // consumer falls behind.
614 let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
615
616 let mut workers = std::mem::take(&mut self.pool);
617 let mut asm = assemble::StreamAssembler::new();
618 let mut first_err: Option<PdfError> = None;
619
620 std::thread::scope(|s| {
621 // Workers: pull a page, process it, report (index-tagged) result.
622 for worker in workers.iter_mut() {
623 let work_rx = Arc::clone(&work_rx);
624 let res_tx = res_tx.clone();
625 s.spawn(move || loop {
626 let item = work_rx.lock().unwrap().recv();
627 let Ok((idx, mut page)) = item else { break };
628 let out = worker.process(idx, &mut page).map(|o| (idx, o));
629 if res_tx.send(out).is_err() {
630 break; // consumer gone
631 }
632 });
633 }
634 // Renderer: feed pages to the pool on its own thread (pdfium stays on a
635 // single thread); report a render error through the same channel.
636 {
637 let res_tx = res_tx.clone();
638 s.spawn(move || {
639 let render = pdfium_backend::for_each_page(
640 bytes,
641 password,
642 render_image,
643 |i, _total, page| {
644 work_tx
645 .send((i, page))
646 .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
647 },
648 );
649 drop(work_tx); // signal workers to finish
650 if let Err(e) = render {
651 let _ = res_tx.send(Err(e));
652 }
653 });
654 }
655 // Drop our own sender so the channel closes once the threads finish.
656 drop(res_tx);
657
658 // Collector (this thread): reorder into document order and emit.
659 let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
660 let mut next = 0usize;
661 for msg in res_rx.iter() {
662 match msg {
663 Err(e) => {
664 if first_err.is_none() {
665 first_err = Some(e);
666 }
667 }
668 Ok((idx, out)) => {
669 buffer.insert(idx, out);
670 if first_err.is_some() {
671 continue; // keep draining so the threads can exit
672 }
673 while let Some((nodes, links)) = buffer.remove(&next) {
674 if let Err(e) = emit(asm.push(nodes), links) {
675 first_err = Some(e);
676 break;
677 }
678 next += 1;
679 }
680 }
681 }
682 }
683 });
684 // Threads have joined; restore the pool for the next conversion.
685 self.pool = workers;
686
687 if let Some(e) = first_err {
688 return Err(e);
689 }
690 emit(asm.finish(), Vec::new())
691 }
692
693 /// Lazily grow the pool to `target_workers`, loading the new workers
694 /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
695 /// one load's wall-time). Cached for reuse across documents.
696 fn ensure_pool(&mut self) -> Result<(), PdfError> {
697 let need = self.target_workers.saturating_sub(self.pool.len());
698 if need == 0 {
699 return Ok(());
700 }
701 let intra = pdf_intra();
702 let no_ocr = self.no_ocr;
703 let tables = self.tables_slot();
704 let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
705 let handles: Vec<_> = (0..need)
706 .map(|_| {
707 let tables = tables.clone();
708 s.spawn(move || Worker::load(intra, tables, no_ocr))
709 })
710 .collect();
711 handles.into_iter().map(|h| h.join().unwrap()).collect()
712 });
713 for w in loaded {
714 self.pool.push(w?);
715 }
716 Ok(())
717 }
718
719 /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
720 /// docling routes images through the same layout+OCR pipeline as a PDF page.
721 pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
722 let image = image::load_from_memory(bytes)
723 .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?
724 .into_rgb8();
725 let (w, h) = image.dimensions();
726 // The image is its own page rendered at 1 px per "point" (scale 1.0); a
727 // standalone image has no text layer, so OCR supplies the cells.
728 let page = PdfPage {
729 width: w as f32,
730 height: h as f32,
731 scale: 1.0,
732 cells: Vec::new(),
733 code_cells: Vec::new(),
734 word_cells: Vec::new(),
735 image,
736 links: Vec::new(),
737 };
738 self.process_pages(vec![page], name)
739 }
740
741 /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
742 /// page (image / METS inputs, which are small and already materialised).
743 fn process_pages(
744 &mut self,
745 mut pages: Vec<PdfPage>,
746 name: &str,
747 ) -> Result<DoclingDocument, PdfError> {
748 let mut doc = DoclingDocument::new(name);
749 let worker = self.primary()?;
750 for (n, page) in pages.iter_mut().enumerate() {
751 let (nodes, links) = worker.process(n, page)?;
752 doc.nodes.extend(nodes);
753 doc.links.extend(links);
754 }
755 assemble::merge_continuations(&mut doc.nodes);
756 Ok(doc)
757 }
758}
759
760/// Convenience one-shot conversion (loads the pipeline per call). Errors are
761/// detailed and surfaced (never silently skipped).
762pub fn convert(
763 bytes: &[u8],
764 password: Option<&str>,
765 name: &str,
766) -> Result<DoclingDocument, PdfError> {
767 convert_with_options(bytes, password, name, false, false)
768}
769
770/// Like [`convert`], but optionally skips loading/running TableFormer (see
771/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
772/// [`Pipeline::no_ocr`]).
773pub fn convert_with_options(
774 bytes: &[u8],
775 password: Option<&str>,
776 name: &str,
777 no_table_former: bool,
778 no_ocr: bool,
779) -> Result<DoclingDocument, PdfError> {
780 Pipeline::new()?
781 .no_table_former(no_table_former)
782 .no_ocr(no_ocr)
783 .convert(bytes, password, name)
784}
785
786/// Convenience one-shot image conversion (loads the pipeline per call).
787pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
788 convert_image_with_options(bytes, name, false, false)
789}
790
791/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
792/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
793/// [`Pipeline::no_ocr`]).
794pub fn convert_image_with_options(
795 bytes: &[u8],
796 name: &str,
797 no_table_former: bool,
798 no_ocr: bool,
799) -> Result<DoclingDocument, PdfError> {
800 Pipeline::new()?
801 .no_table_former(no_table_former)
802 .no_ocr(no_ocr)
803 .convert_image(bytes, name)
804}
805
806/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
807/// scans) through the shared layout + assembly pipeline.
808pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
809 convert_pages_with_options(pages, name, false, false)
810}
811
812/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
813/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
814/// [`Pipeline::no_ocr`]).
815pub fn convert_pages_with_options(
816 pages: Vec<PdfPage>,
817 name: &str,
818 no_table_former: bool,
819 no_ocr: bool,
820) -> Result<DoclingDocument, PdfError> {
821 Pipeline::new()?
822 .no_table_former(no_table_former)
823 .no_ocr(no_ocr)
824 .process_pages(pages, name)
825}
826
827#[cfg(test)]
828mod send_check {
829 /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
830 /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
831 /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
832 /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
833 fn assert_send<T: Send>() {}
834
835 #[test]
836 fn pipeline_is_send() {
837 assert_send::<super::Pipeline>();
838 }
839}