1use image::RgbImage;
7use serde::{Deserialize, Serialize};
8
9pub const WINDOWS_OCR_UNAVAILABLE: &str = "windows-ocr-unavailable:";
11pub const MACOS_VISION_UNAVAILABLE: &str = "macos-vision-unavailable:";
13pub const OCR_UNSUPPORTED_PLATFORM: &str = "ocr-unsupported-platform:";
15
16pub 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#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38pub struct OcrLine {
39 pub text: String,
40 pub rect: OcrRect,
41 pub confidence: Option<f32>,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub enum OcrBackend {
50 Vision,
52 WindowsMedia,
54 Onnx,
56}
57
58impl OcrBackend {
59 pub fn is_native(self) -> bool {
60 !matches!(self, Self::Onnx)
61 }
62}
63
64pub const MAX_PIXELS: u64 = 40_000_000;
67
68pub 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}