Skip to main content

rightkit_ocr/
types.rs

1//! Shared result types, error prefixes and the decode guard.
2//!
3//! One result shape for every backend: text + normalized top-left geometry +
4//! optional confidence (ViewRight's `OcrLine`, the most mature donor).
5
6use image::RgbImage;
7use serde::{Deserialize, Serialize};
8
9/// Prefix for a Windows backend that cannot recognize at all (no language pack).
10pub const WINDOWS_OCR_UNAVAILABLE: &str = "windows-ocr-unavailable:";
11/// Prefix for an Apple Vision request that could not be performed.
12pub const MACOS_VISION_UNAVAILABLE: &str = "macos-vision-unavailable:";
13/// Prefix for a platform with no native OCR backend at all (Linux builds).
14pub const OCR_UNSUPPORTED_PLATFORM: &str = "ocr-unsupported-platform:";
15
16/// Does this error mean the native backend is unusable on this machine (a
17/// capability verdict, and the only thing that arms the ONNX fallback), as
18/// opposed to a per-image failure that must stay visible?
19pub fn is_backend_unavailable(err: &str) -> bool {
20    err.starts_with(WINDOWS_OCR_UNAVAILABLE)
21        || err.starts_with(MACOS_VISION_UNAVAILABLE)
22        || err.starts_with(OCR_UNSUPPORTED_PLATFORM)
23}
24
25/// A normalized rectangle: 0..1 of the source image, **origin top-left**.
26#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase")]
28pub struct OcrRect {
29    pub x: f32,
30    pub y: f32,
31    pub width: f32,
32    pub height: f32,
33}
34
35/// One recognized line with its position on the image.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38pub struct OcrLine {
39    pub text: String,
40    pub rect: OcrRect,
41    /// 0..1 where the backend reports it (Vision, ONNX). Windows.Media.Ocr
42    /// exposes none, so it is `None` there; `None` is not low confidence.
43    pub confidence: Option<f32>,
44}
45
46/// Which backend produced a result.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub enum OcrBackend {
50    /// Apple Vision (macOS).
51    Vision,
52    /// Windows.Media.Ocr.
53    WindowsMedia,
54    /// The two-stage PP-OCR ONNX pipeline.
55    Onnx,
56}
57
58impl OcrBackend {
59    pub fn is_native(self) -> bool {
60        !matches!(self, Self::Onnx)
61    }
62}
63
64/// Largest image decoded, in pixels (enforced on the header, before any pixel
65/// buffer is allocated — a decompression-bomb guard).
66pub const MAX_PIXELS: u64 = 40_000_000;
67
68/// Decode PNG/JPEG bytes to RGB with the [`MAX_PIXELS`] guard.
69pub fn decode_encoded(bytes: &[u8]) -> Result<RgbImage, String> {
70    let reader = image::ImageReader::new(std::io::Cursor::new(bytes))
71        .with_guessed_format()
72        .map_err(|e| format!("Cannot read image header: {e}"))?;
73    let (w, h) = reader
74        .into_dimensions()
75        .map_err(|e| format!("Cannot read image dimensions: {e}"))?;
76    let pixels = u64::from(w) * u64::from(h);
77    if pixels > MAX_PIXELS {
78        return Err(format!(
79            "Image is {w}x{h} ({pixels} pixels), over the {MAX_PIXELS}-pixel limit"
80        ));
81    }
82    let image = image::load_from_memory(bytes).map_err(|e| format!("Cannot decode image: {e}"))?;
83    Ok(image.into_rgb8())
84}