feat: ddddocr-rs 完成 core/ort/tract2 规范整改与发布

准备

  - core:内置官方字符集(OLD/BETA)与 ModelMetadata::from_builtin_*
  构造器
  - ort:导出 Session、实现 Info、修正 cuda feature 接线、共享推理工具
  - tract2:包名更名(原 ddddocr-tract 已被占用)并完成规范整改
  - 集成测试按领域拆分(ocr / det / slide / common / api_surface)
  - 发布准备:Cargo.toml 元数据、workspace 版本 0.2.4、LICENSE/
  NOTICE、README 模型下载说明
This commit is contained in:
2026-08-10 19:56:29 +08:00
parent fe61895926
commit 00e8ab5308
58 changed files with 2542 additions and 2237 deletions

View File

@@ -1,23 +1,25 @@
[package]
name = "ddddocr-ort"
version.workspace = true
edition.workspace = true
license.workspace = true
version = { workspace = true }
edition = { workspace = true }
license = { workspace = true }
description = "ddddocr-rs 的 ONNX Runtime 推理引擎实现"
keywords = ["ocr", "captcha", "ddddocr", "onnxruntime", "ort"]
categories = ["multimedia::images", "computer-vision"]
# repository = "https://github.com/<用户名>/<仓库名>" # 发布前请补充
readme = "../README.md"
[dependencies]
ddddocr-core = { path = "../ddddocr-core" } # 引入兄弟库
ort = { workspace = true ,features = ["cuda"]}
ndarray = { workspace = true } # 继承自工作空间
ddddocr-core = { path = "../ddddocr-core", version = "0.2.4" }
ort = { workspace = true }
ndarray = { workspace = true }
image = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
anyhow = { workspace = true }
thiserror = { workspace = true } # 刚好可以开始接入你需要的标准库错误处理
thiserror = { workspace = true }
tracing = { workspace = true }
[features]
# 1. 声明 cuda feature
# 2. 当开启 ddddocr-ort 的 cuda feature 时,自动开启底层 ort 库的 cuda 支持(如果 ort 库支持的话)
cuda = ["ort/cuda"]
# 开启后启用底层 ort 库的 CUDA 执行提供者支持。
cuda = ["ort/cuda"]

View File

@@ -1 +1 @@
pub mod session;
pub mod session;

View File

@@ -1,63 +1,40 @@
use crate::runtime::{extract_tensor, lock_session, run_session};
use crate::types::Session;
use ddddocr_core::DetOutput;
use ddddocr_core::error::{Result, TensorError};
use ddddocr_core::traits::{DetEngine, InferenceEngine};
use ndarray::Ix3;
use ort::inputs;
use ort::value::TensorRef;
use tracing::debug;
/// 目标检测推理运行时:持有 ORT 会话,输出 [`DetOutput`]。
#[derive(Debug)]
pub struct DetRuntime {
/// ORT 会话句柄。
pub session: Session,
}
impl DetRuntime {
/// 基于已构建的会话创建检测运行时。
pub fn new(session: Session) -> Self {
Self { session }
}
}
impl InferenceEngine for DetRuntime {
type Output = DetOutput; // 明确绑定 OCR 小枚举
type Output = DetOutput;
fn inference(&self, input_array: ndarray::Array4<f32>) -> Result<Self::Output, TensorError> {
// tract 的 run 会返回一个 Vec<TValue>,我们通常只需要第一个输出
// let result = self.ocr.run(tvec!(tensor.into()))?;
let mut session_guard = self
.session
.lock()
.map_err(|_| TensorError::Engine("获取 Session 锁失败 (Poisoned)".to_string()))?;
let result = session_guard
.run(inputs![TensorRef::from_array_view(&input_array).map_err(
|e| TensorError::Engine(format!("构建输入失败: {e}"))
)?])
.map_err(|e| TensorError::Engine(format!("执行模型推理失败: {e}")))?;
// .context("执行模型推理失败")?;
println!("模型输出原始数据: {:?}", result);
// Ok(result.swap_remove(0).into_tensor())
let raw_value = &result[0];
// raw_tensor.into_plain_array()?
let (shape_ref, slice) = raw_value.try_extract_tensor::<f32>().map_err(|_| {
TensorError::Engine("Tract 实体张量无法转换为 ndarray::ArrayD".to_string())
})?;
// 提前利用克隆(Clone)备份好当前未转维度前的真实 shape (Vec<usize>)
let shape_vec: Vec<usize> = shape_ref.to_vec().iter().map(|v| *v as usize).collect();
let shape_vec_slice = shape_vec.as_slice();
let view = ndarray::ArrayViewD::from_shape(shape_vec_slice, slice)
.map_err(|_| TensorError::Engine("构建 ndarray ArrayViewD 失败".to_string()))?;
let mut session_guard = lock_session(&self.session)?;
let result = run_session(&mut session_guard, &input_array)?;
debug!("模型输出原始数据: {:?}", result);
let (view, shape_vec) = extract_tensor::<f32>(&result[0])?;
let array3 = view.to_owned().into_dimensionality::<Ix3>().map_err(|_| {
TensorError::DimensionMismatch {
expected: "3D 检测矩阵 [Batch, Box_Count, Box_Attributes]".to_string(),
actual: shape_vec, // 优雅降维失败时动态捕获
actual: shape_vec,
}
})?;
Ok(DetOutput::Detection(array3))
// 在引擎内部消化掉 DatumType 强耦合
}
}

View File

@@ -1,9 +1,20 @@
//! # ddddocr-ort
//!
//! 基于 ONNX RuntimeORT的推理引擎实现通过 [`loader::ModelLoader`] 构建会话,
//! 再由 [`OcrRuntime`] / [`DetRuntime`] 实现 core 的
//! [`ddddocr_core::traits::InferenceEngine`] 接口。
//! 同时重导出 core 的 [`OcrBuilder`]、[`Slider`]、[`SlideResult`] 等便捷 API。
#![warn(missing_docs)]
mod det;
/// 模型加载器:从路径或字节流构建 ORT 会话。
pub mod loader;
mod ocr;
mod runtime;
mod types;
pub use ddddocr_core::{SlideResult, Slider,OcrBuilder};
pub use ddddocr_core::{OcrBuilder, SlideResult, Slider};
pub use det::session::DetRuntime;
pub use ocr::session::OcrRuntime;
pub use ocr::session::OcrRuntime;
pub use types::Session;

View File

@@ -3,5 +3,5 @@ mod metadata;
mod model;
pub use error::{Error, ParseError, Result};
pub use metadata::{ModelMetadataDto, NormalizationDto, Metadata};
pub use model::ModelLoader;
pub use metadata::{Metadata, ModelMetadataDto, NormalizationDto};
pub use model::ModelLoader;

View File

