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 {
OcrErrorKind::from_message(err).is_some_and(OcrErrorKind::is_backend_unavailable)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum OcrErrorKind {
MacosVisionUnavailable,
WindowsOcrUnavailable,
UnsupportedPlatform,
BackendUnavailable,
NoFallbackConfigured,
BlankPage,
RequestTooLarge,
WorkerTimeout,
WorkerOutputExceeded,
WorkerProtocol,
WorkerFailed,
Provenance,
Artifact,
Runtime,
}
impl OcrErrorKind {
pub fn from_message(message: &str) -> Option<Self> {
if message.starts_with(MACOS_VISION_UNAVAILABLE) {
Some(Self::MacosVisionUnavailable)
} else if message.starts_with(WINDOWS_OCR_UNAVAILABLE) {
Some(Self::WindowsOcrUnavailable)
} else if message.starts_with(OCR_UNSUPPORTED_PLATFORM) {
Some(Self::UnsupportedPlatform)
} else {
None
}
}
pub fn is_backend_unavailable(self) -> bool {
matches!(
self,
Self::MacosVisionUnavailable | Self::WindowsOcrUnavailable | Self::UnsupportedPlatform
)
}
pub fn as_str(self) -> &'static str {
match self {
Self::MacosVisionUnavailable => "macos_vision_unavailable",
Self::WindowsOcrUnavailable => "windows_ocr_unavailable",
Self::UnsupportedPlatform => "unsupported_platform",
Self::BackendUnavailable => "backend_unavailable",
Self::NoFallbackConfigured => "no_fallback_configured",
Self::BlankPage => "blank_page",
Self::RequestTooLarge => "request_too_large",
Self::WorkerTimeout => "worker_timeout",
Self::WorkerOutputExceeded => "worker_output_exceeded",
Self::WorkerProtocol => "worker_protocol",
Self::WorkerFailed => "worker_failed",
Self::Provenance => "provenance",
Self::Artifact => "artifact",
Self::Runtime => "runtime",
}
}
}
#[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())
}