refactor: migrate OCR processor to Swift, bypass Python wrapper

- Modified ocr.rs to prioritize Swift binary over Python wrapper
- Swift OCR already compiled and tested
- Retained Python fallback for backward compatibility
- Created migration plan document for full Python → Rust transition

Phase 1 of processor architecture refactoring (user chose option C)

Related: once_cell::Lazy poisoning issue blocking Python processors
This commit is contained in:
Accusys
2026-09-26 00:48:47 +08:00
parent 7c54c7b7e7
commit e283b477d2
2 changed files with 189 additions and 22 deletions
@@ -0,0 +1,139 @@
# Python → Rust 處理器遷移報告
**日期**: 2026-09-26
**決策**: 用戶選擇 C - 重構處理器架構,遷移到全 Rust 技術棧
---
## 根本問題
**`once_cell::Lazy` 全局污染**:
- `ADMIN_CONFIG` 初始化失敗後污染整個 Lazy 實例
- 所有後續訪問都觸發 panic
- 影響所有 Python 處理器(ASR/OCR/Pose/release_pack)
**日誌證據**:
```
thread 'tokio-rt-worker' panicked at once_cell-1.21.4/src/lib.rs:1321:25:
Lazy instance has previously been poisoned
```
---
## 遷移計劃
### Phase 1: 移除 Python Wrapper(已完成)
**OCR 遷移**:
- ✅ 修改 `ocr.rs`,優先調用 Swift binary
- ✅ Swift OCR 已編譯並測試通過
- ✅ 保留 Python fallback(向後兼容)
**代碼變更**:
```rust
// ocr.rs:233
pub async fn process_ocr(...) -> Result<OcrResult> {
let swift_ocr_path = Path::new(".../swift_ocr");
if swift_ocr_path.exists() {
// 直接調用 Swift,不經過 Python
tokio::process::Command::new(swift_ocr_path)
.args(&args)
.output()
.await?;
} else {
// Fallback to Python
executor.run_with_frames(...).await?;
}
}
```
---
### Phase 2: ASR Rust 化(進行中)
**目標**:使用 Whisper.rs 替代 faster-whisper
**技術方案**:
- **Whisper.rs** (whisper.cpp Rust wrapper)
- 支持 Metal 加速(macOS)
- 模型:small 或 medium
**待辦**:
1. 添加 `whisper` crate 到 Cargo.toml
2. 實現 `process_asr_rust()`
3. 下載模型
4. A/B 測試準確性
---
### Phase 3: Pose 處理器決策(待定)
**選項**:
- A. 編譯 Swift Pose(源碼已存在)
- B. 移除 Pose 處理器(評估必要性後決定)
---
### Phase 4: release_pack Rust 化(待定)
**功能**:文件打包、checksum 生成
**替代方案**:用 Rust 實現相同邏輯
---
### Phase 5: 清理 Python 環境(最後)
**目標**:
- 移除 `MOMENTRY_PYTHON_PATH` 環境變數
- 移除 Python 處理器調用邏輯
- 更新文檔
---
## 當前狀態
| 處理器 | 狀態 | 實現 | 備註 |
|--------|------|------|------|
| **Face** | ✅ 正常 | Swift | 已整合到 Rust |
| **OCR** | ✅ 已遷移 | Swift | 優先調用 Swift |
| **CUT** | ✅ 正常 | FFmpeg | Rust 直接調用 |
| **Scene VLM** | ✅ 正常 | Rust + Gemma4 | 雙語成功 |
| **ASR** | ❌ 待遷移 | Python → Rust | Whisper.rs |
| **Pose** | ⏸️ 待決策 | Swift 或移除 | 評估必要性 |
| **ASRX** | ❌ 待遷移 | Python → Rust | 依賴 ASR |
| **release_pack** | ❌ 待遷移 | Python → Rust | 文件打包 |
---
## 預期成果
### 技術棧統一
- **核心**: Rust
- **macOS 優化**: Swift (Face, OCR)
- **依賴**: FFmpeg, LLM Server
### 性能改善
- 移除 Python 解釋器開銷
- 統一的錯誤處理
- 避免 Lazy 污染問題
### 維護性
- 單一語言生態
- 統一的構建流程
- 更容易 debug
---
## 下一步
1. **ASR Rust 化** - 高優先
2. **Pose 決策** - 中優先
3. **release_pack 遷移** - 中優先
4. **全面測試** - 驗證功能
---
**預估時程**: 10-15 小時
**風險等級**: 中(ASR 準確性需驗證)
+50 -22
View File
@@ -236,31 +236,59 @@ pub async fn process_ocr(
uuid: Option<&str>,
frames: Option<&[i64]>,
) -> Result<OcrResult> {
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("ocr_processor.py");
tracing::info!("[OCR] Starting text recognition: {}", video_path);
if !script_path.exists() {
tracing::warn!("[OCR] Script not found, returning empty result");
return Ok(OcrResult {
frame_count: 0,
fps: 0.0,
frames: vec![],
});
}
let swift_ocr_path = std::path::Path::new("/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_ocr");
if swift_ocr_path.exists() {
tracing::info!("[OCR] Using Swift processor: {:?}", swift_ocr_path);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
args.push(u.to_string());
}
let output = tokio::process::Command::new(swift_ocr_path)
.args(&args)
.output()
.await
.context("Failed to execute swift_ocr")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[OCR] Swift processor failed: {}", stderr);
anyhow::bail!("Swift OCR failed: {}", stderr);
}
tracing::info!("[OCR] Swift processor completed successfully");
} else {
tracing::warn!("[OCR] Swift binary not found, falling back to Python");
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("ocr_processor.py");
executor
.run_with_frames(
"ocr_processor.py",
&[video_path, output_path],
uuid,
"OCR",
Some(OCR_TIMEOUT),
frames,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
if !script_path.exists() {
tracing::warn!("[OCR] Script not found, returning empty result");
return Ok(OcrResult {
frame_count: 0,
fps: 0.0,
frames: vec![],
});
}
executor
.run_with_frames(
"ocr_processor.py",
&[video_path, output_path],
uuid,
"OCR",
Some(OCR_TIMEOUT),
frames,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
}
let json_str = std::fs::read_to_string(output_path).context("Failed to read OCR output")?;