@@ -1,7 +1,10 @@
use ort::Error as OrtError;
/// 模型加载与解析的通用结果类型。
pub type Result<T> = std::result::Result<T, Error>;
#[derive(thiserror::Error, Debug)]
/// 模型加载、解析与 Session 构建阶段的错误。
pub enum Error {
/// 底层构建器配置失败。
#[error("builder构建失败")]
Build(#[from] BuildError),
/// 解析 ONNX 模型/路径失败(如文件损坏、算子不支持、路径非法)
@@ -9,11 +12,11 @@ pub enum Error {
ModelParse(#[from] ParseError),
/// 模型计算图优化失败(如常量折叠、形状推导失败)
#[error("优化 Tract 模型图失败: {0}")]
#[error("优化 ORT 模型图失败: {0}")]
OptimizationFailed(#[source] OrtError),
/// 构建可执行 Session 失败(如输入输出 Tensor 类型/形状未确定)
#[error("构建可运行 Tract 实例失败: {0}")]
#[error("构建可运行的 ORT Session 失败: {0}")]
RunnableBuildFailed(#[source] OrtError),
/// JSON 反序列化失败(自动透传 serde_json 报错)
@@ -24,6 +27,7 @@ pub enum Error {
#[error("Metadata 字节流不是合法的 UTF-8 编码: {0}")]
InvalidUtf8(#[from] std::str::Utf8Error),
/// 模型元数据内容解析失败。
#[error("模型元数据解析失败: {0}")]
MetadataParse(String),
@@ -32,8 +36,6 @@ pub enum Error {
Other(String, #[source] Box<dyn std::error::Error + Send + Sync>),
}
impl Error {
/// 方便将任何第三方 Error 包装为 Error::Other
pub fn new<E>(msg: impl Into<String>, err: E) -> Self
@@ -44,6 +46,7 @@ impl Error {
}
}
#[derive(thiserror::Error, Debug)]
/// 从路径或字节流解析 ONNX 模型失败的错误。
pub enum ParseError {
/// 策略 A从文件路径加载失败附带路径上下文信息方便排查是找不到文件还是格式不对
#[error("从路径 '{0}' 加载 ONNX 模型失败: {1}")]
@@ -54,13 +57,45 @@ pub enum ParseError {
Bytes(#[source] OrtError),
}
#[derive(thiserror::Error, Debug)]
pub enum BuildError{
#[error("builder构建失败")]
pub enum BuildError {
/// 底层 SessionBuilder 构建失败
#[error("构建 ORT SessionBuilder 失败: {0}")]
BuildFailed(#[from] OrtError),
#[error("builder构建失败")]
/// 线程数配置失败。
#[error("{0}")]
Threads(String),
#[error("builder构建失败")]
/// 启用 CUDA 执行提供者失败。
#[error("{0}")]
EnabledCudaFailed(String),
#[error("builder构建失败")]
NotEnabledCuda(String)
}
/// 未编译 CUDA 支持时尝试启用 GPU。
#[error("{0}")]
NotEnabledCuda(String),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wraps_external_error_via_new() {
let io_err = std::io::Error::other("boom");
let err = Error::new("自定义错误", io_err);
assert!(matches!(err, Error::Other(_, _)));
assert!(err.to_string().contains("自定义错误"));
}
#[test]
fn serde_json_error_converts_to_error() {
let json_err = serde_json::from_str::<serde_json::Value>("{").unwrap_err();
let err: Error = json_err.into();
assert!(matches!(err, Error::JsonParse(_)));
}
#[test]
fn ut8_error_converts_to_error() {
let bytes = vec![0xffu8];
let utf8_err = std::str::from_utf8(&bytes).unwrap_err();
let err: Error = utf8_err.into();
assert!(matches!(err, Error::InvalidUtf8(_)));
}
}

View File

@@ -1,13 +1,12 @@
use crate::loader::error::{Error, Result};
use ddddocr_core::ModelMetadata;
use ddddocr_core::Resize;
use ddddocr_core::{Charset, Normalization};
use ddddocr_core::{Charset, ModelMetadata, Normalization, Resize};
use serde::Deserialize;
use std::borrow::Cow;
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")] // 支持 json 中写 "zero_to_one" 或 "minus_one_to_one"
/// 归一化策略的 JSON 反序列化中间表示。
pub enum NormalizationDto {
/// 映射到 [0.0, 1.0] -> pixel / 255.0
ZeroToOne,
@@ -41,8 +40,9 @@ fn default_normalization() -> NormalizationDto {
NormalizationDto::ZeroToOne
}
/// Tract 专属扩展trait 或 工具函数
/// 从 JSON 字符串或字节流解析模型元数据的扩展接口。
pub trait Metadata: Sized {
/// 从 JSON 字符串解析模型元数据。
fn from_json_str(json_str: &str) -> Result<Self>;
/// 机制 2从内存字节流加载极大地方便 include_bytes! 或网络下载)
fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
@@ -56,8 +56,7 @@ impl Metadata for ModelMetadata {
let dto: ModelMetadataDto = serde_json::from_str(json_str)?;
// 1. 将 DTO 的字符串数组转化为强类型的 Charset
let tokens: Vec<Cow<'static, str>> =
dto.charset.into_iter().map(|s| Cow::Owned(s)).collect();
let tokens: Vec<Cow<'static, str>> = dto.charset.into_iter().map(Cow::Owned).collect();
let charset = Charset::new(tokens);
// 2. 解析 resize 策略(重现 Python 的复杂条件判断)
@@ -91,3 +90,104 @@ impl Metadata for ModelMetadata {
))
}
}
#[cfg(test)]
mod tests {
use super::*;
const MINIMAL_JSON: &str = r#"{
"charset": ["a", "b", "c"],
"word": false,
"resize": [-1, 64],
"channel": 1
}"#;
#[test]
fn parses_minimal_json_with_default_normalization() {
let meta = ModelMetadata::from_json_str(MINIMAL_JSON).unwrap();
assert_eq!(meta.charset.size(), 3);
assert!(!meta.word);
assert_eq!(meta.channel, 1);
assert!(matches!(meta.resize, Resize::DynamicWidth(64)));
assert!(matches!(meta.normalization, Normalization::ZeroToOne));
}
#[test]
fn parses_minus_one_to_one_normalization() {
let json = r#"{
"charset": ["a"],
"word": false,
"resize": [-1, 64],
"channel": 1,
"normalization": "minus_one_to_one"
}"#;
let meta = ModelMetadata::from_json_str(json).unwrap();
assert!(matches!(meta.normalization, Normalization::MinusOneToOne));
}
#[test]
fn parses_word_model_as_square_resize() {
let json = r#"{
"charset": ["a"],
"word": true,
"resize": [-1, 64],
"channel": 1
}"#;
let meta = ModelMetadata::from_json_str(json).unwrap();
assert!(matches!(meta.resize, Resize::Square(64)));
}
#[test]
fn parses_fixed_resize() {
let json = r#"{
"charset": ["a"],
"word": false,
"resize": [100, 64],
"channel": 1
}"#;
let meta = ModelMetadata::from_json_str(json).unwrap();
assert!(matches!(meta.resize, Resize::Fixed(100, 64)));
}
#[test]
fn parses_image_alias() {
let json = r#"{
"charset": ["a"],
"word": false,
"image": [200, 64],
"channel": 1
}"#;
let meta = ModelMetadata::from_json_str(json).unwrap();
assert!(matches!(meta.resize, Resize::Fixed(200, 64)));
}
#[test]
fn rejects_resize_with_wrong_length() {
let json = r#"{
"charset": ["a"],
"word": false,
"resize": [1, 2, 3],
"channel": 1
}"#;
assert!(matches!(
ModelMetadata::from_json_str(json),
Err(Error::MetadataParse(_))
));
}
#[test]
fn rejects_invalid_json() {
assert!(matches!(
ModelMetadata::from_json_str("not json"),
Err(Error::JsonParse(_))
));
}
#[test]
fn rejects_invalid_utf8_bytes() {
assert!(matches!(
ModelMetadata::from_json_bytes(&[0xff, 0xfe]),
Err(Error::InvalidUtf8(_))
));
}
}

View File

@@ -6,30 +6,13 @@ use ort::session::Session as OrtSession;
use ort::session::builder::SessionBuilder;
use std::sync::{Arc, Mutex};
// pub struct OrtModelLoader;
//
// impl OrtModelLoader {
// /// 获取针对 ORT 后端的链式构建器
// pub fn builder() -> OrtModelBuilder {
// OrtModelBuilder::default()
// }
// }
/// ORT 专用的链式构建器
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Default)]
pub struct ModelLoader {
use_gpu: bool,
device_id: i32,
intra_threads: Option<usize>,
}
impl Default for ModelLoader {
fn default() -> Self {
Self {
use_gpu: false,
device_id: 0,
intra_threads: None,
}
}
}
impl ModelLoader {
/// 开启或关闭 GPU 加速
pub fn use_gpu(mut self, enable: bool) -> Self {
@@ -42,6 +25,7 @@ impl ModelLoader {
self.device_id = id;
self
}
/// 指定 ORT 内部线程数。
pub fn num_threads(mut self, threads: usize) -> Self {
self.intra_threads = Some(threads);
self
@@ -49,7 +33,7 @@ impl ModelLoader {
/// 内部辅助方法:根据当前的配置构建 ORT 底层的 SessionBuilder
fn create_session_builder(&self) -> Result<SessionBuilder> {
let mut builder = OrtSession::builder().map_err(|e| BuildError::BuildFailed(e))?;
let mut builder = OrtSession::builder().map_err(BuildError::BuildFailed)?;
// 如果用户显式设置了线程数,则配置给 ORT
if let Some(threads) = self.intra_threads {
builder = builder
@@ -99,7 +83,7 @@ impl Loader for ModelLoader {
.commit_from_file(path_ref)
.map_err(|e| ParseError::Path(path_ref.display().to_string(), e))?;
Ok(Arc::new(Mutex::new(session))) // 这里的session需要包装下
Ok(Arc::new(Mutex::new(session)))
}
/// 策略 B从内存字节流加载模型配合 include_bytes! 使用)
fn build_from_bytes(&self, model_bytes: &[u8]) -> Result<Session> {
@@ -112,3 +96,36 @@ impl Loader for ModelLoader {
Ok(Arc::new(Mutex::new(session)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_config() {
let loader = ModelLoader::default();
assert!(!loader.use_gpu);
assert_eq!(loader.device_id, 0);
assert!(loader.intra_threads.is_none());
}
#[test]
fn builder_configures_fields() {
let loader = ModelLoader::default()
.use_gpu(true)
.device_id(2)
.num_threads(4);
assert!(loader.use_gpu);
assert_eq!(loader.device_id, 2);
assert_eq!(loader.intra_threads, Some(4));
}
#[test]
fn builder_is_chainable_and_immutable() {
let base = ModelLoader::default();
let _configured = base.clone().use_gpu(true).device_id(1).num_threads(8);
assert!(!base.use_gpu);
assert_eq!(base.device_id, 0);
assert!(base.intra_threads.is_none());
}
}

View File

@@ -1,107 +1,87 @@
use crate::runtime::{extract_tensor, lock_session, run_session};
use crate::types::Session;
use ddddocr_core::ModelMetadata;
use ddddocr_core::OcrOutput;
use ddddocr_core::error::{DdddError, Result, TensorError};
use ddddocr_core::error::{Result, TensorError};
use ddddocr_core::traits::{InferenceEngine, Info, OcrEngine};
use ddddocr_core::types::{AxisDim, ModelInfo, TensorInfo, TensorType};
use ddddocr_core::utils::normalize_ocr_logits;
use ort::inputs;
use ort::value::{TensorElementType, TensorRef};
use std::sync::Mutex;
// 引入核心层的统一错误类型
/// 明确命名为 AxisDim代表模型某一个轴的维度特征
// #[derive(Clone, PartialEq, Eq)]
// pub enum AxisDim {
// /// 静态固定维度(如通道数固定为 1高度固定为 64
// Static(usize),
// /// 动态符号维度(如宽度是动态的 "image_width"
// Dynamic(String),
// }
use ort::value::{Outlet, TensorElementType, ValueType};
use tracing::debug;
// impl AxisDim {
// /// 便捷方法:判断是否为动态维度
// pub fn is_dynamic(&self) -> bool {
// matches!(self, AxisDim::Dynamic(_))
// }
// }
// /// 自定义 Debug 格式化输出,彻底融化套娃外壳,保证日志干净漂亮
// impl std::fmt::Debug for AxisDim {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// match self {
// AxisDim::Static(size) => write!(f, "{}", size),
// AxisDim::Dynamic(expr) => write!(f, "Dynamic(\"{}\")", expr),
// }
// }
// }
/// 模拟 Python 的 input_info 和 output_info 结构
// #[derive(Debug, Clone)]
// pub struct TensorInfo {
// pub name: String,
// pub shape: Vec<AxisDim>, // 既包含 Fixed 静态维度,也包含 Dynamic 动态符号
// pub data_type: TensorElementType, // 对应 Python 的 type
// }
//
// /// 最终返回的模型完整信息
// #[derive(Debug, Clone)]
// pub struct ModelInfo {
// pub inputs: Vec<TensorInfo>,
// pub outputs: Vec<TensorInfo>,
// /// 硬件执行提供者(采用 Option 兼容不同底层的推理引擎)
// pub providers: Option<Vec<String>>,
// }
/// OCR 推理运行时:持有 ORT 会话与模型元数据,输出 [`OcrOutput`]。
pub struct OcrRuntime {
/// ORT 会话句柄。
pub session: Session,
/// 模型元数据(字符集、归一化策略等)。
pub metadata: ModelMetadata,
}
impl OcrRuntime {
/// 基于已构建的会话与元数据创建 OCR 运行时。
pub fn new(session: Session, metadata: ModelMetadata) -> Self {
Self { session, metadata }
}
/// 将 ORT 输入/输出出口解析为 core 的 [`TensorInfo`] 列表。
fn resolve_outlets(&self, outlets: &[Outlet]) -> Result<Vec<TensorInfo>> {
Ok(outlets
.iter()
.map(|outlet| TensorInfo {
name: outlet.name().to_string(),
shape: resolve_shape(outlet.dtype()),
tensor_type: tensor_type_from_ort(outlet.dtype()),
})
.collect())
}
}
/// 将 ORT 值类型映射为 core 的 [`TensorType`]。
fn tensor_type_from_ort(dtype: &ValueType) -> TensorType {
match dtype.tensor_type() {
Some(TensorElementType::Float32) => TensorType::F32,
Some(TensorElementType::Int64) => TensorType::I64,
_ => TensorType::Other,
}
}
/// 将 ORT 张量形状解析为 [`AxisDim`] 列表,动态维度(`-1`)标记为符号维度。
fn resolve_shape(dtype: &ValueType) -> Vec<AxisDim> {
dtype
.tensor_shape()
.map(|shape| {
shape
.iter()
.map(|&dim| {
if dim >= 0 {
AxisDim::Static(dim as usize)
} else {
AxisDim::Dynamic("dynamic".to_string())
}
})
.collect()
})
.unwrap_or_default()
}
impl OcrEngine for OcrRuntime {
fn metadata(&self) -> &ModelMetadata {
&self.metadata
}
}
impl InferenceEngine for OcrRuntime {
type Output = OcrOutput;
/// 对应 Python 的 _inference
fn inference(&self, input_array: ndarray::Array4<f32>) -> Result<Self::Output, TensorError> {
// tract 的 run 会返回一个 Vec<TValue>,我们通常只需要第一个输出
// let result = self.ocr.run(tvec!(tensor.into()))?;
// let tensor = Tensor::from(input_array);
let mut session_guard = self
.session
.lock()
.map_err(|_| TensorError::Engine("获取 Session 锁失败 (Poisoned)".to_string()))?;
let result = session_guard
.run(inputs![TensorRef::from_array_view(&input_array).map_err(
|e| TensorError::Engine(format!("构建输入失败: {e}"))
)?])
.map_err(|e| TensorError::Engine(format!("执行模型推理失败: {e}")))?;
// .context("执行模型推理失败")?;
println!("模型输出原始数据: {:?}", result);
// Ok(result.swap_remove(0).into_tensor())
fn inference(&self, input_array: ndarray::Array4<f32>) -> Result<Self::Output, TensorError> {
let mut session_guard = lock_session(&self.session)?;
let result = run_session(&mut session_guard, &input_array)?;
debug!("模型输出原始数据: {:?}", result);
let raw_value = &result[0];
match raw_value.dtype().tensor_type().unwrap() {
TensorElementType::Int64 => {
let (array_d, slice) = raw_value
.try_extract_tensor::<i64>()
.map_err(|_| TensorError::Engine("Tract 无法获取 i64 内存视图".to_string()))?;
// .context("Tract 无法获取 i64 内存视图")?;
// 提前提取真实维度
let actual_shape = array_d
.to_vec()
.iter()
.map(|v| *v as usize)
.collect::<Vec<usize>>();
let view = ndarray::ArrayViewD::from_shape(actual_shape.as_slice(), slice)
.map_err(|_| TensorError::Engine("构建 ndarray ArrayViewD 失败".to_string()))?;
// 转成标准的 Array1 传给 core
match raw_value.dtype().tensor_type() {
Some(TensorElementType::Int64) => {
let (view, actual_shape) = extract_tensor::<i64>(raw_value)?;
let array1 = view
.to_owned()
.into_dimensionality::<ndarray::Ix1>()
@@ -111,40 +91,98 @@ impl InferenceEngine for OcrRuntime {
})?;
Ok(OcrOutput::Indices(array1))
}
TensorElementType::Float32 => {
Some(TensorElementType::Float32) => {
let shape = raw_value.shape();
println!("模型输出shape数据: {:?}", shape);
// raw_tensor.to_plain_array_view()
let (shape_ref, slice) = raw_value
.try_extract_tensor::<f32>()
.map_err(|_| TensorError::Engine("Tract 无法获取 f32 内存视图".to_string()))?;
// 1. 极其纯粹的、无拷贝的多维 Shape 压扁清洗
let shape_vec: Vec<usize> =
shape_ref.to_vec().iter().map(|v| *v as usize).collect();
let shape_vec_slice = shape_vec.as_slice();
let view = ndarray::ArrayViewD::from_shape(shape_vec_slice, slice)
.map_err(|_| TensorError::Engine("构建 ndarray ArrayViewD 失败".to_string()))?;
normalize_ocr_logits(view, shape_vec_slice)
debug!("模型输出 shape 数据: {:?}", shape);
let (view, shape_vec) = extract_tensor::<f32>(raw_value)?;
normalize_ocr_logits(view, shape_vec.as_slice())
}
_ => Err(
// anyhow::anyhow!("不支持的模型输出数据类型: {:?}",raw_tensor.datum_type())
TensorError::UnknownOutputFormat,
),
_ => Err(TensorError::UnknownOutputFormat),
}
}
}
impl Info for OcrRuntime {
fn input_info(&self) -> Result<Vec<TensorInfo>> {
todo!()
let session_guard = lock_session(&self.session)?;
self.resolve_outlets(session_guard.inputs())
}
fn output_info(&self) -> Result<Vec<TensorInfo>> {
todo!()
let session_guard = lock_session(&self.session)?;
self.resolve_outlets(session_guard.outputs())
}
fn model_info(&self) -> Result<ModelInfo> {
todo!()
Ok(ModelInfo {
inputs: self.input_info()?,
outputs: self.output_info()?,
providers: None,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use ort::value::{Shape, SymbolicDimensions, TensorElementType};
fn tensor_dtype(ty: TensorElementType) -> ValueType {
ValueType::Tensor {
ty,
shape: Shape::new([1, 64]),
dimension_symbols: SymbolicDimensions::new([String::new(), String::new()]),
}
}
#[test]
fn maps_tensor_element_types() {
assert!(matches!(
tensor_type_from_ort(&tensor_dtype(TensorElementType::Float32)),
TensorType::F32
));
assert!(matches!(
tensor_type_from_ort(&tensor_dtype(TensorElementType::Int64)),
TensorType::I64
));
assert!(matches!(
tensor_type_from_ort(&tensor_dtype(TensorElementType::Uint8)),
TensorType::Other
));
}
#[test]
fn resolves_static_shape() {
let shape = resolve_shape(&tensor_dtype(TensorElementType::Float32));
assert_eq!(shape, vec![AxisDim::Static(1), AxisDim::Static(64)]);
}
#[test]
fn resolves_dynamic_dimension_as_symbol() {
let dtype = ValueType::Tensor {
ty: TensorElementType::Float32,
shape: Shape::new([1, 64, -1]),
dimension_symbols: SymbolicDimensions::new([
String::new(),
String::new(),
String::from("width"),
]),
};
let shape = resolve_shape(&dtype);
assert_eq!(
shape,
vec![
AxisDim::Static(1),
AxisDim::Static(64),
AxisDim::Dynamic("dynamic".to_string())
]
);
}
#[test]
fn non_tensor_dtype_yields_empty_shape() {
let dtype = ValueType::Sequence(Box::new(tensor_dtype(TensorElementType::Float32)));
assert!(resolve_shape(&dtype).is_empty());
assert!(matches!(tensor_type_from_ort(&dtype), TensorType::Other));
}
}

View File

@@ -0,0 +1,41 @@
//! 会话执行相关的共享工具函数。
use crate::types::Session;
use ddddocr_core::error::TensorError;
use ort::inputs;
use ort::session::Session as OrtSession;
use ort::session::SessionOutputs;
use ort::value::{PrimitiveTensorElementType, TensorRef, Value};
use std::sync::MutexGuard;
/// 获取会话互斥锁,失败时转换为引擎错误。
pub(crate) fn lock_session(session: &Session) -> Result<MutexGuard<'_, OrtSession>, TensorError> {
session
.lock()
.map_err(|_| TensorError::Engine("获取 Session 锁失败 (Poisoned)".to_string()))
}
/// 对输入张量执行一次 ORT 推理,返回原始输出值列表。
pub(crate) fn run_session<'a>(
session: &'a mut OrtSession,
input_array: &ndarray::Array4<f32>,
) -> Result<SessionOutputs<'a>, TensorError> {
session
.run(inputs![TensorRef::from_array_view(input_array).map_err(
|e| { TensorError::Engine(format!("构建输入失败: {e}")) }
)?])
.map_err(|e| TensorError::Engine(format!("执行模型推理失败: {e}")))
}
/// 从输出值中提取类型化张量视图,同时返回其真实维度。
pub(crate) fn extract_tensor<T: PrimitiveTensorElementType>(
value: &Value,
) -> Result<(ndarray::ArrayViewD<'_, T>, Vec<usize>), TensorError> {
let (shape_ref, slice) = value
.try_extract_tensor::<T>()
.map_err(|_| TensorError::Engine("无法获取张量内存视图".to_string()))?;
let shape: Vec<usize> = shape_ref.iter().map(|v| *v as usize).collect();
let view = ndarray::ArrayViewD::from_shape(shape.as_slice(), slice)
.map_err(|_| TensorError::Engine("构建 ndarray ArrayViewD 失败".to_string()))?;
Ok((view, shape))
}

View File

@@ -1,4 +1,7 @@
//! ORT 会话共享类型。
use ort::session::Session as OrtSession;
use std::sync::{Arc, Mutex};
/// ORT 会话句柄:由 [`crate::loader::ModelLoader`] 构建,推理时通过互斥锁串行访问。
pub type Session = Arc<Mutex<OrtSession>>;

View File

@@ -0,0 +1,76 @@
//! 外部视角 API 测试:验证 `ddddocr-ort` 的公开类型与方法在外部 crate 中可正常使用。
use ddddocr_core::traits::{Info, Loader};
use ddddocr_core::types::AxisDim;
use ddddocr_core::{ModelMetadata, Normalization, OcrBuilder, Resize, SlideResult, Slider};
use ddddocr_ort::loader::ModelLoader;
use ddddocr_ort::{DetRuntime, OcrRuntime, Session};
use std::path::{Path, PathBuf};
fn model_path(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("models")
.join(name)
}
/// 验证对外导出的类型(含 `Session` 与 core 便捷重导出)均可直接命名。
#[test]
fn public_types_are_nameable() {
let _: Option<Session> = None;
let _: Option<OcrBuilder> = None;
let _: Option<SlideResult> = None;
let _slider = Slider::new();
}
/// 验证构建器链式 API 可组合使用,且返回的会话类型可显式标注。
#[test]
fn loader_chain_builds_session() -> anyhow::Result<()> {
let path = model_path("common_sml2h3_f32.onnx");
assert!(path.exists(), "缺少测试模型: {}", path.display());
let _session: Session = ModelLoader::default()
.use_gpu(false)
.device_id(0)
.num_threads(4)
.build_for_path(path)?;
Ok(())
}
/// 验证 `Info` trait 能从真实会话中解析输入/输出信息。
#[test]
fn info_trait_returns_model_metadata() -> anyhow::Result<()> {
let path = model_path("common_sml2h3_f32.onnx");
assert!(path.exists(), "缺少测试模型: {}", path.display());
let session: Session = ModelLoader::default().build_for_path(path)?;
let metadata = ModelMetadata::from_static_slice(
&["a", "b"],
false,
Resize::DynamicWidth(64),
1,
Normalization::MinusOneToOne,
);
let ocr = OcrRuntime::new(session, metadata);
let inputs = ocr.input_info()?;
let outputs = ocr.output_info()?;
assert!(!inputs.is_empty());
assert!(!outputs.is_empty());
assert!(matches!(inputs[0].shape[0], AxisDim::Static(1)));
assert!(matches!(inputs[0].shape[2], AxisDim::Static(64)));
let model_info = ocr.model_info()?;
assert_eq!(model_info.inputs.len(), inputs.len());
assert_eq!(model_info.outputs.len(), outputs.len());
assert!(model_info.providers.is_none());
Ok(())
}
/// 验证检测运行时可以从构建的会话创建。
#[test]
fn det_runtime_builds_from_session() -> anyhow::Result<()> {
let path = model_path("common_det.onnx");
assert!(path.exists(), "缺少测试模型: {}", path.display());
let session: Session = ModelLoader::default().build_for_path(path)?;
let _det = DetRuntime::new(session);
Ok(())
}

View File

@@ -1,600 +0,0 @@
use std::borrow::Cow;
use std::fs::File;
use std::path::Path;
use anyhow::anyhow;
use ddddocr_core::Charset;
use ddddocr_core::{Normalization, Resize};
pub const CHARSET_BETA: &[&str] = &[
"", "", "", "", "", "", "", "", "", "", "", "", "", "6", "", "",
"", "", "", "", "", "", "", "", "", "", "", "鴿", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "f", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "²", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "!", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "à", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "鹿", "", "", "", "",
"", "p", "L", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "=", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "Y", "", "", "", "", "", "",
"", "", "w", "", "", "3", "", "F", "", "", "", "", "", "", "", "",
"m", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "耀", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "Θ", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "湿",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "X", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "绿", "", "", "", "",
"", "", "滿", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "G", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "x", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "/", "", "", "", "", "", "", "", "", "", "i", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "椿", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", ",", "", "", "", "", "",
"", "T", "", "", "", "N", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "´", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", " ", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "v", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "c",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "''", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "殿", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "B", "", "", "", "О", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "ɔ", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "\"", "", "", "", "", "", "",
"", "", "", "浿", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "n",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ":",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "#", "", "?", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "Φ", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "Q", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", ";", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "轿", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "H", "", "",
"", "", "", "", "", "", "", "", "", "", "", "趿", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "褿", "", "姿", "", "", "", "", "", "", "", "", "", "", "",
"", "K", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "尿", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "W", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", ">", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "P", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "r", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "%",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "l", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "E", "", "", "", "", "", "蹿", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "И", "", "", "", "Z", "", "",
"", "", "", "寿", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "α", "", "", "",
"", "", "", "", "", "", "", "", "", "", "s", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "2", "З", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "Ω", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "@", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "z", "", "", "", "", "", "", "", "", "", "", "", "", "", "访",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "巿", "", "", "", "", "", "D", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "鱿", "", "", "O", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "-", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "西", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "羿",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "麿", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "Р", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "ä", "", "", "", "", "广", "", "",
"", "", "", "", "", "", "4", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "忿", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "涿", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "°", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "^", "", "", "", "$", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "槿", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", ")", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "ü", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "仿", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "1", "", "", "", "", "", "", "", "", "", "", "", "", "Й",
"", "", "", "", "", "", "", "", "", "", "", "", "亿", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", " ", "", "", "", "", "", "", "",
"", "", "", "", "", "", "t", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "竿",
"", "|", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "β", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "b", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "o", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "Ë",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "è", "", "", "", "", "u", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"÷", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"±", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "9", "", "", "", "", "j", "", "", "0", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "\\", "", "", "", "",
"", "", "", "", "", "", "", "8", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "¥", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "贿", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "ò", "", "", "{", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "5", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "岿",
"[", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "驿", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "e", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "A", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "线", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "é", "", "",
"", "", "", "", "", "", "", "~", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "R", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"稿", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "窿", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "g", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "k", "", "", "", "", "", "",
"", "", "", "", "", "鸿", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "退", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "S",
"", "}", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "`", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "怀", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "屿", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "<", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "Я", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "Λ", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "齿", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "+", "", "", "宿", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "I", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "便", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "×", "", "", "",
"", "", "", "", "", "", "", "穿", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "7", "", "", "", "", "",
"", "", "", "", "", "", "", "", ".", "", "d", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "V", "", "", "]", "", "", "", "", "",
"", "", "", "", "", "", "(", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "诿", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "沿", "", "", "", "", "", "", "使", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"·", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "饿", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"J", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "a", "", "", "", "", "", "", "", "", "&", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "h", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "*", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "q", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "_", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "簿", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "罿", "", "П", "",
"U", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "廿", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "馿", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "M", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "y", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "C", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "®", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "婿", "", "", "", "", "", "", "", "", "", "", "",
"", "",
];
pub const CHARSET_OLD: &[&str] = &["", "", "", "", ""];
// pub fn from_builtin_old() -> Self {
// Self::from_static_slice(
// CHARSET_OLD,
// false,
// Resize::DynamicWidth(64),
// 1,
// Normalization::ZeroToOne,
// )
// }
//
// /// 从预设的 Beta 版字符集创建
// pub fn from_builtin_beta() -> Self {
// Self::from_static_slice(
// CHARSET_BETA,
// false,
// Resize::DynamicWidth(64),
// 1,
// Normalization::MinusOneToOne,
// )
// }
// /// 从外部外部 JSON 文件动态加载字符集(在后续优化中移除)
// pub fn from_json_file<P: AsRef<Path>>(path: P) -> anyhow::Result<Self> {
// let path = path.as_ref();
// if !path.exists() {
// return Err(anyhow!("模型元数据配置文件不存在: {:?}", path));
// }
//
// let mut file = File::open(path)?;
// let mut content = String::new();
// file.read_to_string(&mut content)?;
//
// let dto: ModelMetadataDto = serde_json::from_str(&content)
// .map_err(|e| anyhow!("JSON 反序列化失败,请检查字段是否完整: {}", e))?;
//
// // 1. 将 DTO 的字符串数组转化为强类型的 Charset
// let tokens: Vec<Cow<'static, str>> =
// dto.charset.into_iter().map(|s| Cow::Owned(s)).collect();
// let charset = Charset::new(tokens);
//
// // 2. 解析 resize 策略(重现 Python 的复杂条件判断)
// if dto.resize.len() != 2 {
// return Err(anyhow!(
// "'resize (or image)' 字段必须是包含两个元素的数组,例如 [-1, 64]"
// ));
// }
// let r0 = dto.resize[0];
// let r1 = dto.resize[1];
//
// let resize = if r0 == -1 {
// if dto.word {
// // 如果 word 为 true且包含 -1Python 里是 resize 为 (r1, r1) 的正方形
// Resize::Square(r1 as u32)
// } else {
// // 如果 word 为 false且包含 -1Python 里是高度固定为 r1宽度按原图比例缩放
// Resize::DynamicWidth(r1 as u32)
// }
// } else {
// // 正常的固定宽高
// Resize::Fixed(r0 as u32, r1 as u32)
// };
//
// Ok(Self {
// charset,
// word: dto.word,
// resize,
// channel: dto.channel,
// normalization: dto.normalization,
// })
// }

View File

@@ -0,0 +1,25 @@
//! 集成测试共享工具。
use std::path::{Path, PathBuf};
/// 仓库根目录 `models/` 下模型文件的路径。
pub fn model_path(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("models")
.join(name)
}
/// 仓库根目录 `samples/` 下样例图片的路径。
pub fn sample_path(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("samples")
.join(name)
}
/// 加载图片,失败时附带路径上下文。
pub fn load_image<P: AsRef<Path>>(path: P) -> anyhow::Result<image::DynamicImage> {
let path_ref = path.as_ref();
image::open(path_ref).map_err(|e| anyhow::anyhow!("无法加载图片 {:?}: {}", path_ref, e))
}

33
ddddocr-ort/tests/det.rs Normal file
View File

@@ -0,0 +1,33 @@
//! 目标检测集成测试。
mod common;
use common::{model_path, sample_path};
use ddddocr_core::Detector;
use ddddocr_core::traits::Loader;
use ddddocr_ort::DetRuntime;
use ddddocr_ort::loader::ModelLoader;
use image::GenericImageView;
/// 检测模型应能从样例图片中找到至少一个目标,且坐标在图片范围内。
#[test]
fn det_model_detects_targets_in_image() -> anyhow::Result<()> {
let session = ModelLoader::default()
.build_for_path(model_path("common_det.onnx"))
.expect("模型加载失败");
let det = DetRuntime::new(session);
let img = image::open(sample_path("det1.png")).expect("测试图片不存在");
let bboxes = Detector::new(&det).predict(&img)?;
assert!(!bboxes.is_empty(), "应检测到至少一个目标");
let (width, height) = img.dimensions();
for bbox in &bboxes {
assert!(bbox.x1 >= 0 && bbox.y1 >= 0, "检测框左上角不应为负");
assert!(
bbox.x2 <= width as i32 && bbox.y2 <= height as i32,
"检测框右下角不应超出图片范围"
);
}
Ok(())
}

56
ddddocr-ort/tests/ocr.rs Normal file
View File

@@ -0,0 +1,56 @@
//! OCR 识别与模型信息集成测试。
mod common;
use common::{model_path, sample_path};
use ddddocr_core::traits::{Info, Loader};
use ddddocr_core::{ModelMetadata, Normalization, Ocr, Resize};
use ddddocr_ort::OcrRuntime;
use ddddocr_ort::loader::ModelLoader;
/// 用官方 sml2h3 f32 模型识别验证码图片,结果不应为空。
#[test]
fn ocr_classification_recognizes_code_image() {
let session = ModelLoader::default()
.use_gpu(false)
.build_for_path(model_path("common_sml2h3_f32.onnx"))
.expect("模型加载失败");
let metadata = ModelMetadata::from_builtin_beta(
false,
Resize::DynamicWidth(64),
1,
Normalization::MinusOneToOne,
);
let ocr = OcrRuntime::new(session, metadata);
let img = image::open(sample_path("code2.png")).expect("测试图片不存在");
let text = Ocr::builder()
.build_with(&ocr)
.predict(&img)
.expect("识别过程出错")
.into_text();
println!("识别结果: {text}");
assert!(!text.is_empty(), "识别结果不应为空");
}
/// 真实模型应能通过 `Info` trait 返回输入/输出张量信息。
#[test]
fn model_info_lists_inputs_and_outputs() -> anyhow::Result<()> {
let session = ModelLoader::default()
.build_for_path(model_path("common_huashi666_i64.onnx"))
.expect("建立测试模型图失败");
let metadata = ModelMetadata::from_builtin_beta(
false,
Resize::DynamicWidth(64),
1,
Normalization::MinusOneToOne,
);
let ocr = OcrRuntime::new(session, metadata);
let inputs = ocr.input_info()?;
let outputs = ocr.output_info()?;
assert!(!inputs.is_empty(), "模型应有输入张量信息");
assert!(!outputs.is_empty(), "模型应有输出张量信息");
Ok(())
}

View File

@@ -1,253 +0,0 @@
use anyhow::Context;
use ddddocr_core::{DetectionResult, Ocr};
use ddddocr_core::traits::Loader;
use ddddocr_core::{Detector, ModelMetadata, Normalization, Slider};
// 假设你的包名是这个
use ddddocr_ort::{DetRuntime, OcrBuilder, OcrRuntime};
use image::{DynamicImage, ImageBuffer, Luma, Rgb};
use std::fs;
use std::path::Path;
mod char_slice;
use char_slice::CHARSET_BETA;
use ddddocr_core::Resize;
use ddddocr_ort::loader::ModelLoader as OrtModelLoader;
fn load_image<P: AsRef<Path>>(path: P) -> anyhow::Result<image::DynamicImage> {
// 1. 先将泛型转为具体的 &Path 引用
let path_ref = path.as_ref();
// 2. 调用 open 时传入引用utils::open 支持 AsRef<Path>
image::open(path_ref).map_err(|e| {
// 3. 此时 path_ref 依然有效,可以安全地在闭包中使用
anyhow::anyhow!("无法加载图片 {:?}: {}", path_ref, e)
})
}
/// 将检测结果绘制在图像上并保存
fn save_debug_image(
dynamic_img: &DynamicImage, // 【优化点 1】直接传入解码好的引用拒绝重复解码
bboxes: &[DetectionResult], // 【修改点 1】类型改为自定义结构体切片
output_path: &str,
) -> anyhow::Result<()> {
// 删除了原本的 let dynamic_img = image::load_from_memory(image_bytes)?;
let mut img = dynamic_img.to_rgb8();
let (width, height) = img.dimensions();
let red = Rgb([255u8, 0, 0]);
for bbox in bboxes {
// 【修改点 2】将原来的索引 bbox[0].. 改为结构体字段访问 .x1, .y1 ..
let x1 = bbox.x1.max(0).min(width as i32 - 1) as u32;
let y1 = bbox.y1.max(0).min(height as i32 - 1) as u32;
let x2 = bbox.x2.max(0).min(width as i32 - 1) as u32;
let y2 = bbox.y2.max(0).min(height as i32 - 1) as u32;
// 绘制横向线条
for x in x1..=x2 {
img.put_pixel(x, y1, red);
img.put_pixel(x, y2, red);
if y1 + 1 < height {
img.put_pixel(x, y1 + 1, red);
}
if y2.saturating_sub(1) > 0 {
img.put_pixel(x, y2 - 1, red);
}
}
// 绘制纵向线条
for y in y1..=y2 {
img.put_pixel(x1, y, red);
img.put_pixel(x2, y, red);
if x1 + 1 < width {
img.put_pixel(x1 + 1, y, red);
}
if x2.saturating_sub(1) > 0 {
img.put_pixel(x2 - 1, y, red);
}
}
}
img.save(output_path)?;
Ok(())
}
#[allow(dead_code)]
fn save_rust_result(result: &ImageBuffer<Luma<f32>, Vec<f32>>, filename: &str) {
let (width, height) = result.dimensions();
// 1. 寻找最值进行归一化
let mut max_val = f32::MIN;
let mut min_val = f32::MAX;
for p in result.pixels() {
if p.0[0] > max_val {
max_val = p.0[0];
}
if p.0[0] < min_val {
min_val = p.0[0];
}
}
// 2. 创建 8 位灰度图
let mut out_buf = ImageBuffer::new(width, height);
for y in 0..height {
for x in 0..width {
let val = result.get_pixel(x, y).0[0];
let normalized = if max_val > min_val {
((val - min_val) / (max_val - min_val) * 255.0) as u8
} else {
0u8
};
out_buf.put_pixel(x, y, Luma([normalized]));
}
}
// 3. 保存
DynamicImage::ImageLuma8(out_buf).save(filename).unwrap();
println!("Rust 结果热力图已保存至: {}", filename);
}
#[test]
fn test_full_classification() {
let session = OrtModelLoader::default().use_gpu(false)
.build_for_path("D:\\CNWei\\CNW\\Rust\\ddddocr-rs\\models\\common_sml2h3_f32.onnx")
// .build_for_path("D:\\CNWei\\CNW\\Rust\\ddddocr-rs\\models\\common_old.onnx")
.expect("模型加载失败");
let metadata = ModelMetadata::from_static_slice(
CHARSET_BETA,
false,
Resize::DynamicWidth(64),
1,
Normalization::MinusOneToOne,
);
// 1. 初始化模型
let ocr = OcrRuntime::new(session, metadata);
// 2. 加载测试图片
let img =
image::open("D:/CNWei/CNW/Rust/ddddocr-rs/samples/code2.png").expect("测试图片不存在");
// 3. 执行识别
// let result = Ocr::new(&ocr)
// .predict(&img)
// .expect("识别过程出错")
// .into_text();
// let result = OcrBuilder::new()
// .build(&ocr)
// .predict(&img)
// .expect("识别过程出错")
// .into_text();
let res=Ocr::builder().build_with(&ocr).predict(&img).expect("s").into_text();
// println!("识别结果: {}", result);
println!("识别结果: {}", res);
// assert!(!result.is_empty());
assert!(!res.is_empty());
}
#[test]
fn test_det_load() -> anyhow::Result<()> {
let session = OrtModelLoader::default()
.build_for_path("D:\\CNWei\\CNW\\Rust\\ddddocr-rs\\models\\common_det.onnx")
.expect("模型加载失败");
let det = DetRuntime::new(session);
let image_path = "D:/CNWei/CNW/Rust/ddddocr-rs/samples/det1.png";
let image_bytes =
fs::read(image_path).map_err(|e| anyhow::anyhow!("无法读取图片 {}: {}", image_path, e))?;
println!("图片读取成功,字节大小: {}", image_bytes.len());
// 【修改点 1】将字节流解码为统一的 DynamicImage
let img = image::load_from_memory(&image_bytes)
.map_err(|e| anyhow::anyhow!("图片解码失败: {}", e))?;
// 【修改点 2】传入统一的 &DynamicImage 引用
let bboxes = Detector::new(&det).predict(&img)?;
// println!("{:?}", det);
println!("检测到的目标数量: {}", bboxes.len());
if bboxes.is_empty() {
println!("未检测到任何目标。");
} else {
// 如果 save_debug_image 报错,记得去把它的入参类型和内部访问也改为 DetectionResult
save_debug_image(
&img,
&bboxes,
"D:/CNWei/CNW/Rust/ddddocr-rs/samples/result.jpg",
)?;
for (i, bbox) in bboxes.iter().enumerate() {
// 【修改点 3】将原来的 bbox[0].. 索引访问改为结构体字段访问
println!("目标 [{}]: {}", i, bbox);
}
}
Ok(())
}
#[test]
fn test_real_slide_match() {
let engine = Slider::new();
// 1. 加载你准备好的测试图
// 假设图片放在项目根目录下的 assets 文件夹
let target_img = load_image("D:/CNWei/CNW/Rust/ddddocr-rs/samples/hua.png")
.expect("请确保 samples/hua.png 存在");
let bg_img = load_image("D:/CNWei/CNW/Rust/ddddocr-rs/samples/huatu.png")
.expect("请确保 samples/huatu.png 存在");
// 2. 执行匹配
// 如果是那种带有明显阴影边缘的复杂滑块,建议 simple_target 传 false
let start = std::time::Instant::now();
let result = engine
.slide_match(&target_img, &bg_img, false)
.expect("Slide match 执行失败");
let duration = start.elapsed();
// 3. 打印结果
println!("-------------------------------------------");
println!("{}", result);
println!("耗时: {:?}", duration);
println!("-------------------------------------------");
// 验证基本逻辑:坐标不应为 0 (除非匹配失败)
assert_eq!(result.target_x, 237);
assert_eq!(result.target_y, 77);
assert!(result.confidence > 0.0);
}
#[test]
fn test_real_slide_comparison() {
let engine = Slider::new();
// 1. 加载你准备好的测试图
// 假设图片放在项目根目录下的 assets 文件夹
let target_img = load_image("D:/CNWei/CNW/Rust/ddddocr-rs/samples/ken.jpg")
.expect("请确保 samples/ken.jpg 存在");
let bg_img = load_image("D:/CNWei/CNW/Rust/ddddocr-rs/samples/kenyuan.jpg")
.expect("请确保 samples/kenyuan.jpg 存在");
// 2. 执行匹配
// 如果是那种带有明显阴影边缘的复杂滑块,建议 simple_target 传 false
let start = std::time::Instant::now();
let result = engine
.slide_comparison(&target_img, &bg_img)
.expect("Slide match 执行失败");
let duration = start.elapsed();
// 3. 打印结果
println!("-------------------------------------------");
println!("滑块匹配测试结果:");
println!("检测坐标: [x: {}, y: {}]", result.target_x, result.target_y);
println!("置信度: {:.4}", result.confidence);
println!("耗时: {:?}", duration);
println!("-------------------------------------------");
// 验证基本逻辑:坐标不应为 0 (除非匹配失败)
assert_eq!(result.target_x, 171);
assert_eq!(result.target_y, 90);
assert!(result.confidence > 0.0);
}
#[test]
fn test_resolve_shape_logic_direct() {
// 创建一个哑 ModelLoader 实例session 用不上,因为我们直接测私有方法)
let loader = OrtModelLoader::default()
.build_for_path(
// "D:\\CNWei\\CNW\\Rust\\ddddocr-rs\\models\\common_sml2h3_f32.onnx",
"D:\\CNWei\\CNW\\Rust\\ddddocr-rs\\models\\common_huashi666_i64.onnx",
)
.expect("建立测试模型图失败");
}

View File

@@ -0,0 +1,52 @@
//! 滑块匹配集成测试。
mod common;
use common::{load_image, sample_path};
use ddddocr_core::Slider;
/// 边缘模式匹配应定位到预期坐标。
#[test]
fn slide_match_locates_target_position() {
let engine = Slider::new();
let target = load_image(sample_path("target1.png")).expect("请确保 samples/target1.png 存在");
let background = load_image(sample_path("background1.png")).expect("请确保 samples/background1.png 存在");
let start = std::time::Instant::now();
let result = engine
.slide_match(&target, &background, false)
.expect("Slide match 执行失败");
let elapsed = start.elapsed();
println!("边缘模式匹配: {result}");
println!("耗时: {elapsed:?}");
assert_eq!(result.target_x, 237);
assert_eq!(result.target_y, 77);
assert!(result.confidence > 0.0);
}
/// 灰度对比匹配应定位到预期坐标。
#[test]
fn slide_comparison_locates_target_position() {
let engine = Slider::new();
let target = load_image(sample_path("target2.jpg")).expect("请确保 samples/target2.jpg 存在");
let background =
load_image(sample_path("background2.jpg")).expect("请确保 samples/background2.jpg 存在");
let start = std::time::Instant::now();
let result = engine
.slide_comparison(&target, &background)
.expect("Slide comparison 执行失败");
let elapsed = start.elapsed();
println!(
"灰度对比匹配: 坐标 [x: {}, y: {}], 置信度 {:.4}",
result.target_x, result.target_y, result.confidence
);
println!("耗时: {elapsed:?}");
assert_eq!(result.target_x, 171);
assert_eq!(result.target_y, 90);
assert!(result.confidence > 0.0);
}