use image::RgbImage;
use serde::{Deserialize, Serialize};
pub const WINDOWS_OCR_UNAVAILABLE: &str = "windows-ocr-unavailable:";
pub const MACOS_VISION_UNAVAILABLE: &str = "macos-vision-unavailable:";
pub const OCR_UNSUPPORTED_PLATFORM: &str = "ocr-unsupported-platform:";
pub fn is_backend_unavailable(err: &str) -> bool {
err.starts_with(WINDOWS_OCR_UNAVAILABLE)
|| err.starts_with(MACOS_VISION_UNAVAILABLE)
|| err.starts_with(OCR_UNSUPPORTED_PLATFORM)
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OcrRect {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OcrLine {
pub text: String,
pub rect: OcrRect,
pub confidence: Option<f32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OcrBackend {
Vision,
WindowsMedia,
Onnx,
}
impl OcrBackend {
pub fn is_native(self) -> bool {
!matches!(self, Self::Onnx)
}
}
pub const MAX_PIXELS: u64 = 40_000_000;
pub fn decode_encoded(bytes: &[u8]) -> Result<RgbImage, String> {
let reader = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.map_err(|e| format!("Cannot read image header: {e}"))?;
let (w, h) = reader
.into_dimensions()
.map_err(|e| format!("Cannot read image dimensions: {e}"))?;
let pixels = u64::from(w) * u64::from(h);
if pixels > MAX_PIXELS {
return Err(format!(
"Image is {w}x{h} ({pixels} pixels), over the {MAX_PIXELS}-pixel limit"
));
}
let image = image::load_from_memory(bytes).map_err(|e| format!("Cannot decode image: {e}"))?;
Ok(image.into_rgb8())
}