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).
This commit is contained in:
@@ -0,0 +1,260 @@
|
||||
---
|
||||
document_type: "design"
|
||||
service: "MOMENTRY_CORE"
|
||||
title: "Python → Rust Processor 遷移設計"
|
||||
date: "2026-09-15"
|
||||
version: "V1.0"
|
||||
status: "active"
|
||||
owner: "M5"
|
||||
created_by: "OpenCode"
|
||||
tags:
|
||||
- "processor"
|
||||
- "rust"
|
||||
- "migration"
|
||||
- "feasibility-assessment"
|
||||
- "rust-migration"
|
||||
ai_query_hints:
|
||||
- "Python processor 是否可以改寫成 Rust"
|
||||
- "Rust 版 processor 如何驗證效果與 Python 等同"
|
||||
- "facenet512 mlpackage 如何轉 ONNX"
|
||||
- "whisper-rs 如何取代 faster-whisper"
|
||||
- "agglomerative clustering 如何自建 Rust 實作"
|
||||
- "Rust processor 驗證門檻 A/B 測試"
|
||||
related_documents:
|
||||
- "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 自實作評估 |
|
||||
@@ -0,0 +1,178 @@
|
||||
---
|
||||
document_type: "design"
|
||||
service: "MOMENTRY_CORE"
|
||||
title: "Python → Swift Processor 遷移可行性評估"
|
||||
date: "2026-09-15"
|
||||
version: "V1.0"
|
||||
status: "active"
|
||||
owner: "M5"
|
||||
created_by: "OpenCode"
|
||||
tags:
|
||||
- "processor"
|
||||
- "swift"
|
||||
- "migration"
|
||||
- "feasibility"
|
||||
- "feasibility-assessment"
|
||||
ai_query_hints:
|
||||
- "Python processor 是否可以改寫成 Swift"
|
||||
- "swift_ocr / swift_hand / swift_pose / swift_face 目前用在哪些管線"
|
||||
- "哪些 processor 不建議遷移到 Swift"
|
||||
- "ASRX diarization 是否有 Swift 替代方案"
|
||||
- "FaceNet embedding 是否已遷移到 Swift"
|
||||
related_documents:
|
||||
- "REFERENCE/history/PROCESSORS/SPEECH/ASRX_SELF_IMPLEMENTATION_FEASIBILITY.md"
|
||||
- "DESIGN/PROCESSOR_MECHANISMS_REVIEW.md"
|
||||
- "DESIGN/Processor_Refactoring_Assessment.md"
|
||||
- "DESIGN/Processor_Module_V1.0.md"
|
||||
- "DESIGN/Processor_State_Machine_V1.0.md"
|
||||
---
|
||||
|
||||
# Python → Swift Processor 遷移可行性評估
|
||||
|
||||
| 項目 | 內容 |
|
||||
|------|------|
|
||||
| 建立者 | OpenCode |
|
||||
| 建立時間 | 2026-09-15 |
|
||||
| 文件版本 | V1.0 |
|
||||
| 目標讀者 | developer, Core team |
|
||||
| Scope | 現行 Python processor scripts 改寫為 Swift 的可行性評估與分階段建議 |
|
||||
|
||||
---
|
||||
|
||||
## 版本歷史
|
||||
|
||||
| 版本 | 日期 | 目的 | 操作人 |
|
||||
|------|------|------|--------|
|
||||
| V1.0 | 2026-09-15 | 建立 Python → Swift 遷移可行性設計文件 | OpenCode |
|
||||
|
||||
---
|
||||
|
||||
## 1. 執行摘要
|
||||
|
||||
Momentry Core 目前有 **12 個 Rust processor 入口**(位於 `/Users/accusys/momentry_core/src/core/processor/`),其中大部分透過 PythonExecutor 呼叫 `/Users/accusys/momentry_core/scripts/` 下的 Python scripts 執行模型推理。
|
||||
|
||||
**重要發現**:OCR、Hand、Pose、Face detection 四條管線**已經在呼叫 Swift binary**(`swift_ocr`、`swift_hand`、`swift_pose`、`swift_face`),Python 檔案只是薄包裝(thin wrapper)+ fallback。真正的缺口在於:
|
||||
|
||||
- **ASRX speaker diarization** — Apple Speech framework 無法提供真實 diarization
|
||||
- **FaceNet 512D embedding** — 仍由 Python(cv2 crop + coremltools)執行
|
||||
- **Pose keypoint interpolation**(補插值到全 FPS)— 由 Python cv2/numpy 執行
|
||||
- **Face clustering**(sklearn AgglomerativeClustering)— 無 Swift 原生替代
|
||||
- **CLIP / Caption**(HuggingFace transformers / Moondream2 VLM)— 無原生替代
|
||||
|
||||
**結論**:建議採分階段遷移。OCR/Hand/Pose/Face 已完成(Phase A);scene classifier 走 CoreML 與 pose interpolation 移到 Rust/Swift 屬可立即推進(Phase B);其餘為高風險或保留 Python(Phase C/D)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 現行管線對照表
|
||||
|
||||
Active 實作位於 `src/core/processor/`(`src/processing/modules/` 屬 dead code,未在 `lib.rs` 中宣告,且 `src/processing/handlers.rs` 為 TODO stub)。
|
||||
|
||||
| Rust Processor | 呼叫的 Python script | 關鍵實作 | Swift 現況 |
|
||||
|----------------|---------------------|----------|-----------|
|
||||
| ASR | `asr_processor.py` | faster-whisper (`small`, int8, CPU) | `asr_swift` POC(Apple Speech) |
|
||||
| ASRX | `asrx_processor.py` | HSD 混合管線(whisper + speechbrain + sklearn) | `asrx_swift` POC |
|
||||
| OCR | `ocr_processor.py` | 薄包裝 → **`swift_ocr`**,PaddleOCR fallback | ✅ 已完成 |
|
||||
| Face | `face_processor.py` | 薄包裝 → **`swift_face`**(bbox/landmarks/pose)+ CoreML FaceNet 512D embedding | ⚠️ detection 完成,embedding 仍在 Python |
|
||||
| Pose | `pose_processor.py` | 薄包裝 → **`swift_pose`** + cv2/numpy 補插值 + YOLOv8 fallback | ⚠️ detection 完成,interpolation 仍在 Python |
|
||||
| Hand | `hand_processor.py` | 薄包裝 → **`swift_hand`** | ✅ 已完成 |
|
||||
| Appearance | `appearance_processor.py` | 純 cv2/numpy HSV 顏色分析 | ✅ `swift_appearance_expansion` 已存在 |
|
||||
| Cut | `cut_processor.py` | **先原生 ffmpeg `select=gt(scene,0.3)`**,Python 僅 fallback(PySceneDetect) | ✅ 幾乎原生(POC: `swift_cut_test`) |
|
||||
| Face Cluster | `fast_face_clustering_processor.py` | sklearn AgglomerativeClustering(single-stage) | ❌ 無 |
|
||||
| Scene | `scene_classifier.py` | CoreML Places365 / torch MPS | ⚠️ model 已是 `.mlpackage`(`resnet18_places365.mlpackage`) |
|
||||
| Caption | `caption_processor.py` | Moondream2(local VLM) | ❌ 無 |
|
||||
| CLIP | `clip_classifier.py` | HuggingFace transformers(CLIP ViT-B/32) | ❌ 無 |
|
||||
| Face Recognition | `face_recognition_processor.py` / `face_registration.py` | FaceNet 比對/註冊 | ⚠️ 視 FaceNet 遷移而定 |
|
||||
| TKG | (純 Rust,無 Python) | Qdrant `_faces` scroll | n/a |
|
||||
| VLM Summary | (純 Rust,無 Python) | 呼叫 LLM vision function calling | n/a |
|
||||
|
||||
### 關鍵檔案位置
|
||||
|
||||
- Rust 入口:`/Users/accusys/momentry_core/src/core/processor/{asr,asrx,ocr,face,pose,hand,appearance,cut,face_clustering,scene_classification,caption,clip}.rs`
|
||||
- Worker 排程:`/Users/accusys/momentry_core/src/worker/processor.rs:664-1111`
|
||||
- Python scripts:`/Users/accusys/momentry_core/scripts/*_processor.py`
|
||||
- Swift package:`/Users/accusys/momentry_core/scripts/swift_processors/Package.swift`(17 個 executable targets,僅依賴 swift-argument-parser)
|
||||
- Swift binaries 已 build:`scripts/swift_processors/.build/debug/` 與 `.build/release/`
|
||||
|
||||
---
|
||||
|
||||
## 3. 逐管線可行性評估
|
||||
|
||||
| 管線 | 現行機制 | Swift 方案 | 判定 | 說明 |
|
||||
|------|---------|-----------|------|------|
|
||||
| **OCR** | wrapper → `swift_ocr` | 已完成 | ✅ 已完成 | Vision framework OCR,無需 Python |
|
||||
| **Hand** | wrapper → `swift_hand` | 已完成 | ✅ 已完成 | Vision `VNDetectHumanHandPoseRequest` |
|
||||
| **Pose detection** | wrapper → `swift_pose` | 已完成 | ✅ 已完成 | Vision `VNDetectHumanBodyPoseRequest`(ANE 加速) |
|
||||
| **Pose interpolation** | cv2/numpy 補插值到全 FPS | 需自行移植 | ⚠️ 中等 | 純數學運算,可在 Rust/Swift 實作(見 `pose_processor.py:141-258`) |
|
||||
| **Cut** | ffmpeg `select=scene` | 原生已達成 | ✅ 可行 | ffmpeg scene filter 已是第一優先;Python 為 fallback |
|
||||
| **Appearance** | cv2/numpy HSV 分析 | `swift_appearance_expansion` | ✅ 可行 | 已有現成 Swift 實作 |
|
||||
| **Scene classification** | CoreML Places365 / torch MPS | CoreML 直接載入 | ✅ 可行 | model 為 `.mlpackage`,可在 Swift 用 `MLModel` 直接推理 |
|
||||
| **Face detection** | wrapper → `swift_face` | 已完成 | ✅ 已完成 | Vision bbox/landmarks/pose |
|
||||
| **Face embedding** | cv2 crop + CoreML FaceNet 512D | 需 CoreML Swift 移植 | ⚠️ 中等 | `models/facenet512.mlpackage` 為現成 `.mlpackage`;需實驗 `MLModel` 直接輸出 embedding |
|
||||
| **Face clustering** | sklearn AgglomerativeClustering | 無原生替代 | ❌ 困難 | 需自行實作 linkage 演算法或保留 Python |
|
||||
| **ASR** | faster-whisper (`small`/int8) | `asr_swift`(Apple Speech) | ⚠️ 有取捨 | Apple Speech 準確度與多語系能力不及 faster-whisper;`asr_processor.py:4-8` 即因準確度改用 whisper |
|
||||
| **ASRX** | HSD(whisper + speechbrain + sklearn) | `asrx_swift` POC | ❌ 困難 | **Apple Speech 無真實 diarization**;`asrx_swift.swift:9-10` 已自行承認此限制 |
|
||||
| **CLIP** | HF transformers CLIP ViT-B/32 | 需導出 CoreML CLIP | ⚠️ 有條件 | 需將 CLIP model 轉 `.mlpackage`,工程量大 |
|
||||
| **Caption** | Moondream2(local VLM) | 無 Swift-native VLM | ❌ 不建議 | 此規模的本地 VLM 無 Swift 原生替代 |
|
||||
| **TKG / VLM Summary** | 純 Rust | 不需 Python | ✅ n/a | 與 Python 無關 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 遷移階段建議
|
||||
|
||||
### Phase A(已完成):Vision 偵測類 → Swift
|
||||
|
||||
| 管線 | 狀態 |
|
||||
|------|------|
|
||||
| OCR | ✅ `swift_ocr` |
|
||||
| Hand | ✅ `swift_hand` |
|
||||
| Pose detection | ✅ `swift_pose`(需保留 interpolation 回 Python) |
|
||||
| Face detection | ✅ `swift_face`(需保留 embedding 回 Python) |
|
||||
|
||||
### Phase B(建議下一步,風險低)
|
||||
|
||||
| 項目 | 作法 | 預期效益 |
|
||||
|------|------|----------|
|
||||
| Scene classification 走 CoreML | Python `scene_classifier.py` 改為直接呼叫 Swift 載入 `resnet18_places365.mlpackage`(或直接由 Rust 以 CoreML MLModel 執行) | 移除 torch/torchvision MPS 依賴 |
|
||||
| Pose interpolation 移到 Rust | 把 `pose_processor.py:141-258` 的 cv2/numpy 補插值邏輯改寫成 Rust 或 Swift | 移除 cv2/numpy 依賴,減少 wrapper 轉換成本 |
|
||||
| Appearance 切到 Swift | 使用現成 `swift_appearance_expansion`,替換 `appearance_processor.py` | 移除 cv2/numpy 依賴 |
|
||||
| 移除高成熟度管線的 Python fallback | OCR/Hand/Pose 偵測若 Swift 穩定,移除 PaddleOCR / YOLO fallback | 減少 Python 環境依賴 |
|
||||
|
||||
### Phase C(高風險/選配)
|
||||
|
||||
| 項目 | 作法 | 風險 |
|
||||
|------|------|------|
|
||||
| FaceNet embedding 走 CoreML | 實驗以 Swift `MLModel` 直接對 cropped face 產生 512D embedding,取代 `face_processor.py` 的 cv2+coremltools | CoreML input/output 格式需對齊 FaceNet512 原有前處理(歸一化、Crop) |
|
||||
| Face clustering 自建 | 在 Rust/Swift 實作 AgglomerativeClustering(或改用固定閾值 greedy grouping) | 數值結果需與 sklearn 對齊,驗證成本高 |
|
||||
|
||||
### Phase D(不建議)
|
||||
|
||||
| 管線 | 原因 |
|
||||
|------|------|
|
||||
| **ASRX diarization** | Apple Speech framework 無真實 diarization;現行 HSD 管線涉及 whisper + speechbrain + sklearn,移植至 Swift 需重新設計 |
|
||||
| **CLIP** | 需自行導出 CoreML CLIP,且容量與精度不確定 |
|
||||
| **Caption** | Moondream2 等級的本地 VLM 無 Swift 原生替代 |
|
||||
| **ASR 主路徑** | faster-whisper 準確度/多語系優於 Apple Speech;除非接受準確度下降否則保留 Python |
|
||||
|
||||
---
|
||||
|
||||
## 5. 風險與取捨
|
||||
|
||||
| 面向 | 風險 | 因應 |
|
||||
|------|------|------|
|
||||
| **模型準確度** | ASR/ASRX 改用 Apple Speech 後準確度下降 | 主路徑保留 faster-whisper;`asr_swift`/`asrx_swift` 僅做 POC 或輕量用途 |
|
||||
| **checksums 驗證** | PythonExecutor 在每次執行前做 SHA256 檢查(`checksums.sha256`) | 若新增 Swift binary 路徑,需納入 checksum 或明確標示 `verify_script_integrity` 適用範圍 |
|
||||
| **subprocess env 繼承** | Executor 傳入 9 個 env vars(`MOMENTRY_OUTPUT_DIR`、`DATABASE_SCHEMA`、`MOMENTRY_REDIS_PREFIX`、`QDRANT_URL` 等) | Swift subprocess 需比照 Python wrapper 讀取相同 env vars |
|
||||
| **Swift binary 建置時機** | Swift package 需預先 build(debug/release)才能被呼叫 | 沿用 `scripts/setup/upgrade_momentry.sh:285` 的 swift_processors 複製機制,release/deploy 時一併建置 |
|
||||
| **平台綁定** | Swift processors 依賴 macOS Vision/AVFoundation | 目前部署環境即 macOS(M5Max128),無跨平台需求 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 參考文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `REFERENCE/history/PROCESSORS/SPEECH/ASRX_SELF_IMPLEMENTATION_FEASIBILITY.md` | ASRX Swift 自實作可行性(既有) |
|
||||
| `DESIGN/PROCESSOR_MECHANISMS_REVIEW.md` | Processor 產出機制檢討(中斷接續/補充/糾錯) |
|
||||
| `DESIGN/Processor_Refactoring_Assessment.md` | Processor 重構評估 |
|
||||
| `DESIGN/Processor_Module_V1.0.md` | Processor 模組規格 |
|
||||
| `DESIGN/Processor_State_Machine_V1.0.md` | Processor 狀態機設計 |
|
||||
@@ -0,0 +1,560 @@
|
||||
---
|
||||
title: VLM Prompt Admin 可編輯實現計劃
|
||||
version: 1.0
|
||||
date: 2026-08-27
|
||||
author: OpenCode
|
||||
status: draft
|
||||
---
|
||||
|
||||
# VLM Prompt Admin 可編輯實現計劃
|
||||
|
||||
## 目標
|
||||
|
||||
讓 Admin 用戶可以通過 UI 修改 VLM prompt,無需修改程式碼。
|
||||
|
||||
## 現狀分析
|
||||
|
||||
### Prompt 存儲位置
|
||||
|
||||
| 位置 | 類型 | 檔案 | 行數 |
|
||||
|------|------|------|------|
|
||||
| Rust | 硬編碼 | `src/core/processor/vlm_summary.rs` | 1 prompt |
|
||||
| Python | 硬編碼 | `scripts/trace_vlm_caption.py` | 10 prompts |
|
||||
| Python | 硬編碼 | `scripts/scene_vlm_caption.py` | 9 prompts |
|
||||
|
||||
### 問題
|
||||
|
||||
1. ✗ Prompt 硬編碼在程式碼中
|
||||
2. ✗ 修改需要重啟服務
|
||||
3. ✗ 無修改歷史記錄
|
||||
4. ✗ 無 Admin 權限控制
|
||||
5. ✗ 無 UI 編輯界面
|
||||
|
||||
## 方案比較
|
||||
|
||||
### 方案 1: PostgreSQL 存儲
|
||||
|
||||
**優點:**
|
||||
- ✓ 結構化存儲,易於查詢
|
||||
- ✓ 可記錄修改歷史
|
||||
- ✓ 支持事務
|
||||
- ✓ 易於備份
|
||||
|
||||
**缺點:**
|
||||
- ✗ 需要創建新表
|
||||
- ✗ 每次讀取需要資料庫查詢
|
||||
- ✗ Python 腳本需要資料庫連接
|
||||
|
||||
### 方案 2: JSON 配置檔案 (推薦)
|
||||
|
||||
**優點:**
|
||||
- ✓ 實現簡單
|
||||
- ✓ 易於版本控制
|
||||
- ✓ 讀取速度快
|
||||
- ✓ Python 可直接讀取
|
||||
|
||||
**缺點:**
|
||||
- ✗ 無修改歷史 (可通過 git 解決)
|
||||
- ✗ 並發寫入需要鎖
|
||||
|
||||
### 方案 3: Redis + PostgreSQL
|
||||
|
||||
**優點:**
|
||||
- ✓ 讀取速度極快
|
||||
- ✓ 數據持久化
|
||||
- ✓ 支持熱重載
|
||||
|
||||
**缺點:**
|
||||
- ✗ 架構複雜
|
||||
- ✗ 維護成本高
|
||||
|
||||
## 推薦方案: JSON 配置檔案 + Admin API
|
||||
|
||||
### 架構設計
|
||||
|
||||
```
|
||||
┌─────────────────┐
|
||||
│ Portal UI │
|
||||
│ (Admin Page) │
|
||||
└────────┬────────┘
|
||||
│ HTTP
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Admin API │
|
||||
│ (Rust) │
|
||||
└────────┬────────┘
|
||||
│ File I/O
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ vlm_prompts.json│
|
||||
│ (config/) │
|
||||
└─────────────────┘
|
||||
▲
|
||||
│ Read
|
||||
│
|
||||
┌─────────────────┐
|
||||
│ Python Scripts │
|
||||
│ (trace_vlm) │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
### 配置檔案結構
|
||||
|
||||
**檔案:** `config/vlm_prompts.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"updated_at": "2026-08-27T13:00:00Z",
|
||||
"updated_by": "admin",
|
||||
|
||||
"prompts": {
|
||||
"rust_vlm_summary": {
|
||||
"system_prompt": "You are a scene analysis assistant...",
|
||||
"user_prompt": "Summarize this key frame.",
|
||||
"description": "Rust VLM summary for trace",
|
||||
"max_tokens": 512
|
||||
},
|
||||
|
||||
"trace_desc": {
|
||||
"prompt": "Describe this person briefly. For EVERY item...",
|
||||
"description": "Person description",
|
||||
"max_tokens": 100
|
||||
},
|
||||
|
||||
"trace_clothing": {
|
||||
"prompt": "Describe this person's clothing in detail...",
|
||||
"description": "Clothing details",
|
||||
"max_tokens": 100
|
||||
},
|
||||
|
||||
"trace_hand_objects": {
|
||||
"prompt": "Look at the person's hands...",
|
||||
"description": "Objects in hand",
|
||||
"max_tokens": 50
|
||||
},
|
||||
|
||||
"trace_lighting": {
|
||||
"prompt": "What is the lighting condition?",
|
||||
"description": "Lighting condition",
|
||||
"max_tokens": 20
|
||||
},
|
||||
|
||||
"trace_scene": {
|
||||
"prompt": "Classify the scene...",
|
||||
"description": "Scene classification",
|
||||
"max_tokens": 100
|
||||
},
|
||||
|
||||
"trace_background": {
|
||||
"prompt": "Describe the background...",
|
||||
"description": "Background description",
|
||||
"max_tokens": 100
|
||||
},
|
||||
|
||||
"trace_plants": {
|
||||
"prompt": "What plants, trees, or flowers...",
|
||||
"description": "Plants detection",
|
||||
"max_tokens": 100
|
||||
},
|
||||
|
||||
"trace_animals": {
|
||||
"prompt": "What animals are clearly visible?",
|
||||
"description": "Animals detection",
|
||||
"max_tokens": 100
|
||||
},
|
||||
|
||||
"scene_desc": {
|
||||
"prompt": "Describe this scene briefly...",
|
||||
"description": "Scene description",
|
||||
"max_tokens": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### API 設計
|
||||
|
||||
#### GET /api/v1/admin/prompts
|
||||
|
||||
**用途:** 查詢所有 prompts
|
||||
|
||||
**回應:**
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"prompts": {
|
||||
"rust_vlm_summary": {
|
||||
"system_prompt": "...",
|
||||
"user_prompt": "...",
|
||||
"description": "..."
|
||||
},
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### PUT /api/v1/admin/prompts/:key
|
||||
|
||||
**用途:** 更新指定 prompt
|
||||
|
||||
**請求:**
|
||||
```json
|
||||
{
|
||||
"prompt": "新的 prompt 內容",
|
||||
"max_tokens": 150
|
||||
}
|
||||
```
|
||||
|
||||
**回應:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"updated_at": "2026-08-27T14:00:00Z",
|
||||
"updated_by": "admin"
|
||||
}
|
||||
```
|
||||
|
||||
#### POST /api/v1/admin/prompts/reload
|
||||
|
||||
**用途:** 重新載入配置 (如果手動修改了檔案)
|
||||
|
||||
**回應:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Prompts reloaded from config/vlm_prompts.json"
|
||||
}
|
||||
```
|
||||
|
||||
### Admin 權限控制
|
||||
|
||||
#### 方法 1: API Key 白名單
|
||||
|
||||
**實現:**
|
||||
```rust
|
||||
// src/api/middleware.rs
|
||||
pub fn is_admin(api_key: &str) -> bool {
|
||||
let admin_keys = vec![
|
||||
"muser_admin_key_1",
|
||||
"muser_admin_key_2",
|
||||
];
|
||||
admin_keys.contains(&api_key)
|
||||
}
|
||||
```
|
||||
|
||||
#### 方法 2: 資料庫角色表
|
||||
|
||||
**表結構:**
|
||||
```sql
|
||||
CREATE TABLE api_key_roles (
|
||||
api_key VARCHAR(100) PRIMARY KEY,
|
||||
role VARCHAR(20) NOT NULL, -- 'admin', 'user', 'readonly'
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
```
|
||||
|
||||
### Rust 實現
|
||||
|
||||
#### 1. 配置讀取模組
|
||||
|
||||
**檔案:** `src/core/vlm_prompts.rs`
|
||||
|
||||
```rust
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VlmPrompt {
|
||||
pub prompt: String,
|
||||
pub description: String,
|
||||
pub max_tokens: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VlmPromptsConfig {
|
||||
pub version: String,
|
||||
pub updated_at: String,
|
||||
pub updated_by: String,
|
||||
pub prompts: std::collections::HashMap<String, VlmPrompt>,
|
||||
}
|
||||
|
||||
pub struct VlmPromptManager {
|
||||
config: Arc<RwLock<VlmPromptsConfig>>,
|
||||
config_path: String,
|
||||
}
|
||||
|
||||
impl VlmPromptManager {
|
||||
pub fn new(config_path: &str) -> Result<Self> {
|
||||
let config = Self::load_config(config_path)?;
|
||||
Ok(Self {
|
||||
config: Arc::new(RwLock::new(config)),
|
||||
config_path: config_path.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn load_config(path: &str) -> Result<VlmPromptsConfig> {
|
||||
let content = std::fs::read_to_string(path)?;
|
||||
let config: VlmPromptsConfig = serde_json::from_str(&content)?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub async fn get_prompt(&self, key: &str) -> Option<VlmPrompt> {
|
||||
let config = self.config.read().await;
|
||||
config.prompts.get(key).cloned()
|
||||
}
|
||||
|
||||
pub async fn update_prompt(&self, key: &str, prompt: VlmPrompt) -> Result<()> {
|
||||
let mut config = self.config.write().await;
|
||||
config.prompts.insert(key.to_string(), prompt);
|
||||
|
||||
// Save to file
|
||||
let content = serde_json::to_string_pretty(&*config)?;
|
||||
std::fs::write(&self.config_path, content)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reload(&self) -> Result<()> {
|
||||
let new_config = Self::load_config(&self.config_path)?;
|
||||
let mut config = self.config.write().await;
|
||||
*config = new_config;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. API 端點
|
||||
|
||||
**檔案:** `src/api/admin_prompts.rs`
|
||||
|
||||
```rust
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
response::Json,
|
||||
};
|
||||
use crate::core::vlm_prompts::{VlmPrompt, VlmPromptManager};
|
||||
|
||||
pub async fn get_prompts(
|
||||
State(manager): State<Arc<VlmPromptManager>>,
|
||||
) -> Result<Json<VlmPromptsConfig>, StatusCode> {
|
||||
let config = manager.get_all_prompts().await;
|
||||
Ok(Json(config))
|
||||
}
|
||||
|
||||
pub async fn update_prompt(
|
||||
State(manager): State<Arc<VlmPromptManager>>,
|
||||
Path(key): Path<String>,
|
||||
Json(prompt): Json<VlmPrompt>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
manager.update_prompt(&key, prompt).await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": format!("Prompt '{}' updated", key)
|
||||
})))
|
||||
}
|
||||
|
||||
pub async fn reload_prompts(
|
||||
State(manager): State<Arc<VlmPromptManager>>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
manager.reload().await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": "Prompts reloaded"
|
||||
})))
|
||||
}
|
||||
```
|
||||
|
||||
### Python 實現
|
||||
|
||||
#### 1. 配置讀取模組
|
||||
|
||||
**檔案:** `scripts/vlm_prompt_config.py`
|
||||
|
||||
```python
|
||||
#!/opt/homebrew/bin/python3.11
|
||||
"""
|
||||
VLM Prompt Config Loader
|
||||
|
||||
Loads prompts from config/vlm_prompts.json
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict
|
||||
|
||||
CONFIG_PATH = Path(__file__).parent.parent / "config" / "vlm_prompts.json"
|
||||
|
||||
class VlmPromptManager:
|
||||
_instance = None
|
||||
_config = None
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = cls()
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
self._config = self._load_config()
|
||||
|
||||
def _load_config(self) -> Dict:
|
||||
if not CONFIG_PATH.exists():
|
||||
raise FileNotFoundError(f"Config file not found: {CONFIG_PATH}")
|
||||
|
||||
with open(CONFIG_PATH, 'r') as f:
|
||||
return json.load(f)
|
||||
|
||||
def get_prompt(self, key: str) -> Optional[str]:
|
||||
"""Get prompt by key"""
|
||||
prompt_data = self._config.get('prompts', {}).get(key)
|
||||
return prompt_data.get('prompt') if prompt_data else None
|
||||
|
||||
def get_max_tokens(self, key: str) -> int:
|
||||
"""Get max tokens for prompt"""
|
||||
prompt_data = self._config.get('prompts', {}).get(key)
|
||||
return prompt_data.get('max_tokens', 100) if prompt_data else 100
|
||||
|
||||
def reload(self):
|
||||
"""Reload config from file"""
|
||||
self._config = self._load_config()
|
||||
|
||||
# Convenience function
|
||||
def get_vlm_prompt(key: str) -> str:
|
||||
"""Get VLM prompt by key"""
|
||||
manager = VlmPromptManager.get_instance()
|
||||
prompt = manager.get_prompt(key)
|
||||
if not prompt:
|
||||
raise ValueError(f"Prompt not found: {key}")
|
||||
return prompt
|
||||
```
|
||||
|
||||
#### 2. 更新 Python 腳本
|
||||
|
||||
**修改:** `scripts/trace_vlm_caption.py`
|
||||
|
||||
```python
|
||||
# Before:
|
||||
desc_prompt = "Describe this person briefly..."
|
||||
|
||||
# After:
|
||||
from vlm_prompt_config import get_vlm_prompt
|
||||
desc_prompt = get_vlm_prompt('trace_desc')
|
||||
```
|
||||
|
||||
### Portal UI 設計
|
||||
|
||||
#### Admin 頁面
|
||||
|
||||
**路徑:** `/admin/prompts`
|
||||
|
||||
**組件:** `portal/src/views/AdminPromptsView.tsx`
|
||||
|
||||
**功能:**
|
||||
1. 顯示所有 prompts 列表
|
||||
2. 編輯 prompt 內容
|
||||
3. 預覽 prompt 效果
|
||||
4. 保存修改
|
||||
|
||||
**UI 設計:**
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ VLM Prompt 管理 │
|
||||
├─────────────────────────────────────────────┤
|
||||
│ [Trace Prompts] [Scene Prompts] [Rust] │
|
||||
├─────────────────────────────────────────────┤
|
||||
│ Prompt: trace_desc │
|
||||
│ ┌───────────────────────────────────────┐ │
|
||||
│ │ Describe this person briefly... │ │
|
||||
│ │ │ │
|
||||
│ └───────────────────────────────────────┘ │
|
||||
│ Max Tokens: [100] │
|
||||
│ Description: Person description │
|
||||
│ │
|
||||
│ [Save] [Reset] [Test] │
|
||||
└─────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 實現計劃
|
||||
|
||||
### Phase 1: 基礎架構 (1-2 天)
|
||||
|
||||
- [ ] 創建 `config/vlm_prompts.json`
|
||||
- [ ] 實現 Rust `VlmPromptManager`
|
||||
- [ ] 實現 Python `VlmPromptManager`
|
||||
- [ ] 添加環境變數 `MOMENTRY_PROMPTS_CONFIG`
|
||||
|
||||
### Phase 2: API 端點 (1 天)
|
||||
|
||||
- [ ] 創建 `src/api/admin_prompts.rs`
|
||||
- [ ] 實現 GET/PUT/POST 端點
|
||||
- [ ] 添加 Admin 權限中間件
|
||||
- [ ] 更新 API 文檔
|
||||
|
||||
### Phase 3: Python 腳本更新 (1 天)
|
||||
|
||||
- [ ] 更新 `trace_vlm_caption.py`
|
||||
- [ ] 更新 `scene_vlm_caption.py`
|
||||
- [ ] 更新 `interval_vlm_caption.py`
|
||||
- [ ] 移除硬編碼 prompt
|
||||
|
||||
### Phase 4: Portal UI (2-3 天)
|
||||
|
||||
- [ ] 創建 Admin 頁面路由
|
||||
- [ ] 實現 Prompt 編輯器
|
||||
- [ ] 添加權限檢查
|
||||
- [ ] UI/UX 優化
|
||||
|
||||
### Phase 5: 測試與文檔 (1 天)
|
||||
|
||||
- [ ] 單元測試
|
||||
- [ ] 整合測試
|
||||
- [ ] API 文檔更新
|
||||
- [ ] 用戶指南
|
||||
|
||||
## 風險評估
|
||||
|
||||
### 低風險
|
||||
- ✓ JSON 檔案讀取穩定
|
||||
- ✓ Python 腳本更新簡單
|
||||
- ✓ Admin API 實現常規
|
||||
|
||||
### 中風險
|
||||
- ⚠️ 並發寫入可能衝突 (需要文件鎖)
|
||||
- ⚠️ 權限控制需要仔細設計
|
||||
- ⚠️ Portal UI 開發時間
|
||||
|
||||
### 高風險
|
||||
- ✗ 無
|
||||
|
||||
## 後續優化
|
||||
|
||||
### 短期
|
||||
1. 添加修改歷史 (git commits)
|
||||
2. 添加 prompt 版本控制
|
||||
3. 添加 prompt 效果測試功能
|
||||
|
||||
### 長期
|
||||
1. 遷移到資料庫存儲 (如需要)
|
||||
2. 添加 prompt A/B 測試
|
||||
3. 添加 AI 輔助 prompt 優化
|
||||
|
||||
## 相關文件
|
||||
|
||||
- `/Users/accusys/momentry_core/src/core/processor/vlm_summary.rs` - Rust VLM 處理器
|
||||
- `/Users/accusys/momentry_core/scripts/trace_vlm_caption.py` - Python trace VLM
|
||||
- `/Users/accusys/momentry_core/scripts/scene_vlm_caption.py` - Python scene VLM
|
||||
|
||||
## 變更歷史
|
||||
|
||||
| 版本 | 日期 | 作者 | 變更內容 |
|
||||
|------|------|------|----------|
|
||||
| 1.0 | 2026-08-27 | OpenCode | 初始版本 |
|
||||
Reference in New Issue
Block a user