Files
momentry_core/docs_v1.0/DESIGN/PythonToRustProcessorMigration.md
T
Accusys 31d1b4050f fix: correct face detection threshold defaults
- Changed min_confidence from 50.0 to 0.5 (Vision uses 0.0-1.0 range)
- Changed min_size from 32 to 1 (was filtering out all small faces)
- Changed min_capture_quality from 25.0 to 0.25
- Fixes issue where all videos showed 0 faces detected

Root cause: admin_config.rs used wrong defaults (50.0/32) instead of
config.rs constants (0.5/1), causing Vision framework to filter out
ALL faces because confidence threshold exceeded valid range.

Verified: IMG_9449 now correctly detects 191 faces (was 0).
2026-09-18 02:42:21 +08:00

13 KiB
Raw Blame History

document_type, service, title, date, version, status, owner, created_by, tags, ai_query_hints, related_documents
document_type service title date version status owner created_by tags ai_query_hints related_documents
design MOMENTRY_CORE Python → Rust Processor 遷移設計 2026-09-15 V1.0 active M5 OpenCode
processor
rust
migration
feasibility-assessment
rust-migration
Python processor 是否可以改寫成 Rust
Rust 版 processor 如何驗證效果與 Python 等同
facenet512 mlpackage 如何轉 ONNX
whisper-rs 如何取代 faster-whisper
agglomerative clustering 如何自建 Rust 實作
Rust processor 驗證門檻 A/B 測試
DESIGN/PythonToSwiftProcessorMigration.md
DESIGN/PROCESSOR_MECHANISMS_REVIEW.md
DESIGN/Processor_Refactoring_Assessment.md
REFERENCE/history/PROCESSORS/SPEECH/ASRX_SELF_IMPLEMENTATION_FEASIBILITY.md

Python → Rust Processor 遷移設計

項目 內容
建立者 OpenCode
建立時間 2026-09-15
文件版本 V1.0
目標讀者 developer, Core team
Scope 以 Rust 取代現行 Python processor scripts,驗證門檻:效果必須等同 Python 或更佳
Architecture Standalone Rust binaries(比照 swift_processors 模式),沿用 executor 既有機制

版本歷史

版本 日期 目的 操作人
V1.0 2026-09-15 建立 Python → Rust 遷移設計文件 OpenCode

1. 目標與核心原則

1.1 目標

