Skip to main content

docling_pdf/
lib.rs

1//! PDF backend for docling.rs.
2//!
3//! A port of docling's standard PDF pipeline: pdfium extracts the text layer
4//! (cells with bounding boxes) and renders page images; a discriminative ONNX
5//! stack (layout detection, table structure, OCR) classifies regions; the cells
6//! are assembled in reading order into a [`DoclingDocument`].
7//!
8//! Current stages: pdfium text-cell extraction + page rendering ([`pdfium_backend`])
9//! and the deterministic text/reading-order assembly ([`assemble`]). The layout,
10//! table-structure and OCR ONNX stages land behind [`Pipeline`] next.
11
12// Without `ml` only the text-layer path runs; the shared assembly/label
13// helpers it doesn't exercise stay compiled for API stability (the full
14// build still flags genuinely dead code).
15#![cfg_attr(not(feature = "ml"), allow(dead_code))]
16
17// Reading-order assembly. Public under `ocr-prep` so the browser pipeline can
18// reuse the geometric table reconstruction and its reliability gate (#157).
19#[cfg(feature = "ocr-prep")]
20pub mod assemble;
21#[cfg(not(feature = "ocr-prep"))]
22mod assemble;
23mod dp_lines;
24#[cfg(feature = "ml")]
25pub mod enrich;
26// Public so sibling crates (e.g. docling-rag's ONNX embedder) can route their
27// own `ort` sessions through the same `DOCLING_RS_EP` selection. Kept as a
28// re-export after the logic moved to the shared `docling-onnx` crate —
29// `docling_pdf::ep::…` remains the stable path downstream crates code against.
30#[cfg(feature = "ml")]
31pub use docling_onnx as ep;
32// Heading-hierarchy stage (#302): PDF font-name style parsing, outline
33// extraction (pure lopdf), and the level-assignment pass. No feature gate on
34// the logic itself — only the glyph style pass needs pdfium (`ml`).
35#[cfg(feature = "ml")]
36pub mod dparse_render;
37mod font_style;
38mod heading_hierarchy;
39pub mod layout;
40#[cfg(feature = "ml")]
41mod mets;
42#[cfg(feature = "ml")]
43mod ocr;
44#[cfg(any(feature = "ml", feature = "ocr-prep"))]
45pub mod ocr_det;
46#[cfg(feature = "ocr-prep")]
47pub mod ocr_prep;
48#[cfg(feature = "ml")]
49mod orient;
50pub mod outline;
51pub mod pdfium_backend;
52#[cfg(feature = "ml")]
53pub mod quality;
54mod reading_order;
55// Pure-Rust region resampling (page→1024px box-average, crop→448 bilinear) —
56// available to the browser TableFormer path (#157 stage 3), not just `ml`.
57#[cfg(feature = "ocr-prep")]
58pub mod resample;
59#[cfg(feature = "ocr-prep")]
60pub mod scanned;
61// Built-in standard-14 font metrics for the pure-Rust text parser (#187) —
62// no feature gate: the wasm/pdf-text path needs them like the native one.
63pub mod pdf_meta;
64#[cfg(feature = "ml")]
65pub mod raster;
66#[cfg(feature = "ml")]
67pub mod render;
68mod std14;
69#[cfg(feature = "ml")]
70pub mod tableformer;
71#[cfg(feature = "ml")]
72mod tesseract;
73pub mod textparse;
74#[cfg(feature = "ocr-prep")]
75pub mod tf_core;
76// docling's TableFormer cell matcher — pure Rust, shared with the browser
77// TableFormer path (#157 stage 3).
78#[cfg(feature = "ocr-prep")]
79pub mod tf_match;
80pub mod timing;
81
82#[cfg(feature = "ml")]
83use std::collections::BTreeMap;
84use std::fmt;
85#[cfg(feature = "ml")]
86use std::sync::mpsc::{sync_channel, Receiver};
87#[cfg(feature = "ml")]
88use std::sync::{Arc, Mutex};
89
90// An execution provider only exists on its OS, and ort's prebuilt ONNX
91// Runtime binaries follow suit — requesting an impossible pairing otherwise
92// surfaces as a cryptic ort-sys linker error ("no builds available that
93// satisfy the requested feature set"). Catch it at type-check time with an
94// actionable message instead.
95#[cfg(all(feature = "coreml", not(target_vendor = "apple")))]
96compile_error!(
97    "the `coreml` execution provider exists only on Apple targets (macOS/iOS). \
98     On Linux use `--features cuda` or `--features tensorrt` (NVIDIA), on \
99     Windows also `--features directml`, or build without EP features for CPU."
100);
101#[cfg(all(feature = "directml", not(target_os = "windows")))]
102compile_error!(
103    "the `directml` execution provider exists only on Windows. On Linux use \
104     `--features cuda` or `--features tensorrt` (NVIDIA), on macOS \
105     `--features coreml`, or build without EP features for CPU."
106);
107#[cfg(all(any(feature = "cuda", feature = "tensorrt"), target_vendor = "apple"))]
108compile_error!(
109    "the `cuda`/`tensorrt` execution providers have no Apple builds (no NVIDIA \
110     support on macOS). Use `--features coreml` there, or build without EP \
111     features for CPU."
112);
113
114use docling_core::DoclingDocument;
115// The env-knob helpers only gate ML-pipeline diagnostics and tuning; the
116// pure text-layer (wasm) build has no call sites.
117#[cfg(feature = "ml")]
118use docling_core::Node;
119#[cfg(feature = "ml")]
120use docling_core::{debug_log, env};
121
122pub use heading_hierarchy::HeadingHierarchyOptions;
123#[cfg(feature = "ml")]
124pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options, convert_mets_gbs_with_pipeline};
125#[cfg(feature = "ml")]
126pub use ocr::{OcrEngine, OcrLang, OcrMode};
127#[cfg(feature = "ml")]
128pub use pdfium_backend::PdfDocument;
129pub use pdfium_backend::{PdfPage, TextCell};
130#[cfg(feature = "ml")]
131pub use tesseract::{lang_arg as tesseract_lang_arg, TesseractOptions};
132// Plain page rasterization (#243) — pdfium only, no models.
133#[cfg(feature = "ml")]
134pub use pdfium_backend::{render_pages, RenderedPage};
135
136/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
137#[derive(Debug)]
138pub enum PdfError {
139    /// pdfium failed to bind, open, or read the document (and, historically,
140    /// any pipeline error outside the models).
141    Pdfium(String),
142    /// The document itself: an object model lopdf cannot read, a page no
143    /// renderer can draw, a page range outside it.
144    Document(String),
145    /// The layout ONNX model failed to load or run.
146    Layout(String),
147    /// The OCR ONNX model failed to load or run.
148    Ocr(String),
149}
150
151impl fmt::Display for PdfError {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        match self {
154            PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
155            PdfError::Document(m) => write!(f, "pdf: {m}"),
156            PdfError::Layout(m) => write!(f, "pdf: {m}"),
157            PdfError::Ocr(m) => write!(f, "pdf: {m}"),
158        }
159    }
160}
161
162impl std::error::Error for PdfError {}
163
164#[cfg(feature = "pdfium")]
165impl From<pdfium_render::prelude::PdfiumError> for PdfError {
166    fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
167        // A failed dlopen means the library this build was asked to use
168        // (`pdfium` feature) is not there. Say what to do instead of leaking
169        // the raw loader error.
170        if matches!(e, pdfium_render::prelude::PdfiumError::LoadLibraryError(_)) {
171            // The loader error pretty-prints over several lines; compact it.
172            let detail = e
173                .to_string()
174                .split_whitespace()
175                .collect::<Vec<_>>()
176                .join(" ");
177            return PdfError::Pdfium(format!(
178                "the pdfium library is not installed. This build's `pdfium` feature \
179                 was asked for it (DOCLING_RS_RENDERER=pdfium, or a file the pure-Rust \
180                 object model cannot read): point PDFIUM_DYNAMIC_LIB_PATH at a directory \
181                 containing the pdfium library, or unset DOCLING_RS_RENDERER — the \
182                 default renderer needs no library. Declarative formats (DOCX, HTML, \
183                 Markdown, …) never need it. [{detail}]"
184            ));
185        }
186        PdfError::Pdfium(e.to_string())
187    }
188}
189
190/// Convert a PDF's **embedded text layer only** — no ONNX, no
191/// threads: the pure-Rust content-stream parser ([`textparse`]) feeds the same
192/// orphan-region assembly the `no_ocr` pipeline flag uses, so text-layer PDFs
193/// come out identical to `--no-ocr` (flat, line-grouped paragraphs in reading
194/// order; no headings/lists/tables/pictures, and no hyperlink recovery).
195///
196/// This is the only conversion entry compiled without the `ml` feature (it is
197/// what a wasm32 build runs). A scanned/image-only PDF (no embedded text
198/// layer) yields an empty document rather than an error, same as `no_ocr` —
199/// callers can detect that and fall back to an OCR-capable build.
200pub fn convert_text_layer(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
201    convert_text_layer_pages(bytes, name, None)
202}
203
204/// [`convert_text_layer`] restricted to a **1-based inclusive** page window
205/// (issue #80's `--pages`); `None` converts everything. The window is
206/// validated the same way as [`Pipeline::pages`]: `first <= last`, 1-based,
207/// and it must select at least one existing page.
208pub fn convert_text_layer_pages(
209    bytes: &[u8],
210    name: &str,
211    pages: Option<(usize, usize)>,
212) -> Result<DoclingDocument, PdfError> {
213    if let Some((first, last)) = pages {
214        if first == 0 || last < first {
215            return Err(PdfError::Pdfium(format!(
216                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
217            )));
218        }
219    }
220    let mut doc = DoclingDocument::new(name);
221    let mut total = 0usize;
222    let parsed = textparse::pdf_text_pages(bytes);
223    // A vestigial layer (a few typed-in form fields over scanned pages) is not
224    // the document's text: return the empty document, which callers already
225    // report as "no text layer" — so an OCR-capable caller falls back to OCR
226    // instead of proudly extracting thirteen characters.
227    if textparse::text_layer_is_vestigial(&parsed) {
228        return Ok(doc);
229    }
230    for (i, page) in parsed.into_iter().enumerate() {
231        total += 1;
232        if let Some((first, last)) = pages {
233            if i + 1 < first || i + 1 > last {
234                continue;
235            }
236        }
237        let mut regions = Vec::new();
238        assemble::add_orphan_regions(&mut regions, &page.cells);
239        let table_rows = vec![None; regions.len()];
240        let enrich_out = vec![None; regions.len()];
241        let (mut nodes, links) = assemble::assemble_page(&page, regions, &table_rows, &enrich_out);
242        assemble::stamp_page_no(&mut nodes, i + 1);
243        doc.nodes.extend(nodes);
244        doc.links.extend(links);
245    }
246    if let Some((first, last)) = pages {
247        if first > total {
248            return Err(PdfError::Pdfium(format!(
249                "page range {first}-{last} is outside the document ({total} page(s))"
250            )));
251        }
252    }
253    assemble::merge_continuations(&mut doc.nodes);
254    Ok(doc)
255}
256
257/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
258/// Defaults to the available parallelism (ort otherwise picks a low number).
259#[cfg(feature = "ml")]
260pub(crate) fn intra_threads() -> usize {
261    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_THREADS").filter(|&n| n > 0) {
262        return n;
263    }
264    env::cpu_budget()
265}
266
267#[cfg(feature = "ml")]
268/// TableFormer's intra-op width (#262): `DOCLING_RS_TF_INTRA` explicitly,
269/// else the shared [`intra_threads`] budget. The shared TF session used to
270/// take the raw host width on top of the already-sized worker pools —
271/// under a cgroup CPU limit that oversubscription showed up as constant
272/// throttling and ~66% higher peak memory (each intra thread carries its own
273/// arena slab); the reporter's 4-CPU/8-core case dropped from 2.2 GB to
274/// 1.3 GB peak by capping this pool.
275pub(crate) fn tf_intra() -> usize {
276    if let Some(n) = env::parse::<usize>("DOCLING_RS_TF_INTRA").filter(|&n| n > 0) {
277        return n;
278    }
279    intra_threads()
280}
281
282#[cfg(feature = "ml")]
283/// True when `DOCLING_RS_FP32` forces the full-precision models even where
284/// an INT8 variant sits next to the fp32 default.
285pub(crate) fn fp32_forced() -> bool {
286    env::flag("DOCLING_RS_FP32")
287}
288
289#[cfg(feature = "ml")]
290/// Should the int8 model defaults be skipped in favor of fp32? Either the
291/// user said so (`DOCLING_RS_FP32`), or a GPU execution provider is selected
292/// (#74) — the int8 exports are QDQ graphs calibrated for CPU kernels and
293/// only conformance-validated there. An explicit `DOCLING_*_ONNX` path
294/// override still wins over this at every call site.
295pub(crate) fn prefer_fp32() -> bool {
296    fp32_forced() || docling_onnx::prefers_fp32()
297}
298
299#[cfg(feature = "ml")]
300/// Resolve a default (CWD-relative) asset path — the shared chain in
301/// [`docling_core::assets`]: CWD, then next to the executable and one level
302/// above it (the `scripts/install/install.sh` layout).
303pub(crate) fn resolve_asset(rel: &str) -> String {
304    docling_core::assets::resolve(rel)
305}
306
307/// One resolved runtime asset — which file a stage would load right now,
308/// given the CWD, the env overrides and the int8/fp32 preference.
309#[cfg(feature = "ml")]
310#[derive(Debug, Clone)]
311pub struct ModelEntry {
312    /// Pipeline stage, e.g. `layout`, `tableformer.decoder`, `ocr.rec`.
313    pub stage: &'static str,
314    /// The resolved path (absolute or CWD-relative, as it will be opened).
315    pub path: String,
316    /// Whether the file exists right now.
317    pub found: bool,
318    /// File size in bytes (0 when missing) — enough to tell an int8 quant
319    /// from an fp32 graph, or a stale model from a re-published one, at a
320    /// glance without hashing gigabytes per request.
321    pub bytes: u64,
322}
323
324/// Resolve the whole runtime model set **without loading anything** — the
325/// exact selection each stage performs at load time (layout honors the
326/// int8/fp32 preference, TableFormer its decoder ranking, OCR the language
327/// pair), plus the pdfium library. docling-serve exposes this at
328/// `/v1/config` and logs it at startup, so "the server picked up different
329/// models" is one `curl` away instead of a mystery of dissolved tables.
330/// Resolution is CWD-relative with an exe-dir fallback, so the answer can
331/// legitimately differ between two working directories.
332#[cfg(feature = "ml")]
333pub fn model_inventory() -> Vec<ModelEntry> {
334    fn entry(stage: &'static str, path: String) -> ModelEntry {
335        let meta = std::fs::metadata(&path).ok();
336        ModelEntry {
337            stage,
338            found: meta.is_some(),
339            bytes: meta.map(|m| m.len()).unwrap_or(0),
340            path,
341        }
342    }
343    let (enc, dec, bbx) = tableformer::resolved_paths();
344    let (rec, dict) = ocr::resolve_rec_pair(ocr::OcrLang::from_env());
345    let pdfium =
346        env::nonempty("PDFIUM_DYNAMIC_LIB_PATH").unwrap_or_else(|| resolve_asset(".pdfium/lib"));
347    vec![
348        entry(
349            "layout",
350            model_path(
351                "DOCLING_LAYOUT_ONNX",
352                ".models/layout_heron.onnx",
353                ".models/layout_heron_int8.onnx",
354            ),
355        ),
356        entry("tableformer.encoder", enc),
357        entry("tableformer.decoder", dec),
358        entry("tableformer.bbox", bbx),
359        entry("ocr.rec", rec),
360        entry("ocr.dict", dict),
361        entry("pdfium", pdfium),
362    ]
363}
364
365/// Resolve a model path: an explicit env override always wins; otherwise the
366/// INT8 variant of the default path when it exists on disk (the quantized
367/// models are conformance-validated — see docs/PDF_CONFORMANCE.md — and load/run
368/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
369/// precision; else the fp32 default.
370#[cfg(feature = "ml")]
371pub(crate) fn model_path(key: &str, fp32_default: &str, int8_default: &str) -> String {
372    if let Some(p) = env::nonempty(key) {
373        return p;
374    }
375    if !prefer_fp32() {
376        let p = resolve_asset(int8_default);
377        if std::path::Path::new(&p).exists() {
378            return p;
379        }
380    }
381    resolve_asset(fp32_default)
382}
383
384/// Decode a standalone image with hard resource limits. A crafted image can
385/// declare enormous dimensions in a few-KB file; `image::load_from_memory`
386/// then tries to allocate the full pixel buffer (e.g. 60000×60000 → ~10 GB),
387/// and allocation failure aborts the whole process, bypassing the per-request
388/// panic catch. The 256 MiB alloc / 30000-px caps below turn that into a
389/// recoverable decode error instead. `DOCLING_RS_MAX_IMAGE_PIXELS` overrides
390/// the per-side pixel cap for the rare legitimately-huge scan.
391///
392/// Gated on `ml`: the only callers (`convert_image`, the METS backend) are
393/// ML-only, and the `image` crate is an `ml`-feature dependency — the
394/// text-layer wasm build has neither.
395#[cfg(feature = "ml")]
396pub(crate) fn decode_image_limited(bytes: &[u8]) -> Result<image::RgbImage, PdfError> {
397    let max_side: u32 = env::parse("DOCLING_RS_MAX_IMAGE_PIXELS").unwrap_or(30_000);
398    decode_image_with_max_side(bytes, max_side)
399}
400
401/// Whether `bytes` is an ISOBMFF HEIF/HEIC container (the `ftyp` brands
402/// iPhones write). Checked by content, not extension — HEIC regularly
403/// arrives misnamed `.jpg`.
404#[cfg(feature = "ml")]
405fn is_heif(bytes: &[u8]) -> bool {
406    bytes.len() >= 12
407        && &bytes[4..8] == b"ftyp"
408        && matches!(
409            &bytes[8..12],
410            b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"hevs" | b"mif1" | b"msf1"
411        )
412}
413
414/// Decode a HEIF/HEIC primary image via libheif (#211). Behind the opt-in
415/// `heif` feature — libheif is a native dependency the default build (and
416/// wasm) must not carry.
417#[cfg(all(feature = "ml", feature = "heif"))]
418fn decode_heif(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
419    use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
420    let err = |e: String| PdfError::Pdfium(format!("heif: {e}"));
421    let ctx = HeifContext::read_from_bytes(bytes).map_err(|e| err(e.to_string()))?;
422    let handle = ctx.primary_image_handle().map_err(|e| err(e.to_string()))?;
423    if handle.width() > max_side || handle.height() > max_side {
424        return Err(err(format!(
425            "image dimensions {}x{} exceed the {max_side}px per-side cap \
426             (DOCLING_RS_MAX_IMAGE_PIXELS overrides)",
427            handle.width(),
428            handle.height()
429        )));
430    }
431    let lib = LibHeif::new();
432    let img = lib
433        .decode(&handle, ColorSpace::Rgb(RgbChroma::Rgb), None)
434        .map_err(|e| err(e.to_string()))?;
435    let (w, h) = (img.width(), img.height());
436    let planes = img.planes();
437    let plane = planes
438        .interleaved
439        .ok_or_else(|| err("no RGB plane".into()))?;
440    let stride = plane.stride;
441    let mut out = image::RgbImage::new(w, h);
442    for (y, row) in out.rows_mut().enumerate() {
443        let src = &plane.data[y * stride..y * stride + w as usize * 3];
444        for (x, px) in row.enumerate() {
445            px.0 = [src[x * 3], src[x * 3 + 1], src[x * 3 + 2]];
446        }
447    }
448    Ok(out)
449}
450
451#[cfg(feature = "ml")]
452fn decode_image_with_max_side(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
453    use image::{ImageDecoder, ImageReader};
454    use std::io::Cursor;
455
456    if is_heif(bytes) {
457        #[cfg(feature = "heif")]
458        return decode_heif(bytes, max_side);
459        #[cfg(not(feature = "heif"))]
460        return Err(PdfError::Pdfium(
461            "HEIC/HEIF input needs a build with the `heif` cargo feature \
462             (rebuild with --features heif; links the system libheif)"
463                .into(),
464        ));
465    }
466
467    let mut limits = image::Limits::default();
468    limits.max_image_width = Some(max_side);
469    limits.max_image_height = Some(max_side);
470    limits.max_alloc = Some(256 * 1024 * 1024);
471
472    let mut reader = ImageReader::new(Cursor::new(bytes))
473        .with_guessed_format()
474        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
475    reader.limits(limits);
476    let mut decoder = reader
477        .into_decoder()
478        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
479    // docling#4247 (2.128, `ImageOps.exif_transpose`): a camera stores the
480    // sensor readout plus an orientation tag rather than rotated pixels, so
481    // a portrait photo would reach layout and OCR on its side unless the tag
482    // is honoured. An unreadable tag is no orientation, not an error.
483    let orientation = decoder
484        .orientation()
485        .unwrap_or(image::metadata::Orientation::NoTransforms);
486    let mut img = image::DynamicImage::from_decoder(decoder)
487        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
488    img.apply_orientation(orientation);
489    Ok(img.into_rgb8())
490}
491
492#[cfg(feature = "ml")]
493/// One page's assembled output: typed nodes plus the page's hyperlinks (kept
494/// separate so pages processed out of order can be stitched back in page
495/// order) and its confidence scores (#183).
496type PageOut = (
497    Vec<Node>,
498    Vec<(String, String)>,
499    docling_core::confidence::PageConfidence,
500);
501
502#[cfg(feature = "ml")]
503/// A page between region resolution and TableFormer: what `prepare_page`
504/// produced and `complete_page` still needs, so a pool worker can park the
505/// page while another worker holds the shared TableFormer (see `Staged`).
506struct Prepared {
507    regions: Vec<layout::Region>,
508    ocr_confs: Vec<f32>,
509    parse: Option<f64>,
510}
511
512#[cfg(feature = "ml")]
513/// A pool worker's per-page outcome. `NeedsTables` is a page whose only
514/// remaining stage is the shared TableFormer, which was busy when the worker
515/// got there: rather than block on the mutex — one worker idle for the
516/// whole of another worker's table decode, ~9.5 s of the 60-page .NET slice
517/// on a 2-worker pool — the worker keeps the page aside, pulls the next one
518/// off the render channel, and comes back once the slot is free. Results
519/// are reassembled by page index anyway, so completion order is free.
520enum Staged {
521    Done(PageOut),
522    NeedsTables(Prepared),
523}
524
525#[cfg(feature = "ml")]
526/// How many pages a pool worker keeps parked on the TableFormer before it
527/// falls back to waiting: each carries its ~5 MB bitmaps, so this bounds the
528/// extra residency to two pages per worker on top of the render channel.
529const MAX_DEFERRED_PAGES: usize = 2;
530
531#[cfg(feature = "ml")]
532/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
533/// lazily on the first table region any worker sees. Tables appear on a
534/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
535/// weights+arenas by the pool size for nothing; a single shared instance keeps
536/// the peak flat regardless of pool width, and a table's structure prediction
537/// is independent of which worker runs it, so output is byte-identical. The
538/// mutex serialises concurrent tables — the shared instance is loaded with the
539/// full intra-op thread budget to compensate (one wide TableFormer instead of
540/// several narrow ones).
541enum TfSlot {
542    /// Not attempted yet (no table seen so far).
543    Unloaded,
544    /// Load attempted, graphs absent — geometric fallback (warned once).
545    Missing,
546    Ready(tableformer::TableFormer),
547}
548
549#[cfg(feature = "ml")]
550type SharedTables = Arc<Mutex<TfSlot>>;
551
552#[cfg(feature = "ml")]
553/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
554/// one instance per pipeline, loaded on the first region that needs it.
555enum EnrichSlot<T> {
556    Unloaded,
557    /// Load attempted, model files absent — enrichment skipped (warned once).
558    Missing,
559    Ready(T),
560}
561
562#[cfg(feature = "ml")]
563type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
564#[cfg(feature = "ml")]
565type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
566
567#[cfg(feature = "ml")]
568/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
569/// flags (`do_picture_classification`, `do_code_enrichment`,
570/// `do_formula_enrichment`). All off by default.
571#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
572pub struct EnrichmentOptions {
573    /// Classify each picture with DocumentFigureClassifier (26 classes).
574    pub picture_classification: bool,
575    /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
576    pub code: bool,
577    /// Decode display formulas to LaTeX with CodeFormulaV2.
578    pub formula: bool,
579}
580
581#[cfg(feature = "ml")]
582impl EnrichmentOptions {
583    fn any(&self) -> bool {
584        self.picture_classification || self.code || self.formula
585    }
586}
587
588#[cfg(feature = "ml")]
589/// The layout model's input for a page: the pypdfium2-exact scale-1.0 page
590/// image (#478) when the renderer produced one, else the legacy stretch of the 2×
591/// bitmap (browser / METS paths) — see [`layout::LayoutSrc`]. Public so the
592/// diagnostic examples feed [`layout::LayoutModel::predict`] the same input
593/// the pipeline does.
594pub fn layout_src(page: &PdfPage) -> layout::LayoutSrc<'_> {
595    match &page.image_layout {
596        Some(img) => layout::LayoutSrc::PageImage(img),
597        None => layout::LayoutSrc::Raw(&page.image),
598    }
599}
600
601#[cfg(feature = "ml")]
602/// The bitmap + px/pt scale the OCR reads (#254, docling#3877's
603/// `OcrOptions.scale`): the page's own render unless `ocr_scale` asks for a
604/// different resolution, where a PIL-bicubic resample of that render is built
605/// once per page (cached in `cache`) and shared by every OCR pass. Resampling
606/// — rather than a second native pdfium render — keeps one code path across
607/// PDF, image, and hOCR inputs and leaves the layout/TableFormer pixels (and
608/// with them the conformance baseline) untouched; the 144-dpi base render is
609/// itself supersampled down from 216 dpi, so an upscaled OCR view loses
610/// little against a native render.
611fn ocr_input<'a>(
612    cache: &'a mut Option<image::RgbImage>,
613    image: &'a image::RgbImage,
614    scale: f32,
615    ocr_scale: Option<f32>,
616) -> (&'a image::RgbImage, f32) {
617    match ocr_scale {
618        Some(s) if (s - scale).abs() > 1e-3 && image.width() > 1 => {
619            let f = s / scale;
620            let img = cache.get_or_insert_with(|| {
621                let dw = ((image.width() as f32 * f).round() as u32).max(1);
622                let dh = ((image.height() as f32 * f).round() as u32).max(1);
623                resample::pil_resize(image, dw, dh, resample::PilFilter::Bicubic)
624            });
625            (img, s)
626        }
627        _ => (image, scale),
628    }
629}
630
631#[cfg(feature = "ml")]
632/// A self-contained set of the per-page models (layout, OCR). Each parallel
633/// page-worker owns its own `Worker` so inference runs concurrently without
634/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
635/// rarely-hit TableFormer is shared (see [`TfSlot`]).
636struct Worker {
637    /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
638    layout: Option<layout::LayoutModel>,
639    ocr: OcrSlot,
640    det: DetSlot,
641    /// Text-detector results computed ahead of a page's OCR pass (#429), keyed
642    /// by page index: the detector reads nothing but the page image, so it
643    /// runs on its own thread while the layout model predicts — see
644    /// [`Self::detect_alongside`] — and the OCR block collects the boxes here
645    /// instead of paying for detection serially.
646    pending_det: BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
647    /// This worker's intra-op thread budget — also the OCR lane count (see
648    /// [`ocr::OcrModel::load_with`]): a pool worker with two threads runs two
649    /// single-thread recognisers, the primary as many as its cores.
650    intra: usize,
651    /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
652    tables: Option<SharedTables>,
653    /// Shared enrichment slots; `None` unless the corresponding flag is on.
654    classifier: Option<SharedClassifier>,
655    code_formula: Option<SharedCodeFormula>,
656    enrich: EnrichmentOptions,
657    /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
658    /// embedded text layer. See [`Pipeline::no_ocr`].
659    no_ocr: bool,
660    /// Discard the embedded text layer and OCR every page. See
661    /// [`Pipeline::force_full_page_ocr`].
662    force_full_page_ocr: bool,
663    /// Keep text-panel pictures as pictures instead of demoting them to
664    /// paragraphs. See [`Pipeline::no_text_panels`].
665    no_text_panels: bool,
666    /// Never run OCR, but keep layout + TableFormer (#244) — docling's
667    /// `do_ocr=False`. See [`Pipeline::skip_ocr`].
668    skip_ocr: bool,
669    /// Which recognition model [`Self::ocr`] loads. See [`Pipeline::ocr_lang`].
670    ocr_lang: ocr::OcrLang,
671    /// Which engine [`Self::ocr`] is (#460). See [`Pipeline::ocr_engine`].
672    ocr_engine: ocr::OcrEngine,
673    /// Tesseract's `-l` argument (#460). See [`Pipeline::tesseract_lang`].
674    tesseract_lang: Option<String>,
675    /// OCR render scale override (px/pt, #254). See [`Pipeline::ocr_scale`].
676    ocr_scale: Option<f32>,
677}
678
679#[cfg(feature = "ml")]
680/// The worker's lazily-loaded OCR recognition model. `Missing` records a
681/// failed load (#244: degradation over failure — a deployment without the OCR
682/// model still gets layout + TableFormer, and OCR-dependent regions stay
683/// empty) so the load isn't retried per page.
684enum OcrSlot {
685    Unloaded,
686    Ready(Recognizer),
687    Missing,
688}
689
690#[cfg(feature = "ml")]
691/// The loaded OCR engine (#460): PP-OCRv3 via ONNX Runtime or the
692/// `tesseract` binary. Both answer the two questions the page assembly asks
693/// — line cells for text regions, word cells for table regions — in page
694/// points with a 0–1 confidence, so the call sites never know which runs.
695pub(crate) enum Recognizer {
696    PpOcr(ocr::OcrModel),
697    Tesseract(tesseract::TesseractOcr),
698}
699
700#[cfg(feature = "ml")]
701impl Recognizer {
702    /// See [`ocr::OcrModel::ocr_page`].
703    fn ocr_page(
704        &mut self,
705        img: &image::RgbImage,
706        regions: &[layout::Region],
707        scale: f32,
708    ) -> Result<Vec<(TextCell, f32)>, String> {
709        match self {
710            Self::PpOcr(m) => m.ocr_page(img, regions, scale),
711            Self::Tesseract(t) => t.ocr_page(img, regions, scale),
712        }
713    }
714
715    /// See [`ocr::OcrModel::ocr_table_words`].
716    fn ocr_table_words(
717        &mut self,
718        img: &image::RgbImage,
719        regions: &[layout::Region],
720        scale: f32,
721    ) -> Result<Vec<(TextCell, f32)>, String> {
722        match self {
723            Self::PpOcr(m) => m.ocr_table_words(img, regions, scale),
724            Self::Tesseract(t) => t.ocr_table_words(img, regions, scale),
725        }
726    }
727}
728
729#[cfg(feature = "ml")]
730/// The text detector (#429), loaded on the first OCR'd page like the
731/// recognizer; `Missing` keeps the pipeline recognition-only.
732enum DetSlot {
733    Unloaded,
734    Ready(ocr_det::DetModel),
735    Missing,
736}
737
738#[cfg(feature = "ml")]
739impl Worker {
740    #[allow(clippy::too_many_arguments)] // mirrors the Pipeline's option set
741    fn load(
742        intra: usize,
743        tables: Option<SharedTables>,
744        enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
745        enrich: EnrichmentOptions,
746        no_ocr: bool,
747        skip_ocr: bool,
748        force_full_page_ocr: bool,
749        no_text_panels: bool,
750        ocr_lang: ocr::OcrLang,
751        ocr_engine: ocr::OcrEngine,
752        tesseract_lang: Option<String>,
753        ocr_scale: Option<f32>,
754    ) -> Result<Self, PdfError> {
755        Ok(Self {
756            layout: if no_ocr {
757                None
758            } else {
759                Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
760            },
761            ocr: OcrSlot::Unloaded,
762            det: DetSlot::Unloaded,
763            pending_det: BTreeMap::new(),
764            intra,
765            tables,
766            classifier: enrich_slots.0,
767            code_formula: enrich_slots.1,
768            enrich,
769            no_ocr,
770            skip_ocr,
771            force_full_page_ocr,
772            no_text_panels,
773            ocr_lang,
774            ocr_engine,
775            tesseract_lang,
776            ocr_scale,
777        })
778    }
779
780    /// The OCR model, or `None` when this conversion must not (or cannot) OCR:
781    /// `skip_ocr` short-circuits, and a failed model load degrades to `None`
782    /// with a one-time warning instead of failing the conversion (#244) —
783    /// unless `force_full_page_ocr` demanded OCR explicitly, where a missing
784    /// model stays a hard error (the text layer was deliberately discarded, so
785    /// degrading would silently emit an empty document).
786    fn ocr_model(&mut self) -> Result<Option<&mut Recognizer>, PdfError> {
787        if self.skip_ocr {
788            return Ok(None);
789        }
790        if matches!(self.ocr, OcrSlot::Unloaded) {
791            let loaded = match self.ocr_engine {
792                ocr::OcrEngine::PpOcr => {
793                    ocr::OcrModel::load_with(self.ocr_lang, self.intra).map(Recognizer::PpOcr)
794                }
795                ocr::OcrEngine::Tesseract => tesseract::TesseractOcr::load(
796                    tesseract::TesseractOptions::from_env(self.tesseract_lang.clone()),
797                    self.intra,
798                )
799                .map(Recognizer::Tesseract),
800            };
801            match loaded {
802                Ok(model) => self.ocr = OcrSlot::Ready(model),
803                Err(e) if self.force_full_page_ocr => return Err(PdfError::Ocr(e)),
804                Err(e) => {
805                    static WARNED: std::sync::Once = std::sync::Once::new();
806                    let hint = match self.ocr_engine {
807                        ocr::OcrEngine::PpOcr => {
808                            "run scripts/install/download_dependencies.sh for the model"
809                        }
810                        ocr::OcrEngine::Tesseract => {
811                            "install tesseract-ocr with the language pack, or use --ocr-engine ppocr"
812                        }
813                    };
814                    WARNED.call_once(|| {
815                        eprintln!(
816                            "warning: OCR model unavailable ({e}); continuing without OCR — \
817                             scanned pages and text inside images will come back empty \
818                             ({hint})"
819                        );
820                    });
821                    self.ocr = OcrSlot::Missing;
822                }
823            }
824        }
825        Ok(match &mut self.ocr {
826            OcrSlot::Ready(model) => Some(model),
827            _ => None,
828        })
829    }
830
831    /// The text detector (#429): loaded on first use, `None` with `skip_ocr`
832    /// or when the model is not installed — recognition stays region-scoped
833    /// then, exactly the pre-#429 behavior, and `DOCLING_RS_DEBUG` says why.
834    fn det_model(&mut self) -> Option<&mut ocr_det::DetModel> {
835        if self.skip_ocr {
836            return None;
837        }
838        if matches!(self.det, DetSlot::Unloaded) {
839            match ocr_det::DetModel::load(self.intra) {
840                Ok(model) => self.det = DetSlot::Ready(model),
841                Err(e) => {
842                    docling_core::debug_log!(
843                        "docling-pdf: text detection unavailable ({e}); OCR stays region-scoped"
844                    );
845                    self.det = DetSlot::Missing;
846                }
847            }
848        }
849        match &mut self.det {
850            DetSlot::Ready(model) => Some(model),
851            _ => None,
852        }
853    }
854
855    /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
856    /// into its nodes and links. Pure given the page (mutates only the worker's
857    /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
858    fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
859        if self.no_ocr {
860            // Fastest path: no layout/OCR/TableFormer inference at all. The PDF's
861            // embedded text cells (if any) become flat, line-grouped paragraphs in
862            // reading order via the same orphan-region machinery that normally
863            // rescues text the detector missed — here it rescues *all* of it.
864            // Pages with no embedded text layer (scanned/image-only) yield nothing;
865            // convert those without `no_ocr`.
866            let parse = quality::parse_score(&page.cells);
867            let mut regions = Vec::new();
868            assemble::add_orphan_regions(&mut regions, &page.cells);
869            let table_rows = vec![None; regions.len()];
870            let enrich_out = vec![None; regions.len()];
871            let conf = quality::page_confidence(parse, &regions, &[]);
872            let (nodes, links) = timing::timed("assemble_page", || {
873                assemble::assemble_page(page, regions, &table_rows, &enrich_out)
874            });
875            return Ok((nodes, links, conf));
876        }
877        self.normalize_orientation(n, page)?;
878        let det_pages = self.det_candidates(std::slice::from_ref(&(n, &*page)))?;
879        let regions = {
880            let Self {
881                layout,
882                det,
883                pending_det,
884                ocr_scale,
885                ..
886            } = self;
887            let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
888            let page: &PdfPage = &*page;
889            Self::detect_alongside(det, pending_det, *ocr_scale, &det_pages, || {
890                timing::timed("layout.predict", || {
891                    layout.predict(layout_src(page), page.width, page.height)
892                })
893            })
894        }
895        .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
896        self.finish_page(n, page, regions)
897    }
898
899    /// The pages of a batch the text detector should sweep (#429): bitmap
900    /// pages (no text layer) on a run with OCR and the detector available —
901    /// loading both lazily here so the concurrent run below needs no `self`.
902    fn det_candidates<'p>(
903        &mut self,
904        pages: &[(usize, &'p PdfPage)],
905    ) -> Result<Vec<(usize, &'p PdfPage)>, PdfError> {
906        let scanned: Vec<(usize, &PdfPage)> = pages
907            .iter()
908            .filter(|(_, p)| p.cells.is_empty() && p.image.width() > 1)
909            .copied()
910            .collect();
911        if scanned.is_empty() || self.ocr_model()?.is_none() || self.det_model().is_none() {
912            return Ok(Vec::new());
913        }
914        Ok(scanned)
915    }
916
917    /// Run `layout` on the calling thread while the text detector sweeps
918    /// `det_pages` on another (#429): the detector only reads each page's
919    /// image, layout only reads the pages too, and the two sessions are
920    /// independent, so on a scanned page the ~0.7 s detection hides behind
921    /// layout instead of adding to it. Results land in `pending_det` for the
922    /// OCR block; a detector failure is recorded per page and surfaces there.
923    fn detect_alongside<T>(
924        det: &mut DetSlot,
925        pending_det: &mut BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
926        ocr_scale: Option<f32>,
927        det_pages: &[(usize, &PdfPage)],
928        layout: impl FnOnce() -> T,
929    ) -> T {
930        let DetSlot::Ready(det) = det else {
931            return layout();
932        };
933        if det_pages.is_empty() {
934            return layout();
935        }
936        std::thread::scope(|s| {
937            let handle = s.spawn(move || {
938                det_pages
939                    .iter()
940                    .map(|&(n, page)| {
941                        let mut view = None;
942                        let (img, _) = ocr_input(&mut view, &page.image, page.scale, ocr_scale);
943                        (n, timing::timed("ocr.det", || det.detect(img)))
944                    })
945                    .collect::<Vec<_>>()
946            });
947            let out = layout();
948            match handle.join() {
949                Ok(results) => pending_det.extend(results),
950                Err(_) => {
951                    for &(n, _) in det_pages {
952                        pending_det.insert(n, Err("ocr-det: detection thread panicked".into()));
953                    }
954                }
955            }
956            out
957        })
958    }
959
960    /// Content-based orientation normalization (#225), before any inference:
961    /// a physically rotated scan (sideways phone photo, landscape-fed sheet)
962    /// has `/Rotate 0`, so the metadata pass in `extract_page` never fires and
963    /// layout+OCR would read a sideways raster. Only pages with no text layer
964    /// at all are probed (a digital page's raster is upright by construction,
965    /// and its cells — not its pixels — carry the text); the detected angle
966    /// composes with any `/Rotate` normalization through the same
967    /// [`PdfPage::unrotate`] + display-space assembly mapping. Detection is
968    /// evidence-gated and degrades to a no-op — see [`orient`].
969    fn normalize_orientation(&mut self, n: usize, page: &mut PdfPage) -> Result<(), PdfError> {
970        let scanned =
971            page.cells.is_empty() && page.word_cells.is_empty() && page.code_cells.is_empty();
972        if self.no_ocr || self.skip_ocr || !scanned || page.image.width() <= 1 || !orient::enabled()
973        {
974            return Ok(());
975        }
976        // The probe reads text through the OCR model; without one (missing —
977        // #244 degradation) the page stays as rendered.
978        let Some(ocr) = self.ocr_model()? else {
979            return Ok(());
980        };
981        let deg = timing::timed("orient.detect", || {
982            orient::detect(&page.image, ocr, page.scale)
983        });
984        if deg != 0 {
985            debug_log!(
986                "docling-pdf: page {}: content rotated {deg}° in the raster; \
987                 un-rotating before layout/OCR",
988                n + 1
989            );
990            page.unrotate(deg);
991        }
992        Ok(())
993    }
994
995    /// Layout-detect a whole batch of pages with one inference call (issue #73),
996    /// then run each page's remaining stages (OCR / TableFormer / enrichment /
997    /// assembly) per page. Index-aligned with `items`; a layout failure fails
998    /// every page in the batch (they shared the one inference call).
999    fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<Staged, PdfError>> {
1000        if self.no_ocr {
1001            // No layout model to batch — the text-layer-only path is per page.
1002            return items
1003                .iter_mut()
1004                .map(|(n, page)| {
1005                    let n = *n;
1006                    self.process(n, page).map(Staged::Done)
1007                })
1008                .collect();
1009        }
1010        // Orientation-normalize every scanned page before the shared layout
1011        // call — the batched inference must see upright bitmaps too (#225).
1012        for (n, page) in items.iter_mut() {
1013            let n = *n;
1014            if let Err(e) = self.normalize_orientation(n, page) {
1015                // Model-load failure — every page in the batch needs the same
1016                // model, so they all fail alike (mirrors the layout-error arm).
1017                let msg = e.to_string();
1018                return items
1019                    .iter()
1020                    .map(|_| Err(PdfError::Ocr(msg.clone())))
1021                    .collect();
1022            }
1023        }
1024        let inputs: Vec<(layout::LayoutSrc<'_>, f32, f32)> = items
1025            .iter()
1026            .map(|(_, page)| (layout_src(page), page.width, page.height))
1027            .collect();
1028        let refs: Vec<(usize, &PdfPage)> = items.iter().map(|(n, page)| (*n, page)).collect();
1029        let det_pages = match self.det_candidates(&refs) {
1030            Ok(p) => p,
1031            Err(e) => {
1032                let msg = e.to_string();
1033                return items
1034                    .iter()
1035                    .map(|_| Err(PdfError::Ocr(msg.clone())))
1036                    .collect();
1037            }
1038        };
1039        let batched = {
1040            let Self {
1041                layout,
1042                det,
1043                pending_det,
1044                ocr_scale,
1045                ..
1046            } = self;
1047            let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
1048            Self::detect_alongside(det, pending_det, *ocr_scale, &det_pages, || {
1049                timing::timed("layout.predict", || layout.predict_batch(&inputs))
1050            })
1051        };
1052        match batched {
1053            Ok(all) => items
1054                .iter_mut()
1055                .zip(all)
1056                .map(|((n, page), regions)| self.stage_page(*n, page, regions))
1057                .collect(),
1058            Err(e) => items
1059                .iter()
1060                .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
1061                .collect(),
1062        }
1063    }
1064
1065    /// A pool worker's main loop: pull rendered pages off the shared channel
1066    /// (whatever is already there, up to the layout batch size), process them,
1067    /// and hand each finished page — or its error — to `deliver`, which returns
1068    /// `false` to stop early (the streaming consumer went away). Returns when
1069    /// the channel is closed and every page this worker took is delivered.
1070    ///
1071    /// Pages whose TableFormer turn would have to wait are parked (see
1072    /// `Staged`) and retried before every new pull; while any are parked the
1073    /// pull is non-blocking, so an empty channel means the worker waits for
1074    /// the TableFormer rather than for the renderer. The parking budget
1075    /// (`MAX_DEFERRED_PAGES`) bounds resident bitmaps; past it the worker waits
1076    /// like the serial path. Output is independent of completion order — the
1077    /// callers reassemble by page index.
1078    fn run_pool(
1079        &mut self,
1080        work_rx: &Mutex<Receiver<(usize, PdfPage)>>,
1081        layout_batch: usize,
1082        mut deliver: impl FnMut(usize, Result<PageOut, PdfError>) -> bool,
1083    ) {
1084        use std::sync::mpsc::TryRecvError;
1085        let mut deferred: std::collections::VecDeque<(usize, PdfPage, Prepared)> =
1086            std::collections::VecDeque::new();
1087        loop {
1088            // Any parked page the slot has since freed up for, oldest first.
1089            let mut i = 0;
1090            while i < deferred.len() {
1091                let (_, page, prepared) = &deferred[i];
1092                match self.table_rows_try(page, &prepared.regions) {
1093                    Some(rows) => {
1094                        let (idx, mut page, prepared) = deferred.remove(i).expect("index in range");
1095                        if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1096                            return;
1097                        }
1098                    }
1099                    None => i += 1,
1100                }
1101            }
1102            // Hold the receiver lock only for the recv (plus a non-blocking drain
1103            // up to the layout batch size); release before the (long) per-page
1104            // work so other workers can pull concurrently.
1105            let mut batch: Vec<(usize, PdfPage)> = Vec::new();
1106            let mut closed = false;
1107            {
1108                let rx = work_rx.lock().unwrap();
1109                let first = if deferred.is_empty() {
1110                    rx.recv().map_err(|_| TryRecvError::Disconnected)
1111                } else {
1112                    rx.try_recv()
1113                };
1114                match first {
1115                    Ok(item) => {
1116                        batch.push(item);
1117                        while batch.len() < layout_batch {
1118                            match rx.try_recv() {
1119                                Ok(item) => batch.push(item),
1120                                Err(_) => break,
1121                            }
1122                        }
1123                    }
1124                    Err(TryRecvError::Empty) => {}
1125                    Err(TryRecvError::Disconnected) => closed = true,
1126                }
1127            }
1128            if batch.is_empty() {
1129                // Nothing new rendered (or the channel is closed): wait our turn
1130                // on the oldest parked page instead.
1131                match deferred.pop_front() {
1132                    Some((idx, mut page, prepared)) => {
1133                        let rows = self.table_rows_blocking(&page, &prepared.regions);
1134                        if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1135                            return;
1136                        }
1137                        continue;
1138                    }
1139                    None if closed => return,
1140                    None => continue,
1141                }
1142            }
1143            let outs = self.process_batch(&mut batch);
1144            for ((idx, mut page), out) in batch.into_iter().zip(outs) {
1145                let delivered = match out {
1146                    Ok(Staged::Done(out)) => deliver(idx, Ok(out)),
1147                    Ok(Staged::NeedsTables(prepared)) => {
1148                        if deferred.len() < MAX_DEFERRED_PAGES {
1149                            deferred.push_back((idx, page, prepared));
1150                            true
1151                        } else {
1152                            let rows = self.table_rows_blocking(&page, &prepared.regions);
1153                            deliver(idx, self.complete_page(idx, &mut page, prepared, rows))
1154                        }
1155                    }
1156                    Err(e) => deliver(idx, Err(e)),
1157                };
1158                if !delivered {
1159                    return;
1160                }
1161            }
1162        }
1163    }
1164
1165    /// Everything after layout detection: per-label confidence thresholds,
1166    /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
1167    /// TableFormer, enrichment, and page assembly. The serial path: waits
1168    /// for the shared TableFormer when a table needs it.
1169    fn finish_page(
1170        &mut self,
1171        n: usize,
1172        page: &mut PdfPage,
1173        regions: Vec<layout::Region>,
1174    ) -> Result<PageOut, PdfError> {
1175        let prepared = self.prepare_page(n, page, regions)?;
1176        let table_rows = self.table_rows_blocking(page, &prepared.regions);
1177        self.complete_page(n, page, prepared, table_rows)
1178    }
1179
1180    /// The pool path: like [`finish_page`](Self::finish_page), except that a
1181    /// page whose TableFormer turn would have to wait comes back as
1182    /// [`Staged::NeedsTables`] for the worker loop to park (see `Staged`).
1183    fn stage_page(
1184        &mut self,
1185        n: usize,
1186        page: &mut PdfPage,
1187        regions: Vec<layout::Region>,
1188    ) -> Result<Staged, PdfError> {
1189        let prepared = self.prepare_page(n, page, regions)?;
1190        match self.table_rows_try(page, &prepared.regions) {
1191            Some(rows) => Ok(Staged::Done(self.complete_page(n, page, prepared, rows)?)),
1192            None => Ok(Staged::NeedsTables(prepared)),
1193        }
1194    }
1195
1196    /// Does this page need the shared TableFormer at all? Table-free pages
1197    /// never touch (or load) it.
1198    fn needs_tables(&self, regions: &[layout::Region]) -> bool {
1199        self.tables.is_some() && regions.iter().any(|r| assemble::is_table_like(r.label))
1200    }
1201
1202    /// TableFormer structure for every table region of the page, on an
1203    /// already-locked slot (loading the model on first use). Tables serialise
1204    /// on this mutex, so the one instance gets the shared thread budget
1205    /// (quota-aware, #262) — DOCLING_RS_TF_INTRA narrows it further where the
1206    /// memory-per-thread tradeoff matters more than table latency.
1207    fn predict_tables(
1208        guard: &mut TfSlot,
1209        page: &PdfPage,
1210        regions: &[layout::Region],
1211    ) -> Vec<Option<tf_core::TableGrid>> {
1212        let mut table_rows: Vec<Option<tf_core::TableGrid>> = vec![None; regions.len()];
1213        if matches!(*guard, TfSlot::Unloaded) {
1214            *guard = match tableformer::TableFormer::load_with(tf_intra()) {
1215                Some(tf) => TfSlot::Ready(tf),
1216                None => TfSlot::Missing,
1217            };
1218        }
1219        if let TfSlot::Ready(tf) = guard {
1220            // One 1024-px frame per page, shared by all of its tables, and one
1221            // call for all of them: with the dynamic-batch decoder their
1222            // decode steps are shared (each step costs about the same for B
1223            // tables as for one).
1224            let page1024 = tableformer::TableFormer::page_1024(&page.image);
1225            let (idx, boxes): (Vec<usize>, Vec<[f32; 4]>) = regions
1226                .iter()
1227                .enumerate()
1228                .filter(|(_, r)| assemble::is_table_like(r.label))
1229                .map(|(i, r)| (i, [r.l, r.t, r.r, r.b]))
1230                .unzip();
1231            let rows =
1232                tf.predict_tables_on(page.image.height(), &page1024, &boxes, &page.word_cells);
1233            for (i, grid) in idx.into_iter().zip(rows) {
1234                table_rows[i] = grid;
1235            }
1236        }
1237        table_rows
1238    }
1239
1240    /// Table structure for the page, waiting for the shared slot if another
1241    /// worker holds it (else geometric fallback downstream when there is no
1242    /// TableFormer at all). The `tableformer` timing stage here includes any
1243    /// wait.
1244    fn table_rows_blocking(
1245        &self,
1246        page: &PdfPage,
1247        regions: &[layout::Region],
1248    ) -> Vec<Option<tf_core::TableGrid>> {
1249        match self.tables.as_ref().filter(|_| self.needs_tables(regions)) {
1250            Some(slot) => timing::timed("tableformer", || {
1251                Self::predict_tables(&mut slot.lock().unwrap(), page, regions)
1252            }),
1253            None => vec![None; regions.len()],
1254        }
1255    }
1256
1257    /// Non-blocking variant: `None` when the slot is held by another worker
1258    /// right now — the caller parks the page and tries again later.
1259    fn table_rows_try(
1260        &self,
1261        page: &PdfPage,
1262        regions: &[layout::Region],
1263    ) -> Option<Vec<Option<tf_core::TableGrid>>> {
1264        let Some(slot) = self.tables.as_ref().filter(|_| self.needs_tables(regions)) else {
1265            return Some(vec![None; regions.len()]);
1266        };
1267        match slot.try_lock() {
1268            Ok(mut guard) => Some(timing::timed("tableformer", || {
1269                Self::predict_tables(&mut guard, page, regions)
1270            })),
1271            Err(std::sync::TryLockError::WouldBlock) => None,
1272            Err(std::sync::TryLockError::Poisoned(e)) => panic!("TableFormer slot poisoned: {e}"),
1273        }
1274    }
1275
1276    /// The stages before TableFormer: fp32 escalation, per-label confidence
1277    /// thresholds, overlap resolution, orphan-text recovery, OCR for cell-less
1278    /// pages, in-picture text and table-word recognition.
1279    fn prepare_page(
1280        &mut self,
1281        n: usize,
1282        page: &mut PdfPage,
1283        regions: Vec<layout::Region>,
1284    ) -> Result<Prepared, PdfError> {
1285        // Force-OCR is exactly "pretend the text layer is not there": clear
1286        // every cell kind the extractors produced before anything reads them,
1287        // and the ordinary no-text-layer machinery below — full-page OCR,
1288        // OCR-fed TableFormer matching — takes over unchanged. (`no_ocr` wins
1289        // when both are set, mirroring docling, where `force_full_page_ocr`
1290        // is a sub-option of `do_ocr`; the no-ocr path never reaches here.)
1291        // Done here rather than in `process` so the batched layout path
1292        // (`process_batch` → `finish_page`) honors the flag too.
1293        // Parse quality is scored on the extracted text layer before force-OCR
1294        // discards it (docling's page-preprocessing stage runs before OCR too,
1295        // so its parse_score also reflects the original text layer).
1296        let parse = quality::parse_score(&page.cells);
1297        // Recognition confidences of every OCR'd cell on this page → ocr_score.
1298        let mut ocr_confs: Vec<f32> = Vec::new();
1299        // The bitmap the OCR reads (#254): with `ocr_scale` set, a resample of
1300        // the page render at the requested px/pt, built lazily on the first
1301        // OCR use so non-OCR pages never pay for it. Copied out of `self` up
1302        // front — the OCR sites hold `self.ocr_model()`'s mutable borrow.
1303        let ocr_scale = self.ocr_scale;
1304        let mut ocr_view: Option<image::RgbImage> = None;
1305        if self.force_full_page_ocr {
1306            page.cells.clear();
1307            page.code_cells.clear();
1308            page.word_cells.clear();
1309        }
1310        // Quant-robustness guard: the default int8 layout graph keeps its
1311        // confidences near the 0.5 label thresholds, and a different CPU's
1312        // quantized kernels can flip a whole page's detections under them —
1313        // tables and paragraphs then dissolve into orphan one-liners while the
1314        // same build converts the page perfectly elsewhere. When a dense
1315        // digital page ends up with detections covering almost none of its
1316        // text cells, re-run that one page on the fp32 graph (lazy-loaded,
1317        // auto-int8 selection only) and keep whichever detections cover more.
1318        let mut regions = regions;
1319        if !page.cells.is_empty() {
1320            let thresholded = |rs: &[layout::Region]| -> Vec<layout::Region> {
1321                rs.iter()
1322                    .filter(|r| r.score >= layout::label_threshold(r.label))
1323                    .cloned()
1324                    .collect()
1325            };
1326            let text_cells = page
1327                .cells
1328                .iter()
1329                .filter(|c| !c.text.trim().is_empty())
1330                .count();
1331            let cov = assemble::layout_cell_coverage(&thresholded(&regions), &page.cells);
1332            if text_cells >= 15 && cov < 0.5 {
1333                let retry = self
1334                    .layout
1335                    .as_mut()
1336                    .expect("layout model loaded unless no_ocr")
1337                    .predict_fp32_fallback(layout_src(page), page.width, page.height)
1338                    .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
1339                if let Some(retry) = retry {
1340                    let cov2 = assemble::layout_cell_coverage(&thresholded(&retry), &page.cells);
1341                    if cov2 > cov {
1342                        debug_log!(
1343                            "docling-pdf: page {}: int8 layout covered {:.0}% of the text \
1344                             cells; the fp32 retry covers {:.0}% — using it",
1345                            n + 1,
1346                            cov * 100.0,
1347                            cov2 * 100.0
1348                        );
1349                        regions = retry;
1350                    }
1351                }
1352            }
1353        }
1354        // docling's LayoutPostprocessor drops each detection below its label's
1355        // confidence threshold (stricter than the 0.3 base the predictor keeps),
1356        // before any overlap resolution. This removes the low-confidence tables /
1357        // pictures / list-items that otherwise double-emit or mis-classify.
1358        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1359            for r in &regions {
1360                eprintln!(
1361                    "DBG raw {} {:.2} [{:.0},{:.0},{:.0},{:.0}]",
1362                    r.label, r.score, r.l, r.t, r.r, r.b
1363                );
1364            }
1365        }
1366        regions.retain(|r| r.score >= layout::label_threshold(r.label));
1367        // docling's full-page picture filter and same-label picture dedup run
1368        // on the thresholded detections, before overlap resolution: a picture
1369        // that is the whole page goes (its text reads out as text), and a
1370        // figure proposed both whole and as sub-panels collapses to one box
1371        // (see `dedup_pictures`).
1372        assemble::drop_full_page_pictures(&mut regions, page.width, page.height);
1373        assemble::dedup_pictures(&mut regions);
1374        // Resolve overlapping detections once, before OCR.
1375        let mut regions = assemble::resolve(regions);
1376        // Emit text the detector missed as orphan text regions (docling parity).
1377        assemble::add_orphan_regions(&mut regions, &page.cells);
1378        // Drop phantom empty low-confidence picture boxes (docling parity).
1379        assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
1380        // A regular region fully inside a surviving table/index/picture is that
1381        // special's child (a cell / in-figure label), not a separate block —
1382        // remove it so it isn't emitted twice (docling parity).
1383        assemble::drop_contained_regulars(&mut regions);
1384        // A one-line paragraph in the bottom margin under a body-less heading
1385        // is that heading's text, not furniture (deliberate deviation).
1386        assemble::reclaim_heading_body_footers(&mut regions, page.width);
1387        // No text layer → recognise text from the page image via OCR.
1388        let ocred = page.cells.is_empty();
1389        // Lines the text detector found outside every layout region (#429).
1390        let mut det_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1391        if ocred {
1392            // Region-scoped OCR recognizes each region's crop, so two regular
1393            // regions over the same ink would read it twice — a low-score
1394            // paragraph box over the high-score line boxes `greedy` keeps.
1395            // Collapse such groups to one region first; a digital
1396            // page resolves the same overlap through cell ownership in
1397            // `fit_regions_to_cells` and needs nothing here.
1398            assemble::merge_overlapping_regulars(&mut regions);
1399            // `None` = `skip_ocr` or a missing model (#244): the page keeps
1400            // its layout regions (and TableFormer structure below) with no
1401            // recognized text, instead of failing the conversion.
1402            if let Some(ocr) = self.ocr_model()? {
1403                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1404                let cells = timing::timed("ocr.page", || ocr.ocr_page(img, &regions, scl))
1405                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1406                ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
1407                page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
1408                // Table interiors carry no words yet: region-scoped OCR skips
1409                // table labels, and a scanned page has no pdfium text layer — so
1410                // TableFormer's cell matcher got an empty word list and the table
1411                // dissolved (#173). Recognize the table regions' word crops
1412                // (mirroring the browser scanned path): `word_cells` feeds the
1413                // matcher, and the same cells join `cells` so the geometric
1414                // fallback and the table's region text see them too.
1415                if regions.iter().any(|r| assemble::is_table_like(r.label)) {
1416                    let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1417                    let words = timing::timed("ocr.table_words", || {
1418                        ocr.ocr_table_words(img, &regions, scl)
1419                    })
1420                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1421                    ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1422                    let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1423                    page.cells.extend(words.iter().cloned());
1424                    page.word_cells = words;
1425                }
1426            }
1427            // docling's OCR engines detect text lines over the whole bitmap
1428            // and every line becomes a cell, so text the layout model gave no
1429            // region — a diagram's labels, a stamp, a margin note — still
1430            // reads out as orphan text. Region-scoped recognition above stays
1431            // the source inside layout regions; the detector (#429) adds only
1432            // the lines no recognized cell already covers, and the orphan pass
1433            // below places them (those inside a kept picture or table become
1434            // that special's silent children, as upstream).
1435            if self.ocr_model()?.is_some() {
1436                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1437                // Usually computed already, alongside layout (see
1438                // `detect_alongside`); a page that reached OCR another way
1439                // detects here.
1440                // Degradation over failure: a detector that loaded but cannot
1441                // run (a damaged file, an allocation failure) costs the page
1442                // its detected lines, not its conversion — the region-scoped
1443                // pass above is complete on its own.
1444                let detected = match self.pending_det.remove(&n) {
1445                    Some(result) => result,
1446                    None => match self.det_model() {
1447                        Some(det) => timing::timed("ocr.det", || det.detect(img)),
1448                        None => Ok(Vec::new()),
1449                    },
1450                }
1451                .unwrap_or_else(|e| {
1452                    docling_core::debug_log!(
1453                        "docling-pdf: page {}: text detection failed ({e}); keeping the \
1454                         region-scoped OCR only",
1455                        n + 1
1456                    );
1457                    Vec::new()
1458                });
1459                docling_core::debug_log!(
1460                    "docling-pdf: page {}: text detector found {} line(s): {:?}",
1461                    n + 1,
1462                    detected.len(),
1463                    detected
1464                        .iter()
1465                        .map(|d| (
1466                            d.l.round(),
1467                            d.t.round(),
1468                            d.r.round(),
1469                            d.b.round(),
1470                            (d.score * 100.0).round() / 100.0
1471                        ))
1472                        .collect::<Vec<_>>()
1473                );
1474                let uncovered = ocr_det::uncovered_lines(&detected, scl, &regions, &page.cells);
1475                docling_core::debug_log!(
1476                    "docling-pdf: page {}: {} of {} detected line(s) not covered by the region pass",
1477                    n + 1,
1478                    uncovered.len(),
1479                    detected.len()
1480                );
1481                if let (false, Some(ocr)) = (uncovered.is_empty(), self.ocr_model()?) {
1482                    let scored =
1483                        timing::timed("ocr.det_lines", || ocr.ocr_page(img, &uncovered, scl))
1484                            .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1485                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1486                    det_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1487                    page.cells.extend(det_cells.iter().cloned());
1488                }
1489            }
1490        }
1491        // Region-scoped OCR skips `picture` interiors, and a digital page's
1492        // text layer cannot see into an embedded raster either — so a figure
1493        // that is really a text box (terms-and-conditions exported as an
1494        // image) lost its words on every page kind. Python docling OCRs the
1495        // bitmap-covered areas of *every* page — even digital ones — once they
1496        // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
1497        // already do. Recognize the big text-less crops here too; the panel
1498        // demotion / orphan recovery below place the lines.
1499        let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1500        {
1501            let page_area = (page.width * page.height).max(1.0);
1502            let has_text = |r: &layout::Region| {
1503                page.cells.iter().any(|c| {
1504                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1505                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1506                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1507                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
1508                })
1509            };
1510            // A captioned picture can never demote to a text panel (see
1511            // recover_text_panels), and on digital pages its speculative OCR
1512            // would be discarded anyway — don't pay for it.
1513            let captioned = |r: &layout::Region| {
1514                regions.iter().any(|c| {
1515                    c.label == "caption"
1516                        && c.r.min(r.r) - c.l.max(r.l) > 0.0
1517                        && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
1518                })
1519            };
1520            let bare: Vec<layout::Region> = regions
1521                .iter()
1522                .filter(|r| {
1523                    r.label == "picture"
1524                        && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
1525                        && !has_text(r)
1526                        && (ocred || !captioned(r))
1527                })
1528                .map(|r| layout::Region {
1529                    label: "text",
1530                    ..r.clone()
1531                })
1532                .collect();
1533            // Speculative OCR (#244): with `skip_ocr` or no model, big bare
1534            // pictures simply stay pictures.
1535            if let (false, Some(ocr)) = (bare.is_empty(), self.ocr_model()?) {
1536                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1537                let scored = timing::timed("ocr.pictures", || ocr.ocr_page(img, &bare, scl))
1538                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1539                // Speculative in-picture OCR counts toward ocr_score only on
1540                // OCR'd pages, where the recognized lines actually join the
1541                // output; on a digital page they may be discarded below.
1542                if ocred {
1543                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1544                }
1545                pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1546                page.cells.extend(pic_cells.iter().cloned());
1547            }
1548        }
1549        let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
1550        // A "picture" that is really a colored text panel — dense, wide,
1551        // multi-line — reads out as paragraphs instead of shipping as pixels;
1552        // sparse in-picture text (a chart's labels) keeps the crop and stays
1553        // inside it as the picture's silent children (docling parity, #200).
1554        // `no_text_panels` (#173) opts out entirely for image-extraction
1555        // workflows.
1556        if !self.no_text_panels {
1557            assemble::recover_text_panels(&mut regions, &page.cells);
1558        }
1559        // On an OCR'd page, in-picture text that did NOT demote its picture
1560        // mostly stays silent, exactly as in docling: its postprocess step
1561        // "Remove regular clusters that are included in wrappers" walks
1562        // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
1563        // >80 % contained in a kept picture becomes that picture's child and
1564        // never reaches the serializer. Only border-straddlers (≤80 %
1565        // containment) survive as text. Emitting *everything* here used to
1566        // splice a chart's OCR'd axis ticks into the body text right next to
1567        // the image chunk (#200) — so the orphan pass places the recognized
1568        // lines, the containment drop re-runs for the in-table ones, and
1569        // `assemble_page` nests the in-picture ones under their picture
1570        // (JSON-only children, `assemble::picture_parents`).
1571        if ocred && (!pic_cells.is_empty() || !det_cells.is_empty()) {
1572            // Pictures (and wrappers) no longer count as claimers (#165), so
1573            // the plain orphan pass places the recognized lines directly —
1574            // the detector's lines (#429) the same way.
1575            assemble::add_orphan_regions(&mut regions, &pic_cells);
1576            assemble::add_orphan_regions(&mut regions, &det_cells);
1577            assemble::drop_contained_regulars(&mut regions);
1578        } else if !ocred && !pic_cells.is_empty() {
1579            // Digital page, picture kept: its speculative OCR cells must not
1580            // linger in the text-cell set (they were appended at the tail).
1581            let kept: Vec<layout::Region> = regions
1582                .iter()
1583                .filter(|r| r.label == "picture")
1584                .cloned()
1585                .collect();
1586            let tail = page.cells.split_off(cells_before_pic_ocr);
1587            page.cells.extend(tail.into_iter().filter(|c| {
1588                !kept.iter().any(|r| {
1589                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1590                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1591                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1592                    ix * iy / ca > 0.5
1593                })
1594            }));
1595        }
1596        // A text-less *table* detected inside a picture on a digital page — a
1597        // screenshot of a table (2203's Figure 10) — has no text layer and no
1598        // scanned-path OCR to feed it, so its grid used to serialize empty and
1599        // the whole element vanished. docling OCRs bitmap-covered areas on
1600        // every page kind and its table cluster collects those cells; mirror
1601        // the scanned path for exactly these tables: recognize word crops and
1602        // feed them to the TableFormer matcher and the cell set.
1603        if !ocred {
1604            let has_text = |t: &layout::Region| {
1605                page.cells.iter().any(|c| {
1606                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1607                    let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
1608                    let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
1609                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
1610                })
1611            };
1612            let in_picture = |t: &layout::Region| {
1613                regions.iter().any(|r| {
1614                    r.label == "picture" && {
1615                        let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
1616                        let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
1617                        let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
1618                        ix * iy / ta > 0.5
1619                    }
1620                })
1621            };
1622            let pic_tables: Vec<layout::Region> = regions
1623                .iter()
1624                .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
1625                .cloned()
1626                .collect();
1627            // Same degradation as above: without OCR the in-picture table
1628            // keeps its structure (TableFormer is geometry-driven) minus text.
1629            if let (false, Some(ocr)) = (pic_tables.is_empty(), self.ocr_model()?) {
1630                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1631                let words = timing::timed("ocr.table_words", || {
1632                    ocr.ocr_table_words(img, &pic_tables, scl)
1633                })
1634                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1635                ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1636                let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1637                page.cells.extend(words.iter().cloned());
1638                page.word_cells.extend(words);
1639            }
1640        }
1641        // The cells are final: fit every regular region to the cells it
1642        // claims and fold the orphans it now surrounds (#419), before
1643        // TableFormer and the reading order see the boxes.
1644        assemble::fit_regions_to_cells(&mut regions, &page.cells);
1645        Ok(Prepared {
1646            regions,
1647            ocr_confs,
1648            parse,
1649        })
1650    }
1651
1652    /// The stages after TableFormer: enrichment, the page confidence report and
1653    /// assembly into typed nodes.
1654    fn complete_page(
1655        &mut self,
1656        n: usize,
1657        page: &mut PdfPage,
1658        prepared: Prepared,
1659        table_rows: Vec<Option<tf_core::TableGrid>>,
1660    ) -> Result<PageOut, PdfError> {
1661        let Prepared {
1662            regions,
1663            ocr_confs,
1664            parse,
1665        } = prepared;
1666        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1667            for (i, r) in regions.iter().enumerate() {
1668                eprintln!(
1669                    "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
1670                    r.label,
1671                    r.score,
1672                    r.l,
1673                    r.t,
1674                    r.r,
1675                    r.b,
1676                    table_rows[i]
1677                        .as_ref()
1678                        .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
1679                );
1680            }
1681            eprintln!(
1682                "DBG cells={} words={}",
1683                page.cells.len(),
1684                page.word_cells.len()
1685            );
1686        }
1687        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
1688        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
1689        // shape as TableFormer — one lazily-loaded instance per pipeline, only
1690        // ever locked when a page actually has a matching region.
1691        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
1692        if let Some(slot) = self.classifier.as_ref() {
1693            if regions.iter().any(|r| r.label == "picture") {
1694                timing::timed("picture_classifier", || {
1695                    let mut guard = slot.lock().unwrap();
1696                    if matches!(*guard, EnrichSlot::Unloaded) {
1697                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
1698                            Some(m) => EnrichSlot::Ready(m),
1699                            None => EnrichSlot::Missing,
1700                        };
1701                    }
1702                    if let EnrichSlot::Ready(model) = &mut *guard {
1703                        for (i, r) in regions.iter().enumerate() {
1704                            if r.label != "picture" {
1705                                continue;
1706                            }
1707                            let Some(crop) = assemble::crop_region_scaled(
1708                                page,
1709                                [r.l, r.t, r.r, r.b],
1710                                enrich::CLASSIFIER_SCALE,
1711                            ) else {
1712                                continue;
1713                            };
1714                            match model.classify(&crop) {
1715                                Ok(classes) => {
1716                                    enrich_out[i] =
1717                                        Some(assemble::Enrichment::PictureClasses(classes));
1718                                }
1719                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1720                            }
1721                        }
1722                    }
1723                });
1724            }
1725        }
1726        if let Some(slot) = self.code_formula.as_ref() {
1727            let wants = |label: &str| {
1728                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
1729            };
1730            if regions.iter().any(|r| wants(r.label)) {
1731                timing::timed("code_formula", || {
1732                    let mut guard = slot.lock().unwrap();
1733                    if matches!(*guard, EnrichSlot::Unloaded) {
1734                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
1735                            Some(m) => EnrichSlot::Ready(m),
1736                            None => EnrichSlot::Missing,
1737                        };
1738                    }
1739                    if let EnrichSlot::Ready(model) = &mut *guard {
1740                        for (i, r) in regions.iter().enumerate() {
1741                            if !wants(r.label) {
1742                                continue;
1743                            }
1744                            // docling crops the postprocessed cluster box — the
1745                            // union of the region's text cells, not the raw
1746                            // detector box — expanded by 18% per side, at
1747                            // ~120 dpi.
1748                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
1749                                .unwrap_or([r.l, r.t, r.r, r.b]);
1750                            let (w, h) = (br - bl, bb - bt);
1751                            let ex = enrich::CODE_FORMULA_EXPANSION;
1752                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
1753                            let Some(crop) = assemble::crop_region_scaled(
1754                                page,
1755                                bbox,
1756                                enrich::CODE_FORMULA_SCALE,
1757                            ) else {
1758                                continue;
1759                            };
1760                            let kind = if r.label == "code" {
1761                                enrich::CodeFormulaKind::Code
1762                            } else {
1763                                enrich::CodeFormulaKind::Formula
1764                            };
1765                            match model.predict(&crop, kind) {
1766                                Ok(text) => {
1767                                    enrich_out[i] = Some(match kind {
1768                                        enrich::CodeFormulaKind::Code => {
1769                                            let (code, language) =
1770                                                enrich::extract_code_language(&text);
1771                                            assemble::Enrichment::Code {
1772                                                language,
1773                                                text: code,
1774                                            }
1775                                        }
1776                                        enrich::CodeFormulaKind::Formula => {
1777                                            assemble::Enrichment::Formula { latex: text }
1778                                        }
1779                                    });
1780                                }
1781                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1782                            }
1783                        }
1784                    }
1785                });
1786            }
1787        }
1788        // Score the final region set (docling assigns layout_score over the
1789        // postprocessed clusters — the page elements assemble_page emits,
1790        // which leave out the regulars nested in a picture as its children).
1791        let parents = assemble::picture_parents(&regions);
1792        let elements: Vec<layout::Region> = regions
1793            .iter()
1794            .zip(&parents)
1795            .filter(|(_, p)| p.is_none())
1796            .map(|(r, _)| r.clone())
1797            .collect();
1798        let conf = quality::page_confidence(parse, &elements, &ocr_confs);
1799        let (nodes, links) = timing::timed("assemble_page", || {
1800            assemble::assemble_page(page, regions, &table_rows, &enrich_out)
1801        });
1802        Ok((nodes, links, conf))
1803    }
1804}
1805
1806#[cfg(feature = "ml")]
1807/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
1808/// so on a typical machine two threads per worker (sharing one in-cache copy of
1809/// the weights) extracts more throughput than one fat model or many single-thread
1810/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
1811fn pdf_intra() -> usize {
1812    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
1813        return n;
1814    }
1815    if intra_threads() >= 2 {
1816        2
1817    } else {
1818        1
1819    }
1820}
1821
1822#[cfg(feature = "ml")]
1823/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
1824/// overrides; otherwise size the pool so `workers × intra ≈ cores`.
1825///
1826/// The pool scales with the machine (#324 follow-up testing): the old hard cap
1827/// of 4 left most of a many-core box idle — on a 16-core M4 Max, 10 workers
1828/// measured ~1.2× over the capped pool (10.0 → 8.5 s on a 130-page document,
1829/// byte-identical output). The ceiling of 16 is a memory bound, not a
1830/// performance one: each worker holds its own layout/OCR sessions (~0.4 GB),
1831/// so a worst-case pool stays under ~6.5 GB even on a ≥32-core host — and
1832/// docling-serve's per-request pools sit behind its `DOCLING_RS_MAX_MEMORY_MB`
1833/// admission control besides. Machines with 4 or fewer effective threads keep
1834/// the exact old sizing (`threads / intra`, min 1).
1835fn pdf_worker_count() -> usize {
1836    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
1837        return n;
1838    }
1839    (intra_threads() / pdf_intra()).clamp(1, 16)
1840}
1841
1842#[cfg(feature = "ml")]
1843/// Max pages a worker layout-detects with one batched inference call (issue
1844/// #73). Workers drain the work channel opportunistically up to this size —
1845/// whatever is already rendered gets batched, so batching never *waits* for
1846/// pages and adds no latency when rendering is the bottleneck.
1847///
1848/// Default: per-page (1) on the CPU provider, 4 when a GPU provider is
1849/// selected (#338). The old "4 on 8+ cores" CPU default was a hypothesis —
1850/// that single-session amortization pays off with a wider thread budget —
1851/// and every actual CPU measurement lands the other way: a 4-core x86 box
1852/// runs the 9-page 2206.01062 fixture in 8.5 s/conv at batch=1 vs 9.3 s at
1853/// batch=4 (re-measured for #338; the original 8.1 vs 9.3 agrees), and the
1854/// issue-#338 report measured batch=1 ~2× faster on a 16-core M4 Max at
1855/// every worker count — batching only adds cache pressure once workers
1856/// saturate the cores. On a GPU the per-call dispatch overhead is real and
1857/// batching amortizes it, so the GPU default stays. Output is bit-identical
1858/// at every batch size, so this is purely a throughput knob.
1859/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides either way; `1` = per-page.
1860pub(crate) fn pdf_layout_batch() -> usize {
1861    env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
1862        .filter(|&n| n > 0)
1863        .unwrap_or_else(|| if docling_onnx::prefers_fp32() { 4 } else { 1 })
1864}
1865
1866#[cfg(feature = "ml")]
1867/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
1868/// the serial primary (running its model on every core) is faster than fanning out
1869/// — the helper pool's one-time model-load cost only pays off once enough pages
1870/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
1871fn pdf_parallel_min() -> usize {
1872    env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
1873        .filter(|&n| n > 0)
1874        .unwrap_or(6)
1875}
1876
1877#[cfg(feature = "ml")]
1878/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
1879/// so a single-page / small / image / METS input is converted at full intra-op
1880/// speed with no pool to load. A document with enough pages instead fans out
1881/// across a **pool** of narrower workers processed concurrently. Both load lazily
1882/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
1883pub struct Pipeline {
1884    /// Full-intra worker for the serial path; loaded on first serial use.
1885    primary: Option<Worker>,
1886    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
1887    /// path; loaded on first multi-page use and cached.
1888    pool: Vec<Worker>,
1889    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
1890    tables: SharedTables,
1891    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
1892    classifier: SharedClassifier,
1893    code_formula: SharedCodeFormula,
1894    /// Desired pool size for multi-page documents.
1895    target_workers: usize,
1896    /// Page count at/above which the parallel pool is worth its load cost.
1897    parallel_min: usize,
1898    /// Skip loading/running TableFormer; table regions fall back to geometric
1899    /// reconstruction. See [`Pipeline::no_table_former`].
1900    no_table_former: bool,
1901    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
1902    no_ocr: bool,
1903    /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
1904    skip_ocr: bool,
1905    /// OCR every page even when it carries a text layer. See
1906    /// [`Pipeline::force_full_page_ocr`].
1907    force_full_page_ocr: bool,
1908    /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
1909    no_text_panels: bool,
1910    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
1911    enrich: EnrichmentOptions,
1912    /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
1913    page_range: Option<(usize, usize)>,
1914    /// OCR recognition language. See [`Pipeline::ocr_lang`].
1915    ocr_lang: ocr::OcrLang,
1916    /// Which OCR engine runs (#460). See [`Pipeline::ocr_engine`].
1917    ocr_engine: ocr::OcrEngine,
1918    /// Tesseract's languages (#460). See [`Pipeline::tesseract_lang`].
1919    tesseract_lang: Option<String>,
1920    /// Which regions feed the OCR (#254). See [`Pipeline::ocr_mode`].
1921    ocr_mode: ocr::OcrMode,
1922    /// OCR render scale override in px/pt (#254). See [`Pipeline::ocr_scale`].
1923    ocr_scale: Option<f32>,
1924    /// Heading-level inference (#302). See [`Pipeline::heading_hierarchy`].
1925    heading_hierarchy: HeadingHierarchyOptions,
1926    /// Optional per-page progress hook `(done, selected_total)`, invoked after
1927    /// each page finishes on both the serial and parallel buffered paths. Set
1928    /// by the CLI batch mode for dot-progress; `None` costs nothing.
1929    progress: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>,
1930}
1931
1932#[cfg(feature = "ml")]
1933impl Pipeline {
1934    /// Construct the pipeline. Models load lazily on first use (full-intra primary
1935    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
1936    /// loaded that a given document doesn't need.
1937    pub fn new() -> Result<Self, PdfError> {
1938        Ok(Self {
1939            primary: None,
1940            pool: Vec::new(),
1941            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
1942            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1943            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1944            target_workers: pdf_worker_count(),
1945            parallel_min: pdf_parallel_min(),
1946            no_table_former: false,
1947            no_ocr: false,
1948            skip_ocr: false,
1949            force_full_page_ocr: false,
1950            no_text_panels: false,
1951            enrich: EnrichmentOptions::default(),
1952            page_range: None,
1953            ocr_lang: ocr::OcrLang::from_env(),
1954            ocr_engine: ocr::OcrEngine::from_env(),
1955            tesseract_lang: None,
1956            ocr_mode: ocr::OcrMode::from_env(),
1957            ocr_scale: ocr::scale_from_env(),
1958            heading_hierarchy: HeadingHierarchyOptions::default(),
1959            progress: None,
1960        })
1961    }
1962
1963    /// Infer section-header levels after assembly (#302, docling's
1964    /// `HeadingHierarchyModel`): PDF bookmarks > legal/outline numbering >
1965    /// font style, off by default — see [`HeadingHierarchyOptions`]. Pure
1966    /// post-processing configuration; for a warm pipeline use
1967    /// [`set_heading_hierarchy`](Self::set_heading_hierarchy).
1968    pub fn heading_hierarchy(mut self, opts: HeadingHierarchyOptions) -> Self {
1969        self.heading_hierarchy = opts;
1970        self
1971    }
1972
1973    /// In-place variant of [`heading_hierarchy`](Self::heading_hierarchy) for
1974    /// a long-lived pipeline (docling-serve's warm instance) — like
1975    /// [`set_pages`](Self::set_pages), set it before every conversion so no
1976    /// request inherits a previous one's choice.
1977    pub fn set_heading_hierarchy(&mut self, opts: HeadingHierarchyOptions) {
1978        self.heading_hierarchy = opts;
1979    }
1980
1981    /// Run the enabled heading-hierarchy stage (#302) on an assembled
1982    /// document: gather the outline (bookmarks) and the per-page glyph styles
1983    /// on demand, then assign levels in place. `bytes` is `None` on paths
1984    /// with no PDF behind them (standalone images, METS) — those degrade to
1985    /// the numbering signal, exactly like docling without parsed pages.
1986    fn apply_heading_hierarchy(&self, nodes: &mut [Node], bytes: Option<&[u8]>) {
1987        let opts = &self.heading_hierarchy;
1988        if !opts.enabled {
1989            return;
1990        }
1991        let outline = match bytes {
1992            Some(bytes) if opts.use_bookmarks => outline::extract_outline(bytes),
1993            _ => Vec::new(),
1994        };
1995        let styles = match bytes {
1996            Some(bytes) if opts.use_style => {
1997                let pages = heading_hierarchy::heading_pages(nodes);
1998                textparse::glyph_styles(bytes, &pages)
1999            }
2000            _ => Default::default(),
2001        };
2002        heading_hierarchy::apply(nodes, &outline, &styles, opts);
2003    }
2004
2005    /// Install (or clear) the per-page progress hook: called with
2006    /// `(pages_done, pages_selected)` after each page completes during
2007    /// [`convert`](Self::convert). Shared with the parallel workers, so the
2008    /// callback must be cheap and thread-safe.
2009    pub fn set_progress(&mut self, cb: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>) {
2010        self.progress = cb;
2011    }
2012
2013    /// Convert only pages `first..=last` (**1-based**, like the page numbers a
2014    /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
2015    /// skipped before rasterization, so the cost is proportional to the window,
2016    /// not the document. `last` past the end of the document clamps; a window
2017    /// that selects no pages at all (`first` beyond the last page) is an error
2018    /// at convert time. `None` (the default) converts everything.
2019    pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
2020        self.page_range = range;
2021        self
2022    }
2023
2024    /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
2025    /// (e.g. docling-serve's warm instance) that applies a per-request window
2026    /// without rebuilding — unlike the model switches, the window is pure
2027    /// configuration. Set it before every conversion; it stays until changed.
2028    pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
2029        self.page_range = range;
2030    }
2031
2032    /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
2033    /// for the multilingual docling-conformance model. `None` keeps the
2034    /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
2035    /// first conversion; for a warm pipeline use
2036    /// [`set_ocr_lang`](Self::set_ocr_lang).
2037    pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
2038        self.set_ocr_lang(lang);
2039        self
2040    }
2041
2042    /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
2043    /// pipeline (docling-serve's warm instance). Unlike the page window this
2044    /// is a *model* switch: any worker whose cached recognition model was
2045    /// loaded for a different language drops it, to be lazily reloaded on the
2046    /// next OCR-needing page (cheap — the rec models are ~10 MB).
2047    pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
2048        let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
2049        self.ocr_lang = lang;
2050        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2051            if worker.ocr_lang != lang {
2052                worker.ocr_lang = lang;
2053                worker.ocr = OcrSlot::Unloaded;
2054            }
2055        }
2056    }
2057
2058    /// Which OCR engine recognizes text (#460, see [`OcrEngine`]): the
2059    /// built-in PP-OCRv3 recognizer by default, or the system `tesseract`
2060    /// binary (docling's `TesseractCliOcrOptions`) — same layout-region
2061    /// crops, same cells; Tesseract does its own line/word segmentation and
2062    /// reads orientation from its OSD. `None` keeps the process default
2063    /// (`DOCLING_RS_OCR_ENGINE`, else PP-OCR). Set before the first
2064    /// conversion; for a warm pipeline use
2065    /// [`set_ocr_engine`](Self::set_ocr_engine).
2066    pub fn ocr_engine(mut self, engine: Option<ocr::OcrEngine>) -> Self {
2067        self.set_ocr_engine(engine);
2068        self
2069    }
2070
2071    /// In-place variant of [`ocr_engine`](Self::ocr_engine): a model switch
2072    /// like [`set_ocr_lang`](Self::set_ocr_lang) — workers holding the other
2073    /// engine drop it, to be lazily reloaded.
2074    pub fn set_ocr_engine(&mut self, engine: Option<ocr::OcrEngine>) {
2075        let engine = engine.unwrap_or_else(ocr::OcrEngine::from_env);
2076        self.ocr_engine = engine;
2077        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2078            if worker.ocr_engine != engine {
2079                worker.ocr_engine = engine;
2080                worker.ocr = OcrSlot::Unloaded;
2081            }
2082        }
2083    }
2084
2085    /// Tesseract's languages (#460): the `-l` argument, tessdata stems joined
2086    /// with `+` — build it from an `ocr_lang` value with
2087    /// [`tesseract_lang_arg`], which also maps BCP-47 tags and the PP-OCR
2088    /// codes. `None` runs Tesseract's default (`eng`). Ignored under the
2089    /// PP-OCR engine, whose language is [`ocr_lang`](Self::ocr_lang). For a
2090    /// warm pipeline use [`set_tesseract_lang`](Self::set_tesseract_lang).
2091    pub fn tesseract_lang(mut self, lang: Option<String>) -> Self {
2092        self.set_tesseract_lang(lang);
2093        self
2094    }
2095
2096    /// In-place variant of [`tesseract_lang`](Self::tesseract_lang): a model
2097    /// switch like [`set_ocr_lang`](Self::set_ocr_lang) — a worker whose
2098    /// Tesseract was probed for other languages drops it.
2099    pub fn set_tesseract_lang(&mut self, lang: Option<String>) {
2100        self.tesseract_lang = lang.clone();
2101        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2102            if worker.tesseract_lang != lang {
2103                worker.tesseract_lang = lang.clone();
2104                if worker.ocr_engine == ocr::OcrEngine::Tesseract {
2105                    worker.ocr = OcrSlot::Unloaded;
2106                }
2107            }
2108        }
2109    }
2110
2111    /// Resolve the configured 1-based window against a page count into the
2112    /// 0-based inclusive form the backend walks, validating it selects at
2113    /// least one existing page.
2114    fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
2115        let Some((first, last)) = self.page_range else {
2116            return Ok(None);
2117        };
2118        if first == 0 || last < first {
2119            return Err(PdfError::Pdfium(format!(
2120                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
2121            )));
2122        }
2123        if first > total {
2124            return Err(PdfError::Pdfium(format!(
2125                "page range {first}-{last} is outside the document ({total} page(s))"
2126            )));
2127        }
2128        Ok(Some((first - 1, last.min(total) - 1)))
2129    }
2130
2131    /// Enable the opt-in enrichment passes (docling's
2132    /// `do_picture_classification` / `do_code_enrichment` /
2133    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
2134    /// the first matching region; a missing model warns once and is skipped.
2135    /// Set before the first conversion (no effect on already-loaded workers).
2136    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
2137        self.enrich = opts;
2138        self
2139    }
2140
2141    /// Skip loading and running the TableFormer table-structure model. Table
2142    /// regions still get emitted, but reconstructed geometrically from cell
2143    /// positions instead of via the ONNX model's predicted structure — faster
2144    /// (no model load, no per-table inference) at the cost of table fidelity.
2145    /// No effect if a worker is already loaded; set this before the first
2146    /// conversion.
2147    pub fn no_table_former(mut self, disable: bool) -> Self {
2148        self.no_table_former = disable;
2149        self
2150    }
2151
2152    /// Keep every detected `picture` region as a picture. By default an
2153    /// *uncaptioned* picture that reads like a dense, uniform text panel (a
2154    /// terms-and-conditions box exported as an image) is demoted into
2155    /// paragraphs (#157); a chart the layout mislabels can still trip that
2156    /// heuristic on scanned pages, and image-extraction workflows may simply
2157    /// want every crop — this flag disables the demotion entirely (#173).
2158    /// No effect on already-loaded workers; set before the first conversion.
2159    pub fn no_text_panels(mut self, disable: bool) -> Self {
2160        self.no_text_panels = disable;
2161        self
2162    }
2163
2164    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
2165    /// inference of any kind. The PDF's embedded text cells are grouped by line
2166    /// and emitted as plain paragraphs in reading order: no headings, lists,
2167    /// tables, code blocks, or pictures, since that structure comes from the
2168    /// layout model. The fastest possible PDF path, but pages with no embedded
2169    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
2170    /// without this flag. Implies `no_table_former`. No effect if a worker is
2171    /// already loaded; set this before the first conversion.
2172    pub fn no_ocr(mut self, disable: bool) -> Self {
2173        self.no_ocr = disable;
2174        self
2175    }
2176
2177    /// Never run OCR, but keep layout detection and TableFormer — docling's
2178    /// independent `do_ocr=False` (#244), the counterpart of
2179    /// [`no_table_former`](Self::no_table_former). Unlike
2180    /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
2181    /// output — headings, tables, pictures, reading order — is preserved;
2182    /// only text that exists solely as pixels is lost: scanned pages come
2183    /// back with their regions empty, and the speculative OCR of large
2184    /// embedded images never runs. The OCR model is never loaded. Ignored
2185    /// when `no_ocr` is set (there is no OCR to skip);
2186    /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
2187    /// mirroring docling where forcing is a sub-option of `do_ocr`.
2188    pub fn skip_ocr(mut self, disable: bool) -> Self {
2189        self.skip_ocr = disable;
2190        self
2191    }
2192
2193    /// OCR every page from its rendered image even when the page carries an
2194    /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
2195    /// for text layers that exist but lie: broken encodings, subset fonts with
2196    /// garbage mappings, a scanned form with a few typed-in fields. Ignored
2197    /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
2198    /// `force_full_page_ocr` is a sub-option of `do_ocr`).
2199    pub fn force_full_page_ocr(mut self, force: bool) -> Self {
2200        self.force_full_page_ocr = force;
2201        self
2202    }
2203
2204    /// Which document regions feed the OCR — docling's `OcrMode` (#254). The
2205    /// default (`default` = `pdf_aware_layout_regions`) is the standard
2206    /// text-layer-aware behavior; `full_page`/`layout_regions` discard the
2207    /// text layer like [`force_full_page_ocr`](Self::force_full_page_ocr)
2208    /// (see [`ocr::OcrMode`] for why both map onto it). Whichever of the flag
2209    /// and the mode demands forcing wins, mirroring docling's
2210    /// `force_full_page_ocr` → `mode=full_page` bridge. `None` keeps the
2211    /// process default (`DOCLING_RS_OCR_MODE`, else `default`).
2212    pub fn ocr_mode(mut self, mode: Option<ocr::OcrMode>) -> Self {
2213        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
2214        self
2215    }
2216
2217    /// In-place variants of [`force_full_page_ocr`](Self::force_full_page_ocr),
2218    /// [`ocr_mode`](Self::ocr_mode) and [`ocr_scale`](Self::ocr_scale) for a
2219    /// long-lived pipeline (docling-serve's warm instance): all three are pure
2220    /// per-worker configuration — no model reloads — so they apply per request
2221    /// like [`set_pages`](Self::set_pages). Set them before every conversion so
2222    /// no request inherits a previous one's choice.
2223    pub fn set_force_full_page_ocr(&mut self, force: bool) {
2224        self.force_full_page_ocr = force;
2225        self.sync_ocr_config();
2226    }
2227
2228    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
2229    pub fn set_ocr_mode(&mut self, mode: Option<ocr::OcrMode>) {
2230        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
2231        self.sync_ocr_config();
2232    }
2233
2234    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
2235    pub fn set_ocr_scale(&mut self, scale: Option<f32>) {
2236        self.ocr_scale = scale
2237            .filter(|s| s.is_finite() && *s > 0.0)
2238            .or_else(ocr::scale_from_env);
2239        self.sync_ocr_config();
2240    }
2241
2242    /// Whether page extraction should decode the text layer at all. Forced
2243    /// full-page OCR (the flag or `ocr_mode=full_page|layout_regions`) clears
2244    /// every extracted cell unread, so the decode is skipped outright —
2245    /// docling#4061's `skip_cell_extraction` (2.122). `no_ocr` wins over the
2246    /// forcing, as everywhere else: its fast path *is* the text layer.
2247    fn extract_text_layer(&self) -> bool {
2248        self.no_ocr || !(self.force_full_page_ocr || self.ocr_mode.forces_full_page())
2249    }
2250
2251    /// Push the current OCR forcing/scale choice onto already-loaded workers
2252    /// (new workers read it at [`Worker::load`]).
2253    fn sync_ocr_config(&mut self) {
2254        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2255        let scale = self.ocr_scale;
2256        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2257            worker.force_full_page_ocr = force;
2258            worker.ocr_scale = scale;
2259        }
2260    }
2261
2262    /// OCR render scale in pixels per PDF point — docling's `OcrOptions.scale`
2263    /// (#254, upstream docling#3877; their default 3 = 216 dpi). `None`
2264    /// (default: `DOCLING_RS_OCR_SCALE`, else unset) feeds the recognizer the
2265    /// pipeline's own page render (2.0 px/pt = 144 dpi); a different value
2266    /// resamples that render for the OCR input only — layout and TableFormer
2267    /// keep their pinned-resolution pixels, so the conformance baseline never
2268    /// moves. Lower it when the source raster is already high-resolution and
2269    /// upscaling degrades recognition; raise it toward docling's 216 dpi for
2270    /// parity experiments. Non-positive values are ignored.
2271    pub fn ocr_scale(mut self, scale: Option<f32>) -> Self {
2272        self.ocr_scale = scale
2273            .filter(|s| s.is_finite() && *s > 0.0)
2274            .or_else(ocr::scale_from_env);
2275        self
2276    }
2277
2278    /// The shared TableFormer slot handed to each worker, or `None` when the
2279    /// pipeline options skip TableFormer entirely.
2280    fn tables_slot(&self) -> Option<SharedTables> {
2281        if self.no_table_former || self.no_ocr {
2282            None
2283        } else {
2284            Some(Arc::clone(&self.tables))
2285        }
2286    }
2287
2288    /// The shared enrichment slots for a worker (`None` per model unless its
2289    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
2290    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
2291        if self.no_ocr || !self.enrich.any() {
2292            return (None, None);
2293        }
2294        (
2295            self.enrich
2296                .picture_classification
2297                .then(|| Arc::clone(&self.classifier)),
2298            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
2299        )
2300    }
2301
2302    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
2303    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
2304    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
2305    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
2306    /// `DocumentConverter.initialize_pipeline`.
2307    pub fn warm_up(&mut self) -> Result<(), PdfError> {
2308        self.primary()?;
2309        Ok(())
2310    }
2311
2312    /// The full-intra serial worker, loaded on first use.
2313    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
2314        if self.primary.is_none() {
2315            self.primary = Some(Worker::load(
2316                intra_threads(),
2317                self.tables_slot(),
2318                self.enrich_slots(),
2319                self.enrich,
2320                self.no_ocr,
2321                self.skip_ocr,
2322                // The mode-shaped spelling (#254) and the flag are one engine
2323                // truth: whichever demands forcing wins, mirroring docling's
2324                // `force_full_page_ocr` → `mode=full_page` bridge.
2325                self.force_full_page_ocr || self.ocr_mode.forces_full_page(),
2326                self.no_text_panels,
2327                self.ocr_lang,
2328                self.ocr_engine,
2329                self.tesseract_lang.clone(),
2330                self.ocr_scale,
2331            )?);
2332        }
2333        Ok(self.primary.as_mut().unwrap())
2334    }
2335
2336    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
2337    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
2338    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
2339    /// fans the pages out across the worker pool, reassembled in page order so the
2340    /// output is byte-identical to the serial path.
2341    pub fn convert(
2342        &mut self,
2343        bytes: &[u8],
2344        password: Option<&str>,
2345        name: &str,
2346    ) -> Result<DoclingDocument, PdfError> {
2347        let pages = pdfium_backend::page_count(bytes, password)?;
2348        let range = self.resolve_range(pages)?;
2349        // Serial vs parallel is decided by the pages actually converted: a
2350        // 3-page window over a 500-page PDF should not pay the pool load.
2351        let selected = range.map_or(pages, |(a, b)| b - a + 1);
2352        let doc = if self.target_workers >= 2 && selected >= self.parallel_min {
2353            self.convert_parallel(bytes, password, name, range, selected)?
2354        } else {
2355            self.convert_serial(bytes, password, name, range, selected)?
2356        };
2357        timing::report();
2358        Ok(doc)
2359    }
2360
2361    /// Stream pages one at a time through the primary worker — render → process →
2362    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
2363    fn convert_serial(
2364        &mut self,
2365        bytes: &[u8],
2366        password: Option<&str>,
2367        name: &str,
2368        range: Option<(usize, usize)>,
2369        selected: usize,
2370    ) -> Result<DoclingDocument, PdfError> {
2371        let mut doc = DoclingDocument::new(name);
2372        let mut confs = std::collections::BTreeMap::new();
2373        let render_image = !self.no_ocr;
2374        let extract_text = self.extract_text_layer();
2375        let progress = self.progress.clone();
2376        let mut done = 0usize;
2377        let worker = self.primary()?;
2378        pdfium_backend::for_each_page(
2379            bytes,
2380            password,
2381            render_image,
2382            extract_text,
2383            range,
2384            |n, _total, mut page| {
2385                let (mut nodes, links, conf) = worker.process(n, &mut page)?;
2386                assemble::stamp_page_no(&mut nodes, n + 1);
2387                doc.nodes.extend(nodes);
2388                doc.links.extend(links);
2389                confs.insert(n + 1, conf);
2390                if let Some(cb) = &progress {
2391                    done += 1;
2392                    cb(done, selected);
2393                }
2394                Ok::<(), PdfError>(())
2395            },
2396        )?;
2397        assemble::merge_continuations(&mut doc.nodes);
2398        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
2399        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2400        Ok(doc)
2401    }
2402
2403    /// Render pages serially on this thread (pdfium) and process them in parallel
2404    /// across the worker pool. A bounded channel applies backpressure so only a
2405    /// handful of page bitmaps are resident at once; results carry their page
2406    /// index and are reassembled in order, so the output is byte-identical to the
2407    /// serial path.
2408    fn convert_parallel(
2409        &mut self,
2410        bytes: &[u8],
2411        password: Option<&str>,
2412        name: &str,
2413        range: Option<(usize, usize)>,
2414        selected: usize,
2415    ) -> Result<DoclingDocument, PdfError> {
2416        self.ensure_pool()?;
2417        let progress = self.progress.clone();
2418        let pages_done = std::sync::atomic::AtomicUsize::new(0);
2419        let n_workers = self.pool.len();
2420        let render_image = !self.no_ocr;
2421        let extract_text = self.extract_text_layer();
2422        let layout_batch = pdf_layout_batch();
2423        // Bound sized so every worker can accumulate a full layout batch while
2424        // rendering stays ahead (and never below the pre-#73 render-ahead of
2425        // two pages per worker); still a hard cap on resident page bitmaps.
2426        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2427        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2428        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
2429        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
2430
2431        // Move the pool into the scope so each worker gets an exclusive `&mut`.
2432        let mut workers = std::mem::take(&mut self.pool);
2433        std::thread::scope(|s| {
2434            for worker in workers.iter_mut() {
2435                let work_rx = Arc::clone(&work_rx);
2436                let results = Arc::clone(&results);
2437                let first_err = Arc::clone(&first_err);
2438                let progress = progress.clone();
2439                let pages_done = &pages_done;
2440                s.spawn(move || {
2441                    worker.run_pool(&work_rx, layout_batch, |idx, out| {
2442                        match out {
2443                            Ok(out) => {
2444                                results.lock().unwrap().push((idx, out));
2445                                if let Some(cb) = &progress {
2446                                    let d = pages_done
2447                                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2448                                        + 1;
2449                                    cb(d, selected);
2450                                }
2451                            }
2452                            Err(e) => {
2453                                let mut slot = first_err.lock().unwrap();
2454                                if slot.is_none() {
2455                                    *slot = Some(e);
2456                                }
2457                            }
2458                        }
2459                        true
2460                    });
2461                });
2462            }
2463            // Render on this thread and feed the workers; backpressure blocks here
2464            // when the channel is full. Dropping `work_tx` afterwards signals the
2465            // workers (recv → Err) to finish.
2466            let render = pdfium_backend::for_each_page(
2467                bytes,
2468                password,
2469                render_image,
2470                extract_text,
2471                range,
2472                |i, _total, page| {
2473                    work_tx
2474                        .send((i, page))
2475                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2476                },
2477            );
2478            drop(work_tx);
2479            if let Err(e) = render {
2480                let mut slot = first_err.lock().unwrap();
2481                if slot.is_none() {
2482                    *slot = Some(e);
2483                }
2484            }
2485        });
2486        // Threads have joined; restore the pool for the next conversion.
2487        self.pool = workers;
2488
2489        if let Some(e) = first_err.lock().unwrap().take() {
2490            return Err(e);
2491        }
2492        let mut results = Arc::try_unwrap(results)
2493            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
2494            .into_inner()
2495            .unwrap();
2496        results.sort_by_key(|(idx, _)| *idx);
2497        let mut doc = DoclingDocument::new(name);
2498        let mut confs = std::collections::BTreeMap::new();
2499        for (idx, (mut nodes, links, conf)) in results {
2500            assemble::stamp_page_no(&mut nodes, idx + 1);
2501            doc.nodes.extend(nodes);
2502            doc.links.extend(links);
2503            confs.insert(idx + 1, conf);
2504        }
2505        assemble::merge_continuations(&mut doc.nodes);
2506        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
2507        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2508        Ok(doc)
2509    }
2510
2511    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
2512    /// in-document-order batch of nodes (and that span's recovered links) as pages
2513    /// complete, so a caller can serialize Markdown page by page instead of waiting
2514    /// for the whole document. The batches are exactly the buffered [`convert`]'s
2515    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
2516    /// parallel path reorders pages back into document order before emitting, so
2517    /// the output is identical regardless of worker scheduling.
2518    ///
2519    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
2520    /// and its backpressure throttles the whole pipeline. Returning `Err` from
2521    /// `emit` aborts the conversion with that error.
2522    pub fn convert_streaming<F>(
2523        &mut self,
2524        bytes: &[u8],
2525        password: Option<&str>,
2526        name: &str,
2527        emit: F,
2528    ) -> Result<(), PdfError>
2529    where
2530        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2531    {
2532        let _ = name; // page nodes carry no name; the caller owns the document name.
2533        let pages = pdfium_backend::page_count(bytes, password)?;
2534        let range = self.resolve_range(pages)?;
2535        let selected = range.map_or(pages, |(a, b)| b - a + 1);
2536        let r = if self.target_workers >= 2 && selected >= self.parallel_min {
2537            self.convert_streaming_parallel(bytes, password, range, emit)
2538        } else {
2539            self.convert_streaming_serial(bytes, password, range, emit)
2540        };
2541        timing::report();
2542        r
2543    }
2544
2545    /// Serial streaming: render → process → emit, one page at a time, holding back
2546    /// only the tail that might still merge into the next page.
2547    fn convert_streaming_serial<F>(
2548        &mut self,
2549        bytes: &[u8],
2550        password: Option<&str>,
2551        range: Option<(usize, usize)>,
2552        mut emit: F,
2553    ) -> Result<(), PdfError>
2554    where
2555        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2556    {
2557        let mut asm = assemble::StreamAssembler::new();
2558        let render_image = !self.no_ocr;
2559        let extract_text = self.extract_text_layer();
2560        let worker = self.primary()?;
2561        pdfium_backend::for_each_page(
2562            bytes,
2563            password,
2564            render_image,
2565            extract_text,
2566            range,
2567            |n, _total, mut page| {
2568                // Confidence is dropped on the streaming path: the report is
2569                // only complete once every page has run, which defeats
2570                // page-by-page emission — buffered `convert` carries it.
2571                let (nodes, links, _conf) = worker.process(n, &mut page)?;
2572                emit(asm.push(nodes), links)
2573            },
2574        )?;
2575        emit(asm.finish(), Vec::new())
2576    }
2577
2578    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
2579    /// not thread-safe) and process across the worker pool; results carry their
2580    /// page index and are reordered on the calling thread into a
2581    /// [`assemble::StreamAssembler`], which emits each page in document order as
2582    /// soon as its predecessors have arrived. Bounded channels keep only a handful
2583    /// of pages resident and let `emit`'s backpressure reach the renderer.
2584    fn convert_streaming_parallel<F>(
2585        &mut self,
2586        bytes: &[u8],
2587        password: Option<&str>,
2588        range: Option<(usize, usize)>,
2589        mut emit: F,
2590    ) -> Result<(), PdfError>
2591    where
2592        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2593    {
2594        self.ensure_pool()?;
2595        let n_workers = self.pool.len();
2596        let render_image = !self.no_ocr;
2597        let extract_text = self.extract_text_layer();
2598        let layout_batch = pdf_layout_batch();
2599        // Bound sized so every worker can accumulate a full layout batch while
2600        // rendering stays ahead (and never below the pre-#73 render-ahead of
2601        // two pages per worker); still a hard cap on resident page bitmaps.
2602        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2603        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2604        // Workers and the renderer report here; the calling thread drains it in
2605        // page order. Bounded so workers block (bounding resident bitmaps) when the
2606        // consumer falls behind.
2607        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
2608
2609        let mut workers = std::mem::take(&mut self.pool);
2610        let mut asm = assemble::StreamAssembler::new();
2611        let mut first_err: Option<PdfError> = None;
2612
2613        std::thread::scope(|s| {
2614            // Workers: pull a batch of pages (whatever is already rendered, up
2615            // to the layout batch size), process it, report (index-tagged)
2616            // results.
2617            for worker in workers.iter_mut() {
2618                let work_rx = Arc::clone(&work_rx);
2619                let res_tx = res_tx.clone();
2620                s.spawn(move || {
2621                    worker.run_pool(&work_rx, layout_batch, |idx, out| {
2622                        // `false` once the consumer is gone.
2623                        res_tx.send(out.map(|o| (idx, o))).is_ok()
2624                    });
2625                });
2626            }
2627            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
2628            // single thread); report a render error through the same channel.
2629            {
2630                let res_tx = res_tx.clone();
2631                s.spawn(move || {
2632                    let render = pdfium_backend::for_each_page(
2633                        bytes,
2634                        password,
2635                        render_image,
2636                        extract_text,
2637                        range,
2638                        |i, _total, page| {
2639                            work_tx
2640                                .send((i, page))
2641                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2642                        },
2643                    );
2644                    drop(work_tx); // signal workers to finish
2645                    if let Err(e) = render {
2646                        let _ = res_tx.send(Err(e));
2647                    }
2648                });
2649            }
2650            // Drop our own sender so the channel closes once the threads finish.
2651            drop(res_tx);
2652
2653            // Collector (this thread): reorder into document order and emit.
2654            // With a page window, indices start at the window's first page.
2655            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
2656            let mut next = range.map_or(0, |(first, _)| first);
2657            for msg in res_rx.iter() {
2658                match msg {
2659                    Err(e) => {
2660                        if first_err.is_none() {
2661                            first_err = Some(e);
2662                        }
2663                    }
2664                    Ok((idx, out)) => {
2665                        buffer.insert(idx, out);
2666                        if first_err.is_some() {
2667                            continue; // keep draining so the threads can exit
2668                        }
2669                        while let Some((nodes, links, _conf)) = buffer.remove(&next) {
2670                            if let Err(e) = emit(asm.push(nodes), links) {
2671                                first_err = Some(e);
2672                                break;
2673                            }
2674                            next += 1;
2675                        }
2676                    }
2677                }
2678            }
2679        });
2680        // Threads have joined; restore the pool for the next conversion.
2681        self.pool = workers;
2682
2683        if let Some(e) = first_err {
2684            return Err(e);
2685        }
2686        emit(asm.finish(), Vec::new())
2687    }
2688
2689    /// Lazily grow the pool to `target_workers`, loading the new workers
2690    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
2691    /// one load's wall-time). Cached for reuse across documents.
2692    fn ensure_pool(&mut self) -> Result<(), PdfError> {
2693        let need = self.target_workers.saturating_sub(self.pool.len());
2694        if need == 0 {
2695            return Ok(());
2696        }
2697        let intra = pdf_intra();
2698        let no_ocr = self.no_ocr;
2699        let skip_ocr = self.skip_ocr;
2700        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2701        let ntp = self.no_text_panels;
2702        let ocr_lang = self.ocr_lang;
2703        let ocr_engine = self.ocr_engine;
2704        let tesseract_lang = self.tesseract_lang.clone();
2705        let ocr_scale = self.ocr_scale;
2706        let enrich = self.enrich;
2707        let tables = self.tables_slot();
2708        let enrich_slots = self.enrich_slots();
2709        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
2710            let handles: Vec<_> = (0..need)
2711                .map(|_| {
2712                    let tables = tables.clone();
2713                    let enrich_slots = enrich_slots.clone();
2714                    let tesseract_lang = tesseract_lang.clone();
2715                    s.spawn(move || {
2716                        Worker::load(
2717                            intra,
2718                            tables,
2719                            enrich_slots,
2720                            enrich,
2721                            no_ocr,
2722                            skip_ocr,
2723                            force,
2724                            ntp,
2725                            ocr_lang,
2726                            ocr_engine,
2727                            tesseract_lang,
2728                            ocr_scale,
2729                        )
2730                    })
2731                })
2732                .collect();
2733            handles.into_iter().map(|h| h.join().unwrap()).collect()
2734        });
2735        for w in loaded {
2736            self.pool.push(w?);
2737        }
2738        Ok(())
2739    }
2740
2741    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
2742    /// docling routes images through the same layout+OCR pipeline as a PDF page.
2743    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2744        let image = decode_image_limited(bytes)?;
2745        let (w, h) = image.dimensions();
2746        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
2747        // standalone image has no text layer, so OCR supplies the cells.
2748        let page = PdfPage {
2749            width: w as f32,
2750            height: h as f32,
2751            scale: 1.0,
2752            cells: Vec::new(),
2753            code_cells: Vec::new(),
2754            word_cells: Vec::new(),
2755            // A standalone image *is* its own scale-1.0 page image, so the
2756            // layout model sees it through the docling-exact PIL kernel.
2757            image_layout: Some(image.clone()),
2758            image,
2759            links: Vec::new(),
2760            rotation: 0,
2761        };
2762        self.process_pages(vec![page], name)
2763    }
2764
2765    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
2766    /// page (image / METS inputs, which are small and already materialised).
2767    /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
2768    /// caller-configured pipeline (#244).
2769    pub fn process_pages(
2770        &mut self,
2771        mut pages: Vec<PdfPage>,
2772        name: &str,
2773    ) -> Result<DoclingDocument, PdfError> {
2774        let mut doc = DoclingDocument::new(name);
2775        let mut confs = std::collections::BTreeMap::new();
2776        let worker = self.primary()?;
2777        for (n, page) in pages.iter_mut().enumerate() {
2778            let (mut nodes, links, conf) = worker.process(n, page)?;
2779            assemble::stamp_page_no(&mut nodes, n + 1);
2780            doc.nodes.extend(nodes);
2781            doc.links.extend(links);
2782            confs.insert(n + 1, conf);
2783        }
2784        assemble::merge_continuations(&mut doc.nodes);
2785        // No PDF behind these pages (images, METS): the heading-hierarchy
2786        // stage degrades to the numbering signal — exactly docling without
2787        // an outline or parsed pages.
2788        self.apply_heading_hierarchy(&mut doc.nodes, None);
2789        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2790        Ok(doc)
2791    }
2792}
2793
2794/// Number of pages in a PDF, without converting anything — what the CLI batch
2795/// mode prints in its per-document start line.
2796#[cfg(feature = "ml")]
2797pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
2798    pdfium_backend::page_count(bytes, password)
2799}
2800
2801#[cfg(feature = "ml")]
2802/// Convenience one-shot conversion (loads the pipeline per call). Errors are
2803/// detailed and surfaced (never silently skipped).
2804pub fn convert(
2805    bytes: &[u8],
2806    password: Option<&str>,
2807    name: &str,
2808) -> Result<DoclingDocument, PdfError> {
2809    convert_with_options(
2810        bytes,
2811        password,
2812        name,
2813        false,
2814        false,
2815        false,
2816        false,
2817        EnrichmentOptions::default(),
2818        None,
2819        None,
2820    )
2821}
2822
2823#[cfg(feature = "ml")]
2824/// Like [`convert`], but optionally skips loading/running TableFormer (see
2825/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2826/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
2827/// [`Pipeline::enrichments`]).
2828// One positional per pipeline switch mirrors the Pipeline builder; growing
2829// past clippy's arity cap is the price of keeping this one-shot signature
2830// stable-ish instead of churning callers into an options struct mid-series.
2831#[allow(clippy::too_many_arguments)]
2832pub fn convert_with_options(
2833    bytes: &[u8],
2834    password: Option<&str>,
2835    name: &str,
2836    no_table_former: bool,
2837    no_ocr: bool,
2838    force_full_page_ocr: bool,
2839    no_text_panels: bool,
2840    enrich: EnrichmentOptions,
2841    pages: Option<(usize, usize)>,
2842    ocr_lang: Option<OcrLang>,
2843) -> Result<DoclingDocument, PdfError> {
2844    Pipeline::new()?
2845        .no_table_former(no_table_former)
2846        .no_ocr(no_ocr)
2847        .force_full_page_ocr(force_full_page_ocr)
2848        .no_text_panels(no_text_panels)
2849        .enrichments(enrich)
2850        .pages(pages)
2851        .ocr_lang(ocr_lang)
2852        .convert(bytes, password, name)
2853}
2854
2855#[cfg(feature = "ml")]
2856/// Convenience one-shot image conversion (loads the pipeline per call).
2857pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2858    convert_image_with_options(
2859        bytes,
2860        name,
2861        false,
2862        false,
2863        false,
2864        EnrichmentOptions::default(),
2865        None,
2866    )
2867}
2868
2869#[cfg(feature = "ml")]
2870/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
2871/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2872/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2873pub fn convert_image_with_options(
2874    bytes: &[u8],
2875    name: &str,
2876    no_table_former: bool,
2877    no_ocr: bool,
2878    no_text_panels: bool,
2879    enrich: EnrichmentOptions,
2880    ocr_lang: Option<OcrLang>,
2881) -> Result<DoclingDocument, PdfError> {
2882    Pipeline::new()?
2883        .no_table_former(no_table_former)
2884        .no_ocr(no_ocr)
2885        .no_text_panels(no_text_panels)
2886        .enrichments(enrich)
2887        .ocr_lang(ocr_lang)
2888        .convert_image(bytes, name)
2889}
2890
2891#[cfg(feature = "ml")]
2892/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
2893/// scans) through the shared layout + assembly pipeline.
2894pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
2895    convert_pages_with_options(
2896        pages,
2897        name,
2898        false,
2899        false,
2900        false,
2901        EnrichmentOptions::default(),
2902    )
2903}
2904
2905#[cfg(feature = "ml")]
2906/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
2907/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2908/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2909pub fn convert_pages_with_options(
2910    pages: Vec<PdfPage>,
2911    name: &str,
2912    no_table_former: bool,
2913    no_ocr: bool,
2914    no_text_panels: bool,
2915    enrich: EnrichmentOptions,
2916) -> Result<DoclingDocument, PdfError> {
2917    Pipeline::new()?
2918        .no_table_former(no_table_former)
2919        .no_text_panels(no_text_panels)
2920        .no_ocr(no_ocr)
2921        .enrichments(enrich)
2922        .process_pages(pages, name)
2923}
2924
2925#[cfg(feature = "ml")]
2926#[cfg(all(test, feature = "ml"))]
2927mod image_limit_tests {
2928    use super::decode_image_with_max_side;
2929
2930    /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
2931    /// byte literal).
2932    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
2933        use std::io::Cursor;
2934        let img = image::RgbImage::new(w, h);
2935        let mut out = Vec::new();
2936        img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
2937            .unwrap();
2938        out
2939    }
2940
2941    #[test]
2942    fn normal_image_decodes_under_the_cap() {
2943        let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
2944        assert_eq!(img.dimensions(), (8, 8));
2945    }
2946
2947    /// docling#4247 (2.128): the EXIF orientation is applied when a frame is
2948    /// loaded — a 4×2 JPEG tagged "rotate 90° CW" (orientation 6) decodes as
2949    /// 2×4, with the pixels turned.
2950    #[test]
2951    fn exif_orientation_is_applied() {
2952        use std::io::Cursor;
2953        let mut img = image::RgbImage::new(4, 2);
2954        img.put_pixel(0, 0, image::Rgb([255, 0, 0]));
2955        let mut jpeg = Vec::new();
2956        img.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
2957            .unwrap();
2958        // Splice an APP1 Exif segment (little-endian TIFF, one IFD entry:
2959        // Orientation = 6) right after the SOI marker.
2960        let mut tiff = b"II*\0".to_vec();
2961        tiff.extend(8u32.to_le_bytes());
2962        tiff.extend(1u16.to_le_bytes());
2963        tiff.extend(0x0112u16.to_le_bytes());
2964        tiff.extend(3u16.to_le_bytes());
2965        tiff.extend(1u32.to_le_bytes());
2966        tiff.extend(6u16.to_le_bytes());
2967        tiff.extend([0, 0]);
2968        tiff.extend(0u32.to_le_bytes());
2969        let mut app1 = b"Exif\0\0".to_vec();
2970        app1.extend(tiff);
2971        let mut out = jpeg[..2].to_vec();
2972        out.extend([0xff, 0xe1]);
2973        out.extend((app1.len() as u16 + 2).to_be_bytes());
2974        out.extend(app1);
2975        out.extend(&jpeg[2..]);
2976        let plain = decode_image_with_max_side(&jpeg, 30_000).unwrap();
2977        assert_eq!(plain.dimensions(), (4, 2));
2978        let turned = decode_image_with_max_side(&out, 30_000).unwrap();
2979        assert_eq!(turned.dimensions(), (2, 4), "quarter turn swaps the sides");
2980        // Rotating 90° CW moves the top-left pixel to the top-right corner.
2981        assert!(turned.get_pixel(1, 0).0[0] > 128);
2982        assert!(turned.get_pixel(0, 0).0[0] <= 128);
2983    }
2984
2985    #[test]
2986    fn dimensions_over_the_cap_are_rejected_not_aborted() {
2987        // A per-side cap below the image's declared size must yield a
2988        // recoverable Err, never an allocation-abort — the mechanism that stops
2989        // a crafted image declaring 60000×60000 from OOM-killing the process.
2990        let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
2991        assert!(
2992            r.is_err(),
2993            "decode must fail under the pixel cap, not abort"
2994        );
2995    }
2996}
2997
2998#[cfg(test)]
2999mod median_tests {
3000    #[test]
3001    fn median_of_empty_is_zero_not_a_panic() {
3002        // A crafted table can leave a row/column with zero matched cells; the
3003        // even-count branch would index values[0 - 1] and panic (→ remote crash
3004        // via docling-serve) without the empty guard.
3005        assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
3006        assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
3007        assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
3008    }
3009}
3010
3011#[cfg(test)]
3012mod send_check {
3013    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
3014    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
3015    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
3016    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
3017    fn assert_send<T: Send>() {}
3018
3019    #[test]
3020    fn pipeline_is_send() {
3021        assert_send::<super::Pipeline>();
3022    }
3023}
3024
3025#[cfg(all(test, feature = "ml"))]
3026mod ocr_input_tests {
3027    /// #254: without an `ocr_scale` (or with one equal to the render scale)
3028    /// the OCR reads the page render untouched and the cache stays cold; a
3029    /// different scale builds one resampled view, reuses it across calls, and
3030    /// reports the requested px/pt so cell geometry divides back to points.
3031    #[test]
3032    fn ocr_input_resamples_only_on_a_real_scale_change() {
3033        let img = image::RgbImage::new(200, 100);
3034        let mut cache = None;
3035        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, None);
3036        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
3037        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(2.0));
3038        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
3039
3040        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
3041        assert_eq!((v.width(), v.height(), s), (300, 150, 3.0));
3042        let first = cache.as_ref().map(|c| c as *const image::RgbImage);
3043        let (v, _) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
3044        assert_eq!(
3045            Some(v as *const image::RgbImage),
3046            first,
3047            "cached, not rebuilt"
3048        );
3049
3050        let mut down = None;
3051        let (v, s) = super::ocr_input(&mut down, &img, 2.0, Some(1.0));
3052        assert_eq!((v.width(), v.height(), s), (100, 50, 1.0));
3053    }
3054}