Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[rust] Add OCR geometry and detector post-processing

laurenspriem244386354353
diff --git a/rust/crates/ml/src/cv/contours.rs b/rust/crates/ml/src/cv/contours.rs
index 73252cbd50..2ab374e529 100644
--- a/rust/crates/ml/src/cv/contours.rs
+++ b/rust/crates/ml/src/cv/contours.rs
@@ -1,4 +1,5 @@
use image::GrayImage;
+use imageproc::contours::BorderType;
use crate::cv::OpResult;
use crate::cv::image::{Contour, ImageU8};
@@ -16,9 +17,11 @@ pub(crate) fn find_contours(src: &ImageU8) -> OpResult<Vec<Contour>> {
.into_iter()
.map(|c| {
let area = imageproc::geometry::contour_area(&c.points);
+ let outer = c.border_type == BorderType::Outer;
Contour {
points: c.points.into_iter().map(|p| (p.x, p.y)).collect(),
area,
+ outer,
}
})
.collect())
diff --git a/rust/crates/ml/src/cv/image.rs b/rust/crates/ml/src/cv/image.rs
index 9e21ad97b3..872b5ae603 100644
--- a/rust/crates/ml/src/cv/image.rs
+++ b/rust/crates/ml/src/cv/image.rs
@@ -208,4 +208,5 @@ impl ImageF32 {
pub(crate) struct Contour {
pub points: Vec<(i32, i32)>,
pub area: f64,
+ pub outer: bool,
}
diff --git a/rust/crates/ml/src/lib.rs b/rust/crates/ml/src/lib.rs
index 32a7d281f1..6cd23fb566 100644
--- a/rust/crates/ml/src/lib.rs
+++ b/rust/crates/ml/src/lib.rs
@@ -7,6 +7,7 @@ pub mod face;
pub mod indexing;
mod models;
pub use models::ModelPaths;
+pub mod ocr;
mod onnx;
pub use onnx::golden_tooling;
mod pet;
diff --git a/rust/crates/ml/src/ocr/detect.rs b/rust/crates/ml/src/ocr/detect.rs
new file mode 100644
index 0000000000..588161bcc8
--- /dev/null
+++ b/rust/crates/ml/src/ocr/detect.rs
@@ -0,0 +1,345 @@
+use super::Point;
+use super::geometry::{
+ clip_to_bounds, mean_inside_quad, min_area_rect, min_edge, order_corners, scale_points, unclip,
+};
+use crate::cv;
+use crate::cv::image::{Contour, ImageU8};
+use crate::error::{MlError, MlResult};
+
+const BITMAP_THRESHOLD: f32 = 0.3;
+const BOX_SCORE_THRESHOLD: f32 = 0.6;
+const UNCLIP_RATIO: f32 = 1.5;
+const MIN_BOX_SIDE: f32 = 3.0;
+const MIN_UNCLIPPED_SIDE: f32 = MIN_BOX_SIDE + 2.0;
+const MAX_CANDIDATES: usize = 1000;
+const READING_LINE_TOLERANCE: f32 = 10.0;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct DetectionCandidate {
+ pub points: [Point; 4],
+ pub score: f32,
+}
+
+impl DetectionCandidate {
+ fn scaled(self, scale_x: f32, scale_y: f32) -> Self {
+ Self {
+ points: scale_points(&self.points, scale_x, scale_y),
+ score: self.score,
+ }
+ }
+
+ fn top_left(&self) -> Point {
+ self.points[0]
+ }
+}
+
+struct ProbabilityMap<'a> {
+ values: &'a [f32],
+ width: usize,
+ height: usize,
+}
+
+pub fn candidates_from_probability_map(
+ values: &[f32],
+ map_width: usize,
+ map_height: usize,
+ working_width: u32,
+ working_height: u32,
+) -> MlResult<Vec<DetectionCandidate>> {
+ if map_width == 0 || map_height == 0 || values.len() != map_width * map_height {
+ return Err(MlError::Postprocess(format!(
+ "probability map has {} values for {map_width}x{map_height}",
+ values.len()
+ )));
+ }
+ let map = ProbabilityMap {
+ values,
+ width: map_width,
+ height: map_height,
+ };
+ let scale_x = working_width as f32 / map_width as f32;
+ let scale_y = working_height as f32 / map_height as f32;
+ let candidates = largest_outer_contours(&map)?
+ .iter()
+ .filter_map(|contour| candidate_from_contour(contour, &map))
+ .map(|candidate| candidate.scaled(scale_x, scale_y))
+ .collect();
+ Ok(candidates)
+}
+
+fn threshold_bitmap(map: &ProbabilityMap<'_>) -> MlResult<ImageU8> {
+ let data = map
+ .values
+ .iter()
+ .map(|&p| if p > BITMAP_THRESHOLD { 255 } else { 0 })
+ .collect();
+ ImageU8::new(map.width as i32, map.height as i32, 1, data).map_err(MlError::Postprocess)
+}
+
+fn largest_outer_contours(map: &ProbabilityMap<'_>) -> MlResult<Vec<Contour>> {
+ let bitmap = threshold_bitmap(map)?;
+ let mut contours: Vec<Contour> = cv::find_contours(&bitmap)
+ .map_err(MlError::Postprocess)?
+ .into_iter()
+ .filter(|contour| contour.outer)
+ .collect();
+ contours.sort_by(|a, b| b.area.total_cmp(&a.area));
+ contours.truncate(MAX_CANDIDATES);
+ Ok(contours)
+}
+
+fn candidate_from_contour(
+ contour: &Contour,
+ map: &ProbabilityMap<'_>,
+) -> Option<DetectionCandidate> {
+ let rect = order_corners(min_area_rect(&contour.points)?);
+ if min_edge(&rect) < MIN_BOX_SIDE {
+ return None;
+ }
+ let score = mean_inside_quad(map.values, map.width, map.height, &rect);
+ if score < BOX_SCORE_THRESHOLD {
+ return None;
+ }
+ let expanded = unclip(&rect, UNCLIP_RATIO);
+ if min_edge(&expanded) < MIN_UNCLIPPED_SIDE {
+ return None;
+ }
+ let points = clip_to_bounds(&expanded, map.width as f32, map.height as f32);
+ Some(DetectionCandidate { points, score })
+}
+
+pub fn sort_reading_order(candidates: &mut [DetectionCandidate]) {
+ candidates.sort_by(|a, b| a.top_left().y.total_cmp(&b.top_left().y));
+ let mut start = 0;
+ while start < candidates.len() {
+ let line_top = candidates[start].top_left().y;
+ let end = start
+ + candidates[start..]
+ .iter()
+ .take_while(|c| (c.top_left().y - line_top).abs() <= READING_LINE_TOLERANCE)
+ .count();
+ candidates[start..end].sort_by(|a, b| a.top_left().x.total_cmp(&b.top_left().x));
+ start = end;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ocr::geometry::{edge_lengths, unclip};
+
+ const BACKGROUND: f32 = 0.05;
+ const FOREGROUND: f32 = 0.9;
+ const CONTOUR_TOLERANCE: f32 = 1.5;
+ const ROTATED_EDGE_TOLERANCE: f32 = 4.0;
+
+ struct Canvas {
+ width: usize,
+ height: usize,
+ values: Vec<f32>,
+ }
+
+ impl Canvas {
+ fn new(width: usize, height: usize) -> Self {
+ Self {
+ width,
+ height,
+ values: vec![BACKGROUND; width * height],
+ }
+ }
+
+ fn fill_rect(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
+ for y in y0..y1 {
+ for x in x0..x1 {
+ self.values[y * self.width + x] = FOREGROUND;
+ }
+ }
+ }
+
+ fn fill_rotated_rect(&mut self, center: Point, width: f32, height: f32, degrees: f32) {
+ let (sin, cos) = degrees.to_radians().sin_cos();
+ for y in 0..self.height {
+ for x in 0..self.width {
+ let dx = x as f32 - center.x;
+ let dy = y as f32 - center.y;
+ let along = dx * cos + dy * sin;
+ let across = -dx * sin + dy * cos;
+ if along.abs() <= width / 2.0 && across.abs() <= height / 2.0 {
+ self.values[y * self.width + x] = FOREGROUND;
+ }
+ }
+ }
+ }
+
+ fn candidates(&self) -> Vec<DetectionCandidate> {
+ self.candidates_for(self.width as u32, self.height as u32)
+ }
+
+ fn candidates_for(
+ &self,
+ working_width: u32,
+ working_height: u32,
+ ) -> Vec<DetectionCandidate> {
+ candidates_from_probability_map(
+ &self.values,
+ self.width,
+ self.height,
+ working_width,
+ working_height,
+ )
+ .unwrap()
+ }
+ }
+
+ fn traced_rect(x0: usize, y0: usize, x1: usize, y1: usize) -> [Point; 4] {
+ let (left, top) = (x0 as f32, y0 as f32);
+ let (right, bottom) = ((x1 - 1) as f32, (y1 - 1) as f32);
+ [
+ Point::new(left, top),
+ Point::new(right, top),
+ Point::new(right, bottom),
+ Point::new(left, bottom),
+ ]
+ }
+
+ fn assert_quads_close(actual: &[Point; 4], expected: &[Point; 4], tolerance: f32) {
+ for (a, e) in actual.iter().zip(expected) {
+ assert!(
+ (a.x - e.x).abs() <= tolerance && (a.y - e.y).abs() <= tolerance,
+ "expected {expected:?}, got {actual:?}"
+ );
+ }
+ }
+
+ fn center(candidate: &DetectionCandidate) -> Point {
+ let sum = candidate
+ .points
+ .iter()
+ .fold(Point::new(0.0, 0.0), |acc, &p| acc + p);
+ sum * 0.25
+ }
+
+ fn candidate_at(x: f32, y: f32) -> DetectionCandidate {
+ DetectionCandidate {
+ points: [
+ Point::new(x, y),
+ Point::new(x + 50.0, y),
+ Point::new(x + 50.0, y + 10.0),
+ Point::new(x, y + 10.0),
+ ],
+ score: 0.9,
+ }
+ }
+
+ #[test]
+ fn axis_aligned_rectangle_yields_one_expanded_candidate() {
+ let mut canvas = Canvas::new(200, 100);
+ canvas.fill_rect(40, 30, 140, 70);
+ let candidates = canvas.candidates();
+ assert_eq!(candidates.len(), 1, "{candidates:?}");
+ let expected = unclip(&traced_rect(40, 30, 140, 70), UNCLIP_RATIO);
+ assert_quads_close(&candidates[0].points, &expected, CONTOUR_TOLERANCE);
+ assert!((candidates[0].score - FOREGROUND).abs() <= 1e-3);
+ }
+
+ #[test]
+ fn candidates_scale_to_working_image() {
+ let mut canvas = Canvas::new(200, 100);
+ canvas.fill_rect(40, 30, 140, 70);
+ let candidates = canvas.candidates_for(400, 300);
+ assert_eq!(candidates.len(), 1);
+ let unscaled = &canvas.candidates()[0].points;
+ for (scaled, base) in candidates[0].points.iter().zip(unscaled) {
+ assert!((scaled.x - base.x * 2.0).abs() <= 1e-3);
+ assert!((scaled.y - base.y * 3.0).abs() <= 1e-3);
+ }
+ }
+
+ #[test]
+ fn rotated_rectangle_yields_one_candidate_with_expanded_edges() {
+ let (width, height, degrees) = (140.0, 40.0, 20.0f32);
+ let mut canvas = Canvas::new(300, 200);
+ canvas.fill_rotated_rect(Point::new(150.0, 100.0), width, height, degrees);
+ let candidates = canvas.candidates();
+ assert_eq!(candidates.len(), 1, "{candidates:?}");
+ let candidate = &candidates[0];
+ assert!(candidate.score > BOX_SCORE_THRESHOLD, "{}", candidate.score);
+ let d = width * height * UNCLIP_RATIO / (2.0 * (width + height));
+ let [top, right, bottom, left] = edge_lengths(&candidate.points);
+ for (edge, expected) in [
+ (top, width + 2.0 * d),
+ (bottom, width + 2.0 * d),
+ (right, height + 2.0 * d),
+ (left, height + 2.0 * d),
+ ] {
+ assert!(
+ (edge - expected).abs() <= ROTATED_EDGE_TOLERANCE,
+ "edge {edge}, expected {expected}"
+ );
+ }
+ let [tl, tr, _, _] = candidate.points;
+ let angle = (tr.y - tl.y).atan2(tr.x - tl.x).to_degrees();
+ assert!((angle - degrees).abs() <= 2.0, "angle {angle}");
+ }
+
+ #[test]
+ fn separate_rectangles_yield_separate_candidates_and_specks_are_dropped() {
+ let mut canvas = Canvas::new(200, 200);
+ canvas.fill_rect(20, 20, 80, 50);
+ canvas.fill_rect(120, 140, 180, 170);
+ canvas.fill_rect(100, 100, 102, 102);
+ let mut candidates = canvas.candidates();
+ assert_eq!(candidates.len(), 2, "{candidates:?}");
+ sort_reading_order(&mut candidates);
+ let first = center(&candidates[0]);
+ let second = center(&candidates[1]);
+ assert!(
+ (first.x - 49.5).abs() <= 2.0 && (first.y - 34.5).abs() <= 2.0,
+ "{first:?}"
+ );
+ assert!(
+ (second.x - 149.5).abs() <= 2.0 && (second.y - 154.5).abs() <= 2.0,
+ "{second:?}"
+ );
+ }
+
+ #[test]
+ fn reading_order_sorts_lines_top_to_bottom_then_left_to_right() {
+ let mut candidates = vec![
+ candidate_at(200.0, 50.0),
+ candidate_at(30.0, 150.0),
+ candidate_at(20.0, 52.0),
+ candidate_at(110.0, 47.0),
+ ];
+ sort_reading_order(&mut candidates);
+ let order: Vec<(f32, f32)> = candidates
+ .iter()
+ .map(|c| (c.top_left().x, c.top_left().y))
+ .collect();
+ assert_eq!(
+ order,
+ [(20.0, 52.0), (110.0, 47.0), (200.0, 50.0), (30.0, 150.0)]
+ );
+ }
+
+ #[test]
+ fn reading_order_groups_lines_within_ten_pixels_of_the_first_box_inclusive() {
+ let mut candidates = vec![
+ candidate_at(100.0, 40.0),
+ candidate_at(10.0, 50.0),
+ candidate_at(5.0, 50.5),
+ ];
+ sort_reading_order(&mut candidates);
+ let order: Vec<(f32, f32)> = candidates
+ .iter()
+ .map(|c| (c.top_left().x, c.top_left().y))
+ .collect();
+ assert_eq!(order, [(10.0, 50.0), (100.0, 40.0), (5.0, 50.5)]);
+ }
+
+ #[test]
+ fn rejects_probability_map_with_wrong_length() {
+ let error = candidates_from_probability_map(&[0.0; 10], 4, 4, 4, 4).unwrap_err();
+ assert!(matches!(error, MlError::Postprocess(_)), "{error}");
+ }
+}
diff --git a/rust/crates/ml/src/ocr/dictionary.rs b/rust/crates/ml/src/ocr/dictionary.rs
new file mode 100644
index 0000000000..295be010f0
--- /dev/null
+++ b/rust/crates/ml/src/ocr/dictionary.rs
@@ -0,0 +1,79 @@
+use std::path::Path;
+
+use crate::error::{MlError, MlResult};
+
+const BLANK_TOKEN: &str = "blank";
+const SPACE_TOKEN: &str = " ";
+
+pub fn load_dictionary(path: &Path, expected_size: usize) -> MlResult<Vec<String>> {
+ let contents = std::fs::read_to_string(path).map_err(|error| {
+ MlError::CorruptModel(format!(
+ "cannot read OCR dictionary {}: {error}",
+ path.display()
+ ))
+ })?;
+ let mut entries = Vec::with_capacity(expected_size);
+ entries.push(BLANK_TOKEN.to_string());
+ entries.extend(contents.lines().map(str::to_string));
+ entries.push(SPACE_TOKEN.to_string());
+ if entries.len() != expected_size {
+ return Err(MlError::CorruptModel(format!(
+ "OCR dictionary {} has {} entries, recognizer expects {expected_size}",
+ path.display(),
+ entries.len()
+ )));
+ }
+ Ok(entries)
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::Write;
+
+ use super::*;
+
+ const LOCAL_DICTIONARY: &str = "/private/tmp/claude-501/-Users-laurens-dev-ente-repo-ente8/a307b632-3b09-4f43-884c-2830ff54fe8f/scratchpad/models/ppocrv5_dict.txt";
+ const PPOCRV5_VOCABULARY: usize = 18385;
+
+ fn temp_dictionary(contents: &[u8]) -> tempfile::NamedTempFile {
+ let mut file = tempfile::NamedTempFile::new().unwrap();
+ file.write_all(contents).unwrap();
+ file.flush().unwrap();
+ file
+ }
+
+ #[test]
+ fn loads_local_ppocrv5_dictionary() {
+ let path = Path::new(LOCAL_DICTIONARY);
+ if !path.exists() {
+ return;
+ }
+ let entries = load_dictionary(path, PPOCRV5_VOCABULARY).unwrap();
+ assert_eq!(entries.len(), PPOCRV5_VOCABULARY);
+ assert_eq!(entries[0], "blank");
+ assert_eq!(entries[1], "\u{3000}");
+ assert_eq!(entries.last().unwrap(), " ");
+ }
+
+ #[test]
+ fn wraps_lines_with_blank_and_space() {
+ let file = temp_dictionary("\u{3000}\r\na\n \nb\n".as_bytes());
+ let entries = load_dictionary(file.path(), 6).unwrap();
+ assert_eq!(entries, ["blank", "\u{3000}", "a", " ", "b", " "]);
+ }
+
+ #[test]
+ fn rejects_unexpected_entry_count() {
+ let file = temp_dictionary(b"a\nb\nc\n");
+ let error = load_dictionary(file.path(), 6).unwrap_err();
+ assert!(matches!(error, MlError::CorruptModel(_)), "{error}");
+ assert!(error.to_string().contains("has 5 entries"), "{error}");
+ }
+
+ #[test]
+ fn rejects_missing_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let error = load_dictionary(&dir.path().join("missing.txt"), 3).unwrap_err();
+ assert!(matches!(error, MlError::CorruptModel(_)), "{error}");
+ }
+}
diff --git a/rust/crates/ml/src/ocr/geometry.rs b/rust/crates/ml/src/ocr/geometry.rs
new file mode 100644
index 0000000000..3cab319ee7
--- /dev/null
+++ b/rust/crates/ml/src/ocr/geometry.rs
@@ -0,0 +1,373 @@
+use std::ops::{Add, Mul, Sub};
+
+const INSIDE_EPSILON: f32 = 1e-3;
+const PARALLEL_EPSILON: f32 = 1e-6;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Point {
+ pub x: f32,
+ pub y: f32,
+}
+
+impl Point {
+ pub(crate) fn new(x: f32, y: f32) -> Self {
+ Self { x, y }
+ }
+
+ pub(crate) fn distance(self, other: Point) -> f32 {
+ (self.x - other.x).hypot(self.y - other.y)
+ }
+}
+
+impl Add for Point {
+ type Output = Point;
+
+ fn add(self, other: Point) -> Point {
+ Point::new(self.x + other.x, self.y + other.y)
+ }
+}
+
+impl Sub for Point {
+ type Output = Point;
+
+ fn sub(self, other: Point) -> Point {
+ Point::new(self.x - other.x, self.y - other.y)
+ }
+}
+
+impl Mul<f32> for Point {
+ type Output = Point;
+
+ fn mul(self, factor: f32) -> Point {
+ Point::new(self.x * factor, self.y * factor)
+ }
+}
+
+fn cross(a: Point, b: Point) -> f32 {
+ a.x * b.y - a.y * b.x
+}
+
+fn edges(quad: &[Point; 4]) -> [(Point, Point); 4] {
+ [
+ (quad[0], quad[1]),
+ (quad[1], quad[2]),
+ (quad[2], quad[3]),
+ (quad[3], quad[0]),
+ ]
+}
+
+pub(crate) fn order_corners(mut corners: [Point; 4]) -> [Point; 4] {
+ corners.sort_by(|a, b| a.x.total_cmp(&b.x));
+ let [tl, bl] = top_then_bottom(corners[0], corners[1]);
+ let [tr, br] = top_then_bottom(corners[2], corners[3]);
+ [tl, tr, br, bl]
+}
+
+fn top_then_bottom(a: Point, b: Point) -> [Point; 2] {
+ if a.y <= b.y { [a, b] } else { [b, a] }
+}
+
+pub(crate) fn edge_lengths(quad: &[Point; 4]) -> [f32; 4] {
+ edges(quad).map(|(a, b)| a.distance(b))
+}
+
+pub(crate) fn min_edge(quad: &[Point; 4]) -> f32 {
+ edge_lengths(quad).into_iter().fold(f32::INFINITY, f32::min)
+}
+
+pub(crate) fn perimeter(quad: &[Point; 4]) -> f32 {
+ edge_lengths(quad).iter().sum()
+}
+
+fn signed_area(quad: &[Point; 4]) -> f32 {
+ edges(quad).iter().map(|&(a, b)| cross(a, b)).sum::<f32>() / 2.0
+}
+
+pub(crate) fn area(quad: &[Point; 4]) -> f32 {
+ signed_area(quad).abs()
+}
+
+pub(crate) fn min_area_rect(points: &[(i32, i32)]) -> Option<[Point; 4]> {
+ if points.len() < 3 {
+ return None;
+ }
+ let pts: Vec<imageproc::point::Point<i32>> = points
+ .iter()
+ .map(|&(x, y)| imageproc::point::Point::new(x, y))
+ .collect();
+ let rect = imageproc::geometry::min_area_rect(&pts);
+ Some(rect.map(|p| Point::new(p.x as f32, p.y as f32)))
+}
+
+struct Line {
+ origin: Point,
+ direction: Point,
+}
+
+fn intersect(a: &Line, b: &Line) -> Option<Point> {
+ let denominator = cross(a.direction, b.direction);
+ if denominator.abs() <= PARALLEL_EPSILON {
+ return None;
+ }
+ let t = cross(b.origin - a.origin, b.direction) / denominator;
+ Some(a.origin + a.direction * t)
+}
+
+pub(crate) fn unclip(quad: &[Point; 4], ratio: f32) -> [Point; 4] {
+ if min_edge(quad) <= 0.0 {
+ return *quad;
+ }
+ let distance = area(quad) * ratio / perimeter(quad);
+ let outward = if signed_area(quad) >= 0.0 { 1.0 } else { -1.0 };
+ let lines = edges(quad).map(|(a, b)| {
+ let direction = b - a;
+ let normal = Point::new(direction.y, -direction.x) * (outward / a.distance(b));
+ Line {
+ origin: a + normal * distance,
+ direction,
+ }
+ });
+ let corners = std::array::from_fn(|i| {
+ let incoming = &lines[(i + 3) % 4];
+ let outgoing = &lines[i];
+ intersect(incoming, outgoing).unwrap_or(outgoing.origin)
+ });
+ order_corners(corners)
+}
+
+pub(crate) fn clip_to_bounds(quad: &[Point; 4], width: f32, height: f32) -> [Point; 4] {
+ quad.map(|p| Point::new(p.x.clamp(0.0, width), p.y.clamp(0.0, height)))
+}
+
+pub(crate) fn scale_points(quad: &[Point; 4], scale_x: f32, scale_y: f32) -> [Point; 4] {
+ quad.map(|p| Point::new(p.x * scale_x, p.y * scale_y))
+}
+
+fn contains(quad: &[Point; 4], point: Point) -> bool {
+ let mut all_left = true;
+ let mut all_right = true;
+ for (a, b) in edges(quad) {
+ let side = cross(b - a, point - a);
+ all_left &= side >= -INSIDE_EPSILON;
+ all_right &= side <= INSIDE_EPSILON;
+ }
+ all_left || all_right
+}
+
+fn pixel_bounds(coords: impl Iterator<Item = f32>, len: usize) -> (usize, usize) {
+ let (min, max) = coords.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), v| {
+ (lo.min(v), hi.max(v))
+ });
+ let last = (len - 1) as f32;
+ (
+ min.floor().clamp(0.0, last) as usize,
+ max.ceil().clamp(0.0, last) as usize,
+ )
+}
+
+pub(crate) fn mean_inside_quad(
+ values: &[f32],
+ width: usize,
+ height: usize,
+ quad: &[Point; 4],
+) -> f32 {
+ if width == 0 || height == 0 {
+ return 0.0;
+ }
+ let (min_x, max_x) = pixel_bounds(quad.iter().map(|p| p.x), width);
+ let (min_y, max_y) = pixel_bounds(quad.iter().map(|p| p.y), height);
+ let mut sum = 0.0f64;
+ let mut count = 0usize;
+ for y in min_y..=max_y {
+ for x in min_x..=max_x {
+ if contains(quad, Point::new(x as f32, y as f32)) {
+ sum += f64::from(values[y * width + x]);
+ count += 1;
+ }
+ }
+ }
+ if count == 0 {
+ 0.0
+ } else {
+ (sum / count as f64) as f32
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const TOLERANCE: f32 = 1e-3;
+
+ fn rotated_quad() -> [Point; 4] {
+ let (sin, cos) = 20.0f32.to_radians().sin_cos();
+ let center = Point::new(150.0, 100.0);
+ let corner = |along: f32, across: f32| {
+ center + Point::new(along * cos - across * sin, along * sin + across * cos)
+ };
+ [
+ corner(-70.0, -20.0),
+ corner(70.0, -20.0),
+ corner(70.0, 20.0),
+ corner(-70.0, 20.0),
+ ]
+ }
+
+ fn assert_close(actual: Point, expected: Point, tolerance: f32) {
+ assert!(
+ (actual.x - expected.x).abs() <= tolerance
+ && (actual.y - expected.y).abs() <= tolerance,
+ "expected {expected:?}, got {actual:?}"
+ );
+ }
+
+ fn assert_quads_close(actual: &[Point; 4], expected: &[Point; 4], tolerance: f32) {
+ for (a, e) in actual.iter().zip(expected) {
+ assert_close(*a, *e, tolerance);
+ }
+ }
+
+ fn distance_to_line(point: Point, a: Point, b: Point) -> f32 {
+ cross(b - a, point - a).abs() / a.distance(b)
+ }
+
+ #[test]
+ fn order_corners_recovers_shuffled_rotated_quad() {
+ let [tl, tr, br, bl] = rotated_quad();
+ assert_eq!(order_corners([br, tl, bl, tr]), [tl, tr, br, bl]);
+ assert_eq!(order_corners([bl, br, tr, tl]), [tl, tr, br, bl]);
+ }
+
+ #[test]
+ fn order_corners_handles_axis_aligned_ties() {
+ let quad = [
+ Point::new(139.0, 69.0),
+ Point::new(40.0, 69.0),
+ Point::new(139.0, 30.0),
+ Point::new(40.0, 30.0),
+ ];
+ assert_eq!(
+ order_corners(quad),
+ [
+ Point::new(40.0, 30.0),
+ Point::new(139.0, 30.0),
+ Point::new(139.0, 69.0),
+ Point::new(40.0, 69.0),
+ ]
+ );
+ }
+
+ #[test]
+ fn unclip_moves_rectangle_edges_outward_by_d() {
+ let rect = [
+ Point::new(10.0, 10.0),
+ Point::new(50.0, 10.0),
+ Point::new(50.0, 30.0),
+ Point::new(10.0, 30.0),
+ ];
+ let expected = [
+ Point::new(0.0, 0.0),
+ Point::new(60.0, 0.0),
+ Point::new(60.0, 40.0),
+ Point::new(0.0, 40.0),
+ ];
+ assert_eq!(area(&rect), 800.0);
+ assert_eq!(perimeter(&rect), 120.0);
+ assert_quads_close(&unclip(&rect, 1.5), &expected, TOLERANCE);
+ }
+
+ #[test]
+ fn unclip_moves_rotated_edges_outward_by_d() {
+ let quad = rotated_quad();
+ let d = area(&quad) * 1.5 / perimeter(&quad);
+ let expanded = unclip(&quad, 1.5);
+ for ((old_a, _), (new_a, new_b)) in edges(&quad).into_iter().zip(edges(&expanded)) {
+ let moved = distance_to_line(old_a, new_a, new_b);
+ assert!(
+ (moved - d).abs() <= 1e-2,
+ "edge moved {moved}, expected {d}"
+ );
+ }
+ let lengths = edge_lengths(&expanded);
+ let original = edge_lengths(&quad);
+ for (new_len, old_len) in lengths.iter().zip(original) {
+ assert!((new_len - old_len - 2.0 * d).abs() <= 1e-2);
+ }
+ }
+
+ #[test]
+ fn min_area_rect_of_axis_aligned_points() {
+ let points = [
+ (40, 30),
+ (100, 30),
+ (139, 30),
+ (139, 69),
+ (60, 69),
+ (40, 69),
+ (90, 50),
+ ];
+ let rect = order_corners(min_area_rect(&points).expect("rect"));
+ assert_eq!(
+ rect,
+ [
+ Point::new(40.0, 30.0),
+ Point::new(139.0, 30.0),
+ Point::new(139.0, 69.0),
+ Point::new(40.0, 69.0),
+ ]
+ );
+ assert!(min_area_rect(&[(0, 0), (1, 1)]).is_none());
+ }
+
+ #[test]
+ fn clip_to_bounds_clamps_corners() {
+ let quad = [
+ Point::new(-5.0, -3.0),
+ Point::new(120.0, -3.0),
+ Point::new(120.0, 45.0),
+ Point::new(-5.0, 45.0),
+ ];
+ assert_eq!(
+ clip_to_bounds(&quad, 100.0, 40.0),
+ [
+ Point::new(0.0, 0.0),
+ Point::new(100.0, 0.0),
+ Point::new(100.0, 40.0),
+ Point::new(0.0, 40.0),
+ ]
+ );
+ }
+
+ #[test]
+ fn mean_inside_quad_averages_rasterised_pixels() {
+ let width = 10;
+ let height = 10;
+ let mut values = vec![0.0f32; width * height];
+ for y in 2..6 {
+ for x in 2..6 {
+ values[y * width + x] = 1.0;
+ }
+ }
+ let exact = [
+ Point::new(2.0, 2.0),
+ Point::new(5.0, 2.0),
+ Point::new(5.0, 5.0),
+ Point::new(2.0, 5.0),
+ ];
+ assert!((mean_inside_quad(&values, width, height, &exact) - 1.0).abs() <= TOLERANCE);
+ let whole = [
+ Point::new(0.0, 0.0),
+ Point::new(9.0, 0.0),
+ Point::new(9.0, 9.0),
+ Point::new(0.0, 9.0),
+ ];
+ assert!((mean_inside_quad(&values, width, height, &whole) - 0.16).abs() <= TOLERANCE);
+ let outside = [
+ Point::new(-20.0, -20.0),
+ Point::new(-10.0, -20.0),
+ Point::new(-10.0, -10.0),
+ Point::new(-20.0, -10.0),
+ ];
+ assert_eq!(mean_inside_quad(&values, width, height, &outside), 0.0);
+ }
+}
diff --git a/rust/crates/ml/src/ocr/mod.rs b/rust/crates/ml/src/ocr/mod.rs
new file mode 100644
index 0000000000..bcd6519e65
--- /dev/null
+++ b/rust/crates/ml/src/ocr/mod.rs
@@ -0,0 +1,77 @@
+mod detect;
+mod dictionary;
+mod geometry;
+
+pub use detect::{DetectionCandidate, candidates_from_probability_map, sort_reading_order};
+pub use dictionary::load_dictionary;
+pub use geometry::Point;
+
+use thiserror::Error;
+
+use crate::error::MlError;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct OcrModelPaths {
+ pub detection: String,
+ pub classification: String,
+ pub recognition: String,
+ pub dictionary: String,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct DetectTextRequest {
+ pub image_path: String,
+ pub include_all_confidence_scores: bool,
+ pub request_id: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct DetectRegionsRequest {
+ pub image_path: String,
+ pub request_id: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct TextBlock {
+ pub text: String,
+ pub confidence: f32,
+ pub points: [Point; 4],
+ pub characters: Vec<CharacterBox>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct CharacterBox {
+ pub text: String,
+ pub confidence: f32,
+ pub points: [Point; 4],
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct TextDetectionResult {
+ pub blocks: Vec<TextBlock>,
+ pub image_width: u32,
+ pub image_height: u32,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct TextRegion {
+ pub confidence: f32,
+ pub points: [Point; 4],
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct TextRegionDetectionResult {
+ pub regions: Vec<TextRegion>,
+ pub image_width: u32,
+ pub image_height: u32,
+}
+
+#[derive(Debug, Error)]
+pub enum OcrError {
+ #[error("image not found: {0}")]
+ ImageNotFound(String),
+ #[error("cancelled")]
+ Cancelled,
+ #[error(transparent)]
+ Ml(#[from] MlError),
+}