以 Rust 取代現行 src/core/processor/*.rs 所呼叫的 Python processor scripts,移除或最小化 Python runtime 依賴。

1.2 核心原則(與 Swift 版的根本差異)

路線 原則 後果
Swift 版(已評估) 換模型(Apple Vision/Speech 取代 Python 模型) 準確度需重新驗證;ASRX 無 Apple 對應。故不可行/風險高
Rust 版(本文件) 不換模型、只換 runtime 使用相同模型與演算法,輸出可對齊,驗證成本低

換引擎(engine),不換模型(weights)。faster-whisper → whisper.cpp 載入同一個 Whisper 權重;coremltools 的 FaceNet512 → ONNX 載入同樣權重;cv2 演算法 → ndarray 實作相同公式。

1.3 ⛔ 驗證門檻(P0 Mandatory):效果等同 Python 或更佳

任何 Rust processor 未通過 A/B 對齊驗證前,不得取代 Python 版本。

# 門檻 驗收標準
1 同檔案 A/B 測試 同一支測試影片同時跑 Python 與 Rust 版,輸出 JSON 結構一致
2 數值容忍度 座標/confidence/分數等在容差內一致(建議 tolerance 見各 processor)
3 召回率不下降 detection 數量(frames/faces/persons/scenes)不得明顯少於 Python 版
4 無回歸 既有 integration test(若存在)與 Pipeline 驗證通過
5 效能不劣化 RTF/處理時間不得劣於 Python 版超過可接受範圍(預設 2x 內)

未過門檻的 Rust processor → 標記 experimental,主路徑維持 Python。


2. Rust library 對應表

Python library Rust 對應 crate 成熟度 備註
faster-whisper (CTranslate2) whisper-rs(whisper.cpp bindings) 🟢 同權重;需重寫 scene 分段與 resume
torch / torchvision candle 或 ort(ONNX Runtime) 🟢 candle 純 Rust;ort 效能佳
coremltools (.mlpackage) coremltools 先轉 ONNX,ort 載入 🟡 需一次性轉檔步驟
cv2 / numpy ndarray + image / imageproc / kmeans-ndarray 🟢 純數學運算
sklearn AgglomerativeClustering 無現成 crate → 自建 🔴 需自實作(見 §6.5)
ultralytics YOLO ort + yolov8n-pose.onnx 🟢 Ultralytics 官方 Rust example
transformers (CLIP) candle-clip 或 ONNX + ort 🟢/🟡
transformers (Moondream2) 無現成 Rust 支援 🔴 建議保留 Python
PaddleOCR ort + PaddleOCR ONNX(oar-ocr) 🟢 僅 fallback 用途
speechbrain ECAPA-TDNN 轉 ONNX + ort 🟡 語者 embedding
Silero VAD voice_activity_detector(ONNX) 🟢 ASRX VAD

環境前提

  • 部署機器為 macOS(M5Max128),ort 可選 CoreML/Metal 或 CPU EP。
  • Rust toolchain 已具備(cargo build 正常)。

3. 目標架構

3.1 概覽

src/core/processor/{name}.rs  (Rust 入口,維持不變)
        │
        ▼
   ProcessorExecutor        --or-->   RustProcessorRunner (新)
        │                              │
        ▼                              ▼
   python script (舊路徑)         standalone Rust binary
   ├─ 沿用 .tmp/.partial                ├─ scripts/rust_processors/{name}
   ├─ resume / retry                    └─ 輸出相同 JSON schema
   └─ SHA256 checksum

3.2 Standalone Rust binaries(與 swift_processors 同模式)

  • 新目錄:scripts/rust_processors/(Swift 版在 scripts/swift_processors/)。
  • 每個 processor 編譯為獨立 binary:rust_ocr、rust_pose、rust_asr、rust_appearance……
  • 呼叫介面與 Swift 對齊:[video_path, output_path, --sample-interval N, --uuid U, --frames ...]。
  • 輸出 JSON schema 與 Python 版完全一致(A/B 驗證的前提)。
  • 由 executor(或新的 RustExecutor)呼叫,沿用 .tmp → .json 提升、timeout、retry 機制。

3.3 模型檔案

模型 Python 來源 Rust 使用 轉檔需求
Whisper small faster-whisper (CTranslate2) whisper.cpp .ggml 格式 🟡 需下載/轉換 ggml 版權重
FaceNet512 models/facenet512.mlpackage ONNX 🟡 需轉檔
Places365 (scene) resnet18_places365.mlpackage ONNX 🟡 需轉檔
YOLOv8n-pose ultralytics .pt .onnx 🟢 官方支援 export
ECAPA-TDNN speechbrain(torch) ONNX 🟡 需轉檔
CLIP ViT-B/32 transformers ONNX / candle 🟡

轉檔機制:一次性的 scripts/model_export/ Python 工具(保留 Python 僅做轉檔,不需在 runtime 依賴)。


4. 逐 Processor 可行性與驗證標準

# Processor Python library Rust 方案 判定 驗證容忍度 關鍵工程點
P1 Appearance cv2/numpy (HSV + kmeans) ndarray + kmeans-ndarray 🟢 高 區域 bbox 像素級一致;色表 2% 差異;kmeans 非確定性 → 需固定 seed/容差放寬 最簡單,先行
P2 Pose swift_pose + cv2/numpy interpolation + YOLO fallback swift_pose + ndarray 插值 + ort YOLO 🟢 高 插值座標 ±0.5px;YOLO keypoint ±0.1(COCO 17 vs Vision 19 混用需定義 mapping) 插值純線性;YOLO 需 mapping
P3 Cut ffmpeg + PySceneDetect fallback 已原生 ffmpeg 🟢 高 scene 邊界 ±1 frame 已是 Rust,僅需補 Rust 版 PySceneDetect 漸變偵測(選配)
P4 Hand swift_hand wrapper 保留 swift_hand 🟢 高 不需 Rust 化 已 100% Swift
P5 Face clustering sklearn AgglomerativeClustering 自建 Rust 🟡 中 語者分群結果 correspondence 一致(speaker 編號可不同,成員須一致) 需實作 cosine + average linkage
P6 Face swift_face + coremltools FaceNet512 swift_face + ONNX FaceNet 🟡 中 embedding 餘弦相似度 >0.999;Qdrant push 一致 facenet512 轉 ONNX
P7 Scene torch/torchvision places365 ONNX places365 🟡 中 top-1 分類一致(容差可放寬 top-3) 轉檔
P8 OCR swift_ocr + PaddleOCR fallback 保留 swift_ocr;fallback 換 oar-ocr 🟢 高 不適用(已是 Swift) fallback 不見得需要 Rust
P9 ASR faster-whisper whisper-rs 🟡 中 文字內容一致(WER差 ≤1%);時間戳 ±0.5s;resume 行為對齊 需下載 ggml 權重;scene 分段重寫
P10 ASRX faster-whisper + VAD + ECAPA + Agglomerative whisper-rs + ort VAD + ONNX ECAPA + 自建 clustering 🟡 中 見 P5;語者 embedding 相似 工程量最大
P11 CLIP transformers CLIP candle-clip / ONNX 🟡 中 top-k 標籤一致 轉檔
P12 Caption Moondream2 VLM 無現成 🔴 低 — 保留 Python

驗證測試集(共用)

  • 主要測試檔:IMG_9449 (1).MOV(UUID 4655a0ab3c077e30c12b2298c2750650)
  • 每 processor 選 3–5 支涵蓋正/負例的影片做 A/B。

5. 遷移階段計畫

Phase 1 — 低風險、純演算法(不需模型轉檔)

項目 作法
Appearance Rust 版 rust_appearance(ndarray)A/B 對齊後取代
Pose interpolation Rust/ndarray 插值取代 pose_processor.py cv2 插值
Cut 補 Rust 版漸變偵測(選配)
Face clustering 自建 Rust agglomerative,A/B 對齊

驗證:scripts/ab_verify/appearance/ 等目錄建 A/B harness,跑 Python vs Rust,輸出 diff report。

Phase 2 — 需要模型轉檔

項目 作法
Face facenet512.mlpackage → ONNX(P0 驗證轉檔可行性)
Scene places365 → ONNX
CLIP ONNX / candle-clip

驗證:embedding/分類 A/B 對齊。

Phase 3 — ASR/ASRX(工程量大)

項目 作法
ASR whisper-rs + scene 分段 + resume;ggml 權重下載
ASRX whisper-rs + ort VAD + ONNX ECAPA + Rust agglomerative

驗證:文字 WER 差 ≤1%、時間戳 ±0.5s、語者分群 correspondence。

Phase 4 — 保留 Python

項目 理由
Caption Moondream2 無 Rust 支援;維持 Python(或評估 llama.cpp 載入)

6. 關鍵技術評估

6.1 whisper-rs(ASR)

  • whisper-rs 0.16(2026-03 更新)支援 Metal/CoreML feature;sample 用 small int8 需對齊 whisper.cpp ggml 權重。
  • 需實作:CUT scene 分段轉錄、.tmp resume(Python 版 asr_processor.py:275-413),與 word_timestamps 對齊。
  • 語音段標計時:whisper.cpp 回傳 segment 級 start/end,可對齊 schema。

6.2 FaceNet512 → ONNX

  • Python coremltools 可直接載入 .mlpackage 並 convert(representation_type="mlprogram")…但 ONNX 需經 torch/CoreML → ane 具備試作風險。
  • 另一途徑:用 FaceNet pytorch 官方 weight(facenet-pytorch)直接 export ONNX,替換現行 CoreML 權重 —— 代價是權重來源變更,需 A/B 確認 embedding 可比。

6.3 places365 → ONNX

  • torchvision resnet18(weights=Places365) 以 torch.onnx.export 輸出。

6.4 ECAPA-TDNN → ONNX

  • speechbrain 模型可 torch.onnx.export,需修掉 dynamic axis 問題;或改用開源 ecapa-tdnn.onnx 權重(需 A/B 驗證 embedding)。

6.5 AgglomerativeClustering 自建(P5/P10)

  • sklearn 預設:metric=cosine(實為 1 - cosine)、linkage=average。
  • Rust 實作重點:
    1. 距離 matrix 用 cosine(cosine_similarity → distance = 1 - sim)。
    2. average linkage(UPGMA):pairwise 平均距離更新。
    3. distance_threshold 切 cut(face_clustering.rs:82 用 distance = 1.0 - similarity)。
    4. 建 cluster tree,回傳 labels。
  • 驗證:speaker 分群成員 correspondence,編號不需一致。

7. 風險與取捨

面向 風險 因應
權重來源變更 FaceNet/whisper 若改 ggml/ONNX 權重,embedding/文字可能微差 一律 A/B 驗證;差距超標則保留 Python
轉檔障礙 .mlpackage → ONNX 可能失敗或輸出異常 Phase 2 先行 POC(scripts/model_export/);失敗則評估 pytorch 權重替代
agglomerative 對齊 sklearn 數值細節(數值穩定性、連結順序)難完全複製 驗證以分群成員一致為準,非數值位元一致
非確定性 kmeans(Appearance)每次結果略異 固定 seed;驗證容差放寬
效能 whisper.cpp vs faster-whisper 於 Mac 上速度差異 whisper.cpp Metal 加速較優;仍需實測 RTF
Double 維護 驗證期間 Python/Rust 並存 EXPERIMENTAL flag / env 切換;未過驗證不接主路徑

8. 結論

  • Rust 取代 Python 技術上完全可行:12 個 processor 中 11 個可行,僅 Caption 建議保留 Python。
  • 關鍵成功要素是「不換模型」:與 Swift 版最大差異在於維持相同模型/演算法,使 A/B 驗證成本低。
  • Phase 1(Appearance/Pose interpolation/Cut/Face clustering)為最佳切入點:不需模型轉檔,立即驗證架構可行性。
  • Phase 2 的 .mlpackage → ONNX 轉檔是最大技術風險,建議列為 POC 優先驗證。

9. 參考文件

文件 用途
DESIGN/PythonToSwiftProcessorMigration.md Swift 遷移評估(對照用)
DESIGN/PROCESSOR_MECHANISMS_REVIEW.md Processor 機制檢討
DESIGN/Processor_Refactoring_Assessment.md 重構評估
REFERENCE/history/PROCESSORS/SPEECH/ASRX_SELF_IMPLEMENTATION_FEASIBILITY.md ASRX 自實作評估