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
17mod adobe_glyph_list;
18// Reading-order assembly. Public under `ocr-prep` so the browser pipeline can
19// reuse the geometric table reconstruction and its reliability gate (#157).
20#[cfg(feature = "ocr-prep")]
21pub mod assemble;
22#[cfg(not(feature = "ocr-prep"))]
23mod assemble;
24// Vector checkbox squares from the text parser's path walk (#609).
25pub mod checkbox;
26mod dp_lines;
27#[cfg(feature = "ml")]
28pub mod enrich;
29// Public so sibling crates (e.g. docling-rag's ONNX embedder) can route their
30// own `ort` sessions through the same `DOCLING_RS_EP` selection. Kept as a
31// re-export after the logic moved to the shared `docling-onnx` crate —
32// `docling_pdf::ep::…` remains the stable path downstream crates code against.
33#[cfg(feature = "ml")]
34pub use docling_onnx as ep;
35// Heading-hierarchy stage (#302): PDF font-name style parsing, outline
36// extraction (pure lopdf), and the level-assignment pass. No feature gate on
37// the logic itself — only the glyph style pass needs pdfium (`ml`).
38#[cfg(feature = "render")]
39pub mod dparse_render;
40mod font_style;
41mod heading_hierarchy;
42pub mod layout;
43#[cfg(feature = "ml")]
44mod mets;
45#[cfg(feature = "ner")]
46pub mod ner;
47mod numbering_lexicon;
48#[cfg(feature = "ml")]
49mod ocr;
50#[cfg(feature = "ml")]
51mod ocr_cls;
52#[cfg(any(feature = "ml", feature = "ocr-prep"))]
53pub mod ocr_det;
54#[cfg(feature = "ocr-prep")]
55pub mod ocr_prep;
56// HEIC/HEIF decoding (#211, #1249): heifer, pure Rust — the native image
57// pipeline and the browser OCR build share it.
58#[cfg(feature = "heif")]
59pub mod heif;
60#[cfg(feature = "ml")]
61mod orient;
62pub mod outline;
63pub mod pdfium_backend;
64#[cfg(feature = "ml")]
65pub mod picture;
66#[cfg(feature = "ml")]
67pub mod quality;
68mod reading_order;
69#[cfg(feature = "ml")]
70mod redact_ocr;
71// Pure-Rust region resampling (page→1024px box-average, crop→448 bilinear) —
72// available to the browser TableFormer path (#157 stage 3), not just `ml`.
73#[cfg(feature = "ocr-prep")]
74pub mod resample;
75#[cfg(feature = "ocr-prep")]
76pub mod scanned;
77// Built-in standard-14 font metrics for the pure-Rust text parser (#187) —
78// no feature gate: the wasm/pdf-text path needs them like the native one.
79pub mod info;
80pub mod pdf_meta;
81// What the reader repaired to read a file (#934) — typed provenance, on
82// demand; pure Rust like `pdf_meta`.
83pub mod repairs;
84pub use repairs::{pdf_repairs, try_pdf_repairs, PdfRepair, RepairInspectError};
85// Embedded images as picture images (#1007, `use_embedded_picture_images`).
86#[cfg(feature = "render")]
87pub mod embedded;
88mod encodings;
89mod glyph_names;
90#[cfg(feature = "render")]
91pub mod raster;
92#[cfg(feature = "render")]
93pub mod render;
94mod script_position;
95mod std14;
96mod symbol_fonts;
97#[cfg(feature = "ml")]
98mod table_tokens;
99#[cfg(feature = "ml")]
100pub mod tableformer;
101#[cfg(feature = "ml")]
102mod tesseract;
103pub mod textparse;
104#[cfg(feature = "ocr-prep")]
105pub mod tf_core;
106// docling's TableFormer cell matcher — pure Rust, shared with the browser
107// TableFormer path (#157 stage 3).
108#[cfg(feature = "ocr-prep")]
109pub mod tf_match;
110pub mod timing;
111mod tounicode;
112
113#[cfg(feature = "ml")]
114use std::collections::BTreeMap;
115use std::fmt;
116#[cfg(feature = "ml")]
117use std::sync::mpsc::{sync_channel, Receiver};
118#[cfg(feature = "ml")]
119use std::sync::{Arc, Mutex};
120
121// An execution provider only exists on its OS, and ort's prebuilt ONNX
122// Runtime binaries follow suit — requesting an impossible pairing otherwise
123// surfaces as a cryptic ort-sys linker error ("no builds available that
124// satisfy the requested feature set"). Catch it at type-check time with an
125// actionable message instead.
126#[cfg(all(feature = "coreml", not(target_vendor = "apple")))]
127compile_error!(
128    "the `coreml` execution provider exists only on Apple targets (macOS/iOS). \
129     On Linux use `--features cuda` or `--features tensorrt` (NVIDIA), on \
130     Windows also `--features directml`, or build without EP features for CPU."
131);
132#[cfg(all(feature = "directml", not(target_os = "windows")))]
133compile_error!(
134    "the `directml` execution provider exists only on Windows. On Linux use \
135     `--features cuda` or `--features tensorrt` (NVIDIA), on macOS \
136     `--features coreml`, or build without EP features for CPU."
137);
138#[cfg(all(any(feature = "cuda", feature = "tensorrt"), target_vendor = "apple"))]
139compile_error!(
140    "the `cuda`/`tensorrt` execution providers have no Apple builds (no NVIDIA \
141     support on macOS). Use `--features coreml` there, or build without EP \
142     features for CPU."
143);
144
145use docling_core::DoclingDocument;
146pub use docling_core::EncryptionError;
147// The env-knob helpers only gate ML-pipeline diagnostics and tuning; the
148// pure text-layer (wasm) build has no call sites.
149#[cfg(feature = "ml")]
150use docling_core::Node;
151#[cfg(feature = "ml")]
152use docling_core::{debug_log, env};
153
154pub use dp_lines::WordGap;
155pub use heading_hierarchy::HeadingHierarchyOptions;
156#[cfg(feature = "ml")]
157pub use mets::{convert_mets_gbs, convert_mets_gbs_with_options, convert_mets_gbs_with_pipeline};
158#[cfg(feature = "ml")]
159pub use ocr::{OcrEngine, OcrLang, OcrMode, OcrModel, RecognizedLine};
160#[cfg(feature = "render")]
161pub use pdfium_backend::PdfDocument;
162pub use pdfium_backend::TextOptions;
163pub use pdfium_backend::{PdfPage, TextCell};
164#[cfg(feature = "ml")]
165pub use tesseract::{
166    installed_languages as tesseract_languages, lang_arg as tesseract_lang_arg, TesseractOptions,
167};
168// Plain page rasterization (#243) — pdfium only, no models.
169#[cfg(feature = "render")]
170pub use pdfium_backend::{render_pages, RenderedPage};
171#[cfg(feature = "ml")]
172pub use render::Omission;
173
174/// Errors from the PDF backend. Detailed and surfaced (never silently skipped).
175#[derive(Debug)]
176pub enum PdfError {
177    /// pdfium failed to bind, open, or read the document (and, historically,
178    /// any pipeline error outside the models).
179    Pdfium(String),
180    /// The document itself: an object model lopdf cannot read, a page no
181    /// renderer can draw, a page range outside it.
182    Document(String),
183    /// The layout ONNX model failed to load or run.
184    Layout(String),
185    /// The OCR ONNX model failed to load or run.
186    Ocr(String),
187    /// The document budget ([`Pipeline::document_timeout`]) ran out between
188    /// two pages. Internally the sentinel that stops the page walk; a caller
189    /// never sees it from [`Pipeline::convert`] — the conversion returns the
190    /// pages it finished and reports the cut through [`Completion`].
191    Timeout(String),
192    /// The document is encrypted and the password given (or none) does not
193    /// open it (#636) — the typed value a caller prompts for a password on,
194    /// reachable through [`std::error::Error::source`] too. Its text is the
195    /// one docling raises.
196    Encrypted(EncryptionError),
197    /// The conversion was cancelled through its [`CancelToken`]
198    /// ([`Pipeline::set_cancel`], #1260) before it finished.
199    Cancelled,
200}
201
202impl fmt::Display for PdfError {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        match self {
205            PdfError::Pdfium(m) => write!(f, "pdf: pdfium error: {m}"),
206            PdfError::Document(m) => write!(f, "pdf: {m}"),
207            PdfError::Layout(m) => write!(f, "pdf: {m}"),
208            PdfError::Ocr(m) => write!(f, "pdf: {m}"),
209            PdfError::Timeout(m) => write!(f, "pdf: {m}"),
210            PdfError::Encrypted(EncryptionError::WrongPassword) => {
211                f.write_str("pdf: the PDF is encrypted and the password is wrong")
212            }
213            PdfError::Encrypted(EncryptionError::NeedPassword) => {
214                f.write_str("pdf: the PDF is encrypted: a password is required")
215            }
216            PdfError::Encrypted(e) => write!(f, "pdf: the PDF is encrypted: {e}"),
217            PdfError::Cancelled => f.write_str("pdf: the conversion was cancelled"),
218        }
219    }
220}
221
222/// How a conversion ended: every selected page, or the pages that fit the
223/// document budget (docling's `document_timeout`, `PARTIAL_SUCCESS`).
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum Completion {
226    /// Every selected page was processed.
227    Complete,
228    /// The budget ran out: `pages_done` of `pages_selected` pages are in the
229    /// document, the rest were never rendered (or never processed).
230    TimedOut {
231        pages_done: usize,
232        pages_selected: usize,
233        budget: std::time::Duration,
234    },
235}
236
237/// One finished page, as the per-page progress hook
238/// ([`Pipeline::set_progress`]) reports it — docling's `PageCompletedProgress`
239/// minus the document fields the caller adds (#783).
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub struct PageProgress {
242    /// The page's 1-based number in the document: a page window keeps the
243    /// source numbering, so a `2-3` window reports pages 2 and 3.
244    pub page_no: usize,
245    /// Pages finished so far in this conversion, this one included. On the
246    /// parallel walks pages finish out of order, so this — not `page_no` —
247    /// drives a progress bar.
248    pub pages_done: usize,
249    /// Pages the conversion selected: the window's size, else the whole
250    /// document.
251    pub pages_selected: usize,
252}
253
254/// The per-page progress hook: shared with the parallel workers, so it must
255/// be cheap and thread-safe.
256pub type PageProgressHook = std::sync::Arc<dyn Fn(PageProgress) + Send + Sync>;
257
258impl Completion {
259    pub fn timed_out(&self) -> bool {
260        matches!(self, Completion::TimedOut { .. })
261    }
262
263    /// docling's `ErrorItem.error_message` for the cut, `None` when complete.
264    pub fn message(&self) -> Option<String> {
265        match self {
266            Completion::Complete => None,
267            Completion::TimedOut {
268                pages_done,
269                pages_selected,
270                budget,
271            } => Some(format!(
272                "document timeout of {:.3}s exceeded after {pages_done} of {pages_selected} \
273                 pages; the output holds the pages processed",
274                budget.as_secs_f64()
275            )),
276        }
277    }
278}
279
280/// A converted document and how its conversion ended ([`Completion`]).
281#[derive(Debug, Clone)]
282pub struct Converted {
283    pub document: DoclingDocument,
284    pub completion: Completion,
285}
286
287/// A cooperative cancellation flag for a running conversion (#1260): a
288/// clone handed to [`Pipeline::set_cancel`] and one kept by the caller, who
289/// [`cancel`](Self::cancel)s from any thread. It is checked where the
290/// [`document_timeout`](Pipeline::document_timeout) is — between pages, on
291/// the renderer and every worker — so a page in flight finishes and the walk
292/// stops before the next; the conversion then fails with
293/// [`PdfError::Cancelled`] instead of assembling a document nobody waits
294/// for. docling-serve cancels when the HTTP client goes away, which is what
295/// frees its one shared warm pipeline for the requests queued behind it.
296#[derive(Debug, Clone, Default)]
297pub struct CancelToken(std::sync::Arc<std::sync::atomic::AtomicBool>);
298
299impl CancelToken {
300    pub fn new() -> Self {
301        Self::default()
302    }
303
304    /// Ask the conversion to stop at its next page boundary. Idempotent.
305    pub fn cancel(&self) {
306        self.0.store(true, std::sync::atomic::Ordering::Relaxed);
307    }
308
309    pub fn is_cancelled(&self) -> bool {
310        self.0.load(std::sync::atomic::Ordering::Relaxed)
311    }
312}
313
314/// What ends a page walk early: the document budget's deadline (#497) and
315/// the caller's cancellation (#1260), checked together at the same page
316/// boundaries.
317#[derive(Debug, Clone, Default)]
318struct Budget {
319    deadline: Option<std::time::Instant>,
320    cancel: Option<CancelToken>,
321}
322
323impl Budget {
324    fn cancelled(&self) -> bool {
325        self.cancel.as_ref().is_some_and(CancelToken::is_cancelled)
326    }
327}
328
329/// Has the document budget run out, or the conversion been cancelled?
330/// Either stops the walk through the same sentinel; the caller tells them
331/// apart afterwards with [`Budget::cancelled`].
332fn expired(budget: &Budget) -> bool {
333    budget.cancelled()
334        || budget
335            .deadline
336            .is_some_and(|d| std::time::Instant::now() >= d)
337}
338
339/// The sentinel the page walks stop on once the budget is gone.
340fn timeout_sentinel() -> PdfError {
341    PdfError::Timeout("document timeout exceeded".into())
342}
343
344impl std::error::Error for PdfError {
345    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
346        match self {
347            PdfError::Encrypted(e) => Some(e),
348            _ => None,
349        }
350    }
351}
352
353#[cfg(feature = "pdfium")]
354impl From<pdfium_render::prelude::PdfiumError> for PdfError {
355    fn from(e: pdfium_render::prelude::PdfiumError) -> Self {
356        // A failed dlopen means the library this build was asked to use
357        // (`pdfium` feature) is not there. Say what to do instead of leaking
358        // the raw loader error.
359        if matches!(e, pdfium_render::prelude::PdfiumError::LoadLibraryError(_)) {
360            // The loader error pretty-prints over several lines; compact it.
361            let detail = e
362                .to_string()
363                .split_whitespace()
364                .collect::<Vec<_>>()
365                .join(" ");
366            return PdfError::Pdfium(format!(
367                "the pdfium library is not installed. This build's `pdfium` feature \
368                 was asked for it (DOCLING_RS_RENDERER=pdfium, or a file the pure-Rust \
369                 object model cannot read): point PDFIUM_DYNAMIC_LIB_PATH at a directory \
370                 containing the pdfium library, or unset DOCLING_RS_RENDERER — the \
371                 default renderer needs no library. Declarative formats (DOCX, HTML, \
372                 Markdown, …) never need it. [{detail}]"
373            ));
374        }
375        PdfError::Pdfium(e.to_string())
376    }
377}
378
379/// Convert a PDF's **embedded text layer only** — no ONNX, no
380/// threads: the pure-Rust content-stream parser ([`textparse`]) feeds the same
381/// orphan-region assembly the `no_ocr` pipeline flag uses, so text-layer PDFs
382/// come out identical to `--text-layer-only` (flat, line-grouped paragraphs in reading
383/// order; no headings/lists/tables/pictures, and no hyperlink recovery).
384///
385/// This is the only conversion entry compiled without the `ml` feature (it is
386/// what a wasm32 build runs). A scanned/image-only PDF (no embedded text
387/// layer) yields an empty document rather than an error, same as `no_ocr` —
388/// callers can detect that and fall back to an OCR-capable build.
389pub fn convert_text_layer(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
390    convert_text_layer_pages(bytes, name, None)
391}
392
393/// The error for bytes no reader here can parse as a PDF — not a PDF at
394/// all, or one damaged past the parser's repairs. Said about the file, not
395/// about a missing renderer or text layer: no library would read it either.
396pub(crate) const UNREADABLE: &str =
397    "not a readable PDF: the file is damaged or not a PDF (its structure could not be parsed)";
398
399/// [`convert_text_layer`] restricted to a **1-based inclusive** page window
400/// (issue #80's `--pages`); `None` converts everything. The window is
401/// validated the same way as [`Pipeline::pages`]: `first <= last`, 1-based,
402/// and it must select at least one existing page.
403pub fn convert_text_layer_pages(
404    bytes: &[u8],
405    name: &str,
406    pages: Option<(usize, usize)>,
407) -> Result<DoclingDocument, PdfError> {
408    convert_text_layer_pages_with(bytes, name, pages, None)
409}
410
411/// [`convert_text_layer_pages`] with the word-gap rule of the text layer's
412/// line and word contraction (#921, [`WordGap`]); `None` = the process
413/// default (`DOCLING_RS_PDF_WORD_GAP`, else [`WordGap::Adaptive`]).
414pub fn convert_text_layer_pages_with(
415    bytes: &[u8],
416    name: &str,
417    pages: Option<(usize, usize)>,
418    word_gap: Option<WordGap>,
419) -> Result<DoclingDocument, PdfError> {
420    convert_text_layer_pages_opts(
421        bytes,
422        name,
423        pages,
424        TextOptions {
425            word_gap,
426            ..TextOptions::from_env()
427        },
428    )
429}
430
431/// [`convert_text_layer_pages`] with every text-layer setting (#921): the
432/// word-gap rule and whether typographic punctuation is kept as drawn.
433pub fn convert_text_layer_pages_opts(
434    bytes: &[u8],
435    name: &str,
436    pages: Option<(usize, usize)>,
437    text: TextOptions,
438) -> Result<DoclingDocument, PdfError> {
439    if let Some((first, last)) = pages {
440        if first == 0 || last < first {
441            return Err(PdfError::Pdfium(format!(
442                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
443            )));
444        }
445    }
446    let mut doc = DoclingDocument::new(name);
447    // A file nothing can open is an error, not a PDF that merely has no
448    // text layer (the caller's "scanned? needs OCR" hint).
449    let Some(mut parser) = textparse::PageTextParser::open(bytes) else {
450        return Err(PdfError::Document(UNREADABLE.into()));
451    };
452    parser.set_word_gap(text.word_gap);
453    parser.set_keep_typography(Some(text.keep_typography));
454    // Pages are parsed, assembled and dropped one at a time: holding every
455    // page's cells until the end made the peak scale with the whole file —
456    // and a page window still paid for every page outside it.
457    let total = parser.page_count();
458    let mut tally = textparse::TextLayerTally::default();
459    for i in 0..total {
460        let selected = pages.is_none_or(|(first, last)| (first..=last).contains(&(i + 1)));
461        // A page outside the window only feeds the vestigial verdict below,
462        // so it is parsed only until that verdict is settled (on any real
463        // text layer, by the first page or two).
464        if !selected && tally.proves_text(total) {
465            continue;
466        }
467        let page = parser.text_page(i);
468        tally.add(&page);
469        if !selected {
470            continue;
471        }
472        let mut regions = Vec::new();
473        assemble::add_orphan_regions(&mut regions, &page.cells);
474        let table_rows = vec![None; regions.len()];
475        let enrich_out = vec![None; regions.len()];
476        let (mut nodes, links) =
477            assemble::assemble_page(&page, regions, &table_rows, &enrich_out, None);
478        assemble::float_running_head(&mut nodes, &page.cells);
479        assemble::stamp_page_no(&mut nodes, i + 1);
480        doc.nodes.extend(nodes);
481        doc.links.extend(links);
482    }
483    // A vestigial layer (a few typed-in form fields over scanned pages) is not
484    // the document's text: return the empty document, which callers already
485    // report as "no text layer" — so an OCR-capable caller falls back to OCR
486    // instead of proudly extracting thirteen characters.
487    if tally.is_vestigial() {
488        return Ok(DoclingDocument::new(name));
489    }
490    if let Some((first, last)) = pages {
491        if first > total {
492            return Err(PdfError::Pdfium(format!(
493                "page range {first}-{last} is outside the document ({total} page(s))"
494            )));
495        }
496    }
497    assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::Lines);
498    // Grown a page at a time, the node vector can be up to half spare
499    // capacity — hundreds of MB on a long document, held for its lifetime.
500    doc.nodes.shrink_to_fit();
501    Ok(doc)
502}
503
504/// Whether a PDF's embedded text layer is the document's text — the verdict
505/// behind [`Pipeline::text_layer_auto`]: `true` when the pages carry real
506/// text, `false` for a scanned / image-only file or a vestigial layer (a few
507/// typed-in form fields over scans; [`textparse::TextLayerTally`]'s rule,
508/// the one [`convert_text_layer`] answers with an empty document). Pure
509/// Rust, no render, no model: the pages are parsed only until the verdict
510/// is settled — on a digital document, by the first page or two; a scanned
511/// one is walked to the end, which is cheap (its content streams hold no
512/// text). Every page counts, not just a page window: the window is the
513/// caller's output selection, the document's nature is the whole file's.
514/// An unreadable file is an error, as on every other path.
515pub fn text_layer_has_text(bytes: &[u8], password: Option<&str>) -> Result<bool, PdfError> {
516    let Some(mut parser) = textparse::PageTextParser::open_with_password(bytes, password) else {
517        return Err(PdfError::Document(UNREADABLE.into()));
518    };
519    let total = parser.page_count();
520    let mut tally = textparse::TextLayerTally::default();
521    for i in 0..total {
522        if tally.proves_text(total) {
523            return Ok(true);
524        }
525        tally.add(&parser.text_page(i));
526    }
527    Ok(!tally.is_vestigial())
528}
529
530/// Threads ONNX inference may use, capped by `DOCLING_RS_PDF_THREADS` if set.
531/// Defaults to the available parallelism (ort otherwise picks a low number).
532#[cfg(feature = "ml")]
533pub(crate) fn intra_threads() -> usize {
534    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_THREADS").filter(|&n| n > 0) {
535        return n;
536    }
537    env::cpu_budget()
538}
539
540#[cfg(feature = "ml")]
541/// TableFormer's intra-op width (#262): `DOCLING_RS_TF_INTRA` explicitly,
542/// else the shared [`intra_threads`] budget. The shared TF session used to
543/// take the raw host width on top of the already-sized worker pools —
544/// under a cgroup CPU limit that oversubscription showed up as constant
545/// throttling and ~66% higher peak memory (each intra thread carries its own
546/// arena slab); the reporter's 4-CPU/8-core case dropped from 2.2 GB to
547/// 1.3 GB peak by capping this pool.
548pub(crate) fn tf_intra() -> usize {
549    if let Some(n) = env::parse::<usize>("DOCLING_RS_TF_INTRA").filter(|&n| n > 0) {
550        return n;
551    }
552    intra_threads()
553}
554
555#[cfg(feature = "ml")]
556/// True when `DOCLING_RS_FP32` forces the full-precision models even where
557/// an INT8 variant sits next to the fp32 default.
558pub(crate) fn fp32_forced() -> bool {
559    env::flag("DOCLING_RS_FP32")
560}
561
562#[cfg(feature = "ml")]
563/// Should the int8 model defaults be skipped in favor of fp32? Either the
564/// user said so (`DOCLING_RS_FP32`), or a GPU execution provider is selected
565/// (#74) — the int8 exports are QDQ graphs calibrated for CPU kernels and
566/// only conformance-validated there. An explicit `DOCLING_*_ONNX` path
567/// override still wins over this at every call site.
568pub(crate) fn prefer_fp32() -> bool {
569    fp32_forced() || docling_onnx::prefers_fp32()
570}
571
572#[cfg(feature = "render")]
573/// Resolve a default (CWD-relative) asset path — the shared chain in
574/// [`docling_core::assets`]: CWD, then next to the executable and one level
575/// above it (the `scripts/install/install.sh` layout).
576pub(crate) fn resolve_asset(rel: &str) -> String {
577    docling_core::assets::resolve(rel)
578}
579
580/// One resolved runtime asset — which file a stage would load right now,
581/// given the CWD, the env overrides and the int8/fp32 preference.
582#[cfg(feature = "ml")]
583#[derive(Debug, Clone)]
584pub struct ModelEntry {
585    /// Pipeline stage, e.g. `layout`, `tableformer.decoder`, `ocr.rec`.
586    pub stage: &'static str,
587    /// The resolved path (absolute or CWD-relative, as it will be opened).
588    pub path: String,
589    /// Whether the file exists right now.
590    pub found: bool,
591    /// File size in bytes (0 when missing) — enough to tell an int8 quant
592    /// from an fp32 graph, or a stale model from a re-published one, at a
593    /// glance without hashing gigabytes per request.
594    pub bytes: u64,
595}
596
597/// Resolve the whole runtime model set **without loading anything** — the
598/// exact selection each stage performs at load time (layout honors the
599/// int8/fp32 preference, TableFormer its decoder ranking, OCR the language
600/// pair), plus the pdfium library. docling-serve exposes this at
601/// `/v1/config` and logs it at startup, so "the server picked up different
602/// models" is one `curl` away instead of a mystery of dissolved tables.
603/// Resolution is CWD-relative with an exe-dir fallback, so the answer can
604/// legitimately differ between two working directories.
605#[cfg(feature = "ml")]
606pub fn model_inventory() -> Vec<ModelEntry> {
607    fn entry(stage: &'static str, path: String) -> ModelEntry {
608        let meta = std::fs::metadata(&path).ok();
609        ModelEntry {
610            stage,
611            found: meta.is_some(),
612            bytes: meta.map(|m| m.len()).unwrap_or(0),
613            path,
614        }
615    }
616    let (enc, dec, bbx) = tableformer::resolved_paths();
617    let (rec, dict) = ocr::resolve_rec_pair(ocr::OcrLang::from_env());
618    let pdfium =
619        env::nonempty("PDFIUM_DYNAMIC_LIB_PATH").unwrap_or_else(|| resolve_asset(".pdfium/lib"));
620    vec![
621        entry(
622            "layout",
623            model_path(
624                "DOCLING_LAYOUT_ONNX",
625                ".models/layout_heron.onnx",
626                ".models/layout_heron_int8.onnx",
627            ),
628        ),
629        entry("tableformer.encoder", enc),
630        entry("tableformer.decoder", dec),
631        entry("tableformer.bbox", bbx),
632        entry("ocr.rec", rec),
633        entry("ocr.dict", dict),
634        entry("ocr.textline_ori", ocr_cls::resolve_cls_path()),
635        entry("pdfium", pdfium),
636    ]
637}
638
639/// Resolve a model path: an explicit env override always wins; otherwise the
640/// INT8 variant of the default path when it exists on disk (the quantized
641/// models are conformance-validated — see docs/PDF_CONFORMANCE.md — and load/run
642/// markedly faster on CPU), unless `DOCLING_RS_FP32` opts back into full
643/// precision; else the fp32 default.
644#[cfg(feature = "ml")]
645pub(crate) fn model_path(key: &str, fp32_default: &str, int8_default: &str) -> String {
646    if let Some(p) = env::nonempty(key) {
647        return p;
648    }
649    if !prefer_fp32() {
650        let p = resolve_asset(int8_default);
651        if std::path::Path::new(&p).exists() {
652            return p;
653        }
654    }
655    resolve_asset(fp32_default)
656}
657
658/// Decode a standalone image with hard resource limits. A crafted image can
659/// declare enormous dimensions in a few-KB file; `image::load_from_memory`
660/// then tries to allocate the full pixel buffer (e.g. 60000×60000 → ~10 GB),
661/// and allocation failure aborts the whole process, bypassing the per-request
662/// panic catch. The 256 MiB alloc / 30000-px caps below turn that into a
663/// recoverable decode error instead. `DOCLING_RS_MAX_IMAGE_PIXELS` overrides
664/// the per-side pixel cap for the rare legitimately-huge scan.
665///
666/// Gated on `ml`: the only callers (`convert_image`, the METS backend) are
667/// ML-only, and the `image` crate is an `ml`-feature dependency — the
668/// text-layer wasm build has neither.
669#[cfg(feature = "ml")]
670pub(crate) fn decode_image_limited(bytes: &[u8]) -> Result<image::RgbImage, PdfError> {
671    decode_image_with_max_side(bytes, max_image_side())
672}
673
674/// `DOCLING_RS_MAX_IMAGE_PIXELS`: the per-side pixel cap of an image input
675/// (30000).
676#[cfg(feature = "ml")]
677pub(crate) fn max_image_side() -> u32 {
678    env::parse("DOCLING_RS_MAX_IMAGE_PIXELS").unwrap_or(30_000)
679}
680
681/// The `(horizontal, vertical)` resolution an image input's page is sized by,
682/// as docling's `ImageDocumentBackend` reads it (#1093): Pillow's
683/// `info["dpi"]` ([`docling_core::image_dpi::resolution`]), 72 when the file
684/// records none or the `(1, 1)` / `(0, 0)` placeholders, the axes swapped when
685/// the EXIF orientation turned the frame a quarter (`decoded` is the size
686/// after [`decode_image_limited`] applied it; docling's `_oriented_frame`
687/// compares the sizes the same way). A resolution docling rejects — not
688/// finite, zero or negative on one axis — fails its conversion; here it reads
689/// as 72, degradation over failure.
690#[cfg(feature = "ml")]
691fn image_page_dpi(bytes: &[u8], decoded: (u32, u32)) -> (f64, f64) {
692    const DEFAULT: (f64, f64) = (72.0, 72.0);
693    let dpi = match docling_core::image_dpi::resolution(bytes) {
694        None => return DEFAULT,
695        Some(d) if d == (1.0, 1.0) || d == (0.0, 0.0) => return DEFAULT,
696        Some((x, y)) if !(x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0) => return DEFAULT,
697        Some(d) => d,
698    };
699    let stored = image::ImageReader::new(std::io::Cursor::new(bytes))
700        .with_guessed_format()
701        .ok()
702        .and_then(|r| r.into_dimensions().ok());
703    match stored {
704        Some(size) if size != decoded => (dpi.1, dpi.0),
705        _ => dpi,
706    }
707}
708
709/// Whether `bytes` is an ISOBMFF HEIF/HEIC container (the `ftyp` brands
710/// iPhones write). Checked by content, not extension — HEIC regularly
711/// arrives misnamed `.jpg`.
712pub fn is_heif(bytes: &[u8]) -> bool {
713    bytes.len() >= 12
714        && &bytes[4..8] == b"ftyp"
715        && matches!(
716            &bytes[8..12],
717            b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"hevs" | b"mif1" | b"msf1"
718        )
719}
720
721#[cfg(feature = "ml")]
722fn decode_image_with_max_side(bytes: &[u8], max_side: u32) -> Result<image::RgbImage, PdfError> {
723    use image::{ImageDecoder, ImageReader};
724    use std::io::Cursor;
725
726    if is_heif(bytes) {
727        #[cfg(feature = "heif")]
728        return heif::decode(bytes, max_side).map_err(|e| PdfError::Pdfium(format!("heif: {e}")));
729        #[cfg(not(feature = "heif"))]
730        return Err(PdfError::Pdfium(
731            "HEIC/HEIF input needs a build with the `heif` cargo feature \
732             (rebuild with --features heif)"
733                .into(),
734        ));
735    }
736
737    let mut limits = image::Limits::default();
738    limits.max_image_width = Some(max_side);
739    limits.max_image_height = Some(max_side);
740    limits.max_alloc = Some(256 * 1024 * 1024);
741
742    let mut reader = ImageReader::new(Cursor::new(bytes))
743        .with_guessed_format()
744        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
745    reader.limits(limits);
746    let mut decoder = reader
747        .into_decoder()
748        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
749    // docling#4247 (2.128, `ImageOps.exif_transpose`): a camera stores the
750    // sensor readout plus an orientation tag rather than rotated pixels, so
751    // a portrait photo would reach layout and OCR on its side unless the tag
752    // is honoured. An unreadable tag is no orientation, not an error.
753    let orientation = decoder
754        .orientation()
755        .unwrap_or(image::metadata::Orientation::NoTransforms);
756    let mut img = image::DynamicImage::from_decoder(decoder)
757        .map_err(|e| PdfError::Pdfium(format!("image: {e}")))?;
758    img.apply_orientation(orientation);
759    // Transparency onto white, 16-bit samples truncated — docling's
760    // `to_rgb` (#1149).
761    Ok(ocr_prep::flatten_onto_white(img))
762}
763
764/// Image outputs of the PDF/image pipeline (#519/#520): the scale picture
765/// crops are delivered at and whether each page's render is kept as the
766/// document's page image. See [`Pipeline::images_scale`] /
767/// [`Pipeline::generate_page_images`].
768#[derive(Debug, Clone, Copy, Default, PartialEq)]
769pub struct ImageOutput {
770    /// Pixels per PDF point for picture crops and page images — docling's
771    /// `images_scale`. `None` keeps the pipeline's own page render (2.0
772    /// px/pt), resampling nothing.
773    pub scale: Option<f32>,
774    /// Keep every page's render as the document's page image — docling's
775    /// `generate_page_images`.
776    pub page_images: bool,
777    /// A picture region holding exactly one safe embedded image gets that
778    /// bitmap at native resolution (`dpi` 72) instead of a render crop —
779    /// docling's `use_embedded_picture_images` (#1007, docling#5143; see
780    /// [`embedded`]). Anything uncertain keeps the crop.
781    pub embedded_pictures: bool,
782}
783
784#[cfg(feature = "ml")]
785/// Whether a page's text layer is furniture rather than its text (#936): a
786/// page number, a running header — at most [`SPARSE_LAYER_WORDS`] non-blank
787/// words covering under 2 % of the page — beside text drawn as outlines. A
788/// digital page's body text covers far more, so it never pays for the
789/// orientation probe. The area test alone was not enough: a figure page with
790/// a one-line caption (1–2 % covered, 20–30 words — three of the sixteen
791/// pages of `2203.01017v2.pdf`) passed it and paid the full-page text
792/// detector on every such page, +44 % on the document; the word cap keeps
793/// the probe for the layer a sideways outline page keeps (the reporter's
794/// `Page 1`: 2 words, 0.05 %).
795fn sparse_text_layer(page: &PdfPage) -> bool {
796    let (mut covered, mut words) = (0.0f32, 0usize);
797    for c in page.cells.iter().filter(|c| !c.text.trim().is_empty()) {
798        covered += (c.r - c.l).max(0.0) * (c.b - c.t).max(0.0);
799        words += c.text.split_whitespace().count();
800    }
801    words <= SPARSE_LAYER_WORDS && covered < 0.02 * page.width * page.height
802}
803
804#[cfg(feature = "ml")]
805/// The detector's longer-side cap for the orientation probe of a page that
806/// has a text layer (#945): the pre-#570 budget, enough for the few wide
807/// lines the probe scores.
808const PROBE_DET_MAX_SIDE: u32 = 960;
809
810#[cfg(feature = "ml")]
811/// [`sparse_text_layer`]'s word cap: a page number plus a running header of
812/// a few words, not a caption.
813const SPARSE_LAYER_WORDS: usize = 12;
814
815#[cfg(feature = "ml")]
816/// The layout regions of a page with a text layer that no programmatic text
817/// touches — docling's "clusters without any visible programmatic text"
818/// (`_find_pdf_aware_layout_ocr_rects`: any text cell intersecting the
819/// cluster counts), so their text, if any, is drawn as outlines (#931).
820/// Text, furniture and table regions only: pictures have their own pass.
821/// Furniture is relabeled `text`, the label region OCR reads.
822fn text_less_regions(regions: &[layout::Region], cells: &[TextCell]) -> Vec<layout::Region> {
823    regions
824        .iter()
825        .filter(|r| {
826            ocr_prep::is_text_label(r.label)
827                || assemble::is_table_like(r.label)
828                || matches!(r.label, "page_header" | "page_footer")
829        })
830        .filter(|r| {
831            !cells.iter().any(|c| {
832                !c.text.trim().is_empty()
833                    && c.r.min(r.r) > c.l.max(r.l)
834                    && c.b.min(r.b) > c.t.max(r.t)
835            })
836        })
837        .map(|r| layout::Region {
838            label: match r.label {
839                "page_header" | "page_footer" => "text",
840                l => l,
841            },
842            ..r.clone()
843        })
844        .collect()
845}
846
847#[cfg(feature = "ml")]
848/// docling's `THIN_SHAPE_LINE_HEIGHTS`: a band no thicker than this many
849/// text lines is accounted for by any text on it.
850const THIN_BAND_LINES: f32 = 2.0;
851#[cfg(feature = "ml")]
852/// docling's `TEXT_BACKED_MIN_COVERAGE`: a thicker area is accounted for
853/// when text covers this share of it.
854const TEXT_BACKED_MIN_COVERAGE: f32 = 0.1;
855#[cfg(feature = "ml")]
856/// The share of a region a bitmap must cover for [`bitmap_regions`] to OCR
857/// it.
858const BITMAP_REGION_COVER: f32 = 0.5;
859
860#[cfg(feature = "ml")]
861/// The layout regions of a page with a text layer that lie on a bitmap the
862/// text layer does not account for (#999) — docling's other
863/// `_find_pdf_aware_layout_ocr_rects` trigger, "clusters overlapping a
864/// bitmap": a scanned form with one typed-in value has text in its table
865/// region, so [`text_less_regions`] skipped it and the table read the one
866/// native word. The same labels as there; regions [`text_less_regions`]
867/// already takes are left to it.
868///
869/// Narrower than docling, on purpose: docling OCRs every cluster that
870/// touches a bitmap. Here the bitmap must cover at least
871/// [`BITMAP_REGION_COVER`] of the region, and its part inside the region
872/// must not be accounted for by the text layer, judged with docling's own
873/// rule for shapes (`_text_accounts_for`: a band no thicker than two text
874/// lines is explained by any text on it, a thicker one by text over a
875/// tenth of it). A searchable scan — an invisible text layer over the
876/// page image — and a digital page's logo or figure beside its text are
877/// left to their text layer instead of being OCR'd a second time.
878fn bitmap_regions(
879    regions: &[layout::Region],
880    cells: &[TextCell],
881    bitmaps: &[[f32; 4]],
882) -> Vec<layout::Region> {
883    if bitmaps.is_empty() {
884        return Vec::new();
885    }
886    let ink = |c: &&TextCell| !c.text.trim().is_empty();
887    regions
888        .iter()
889        .filter(|r| {
890            ocr_prep::is_text_label(r.label)
891                || assemble::is_table_like(r.label)
892                || matches!(r.label, "page_header" | "page_footer")
893        })
894        .filter(|r| {
895            // Regions with no text at all are `text_less_regions`'.
896            cells
897                .iter()
898                .filter(ink)
899                .any(|c| c.r.min(r.r) > c.l.max(r.l) && c.b.min(r.b) > c.t.max(r.t))
900        })
901        .filter(|r| {
902            let area = ((r.r - r.l) * (r.b - r.t)).max(1.0);
903            bitmaps.iter().any(|&[bl, bt, br, bb]| {
904                let (l, t, rr, b) = (bl.max(r.l), bt.max(r.t), br.min(r.r), bb.min(r.b));
905                let (w, h) = (rr - l, b - t);
906                if w <= 0.0 || h <= 0.0 || w * h < BITMAP_REGION_COVER * area {
907                    return false;
908                }
909                let under: Vec<(f32, f32)> = cells
910                    .iter()
911                    .filter(ink)
912                    .filter_map(|c| {
913                        let iw = c.r.min(rr) - c.l.max(l);
914                        let ih = c.b.min(b) - c.t.max(t);
915                        (iw > 0.0 && ih > 0.0).then_some((c.b - c.t, iw * ih))
916                    })
917                    .collect();
918                if under.is_empty() {
919                    return true;
920                }
921                let mut heights: Vec<f32> = under.iter().map(|u| u.0).collect();
922                heights.sort_by(f32::total_cmp);
923                let line = heights[heights.len() / 2];
924                if w.min(h) <= THIN_BAND_LINES * line {
925                    return false;
926                }
927                let covered: f32 = under.iter().map(|u| u.1).sum();
928                covered / (w * h) < TEXT_BACKED_MIN_COVERAGE
929            })
930        })
931        .map(|r| layout::Region {
932            label: match r.label {
933                "page_header" | "page_footer" => "text",
934                l => l,
935            },
936            ..r.clone()
937        })
938        .collect()
939}
940
941#[cfg(feature = "ml")]
942/// The OCR'd cells with their recognition confidence, for the per-cell report
943/// (#915): a copy of what feeds the page `ocr_score`, kept beside it.
944fn cell_confs(scored: &[(TextCell, f32)]) -> Vec<docling_core::OcrCellConfidence> {
945    scored
946        .iter()
947        .map(|(c, conf)| docling_core::OcrCellConfidence {
948            text: c.text.clone(),
949            l: c.l,
950            t: c.t,
951            r: c.r,
952            b: c.b,
953            confidence: *conf,
954        })
955        .collect()
956}
957
958#[cfg(feature = "ml")]
959/// The document's report: page scores plus the per-cell OCR confidences (#915).
960fn confidence_report(
961    confs: std::collections::BTreeMap<usize, docling_core::confidence::PageConfidence>,
962    cells: std::collections::BTreeMap<usize, Vec<docling_core::OcrCellConfidence>>,
963) -> docling_core::ConfidenceReport {
964    cells.into_iter().fold(
965        docling_core::ConfidenceReport::from_pages(confs),
966        |report, (n, cells)| report.with_ocr_cells(n, cells),
967    )
968}
969
970#[cfg(feature = "ml")]
971/// One page's assembled output: typed nodes plus the page's hyperlinks (kept
972/// separate so pages processed out of order can be stitched back in page
973/// order) and its confidence scores (#183).
974type PageOut = (
975    Vec<Node>,
976    Vec<(String, String)>,
977    docling_core::confidence::PageConfidence,
978    // The page image, when page images are requested (#520).
979    Option<docling_core::PictureImage>,
980    // The page's OCR cells with their recognition confidence (#915).
981    Vec<docling_core::OcrCellConfidence>,
982);
983
984/// One page from its text layer alone — the fastest path: no layout, OCR
985/// or TableFormer inference at all. The embedded text cells (if any) become
986/// flat, line-grouped paragraphs in reading order via the same
987/// orphan-region machinery that normally rescues text the detector missed —
988/// here it rescues *all* of it. A page with no text layer (scanned /
989/// image-only) yields nothing. Shared by the `no_ocr` worker branch
990/// (images, METS) and the worker-less PDF loop of
991/// [`Pipeline::convert_text_only`], so `text_layer_only=true` and an
992/// `auto` document with text come out byte-identical.
993#[cfg(feature = "ml")]
994fn text_only_page(
995    page: &PdfPage,
996    images_scale: Option<f32>,
997) -> (
998    Vec<Node>,
999    Vec<(String, String)>,
1000    docling_core::confidence::PageConfidence,
1001) {
1002    let parse = quality::parse_score(&page.cells);
1003    let mut regions = Vec::new();
1004    assemble::add_orphan_regions(&mut regions, &page.cells);
1005    let table_rows = vec![None; regions.len()];
1006    let enrich_out = vec![None; regions.len()];
1007    let conf = quality::page_confidence(parse, &regions, &[]);
1008    let (nodes, links) = timing::timed("assemble_page", || {
1009        assemble::assemble_page(page, regions, &table_rows, &enrich_out, images_scale)
1010    });
1011    (nodes, links, conf)
1012}
1013
1014/// The page's image for the document's page images (#520) under `images`:
1015/// `None` unless page images were requested, or when the page has no bitmap
1016/// (the text-layer-only paths never render one).
1017#[cfg(feature = "ml")]
1018fn page_image_under(
1019    images: ImageOutput,
1020    n: usize,
1021    page: &PdfPage,
1022) -> Option<docling_core::PictureImage> {
1023    if !images.page_images {
1024        return None;
1025    }
1026    let image = assemble::page_image(page, images.scale);
1027    if image.is_none() {
1028        docling_core::debug_log!("page {}: no page bitmap for the page image", n + 1);
1029    }
1030    image
1031}
1032
1033#[cfg(feature = "ml")]
1034/// A page between region resolution and TableFormer: what `prepare_page`
1035/// produced and `complete_page` still needs, so a pool worker can park the
1036/// page while another worker holds the shared TableFormer (see `Staged`).
1037struct Prepared {
1038    regions: Vec<layout::Region>,
1039    ocr_confs: Vec<f32>,
1040    ocr_cells: Vec<docling_core::OcrCellConfidence>,
1041    parse: Option<f64>,
1042    /// The OCR lines read inside the pictures of a text-layer page under
1043    /// `picture_ocr` (#1219), hung on the assembled pictures.
1044    picture_text: Vec<pdfium_backend::TextCell>,
1045}
1046
1047#[cfg(feature = "ml")]
1048/// A pool worker's per-page outcome. `NeedsTables` is a page whose only
1049/// remaining stage is the shared TableFormer, which was busy when the worker
1050/// got there: rather than block on the mutex — one worker idle for the
1051/// whole of another worker's table decode, ~9.5 s of the 60-page .NET slice
1052/// on a 2-worker pool — the worker keeps the page aside, pulls the next one
1053/// off the render channel, and comes back once the slot is free. Results
1054/// are reassembled by page index anyway, so completion order is free.
1055enum Staged {
1056    Done(PageOut),
1057    NeedsTables(Prepared),
1058}
1059
1060#[cfg(feature = "ml")]
1061/// How many pages a pool worker keeps parked on the TableFormer before it
1062/// falls back to waiting: each carries its ~5 MB bitmaps, so this bounds the
1063/// extra residency to two pages per worker on top of the render channel.
1064const MAX_DEFERRED_PAGES: usize = 2;
1065
1066#[cfg(feature = "ml")]
1067/// The pool-wide TableFormer slot: one instance shared by every worker, loaded
1068/// lazily on the first table region any worker sees. Tables appear on a
1069/// minority of pages, so per-worker copies mostly multiplied ~0.4 GB of
1070/// weights+arenas by the pool size for nothing; a single shared instance keeps
1071/// the peak flat regardless of pool width, and a table's structure prediction
1072/// is independent of which worker runs it, so output is byte-identical. The
1073/// mutex serialises concurrent tables — the shared instance is loaded with the
1074/// full intra-op thread budget to compensate (one wide TableFormer instead of
1075/// several narrow ones).
1076enum TfSlot {
1077    /// Not attempted yet (no table seen so far).
1078    Unloaded,
1079    /// Load attempted, graphs absent — geometric fallback (warned once).
1080    Missing,
1081    Ready(tableformer::TableFormer),
1082}
1083
1084#[cfg(feature = "ml")]
1085impl TfSlot {
1086    /// Load TableFormer on the first call: `Ready`, or `Missing` when its
1087    /// graphs are absent (the geometric fallback — degradation, not an
1088    /// error). Later calls are no-ops either way.
1089    fn load(&mut self) {
1090        if matches!(self, TfSlot::Unloaded) {
1091            *self = match tableformer::TableFormer::load_with(tf_intra()) {
1092                Some(tf) => TfSlot::Ready(tf),
1093                None => TfSlot::Missing,
1094            };
1095        }
1096    }
1097}
1098
1099#[cfg(feature = "ml")]
1100type SharedTables = Arc<Mutex<TfSlot>>;
1101
1102#[cfg(feature = "ml")]
1103/// The same lazy shared-slot pattern for the (rarer still) enrichment models:
1104/// one instance per pipeline, loaded on the first region that needs it.
1105enum EnrichSlot<T> {
1106    Unloaded,
1107    /// Load attempted, model files absent — enrichment skipped (warned once).
1108    Missing,
1109    Ready(T),
1110}
1111
1112#[cfg(feature = "ml")]
1113type SharedClassifier = Arc<Mutex<EnrichSlot<enrich::PictureClassifier>>>;
1114#[cfg(feature = "ml")]
1115type SharedCodeFormula = Arc<Mutex<EnrichSlot<enrich::CodeFormula>>>;
1116
1117#[cfg(feature = "ml")]
1118/// The opt-in enrichment passes, mirroring docling's `PdfPipelineOptions`
1119/// flags (`do_picture_classification`, `do_code_enrichment`,
1120/// `do_formula_enrichment`). All off by default.
1121#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1122pub struct EnrichmentOptions {
1123    /// Classify each picture with DocumentFigureClassifier (26 classes).
1124    pub picture_classification: bool,
1125    /// Rewrite code blocks (and detect their language) with CodeFormulaV2.
1126    pub code: bool,
1127    /// Decode display formulas to LaTeX with CodeFormulaV2.
1128    pub formula: bool,
1129}
1130
1131#[cfg(feature = "ml")]
1132impl EnrichmentOptions {
1133    fn any(&self) -> bool {
1134        self.picture_classification || self.code || self.formula
1135    }
1136}
1137
1138#[cfg(feature = "ml")]
1139/// The layout model's input for a page: the pypdfium2-exact scale-1.0 page
1140/// image (#478) when the renderer produced one, else the legacy stretch of the 2×
1141/// bitmap (browser / METS paths) — see [`layout::LayoutSrc`]. Public so the
1142/// diagnostic examples feed [`layout::LayoutModel::predict`] the same input
1143/// the pipeline does.
1144pub fn layout_src(page: &PdfPage) -> layout::LayoutSrc<'_> {
1145    match &page.image_layout {
1146        Some(img) => layout::LayoutSrc::PageImage(img),
1147        None => layout::LayoutSrc::Raw(&page.image),
1148    }
1149}
1150
1151#[cfg(feature = "ml")]
1152/// RapidOCR's longest side (`Global.max_side_len`, 2000): docling renders the
1153/// OCR input at `OcrOptions.scale` = 3 and RapidOCR then shrinks what exceeds
1154/// this before detecting and recognizing, so that is the resolution its
1155/// models actually see.
1156pub(crate) const RAPIDOCR_MAX_SIDE: f32 = 2000.0;
1157
1158#[cfg(feature = "ml")]
1159/// The px/pt the OCR reads a page at: the caller's `ocr_scale` when set; else,
1160/// for a standalone bitmap input — its own scale-1.0 page, a resolution the
1161/// pipeline did not choose — docling's rule (#570): three pixels per point
1162/// (`OcrOptions.scale`), shrunk so the longer side stays within RapidOCR's
1163/// 2000 px (a 754 × 1000 scanned form reads at 2.0; a 3000 px photo at 0.67,
1164/// as RapidOCR would downsample it). `None` for a rendered page (PDF, hOCR),
1165/// which keeps its own render — the 2.0 px/pt the conformance baselines are
1166/// pinned to. Measured on FUNSD at 1.0 / 2.0 / 3.0 px/pt: 0.825 / 0.856 /
1167/// 0.836 word recall — the recognizer likes its crops at the resolution
1168/// RapidOCR hands it, no more.
1169fn page_ocr_scale(ocr_scale: Option<f32>, width: f32, height: f32, scale: f32) -> Option<f32> {
1170    if ocr_scale.is_some() || scale != 1.0 {
1171        return ocr_scale;
1172    }
1173    let longest = width.max(height);
1174    if longest <= 0.0 {
1175        return None;
1176    }
1177    let s = 3.0f32.min(RAPIDOCR_MAX_SIDE / longest);
1178    ((s - 1.0).abs() > 1e-3).then_some(s)
1179}
1180
1181#[cfg(feature = "ml")]
1182/// The bitmap + px/pt scale the OCR reads (#254, docling#3877's
1183/// `OcrOptions.scale`): the page's own render unless `ocr_scale` asks for a
1184/// different resolution, where a PIL-bicubic resample of that render is built
1185/// once per page (cached in `cache`) and shared by every OCR pass. Resampling
1186/// — rather than a second native pdfium render — keeps one code path across
1187/// PDF, image, and hOCR inputs and leaves the layout/TableFormer pixels (and
1188/// with them the conformance baseline) untouched; the 144-dpi base render is
1189/// itself supersampled down from 216 dpi, so an upscaled OCR view loses
1190/// little against a native render.
1191fn ocr_input<'a>(
1192    cache: &'a mut Option<image::RgbImage>,
1193    image: &'a image::RgbImage,
1194    scale: f32,
1195    ocr_scale: Option<f32>,
1196) -> (&'a image::RgbImage, f32) {
1197    match ocr_scale {
1198        Some(s) if (s - scale).abs() > 1e-3 && image.width() > 1 => {
1199            let f = s / scale;
1200            let img = cache.get_or_insert_with(|| {
1201                let dw = ((image.width() as f32 * f).round() as u32).max(1);
1202                let dh = ((image.height() as f32 * f).round() as u32).max(1);
1203                resample::pil_resize(image, dw, dh, resample::PilFilter::Bicubic)
1204            });
1205            (img, s)
1206        }
1207        _ => (image, scale),
1208    }
1209}
1210
1211#[cfg(feature = "ml")]
1212/// A self-contained set of the per-page models (layout, OCR). Each parallel
1213/// page-worker owns its own `Worker` so inference runs concurrently without
1214/// sharing an ONNX session (`ort`'s `Session::run` is `&mut self`); only the
1215/// rarely-hit TableFormer is shared (see [`TfSlot`]).
1216struct Worker {
1217    /// `None` when `no_ocr` skips layout entirely — no model load, no inference.
1218    layout: Option<layout::LayoutModel>,
1219    ocr: OcrSlot,
1220    /// What this worker's OCR requests met since the pipeline last asked
1221    /// (#1210): set by [`Self::ocr_model`] whenever a page wants OCR, read
1222    /// and cleared by [`Pipeline::take_ocr_status`]. `None` = no request.
1223    ocr_status: Option<docling_core::OcrStatus>,
1224    det: SharedDet,
1225    /// Text-detector results computed ahead of a page's OCR pass (#429), keyed
1226    /// by page index: the detector reads nothing but the page image, so it
1227    /// runs on its own thread while the layout model predicts — see
1228    /// [`Self::detect_alongside`] — and the OCR block collects the boxes here
1229    /// instead of paying for detection serially.
1230    pending_det: BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
1231    /// This worker's intra-op thread budget — also the OCR lane count (see
1232    /// [`ocr::OcrModel::load_with`]): a pool worker with two threads runs two
1233    /// single-thread recognisers, the primary as many as its cores.
1234    intra: usize,
1235    /// Shared TableFormer slot; `None` when `no_table_former`/`no_ocr` skip it.
1236    tables: Option<SharedTables>,
1237    /// Shared enrichment slots; `None` unless the corresponding flag is on.
1238    classifier: Option<SharedClassifier>,
1239    code_formula: Option<SharedCodeFormula>,
1240    enrich: EnrichmentOptions,
1241    /// Skip layout, OCR, and TableFormer; reconstruct text purely from the PDF's
1242    /// embedded text layer. See [`Pipeline::no_ocr`].
1243    no_ocr: bool,
1244    /// Discard the embedded text layer and OCR every page. See
1245    /// [`Pipeline::force_full_page_ocr`].
1246    force_full_page_ocr: bool,
1247    /// OCR a page whose text layer [`quality::is_broken_text_layer`] judges
1248    /// broken, that page only (#1006). See
1249    /// [`Pipeline::replace_broken_text_layer`].
1250    replace_broken_text_layer: bool,
1251    /// Read the pictures of a text-layer page (#1219). See
1252    /// [`Pipeline::picture_ocr`].
1253    picture_ocr: bool,
1254    /// Keep text-panel pictures as pictures instead of demoting them to
1255    /// paragraphs. See [`Pipeline::no_text_panels`].
1256    no_text_panels: bool,
1257    /// Never run OCR, but keep layout + TableFormer (#244) — docling's
1258    /// `do_ocr=False`. See [`Pipeline::skip_ocr`].
1259    skip_ocr: bool,
1260    /// Which recognition model [`Self::ocr`] loads. See [`Pipeline::ocr_lang`].
1261    ocr_lang: ocr::OcrLang,
1262    /// Which engine [`Self::ocr`] is (#460). See [`Pipeline::ocr_engine`].
1263    ocr_engine: ocr::OcrEngine,
1264    /// Tesseract's `-l` argument (#460). See [`Pipeline::tesseract_lang`].
1265    tesseract_lang: Option<String>,
1266    /// OCR render scale override (px/pt, #254). See [`Pipeline::ocr_scale`].
1267    ocr_scale: Option<f32>,
1268    /// RapidOCR's line orientation handling (#666), handed to the PP-OCR
1269    /// recognizer. See [`Pipeline::ocr_textline_orientation`].
1270    textline_orientation: bool,
1271    /// Picture-crop scale and page images (#519/#520). See [`ImageOutput`].
1272    images: ImageOutput,
1273}
1274
1275#[cfg(feature = "ml")]
1276/// The worker's lazily-loaded OCR recognition model. `Missing` records a
1277/// failed load (#244: degradation over failure — a deployment without the OCR
1278/// model still gets layout + TableFormer, and OCR-dependent regions stay
1279/// empty) so the load isn't retried per page. It keeps the load error: every
1280/// later conversion that wants OCR reports it on its result (#1210), not
1281/// only the first one the one-time warning reached.
1282enum OcrSlot {
1283    Unloaded,
1284    Ready(Recognizer),
1285    Missing(String),
1286}
1287
1288#[cfg(feature = "ml")]
1289/// The loaded OCR engine (#460): PP-OCRv3 via ONNX Runtime or the
1290/// `tesseract` binary. Both answer the two questions the page assembly asks
1291/// — line cells for text regions, word cells for table regions — in page
1292/// points with a 0–1 confidence, so the call sites never know which runs.
1293pub(crate) enum Recognizer {
1294    PpOcr(ocr::OcrModel),
1295    Tesseract(tesseract::TesseractOcr),
1296}
1297
1298#[cfg(feature = "ml")]
1299impl Recognizer {
1300    /// See [`ocr::OcrModel::ocr_page_with`].
1301    fn ocr_page(
1302        &mut self,
1303        img: &image::RgbImage,
1304        regions: &[layout::Region],
1305        scale: f32,
1306    ) -> Result<Vec<(TextCell, f32)>, String> {
1307        self.ocr_page_with(img, regions, scale, None)
1308    }
1309
1310    /// [`Self::ocr_page`] with the detector's boxes (#570). Tesseract segments its
1311    /// own lines and ignores the detector's boxes.
1312    fn ocr_page_with(
1313        &mut self,
1314        img: &image::RgbImage,
1315        regions: &[layout::Region],
1316        scale: f32,
1317        detected: Option<&[ocr_det::DetBox]>,
1318    ) -> Result<Vec<(TextCell, f32)>, String> {
1319        match self {
1320            Self::PpOcr(m) => m.ocr_page_with(img, regions, scale, detected),
1321            Self::Tesseract(t) => t.ocr_page(img, regions, scale),
1322        }
1323    }
1324
1325    /// See [`ocr::OcrModel::ocr_table_words`].
1326    fn ocr_table_words(
1327        &mut self,
1328        img: &image::RgbImage,
1329        regions: &[layout::Region],
1330        scale: f32,
1331        detected: Option<&[ocr_det::DetBox]>,
1332    ) -> Result<Vec<(TextCell, f32)>, String> {
1333        match self {
1334            Self::PpOcr(m) => m.ocr_table_words(img, regions, scale, detected),
1335            Self::Tesseract(t) => t.ocr_table_words(img, regions, scale),
1336        }
1337    }
1338}
1339
1340#[cfg(feature = "ml")]
1341/// The text detector (#429), loaded on the first OCR'd page like the
1342/// recognizer; `Missing` keeps the pipeline recognition-only. One instance
1343/// is shared by every worker ([`SharedDet`], #945, as TableFormer is): the
1344/// DB net's activation arena at the 2000 px input (#570) is ~250 MB, the
1345/// largest of any OCR model, and per-worker copies multiplied it by the
1346/// pool width for a model that runs once per page. The mutex serializes
1347/// concurrent detections; each worker's layout still runs alongside its
1348/// own, so the wall time is unchanged, and a page's boxes do not depend on
1349/// which worker detected them, so the output is byte-identical.
1350enum DetSlot {
1351    Unloaded,
1352    Ready(ocr_det::DetModel),
1353    Missing,
1354}
1355
1356#[cfg(feature = "ml")]
1357impl DetSlot {
1358    /// Load the detector on the first call — with the full intra-op budget,
1359    /// one wide session for the pool — `Missing` (said once under
1360    /// `DOCLING_RS_DEBUG`) when the model is not installed.
1361    fn load(&mut self) {
1362        if matches!(self, DetSlot::Unloaded) {
1363            *self = match ocr_det::DetModel::load(intra_threads()) {
1364                Ok(model) => DetSlot::Ready(model),
1365                Err(e) => {
1366                    docling_core::debug_log!(
1367                        "docling-pdf: text detection unavailable ({e}); OCR stays region-scoped"
1368                    );
1369                    DetSlot::Missing
1370                }
1371            };
1372        }
1373    }
1374}
1375
1376#[cfg(feature = "ml")]
1377type SharedDet = Arc<Mutex<DetSlot>>;
1378
1379#[cfg(feature = "ml")]
1380impl Worker {
1381    #[allow(clippy::too_many_arguments)] // mirrors the Pipeline's option set
1382    fn load(
1383        intra: usize,
1384        tables: Option<SharedTables>,
1385        det: SharedDet,
1386        enrich_slots: (Option<SharedClassifier>, Option<SharedCodeFormula>),
1387        enrich: EnrichmentOptions,
1388        no_ocr: bool,
1389        skip_ocr: bool,
1390        force_full_page_ocr: bool,
1391        no_text_panels: bool,
1392        ocr_lang: ocr::OcrLang,
1393        ocr_engine: ocr::OcrEngine,
1394        tesseract_lang: Option<String>,
1395        ocr_scale: Option<f32>,
1396        textline_orientation: bool,
1397        images: ImageOutput,
1398    ) -> Result<Self, PdfError> {
1399        Ok(Self {
1400            images,
1401            layout: if no_ocr {
1402                None
1403            } else {
1404                Some(layout::LayoutModel::load_with(intra).map_err(PdfError::Layout)?)
1405            },
1406            ocr: OcrSlot::Unloaded,
1407            ocr_status: None,
1408            det,
1409            pending_det: BTreeMap::new(),
1410            intra,
1411            tables,
1412            classifier: enrich_slots.0,
1413            code_formula: enrich_slots.1,
1414            enrich,
1415            no_ocr,
1416            skip_ocr,
1417            force_full_page_ocr,
1418            // Set by the pipeline after loading (`sync_ocr_config`).
1419            replace_broken_text_layer: false,
1420            picture_ocr: false,
1421            no_text_panels,
1422            ocr_lang,
1423            ocr_engine,
1424            tesseract_lang,
1425            ocr_scale,
1426            textline_orientation,
1427        })
1428    }
1429
1430    /// Set [`Pipeline::ocr_textline_orientation`] here and on a loaded
1431    /// PP-OCR recognizer.
1432    fn set_textline_orientation(&mut self, enable: bool) {
1433        self.textline_orientation = enable;
1434        if let OcrSlot::Ready(Recognizer::PpOcr(m)) = &mut self.ocr {
1435            m.set_textline_orientation(enable);
1436        }
1437    }
1438
1439    /// The OCR model, or `None` when this conversion must not (or cannot) OCR:
1440    /// `skip_ocr` short-circuits, and a failed model load degrades to `None`
1441    /// with a one-time warning instead of failing the conversion (#244) —
1442    /// unless `force_full_page_ocr` demanded OCR explicitly, where a missing
1443    /// model stays a hard error (the text layer was deliberately discarded, so
1444    /// degrading would silently emit an empty document).
1445    fn ocr_model(&mut self) -> Result<Option<&mut Recognizer>, PdfError> {
1446        if self.skip_ocr {
1447            return Ok(None);
1448        }
1449        if matches!(self.ocr, OcrSlot::Unloaded) {
1450            let loaded = match self.ocr_engine {
1451                ocr::OcrEngine::PpOcr => {
1452                    ocr::OcrModel::load_with(self.ocr_lang, self.intra).map(|mut m| {
1453                        m.set_textline_orientation(self.textline_orientation);
1454                        Recognizer::PpOcr(m)
1455                    })
1456                }
1457                ocr::OcrEngine::Tesseract => tesseract::TesseractOcr::load(
1458                    tesseract::TesseractOptions::from_env(self.tesseract_lang.clone()),
1459                    self.intra,
1460                )
1461                .map(Recognizer::Tesseract),
1462            };
1463            match loaded {
1464                Ok(model) => self.ocr = OcrSlot::Ready(model),
1465                Err(e) if self.force_full_page_ocr => return Err(PdfError::Ocr(e)),
1466                Err(e) => {
1467                    static WARNED: std::sync::Once = std::sync::Once::new();
1468                    let hint = match self.ocr_engine {
1469                        ocr::OcrEngine::PpOcr => {
1470                            "install the models with scripts/install/download_dependencies.sh, \
1471                             or docling_rs.download_models() from Python"
1472                        }
1473                        ocr::OcrEngine::Tesseract => {
1474                            "install tesseract-ocr with the language pack, or use --ocr-engine ppocr"
1475                        }
1476                    };
1477                    WARNED.call_once(|| {
1478                        eprintln!(
1479                            "warning: OCR model unavailable ({e}); continuing without OCR — \
1480                             scanned pages and text inside images will come back empty \
1481                             ({hint})"
1482                        );
1483                    });
1484                    self.ocr = OcrSlot::Missing(e.to_string());
1485                }
1486            }
1487        }
1488        // Every call is a page (or picture) asking for OCR — the callers
1489        // reach here only once a text-less region needs reading — so the
1490        // slot's state is what that request met (#1210).
1491        let met = match &self.ocr {
1492            OcrSlot::Ready(_) => docling_core::OcrStatus::Available,
1493            OcrSlot::Missing(reason) => docling_core::OcrStatus::Unavailable {
1494                reason: reason.clone(),
1495            },
1496            OcrSlot::Unloaded => unreachable!("loaded above"),
1497        };
1498        self.ocr_status = docling_core::OcrStatus::merge_opt(self.ocr_status.take(), Some(met));
1499        Ok(match &mut self.ocr {
1500            OcrSlot::Ready(model) => Some(model),
1501            _ => None,
1502        })
1503    }
1504
1505    /// [`Self::ocr_model`] when `wanted`, else `None` without touching the
1506    /// slot: the call sites that only *may* need OCR (a region left without
1507    /// text, a picture-table) ask through here, so a page with nothing to
1508    /// read neither loads the model nor counts as an OCR request on the
1509    /// result's status (#1210) — a born-digital page needs no OCR, whatever
1510    /// the engine's state.
1511    fn ocr_model_if(&mut self, wanted: bool) -> Result<Option<&mut Recognizer>, PdfError> {
1512        if wanted {
1513            self.ocr_model()
1514        } else {
1515            Ok(None)
1516        }
1517    }
1518
1519    /// Run `f` on the shared text detector (#429/#945), loading it on first
1520    /// use; `None` with `skip_ocr` or when the model is not installed —
1521    /// recognition stays region-scoped then, exactly the pre-#429 behavior.
1522    /// The slot's lock is held for the call, which serializes detections
1523    /// across the pool.
1524    fn with_det<R>(&mut self, f: impl FnOnce(&mut ocr_det::DetModel) -> R) -> Option<R> {
1525        if self.skip_ocr {
1526            return None;
1527        }
1528        let mut slot = self.det.lock().unwrap_or_else(|p| p.into_inner());
1529        slot.load();
1530        match &mut *slot {
1531            DetSlot::Ready(model) => Some(f(model)),
1532            _ => None,
1533        }
1534    }
1535
1536    /// Whether the text detector is there to run (loading it on first use).
1537    fn det_available(&mut self) -> bool {
1538        self.with_det(|_| ()).is_some()
1539    }
1540
1541    /// OCR one picture of a text-layer page (#1219, `picture_ocr`) the way
1542    /// the picture OCR of the other formats reads an embedded image
1543    /// (`Pipeline::ocr_picture`): the region's own crop of the page render,
1544    /// the text detector's boxes on that crop as the line crops when the
1545    /// detector is installed — a photo's label or a seal's ring of text is
1546    /// no stack of horizontal strips, which is all the ink projection can
1547    /// cut — and the recognizer's lines mapped back to page points. Empty
1548    /// without the recognizer (its one-time warning says why) or `skip_ocr`.
1549    fn read_picture_region(
1550        &mut self,
1551        page: &PdfPage,
1552        r: &layout::Region,
1553        ocr_scale: Option<f32>,
1554    ) -> Result<Vec<pdfium_backend::TextCell>, String> {
1555        let s = page.scale;
1556        let (iw, ih) = (page.image.width(), page.image.height());
1557        let x0 = ((r.l * s).floor().max(0.0) as u32).min(iw);
1558        let y0 = ((r.t * s).floor().max(0.0) as u32).min(ih);
1559        let x1 = ((r.r * s).ceil().max(0.0) as u32).min(iw);
1560        let y1 = ((r.b * s).ceil().max(0.0) as u32).min(ih);
1561        if x1 <= x0 + 1 || y1 <= y0 + 1 {
1562            return Ok(Vec::new());
1563        }
1564        let crop = image::imageops::crop_imm(&page.image, x0, y0, x1 - x0, y1 - y0).to_image();
1565        let mut cache = None;
1566        let (view, scale) = ocr_input(&mut cache, &crop, s, ocr_scale);
1567        let (ox, oy) = (x0 as f32 / s, y0 as f32 / s);
1568        let region = layout::Region {
1569            label: "text",
1570            score: 1.0,
1571            l: 0.0,
1572            t: 0.0,
1573            r: (x1 - x0) as f32 / s,
1574            b: (y1 - y0) as f32 / s,
1575        };
1576        // A detector that cannot run costs the picture its detected lines,
1577        // not the conversion: the projection strips read it instead.
1578        let detected = self
1579            .with_det(|det| det.detect(view))
1580            .and_then(Result::ok)
1581            .filter(|d| ocr::det_lines() && !d.is_empty());
1582        let Some(model) = self.ocr_model().map_err(|e| e.to_string())? else {
1583            return Ok(Vec::new());
1584        };
1585        let cells = model.ocr_page_with(
1586            view,
1587            std::slice::from_ref(&region),
1588            scale,
1589            detected.as_deref(),
1590        )?;
1591        Ok(cells
1592            .into_iter()
1593            .map(|(mut c, _)| {
1594                c.l += ox;
1595                c.r += ox;
1596                c.t += oy;
1597                c.b += oy;
1598                c
1599            })
1600            .collect())
1601    }
1602
1603    /// Run layout (+ OCR for cell-less pages) + TableFormer and assemble page `n`
1604    /// into its nodes and links. Pure given the page (mutates only the worker's
1605    /// lazily-loaded OCR model), so it is safe to run concurrently across pages.
1606    fn process(&mut self, n: usize, page: &mut PdfPage) -> Result<PageOut, PdfError> {
1607        if self.no_ocr {
1608            // Fastest path (`text_only_page`): the text layer alone, nothing
1609            // inferred. Pages with no embedded text layer yield nothing;
1610            // convert those without `no_ocr`.
1611            let (nodes, links, conf) = text_only_page(page, self.images.scale);
1612            return Ok((nodes, links, conf, self.page_image(n, page), Vec::new()));
1613        }
1614        self.normalize_orientation(n, page)?;
1615        let det_pages = self.det_candidates(std::slice::from_ref(&(n, &*page)))?;
1616        let regions = {
1617            let Self {
1618                layout,
1619                det,
1620                pending_det,
1621                ocr_scale,
1622                ..
1623            } = self;
1624            let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
1625            let page: &PdfPage = &*page;
1626            Self::detect_alongside(&*det, pending_det, *ocr_scale, &det_pages, || {
1627                timing::timed("layout.predict", || {
1628                    layout.predict(layout_src(page), page.width, page.height)
1629                })
1630            })
1631        }
1632        .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
1633        // The 2x bitmap (#682), when the detections read it (#897).
1634        self.ensure_bitmap(page, &regions)?;
1635        self.finish_page(n, page, regions)
1636    }
1637
1638    /// The page's render as docling's `PageItem.image` (#520), at
1639    /// [`ImageOutput::scale`] — `None` unless page images were requested, or
1640    /// when the page has no bitmap (the text-layer-only `no_ocr` path never
1641    /// renders one).
1642    fn page_image(&self, n: usize, page: &PdfPage) -> Option<docling_core::PictureImage> {
1643        page_image_under(self.images, n, page)
1644    }
1645
1646    /// The pages of a batch the text detector should sweep (#429): bitmap
1647    /// pages (no text layer) on a run with OCR and the detector available —
1648    /// loading both lazily here so the concurrent run below needs no `self`.
1649    fn det_candidates<'p>(
1650        &mut self,
1651        pages: &[(usize, &'p PdfPage)],
1652    ) -> Result<Vec<(usize, &'p PdfPage)>, PdfError> {
1653        // Pages the orientation pass already detected (#571) are skipped:
1654        // their boxes wait in `pending_det`.
1655        let scanned: Vec<(usize, &PdfPage)> = pages
1656            .iter()
1657            .filter(|(n, p)| {
1658                p.cells.is_empty() && p.image.width() > 1 && !self.pending_det.contains_key(n)
1659            })
1660            .copied()
1661            .collect();
1662        if scanned.is_empty() || self.ocr_model()?.is_none() || !self.det_available() {
1663            return Ok(Vec::new());
1664        }
1665        Ok(scanned)
1666    }
1667
1668    /// Run `layout` on the calling thread while the text detector sweeps
1669    /// `det_pages` on another (#429): the detector only reads each page's
1670    /// image, layout only reads the pages too, and the two sessions are
1671    /// independent, so on a scanned page the ~0.7 s detection hides behind
1672    /// layout instead of adding to it. Results land in `pending_det` for the
1673    /// OCR block; a detector failure is recorded per page and surfaces there.
1674    fn detect_alongside<T>(
1675        det: &SharedDet,
1676        pending_det: &mut BTreeMap<usize, Result<Vec<ocr_det::DetBox>, String>>,
1677        ocr_scale: Option<f32>,
1678        det_pages: &[(usize, &PdfPage)],
1679        layout: impl FnOnce() -> T,
1680    ) -> T {
1681        if det_pages.is_empty() {
1682            return layout();
1683        }
1684        // Loaded by `det_candidates` (which produced a non-empty list); the
1685        // lock is held while this worker's layout runs, so another worker's
1686        // detection waits for this one — its layout does not.
1687        let mut slot = det.lock().unwrap_or_else(|p| p.into_inner());
1688        let DetSlot::Ready(det) = &mut *slot else {
1689            return layout();
1690        };
1691        std::thread::scope(|s| {
1692            let handle = s.spawn(move || {
1693                det_pages
1694                    .iter()
1695                    .map(|&(n, page)| {
1696                        let mut view = None;
1697                        let (img, _) = ocr_input(
1698                            &mut view,
1699                            &page.image,
1700                            page.scale,
1701                            page_ocr_scale(ocr_scale, page.width, page.height, page.scale),
1702                        );
1703                        (
1704                            n,
1705                            timing::timed("ocr.det", || {
1706                                det.detect_scan(img, ocr_scale.is_none() && page.scale != 1.0)
1707                            }),
1708                        )
1709                    })
1710                    .collect::<Vec<_>>()
1711            });
1712            let out = layout();
1713            match handle.join() {
1714                Ok(results) => pending_det.extend(results),
1715                Err(_) => {
1716                    for &(n, _) in det_pages {
1717                        pending_det.insert(n, Err("ocr-det: detection thread panicked".into()));
1718                    }
1719                }
1720            }
1721            out
1722        })
1723    }
1724
1725    /// Content-based orientation normalization (#225), before any inference:
1726    /// a physically rotated scan (sideways phone photo, landscape-fed sheet)
1727    /// has `/Rotate 0`, so the metadata pass in `extract_page` never fires and
1728    /// layout+OCR would read a sideways raster. Only pages with no text layer
1729    /// at all are probed (a digital page's raster is upright by construction,
1730    /// and its cells — not its pixels — carry the text); the detected angle
1731    /// composes with any `/Rotate` normalization through the same
1732    /// [`PdfPage::unrotate`] + display-space assembly mapping. Detection is
1733    /// evidence-gated and degrades to a no-op — see [`orient`].
1734    fn normalize_orientation(&mut self, n: usize, page: &mut PdfPage) -> Result<(), PdfError> {
1735        let scanned =
1736            page.cells.is_empty() && page.word_cells.is_empty() && page.code_cells.is_empty();
1737        if self.no_ocr || self.skip_ocr || !orient::enabled() {
1738            return Ok(());
1739        }
1740        // A sideways page drawn as vector outlines keeps a small upright text
1741        // layer (a page number, a running header, #936): the layer is too thin
1742        // to be the page's text, so the raster is probed like a scan's. The
1743        // render may still be deferred for a page that needed no bitmap.
1744        if !scanned {
1745            if !sparse_text_layer(page) {
1746                return Ok(());
1747            }
1748            page.resolve_image()?;
1749        }
1750        if page.image.width() <= 1 {
1751            return Ok(());
1752        }
1753        // The probe reads text through the OCR model; without one (missing —
1754        // #244 degradation) the page stays as rendered.
1755        if self.ocr_model()?.is_none() {
1756            return Ok(());
1757        }
1758        // The text detector's lines are the probe's crops (#571). Detected on
1759        // the page image as rendered; an upright scan keeps them for the OCR
1760        // pass (`pending_det`) when that pass reads the same bitmap, so the
1761        // detector runs once per page as before — a rotated page detects
1762        // again on the un-rotated image, alongside layout. A page with a
1763        // (thin) text layer only needs the probe's few wide lines and its
1764        // OCR pass detects on region crops (#931), so it pays the pre-#570
1765        // 960 px budget here instead of the full one (#945).
1766        let ocr_scale = page_ocr_scale(self.ocr_scale, page.width, page.height, page.scale);
1767        let image = &page.image;
1768        let boxes: Vec<ocr_det::DetBox> = self
1769            .with_det(|det| {
1770                timing::timed("orient.det", || {
1771                    if scanned {
1772                        det.detect_scan(image, ocr_scale.is_none() && page.scale != 1.0)
1773                    } else {
1774                        det.detect_capped(image, PROBE_DET_MAX_SIDE)
1775                    }
1776                })
1777            })
1778            .unwrap_or(Ok(Vec::new()))
1779            .unwrap_or_else(|e| {
1780                debug_log!(
1781                    "docling-pdf: page {}: text detection failed ({e}); probing projection strips",
1782                    n + 1
1783                );
1784                Vec::new()
1785            });
1786        let Some(ocr) = self.ocr_model()? else {
1787            return Ok(());
1788        };
1789        let deg = timing::timed("orient.detect", || {
1790            orient::detect(&page.image, ocr, page.scale, &boxes)
1791        });
1792        if deg != 0 {
1793            debug_log!(
1794                "docling-pdf: page {}: content rotated {deg}° in the raster; \
1795                 un-rotating before layout/OCR",
1796                n + 1
1797            );
1798            page.unrotate(deg);
1799        } else if scanned
1800            && !boxes.is_empty()
1801            && ocr_scale.is_none_or(|s| (s - page.scale).abs() <= 1e-3)
1802        {
1803            self.pending_det.insert(n, Ok(boxes));
1804        }
1805        Ok(())
1806    }
1807
1808    /// Layout-detect a whole batch of pages with one inference call (issue #73),
1809    /// then run each page's remaining stages (OCR / TableFormer / enrichment /
1810    /// assembly) per page. Index-aligned with `items`; a layout failure fails
1811    /// every page in the batch (they shared the one inference call).
1812    fn process_batch(&mut self, items: &mut [(usize, PdfPage)]) -> Vec<Result<Staged, PdfError>> {
1813        if self.no_ocr {
1814            // No layout model to batch — the text-layer-only path is per page.
1815            return items
1816                .iter_mut()
1817                .map(|(n, page)| {
1818                    let n = *n;
1819                    self.process(n, page).map(Staged::Done)
1820                })
1821                .collect();
1822        }
1823        // Orientation-normalize every scanned page before the shared layout
1824        // call — the batched inference must see upright bitmaps too (#225).
1825        for (n, page) in items.iter_mut() {
1826            let n = *n;
1827            if let Err(e) = self.normalize_orientation(n, page) {
1828                // Model-load failure — every page in the batch needs the same
1829                // model, so they all fail alike (mirrors the layout-error arm).
1830                let msg = e.to_string();
1831                return items
1832                    .iter()
1833                    .map(|_| Err(PdfError::Ocr(msg.clone())))
1834                    .collect();
1835            }
1836        }
1837        let inputs: Vec<(layout::LayoutSrc<'_>, f32, f32)> = items
1838            .iter()
1839            .map(|(_, page)| (layout_src(page), page.width, page.height))
1840            .collect();
1841        let refs: Vec<(usize, &PdfPage)> = items.iter().map(|(n, page)| (*n, page)).collect();
1842        let det_pages = match self.det_candidates(&refs) {
1843            Ok(p) => p,
1844            Err(e) => {
1845                let msg = e.to_string();
1846                return items
1847                    .iter()
1848                    .map(|_| Err(PdfError::Ocr(msg.clone())))
1849                    .collect();
1850            }
1851        };
1852        let batched = {
1853            let Self {
1854                layout,
1855                det,
1856                pending_det,
1857                ocr_scale,
1858                ..
1859            } = self;
1860            let layout = layout.as_mut().expect("layout model loaded unless no_ocr");
1861            Self::detect_alongside(&*det, pending_det, *ocr_scale, &det_pages, || {
1862                timing::timed("layout.predict", || layout.predict_batch(&inputs))
1863            })
1864        };
1865        match batched {
1866            Ok(all) => items
1867                .iter_mut()
1868                .zip(all)
1869                .map(|((n, page), regions)| {
1870                    // The 2x bitmap (#682), when the detections read it (#897).
1871                    self.ensure_bitmap(page, &regions)?;
1872                    self.stage_page(*n, page, regions)
1873                })
1874                .collect(),
1875            Err(e) => items
1876                .iter()
1877                .map(|(n, _)| Err(PdfError::Layout(format!("page {}: {e}", n + 1))))
1878                .collect(),
1879        }
1880    }
1881
1882    /// A pool worker's main loop: pull rendered pages off the shared channel
1883    /// (whatever is already there, up to the layout batch size), process them,
1884    /// and hand each finished page — or its error — to `deliver`, which returns
1885    /// `false` to stop early (the streaming consumer went away). Returns when
1886    /// the channel is closed and every page this worker took is delivered.
1887    ///
1888    /// Pages whose TableFormer turn would have to wait are parked (see
1889    /// `Staged`) and retried before every new pull; while any are parked the
1890    /// pull is non-blocking, so an empty channel means the worker waits for
1891    /// the TableFormer rather than for the renderer. The parking budget
1892    /// (`MAX_DEFERRED_PAGES`) bounds resident bitmaps; past it the worker waits
1893    /// like the serial path. Output is independent of completion order — the
1894    /// callers reassemble by page index.
1895    fn run_pool(
1896        &mut self,
1897        work_rx: &Mutex<Receiver<(usize, PdfPage)>>,
1898        layout_batch: usize,
1899        deadline: &Budget,
1900        mut deliver: impl FnMut(usize, Result<PageOut, PdfError>) -> bool,
1901    ) {
1902        use std::sync::mpsc::TryRecvError;
1903        let mut deferred: std::collections::VecDeque<(usize, PdfPage, Prepared)> =
1904            std::collections::VecDeque::new();
1905        loop {
1906            // The document budget (#497), checked between pages: once it is
1907            // spent, every page still queued or parked is reported as timed
1908            // out instead of processed — the renderer stops feeding at the
1909            // same check, so the queue drains quickly.
1910            if expired(deadline) {
1911                while let Some((idx, _, _)) = deferred.pop_front() {
1912                    if !deliver(idx, Err(timeout_sentinel())) {
1913                        return;
1914                    }
1915                }
1916                let rx = work_rx.lock().unwrap();
1917                loop {
1918                    match rx.recv() {
1919                        Ok((idx, _page)) => {
1920                            if !deliver(idx, Err(timeout_sentinel())) {
1921                                return;
1922                            }
1923                        }
1924                        Err(_) => return,
1925                    }
1926                }
1927            }
1928            // Any parked page the slot has since freed up for, oldest first.
1929            let mut i = 0;
1930            while i < deferred.len() {
1931                let (_, page, prepared) = &deferred[i];
1932                match self.table_rows_try(page, &prepared.regions) {
1933                    Some(rows) => {
1934                        let (idx, mut page, prepared) = deferred.remove(i).expect("index in range");
1935                        if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1936                            return;
1937                        }
1938                    }
1939                    None => i += 1,
1940                }
1941            }
1942            // Hold the receiver lock only for the recv (plus a non-blocking drain
1943            // up to the layout batch size); release before the (long) per-page
1944            // work so other workers can pull concurrently.
1945            let mut batch: Vec<(usize, PdfPage)> = Vec::new();
1946            let mut closed = false;
1947            {
1948                let rx = work_rx.lock().unwrap();
1949                let first = if deferred.is_empty() {
1950                    rx.recv().map_err(|_| TryRecvError::Disconnected)
1951                } else {
1952                    rx.try_recv()
1953                };
1954                match first {
1955                    Ok(item) => {
1956                        batch.push(item);
1957                        while batch.len() < layout_batch {
1958                            match rx.try_recv() {
1959                                Ok(item) => batch.push(item),
1960                                Err(_) => break,
1961                            }
1962                        }
1963                    }
1964                    Err(TryRecvError::Empty) => {}
1965                    Err(TryRecvError::Disconnected) => closed = true,
1966                }
1967            }
1968            if batch.is_empty() {
1969                // Nothing new rendered (or the channel is closed): wait our turn
1970                // on the oldest parked page instead.
1971                match deferred.pop_front() {
1972                    Some((idx, mut page, prepared)) => {
1973                        let rows = self.table_rows_blocking(&page, &prepared.regions);
1974                        if !deliver(idx, self.complete_page(idx, &mut page, prepared, rows)) {
1975                            return;
1976                        }
1977                        continue;
1978                    }
1979                    None if closed => return,
1980                    None => continue,
1981                }
1982            }
1983            let outs = self.process_batch(&mut batch);
1984            for ((idx, mut page), out) in batch.into_iter().zip(outs) {
1985                let delivered = match out {
1986                    Ok(Staged::Done(out)) => deliver(idx, Ok(out)),
1987                    Ok(Staged::NeedsTables(prepared)) => {
1988                        if deferred.len() < MAX_DEFERRED_PAGES {
1989                            deferred.push_back((idx, page, prepared));
1990                            true
1991                        } else {
1992                            let rows = self.table_rows_blocking(&page, &prepared.regions);
1993                            deliver(idx, self.complete_page(idx, &mut page, prepared, rows))
1994                        }
1995                    }
1996                    Err(e) => deliver(idx, Err(e)),
1997                };
1998                if !delivered {
1999                    return;
2000                }
2001            }
2002        }
2003    }
2004
2005    /// Everything after layout detection: per-label confidence thresholds,
2006    /// overlap resolution, orphan-text recovery, OCR for cell-less pages,
2007    /// TableFormer, enrichment, and page assembly. The serial path: waits
2008    /// for the shared TableFormer when a table needs it.
2009    fn finish_page(
2010        &mut self,
2011        n: usize,
2012        page: &mut PdfPage,
2013        regions: Vec<layout::Region>,
2014    ) -> Result<PageOut, PdfError> {
2015        let prepared = self.prepare_page(n, page, regions)?;
2016        self.ensure_bitmap(page, &prepared.regions)?;
2017        let table_rows = self.table_rows_blocking(page, &prepared.regions);
2018        self.complete_page(n, page, prepared, table_rows)
2019    }
2020
2021    /// The pool path: like [`finish_page`](Self::finish_page), except that a
2022    /// page whose TableFormer turn would have to wait comes back as
2023    /// [`Staged::NeedsTables`] for the worker loop to park (see `Staged`).
2024    fn stage_page(
2025        &mut self,
2026        n: usize,
2027        page: &mut PdfPage,
2028        regions: Vec<layout::Region>,
2029    ) -> Result<Staged, PdfError> {
2030        let prepared = self.prepare_page(n, page, regions)?;
2031        self.ensure_bitmap(page, &prepared.regions)?;
2032        match self.table_rows_try(page, &prepared.regions) {
2033            Some(rows) => Ok(Staged::Done(self.complete_page(n, page, prepared, rows)?)),
2034            None => Ok(Staged::NeedsTables(prepared)),
2035        }
2036    }
2037
2038    /// Does this page read its 2x bitmap (#897)? Layout reads the separate
2039    /// 1x render; after it, the bitmap feeds TableFormer, picture crops (and
2040    /// the picture classifier, in-picture OCR and the image outputs on
2041    /// them), the code/formula enrichment crops, page images and OCR. A
2042    /// page without any of those — on a text-heavy document most pages —
2043    /// never renders it. Decided on the detections as they stand (a
2044    /// superset of what survives postprocessing, which only drops or
2045    /// demotes pictures and tables), and asked again wherever the regions
2046    /// change.
2047    fn needs_bitmap(&self, page: &PdfPage, regions: &[layout::Region]) -> bool {
2048        self.images.page_images
2049            || self.force_full_page_ocr
2050            || page.cells.is_empty()
2051            || regions.iter().any(|r| {
2052                r.label == "picture"
2053                    || assemble::is_table_like(r.label)
2054                    || (r.label == "code" && self.enrich.code)
2055                    || (r.label == "formula" && self.enrich.formula)
2056            })
2057    }
2058
2059    /// Install the page's deferred 2x bitmap (#682) if [`Self::needs_bitmap`]
2060    /// says it is read — rendering it now when it was not rendered already —
2061    /// and otherwise decline it, so the render helper skips it when it has
2062    /// not got to it yet (#897). Idempotent, and a declined page can still
2063    /// be resolved later (an fp32 layout retry with new detections).
2064    fn ensure_bitmap(
2065        &self,
2066        page: &mut PdfPage,
2067        regions: &[layout::Region],
2068    ) -> Result<(), PdfError> {
2069        if page.image_pending() {
2070            if self.needs_bitmap(page, regions) {
2071                page.resolve_image()?;
2072            } else {
2073                page.decline_image();
2074            }
2075        }
2076        Ok(())
2077    }
2078
2079    /// Does this page need the shared TableFormer at all? Table-free pages
2080    /// never touch (or load) it.
2081    fn needs_tables(&self, regions: &[layout::Region]) -> bool {
2082        self.tables.is_some() && regions.iter().any(|r| assemble::is_table_like(r.label))
2083    }
2084
2085    /// TableFormer structure for every table region of the page, on an
2086    /// already-locked slot (loading the model on first use). Tables serialise
2087    /// on this mutex, so the one instance gets the shared thread budget
2088    /// (quota-aware, #262) — DOCLING_RS_TF_INTRA narrows it further where the
2089    /// memory-per-thread tradeoff matters more than table latency.
2090    fn predict_tables(
2091        guard: &mut TfSlot,
2092        page: &PdfPage,
2093        regions: &[layout::Region],
2094    ) -> Vec<Option<tf_core::TableGrid>> {
2095        let mut table_rows: Vec<Option<tf_core::TableGrid>> = vec![None; regions.len()];
2096        debug_assert!(
2097            !page.image_pending(),
2098            "TableFormer reached an unrendered page bitmap"
2099        );
2100        guard.load();
2101        if let TfSlot::Ready(tf) = guard {
2102            // One 1024-px frame per page, shared by all of its tables, and one
2103            // call for all of them: with the dynamic-batch decoder their
2104            // decode steps are shared (each step costs about the same for B
2105            // tables as for one).
2106            let page1024 = tableformer::TableFormer::page_1024(&page.image);
2107            let (idx, boxes): (Vec<usize>, Vec<[f32; 4]>) = regions
2108                .iter()
2109                .enumerate()
2110                .filter(|(_, r)| assemble::is_table_like(r.label))
2111                .map(|(i, r)| (i, [r.l, r.t, r.r, r.b]))
2112                .unzip();
2113            let rows =
2114                tf.predict_tables_on(page.image.height(), &page1024, &boxes, &page.word_cells);
2115            for (i, grid) in idx.into_iter().zip(rows) {
2116                table_rows[i] = grid;
2117            }
2118        }
2119        table_rows
2120    }
2121
2122    /// Table structure for the page, waiting for the shared slot if another
2123    /// worker holds it (else geometric fallback downstream when there is no
2124    /// TableFormer at all). The `tableformer` timing stage here includes any
2125    /// wait.
2126    fn table_rows_blocking(
2127        &self,
2128        page: &PdfPage,
2129        regions: &[layout::Region],
2130    ) -> Vec<Option<tf_core::TableGrid>> {
2131        match self.tables.as_ref().filter(|_| self.needs_tables(regions)) {
2132            Some(slot) => timing::timed("tableformer", || {
2133                Self::predict_tables(&mut slot.lock().unwrap(), page, regions)
2134            }),
2135            None => vec![None; regions.len()],
2136        }
2137    }
2138
2139    /// Non-blocking variant: `None` when the slot is held by another worker
2140    /// right now — the caller parks the page and tries again later.
2141    fn table_rows_try(
2142        &self,
2143        page: &PdfPage,
2144        regions: &[layout::Region],
2145    ) -> Option<Vec<Option<tf_core::TableGrid>>> {
2146        let Some(slot) = self.tables.as_ref().filter(|_| self.needs_tables(regions)) else {
2147            return Some(vec![None; regions.len()]);
2148        };
2149        match slot.try_lock() {
2150            Ok(mut guard) => Some(timing::timed("tableformer", || {
2151                Self::predict_tables(&mut guard, page, regions)
2152            })),
2153            Err(std::sync::TryLockError::WouldBlock) => None,
2154            Err(std::sync::TryLockError::Poisoned(e)) => panic!("TableFormer slot poisoned: {e}"),
2155        }
2156    }
2157
2158    /// The stages before TableFormer: fp32 escalation, per-label confidence
2159    /// thresholds, overlap resolution, orphan-text recovery, OCR for cell-less
2160    /// pages, in-picture text and table-word recognition.
2161    fn prepare_page(
2162        &mut self,
2163        n: usize,
2164        page: &mut PdfPage,
2165        regions: Vec<layout::Region>,
2166    ) -> Result<Prepared, PdfError> {
2167        // Force-OCR is exactly "pretend the text layer is not there": clear
2168        // every cell kind the extractors produced before anything reads them,
2169        // and the ordinary no-text-layer machinery below — full-page OCR,
2170        // OCR-fed TableFormer matching — takes over unchanged. (`no_ocr` wins
2171        // when both are set, mirroring docling, where `force_full_page_ocr`
2172        // is a sub-option of `do_ocr`; the no-ocr path never reaches here.)
2173        // Done here rather than in `process` so the batched layout path
2174        // (`process_batch` → `finish_page`) honors the flag too.
2175        // Parse quality is scored on the extracted text layer before force-OCR
2176        // discards it (docling's page-preprocessing stage runs before OCR too,
2177        // so its parse_score also reflects the original text layer).
2178        let mut parse = quality::parse_score(&page.cells);
2179        // docling#4654 (#1006): a text layer a broken font mapping produced
2180        // (`quality::is_broken_text_layer`) is replaced by full-page OCR on
2181        // this page only, its `parse_score` zeroed — it keeps describing the
2182        // PDF layer. Judged only with OCR available: a page whose layer is
2183        // discarded with no recognizer to read it would lose its text, so a
2184        // missing model keeps the (broken) layer, degradation over failure.
2185        let replace_broken = !self.force_full_page_ocr
2186            && self.replace_broken_text_layer
2187            && parse.is_some()
2188            && quality::is_broken_text_layer(
2189                &page
2190                    .cells
2191                    .iter()
2192                    .map(|c| c.text.as_str())
2193                    .collect::<Vec<_>>()
2194                    .join("\n"),
2195            )
2196            && self.ocr_model()?.is_some();
2197        if replace_broken {
2198            debug_log!(
2199                "docling-pdf: page {}: broken text layer — replaced by full-page OCR",
2200                n + 1
2201            );
2202            parse = Some(0.0);
2203        }
2204        // Recognition confidences of every OCR'd cell on this page → ocr_score.
2205        let mut ocr_confs: Vec<f32> = Vec::new();
2206        let mut ocr_cells: Vec<docling_core::OcrCellConfidence> = Vec::new();
2207        // The bitmap the OCR reads (#254): with `ocr_scale` set, a resample of
2208        // the page render at the requested px/pt, built lazily on the first
2209        // OCR use so non-OCR pages never pay for it. Copied out of `self` up
2210        // front — the OCR sites hold `self.ocr_model()`'s mutable borrow.
2211        let ocr_scale = page_ocr_scale(self.ocr_scale, page.width, page.height, page.scale);
2212        let mut ocr_view: Option<image::RgbImage> = None;
2213        if self.force_full_page_ocr || replace_broken {
2214            page.cells.clear();
2215            page.code_cells.clear();
2216            page.word_cells.clear();
2217        }
2218        if replace_broken {
2219            // The bitmap was judged on the text layer just discarded (a prose
2220            // page declines it, #897); the OCR reads it now.
2221            self.ensure_bitmap(page, &regions)?;
2222        }
2223        // Quant-robustness guard: the default int8 layout graph keeps its
2224        // confidences near the 0.5 label thresholds, and a different CPU's
2225        // quantized kernels can flip a whole page's detections under them —
2226        // tables and paragraphs then dissolve into orphan one-liners while the
2227        // same build converts the page perfectly elsewhere. When a dense
2228        // digital page ends up with detections covering almost none of its
2229        // text cells, re-run that one page on the fp32 graph (lazy-loaded,
2230        // auto-int8 selection only) and keep whichever detections cover more.
2231        let mut regions = regions;
2232        if !page.cells.is_empty() {
2233            let thresholded = |rs: &[layout::Region]| -> Vec<layout::Region> {
2234                rs.iter()
2235                    .filter(|r| r.score >= layout::label_threshold(r.label))
2236                    .cloned()
2237                    .collect()
2238            };
2239            let text_cells = page
2240                .cells
2241                .iter()
2242                .filter(|c| !c.text.trim().is_empty())
2243                .count();
2244            let cov = assemble::layout_cell_coverage(&thresholded(&regions), &page.cells);
2245            if text_cells >= 15 && cov < 0.5 {
2246                let retry = self
2247                    .layout
2248                    .as_mut()
2249                    .expect("layout model loaded unless no_ocr")
2250                    .predict_fp32_fallback(layout_src(page), page.width, page.height)
2251                    .map_err(|e| PdfError::Layout(format!("page {}: {e}", n + 1)))?;
2252                if let Some(retry) = retry {
2253                    let cov2 = assemble::layout_cell_coverage(&thresholded(&retry), &page.cells);
2254                    if cov2 > cov {
2255                        debug_log!(
2256                            "docling-pdf: page {}: int8 layout covered {:.0}% of the text \
2257                             cells; the fp32 retry covers {:.0}% — using it",
2258                            n + 1,
2259                            cov * 100.0,
2260                            cov2 * 100.0
2261                        );
2262                        regions = retry;
2263                        // New detections may read the bitmap the first ones
2264                        // did not (#897).
2265                        self.ensure_bitmap(page, &regions)?;
2266                    }
2267                }
2268            }
2269        }
2270        // docling's LayoutPostprocessor drops each detection below its label's
2271        // confidence threshold (stricter than the 0.3 base the predictor keeps),
2272        // before any overlap resolution. This removes the low-confidence tables /
2273        // pictures / list-items that otherwise double-emit or mis-classify.
2274        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
2275            for r in &regions {
2276                eprintln!(
2277                    "DBG raw {} {:.2} [{:.2},{:.2},{:.2},{:.2}]",
2278                    r.label, r.score, r.l, r.t, r.r, r.b
2279                );
2280            }
2281        }
2282        regions.retain(|r| r.score >= layout::label_threshold(r.label));
2283        // docling's full-page picture filter and same-label picture dedup run
2284        // on the thresholded detections, before overlap resolution: a picture
2285        // that is the whole page goes (its text reads out as text), and a
2286        // figure proposed both whole and as sub-panels collapses to one box
2287        // (see `dedup_pictures`).
2288        assemble::drop_full_page_pictures(&mut regions, page.width, page.height);
2289        assemble::dedup_pictures(&mut regions);
2290        // Resolve overlapping detections once, before OCR.
2291        let mut regions = assemble::resolve(regions);
2292        // Emit text the detector missed as orphan text regions (docling parity).
2293        assemble::add_orphan_regions(&mut regions, &page.cells);
2294        // Drop phantom empty low-confidence picture boxes (docling parity).
2295        assemble::drop_false_pictures(&mut regions, &page.cells, page.width, page.height);
2296        // A regular region fully inside a surviving table/index/picture is that
2297        // special's child (a cell / in-figure label), not a separate block —
2298        // remove it so it isn't emitted twice (docling parity).
2299        assemble::drop_contained_regulars(&mut regions);
2300        // A one-line paragraph in the bottom margin under a body-less heading
2301        // is that heading's text, not furniture (deliberate deviation).
2302        assemble::reclaim_heading_body_footers(&mut regions, page.width);
2303        // No text layer → recognise text from the page image via OCR.
2304        let ocred = page.cells.is_empty();
2305        // Lines the text detector found outside every layout region (#429).
2306        let mut det_cells: Vec<pdfium_backend::TextCell> = Vec::new();
2307        if ocred {
2308            // Region-scoped OCR recognizes each region's crop, so two regular
2309            // regions over the same ink would read it twice — a low-score
2310            // paragraph box over the high-score line boxes `greedy` keeps.
2311            // Collapse such groups to one region first; a digital
2312            // page resolves the same overlap through cell ownership in
2313            // `fit_regions_to_cells` and needs nothing here.
2314            assemble::merge_overlapping_regulars(&mut regions);
2315            // The text detector's lines (#429), fetched before the region
2316            // pass: with `det` line mode (#570, the default) they are the
2317            // recognizer's crops inside the regions too — RapidOCR's own line
2318            // source — not only the supplement outside them. Usually computed
2319            // already, alongside layout (see `detect_alongside`); a page that
2320            // reached OCR another way detects here. Degradation over failure:
2321            // a detector that loaded but cannot run (a damaged file, an
2322            // allocation failure) costs the page its detected lines, not its
2323            // conversion — the projection segmentation is complete on its own.
2324            let detected: Vec<ocr_det::DetBox> = if self.ocr_model()?.is_some() {
2325                let (img, _) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2326                match self.pending_det.remove(&n) {
2327                    Some(result) => result,
2328                    None => self
2329                        .with_det(|det| {
2330                            timing::timed("ocr.det", || {
2331                                det.detect_scan(img, ocr_scale.is_none() && page.scale != 1.0)
2332                            })
2333                        })
2334                        .unwrap_or(Ok(Vec::new())),
2335                }
2336                .unwrap_or_else(|e| {
2337                    docling_core::debug_log!(
2338                        "docling-pdf: page {}: text detection failed ({e}); keeping the \
2339                         region-scoped OCR only",
2340                        n + 1
2341                    );
2342                    Vec::new()
2343                })
2344            } else {
2345                Vec::new()
2346            };
2347            docling_core::debug_log!(
2348                "docling-pdf: page {}: text detector found {} line(s): {:?}",
2349                n + 1,
2350                detected.len(),
2351                detected
2352                    .iter()
2353                    .map(|d| (
2354                        d.l.round(),
2355                        d.t.round(),
2356                        d.r.round(),
2357                        d.b.round(),
2358                        (d.score * 100.0).round() / 100.0
2359                    ))
2360                    .collect::<Vec<_>>()
2361            );
2362            let det_lines =
2363                (ocr::det_lines() && !detected.is_empty()).then_some(detected.as_slice());
2364            // `None` = `skip_ocr` or a missing model (#244): the page keeps
2365            // its layout regions (and TableFormer structure below) with no
2366            // recognized text, instead of failing the conversion.
2367            if let Some(ocr) = self.ocr_model()? {
2368                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2369                let cells = timing::timed("ocr.page", || {
2370                    ocr.ocr_page_with(img, &regions, scl, det_lines)
2371                })
2372                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2373                ocr_confs.extend(cells.iter().map(|(_, conf)| conf));
2374                ocr_cells.extend(cell_confs(&cells));
2375                page.cells = cells.into_iter().map(|(cell, _)| cell).collect();
2376                // Table interiors carry no words yet: region-scoped OCR skips
2377                // table labels, and a scanned page has no pdfium text layer — so
2378                // TableFormer's cell matcher got an empty word list and the table
2379                // dissolved (#173). Recognize the table regions' word crops
2380                // (mirroring the browser scanned path): `word_cells` feeds the
2381                // matcher, and the same cells join `cells` so the geometric
2382                // fallback and the table's region text see them too.
2383                if regions.iter().any(|r| assemble::is_table_like(r.label)) {
2384                    let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2385                    let words = timing::timed("ocr.table_words", || {
2386                        ocr.ocr_table_words(img, &regions, scl, det_lines)
2387                    })
2388                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2389                    ocr_confs.extend(words.iter().map(|(_, conf)| conf));
2390                    ocr_cells.extend(cell_confs(&words));
2391                    let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
2392                    page.cells.extend(words.iter().cloned());
2393                    page.word_cells = words;
2394                }
2395            }
2396            // docling's OCR engines detect text lines over the whole bitmap
2397            // and every line becomes a cell, so text the layout model gave no
2398            // region — a diagram's labels, a stamp, a margin note — still
2399            // reads out as orphan text. Region-scoped recognition above stays
2400            // the source inside layout regions; the detector (#429) adds only
2401            // the lines no recognized cell already covers, and the orphan pass
2402            // below places them (those inside a kept picture or table become
2403            // that special's silent children, as upstream).
2404            if self.ocr_model()?.is_some() {
2405                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2406                let uncovered = ocr_det::uncovered_lines(&detected, scl, &regions, &page.cells);
2407                docling_core::debug_log!(
2408                    "docling-pdf: page {}: {} of {} detected line(s) not covered by the region pass",
2409                    n + 1,
2410                    uncovered.len(),
2411                    detected.len()
2412                );
2413                if let Some(ocr) = self.ocr_model_if(!uncovered.is_empty())? {
2414                    let scored =
2415                        timing::timed("ocr.det_lines", || ocr.ocr_page(img, &uncovered, scl))
2416                            .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2417                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
2418                    ocr_cells.extend(cell_confs(&scored));
2419                    det_cells = scored.into_iter().map(|(cell, _)| cell).collect();
2420                    page.cells.extend(det_cells.iter().cloned());
2421                }
2422            }
2423        } else {
2424            // A page with a text layer can still draw part of its text as
2425            // vector outlines (`gs -dNoOutputFonts`, flattened print PDFs):
2426            // the layout model finds the paragraph, the text layer holds
2427            // nothing there, and the region dropped empty — one native `Page
2428            // 1` footer was enough to switch the page's OCR off (#931).
2429            // docling's default `pdf_aware_layout_regions` OCRs every layout
2430            // cluster without any programmatic text in it
2431            // (`_find_pdf_aware_layout_ocr_rects`); do the same for the text,
2432            // furniture and table regions (pictures go through the bare-
2433            // picture pass below). Its other trigger, a cluster over a
2434            // bitmap, takes the regions a scan's image covers past a thin
2435            // text layer (#999, `bitmap_regions`).
2436            let mut empty = text_less_regions(&regions, &page.cells);
2437            empty.extend(bitmap_regions(&regions, &page.cells, &page.bitmaps));
2438            if !empty.is_empty() && self.ocr_model()?.is_some() {
2439                // A page with a text layer and no picture or table had its
2440                // bitmap declined (#897); render it now — rare, and only
2441                // for the page that needs it.
2442                page.resolve_image()?;
2443                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2444                // Detected on the empty regions' crops, not the page (#945):
2445                // the page at the 2000 px budget cost ~2.3 s and ~250 MB per
2446                // such page for a caption's worth of lines; a crop reads at
2447                // full render resolution for a fraction of it. A margin of
2448                // half a line keeps the DB net's context at the edges.
2449                let rects: Vec<(u32, u32, u32, u32)> = empty
2450                    .iter()
2451                    .map(|r| {
2452                        let m = (0.5 * (r.b - r.t)).clamp(4.0, 24.0) * scl;
2453                        (
2454                            ((r.l * scl - m).max(0.0)) as u32,
2455                            ((r.t * scl - m).max(0.0)) as u32,
2456                            (r.r * scl + m).ceil() as u32,
2457                            (r.b * scl + m).ceil() as u32,
2458                        )
2459                    })
2460                    .collect();
2461                let detected = self
2462                    .with_det(|det| timing::timed("ocr.det", || det.detect_regions(img, &rects)))
2463                    .unwrap_or(Ok(Vec::new()))
2464                    .unwrap_or_else(|e| {
2465                        docling_core::debug_log!(
2466                            "docling-pdf: page {}: text detection failed ({e}); keeping the \
2467                             region-scoped OCR only",
2468                            n + 1
2469                        );
2470                        Vec::new()
2471                    });
2472                let det_lines =
2473                    (ocr::det_lines() && !detected.is_empty()).then_some(detected.as_slice());
2474                let ocr = self.ocr_model()?.expect("checked above");
2475                // docling's merge for this mode (`PDF_FIRST`): every native
2476                // cell is kept, and an OCR cell only where it touches none —
2477                // a typed-in value over its own scanned pixels is read once.
2478                let native = page.cells.clone();
2479                let pdf_first = |cells: &mut Vec<(TextCell, f32)>| {
2480                    cells.retain(|(c, _)| table_tokens::uncovered([c], &native).len() == 1)
2481                };
2482                let mut scored = timing::timed("ocr.page", || {
2483                    ocr.ocr_page_with(img, &empty, scl, det_lines)
2484                })
2485                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2486                pdf_first(&mut scored);
2487                docling_core::debug_log!(
2488                    "docling-pdf: page {}: {} text-less layout region(s) OCR'd, {} line(s)",
2489                    n + 1,
2490                    empty.len(),
2491                    scored.len()
2492                );
2493                ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
2494                ocr_cells.extend(cell_confs(&scored));
2495                page.cells.extend(scored.into_iter().map(|(cell, _)| cell));
2496                if empty.iter().any(|r| assemble::is_table_like(r.label)) {
2497                    let mut words = timing::timed("ocr.table_words", || {
2498                        ocr.ocr_table_words(img, &empty, scl, det_lines)
2499                    })
2500                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2501                    pdf_first(&mut words);
2502                    ocr_confs.extend(words.iter().map(|(_, conf)| conf));
2503                    ocr_cells.extend(cell_confs(&words));
2504                    let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
2505                    page.cells.extend(words.iter().cloned());
2506                    // TableFormer's tokens (#999, docling's
2507                    // `_words_and_ocr_cells`): the native words beside the
2508                    // surviving OCR lines — the matcher saw the natives
2509                    // alone, and one typed-in value made the whole table.
2510                    page.word_cells =
2511                        table_tokens::words_and_ocr_cells(&page.word_cells, &[], &words);
2512                }
2513            }
2514        }
2515        // Region-scoped OCR skips `picture` interiors, and a digital page's
2516        // text layer cannot see into an embedded raster either — so a figure
2517        // that is really a text box (terms-and-conditions exported as an
2518        // image) lost its words on every page kind. Python docling OCRs the
2519        // bitmap-covered areas of *every* page — even digital ones — once they
2520        // exceed `bitmap_area_threshold` (5 % of the page); the browser paths
2521        // already do. Recognize the big text-less crops here too; the panel
2522        // demotion / orphan recovery below place the lines.
2523        let mut pic_cells: Vec<pdfium_backend::TextCell> = Vec::new();
2524        {
2525            let page_area = (page.width * page.height).max(1.0);
2526            let has_text = |r: &layout::Region| {
2527                page.cells.iter().any(|c| {
2528                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
2529                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
2530                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
2531                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
2532                })
2533            };
2534            // A captioned picture can never demote to a text panel (see
2535            // recover_text_panels), and on digital pages its speculative OCR
2536            // would be discarded anyway — don't pay for it.
2537            let captioned = |r: &layout::Region| {
2538                regions.iter().any(|c| {
2539                    c.label == "caption"
2540                        && c.r.min(r.r) - c.l.max(r.l) > 0.0
2541                        && ((c.t >= r.b && c.t - r.b <= 25.0) || (r.t >= c.b && r.t - c.b <= 25.0))
2542                })
2543            };
2544            let bare: Vec<layout::Region> = regions
2545                .iter()
2546                .filter(|r| {
2547                    r.label == "picture"
2548                        && (r.r - r.l) * (r.b - r.t) / page_area >= 0.05
2549                        && !has_text(r)
2550                        && (ocred || !captioned(r))
2551                })
2552                .map(|r| layout::Region {
2553                    label: "text",
2554                    ..r.clone()
2555                })
2556                .collect();
2557            // Speculative OCR (#244): with `skip_ocr` or no model, big bare
2558            // pictures simply stay pictures.
2559            if let Some(ocr) = self.ocr_model_if(!bare.is_empty())? {
2560                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2561                let scored = timing::timed("ocr.pictures", || ocr.ocr_page(img, &bare, scl))
2562                    .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2563                // Speculative in-picture OCR counts toward ocr_score only on
2564                // OCR'd pages, where the recognized lines actually join the
2565                // output; on a digital page they may be discarded below.
2566                if ocred {
2567                    ocr_confs.extend(scored.iter().map(|(_, conf)| conf));
2568                    ocr_cells.extend(cell_confs(&scored));
2569                }
2570                pic_cells = scored.into_iter().map(|(cell, _)| cell).collect();
2571                page.cells.extend(pic_cells.iter().cloned());
2572            }
2573        }
2574        let cells_before_pic_ocr = page.cells.len() - pic_cells.len();
2575        // A "picture" that is really a colored text panel — dense, wide,
2576        // multi-line — reads out as paragraphs instead of shipping as pixels;
2577        // sparse in-picture text (a chart's labels) keeps the crop and stays
2578        // inside it as the picture's silent children (docling parity, #200).
2579        // `no_text_panels` (#173) opts out entirely for image-extraction
2580        // workflows.
2581        if !self.no_text_panels {
2582            assemble::recover_text_panels(&mut regions, &page.cells);
2583        }
2584        // On an OCR'd page, in-picture text that did NOT demote its picture
2585        // mostly stays silent, exactly as in docling: its postprocess step
2586        // "Remove regular clusters that are included in wrappers" walks
2587        // SPECIAL_TYPES — which includes PICTURE — so an orphan text cluster
2588        // >80 % contained in a kept picture becomes that picture's child and
2589        // never reaches the serializer. Only border-straddlers (≤80 %
2590        // containment) survive as text. Emitting *everything* here used to
2591        // splice a chart's OCR'd axis ticks into the body text right next to
2592        // the image chunk (#200) — so the orphan pass places the recognized
2593        // lines, the containment drop re-runs for the in-table ones, and
2594        // `assemble_page` nests the in-picture ones under their picture
2595        // (JSON-only children, `assemble::picture_parents`).
2596        if ocred && (!pic_cells.is_empty() || !det_cells.is_empty()) {
2597            // Pictures (and wrappers) no longer count as claimers (#165), so
2598            // the plain orphan pass places the recognized lines directly —
2599            // the detector's lines (#429) the same way.
2600            assemble::add_orphan_regions(&mut regions, &pic_cells);
2601            assemble::add_orphan_regions(&mut regions, &det_cells);
2602            assemble::drop_contained_regulars(&mut regions);
2603        } else if !ocred && !pic_cells.is_empty() {
2604            // Digital page, picture kept: its speculative OCR cells must not
2605            // linger in the text-cell set (they were appended at the tail).
2606            let kept: Vec<layout::Region> = regions
2607                .iter()
2608                .filter(|r| r.label == "picture")
2609                .cloned()
2610                .collect();
2611            let tail = page.cells.split_off(cells_before_pic_ocr);
2612            page.cells.extend(tail.into_iter().filter(|c| {
2613                !kept.iter().any(|r| {
2614                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
2615                    let ix = (r.r.min(c.r) - r.l.max(c.l)).max(0.0);
2616                    let iy = (r.b.min(c.b) - r.t.max(c.t)).max(0.0);
2617                    ix * iy / ca > 0.5
2618                })
2619            }));
2620        }
2621        // `picture_ocr` (#1219): on a text-layer page, every picture that
2622        // stayed a picture is read — the small ones the 5 % threshold skips
2623        // (a seal, a stamp) and the big ones whose speculative lines were just
2624        // discarded (a photo's rating label) — and its lines become the
2625        // picture's description after assembly. Each is read on its own crop
2626        // with the detector's line boxes (`read_picture_region`), not reusing
2627        // the speculative pass's lines: those are the ink-projection strips a
2628        // text panel splits into, which read a label inside a photo as
2629        // nothing. The lines never join `page.cells`: the text layer and the
2630        // layout stay exactly as without the option, only the pictures gain
2631        // an annotation.
2632        let mut picture_text: Vec<pdfium_backend::TextCell> = Vec::new();
2633        if self.picture_ocr && !ocred {
2634            let todo: Vec<layout::Region> = regions
2635                .iter()
2636                .filter(|r| r.label == "picture")
2637                .cloned()
2638                .collect();
2639            for r in &todo {
2640                let cells = timing::timed("ocr.picture_text", || {
2641                    self.read_picture_region(page, r, ocr_scale)
2642                })
2643                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2644                picture_text.extend(cells);
2645            }
2646        }
2647        // A text-less *table* detected inside a picture on a digital page — a
2648        // screenshot of a table (2203's Figure 10) — has no text layer and no
2649        // scanned-path OCR to feed it, so its grid used to serialize empty and
2650        // the whole element vanished. docling OCRs bitmap-covered areas on
2651        // every page kind and its table cluster collects those cells; mirror
2652        // the scanned path for exactly these tables: recognize word crops and
2653        // feed them to the TableFormer matcher and the cell set.
2654        if !ocred {
2655            let has_text = |t: &layout::Region| {
2656                page.cells.iter().any(|c| {
2657                    let ca = ((c.r - c.l) * (c.b - c.t)).max(1.0);
2658                    let ix = (t.r.min(c.r) - t.l.max(c.l)).max(0.0);
2659                    let iy = (t.b.min(c.b) - t.t.max(c.t)).max(0.0);
2660                    !c.text.trim().is_empty() && ix * iy / ca > 0.5
2661                })
2662            };
2663            let in_picture = |t: &layout::Region| {
2664                regions.iter().any(|r| {
2665                    r.label == "picture" && {
2666                        let ta = ((t.r - t.l) * (t.b - t.t)).max(1.0);
2667                        let ix = (r.r.min(t.r) - r.l.max(t.l)).max(0.0);
2668                        let iy = (r.b.min(t.b) - r.t.max(t.t)).max(0.0);
2669                        ix * iy / ta > 0.5
2670                    }
2671                })
2672            };
2673            let pic_tables: Vec<layout::Region> = regions
2674                .iter()
2675                .filter(|t| assemble::is_table_like(t.label) && !has_text(t) && in_picture(t))
2676                .cloned()
2677                .collect();
2678            // Same degradation as above: without OCR the in-picture table
2679            // keeps its structure (TableFormer is geometry-driven) minus text.
2680            if let Some(ocr) = self.ocr_model_if(!pic_tables.is_empty())? {
2681                let (img, scl) = ocr_input(&mut ocr_view, &page.image, page.scale, ocr_scale);
2682                let words = timing::timed("ocr.table_words", || {
2683                    ocr.ocr_table_words(img, &pic_tables, scl, None)
2684                })
2685                .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?;
2686                ocr_confs.extend(words.iter().map(|(_, conf)| conf));
2687                ocr_cells.extend(cell_confs(&words));
2688                let words: Vec<_> = words.into_iter().map(|(cell, _)| cell).collect();
2689                page.cells.extend(words.iter().cloned());
2690                page.word_cells.extend(words);
2691            }
2692        }
2693        // `do_table_structure=False`: OCR has already read any table crops.
2694        // `tables` is `None` only then on this path (`no_ocr` returns before
2695        // layout). A scan has no text layer, so dropping the region earlier
2696        // loses those words when the text detector is absent. docling emits
2697        // an empty table here; the words stay text. A missing TableFormer
2698        // model keeps `tables` as `Some` and still reconstructs.
2699        if self.tables.is_none() {
2700            assemble::release_unstructured_tables_after_ocr(&mut regions, &page.cells);
2701        }
2702        // The cells are final: fit every regular region to the cells it
2703        // claims and fold the orphans it now surrounds (#419), before
2704        // TableFormer and the reading order see the boxes.
2705        assemble::fit_regions_to_cells(&mut regions, &page.cells);
2706        Ok(Prepared {
2707            regions,
2708            ocr_confs,
2709            ocr_cells,
2710            parse,
2711            picture_text,
2712        })
2713    }
2714
2715    /// The stages after TableFormer: enrichment, the page confidence report and
2716    /// assembly into typed nodes.
2717    fn complete_page(
2718        &mut self,
2719        n: usize,
2720        page: &mut PdfPage,
2721        prepared: Prepared,
2722        table_rows: Vec<Option<tf_core::TableGrid>>,
2723    ) -> Result<PageOut, PdfError> {
2724        let Prepared {
2725            regions,
2726            ocr_confs,
2727            ocr_cells,
2728            parse,
2729            picture_text,
2730        } = prepared;
2731        // The crops and the page image below read the bitmap (#897).
2732        self.ensure_bitmap(page, &regions)?;
2733        if env::flag("DOCLING_RS_DEBUG_REGIONS") {
2734            for (i, r) in regions.iter().enumerate() {
2735                eprintln!(
2736                    "DBG final {} {:.2} [{:.0},{:.0},{:.0},{:.0}] rows={:?}",
2737                    r.label,
2738                    r.score,
2739                    r.l,
2740                    r.t,
2741                    r.r,
2742                    r.b,
2743                    table_rows[i]
2744                        .as_ref()
2745                        .map(|t| (t.rows.len(), t.rows.first().map(|r| r.len())))
2746                );
2747            }
2748            eprintln!(
2749                "DBG cells={} words={}",
2750                page.cells.len(),
2751                page.word_cells.len()
2752            );
2753        }
2754        // Enrichment passes (opt-in): DocumentPictureClassifier over picture
2755        // regions, CodeFormulaV2 over code/formula regions. Same shared-slot
2756        // shape as TableFormer — one lazily-loaded instance per pipeline, only
2757        // ever locked when a page actually has a matching region.
2758        let mut enrich_out: Vec<Option<assemble::Enrichment>> = vec![None; regions.len()];
2759        if let Some(slot) = self.classifier.as_ref() {
2760            if regions.iter().any(|r| r.label == "picture") {
2761                timing::timed("picture_classifier", || {
2762                    let mut guard = slot.lock().unwrap();
2763                    if matches!(*guard, EnrichSlot::Unloaded) {
2764                        *guard = match enrich::PictureClassifier::load_with(intra_threads()) {
2765                            Some(m) => EnrichSlot::Ready(m),
2766                            None => EnrichSlot::Missing,
2767                        };
2768                    }
2769                    if let EnrichSlot::Ready(model) = &mut *guard {
2770                        for (i, r) in regions.iter().enumerate() {
2771                            if r.label != "picture" {
2772                                continue;
2773                            }
2774                            let Some(crop) = assemble::crop_region_scaled(
2775                                page,
2776                                [r.l, r.t, r.r, r.b],
2777                                enrich::CLASSIFIER_SCALE,
2778                            ) else {
2779                                continue;
2780                            };
2781                            match model.classify(&crop) {
2782                                Ok(classes) => {
2783                                    enrich_out[i] =
2784                                        Some(assemble::Enrichment::PictureClasses(classes));
2785                                }
2786                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
2787                            }
2788                        }
2789                    }
2790                });
2791            }
2792        }
2793        if let Some(slot) = self.code_formula.as_ref() {
2794            let wants = |label: &str| {
2795                (label == "code" && self.enrich.code) || (label == "formula" && self.enrich.formula)
2796            };
2797            if regions.iter().any(|r| wants(r.label)) {
2798                timing::timed("code_formula", || {
2799                    let mut guard = slot.lock().unwrap();
2800                    if matches!(*guard, EnrichSlot::Unloaded) {
2801                        *guard = match enrich::CodeFormula::load_with(intra_threads()) {
2802                            Some(m) => EnrichSlot::Ready(m),
2803                            None => EnrichSlot::Missing,
2804                        };
2805                    }
2806                    if let EnrichSlot::Ready(model) = &mut *guard {
2807                        for (i, r) in regions.iter().enumerate() {
2808                            if !wants(r.label) {
2809                                continue;
2810                            }
2811                            // docling crops the postprocessed cluster box — the
2812                            // union of the region's text cells, not the raw
2813                            // detector box — expanded by 18% per side, at
2814                            // ~120 dpi.
2815                            let [bl, bt, br, bb] = assemble::region_cell_bbox(r, &page.cells)
2816                                .unwrap_or([r.l, r.t, r.r, r.b]);
2817                            let (w, h) = (br - bl, bb - bt);
2818                            let ex = enrich::CODE_FORMULA_EXPANSION;
2819                            let bbox = [bl - w * ex, bt - h * ex, br + w * ex, bb + h * ex];
2820                            let Some(crop) = assemble::crop_region_scaled(
2821                                page,
2822                                bbox,
2823                                enrich::CODE_FORMULA_SCALE,
2824                            ) else {
2825                                continue;
2826                            };
2827                            let kind = if r.label == "code" {
2828                                enrich::CodeFormulaKind::Code
2829                            } else {
2830                                enrich::CodeFormulaKind::Formula
2831                            };
2832                            match model.predict(&crop, kind) {
2833                                Ok(text) => {
2834                                    enrich_out[i] = Some(match kind {
2835                                        enrich::CodeFormulaKind::Code => {
2836                                            let (code, language) =
2837                                                enrich::extract_code_language(&text);
2838                                            assemble::Enrichment::Code {
2839                                                language,
2840                                                text: code,
2841                                            }
2842                                        }
2843                                        enrich::CodeFormulaKind::Formula => {
2844                                            assemble::Enrichment::Formula { latex: text }
2845                                        }
2846                                    });
2847                                }
2848                                Err(e) => eprintln!("docling-pdf: page {}: {e}", n + 1),
2849                            }
2850                        }
2851                    }
2852                });
2853            }
2854        }
2855        // Score the final region set (docling assigns layout_score over the
2856        // postprocessed clusters — the page elements assemble_page emits,
2857        // which leave out the regulars nested in a picture as its children).
2858        let parents = assemble::picture_parents(&regions);
2859        let elements: Vec<layout::Region> = regions
2860            .iter()
2861            .zip(&parents)
2862            .filter(|(_, p)| p.is_none())
2863            .map(|(r, _)| r.clone())
2864            .collect();
2865        let conf = quality::page_confidence(parse, &elements, &ocr_confs);
2866        let (mut nodes, links) = timing::timed("assemble_page", || {
2867            assemble::assemble_page(page, regions, &table_rows, &enrich_out, self.images.scale)
2868        });
2869        if !picture_text.is_empty() {
2870            let provenance = match self.ocr_engine {
2871                ocr::OcrEngine::PpOcr => "ppocr",
2872                ocr::OcrEngine::Tesseract => "tesseract",
2873            };
2874            picture::describe_pictures(&mut nodes, page, &picture_text, provenance);
2875        }
2876        Ok((nodes, links, conf, self.page_image(n, page), ocr_cells))
2877    }
2878}
2879
2880#[cfg(feature = "ml")]
2881/// Per-worker ONNX intra-op threads. The layout model is memory-bandwidth bound,
2882/// so on a typical machine two threads per worker (sharing one in-cache copy of
2883/// the weights) extracts more throughput than one fat model or many single-thread
2884/// workers. `DOCLING_RS_PDF_INTRA` overrides for per-machine tuning.
2885fn pdf_intra() -> usize {
2886    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_INTRA").filter(|&n| n > 0) {
2887        return n;
2888    }
2889    if intra_threads() >= 2 {
2890        2
2891    } else {
2892        1
2893    }
2894}
2895
2896#[cfg(feature = "ml")]
2897/// How many page-workers to spin up for a multi-page PDF. `DOCLING_RS_PDF_WORKERS`
2898/// overrides; otherwise size the pool so `workers × intra ≈ cores`.
2899///
2900/// The pool scales with the machine (#324 follow-up testing): the old hard cap
2901/// of 4 left most of a many-core box idle — on a 16-core M4 Max, 10 workers
2902/// measured ~1.2× over the capped pool (10.0 → 8.5 s on a 130-page document,
2903/// byte-identical output). The ceiling of 16 is a memory bound, not a
2904/// performance one: each worker holds its own layout/OCR sessions (~0.4 GB),
2905/// so a worst-case pool stays under ~6.5 GB even on a ≥32-core host — and
2906/// docling-serve's per-request pools sit behind its `DOCLING_RS_MAX_MEMORY_MB`
2907/// admission control besides. Machines with 4 or fewer effective threads keep
2908/// the exact old sizing (`threads / intra`, min 1).
2909fn pdf_worker_count() -> usize {
2910    if let Some(n) = env::parse::<usize>("DOCLING_RS_PDF_WORKERS").filter(|&n| n > 0) {
2911        return n;
2912    }
2913    // One GPU behind every worker (#842): the pool multiplies the sessions,
2914    // and on the device that is memory, not speed — the serial primary's
2915    // render-ahead already overlaps rasterization with inference.
2916    if docling_onnx::prefers_single_worker() {
2917        return 1;
2918    }
2919    (intra_threads() / pdf_intra()).clamp(1, 16)
2920}
2921
2922#[cfg(feature = "ml")]
2923/// Max pages a worker layout-detects with one batched inference call (issue
2924/// #73). Workers drain the work channel opportunistically up to this size —
2925/// whatever is already rendered gets batched, so batching never *waits* for
2926/// pages and adds no latency when rendering is the bottleneck.
2927///
2928/// Default: per-page (1) on the CPU provider, 4 when a CUDA-class GPU
2929/// provider is selected (#338) — CoreML stays per-page (#602,
2930/// [`docling_onnx::prefers_batching`]): only the pinned batch=1 graph is
2931/// static, and static partitions are all CoreML is allowed to take. The old
2932/// "4 on 8+ cores" CPU default was a hypothesis — that single-session
2933/// amortization pays off with a wider thread budget —
2934/// and every actual CPU measurement lands the other way: a 4-core x86 box
2935/// runs the 9-page 2206.01062 fixture in 8.5 s/conv at batch=1 vs 9.3 s at
2936/// batch=4 (re-measured for #338; the original 8.1 vs 9.3 agrees), and the
2937/// issue-#338 report measured batch=1 ~2× faster on a 16-core M4 Max at
2938/// every worker count — batching only adds cache pressure once workers
2939/// saturate the cores. On a GPU the per-call dispatch overhead is real and
2940/// batching amortizes it, so the GPU default stays. Output is bit-identical
2941/// at every batch size, so this is purely a throughput knob.
2942/// `DOCLING_RS_PDF_LAYOUT_BATCH` overrides either way; `1` = per-page.
2943pub(crate) fn pdf_layout_batch() -> usize {
2944    env::parse::<usize>("DOCLING_RS_PDF_LAYOUT_BATCH")
2945        .filter(|&n| n > 0)
2946        .unwrap_or_else(|| {
2947            if docling_onnx::prefers_batching() {
2948                4
2949            } else {
2950                1
2951            }
2952        })
2953}
2954
2955#[cfg(feature = "ml")]
2956/// Pages the serial path renders ahead of the one being processed
2957/// ([`Pipeline::render_ahead`], #682): one in flight on the worker, two
2958/// rendered and waiting — a bound on resident page bitmaps, like the
2959/// pool's channel.
2960const RENDER_AHEAD: usize = 2;
2961
2962#[cfg(feature = "ml")]
2963/// Minimum page count before a PDF goes to the parallel worker pool; below
2964/// it the serial primary runs its model on every core. Four since #682 (was
2965/// six, from the days of the pool's uncached model load): the layout model's
2966/// intra-op scaling is weak (on a 4-core x86 box 4 threads run a page 2.35×
2967/// faster than one, 2 threads 1.6×), so two workers of two threads convert
2968/// pages faster than one worker of four converts them in turn — 4–5-page
2969/// digital documents measured 18% faster than the serial path with its
2970/// render-ahead, the pool's load included (the pool is sized to the page
2971/// count, [`Pipeline::ensure_pool_for`]). Not lower: the text detector a
2972/// scanned page needs scales well with threads, so a 2–3-page scan runs
2973/// 15–20% *slower* split across two-thread workers than on the four-thread
2974/// primary. `DOCLING_RS_PDF_PARALLEL_MIN` overrides.
2975fn pdf_parallel_min() -> usize {
2976    env::parse::<usize>("DOCLING_RS_PDF_PARALLEL_MIN")
2977        .filter(|&n| n > 0)
2978        .unwrap_or(4)
2979}
2980
2981#[cfg(feature = "ml")]
2982/// A reusable PDF pipeline. The **primary** worker runs its models on every core,
2983/// so a single-page / small / image / METS input is converted at full intra-op
2984/// speed with no pool to load. A document with enough pages instead fans out
2985/// across a **pool** of narrower workers processed concurrently. Both load lazily
2986/// and are cached for reuse, so a one-shot conversion only pays for what it uses.
2987pub struct Pipeline {
2988    /// Full-intra worker for the serial path; loaded on first serial use.
2989    primary: Option<Worker>,
2990    /// Narrower workers (≈cores/`target_workers` threads each) for the parallel
2991    /// path; loaded on first multi-page use and cached.
2992    pool: Vec<Worker>,
2993    /// The single TableFormer instance every worker shares (see [`TfSlot`]).
2994    tables: SharedTables,
2995    /// The pool-wide text detector slot (#945), see [`DetSlot`].
2996    det: SharedDet,
2997    /// The shared enrichment-model slots (same pattern as [`TfSlot`]).
2998    classifier: SharedClassifier,
2999    code_formula: SharedCodeFormula,
3000    /// Desired pool size for multi-page documents.
3001    target_workers: usize,
3002    /// Page count at/above which the parallel pool is worth its load cost.
3003    parallel_min: usize,
3004    /// Skip loading/running TableFormer; table regions fall back to geometric
3005    /// reconstruction. See [`Pipeline::no_table_former`].
3006    no_table_former: bool,
3007    /// Skip layout, OCR, and TableFormer entirely. See [`Pipeline::no_ocr`].
3008    no_ocr: bool,
3009    /// Per document: the text layer alone when it carries the text, the
3010    /// full pipeline otherwise. See [`Pipeline::text_layer_auto`].
3011    text_layer_auto: bool,
3012    /// Keep layout + TableFormer, never OCR (#244). See [`Pipeline::skip_ocr`].
3013    skip_ocr: bool,
3014    /// OCR every page even when it carries a text layer. See
3015    /// [`Pipeline::force_full_page_ocr`].
3016    force_full_page_ocr: bool,
3017    /// OCR only the pages whose text layer is broken (#1006). See
3018    /// [`Pipeline::replace_broken_text_layer`].
3019    replace_broken_text_layer: bool,
3020    /// Read the pictures of a text-layer page (#1219). See
3021    /// [`Pipeline::picture_ocr`].
3022    picture_ocr: bool,
3023    /// Mark superscripts and subscripts (#1005). See
3024    /// [`Pipeline::script_positions`].
3025    script_positions: bool,
3026    /// Never demote text-panel pictures. See [`Pipeline::no_text_panels`].
3027    no_text_panels: bool,
3028    /// Opt-in enrichment passes. See [`Pipeline::enrichments`].
3029    enrich: EnrichmentOptions,
3030    /// 1-based inclusive page window to convert. See [`Pipeline::pages`].
3031    page_range: Option<(usize, usize)>,
3032    /// OCR recognition language. See [`Pipeline::ocr_lang`].
3033    ocr_lang: ocr::OcrLang,
3034    /// Which OCR engine runs (#460). See [`Pipeline::ocr_engine`].
3035    ocr_engine: ocr::OcrEngine,
3036    /// Tesseract's languages (#460). See [`Pipeline::tesseract_lang`].
3037    tesseract_lang: Option<String>,
3038    /// Which regions feed the OCR (#254). See [`Pipeline::ocr_mode`].
3039    ocr_mode: ocr::OcrMode,
3040    /// OCR render scale override in px/pt (#254). See [`Pipeline::ocr_scale`].
3041    ocr_scale: Option<f32>,
3042    /// Picture OCR scale (#666). See [`Pipeline::picture_ocr_scale`].
3043    picture_ocr_scale: Option<f32>,
3044    /// The text layer's word-gap rule (#921); `None` = the environment's
3045    /// (`DOCLING_RS_PDF_WORD_GAP`), else [`WordGap::Adaptive`].
3046    word_gap: Option<WordGap>,
3047    /// Keep typographic punctuation as drawn (#921); `None` = the
3048    /// environment's (`DOCLING_RS_PDF_KEEP_TYPOGRAPHY`), else folding.
3049    keep_typography: Option<bool>,
3050    /// RapidOCR's line orientation handling (#666). See
3051    /// [`Pipeline::ocr_textline_orientation`].
3052    textline_orientation: bool,
3053    /// Picture-crop scale and page images (#519/#520). See
3054    /// [`Pipeline::images_scale`] / [`Pipeline::generate_page_images`].
3055    images: ImageOutput,
3056    /// Heading-level inference (#302). See [`Pipeline::heading_hierarchy`].
3057    heading_hierarchy: HeadingHierarchyOptions,
3058    /// Optional per-page progress hook, invoked after each page finishes on
3059    /// every walk — the serial and parallel buffered paths, both streaming
3060    /// paths and the pre-rendered page path (images, METS). The converter
3061    /// turns it into its progress events (#783); `None` costs nothing.
3062    progress: Option<PageProgressHook>,
3063    /// Per-document wall-clock budget (docling's `document_timeout`, #497).
3064    /// See [`Pipeline::document_timeout`].
3065    document_timeout: Option<std::time::Duration>,
3066    /// Cooperative cancellation (#1260). See [`Pipeline::set_cancel`].
3067    cancel: Option<CancelToken>,
3068}
3069
3070#[cfg(feature = "ml")]
3071impl Pipeline {
3072    /// Construct the pipeline. Models load lazily on first use (full-intra primary
3073    /// for serial inputs, the helper pool for multi-page PDFs), so nothing is
3074    /// loaded that a given document doesn't need.
3075    pub fn new() -> Result<Self, PdfError> {
3076        Ok(Self {
3077            primary: None,
3078            pool: Vec::new(),
3079            tables: Arc::new(Mutex::new(TfSlot::Unloaded)),
3080            det: Arc::new(Mutex::new(DetSlot::Unloaded)),
3081            classifier: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
3082            code_formula: Arc::new(Mutex::new(EnrichSlot::Unloaded)),
3083            target_workers: pdf_worker_count(),
3084            parallel_min: pdf_parallel_min(),
3085            no_table_former: false,
3086            no_ocr: false,
3087            text_layer_auto: false,
3088            skip_ocr: false,
3089            force_full_page_ocr: false,
3090            replace_broken_text_layer: false,
3091            picture_ocr: false,
3092            script_positions: false,
3093            no_text_panels: false,
3094            enrich: EnrichmentOptions::default(),
3095            page_range: None,
3096            ocr_lang: ocr::OcrLang::from_env(),
3097            ocr_engine: ocr::OcrEngine::from_env(),
3098            tesseract_lang: None,
3099            ocr_mode: ocr::OcrMode::from_env(),
3100            ocr_scale: ocr::scale_from_env(),
3101            picture_ocr_scale: ocr::picture_scale_from_env(),
3102            word_gap: None,
3103            keep_typography: None,
3104            textline_orientation: ocr::textline_orientation_from_env(),
3105            images: ImageOutput::default(),
3106            heading_hierarchy: HeadingHierarchyOptions::default(),
3107            progress: None,
3108            document_timeout: None,
3109            cancel: None,
3110        })
3111    }
3112
3113    /// A wall-clock budget for each document (docling's
3114    /// `PipelineOptions.document_timeout`, #497; `None` = unlimited, the
3115    /// default). The budget starts when a conversion starts and is checked
3116    /// cooperatively between pages: once it is spent, no further page is
3117    /// rendered or processed, the pages already finished are assembled into
3118    /// the document, and the outcome says so (`Completion::TimedOut`, which
3119    /// the converter reports as `PartialSuccess` with a timeout error, the
3120    /// way docling does). A page in flight finishes — the check costs
3121    /// nothing inside a page, and a single-page document (an image) is never
3122    /// cut. For a long-lived pipeline use
3123    /// [`set_document_timeout`](Self::set_document_timeout) before each
3124    /// conversion.
3125    pub fn document_timeout(mut self, timeout: Option<std::time::Duration>) -> Self {
3126        self.document_timeout = timeout;
3127        self
3128    }
3129
3130    /// In-place variant of [`document_timeout`](Self::document_timeout) for a
3131    /// warm pipeline — set it before every conversion so no request inherits
3132    /// a previous one's budget.
3133    pub fn set_document_timeout(&mut self, timeout: Option<std::time::Duration>) {
3134        self.document_timeout = timeout;
3135    }
3136
3137    /// Cooperative cancellation of the next conversions (#1260): once the
3138    /// token is cancelled, the running conversion stops at its next page
3139    /// boundary and fails with [`PdfError::Cancelled`]. `None` (the
3140    /// default) = never cancelled. A warm pipeline sets it before every
3141    /// conversion, like the budget, so no request inherits another's token.
3142    pub fn set_cancel(&mut self, cancel: Option<CancelToken>) {
3143        self.cancel = cancel;
3144    }
3145
3146    /// The budget of a conversion starting now: the configured
3147    /// `document_timeout` as a deadline, plus the cancellation token.
3148    fn deadline(&self) -> Budget {
3149        Budget {
3150            deadline: self.document_timeout.map(|t| std::time::Instant::now() + t),
3151            cancel: self.cancel.clone(),
3152        }
3153    }
3154
3155    /// The error a cancelled conversion fails with, `Ok` when it was not.
3156    fn check_cancelled(budget: &Budget) -> Result<(), PdfError> {
3157        if budget.cancelled() {
3158            return Err(PdfError::Cancelled);
3159        }
3160        Ok(())
3161    }
3162
3163    /// The [`Completion`] of a walk that processed `done` of `selected` pages.
3164    fn completion(&self, timed_out: bool, done: usize, selected: usize) -> Completion {
3165        match (timed_out, self.document_timeout) {
3166            (true, Some(budget)) => Completion::TimedOut {
3167                pages_done: done,
3168                pages_selected: selected,
3169                budget,
3170            },
3171            _ => Completion::Complete,
3172        }
3173    }
3174
3175    /// Infer section-header levels after assembly (#302, docling's
3176    /// `HeadingHierarchyModel`): PDF bookmarks > legal/outline numbering >
3177    /// font style, off by default — see [`HeadingHierarchyOptions`]. Pure
3178    /// post-processing configuration; for a warm pipeline use
3179    /// [`set_heading_hierarchy`](Self::set_heading_hierarchy).
3180    pub fn heading_hierarchy(mut self, opts: HeadingHierarchyOptions) -> Self {
3181        self.heading_hierarchy = opts;
3182        self
3183    }
3184
3185    /// In-place variant of [`heading_hierarchy`](Self::heading_hierarchy) for
3186    /// a long-lived pipeline (docling-serve's warm instance) — like
3187    /// [`set_pages`](Self::set_pages), set it before every conversion so no
3188    /// request inherits a previous one's choice.
3189    pub fn set_heading_hierarchy(&mut self, opts: HeadingHierarchyOptions) {
3190        self.heading_hierarchy = opts;
3191    }
3192
3193    /// Run the enabled heading-hierarchy stage (#302) on an assembled
3194    /// document: gather the outline (bookmarks) and the per-page glyph styles
3195    /// on demand, then assign levels in place. `bytes` is `None` on paths
3196    /// with no PDF behind them (standalone images, METS) — those degrade to
3197    /// the numbering signal, exactly like docling without parsed pages.
3198    fn apply_heading_hierarchy(&self, nodes: &mut [Node], bytes: Option<&[u8]>) {
3199        let opts = &self.heading_hierarchy;
3200        if !opts.enabled {
3201            return;
3202        }
3203        let outline = match bytes {
3204            Some(bytes) if opts.use_bookmarks => outline::extract_outline(bytes),
3205            _ => Vec::new(),
3206        };
3207        let styles = match bytes {
3208            Some(bytes) if opts.use_style => {
3209                let pages = heading_hierarchy::heading_pages(nodes);
3210                textparse::glyph_styles(bytes, &pages)
3211            }
3212            _ => Default::default(),
3213        };
3214        heading_hierarchy::apply(nodes, &outline, &styles, opts);
3215    }
3216
3217    /// Run the opt-in script-position stage (#1005) on an assembled
3218    /// document, after the heading hierarchy as docling runs it.
3219    fn apply_script_positions(&self, nodes: &mut [Node], bytes: &[u8]) {
3220        if self.script_positions {
3221            timing::timed("script_position", || script_position::apply(nodes, bytes));
3222        }
3223    }
3224
3225    /// Mark superscript and subscript text — docling's
3226    /// `script_position_options.enabled` (docling#4815, #1005). Characters
3227    /// drawn smaller than their line and raised or lowered against it
3228    /// (footnote markers, `1st`, `mc²`, `H₂O`) become runs with
3229    /// `formatting.script`: a paragraph or footnote holding them keeps its
3230    /// place, and its text moves into an inline group of the runs in the
3231    /// JSON (HTML `<sup>`/`<sub>`, DocLang `<superscript>`/`<subscript>`);
3232    /// Markdown joins the runs as docling does (`E = mc2 in 1905.`, where the
3233    /// plain text layer reads `E = mc 2 in 1905.`). Headings, captions,
3234    /// tables, code, formulas, list items, OCR'd and invisible text are left
3235    /// alone. Off by default: the output is unchanged.
3236    pub fn script_positions(mut self, enable: bool) -> Self {
3237        self.set_script_positions(enable);
3238        self
3239    }
3240
3241    /// In-place variant of [`script_positions`](Self::script_positions).
3242    pub fn set_script_positions(&mut self, enable: bool) {
3243        self.script_positions = enable;
3244    }
3245
3246    /// Install (or clear) the per-page progress hook: called with a
3247    /// [`PageProgress`] after each page completes, on every conversion entry
3248    /// point ([`convert`](Self::convert), the streaming variants,
3249    /// [`convert_image`](Self::convert_image), [`process_pages`](Self::process_pages)).
3250    /// Shared with the parallel workers, so the callback must be cheap and
3251    /// thread-safe. A page the budget cut off is never reported here — the
3252    /// walk's [`Completion`] says how many were; the converter reports those
3253    /// as failed pages (#783).
3254    pub fn set_progress(&mut self, cb: Option<PageProgressHook>) {
3255        self.progress = cb;
3256    }
3257
3258    /// Convert only pages `first..=last` (**1-based**, like the page numbers a
3259    /// PDF viewer shows — issue #80's `--pages A-B`). Out-of-range pages are
3260    /// skipped before rasterization, so the cost is proportional to the window,
3261    /// not the document. `last` past the end of the document clamps; a window
3262    /// that selects no pages at all (`first` beyond the last page) is an error
3263    /// at convert time. `None` (the default) converts everything.
3264    pub fn pages(mut self, range: Option<(usize, usize)>) -> Self {
3265        self.page_range = range;
3266        self
3267    }
3268
3269    /// In-place variant of [`pages`](Self::pages) for a long-lived pipeline
3270    /// (e.g. docling-serve's warm instance) that applies a per-request window
3271    /// without rebuilding — unlike the model switches, the window is pure
3272    /// configuration. Set it before every conversion; it stays until changed.
3273    pub fn set_pages(&mut self, range: Option<(usize, usize)>) {
3274        self.page_range = range;
3275    }
3276
3277    /// OCR recognition language (see [`OcrLang`]): English by default, `ch`
3278    /// for the multilingual docling-conformance model. `None` keeps the
3279    /// process default (`DOCLING_RS_OCR_LANG`, else English). Set before the
3280    /// first conversion; for a warm pipeline use
3281    /// [`set_ocr_lang`](Self::set_ocr_lang).
3282    pub fn ocr_lang(mut self, lang: Option<ocr::OcrLang>) -> Self {
3283        self.set_ocr_lang(lang);
3284        self
3285    }
3286
3287    /// In-place variant of [`ocr_lang`](Self::ocr_lang) for a long-lived
3288    /// pipeline (docling-serve's warm instance). Unlike the page window this
3289    /// is a *model* switch: any worker whose cached recognition model was
3290    /// loaded for a different language drops it, to be lazily reloaded on the
3291    /// next OCR-needing page (cheap — the rec models are ~10 MB).
3292    pub fn set_ocr_lang(&mut self, lang: Option<ocr::OcrLang>) {
3293        let lang = lang.unwrap_or_else(ocr::OcrLang::from_env);
3294        self.ocr_lang = lang;
3295        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3296            if worker.ocr_lang != lang {
3297                worker.ocr_lang = lang;
3298                worker.ocr = OcrSlot::Unloaded;
3299            }
3300        }
3301    }
3302
3303    /// Which OCR engine recognizes text (#460, see [`OcrEngine`]): the
3304    /// built-in PP-OCRv3 recognizer by default, or the system `tesseract`
3305    /// binary (docling's `TesseractCliOcrOptions`) — same layout-region
3306    /// crops, same cells; Tesseract does its own line/word segmentation and
3307    /// reads orientation from its OSD. `None` keeps the process default
3308    /// (`DOCLING_RS_OCR_ENGINE`, else PP-OCR). Set before the first
3309    /// conversion; for a warm pipeline use
3310    /// [`set_ocr_engine`](Self::set_ocr_engine).
3311    pub fn ocr_engine(mut self, engine: Option<ocr::OcrEngine>) -> Self {
3312        self.set_ocr_engine(engine);
3313        self
3314    }
3315
3316    /// In-place variant of [`ocr_engine`](Self::ocr_engine): a model switch
3317    /// like [`set_ocr_lang`](Self::set_ocr_lang) — workers holding the other
3318    /// engine drop it, to be lazily reloaded.
3319    pub fn set_ocr_engine(&mut self, engine: Option<ocr::OcrEngine>) {
3320        let engine = engine.unwrap_or_else(ocr::OcrEngine::from_env);
3321        self.ocr_engine = engine;
3322        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3323            if worker.ocr_engine != engine {
3324                worker.ocr_engine = engine;
3325                worker.ocr = OcrSlot::Unloaded;
3326            }
3327        }
3328    }
3329
3330    /// What the OCR requests of the conversions since the last call met
3331    /// (#1210), and clear it: `None` when nothing asked for OCR (a digital
3332    /// PDF, `skip_ocr`, `no_ocr`), [`OcrStatus::Available`] when the engine
3333    /// read every request, [`OcrStatus::Unavailable`] — with the load error
3334    /// — when one went without it because the engine could not load (the
3335    /// #244 degradation: the conversion succeeds, the text OCR would have
3336    /// read is missing). A caller reads it after each conversion; a warm
3337    /// pipeline's caller also once before, to drop what an earlier
3338    /// conversion that failed half-way left behind.
3339    ///
3340    /// [`OcrStatus::Available`]: docling_core::OcrStatus::Available
3341    /// [`OcrStatus::Unavailable`]: docling_core::OcrStatus::Unavailable
3342    pub fn take_ocr_status(&mut self) -> Option<docling_core::OcrStatus> {
3343        self.primary
3344            .iter_mut()
3345            .chain(self.pool.iter_mut())
3346            .fold(None, |acc, worker| {
3347                docling_core::OcrStatus::merge_opt(acc, worker.ocr_status.take())
3348            })
3349    }
3350
3351    /// Tesseract's languages (#460): the `-l` argument, tessdata stems joined
3352    /// with `+` — build it from an `ocr_lang` value with
3353    /// [`tesseract_lang_arg`], which also maps BCP-47 tags and the PP-OCR
3354    /// codes. `None` runs Tesseract's default (`eng`). Ignored under the
3355    /// PP-OCR engine, whose language is [`ocr_lang`](Self::ocr_lang). For a
3356    /// warm pipeline use [`set_tesseract_lang`](Self::set_tesseract_lang).
3357    pub fn tesseract_lang(mut self, lang: Option<String>) -> Self {
3358        self.set_tesseract_lang(lang);
3359        self
3360    }
3361
3362    /// In-place variant of [`tesseract_lang`](Self::tesseract_lang): a model
3363    /// switch like [`set_ocr_lang`](Self::set_ocr_lang) — a worker whose
3364    /// Tesseract was probed for other languages drops it.
3365    pub fn set_tesseract_lang(&mut self, lang: Option<String>) {
3366        self.tesseract_lang = lang.clone();
3367        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3368            if worker.tesseract_lang != lang {
3369                worker.tesseract_lang = lang.clone();
3370                if worker.ocr_engine == ocr::OcrEngine::Tesseract {
3371                    worker.ocr = OcrSlot::Unloaded;
3372                }
3373            }
3374        }
3375    }
3376
3377    /// Resolve the configured 1-based window against a page count into the
3378    /// 0-based inclusive form the backend walks, validating it selects at
3379    /// least one existing page.
3380    fn resolve_range(&self, total: usize) -> Result<Option<(usize, usize)>, PdfError> {
3381        let Some((first, last)) = self.page_range else {
3382            return Ok(None);
3383        };
3384        if first == 0 || last < first {
3385            return Err(PdfError::Pdfium(format!(
3386                "invalid page range {first}-{last} (pages are 1-based, first <= last)"
3387            )));
3388        }
3389        if first > total {
3390            return Err(PdfError::Pdfium(format!(
3391                "page range {first}-{last} is outside the document ({total} page(s))"
3392            )));
3393        }
3394        Ok(Some((first - 1, last.min(total) - 1)))
3395    }
3396
3397    /// Enable the opt-in enrichment passes (docling's
3398    /// `do_picture_classification` / `do_code_enrichment` /
3399    /// `do_formula_enrichment`). Each enabled pass lazily loads its model on
3400    /// the first matching region; a missing model warns once and is skipped.
3401    /// Set before the first conversion (no effect on already-loaded workers).
3402    pub fn enrichments(mut self, opts: EnrichmentOptions) -> Self {
3403        self.enrich = opts;
3404        self
3405    }
3406
3407    /// Skip table structure — docling's `do_table_structure=False`
3408    /// (`--no-tables`). Layout still runs. docling 2.150 still emits an
3409    /// empty table for that region (`text=""`, no cells). This port drops
3410    /// it after OCR and keeps the words as text items, each with its own
3411    /// box. The geometric grid is the other case, when TableFormer was
3412    /// requested and its model files are missing.
3413    /// No effect if a worker is already loaded; set this before the first
3414    /// conversion.
3415    pub fn no_table_former(mut self, disable: bool) -> Self {
3416        self.no_table_former = disable;
3417        self
3418    }
3419
3420    /// Keep every detected `picture` region as a picture. By default an
3421    /// *uncaptioned* picture that reads like a dense, uniform text panel (a
3422    /// terms-and-conditions box exported as an image) is demoted into
3423    /// paragraphs (#157); a chart the layout mislabels can still trip that
3424    /// heuristic on scanned pages, and image-extraction workflows may simply
3425    /// want every crop — this flag disables the demotion entirely (#173).
3426    /// No effect on already-loaded workers; set before the first conversion.
3427    pub fn no_text_panels(mut self, disable: bool) -> Self {
3428        self.no_text_panels = disable;
3429        self
3430    }
3431
3432    /// Skip layout detection, OCR, and TableFormer entirely — no model load, no
3433    /// inference of any kind. The PDF's embedded text cells are grouped by line
3434    /// and emitted as plain paragraphs in reading order: no headings, lists,
3435    /// tables, code blocks, or pictures, since that structure comes from the
3436    /// layout model. The fastest possible PDF path, but pages with no embedded
3437    /// text layer (scanned/image-only PDFs) yield no text at all — convert those
3438    /// without this flag. Implies `no_table_former`. A PDF conversion reads
3439    /// the flag per call (its pages never touch a worker); image and METS
3440    /// pages read the flag the workers were loaded with, so set it before
3441    /// the first conversion for those.
3442    pub fn no_ocr(mut self, disable: bool) -> Self {
3443        self.no_ocr = disable;
3444        self
3445    }
3446
3447    /// Decide per document between the two: a PDF whose embedded text layer
3448    /// carries its text converts as under [`no_ocr`](Self::no_ocr) — the
3449    /// text layer alone, flat paragraphs, no model loaded, no inference —
3450    /// and one without a usable layer (scanned / image-only, or a vestigial
3451    /// layer of a few typed-in form fields; [`text_layer_has_text`]) runs the
3452    /// full pipeline, which OCRs its pages. The verdict is the document's,
3453    /// not a page's: a digital file with a few scanned pages inserted keeps
3454    /// the text path, and those pages come back empty as under `no_ocr`.
3455    /// `no_ocr` wins when both are set; forcing (`force_full_page_ocr`,
3456    /// `ocr_mode`) is read only on the pipeline side of the verdict, as
3457    /// under `no_ocr`. A per-conversion setting: the workers and their
3458    /// models are untouched, so a warm pipeline serving digital and scanned
3459    /// documents in turn reloads nothing.
3460    pub fn text_layer_auto(mut self, enable: bool) -> Self {
3461        self.text_layer_auto = enable;
3462        self
3463    }
3464
3465    /// Set [`text_layer_auto`](Self::text_layer_auto) on a built pipeline.
3466    pub fn set_text_layer_auto(&mut self, enable: bool) {
3467        self.text_layer_auto = enable;
3468    }
3469
3470    /// Never run OCR, but keep layout detection and TableFormer — docling's
3471    /// independent `do_ocr=False` (#244), the counterpart of
3472    /// [`no_table_former`](Self::no_table_former). Unlike
3473    /// [`no_ocr`](Self::no_ocr) (which skips the whole ML stack), structured
3474    /// output — headings, tables, pictures, reading order — is preserved;
3475    /// only text that exists solely as pixels is lost: scanned pages come
3476    /// back with their regions empty, and the speculative OCR of large
3477    /// embedded images never runs. The OCR model is never loaded. Ignored
3478    /// when `no_ocr` is set (there is no OCR to skip);
3479    /// takes precedence over [`force_full_page_ocr`](Self::force_full_page_ocr),
3480    /// mirroring docling where forcing is a sub-option of `do_ocr`.
3481    pub fn skip_ocr(mut self, disable: bool) -> Self {
3482        self.skip_ocr = disable;
3483        self
3484    }
3485
3486    /// OCR every page from its rendered image even when the page carries an
3487    /// embedded text layer — docling's `force_full_page_ocr`. The escape hatch
3488    /// for text layers that exist but lie: broken encodings, subset fonts with
3489    /// garbage mappings, a scanned form with a few typed-in fields. Ignored
3490    /// when [`no_ocr`](Self::no_ocr) is set, mirroring docling (there
3491    /// `force_full_page_ocr` is a sub-option of `do_ocr`).
3492    pub fn force_full_page_ocr(mut self, force: bool) -> Self {
3493        self.force_full_page_ocr = force;
3494        self
3495    }
3496
3497    /// Which document regions feed the OCR — docling's `OcrMode` (#254). The
3498    /// default (`default` = `pdf_aware_layout_regions`) is the standard
3499    /// text-layer-aware behavior; `full_page`/`layout_regions` discard the
3500    /// text layer like [`force_full_page_ocr`](Self::force_full_page_ocr)
3501    /// (see [`ocr::OcrMode`] for why both map onto it). Whichever of the flag
3502    /// and the mode demands forcing wins, mirroring docling's
3503    /// `force_full_page_ocr` → `mode=full_page` bridge. `None` keeps the
3504    /// process default (`DOCLING_RS_OCR_MODE`, else `default`).
3505    pub fn ocr_mode(mut self, mode: Option<ocr::OcrMode>) -> Self {
3506        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
3507        self
3508    }
3509
3510    /// In-place variants of [`force_full_page_ocr`](Self::force_full_page_ocr),
3511    /// [`ocr_mode`](Self::ocr_mode) and [`ocr_scale`](Self::ocr_scale) for a
3512    /// long-lived pipeline (docling-serve's warm instance): all three are pure
3513    /// per-worker configuration — no model reloads — so they apply per request
3514    /// like [`set_pages`](Self::set_pages). Set them before every conversion so
3515    /// no request inherits a previous one's choice.
3516    pub fn set_force_full_page_ocr(&mut self, force: bool) {
3517        self.force_full_page_ocr = force;
3518        self.sync_ocr_config();
3519    }
3520
3521    /// Replace a broken PDF text layer with OCR, page by page — docling's
3522    /// `replace_broken_text_layer` (docling#4654, #1006). A page whose text
3523    /// layer [`quality::is_broken_text_layer`] judges broken — control,
3524    /// U+FFFD or private-use characters on the page or in many of its
3525    /// lines, Latin letters that stand for another script, too few vowels —
3526    /// is read with full-page OCR, its `parse_score` set to 0; every other
3527    /// page, and a page without a text layer, keeps the usual behavior. A
3528    /// low `parse_score` alone never replaces a page. Off by default;
3529    /// ignored under [`no_ocr`](Self::no_ocr) / [`skip_ocr`](Self::skip_ocr)
3530    /// (a sub-option of docling's `do_ocr`) and moot under
3531    /// [`force_full_page_ocr`](Self::force_full_page_ocr). Pure per-worker
3532    /// configuration, like the forcing flag.
3533    pub fn replace_broken_text_layer(mut self, replace: bool) -> Self {
3534        self.set_replace_broken_text_layer(replace);
3535        self
3536    }
3537
3538    /// In-place variant of
3539    /// [`replace_broken_text_layer`](Self::replace_broken_text_layer).
3540    pub fn set_replace_broken_text_layer(&mut self, replace: bool) {
3541        self.replace_broken_text_layer = replace;
3542        self.sync_ocr_config();
3543    }
3544
3545    /// Read the text inside the pictures of a page that has a text layer
3546    /// (#1219) — the PDF side of `do_picture_ocr`. By default such a page
3547    /// OCRs only the bare pictures that cover ≥ 5 % of it (docling's
3548    /// `bitmap_area_threshold`) and keeps their lines only when the
3549    /// picture demotes to a text panel; a seal, a stamp or a photo's
3550    /// rating label keeps no text at all. With this on, every picture that
3551    /// stays a picture is OCR'd on its own crop, with the text detector's
3552    /// line boxes when `ocr_det.onnx` is installed, and its lines land on it as docling's `description`
3553    /// annotation (`provenance` = the OCR engine), where the picture OCR of
3554    /// the other formats puts them — Markdown prints it under the caption,
3555    /// JSON writes `meta.description`. Docling instead nests the OCR cells
3556    /// under the picture as children, which Markdown prints only with
3557    /// `traverse_pictures`; the annotation keeps one shape for every
3558    /// format. Scanned pages are unchanged — the page OCR reads their
3559    /// pictures already. Off by default: same output, same time. Ignored
3560    /// under [`no_ocr`](Self::no_ocr) / [`skip_ocr`](Self::skip_ocr).
3561    pub fn picture_ocr(mut self, enable: bool) -> Self {
3562        self.set_picture_ocr(enable);
3563        self
3564    }
3565
3566    /// In-place variant of [`picture_ocr`](Self::picture_ocr).
3567    pub fn set_picture_ocr(&mut self, enable: bool) {
3568        self.picture_ocr = enable;
3569        self.sync_ocr_config();
3570    }
3571
3572    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
3573    pub fn set_ocr_mode(&mut self, mode: Option<ocr::OcrMode>) {
3574        self.ocr_mode = mode.unwrap_or_else(ocr::OcrMode::from_env);
3575        self.sync_ocr_config();
3576    }
3577
3578    /// How the text layer splits words where the PDF draws no space glyph
3579    /// (#921): docling-parse ≥ 7's line-local [`WordGap::Adaptive`]
3580    /// threshold (the default), a fixed [`WordGap::Factor`] of the two
3581    /// flanking glyphs' mean advance, or [`WordGap::Legacy`] (docling-parse
3582    /// ≤ 6's running-mean rule). `None` keeps `DOCLING_RS_PDF_WORD_GAP`,
3583    /// else the default.
3584    pub fn set_word_gap(&mut self, gap: Option<WordGap>) {
3585        self.word_gap = gap;
3586    }
3587
3588    /// See [`set_force_full_page_ocr`](Self::set_force_full_page_ocr).
3589    pub fn set_ocr_scale(&mut self, scale: Option<f32>) {
3590        self.ocr_scale = scale
3591            .filter(|s| s.is_finite() && *s > 0.0)
3592            .or_else(ocr::scale_from_env);
3593        self.sync_ocr_config();
3594    }
3595
3596    /// Resolution of the picture-OCR enrichment (#645) in pixels per
3597    /// picture pixel, before RapidOCR's 2000 px longer-side cap (#666) —
3598    /// RapidOCR reads a picture at its native pixels (`1.0`) and only
3599    /// shrinks what exceeds 2000 px. `None` (default:
3600    /// `DOCLING_RS_PICTURE_OCR_SCALE`, else unset) keeps the image-input
3601    /// rule pictures shared with scanned images: [`ocr_scale`](Self::ocr_scale)
3602    /// when set, else 3 px/pt shrunk to the 2000 px cap — which upscales a
3603    /// 720 × 180 screenshot to 2000 × 500. Pages and image inputs are
3604    /// unaffected. Non-positive values are ignored.
3605    pub fn picture_ocr_scale(mut self, scale: Option<f32>) -> Self {
3606        self.set_picture_ocr_scale(scale);
3607        self
3608    }
3609
3610    /// In-place [`picture_ocr_scale`](Self::picture_ocr_scale) for a warm
3611    /// pipeline.
3612    pub fn set_picture_ocr_scale(&mut self, scale: Option<f32>) {
3613        self.picture_ocr_scale = scale
3614            .filter(|s| s.is_finite() && *s > 0.0)
3615            .or_else(ocr::picture_scale_from_env);
3616    }
3617
3618    /// RapidOCR's handling of text-line orientation (#666), off by default
3619    /// (`DOCLING_RS_OCR_TEXTLINE_ORIENTATION` sets the process default): each
3620    /// detected line is cropped along the detector's rotated rectangle (a
3621    /// perspective warp, `get_rotate_crop_image`) instead of its axis-aligned
3622    /// box, a crop at least 1.5× taller than wide is turned 90°
3623    /// counter-clockwise, and the PP-LCNet text-line orientation classifier
3624    /// (`.models/ocr_textline_ori.onnx`, `DOCLING_OCR_TEXTLINE_ORI_ONNX`)
3625    /// turns lines it reads as upside down (`180` above 0.9). Vertical axis
3626    /// titles, rotated headers, skewed and upside-down lines then read as
3627    /// text. Applies to every PP-OCR line read off the detector — pages and
3628    /// pictures alike — but not to table words or the projection fallback;
3629    /// the reported boxes stay axis-aligned. A missing classifier warns once
3630    /// and keeps the crop and the 90° turn. Tesseract orients on its own.
3631    pub fn ocr_textline_orientation(mut self, enable: bool) -> Self {
3632        self.set_ocr_textline_orientation(Some(enable));
3633        self
3634    }
3635
3636    /// In-place [`ocr_textline_orientation`](Self::ocr_textline_orientation)
3637    /// for a warm pipeline (serve, the bindings' `Pipeline`), applied to
3638    /// loaded workers too; `None` restores the process default
3639    /// (`DOCLING_RS_OCR_TEXTLINE_ORIENTATION`), like
3640    /// [`set_ocr_scale`](Self::set_ocr_scale).
3641    pub fn set_ocr_textline_orientation(&mut self, enable: Option<bool>) {
3642        self.textline_orientation = enable.unwrap_or_else(ocr::textline_orientation_from_env);
3643        self.sync_ocr_config();
3644    }
3645
3646    /// Whether page extraction should decode the text layer at all. Forced
3647    /// full-page OCR (the flag or `ocr_mode=full_page|layout_regions`) clears
3648    /// every extracted cell unread, so the decode is skipped outright —
3649    /// docling#4061's `skip_cell_extraction` (2.122). `no_ocr` wins over the
3650    /// forcing, as everywhere else: its fast path *is* the text layer.
3651    fn extract_text_layer(&self) -> bool {
3652        self.no_ocr || !(self.force_full_page_ocr || self.ocr_mode.forces_full_page())
3653    }
3654
3655    /// When the walk renders the 2x bitmaps of pages with a text layer
3656    /// (#897). Adaptively by default: while the document's recent pages read
3657    /// theirs, each starts on the helper thread as the page leaves the walk,
3658    /// overlapping layout (#682); while they do not (prose), only a page that
3659    /// reads it renders it, after layout. Page images read every bitmap, so
3660    /// they keep the #682 schedule. `DOCLING_RS_PAGE_BITMAP` picks one
3661    /// explicitly: `eager` (every bitmap, during layout), `adaptive`,
3662    /// `on-demand` (only the bitmaps read — the least CPU, with every render
3663    /// after layout).
3664    fn bitmap_render(&self) -> pdfium_backend::BitmapRender {
3665        use pdfium_backend::BitmapRender;
3666        match env::nonempty("DOCLING_RS_PAGE_BITMAP")
3667            .map(|v| v.to_ascii_lowercase())
3668            .as_deref()
3669        {
3670            Some("eager") => BitmapRender::Eager,
3671            Some("on-demand" | "ondemand" | "lazy") => BitmapRender::OnDemand,
3672            _ if self.images.page_images => BitmapRender::Eager,
3673            _ => BitmapRender::Adaptive,
3674        }
3675    }
3676
3677    /// Push the current OCR forcing/scale choice onto already-loaded workers
3678    /// (new workers read it at [`Worker::load`]).
3679    fn sync_ocr_config(&mut self) {
3680        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
3681        let scale = self.ocr_scale;
3682        let orient = self.textline_orientation;
3683        let replace = self.replace_broken_text_layer;
3684        let pictures = self.picture_ocr;
3685        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3686            worker.force_full_page_ocr = force;
3687            worker.replace_broken_text_layer = replace;
3688            worker.picture_ocr = pictures;
3689            worker.ocr_scale = scale;
3690            worker.set_textline_orientation(orient);
3691        }
3692    }
3693
3694    /// Pixels per PDF point for picture crops and page images — docling's
3695    /// `images_scale` (#519/#520). `None` (the default) delivers crops at the
3696    /// pipeline's own page render, 2.0 px/pt (144 dpi), untouched. Another
3697    /// value resamples that render (CatmullRom, docling's PIL BICUBIC), so
3698    /// values above 2.0 upsample rather than re-render. Each picture's
3699    /// `dpi` (docling-core's `ImageRef.dpi`) is 72·scale, so consumers mapping
3700    /// pixels back to points stay exact. Layout, OCR and TableFormer inputs
3701    /// are unaffected. Non-positive values are ignored.
3702    pub fn images_scale(mut self, scale: Option<f32>) -> Self {
3703        self.set_images(ImageOutput {
3704            scale,
3705            ..self.images
3706        });
3707        self
3708    }
3709
3710    /// Keep each page's render as the document's page image — docling's
3711    /// `generate_page_images` (#520): the JSON export writes it as the page's
3712    /// `image` (docling-core's `PageItem.image`, at [`Self::images_scale`],
3713    /// `dpi` = 72·scale), which is what docling-core's
3714    /// `TableItem.get_image` / `FormulaItem.get_image` crop from. Off by
3715    /// default: a page image is a full-page PNG per page held in memory.
3716    /// Pages converted with `no_ocr` (text layer only) are never rendered and
3717    /// get none; streaming conversions carry no page map and drop them.
3718    pub fn generate_page_images(mut self, enabled: bool) -> Self {
3719        self.set_images(ImageOutput {
3720            page_images: enabled,
3721            ..self.images
3722        });
3723        self
3724    }
3725
3726    /// Use a picture's embedded image instead of the render crop when its
3727    /// region holds exactly one image XObject with nothing painted over it —
3728    /// docling's `use_embedded_picture_images` (#1007, docling#5143). The
3729    /// bitmap keeps its native pixel size and the picture's `dpi` is 72; a
3730    /// masked, transparent, clipped, rotated or overlapped image, a second
3731    /// image or text in the box, a `/Rotate`d page or an image that does not
3732    /// decode keep the crop. Off by default; layout, OCR and page images are
3733    /// unaffected.
3734    pub fn use_embedded_picture_images(mut self, enabled: bool) -> Self {
3735        self.set_images(ImageOutput {
3736            embedded_pictures: enabled,
3737            ..self.images
3738        });
3739        self
3740    }
3741
3742    /// Both image outputs at once, also on already-loaded workers — the
3743    /// per-request form a warm pipeline (serve, the Node `Pipeline`) uses,
3744    /// like [`set_ocr_scale`](Self::set_ocr_scale). A non-finite or
3745    /// non-positive scale reads as unset.
3746    pub fn set_images(&mut self, images: ImageOutput) {
3747        self.images = ImageOutput {
3748            scale: images.scale.filter(|s| s.is_finite() && *s > 0.0),
3749            ..images
3750        };
3751        let images = self.images;
3752        for worker in self.primary.iter_mut().chain(self.pool.iter_mut()) {
3753            worker.images = images;
3754        }
3755    }
3756
3757    /// OCR render scale in pixels per PDF point — docling's `OcrOptions.scale`
3758    /// (#254, upstream docling#3877; their default 3 = 216 dpi). `None`
3759    /// (default: `DOCLING_RS_OCR_SCALE`, else unset) feeds the recognizer the
3760    /// pipeline's own page render (2.0 px/pt = 144 dpi) for a rendered page,
3761    /// and for a standalone image input docling's own resolution (#570): 3
3762    /// px/pt shrunk so the longer side stays within RapidOCR's 2000 px — what
3763    /// its models see after RapidOCR's `max_side_len` pass (a 754 × 1000 scan
3764    /// reads at 2.0). A set value resamples the render / image for the OCR
3765    /// input only — layout and TableFormer keep their pinned-resolution
3766    /// pixels, so the conformance baseline never moves. Lower it when the
3767    /// source raster is already high-resolution and upscaling degrades
3768    /// recognition; raise it toward docling's 216 dpi for parity experiments.
3769    /// Non-positive values are ignored.
3770    pub fn ocr_scale(mut self, scale: Option<f32>) -> Self {
3771        self.ocr_scale = scale
3772            .filter(|s| s.is_finite() && *s > 0.0)
3773            .or_else(ocr::scale_from_env);
3774        self
3775    }
3776
3777    /// Keep typographic punctuation as drawn — `„ “ ‚ ‘`, dashes, `…` —
3778    /// instead of folding it to ASCII as docling-parse's sanitizer does
3779    /// (`pdf_keep_typography`, #921). `None` keeps
3780    /// `DOCLING_RS_PDF_KEEP_TYPOGRAPHY`, else folding.
3781    pub fn set_keep_typography(&mut self, keep: Option<bool>) {
3782        self.keep_typography = keep;
3783    }
3784
3785    /// See [`set_keep_typography`](Self::set_keep_typography).
3786    pub fn keep_typography(mut self, keep: Option<bool>) -> Self {
3787        self.keep_typography = keep;
3788        self
3789    }
3790
3791    /// The text-layer settings the page walk applies.
3792    fn text_options(&self) -> pdfium_backend::TextOptions {
3793        pdfium_backend::TextOptions {
3794            word_gap: self.word_gap,
3795            keep_typography: self
3796                .keep_typography
3797                .unwrap_or_else(assemble::keep_typography_from_env),
3798            embedded_pictures: self.images.embedded_pictures,
3799        }
3800    }
3801
3802    /// See [`set_word_gap`](Self::set_word_gap).
3803    pub fn word_gap(mut self, gap: Option<WordGap>) -> Self {
3804        self.word_gap = gap;
3805        self
3806    }
3807
3808    /// The shared TableFormer slot handed to each worker, or `None` when the
3809    /// pipeline options skip TableFormer entirely.
3810    fn tables_slot(&self) -> Option<SharedTables> {
3811        if self.no_table_former || self.no_ocr {
3812            None
3813        } else {
3814            Some(Arc::clone(&self.tables))
3815        }
3816    }
3817
3818    /// The shared enrichment slots for a worker (`None` per model unless its
3819    /// flag is on; `no_ocr` skips layout, so there are no regions to enrich).
3820    fn enrich_slots(&self) -> (Option<SharedClassifier>, Option<SharedCodeFormula>) {
3821        if self.no_ocr || !self.enrich.any() {
3822            return (None, None);
3823        }
3824        (
3825            self.enrich
3826                .picture_classification
3827                .then(|| Arc::clone(&self.classifier)),
3828            (self.enrich.code || self.enrich.formula).then(|| Arc::clone(&self.code_formula)),
3829        )
3830    }
3831
3832    /// Eagerly load the models (the full-intra serial worker: layout + OCR, and
3833    /// the shared TableFormer unless disabled) so the first conversion doesn't pay
3834    /// the load cost. Idempotent; respects `no_ocr` / `no_table_former` (with
3835    /// `no_ocr` there is nothing to load). The docling.rs analogue of docling's
3836    /// `DocumentConverter.initialize_pipeline`.
3837    pub fn warm_up(&mut self) -> Result<(), PdfError> {
3838        self.primary()?;
3839        // The shared TableFormer loads on the first table otherwise — a
3840        // document with one would still pay for it (#548).
3841        if let Some(tables) = self.tables_slot() {
3842            tables.lock().unwrap_or_else(|p| p.into_inner()).load();
3843        }
3844        Ok(())
3845    }
3846
3847    /// [`warm_up`](Self::warm_up) plus the parallel page-worker pool, so the
3848    /// first *multi-page* conversion is no slower than later ones either: a
3849    /// document of `DOCLING_RS_PDF_PARALLEL_MIN` pages (6) or more fans out across the pool,
3850    /// whose workers each load their own layout/OCR sessions on first use
3851    /// (#548 — docling-serve's `--warmup` left a 9-page PDF paying that load).
3852    /// Costs the pool's memory up front (~0.4 GB a worker); with a pool of one
3853    /// worker it is exactly `warm_up`.
3854    pub fn warm_up_all(&mut self) -> Result<(), PdfError> {
3855        self.warm_up()?;
3856        if self.target_workers >= 2 {
3857            self.ensure_pool()?;
3858        }
3859        Ok(())
3860    }
3861
3862    /// The full-intra serial worker, loaded on first use.
3863    fn primary(&mut self) -> Result<&mut Worker, PdfError> {
3864        if self.primary.is_none() {
3865            self.primary = Some(Worker::load(
3866                intra_threads(),
3867                self.tables_slot(),
3868                Arc::clone(&self.det),
3869                self.enrich_slots(),
3870                self.enrich,
3871                self.no_ocr,
3872                self.skip_ocr,
3873                // The mode-shaped spelling (#254) and the flag are one engine
3874                // truth: whichever demands forcing wins, mirroring docling's
3875                // `force_full_page_ocr` → `mode=full_page` bridge.
3876                self.force_full_page_ocr || self.ocr_mode.forces_full_page(),
3877                self.no_text_panels,
3878                self.ocr_lang,
3879                self.ocr_engine,
3880                self.tesseract_lang.clone(),
3881                self.ocr_scale,
3882                self.textline_orientation,
3883                self.images,
3884            )?);
3885            if let Some(w) = self.primary.as_mut() {
3886                w.replace_broken_text_layer = self.replace_broken_text_layer;
3887                w.picture_ocr = self.picture_ocr;
3888            }
3889        }
3890        Ok(self.primary.as_mut().unwrap())
3891    }
3892
3893    /// Convert a PDF (bytes) to a [`DoclingDocument`]. A document with fewer than
3894    /// `parallel_min` pages (or a pool size of 1) streams through the full-intra
3895    /// primary; a larger one renders on this thread (pdfium is not thread-safe) and
3896    /// fans the pages out across the worker pool, reassembled in page order so the
3897    /// output is byte-identical to the serial path.
3898    pub fn convert(
3899        &mut self,
3900        bytes: &[u8],
3901        password: Option<&str>,
3902        name: &str,
3903    ) -> Result<DoclingDocument, PdfError> {
3904        self.convert_outcome(bytes, password, name)
3905            .map(|c| c.document)
3906    }
3907
3908    /// [`convert`](Self::convert) that also says how the conversion ended —
3909    /// whether the [`document_timeout`](Self::document_timeout) cut it short
3910    /// and how many pages made it (`Completion`).
3911    pub fn convert_outcome(
3912        &mut self,
3913        bytes: &[u8],
3914        password: Option<&str>,
3915        name: &str,
3916    ) -> Result<Converted, PdfError> {
3917        let deadline = self.deadline();
3918        let pages = pdfium_backend::page_count(bytes, password)?;
3919        let range = self.resolve_range(pages)?;
3920        // Serial vs parallel is decided by the pages actually converted: a
3921        // 3-page window over a 500-page PDF should not pay the pool load.
3922        let selected = range.map_or(pages, |(a, b)| b - a + 1);
3923        let (document, done, timed_out) = if self.text_only_for(bytes, password)? {
3924            self.convert_text_only(bytes, password, name, range, selected, &deadline)?
3925        } else if self.target_workers >= 2 && selected >= self.parallel_min {
3926            self.convert_parallel(bytes, password, name, range, selected, &deadline)?
3927        } else {
3928            self.convert_serial(bytes, password, name, range, selected, &deadline)?
3929        };
3930        timing::report();
3931        // A cancelled walk stopped like a timed-out one; nobody waits for
3932        // its pages, so it fails instead of reporting a partial document.
3933        Self::check_cancelled(&deadline)?;
3934        Ok(Converted {
3935            document,
3936            completion: self.completion(timed_out, done, selected),
3937        })
3938    }
3939
3940    /// Whether this document converts from its text layer alone: always
3941    /// under [`no_ocr`](Self::no_ocr); under
3942    /// [`text_layer_auto`](Self::text_layer_auto), when the layer carries
3943    /// the text ([`text_layer_has_text`]). Decided before any worker — and
3944    /// so any model — is touched.
3945    fn text_only_for(&self, bytes: &[u8], password: Option<&str>) -> Result<bool, PdfError> {
3946        if self.no_ocr {
3947            return Ok(true);
3948        }
3949        if !self.text_layer_auto {
3950            return Ok(false);
3951        }
3952        let has_text = text_layer_has_text(bytes, password)?;
3953        docling_core::debug_log!(
3954            "text_layer_only=auto: {}",
3955            if has_text {
3956                "the text layer carries the document, converting it alone"
3957            } else {
3958                "no usable text layer, running the full pipeline"
3959            }
3960        );
3961        Ok(has_text)
3962    }
3963
3964    /// The text layer alone, page by page — no worker, no model, no page
3965    /// bitmap: [`text_only_page`] on each extracted page, in order. The path
3966    /// of [`no_ocr`](Self::no_ocr) and of an [`auto`](Self::text_layer_auto)
3967    /// document with text; byte-identical to the serial walk, since the
3968    /// worker's `no_ocr` branch is the same function.
3969    fn convert_text_only(
3970        &mut self,
3971        bytes: &[u8],
3972        password: Option<&str>,
3973        name: &str,
3974        range: Option<(usize, usize)>,
3975        selected: usize,
3976        deadline: &Budget,
3977    ) -> Result<(DoclingDocument, usize, bool), PdfError> {
3978        let mut doc = DoclingDocument::new(name);
3979        let mut confs = std::collections::BTreeMap::new();
3980        let images = self.images;
3981        let progress = self.progress.clone();
3982        let mut done = 0usize;
3983        let timed_out = Self::render_ahead(
3984            bytes,
3985            password,
3986            false,
3987            pdfium_backend::BitmapRender::Eager,
3988            true,
3989            range,
3990            deadline,
3991            self.text_options(),
3992            |n, page| {
3993                let (mut nodes, links, conf) = text_only_page(&page, images.scale);
3994                assemble::stamp_page_no(&mut nodes, n + 1);
3995                if let Some(img) = page_image_under(images, n, &page) {
3996                    doc.page_images.insert(n + 1, img);
3997                }
3998                doc.nodes.extend(nodes);
3999                doc.links.extend(links);
4000                confs.insert(n + 1, conf);
4001                done += 1;
4002                if let Some(cb) = &progress {
4003                    cb(PageProgress {
4004                        page_no: n + 1,
4005                        pages_done: done,
4006                        pages_selected: selected,
4007                    });
4008                }
4009                Ok(())
4010            },
4011        )?;
4012        assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::Lines);
4013        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
4014        self.apply_script_positions(&mut doc.nodes, bytes);
4015        doc.confidence = Some(docling_core::ConfidenceReport::from_pages(confs));
4016        Ok((doc, done, timed_out))
4017    }
4018
4019    /// Stream pages one at a time through the primary worker — render → process →
4020    /// drop — so the document holds ~one page bitmap (~5 MB) at a time.
4021    fn convert_serial(
4022        &mut self,
4023        bytes: &[u8],
4024        password: Option<&str>,
4025        name: &str,
4026        range: Option<(usize, usize)>,
4027        selected: usize,
4028        deadline: &Budget,
4029    ) -> Result<(DoclingDocument, usize, bool), PdfError> {
4030        let mut doc = DoclingDocument::new(name);
4031        let mut confs = std::collections::BTreeMap::new();
4032        let mut ocr_cells_by_page = std::collections::BTreeMap::new();
4033        let render_image = !self.no_ocr;
4034        let bitmap = self.bitmap_render();
4035        let extract_text = self.extract_text_layer();
4036        let progress = self.progress.clone();
4037        let mut done = 0usize;
4038        let text = self.text_options();
4039        let worker = self.primary()?;
4040        let timed_out = Self::render_ahead(
4041            bytes,
4042            password,
4043            render_image,
4044            bitmap,
4045            extract_text,
4046            range,
4047            deadline,
4048            text,
4049            |n, mut page| {
4050                let (mut nodes, links, conf, page_image, ocr_cells) =
4051                    worker.process(n, &mut page)?;
4052                assemble::stamp_page_no(&mut nodes, n + 1);
4053                if let Some(img) = page_image {
4054                    doc.page_images.insert(n + 1, img);
4055                }
4056                doc.nodes.extend(nodes);
4057                doc.links.extend(links);
4058                confs.insert(n + 1, conf);
4059                ocr_cells_by_page.insert(n + 1, ocr_cells);
4060                done += 1;
4061                if let Some(cb) = &progress {
4062                    cb(PageProgress {
4063                        page_no: n + 1,
4064                        pages_done: done,
4065                        pages_selected: selected,
4066                    });
4067                }
4068                Ok(())
4069            },
4070        )?;
4071        assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::AcrossPages);
4072        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
4073        self.apply_script_positions(&mut doc.nodes, bytes);
4074        doc.confidence = Some(confidence_report(confs, ocr_cells_by_page));
4075        Ok((doc, done, timed_out))
4076    }
4077
4078    /// The serial path's schedule (#682): pages render on a scoped thread
4079    /// and queue through a [`RENDER_AHEAD`]-page channel while the primary
4080    /// worker processes the previous one on the calling thread, so a page's
4081    /// two rasters (about a third of a digital page's cost) hide behind
4082    /// layout and TableFormer instead of preceding them — the render-ahead
4083    /// the worker pool always had, for documents too small for the pool.
4084    /// One consumer, pages in order: the output is byte-identical to the
4085    /// sequential walk. `consume` runs on the calling thread (a streaming
4086    /// `emit` need not be `Send`). A spent budget (#497) ends the walk at
4087    /// the renderer and the consumer alike; a consumer error closes the
4088    /// channel, which stops the renderer, and is the one reported.
4089    #[allow(clippy::too_many_arguments)]
4090    fn render_ahead<F>(
4091        bytes: &[u8],
4092        password: Option<&str>,
4093        render_image: bool,
4094        bitmap: pdfium_backend::BitmapRender,
4095        extract_text: bool,
4096        range: Option<(usize, usize)>,
4097        deadline: &Budget,
4098        text: pdfium_backend::TextOptions,
4099        mut consume: F,
4100    ) -> Result<bool, PdfError>
4101    where
4102        F: FnMut(usize, PdfPage) -> Result<(), PdfError>,
4103    {
4104        let (tx, rx) = sync_channel::<(usize, PdfPage)>(RENDER_AHEAD);
4105        std::thread::scope(|s| {
4106            let render = s.spawn(move || {
4107                pdfium_backend::walk_pages(
4108                    bytes,
4109                    password,
4110                    render_image,
4111                    extract_text,
4112                    range,
4113                    bitmap,
4114                    text,
4115                    |n, _total, page| {
4116                        if expired(deadline) {
4117                            return Err(timeout_sentinel());
4118                        }
4119                        tx.send((n, page))
4120                            .map_err(|_| PdfError::Pdfium("page channel closed".into()))
4121                    },
4122                )
4123            });
4124            let mut timed_out = false;
4125            let mut failed = None;
4126            for (n, page) in rx.iter() {
4127                if expired(deadline) {
4128                    timed_out = true;
4129                    break;
4130                }
4131                if let Err(e) = consume(n, page) {
4132                    failed = Some(e);
4133                    break;
4134                }
4135            }
4136            // Closing the channel ends a walk still rendering.
4137            drop(rx);
4138            let walk = render
4139                .join()
4140                .map_err(|_| PdfError::Pdfium("page render thread panicked".into()))?;
4141            if let Some(e) = failed {
4142                return Err(e);
4143            }
4144            match walk {
4145                Ok(()) => Ok(timed_out),
4146                Err(PdfError::Timeout(_)) => Ok(true),
4147                Err(_) if timed_out => Ok(true),
4148                Err(e) => Err(e),
4149            }
4150        })
4151    }
4152
4153    /// Render pages serially on this thread (pdfium) and process them in parallel
4154    /// across the worker pool. A bounded channel applies backpressure so only a
4155    /// handful of page bitmaps are resident at once; results carry their page
4156    /// index and are reassembled in order, so the output is byte-identical to the
4157    /// serial path.
4158    fn convert_parallel(
4159        &mut self,
4160        bytes: &[u8],
4161        password: Option<&str>,
4162        name: &str,
4163        range: Option<(usize, usize)>,
4164        selected: usize,
4165        deadline: &Budget,
4166    ) -> Result<(DoclingDocument, usize, bool), PdfError> {
4167        let text = self.text_options();
4168        self.ensure_pool_for(selected)?;
4169        let progress = self.progress.clone();
4170        let pages_done = std::sync::atomic::AtomicUsize::new(0);
4171        let timed_out = std::sync::atomic::AtomicBool::new(false);
4172        let n_workers = self.pool.len();
4173        let render_image = !self.no_ocr;
4174        let bitmap = self.bitmap_render();
4175        let extract_text = self.extract_text_layer();
4176        let layout_batch = pdf_layout_batch();
4177        // Bound sized so every worker can accumulate a full layout batch while
4178        // rendering stays ahead (and never below the pre-#73 render-ahead of
4179        // two pages per worker); still a hard cap on resident page bitmaps.
4180        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
4181        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
4182        let results: Arc<Mutex<Vec<(usize, PageOut)>>> = Arc::new(Mutex::new(Vec::new()));
4183        let first_err: Arc<Mutex<Option<PdfError>>> = Arc::new(Mutex::new(None));
4184
4185        // Move the pool into the scope so each worker gets an exclusive `&mut`.
4186        let mut workers = std::mem::take(&mut self.pool);
4187        std::thread::scope(|s| {
4188            for worker in workers.iter_mut() {
4189                let work_rx = Arc::clone(&work_rx);
4190                let results = Arc::clone(&results);
4191                let first_err = Arc::clone(&first_err);
4192                let progress = progress.clone();
4193                let pages_done = &pages_done;
4194                let timed_out = &timed_out;
4195                s.spawn(move || {
4196                    worker.run_pool(&work_rx, layout_batch, deadline, |idx, out| {
4197                        match out {
4198                            Ok(out) => {
4199                                results.lock().unwrap().push((idx, out));
4200                                let d = pages_done
4201                                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
4202                                    + 1;
4203                                if let Some(cb) = &progress {
4204                                    cb(PageProgress {
4205                                        page_no: idx + 1,
4206                                        pages_done: d,
4207                                        pages_selected: selected,
4208                                    });
4209                                }
4210                            }
4211                            // The budget ran out before this page's turn: the
4212                            // page is left out, the document is partial.
4213                            Err(PdfError::Timeout(_)) => {
4214                                timed_out.store(true, std::sync::atomic::Ordering::Relaxed);
4215                            }
4216                            Err(e) => {
4217                                let mut slot = first_err.lock().unwrap();
4218                                if slot.is_none() {
4219                                    *slot = Some(e);
4220                                }
4221                            }
4222                        }
4223                        true
4224                    });
4225                });
4226            }
4227            // Render on this thread and feed the workers; backpressure blocks here
4228            // when the channel is full. Dropping `work_tx` afterwards signals the
4229            // workers (recv → Err) to finish. A spent budget ends the walk before
4230            // the next page is rendered.
4231            let render = pdfium_backend::walk_pages(
4232                bytes,
4233                password,
4234                render_image,
4235                extract_text,
4236                range,
4237                bitmap,
4238                text,
4239                |i, _total, page| {
4240                    if expired(deadline) {
4241                        return Err(timeout_sentinel());
4242                    }
4243                    work_tx
4244                        .send((i, page))
4245                        .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
4246                },
4247            );
4248            drop(work_tx);
4249            match render {
4250                Ok(()) => {}
4251                Err(PdfError::Timeout(_)) => {
4252                    timed_out.store(true, std::sync::atomic::Ordering::Relaxed);
4253                }
4254                Err(e) => {
4255                    let mut slot = first_err.lock().unwrap();
4256                    if slot.is_none() {
4257                        *slot = Some(e);
4258                    }
4259                }
4260            }
4261        });
4262        // Threads have joined; restore the pool for the next conversion.
4263        self.pool = workers;
4264
4265        if let Some(e) = first_err.lock().unwrap().take() {
4266            return Err(e);
4267        }
4268        let mut results = Arc::try_unwrap(results)
4269            .unwrap_or_else(|arc| Mutex::new(arc.lock().unwrap().clone()))
4270            .into_inner()
4271            .unwrap();
4272        results.sort_by_key(|(idx, _)| *idx);
4273        let done = results.len();
4274        let mut doc = DoclingDocument::new(name);
4275        let mut confs = std::collections::BTreeMap::new();
4276        let mut ocr_cells_by_page = std::collections::BTreeMap::new();
4277        for (idx, (mut nodes, links, conf, page_image, ocr_cells)) in results {
4278            assemble::stamp_page_no(&mut nodes, idx + 1);
4279            if let Some(img) = page_image {
4280                doc.page_images.insert(idx + 1, img);
4281            }
4282            doc.nodes.extend(nodes);
4283            doc.links.extend(links);
4284            confs.insert(idx + 1, conf);
4285            ocr_cells_by_page.insert(idx + 1, ocr_cells);
4286        }
4287        assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::AcrossPages);
4288        self.apply_heading_hierarchy(&mut doc.nodes, Some(bytes));
4289        self.apply_script_positions(&mut doc.nodes, bytes);
4290        doc.confidence = Some(confidence_report(confs, ocr_cells_by_page));
4291        let timed_out = timed_out.load(std::sync::atomic::Ordering::Relaxed);
4292        Ok((doc, done, timed_out))
4293    }
4294
4295    /// Convert a PDF in **streaming** mode: `emit` is called with each finalized,
4296    /// in-document-order batch of nodes (and that span's recovered links) as pages
4297    /// complete, so a caller can serialize Markdown page by page instead of waiting
4298    /// for the whole document. The batches are exactly the buffered [`convert`]'s
4299    /// nodes, split at safe block boundaries by [`assemble::StreamAssembler`] — the
4300    /// parallel path reorders pages back into document order before emitting, so
4301    /// the output is identical regardless of worker scheduling.
4302    ///
4303    /// `emit` runs on the calling thread (never a worker), so it needn't be `Send`
4304    /// and its backpressure throttles the whole pipeline. Returning `Err` from
4305    /// `emit` aborts the conversion with that error.
4306    pub fn convert_streaming<F>(
4307        &mut self,
4308        bytes: &[u8],
4309        password: Option<&str>,
4310        name: &str,
4311        emit: F,
4312    ) -> Result<(), PdfError>
4313    where
4314        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4315    {
4316        self.convert_streaming_outcome(bytes, password, name, emit)
4317            .map(|_| ())
4318    }
4319
4320    /// [`convert_streaming`](Self::convert_streaming) that also says how the
4321    /// conversion ended ([`Completion`]): a spent
4322    /// [`document_timeout`](Self::document_timeout) stops the walk, the pages
4323    /// finished so far are emitted (the tail included) and the outcome is
4324    /// `TimedOut` — never an error.
4325    pub fn convert_streaming_outcome<F>(
4326        &mut self,
4327        bytes: &[u8],
4328        password: Option<&str>,
4329        name: &str,
4330        emit: F,
4331    ) -> Result<Completion, PdfError>
4332    where
4333        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4334    {
4335        let _ = name; // page nodes carry no name; the caller owns the document name.
4336        let deadline = self.deadline();
4337        let pages = pdfium_backend::page_count(bytes, password)?;
4338        let range = self.resolve_range(pages)?;
4339        let selected = range.map_or(pages, |(a, b)| b - a + 1);
4340        let r = if self.text_only_for(bytes, password)? {
4341            self.convert_streaming_text_only(bytes, password, range, &deadline, selected, emit)
4342        } else if self.target_workers >= 2 && selected >= self.parallel_min {
4343            self.convert_streaming_parallel(bytes, password, range, &deadline, selected, emit)
4344        } else {
4345            self.convert_streaming_serial(bytes, password, range, &deadline, selected, emit)
4346        };
4347        timing::report();
4348        let (done, timed_out) = r?;
4349        Self::check_cancelled(&deadline)?;
4350        Ok(self.completion(timed_out, done, selected))
4351    }
4352
4353    /// Streaming from the text layer alone ([`convert_text_only`](Self::convert_text_only)'s
4354    /// emitting twin): extract → [`text_only_page`] → emit, one page at a
4355    /// time, holding back only the tail that might still merge into the next
4356    /// page. No worker, no model, no bitmap.
4357    fn convert_streaming_text_only<F>(
4358        &mut self,
4359        bytes: &[u8],
4360        password: Option<&str>,
4361        range: Option<(usize, usize)>,
4362        deadline: &Budget,
4363        selected: usize,
4364        mut emit: F,
4365    ) -> Result<(usize, bool), PdfError>
4366    where
4367        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4368    {
4369        let mut asm = assemble::StreamAssembler::new(assemble::Continuations::Lines);
4370        let images = self.images;
4371        let progress = self.progress.clone();
4372        let mut done = 0usize;
4373        let timed_out = Self::render_ahead(
4374            bytes,
4375            password,
4376            false,
4377            pdfium_backend::BitmapRender::Eager,
4378            true,
4379            range,
4380            deadline,
4381            self.text_options(),
4382            |n, page| {
4383                let (nodes, links, _conf) = text_only_page(&page, images.scale);
4384                done += 1;
4385                if let Some(cb) = &progress {
4386                    cb(PageProgress {
4387                        page_no: n + 1,
4388                        pages_done: done,
4389                        pages_selected: selected,
4390                    });
4391                }
4392                emit(asm.push(nodes), links)
4393            },
4394        )?;
4395        emit(asm.finish(), Vec::new())?;
4396        Ok((done, timed_out))
4397    }
4398
4399    /// Serial streaming: render → process → emit, one page at a time, holding back
4400    /// only the tail that might still merge into the next page.
4401    fn convert_streaming_serial<F>(
4402        &mut self,
4403        bytes: &[u8],
4404        password: Option<&str>,
4405        range: Option<(usize, usize)>,
4406        deadline: &Budget,
4407        selected: usize,
4408        mut emit: F,
4409    ) -> Result<(usize, bool), PdfError>
4410    where
4411        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4412    {
4413        let mut asm = assemble::StreamAssembler::new(assemble::Continuations::AcrossPages);
4414        let render_image = !self.no_ocr;
4415        let bitmap = self.bitmap_render();
4416        let extract_text = self.extract_text_layer();
4417        let progress = self.progress.clone();
4418        let text = self.text_options();
4419        let worker = self.primary()?;
4420        let mut done = 0usize;
4421        let timed_out = Self::render_ahead(
4422            bytes,
4423            password,
4424            render_image,
4425            bitmap,
4426            extract_text,
4427            range,
4428            deadline,
4429            text,
4430            |n, mut page| {
4431                // Confidence is dropped on the streaming path: the report is
4432                // only complete once every page has run, which defeats
4433                // page-by-page emission — buffered `convert` carries it.
4434                let (nodes, links, _conf, _page_image, _cells) = worker.process(n, &mut page)?;
4435                done += 1;
4436                if let Some(cb) = &progress {
4437                    cb(PageProgress {
4438                        page_no: n + 1,
4439                        pages_done: done,
4440                        pages_selected: selected,
4441                    });
4442                }
4443                emit(asm.push(nodes), links)
4444            },
4445        )?;
4446        emit(asm.finish(), Vec::new())?;
4447        Ok((done, timed_out))
4448    }
4449
4450    /// Parallel streaming: pages render serially on a dedicated thread (pdfium is
4451    /// not thread-safe) and process across the worker pool; results carry their
4452    /// page index and are reordered on the calling thread into a
4453    /// [`assemble::StreamAssembler`], which emits each page in document order as
4454    /// soon as its predecessors have arrived. Bounded channels keep only a handful
4455    /// of pages resident and let `emit`'s backpressure reach the renderer.
4456    fn convert_streaming_parallel<F>(
4457        &mut self,
4458        bytes: &[u8],
4459        password: Option<&str>,
4460        range: Option<(usize, usize)>,
4461        deadline: &Budget,
4462        selected: usize,
4463        mut emit: F,
4464    ) -> Result<(usize, bool), PdfError>
4465    where
4466        F: FnMut(Vec<Node>, Vec<(String, String)>) -> Result<(), PdfError>,
4467    {
4468        let text = self.text_options();
4469        self.ensure_pool_for(selected)?;
4470        let n_workers = self.pool.len();
4471        let render_image = !self.no_ocr;
4472        let bitmap = self.bitmap_render();
4473        let extract_text = self.extract_text_layer();
4474        let progress = self.progress.clone();
4475        let layout_batch = pdf_layout_batch();
4476        // Bound sized so every worker can accumulate a full layout batch while
4477        // rendering stays ahead (and never below the pre-#73 render-ahead of
4478        // two pages per worker); still a hard cap on resident page bitmaps.
4479        let (work_tx, work_rx) = sync_channel::<(usize, PdfPage)>(n_workers * layout_batch.max(2));
4480        let work_rx: Arc<Mutex<Receiver<(usize, PdfPage)>>> = Arc::new(Mutex::new(work_rx));
4481        // Workers and the renderer report here; the calling thread drains it in
4482        // page order. Bounded so workers block (bounding resident bitmaps) when the
4483        // consumer falls behind.
4484        let (res_tx, res_rx) = sync_channel::<Result<(usize, PageOut), PdfError>>(n_workers * 2);
4485
4486        let mut workers = std::mem::take(&mut self.pool);
4487        let mut asm = assemble::StreamAssembler::new(assemble::Continuations::AcrossPages);
4488        let mut first_err: Option<PdfError> = None;
4489        let mut timed_out = false;
4490        let mut done = 0usize;
4491
4492        std::thread::scope(|s| {
4493            // Workers: pull a batch of pages (whatever is already rendered, up
4494            // to the layout batch size), process it, report (index-tagged)
4495            // results.
4496            for worker in workers.iter_mut() {
4497                let work_rx = Arc::clone(&work_rx);
4498                let res_tx = res_tx.clone();
4499                s.spawn(move || {
4500                    worker.run_pool(&work_rx, layout_batch, deadline, |idx, out| {
4501                        // `false` once the consumer is gone.
4502                        res_tx.send(out.map(|o| (idx, o))).is_ok()
4503                    });
4504                });
4505            }
4506            // Renderer: feed pages to the pool on its own thread (pdfium stays on a
4507            // single thread); report a render error through the same channel. A
4508            // spent budget ends the walk before the next page is rendered.
4509            {
4510                let res_tx = res_tx.clone();
4511                s.spawn(move || {
4512                    let render = pdfium_backend::walk_pages(
4513                        bytes,
4514                        password,
4515                        render_image,
4516                        extract_text,
4517                        range,
4518                        bitmap,
4519                        text,
4520                        |i, _total, page| {
4521                            if expired(deadline) {
4522                                return Err(timeout_sentinel());
4523                            }
4524                            work_tx
4525                                .send((i, page))
4526                                .map_err(|_| PdfError::Pdfium("page-worker channel closed".into()))
4527                        },
4528                    );
4529                    drop(work_tx); // signal workers to finish
4530                    if let Err(e) = render {
4531                        let _ = res_tx.send(Err(e));
4532                    }
4533                });
4534            }
4535            // Drop our own sender so the channel closes once the threads finish.
4536            drop(res_tx);
4537
4538            // Collector (this thread): reorder into document order and emit.
4539            // With a page window, indices start at the window's first page.
4540            // A timed-out page leaves a hole in the sequence: everything
4541            // before it emits in order, the pages after it stay buffered —
4542            // they are the pages the budget did not cover, and the document
4543            // ends at the cut like the buffered path's.
4544            let mut buffer: BTreeMap<usize, PageOut> = BTreeMap::new();
4545            let mut next = range.map_or(0, |(first, _)| first);
4546            for msg in res_rx.iter() {
4547                match msg {
4548                    Err(PdfError::Timeout(_)) => timed_out = true,
4549                    Err(e) => {
4550                        if first_err.is_none() {
4551                            first_err = Some(e);
4552                        }
4553                    }
4554                    Ok((idx, out)) => {
4555                        buffer.insert(idx, out);
4556                        if first_err.is_some() {
4557                            continue; // keep draining so the threads can exit
4558                        }
4559                        // A stream carries Markdown, not the page map: page
4560                        // images (#520) have nowhere to go and are dropped.
4561                        while let Some((nodes, links, _conf, _page_image, _cells)) =
4562                            buffer.remove(&next)
4563                        {
4564                            if let Err(e) = emit(asm.push(nodes), links) {
4565                                first_err = Some(e);
4566                                break;
4567                            }
4568                            next += 1;
4569                            done += 1;
4570                            // Reported in document order, as emitted: a page
4571                            // that finished early counts once it is emitted.
4572                            if let Some(cb) = &progress {
4573                                cb(PageProgress {
4574                                    page_no: next,
4575                                    pages_done: done,
4576                                    pages_selected: selected,
4577                                });
4578                            }
4579                        }
4580                    }
4581                }
4582            }
4583            // Pages that finished after a hole (a page the budget skipped
4584            // before them) cannot follow it in document order; count them
4585            // out of the document like the skipped one.
4586            if timed_out && !buffer.is_empty() {
4587                buffer.clear();
4588            }
4589        });
4590        // Threads have joined; restore the pool for the next conversion.
4591        self.pool = workers;
4592
4593        if let Some(e) = first_err {
4594            return Err(e);
4595        }
4596        emit(asm.finish(), Vec::new())?;
4597        Ok((done, timed_out))
4598    }
4599
4600    /// Lazily grow the pool to `target_workers`, loading the new workers
4601    /// concurrently (model load is mostly I/O + mmap, so N loads overlap to roughly
4602    /// one load's wall-time). Cached for reuse across documents.
4603    fn ensure_pool(&mut self) -> Result<(), PdfError> {
4604        self.ensure_pool_for(self.target_workers)
4605    }
4606
4607    /// [`ensure_pool`](Self::ensure_pool) for a document of `pages` pages:
4608    /// no more workers than pages (#682 — a two-page document on a 16-core
4609    /// host loads two workers, not eight), never fewer than two, and never
4610    /// more than `target_workers`; a later, longer document grows the pool.
4611    fn ensure_pool_for(&mut self, pages: usize) -> Result<(), PdfError> {
4612        let want = pages.max(2).min(self.target_workers);
4613        let need = want.saturating_sub(self.pool.len());
4614        if need == 0 {
4615            return Ok(());
4616        }
4617        let intra = pdf_intra();
4618        let no_ocr = self.no_ocr;
4619        let skip_ocr = self.skip_ocr;
4620        let force = self.force_full_page_ocr || self.ocr_mode.forces_full_page();
4621        let ntp = self.no_text_panels;
4622        let ocr_lang = self.ocr_lang;
4623        let ocr_engine = self.ocr_engine;
4624        let tesseract_lang = self.tesseract_lang.clone();
4625        let ocr_scale = self.ocr_scale;
4626        let textline_orientation = self.textline_orientation;
4627        let images = self.images;
4628        let enrich = self.enrich;
4629        let tables = self.tables_slot();
4630        let det = Arc::clone(&self.det);
4631        let enrich_slots = self.enrich_slots();
4632        let loaded: Vec<Result<Worker, PdfError>> = std::thread::scope(|s| {
4633            let handles: Vec<_> = (0..need)
4634                .map(|_| {
4635                    let tables = tables.clone();
4636                    let det = Arc::clone(&det);
4637                    let enrich_slots = enrich_slots.clone();
4638                    let tesseract_lang = tesseract_lang.clone();
4639                    s.spawn(move || {
4640                        Worker::load(
4641                            intra,
4642                            tables,
4643                            det,
4644                            enrich_slots,
4645                            enrich,
4646                            no_ocr,
4647                            skip_ocr,
4648                            force,
4649                            ntp,
4650                            ocr_lang,
4651                            ocr_engine,
4652                            tesseract_lang,
4653                            ocr_scale,
4654                            textline_orientation,
4655                            images,
4656                        )
4657                    })
4658                })
4659                .collect();
4660            handles.into_iter().map(|h| h.join().unwrap()).collect()
4661        });
4662        for w in loaded {
4663            let mut w = w?;
4664            w.replace_broken_text_layer = self.replace_broken_text_layer;
4665            w.picture_ocr = self.picture_ocr;
4666            self.pool.push(w);
4667        }
4668        Ok(())
4669    }
4670
4671    /// Convert a standalone image (PNG/JPEG/TIFF/WebP/…) as a single page —
4672    /// docling routes images through the same layout+OCR pipeline as a PDF page.
4673    pub fn convert_image(&mut self, bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
4674        let image = decode_image_limited(bytes)?;
4675        let (w, h) = image.dimensions();
4676        // The image is its own page rendered at 1 px per "point" (scale 1.0); a
4677        // standalone image has no text layer, so OCR supplies the cells.
4678        let page = PdfPage {
4679            width: w as f32,
4680            height: h as f32,
4681            scale: 1.0,
4682            cells: Vec::new(),
4683            code_cells: Vec::new(),
4684            checkboxes: Vec::new(),
4685            bitmaps: Vec::new(),
4686            shapes: Default::default(),
4687            word_cells: Vec::new(),
4688            // A standalone image *is* its own scale-1.0 page image, so the
4689            // layout model sees it through the docling-exact PIL kernel.
4690            image_layout: Some(image.clone()),
4691            image,
4692            links: Vec::new(),
4693            rotation: 0,
4694            keep_typography: false,
4695            #[cfg(feature = "render")]
4696            embedded_images: Vec::new(),
4697            pending_image: None,
4698        };
4699        let mut doc = self.process_pages(vec![page], name)?;
4700        // docling sizes the page from the file's resolution (#1093); the
4701        // models above ran on the file's own pixels, which only the page unit
4702        // changes, so the text and the reading order cannot move.
4703        let (dpi_x, dpi_y) = image_page_dpi(bytes, (w, h));
4704        if (dpi_x, dpi_y) != (72.0, 72.0) {
4705            doc.rescale_page_units((72.0 / dpi_x) as f32, (72.0 / dpi_y) as f32);
4706        }
4707        Ok(doc)
4708    }
4709
4710    /// Run layout (+ OCR for cell-less pages) and assemble each already-rendered
4711    /// page (image / METS inputs, which are small and already materialised).
4712    /// Public so [`mets::convert_mets_gbs_with_pipeline`] can drive a
4713    /// caller-configured pipeline (#244).
4714    pub fn process_pages(
4715        &mut self,
4716        pages: Vec<PdfPage>,
4717        name: &str,
4718    ) -> Result<DoclingDocument, PdfError> {
4719        let numbered = pages
4720            .into_iter()
4721            .enumerate()
4722            .map(|(n, p)| (n + 1, p))
4723            .collect();
4724        self.process_numbered_pages(numbered, name)
4725    }
4726
4727    /// [`Pipeline::process_pages`] with each page's 1-based number given —
4728    /// a METS archive that left a page out keeps the numbers of the pages
4729    /// after it (#1147).
4730    pub fn process_numbered_pages(
4731        &mut self,
4732        mut pages: Vec<(usize, PdfPage)>,
4733        name: &str,
4734    ) -> Result<DoclingDocument, PdfError> {
4735        let mut doc = DoclingDocument::new(name);
4736        let mut confs = std::collections::BTreeMap::new();
4737        let mut ocr_cells_by_page = std::collections::BTreeMap::new();
4738        let progress = self.progress.clone();
4739        let total = pages.len();
4740        let worker = self.primary()?;
4741        for (done, (page_no, page)) in pages.iter_mut().enumerate() {
4742            let page_no = *page_no;
4743            let (mut nodes, links, conf, page_image, ocr_cells) =
4744                worker.process(page_no - 1, page)?;
4745            assemble::stamp_page_no(&mut nodes, page_no);
4746            if let Some(img) = page_image {
4747                doc.page_images.insert(page_no, img);
4748            }
4749            doc.nodes.extend(nodes);
4750            doc.links.extend(links);
4751            confs.insert(page_no, conf);
4752            ocr_cells_by_page.insert(page_no, ocr_cells);
4753            if let Some(cb) = &progress {
4754                cb(PageProgress {
4755                    page_no,
4756                    pages_done: done + 1,
4757                    pages_selected: total,
4758                });
4759            }
4760        }
4761        assemble::merge_continuations(&mut doc.nodes, assemble::Continuations::AcrossPages);
4762        // No PDF behind these pages (images, METS): the heading-hierarchy
4763        // stage degrades to the numbering signal — exactly docling without
4764        // an outline or parsed pages.
4765        self.apply_heading_hierarchy(&mut doc.nodes, None);
4766        doc.confidence = Some(confidence_report(confs, ocr_cells_by_page));
4767        Ok(doc)
4768    }
4769}
4770
4771/// Number of pages in a PDF, without converting anything — what the CLI batch
4772/// mode prints in its per-document start line.
4773#[cfg(feature = "ml")]
4774pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
4775    pdfium_backend::page_count(bytes, password)
4776}
4777
4778#[cfg(feature = "ml")]
4779/// Convenience one-shot conversion (loads the pipeline per call). Errors are
4780/// detailed and surfaced (never silently skipped).
4781pub fn convert(
4782    bytes: &[u8],
4783    password: Option<&str>,
4784    name: &str,
4785) -> Result<DoclingDocument, PdfError> {
4786    convert_with_options(
4787        bytes,
4788        password,
4789        name,
4790        false,
4791        false,
4792        false,
4793        false,
4794        EnrichmentOptions::default(),
4795        None,
4796        None,
4797    )
4798}
4799
4800#[cfg(feature = "ml")]
4801/// Like [`convert`], but optionally skips loading/running TableFormer (see
4802/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
4803/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes (see
4804/// [`Pipeline::enrichments`]).
4805// One positional per pipeline switch mirrors the Pipeline builder; growing
4806// past clippy's arity cap is the price of keeping this one-shot signature
4807// stable-ish instead of churning callers into an options struct mid-series.
4808#[allow(clippy::too_many_arguments)]
4809pub fn convert_with_options(
4810    bytes: &[u8],
4811    password: Option<&str>,
4812    name: &str,
4813    no_table_former: bool,
4814    no_ocr: bool,
4815    force_full_page_ocr: bool,
4816    no_text_panels: bool,
4817    enrich: EnrichmentOptions,
4818    pages: Option<(usize, usize)>,
4819    ocr_lang: Option<OcrLang>,
4820) -> Result<DoclingDocument, PdfError> {
4821    Pipeline::new()?
4822        .no_table_former(no_table_former)
4823        .no_ocr(no_ocr)
4824        .force_full_page_ocr(force_full_page_ocr)
4825        .no_text_panels(no_text_panels)
4826        .enrichments(enrich)
4827        .pages(pages)
4828        .ocr_lang(ocr_lang)
4829        .convert(bytes, password, name)
4830}
4831
4832#[cfg(feature = "ml")]
4833/// Convenience one-shot image conversion (loads the pipeline per call).
4834pub fn convert_image(bytes: &[u8], name: &str) -> Result<DoclingDocument, PdfError> {
4835    convert_image_with_options(
4836        bytes,
4837        name,
4838        false,
4839        false,
4840        false,
4841        EnrichmentOptions::default(),
4842        None,
4843    )
4844}
4845
4846#[cfg(feature = "ml")]
4847/// Like [`convert_image`], but optionally skips loading/running TableFormer (see
4848/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
4849/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
4850pub fn convert_image_with_options(
4851    bytes: &[u8],
4852    name: &str,
4853    no_table_former: bool,
4854    no_ocr: bool,
4855    no_text_panels: bool,
4856    enrich: EnrichmentOptions,
4857    ocr_lang: Option<OcrLang>,
4858) -> Result<DoclingDocument, PdfError> {
4859    Pipeline::new()?
4860        .no_table_former(no_table_former)
4861        .no_ocr(no_ocr)
4862        .no_text_panels(no_text_panels)
4863        .enrichments(enrich)
4864        .ocr_lang(ocr_lang)
4865        .convert_image(bytes, name)
4866}
4867
4868#[cfg(feature = "ml")]
4869/// Convert pre-segmented pages (image + already-known text cells, e.g. METS/hOCR
4870/// scans) through the shared layout + assembly pipeline.
4871pub fn convert_pages(pages: Vec<PdfPage>, name: &str) -> Result<DoclingDocument, PdfError> {
4872    convert_pages_with_options(
4873        pages,
4874        name,
4875        false,
4876        false,
4877        false,
4878        EnrichmentOptions::default(),
4879    )
4880}
4881
4882#[cfg(feature = "ml")]
4883/// Like [`convert_pages`], but optionally skips loading/running TableFormer (see
4884/// [`Pipeline::no_table_former`]) and/or layout+OCR+TableFormer entirely (see
4885/// [`Pipeline::no_ocr`]), and/or enables the enrichment passes.
4886pub fn convert_pages_with_options(
4887    pages: Vec<PdfPage>,
4888    name: &str,
4889    no_table_former: bool,
4890    no_ocr: bool,
4891    no_text_panels: bool,
4892    enrich: EnrichmentOptions,
4893) -> Result<DoclingDocument, PdfError> {
4894    Pipeline::new()?
4895        .no_table_former(no_table_former)
4896        .no_text_panels(no_text_panels)
4897        .no_ocr(no_ocr)
4898        .enrichments(enrich)
4899        .process_pages(pages, name)
4900}
4901
4902#[cfg(feature = "ml")]
4903#[cfg(all(test, feature = "ml"))]
4904mod image_limit_tests {
4905    use super::decode_image_with_max_side;
4906
4907    /// A small valid PNG encoded via the `image` crate (robust vs. a hand-rolled
4908    /// byte literal).
4909    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
4910        use std::io::Cursor;
4911        let img = image::RgbImage::new(w, h);
4912        let mut out = Vec::new();
4913        img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
4914            .unwrap();
4915        out
4916    }
4917
4918    #[test]
4919    fn normal_image_decodes_under_the_cap() {
4920        let img = decode_image_with_max_side(&png_bytes(8, 8), 30_000).expect("8x8 decodes");
4921        assert_eq!(img.dimensions(), (8, 8));
4922    }
4923
4924    /// docling#4247 (2.128): the EXIF orientation is applied when a frame is
4925    /// loaded — a 4×2 JPEG tagged "rotate 90° CW" (orientation 6) decodes as
4926    /// 2×4, with the pixels turned.
4927    #[test]
4928    fn exif_orientation_is_applied() {
4929        use std::io::Cursor;
4930        let mut img = image::RgbImage::new(4, 2);
4931        img.put_pixel(0, 0, image::Rgb([255, 0, 0]));
4932        let mut jpeg = Vec::new();
4933        img.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
4934            .unwrap();
4935        // Splice an APP1 Exif segment (little-endian TIFF, one IFD entry:
4936        // Orientation = 6) right after the SOI marker.
4937        let mut tiff = b"II*\0".to_vec();
4938        tiff.extend(8u32.to_le_bytes());
4939        tiff.extend(1u16.to_le_bytes());
4940        tiff.extend(0x0112u16.to_le_bytes());
4941        tiff.extend(3u16.to_le_bytes());
4942        tiff.extend(1u32.to_le_bytes());
4943        tiff.extend(6u16.to_le_bytes());
4944        tiff.extend([0, 0]);
4945        tiff.extend(0u32.to_le_bytes());
4946        let mut app1 = b"Exif\0\0".to_vec();
4947        app1.extend(tiff);
4948        let mut out = jpeg[..2].to_vec();
4949        out.extend([0xff, 0xe1]);
4950        out.extend((app1.len() as u16 + 2).to_be_bytes());
4951        out.extend(app1);
4952        out.extend(&jpeg[2..]);
4953        let plain = decode_image_with_max_side(&jpeg, 30_000).unwrap();
4954        assert_eq!(plain.dimensions(), (4, 2));
4955        let turned = decode_image_with_max_side(&out, 30_000).unwrap();
4956        assert_eq!(turned.dimensions(), (2, 4), "quarter turn swaps the sides");
4957        // Rotating 90° CW moves the top-left pixel to the top-right corner.
4958        assert!(turned.get_pixel(1, 0).0[0] > 128);
4959        assert!(turned.get_pixel(0, 0).0[0] <= 128);
4960    }
4961
4962    #[test]
4963    fn dimensions_over_the_cap_are_rejected_not_aborted() {
4964        // A per-side cap below the image's declared size must yield a
4965        // recoverable Err, never an allocation-abort — the mechanism that stops
4966        // a crafted image declaring 60000×60000 from OOM-killing the process.
4967        let r = decode_image_with_max_side(&png_bytes(8, 8), 4);
4968        assert!(
4969            r.is_err(),
4970            "decode must fail under the pixel cap, not abort"
4971        );
4972    }
4973}
4974
4975#[cfg(all(test, feature = "ml"))]
4976mod image_page_dpi_tests {
4977    use super::{decode_image_with_max_side, image_page_dpi};
4978    use image::codecs::jpeg::{JpegEncoder, PixelDensity, PixelDensityUnit};
4979
4980    /// A 4 × 2 JPEG whose JFIF records `density`, tagged with EXIF
4981    /// `orientation` when given.
4982    fn jpeg(density: PixelDensity, orientation: Option<u16>) -> Vec<u8> {
4983        let img = image::RgbImage::new(4, 2);
4984        let mut out = Vec::new();
4985        let mut enc = JpegEncoder::new(&mut out);
4986        enc.set_pixel_density(density);
4987        enc.encode_image(&img).unwrap();
4988        let Some(o) = orientation else {
4989            return out;
4990        };
4991        // An APP1 Exif segment (little-endian TIFF, one IFD entry:
4992        // Orientation) right after SOI; the JFIF density stays authoritative.
4993        let mut app1 = b"Exif\0\0II*\0".to_vec();
4994        app1.extend(8u32.to_le_bytes());
4995        app1.extend(1u16.to_le_bytes());
4996        app1.extend(0x0112u16.to_le_bytes());
4997        app1.extend(3u16.to_le_bytes());
4998        app1.extend(1u32.to_le_bytes());
4999        app1.extend(o.to_le_bytes());
5000        app1.extend([0, 0, 0, 0, 0, 0]);
5001        let mut spliced = out[..2].to_vec();
5002        spliced.extend([0xff, 0xe1]);
5003        spliced.extend((app1.len() as u16 + 2).to_be_bytes());
5004        spliced.extend(app1);
5005        spliced.extend(&out[2..]);
5006        spliced
5007    }
5008
5009    fn dpi_of(bytes: &[u8]) -> (f64, f64) {
5010        let decoded = decode_image_with_max_side(bytes, 30_000).unwrap();
5011        image_page_dpi(bytes, decoded.dimensions())
5012    }
5013
5014    /// docling's `_get_frame_dpi`: each axis's resolution as Pillow reads it;
5015    /// none, `(1, 1)` and `(0, 0)` read as 72.
5016    #[test]
5017    fn the_page_takes_the_files_resolution() {
5018        let anisotropic = PixelDensity {
5019            density: (300, 150),
5020            unit: PixelDensityUnit::Inches,
5021        };
5022        assert_eq!(dpi_of(&jpeg(anisotropic, None)), (300.0, 150.0));
5023        assert_eq!(dpi_of(&jpeg(PixelDensity::default(), None)), (72.0, 72.0));
5024        assert_eq!(dpi_of(&jpeg(PixelDensity::dpi(1), None)), (72.0, 72.0));
5025        assert_eq!(dpi_of(&jpeg(PixelDensity::dpi(0), None)), (72.0, 72.0));
5026    }
5027
5028    /// docling's `_oriented_frame`: a quarter-turn EXIF orientation swaps the
5029    /// frame's sides, and the resolution's axes with them; a half turn does
5030    /// not.
5031    #[test]
5032    fn a_quarter_turn_swaps_the_axes() {
5033        let anisotropic = PixelDensity {
5034            density: (300, 150),
5035            unit: PixelDensityUnit::Inches,
5036        };
5037        assert_eq!(dpi_of(&jpeg(anisotropic, Some(6))), (150.0, 300.0));
5038        assert_eq!(dpi_of(&jpeg(anisotropic, Some(3))), (300.0, 150.0));
5039    }
5040}
5041
5042#[cfg(all(test, feature = "ml"))]
5043mod ocr_scale_tests {
5044    use super::*;
5045
5046    /// #570: an explicit scale wins everywhere; a rendered page keeps its
5047    /// render; a scale-1.0 image page reads at docling's 3 px/pt, shrunk to
5048    /// RapidOCR's 2000 px longer side (a FUNSD scan at 2.0, a 3000 px photo
5049    /// downsampled to 0.67), and an image that lands at 1.0 is not resampled.
5050    #[test]
5051    fn image_inputs_follow_rapidocrs_resolution() {
5052        assert_eq!(page_ocr_scale(Some(1.5), 754.0, 1000.0, 1.0), Some(1.5));
5053        assert_eq!(page_ocr_scale(None, 612.0, 792.0, 2.0), None);
5054        assert_eq!(page_ocr_scale(None, 754.0, 1000.0, 1.0), Some(2.0));
5055        assert_eq!(page_ocr_scale(None, 400.0, 600.0, 1.0), Some(3.0));
5056        let s = page_ocr_scale(None, 3000.0, 2000.0, 1.0).unwrap();
5057        assert!((s - 2.0 / 3.0).abs() < 1e-6, "{s}");
5058        assert_eq!(page_ocr_scale(None, 2000.0, 1500.0, 1.0), None);
5059    }
5060}
5061
5062#[cfg(test)]
5063mod median_tests {
5064    #[test]
5065    fn median_of_empty_is_zero_not_a_panic() {
5066        // A crafted table can leave a row/column with zero matched cells; the
5067        // even-count branch would index values[0 - 1] and panic (→ remote crash
5068        // via docling-serve) without the empty guard.
5069        assert_eq!(super::tf_match::median_for_test(&mut []), 0.0);
5070        assert_eq!(super::tf_match::median_for_test(&mut [4.0, 2.0]), 3.0);
5071        assert_eq!(super::tf_match::median_for_test(&mut [5.0, 1.0, 3.0]), 3.0);
5072    }
5073}
5074
5075#[cfg(test)]
5076mod unreadable_tests {
5077    /// The text-layer path (the wasm build's only one) tells a file nothing
5078    /// can open apart from a PDF that merely has no text layer: garbage is
5079    /// an error about the file, a real PDF converts.
5080    #[test]
5081    fn text_layer_path_reports_an_unreadable_file() {
5082        for bytes in [b"garbage".as_slice(), b"", b"%PDF-1.7\n%%EOF\n"] {
5083            let err = super::convert_text_layer(bytes, "x.pdf").unwrap_err();
5084            assert!(err.to_string().contains("not a readable PDF"), "{err}");
5085        }
5086        let real = std::fs::read(
5087            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5088                .join("../../tests/data/pdf/sources/multi_page.pdf"),
5089        )
5090        .unwrap();
5091        assert!(!super::convert_text_layer(&real, "multi_page.pdf")
5092            .unwrap()
5093            .nodes
5094            .is_empty());
5095    }
5096}
5097
5098#[cfg(test)]
5099mod send_check {
5100    /// The Node bindings (`docling-node`) run a shared [`super::Pipeline`] on
5101    /// libuv worker threads (`Arc<Mutex<Pipeline>>`), which is only sound while
5102    /// `Pipeline: Send` holds — this fails to compile if a non-`Send` field
5103    /// (e.g. an `Rc` or a raw pdfium handle) ever lands in the pipeline.
5104    fn assert_send<T: Send>() {}
5105
5106    #[test]
5107    fn pipeline_is_send() {
5108        assert_send::<super::Pipeline>();
5109    }
5110}
5111
5112#[cfg(all(test, feature = "ml"))]
5113mod ocr_input_tests {
5114    /// #254: without an `ocr_scale` (or with one equal to the render scale)
5115    /// the OCR reads the page render untouched and the cache stays cold; a
5116    /// different scale builds one resampled view, reuses it across calls, and
5117    /// reports the requested px/pt so cell geometry divides back to points.
5118    #[test]
5119    fn ocr_input_resamples_only_on_a_real_scale_change() {
5120        let img = image::RgbImage::new(200, 100);
5121        let mut cache = None;
5122        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, None);
5123        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
5124        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(2.0));
5125        assert!(std::ptr::eq(v, &img) && s == 2.0 && cache.is_none());
5126
5127        let (v, s) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
5128        assert_eq!((v.width(), v.height(), s), (300, 150, 3.0));
5129        let first = cache.as_ref().map(|c| c as *const image::RgbImage);
5130        let (v, _) = super::ocr_input(&mut cache, &img, 2.0, Some(3.0));
5131        assert_eq!(
5132            Some(v as *const image::RgbImage),
5133            first,
5134            "cached, not rebuilt"
5135        );
5136
5137        let mut down = None;
5138        let (v, s) = super::ocr_input(&mut down, &img, 2.0, Some(1.0));
5139        assert_eq!((v.width(), v.height(), s), (100, 50, 1.0));
5140    }
5141}
5142
5143#[cfg(all(test, feature = "ml"))]
5144mod text_layer_auto_tests {
5145    use std::path::Path;
5146
5147    fn fixture(rel: &str) -> Vec<u8> {
5148        std::fs::read(
5149            Path::new(env!("CARGO_MANIFEST_DIR"))
5150                .join("../..")
5151                .join(rel),
5152        )
5153        .unwrap()
5154    }
5155
5156    /// The verdict behind `text_layer_only=auto`: a digital PDF's layer
5157    /// carries it, a scan's does not, and garbage is the file's error.
5158    #[test]
5159    fn text_layer_verdict_tells_digital_from_scanned() {
5160        let digital = fixture("tests/data/pdf/sources/multi_page.pdf");
5161        assert!(super::text_layer_has_text(&digital, None).unwrap());
5162        let scanned = fixture("tests/data/scanned/sources/ocr_test_raster.pdf");
5163        assert!(!super::text_layer_has_text(&scanned, None).unwrap());
5164        let err = super::text_layer_has_text(b"garbage", None).unwrap_err();
5165        assert!(err.to_string().contains("not a readable PDF"), "{err}");
5166    }
5167
5168    /// On a digital PDF `auto` is the `no_ocr` path byte for byte — the
5169    /// buffered and the streaming conversion alike — and touches no model:
5170    /// the pipeline below has none to load (`Pipeline::new` loads lazily),
5171    /// so a conversion that reached a worker would fail.
5172    #[test]
5173    fn auto_on_a_digital_pdf_is_the_text_layer_path() {
5174        let bytes = fixture("tests/data/pdf/sources/multi_page.pdf");
5175        let mut only = super::Pipeline::new().unwrap().no_ocr(true);
5176        let mut auto = super::Pipeline::new().unwrap().text_layer_auto(true);
5177        let a = only.convert(&bytes, None, "multi_page.pdf").unwrap();
5178        let b = auto.convert(&bytes, None, "multi_page.pdf").unwrap();
5179        assert!(!a.nodes.is_empty());
5180        assert_eq!(a.export_to_markdown(), b.export_to_markdown());
5181        assert_eq!(a.confidence, b.confidence);
5182        let streamed = |p: &mut super::Pipeline| {
5183            let mut nodes = Vec::new();
5184            p.convert_streaming(&bytes, None, "multi_page.pdf", |page, _| {
5185                nodes.extend(page);
5186                Ok(())
5187            })
5188            .unwrap();
5189            nodes
5190        };
5191        assert_eq!(streamed(&mut only), streamed(&mut auto));
5192    }
5193}
5194
5195#[cfg(all(test, feature = "ml"))]
5196mod bitmap_region_tests {
5197    use super::{bitmap_regions, layout::Region, TextCell};
5198
5199    fn region(label: &'static str, l: f32, t: f32, r: f32, b: f32) -> Region {
5200        Region {
5201            label,
5202            score: 1.0,
5203            l,
5204            t,
5205            r,
5206            b,
5207        }
5208    }
5209
5210    fn cell(text: &str, l: f32, t: f32, r: f32, b: f32) -> TextCell {
5211        TextCell {
5212            text: text.into(),
5213            l,
5214            t,
5215            r,
5216            b,
5217        }
5218    }
5219
5220    const PAGE: [f32; 4] = [0.0, 0.0, 612.0, 792.0];
5221
5222    /// #999: a scanned table with one typed-in value is OCR'd; a text-less
5223    /// region is left to `text_less_regions`; a page without a bitmap, or a
5224    /// region the scan barely touches, is not.
5225    #[test]
5226    fn a_scan_under_a_thin_layer_is_read() {
5227        let table = region("table", 100.0, 300.0, 500.0, 500.0);
5228        let blank = region("text", 100.0, 100.0, 500.0, 120.0);
5229        let cells = [cell("420", 226.0, 444.0, 251.0, 458.0)];
5230        let got = bitmap_regions(&[table.clone(), blank], &cells, &[PAGE]);
5231        assert_eq!(got.len(), 1);
5232        assert_eq!((got[0].label, got[0].t), ("table", 300.0));
5233        assert!(bitmap_regions(std::slice::from_ref(&table), &cells, &[]).is_empty());
5234        // A logo over a corner of the region: not half of it.
5235        let logo = [450.0, 290.0, 520.0, 340.0];
5236        assert!(bitmap_regions(&[table], &cells, &[logo]).is_empty());
5237    }
5238
5239    /// A searchable scan — an invisible layer over the page image — keeps
5240    /// its text layer: a one-line region is a thin band any text explains,
5241    /// a paragraph is covered well past a tenth of its area.
5242    #[test]
5243    fn a_searchable_scan_keeps_its_text_layer() {
5244        let line = region("text", 72.0, 100.0, 540.0, 114.0);
5245        let para = region("text", 72.0, 200.0, 540.0, 260.0);
5246        let cells: Vec<TextCell> = std::iter::once(cell("Heading", 72.0, 100.0, 300.0, 114.0))
5247            .chain((0..4).map(|i| {
5248                let t = 200.0 + 15.0 * i as f32;
5249                cell("body text", 72.0, t, 540.0, t + 12.0)
5250            }))
5251            .collect();
5252        assert!(bitmap_regions(&[line, para], &cells, &[PAGE]).is_empty());
5253    }
5254}
5255
5256/// The worker decides tables-off from an empty TableFormer slot. A missing
5257/// model is a present slot whose load came back empty, and that path keeps
5258/// the table region for the geometric grid.
5259#[cfg(all(test, feature = "ml"))]
5260mod tables_off_gate {
5261    use std::sync::{Arc, Mutex};
5262
5263    use super::{
5264        assemble, layout::Region, pdfium_backend::PdfPage, pdfium_backend::TextCell, DetSlot,
5265        EnrichmentOptions, ImageOutput, OcrSlot, TfSlot, Worker,
5266    };
5267
5268    fn worker(tables: Option<super::SharedTables>) -> Worker {
5269        Worker {
5270            layout: None,
5271            ocr: OcrSlot::Unloaded,
5272            ocr_status: None,
5273            det: Arc::new(Mutex::new(DetSlot::Missing)),
5274            pending_det: Default::default(),
5275            intra: 1,
5276            tables,
5277            classifier: None,
5278            code_formula: None,
5279            enrich: EnrichmentOptions::default(),
5280            no_ocr: false,
5281            force_full_page_ocr: false,
5282            replace_broken_text_layer: false,
5283            picture_ocr: false,
5284            no_text_panels: true,
5285            // No recognizer in the test. The scanned-page test covers the
5286            // cells `ocr_table_words` would have appended before the release.
5287            skip_ocr: true,
5288            ocr_lang: Default::default(),
5289            ocr_engine: Default::default(),
5290            tesseract_lang: None,
5291            ocr_scale: None,
5292            textline_orientation: false,
5293            images: ImageOutput::default(),
5294        }
5295    }
5296
5297    /// #1210: a failed OCR load is reported for every request, and only for
5298    /// a request — a page that may need OCR but has nothing to read does not
5299    /// count, nor touch the slot.
5300    #[test]
5301    fn a_missing_ocr_model_is_recorded_per_request() {
5302        let mut w = worker(None);
5303        w.skip_ocr = false;
5304        w.ocr = OcrSlot::Missing("no model".into());
5305        assert!(w.ocr_model_if(false).unwrap().is_none());
5306        assert_eq!(w.ocr_status, None, "nothing asked for OCR");
5307        assert!(w.ocr_model().unwrap().is_none(), "degrades, not fails");
5308        let unavailable = docling_core::OcrStatus::Unavailable {
5309            reason: "no model".into(),
5310        };
5311        assert_eq!(w.ocr_status, Some(unavailable.clone()));
5312        // The pipeline folds its workers' state and clears it.
5313        let Ok(mut p) = super::Pipeline::new() else {
5314            return;
5315        };
5316        p.primary = Some(w);
5317        assert_eq!(p.take_ocr_status(), Some(unavailable));
5318        assert_eq!(p.take_ocr_status(), None, "taken");
5319        // `skip_ocr` never asks.
5320        let mut skipped = worker(None);
5321        skipped.ocr = OcrSlot::Missing("no model".into());
5322        assert!(skipped.ocr_model().unwrap().is_none());
5323        assert_eq!(skipped.ocr_status, None);
5324    }
5325
5326    fn axle_page() -> (PdfPage, Vec<Region>) {
5327        let cells = vec![TextCell {
5328            text: "Axle:".into(),
5329            l: 40.0,
5330            t: 100.0,
5331            r: 90.0,
5332            b: 112.0,
5333        }];
5334        let regions = vec![Region {
5335            label: "table",
5336            score: 0.9,
5337            l: 30.0,
5338            t: 90.0,
5339            r: 220.0,
5340            b: 180.0,
5341        }];
5342        (PdfPage::from_cells(600.0, 800.0, 1.0, cells), regions)
5343    }
5344
5345    #[test]
5346    fn tables_off_drops_the_table_region() {
5347        let (mut page, regions) = axle_page();
5348        let prepared = worker(None).prepare_page(0, &mut page, regions).unwrap();
5349        assert!(prepared
5350            .regions
5351            .iter()
5352            .all(|r| !assemble::is_table_like(r.label)));
5353        assert!(prepared.regions.iter().any(|r| r.label == "text"));
5354    }
5355
5356    #[test]
5357    fn missing_tableformer_keeps_the_table_region() {
5358        let (mut page, regions) = axle_page();
5359        let tables = Arc::new(Mutex::new(TfSlot::Missing));
5360        let prepared = worker(Some(tables))
5361            .prepare_page(0, &mut page, regions)
5362            .unwrap();
5363        assert!(prepared.regions.iter().any(|r| r.label == "table"));
5364    }
5365}
5366
5367/// #1149: an image input decodes to the page docling reads — transparency
5368/// on white, a 16-bit `tRNS` key included, 16-bit samples truncated.
5369/// docling's `test_transparent_background_is_flattened_onto_white`,
5370/// `test_to_rgb_scales_the_transparency_key_of_16_bit_images` and
5371/// `test_16_bit_grayscale_is_scaled_to_8_bits[PNG]`.
5372#[cfg(all(test, feature = "ml"))]
5373mod image_input_tests {
5374    use super::decode_image_with_max_side;
5375
5376    fn png(img: image::DynamicImage) -> Vec<u8> {
5377        let mut out = Vec::new();
5378        img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
5379            .unwrap();
5380        out
5381    }
5382
5383    /// A PNG chunk inserted before `IDAT`.
5384    fn with_chunk(png: &[u8], kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
5385        let crc = |bytes: &[u8]| {
5386            let mut c = 0xFFFF_FFFFu32;
5387            for &b in bytes {
5388                c ^= u32::from(b);
5389                for _ in 0..8 {
5390                    c = if c & 1 != 0 {
5391                        0xEDB8_8320 ^ (c >> 1)
5392                    } else {
5393                        c >> 1
5394                    };
5395                }
5396            }
5397            !c
5398        };
5399        let idat = png.windows(4).position(|w| w == b"IDAT").unwrap() - 4;
5400        let mut chunk = (data.len() as u32).to_be_bytes().to_vec();
5401        let body = [kind.as_slice(), data].concat();
5402        chunk.extend_from_slice(&body);
5403        chunk.extend_from_slice(&crc(&body).to_be_bytes());
5404        [&png[..idat], &chunk, &png[idat..]].concat()
5405    }
5406
5407    #[test]
5408    fn transparent_inputs_are_flattened_onto_white() {
5409        let mut rgba = image::RgbaImage::from_pixel(8, 8, image::Rgba([0, 0, 0, 0]));
5410        rgba.put_pixel(0, 0, image::Rgba([0, 0, 0, 255]));
5411        let page = decode_image_with_max_side(&png(rgba.into()), 1000).unwrap();
5412        assert_eq!(page.get_pixel(0, 0).0, [0, 0, 0]);
5413        assert_eq!(page.get_pixel(4, 4).0, [255, 255, 255]);
5414
5415        // 16-bit gray, 4000 and 60000, the 60000 key transparent.
5416        let g: image::ImageBuffer<image::Luma<u16>, Vec<u16>> =
5417            image::ImageBuffer::from_fn(2, 1, |x, _| image::Luma([[4000u16, 60000][x as usize]]));
5418        let plain = png(image::DynamicImage::ImageLuma16(g));
5419        let page = decode_image_with_max_side(&plain, 1000).unwrap();
5420        assert_eq!(
5421            (page.get_pixel(0, 0).0, page.get_pixel(1, 0).0),
5422            ([15; 3], [234; 3])
5423        );
5424        let keyed = with_chunk(&plain, b"tRNS", &60000u16.to_be_bytes());
5425        let page = decode_image_with_max_side(&keyed, 1000).unwrap();
5426        assert_eq!(
5427            (page.get_pixel(0, 0).0, page.get_pixel(1, 0).0),
5428            ([15; 3], [255; 3])
5429        );
5430    }
5431}