Skip to main content

docling_pdf/
ocr_det.rs

1//! PP-OCR text *detection* for bitmap pages (#429): the DB (Differentiable
2//! Binarization) detector RapidOCR runs in front of its recognizer, ported so
3//! text the layout model gives no region — a diagram's labels, a chart's
4//! ticks, a stamp, a page number in the margin — is still read.
5//!
6//! The pipeline's OCR has always been *recognition-only*: PP-OCRv3 rec runs
7//! on the lines inside layout regions, and nothing else on a page is looked
8//! at. docling's engines (RapidOCR, EasyOCR, Tesseract) instead detect text
9//! lines over the whole bitmap and every detected line becomes a cell — the
10//! ones no layout cluster claims turn into orphan text clusters (confidence
11//! 1.0) and read out in the flow. `ModalNet-19.png` shows the gap: the layout
12//! model scores only `SoftMax` above its 0.5 threshold (docling's own layout
13//! run yields *zero* clusters there), yet docling reads `MatMul`, `SoftMax`,
14//! `Mask (opt.)`, `Scale`, `Q`, `K` — all from its detector.
15//!
16//! Model: RapidOCR's `PP-OCRv6_det_small.onnx` (the one docling 2.127's
17//! RapidOCR default resolves to; `.models/ocr_det.onnx`, `DOCLING_OCR_DET_ONNX`
18//! overrides). Pre/post-processing follow `rapidocr/ch_ppocr_det`
19//! (`DetPreProcess` / `DBPostProcess`) with RapidOCR's config: shorter side
20//! scaled up to 736 (`limit_type: min`), sides rounded to multiples of 32,
21//! BGR channel order (cv2 input), `(x/255 − 0.5)/0.5`; probability threshold
22//! 0.3, 2×2 dilation, per-blob minimum-area rectangle, `box_score_fast` ≥ 0.5,
23//! unclip ratio 1.6, RapidOCR's row-then-column box order. Two deliberate
24//! simplifications: only outer blob boundaries are considered (OpenCV's
25//! `RETR_LIST` also walks hole contours, whose boxes fail the score gate
26//! anyway), and a detected quad is handed on as its axis-aligned bounding
27//! box — the recognizer's line prep crops rectangles, and rotated lines are
28//! not what documents lose today.
29//!
30//! Since #570 the detector is also the recognizer's *line source* inside the
31//! layout regions (`ocr_prep::prep_region_lines_det`), as it is for RapidOCR:
32//! the projection split that preceded it cut a region into full-width strips,
33//! which on forms — several fields per baseline — glued and dropped words
34//! (FUNSD word recall 0.57 → 0.68 on this change alone; `DOCLING_RS_OCR_LINES=
35//! projection` restores the strips). Detected boxes outside every region are
36//! still recognized and placed as orphan text (`uncovered_lines`). Missing
37//! model → no detection, quietly (`DOCLING_RS_DEBUG` reports it): regions
38//! fall back to the projection split, the margins go unread.
39
40use image::RgbImage;
41
42/// RapidOCR `Det.limit_side_len` with `limit_type: min`.
43pub const LIMIT_SIDE_LEN: u32 = 736;
44/// `DBPostProcess(thresh=…)`: probability → binary mask.
45pub const THRESH: f32 = 0.3;
46/// `DBPostProcess(box_thresh=…)`: minimum mean probability inside a box.
47pub const BOX_THRESH: f32 = 0.5;
48/// `DBPostProcess(unclip_ratio=…)`.
49pub const UNCLIP_RATIO: f32 = 1.6;
50/// `DBPostProcess.min_size`: the shortest side a blob's rectangle may have.
51const MIN_SIZE: f32 = 3.0;
52/// `TextDetector._BOX_SORT_Y_THRESHOLD`: boxes whose top-left `y` differ by
53/// less than this share a row when ordering.
54const BOX_SORT_Y_THRESHOLD: f32 = 10.0;
55
56/// One detected text line: its axis-aligned box in *input image pixels* and
57/// the DB score (mean probability inside the pre-unclip rectangle).
58#[derive(Debug, Clone, Copy, PartialEq)]
59pub struct DetBox {
60    pub l: f32,
61    pub t: f32,
62    pub r: f32,
63    pub b: f32,
64    pub score: f32,
65}
66
67/// `DetPreProcess.resize`: the network input size for a `w × h` image —
68/// shorter side scaled up to [`LIMIT_SIDE_LEN`] (never down), both sides
69/// rounded to a multiple of 32. `None` when a side rounds to zero.
70pub fn det_input_size(w: u32, h: u32) -> Option<(u32, u32)> {
71    det_input_size_capped(w, h, max_side_cap())
72}
73
74/// Default cap on the detector input's longer side: RapidOCR's
75/// `Global.max_side_len` (2000) — the longest side its whole OCR input is
76/// shrunk to before detection, and so what docling's detector sees. Until
77/// #570 this was PaddleOCR's 960 (`det_limit_side_len`, `limit_type: max`):
78/// while the detector only supplemented the region pass that cost about a
79/// third of the detection time and moved outputs by noise-level amounts;
80/// now that its boxes are the recognizer's crops the resolution is recall —
81/// 960 reads 0.834 of FUNSD's words where 2000 reads 0.856 (30 forms, same
82/// recognizer). A Letter page at the 2.0 px/pt render goes in at 1216 ×
83/// 1600; `DOCLING_RS_OCR_DET_MAX_SIDE=0` lifts the cap entirely, 960 restores
84/// the old budget.
85pub const DEFAULT_MAX_SIDE: u32 = 2000;
86
87/// `DOCLING_RS_OCR_DET_MAX_SIDE`: the cap on the detector input's longer
88/// side — [`DEFAULT_MAX_SIDE`] unless set, `0` = uncapped (RapidOCR's rule).
89/// The DB net is the costliest OCR stage on a scanned page and its cost is
90/// linear in input pixels; a tighter cap trades small-print recall for time.
91fn max_side_cap() -> u32 {
92    static CAP: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
93    *CAP.get_or_init(|| {
94        docling_core::env::parse::<u32>("DOCLING_RS_OCR_DET_MAX_SIDE").unwrap_or(DEFAULT_MAX_SIDE)
95    })
96}
97
98/// [`det_input_size`] with an explicit longer-side cap (`0` = none): the cap
99/// scales the image down first, then RapidOCR's shorter-side rule applies to
100/// what is left (so a capped input never exceeds the cap).
101pub fn det_input_size_capped(w: u32, h: u32, max_side: u32) -> Option<(u32, u32)> {
102    if w == 0 || h == 0 {
103        return None;
104    }
105    let (w, h) = (w as f32, h as f32);
106    // RapidOCR's rule first (shorter side up to 736, never down), then the
107    // cap pulls the longer side back if that overshoots it.
108    let mut ratio = if w.min(h) < LIMIT_SIDE_LEN as f32 {
109        LIMIT_SIDE_LEN as f32 / w.min(h)
110    } else {
111        1.0
112    };
113    if max_side > 0 && w.max(h) * ratio > max_side as f32 {
114        ratio = max_side as f32 / w.max(h);
115    }
116    let round32 = |v: f32| ((v as i64 as f32 / 32.0).round() * 32.0) as i64;
117    let (rw, rh) = (round32(w * ratio), round32(h * ratio));
118    (rw > 0 && rh > 0).then_some((rw as u32, rh as u32))
119}
120
121/// The NCHW float input for the detector: the image resized to
122/// [`det_input_size`] (bilinear, cv2's default), channels in **BGR** order
123/// (RapidOCR feeds a cv2 image), normalized `(x/255 − 0.5)/0.5`. Returns the
124/// tensor and its `(width, height)`.
125pub fn prep_det_input(img: &RgbImage) -> Option<(Vec<f32>, u32, u32)> {
126    let (w, h) = det_input_size(img.width(), img.height())?;
127    let resized = if (w, h) == img.dimensions() {
128        img.clone()
129    } else {
130        resize_bilinear(img, w, h)
131    };
132    let n = (w * h) as usize;
133    let mut data = vec![0f32; 3 * n];
134    for (i, px) in resized.pixels().enumerate() {
135        // B, G, R planes.
136        data[i] = px[2] as f32 / 127.5 - 1.0;
137        data[n + i] = px[1] as f32 / 127.5 - 1.0;
138        data[2 * n + i] = px[0] as f32 / 127.5 - 1.0;
139    }
140    Some((data, w, h))
141}
142
143/// Bilinear resize (cv2's default `INTER_LINEAR`) — `fast_image_resize`'s SIMD
144/// convolution with the triangle kernel, the scalar `image` crate resize with
145/// `DOCLING_RS_SLOW_RESIZE=1` (same kernel, several times slower; the
146/// scalar path is also the fallback should the SIMD one refuse the buffer).
147fn resize_bilinear(img: &RgbImage, w: u32, h: u32) -> RgbImage {
148    #[cfg(feature = "ml")]
149    {
150        use fast_image_resize as fir;
151        static SLOW: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
152        let slow = *SLOW.get_or_init(|| docling_core::env::flag("DOCLING_RS_SLOW_RESIZE"));
153        if !slow {
154            let fast = || {
155                let src = fir::images::ImageRef::new(
156                    img.width(),
157                    img.height(),
158                    img.as_raw(),
159                    fir::PixelType::U8x3,
160                )
161                .ok()?;
162                let mut dst = fir::images::Image::new(w, h, fir::PixelType::U8x3);
163                fir::Resizer::new()
164                    .resize(
165                        &src,
166                        &mut dst,
167                        &fir::ResizeOptions::new()
168                            .resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::Bilinear)),
169                    )
170                    .ok()?;
171                RgbImage::from_raw(w, h, dst.into_vec())
172            };
173            if let Some(out) = fast() {
174                return out;
175            }
176        }
177    }
178    image::imageops::resize(img, w, h, image::imageops::FilterType::Triangle)
179}
180
181/// `DBPostProcess.__call__`: text boxes from the detector's `w × h`
182/// probability map, mapped onto a `dest_w × dest_h` image (the one the map was
183/// computed from). Boxes come back in RapidOCR's reading order.
184pub fn db_boxes(prob: &[f32], w: usize, h: usize, dest_w: u32, dest_h: u32) -> Vec<DetBox> {
185    if prob.len() < w * h || w == 0 || h == 0 {
186        return Vec::new();
187    }
188    // Binarize, then dilate with a 2×2 kernel (cv2.dilate, anchor at the
189    // kernel center = its bottom-right cell, so a pixel lights up when it or
190    // its left / upper / upper-left neighbour is set).
191    let seg = |x: usize, y: usize| prob[y * w + x] > THRESH;
192    let mut mask = vec![false; w * h];
193    for y in 0..h {
194        for x in 0..w {
195            mask[y * w + x] = seg(x, y)
196                || (x > 0 && seg(x - 1, y))
197                || (y > 0 && seg(x, y - 1))
198                || (x > 0 && y > 0 && seg(x - 1, y - 1));
199        }
200    }
201    let mut quads: Vec<([(f32, f32); 4], f32)> = Vec::new();
202    let mut seen = vec![false; w * h];
203    let mut stack = Vec::new();
204    let mut component = Vec::new();
205    for start in 0..w * h {
206        if !mask[start] || seen[start] {
207            continue;
208        }
209        // 8-connected blob (cv2.findContours' outer boundary connectivity).
210        component.clear();
211        seen[start] = true;
212        stack.push(start);
213        while let Some(i) = stack.pop() {
214            component.push(i);
215            let (x, y) = (i % w, i / w);
216            for dy in -1i64..=1 {
217                for dx in -1i64..=1 {
218                    let (nx, ny) = (x as i64 + dx, y as i64 + dy);
219                    if nx < 0 || ny < 0 || nx >= w as i64 || ny >= h as i64 {
220                        continue;
221                    }
222                    let j = ny as usize * w + nx as usize;
223                    if mask[j] && !seen[j] {
224                        seen[j] = true;
225                        stack.push(j);
226                    }
227                }
228            }
229        }
230        if quads.len() >= 1000 {
231            // `max_candidates`.
232            break;
233        }
234        // The contour points are pixel centers on the blob's boundary; the
235        // minimum-area rectangle of the boundary is that of the whole blob.
236        let boundary: Vec<(f32, f32)> = component
237            .iter()
238            .copied()
239            .filter(|&i| {
240                let (x, y) = (i % w, i / w);
241                x == 0
242                    || y == 0
243                    || x + 1 == w
244                    || y + 1 == h
245                    || !mask[i - 1]
246                    || !mask[i + 1]
247                    || !mask[i - w]
248                    || !mask[i + w]
249            })
250            .map(|i| ((i % w) as f32, (i / w) as f32))
251            .collect();
252        let Some((corners, sside)) = min_area_rect(&boundary) else {
253            continue;
254        };
255        if sside < MIN_SIZE {
256            continue;
257        }
258        let score = box_score_fast(prob, w, h, &corners);
259        if score < BOX_THRESH {
260            continue;
261        }
262        let Some((expanded, sside)) = unclip(&corners) else {
263            continue;
264        };
265        if sside < MIN_SIZE + 2.0 {
266            continue;
267        }
268        // Into the source image's pixel grid.
269        let mapped: [(f32, f32); 4] = std::array::from_fn(|k| {
270            let (x, y) = expanded[k];
271            (
272                (x / w as f32 * dest_w as f32)
273                    .round()
274                    .clamp(0.0, dest_w as f32),
275                (y / h as f32 * dest_h as f32)
276                    .round()
277                    .clamp(0.0, dest_h as f32),
278            )
279        });
280        quads.push((mapped, score));
281    }
282    // `filter_det_res`: drop boxes whose rectangle is ≤ 3 px on a side.
283    let mut boxes: Vec<DetBox> = quads
284        .into_iter()
285        .filter_map(|(q, score)| {
286            let side =
287                |a: (f32, f32), b: (f32, f32)| ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt();
288            let (rw, rh) = (side(q[0], q[1]).floor(), side(q[0], q[3]).floor());
289            if rw <= 3.0 || rh <= 3.0 {
290                return None;
291            }
292            let xs = q.iter().map(|p| p.0);
293            let ys = q.iter().map(|p| p.1);
294            Some(DetBox {
295                l: xs.clone().fold(f32::MAX, f32::min),
296                t: ys.clone().fold(f32::MAX, f32::min),
297                r: xs.fold(f32::MIN, f32::max),
298                b: ys.fold(f32::MIN, f32::max),
299                score,
300            })
301        })
302        .collect();
303    sort_boxes(&mut boxes);
304    boxes
305}
306
307/// `TextDetector.sorted_boxes`: by top edge, then a bubble pass that swaps
308/// *adjacent* boxes whose tops lie within [`BOX_SORT_Y_THRESHOLD`] when the
309/// lower one starts further left — RapidOCR's exact algorithm. The first
310/// port (#429) grouped boxes into rows transitively (consecutive tops within
311/// the threshold = one row) and sorted each row by `x`; on a two-column
312/// newspaper every line top is within 10 px of the next line's in the other
313/// column, the whole page chained into one "row", and the lines of a column
314/// came out ordered by their left edge — scrambled — once they became the
315/// recognizer's crops (#570). RapidOCR's local swaps only reorder boxes that
316/// genuinely share a baseline.
317pub fn sort_boxes(boxes: &mut [DetBox]) {
318    boxes.sort_by(|a, b| a.t.total_cmp(&b.t).then(a.l.total_cmp(&b.l)));
319    for i in 0..boxes.len().saturating_sub(1) {
320        let mut j = i;
321        loop {
322            let (upper, lower) = (j, j + 1);
323            if (boxes[lower].t - boxes[upper].t).abs() < BOX_SORT_Y_THRESHOLD
324                && boxes[lower].l < boxes[upper].l
325            {
326                boxes.swap(upper, lower);
327            } else {
328                break;
329            }
330            if j == 0 {
331                break;
332            }
333            j -= 1;
334        }
335    }
336}
337
338/// A candidate enclosing rectangle: its area, corners and shorter side.
339type RectCandidate = (f32, [(f32, f32); 4], f32);
340
341/// `cv2.minAreaRect` over a point set (rotating calipers on the convex hull):
342/// the four corners of the smallest enclosing rectangle and its shorter side,
343/// in the order `get_mini_boxes` returns (top-left, top-right, bottom-right,
344/// bottom-left, for an upright box). `None` for fewer than one point.
345pub fn min_area_rect(points: &[(f32, f32)]) -> Option<([(f32, f32); 4], f32)> {
346    let hull = convex_hull(points);
347    if hull.is_empty() {
348        return None;
349    }
350    if hull.len() <= 2 {
351        // A single pixel or a straight run: a degenerate rectangle along it.
352        let (a, b) = (hull[0], *hull.last().unwrap());
353        return Some((order_corners([a, b, b, a]), 0.0));
354    }
355    let mut best: Option<RectCandidate> = None;
356    for i in 0..hull.len() {
357        let (p, q) = (hull[i], hull[(i + 1) % hull.len()]);
358        let (ex, ey) = (q.0 - p.0, q.1 - p.1);
359        let len = (ex * ex + ey * ey).sqrt();
360        if len < 1e-6 {
361            continue;
362        }
363        let (ux, uy) = (ex / len, ey / len);
364        let (vx, vy) = (-uy, ux);
365        let (mut umin, mut umax, mut vmin, mut vmax) = (f32::MAX, f32::MIN, f32::MAX, f32::MIN);
366        for &(x, y) in &hull {
367            let u = x * ux + y * uy;
368            let v = x * vx + y * vy;
369            umin = umin.min(u);
370            umax = umax.max(u);
371            vmin = vmin.min(v);
372            vmax = vmax.max(v);
373        }
374        let area = (umax - umin) * (vmax - vmin);
375        if best.as_ref().is_none_or(|(a, _, _)| area < *a) {
376            let corner = |u: f32, v: f32| (u * ux + v * vx, u * uy + v * vy);
377            let corners = [
378                corner(umin, vmin),
379                corner(umax, vmin),
380                corner(umax, vmax),
381                corner(umin, vmax),
382            ];
383            best = Some((area, corners, (umax - umin).min(vmax - vmin)));
384        }
385    }
386    best.map(|(_, corners, sside)| (order_corners(corners), sside))
387}
388
389/// `get_mini_boxes`' corner order: sort by x, then the left pair top-first and
390/// the right pair top-first → `[tl, tr, br, bl]`.
391fn order_corners(mut c: [(f32, f32); 4]) -> [(f32, f32); 4] {
392    c.sort_by(|a, b| a.0.total_cmp(&b.0));
393    let (i1, i4) = if c[1].1 > c[0].1 { (0, 1) } else { (1, 0) };
394    let (i2, i3) = if c[3].1 > c[2].1 { (2, 3) } else { (3, 2) };
395    [c[i1], c[i2], c[i3], c[i4]]
396}
397
398/// Andrew's monotone chain; counter-clockwise, no collinear duplicates.
399fn convex_hull(points: &[(f32, f32)]) -> Vec<(f32, f32)> {
400    let mut pts: Vec<(f32, f32)> = points.to_vec();
401    pts.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
402    pts.dedup();
403    if pts.len() < 3 {
404        return pts;
405    }
406    let cross = |o: (f32, f32), a: (f32, f32), b: (f32, f32)| {
407        (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0)
408    };
409    let mut lower: Vec<(f32, f32)> = Vec::new();
410    for &p in &pts {
411        while lower.len() >= 2 && cross(lower[lower.len() - 2], lower[lower.len() - 1], p) <= 0.0 {
412            lower.pop();
413        }
414        lower.push(p);
415    }
416    let mut upper: Vec<(f32, f32)> = Vec::new();
417    for &p in pts.iter().rev() {
418        while upper.len() >= 2 && cross(upper[upper.len() - 2], upper[upper.len() - 1], p) <= 0.0 {
419            upper.pop();
420        }
421        upper.push(p);
422    }
423    lower.pop();
424    upper.pop();
425    lower.extend(upper);
426    lower
427}
428
429/// `box_score_fast`: mean probability over the pixels inside the rectangle
430/// (a convex quad — the pixel-center test replaces `cv2.fillPoly`).
431fn box_score_fast(prob: &[f32], w: usize, h: usize, quad: &[(f32, f32); 4]) -> f32 {
432    let xmin = quad
433        .iter()
434        .map(|p| p.0)
435        .fold(f32::MAX, f32::min)
436        .floor()
437        .clamp(0.0, (w - 1) as f32) as usize;
438    let xmax = quad
439        .iter()
440        .map(|p| p.0)
441        .fold(f32::MIN, f32::max)
442        .ceil()
443        .clamp(0.0, (w - 1) as f32) as usize;
444    let ymin = quad
445        .iter()
446        .map(|p| p.1)
447        .fold(f32::MAX, f32::min)
448        .floor()
449        .clamp(0.0, (h - 1) as f32) as usize;
450    let ymax = quad
451        .iter()
452        .map(|p| p.1)
453        .fold(f32::MIN, f32::max)
454        .ceil()
455        .clamp(0.0, (h - 1) as f32) as usize;
456    let (mut sum, mut n) = (0f64, 0usize);
457    for y in ymin..=ymax {
458        for x in xmin..=xmax {
459            if inside_convex(quad, (x as f32, y as f32)) {
460                sum += prob[y * w + x] as f64;
461                n += 1;
462            }
463        }
464    }
465    if n == 0 {
466        0.0
467    } else {
468        (sum / n as f64) as f32
469    }
470}
471
472/// Point-in-convex-polygon (boundary counts as inside), any winding.
473fn inside_convex(quad: &[(f32, f32); 4], p: (f32, f32)) -> bool {
474    let mut pos = false;
475    let mut neg = false;
476    for i in 0..4 {
477        let (a, b) = (quad[i], quad[(i + 1) % 4]);
478        let cross = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
479        pos |= cross > 1e-6;
480        neg |= cross < -1e-6;
481    }
482    !(pos && neg)
483}
484
485/// `unclip` + `get_mini_boxes`: grow the rectangle outward by
486/// `area · unclip_ratio / perimeter` (the polygon offset of a rectangle is a
487/// rounded rectangle whose minimum-area rectangle is the original grown by
488/// the offset on every side). Returns the corners and the shorter side.
489fn unclip(quad: &[(f32, f32); 4]) -> Option<([(f32, f32); 4], f32)> {
490    let side = |a: (f32, f32), b: (f32, f32)| ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt();
491    let (wlen, hlen) = (side(quad[0], quad[1]), side(quad[1], quad[2]));
492    let perimeter = 2.0 * (wlen + hlen);
493    if perimeter < 1e-6 {
494        return None;
495    }
496    let d = wlen * hlen * UNCLIP_RATIO / perimeter;
497    let (cx, cy) = (
498        quad.iter().map(|p| p.0).sum::<f32>() / 4.0,
499        quad.iter().map(|p| p.1).sum::<f32>() / 4.0,
500    );
501    // Unit axes of the rectangle.
502    let (ux, uy) = if wlen > 1e-6 {
503        (
504            (quad[1].0 - quad[0].0) / wlen,
505            (quad[1].1 - quad[0].1) / wlen,
506        )
507    } else {
508        (1.0, 0.0)
509    };
510    let (vx, vy) = if hlen > 1e-6 {
511        (
512            (quad[2].0 - quad[1].0) / hlen,
513            (quad[2].1 - quad[1].1) / hlen,
514        )
515    } else {
516        (-uy, ux)
517    };
518    let (hw, hh) = (wlen / 2.0 + d, hlen / 2.0 + d);
519    let corner = |su: f32, sv: f32| {
520        (
521            cx + su * hw * ux + sv * hh * vx,
522            cy + su * hw * uy + sv * hh * vy,
523        )
524    };
525    let corners = order_corners([
526        corner(-1.0, -1.0),
527        corner(1.0, -1.0),
528        corner(1.0, 1.0),
529        corner(-1.0, 1.0),
530    ]);
531    Some((corners, (wlen + 2.0 * d).min(hlen + 2.0 * d)))
532}
533
534/// The detected lines the recognizer still has to read (#429): those not
535/// already covered by the region-scoped pass. `detected` is in image pixels
536/// at `scale` px/pt; `regions` and `cells` are the page's layout regions and
537/// the cells recognized so far, in page points. A line counts as covered when
538/// it lies mostly (> 50 %) inside a text-like or table region — whose lines
539/// the region pass segmented and recognized, whatever it made of them — when
540/// the recognized cells inside it sum to > 30 % of its area, or when a line
541/// accepted earlier in reading order overlaps it by > 30 %. Cumulative on
542/// purpose: DB happily spans two adjacent columns in one box, and judged cell
543/// by cell such a box overlaps every cell a little while re-reading all of
544/// them (the `old_newspaper` scan doubled a paragraph that way); and DB can
545/// emit a word and its whole line. Returns `text` regions in page points for
546/// the recognizer's line prep. Shared by the native worker and the browser
547/// pipeline.
548pub fn uncovered_lines(
549    detected: &[DetBox],
550    scale: f32,
551    regions: &[crate::layout::Region],
552    cells: &[crate::pdfium_backend::TextCell],
553) -> Vec<crate::layout::Region> {
554    let mut accepted: Vec<crate::layout::Region> = Vec::new();
555    for d in detected.iter().map(|d| crate::layout::Region {
556        label: "text",
557        score: d.score,
558        l: d.l / scale,
559        t: d.t / scale,
560        r: d.r / scale,
561        b: d.b / scale,
562    }) {
563        let da = ((d.r - d.l) * (d.b - d.t)).max(1.0);
564        let inter = |l: f32, t: f32, r: f32, b: f32| {
565            (d.r.min(r) - d.l.max(l)).max(0.0) * (d.b.min(b) - d.t.max(t)).max(0.0)
566        };
567        let in_region = regions.iter().any(|r| {
568            (crate::ocr_prep::is_text_label(r.label) || crate::assemble::is_table_like(r.label))
569                && inter(r.l, r.t, r.r, r.b) / da > 0.5
570        });
571        let by_cells: f32 = cells.iter().map(|c| inter(c.l, c.t, c.r, c.b)).sum::<f32>() / da;
572        let by_accepted = accepted
573            .iter()
574            .any(|u| inter(u.l, u.t, u.r, u.b) / da > 0.3);
575        if !in_region && by_cells <= 0.3 && !by_accepted {
576            accepted.push(d);
577        }
578    }
579    accepted
580}
581
582#[cfg(feature = "ml")]
583pub use session::DetModel;
584
585#[cfg(feature = "ml")]
586mod session {
587    use super::{db_boxes, prep_det_input, DetBox};
588    use image::RgbImage;
589    use ort::session::Session;
590    use ort::value::Tensor;
591
592    /// The detector session. Loaded lazily by the page worker alongside the
593    /// recognizer; absent model → the pipeline runs recognition-only.
594    pub struct DetModel {
595        session: Session,
596    }
597
598    /// `DOCLING_OCR_DET_ONNX`, else `.models/ocr_det.onnx` through the asset
599    /// resolver (CWD, `DOCLING_RS_MODELS_DIR`, exe dir).
600    pub(crate) fn resolve_det_path() -> String {
601        docling_core::env::nonempty("DOCLING_OCR_DET_ONNX")
602            .unwrap_or_else(|| crate::resolve_asset(".models/ocr_det.onnx"))
603    }
604
605    impl DetModel {
606        /// Load the detector with `intra` intra-op threads (the worker's layout
607        /// thread budget; DB is a plain conv net, so the output is stable
608        /// across thread counts to the precision a 0.3 threshold sees).
609        pub fn load(intra: usize) -> Result<Self, String> {
610            let path = resolve_det_path();
611            if !std::path::Path::new(&path).exists() {
612                return Err(format!("text detection model not found at {path}"));
613            }
614            let builder = docling_onnx::session_builder()
615                .map_err(|e| format!("ocr-det: builder: {e}"))?
616                .with_intra_threads(intra.max(1))
617                .map_err(|e| format!("ocr-det: intra_threads: {e}"))?;
618            let builder = docling_onnx::apply(builder).map_err(|e| format!("ocr-det: {e}"))?;
619            let session = docling_onnx::commit(builder, &path, "det")
620                .map_err(|e| format!("ocr-det: load {path}: {e}"))?;
621            Ok(Self { session })
622        }
623
624        /// Detect text lines on `img`; boxes in `img` pixels, reading order.
625        pub fn detect(&mut self, img: &RgbImage) -> Result<Vec<DetBox>, String> {
626            let Some((data, w, h)) = crate::timing::timed("ocr.det.prep", || prep_det_input(img))
627            else {
628                return Ok(Vec::new());
629            };
630            let input = Tensor::from_array(([1usize, 3, h as usize, w as usize], data))
631                .map_err(|e| format!("ocr-det: input: {e}"))?;
632            let name = self.session.inputs()[0].name().to_string();
633            let outputs = crate::timing::timed("ocr.det.net", || {
634                self.session
635                    .run(ort::inputs![name.as_str() => input])
636                    .map_err(|e| format!("ocr-det: run: {e}"))
637            })?;
638            let (shape, prob) = outputs[0]
639                .try_extract_tensor::<f32>()
640                .map_err(|e| format!("ocr-det: output: {e}"))?;
641            let dims: Vec<usize> = shape.iter().map(|&d| d as usize).collect();
642            let (ph, pw) = match dims.as_slice() {
643                [_, _, ph, pw] => (*ph, *pw),
644                _ => return Err(format!("ocr-det: unexpected output shape {dims:?}")),
645            };
646            Ok(crate::timing::timed("ocr.det.post", || {
647                db_boxes(prob, pw, ph, img.width(), img.height())
648            }))
649        }
650    }
651}
652
653#[cfg(test)]
654mod tests {
655    use super::*;
656
657    #[test]
658    fn input_size_scales_the_short_side_to_736_in_multiples_of_32() {
659        // RapidOCR's uncapped rule. 445 × 884: short side 445 → ×1.654;
660        // 736 × 1462 → 736 × 1472.
661        assert_eq!(det_input_size_capped(445, 884, 0), Some((736, 1472)));
662        // Already ≥ 736 on the short side: unchanged bar the /32 rounding.
663        assert_eq!(det_input_size_capped(1335, 2652, 0), Some((1344, 2656)));
664        assert_eq!(det_input_size(0, 10), None);
665        // The default cap (2000, RapidOCR's) applies when the env knob is
666        // unset — a Letter render stays at its shorter-side-rule size.
667        assert_eq!(det_input_size(1224, 1584), Some((1216, 1600)));
668        // A longer-side cap scales a big page down (1224 × 1584 → 736 × 960
669        // for 960) and leaves a small image's shorter-side upscale alone
670        // (445 × 884 still goes to 736 × 1472 under a 1500 cap, 480 × 960
671        // under 960).
672        assert_eq!(det_input_size_capped(1224, 1584, 960), Some((736, 960)));
673        assert_eq!(det_input_size_capped(445, 884, 1500), Some((736, 1472)));
674        assert_eq!(det_input_size_capped(445, 884, 960), Some((480, 960)));
675        assert_eq!(det_input_size_capped(1224, 1584, 0), Some((1216, 1600)));
676    }
677
678    #[test]
679    fn det_input_is_bgr_normalized() {
680        let mut img = RgbImage::new(736, 736);
681        img.put_pixel(0, 0, image::Rgb([255, 0, 128]));
682        let (data, w, h) = prep_det_input(&img).unwrap();
683        assert_eq!((w, h), (736, 736));
684        let n = (w * h) as usize;
685        // Blue plane first: pixel (0,0) has B=128 → ~0.0039; G=0 → -1; R=255 → 1.
686        assert!((data[0] - (128.0 / 127.5 - 1.0)).abs() < 1e-6);
687        assert_eq!(data[n], -1.0);
688        assert_eq!(data[2 * n], 1.0);
689    }
690
691    #[test]
692    fn min_area_rect_of_an_upright_and_a_tilted_blob() {
693        let pts: Vec<(f32, f32)> = (0..20)
694            .flat_map(|x| (0..5).map(move |y| (x as f32, y as f32)))
695            .collect();
696        let (c, sside) = min_area_rect(&pts).unwrap();
697        assert!((sside - 4.0).abs() < 1e-3);
698        assert!(
699            (c[0].0 - 0.0).abs() < 1e-3 && (c[0].1 - 0.0).abs() < 1e-3,
700            "{c:?}"
701        );
702        assert!(
703            (c[2].0 - 19.0).abs() < 1e-3 && (c[2].1 - 4.0).abs() < 1e-3,
704            "{c:?}"
705        );
706        // The same strip rotated 45°: the tight rectangle is ~19 × 4, not the
707        // axis-aligned 16 × 16 box.
708        let s = std::f32::consts::FRAC_1_SQRT_2;
709        let rot: Vec<(f32, f32)> = pts
710            .iter()
711            .map(|&(x, y)| (x * s - y * s + 50.0, x * s + y * s + 50.0))
712            .collect();
713        let (_, sside) = min_area_rect(&rot).unwrap();
714        assert!((sside - 4.0).abs() < 1e-2, "{sside}");
715    }
716
717    /// Two text-like blobs on a probability map → two boxes, grown by the
718    /// unclip distance (area·1.6/perimeter) on every side, in reading order,
719    /// scaled to the destination image; a faint blob below `box_thresh` and a
720    /// speck below `min_size` are dropped.
721    #[test]
722    fn db_boxes_from_a_synthetic_probability_map() {
723        let (w, h) = (128usize, 64usize);
724        let mut prob = vec![0f32; w * h];
725        let blob = |prob: &mut Vec<f32>, l: usize, t: usize, r: usize, b: usize, p: f32| {
726            for y in t..b {
727                for x in l..r {
728                    prob[y * w + x] = p;
729                }
730            }
731        };
732        blob(&mut prob, 70, 10, 110, 20, 0.9); // right, upper row
733        blob(&mut prob, 10, 12, 50, 22, 0.9); // left, same row (top within 10)
734        blob(&mut prob, 10, 40, 60, 48, 0.35); // above thresh but mean < box_thresh
735        blob(&mut prob, 100, 50, 102, 52, 0.9); // speck
736        let boxes = db_boxes(&prob, w, h, 256, 128);
737        assert_eq!(boxes.len(), 2, "{boxes:?}");
738        // Left blob first (same row, smaller x). Its rectangle spans pixel
739        // centers 10..49 × 12..21 (39 × 9 after dilation shifts by one:
740        // 10..50 × 12..22 → 40 × 10), unclip d = 400·1.6/100 = 6.4.
741        let a = &boxes[0];
742        assert!(a.l < boxes[1].l);
743        // The dilated rectangle takes in one zero-probability rim row and
744        // column, so the mean sits a little under the blob's 0.9 — RapidOCR
745        // scores the dilated contour on the raw map the same way.
746        assert!(a.score > 0.75 && a.score < 0.9, "{}", a.score);
747        // Doubled for the 2× destination scale: l ≈ (10 − 6.4)·2, r ≈ (50 + 6.4)·2.
748        assert!(
749            (a.l - 7.0).abs() <= 2.0 && (a.r - 113.0).abs() <= 2.0,
750            "{a:?}"
751        );
752        assert!(
753            (a.t - 11.0).abs() <= 2.0 && (a.b - 57.0).abs() <= 2.0,
754            "{a:?}"
755        );
756    }
757
758    /// The coverage rule: a line inside a text region, one whose area
759    /// recognized cells mostly fill (cumulatively — two half-covering cells
760    /// count), and a duplicate of an accepted line are all skipped; a line in
761    /// the open is kept, converted to page points.
762    #[test]
763    fn uncovered_lines_skip_what_the_region_pass_read() {
764        use crate::layout::Region;
765        use crate::pdfium_backend::TextCell;
766        let bx = |l: f32, t: f32, r: f32, b: f32| DetBox {
767            l,
768            t,
769            r,
770            b,
771            score: 0.9,
772        };
773        let regions = vec![Region {
774            label: "text",
775            score: 0.9,
776            l: 0.0,
777            t: 0.0,
778            r: 100.0,
779            b: 20.0,
780        }];
781        let cell = |l: f32, r: f32| TextCell {
782            text: "x".into(),
783            l,
784            t: 50.0,
785            r,
786            b: 60.0,
787        };
788        let cells = vec![cell(0.0, 50.0), cell(50.0, 100.0)];
789        let detected = vec![
790            bx(0.0, 0.0, 200.0, 40.0), // inside the text region (page pts 0..100 × 0..20)
791            bx(0.0, 100.0, 200.0, 120.0), // two cells cover it half each → covered
792            bx(0.0, 300.0, 200.0, 320.0), // in the open → kept
793            bx(20.0, 302.0, 100.0, 318.0), // a word of the accepted line → duplicate
794        ];
795        let out = uncovered_lines(&detected, 2.0, &regions, &cells);
796        assert_eq!(out.len(), 1, "{out:?}");
797        assert_eq!(
798            (out[0].l, out[0].t, out[0].r, out[0].b),
799            (0.0, 150.0, 100.0, 160.0)
800        );
801        assert_eq!(out[0].label, "text");
802    }
803
804    #[test]
805    fn boxes_sort_by_row_then_column() {
806        let bx = |l: f32, t: f32| DetBox {
807            l,
808            t,
809            r: l + 10.0,
810            b: t + 10.0,
811            score: 1.0,
812        };
813        let mut boxes = vec![
814            bx(50.0, 100.0),
815            bx(10.0, 105.0),
816            bx(30.0, 20.0),
817            bx(5.0, 200.0),
818        ];
819        sort_boxes(&mut boxes);
820        let order: Vec<(f32, f32)> = boxes.iter().map(|b| (b.l, b.t)).collect();
821        assert_eq!(
822            order,
823            vec![(30.0, 20.0), (10.0, 105.0), (50.0, 100.0), (5.0, 200.0)]
824        );
825        // Two columns whose line tops interleave within the threshold (a
826        // newspaper): each column's lines must stay top-to-bottom, and a
827        // right-column line sorts after the left-column line it shares a
828        // baseline with — RapidOCR's result, not one page-wide "row".
829        let mut cols = vec![
830            bx(97.0, 154.0),
831            bx(96.0, 173.0),
832            bx(600.0, 160.0),
833            bx(97.0, 191.0),
834            bx(601.0, 178.0),
835            bx(600.0, 197.0),
836        ];
837        sort_boxes(&mut cols);
838        let order: Vec<(f32, f32)> = cols.iter().map(|b| (b.l, b.t)).collect();
839        assert_eq!(
840            order,
841            vec![
842                (97.0, 154.0),
843                (600.0, 160.0),
844                (96.0, 173.0),
845                (601.0, 178.0),
846                (97.0, 191.0),
847                (600.0, 197.0)
848            ]
849        );
850    }
851}