Files
ddddocr-rs/src/models/loader.rs
CNWei 2d9cb35590 feat(ocr,det,slide): 重构项目结构
- 优化 规范化模型目录
- 重构 Ocr,Detector,Slide 拆分规范化
2026-07-09 19:26:58 +08:00

49 lines
1.3 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use anyhow::Context;
use std::io::Cursor;
use tract_onnx::onnx;
use tract_onnx::prelude::*;
/// OCR 模型:包含路径和字符集
pub enum ModelType {
Ocr,
Det,
Custom,
}
// 定义统一的 trait
pub trait ModelSession {
fn get_model_type(&self) -> ModelType;
fn desc(&self) -> String;
}
pub struct ModelLoader {
pub session: RunnableModel<TypedFact, Box<dyn TypedOp>, Graph<TypedFact, Box<dyn TypedOp>>>,
}
impl ModelLoader {
pub fn model_for_path<P>(model_path: P) -> anyhow::Result<Self>
where
P: AsRef<std::path::Path>,
{
let session = onnx()
.model_for_path(model_path)
.with_context(|| "加载 ONNX 模型失败,请检查路径是否正确")?
.into_optimized()?
.into_runnable()?;
Ok(Self { session })
}
/// 策略 B从内存字节流加载模型配合 include_bytes! 使用)
pub fn model_from_bytes(model_bytes: &[u8]) -> anyhow::Result<Self> {
// 使用 std::io::Cursor 将 &[u8] 包装为可读的流(实现 std::io::Read
let mut cursor = Cursor::new(model_bytes);
let session = onnx()
.model_for_read(&mut cursor)
.with_context(|| "从内存字节流解析 ONNX 模型失败")?
.into_optimized()?
.into_runnable()?;
Ok(Self { session })
}
}