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

@@ -2,11 +2,11 @@
resolver = "2" resolver = "2"
members = [ members = [
"ddddocr-core", "ddddocr-ort", "ddddocr-core", "ddddocr-ort",
"ddddocr-tract", "ddddocr-tract2",
] ]
[workspace.package] [workspace.package]
version = "0.2.1" version = "0.2.4"
edition = "2024" edition = "2024"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"

2
NOTICE
View File

@@ -4,3 +4,5 @@ Copyright 2026 CNWei
This product includes software developed by: This product includes software developed by:
- sml2h3 (ddddocr) - Model weights and original logic. - sml2h3 (ddddocr) - Model weights and original logic.
- Sonos (tract) - ONNX inference engine. - Sonos (tract) - ONNX inference engine.
- pyke.io (ort) - Rust bindings for ONNX Runtime.
- Microsoft (ONNX Runtime contributors) - ONNX inference engine.

144
README.md
View File

@@ -1,45 +1,135 @@
# ddddocr-rs # ddddocr-rs
带带弟弟 OCR (ddddocr) 的 Rust 移植版。高性能、低占用,支持多种验证码识别与检测 [带带弟弟 OCRddddocr](https://github.com/sml2h3/ddddocr) 的 Rust 移植版:提供验证码 OCR 识别、目标检测与滑块匹配能力。核心库与推理引擎解耦,同一套 API 可切换 [Tract](https://github.com/sonos/tract) 或 [ONNX Runtime](https://onnxruntime.ai/) 后端
🧩 滑块识别算法核心知识点总结 ## 架构
本项目实现了两种核心匹配模式,其底层逻辑与 OpenCV 的对齐情况如下:
1. 匹配模式对比 (Match Modes) 项目为 Cargo workspace包含三个 crate
|**模式**|**算法原理**|**适用场景**|**备注**|
|---|---|---|---|
|**边缘模式** (Edge-based)|基于 **Canny 边缘检测** 提取轮廓后再进行匹配。|**推荐方案**
。适用于绝大多数拼图滑块。|天然免疫拼图周边的透明/黑色留白干扰,坐标最精准。|
|**简单模式** (Simple/Gray)|直接基于 **灰度像素值** 进行归一化互相关计算。|适用于无明显边缘、靠颜色差异识别的场景。|对背景和透明边框敏感,可能存在重心偏移。|
2. 数学公式差异 (NCC vs. CCOEFF) | crate | 说明 |
在简单模式下,本项目采用的是 归一化互相关 (NCC),对应 OpenCV 中的 TM_CCORR_NORMED。 |---|---|
| `ddddocr-core` | 引擎无关的核心库OCR / 目标检测 / 滑块匹配、模型元数据与图像预处理 |
| `ddddocr-ort` | ONNX Runtime 推理后端(可选 `cuda` feature 启用 GPU 加速) |
| `ddddocr-tract2` | Tract纯 Rust推理后端 |
逻辑对齐Rust 的 match_template 结果与 Python cv2.TM_CCORR_NORMED 完全一致 `ddddocr-core` 通过 `traits::InferenceEngine` / `OcrEngine` / `DetEngine` 抽象推理能力,由 `ddddocr-ort` / `ddddocr-tract2` 实现,业务代码只依赖核心库接口即可
关于偏移若拼图原始图片Target四周包含大量的透明留白 ## 快速开始
CCORR (本项目):会将留白视为图像的一部分,计算出的是整张图片框的中心。 在 Cargo.toml 中添加:
CCOEFF (OpenCV 默认):会自动进行“均值中心化”,在一定程度上能削弱留白的影响。 ```toml
[dependencies]
ddddocr-core = "0.2"
ddddocr-ort = "0.2" # 或 ddddocr-tract2 = "0.2"
```
最佳实践:若发现坐标有固定位移,建议优先切换至 边缘模式,或对滑块图进行 Bounding Box 裁剪 后再匹配。 核心库自带一个不依赖真实模型的演示示例(用假引擎演示完整调用链):
3. 图像预处理一致性 ```bash
cargo run -p ddddocr-core --example quick_start
```
为确保识别精度,本项目在 Rust 中完美复刻了 Python OpenCV 的预处理链路 真实推理需要自行准备 ONNX 模型文件crate 包内不包含模型)。以 ORT 后端为例
- **灰度化权重**:采用 OpenCV 标准感光公式 $0.299R + 0.587G + 0.114B$。 ```rust
use ddddocr_core::traits::{Info, Loader};
use ddddocr_core::{ModelMetadata, Normalization, Ocr, Resize};
- **Alpha 处理**:在将 PNG 转为 RGB 时,自动将透明区域填充为黑色,确保与 PIL (Python Imaging Library) 行为一致。 // 1. 构建会话等价写法ddddocr_tract2::loader::ModelLoader
let session = ddddocr_ort::loader::ModelLoader::default()
.build_for_path("models/common.onnx")?;
- **坐标定义**:所有返回坐标均为匹配区域的 **几何中心点** $(x + w/2, y + h/2)$。 // 2. 组装 OCR 运行时
let metadata = ModelMetadata::from_static_slice(
&["a", "b"], // 字符集
false, // 非单字模型
Resize::DynamicWidth(64), // 高度固定 64、宽度等比缩放
1, // 灰度单通道
Normalization::MinusOneToOne,
);
let ocr = ddddocr_ort::OcrRuntime::new(session, metadata);
💡 开发者建议: // 3. 识别图片
let result = Ocr::builder().build_with(&ocr).predict(&image)?;
println!("识别结果: {}", result);
```
如果识别结果在 $X$ 轴上有大约 $10px$ 左右的固定误差,通常是因为滑块原图自带了透明边距(留白)。此时请确保 目标检测与滑块匹配类似:`Detector::new(&engine).predict(&image)` 返回检测框列表;`Slider::new().slide_match(target, background, simple_target)` 返回匹配坐标与置信度。
simple_target=false。该模式会通过 Canny 边缘检测 提取轮廓特征,能自动锁定拼图实体并忽略背景留白的像素干扰。
鸣谢 (Credits)
- 本项目是 [ddddocr](https://github.com/sml2h3/ddddocr) 的 Rust 移植版本,原作者为 sml2h3。衷心感谢原作者对 OCR 社区做出的杰出贡献。 ## 模型下载
- 推理引擎基于 [tract (Sonos)](https://github.com/sonos/tract)。感谢其为 Rust 生态提供的轻量级推理方案。
OCR / 目标检测需要 ONNX 模型文件。官方模型位于 [ddddocr 仓库 `ddddocr/` 目录](https://github.com/sml2h3/ddddocr/blob/master/ddddocr/),下载后放入仓库根目录的 `models/` 文件夹:
| 文件 | 大小 | 用途 | 直链 |
|---|---|---|---|
| `common.onnx` | 约 51.6 MB | 新版 OCR 模型(默认) | [下载](https://raw.githubusercontent.com/sml2h3/ddddocr/master/ddddocr/common.onnx) |
| `common_det.onnx` | 约 19.2 MB | 目标检测模型 | [下载](https://raw.githubusercontent.com/sml2h3/ddddocr/master/ddddocr/common_det.onnx) |
| `common_old.onnx` | 约 13 MB | 旧版 OCR 模型 | [下载](https://raw.githubusercontent.com/sml2h3/ddddocr/master/ddddocr/common_old.onnx) |
> 注意:`ddddocr-tract2` 不支持旧版模型 `common_old.onnx`,请使用 `common.onnx`。
>
> 字符集配对:`common.onnx` 对应内置 Beta 字符集(`Charset` / `ModelMetadata::from_builtin_beta`,归一化 `MinusOneToOne``common_old.onnx` 对应旧版字符集(`from_builtin_old`,归一化 `ZeroToOne`)。
>
> 仓库测试使用的 `common_sml2h3_f32.onnx`、`common_huashi666_i64.onnx` 为社区转换的 f32 / i64 变体模型(与 `common.onnx` 同源),不在上述官方目录中,需自行获取。
## 字符集与内置默认值
OCR 模型的字符集token 列表)是模型的一部分:字符 `i` 对应模型输出 logits 的第 `i` 列,必须与模型训练时一致,否则识别结果会错位。
字符集有两种提供方式:
- 通过模型元数据 JSON 的 `charset` 字段(`Metadata::from_json_str` / `from_json_bytes` 自动解析);
- 代码内显式指定:`ModelMetadata::from_static_slice(&["", "a", "b"], ...)``Charset::new(...)`
`ddddocr-core` 内置官方模型的默认字符集(旧版 `CHARSET_OLD` 与 Beta `CHARSET_BETA`),作为免配置的快速通道。字符集数据独立存放在 `ddddocr-core/src/ocr/builtin.rs` 私有模块中(与业务逻辑分离),通过 `ModelMetadata` 的公开构造方法使用:
```rust
use ddddocr_core::{ModelMetadata, Normalization, Resize};
// 官方旧版模型配套
let meta = ModelMetadata::from_builtin_old(
false,
Resize::DynamicWidth(64),
1,
Normalization::ZeroToOne,
);
// 官方 Beta 模型配套
let meta = ModelMetadata::from_builtin_beta(
false,
Resize::DynamicWidth(64),
1,
Normalization::MinusOneToOne,
);
```
数据内置于代码,不依赖外部文件。若使用自有模型,请仍以元数据 JSON 或 `from_static_slice` 指定匹配的字符集。
## 滑块匹配核心知识点
项目实现两种匹配模式,底层逻辑与 OpenCV 对齐:
| 模式 | 算法原理 | 适用场景 | 备注 |
|---|---|---|---|
| 边缘模式Edge-based | 基于 Canny 边缘检测提取轮廓后匹配 | **推荐方案**,适用于绝大多数拼图滑块 | 天然免疫拼图周边透明/黑色留白干扰,坐标最精准 |
| 简单模式Simple/Gray | 基于灰度像素值做归一化互相关NCC | 无明显边缘、靠颜色差异识别的场景 | 对背景和透明边框敏感,可能存在重心偏移 |
关键点:
- 简单模式采用归一化互相关NCC与 OpenCV 的 `TM_CCORR_NORMED` 完全一致。
- 若拼图原图四周带透明留白本项目会将留白计入整张图片框中心OpenCV 默认的 CCOEFF 会做均值中心化削弱留白影响。
- 图像预处理与 Python 链路保持一致:灰度权重采用 OpenCV 标准感光公式 `0.299R + 0.587G + 0.114B`PNG 转 RGB 时透明区域填充为黑色;返回坐标为匹配区域的几何中心 `(x + w/2, y + h/2)`
> 若识别结果在 X 轴上有约 10px 固定误差,通常是滑块原图自带透明边距所致。此时请确保 `simple_target = false`,边缘模式会自动锁定拼图实体并忽略留白干扰。
## 致谢
- [sml2h3 (ddddocr)](https://github.com/sml2h3/ddddocr) - 模型权重与原始逻辑。
- [Sonos (tract)](https://github.com/sonos/tract) - 纯 Rust ONNX 推理引擎。
- [pyke.io (ort)](https://github.com/pykeio/ort) - ONNX Runtime 的 Rust 绑定。
- [Microsoft (ONNX Runtime)](https://onnxruntime.ai/) - ONNX 推理引擎。
## License
`MIT OR Apache-2.0`,许可证文本见仓库根目录的 `LICENSE-MIT``LICENSE-APACHE`

BIN
code3.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

View File

@@ -165,7 +165,7 @@ mod tests {
#[test] #[test]
fn new_wraps_third_party_error() { fn new_wraps_third_party_error() {
let io_err = std::io::Error::new(std::io::ErrorKind::Other, "boom"); let io_err = std::io::Error::other("boom");
let err = DdddError::new(io_err); let err = DdddError::new(io_err);
assert!(matches!(err, DdddError::Other(_))); assert!(matches!(err, DdddError::Other(_)));
} }

View File

@@ -2,7 +2,7 @@
//! //!
//! `ddddocr-rs` 的核心库:提供与具体推理引擎解耦的 OCR 识别、目标检测det与滑块匹配slide能力。 //! `ddddocr-rs` 的核心库:提供与具体推理引擎解耦的 OCR 识别、目标检测det与滑块匹配slide能力。
//! 推理能力由 [`traits::InferenceEngine`]、[`traits::OcrEngine`]、[`traits::DetEngine`] 抽象, //! 推理能力由 [`traits::InferenceEngine`]、[`traits::OcrEngine`]、[`traits::DetEngine`] 抽象,
//! 由 `ddddocr-tract`、`ddddocr-ort` 等引擎 crate 实现。 //! 由 `ddddocr-tract2`、`ddddocr-ort` 等引擎 crate 实现。
//! //!
//! 完整可运行示例见 `ddddocr-core/examples/quick_start.rs`。 //! 完整可运行示例见 `ddddocr-core/examples/quick_start.rs`。

View File

@@ -1,6 +1,7 @@
//! OCR 模块:识别器构建器、执行入口及元数据、字符集等类型。 //! OCR 模块:识别器构建器、执行入口及元数据、字符集等类型。
mod builder; mod builder;
mod builtin;
mod charset; mod charset;
mod color_filter; mod color_filter;
mod executor; mod executor;

File diff suppressed because it is too large Load Diff

View File

@@ -88,6 +88,37 @@ impl ModelMetadata {
normalization, normalization,
} }
} }
/// 使用内置旧版字符集(与官方旧版模型配套)。
pub fn from_builtin_old(
word: bool,
resize: Resize,
channel: u8,
normalization: Normalization,
) -> Self {
Self::from_static_slice(
super::builtin::CHARSET_OLD,
word,
resize,
channel,
normalization,
)
}
/// 使用内置 Beta 字符集(与官方 Beta 模型配套)。
pub fn from_builtin_beta(
word: bool,
resize: Resize,
channel: u8,
normalization: Normalization,
) -> Self {
Self::from_static_slice(
super::builtin::CHARSET_BETA,
word,
resize,
channel,
normalization,
)
}
} }
#[cfg(test)] #[cfg(test)]

View File

@@ -15,7 +15,7 @@ pub trait Info {
fn model_info(&self) -> crate::error::Result<ModelInfo>; fn model_info(&self) -> crate::error::Result<ModelInfo>;
} }
/// 推理引擎统一抽象接口,由 ddddocr-tract、ddddocr-ort 等引擎 crate 实现。 /// 推理引擎统一抽象接口,由 ddddocr-tract2、ddddocr-ort 等引擎 crate 实现。
pub trait InferenceEngine { pub trait InferenceEngine {
/// 引擎产出的输出枚举OCR 为 [`crate::OcrOutput`],检测为 [`crate::DetOutput`])。 /// 引擎产出的输出枚举OCR 为 [`crate::OcrOutput`],检测为 [`crate::DetOutput`])。
type Output; type Output;

View File

@@ -1,23 +1,25 @@
[package] [package]
name = "ddddocr-ort" name = "ddddocr-ort"
version.workspace = true version = { workspace = true }
edition.workspace = true edition = { workspace = true }
license.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] [dependencies]
ddddocr-core = { path = "../ddddocr-core" } # 引入兄弟库 ddddocr-core = { path = "../ddddocr-core", version = "0.2.4" }
ort = { workspace = true ,features = ["cuda"]} ort = { workspace = true }
ndarray = { workspace = true } # 继承自工作空间 ndarray = { workspace = true }
image = { workspace = true } image = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
anyhow = { workspace = true } anyhow = { workspace = true }
thiserror = { workspace = true } # 刚好可以开始接入你需要的标准库错误处理 thiserror = { workspace = true }
tracing = { workspace = true }
[features] [features]
# 1. 声明 cuda feature # 开启后启用底层 ort 库的 CUDA 执行提供者支持。
# 2. 当开启 ddddocr-ort 的 cuda feature 时,自动开启底层 ort 库的 cuda 支持(如果 ort 库支持的话)
cuda = ["ort/cuda"] cuda = ["ort/cuda"]

View File

@@ -1,63 +1,40 @@
use crate::runtime::{extract_tensor, lock_session, run_session};
use crate::types::Session; use crate::types::Session;
use ddddocr_core::DetOutput; use ddddocr_core::DetOutput;
use ddddocr_core::error::{Result, TensorError}; use ddddocr_core::error::{Result, TensorError};
use ddddocr_core::traits::{DetEngine, InferenceEngine}; use ddddocr_core::traits::{DetEngine, InferenceEngine};
use ndarray::Ix3; use ndarray::Ix3;
use ort::inputs; use tracing::debug;
use ort::value::TensorRef;
/// 目标检测推理运行时:持有 ORT 会话,输出 [`DetOutput`]。
#[derive(Debug)] #[derive(Debug)]
pub struct DetRuntime { pub struct DetRuntime {
/// ORT 会话句柄。
pub session: Session, pub session: Session,
} }
impl DetRuntime { impl DetRuntime {
/// 基于已构建的会话创建检测运行时。
pub fn new(session: Session) -> Self { pub fn new(session: Session) -> Self {
Self { session } Self { session }
} }
} }
impl InferenceEngine for DetRuntime { impl InferenceEngine for DetRuntime {
type Output = DetOutput; // 明确绑定 OCR 小枚举 type Output = DetOutput;
fn inference(&self, input_array: ndarray::Array4<f32>) -> Result<Self::Output, TensorError> { fn inference(&self, input_array: ndarray::Array4<f32>) -> Result<Self::Output, TensorError> {
// tract 的 run 会返回一个 Vec<TValue>,我们通常只需要第一个输出 let mut session_guard = lock_session(&self.session)?;
// let result = self.ocr.run(tvec!(tensor.into()))?; let result = run_session(&mut session_guard, &input_array)?;
let mut session_guard = self debug!("模型输出原始数据: {:?}", result);
.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 (view, shape_vec) = extract_tensor::<f32>(&result[0])?;
let array3 = view.to_owned().into_dimensionality::<Ix3>().map_err(|_| { let array3 = view.to_owned().into_dimensionality::<Ix3>().map_err(|_| {
TensorError::DimensionMismatch { TensorError::DimensionMismatch {
expected: "3D 检测矩阵 [Batch, Box_Count, Box_Attributes]".to_string(), expected: "3D 检测矩阵 [Batch, Box_Count, Box_Attributes]".to_string(),
actual: shape_vec, // 优雅降维失败时动态捕获 actual: shape_vec,
} }
})?; })?;
Ok(DetOutput::Detection(array3)) 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; mod det;
/// 模型加载器:从路径或字节流构建 ORT 会话。
pub mod loader; pub mod loader;
mod ocr; mod ocr;
mod runtime;
mod types; mod types;
pub use ddddocr_core::{OcrBuilder, SlideResult, Slider};
pub use ddddocr_core::{SlideResult, Slider,OcrBuilder};
pub use det::session::DetRuntime; 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; mod model;
pub use error::{Error, ParseError, Result}; pub use error::{Error, ParseError, Result};
pub use metadata::{ModelMetadataDto, NormalizationDto, Metadata}; pub use metadata::{Metadata, ModelMetadataDto, NormalizationDto};
pub use model::ModelLoader; pub use model::ModelLoader;

View File

@@ -1,7 +1,10 @@
use ort::Error as OrtError; use ort::Error as OrtError;
/// 模型加载与解析的通用结果类型。
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]
/// 模型加载、解析与 Session 构建阶段的错误。
pub enum Error { pub enum Error {
/// 底层构建器配置失败。
#[error("builder构建失败")] #[error("builder构建失败")]
Build(#[from] BuildError), Build(#[from] BuildError),
/// 解析 ONNX 模型/路径失败(如文件损坏、算子不支持、路径非法) /// 解析 ONNX 模型/路径失败(如文件损坏、算子不支持、路径非法)
@@ -9,11 +12,11 @@ pub enum Error {
ModelParse(#[from] ParseError), ModelParse(#[from] ParseError),
/// 模型计算图优化失败(如常量折叠、形状推导失败) /// 模型计算图优化失败(如常量折叠、形状推导失败)
#[error("优化 Tract 模型图失败: {0}")] #[error("优化 ORT 模型图失败: {0}")]
OptimizationFailed(#[source] OrtError), OptimizationFailed(#[source] OrtError),
/// 构建可执行 Session 失败(如输入输出 Tensor 类型/形状未确定) /// 构建可执行 Session 失败(如输入输出 Tensor 类型/形状未确定)
#[error("构建可运行 Tract 实例失败: {0}")] #[error("构建可运行的 ORT Session 失败: {0}")]
RunnableBuildFailed(#[source] OrtError), RunnableBuildFailed(#[source] OrtError),
/// JSON 反序列化失败(自动透传 serde_json 报错) /// JSON 反序列化失败(自动透传 serde_json 报错)
@@ -24,6 +27,7 @@ pub enum Error {
#[error("Metadata 字节流不是合法的 UTF-8 编码: {0}")] #[error("Metadata 字节流不是合法的 UTF-8 编码: {0}")]
InvalidUtf8(#[from] std::str::Utf8Error), InvalidUtf8(#[from] std::str::Utf8Error),
/// 模型元数据内容解析失败。
#[error("模型元数据解析失败: {0}")] #[error("模型元数据解析失败: {0}")]
MetadataParse(String), MetadataParse(String),
@@ -32,8 +36,6 @@ pub enum Error {
Other(String, #[source] Box<dyn std::error::Error + Send + Sync>), Other(String, #[source] Box<dyn std::error::Error + Send + Sync>),
} }
impl Error { impl Error {
/// 方便将任何第三方 Error 包装为 Error::Other /// 方便将任何第三方 Error 包装为 Error::Other
pub fn new<E>(msg: impl Into<String>, err: E) -> Self pub fn new<E>(msg: impl Into<String>, err: E) -> Self
@@ -44,6 +46,7 @@ impl Error {
} }
} }
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]
/// 从路径或字节流解析 ONNX 模型失败的错误。
pub enum ParseError { pub enum ParseError {
/// 策略 A从文件路径加载失败附带路径上下文信息方便排查是找不到文件还是格式不对 /// 策略 A从文件路径加载失败附带路径上下文信息方便排查是找不到文件还是格式不对
#[error("从路径 '{0}' 加载 ONNX 模型失败: {1}")] #[error("从路径 '{0}' 加载 ONNX 模型失败: {1}")]
@@ -54,13 +57,45 @@ pub enum ParseError {
Bytes(#[source] OrtError), Bytes(#[source] OrtError),
} }
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]
pub enum BuildError{ pub enum BuildError {
#[error("builder构建失败")] /// 底层 SessionBuilder 构建失败
#[error("构建 ORT SessionBuilder 失败: {0}")]
BuildFailed(#[from] OrtError), BuildFailed(#[from] OrtError),
#[error("builder构建失败")] /// 线程数配置失败。
#[error("{0}")]
Threads(String), Threads(String),
#[error("builder构建失败")] /// 启用 CUDA 执行提供者失败。
#[error("{0}")]
EnabledCudaFailed(String), EnabledCudaFailed(String),
#[error("builder构建失败")] /// 未编译 CUDA 支持时尝试启用 GPU。
NotEnabledCuda(String) #[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 crate::loader::error::{Error, Result};
use ddddocr_core::ModelMetadata; use ddddocr_core::{Charset, ModelMetadata, Normalization, Resize};
use ddddocr_core::Resize;
use ddddocr_core::{Charset, Normalization};
use serde::Deserialize; use serde::Deserialize;
use std::borrow::Cow; use std::borrow::Cow;
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "snake_case")] // 支持 json 中写 "zero_to_one" 或 "minus_one_to_one" #[serde(rename_all = "snake_case")] // 支持 json 中写 "zero_to_one" 或 "minus_one_to_one"
/// 归一化策略的 JSON 反序列化中间表示。
pub enum NormalizationDto { pub enum NormalizationDto {
/// 映射到 [0.0, 1.0] -> pixel / 255.0 /// 映射到 [0.0, 1.0] -> pixel / 255.0
ZeroToOne, ZeroToOne,
@@ -41,8 +40,9 @@ fn default_normalization() -> NormalizationDto {
NormalizationDto::ZeroToOne NormalizationDto::ZeroToOne
} }
/// Tract 专属扩展trait 或 工具函数 /// 从 JSON 字符串或字节流解析模型元数据的扩展接口。
pub trait Metadata: Sized { pub trait Metadata: Sized {
/// 从 JSON 字符串解析模型元数据。
fn from_json_str(json_str: &str) -> Result<Self>; fn from_json_str(json_str: &str) -> Result<Self>;
/// 机制 2从内存字节流加载极大地方便 include_bytes! 或网络下载) /// 机制 2从内存字节流加载极大地方便 include_bytes! 或网络下载)
fn from_json_bytes(bytes: &[u8]) -> Result<Self> { 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)?; let dto: ModelMetadataDto = serde_json::from_str(json_str)?;
// 1. 将 DTO 的字符串数组转化为强类型的 Charset // 1. 将 DTO 的字符串数组转化为强类型的 Charset
let tokens: Vec<Cow<'static, str>> = let tokens: Vec<Cow<'static, str>> = dto.charset.into_iter().map(Cow::Owned).collect();
dto.charset.into_iter().map(|s| Cow::Owned(s)).collect();
let charset = Charset::new(tokens); let charset = Charset::new(tokens);
// 2. 解析 resize 策略(重现 Python 的复杂条件判断) // 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 ort::session::builder::SessionBuilder;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
// pub struct OrtModelLoader;
//
// impl OrtModelLoader {
// /// 获取针对 ORT 后端的链式构建器
// pub fn builder() -> OrtModelBuilder {
// OrtModelBuilder::default()
// }
// }
/// ORT 专用的链式构建器 /// ORT 专用的链式构建器
#[derive(Debug, Clone)] #[derive(Debug, Clone, Default)]
pub struct ModelLoader { pub struct ModelLoader {
use_gpu: bool, use_gpu: bool,
device_id: i32, device_id: i32,
intra_threads: Option<usize>, intra_threads: Option<usize>,
} }
impl Default for ModelLoader {
fn default() -> Self {
Self {
use_gpu: false,
device_id: 0,
intra_threads: None,
}
}
}
impl ModelLoader { impl ModelLoader {
/// 开启或关闭 GPU 加速 /// 开启或关闭 GPU 加速
pub fn use_gpu(mut self, enable: bool) -> Self { pub fn use_gpu(mut self, enable: bool) -> Self {
@@ -42,6 +25,7 @@ impl ModelLoader {
self.device_id = id; self.device_id = id;
self self
} }
/// 指定 ORT 内部线程数。
pub fn num_threads(mut self, threads: usize) -> Self { pub fn num_threads(mut self, threads: usize) -> Self {
self.intra_threads = Some(threads); self.intra_threads = Some(threads);
self self
@@ -49,7 +33,7 @@ impl ModelLoader {
/// 内部辅助方法:根据当前的配置构建 ORT 底层的 SessionBuilder /// 内部辅助方法:根据当前的配置构建 ORT 底层的 SessionBuilder
fn create_session_builder(&self) -> Result<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 // 如果用户显式设置了线程数,则配置给 ORT
if let Some(threads) = self.intra_threads { if let Some(threads) = self.intra_threads {
builder = builder builder = builder
@@ -99,7 +83,7 @@ impl Loader for ModelLoader {
.commit_from_file(path_ref) .commit_from_file(path_ref)
.map_err(|e| ParseError::Path(path_ref.display().to_string(), e))?; .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! 使用) /// 策略 B从内存字节流加载模型配合 include_bytes! 使用)
fn build_from_bytes(&self, model_bytes: &[u8]) -> Result<Session> { fn build_from_bytes(&self, model_bytes: &[u8]) -> Result<Session> {
@@ -112,3 +96,36 @@ impl Loader for ModelLoader {
Ok(Arc::new(Mutex::new(session))) 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 crate::types::Session;
use ddddocr_core::ModelMetadata; use ddddocr_core::ModelMetadata;
use ddddocr_core::OcrOutput; 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::traits::{InferenceEngine, Info, OcrEngine};
use ddddocr_core::types::{AxisDim, ModelInfo, TensorInfo, TensorType}; use ddddocr_core::types::{AxisDim, ModelInfo, TensorInfo, TensorType};
use ddddocr_core::utils::normalize_ocr_logits; use ddddocr_core::utils::normalize_ocr_logits;
use ort::inputs; use ort::value::{Outlet, TensorElementType, ValueType};
use ort::value::{TensorElementType, TensorRef}; use tracing::debug;
use std::sync::Mutex;
// 引入核心层的统一错误类型
/// 明确命名为 AxisDim代表模型某一个轴的维度特征
// #[derive(Clone, PartialEq, Eq)]
// pub enum AxisDim {
// /// 静态固定维度(如通道数固定为 1高度固定为 64
// Static(usize),
// /// 动态符号维度(如宽度是动态的 "image_width"
// Dynamic(String),
// }
// impl AxisDim { /// OCR 推理运行时:持有 ORT 会话与模型元数据,输出 [`OcrOutput`]。
// /// 便捷方法:判断是否为动态维度
// 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>>,
// }
pub struct OcrRuntime { pub struct OcrRuntime {
/// ORT 会话句柄。
pub session: Session, pub session: Session,
/// 模型元数据(字符集、归一化策略等)。
pub metadata: ModelMetadata, pub metadata: ModelMetadata,
} }
impl OcrRuntime { impl OcrRuntime {
/// 基于已构建的会话与元数据创建 OCR 运行时。
pub fn new(session: Session, metadata: ModelMetadata) -> Self { pub fn new(session: Session, metadata: ModelMetadata) -> Self {
Self { session, metadata } 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 { impl OcrEngine for OcrRuntime {
fn metadata(&self) -> &ModelMetadata { fn metadata(&self) -> &ModelMetadata {
&self.metadata &self.metadata
} }
} }
impl InferenceEngine for OcrRuntime { impl InferenceEngine for OcrRuntime {
type Output = OcrOutput; 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 fn inference(&self, input_array: ndarray::Array4<f32>) -> Result<Self::Output, TensorError> {
.run(inputs![TensorRef::from_array_view(&input_array).map_err( let mut session_guard = lock_session(&self.session)?;
|e| TensorError::Engine(format!("构建输入失败: {e}")) let result = run_session(&mut session_guard, &input_array)?;
)?]) debug!("模型输出原始数据: {:?}", result);
.map_err(|e| TensorError::Engine(format!("执行模型推理失败: {e}")))?;
// .context("执行模型推理失败")?;
println!("模型输出原始数据: {:?}", result);
// Ok(result.swap_remove(0).into_tensor())
let raw_value = &result[0]; let raw_value = &result[0];
match raw_value.dtype().tensor_type().unwrap() { match raw_value.dtype().tensor_type() {
TensorElementType::Int64 => { Some(TensorElementType::Int64) => {
let (array_d, slice) = raw_value let (view, actual_shape) = extract_tensor::<i64>(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
let array1 = view let array1 = view
.to_owned() .to_owned()
.into_dimensionality::<ndarray::Ix1>() .into_dimensionality::<ndarray::Ix1>()
@@ -111,40 +91,98 @@ impl InferenceEngine for OcrRuntime {
})?; })?;
Ok(OcrOutput::Indices(array1)) Ok(OcrOutput::Indices(array1))
} }
TensorElementType::Float32 => { Some(TensorElementType::Float32) => {
let shape = raw_value.shape(); let shape = raw_value.shape();
println!("模型输出shape数据: {:?}", shape); debug!("模型输出 shape 数据: {:?}", shape);
// raw_tensor.to_plain_array_view() let (view, shape_vec) = extract_tensor::<f32>(raw_value)?;
let (shape_ref, slice) = raw_value normalize_ocr_logits(view, shape_vec.as_slice())
.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)
} }
_ => Err( _ => Err(TensorError::UnknownOutputFormat),
// anyhow::anyhow!("不支持的模型输出数据类型: {:?}",raw_tensor.datum_type())
TensorError::UnknownOutputFormat,
),
} }
} }
} }
impl Info for OcrRuntime { impl Info for OcrRuntime {
fn input_info(&self) -> Result<Vec<TensorInfo>> { 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>> { 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> { 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 ort::session::Session as OrtSession;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
/// ORT 会话句柄:由 [`crate::loader::ModelLoader`] 构建,推理时通过互斥锁串行访问。
pub type Session = Arc<Mutex<OrtSession>>; 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);
}

View File

@@ -1,26 +0,0 @@
[package]
name = "ddddocr-tract"
version = { workspace = true }
edition = { workspace = true }
license = { workspace = true }
[dependencies]
ddddocr-core = { path = "../ddddocr-core" } # 引入兄弟库
tract-onnx = { workspace = true }
tract-linalg = {workspace = true }
ndarray = { workspace = true } # 继承自工作空间
image = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
anyhow = { workspace = true }
thiserror = { workspace = true } # 刚好可以开始接入你需要的标准库错误处理
[features]
default = []
embed-models = [] # 这是一个留给有特殊需求、且自己下载了模型放入 models/ 目录的人的后门

View File

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

View File

@@ -1,52 +0,0 @@
use crate::types::Session;
use ddddocr_core::error::{Result, TensorError};
use ddddocr_core::{ DetOutput};
use ddddocr_core::traits::{DetEngine, InferenceEngine};
use ndarray::Ix3;
use tract_onnx::prelude::*;
#[derive(Debug)]
pub struct DetRuntime {
pub session: Session,
}
impl DetRuntime {
pub fn new(session: Session) -> Self {
Self { session }
}
}
impl InferenceEngine for DetRuntime {
type Output = DetOutput; // 明确绑定 OCR 小枚举
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 result = self
.session
.run(tvec!(tensor.into()))
.map_err(|_| TensorError::Engine("执行模型推理失败".to_string()))?;
println!("模型输出原始数据: {:?}", result);
// Ok(result.swap_remove(0).into_tensor())
let raw_tensor = result.swap_remove(0).into_tensor();
// raw_tensor.into_plain_array()?
let array_d = raw_tensor.into_plain_array::<f32>().map_err(|_| {
TensorError::Engine("Tract 实体张量无法转换为 ndarray::ArrayD".to_string())
})?;
// 提前利用克隆(Clone)备份好当前未转维度前的真实 shape (Vec<usize>)
let actual_shape = array_d.shape().to_vec();
let array3 = array_d.into_dimensionality::<Ix3>().map_err(|_| {
TensorError::DimensionMismatch {
expected: "3D 检测矩阵 [Batch, Box_Count, Box_Attributes]".to_string(),
actual: actual_shape, // 优雅降维失败时动态捕获
}
})?;
Ok(DetOutput::Detection(array3))
// 在引擎内部消化掉 DatumType 强耦合
}
}
impl DetEngine for DetRuntime {}

View File

@@ -1,8 +0,0 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum TensorError {
/// 替换原有的 anyhow::Error明确将 Tract/ONNX 引擎底层报错序列化为干净的 String
#[error("推理引擎内部发生异常: {0}")]
Engine(String),
}

View File

@@ -1,11 +0,0 @@
mod det;
mod error;
pub mod loader;
mod ocr;
mod types;
pub use ddddocr_core::{
DetectionResult, Detector, ModelMetadata, Normalization, Ocr, OcrBuilder, SlideResult, Slider,
};
pub use det::session::DetRuntime;
pub use ocr::session::OcrRuntime;

View File

@@ -1,153 +0,0 @@
use crate::types::Session;
use ddddocr_core::ModelMetadata;
use ddddocr_core::OcrOutput;
use ddddocr_core::error::{DdddError, 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 tract_onnx::prelude::{DatumType, OutletId, ShapeFact, TypedModel};
use tract_onnx::prelude::{IntoTensor, Tensor, tvec};
pub struct OcrRuntime {
pub session: Session,
pub metadata: ModelMetadata,
}
impl OcrRuntime {
pub fn new(session: Session, metadata: ModelMetadata) -> Self {
Self { session, metadata }
}
/// 获取模型输入的节点信息列表
/// 提取出来的公共转换逻辑:将一组 OutletId 解析为 TensorInfo 列表
fn resolve_tensors(&self, model: &TypedModel, outlets: &[OutletId]) -> Result<Vec<TensorInfo>> {
outlets
.iter()
.map(|&outlet_id| {
let fact = model.outlet_fact(outlet_id).map_err(DdddError::new)?;
// .map_err(|e| {
// DdddError::InternalError(format!("解析节点 Fact 失败: {:?}", e))
// })?;
let shape = self.resolve_shape(&fact.shape);
let node_name = model.node(outlet_id.node).name.clone();
let tensor_type = match fact.datum_type {
DatumType::F32 => TensorType::F32,
DatumType::I64 => TensorType::I64,
_ => TensorType::Other,
};
Ok(TensorInfo {
name: node_name,
shape,
tensor_type,
})
})
.collect() // 函数式声明:自动传播第一处发生的错误
}
/// 安全还原 Tract 维度至 Vec<AxisDim>
fn resolve_shape(&self, shape_fact: &ShapeFact) -> Vec<AxisDim> {
let tract_shape = shape_fact.to_tvec();
let resolved = tract_shape
.iter()
.map(|dim| {
// 防御性编程:必须同时满足能够转换为 i64 且 大于等于 0
if let Ok(size) = dim.to_i64() {
if size >= 0 {
AxisDim::Static(size as usize)
} else {
// 如果 ONNX 导出时某些动态维度被标记为了 -1安全地作为动态符号捕获
AxisDim::Dynamic(dim.to_string())
}
} else {
AxisDim::Dynamic(dim.to_string())
}
})
.collect();
resolved
}
}
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 result = self
.session
.run(tvec!(tensor.into()))
.map_err(|_| TensorError::Engine("执行模型推理失败".to_string()))?;
// .context("执行模型推理失败")?;
println!("模型输出原始数据: {:?}", result);
// Ok(result.swap_remove(0).into_tensor())
let raw_tensor = result.swap_remove(0).into_tensor();
// 在引擎内部消化掉 DatumType 强耦合
match raw_tensor.datum_type() {
DatumType::I64 => {
let array_d = raw_tensor
.into_plain_array::<i64>()
.map_err(|_| TensorError::Engine("Tract 无法获取 i64 内存视图".to_string()))?;
// .context("Tract 无法获取 i64 内存视图")?;
// 🌟 提前提取真实维度
let actual_shape = array_d.shape().to_vec();
// 转成标准的 Array1 传给 core
let array1 = array_d
.to_owned()
.into_dimensionality::<ndarray::Ix1>()
.map_err(|_| TensorError::DimensionMismatch {
expected: "1D 字符索引静态矩阵".to_string(),
actual: actual_shape,
})?;
Ok(OcrOutput::Indices(array1))
}
DatumType::F32 => {
let shape = raw_tensor.shape();
println!("模型输出shape数据: {:?}", shape);
// raw_tensor.to_plain_array_view()
let view = raw_tensor
.to_plain_array_view::<f32>()
.map_err(|_| TensorError::Engine("Tract 无法获取 f32 内存视图".to_string()))?;
// 1. 极其纯粹的、无拷贝的多维 Shape 压扁清洗
normalize_ocr_logits(view, shape)
}
_ => Err(
// anyhow::anyhow!("不支持的模型输出数据类型: {:?}",raw_tensor.datum_type())
TensorError::UnknownOutputFormat,
),
}
}
}
impl Info for OcrRuntime {
fn input_info(&self) -> Result<Vec<TensorInfo>> {
let model = self.session.model();
let outlets = model.input_outlets().map_err(DdddError::new)?;
self.resolve_tensors(model, outlets)
}
/// 获取模型输出的节点信息列表
fn output_info(&self) -> Result<Vec<TensorInfo>> {
let model = self.session.model();
let outlets = model.output_outlets().map_err(DdddError::new)?;
self.resolve_tensors(model, outlets)
}
/// 获取模型详细元数据信息(对标 Python ddddocr 的 get_model_info
/// 完美包容 [1, 1, 64, image_width] 这样的变长图像模型
/// 获取模型详细元数据信息(代码更紧凑、优雅)
fn model_info(&self) -> Result<ModelInfo> {
Ok(ModelInfo {
inputs: self.input_info()?,
outputs: self.output_info()?,
providers: None,
})
}
}

View File

@@ -1,4 +0,0 @@
use std::sync::Arc;
use tract_onnx::prelude::TypedRunnableModel;
pub type Session = Arc<TypedRunnableModel>;

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

@@ -1,251 +0,0 @@
use anyhow::Context;
use ddddocr_core::traits::Loader;
use ddddocr_tract::{DetectionResult, Ocr};
use ddddocr_tract::{Detector, ModelMetadata, Normalization, Slider};
// 假设你的包名是这个
use ddddocr_tract::{DetRuntime, 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_tract::loader::ModelLoader as TractModelLoader;
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 = TractModelLoader::default()
.build_for_path("D:\\CNWei\\CNW\\Rust\\ddddocr-rs\\models\\common_sml2h3_f32.onnx")
.expect("模型加载失败");
let metadata = ModelMetadata::from_static_slice(
CHARSET_BETA,
false,
Resize::DynamicWidth(64),
1,
Normalization::MinusOneToOne,
);
// 1. 初始化模型
let ocr_runtime = 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_runtime)
// .predict(&img)
// .expect("识别过程出错")
// .into_text();
let result = Ocr::builder()
.build_with(&ocr_runtime)
.predict(&img)
.expect("识别过程出错")
.into_text();
println!("识别结果: {}", result);
assert!(!result.is_empty());
}
#[test]
fn test_det_load() -> anyhow::Result<()> {
let det_model = TractModelLoader::default()
.build_for_path("D:\\CNWei\\CNW\\Rust\\ddddocr-rs\\models\\common_det.onnx")
.expect("模型加载失败");
let det = DetRuntime::new(det_model);
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 = TractModelLoader::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("建立测试模型图失败");
println!("{:?}", loader.model().inputs);
}

22
ddddocr-tract2/Cargo.toml Normal file
View File

@@ -0,0 +1,22 @@
[package]
name = "ddddocr-tract2"
version = { workspace = true }
edition = { workspace = true }
license = { workspace = true }
description = "ddddocr-rs 的 Tract 推理引擎实现"
keywords = ["ocr", "captcha", "ddddocr", "onnxruntime", "tract"]
categories = ["multimedia::images", "computer-vision"]
# repository = "https://github.com/<用户名>/<仓库名>" # 发布前请补充
readme = "../README.md"
[dependencies]
ddddocr-core = { path = "../ddddocr-core", version = "0.2.4" }
tract-onnx = { workspace = true }
tract-linalg = { workspace = true }
ndarray = { workspace = true }
image = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
anyhow = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }

View File

@@ -0,0 +1,44 @@
use crate::runtime::{extract_plain_array, 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 tracing::debug;
use tract_onnx::prelude::*;
#[derive(Debug)]
/// 目标检测推理运行时:持有 Tract 会话,输出 [`DetOutput`]。
pub struct DetRuntime {
/// Tract 会话句柄。
pub session: Session,
}
impl DetRuntime {
/// 基于已构建的会话创建检测运行时。
pub fn new(session: Session) -> Self {
Self { session }
}
}
impl InferenceEngine for DetRuntime {
type Output = DetOutput;
fn inference(&self, input_array: ndarray::Array4<f32>) -> Result<Self::Output, TensorError> {
let mut result = run_session(&self.session, input_array)?;
debug!("模型输出原始数据: {:?}", result);
let raw_tensor = result.swap_remove(0).into_tensor();
let array_d = extract_plain_array::<f32>(raw_tensor)?;
let actual_shape = array_d.shape().to_vec();
let array3 =
array_d
.into_dimensionality::<Ix3>()
.map_err(|_| TensorError::DimensionMismatch {
expected: "3D 检测矩阵 [Batch, Box_Count, Box_Attributes]".to_string(),
actual: actual_shape,
})?;
Ok(DetOutput::Detection(array3))
}
}
impl DetEngine for DetRuntime {}

22
ddddocr-tract2/src/lib.rs Normal file
View File

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

View File

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

View File

@@ -1,6 +1,8 @@
use tract_onnx::prelude::TractError; use tract_onnx::prelude::TractError;
/// 模型加载与解析的通用结果类型。
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]
/// 模型加载、解析与 Session 构建阶段的错误。
pub enum Error { pub enum Error {
/// 解析 ONNX 模型/路径失败(如文件损坏、算子不支持、路径非法) /// 解析 ONNX 模型/路径失败(如文件损坏、算子不支持、路径非法)
#[error("解析 ONNX 模型结构失败: {0}")] #[error("解析 ONNX 模型结构失败: {0}")]
@@ -22,6 +24,7 @@ pub enum Error {
#[error("Metadata 字节流不是合法的 UTF-8 编码: {0}")] #[error("Metadata 字节流不是合法的 UTF-8 编码: {0}")]
InvalidUtf8(#[from] std::str::Utf8Error), InvalidUtf8(#[from] std::str::Utf8Error),
/// 模型元数据内容解析失败。
#[error("模型元数据解析失败: {0}")] #[error("模型元数据解析失败: {0}")]
MetadataParse(String), MetadataParse(String),
@@ -38,8 +41,9 @@ impl Error {
Self::Other(msg.into(), err.into()) Self::Other(msg.into(), err.into())
} }
} }
#[derive(thiserror::Error,Debug)] #[derive(thiserror::Error, Debug)]
pub enum ParseError{ /// 从路径或字节流解析 ONNX 模型失败的错误。
pub enum ParseError {
/// 策略 A从文件路径加载失败附带路径上下文信息方便排查是找不到文件还是格式不对 /// 策略 A从文件路径加载失败附带路径上下文信息方便排查是找不到文件还是格式不对
#[error("从路径 '{0}' 加载 ONNX 模型失败: {1}")] #[error("从路径 '{0}' 加载 ONNX 模型失败: {1}")]
Path(String, #[source] TractError), Path(String, #[source] TractError),
@@ -48,3 +52,31 @@ pub enum ParseError{
#[error("从内存字节流解析 ONNX 模型失败: {0}")] #[error("从内存字节流解析 ONNX 模型失败: {0}")]
Bytes(#[source] TractError), Bytes(#[source] TractError),
} }
#[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 invalid_utf8_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

@@ -8,6 +8,7 @@ use std::borrow::Cow;
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "snake_case")] // 支持 json 中写 "zero_to_one" 或 "minus_one_to_one" #[serde(rename_all = "snake_case")] // 支持 json 中写 "zero_to_one" 或 "minus_one_to_one"
/// 归一化策略的 JSON 反序列化中间表示。
pub enum NormalizationDto { pub enum NormalizationDto {
/// 映射到 [0.0, 1.0] -> pixel / 255.0 /// 映射到 [0.0, 1.0] -> pixel / 255.0
ZeroToOne, ZeroToOne,
@@ -41,8 +42,9 @@ fn default_normalization() -> NormalizationDto {
NormalizationDto::ZeroToOne NormalizationDto::ZeroToOne
} }
/// Tract 专属扩展trait 或 工具函数 /// 从 JSON 字符串或字节流解析模型元数据的扩展接口。
pub trait Metadata: Sized { pub trait Metadata: Sized {
/// 从 JSON 字符串解析模型元数据。
fn from_json_str(json_str: &str) -> Result<Self>; fn from_json_str(json_str: &str) -> Result<Self>;
/// 机制 2从内存字节流加载极大地方便 include_bytes! 或网络下载) /// 机制 2从内存字节流加载极大地方便 include_bytes! 或网络下载)
fn from_json_bytes(bytes: &[u8]) -> Result<Self> { fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
@@ -56,8 +58,7 @@ impl Metadata for ModelMetadata {
let dto: ModelMetadataDto = serde_json::from_str(json_str)?; let dto: ModelMetadataDto = serde_json::from_str(json_str)?;
// 1. 将 DTO 的字符串数组转化为强类型的 Charset // 1. 将 DTO 的字符串数组转化为强类型的 Charset
let tokens: Vec<Cow<'static, str>> = let tokens: Vec<Cow<'static, str>> = dto.charset.into_iter().map(Cow::Owned).collect();
dto.charset.into_iter().map(|s| Cow::Owned(s)).collect();
let charset = Charset::new(tokens); let charset = Charset::new(tokens);
// 2. 解析 resize 策略(重现 Python 的复杂条件判断) // 2. 解析 resize 策略(重现 Python 的复杂条件判断)
@@ -91,3 +92,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

@@ -46,13 +46,10 @@ impl Loader for ModelLoader {
let session = onnx() let session = onnx()
.model_for_path(path_ref) .model_for_path(path_ref)
.map_err(|e| ParseError::Path(path_ref.display().to_string(), e))? .map_err(|e| ParseError::Path(path_ref.display().to_string(), e))?
// .with_context(|| "加载 ONNX 模型失败,请检查路径是否正确")?
.into_optimized() .into_optimized()
.map_err(Error::OptimizationFailed)? .map_err(Error::OptimizationFailed)?
// .with_context(|| "优化 Tract 模型图失败")?
.into_runnable() .into_runnable()
.map_err(Error::RunnableBuildFailed)?; .map_err(Error::RunnableBuildFailed)?;
// .with_context(|| "构建可运行 Tract 实例失败")?;
Ok(session) Ok(session)
} }
/// 策略 B从内存字节流加载模型配合 include_bytes! 使用) /// 策略 B从内存字节流加载模型配合 include_bytes! 使用)
@@ -64,13 +61,10 @@ impl Loader for ModelLoader {
let session = onnx() let session = onnx()
.model_for_read(&mut cursor) .model_for_read(&mut cursor)
.map_err(ParseError::Bytes)? .map_err(ParseError::Bytes)?
// .with_context(|| "从内存字节流解析 ONNX 模型失败")?
.into_optimized() .into_optimized()
.map_err(Error::OptimizationFailed)? .map_err(Error::OptimizationFailed)?
// .with_context(|| "优化 Tract 模型图失败")?
.into_runnable() .into_runnable()
.map_err(Error::RunnableBuildFailed)?; .map_err(Error::RunnableBuildFailed)?;
// .with_context(|| "构建可运行 Tract 实例失败")?;
Ok(session) Ok(session)
} }
@@ -80,48 +74,22 @@ impl Loader for ModelLoader {
mod tests { mod tests {
use super::*; use super::*;
/// 辅助函数:动态构建一个简单的 ONNX/Tract 内存模型图用于测试 #[test]
fn create_test_model() -> std::result::Result<Session, anyhow::Error> { fn default_config() {
let mut rect = TypedModel::default(); let loader = ModelLoader::default();
assert!(loader.num_threads.is_none());
// 0.21.10 最稳妥的静态 Fact 构建
let input_fact = TypedFact::dt_shape(DatumType::F32, &[1, 3, 224, 224]);
let input_node = rect
.add_source("input", input_fact)
.map_err(|e| anyhow::anyhow!("{:?}", e))?;
rect.set_input_outlets(&[input_node.into()])
.map_err(|e| anyhow::anyhow!("{:?}", e))?;
let typed = rect
.into_optimized()
.map_err(|e| anyhow::anyhow!("{:?}", e))?;
let runnable = typed
.into_runnable()
.map_err(|e| anyhow::anyhow!("{:?}", e))?;
Ok(runnable)
} }
// #[test] #[test]
// fn test_input_output_shapes_and_type() { fn builder_configures_threads() {
// let session = create_test_model().expect("建立测试模型图失败"); let loader = ModelLoader::default().num_threads(4);
// assert_eq!(loader.num_threads, Some(4));
// println!("{:?}", ModelLoader::model_info(&session).unwrap()); }
// // 1. 测试输入维度解析
// } #[test]
// fn builder_is_chainable_and_immutable() {
// #[test] let base = ModelLoader::default();
// fn test_resolve_shape_logic_direct() { let _configured = base.clone().num_threads(8);
// // 创建一个哑 ModelLoader 实例session 用不上,因为我们直接测私有方法) assert!(base.num_threads.is_none());
// let session = create_test_model().expect("建立测试模型图失败"); }
//
// let dims: Vec<TDim> = vec![TDim::from(1), TDim::from(3), TDim::from(224)];
// // 方案二的精髓:我们直接利用已导出的 ShapeFact 来纯手工验证边界逻辑!
// // 1. 验证纯静态维度是否被正确还原
// let static_shape = ShapeFact::from_dims(dims);
//
// let res = ModelLoader
// ::resolve_shape(&static_shape);
// }
} }

View File

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

View File

@@ -0,0 +1,174 @@
use crate::runtime::{extract_plain_array, run_session};
use crate::types::Session;
use ddddocr_core::ModelMetadata;
use ddddocr_core::OcrOutput;
use ddddocr_core::error::{DdddError, 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 tracing::debug;
use tract_onnx::prelude::{DatumType, IntoTensor, OutletId, ShapeFact, TypedModel};
/// OCR 推理运行时:持有 Tract 会话与模型元数据,输出 [`OcrOutput`]。
pub struct OcrRuntime {
/// Tract 会话句柄。
pub session: Session,
/// 模型元数据(字符集、归一化策略等)。
pub metadata: ModelMetadata,
}
impl OcrRuntime {
/// 基于已构建的会话与元数据创建 OCR 运行时。
pub fn new(session: Session, metadata: ModelMetadata) -> Self {
Self { session, metadata }
}
/// 提取出来的公共转换逻辑:将一组 OutletId 解析为 TensorInfo 列表
fn resolve_tensors(&self, model: &TypedModel, outlets: &[OutletId]) -> Result<Vec<TensorInfo>> {
outlets
.iter()
.map(|&outlet_id| {
let fact = model.outlet_fact(outlet_id).map_err(DdddError::new)?;
let shape = resolve_shape(&fact.shape);
let node_name = model.node(outlet_id.node).name.clone();
let tensor_type = tensor_type_from_datum(fact.datum_type);
Ok(TensorInfo {
name: node_name,
shape,
tensor_type,
})
})
.collect() // 函数式声明:自动传播第一处发生的错误
}
}
/// 将 Tract 的 DatumType 映射为 core 的 [`TensorType`]。
fn tensor_type_from_datum(datum: DatumType) -> TensorType {
match datum {
DatumType::F32 => TensorType::F32,
DatumType::I64 => TensorType::I64,
_ => TensorType::Other,
}
}
/// 安全还原 Tract 维度至 [`AxisDim`] 列表。
fn resolve_shape(shape_fact: &ShapeFact) -> Vec<AxisDim> {
shape_fact
.to_tvec()
.iter()
.map(|dim| {
// 防御性编程:必须同时满足能够转换为 i64 且 大于等于 0
if let Ok(size) = dim.to_i64() {
if size >= 0 {
AxisDim::Static(size as usize)
} else {
// 如果 ONNX 导出时某些动态维度被标记为了 -1安全地作为动态符号捕获
AxisDim::Dynamic(dim.to_string())
}
} else {
AxisDim::Dynamic(dim.to_string())
}
})
.collect()
}
impl OcrEngine for OcrRuntime {
fn metadata(&self) -> &ModelMetadata {
&self.metadata
}
}
impl InferenceEngine for OcrRuntime {
type Output = OcrOutput;
fn inference(&self, input_array: ndarray::Array4<f32>) -> Result<Self::Output, TensorError> {
let mut result = run_session(&self.session, input_array)?;
debug!("模型输出原始数据: {:?}", result);
let raw_tensor = result.swap_remove(0).into_tensor();
match raw_tensor.datum_type() {
DatumType::I64 => {
let array_d = extract_plain_array::<i64>(raw_tensor)?;
let actual_shape = array_d.shape().to_vec();
let array1 = array_d.into_dimensionality::<ndarray::Ix1>().map_err(|_| {
TensorError::DimensionMismatch {
expected: "1D 字符索引静态矩阵".to_string(),
actual: actual_shape,
}
})?;
Ok(OcrOutput::Indices(array1))
}
DatumType::F32 => {
let shape = raw_tensor.shape().to_vec();
debug!("模型输出 shape 数据: {:?}", shape);
let array = extract_plain_array::<f32>(raw_tensor)?;
normalize_ocr_logits(array.view(), array.shape())
}
_ => Err(TensorError::UnknownOutputFormat),
}
}
}
impl Info for OcrRuntime {
fn input_info(&self) -> Result<Vec<TensorInfo>> {
let model = self.session.model();
let outlets = model.input_outlets().map_err(DdddError::new)?;
self.resolve_tensors(model, outlets)
}
/// 获取模型输出的节点信息列表
fn output_info(&self) -> Result<Vec<TensorInfo>> {
let model = self.session.model();
let outlets = model.output_outlets().map_err(DdddError::new)?;
self.resolve_tensors(model, outlets)
}
/// 获取模型详细元数据信息(对标 Python ddddocr 的 get_model_info
/// 完美包容 [1, 1, 64, image_width] 这样的变长图像模型
/// 获取模型详细元数据信息(代码更紧凑、优雅)
fn model_info(&self) -> Result<ModelInfo> {
Ok(ModelInfo {
inputs: self.input_info()?,
outputs: self.output_info()?,
providers: None,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use tract_onnx::prelude::*;
#[test]
fn maps_datum_types() {
assert!(matches!(
tensor_type_from_datum(DatumType::F32),
TensorType::F32
));
assert!(matches!(
tensor_type_from_datum(DatumType::I64),
TensorType::I64
));
assert!(matches!(
tensor_type_from_datum(DatumType::U8),
TensorType::Other
));
}
#[test]
fn resolves_static_shape() {
let fact = ShapeFact::from_dims(vec![TDim::from(1), TDim::from(64)]);
assert_eq!(
resolve_shape(&fact),
vec![AxisDim::Static(1), AxisDim::Static(64)]
);
}
#[test]
fn resolves_dynamic_dimension_as_symbol() {
let scope = SymbolScope::default();
let dims = vec![TDim::from(1), TDim::from(64), scope.sym("width").into()];
let fact = ShapeFact::from_dims(dims);
let shape = resolve_shape(&fact);
assert_eq!(shape[0], AxisDim::Static(1));
assert_eq!(shape[1], AxisDim::Static(64));
assert!(matches!(&shape[2], AxisDim::Dynamic(_)));
}
}

View File

@@ -0,0 +1,25 @@
//! 会话执行相关的共享工具函数。
use crate::types::Session;
use ddddocr_core::error::TensorError;
use tract_onnx::prelude::{Datum, TValue, TVec, Tensor, tvec};
/// 对输入张量执行一次 Tract 推理,返回原始输出值列表。
pub(crate) fn run_session(
session: &Session,
input_array: ndarray::Array4<f32>,
) -> Result<TVec<TValue>, TensorError> {
let tensor = Tensor::from(input_array);
session
.run(tvec!(tensor.into()))
.map_err(|e| TensorError::Engine(format!("执行模型推理失败: {e}")))
}
/// 将 Tensor 转换为 ndarray 的 `ArrayD`。
pub(crate) fn extract_plain_array<D: Datum>(
tensor: Tensor,
) -> Result<ndarray::ArrayD<D>, TensorError> {
tensor
.into_plain_array::<D>()
.map_err(|_| TensorError::Engine("无法获取张量内存视图".to_string()))
}

View File

@@ -0,0 +1,7 @@
//! Tract 会话共享类型。
use std::sync::Arc;
use tract_onnx::prelude::TypedRunnableModel;
/// Tract 会话句柄:由 [`crate::loader::ModelLoader`] 构建,可直接并发执行推理。
pub type Session = Arc<TypedRunnableModel>;

View File

@@ -0,0 +1,74 @@
//! 外部视角 API 测试:验证 `ddddocr-tract2` 的公开类型与方法在外部 crate 中可正常使用。
use ddddocr_core::Resize;
use ddddocr_core::traits::{Info, Loader};
use ddddocr_core::types::AxisDim;
use ddddocr_tract2::loader::ModelLoader;
use ddddocr_tract2::{
DetRuntime, ModelMetadata, Normalization, OcrBuilder, OcrRuntime, Session, SlideResult, Slider,
};
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().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

@@ -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))
}

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_tract2::DetRuntime;
use ddddocr_tract2::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(())
}

View File

@@ -0,0 +1,55 @@
//! OCR 识别与模型信息集成测试。
mod common;
use common::{model_path, sample_path};
use ddddocr_core::traits::{Info, Loader};
use ddddocr_core::{ModelMetadata, Normalization, Ocr, Resize};
use ddddocr_tract2::OcrRuntime;
use ddddocr_tract2::loader::ModelLoader;
/// 用官方 sml2h3 f32 模型识别验证码图片,结果不应为空。
#[test]
fn ocr_classification_recognizes_code_image() {
let session = ModelLoader::default()
.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

@@ -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);
}

View File

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 94 KiB

View File

Before

Width:  |  Height:  |  Size: 8.0 KiB

After

Width:  |  Height:  |  Size: 8.0 KiB

View File

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

View File

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 8.3 KiB