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        // No text layer → recognise text from the page image via OCR.
1385        let ocred = page.cells.is_empty();
1386        // Lines the text detector found outside every layout region (#429).
1387        let mut det_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1388        if ocred {
1389            // Region-scoped OCR recognizes each region's crop, so two regular
1390            // regions over the same ink would read it twice — a low-score
1391            // paragraph box over the high-score line boxes `greedy` keeps.
1392            // Collapse such groups to one region first; a digital
1393            // page resolves the same overlap through cell ownership in
1394            // `fit_regions_to_cells` and needs nothing here.
1395            assemble::merge_overlapping_regulars(&mut regions);
1396            // `None` = `skip_ocr` or a missing model (#244): the page keeps
1397            // its layout regions (and TableFormer structure below) with no
1398            // recognized text, instead of failing the conversion.
1399            if let Some(ocr) = self.ocr_model()? {
1400                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1401                let cells = timing::timed("ocr.page", || ocr.ocr_page(img, &regions, scl))
1402                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1403                ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
1404                page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
1405                // Table interiors carry no words yet: region-scoped OCR skips
1406                // table labels, and a scanned page has no pdfium text layer — so
1407                // TableFormer's cell matcher got an empty word list and the table
1408                // dissolved (#173). Recognize the table regions' word crops
1409                // (mirroring the browser scanned path): `word_cells` feeds the
1410                // matcher, and the same cells join `cells` so the geometric
1411                // fallback and the table's region text see them too.
1412                if regions.iter().any(|r| assemble::is_table_like(r.label)) {
1413                    let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1414                    let words = timing::timed("ocr.table_words", || {
1415                        ocr.ocr_table_words(img, &regions, scl)
1416                    })
1417                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1418                    ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1419                    let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1420                    page.cells.extend(words.iter().cloned());
1421                    page.word_cells = words;
1422                }
1423            }
1424            // docling's OCR engines detect text lines over the whole bitmap
1425            // and every line becomes a cell, so text the layout model gave no
1426            // region — a diagram's labels, a stamp, a margin note — still
1427            // reads out as orphan text. Region-scoped recognition above stays
1428            // the source inside layout regions; the detector (#429) adds only
1429            // the lines no recognized cell already covers, and the orphan pass
1430            // below places them (those inside a kept picture or table become
1431            // that special's silent children, as upstream).
1432            if self.ocr_model()?.is_some() {
1433                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1434                // Usually computed already, alongside layout (see
1435                // `detect_alongside`); a page that reached OCR another way
1436                // detects here.
1437                // Degradation over failure: a detector that loaded but cannot
1438                // run (a damaged file, an allocation failure) costs the page
1439                // its detected lines, not its conversion — the region-scoped
1440                // pass above is complete on its own.
1441                let detected = match self.pending_det.remove(&n) {
1442                    Some(result) => result,
1443                    None => match self.det_model() {
1444                        Some(det) => timing::timed("ocr.det", || det.detect(img)),
1445                        None => Ok(Vec::new()),
1446                    },
1447                }
1448                .unwrap_or_else(|e| {
1449                    docling_core::debug_log!(
1450                        "docling-pdf: page {}: text detection failed ({e}); keeping the \
1451                         region-scoped OCR only",
1452                        n + 1
1453                    );
1454                    Vec::new()
1455                });
1456                docling_core::debug_log!(
1457                    "docling-pdf: page {}: text detector found {} line(s): {:?}",
1458                    n + 1,
1459                    detected.len(),
1460                    detected
1461                        .iter()
1462                        .map(|d| (
1463                            d.l.round(),
1464                            d.t.round(),
1465                            d.r.round(),
1466                            d.b.round(),
1467                            (d.score * 100.0).round() / 100.0
1468                        ))
1469                        .collect::<Vec<_>>()
1470                );
1471                let uncovered = ocr_det::uncovered_lines(&detected, scl, &regions, &page.cells);
1472                docling_core::debug_log!(
1473                    "docling-pdf: page {}: {} of {} detected line(s) not covered by the region pass",
1474                    n + 1,
1475                    uncovered.len(),
1476                    detected.len()
1477                );
1478                if let (false, Some(ocr)) = (uncovered.is_empty(), self.ocr_model()?) {
1479                    let scored =
1480                        timing::timed("ocr.det_lines", || ocr.ocr_page(img, &uncovered, scl))
1481                            .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1482                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1483                    det_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1484                    page.cells.extend(det_cells.iter().cloned());
1485                }
1486            }
1487        }
1488        // Region-scoped OCR skips `picture` interiors, and a digital page's
1489        // text layer cannot see into an embedded raster either — so a figure
1490        // that is really a text box (terms-and-conditions exported as an
1491        // image) lost its words on every page kind. Python docling OCRs the
1492        // bitmap-covered areas of *every* page — even digital ones — once they
1493        // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
1494        // already do. Recognize the big text-less crops here too; the panel
1495        // demotion / orphan recovery below place the lines.
1496        let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
1497        {
1498            let page_area = (page.width * page.height).max(1.0);
1499            let has_text = |r: &layout::Region| {
1500                page.cells.iter().any(|c| {
1501                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1502                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1503                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1504                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
1505                })
1506            };
1507            // A captioned picture can never demote to a text panel (see
1508            // recover_text_panels), and on digital pages its speculative OCR
1509            // would be discarded anyway — don't pay for it.
1510            let captioned = |r: &layout::Region| {
1511                regions.iter().any(|c| {
1512                    c.label == "caption"
1513                        && c.r.min(r.r) - c.l.max(r.l) > 0.0
1514                        && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
1515                })
1516            };
1517            let bare: Vec<layout::Region> = regions
1518                .iter()
1519                .filter(|r| {
1520                    r.label == "picture"
1521                        && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
1522                        && !has_text(r)
1523                        && (ocred || !captioned(r))
1524                })
1525                .map(|r| layout::Region {
1526                    label: "text",
1527                    ..r.clone()
1528                })
1529                .collect();
1530            // Speculative OCR (#244): with `skip_ocr` or no model, big bare
1531            // pictures simply stay pictures.
1532            if let (false, Some(ocr)) = (bare.is_empty(), self.ocr_model()?) {
1533                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1534                let scored = timing::timed("ocr.pictures", || ocr.ocr_page(img, &bare, scl))
1535                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1536                // Speculative in-picture OCR counts toward ocr_score only on
1537                // OCR'd pages, where the recognized lines actually join the
1538                // output; on a digital page they may be discarded below.
1539                if ocred {
1540                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
1541                }
1542                pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
1543                page.cells.extend(pic_cells.iter().cloned());
1544            }
1545        }
1546        let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
1547        // A "picture" that is really a colored text panel — dense, wide,
1548        // multi-line — reads out as paragraphs instead of shipping as pixels;
1549        // sparse in-picture text (a chart's labels) keeps the crop and stays
1550        // inside it as the picture's silent children (docling parity, #200).
1551        // `no_text_panels` (#173) opts out entirely for image-extraction
1552        // workflows.
1553        if !self.no_text_panels {
1554            assemble::recover_text_panels(&mut regions, &page.cells);
1555        }
1556        // On an OCR'd page, in-picture text that did NOT demote its picture
1557        // mostly stays silent, exactly as in docling: its postprocess step
1558        // "Remove regular clusters that are included in wrappers" walks
1559        // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
1560        // >80 % contained in a kept picture becomes that picture's child and
1561        // never reaches the serializer. Only border-straddlers (≤80 %
1562        // containment) survive as text. Emitting *everything* here used to
1563        // splice a chart's OCR'd axis ticks into the body text right next to
1564        // the image chunk (#200) — so the orphan pass places the recognized
1565        // lines, the containment drop re-runs for the in-table ones, and
1566        // `assemble_page` nests the in-picture ones under their picture
1567        // (JSON-only children, `assemble::picture_parents`).
1568        if ocred && (!pic_cells.is_empty() || !det_cells.is_empty()) {
1569            // Pictures (and wrappers) no longer count as claimers (#165), so
1570            // the plain orphan pass places the recognized lines directly —
1571            // the detector's lines (#429) the same way.
1572            assemble::add_orphan_regions(&mut regions, &pic_cells);
1573            assemble::add_orphan_regions(&mut regions, &det_cells);
1574            assemble::drop_contained_regulars(&mut regions);
1575        } else if !ocred && !pic_cells.is_empty() {
1576            // Digital page, picture kept: its speculative OCR cells must not
1577            // linger in the text-cell set (they were appended at the tail).
1578            let kept: Vec<layout::Region> = regions
1579                .iter()
1580                .filter(|r| r.label == "picture")
1581                .cloned()
1582                .collect();
1583            let tail = page.cells.split_off(cells_before_pic_ocr);
1584            page.cells.extend(tail.into_iter().filter(|c| {
1585                !kept.iter().any(|r| {
1586                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1587                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
1588                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
1589                    ix * iy / ca > 0.5
1590                })
1591            }));
1592        }
1593        // A text-less *table* detected inside a picture on a digital page — a
1594        // screenshot of a table (2203's Figure 10) — has no text layer and no
1595        // scanned-path OCR to feed it, so its grid used to serialize empty and
1596        // the whole element vanished. docling OCRs bitmap-covered areas on
1597        // every page kind and its table cluster collects those cells; mirror
1598        // the scanned path for exactly these tables: recognize word crops and
1599        // feed them to the TableFormer matcher and the cell set.
1600        if !ocred {
1601            let has_text = |t: &layout::Region| {
1602                page.cells.iter().any(|c| {
1603                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
1604                    let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
1605                    let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
1606                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
1607                })
1608            };
1609            let in_picture = |t: &layout::Region| {
1610                regions.iter().any(|r| {
1611                    r.label == "picture" && {
1612                        let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
1613                        let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
1614                        let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
1615                        ix * iy / ta > 0.5
1616                    }
1617                })
1618            };
1619            let pic_tables: Vec<layout::Region> = regions
1620                .iter()
1621                .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
1622                .cloned()
1623                .collect();
1624            // Same degradation as above: without OCR the in-picture table
1625            // keeps its structure (TableFormer is geometry-driven) minus text.
1626            if let (false, Some(ocr)) = (pic_tables.is_empty(), self.ocr_model()?) {
1627                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
1628                let words = timing::timed("ocr.table_words", || {
1629                    ocr.ocr_table_words(img, &pic_tables, scl)
1630                })
1631                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
1632                ocr_confs.extend(words.iter().map(|(_, conf)| conf));
1633                let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
1634                page.cells.extend(words.iter().cloned());
1635                page.word_cells.extend(words);
1636            }
1637        }
1638        // The cells are final: fit every regular region to the cells it
1639        // claims and fold the orphans it now surrounds (#419), before
1640        // TableFormer and the reading order see the boxes.
1641        assemble::fit_regions_to_cells(&mut regions, &page.cells);
1642        Ok(Prepared {
1643            regions,
1644            ocr_confs,
1645            parse,
1646        })
1647    }
1648
1649    /// The stages after TableFormer: enrichment, the page confidence report and
1650    /// assembly into typed nodes.
1651    fn complete_page(
1652        &mut self,
1653        n: usize,
1654        page: &mut PdfPage,
1655        prepared: Prepared,
1656        table_rows: Vec<Option<tf_core::TableGrid>>,
1657    ) -> Result<PageOut, PdfError> {
1658        let Prepared {
1659            regions,
1660            ocr_confs,
1661            parse,
1662        } = prepared;
1663        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
1664            for (i, r) in regions.iter().enumerate() {
1665                eprintln!(
1666                    "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
1667                    r.label,
1668                    r.score,
1669                    r.l,
1670                    r.t,
1671                    r.r,
1672                    r.b,
1673                    table_rows[i]
1674                        .as_ref()
1675                        .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
1676                );
1677            }
1678            eprintln!(
1679                "DBG cells={} words={}",
1680                page.cells.len(),
1681                page.word_cells.len()
1682            );
1683        }
1684        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
1685        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
1686        // shape as TableFormer — one lazily-loaded instance per pipeline, only
1687        // ever locked when a page actually has a matching region.
1688        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
1689        if let Some(slot) = self.classifier.as_ref() {
1690            if regions.iter().any(|r| r.label == "picture") {
1691                timing::timed("picture_classifier", || {
1692                    let mut guard = slot.lock().unwrap();
1693                    if matches!(*guard, EnrichSlot::Unloaded) {
1694                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
1695                            Some(m) => EnrichSlot::Ready(m),
1696                            None => EnrichSlot::Missing,
1697                        };
1698                    }
1699                    if let EnrichSlot::Ready(model) = &mut *guard {
1700                        for (i, r) in regions.iter().enumerate() {
1701                            if r.label != "picture" {
1702                                continue;
1703                            }
1704                            let Some(crop) = assemble::crop_region_scaled(
1705                                page,
1706                                [r.l, r.t, r.r, r.b],
1707                                enrich::CLASSIFIER_SCALE,
1708                            ) else {
1709                                continue;
1710                            };
1711                            match model.classify(&crop) {
1712                                Ok(classes) => {
1713                                    enrich_out[i] =
1714                                        Some(assemble::Enrichment::PictureClasses(classes));
1715                                }
1716                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1717                            }
1718                        }
1719                    }
1720                });
1721            }
1722        }
1723        if let Some(slot) = self.code_formula.as_ref() {
1724            let wants = |label: &str| {
1725                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
1726            };
1727            if regions.iter().any(|r| wants(r.label)) {
1728                timing::timed("code_formula", || {
1729                    let mut guard = slot.lock().unwrap();
1730                    if matches!(*guard, EnrichSlot::Unloaded) {
1731                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
1732                            Some(m) => EnrichSlot::Ready(m),
1733                            None => EnrichSlot::Missing,
1734                        };
1735                    }
1736                    if let EnrichSlot::Ready(model) = &mut *guard {
1737                        for (i, r) in regions.iter().enumerate() {
1738                            if !wants(r.label) {
1739                                continue;
1740                            }
1741                            // docling crops the postprocessed cluster box — the
1742                            // union of the region's text cells, not the raw
1743                            // detector box — expanded by 18% per side, at
1744                            // ~120 dpi.
1745                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
1746                                .unwrap_or([r.l, r.t, r.r, r.b]);
1747                            let (w, h) = (br - bl, bb - bt);
1748                            let ex = enrich::CODE_FORMULA_EXPANSION;
1749                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
1750                            let Some(crop) = assemble::crop_region_scaled(
1751                                page,
1752                                bbox,
1753                                enrich::CODE_FORMULA_SCALE,
1754                            ) else {
1755                                continue;
1756                            };
1757                            let kind = if r.label == "code" {
1758                                enrich::CodeFormulaKind::Code
1759                            } else {
1760                                enrich::CodeFormulaKind::Formula
1761                            };
1762                            match model.predict(&crop, kind) {
1763                                Ok(text) => {
1764                                    enrich_out[i] = Some(match kind {
1765                                        enrich::CodeFormulaKind::Code => {
1766                                            let (code, language) =
1767                                                enrich::extract_code_language(&text);
1768                                            assemble::Enrichment::Code {
1769                                                language,
1770                                                text: code,
1771                                            }
1772                                        }
1773                                        enrich::CodeFormulaKind::Formula => {
1774                                            assemble::Enrichment::Formula { latex: text }
1775                                        }
1776                                    });
1777                                }
1778                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
1779                            }
1780                        }
1781                    }
1782                });
1783            }
1784        }
1785        // Score the final region set (docling assigns layout_score over the
1786        // postprocessed clusters — the page elements assemble_page emits,
1787        // which leave out the regulars nested in a picture as its children).
1788        let parents = assemble::picture_parents(&regions);
1789        let elements: Vec<layout::Region> = regions
1790            .iter()
1791            .zip(&parents)
1792            .filter(|(_, p)| p.is_none())
1793            .map(|(r, _)| r.clone())
1794            .collect();
1795        let conf = quality::page_confidence(parse, &elements, &ocr_confs);
1796        let (nodes, links) = timing::timed("assemble_page", || {
1797            assemble::assemble_page(page, regions, &table_rows, &enrich_out)
1798        });
1799        Ok((nodes, links, conf))
1800    }
1801}
1802
1803#[cfg(feature = "ml")]
1804/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
1805/// so on a typical machine two threads per worker (sharing one in-cache copy of
1806/// the weights) extracts more throughput than one fat model or many single-thread
1807/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
1808fn pdf_intra() -> usize {
1809    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
1810        return n;
1811    }
1812    if intra_threads() >= 2 {
1813        2
1814    } else {
1815        1
1816    }
1817}
1818
1819#[cfg(feature = "ml")]
1820/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
1821/// overrides; otherwise size the pool so `workers × intra ≈ cores`.
1822///
1823/// The pool scales with the machine (#324 follow-up testing): the old hard cap
1824/// of 4 left most of a many-core box idle — on a 16-core M4 Max, 10 workers
1825/// measured ~1.2× over the capped pool (10.0 → 8.5 s on a 130-page document,
1826/// byte-identical output). The ceiling of 16 is a memory bound, not a
1827/// performance one: each worker holds its own layout/OCR sessions (~0.4 GB),
1828/// so a worst-case pool stays under ~6.5 GB even on a ≥32-core host — and
1829/// docling-serve's per-request pools sit behind its `DOCLING_RS_MAX_MEMORY_MB`
1830/// admission control besides. Machines with 4 or fewer effective threads keep
1831/// the exact old sizing (`threads / intra`, min 1).
1832fn pdf_worker_count() -> usize {
1833    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
1834        return n;
1835    }
1836    (intra_threads() / pdf_intra()).clamp(1, 16)
1837}
1838
1839#[cfg(feature = "ml")]
1840/// Max pages a worker layout-detects with one batched inference call (issue
1841/// #73). Workers drain the work channel opportunistically up to this size —
1842/// whatever is already rendered gets batched, so batching never *waits* for
1843/// pages and adds no latency when rendering is the bottleneck.
1844///
1845/// Default: per-page (1) on the CPU provider, 4 when a GPU provider is
1846/// selected (#338). The old "4 on 8+ cores" CPU default was a hypothesis —
1847/// that single-session amortization pays off with a wider thread budget —
1848/// and every actual CPU measurement lands the other way: a 4-core x86 box
1849/// runs the 9-page 2206.01062 fixture in 8.5 s/conv at batch=1 vs 9.3 s at
1850/// batch=4 (re-measured for #338; the original 8.1 vs 9.3 agrees), and the
1851/// issue-#338 report measured batch=1 ~2× faster on a 16-core M4 Max at
1852/// every worker count — batching only adds cache pressure once workers
1853/// saturate the cores. On a GPU the per-call dispatch overhead is real and
1854/// batching amortizes it, so the GPU default stays. Output is bit-identical
1855/// at every batch size, so this is purely a throughput knob.
1856/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides either way; `1` = per-page.
1857pub(crate) fn pdf_layout_batch() -> usize {
1858    env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
1859        .filter(|&n| n > 0)
1860        .unwrap_or_else(|| if docling_onnx::prefers_fp32() { 4 } else { 1 })
1861}
1862
1863#[cfg(feature = "ml")]
1864/// Minimum page count before a PDF is worth the parallel worker pool. Below this,
1865/// the serial primary (running its model on every core) is faster than fanning out
1866/// — the helper pool's one-time model-load cost only pays off once enough pages
1867/// share it. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
1868fn pdf_parallel_min() -> usize {
1869    env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
1870        .filter(|&n| n > 0)
1871        .unwrap_or(6)
1872}
1873
1874#[cfg(feature = "ml")]
1875/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
1876/// so a single-page / small / image / METS input is converted at full intra-op
1877/// speed with no pool to load. A document with enough pages instead fans out
1878/// across a **pool** of narrower workers processed concurrently. Both load lazily
1879/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
1880pub struct Pipeline {
1881    /// Full-intra worker for the serial path; loaded on first serial use.
1882    primary: Option<Worker>,
1883    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
1884    /// path; loaded on first multi-page use and cached.
1885    pool: Vec<Worker>,
1886    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
1887    tables: SharedTables,
1888    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
1889    classifier: SharedClassifier,
1890    code_formula: SharedCodeFormula,
1891    /// Desired pool size for multi-page documents.
1892    target_workers: usize,
1893    /// Page count at/above which the parallel pool is worth its load cost.
1894    parallel_min: usize,
1895    /// Skip loading/running TableFormer; table regions fall back to geometric
1896    /// reconstruction. See [`Pipeline::no_table_former`].
1897    no_table_former: bool,
1898    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
1899    no_ocr: bool,
1900    /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
1901    skip_ocr: bool,
1902    /// OCR every page even when it carries a text layer. See
1903    /// [`Pipeline::force_full_page_ocr`].
1904    force_full_page_ocr: bool,
1905    /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
1906    no_text_panels: bool,
1907    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
1908    enrich: EnrichmentOptions,
1909    /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
1910    page_range: Option<(usize, usize)>,
1911    /// OCR recognition language. See [`Pipeline::ocr_lang`].
1912    ocr_lang: ocr::OcrLang,
1913    /// Which OCR engine runs (#460). See [`Pipeline::ocr_engine`].
1914    ocr_engine: ocr::OcrEngine,
1915    /// Tesseract's languages (#460). See [`Pipeline::tesseract_lang`].
1916    tesseract_lang: Option<String>,
1917    /// Which regions feed the OCR (#254). See [`Pipeline::ocr_mode`].
1918    ocr_mode: ocr::OcrMode,
1919    /// OCR render scale override in px/pt (#254). See [`Pipeline::ocr_scale`].
1920    ocr_scale: Option<f32>,
1921    /// Heading-level inference (#302). See [`Pipeline::heading_hierarchy`].
1922    heading_hierarchy: HeadingHierarchyOptions,
1923    /// Optional per-page progress hook `(done, selected_total)`, invoked after
1924    /// each page finishes on both the serial and parallel buffered paths. Set
1925    /// by the CLI batch mode for dot-progress; `None` costs nothing.
1926    progress: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>,
1927}
1928
1929#[cfg(feature = "ml")]
1930impl Pipeline {
1931    /// Construct the pipeline. Models load lazily on first use (full-intra primary
1932    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
1933    /// loaded that a given document doesn't need.
1934    pub fn new() -> Result<Self, PdfError> {
1935        Ok(Self {
1936            primary: None,
1937            pool: Vec::new(),
1938            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
1939            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1940            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
1941            target_workers: pdf_worker_count(),
1942            parallel_min: pdf_parallel_min(),
1943            no_table_former: false,
1944            no_ocr: false,
1945            skip_ocr: false,
1946            force_full_page_ocr: false,
1947            no_text_panels: false,
1948            enrich: EnrichmentOptions::default(),
1949            page_range: None,
1950            ocr_lang: ocr::OcrLang::from_env(),
1951            ocr_engine: ocr::OcrEngine::from_env(),
1952            tesseract_lang: None,
1953            ocr_mode: ocr::OcrMode::from_env(),
1954            ocr_scale: ocr::scale_from_env(),
1955            heading_hierarchy: HeadingHierarchyOptions::default(),
1956            progress: None,
1957        })
1958    }
1959
1960    /// Infer section-header levels after assembly (#302, docling's
1961    /// `HeadingHierarchyModel`): PDF bookmarks > legal/outline numbering >
1962    /// font style, off by default — see [`HeadingHierarchyOptions`]. Pure
1963    /// post-processing configuration; for a warm pipeline use
1964    /// [`set_heading_hierarchy`](Self::set_heading_hierarchy).
1965    pub fn heading_hierarchy(mut self, opts: HeadingHierarchyOptions) -> Self {
1966        self.heading_hierarchy = opts;
1967        self
1968    }
1969
1970    /// In-place variant of [`heading_hierarchy`](Self::heading_hierarchy) for
1971    /// a long-lived pipeline (docling-serve's warm instance) — like
1972    /// [`set_pages`](Self::set_pages), set it before every conversion so no
1973    /// request inherits a previous one's choice.
1974    pub fn set_heading_hierarchy(&mut self, opts: HeadingHierarchyOptions) {
1975        self.heading_hierarchy = opts;
1976    }
1977
1978    /// Run the enabled heading-hierarchy stage (#302) on an assembled
1979    /// document: gather the outline (bookmarks) and the per-page glyph styles
1980    /// on demand, then assign levels in place. `bytes` is `None` on paths
1981    /// with no PDF behind them (standalone images, METS) — those degrade to
1982    /// the numbering signal, exactly like docling without parsed pages.
1983    fn apply_heading_hierarchy(&self, nodes: &mut [Node], bytes: Option<&[u8]>) {
1984        let opts = &self.heading_hierarchy;
1985        if !opts.enabled {
1986            return;
1987        }
1988        let outline = match bytes {
1989            Some(bytes) if opts.use_bookmarks => outline::extract_outline(bytes),
1990            _ => Vec::new(),
1991        };
1992        let styles = match bytes {
1993            Some(bytes) if opts.use_style => {
1994                let pages = heading_hierarchy::heading_pages(nodes);
1995                textparse::glyph_styles(bytes, &pages)
1996            }
1997            _ => Default::default(),
1998        };
1999        heading_hierarchy::apply(nodes, &outline, &styles, opts);
2000    }
2001
2002    /// Install (or clear) the per-page progress hook: called with
2003    /// `(pages_done, pages_selected)` after each page completes during
2004    /// [`convert`](Self::convert). Shared with the parallel workers, so the
2005    /// callback must be cheap and thread-safe.
2006    pub fn set_progress(&mut self, cb: Option<Arc<dyn Fn(usize, usize) + Send + Sync>>) {
2007        self.progress = cb;
2008    }
2009
2010    /// Convert only pages `first..=last` (**1-based**, like the page numbers a
2011    /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
2012    /// skipped before rasterization, so the cost is proportional to the window,
2013    /// not the document. `last` past the end of the document clamps; a window
2014    /// that selects no pages at all (`first` beyond the last page) is an error
2015    /// at convert time. `None` (the default) converts everything.
2016    pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
2017        self.page_range = range;
2018        self
2019    }
2020
2021    /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
2022    /// (e.g. docling-serve's warm instance) that applies a per-request window
2023    /// without rebuilding — unlike the model switches, the window is pure
2024    /// configuration. Set it before every conversion; it stays until changed.
2025    pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
2026        self.page_range = range;
2027    }
2028
2029    /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
2030    /// for the multilingual docling-conformance model. `None` keeps the
2031    /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
2032    /// first conversion; for a warm pipeline use
2033    /// [`set_ocr_lang`](Self::set_ocr_lang).
2034    pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
2035        self.set_ocr_lang(lang);
2036        self
2037    }
2038
2039    /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
2040    /// pipeline (docling-serve's warm instance). Unlike the page window this
2041    /// is a *model* switch: any worker whose cached recognition model was
2042    /// loaded for a different language drops it, to be lazily reloaded on the
2043    /// next OCR-needing page (cheap — the rec models are ~10 MB).
2044    pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
2045        let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
2046        self.ocr_lang = lang;
2047        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2048            if worker.ocr_lang != lang {
2049                worker.ocr_lang = lang;
2050                worker.ocr = OcrSlot::Unloaded;
2051            }
2052        }
2053    }
2054
2055    /// Which OCR engine recognizes text (#460, see [`OcrEngine`]): the
2056    /// built-in PP-OCRv3 recognizer by default, or the system `tesseract`
2057    /// binary (docling's `TesseractCliOcrOptions`) — same layout-region
2058    /// crops, same cells; Tesseract does its own line/word segmentation and
2059    /// reads orientation from its OSD. `None` keeps the process default
2060    /// (`DOCLING_RS_OCR_ENGINE`, else PP-OCR). Set before the first
2061    /// conversion; for a warm pipeline use
2062    /// [`set_ocr_engine`](Self::set_ocr_engine).
2063    pub fn ocr_engine(mut self, engine: Option<ocr::OcrEngine>) -> Self {
2064        self.set_ocr_engine(engine);
2065        self
2066    }
2067
2068    /// In-place variant of [`ocr_engine`](Self::ocr_engine): a model switch
2069    /// like [`set_ocr_lang`](Self::set_ocr_lang) — workers holding the other
2070    /// engine drop it, to be lazily reloaded.
2071    pub fn set_ocr_engine(&mut self, engine: Option<ocr::OcrEngine>) {
2072        let engine = engine.unwrap_or_else(ocr::OcrEngine::from_env);
2073        self.ocr_engine = engine;
2074        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2075            if worker.ocr_engine != engine {
2076                worker.ocr_engine = engine;
2077                worker.ocr = OcrSlot::Unloaded;
2078            }
2079        }
2080    }
2081
2082    /// Tesseract's languages (#460): the `-l` argument, tessdata stems joined
2083    /// with `+` — build it from an `ocr_lang` value with
2084    /// [`tesseract_lang_arg`], which also maps BCP-47 tags and the PP-OCR
2085    /// codes. `None` runs Tesseract's default (`eng`). Ignored under the
2086    /// PP-OCR engine, whose language is [`ocr_lang`](Self::ocr_lang). For a
2087    /// warm pipeline use [`set_tesseract_lang`](Self::set_tesseract_lang).
2088    pub fn tesseract_lang(mut self, lang: Option<String>) -> Self {
2089        self.set_tesseract_lang(lang);
2090        self
2091    }
2092
2093    /// In-place variant of [`tesseract_lang`](Self::tesseract_lang): a model
2094    /// switch like [`set_ocr_lang`](Self::set_ocr_lang) — a worker whose
2095    /// Tesseract was probed for other languages drops it.
2096    pub fn set_tesseract_lang(&mut self, lang: Option<String>) {
2097        self.tesseract_lang = lang.clone();
2098        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2099            if worker.tesseract_lang != lang {
2100                worker.tesseract_lang = lang.clone();
2101                if worker.ocr_engine == ocr::OcrEngine::Tesseract {
2102                    worker.ocr = OcrSlot::Unloaded;
2103                }
2104            }
2105        }
2106    }
2107
2108    /// Resolve the configured 1-based window against a page count into the
2109    /// 0-based inclusive form the backend walks, validating it selects at
2110    /// least one existing page.
2111    fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
2112        let Some((first, last)) = self.page_range else {
2113            return Ok(None);
2114        };
2115        if first == 0 || last < first {
2116            return Err(PdfError::Pdfium(format!(
2117                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
2118            )));
2119        }
2120        if first > total {
2121            return Err(PdfError::Pdfium(format!(
2122                "page range {first}-{last} is outside the document ({total} page(s))"
2123            )));
2124        }
2125        Ok(Some((first - 1, last.min(total) - 1)))
2126    }
2127
2128    /// Enable the opt-in enrichment passes (docling's
2129    /// `do_picture_classification` / `do_code_enrichment` /
2130    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
2131    /// the first matching region; a missing model warns once and is skipped.
2132    /// Set before the first conversion (no effect on already-loaded workers).
2133    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
2134        self.enrich = opts;
2135        self
2136    }
2137
2138    /// Skip loading and running the TableFormer table-structure model. Table
2139    /// regions still get emitted, but reconstructed geometrically from cell
2140    /// positions instead of via the ONNX model's predicted structure — faster
2141    /// (no model load, no per-table inference) at the cost of table fidelity.
2142    /// No effect if a worker is already loaded; set this before the first
2143    /// conversion.
2144    pub fn no_table_former(mut self, disable: bool) -> Self {
2145        self.no_table_former = disable;
2146        self
2147    }
2148
2149    /// Keep every detected `picture` region as a picture. By default an
2150    /// *uncaptioned* picture that reads like a dense, uniform text panel (a
2151    /// terms-and-conditions box exported as an image) is demoted into
2152    /// paragraphs (#157); a chart the layout mislabels can still trip that
2153    /// heuristic on scanned pages, and image-extraction workflows may simply
2154    /// want every crop — this flag disables the demotion entirely (#173).
2155    /// No effect on already-loaded workers; set before the first conversion.
2156    pub fn no_text_panels(mut self, disable: bool) -> Self {
2157        self.no_text_panels = disable;
2158        self
2159    }
2160
2161    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
2162    /// inference of any kind. The PDF's embedded text cells are grouped by line
2163    /// and emitted as plain paragraphs in reading order: no headings, lists,
2164    /// tables, code blocks, or pictures, since that structure comes from the
2165    /// layout model. The fastest possible PDF path, but pages with no embedded
2166    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
2167    /// without this flag. Implies `no_table_former`. No effect if a worker is
2168    /// already loaded; set this before the first conversion.
2169    pub fn no_ocr(mut self, disable: bool) -> Self {
2170        self.no_ocr = disable;
2171        self
2172    }
2173
2174    /// Never run OCR, but keep layout detection and TableFormer — docling's
2175    /// independent `do_ocr=False` (#244), the counterpart of
2176    /// [`no_table_former`](Self::no_table_former). Unlike
2177    /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
2178    /// output — headings, tables, pictures, reading order — is preserved;
2179    /// only text that exists solely as pixels is lost: scanned pages come
2180    /// back with their regions empty, and the speculative OCR of large
2181    /// embedded images never runs. The OCR model is never loaded. Ignored
2182    /// when `no_ocr` is set (there is no OCR to skip);
2183    /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
2184    /// mirroring docling where forcing is a sub-option of `do_ocr`.
2185    pub fn skip_ocr(mut self, disable: bool) -> Self {
2186        self.skip_ocr = disable;
2187        self
2188    }
2189
2190    /// OCR every page from its rendered image even when the page carries an
2191    /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
2192    /// for text layers that exist but lie: broken encodings, subset fonts with
2193    /// garbage mappings, a scanned form with a few typed-in fields. Ignored
2194    /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
2195    /// `force_full_page_ocr` is a sub-option of `do_ocr`).
2196    pub fn force_full_page_ocr(mut self, force: bool) -> Self {
2197        self.force_full_page_ocr = force;
2198        self
2199    }
2200
2201    /// Which document regions feed the OCR — docling's `OcrMode` (#254). The
2202    /// default (`default` = `pdf_aware_layout_regions`) is the standard
2203    /// text-layer-aware behavior; `full_page`/`layout_regions` discard the
2204    /// text layer like [`force_full_page_ocr`](Self::force_full_page_ocr)
2205    /// (see [`ocr::OcrMode`] for why both map onto it). Whichever of the flag
2206    /// and the mode demands forcing wins, mirroring docling's
2207    /// `force_full_page_ocr` → `mode=full_page` bridge. `None` keeps the
2208    /// process default (`DOCLING_RS_OCR_MODE`, else `default`).
2209    pub fn ocr_mode(mut self, mode: Option<ocr::OcrMode>) -> Self {
2210        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
2211        self
2212    }
2213
2214    /// In-place variants of [`force_full_page_ocr`](Self::force_full_page_ocr),
2215    /// [`ocr_mode`](Self::ocr_mode) and [`ocr_scale`](Self::ocr_scale) for a
2216    /// long-lived pipeline (docling-serve's warm instance): all three are pure
2217    /// per-worker configuration — no model reloads — so they apply per request
2218    /// like [`set_pages`](Self::set_pages). Set them before every conversion so
2219    /// no request inherits a previous one's choice.
2220    pub fn set_force_full_page_ocr(&mut self, force: bool) {
2221        self.force_full_page_ocr = force;
2222        self.sync_ocr_config();
2223    }
2224
2225    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
2226    pub fn set_ocr_mode(&mut self, mode: Option<ocr::OcrMode>) {
2227        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
2228        self.sync_ocr_config();
2229    }
2230
2231    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
2232    pub fn set_ocr_scale(&mut self, scale: Option<f32>) {
2233        self.ocr_scale = scale
2234            .filter(|s| s.is_finite() && *s > 0.0)
2235            .or_else(ocr::scale_from_env);
2236        self.sync_ocr_config();
2237    }
2238
2239    /// Whether page extraction should decode the text layer at all. Forced
2240    /// full-page OCR (the flag or `ocr_mode=full_page|layout_regions`) clears
2241    /// every extracted cell unread, so the decode is skipped outright —
2242    /// docling#4061's `skip_cell_extraction` (2.122). `no_ocr` wins over the
2243    /// forcing, as everywhere else: its fast path *is* the text layer.
2244    fn extract_text_layer(&self) -> bool {
2245        self.no_ocr || !(self.force_full_page_ocr || self.ocr_mode.forces_full_page())
2246    }
2247
2248    /// Push the current OCR forcing/scale choice onto already-loaded workers
2249    /// (new workers read it at [`Worker::load`]).
2250    fn sync_ocr_config(&mut self) {
2251        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2252        let scale = self.ocr_scale;
2253        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
2254            worker.force_full_page_ocr = force;
2255            worker.ocr_scale = scale;
2256        }
2257    }
2258
2259    /// OCR render scale in pixels per PDF point — docling's `OcrOptions.scale`
2260    /// (#254, upstream docling#3877; their default 3 = 216 dpi). `None`
2261    /// (default: `DOCLING_RS_OCR_SCALE`, else unset) feeds the recognizer the
2262    /// pipeline's own page render (2.0 px/pt = 144 dpi); a different value
2263    /// resamples that render for the OCR input only — layout and TableFormer
2264    /// keep their pinned-resolution pixels, so the conformance baseline never
2265    /// moves. Lower it when the source raster is already high-resolution and
2266    /// upscaling degrades recognition; raise it toward docling's 216 dpi for
2267    /// parity experiments. Non-positive values are ignored.
2268    pub fn ocr_scale(mut self, scale: Option<f32>) -> Self {
2269        self.ocr_scale = scale
2270            .filter(|s| s.is_finite() && *s > 0.0)
2271            .or_else(ocr::scale_from_env);
2272        self
2273    }
2274
2275    /// The shared TableFormer slot handed to each worker, or `None` when the
2276    /// pipeline options skip TableFormer entirely.
2277    fn tables_slot(&self) -> Option<SharedTables> {
2278        if self.no_table_former || self.no_ocr {
2279            None
2280        } else {
2281            Some(Arc::clone(&self.tables))
2282        }
2283    }
2284
2285    /// The shared enrichment slots for a worker (`None` per model unless its
2286    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
2287    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
2288        if self.no_ocr || !self.enrich.any() {
2289            return (None, None);
2290        }
2291        (
2292            self.enrich
2293                .picture_classification
2294                .then(|| Arc::clone(&self.classifier)),
2295            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
2296        )
2297    }
2298
2299    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
2300    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
2301    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
2302    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
2303    /// `DocumentConverter.initialize_pipeline`.
2304    pub fn warm_up(&mut self) -> Result<(), PdfError> {
2305        self.primary()?;
2306        Ok(())
2307    }
2308
2309    /// The full-intra serial worker, loaded on first use.
2310    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
2311        if self.primary.is_none() {
2312            self.primary = Some(Worker::load(
2313                intra_threads(),
2314                self.tables_slot(),
2315                self.enrich_slots(),
2316                self.enrich,
2317                self.no_ocr,
2318                self.skip_ocr,
2319                // The mode-shaped spelling (#254) and the flag are one engine
2320                // truth: whichever demands forcing wins, mirroring docling's
2321                // `force_full_page_ocr` → `mode=full_page` bridge.
2322                self.force_full_page_ocr || self.ocr_mode.forces_full_page(),
2323                self.no_text_panels,
2324                self.ocr_lang,
2325                self.ocr_engine,
2326                self.tesseract_lang.clone(),
2327                self.ocr_scale,
2328            )?);
2329        }
2330        Ok(self.primary.as_mut().unwrap())
2331    }
2332
2333    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
2334    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
2335    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
2336    /// fans the pages out across the worker pool, reassembled in page order so the
2337    /// output is byte-identical to the serial path.
2338    pub fn convert(
2339        &mut self,
2340        bytes: &[u8],
2341        password: Option<&str>,
2342        name: &str,
2343    ) -> Result<DoclingDocument, PdfError> {
2344        let pages = pdfium_backend::page_count(bytes, password)?;
2345        let range = self.resolve_range(pages)?;
2346        // Serial vs parallel is decided by the pages actually converted: a
2347        // 3-page window over a 500-page PDF should not pay the pool load.
2348        let selected = range.map_or(pages, |(a, b)| b - a + 1);
2349        let doc = if self.target_workers >= 2 && selected >= self.parallel_min {
2350            self.convert_parallel(bytes, password, name, range, selected)?
2351        } else {
2352            self.convert_serial(bytes, password, name, range, selected)?
2353        };
2354        timing::report();
2355        Ok(doc)
2356    }
2357
2358    /// Stream pages one at a time through the primary worker — render → process →
2359    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
2360    fn convert_serial(
2361        &mut self,
2362        bytes: &[u8],
2363        password: Option<&str>,
2364        name: &str,
2365        range: Option<(usize, usize)>,
2366        selected: usize,
2367    ) -> Result<DoclingDocument, PdfError> {
2368        let mut doc = DoclingDocument::new(name);
2369        let mut confs = std::collections::BTreeMap::new();
2370        let render_image = !self.no_ocr;
2371        let extract_text = self.extract_text_layer();
2372        let progress = self.progress.clone();
2373        let mut done = 0usize;
2374        let worker = self.primary()?;
2375        pdfium_backend::for_each_page(
2376            bytes,
2377            password,
2378            render_image,
2379            extract_text,
2380            range,
2381            |n, _total, mut page| {
2382                let (mut nodes, links, conf) = worker.process(n, &mut page)?;
2383                assemble::stamp_page_no(&mut nodes, n + 1);
2384                doc.nodes.extend(nodes);
2385                doc.links.extend(links);
2386                confs.insert(n + 1, conf);
2387                if let Some(cb) = &progress {
2388                    done += 1;
2389                    cb(done, selected);
2390                }
2391                Ok::<(), PdfError>(())
2392            },
2393        )?;
2394        assemble::merge_continuations(&mut doc.nodes);
2395        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
2396        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2397        Ok(doc)
2398    }
2399
2400    /// Render pages serially on this thread (pdfium) and process them in parallel
2401    /// across the worker pool. A bounded channel applies backpressure so only a
2402    /// handful of page bitmaps are resident at once; results carry their page
2403    /// index and are reassembled in order, so the output is byte-identical to the
2404    /// serial path.
2405    fn convert_parallel(
2406        &mut self,
2407        bytes: &[u8],
2408        password: Option<&str>,
2409        name: &str,
2410        range: Option<(usize, usize)>,
2411        selected: usize,
2412    ) -> Result<DoclingDocument, PdfError> {
2413        self.ensure_pool()?;
2414        let progress = self.progress.clone();
2415        let pages_done = std::sync::atomic::AtomicUsize::new(0);
2416        let n_workers = self.pool.len();
2417        let render_image = !self.no_ocr;
2418        let extract_text = self.extract_text_layer();
2419        let layout_batch = pdf_layout_batch();
2420        // Bound sized so every worker can accumulate a full layout batch while
2421        // rendering stays ahead (and never below the pre-#73 render-ahead of
2422        // two pages per worker); still a hard cap on resident page bitmaps.
2423        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2424        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2425        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
2426        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
2427
2428        // Move the pool into the scope so each worker gets an exclusive `&mut`.
2429        let mut workers = std::mem::take(&mut self.pool);
2430        std::thread::scope(|s| {
2431            for worker in workers.iter_mut() {
2432                let work_rx = Arc::clone(&work_rx);
2433                let results = Arc::clone(&results);
2434                let first_err = Arc::clone(&first_err);
2435                let progress = progress.clone();
2436                let pages_done = &pages_done;
2437                s.spawn(move || {
2438                    worker.run_pool(&work_rx, layout_batch, |idx, out| {
2439                        match out {
2440                            Ok(out) => {
2441                                results.lock().unwrap().push((idx, out));
2442                                if let Some(cb) = &progress {
2443                                    let d = pages_done
2444                                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2445                                        + 1;
2446                                    cb(d, selected);
2447                                }
2448                            }
2449                            Err(e) => {
2450                                let mut slot = first_err.lock().unwrap();
2451                                if slot.is_none() {
2452                                    *slot = Some(e);
2453                                }
2454                            }
2455                        }
2456                        true
2457                    });
2458                });
2459            }
2460            // Render on this thread and feed the workers; backpressure blocks here
2461            // when the channel is full. Dropping `work_tx` afterwards signals the
2462            // workers (recv → Err) to finish.
2463            let render = pdfium_backend::for_each_page(
2464                bytes,
2465                password,
2466                render_image,
2467                extract_text,
2468                range,
2469                |i, _total, page| {
2470                    work_tx
2471                        .send((i, page))
2472                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2473                },
2474            );
2475            drop(work_tx);
2476            if let Err(e) = render {
2477                let mut slot = first_err.lock().unwrap();
2478                if slot.is_none() {
2479                    *slot = Some(e);
2480                }
2481            }
2482        });
2483        // Threads have joined; restore the pool for the next conversion.
2484        self.pool = workers;
2485
2486        if let Some(e) = first_err.lock().unwrap().take() {
2487            return Err(e);
2488        }
2489        let mut results = Arc::try_unwrap(results)
2490            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
2491            .into_inner()
2492            .unwrap();
2493        results.sort_by_key(|(idx, _)| *idx);
2494        let mut doc = DoclingDocument::new(name);
2495        let mut confs = std::collections::BTreeMap::new();
2496        for (idx, (mut nodes, links, conf)) in results {
2497            assemble::stamp_page_no(&mut nodes, idx + 1);
2498            doc.nodes.extend(nodes);
2499            doc.links.extend(links);
2500            confs.insert(idx + 1, conf);
2501        }
2502        assemble::merge_continuations(&mut doc.nodes);
2503        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
2504        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2505        Ok(doc)
2506    }
2507
2508    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
2509    /// in-document-order batch of nodes (and that span's recovered links) as pages
2510    /// complete, so a caller can serialize Markdown page by page instead of waiting
2511    /// for the whole document. The batches are exactly the buffered [`convert`]'s
2512    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
2513    /// parallel path reorders pages back into document order before emitting, so
2514    /// the output is identical regardless of worker scheduling.
2515    ///
2516    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
2517    /// and its backpressure throttles the whole pipeline. Returning `Err` from
2518    /// `emit` aborts the conversion with that error.
2519    pub fn convert_streaming<F>(
2520        &mut self,
2521        bytes: &[u8],
2522        password: Option<&str>,
2523        name: &str,
2524        emit: F,
2525    ) -> Result<(), PdfError>
2526    where
2527        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2528    {
2529        let _ = name; // page nodes carry no name; the caller owns the document name.
2530        let pages = pdfium_backend::page_count(bytes, password)?;
2531        let range = self.resolve_range(pages)?;
2532        let selected = range.map_or(pages, |(a, b)| b - a + 1);
2533        let r = if self.target_workers >= 2 && selected >= self.parallel_min {
2534            self.convert_streaming_parallel(bytes, password, range, emit)
2535        } else {
2536            self.convert_streaming_serial(bytes, password, range, emit)
2537        };
2538        timing::report();
2539        r
2540    }
2541
2542    /// Serial streaming: render → process → emit, one page at a time, holding back
2543    /// only the tail that might still merge into the next page.
2544    fn convert_streaming_serial<F>(
2545        &mut self,
2546        bytes: &[u8],
2547        password: Option<&str>,
2548        range: Option<(usize, usize)>,
2549        mut emit: F,
2550    ) -> Result<(), PdfError>
2551    where
2552        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2553    {
2554        let mut asm = assemble::StreamAssembler::new();
2555        let render_image = !self.no_ocr;
2556        let extract_text = self.extract_text_layer();
2557        let worker = self.primary()?;
2558        pdfium_backend::for_each_page(
2559            bytes,
2560            password,
2561            render_image,
2562            extract_text,
2563            range,
2564            |n, _total, mut page| {
2565                // Confidence is dropped on the streaming path: the report is
2566                // only complete once every page has run, which defeats
2567                // page-by-page emission — buffered `convert` carries it.
2568                let (nodes, links, _conf) = worker.process(n, &mut page)?;
2569                emit(asm.push(nodes), links)
2570            },
2571        )?;
2572        emit(asm.finish(), Vec::new())
2573    }
2574
2575    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
2576    /// not thread-safe) and process across the worker pool; results carry their
2577    /// page index and are reordered on the calling thread into a
2578    /// [`assemble::StreamAssembler`], which emits each page in document order as
2579    /// soon as its predecessors have arrived. Bounded channels keep only a handful
2580    /// of pages resident and let `emit`'s backpressure reach the renderer.
2581    fn convert_streaming_parallel<F>(
2582        &mut self,
2583        bytes: &[u8],
2584        password: Option<&str>,
2585        range: Option<(usize, usize)>,
2586        mut emit: F,
2587    ) -> Result<(), PdfError>
2588    where
2589        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
2590    {
2591        self.ensure_pool()?;
2592        let n_workers = self.pool.len();
2593        let render_image = !self.no_ocr;
2594        let extract_text = self.extract_text_layer();
2595        let layout_batch = pdf_layout_batch();
2596        // Bound sized so every worker can accumulate a full layout batch while
2597        // rendering stays ahead (and never below the pre-#73 render-ahead of
2598        // two pages per worker); still a hard cap on resident page bitmaps.
2599        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
2600        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
2601        // Workers and the renderer report here; the calling thread drains it in
2602        // page order. Bounded so workers block (bounding resident bitmaps) when the
2603        // consumer falls behind.
2604        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
2605
2606        let mut workers = std::mem::take(&mut self.pool);
2607        let mut asm = assemble::StreamAssembler::new();
2608        let mut first_err: Option<PdfError> = None;
2609
2610        std::thread::scope(|s| {
2611            // Workers: pull a batch of pages (whatever is already rendered, up
2612            // to the layout batch size), process it, report (index-tagged)
2613            // results.
2614            for worker in workers.iter_mut() {
2615                let work_rx = Arc::clone(&work_rx);
2616                let res_tx = res_tx.clone();
2617                s.spawn(move || {
2618                    worker.run_pool(&work_rx, layout_batch, |idx, out| {
2619                        // `false` once the consumer is gone.
2620                        res_tx.send(out.map(|o| (idx, o))).is_ok()
2621                    });
2622                });
2623            }
2624            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
2625            // single thread); report a render error through the same channel.
2626            {
2627                let res_tx = res_tx.clone();
2628                s.spawn(move || {
2629                    let render = pdfium_backend::for_each_page(
2630                        bytes,
2631                        password,
2632                        render_image,
2633                        extract_text,
2634                        range,
2635                        |i, _total, page| {
2636                            work_tx
2637                                .send((i, page))
2638                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
2639                        },
2640                    );
2641                    drop(work_tx); // signal workers to finish
2642                    if let Err(e) = render {
2643                        let _ = res_tx.send(Err(e));
2644                    }
2645                });
2646            }
2647            // Drop our own sender so the channel closes once the threads finish.
2648            drop(res_tx);
2649
2650            // Collector (this thread): reorder into document order and emit.
2651            // With a page window, indices start at the window's first page.
2652            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
2653            let mut next = range.map_or(0, |(first, _)| first);
2654            for msg in res_rx.iter() {
2655                match msg {
2656                    Err(e) => {
2657                        if first_err.is_none() {
2658                            first_err = Some(e);
2659                        }
2660                    }
2661                    Ok((idx, out)) => {
2662                        buffer.insert(idx, out);
2663                        if first_err.is_some() {
2664                            continue; // keep draining so the threads can exit
2665                        }
2666                        while let Some((nodes, links, _conf)) = buffer.remove(&next) {
2667                            if let Err(e) = emit(asm.push(nodes), links) {
2668                                first_err = Some(e);
2669                                break;
2670                            }
2671                            next += 1;
2672                        }
2673                    }
2674                }
2675            }
2676        });
2677        // Threads have joined; restore the pool for the next conversion.
2678        self.pool = workers;
2679
2680        if let Some(e) = first_err {
2681            return Err(e);
2682        }
2683        emit(asm.finish(), Vec::new())
2684    }
2685
2686    /// Lazily grow the pool to `target_workers`, loading the new workers
2687    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
2688    /// one load's wall-time). Cached for reuse across documents.
2689    fn ensure_pool(&mut self) -> Result<(), PdfError> {
2690        let need = self.target_workers.saturating_sub(self.pool.len());
2691        if need == 0 {
2692            return Ok(());
2693        }
2694        let intra = pdf_intra();
2695        let no_ocr = self.no_ocr;
2696        let skip_ocr = self.skip_ocr;
2697        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
2698        let ntp = self.no_text_panels;
2699        let ocr_lang = self.ocr_lang;
2700        let ocr_engine = self.ocr_engine;
2701        let tesseract_lang = self.tesseract_lang.clone();
2702        let ocr_scale = self.ocr_scale;
2703        let enrich = self.enrich;
2704        let tables = self.tables_slot();
2705        let enrich_slots = self.enrich_slots();
2706        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
2707            let handles: Vec<_> = (0..need)
2708                .map(|_| {
2709                    let tables = tables.clone();
2710                    let enrich_slots = enrich_slots.clone();
2711                    let tesseract_lang = tesseract_lang.clone();
2712                    s.spawn(move || {
2713                        Worker::load(
2714                            intra,
2715                            tables,
2716                            enrich_slots,
2717                            enrich,
2718                            no_ocr,
2719                            skip_ocr,
2720                            force,
2721                            ntp,
2722                            ocr_lang,
2723                            ocr_engine,
2724                            tesseract_lang,
2725                            ocr_scale,
2726                        )
2727                    })
2728                })
2729                .collect();
2730            handles.into_iter().map(|h| h.join().unwrap()).collect()
2731        });
2732        for w in loaded {
2733            self.pool.push(w?);
2734        }
2735        Ok(())
2736    }
2737
2738    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
2739    /// docling routes images through the same layout+OCR pipeline as a PDF page.
2740    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2741        let image = decode_image_limited(bytes)?;
2742        let (w, h) = image.dimensions();
2743        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
2744        // standalone image has no text layer, so OCR supplies the cells.
2745        let page = PdfPage {
2746            width: w as f32,
2747            height: h as f32,
2748            scale: 1.0,
2749            cells: Vec::new(),
2750            code_cells: Vec::new(),
2751            word_cells: Vec::new(),
2752            // A standalone image *is* its own scale-1.0 page image, so the
2753            // layout model sees it through the docling-exact PIL kernel.
2754            image_layout: Some(image.clone()),
2755            image,
2756            links: Vec::new(),
2757            rotation: 0,
2758        };
2759        self.process_pages(vec![page], name)
2760    }
2761
2762    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
2763    /// page (image / METS inputs, which are small and already materialised).
2764    /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
2765    /// caller-configured pipeline (#244).
2766    pub fn process_pages(
2767        &mut self,
2768        mut pages: Vec<PdfPage>,
2769        name: &str,
2770    ) -> Result<DoclingDocument, PdfError> {
2771        let mut doc = DoclingDocument::new(name);
2772        let mut confs = std::collections::BTreeMap::new();
2773        let worker = self.primary()?;
2774        for (n, page) in pages.iter_mut().enumerate() {
2775            let (mut nodes, links, conf) = worker.process(n, page)?;
2776            assemble::stamp_page_no(&mut nodes, n + 1);
2777            doc.nodes.extend(nodes);
2778            doc.links.extend(links);
2779            confs.insert(n + 1, conf);
2780        }
2781        assemble::merge_continuations(&mut doc.nodes);
2782        // No PDF behind these pages (images, METS): the heading-hierarchy
2783        // stage degrades to the numbering signal — exactly docling without
2784        // an outline or parsed pages.
2785        self.apply_heading_hierarchy(&mut doc.nodes, None);
2786        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
2787        Ok(doc)
2788    }
2789}
2790
2791/// Number of pages in a PDF, without converting anything — what the CLI batch
2792/// mode prints in its per-document start line.
2793#[cfg(feature = "ml")]
2794pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
2795    pdfium_backend::page_count(bytes, password)
2796}
2797
2798#[cfg(feature = "ml")]
2799/// Convenience one-shot conversion (loads the pipeline per call). Errors are
2800/// detailed and surfaced (never silently skipped).
2801pub fn convert(
2802    bytes: &[u8],
2803    password: Option<&str>,
2804    name: &str,
2805) -> Result<DoclingDocument, PdfError> {
2806    convert_with_options(
2807        bytes,
2808        password,
2809        name,
2810        false,
2811        false,
2812        false,
2813        false,
2814        EnrichmentOptions::default(),
2815        None,
2816        None,
2817    )
2818}
2819
2820#[cfg(feature = "ml")]
2821/// Like [`convert`], but optionally skips loading/running TableFormer (see
2822/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2823/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
2824/// [`Pipeline::enrichments`]).
2825// One positional per pipeline switch mirrors the Pipeline builder; growing
2826// past clippy's arity cap is the price of keeping this one-shot signature
2827// stable-ish instead of churning callers into an options struct mid-series.
2828#[allow(clippy::too_many_arguments)]
2829pub fn convert_with_options(
2830    bytes: &[u8],
2831    password: Option<&str>,
2832    name: &str,
2833    no_table_former: bool,
2834    no_ocr: bool,
2835    force_full_page_ocr: bool,
2836    no_text_panels: bool,
2837    enrich: EnrichmentOptions,
2838    pages: Option<(usize, usize)>,
2839    ocr_lang: Option<OcrLang>,
2840) -> Result<DoclingDocument, PdfError> {
2841    Pipeline::new()?
2842        .no_table_former(no_table_former)
2843        .no_ocr(no_ocr)
2844        .force_full_page_ocr(force_full_page_ocr)
2845        .no_text_panels(no_text_panels)
2846        .enrichments(enrich)
2847        .pages(pages)
2848        .ocr_lang(ocr_lang)
2849        .convert(bytes, password, name)
2850}
2851
2852#[cfg(feature = "ml")]
2853/// Convenience one-shot image conversion (loads the pipeline per call).
2854pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
2855    convert_image_with_options(
2856        bytes,
2857        name,
2858        false,
2859        false,
2860        false,
2861        EnrichmentOptions::default(),
2862        None,
2863    )
2864}
2865
2866#[cfg(feature = "ml")]
2867/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
2868/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2869/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2870pub fn convert_image_with_options(
2871    bytes: &[u8],
2872    name: &str,
2873    no_table_former: bool,
2874    no_ocr: bool,
2875    no_text_panels: bool,
2876    enrich: EnrichmentOptions,
2877    ocr_lang: Option<OcrLang>,
2878) -> Result<DoclingDocument, PdfError> {
2879    Pipeline::new()?
2880        .no_table_former(no_table_former)
2881        .no_ocr(no_ocr)
2882        .no_text_panels(no_text_panels)
2883        .enrichments(enrich)
2884        .ocr_lang(ocr_lang)
2885        .convert_image(bytes, name)
2886}
2887
2888#[cfg(feature = "ml")]
2889/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
2890/// scans) through the shared layout + assembly pipeline.
2891pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
2892    convert_pages_with_options(
2893        pages,
2894        name,
2895        false,
2896        false,
2897        false,
2898        EnrichmentOptions::default(),
2899    )
2900}
2901
2902#[cfg(feature = "ml")]
2903/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
2904/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
2905/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
2906pub fn convert_pages_with_options(
2907    pages: Vec<PdfPage>,
2908    name: &str,
2909    no_table_former: bool,
2910    no_ocr: bool,
2911    no_text_panels: bool,
2912    enrich: EnrichmentOptions,
2913) -> Result<DoclingDocument, PdfError> {
2914    Pipeline::new()?
2915        .no_table_former(no_table_former)
2916        .no_text_panels(no_text_panels)
2917        .no_ocr(no_ocr)
2918        .enrichments(enrich)
2919        .process_pages(pages, name)
2920}
2921
2922#[cfg(feature = "ml")]
2923#[cfg(all(test, feature = "ml"))]
2924mod image_limit_tests {
2925    use super::decode_image_with_max_side;
2926
2927    /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
2928    /// byte literal).
2929    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
2930        use std::io::Cursor;
2931        let img = image::RgbImage::new(w, h);
2932        let mut out = Vec::new();
2933        img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
2934            .unwrap();
2935        out
2936    }
2937
2938    #[test]
2939    fn normal_image_decodes_under_the_cap() {
2940        let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
2941        assert_eq!(img.dimensions(), (8, 8));
2942    }
2943
2944    /// docling#4247 (2.128): the EXIF orientation is applied when a frame is
2945    /// loaded — a 4×2 JPEG tagged "rotate 90° CW" (orientation 6) decodes as
2946    /// 2×4, with the pixels turned.
2947    #[test]
2948    fn exif_orientation_is_applied() {
2949        use std::io::Cursor;
2950        let mut img = image::RgbImage::new(4, 2);
2951        img.put_pixel(0, 0, image::Rgb([255, 0, 0]));
2952        let mut jpeg = Vec::new();
2953        img.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
2954            .unwrap();
2955        // Splice an APP1 Exif segment (little-endian TIFF, one IFD entry:
2956        // Orientation = 6) right after the SOI marker.
2957        let mut tiff = b"II*\0".to_vec();
2958        tiff.extend(8u32.to_le_bytes());
2959        tiff.extend(1u16.to_le_bytes());
2960        tiff.extend(0x0112u16.to_le_bytes());
2961        tiff.extend(3u16.to_le_bytes());
2962        tiff.extend(1u32.to_le_bytes());
2963        tiff.extend(6u16.to_le_bytes());
2964        tiff.extend([0, 0]);
2965        tiff.extend(0u32.to_le_bytes());
2966        let mut app1 = b"Exif\0\0".to_vec();
2967        app1.extend(tiff);
2968        let mut out = jpeg[..2].to_vec();
2969        out.extend([0xff, 0xe1]);
2970        out.extend((app1.len() as u16 + 2).to_be_bytes());
2971        out.extend(app1);
2972        out.extend(&jpeg[2..]);
2973        let plain = decode_image_with_max_side(&jpeg, 30_000).unwrap();
2974        assert_eq!(plain.dimensions(), (4, 2));
2975        let turned = decode_image_with_max_side(&out, 30_000).unwrap();
2976        assert_eq!(turned.dimensions(), (2, 4), "quarter turn swaps the sides");
2977        // Rotating 90° CW moves the top-left pixel to the top-right corner.
2978        assert!(turned.get_pixel(1, 0).0[0] > 128);
2979        assert!(turned.get_pixel(0, 0).0[0] <= 128);
2980    }
2981
2982    #[test]
2983    fn dimensions_over_the_cap_are_rejected_not_aborted() {
2984        // A per-side cap below the image's declared size must yield a
2985        // recoverable Err, never an allocation-abort — the mechanism that stops
2986        // a crafted image declaring 60000×60000 from OOM-killing the process.
2987        let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
2988        assert!(
2989            r.is_err(),
2990            "decode must fail under the pixel cap, not abort"
2991        );
2992    }
2993}
2994
2995#[cfg(test)]
2996mod median_tests {
2997    #[test]
2998    fn median_of_empty_is_zero_not_a_panic() {
2999        // A crafted table can leave a row/column with zero matched cells; the
3000        // even-count branch would index values[0 - 1] and panic (→ remote crash
3001        // via docling-serve) without the empty guard.
3002        assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
3003        assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
3004        assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
3005    }
3006}
3007
3008#[cfg(test)]
3009mod send_check {
3010    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
3011    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
3012    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
3013    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
3014    fn assert_send<T: Send>() {}
3015
3016    #[test]
3017    fn pipeline_is_send() {
3018        assert_send::<super::Pipeline>();
3019    }
3020}
3021
3022#[cfg(all(test, feature = "ml"))]
3023mod ocr_input_tests {
3024    /// #254: without an `ocr_scale` (or with one equal to the render scale)
3025    /// the OCR reads the page render untouched and the cache stays cold; a
3026    /// different scale builds one resampled view, reuses it across calls, and
3027    /// reports the requested px/pt so cell geometry divides back to points.
3028    #[test]
3029    fn ocr_input_resamples_only_on_a_real_scale_change() {
3030        let img = image::RgbImage::new(200, 100);
3031        let mut cache = None;
3032        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, None);
3033        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
3034        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(2.0));
3035        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
3036
3037        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
3038        assert_eq!((v.width(), v.height(), s), (300, 150, 3.0));
3039        let first = cache.as_ref().map(|c| c as *const image::RgbImage);
3040        let (v, _) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
3041        assert_eq!(
3042            Some(v as *const image::RgbImage),
3043            first,
3044            "cached, not rebuilt"
3045        );
3046
3047        let mut down = None;
3048        let (v, s) = super::ocr_input(&mut down, &img, 2.0, Some(1.0));
3049        assert_eq!((v.width(), v.height(), s), (100, 50, 1.0));
3050    }
3051}