diff --git a/config/admin_config.json b/config/admin_config.json index 4c8b0eb4..6d2987f7 100644 --- a/config/admin_config.json +++ b/config/admin_config.json @@ -195,5 +195,23 @@ "max_concurrent_stages": 5, "default_timeout_secs": 7200, "flows": {} + }, + "asr_config": { + "garbled_check_enabled": true, + "first_sentence_thresholds": { + "max_top_char_ratio": 0.6, + "min_lang_prob": 0.4, + "min_repeat_slice_repeat": 5 + }, + "language_candidates": [ + "ja", + "zh", + "en" + ], + "vlm_rescue_enabled": true, + "vlm_max_tokens": 500, + "vlm_temperature": 0.1, + "vlm_timeout_secs": 120, + "vlm_max_audio_secs": 60 } -} \ No newline at end of file +} diff --git a/config/processor_tools_v3.json b/config/processor_tools_v3.json index cba67193..da3fe0a1 100644 --- a/config/processor_tools_v3.json +++ b/config/processor_tools_v3.json @@ -80,7 +80,7 @@ "parameters": { "model_dir": "/Users/accusys/models/whisper-small-mlx" }, - "output_file": "{file_uuid}.asr_asrx.json", + "output_file": "{file_uuid}.asrx.json", "timeout": 3600 } ], @@ -158,7 +158,9 @@ "--min-trace-len", "{min_trace_len}", "--min-confidence", - "{min_confidence}" + "{min_confidence}", + "--video-path", + "{video_path}" ] }, "parameters": { diff --git a/docs_v1.0/M4_workspace/2026-11-03_fs_count_display_issue.md b/docs_v1.0/M4_workspace/2026-11-03_fs_count_display_issue.md new file mode 100644 index 00000000..d026e063 --- /dev/null +++ b/docs_v1.0/M4_workspace/2026-11-03_fs_count_display_issue.md @@ -0,0 +1,23 @@ +# FS Count Display Issue + +## Problem +Face group cards sometimes don't show the FS count number. + +## Root Cause +`src/views/PeopleView.vue:1153` - `faceGroups` computed property: +```javascript +trace_count: c.trace_count, // no fallback +``` + +When `c.trace_count` is `undefined` (e.g., old cache data), the card shows empty. + +## Proposed Fix +```javascript +trace_count: c.trace_count ?? traceIds.length, +``` + +## Files to Modify +- `/Users/accusys/momentry_studio/src/views/PeopleView.vue` + +## Assigned to +Studio team diff --git a/docs_v1.0/OPERATIONS/Launchd_Services_Audit_2026-11-05.md b/docs_v1.0/OPERATIONS/Launchd_Services_Audit_2026-11-05.md new file mode 100644 index 00000000..b20accaf --- /dev/null +++ b/docs_v1.0/OPERATIONS/Launchd_Services_Audit_2026-11-05.md @@ -0,0 +1,94 @@ +# launchd 服務全面盤點與管理改善方案 — 2026-11-05 + +| 項目 | 內容 | +|------|------| +| **範圍** | 本機(m5max128, macOS, arm64)全部 LaunchAgents 服務盤點、發現的漂移與重複、治理建議 | +| **方法** | `plutil` 逐 plist 解析欄位 + `launchctl list` 對照 + `lsof`/`ps` 埠層核對 | +| **狀態** | §3 行動清單已核可執行(1.1 版) | + +--- + +## 1. 服務清單與現況 + +### 1.1 momentry 核心鏈 + +| Service | 狀態 | Port | Binary | 註記 | +|---|---|---|---|---| +| `com.momentry.api` | 🟢 PID 857 | 3002 | ✅ `momentry_core/target/release/momentry` | wrapper_production.sh exec target/release;**初版誤判為 /tmp,已更正**——從未使用 /tmp(對 /health 需 API key,正常) | +| `com.momentry.pipeline_worker` | 🟢 PID 63939 | - | ✅ `momentry_core/target/release/pipeline_worker` | 實際處理任務的 worker | +| `com.momentry.worker` | ⚪ 未註冊(備用) | - | ✅(已修)`momentry_core/target/release/momentry` | plist 已改指 target/release;**保持未註冊**避免與 pipeline_worker 雙跑,需要時再 bootstrap | +| `com.momentry.proxy` | 🟢 PID 64947 | 8888 | ✅(已修)`/Users/accusys/momentry/bin/momentry-proxy` | **本次修復**——此前由 studio 的 `npm run dev` 附帶 spawn(debug build、kill -9 搶 8888);package.json dev script 已改純 `vite`、plist 改 release binary 並 bootstrap | +| `com.momentry.embedding` | 🟢 PID 896 | 11436 | wrapper_embedding.sh | OK | +| `com.momentry.chat-llamacpp` | 🟢 PID 56973 | 8080 | ✅ `~/llama.cpp/build/bin/llama-server` | **本次修復註冊**(gemma4 + mmproj;語音轉錄 004/020 已驗證) | +| `com.momentry.markbase` | 🟢 PID 904 | 11438 | ✅ `~/markbase/target/release/markbase-core` | OK | +| `com.momentry.markbaseengine` | 🟢 PID 891 | 8089 | `~/markbaseengine_service` | OK | +| `com.momentry.sftpgo` | 🟢 PID 882 | 2022/8081/8090 | `~/bin/sftpgo` | OK | +| `com.momentry.gitea` | 🟢 PID 865 | 3000 | `~/gitea/bin/gitea` | OK | +| `com.momentry.studio` | 🟢 PID 888 | 3200/5173 | npm | OK | + +### 1.2 基礎設施 + +| Service | 狀態 | Port | 註記 | +|---|---|---|---| +| PostgreSQL(自管版) | 🟢 PID 414 | 5432 | `/Users/accusys/pgsql/18.3/bin/postgres`;launchctl 上 `com.momentry.postgresql` 顯示 EXIT=0,實際行程非該 plist 巢管(來源待查) | +| Redis | 🟢 單一(本次裁減後) | 6379 | **原雙活已裁減**:pid 833(手動裸啟、無 config、無資料、cwd=/)已終止;保留 `sh.brew.redis` pid 885(382 keys 完好)。⚠️ 兩者皆未設密碼,而 AGENTS 連線字串含 `:accusys@`——建議補 `requirepass` 對齊 | +| MongoDB | 🟢 PID 856 | 27017 | 跑的是 `homebrew.mxcl.mongodb-community`;`com.momentry.mongodb` EXIT=100 | +| MariaDB | 🟢 PID 901 | 3306 | 跑的是 `homebrew.mxcl.mariadb`(WordPress legacy) | +| 反向代理 | ⚠️ | 9001/9002 | `homebrew.mxcl.nginx` 在跑;`com.momentry.caddy` EXIT=0 未啟動 → 80/443 對外層缺位 | +| Ollama | 🟢 PID 880 | 11434 | `homebrew.mxcl.ollama`(port_registry 有列,用途待確認) | + +### 1.3 重複/歧義服務(治理第一刀) + +| 領域 | 兩個來源 | 建議 | +|---|---|---| +| PHP-FPM | ~~`com.momentry.php`(PID 861)~~ + `homebrew.mxcl.php@8.4`(PID 884) | ✅ **已裁減**(2026-11-05):bootout `com.momentry.php`、plist 改名 `.disabled`;9100 pool 由 brew php@8.4 續服 | +| Ollama | `homebrew.mxcl.ollama` + `com.momentry.ollama` | 保 homebrew 版,刪 momentry plist | +| MariaDB | `homebrew.mxcl.mariadb` + `com.momentry.mariadb` | 保 homebrew 版,刪 momentry plist | +| MongoDB | `homebrew.mxcl.mongodb-community` + `com.momentry.mongodb` | 保 homebrew 版 | +| 舊 LLM 服務 | `com.momentry.llamacpp` / `llamacpp-a4b` / `llamacpp-e4b` | ✅ **已下架**(2026-11-05):bootout + plist 改名 `.disabled`;統一由 `com.momentry.chat-llamacpp` 服務 | +| 反向代理 | caddy(不跑)vs nginx(:9001/9002) | 依 port_registry 決定一人(80/443 → Caddy 為文件設計) | + +### 1.4 本次已修復 + +| 修復 | 結果 | +|---|---| +| `com.momentry.chat-llamacpp` 處於 disabled 狀態(`launchctl print-disabled` 可見),導致 `bootstrap` 回 error 5 | `launchctl enable` → `bootstrap` 成功;:8080 回歸 launchd 管理,KeepAlive 看門狗生效,健康檢查 200 | + +--- + +## 2. 治理方案(建議,按優先級) + +| # | 提案 | 理由 | +|---|------|------| +| P1 | **生產 binary 移出 `/tmp/final_install`**:api / worker / proxy 的 plist 與始動路徑改到 `/Users/accusys/momentry_core/target/release/` | /tmp 在重開機可能被清空;且與 AGENTS.md 記載(target/release/momentry)一致 | +| P2 | **plist 單一來源**:以 `momentry_core/momentry_runtime/plist/` 為唯一母本,提供 install 腳本布林部署到 `~/Library/LaunchAgents`;一律 `launchctl bootstrap` / `bootout`(不再用 `load` / `unload`) | 現況多處漂移(/tmp、EXIT=0 仍掛空 plist) | +| P3 | **port 單一擁有者**:以 `config/port_registry.tsv` 為 source of truth,新增服務前先查是否已有人佔用同一 port | 現況雙 redis、雙 php 已是第一梯队撞名 | +| P4 | **重複服務裁減**:PHP / Ollama / MariaDB / MongoDB 依 §1.3 建議二擇一 | 消除行為歧義 | +| P5 | **日誌統一 + rotation**:各 plist 統一輸出到 momentry_core/logs/\.log,加大小/時間輪替策略 | 現況分散(~/momentry/log、logs、temp 皆有) | +| P6 | **KeepAlive 政策**:核心服務(api/worker/llama/qdrant/redis/pg)= true;週邊輔助 = 依任務性質 | 失敗自動復活,本次 chat-llamacpp 即靠此修復 | +| P7 | **啟動依賴順序**:infra(pg→redis→qdrant→mongo)→ LLM(8080→11436)→ app(api→worker)在 plist 加 `AssociatedBundleIdentifiers`-無效者改以 start script 排程 | 避免 app 起來但 data layer 未就緒 | +| P8 | **定期健康快照**:腳本比對 `launchctl list` 與 port_registry,輸出偏差報告(EXIT 非 0、未註冊、雙活) | 將本份盤點自動化 | + +--- + +## 3. 立即行動清單(2026-11-05 已核可執行) + +| # | 動作 | 結果 | +|---|------|------| +| 1 | api / worker / proxy plist binary 移出 `/tmp/final_install` | ✅ 完成。api 原本就正確(wrapper → target/release,初版報告誤判已更正);worker plist 已改 target/release + WD `momentry_core`(保持未註冊備用);proxy plist 已改 `/Users/accusys/momentry/bin/momentry-proxy` | +| 2 | `com.momentry.proxy` 納回 launchd 管理 | ✅ 完成。PID 64947、:8888 正常;衝突源已消除——`momentry_studio/package.json` 的 `dev` script 移除「kill -9 8888 + spawn debug proxy」段落,改純 `vite` | +| 3 | redis pid 833 裁掉 | ✅ 完成。確認 833 = 手動裸啟、無密碼、無任何資料庫檔、cwd=/;終止後 brew 885 單獨服務,DBSIZE 382 無損、PING OK | +| 4 | PHP 二擇一 → homebrew php@8.4;停 `com.momentry.php` | ✅ 完成。bootout 後 9000 pool 由 884(brew php@8.4)續服;plist 改名 `.disabled` | +| 5 | caddy vs nginx:80/443 歸 caddy | ⏸ 未執行(本次未核可) | +| 6 | 舊 llamacpp plist ×3 移除 | ✅ 完成。bootout + 改名 `*.plist.disabled`(重開機不會復活) | + +> rollback 方式:`.disabled` 檔案改回原名 + `launchctl bootstrap` 即可。 + +--- + +## 4. 版本歷史 + +| 版本 | 日期 | 變更 | +|------|------|------| +| 1.0 | 2026-11-05 | 初版盤點;修復 chat-llamacpp disabled 狀態並註冊回 launchd;提出 P1–P8 治理方案(OpenCode) | +| 1.1 | 2026-11-05 | §3 行動清單核可執行(#1/2/3/4/6 完成,#5 待議):proxy 納回 launchd(PID 64947)、redis 雙活裁減、php/舊 llamacpp plist 下架;更正 api 誤判與 proxy 脫管根因(studio dev script 搶 8888) | diff --git a/installer/build-dmg.sh b/installer/build-dmg.sh new file mode 100755 index 00000000..f4ba5fde --- /dev/null +++ b/installer/build-dmg.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# 打包 MomentryCore.dmg +set -e + +SRC="/Users/accusys/momentry_core" +BUILD="$SRC/installer/build" +APP="$BUILD/MomentryCore" + +echo ">>> 清理舊 build..." +rm -rf "$BUILD" +mkdir -p "$APP"/{bin,config,tools,logs} + +echo ">>> 複製 binaries..." +cp "$SRC/target/release/momentry" "$APP/bin/" 2>/dev/null || echo " [!] momentry 不存在,執行: cargo build --release" +cp "$SRC/target/release/pipeline_worker" "$APP/bin/" 2>/dev/null || echo " [!] pipeline_worker 不存在" +chmod +x "$APP/bin/"* 2>/dev/null || true + +echo ">>> 複製 config..." +cp "$SRC/installer/config/"* "$APP/config/" +cp "$SRC/config/pipeline_flows.json" "$APP/config/" 2>/dev/null || true +cp "$SRC/config/processor_tools_v3.json" "$APP/config/" 2>/dev/null || true +cp "$SRC/config/admin_config.json" "$APP/config/" 2>/dev/null || true + +echo ">>> 複製 tools (排除 .build, __pycache__)..." +rsync -av --exclude='.build' --exclude='__pycache__' --exclude='*.pyc' \ + "$SRC/tools/" "$APP/tools/" 2>/dev/null || \ + cp -rf "$SRC/tools/"* "$APP/tools/" 2>/dev/null || true + +echo ">>> 複製 install.sh..." +cp "$SRC/installer/install.sh" "$APP/" +cp "$SRC/installer/uninstall.sh" "$APP/" +chmod +x "$APP/install.sh" "$APP/uninstall.sh" + +echo ">>> 建立 README..." +cat > "$APP/README.txt" << 'README' +Momentry Core 安裝說明 + +1. 確認依賴已安裝: + brew install postgresql redis mongodb-mongosh qdrant ffmpeg python@3.11 + +2. 啟動外部服務: + brew services start postgresql + brew services start redis + brew services start mongodb-community + brew services start qdrant + +3. 執行安裝腳本: + ./install.sh + +4. 驗證: + curl http://localhost:3002/api/v1/health +README + +echo ">>> 建立 .dmg..." +DMG="$BUILD/MomentryCore.dmg" +hdiutil create -volname "MomentryCore" \ + -srcfolder "$APP" \ + -ov -format UDZO "$DMG" + +echo "" +echo "================================================" +echo " DMG 建立完成!" +echo " 位置: $DMG" +echo " 大小: $(du -h "$DMG" | cut -f1)" +echo "================================================" diff --git a/installer/build/MomentryCore.dmg b/installer/build/MomentryCore.dmg new file mode 100644 index 00000000..850b4f29 Binary files /dev/null and b/installer/build/MomentryCore.dmg differ diff --git a/installer/build/MomentryCore/README.txt b/installer/build/MomentryCore/README.txt new file mode 100644 index 00000000..a8295aa7 --- /dev/null +++ b/installer/build/MomentryCore/README.txt @@ -0,0 +1,16 @@ +Momentry Core 安裝說明 + +1. 確認依賴已安裝: + brew install postgresql redis mongodb-mongosh qdrant ffmpeg python@3.11 + +2. 啟動外部服務: + brew services start postgresql + brew services start redis + brew services start mongodb-community + brew services start qdrant + +3. 執行安裝腳本: + ./install.sh + +4. 驗證: + curl http://localhost:3002/api/v1/health diff --git a/installer/build/MomentryCore/bin/momentry b/installer/build/MomentryCore/bin/momentry new file mode 100755 index 00000000..78875ee0 Binary files /dev/null and b/installer/build/MomentryCore/bin/momentry differ diff --git a/installer/build/MomentryCore/bin/pipeline_worker b/installer/build/MomentryCore/bin/pipeline_worker new file mode 100755 index 00000000..72fc9ede Binary files /dev/null and b/installer/build/MomentryCore/bin/pipeline_worker differ diff --git a/installer/build/MomentryCore/config/admin_config.json b/installer/build/MomentryCore/config/admin_config.json new file mode 100644 index 00000000..4c8b0eb4 --- /dev/null +++ b/installer/build/MomentryCore/config/admin_config.json @@ -0,0 +1,199 @@ +{ + "version": "1.0.0", + "updated_at": "2026-10-26T17:18:56.139925+00:00", + "updated_by": "admin", + "vlm_prompts": { + "rust_vlm_summary": { + "system_prompt": "You are a helpful assistant that describes people in images.", + "user_prompt": "Describe the person in this image. Focus on clothing, accessories, and distinctive features.", + "max_tokens": 300, + "description": "Face trace VLM prompt for person description" + }, + "scene_vlm": { + "system_prompt": "You are a helpful assistant that analyzes video scenes.", + "user_prompt": "Describe this scene. What is happening? What objects and people are visible?", + "max_tokens": 200, + "description": "Scene analysis VLM prompt" + } + }, + "llm_config": { + "chat": { + "url": "http://localhost:8080/v1/chat/completions", + "model": "gemma-4-12b-it", + "timeout": 30 + }, + "summary": { + "url": "http://localhost:8080/v1/chat/completions", + "model": "gemma-4-12b-it", + "timeout": 60 + } + }, + "processor_config": { + "FACE": { + "timeout": 3600, + "enabled": true, + "tools": [ + { + "name": "swift", + "priority": 0, + "enabled": true, + "parameters": {} + }, + { + "name": "python", + "priority": 2, + "enabled": true, + "parameters": {} + } + ], + "default_tool": "swift" + }, + "FACE_TRACE": { + "timeout": 3600, + "enabled": true, + "tools": [ + { + "name": "rust", + "priority": 0, + "enabled": true, + "parameters": {} + }, + { + "name": "python", + "priority": 1, + "enabled": true, + "parameters": {} + } + ], + "default_tool": "rust" + }, + "POSE": { + "timeout": 3600, + "enabled": true, + "tools": [ + { + "name": "swift", + "priority": 0, + "enabled": true, + "parameters": {} + }, + { + "name": "rust", + "priority": 1, + "enabled": true, + "parameters": {} + }, + { + "name": "mediapipe", + "priority": 2, + "enabled": true, + "parameters": { + "min_confidence": 0.5, + "model_complexity": 2 + } + } + ], + "default_tool": "swift" + }, + "CUT": { + "timeout": 3600, + "enabled": true, + "tools": [ + { + "name": "rust", + "priority": 0, + "enabled": true, + "parameters": {} + }, + { + "name": "python", + "priority": 2, + "enabled": true, + "parameters": {} + } + ], + "default_tool": "rust" + }, + "ASRX": { + "timeout": 3600, + "enabled": true, + "tools": [ + { + "name": "swift", + "priority": 0, + "enabled": true, + "parameters": {} + } + ], + "default_tool": "swift" + }, + "OCR": { + "timeout": 3600, + "enabled": true, + "tools": [ + { + "name": "swift", + "priority": 0, + "enabled": true, + "parameters": {} + } + ], + "default_tool": "swift" + } + }, + "filter_config": { + "face": { + "min_confidence": 0.5, + "min_size": 30 + } + }, + "face_filter_defaults": { + "min_confidence": 50.0, + "min_size": 1, + "min_capture_quality": 0.25 + }, + "paths": { + "output_dir": "", + "backup_dir": "", + "scripts_dir": "", + "cli_dir": "", + "python_path": "", + "ffmpeg_path": "" + }, + "concurrency": { + "max_concurrent_jobs": 0, + "poll_interval": 0, + "batch_size": 0, + "processor_timeout_secs": 0 + }, + "feature_flags": { + "cache_enabled": false, + "auto_pipeline_enabled": false, + "watcher_auto_register": false, + "summary_enabled": false + }, + "server": { + "port": 0, + "media_base_url": "", + "serve_base_url": "", + "storage_root": "", + "timezone": "" + }, + "admin_settings": { + "session_timeout": 0, + "max_login_attempts": 0, + "api_key_expiry_days": 0, + "system_stats_refresh_sec": 0, + "preferred_language": "" + }, + "search": { + "vlm_min_score": 0.0, + "vlm_output_language": "ja" + }, + "pipeline": { + "enabled": true, + "max_concurrent_stages": 5, + "default_timeout_secs": 7200, + "flows": {} + } +} \ No newline at end of file diff --git a/installer/build/MomentryCore/config/pipeline_flows.json b/installer/build/MomentryCore/config/pipeline_flows.json new file mode 100644 index 00000000..bc9095cb --- /dev/null +++ b/installer/build/MomentryCore/config/pipeline_flows.json @@ -0,0 +1,356 @@ +{ + "version": "2.0.0", + "updated_at": "2026-10-16T17:00:00Z", + "updated_by": "core_team", + "enabled": true, + "max_concurrent_stages": 3, + "default_timeout_secs": 3600, + "phases": [ + { + "id": 1, + "name": "基础分析", + "name_en": "Foundation", + "description": "场景切分与分析", + "progress_weight": 0.15, + "color": "#4CAF50", + "icon": "foundation", + "parallel_strategy": "sequential", + "processors": ["cut"] + }, + { + "id": 2, + "name": "核心处理", + "name_en": "Core Processing", + "description": "语音识别、人脸检测、文字识别", + "progress_weight": 0.60, + "color": "#2196F3", + "icon": "processing", + "parallel_strategy": "limited_parallel", + "max_concurrent": 3, + "processors": ["asr_asrx", "face", "ocr"] + }, + { + "id": 3, + "name": "深度分析", + "name_en": "Deep Analysis", + "description": "说话人识别、场景描述、人脸聚类", + "progress_weight": 0.20, + "color": "#9C27B0", + "icon": "analysis", + "parallel_strategy": "limited_parallel", + "max_concurrent": 3, + "processors": ["scene_vlm", "face_trace", "face_cluster"] + }, + { + "id": 4, + "name": "知识构建", + "name_en": "Knowledge Building", + "description": "时序知识图谱构建", + "progress_weight": 0.05, + "color": "#FF9800", + "icon": "knowledge", + "parallel_strategy": "sequential", + "processors": ["tkg"] + } + ], + "flows": { + "register": { + "name": "Video Registration Pipeline", + "description": "Complete video processing pipeline for new video files", + "version": "2.0.0", + "enabled": true, + "stages": [ + { + "name": "cut", + "processor_type": "cut", + "phase": 1, + "phase_name": "基础分析", + "phase_name_en": "Foundation", + "progress_weight": 1.0, + "display_name": "场景切分", + "display_name_en": "Scene Cut Detection", + "description": "Scene cut detection using ffmpeg or Python scenedetect", + "required": true, + "enabled": true, + "timeout_secs": 3600, + "parallel": false, + "estimated_time_secs": 5, + "resource_type": "cpu", + "dependencies": [], + "tool": { + "name": "rust_cut", + "priority": 0, + "description": "High-performance Rust-based scene detection", + "parameters": { + "min_scene_duration": 0.5, + "threshold": 0.3 + }, + "usage_notes": "Uses ffmpeg for native detection. Falls back to Python scenedetect if unavailable." + }, + "condition": { + "skip_if_exists": "*.cut.json" + }, + "on_failure": "continue" + }, + { + "name": "asr_asrx", + "processor_type": "asr_asrx", + "phase": 2, + "phase_name": "核心处理", + "phase_name_en": "Core Processing", + "progress_weight": 0.35, + "display_name": "語音識別與說話人分離", + "display_name_en": "ASR + Speaker Diarization", + "description": "Automatic Speech Recognition with Speaker Diarization using Rust + MLX Whisper", + "required": false, + "enabled": true, + "timeout_secs": 3600, + "parallel": true, + "estimated_time_secs": 25, + "resource_type": "gpu", + "dependencies": [], + "tool": { + "name": "rust_asr_asrx", + "priority": 0, + "description": "High-performance Rust ASR + Diarization with MLX Whisper", + "parameters": { + "model": "/Users/accusys/models/whisper-small-mlx", + "diarize": true + }, + "usage_notes": "Combines ASR and Diarization in one processor. Uses verified whisper-small-mlx model." + }, + "condition": { + "skip_if_exists": "*.asr_asrx.json" + }, + "on_failure": "continue" + }, + { + "name": "face", + "processor_type": "face", + "phase": 2, + "phase_name": "核心处理", + "phase_name_en": "Core Processing", + "progress_weight": 0.35, + "display_name": "人脸检测", + "display_name_en": "Face Detection", + "description": "Face detection and tracking", + "required": false, + "enabled": true, + "timeout_secs": 7200, + "parallel": true, + "estimated_time_secs": 15, + "resource_type": "ane", + "dependencies": [], + "tool": { + "name": "swift_face", + "priority": 0, + "description": "Apple Vision framework face detection (ANE accelerated)", + "parameters": { + "min_confidence": 0.5, + "min_size": 1 + }, + "usage_notes": "Uses Apple Neural Engine for acceleration. Falls back to Python InsightFace if unavailable." + }, + "condition": { + "skip_if_exists": "*.face.json" + }, + "on_failure": "continue" + }, + { + "name": "ocr", + "processor_type": "ocr", + "phase": 2, + "phase_name": "核心处理", + "phase_name_en": "Core Processing", + "progress_weight": 0.30, + "display_name": "文字识别", + "display_name_en": "OCR", + "description": "OCR text extraction using Apple Vision Framework", + "required": false, + "enabled": true, + "timeout_secs": 7200, + "parallel": true, + "estimated_time_secs": 10, + "resource_type": "ane", + "dependencies": [], + "tool": { + "name": "swift_ocr", + "priority": 0, + "description": "Apple Vision VNRecognizeTextRequest (ANE accelerated)", + "parameters": { + "recognition_level": "accurate", + "uses_language_correction": true + }, + "usage_notes": "Uses Apple Neural Engine for acceleration. Supports multiple languages with real-time recognition. 2.5x faster than Python (2s vs 5s)." + }, + "condition": { + "skip_if_exists": "*.ocr.json" + }, + "on_failure": "continue" + }, + { + "name": "scene_vlm", + "processor_type": "scene_vlm", + "phase": 3, + "phase_name": "深度分析", + "phase_name_en": "Deep Analysis", + "progress_weight": 0.35, + "display_name": "场景描述", + "display_name_en": "Scene Description", + "description": "Scene VLM analysis for scene descriptions", + "required": false, + "enabled": true, + "timeout_secs": 7200, + "parallel": true, + "estimated_time_secs": 10, + "resource_type": "gpu", + "dependencies": ["cut"], + "tool": { + "name": "gemma_vlm", + "priority": 0, + "description": "Gemma 4 12B with mmproj for vision-language analysis", + "parameters": { + "max_tokens": 900, + "temperature": 0.1 + }, + "usage_notes": "Generates scene descriptions in multiple languages. Requires mmproj loaded." + }, + "condition": { + "depends_on": "cut", + "skip_if_exists": "*.scenes.json" + }, + "on_failure": "continue" + }, + { + "name": "face_trace", + "processor_type": "face_trace", + "phase": 3, + "phase_name": "深度分析", + "phase_name_en": "Deep Analysis", + "progress_weight": 0.20, + "display_name": "人脸追踪", + "display_name_en": "Face Tracing", + "description": "Face tracking to generate face traces using IoU + Embedding Similarity", + "required": false, + "enabled": true, + "timeout_secs": 3600, + "parallel": true, + "estimated_time_secs": 5, + "resource_type": "cpu", + "dependencies": ["face"], + "tool": { + "name": "rust_face_trace", + "priority": 0, + "description": "Rust-based face tracking with IoU + Embedding similarity matching", + "parameters": { + "similarity_threshold": 0.85, + "iou_threshold": 0.3 + }, + "usage_notes": "Uses Qdrant _faces collection for embeddings. Matches faces based on IoU (bbox overlap) and embedding similarity. Traces are continuous face sequences; same person may have multiple traces due to cuts or temporary exits." + }, + "condition": { + "depends_on": "face", + "skip_if_exists": "*.face_traced.json" + }, + "on_failure": "continue" + }, + { + "name": "face_cluster", + "processor_type": "face_cluster", + "phase": 3, + "phase_name": "深度分析", + "phase_name_en": "Deep Analysis", + "progress_weight": 0.25, + "display_name": "人脸聚类", + "display_name_en": "Face Clustering", + "description": "Face clustering and grouping with improved threshold", + "required": false, + "enabled": true, + "timeout_secs": 3600, + "parallel": true, + "estimated_time_secs": 5, + "resource_type": "cpu", + "dependencies": ["face_trace"], + "tool": { + "name": "rust_face_cluster", + "priority": 0, + "description": "Rust-based face clustering with Stage 2 merge support", + "parameters": { + "threshold": 0.15, + "stage2": false, + "method": "leader", + "min_face_count": 20, + "max_bbox_area": 150000 + }, + "usage_notes": "Uses Qdrant _faces collection for embeddings. Threshold=0.15 to correctly separate male/female faces. Stage 2 merge disabled to prevent over-merging. Auto-filters low-quality clusters: face_count<20 or bbox_area>150000 (hand/object detections)." + }, + "condition": { + "depends_on": "face_trace", + "skip_if_exists": "*.face_cluster.json" + }, + "on_failure": "continue" + }, + { + "name": "tkg", + "processor_type": "tkg", + "phase": 4, + "phase_name": "知识构建", + "phase_name_en": "Knowledge Building", + "progress_weight": 1.0, + "display_name": "知识图谱", + "display_name_en": "Knowledge Graph", + "description": "Temporal knowledge graph construction", + "required": false, + "enabled": true, + "timeout_secs": 3600, + "parallel": false, + "estimated_time_secs": 5, + "resource_type": "cpu", + "dependencies": ["asr_asrx", "face_cluster"], + "condition": { + "depends_on": ["asr_asrx", "face_cluster"], + "skip_if_exists": "*.tkg.json" + }, + "on_failure": "continue" + } + ] + }, + "reprocess": { + "name": "Reprocessing Pipeline", + "description": "Selective reprocessing of specific processors", + "version": "2.0.0", + "enabled": true, + "stages": [] + }, + "phase1_pack": { + "name": "Phase 1 Packaging Pipeline", + "description": "Package Phase 1 results for delivery", + "version": "2.0.0", + "enabled": true, + "stages": [ + { + "name": "pack", + "processor_type": "pack", + "phase": 4, + "phase_name": "知识构建", + "phase_name_en": "Knowledge Building", + "progress_weight": 1.0, + "display_name": "打包", + "display_name_en": "Pack", + "description": "Create release package with all Phase 1 outputs", + "required": true, + "enabled": true, + "timeout_secs": 600, + "parallel": false, + "estimated_time_secs": 10, + "resource_type": "cpu", + "dependencies": [], + "parameters": { + "phase": 1, + "include_metadata": true + } + } + ] + } + } +} \ No newline at end of file diff --git a/installer/build/MomentryCore/config/processor_tools_v3.json b/installer/build/MomentryCore/config/processor_tools_v3.json new file mode 100644 index 00000000..cba67193 --- /dev/null +++ b/installer/build/MomentryCore/config/processor_tools_v3.json @@ -0,0 +1,331 @@ +{ + "processor_config": { + "face": { + "implementations": [ + { + "tool": "swift", + "model": null, + "priority": 0, + "enabled": true, + "command": { + "executable": "scripts/swift_processors/.build/release/swift_face", + "args": [ + "{video_path}", + "{output_path}", + "--uuid", + "{file_uuid}" + ] + }, + "parameters": {}, + "output_file": "{file_uuid}.face.json", + "timeout": 3600 + } + ], + "default": { + "tool": "swift", + "model": null + } + }, + "asr": { + "implementations": [ + { + "tool": "rust", + "model": "whisper", + "priority": 0, + "enabled": true, + "command": { + "executable": "tools/cli/rust/target/release/rust_whisper", + "args": [ + "{video_path}", + "--output", + "{output_path}", + "--uuid", + "{file_uuid}", + "--model", + "{model_size}" + ] + }, + "parameters": { + "model_size": "base" + }, + "output_file": "{file_uuid}.asr.json", + "timeout": 3600 + } + ], + "default": { + "tool": "rust", + "model": "whisper" + } + }, + "asr_asrx": { + "implementations": [ + { + "tool": "rust", + "model": "whisper", + "priority": 0, + "enabled": true, + "command": { + "executable": "tools/cli/rust/target/release/rust_asr_asrx", + "args": [ + "--input", + "{video_path}", + "--output", + "{output_path}", + "--model", + "/Users/accusys/models/whisper-small-mlx", + "--diarize", + "true" + ] + }, + "parameters": { + "model_dir": "/Users/accusys/models/whisper-small-mlx" + }, + "output_file": "{file_uuid}.asr_asrx.json", + "timeout": 3600 + } + ], + "default": { + "tool": "rust", + "model": "whisper" + } + }, + "asrx": { + "implementations": [ + { + "tool": "rust", + "model": null, + "priority": 0, + "enabled": true, + "command": { + "executable": "tools/cli/rust/target/release/rust_asrx", + "args": [ + "{video_path}", + "{output_path}", + "--uuid", + "{file_uuid}" + ] + }, + "parameters": {}, + "output_file": "{file_uuid}.asrx.json", + "timeout": 1800 + } + ], + "default": { + "tool": "rust", + "model": null + } + }, + "ocr": { + "implementations": [ + { + "tool": "swift", + "model": null, + "priority": 0, + "enabled": true, + "command": { + "executable": "scripts/swift_processors/.build/release/swift_ocr", + "args": [ + "{video_path}", + "--output", + "{output_path}", + "--uuid", + "{file_uuid}" + ] + }, + "parameters": {}, + "output_file": "{file_uuid}.ocr.json", + "timeout": 3600 + } + ], + "default": { + "tool": "swift", + "model": null + } + }, + "face_trace": { + "implementations": [ + { + "tool": "rust", + "model": null, + "priority": 0, + "enabled": true, + "command": { + "executable": "tools/cli/rust/target/release/rust_store_traced_faces", + "args": [ + "{file_uuid}", + "--output-dir", + "{output_dir}", + "--min-trace-len", + "{min_trace_len}", + "--min-confidence", + "{min_confidence}" + ] + }, + "parameters": { + "min_trace_len": 0, + "min_confidence": 0.0 + }, + "output_file": "{file_uuid}.face_traced.json", + "timeout": 600 + } + ], + "default": { + "tool": "rust", + "model": null + } + }, + "scene_vlm_summary": { + "implementations": [ + { + "tool": "rust", + "model": "gemma-4-12b-it", + "priority": 0, + "enabled": true, + "command": { + "executable": "tools/cli/rust/target/release/rust_scene_vlm", + "args": [ + "--file-uuid", + "{file_uuid}", + "--output-dir", + "{output_dir}", + "--llm-url", + "{llm_url}", + "--max-tokens", + "{max_tokens}" + ] + }, + "parameters": { + "llm_url": "http://localhost:8080/v1/chat/completions", + "max_tokens": 900 + }, + "output_file": "{file_uuid}.scene_vlm.json", + "timeout": 1800 + } + ], + "default": { + "tool": "rust", + "model": null + } + }, + "tkg": { + "implementations": [ + { + "tool": "rust", + "model": null, + "priority": 0, + "enabled": true, + "command": { + "executable": "tools/cli/rust/target/release/rust_tkg", + "args": [ + "--file-uuid", + "{file_uuid}", + "--output-dir", + "{output_dir}" + ] + }, + "parameters": {}, + "output_file": "{file_uuid}.tkg.json", + "timeout": 1800 + } + ], + "default": { + "tool": "rust", + "model": null + } + }, + "cut": { + "implementations": [ + { + "tool": "rust", + "model": null, + "priority": 0, + "enabled": true, + "command": { + "executable": "tools/cli/rust/target/release/rust_cut", + "args": [ + "{video_path}", + "--output", + "{output_path}", + "--uuid", + "{file_uuid}", + "--min-scene-duration", + "{min_scene_duration}" + ] + }, + "parameters": { + "use_ffmpeg": true, + "min_scene_duration": 0.5 + }, + "output_file": "{file_uuid}.cut.json", + "timeout": 1800 + } + ], + "default": { + "tool": "rust", + "model": null + } + } + }, + "variables": { + "video_path": "Full path to video file", + "output_path": "Full path to output JSON file", + "output_dir": "Output directory (default: /Users/accusys/momentry/output)", + "file_uuid": "Video file UUID", + "face_json": "Path to face.json file" + }, + "environment": { + "MOMENTRY_OUTPUT_DIR": "/Users/accusys/momentry/output", + "MOMENTRY_SCRIPTS_DIR": "tools/script/", + "MOMENTRY_CLI_DIR": "tools/cli/", + "MOMENTRY_PYTHON_PATH": "/opt/homebrew/bin/python3.11", + "DATABASE_SCHEMA": "public", + "DATABASE_URL": "postgres://accusys@localhost:5432/momentry", + "REDIS_URL": "redis://:accusys@localhost:6379" + }, + "models": { + "whisper": { + "description": "OpenAI Whisper ASR model", + "sizes": [ + "tiny", + "base", + "small", + "medium", + "large", + "large-v3" + ], + "default_size": "large-v3", + "model_dir": "/Users/accusys/models/whisper-small-mlx" + }, + "mediapipe": { + "description": "MediaPipe Pose estimation", + "model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task", + "complexity_levels": [ + 0, + 1, + 2 + ], + "default_complexity": 2 + }, + "facenet": { + "description": "FaceNet 512D embedding model", + "model_path": "/Users/accusys/models/facenet512.mlpackage" + }, + "gemma-4-12b-it": { + "description": "Gemma 4 12B instruct model for VLM/LLM", + "model_path": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf", + "mmproj_path": "/Users/accusys/models/mmproj-F16.gguf", + "llm_url": "http://localhost:8080/v1/chat/completions" + }, + "embeddinggemma-300m": { + "description": "Embedding Gemma 300M for vector embeddings", + "model_path": "/Users/accusys/models/embeddinggemma-300M-Q8_0.gguf", + "embedding_url": "http://localhost:11436/embed" + } + }, + "metadata": { + "version": "3.0", + "description": "Processor configuration - CLI tools (rust/swift) prioritized", + "priority_policy": "rust/swift CLI (priority 0) > python (priority 1+)", + "last_updated": "2026-09-27" + } +} \ No newline at end of file diff --git a/installer/build/MomentryCore/config/production.env.template b/installer/build/MomentryCore/config/production.env.template new file mode 100644 index 00000000..d45906f8 --- /dev/null +++ b/installer/build/MomentryCore/config/production.env.template @@ -0,0 +1,17 @@ +DATABASE_URL=postgres://accusys@localhost:5432/momentry +DATABASE_SCHEMA=public +REDIS_URL=redis://:accusys@localhost:6379 +MOMENTRY_REDIS_PREFIX=momentry: +MOMENTRY_SERVER_PORT=3002 +MOMENTRY_OUTPUT_DIR=$HOME/momentry/output +MOMENTRY_BACKUP_DIR=$HOME/momentry/backup +QDRANT_URL=http://127.0.0.1:6333 +MONGODB_URL=mongodb://localhost:27017 +MOMENTRY_LLM_VISION_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it +MOMENTRY_LLM_CHAT_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it +MOMENTRY_LLM_SUMMARY_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_SUMMARY_MODEL=gemma-4-12b-it +MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11 +RUST_LOG=info diff --git a/installer/build/MomentryCore/install.sh b/installer/build/MomentryCore/install.sh new file mode 100755 index 00000000..24d26b40 --- /dev/null +++ b/installer/build/MomentryCore/install.sh @@ -0,0 +1,143 @@ +#!/bin/bash +# Momentry Core 安裝腳本 +set -e + +APP_NAME="MomentryCore" +INSTALL_DIR="$HOME/Library/Application Support/$APP_NAME" +LAUNCHD_DIR="$HOME/Library/LaunchAgents" +LOG_DIR="$INSTALL_DIR/logs" + +RED='\033[0;31m' +GREEN='\033[0;32m' +NC='\033[0m' + +echo "================================================" +echo " Momentry Core 安裝程式" +echo "================================================" + +# 1. 檢查依賴 +echo ">>> 檢查系統依賴..." +MISSING="" +check() { + if eval "$2" >/dev/null 2>&1; then + echo " [OK] $1" + else + echo " [FAIL] $1 - $3" + MISSING="$MISSING $1" + fi +} +check "PostgreSQL" "psql --version" "brew install postgresql" +check "Redis" "redis-cli ping" "brew install redis" +check "Qdrant" "curl -s --max-time 3 http://localhost:6333/ready | grep -q ok" "brew install qdrant" +check "MongoDB" "mongosh --version || mongo --version" "brew install mongosh" +check "Python 3.11" "python3.11 --version" "brew install python@3.11" +check "ffprobe" "ffprobe -version" "brew install ffmpeg" +check "MarkBaseServer" "curl -s --max-time 3 http://localhost:8080/v1/models | grep -q model" "安裝 MarkBaseEngine" + +if [ -n "$MISSING" ]; then + echo -e "\n${RED}缺少依賴:$MISSING${NC}" + echo "brew install postgresql redis mongosh ffmpeg python@3.11" + exit 1 +fi +echo -e "\n${GREEN}所有依賴已安裝${NC}" + +# 2. 建立目錄 +echo ">>> 建立目錄..." +mkdir -p "$INSTALL_DIR"/{bin,config,tools/script,tools/cli,logs} +SRC_DIR="$(cd "$(dirname "$0")" && pwd)" +cp -f "$SRC_DIR/bin/momentry" "$INSTALL_DIR/bin/" 2>/dev/null || echo " [!] momentry binary 需手動放置" +cp -f "$SRC_DIR/bin/pipeline_worker" "$INSTALL_DIR/bin/" 2>/dev/null || echo " [!] pipeline_worker 需手動放置" +chmod +x "$INSTALL_DIR/bin/"* 2>/dev/null || true +cp -rf "$SRC_DIR/config/"* "$INSTALL_DIR/config/" 2>/dev/null || true +cp -rf "$SRC_DIR/tools/"* "$INSTALL_DIR/tools/" 2>/dev/null || true +echo " -> $INSTALL_DIR" + +# 3. 產生 .env +ENV_FILE="$INSTALL_DIR/.env" +if [ ! -f "$ENV_FILE" ]; then + cat > "$ENV_FILE" << ENVEOF +DATABASE_URL=postgres://accusys@localhost:5432/momentry +DATABASE_SCHEMA=public +REDIS_URL=redis://:accusys@localhost:6379 +MOMENTRY_REDIS_PREFIX=momentry: +MOMENTRY_SERVER_PORT=3002 +MOMENTRY_OUTPUT_DIR=$HOME/momentry/output +QDRANT_URL=http://127.0.0.1:6333 +MONGODB_URL=mongodb://localhost:27017 +MOMENTRY_LLM_VISION_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it +MOMENTRY_LLM_CHAT_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it +MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11 +MOMENTRY_SCRIPTS_DIR=$INSTALL_DIR/tools/script +MOMENTRY_CLI_DIR=$INSTALL_DIR/tools/cli +RUST_LOG=info +ENVEOF + echo " [OK] 已產生 .env" +else + echo " [OK] .env 已存在" +fi + +# 4. 安裝 Launchd +echo ">>> 安裝 launchd services..." +cat > "$LAUNCHD_DIR/com.momentry-core.server.plist" << PLIST + + + + Labelcom.momentry-core.server + Program$INSTALL_DIR/bin/momentry + ProgramArguments + momentryserver + --host0.0.0.0 + --port3002 + + WorkingDirectory$INSTALL_DIR + EnvironmentVariables + DOTENV_PATH$ENV_FILE + + KeepAliveSuccessfulExit + RunAtLoad + StandardOutPath$LOG_DIR/server.log + StandardErrorPath$LOG_DIR/server.log + +PLIST + +cat > "$LAUNCHD_DIR/com.momentry-core.worker.plist" << PLIST + + + + Labelcom.momentry-core.worker + Program$INSTALL_DIR/bin/pipeline_worker + WorkingDirectory$INSTALL_DIR + EnvironmentVariables + DOTENV_PATH$ENV_FILE + + KeepAliveSuccessfulExit + RunAtLoad + StandardOutPath$LOG_DIR/worker.log + StandardErrorPath$LOG_DIR/worker.log + +PLIST +echo " [OK] server + worker plist" + +# 5. 啟動 +echo ">>> 啟動服務..." +launchctl bootout "gui/$(id -u)/com.momentry-core.server" 2>/dev/null || true +launchctl bootout "gui/$(id -u)/com.momentry-core.worker" 2>/dev/null || true +sleep 1 +launchctl bootstrap "gui/$(id -u)" "$LAUNCHD_DIR/com.momentry-core.server.plist" +launchctl bootstrap "gui/$(id -u)" "$LAUNCHD_DIR/com.momentry-core.worker.plist" +sleep 3 + +if curl -s --max-time 5 "http://localhost:3002/api/v1/health" >/dev/null 2>&1; then + echo -e "${GREEN}[OK] API server 啟動成功${NC}" +else + echo -e "${YELLOW}[!] 檢查日誌: $LOG_DIR/server.log${NC}" +fi + +echo "" +echo "================================================" +echo " 安裝完成!" +echo " 目錄: $INSTALL_DIR" +echo " API: http://localhost:3002" +echo "================================================" diff --git a/installer/build/MomentryCore/tools/README.md b/installer/build/MomentryCore/tools/README.md new file mode 100644 index 00000000..b5e4d0ea --- /dev/null +++ b/installer/build/MomentryCore/tools/README.md @@ -0,0 +1,179 @@ +--- +title: Tools Directory +version: 1.1 +date: 2026-09-27 +author: OpenCode +status: migrated +--- + +## 目錄結構 + +``` +tools/ +├── script/ # Python 處理器腳本 +│ ├── asr/ # ASR 處理器 +│ ├── face/ # Face 處理器 +│ ├── pose/ # Pose 處理器 +│ ├── cut/ # Cut 處理器 +│ ├── ocr/ # OCR 處理器 +│ ├── vlm/ # VLM 處理器 +│ ├── embedding/ # Embedding 服務器 +│ ├── identity/ # Identity 處理器 +│ └── utils/ # 工具腳本 +└── cli/ # Swift/Rust CLI 工具 + ├── swift/ # Swift 處理器 + └── rust/ # Rust 處理器 +``` + +## Python 腳本 (script/) + +### ASR +- `asr_processor_base.py` - ASR 基礎類 +- `asr_processor_contract_v1.py` - ASR V1 合約 +- `asr_processor_contract_v2.py` - ASR V2 合約 + +### Face +- `face_processor.py` - Face 處理器 +- `store_traced_faces.py` - Face 追蹤存儲 + +### Pose +- `pose_processor.py` - Pose 處理器 + +### Cut +- `cut_processor.py` - Cut 處理器 + +### OCR +- `ocr_processor.py` - OCR 處理器 + +### VLM +- `tkg_builder.py` - TKG Builder +- `appearance_processor_v2.py` - Appearance 處理器 + +### Embedding +- `embeddinggemma_server.py` - Embedding 服務器 + +### Identity +- `identity_agent.py` - Identity Agent +- `identity_bind.py` - Identity 綁定 +- `identity_matcher.py` - Identity 匹配 + +## CLI 工具 (cli/) + +### Swift + +**處理器**: +- `asr_swift.swift` - ASR Swift 處理器 +- `asrx_swift.swift` - ASRX Swift 處理器 +- `swift_face.swift` - Face Swift 處理器 +- `swift_pose.swift` - Pose Swift 處理器 +- `swift_ocr.swift` - OCR Swift 處理器 +- `swift_hand.swift` - Hand Swift 處理器 +- `swift_face_pose.swift` - Face+Pose Swift 處理器 + +**擴展**: +- `swift_appearance_expansion.swift` - Appearance 擴展 +- `swift_pose_expansion.swift` - Pose 擴展 + +**測試**: +- `face_vision_test.swift` +- `pose_benchmark.swift` +- `speaker_test.swift` + +### Rust + +獨立的 Rust CLI 工具項目,包含: +- Face Cluster +- Appearance +- Pose + +## 使用方式 + +### Python 腳本 + +```bash +# ASR +python3 tools/script/asr/asr_processor_contract_v2.py + +# Face +python3 tools/script/face/face_processor.py + +# TKG +python3 tools/script/vlm/tkg_builder.py +``` + +### Swift CLI + +```bash +# 編譯 +cd tools/cli/swift +swift build + +# 運行 +swift run asr_swift +swift run swift_face +``` + +### Rust CLI + +```bash +# 編譯 +cd tools/cli/rust +cargo build --release + +# 運行 +./target/release/face_cluster +./target/release/appearance +``` + +## 環境變數配置 + +### 腳本路徑 + +```bash +# Python 腳本路徑 +export MOMENTRY_SCRIPTS_DIR=/Users/accusys/momentry_core/tools/script + +# CLI 工具路徑 +export MOMENTRY_CLI_DIR=/Users/accusys/momentry_core/tools/cli +``` + +### 其他路徑 + +```bash +# 輸出路徑 +export MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output + +# Python 路徑 +export MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11 +``` + +## Rust 代碼中使用 + +```rust +use crate::core::config::{SCRIPTS_DIR, CLI_DIR}; + +// 獲取腳本路徑 +let scripts_dir = SCRIPTS_DIR.as_str(); + +// 獲取 CLI 路徑 +let cli_dir = CLI_DIR.as_str(); +``` + +## 遷移說明 + +### 來源 + +- Python: `scripts/` → `tools/script/` +- Swift: `scripts/swift_processors/` → `tools/cli/swift/` +- Rust: `scripts/rust_processors/` → `tools/cli/rust/` + +### 原路徑保留 + +舊路徑 `scripts/` 仍然存在,可以繼續使用。 + +新代碼建議使用 `tools/` 路徑。 + +## 相關文檔 + +- `/Users/accusys/momentry_core/docs_v1.0/DESIGN/Tools_Directory_Restructure.md` +- `/Users/accusys/momentry_core/AGENTS.md` - 環境變數配置 diff --git a/installer/build/MomentryCore/tools/cli/rust/.gitignore b/installer/build/MomentryCore/tools/cli/rust/.gitignore new file mode 100644 index 00000000..38c08a83 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock.orig \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/rust/Cargo.lock b/installer/build/MomentryCore/tools/cli/rust/Cargo.lock new file mode 100644 index 00000000..ccbc4157 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/Cargo.lock @@ -0,0 +1,3144 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom 8.0.0", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "der" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" +dependencies = [ + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "exr" +version = "1.74.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "num-complex", + "pulp", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hmac-sha256" +version = "1.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec9d92d097f4749b64e8cc33d924d9f40a2d4eb91402b458014b781f5733d60f" + +[[package]] +name = "hound" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lzma-rust2" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619" + +[[package]] +name = "matrixmultiply" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +dependencies = [ + "autocfg", + "rawpointer", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "ndarray" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "bytemuck", + "num-traits", +] + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "ort" +version = "2.0.0-rc.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4336a1e2b38848325241c72889086886004e589b7c74f335e60a8e8db5138a0b" +dependencies = [ + "ndarray", + "ort-sys", + "smallvec", + "tracing", + "ureq 3.4.2", +] + +[[package]] +name = "ort-sys" +version = "2.0.0-rc.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf211e3776eea6aec988552fa118dd746d70e1b1e5e244058d1c98015f3e5872" +dependencies = [ + "hmac-sha256", + "lzma-rust2", + "ureq 3.4.2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pulp" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools 0.14.0", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand", + "rand_chacha", + "simd_helpers", + "thiserror", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rust_processors" +version = "0.1.0" +dependencies = [ + "anyhow", + "async-trait", + "base64 0.22.1", + "chrono", + "clap", + "hound", + "image", + "ndarray", + "ort", + "regex", + "reqwest", + "rustfft", + "serde", + "serde_json", + "tokio", + "ureq 2.12.1", + "uuid", + "whisper-rs", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "socks" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0c3dbbd9ae980613c6dd8e28a9407b50509d3803b57624d5dfe8315218cd58b" +dependencies = [ + "byteorder", + "libc", + "winapi", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64 0.22.1", + "flate2", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "ureq" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +dependencies = [ + "base64 0.23.1", + "der", + "log", + "native-tls", + "percent-encoding", + "rustls-pki-types", + "socks", + "ureq-proto", + "utf8-zero", + "webpki-root-certs", +] + +[[package]] +name = "ureq-proto" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.5", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.9", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "whisper-rs" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2088172d00f936c348d6a72f488dc2660ab3f507263a195df308a3c2383229f6" +dependencies = [ + "whisper-rs-sys", +] + +[[package]] +name = "whisper-rs-sys" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6986c0fe081241d391f09b9a071fbcbb59720c3563628c3c829057cf69f2a56f" +dependencies = [ + "bindgen", + "cfg-if", + "cmake", + "fs_extra", + "semver", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/installer/build/MomentryCore/tools/cli/rust/Cargo.toml b/installer/build/MomentryCore/tools/cli/rust/Cargo.toml new file mode 100644 index 00000000..793de338 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/Cargo.toml @@ -0,0 +1,78 @@ +[package] +name = "rust_processors" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "rust_vad" +path = "src/bin/rust_vad.rs" + +[[bin]] +name = "rust_appearance" +path = "src/bin/rust_appearance.rs" + +[[bin]] +name = "rust_pose" +path = "src/bin/rust_pose.rs" + +[[bin]] +name = "rust_cut" +path = "src/bin/rust_cut.rs" + +[[bin]] +name = "rust_face_cluster" +path = "src/bin/rust_face_cluster.rs" + +[[bin]] +name = "rust_store_traced_faces" +path = "src/bin/rust_store_traced_faces.rs" + +[[bin]] +name = "rust_scene_vlm" +path = "src/bin/rust_scene_vlm.rs" + +[[bin]] +name = "rust_facenet" +path = "src/bin/rust_facenet.rs" + +[[bin]] +name = "rust_facenet_coreml" +path = "src/bin/rust_facenet_coreml.rs" + +[[bin]] +name = "rust_face_processor" +path = "src/bin/rust_face_processor.rs" + +[[bin]] +name = "rust_asrx" +path = "src/bin/rust_asrx.rs" + +[[bin]] +name = "rust_asr_asrx" +path = "src/bin/rust_asr_asrx.rs" + +[[bin]] +name = "rust_whisper_rs" +path = "src/bin/rust_whisper_rs.rs" + +[dependencies] +ort = { version = "2.0.0-rc.13", features = ["download-binaries"] } +hound = "3.5" +ndarray = "0.17" +rustfft = "6.4" +anyhow = "1.0" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +clap = { version = "4.0", features = ["derive"] } +image = "0.25" +tokio = { version = "1.0", features = ["full"] } +async-trait = "0.1" +reqwest = { version = "0.12", features = ["json", "blocking"] } +base64 = "0.22" +regex = "1.0" +chrono = { version = "0.4", features = ["serde"] } +uuid = { version = "1.0", features = ["v4"] } +ureq = { version = "2.9", features = ["json"] } +whisper-rs = { version = "0.16", features = ["metal"] } + +[workspace] diff --git a/installer/build/MomentryCore/tools/cli/rust/Cargo.toml.old b/installer/build/MomentryCore/tools/cli/rust/Cargo.toml.old new file mode 100644 index 00000000..42e1d9cc --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/Cargo.toml.old @@ -0,0 +1,59 @@ +[package] +name = "rust_processors" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "rust_vad" +path = "src/bin/rust_vad.rs" + +[[bin]] +name = "rust_appearance" +path = "src/bin/rust_appearance.rs" + +[[bin]] +name = "rust_pose" +path = "src/bin/rust_pose.rs" + +[[bin]] +name = "rust_cut" +path = "src/bin/rust_cut.rs" + +[[bin]] +name = "rust_face_cluster" +path = "src/bin/rust_face_cluster.rs" + +[[bin]] +name = "rust_store_traced_faces" +path = "src/bin/rust_store_traced_faces.rs" + +[[bin]] +name = "rust_scene_vlm" +path = "src/bin/rust_scene_vlm.rs" + +[[bin]] +name = "rust_facenet" +path = "src/bin/rust_facenet.rs" + +[[bin]] +name = "rust_facenet_coreml" +path = "src/bin/rust_facenet_coreml.rs" + +[dependencies] +ort = { version = "2.0.0-rc.13", features = ["download-binaries", "coreml"] } +hound = "3.5" +ndarray = "0.17" +anyhow = "1.0" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +clap = { version = "4.0", features = ["derive"] } +image = "0.25" +tokio = { version = "1.0", features = ["full"] } +async-trait = "0.1" +reqwest = { version = "0.12", features = ["json"] } +base64 = "0.22" +regex = "1.0" +chrono = { version = "0.4", features = ["serde"] } +uuid = { version = "1.0", features = ["v4"] } + +[workspace] diff --git a/installer/build/MomentryCore/tools/cli/rust/src/asrx/cluster.rs b/installer/build/MomentryCore/tools/cli/rust/src/asrx/cluster.rs new file mode 100644 index 00000000..8155e15a --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/asrx/cluster.rs @@ -0,0 +1,138 @@ +//! Speaker clustering: faithful port of `speaker_cluster_fixed.py` +//! (agglomerative average-linkage with cosine distance). + +/// Cosine distance matrix `[n][n]` for L2-normalized embeddings. +/// `dist[i][j] = 1 - dot(e_i, e_j)`. +pub fn cosine_distances(embeddings: &[Vec]) -> Vec> { + let n = embeddings.len(); + let mut d = vec![vec![0f32; n]; n]; + for i in 0..n { + for j in (i + 1)..n { + let dot: f32 = embeddings[i] + .iter() + .zip(embeddings[j].iter()) + .map(|(a, b)| a * b) + .sum(); + let v = 1.0 - dot; + d[i][j] = v; + d[j][i] = v; + } + } + d +} + +/// Port of `estimate_n_speakers_from_embeddings`; result clamped to `[2, max]`. +pub fn estimate_n_speakers(distances: &[Vec], max_speakers: usize) -> usize { + let n = distances.len(); + if n < 2 { + return 2; + } + let sample = n.min(200); + let mut min_distances = Vec::with_capacity(sample); + for i in 0..sample { + let mut row = distances[i].clone(); + row.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + if row.len() > 1 { + min_distances.push(row[1]); + } + } + if min_distances.is_empty() { + return 2; + } + let avg = min_distances.iter().sum::() / min_distances.len() as f32; + let threshold = avg * 1.5; + + let m = min_distances.len(); + let mut assigned = vec![false; m]; + let mut n_speakers = 1usize; + for i in 0..m { + if assigned[i] { + continue; + } + n_speakers += 1; + for j in (i + 1)..m { + if assigned[j] { + continue; + } + let idx_i = if n > 200 { i * (n / 200) } else { i }; + let idx_j = if n > 200 { j * (n / 200) } else { j }; + if idx_i < n && idx_j < n && distances[idx_i][idx_j] < threshold { + assigned[j] = true; + } + } + } + n_speakers.clamp(2, max_speakers.max(2)) +} + +/// Agglomerative clustering (average linkage) using a precomputed distance +/// matrix, stopping at `k` clusters. Returns a label per point. +pub fn agglomerative(distances: &[Vec], k: usize) -> Vec { + let n = distances.len(); + if n == 0 { + return Vec::new(); + } + if k >= n { + return (0..n).collect(); + } + let mut d = distances.to_vec(); + let mut root: Vec = (0..n).collect(); // union-find representative + let mut active = vec![true; n]; + let mut size = vec![1usize; n]; + let mut remaining = n; + + while remaining > k { + let mut best_i = 0; + let mut best_j = 1; + let mut best = f32::INFINITY; + for i in 0..n { + if !active[i] { + continue; + } + for j in (i + 1)..n { + if active[j] && d[i][j] < best { + best = d[i][j]; + best_i = i; + best_j = j; + } + } + } + + // Merge best_j into best_i (UPGMA average linkage update). + let (i, j) = (best_i, best_j); + let si = size[i] as f32; + let sj = size[j] as f32; + for x in 0..n { + if x == i || x == j || !active[x] { + continue; + } + let v = (si * d[i][x] + sj * d[j][x]) / (si + sj); + d[i][x] = v; + d[x][i] = v; + } + size[i] += size[j]; + active[j] = false; + root[j] = i; + remaining -= 1; + } + + let find = |root: &Vec, mut x: usize| -> usize { + while root[x] != x { + x = root[x]; + } + x + }; + + let mut label_of: std::collections::HashMap = std::collections::HashMap::new(); + let mut labels = vec![0usize; n]; + let mut next = 0usize; + for p in 0..n { + let r = find(&root, p); + let label = *label_of.entry(r).or_insert_with(|| { + let l = next; + next += 1; + l + }); + labels[p] = label; + } + labels +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/asrx/mod.rs b/installer/build/MomentryCore/tools/cli/rust/src/asrx/mod.rs new file mode 100644 index 00000000..7b251fee --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/asrx/mod.rs @@ -0,0 +1,192 @@ +//! Rust-native speaker diarization (ASRX) building blocks. +//! +//! - `Frontend`: speechbrain-compatible fbank frontend (framing, STFT via +//! rustfft, mel filterbank, log-dB, sentence mean-normalization). +//! - `Ecapa`: ECAPA-TDNN speaker-embedding network (ONNX, `feats -> embedding`). + +pub mod cluster; + +use anyhow::{Context, Result}; +use ndarray::IxDyn; +use ort::session::{builder::GraphOptimizationLevel, Session}; +use ort::value::Value; +use rustfft::num_complex::Complex; +use rustfft::FftPlanner; + +pub const SAMPLE_RATE: usize = 16000; +pub const N_FFT: usize = 400; +pub const HOP_LENGTH: usize = 160; +pub const WIN_LENGTH: usize = 400; +pub const N_BINS: usize = N_FFT / 2 + 1; // 201 +pub const N_MELS: usize = 80; +const PAD: usize = N_FFT / 2; +const AMIN: f32 = 1e-10; +const TOP_DB: f32 = 80.0; +const MULTIPLIER: f32 = 10.0; + +/// speechbrain-compatible log-mel frontend. +pub struct Frontend { + window: Vec, + mel: Vec, // [N_BINS * N_MELS], row-major (freq-major) + planner: FftPlanner, +} + +impl Frontend { + /// Load the hamming window (400 f32) and the mel matrix (201x80 f32). + pub fn new(window_path: &str, mel_path: &str) -> Result { + let window = read_f32_file(window_path)?; + if window.len() != WIN_LENGTH { + anyhow::bail!( + "window file has {} values, expected {}", + window.len(), + WIN_LENGTH + ); + } + let mel = read_f32_file(mel_path)?; + if mel.len() != N_BINS * N_MELS { + anyhow::bail!( + "mel file has {} values, expected {}", + mel.len(), + N_BINS * N_MELS + ); + } + Ok(Self { + window, + mel, + planner: FftPlanner::new(), + }) + } + + /// Compute log-mel features [n_frames, N_MELS] (flattened) for a waveform. + /// + /// Mirrors speechbrain `Fbank` with `mean_var_norm(norm_type="sentence", + /// std_norm=False)`: center-padded framing, power spectrum, mel matmul, + /// amplitude-to-dB with top_db clipping, then per-utterance mean removal. + pub fn compute_feats(&mut self, samples: &[f32]) -> (Vec, usize) { + let n = samples.len(); + if n == 0 { + return (Vec::new(), 0); + } + let n_frames = 1 + n / HOP_LENGTH; + let mut fbank = vec![0f32; n_frames * N_MELS]; + + let fft = self.planner.plan_fft_forward(N_FFT); + let mut buffer = vec![Complex::new(0f32, 0f32); N_FFT]; + + for t in 0..n_frames { + let base = t * HOP_LENGTH; + for k in 0..N_FFT { + let idx = base + k; + let s = if idx >= PAD { + let si = idx - PAD; + if si < n { + samples[si] + } else { + 0.0 + } + } else { + 0.0 + }; + buffer[k] = Complex::new(s * self.window[k], 0.0); + } + fft.process(&mut buffer); + + let row = &mut fbank[t * N_MELS..(t + 1) * N_MELS]; + for m in 0..N_MELS { + let mut acc = 0.0f32; + for b in 0..N_BINS { + let p = buffer[b].re * buffer[b].re + buffer[b].im * buffer[b].im; + acc += self.mel[b * N_MELS + m] * p; + } + row[m] = acc; + } + } + + // amplitude_to_DB: 10*log10(clamp(x, amin)) with db_multiplier = 0. + let mut db_max = f32::NEG_INFINITY; + for v in fbank.iter_mut() { + *v = MULTIPLIER * v.max(AMIN).log10(); + if *v > db_max { + db_max = *v; + } + } + let floor = db_max - TOP_DB; + for v in fbank.iter_mut() { + if *v < floor { + *v = floor; + } + } + + // sentence mean normalization (std_norm=False -> subtract mean only) + let mut mean = vec![0f32; N_MELS]; + for t in 0..n_frames { + for m in 0..N_MELS { + mean[m] += fbank[t * N_MELS + m]; + } + } + let inv = 1.0 / n_frames as f32; + for m in 0..N_MELS { + mean[m] *= inv; + } + for t in 0..n_frames { + for m in 0..N_MELS { + fbank[t * N_MELS + m] -= mean[m]; + } + } + + (fbank, n_frames) + } +} + +/// ECAPA-TDNN speaker embedding network (ONNX). +pub struct Ecapa { + session: Session, +} + +impl Ecapa { + pub fn new(model_path: &str) -> Result { + let session = Session::builder()? + .with_optimization_level(GraphOptimizationLevel::Level1) + .map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))? + .commit_from_file(model_path) + .map_err(|e| anyhow::anyhow!("Failed to load ECAPA model: {}", e))?; + Ok(Self { session }) + } + + /// Run the embedding network on features [n_frames, N_MELS]; returns 192-d. + pub fn embed(&mut self, feats: &[f32], n_frames: usize) -> Result> { + let input = ndarray::Array::from_shape_vec(IxDyn(&[1, n_frames, N_MELS]), feats.to_vec()) + .context("Failed to create ECAPA input array")?; + + let input_value = Value::from_array(input).context("Failed to create input value")?; + let inputs = ort::inputs!["feats" => input_value]; + + let outputs = self.session.run(inputs).context("Failed to run ECAPA")?; + let out = outputs["embedding"] + .try_extract_tensor::() + .context("Failed to extract embedding")?; + Ok(out.1.to_vec()) + } +} + +fn read_f32_file(path: &str) -> Result> { + let bytes = std::fs::read(path).with_context(|| format!("Failed to read {}", path))?; + if bytes.len() % 4 != 0 { + anyhow::bail!("{} length not a multiple of 4", path); + } + let mut out = Vec::with_capacity(bytes.len() / 4); + for chunk in bytes.chunks_exact(4) { + out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])); + } + Ok(out) +} + +/// L2-normalize a vector in place. +pub fn l2_normalize(v: &mut [f32]) { + let norm = v.iter().map(|x| x * x).sum::().sqrt(); + if norm > 0.0 { + for x in v.iter_mut() { + *x /= norm; + } + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/crop.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/crop.rs new file mode 100644 index 00000000..d4f791d2 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/crop.rs @@ -0,0 +1,41 @@ +use anyhow::{Context, Result}; +use image::{RgbImage, imageops}; +use crate::face_processor::BBox; + +pub struct FaceCropper; + +impl FaceCropper { + pub fn new() -> Self { + Self + } + + pub fn crop(&self, frame: &RgbImage, bbox: &BBox) -> Result { + let width = frame.width() as i32; + let height = frame.height() as i32; + + // Clamp bbox to frame boundaries + let x = bbox.x.max(0).min(width - 1) as u32; + let y = bbox.y.max(0).min(height - 1) as u32; + let w = bbox.width.max(1).min(width - x as i32) as u32; + let h = bbox.height.max(1).min(height - y as i32) as u32; + + // Clone frame for cropping (imageops::crop needs mutable reference) + let mut frame_clone = frame.clone(); + + // Crop face + let cropped = imageops::crop(&mut frame_clone, x, y, w, h).to_image(); + + Ok(cropped) + } + + pub fn resize_to_160(&self, face: &RgbImage) -> Result { + let resized = imageops::resize( + face, + 160, + 160, + imageops::FilterType::Lanczos3, + ); + + Ok(resized) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/detection.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/detection.rs new file mode 100644 index 00000000..6a2fbf28 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/detection.rs @@ -0,0 +1,181 @@ +use anyhow::{Context, Result}; +use std::path::Path; +use std::process::Command; +use std::fs; +use serde::Deserialize; +use crate::face_processor::{FaceDetection, BBox, PoseInfo}; + +#[derive(Debug, Deserialize)] +struct SwiftOutput { + #[serde(default)] + fps: f64, + #[serde(default)] + frame_count: usize, + frames: Vec, +} + +#[derive(Debug, Deserialize)] +struct SwiftFrame { + frame: usize, + #[serde(default)] + timestamp: f64, + faces: Vec, +} + +#[derive(Debug, Deserialize)] +struct SwiftFace { + bbox: Option, + confidence: f64, + #[serde(rename = "captureQuality")] + capture_quality: Option, + pose: Option, + landmarks: Option, +} + +#[derive(Debug, Deserialize)] +#[derive(Clone)] +struct SwiftBBox { + x: f64, + y: f64, + width: f64, + height: f64, +} + +#[derive(Debug, Deserialize)] +struct SwiftPose { + roll: f64, + yaw: f64, + pitch: f64, +} + +#[derive(Debug, Deserialize)] +struct SwiftLandmarks { + face_oval: Option>>, + left_eye: Option>>, + right_eye: Option>>, + nose: Option>>, + lips: Option, +} + +impl SwiftFace { + fn get_bbox(&self) -> Option { + // If bbox is directly provided + if let Some(ref bbox) = self.bbox { + return Some(bbox.clone()); + } + + // Otherwise, derive from landmarks + if let Some(ref landmarks) = self.landmarks { + if let Some(ref face_oval) = landmarks.face_oval { + if !face_oval.is_empty() { + let mut min_x = f64::MAX; + let mut min_y = f64::MAX; + let mut max_x = f64::MIN; + let mut max_y = f64::MIN; + + for point in face_oval { + if point.len() >= 2 { + min_x = min_x.min(point[0]); + min_y = min_y.min(point[1]); + max_x = max_x.max(point[0]); + max_y = max_y.max(point[1]); + } + } + + return Some(SwiftBBox { + x: min_x, + y: min_y, + width: max_x - min_x, + height: max_y - min_y, + }); + } + } + } + + None + } +} + +pub struct FaceDetector { + swift_binary: String, +} + +impl FaceDetector { + pub fn new() -> Result { + let swift_binary = Self::find_swift_binary()?; + Ok(Self { swift_binary }) + } + + fn find_swift_binary() -> Result { + // Try release build first + let release = "scripts/swift_processors/.build/release/swift_face"; + if Path::new(release).exists() { + return Ok(release.to_string()); + } + + // Try debug build + let debug = "scripts/swift_processors/.build/debug/swift_face"; + if Path::new(debug).exists() { + return Ok(debug.to_string()); + } + + anyhow::bail!("Swift face binary not found") + } + + pub fn detect(&self, video_path: &Path, output_path: &Path, sample_interval: usize) -> Result> { + println!("[DETECTION] Running Swift face detection..."); + + // Swift writes to file, not stdout + let output = Command::new(&self.swift_binary) + .arg(video_path) + .arg(output_path) + .arg("--sample-interval") + .arg(sample_interval.to_string()) + .output() + .context("Failed to run Swift face detection")?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + anyhow::bail!("Swift face detection failed: {}", stderr); + } + + // Read JSON from output file + let json_content = fs::read_to_string(output_path) + .context("Failed to read Swift detection output file")?; + + // Parse Swift output: {"frames": [...], "fps": ..., "frame_count": ...} + let swift_output: SwiftOutput = serde_json::from_str(&json_content) + .context("Failed to parse Swift detection JSON")?; + + println!("[DETECTION] Swift fps: {}, frame_count: {}", swift_output.fps, swift_output.frame_count); + + // Convert to our format + let faces: Vec = swift_output.frames.into_iter().flat_map(|frame| { + frame.faces.into_iter().filter_map(|face| { + let swift_bbox = face.get_bbox()?; + + Some(FaceDetection { + frame: frame.frame, + timestamp: frame.timestamp, + bbox: BBox { + x: swift_bbox.x as i32, + y: swift_bbox.y as i32, + width: swift_bbox.width as i32, + height: swift_bbox.height as i32, + }, + confidence: face.confidence, + capture_quality: face.capture_quality, + pose: face.pose.map(|p| PoseInfo { + roll: p.roll, + yaw: p.yaw, + pitch: p.pitch, + }), + }) + }).collect::>() + }).collect(); + + println!("[DETECTION] Found {} faces", faces.len()); + + Ok(faces) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/embedding.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/embedding.rs new file mode 100644 index 00000000..f4063d61 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/embedding.rs @@ -0,0 +1,66 @@ +use anyhow::{Context, Result}; +use image::{RgbImage, imageops}; +use ndarray::IxDyn; +use ort::{session::Session, value::Value}; +use std::path::Path; + +pub struct EmbeddingExtractor { + session: Session, +} + +impl EmbeddingExtractor { + pub fn new(model_path: &Path) -> Result { + println!("[EMBEDDING] Loading model: {:?}", model_path); + + let session = Session::builder() + .context("Failed to create session builder")? + .commit_from_file(model_path) + .context("Failed to load model")?; + + println!("[EMBEDDING] Model loaded successfully"); + + Ok(Self { session }) + } + + pub fn extract(&mut self, face: &RgbImage) -> Result> { + // Preprocess: resize to 160x160 and normalize to [-1, 1] + let resized = imageops::resize( + face, + 160, + 160, + imageops::FilterType::Lanczos3, + ); + + // Convert to normalized tensor + let mut input_array = ndarray::Array::from_shape_vec( + IxDyn(&[1, 3, 160, 160]), + vec![0.0f32; 1 * 3 * 160 * 160] + ).context("Failed to create input array")?; + + for (x, y, pixel) in resized.enumerate_pixels() { + let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32); + input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0; + input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0; + input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0; + } + + // Create input value + let input_value = Value::from_array(input_array) + .context("Failed to create input value")?; + + let inputs = ort::inputs!["input" => input_value]; + + // Run inference + let outputs = self.session.run(inputs) + .context("Failed to run inference")?; + + // Extract output + let output = outputs["output"].try_extract_tensor::() + .context("Failed to extract output tensor")?; + + let output_data = output.1; + let embedding = output_data.to_vec(); + + Ok(embedding) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/mod.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/mod.rs new file mode 100644 index 00000000..091d3ca6 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/mod.rs @@ -0,0 +1,13 @@ +pub mod types; +pub mod video; +pub mod qdrant; +pub mod detection; +pub mod crop; +pub mod embedding; + +pub use types::*; +pub use video::VideoReader; +pub use qdrant::{QdrantFaceStore, FaceEmbedPayload}; +pub use detection::FaceDetector; +pub use crop::FaceCropper; +pub use embedding::EmbeddingExtractor; diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/qdrant.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/qdrant.rs new file mode 100644 index 00000000..469832c8 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/qdrant.rs @@ -0,0 +1,141 @@ +use anyhow::{Context, Result, bail}; +use serde_json::json; + +const COLLECTION_NAME: &str = "_faces"; +const VECTOR_SIZE: usize = 512; + +#[derive(Debug, Clone)] +pub struct FaceEmbedPayload { + pub frame: usize, + pub trace_id: i64, + pub bbox: crate::face_processor::BBox, + pub confidence: f64, + pub capture_quality: Option, + pub embedding: Vec, +} + +pub struct QdrantFaceStore { + url: String, + api_key: String, +} + +impl QdrantFaceStore { + pub async fn new() -> Result { + let url = std::env::var("QDRANT_URL") + .unwrap_or_else(|_| "http://localhost:6333".to_string()); + + let api_key = std::env::var("QDRANT_API_KEY") + .unwrap_or_else(|_| "Test3200Test3200Test3200".to_string()); + + let store = Self { url, api_key }; + store.ensure_collection().await?; + + Ok(store) + } + + async fn ensure_collection(&self) -> Result<()> { + let client = reqwest::Client::new(); + + let url = format!("{}/collections/{}", self.url, COLLECTION_NAME); + let resp = client + .get(&url) + .header("Api-Key", &self.api_key) + .send() + .await?; + + if resp.status() == 404 { + println!("[QDRANT] Creating collection: {}", COLLECTION_NAME); + + let create_url = format!("{}/collections/{}", self.url, COLLECTION_NAME); + let body = json!({ + "vectors": { + "size": VECTOR_SIZE, + "distance": "Cosine" + } + }); + + client + .put(&create_url) + .header("Api-Key", &self.api_key) + .json(&body) + .send() + .await?; + + println!("[QDRANT] Collection created"); + } + + Ok(()) + } + + fn generate_point_id(file_uuid: &str, frame: usize, trace_id: i64) -> u64 { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + let key = format!("{}_{}_{}", file_uuid, frame, trace_id); + let mut hasher = DefaultHasher::new(); + key.hash(&mut hasher); + hasher.finish() + } + + pub async fn push_embeddings_batch( + &self, + file_uuid: &str, + faces: Vec, + ) -> Result { + if faces.is_empty() { + return Ok(0); + } + + println!("[QDRANT] Pushing {} embeddings", faces.len()); + + let points: Vec<_> = faces + .iter() + .map(|face| { + let point_id = Self::generate_point_id(file_uuid, face.frame, face.trace_id); + json!({ + "id": point_id, + "vector": &face.embedding, + "payload": { + "file_uuid": file_uuid, + "frame": face.frame, + "trace_id": face.trace_id, + "bbox": { + "x": face.bbox.x, + "y": face.bbox.y, + "width": face.bbox.width, + "height": face.bbox.height, + }, + "confidence": face.confidence, + "capture_quality": face.capture_quality.unwrap_or(0.0), + "identity_id": 0, + "identity_uuid": "", + "stranger_id": 0, + } + }) + }) + .collect(); + + let body = json!({"points": points}); + + let client = reqwest::Client::new(); + let url = format!("{}/collections/{}/points?wait=true", self.url, COLLECTION_NAME); + + let resp = client + .put(&url) + .header("Api-Key", &self.api_key) + .json(&body) + .send() + .await?; + + let status = resp.status(); + let response_text = resp.text().await?; + + if !status.is_success() { + bail!("Qdrant upsert failed ({}): {}", status, response_text); + } + + println!("[QDRANT] Pushed {} embeddings successfully", faces.len()); + + Ok(faces.len()) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/types.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/types.rs new file mode 100644 index 00000000..12685202 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/types.rs @@ -0,0 +1,78 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BBox { + pub x: i32, + pub y: i32, + pub width: i32, + pub height: i32, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FaceDetection { + pub frame: usize, + pub timestamp: f64, + pub bbox: BBox, + pub confidence: f64, + pub capture_quality: Option, + pub pose: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PoseInfo { + pub roll: f64, + pub yaw: f64, + pub pitch: f64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FaceEmbedding { + pub frame: usize, + pub trace_id: usize, + pub bbox: BBox, + pub confidence: f64, + pub embedding: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FaceOutput { + pub status: String, + pub frame_count: usize, + pub fps: f64, + pub frames: Vec, + pub total_faces: usize, + pub metadata: Metadata, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FrameData { + pub frame: usize, + pub timestamp: f64, + pub faces: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FaceInfo { + pub x: i32, + pub y: i32, + pub width: i32, + pub height: i32, + pub confidence: f64, + pub pose_angle: Option, + pub capture_quality: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PoseAngle { + pub angle: String, + pub roll: f64, + pub yaw: f64, + pub pitch: f64, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Metadata { + pub embedding_method: String, + pub embedding_model: String, + pub total_embeddings: usize, +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/video.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/video.rs new file mode 100644 index 00000000..e3e221d9 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/face_processor/video.rs @@ -0,0 +1,100 @@ +use anyhow::{Context, Result}; +use image::{RgbImage, ImageBuffer}; +use std::path::Path; +use std::process::Command; + +pub struct VideoReader { + video_path: String, + fps: f64, + frame_count: usize, + width: u32, + height: u32, +} + +impl VideoReader { + pub fn new(video_path: &Path) -> Result { + // Use ffprobe to get video info + let output = Command::new("ffprobe") + .args(&[ + "-v", "error", + "-select_streams", "v:0", + "-count_packets", + "-show_entries", "stream=width,height,r_frame_rate,nb_read_packets", + "-of", "csv=p=0", + video_path.to_str().unwrap() + ]) + .output() + .context("Failed to run ffprobe")?; + + let info = String::from_utf8_lossy(&output.stdout); + let parts: Vec<&str> = info.trim().split(',').collect(); + + if parts.len() < 4 { + anyhow::bail!("Invalid ffprobe output"); + } + + let width: u32 = parts[0].parse()?; + let height: u32 = parts[1].parse()?; + + let fps_parts: Vec<&str> = parts[2].split('/').collect(); + let fps = if fps_parts.len() == 2 { + fps_parts[0].parse::()? / fps_parts[1].parse::()? + } else { + parts[2].parse()? + }; + + let frame_count: usize = parts[3].parse()?; + + Ok(Self { + video_path: video_path.to_str().unwrap().to_string(), + fps, + frame_count, + width, + height, + }) + } + + pub fn fps(&self) -> f64 { + self.fps + } + + pub fn frame_count(&self) -> usize { + self.frame_count + } + + pub fn width(&self) -> u32 { + self.width + } + + pub fn height(&self) -> u32 { + self.height + } + + pub fn read_frame(&mut self, frame_num: usize) -> Result> { + // Use ffmpeg to extract a specific frame + let output = Command::new("ffmpeg") + .args(&[ + "-i", &self.video_path, + "-vf", &format!("select=eq(n\\,{})", frame_num), + "-vframes", "1", + "-f", "image2pipe", + "-pix_fmt", "rgb24", + "-vcodec", "rawvideo", + "-" + ]) + .output() + .context("Failed to run ffmpeg")?; + + if !output.status.success() { + return Ok(None); + } + + let data = output.stdout; + + // Create image from raw RGB data + let img = ImageBuffer::from_raw(self.width, self.height, data) + .context("Failed to create image buffer")?; + + Ok(Some(img)) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_appearance.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_appearance.rs new file mode 100644 index 00000000..d700c22f --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_appearance.rs @@ -0,0 +1,817 @@ +use std::process::Command; + +use image::GenericImageView; +use clap::Parser; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Parser)] +#[command(name = "rust_appearance", about = "Appearance Processor (Rust port of appearance_processor.py)")] +struct Args { + video_path: std::path::PathBuf, + pose_json: std::path::PathBuf, + output_path: std::path::PathBuf, + #[arg(short = 'u', long = "uuid", default_value = "")] + uuid: String, + #[arg(long = "frames", default_value = None)] + frames: Option, +} + +#[derive(Deserialize)] +struct Keypoint { + name: String, + x: f64, + y: f64, + #[serde(default = "default_conf")] + confidence: f64, +} + +fn default_conf() -> f64 { + 1.0 +} + +#[derive(Deserialize, Clone)] +#[serde(default)] +struct BBox { + x: f64, + y: f64, + width: f64, + height: f64, +} + +impl Default for BBox { + fn default() -> Self { + Self { x: 0.0, y: 0.0, width: 0.0, height: 0.0 } + } +} + +#[derive(Deserialize)] +struct Person { + bbox: BBox, + #[serde(default)] + keypoints: Vec, +} + +#[derive(Deserialize)] +struct PoseFrame { + frame: i64, + #[serde(default)] + timestamp: Option, + #[serde(default)] + persons: Vec, +} + +#[derive(Deserialize)] +struct PoseData { + #[serde(default)] + fps: f64, + #[serde(default)] + frames: Vec, +} + +#[derive(Deserialize)] +struct FaceData { + #[serde(default)] + frames: Vec, +} + +#[derive(Deserialize)] +struct FaceFrame { + frame: i64, + #[serde(default)] + faces: Vec, +} + +#[derive(Deserialize, Clone)] +struct FaceBBox { + x: f64, + y: f64, + width: f64, + height: f64, +} + +// Output schema (matches Python appearance_processor.py) +#[derive(Serialize)] +struct Output { + frame_count: u64, + fps: f64, + frames: Vec, +} + +#[derive(Serialize)] +struct OutputFrame { + frame: i64, + timestamp: f64, + persons: Vec, +} + +#[derive(Serialize)] +struct OutputPerson { + person_id: usize, + // Python emits the pose.json bbox verbatim (raw numbers). Keep original JSON to match + // integer/float representation exactly. + bbox: Value, + facing: String, + body_parts: Vec, + dominant_colors: Vec>, + hsv_histogram: Vec>, +} + +#[derive(Serialize)] +struct BodyPart { + name: String, + bbox: OBBox, + hsv_histogram: Vec>, + dominant_colors: Vec>, +} + +#[derive(Serialize)] +struct OBBox { + x: f64, + y: f64, + width: f64, + height: f64, +} + +fn get_kp<'a>(keypoints: &'a [Keypoint], name: &str) -> Option<&'a Keypoint> { + keypoints.iter().find(|kp| kp.name == name) +} + +fn determine_facing(keypoints: &[Keypoint]) -> String { + let nose = get_kp(keypoints, "nose"); + let l_shoulder = get_kp(keypoints, "left_shoulder"); + let r_shoulder = get_kp(keypoints, "right_shoulder"); + + if nose.is_some_and(|n| n.confidence > 0.5) { + return "front".to_string(); + } + let sh_vis = [l_shoulder, r_shoulder] + .iter() + .filter(|s| s.is_some_and(|k| k.confidence > 0.5)) + .count(); + if sh_vis >= 2 && nose.is_none_or(|n| n.confidence < 0.2) { + return "back".to_string(); + } + if sh_vis >= 1 { + return "profile".to_string(); + } + "unknown".to_string() +} + +fn compute_body_regions( + keypoints: &[Keypoint], + face: &FaceBBox, +) -> Vec<(String, BBox)> { + let fx = face.x; + let fy = face.y; + let fw = face.width; + let fh = face.height; + let face_cx = fx + fw / 2.0; + + let nose = get_kp(keypoints, "nose"); + let ls = get_kp(keypoints, "left_shoulder"); + let rs = get_kp(keypoints, "right_shoulder"); + let lw = get_kp(keypoints, "left_wrist"); + let rw = get_kp(keypoints, "right_wrist"); + let lh = get_kp(keypoints, "left_hip"); + let rh = get_kp(keypoints, "right_hip"); + let la = get_kp(keypoints, "left_ankle"); + let ra = get_kp(keypoints, "right_ankle"); + + let kp_nose = nose.map(|n| (n.x, n.y)).unwrap_or((face_cx, fy + fh * 0.5)); + let kp_sh_l = ls.map(|s| s.x).unwrap_or(face_cx - fw * 1.5); + let kp_sh_r = rs.map(|s| s.x).unwrap_or(face_cx + fw * 1.5); + let kp_sh_mid_x = (kp_sh_l + kp_sh_r) / 2.0; + let kp_sh_mid_y = if ls.is_some() && rs.is_some() { + (ls.unwrap().y + rs.unwrap().y) / 2.0 + } else { + fy + fh + fh * 0.3 + }; + let kp_hip_y = if lh.is_some() && rh.is_some() { + (lh.unwrap().y + rh.unwrap().y) / 2.0 + } else { + kp_sh_mid_y + fw * 2.0 + }; + let kp_hip_l = lh.map(|x| x.x).unwrap_or(kp_sh_mid_x - fw * 1.2); + let kp_hip_r = rh.map(|x| x.x).unwrap_or(kp_sh_mid_x + fw * 1.2); + + // Ordered to match Python dict insertion order (head → neck → upper → lower → hand → foot) + let mut ordered_names: Vec<&str> = vec![ + "head", + "neck", + "front_upper_body", + "back_upper_body", + "front_lower_body", + "back_lower_body", + "left_hand", + "right_hand", + "left_foot", + "right_foot", + ]; + let mut regions: Vec<(String, BBox)> = Vec::new(); + + let head_w = fw * 1.6; + let head_h = fh * 1.5; + regions.push(("head".to_string(), BBox { + x: kp_nose.0 - head_w / 2.0, + y: kp_nose.1 - head_h * 0.5, + width: head_w, + height: head_h, + })); + + let neck_w = fw * 1.5; + regions.push(("neck".to_string(), BBox { + x: kp_sh_mid_x - neck_w / 2.0, + y: kp_nose.1 + fh * 0.4, + width: neck_w, + height: (kp_sh_mid_y - kp_nose.1 - fh * 0.4).max(fh * 0.3), + })); + + let ub_w = ((kp_sh_r - kp_sh_l).abs() * 1.3).max(fw * 3.0); + let ub_h = fh * 3.0; + let upper = BBox { + x: kp_sh_mid_x - ub_w / 2.0, + y: kp_sh_mid_y, + width: ub_w, + height: ub_h, + }; + regions.push(("front_upper_body".to_string(), upper.clone())); + regions.push(("back_upper_body".to_string(), upper)); + + let lb_w = ((kp_hip_r - kp_hip_l).abs() * 1.3).max(fw * 3.5); + let lb_h = fh * 3.0; + let lower = BBox { + x: kp_sh_mid_x - lb_w / 2.0, + y: kp_hip_y, + width: lb_w, + height: lb_h, + }; + regions.push(("front_lower_body".to_string(), lower.clone())); + regions.push(("back_lower_body".to_string(), lower)); + + // hands: wrist-aligned + let hs = fw * 1.0; + let left_hand = if lw.is_some_and(|k| k.confidence > 0.3) { + BBox { + x: lw.unwrap().x - hs / 2.0, + y: lw.unwrap().y - hs / 2.0, + width: hs, + height: hs, + } + } else { + BBox { + x: kp_sh_l - hs, + y: kp_sh_mid_y + fh * 0.5, + width: hs, + height: hs, + } + }; + let right_hand = if rw.is_some_and(|k| k.confidence > 0.3) { + BBox { + x: rw.unwrap().x - hs / 2.0, + y: rw.unwrap().y - hs / 2.0, + width: hs, + height: hs, + } + } else { + BBox { + x: kp_sh_r, + y: kp_sh_mid_y + fh * 0.5, + width: hs, + height: hs, + } + }; + regions.push(("left_hand".to_string(), left_hand)); + regions.push(("right_hand".to_string(), right_hand)); + + // feet: ankle-aligned + let fs = fw * 1.0; + let left_foot = if la.is_some_and(|k| k.confidence > 0.3) { + BBox { + x: la.unwrap().x - fs / 2.0, + y: la.unwrap().y, + width: fs, + height: fs * 0.75, + } + } else { + BBox { + x: kp_sh_mid_x - fw * 1.0, + y: kp_hip_y + fh * 2.5, + width: fs, + height: fs * 0.75, + } + }; + let right_foot = if ra.is_some_and(|k| k.confidence > 0.3) { + BBox { + x: ra.unwrap().x - fs / 2.0, + y: ra.unwrap().y, + width: fs, + height: fs * 0.75, + } + } else { + BBox { + x: kp_sh_mid_x + fw * 1.0 - fs, + y: kp_hip_y + fh * 2.5, + width: fs, + height: fs * 0.75, + } + }; + regions.push(("left_foot".to_string(), left_foot)); + regions.push(("right_foot".to_string(), right_foot)); + + let _ = &mut ordered_names; + + // Extrapolate each bbox outward + let margins: [(&str, f64); 10] = [ + ("head", 0.10), + ("neck", 0.15), + ("front_upper_body", 0.20), + ("back_upper_body", 0.20), + ("front_lower_body", 0.15), + ("back_lower_body", 0.15), + ("left_hand", 0.25), + ("right_hand", 0.25), + ("left_foot", 0.20), + ("right_foot", 0.20), + ]; + let margin: std::collections::HashMap<&str, f64> = margins.iter().copied().collect(); + + regions + .into_iter() + .map(|(name, rb)| { + let m = margin.get(name.as_str()).copied().unwrap_or(0.15); + let dx = (rb.width * m) as i64; + let dy = (rb.height * m) as i64; + ( + name.clone(), + BBox { + x: rb.x - dx as f64, + y: rb.y - dy as f64, + width: rb.width + dx as f64 * 2.0, + height: rb.height + dy as f64 * 2.0, + }, + ) + }) + .collect() +} + +fn filter_by_facing(regions: Vec<(String, BBox)>, facing: &str) -> Vec<(String, BBox)> { + let (keep_front, keep_back) = match facing { + "front" => (true, false), + "back" => (false, true), + _ => (true, true), + }; + regions + .into_iter() + .filter(|(name, _)| { + if name == "front_upper_body" || name == "front_lower_body" { + keep_front + } else if name == "back_upper_body" || name == "back_lower_body" { + keep_back + } else { + true + } + }) + .collect() +} + +fn safe_roi( + frame: &image::RgbImage, + x: f64, + y: f64, + w: f64, + h: f64, +) -> Option { + if w <= 0.0 || h <= 0.0 { + return None; + } + let x1 = (x.max(0.0)) as u32; + let y1 = (y.max(0.0)) as u32; + let x2 = ((x + w).min(frame.width() as f64)) as u32; + let y2 = ((y + h).min(frame.height() as f64)) as u32; + if x2 <= x1 || y2 <= y1 { + return None; + } + frame.try_view(x1, y1, x2 - x1, y2 - y1).ok().map(|v| v.to_image()) +} + +// Deterministic k-means (k=5, attempts=10, iter=10, eps=1.0) on HSV pixels — seed fixed +// so output is reproducible (Python cv2.kmeans uses KMEANS_RANDOM_CENTERS: non-deterministic). +// A/B gate relaxes dominant color comparison accordingly. +fn kmeans_dominant(pixels: &[[f64; 3]], k: usize, attempts: usize) -> Vec<[f64; 3]> { + if pixels.is_empty() { + return vec![]; + } + if pixels.len() < 5 { + // Python: fewer than 5 pixels → mean as single dominant color + let mut mean = [0.0; 3]; + for p in pixels { + for i in 0..3 { + mean[i] += p[i]; + } + } + for i in 0..3 { + mean[i] /= pixels.len() as f64; + } + return vec![mean]; + } + + let mut best: Option<(f64, Vec<[f64; 3]>)> = None; + for seed in 0..attempts as u64 { + let mut centers = init_centers(pixels, k, seed); + for _ in 0..10 { + let (labels, _counts) = assign(pixels, ¢ers); + let new_centers = recompute(pixels, &labels, k); + let max_shift = centers + .iter() + .zip(new_centers.iter()) + .map(|(a, b)| dist(a, b)) + .fold(0.0f64, f64::max); + centers = new_centers; + if max_shift <= 1.0 { + break; + } + } + let (labels, _counts) = assign(pixels, ¢ers); + let sse: f64 = pixels + .iter() + .zip(labels.iter()) + .map(|(p, &l)| dist(p, ¢ers[l])) + .sum(); + if best.as_ref().map(|(e, _)| sse < *e).unwrap_or(true) { + best = Some((sse, centers)); + } + } + + let (_, centers) = best.unwrap(); + let (labels, _counts) = assign(pixels, ¢ers); + let mut counts = vec![0usize; k]; + for &l in &labels { + counts[l] += 1; + } + // Sort centers by cluster count descending (Python: centers[np.argsort(-counts)[:5]]) + let mut idx: Vec = (0..k).collect(); + idx.sort_by(|&a, &b| counts[b].cmp(&counts[a])); + idx.iter().map(|&i| centers[i]).collect() +} + +fn dist(a: &[f64; 3], b: &[f64; 3]) -> f64 { + ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt() +} + +fn init_centers(pixels: &[[f64; 3]], k: usize, seed: u64) -> Vec<[f64; 3]> { + let mut rng = SplitMix64::new(seed); + let n = pixels.len(); + let mut chosen = Vec::with_capacity(k); + let mut used = std::collections::BTreeSet::new(); + while chosen.len() < k { + let i = (rng.next_u64() % n as u64) as usize; + if used.insert(i) { + chosen.push(pixels[i]); + } + } + chosen +} + +fn assign(pixels: &[[f64; 3]], centers: &[[f64; 3]]) -> (Vec, Vec) { + let mut labels = Vec::with_capacity(pixels.len()); + let mut counts = vec![0usize; centers.len()]; + for p in pixels { + let mut best_i = 0; + let mut best_d = f64::INFINITY; + for (i, c) in centers.iter().enumerate() { + let d = dist(p, c); + if d < best_d { + best_d = d; + best_i = i; + } + } + labels.push(best_i); + counts[best_i] += 1; + } + (labels, counts) +} + +fn recompute(pixels: &[[f64; 3]], labels: &[usize], k: usize) -> Vec<[f64; 3]> { + let mut sums = vec![[0.0; 3]; k]; + let mut counts = vec![0usize; k]; + for (p, &l) in pixels.iter().zip(labels.iter()) { + for i in 0..3 { + sums[l][i] += p[i]; + } + counts[l] += 1; + } + let mut centers = vec![[0.0; 3]; k]; + for i in 0..k { + if counts[i] > 0 { + for j in 0..3 { + centers[i][j] = sums[i][j] / counts[i] as f64; + } + } + } + centers +} + +/// SplitMix64 PRNG (deterministic). +struct SplitMix64 { + state: u64, +} + +impl SplitMix64 { + fn new(seed: u64) -> Self { + Self { state: seed } + } + fn next_u64(&mut self) -> u64 { + self.state = self.state.wrapping_add(0x9E3779B97F4A7C15); + let mut z = self.state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB); + z ^ (z >> 31) + } +} + +fn extract_color(roi: &image::RgbImage) -> Option<(Vec>, Vec>)> { + if roi.width() < 2 || roi.height() < 2 { + return None; + } + + let mut h_hist = vec![0.0f64; 30]; + let mut s_hist = vec![0.0f64; 32]; + let mut v_hist = vec![0.0f64; 32]; + let mut pixels: Vec<[f64; 3]> = Vec::new(); + + for px in roi.pixels() { + let r = px[0] as f64; + let g = px[1] as f64; + let b = px[2] as f64; + // OpenCV BGR2HSV and RGB2HSV produce the same HSV for the same underlying color + // triple; PNG stores (R,G,B), so identical to cv2 frame interpreted as BGR. + let (h, s, v) = bgr2hsv(r, g, b); + let hb = ((h / 6.0).floor() as usize).min(29); + let sb = ((s / 8.0).floor() as usize).min(31); + let vb = ((v / 8.0).floor() as usize).min(31); + h_hist[hb] += 1.0; + s_hist[sb] += 1.0; + v_hist[vb] += 1.0; + pixels.push([h, s, v]); + } + + let hs = h_hist.iter().sum::().max(1.0); + let ss = s_hist.iter().sum::().max(1.0); + let vs = v_hist.iter().sum::().max(1.0); + + let h_norm: Vec = h_hist.iter().map(|x| x / hs).collect(); + let s_norm: Vec = s_hist.iter().map(|x| x / ss).collect(); + let v_norm: Vec = v_hist.iter().map(|x| x / vs).collect(); + + // Subsample for kmeans if too many pixels (cv2 uses all but is SIMD-optimized) + let kmeans_pixels = if pixels.len() > 10000 { + let step = pixels.len() / 10000; + pixels.iter().step_by(step).copied().collect::>() + } else { + pixels.clone() + }; + let dominant = kmeans_dominant(&kmeans_pixels, 5, 10); + let dominant: Vec> = dominant.iter().map(|d| d.to_vec()).collect(); + + Some((vec![h_norm, s_norm, v_norm], dominant)) +} + +/// OpenCV 8-bit BGR→HSV. H in [0,180], S and V in [0,255]. +fn bgr2hsv(r: f64, g: f64, b: f64) -> (f64, f64, f64) { + let v = r.max(g).max(b); + let mn = r.min(g).min(b); + let delta = v - mn; + if delta == 0.0 { + return (0.0, 0.0, v); + } + let s = delta * 255.0 / v; + let mut h; + if v == r { + h = 60.0 * (g - b) / delta; + } else if v == g { + h = 60.0 * (2.0 + (b - r) / delta); + } else { + h = 60.0 * (4.0 + (r - g) / delta); + } + if h < 0.0 { + h += 360.0; + } + (h / 2.0, s, v) +} + +/// Extract only the needed frames in one ffmpeg pass. Builds a `select` filter expression +/// compressing contiguous frame ranges into `between(n,a,b)` terms. +fn extract_frames( + video_path: &std::path::Path, + needed: &[i64], + out_tmp: &std::path::Path, +) -> Result, String> { + if needed.is_empty() { + return Ok(vec![]); + } + std::fs::create_dir_all(out_tmp).map_err(|e| e.to_string())?; + + // Compact runs + let mut terms: Vec = Vec::new(); + let mut i = 0usize; + while i < needed.len() { + let start = needed[i]; + let mut end = start; + let mut j = i; + while j + 1 < needed.len() && needed[j + 1] == end + 1 { + end += 1; + j += 1; + } + if start == end { + terms.push(format!("eq(n\\,{})", start)); + } else { + terms.push(format!("between(n\\,{}\\,{})", start, end)); + } + i = j + 1; + } + let select_expr = terms.join("+"); + + let filter = format!("select='{}'", select_expr); + let out_pattern = out_tmp.join("frame_%05d.png"); + let status = Command::new("ffmpeg") + .arg("-v") + .arg("error") + .arg("-i") + .arg(video_path) + .arg("-vf") + .arg(&filter) + .arg("-vsync") + .arg("0") + .arg("-f") + .arg("image2") + .arg(&out_pattern) + .status() + .map_err(|e| format!("ffmpeg launch failed: {e}"))?; + if !status.success() { + return Err(format!("ffmpeg failed with status {status}")); + } + + // Output files are named frame_00001.png ... in the same order as the needed list. + let mut paths = Vec::with_capacity(needed.len()); + for (i, _) in needed.iter().enumerate() { + let p = out_tmp.join(format!("frame_{:05}.png", i + 1)); + if !p.exists() { + return Err(format!("ffmpeg expected output {p:?} missing")); + } + paths.push(p); + } + Ok(paths) +} + +fn main() { + let args = Args::parse(); + + let pose_str = std::fs::read_to_string(&args.pose_json).expect("Failed to read pose json"); + let pose: PoseData = serde_json::from_str(&pose_str).expect("Failed to parse pose json"); + + // Load face.json for anchor bbox (same directory as pose_json) + let face_path = + std::path::PathBuf::from(args.pose_json.to_string_lossy().replace(".pose.json", ".face.json")); + let mut face_by_frame: std::collections::BTreeMap = std::collections::BTreeMap::new(); + if face_path.exists() { + let face_str = std::fs::read_to_string(&face_path).expect("Failed to read face json"); + if let Ok(face_data) = serde_json::from_str::(&face_str) { + for fframe in face_data.frames { + if let Some(first) = fframe.faces.first() { + face_by_frame.insert(fframe.frame, first.clone()); + } + } + } + } + + let fps = if pose.fps > 0.0 { pose.fps } else { 30.0 }; + + // Collect needed frames (pose frames that have persons), sorted for ffmpeg select + let mut needed: Vec = pose + .frames + .iter() + .filter(|f| !f.persons.is_empty()) + .map(|f| f.frame) + .collect(); + needed.sort_unstable(); + + // Extract frames + let out_tmp = args.output_path.with_extension("frames_tmp"); + let frame_paths = match extract_frames(&args.video_path, &needed, &out_tmp) { + Ok(p) => p, + Err(e) => { + eprintln!("[APPEARANCE] frame extraction failed: {e}"); + std::process::exit(1); + } + }; + // Map frame number → extracted file + let frame_file: std::collections::BTreeMap = needed + .iter() + .enumerate() + .map(|(i, &f)| (f, frame_paths[i].clone())) + .collect(); + + let mut frames_out: Vec = Vec::new(); + + for pose_frame in pose.frames.iter().filter(|f| !f.persons.is_empty()) { + let frame_num = pose_frame.frame; + let frame_img = match frame_file.get(&frame_num) { + Some(p) => match image::open(p) { + Ok(img) => img.to_rgb8(), + Err(e) => { + eprintln!("[APPEARANCE] failed to decode {p:?}: {e}"); + continue; + } + }, + None => continue, + }; + + // Get face bbox for this frame (Python: face_by_frame.get(frame_num, persons[0].bbox)) + let fallback = pose_frame.persons[0].bbox.clone(); + let face_bbox = face_by_frame + .get(&frame_num) + .cloned() + .unwrap_or_else(|| FaceBBox { + x: fallback.x, + y: fallback.y, + width: fallback.width, + height: fallback.height, + }); + + let mut frame_persons = Vec::new(); + for (pid, person) in pose_frame.persons.iter().enumerate() { + let keypoints = &person.keypoints; + if keypoints.is_empty() { + continue; + } + let bbox = &person.bbox; + let facing = determine_facing(keypoints); + let all_regions = compute_body_regions(keypoints, &face_bbox); + let regions = filter_by_facing(all_regions, &facing); + + let mut body_parts = Vec::new(); + for (name, rb) in regions { + let roi = safe_roi(&frame_img, rb.x, rb.y, rb.width, rb.height); + if let Some(roi_img) = roi { + if let Some((hist, colors)) = extract_color(&roi_img) { + body_parts.push(BodyPart { + name, + bbox: OBBox { + x: rb.x, + y: rb.y, + width: rb.width, + height: rb.height, + }, + hsv_histogram: hist, + dominant_colors: colors, + }); + } + } + } + + let mut full: Option<(Vec>, Vec>)> = None; + if bbox.width > 0.0 && bbox.height > 0.0 { + let full_roi = safe_roi(&frame_img, bbox.x, bbox.y, bbox.width, bbox.height); + if let Some(f) = full_roi { + full = extract_color(&f); + } + } + + let empty_hist = vec![vec![], vec![], vec![]]; + let person_bbox_json = serde_json::json!({ + "x": bbox.x, + "y": bbox.y, + "width": bbox.width, + "height": bbox.height, + }); + frame_persons.push(OutputPerson { + person_id: pid, + bbox: person_bbox_json, + facing, + body_parts, + dominant_colors: full.as_ref().map(|(_, c)| c.clone()).unwrap_or_default(), + hsv_histogram: full.as_ref().map(|(h, _)| h.clone()).unwrap_or(empty_hist), + }); + } + + if !frame_persons.is_empty() { + frames_out.push(OutputFrame { + frame: frame_num, + timestamp: pose_frame.timestamp.unwrap_or(frame_num as f64 / fps), + persons: frame_persons, + }); + } + } + + let _ = std::fs::remove_dir_all(&out_tmp); + + let output = Output { + frame_count: frames_out.len() as u64, + fps, + frames: frames_out, + }; + let json_str = serde_json::to_string_pretty(&output).expect("serialize failed"); + std::fs::write(&args.output_path, json_str).expect("Failed to write output"); + eprintln!("[APPEARANCE] Done: {} frames", output.frame_count); +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_asr_asrx.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_asr_asrx.rs new file mode 100644 index 00000000..15921ce2 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_asr_asrx.rs @@ -0,0 +1,374 @@ +use clap::Parser; +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::path::Path; +use std::process::Command; +use std::time::Instant; +use std::collections::BTreeMap; + +use rust_processors::asrx::cluster; +use rust_processors::asrx::{l2_normalize, Ecapa, Frontend, SAMPLE_RATE}; +use rust_processors::vad::AudioReader; + +#[derive(Parser)] +#[command(name = "rust_asr_asrx")] +#[command(about = "ASR + Diarization (Rust + MLX Whisper)")] +#[command(version)] +struct Cli { + /// Input audio/video file + #[arg(short, long)] + input: String, + + /// Output JSON file + #[arg(short, long)] + output: String, + + /// Whisper model path + #[arg(long, default_value = "/Users/accusys/models/whisper-small-mlx")] + model: String, + + /// VAD model path + #[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")] + vad_model: String, + + /// Language (auto-detect if not specified) + #[arg(short, long)] + language: Option, + + /// Enable diarization + #[arg(long, default_value = "true")] + diarize: bool, + + /// ECAPA model path + #[arg(long, default_value = "/Users/accusys/models/ecapa_tdnn.onnx")] + ecapa_model: String, + + /// ECAPA window file + #[arg(long, default_value = "/Users/accusys/models/ecapa_window_400.f32")] + window_file: String, + + /// ECAPA mel file + #[arg(long, default_value = "/Users/accusys/models/ecapa_mel_201x80.f32")] + mel_file: String, + + /// Max speakers + #[arg(long, default_value = "10")] + max_speakers: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Segment { + id: usize, + start: f64, + end: f64, + text: String, + speaker_id: Option, + is_multi_speaker: bool, +} + +#[derive(Debug, Serialize, Deserialize)] +struct AsrResult { + text: String, + segments: Vec, + language: String, +} + +#[derive(Debug, Serialize, Deserialize)] +struct AsrSegment { + id: usize, + start: f64, + end: f64, + text: String, +} + +fn main() -> Result<()> { + let cli = Cli::parse(); + + println!("[ASR-ASRX] Starting..."); + let start_total = Instant::now(); + + let input_path = Path::new(&cli.input); + if !input_path.exists() { + anyhow::bail!("Input file not found: {}", cli.input); + } + + // Step 1: Extract audio (if video) + println!("[1/4] Extracting audio..."); + let audio_path = if is_video_file(&cli.input) { + extract_audio(&cli.input)? + } else { + cli.input.clone() + }; + + // Step 2: VAD detection + println!("[2/4] VAD detection..."); + let vad_segments = run_vad(&audio_path, &cli.vad_model)?; + println!("[VAD] Found {} speech segments", vad_segments.len()); + + // Step 3: ASR transcription + println!("[3/6] ASR transcription..."); + let asr_result = run_mlx_whisper(&audio_path, &cli.model, cli.language.as_deref())?; + println!("[ASR] Language: {}", asr_result.language); + println!("[ASR] Segments: {}", asr_result.segments.len()); + + // Step 4: Diarization (if enabled) + let segments = if cli.diarize { + println!("[4/6] Computing embeddings..."); + println!("[5/6] Clustering speakers..."); + println!("[6/6] Assigning speaker IDs..."); + perform_diarization( + &audio_path, + &asr_result.segments, + &cli.ecapa_model, + &cli.window_file, + &cli.mel_file, + cli.max_speakers, + )? + } else { + println!("[4/6] Skipping diarization..."); + asr_result.segments.iter().enumerate().map(|(i, seg)| { + Segment { + id: i, + start: seg.start, + end: seg.end, + text: seg.text.clone(), + speaker_id: None, + is_multi_speaker: false, + } + }).collect() + }; + + // Count speakers + let n_speakers = segments.iter() + .filter_map(|s| s.speaker_id.as_ref()) + .map(|s| s.clone()) + .collect::>() + .len(); + + // Build speaker stats + let mut speaker_stats: BTreeMap = BTreeMap::new(); + for seg in &segments { + if let Some(ref speaker) = seg.speaker_id { + let entry = speaker_stats.entry(speaker.clone()).or_insert((0, 0.0)); + entry.0 += 1; + entry.1 += seg.end - seg.start; + } + } + + let stats_json: serde_json::Value = speaker_stats + .into_iter() + .map(|(k, (count, dur))| (k, json!({"count": count, "duration": (dur * 1000.0).round() / 1000.0}))) + .collect(); + + // Output + let output = json!({ + "language": asr_result.language, + "model": cli.model, + "processor": "rust_asr_asrx", + "segments": segments, + "n_speakers": n_speakers, + "speaker_stats": stats_json, + "processing_time": { + "total": start_total.elapsed().as_secs_f64() + } + }); + + std::fs::write(&cli.output, serde_json::to_string_pretty(&output)?)?; + println!("[ASR-ASRX] Output: {}", cli.output); + println!("[ASR-ASRX] Done in {:.2}s", start_total.elapsed().as_secs_f32()); + + Ok(()) +} + +fn is_video_file(path: &str) -> bool { + let ext = Path::new(path) + .extension() + .and_then(|s| s.to_str()) + .unwrap_or(""); + + matches!(ext.to_lowercase().as_str(), "mp4" | "mkv" | "avi" | "mov") +} + +fn extract_audio(input: &str) -> Result { + let output = input.replace(".mp4", ".wav").replace(".mkv", ".wav"); + + let status = Command::new("ffmpeg") + .args(&[ + "-y", "-i", input, + "-vn", "-acodec", "pcm_s16le", + "-ar", "16000", "-ac", "1", + &output + ]) + .status() + .context("Failed to run ffmpeg")?; + + if !status.success() { + anyhow::bail!("ffmpeg failed"); + } + + Ok(output) +} + +fn run_vad(audio_path: &str, vad_model: &str) -> Result> { + let binary = "/Users/accusys/momentry_core/tools/cli/rust/target/release/rust_vad"; + + let output = Command::new(binary) + .args(&["--audio", audio_path, "--model", vad_model, "--format", "json"]) + .output() + .context("Failed to run rust_vad")?; + + if !output.status.success() { + anyhow::bail!("rust_vad failed: {}", String::from_utf8_lossy(&output.stderr)); + } + + let stdout = String::from_utf8_lossy(&output.stdout); + let json_str = stdout.lines() + .skip_while(|line| !line.starts_with('{')) + .collect::>() + .join("\n"); + + let json: serde_json::Value = serde_json::from_str(&json_str) + .context("Failed to parse VAD JSON")?; + let segments = json["segments"] + .as_array() + .context("Invalid VAD output")?; + + Ok(segments.iter().map(|s| { + let start = s["start"].as_f64().unwrap(); + let end = s["end"].as_f64().unwrap(); + (start, end) + }).collect()) +} + +fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Result { + let mut args = vec![ + audio_path.to_string(), + "--model".to_string(), model.to_string(), + "--output-format".to_string(), "json".to_string(), + ]; + + if let Some(lang) = language { + args.push("--language".to_string()); + args.push(lang.to_string()); + } + + let output = Command::new("/opt/homebrew/bin/mlx_whisper") + .args(&args) + .current_dir("/tmp") + .output() + .context("Failed to run mlx_whisper")?; + + if !output.status.success() { + anyhow::bail!("mlx_whisper failed: {}", String::from_utf8_lossy(&output.stderr)); + } + + let output_file = Path::new(audio_path) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap(); + + let json_path = format!("/tmp/{}.json", output_file); + let json_content = std::fs::read_to_string(&json_path) + .context("Failed to read MLX Whisper output")?; + + let json: serde_json::Value = serde_json::from_str(&json_content)?; + + let segments = json["segments"] + .as_array() + .context("Invalid MLX Whisper output")? + .iter() + .enumerate() + .map(|(i, s)| AsrSegment { + id: i, + start: s["start"].as_f64().unwrap(), + end: s["end"].as_f64().unwrap(), + text: s["text"].as_str().unwrap().to_string(), + }) + .collect(); + + Ok(AsrResult { + text: json["text"].as_str().unwrap().to_string(), + segments, + language: json["language"].as_str().unwrap().to_string(), + }) +} + +fn perform_diarization( + audio_path: &str, + asr_segments: &[AsrSegment], + ecapa_model: &str, + window_file: &str, + mel_file: &str, + max_speakers: usize, +) -> Result> { + // Load audio + let audio = AudioReader::from_wav(audio_path) + .context("Failed to read audio for diarization")?; + let samples = audio.samples(); + + // Initialize ECAPA + let mut frontend = Frontend::new(window_file, mel_file) + .context("Failed to load ASRX frontend")?; + let mut ecapa = Ecapa::new(ecapa_model) + .context("Failed to load ECAPA model")?; + + // Compute embeddings for each segment + let mut embeddings: Vec> = Vec::with_capacity(asr_segments.len()); + + for seg in asr_segments { + let a = (seg.start * SAMPLE_RATE as f64) as usize; + let b = ((seg.end * SAMPLE_RATE as f64) as usize).min(samples.len()); + + let seg_audio = if b > a { + &samples[a..b] + } else { + &samples[0..0] + }; + + let (feats, n_frames) = frontend.compute_feats(seg_audio); + let mut emb = if n_frames > 0 { + ecapa.embed(&feats, n_frames)? + } else { + vec![0f32; 192] + }; + + l2_normalize(&mut emb); + embeddings.push(emb); + } + + // Clustering + let distances = cluster::cosine_distances(&embeddings); + let n_est = cluster::estimate_n_speakers(&distances, max_speakers); + let k = n_est.min(asr_segments.len()).max(1); + let labels = cluster::agglomerative(&distances, k); + + // Build segments with speaker IDs + let segments: Vec = asr_segments + .iter() + .enumerate() + .map(|(i, seg)| Segment { + id: i, + start: seg.start, + end: seg.end, + text: seg.text.clone(), + speaker_id: Some(format!("SPEAKER_{}", labels[i])), + is_multi_speaker: false, + }) + .collect(); + + Ok(segments) +} + +fn combine_vad_asr(vad_segments: &[(f64, f64)], asr_result: &AsrResult) -> Vec { + asr_result.segments.iter().enumerate().map(|(i, asr_seg)| { + Segment { + id: i, + start: asr_seg.start, + end: asr_seg.end, + text: asr_seg.text.clone(), + speaker_id: None, + is_multi_speaker: false, + } + }).collect() +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_asrx.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_asrx.rs new file mode 100644 index 00000000..853662b8 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_asrx.rs @@ -0,0 +1,488 @@ +use anyhow::{Context, Result}; +use clap::Parser; +use serde_json::json; +use std::path::Path; +use std::process::Command; +use std::time::Instant; + +use rust_processors::asrx::cluster; +use rust_processors::asrx::{l2_normalize, Ecapa, Frontend, SAMPLE_RATE}; +use rust_processors::vad::segment::SegmentCollector; +use rust_processors::vad::{AudioReader, SileroVad}; + +#[derive(Parser)] +#[command(name = "rust_asrx")] +#[command(about = "Rust-native speaker diarization (ASRX)")] +struct Cli { + /// Input video file + video_path: String, + + /// Output JSON path ({file_uuid}.asrx.json) + output_path: String, + + /// File UUID (for Redis publishing compatibility) + #[arg(long)] + uuid: Option, + + /// File UUID (for Qdrant storage compatibility) + #[arg(long = "file-uuid")] + file_uuid: Option, + + #[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")] + vad_model: String, + + #[arg(long, default_value = "/Users/accusys/models/ecapa_tdnn.onnx")] + ecapa_model: String, + + #[arg(long, default_value = "/Users/accusys/models/ecapa_window_400.f32")] + window_file: String, + + #[arg(long, default_value = "/Users/accusys/models/ecapa_mel_201x80.f32")] + mel_file: String, + + #[arg(long, default_value = "10")] + max_speakers: usize, + + #[arg(long, default_value = "0.5")] + vad_threshold: f32, + + #[arg(long, default_value = "500")] + min_speech: u32, + + #[arg(long, default_value = "300")] + min_silence: u32, +} + +const CHUNK_SIZE: usize = 512; + +struct AsrSegment { + start: f32, + end: f32, + text: String, +} + +fn main() -> Result<()> { + let cli = Cli::parse(); + let start_all = Instant::now(); + + let output_dir = Path::new(&cli.output_path) + .parent() + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| Path::new(".").to_path_buf()); + let uuid_part = Path::new(&cli.output_path) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("") + .split('.') + .next() + .unwrap_or("") + .to_string(); + let asr_path = cli.output_path.replace(".asrx.json", ".asr.json"); + + let write_result = |status: &str, + language: Option<&str>, + segments: Vec, + n_speakers: usize, + speaker_stats: serde_json::Value| + -> Result<()> { + let out = json!({ + "status": status, + "language": language, + "segments": segments, + "segment_count": segments.len(), + "n_speakers": n_speakers, + "speaker_stats": speaker_stats, + }); + if let Some(parent) = Path::new(&cli.output_path).parent() { + let _ = std::fs::create_dir_all(parent); + } + std::fs::write(&cli.output_path, serde_json::to_string_pretty(&out)?) + .context("Failed to write ASRX output")?; + Ok(()) + }; + + // 1. Probe audio tracks; skip if none. + println!("[rust_asrx] Probing audio tracks: {}", cli.video_path); + let tracks = probe_audio_tracks(&cli.video_path); + if tracks.is_empty() { + println!("[rust_asrx] No audio stream detected"); + return write_result("no_audio_track", None, vec![], 0, json!({})); + } + + // 2. If ASR already reported silence/no-audio, mirror it. + if Path::new(&asr_path).exists() { + if let Ok(text) = std::fs::read_to_string(&asr_path) { + if let Ok(v) = serde_json::from_str::(&text) { + let asr_status = v.get("status").and_then(|s| s.as_str()).unwrap_or(""); + let asr_lang = v.get("language").and_then(|s| s.as_str()); + if asr_status == "no_audio_track" || asr_status == "silent_audio" { + println!("[rust_asrx] ASR status={}, skipping", asr_status); + return write_result(asr_status, asr_lang, vec![], 0, json!({})); + } + } + } + } + + // 3. Load ASR segments for time alignment (text source). + let (asr_segments, language) = load_asr_segments(&asr_path); + + // 4. Extract audio to 16kHz mono WAV. + let tmp_wav = format!("/tmp/rust_asrx_{}.wav", uuid_part); + let track_index = select_best_track(&tracks); + if let Err(e) = extract_audio(&cli.video_path, track_index, &tmp_wav) { + println!("[rust_asrx] Audio extraction failed: {}", e); + return write_result("silent_audio", language.as_deref(), vec![], 0, json!({})); + } + + let audio = AudioReader::from_wav(&tmp_wav).context("Failed to read extracted WAV")?; + let samples = audio.samples(); + let duration = audio.duration(); + let _ = std::fs::remove_file(&tmp_wav); + + // 5. VAD refinement per ASR segment (or whole file if no ASR). + let mut vad = SileroVad::new(&cli.vad_model).context("Failed to load Silero VAD")?; + let mut refined: Vec<(f32, f32, String)> = Vec::new(); + if asr_segments.is_empty() { + let subs = scan_within_segment( + &mut vad, + samples, + 0.0, + duration, + cli.vad_threshold, + cli.min_speech, + cli.min_silence, + ); + for (s, e) in subs { + refined.push((s, e, String::new())); + } + } else { + for seg in &asr_segments { + let subs = scan_within_segment( + &mut vad, + samples, + seg.start, + seg.end, + cli.vad_threshold, + cli.min_speech, + cli.min_silence, + ); + if subs.is_empty() { + refined.push((seg.start, seg.end, seg.text.clone())); + } else { + for (s, e) in subs { + refined.push((s, e, seg.text.clone())); + } + } + } + } + + if refined.is_empty() { + println!("[rust_asrx] No speech segments"); + return write_result("silent_audio", language.as_deref(), vec![], 0, json!({})); + } + println!("[rust_asrx] Refined segments: {}", refined.len()); + + // 6. Speaker embeddings (ECAPA) per refined segment. + let mut frontend = Frontend::new(&cli.window_file, &cli.mel_file) + .context("Failed to load ASRX frontend constants")?; + let mut ecapa = Ecapa::new(&cli.ecapa_model).context("Failed to load ECAPA model")?; + let mut embeddings: Vec> = Vec::with_capacity(refined.len()); + for (s, e, _) in &refined { + let a = (*s * SAMPLE_RATE as f32) as usize; + let b = ((*e * SAMPLE_RATE as f32) as usize).min(samples.len()); + let seg_audio = if b > a { + &samples[a..b] + } else { + &samples[0..0] + }; + let (feats, n_frames) = frontend.compute_feats(seg_audio); + let mut emb = if n_frames > 0 { + ecapa.embed(&feats, n_frames)? + } else { + vec![0f32; 192] + }; + l2_normalize(&mut emb); + embeddings.push(emb); + } + + // 7. Clustering. + let distances = cluster::cosine_distances(&embeddings); + let n_est = cluster::estimate_n_speakers(&distances, cli.max_speakers); + let k = n_est.min(refined.len()).max(1); + let labels = cluster::agglomerative(&distances, k); + let n_speakers = labels.iter().copied().max().map(|m| m + 1).unwrap_or(0); + println!("[rust_asrx] Estimated speakers: {}", n_speakers); + + // 8. Quality (cosine similarity to cluster centroid). + let qualities = cluster_qualities(&embeddings, &labels); + + // 9. Build segments. + let fps = read_fps(&output_dir, &uuid_part); + let mut segments: Vec = Vec::with_capacity(refined.len()); + let mut speaker_stats: std::collections::BTreeMap = + std::collections::BTreeMap::new(); + for (i, (s, e, text)) in refined.iter().enumerate() { + let speaker = format!("SPEAKER_{}", labels[i]); + let start_frame = (s * fps) as u64; + let end_frame = (e * fps) as u64; + segments.push(json!({ + "start_time": round3(*s), + "end_time": round3(*e), + "start_frame": start_frame, + "end_frame": end_frame, + "text": text, + "speaker_id": speaker, + "language": language, + "lang_prob": 0.0, + "quality": (qualities[i] * 1000.0).round() / 1000.0, + })); + let entry = speaker_stats.entry(speaker).or_insert((0, 0.0)); + entry.0 += 1; + entry.1 += (*e - *s) as f64; + } + let stats_json: serde_json::Value = speaker_stats + .into_iter() + .map(|(k, (count, dur))| (k, json!({"count": count, "duration": round3(dur as f32)}))) + .collect(); + + write_result( + "has_transcript", + language.as_deref(), + segments, + n_speakers, + stats_json, + )?; + println!( + "[rust_asrx] Done: {} segments, {} speakers in {:.2}s", + refined.len(), + n_speakers, + start_all.elapsed().as_secs_f32() + ); + Ok(()) +} + +fn round3(v: f32) -> f64 { + ((v as f64) * 1000.0).round() / 1000.0 +} + +/// VAD-scan a time window and return refined sub-segments on the global timeline. +fn scan_within_segment( + vad: &mut SileroVad, + samples: &[f32], + start_sec: f32, + end_sec: f32, + threshold: f32, + min_speech_ms: u32, + min_silence_ms: u32, +) -> Vec<(f32, f32)> { + let a = (start_sec * SAMPLE_RATE as f32) as usize; + let b = ((end_sec * SAMPLE_RATE as f32) as usize).min(samples.len()); + if b <= a { + return Vec::new(); + } + let sub = &samples[a..b]; + let offset = a as f32 / SAMPLE_RATE as f32; + + vad.reset_state(); + let mut collector = SegmentCollector::new(threshold, min_speech_ms, min_silence_ms); + let mut i = 0; + while i < sub.len() { + let end = (i + CHUNK_SIZE).min(sub.len()); + let mut chunk = sub[i..end].to_vec(); + if chunk.len() < CHUNK_SIZE { + chunk.resize(CHUNK_SIZE, 0.0); + } + let prob = match vad.detect(&chunk) { + Ok(p) => p, + Err(_) => 0.0, + }; + collector.process(i as f32 / SAMPLE_RATE as f32, prob); + i += CHUNK_SIZE; + } + collector.finalize(sub.len() as f32 / SAMPLE_RATE as f32); + collector + .segments() + .iter() + .map(|s| (s.start_sec + offset, s.end_sec + offset)) + .collect() +} + +fn cluster_qualities(embeddings: &[Vec], labels: &[usize]) -> Vec { + let n = embeddings.len(); + let dim = if n > 0 { embeddings[0].len() } else { 0 }; + let k = labels.iter().copied().max().map(|m| m + 1).unwrap_or(0); + let mut centroids = vec![vec![0f32; dim]; k]; + let mut counts = vec![0usize; k]; + for (i, emb) in embeddings.iter().enumerate() { + let l = labels[i]; + for d in 0..dim { + centroids[l][d] += emb[d]; + } + counts[l] += 1; + } + for l in 0..k { + if counts[l] > 0 { + for d in 0..dim { + centroids[l][d] /= counts[l] as f32; + } + l2_normalize(&mut centroids[l]); + } + } + (0..n) + .map(|i| { + let l = labels[i]; + embeddings[i] + .iter() + .zip(centroids[l].iter()) + .map(|(a, b)| a * b) + .sum::() + }) + .collect() +} + +fn load_asr_segments(asr_path: &str) -> (Vec, Option) { + let mut segments = Vec::new(); + let mut language = None; + if let Ok(text) = std::fs::read_to_string(asr_path) { + if let Ok(v) = serde_json::from_str::(&text) { + language = v + .get("language") + .and_then(|s| s.as_str()) + .map(|s| s.to_string()); + if let Some(arr) = v.get("segments").and_then(|s| s.as_array()) { + for seg in arr { + let start = seg + .get("start_time") + .or_else(|| seg.get("start")) + .and_then(|n| n.as_f64()) + .unwrap_or(0.0) as f32; + let end = seg + .get("end_time") + .or_else(|| seg.get("end")) + .and_then(|n| n.as_f64()) + .unwrap_or(0.0) as f32; + let text = seg + .get("text") + .and_then(|s| s.as_str()) + .unwrap_or("") + .to_string(); + segments.push(AsrSegment { start, end, text }); + } + } + } + } + (segments, language) +} + +struct AudioTrack { + index: i64, + language: String, + channels: i64, +} + +fn probe_audio_tracks(video_path: &str) -> Vec { + let out = Command::new("ffprobe") + .args([ + "-v", + "quiet", + "-print_format", + "json", + "-show_streams", + "-select_streams", + "a", + video_path, + ]) + .output(); + let out = match out { + Ok(o) if o.status.success() => o, + _ => return Vec::new(), + }; + let v: serde_json::Value = match serde_json::from_slice(&out.stdout) { + Ok(v) => v, + Err(_) => return Vec::new(), + }; + let mut tracks = Vec::new(); + if let Some(streams) = v.get("streams").and_then(|s| s.as_array()) { + for s in streams { + tracks.push(AudioTrack { + index: s.get("index").and_then(|x| x.as_i64()).unwrap_or(0), + language: s + .get("tags") + .and_then(|t| t.get("language")) + .and_then(|l| l.as_str()) + .unwrap_or("und") + .to_string(), + channels: s.get("channels").and_then(|c| c.as_i64()).unwrap_or(0), + }); + } + } + tracks +} + +/// Prefer English, else the track with the most channels. +fn select_best_track(tracks: &[AudioTrack]) -> i64 { + for t in tracks { + if t.language == "eng" || t.language == "en" { + return t.index; + } + } + let mut best = &tracks[0]; + for t in tracks { + if t.channels > best.channels { + best = t; + } + } + best.index +} + +fn extract_audio(video_path: &str, track_index: i64, output_wav: &str) -> Result<()> { + let status = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "quiet", + "-i", + video_path, + "-map", + &format!("0:{}", track_index), + "-ar", + "16000", + "-ac", + "1", + "-sample_fmt", + "s16", + output_wav, + ]) + .status() + .context("Failed to run ffmpeg")?; + if !status.success() { + anyhow::bail!("ffmpeg exited with {}", status); + } + Ok(()) +} + +fn read_fps(output_dir: &Path, uuid_part: &str) -> f32 { + let probe_path = output_dir.join(format!("{}.probe.json", uuid_part)); + if let Ok(text) = std::fs::read_to_string(&probe_path) { + if let Ok(v) = serde_json::from_str::(&text) { + if let Some(streams) = v.get("streams").and_then(|s| s.as_array()) { + for s in streams { + if s.get("codec_type").and_then(|c| c.as_str()) == Some("video") { + if let Some(rate) = s.get("r_frame_rate").and_then(|r| r.as_str()) { + if let Some((num, den)) = rate.split_once('/') { + let n: f32 = num.parse().unwrap_or(30.0); + let d: f32 = den.parse().unwrap_or(1.0); + if d > 0.0 { + return n / d; + } + } else if let Ok(f) = rate.parse::() { + return f; + } + } + } + } + } + } + } + 30.0 +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_cut.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_cut.rs new file mode 100644 index 00000000..308c85f9 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_cut.rs @@ -0,0 +1,179 @@ +use anyhow::{Context, Result}; +use clap::Parser; +use serde::{Deserialize, Serialize}; +use std::process::Command; + +#[derive(Parser)] +#[command(name = "rust_cut")] +#[command(about = "Scene detection using ffmpeg")] +struct Cli { + /// Video file path + #[arg(required = true)] + video_path: String, + + /// Output JSON path + #[arg(long)] + output: Option, + + /// Video UUID + #[arg(long)] + uuid: Option, + + /// Minimum scene duration (seconds) + #[arg(long, default_value = "0.5")] + min_scene_duration: f64, +} + +#[derive(Debug, Serialize, Deserialize)] +struct CutResult { + scene_count: usize, + scenes: Vec, + video_info: VideoInfo, +} + +#[derive(Debug, Serialize, Deserialize)] +struct Scene { + scene_id: usize, + start_frame: u64, + start_time: f64, + end_frame: u64, + end_time: f64, + duration: f64, +} + +#[derive(Debug, Serialize, Deserialize)] +struct VideoInfo { + duration: f64, + fps: f64, + frame_count: u64, +} + +fn main() -> Result<()> { + let args = Cli::parse(); + + println!("[CUT] Processing: {}", args.video_path); + + let output_path = args.output.unwrap_or_else(|| { + args.video_path.replace(".mp4", ".cut.json") + }); + + let video_info = get_video_info(&args.video_path)?; + println!("[CUT] Duration: {:.1}s, FPS: {:.1}, Frames: {}", + video_info.duration, video_info.fps, video_info.frame_count); + + let scenes = detect_scenes(&args.video_path, args.min_scene_duration, &video_info)?; + println!("[CUT] Detected {} scenes", scenes.len()); + + let result = CutResult { + scene_count: scenes.len(), + scenes, + video_info, + }; + + let json = serde_json::to_string_pretty(&result)?; + std::fs::write(&output_path, json)?; + println!("[CUT] Output: {}", output_path); + + Ok(()) +} + +fn get_video_info(video_path: &str) -> Result { + let output = Command::new("ffprobe") + .args([ + "-v", "quiet", + "-print_format", "json", + "-show_format", + "-show_streams", + video_path, + ]) + .output() + .context("Failed to run ffprobe")?; + + if !output.status.success() { + anyhow::bail!("ffprobe failed"); + } + + let json: serde_json::Value = serde_json::from_slice(&output.stdout)?; + + let duration = json["format"]["duration"] + .as_str() + .and_then(|s| s.parse().ok()) + .unwrap_or(0.0); + + let fps_str = json["streams"][0]["r_frame_rate"] + .as_str() + .unwrap_or("30/1"); + + let fps = if fps_str.contains('/') { + let parts: Vec<&str> = fps_str.split('/').collect(); + let num: f64 = parts[0].parse().unwrap_or(30.0); + let den: f64 = parts[1].parse().unwrap_or(1.0); + num / den + } else { + fps_str.parse().unwrap_or(30.0) + }; + + let frame_count = (duration * fps) as u64; + + Ok(VideoInfo { + duration, + fps, + frame_count, + }) +} + +fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) -> Result> { + let output = Command::new("ffmpeg") + .args([ + "-i", video_path, + "-vf", "select='gt(scene,0.3)',showinfo", + "-f", "null", + "-", + ]) + .output() + .context("Failed to run ffmpeg")?; + + let stderr = String::from_utf8_lossy(&output.stderr); + let mut scenes = Vec::new(); + + let mut last_time = 0.0; + let mut scene_id = 0; + + for line in stderr.lines() { + if line.contains("pts_time:") { + if let Some(time_str) = line.split("pts_time:").nth(1) { + if let Ok(time) = time_str.split_whitespace().next().unwrap_or("0").parse::() { + if time - last_time >= min_duration { + let start_frame = (last_time * video_info.fps) as u64; + let end_frame = (time * video_info.fps) as u64; + + scenes.push(Scene { + scene_id, + start_frame, + start_time: last_time, + end_frame, + end_time: time, + duration: time - last_time, + }); + + scene_id += 1; + last_time = time; + } + } + } + } + } + + if scenes.is_empty() { + scenes.push(Scene { + scene_id: 0, + start_frame: 0, + start_time: 0.0, + end_frame: video_info.frame_count, + end_time: video_info.duration, + duration: video_info.duration, + }); + } + + Ok(scenes) +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_face_cluster.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_face_cluster.rs new file mode 100644 index 00000000..99063a23 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_face_cluster.rs @@ -0,0 +1,979 @@ +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::time::Duration; + +use clap::Parser; +use serde_json::{json, Value}; + +/// Face Clustering Processor (Rust port of fast_face_clustering_processor.py) +/// +/// Loads face embeddings from Qdrant `_faces`, groups by trace_id, computes +/// weighted-average embeddings per trace, then clusters traces with either the +/// seed-leader method (default, deterministic) or average-linkage agglomerative. +#[derive(Parser)] +#[command(name = "rust_face_cluster", about = "Face Clustering Processor (Rust port)")] +struct Args { + video_path: String, + output_path: PathBuf, + #[arg(short = 'u', long = "uuid", default_value = "")] + uuid: String, + #[arg(long = "frames", default_value = None)] + frames: Option, + #[arg(long = "method", default_value = "leader")] + method: String, +#[arg(long = "threshold", default_value_t = 0.15)] +threshold: f64, +#[arg(long = "stage2")] +stage2: bool, +#[arg(long = "merge-threshold", default_value_t = 0.20)] +merge_threshold: f64, + #[arg(long = "force")] + force: bool, +} + +const CONFIDENCE_THRESHOLD: f64 = 0.5; +const DEFAULT_QDRANT_URL: &str = "http://localhost:6333"; +const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200"; + +#[derive(Clone)] +struct FacePoint { + payload: Value, + vector: Vec, +} + +fn env_var(name: &str, default: &str) -> String { + std::env::var(name).unwrap_or_else(|_| default.to_string()) +} + +/// Mimic Python's `round(x, n)` (banker's rounding / round-half-to-even). +fn round_digits(x: f64, digits: i32) -> f64 { + let factor = 10_f64.powi(digits); + (x * factor).round_ties_even() / factor +} + +/// Recursively round all float values to 2 decimals (Python `round_json_numbers`). +fn round_json(value: Value) -> Value { + match value { + Value::Number(n) => { + if n.is_f64() { + let f = n.as_f64().unwrap_or(0.0); + let r = round_digits(f, 2); + serde_json::Number::from_f64(r) + .map(Value::Number) + .unwrap_or(Value::Number(n)) + } else { + Value::Number(n) + } + } + Value::Array(items) => Value::Array(items.into_iter().map(round_json).collect()), + Value::Object(map) => { + Value::Object(map.into_iter().map(|(k, v)| (k, round_json(v))).collect()) + } + other => other, + } +} + +fn write_empty_output(status: &str, file_uuid: &str, output_path: &std::path::Path) { + let output_data = json!({ + "status": status, + "file_uuid": file_uuid, + "clusters": [], + "frames": [], + }); + let text = serde_json::to_string_pretty(&output_data).unwrap_or_default(); + let _ = std::fs::write(output_path, text); + eprintln!("Wrote empty output ({}) to {}", status, output_path.display()); +} + +/// Scroll all Qdrant `_faces` points (payload + vector) for a file via HTTP. +fn load_qdrant_faces(uuid: &str) -> Vec { + let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL); + let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY); + let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url); + + let mut all_points: Vec = Vec::new(); + let mut offset: Option = None; + loop { + let mut body = json!({ + "limit": 10000, + "with_payload": true, + "with_vector": true, + "filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]}, + }); + if let Some(ref off) = offset { + body["offset"] = off.clone(); + } + + let resp = ureq::post(&scroll_url) + .set("api-key", &qdrant_api_key) + .timeout(Duration::from_secs(60)) + .send_json(body); + + match resp { + Ok(r) => { + let data: Value = r.into_json().unwrap_or(Value::Null); + let points = data + .pointer("/result/points") + .and_then(|p| p.as_array()) + .cloned() + .unwrap_or_default(); + for p in points { + let payload = p.get("payload").cloned().unwrap_or(Value::Null); + let vector = p + .get("vector") + .and_then(|v| v.as_array()) + .map(|v| { + v.iter() + .filter_map(|x| x.as_f64()) + .collect::>() + }) + .unwrap_or_default(); + all_points.push(FacePoint { payload, vector }); + } + let next = data.pointer("/result/next_page_offset").cloned(); + match next { + Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)), + Some(Value::Number(_)) => break, + Some(Value::Null) | None => break, + other => { + offset = other; + } + } + } + Err(e) => { + eprintln!("Qdrant scroll error: {}", e); + break; + } + } + } + eprintln!("Loaded {} points from Qdrant _faces", all_points.len()); + all_points +} + +fn dot(a: &[f64], b: &[f64]) -> f64 { + a.iter().zip(b).map(|(x, y)| x * y).sum() +} + +fn norm(v: &[f64]) -> f64 { + v.iter().map(|x| x * x).sum::().sqrt() +} + +fn cosine_similarity(a: &[f64], b: &[f64]) -> f64 { + let n1 = norm(a); + let n2 = norm(b); + if n1 > 0.0 && n2 > 0.0 { + dot(a, b) / (n1 * n2) + } else { + -1.0 + } +} + +/// Weighted-average embedding per trace + pairs (cluster_by_trace). +/// Returns (trace_embeddings: BTreeMap>). +fn cluster_by_trace( + points: &[FacePoint], + min_faces_per_trace: usize, + confidence_threshold: f64, +) -> BTreeMap> { + let high_conf: Vec<&FacePoint> = points + .iter() + .filter(|p| { + p.payload + .get("confidence") + .and_then(|c| c.as_f64()) + .unwrap_or(0.0) + >= confidence_threshold + }) + .collect(); + eprintln!( + "[FILTER] {}/{} faces pass confidence >= {}", + high_conf.len(), + points.len(), + confidence_threshold + ); + + let mut traces: BTreeMap> = BTreeMap::new(); + for p in &high_conf { + if let Some(trace_id) = p.payload.get("trace_id").and_then(|t| t.as_i64()) { + if trace_id >= 0 { + traces.entry(trace_id).or_default().push(p); + } + } + } + eprintln!("[TRACE] Found {} unique traces", traces.len()); + + let mut trace_embeddings: BTreeMap> = BTreeMap::new(); + for (trace_id, trace_points) in traces.iter() { + if trace_points.len() < min_faces_per_trace { + continue; + } + let mut embeddings: Vec<&[f64]> = Vec::new(); + let mut weights: Vec = Vec::new(); + for p in trace_points { + embeddings.push(&p.vector); + weights.push(p.payload.get("confidence").and_then(|c| c.as_f64()).unwrap_or(1.0)); + } + let weight_sum: f64 = weights.iter().sum(); + for w in weights.iter_mut() { + *w /= weight_sum; + } + let dim = embeddings.first().map(|e| e.len()).unwrap_or(0); + let mut avg = vec![0.0_f64; dim]; + for (e, w) in embeddings.iter().zip(weights.iter()) { + for (i, x) in e.iter().enumerate() { + avg[i] += x * w; + } + } + let n = norm(&avg); + if n > 0.0 { + for x in avg.iter_mut() { + *x /= n; + } + } + trace_embeddings.insert(*trace_id, avg); + } + eprintln!( + "[TRACE] {} traces with >= {} faces", + trace_embeddings.len(), + min_faces_per_trace + ); + trace_embeddings +} + +/// Seed-leader clustering with incremental mean centroids (Python default method). +/// Returns (trace_to_person, trace_similarities). +fn seed_leader_cluster( + trace_embeddings: &BTreeMap>, + threshold: f64, +) -> (BTreeMap, BTreeMap) { + let trace_ids: Vec<&i64> = trace_embeddings.keys().collect(); + let n_traces = trace_ids.len(); + if n_traces == 0 { + return (BTreeMap::new(), BTreeMap::new()); + } + if n_traces == 1 { + let tid = *trace_ids[0]; + let mut tm = BTreeMap::new(); + tm.insert(tid, 0); + let mut sm = BTreeMap::new(); + sm.insert(tid, 1.0); + return (tm, sm); + } + + let sim_threshold = 1.0 - threshold; + let mut persons: Vec<(Vec, Vec)> = Vec::new(); // (centroid, member_trace_ids) + let mut trace_similarities: BTreeMap = BTreeMap::new(); + + for tid in trace_ids { + let centroid = trace_embeddings[tid].clone(); + if persons.is_empty() { + persons.push((centroid, vec![*tid])); + trace_similarities.insert(*tid, 1.0); + continue; + } + + let mut best_sim = -1.0; + let mut best_person_idx: Option = None; + for (idx, person) in persons.iter().enumerate() { + let sim = cosine_similarity(¢roid, &person.0); + if sim > best_sim { + best_sim = sim; + best_person_idx = Some(idx); + } + } + + match best_person_idx { + Some(idx) if best_sim >= sim_threshold => { + persons[idx].1.push(*tid); + trace_similarities.insert(*tid, best_sim); + let members: Vec> = persons[idx] + .1 + .iter() + .map(|m| trace_embeddings[m].clone()) + .collect(); + let dim = members[0].len(); + let mut mean = vec![0.0_f64; dim]; + for m in &members { + for (i, x) in m.iter().enumerate() { + mean[i] += x; + } + } + let cnt = members.len() as f64; + for x in mean.iter_mut() { + *x /= cnt; + } + persons[idx].0 = mean; + } + _ => { + persons.push((centroid, vec![*tid])); + trace_similarities.insert(*tid, 1.0); + } + } + } + + let mut trace_to_person: BTreeMap = BTreeMap::new(); + for (person_label, person) in persons.iter().enumerate() { + for m in &person.1 { + trace_to_person.insert(*m, person_label as i64); + } + } + eprintln!("[CLUSTER] Seed-leader detected {} unique persons", persons.len()); + (trace_to_person, trace_similarities) +} + +/// Average-linkage agglomerative clustering (sklearn AgglomerativeClustering +/// with metric="cosine", linkage="average", distance_threshold=threshold). +/// Trace similarity is a 1.0 placeholder, matching the Python script. +fn agglomerative_cluster( + trace_embeddings: &BTreeMap>, + threshold: f64, +) -> (BTreeMap, BTreeMap) { + let trace_ids: Vec<&i64> = trace_embeddings.keys().collect(); + let n = trace_ids.len(); + if n == 0 { + return (BTreeMap::new(), BTreeMap::new()); + } + if n == 1 { + let mut tm = BTreeMap::new(); + tm.insert(*trace_ids[0], 0); + let mut sm = BTreeMap::new(); + sm.insert(*trace_ids[0], 1.0); + return (tm, sm); + } + + // distance matrix: 1 - cosine + let mut dist = vec![vec![0.0_f64; n]; n]; + for i in 0..n { + for j in (i + 1)..n { + let d = 1.0 - cosine_similarity(&trace_embeddings[&trace_ids[i]], &trace_embeddings[&trace_ids[j]]); + dist[i][j] = d; + dist[j][i] = d; + } + } + + // Each cluster: set of member indices. Merges happen in-place: targets stay + // within 0..n, merged-away clusters are cleared + marked inactive. + let mut clusters: Vec> = (0..n).map(|i| vec![i]).collect(); + let mut active = vec![true; n]; + + loop { + // Find pair (a, b) with min distance among active clusters (average linkage). + // Given the input is trace means, average linkage of members = average of + // pairwise distances. We maintain dist as the average linkage between clusters. + let mut best_d = f64::INFINITY; + let mut best_pair: Option<(usize, usize)> = None; + for a in 0..n { + if !active[a] || clusters[a].is_empty() { + continue; + } + for b in (a + 1)..n { + if !active[b] || clusters[b].is_empty() { + continue; + } + if dist[a][b] < best_d { + best_d = dist[a][b]; + best_pair = Some((a, b)); + } + } + } + + let Some((a, b)) = best_pair else { break }; + if best_d > threshold { + break; + } + + // Merge b into a. + let mut merged = clusters[a].clone(); + merged.extend_from_slice(&clusters[b]); + clusters[a] = merged; + clusters[b].clear(); + active[b] = false; + + // Update average-linkage distances from merged cluster (a) to all others. + // Recompute via members is exact for average linkage (UPGMA). + for k in 0..n { + if !active[k] || k == a || clusters[k].is_empty() { + continue; + } + let mut sum = 0.0; + let mut cnt = 0; + for &mi in &clusters[a] { + for &mk in &clusters[k] { + sum += 1.0 - cosine_similarity( + &trace_embeddings[&trace_ids[mi]], + &trace_embeddings[&trace_ids[mk]], + ); + cnt += 1; + } + } + dist[a][k] = if cnt > 0 { sum / cnt as f64 } else { f64::INFINITY }; + dist[k][a] = dist[a][k]; + } + } + + let mut trace_to_person: BTreeMap = BTreeMap::new(); + let mut label = 0; + for cid in 0..n { + if active[cid] && !clusters[cid].is_empty() { + for &mi in &clusters[cid] { + trace_to_person.insert(*trace_ids[mi], label); + } + label += 1; + } + } + + let mut trace_similarities: BTreeMap = BTreeMap::new(); + for tid in trace_ids.iter() { + trace_similarities.insert(**tid, 1.0); + } + + eprintln!("[CLUSTER] Agglomerative detected {} unique persons", label); + (trace_to_person, trace_similarities) +} + +/// Stage 2: Merge over-split clusters based on centroid similarity. +/// 1. Compute centroid for each person (mean of trace embeddings) +/// 2. Find person pairs with distance < merge_threshold +/// 3. Merge iteratively +/// 4. Remap labels to consecutive integers +fn stage2_merge_clusters( + trace_embeddings: &BTreeMap>, + initial_labels: &BTreeMap, + merge_threshold: f64, +) -> BTreeMap { + // 1. Compute centroids for each person + let mut person_centroids: BTreeMap> = BTreeMap::new(); + let mut person_counts: BTreeMap = BTreeMap::new(); + + for (trace_id, embedding) in trace_embeddings.iter() { + let person_label = initial_labels[trace_id]; + let centroid = person_centroids.entry(person_label).or_insert(vec![0.0; embedding.len()]); + for (i, &val) in embedding.iter().enumerate() { + centroid[i] += val; + } + *person_counts.entry(person_label).or_insert(0) += 1; + } + + // Normalize centroids + for (person_label, centroid) in person_centroids.iter_mut() { + let count = person_counts[person_label] as f64; + for val in centroid.iter_mut() { + *val /= count; + } + } + + // 2. Find merge pairs (distance < merge_threshold) + let person_labels: Vec = person_centroids.keys().cloned().collect(); + let mut merge_pairs: Vec<(i64, i64)> = Vec::new(); + + for i in 0..person_labels.len() { + for j in (i + 1)..person_labels.len() { + let label1 = person_labels[i]; + let label2 = person_labels[j]; + let dist = 1.0 - cosine_similarity(&person_centroids[&label1], &person_centroids[&label2]); + if dist < merge_threshold { + merge_pairs.push((label1, label2)); + eprintln!("[STAGE2] Merge candidate: Person_{} <-> Person_{} (distance={:.4})", + label1, label2, dist); + } + } + } + + if merge_pairs.is_empty() { + eprintln!("[STAGE2] No clusters to merge"); + return initial_labels.clone(); + } + + // 3. Merge iteratively (union-find style) + let mut label_mapping: BTreeMap = person_labels.iter().map(|&l| (l, l)).collect(); + + for (label1, label2) in merge_pairs { + let target = label_mapping[&label1]; + let source = label_mapping[&label2]; + if target != source { + // Merge source into target (use smaller label as target) + let final_target = if target < source { target } else { source }; + let final_source = if target < source { source } else { target }; + + for (_, mapped) in label_mapping.iter_mut() { + if *mapped == final_source { + *mapped = final_target; + } + } + } + } + + // 4. Remap to consecutive integers + let final_labels: std::collections::HashSet = label_mapping.values().cloned().collect(); + let mut sorted_labels: Vec = final_labels.into_iter().collect(); + sorted_labels.sort(); + + let mut label_to_person: BTreeMap = BTreeMap::new(); + for (i, &label) in sorted_labels.iter().enumerate() { + label_to_person.insert(label, i as i64); + } + + // 5. Build final trace_to_person mapping + let mut trace_to_person: BTreeMap = BTreeMap::new(); + for (trace_id, &initial_label) in initial_labels.iter() { + let merged_label = label_mapping[&initial_label]; + let final_label = label_to_person[&merged_label]; + trace_to_person.insert(*trace_id, final_label); + } + + let n_before = person_labels.len(); + let n_after = sorted_labels.len(); + eprintln!("[STAGE2] Merged {} -> {} persons", n_before, n_after); + + trace_to_person +} + +fn main() { + let args = Args::parse(); + + let uuid = if args.uuid.is_empty() { + std::path::Path::new(&args.video_path) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("quick_preview") + .to_string() + } else { + args.uuid.clone() + }; + + let output_dir = args.output_path.parent().unwrap_or(std::path::Path::new(".")); + let mut face_json_path = output_dir.join(format!("{}.face.json", uuid)); + + eprintln!("[FACE_CLUSTER] Starting face clustering: {}", args.video_path); + eprintln!("[DEBUG] Output dir: {:?}", output_dir); + eprintln!("[DEBUG] Initial face_json_path: {:?}", face_json_path); + eprintln!("[DEBUG] File exists (attempt 1): {}", face_json_path.exists()); + + if !face_json_path.exists() { + face_json_path = output_dir.join(&uuid).join(format!("{}.face.json", uuid)); + eprintln!("[DEBUG] Fallback face_json_path: {:?}", face_json_path); + eprintln!("[DEBUG] File exists (attempt 2): {}", face_json_path.exists()); + } + + if !face_json_path.exists() { + eprintln!("Face JSON not found."); + write_empty_output("no_face_json", &uuid, &args.output_path); + return; + } + + let face_json_content = std::fs::read_to_string(&face_json_path).expect("Failed to read face.json"); + eprintln!("[DEBUG] Face JSON content length: {} bytes", face_json_content.len()); + + let face_data: Value = serde_json::from_str(&face_json_content).expect("Failed to parse face.json"); + eprintln!("[DEBUG] Face data top-level keys: {:?}", face_data.as_object().map(|o| o.keys().collect::>())); + + let frames_list = face_data.get("frames").and_then(|f| f.as_array()).cloned().unwrap_or_default(); + eprintln!("[DEBUG] Frames list length: {}", frames_list.len()); + + if frames_list.is_empty() { + eprintln!("No frames in JSON (no faces)."); + write_empty_output("no_faces", &uuid, &args.output_path); + return; + } + + let fps_value = face_data + .get("fps") + .and_then(|f| f.as_f64()) + .unwrap_or(23.98); + + let points = load_qdrant_faces(&uuid); + if points.is_empty() { + eprintln!("No embeddings found in Qdrant."); + write_empty_output("no_embeddings", &uuid, &args.output_path); + return; + } + + let threshold = args.threshold; + let trace_embeddings = cluster_by_trace(&points, 1, CONFIDENCE_THRESHOLD); + if trace_embeddings.is_empty() { + eprintln!("No valid traces found."); + write_empty_output("no_embeddings", &uuid, &args.output_path); + return; + } + + let (initial_trace_to_person, trace_similarities) = if args.method == "agglomerative" { + agglomerative_cluster(&trace_embeddings, threshold) + } else { + seed_leader_cluster(&trace_embeddings, threshold) + }; + + // Stage 2: Merge over-split clusters (optional) + let trace_to_person = if args.stage2 { + eprintln!("[STAGE2] Applying Stage 2 merge with threshold={}", args.merge_threshold); + stage2_merge_clusters(&trace_embeddings, &initial_trace_to_person, args.merge_threshold) + } else { + initial_trace_to_person + }; + + if trace_to_person.is_empty() { + eprintln!("Clustering produced no results."); + write_empty_output("no_embeddings", &uuid, &args.output_path); + return; + } + + let n_persons: usize = trace_to_person.values().collect::>().len(); + eprintln!("Clustering result: {} persons ({} traces)", n_persons, trace_to_person.len()); + + // Load face_traced.json to get trace_id for each face. + let traced_path = output_dir.join(format!("{}.face_traced.json", uuid)); + let mut traced_frames: Value = Value::Object(Default::default()); + if traced_path.exists() { + if let Ok(s) = std::fs::read_to_string(&traced_path) { + if let Ok(v) = serde_json::from_str::(&s) { + let frames_raw = v.get("frames").cloned().unwrap_or_else(|| Value::Object(Default::default())); + // Handle both array and object formats + if let Some(frames_array) = frames_raw.as_array() { + // Convert array to object for compatibility + for frame_obj in frames_array { + if let Some(frame_num) = frame_obj.get("frame").and_then(|f| f.as_u64()) { + if let Some(obj) = traced_frames.as_object_mut() { + obj.insert(frame_num.to_string(), frame_obj.clone()); + } + } + } + eprintln!(" Loaded face_traced.json: {} frames (converted from array)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0)); + } else if frames_raw.is_object() { + traced_frames = frames_raw; + eprintln!(" Loaded face_traced.json: {} frames (dict)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0)); + } else { + eprintln!(" Warning: Unexpected frames format: {:?}", frames_raw); + } + } + } + } + + let mut matched_count = 0_i64; + let mut frames_list = frames_list; + for (frame_idx, frame_obj) in frames_list.iter_mut().enumerate() { + let frame_num = frame_obj + .get("frame") + .and_then(|f| f.as_i64()) + .unwrap_or(frame_idx as i64); + let traced_frame = traced_frames + .get(frame_num.to_string().as_str()) + .cloned() + .unwrap_or_else(|| json!({})); + let traced_faces = traced_frame + .get("faces") + .and_then(|f| f.as_array()) + .cloned() + .unwrap_or_default(); + + if let Some(faces) = frame_obj.get_mut("faces").and_then(|f| f.as_array_mut()) { + for (face_idx, face) in faces.iter_mut().enumerate() { + let trace_id = traced_faces + .get(face_idx) + .and_then(|f| f.get("trace_id")) + .and_then(|t| t.as_i64()); + if let Some(trace_id) = trace_id { + if let Some(person_label) = trace_to_person.get(&trace_id) { + face["person_id"] = json!(format!("Person_{}", person_label)); + face["trace_id"] = json!(trace_id); + matched_count += 1; + } + } + } + } + } + eprintln!(" Assigned person_id to {} faces", matched_count); + + if matched_count == 0 { + eprintln!("No faces matched to any trace - check Qdrant data integrity"); + write_empty_output("no_faces", &uuid, &args.output_path); + return; + } + + // Person face counts + best face (representative). + let mut person_face_count: BTreeMap = BTreeMap::new(); + let mut person_best_face: BTreeMap = BTreeMap::new(); + for (frame_idx, frame_obj) in frames_list.iter().enumerate() { + let frame_num = frame_obj.get("frame") + .and_then(|f| f.as_u64()) + .unwrap_or(frame_idx as u64); + let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default(); + for (face_idx, face) in faces.iter().enumerate() { + let person_id = face.get("person_id").and_then(|p| p.as_str()); + if let Some(person_id) = person_id { + *person_face_count.entry(person_id.to_string()).or_insert(0) += 1; + let confidence = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.9); + let entry = person_best_face + .entry(person_id.to_string()) + .or_insert_with(|| { + json!({ + "confidence": f64::NEG_INFINITY, + }) + }); + if confidence > entry.get("confidence").and_then(|c| c.as_f64()).unwrap_or(f64::NEG_INFINITY) { + *entry = json!({ + "face_id": format!("face_{}_{}", frame_num, face_idx), + "confidence": confidence, + "frame": frame_num, + "bbox": { + "x": face.get("x").cloned().unwrap_or(Value::Null), + "y": face.get("y").cloned().unwrap_or(Value::Null), + "width": face.get("width").cloned().unwrap_or(Value::Null), + "height": face.get("height").cloned().unwrap_or(Value::Null), + } + }); + } + } + } + } + + // Build per-person similarity stats from trace_similarities. + let mut person_sims: BTreeMap> = BTreeMap::new(); + let sim_threshold_value = 1.0 - threshold; + for (tid, person_label) in trace_to_person.iter() { + let sim = trace_similarities.get(tid).copied().unwrap_or(0.0); + person_sims.entry(*person_label).or_default().push(sim); + } + + let mut sorted_persons: Vec<(&String, &u64)> = person_face_count.iter().collect(); + sorted_persons.sort_by(|a, b| b.1.cmp(a.1)); + + let mut clusters: Vec = Vec::new(); + for (person_id, count) in sorted_persons { + let person_label: Option = person_id + .split('_') + .nth(1) + .and_then(|s| s.parse::().ok()); + + let mut similarity_info: Option = None; + if let Some(label) = person_label { + if let Some(sims) = person_sims.get(&label) { + if !sims.is_empty() { + let min_s = sims.iter().cloned().fold(f64::INFINITY, f64::min); + let avg_s = sims.iter().sum::() / sims.len() as f64; + similarity_info = Some(json!({ + "min": round_digits(min_s, 4), + "avg": round_digits(avg_s, 4), + "threshold": round_digits(sim_threshold_value, 4), + })); + } + } + } + + let mut cluster_entry = json!({ + "cluster_id": person_id, + "face_count": count, + }); + if let Some(rep) = person_best_face.get(person_id) { + cluster_entry["representative_face"] = rep.clone(); + } + if let Some(sim) = similarity_info { + cluster_entry["similarity"] = sim; + } + clusters.push(cluster_entry); + } + + // Build output frames. + let mut output_frames: Vec = Vec::new(); + for (frame_idx, frame_obj) in frames_list.iter().enumerate() { + let frame_num = frame_obj.get("frame") + .and_then(|f| f.as_u64()) + .unwrap_or(frame_idx as u64); + let timestamp = frame_obj.get("timestamp").cloned().unwrap_or_else(|| { + if fps_value > 0.0 { + json!(frame_num as f64 / fps_value) + } else { + json!(0) + } + }); + let mut output_faces: Vec = Vec::new(); + let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default(); + for (face_idx, face) in faces.iter().enumerate() { + let person_id = face.get("person_id").and_then(|p| p.as_str()); + if let Some(person_id) = person_id { + output_faces.push(json!({ + "face_id": format!("face_{}_{}", frame_num, face_idx), + "cluster_id": person_id, + "trace_id": face.get("trace_id").cloned().unwrap_or(Value::Null), + "confidence": face.get("confidence").cloned().unwrap_or(json!(0.9)), + })); + } + } + if !output_faces.is_empty() { + output_frames.push(json!({ + "frame": frame_num, + "timestamp": timestamp, + "faces": output_faces, + })); + } + } + + // Filter low-quality clusters (hand detections, isolated faces) + // Filter criteria: + // - face_count < 5 (too few faces, likely isolated or hand) + // - bbox_area > 200,000 (abnormally large bbox, likely hand/object) + let min_face_count = 3; + let max_bbox_area = 200_000.0; + + let mut filtered_cluster_ids: std::collections::HashSet = std::collections::HashSet::new(); + let mut filtered_clusters: Vec = Vec::new(); + + for cluster in &clusters { + let cluster_id = cluster.get("cluster_id").and_then(|c| c.as_str()).unwrap_or(""); + let face_count = cluster.get("face_count").and_then(|c| c.as_i64()).unwrap_or(0); + + // Calculate bbox area from representative_face + let bbox_area: f64 = cluster.get("representative_face") + .and_then(|rf| rf.get("bbox")) + .map(|bbox| { + let w = bbox.get("width").and_then(|w| w.as_f64()).unwrap_or(0.0); + let h = bbox.get("height").and_then(|h| h.as_f64()).unwrap_or(0.0); + w * h + }) + .unwrap_or(0.0); + + // Filter logic + if face_count < min_face_count || bbox_area > max_bbox_area { + eprintln!("[CLUSTER] Filtered out {}: face_count={}, bbox_area={}", + cluster_id, face_count, bbox_area); + filtered_cluster_ids.insert(cluster_id.to_string()); + } else { + filtered_clusters.push(cluster.clone()); + } + } + + // Remove filtered clusters from output_frames + let filtered_frames: Vec = output_frames.iter().map(|frame| { + let faces = frame.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default(); + let filtered_faces: Vec = faces.iter() + .filter(|face| { + let cluster_id = face.get("cluster_id").and_then(|c| c.as_str()).unwrap_or(""); + !filtered_cluster_ids.contains(cluster_id) + }) + .cloned() + .collect(); + + if filtered_faces.is_empty() { + Value::Null + } else { + json!({ + "frame": frame.get("frame").cloned().unwrap_or(Value::Null), + "timestamp": frame.get("timestamp").cloned().unwrap_or(Value::Null), + "faces": filtered_faces, + }) + } + }).filter(|f| !f.is_null()).collect(); + + eprintln!("[CLUSTER] Filtered {} low-quality clusters ({} total)", + filtered_cluster_ids.len(), clusters.len()); + eprintln!("[CLUSTER] Remaining: {} clusters", filtered_clusters.len()); + + let mut output_data = json!({ + "status": "has_faces", + "file_uuid": uuid, + "clusters": filtered_clusters, + "frames": filtered_frames, + }); + + // Auto-bind speakers from asrx.json. + let asrx_path = output_dir.join(format!("{}.asrx.json", uuid)); + let speaker_mapping = auto_bind_speakers(&output_frames, &asrx_path); + if !speaker_mapping.is_null() { + output_data["speaker_person_mapping"] = speaker_mapping; + } + + let rounded = round_json(output_data); + let text = serde_json::to_string_pretty(&rounded).map_err(|e| e.to_string()); + match text { + Ok(t) => { + std::fs::write(&args.output_path, t).expect("Failed to write output"); + eprintln!("Saved clustered data to {}", args.output_path.display()); + } + Err(e) => { + eprintln!("Failed to serialize output: {}", e); + std::process::exit(1); + } + } +} + +/// Compute speaker -> Person_N mapping by vote (Python auto_bind_speakers). +fn auto_bind_speakers(output_frames: &[Value], asrx_path: &std::path::Path) -> Value { + if !asrx_path.exists() { + eprintln!("Missing data for speaker binding."); + return Value::Null; + } + + let asrx_data: Value = match std::fs::read_to_string(asrx_path) { + Ok(s) => match serde_json::from_str(&s) { + Ok(v) => v, + Err(e) => { + eprintln!(" Failed to load ASRX: {}", e); + return Value::Null; + } + }, + Err(_) => return Value::Null, + }; + + eprintln!("Auto-binding Speakers to Persons..."); + + let mut face_spans: Vec<(f64, String)> = Vec::new(); + for frame_obj in output_frames { + if let Some(ts) = frame_obj.get("timestamp").and_then(|t| t.as_f64()) { + if let Some(faces) = frame_obj.get("faces").and_then(|f| f.as_array()) { + for face in faces { + if let Some(person_id) = face.get("cluster_id").and_then(|p| p.as_str()) { + face_spans.push((ts, person_id.to_string())); + } + } + } + } + } + + let mut speaker_person_counts: BTreeMap> = BTreeMap::new(); + let segments = asrx_data.get("segments").and_then(|s| s.as_array()).cloned().unwrap_or_default(); + for seg in &segments { + let start = seg.get("start_time").or_else(|| seg.get("start")).and_then(|x| x.as_f64()); + let end = seg.get("end_time").or_else(|| seg.get("end")).and_then(|x| x.as_f64()); + let speaker = seg.get("speaker_id").and_then(|x| x.as_str()); + if speaker.is_none() || start.is_none() || end.is_none() { + continue; + } + let speaker = speaker.unwrap(); + let start = start.unwrap(); + let end = end.unwrap(); + let candidates: Vec<&(f64, String)> = face_spans + .iter() + .filter(|(ts, _)| start <= *ts && *ts <= end) + .collect(); + if !candidates.is_empty() { + let mut person_counts: BTreeMap = BTreeMap::new(); + for (_, pid) in candidates.iter() { + *person_counts.entry(pid.clone()).or_insert(0) += 1; + } + let best_person = person_counts + .iter() + .max_by(|a, b| a.1.cmp(b.1)) + .map(|(p, _)| p.clone()); + if let Some(best) = best_person { + let entry = speaker_person_counts.entry(speaker.to_string()).or_default(); + *entry.entry(best).or_insert(0) += 1; + } + } + } + + let mut mapping: BTreeMap = BTreeMap::new(); + for (speaker, persons) in speaker_person_counts.iter() { + if persons.is_empty() { + continue; + } + let best_person = persons.iter().max_by(|a, b| a.1.cmp(b.1)).map(|(p, _)| p); + if let Some(best) = best_person { + mapping.insert(speaker.clone(), best.clone()); + eprintln!(" {} is likely {} ({} votes)", speaker, best, persons[best]); + } + } + + if mapping.is_empty() { + Value::Null + } else { + serde_json::to_value(mapping).unwrap_or(Value::Null) + } +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_face_processor.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_face_processor.rs new file mode 100644 index 00000000..8462e5e4 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_face_processor.rs @@ -0,0 +1,205 @@ +use anyhow::{Context, Result}; +use clap::Parser; +use std::path::PathBuf; +use std::time::Instant; + +mod face_processor; + +use face_processor::{ + FaceOutput, FrameData, FaceInfo, Metadata, PoseAngle, + VideoReader, FaceDetector, FaceCropper, EmbeddingExtractor, + QdrantFaceStore, FaceEmbedPayload, +}; + +#[derive(Parser, Debug)] +#[command(name = "rust_face_processor")] +#[command(about = "Face detection and embedding extraction using Rust")] +struct Args { + /// Path to video file + #[arg(short, long)] + video: PathBuf, + + /// Path to output JSON file + #[arg(short, long)] + output: PathBuf, + + /// Video file UUID + #[arg(short, long)] + uuid: String, + + /// Sample interval (frames) + #[arg(long, default_value = "3")] + sample_interval: usize, + + /// Path to ONNX model + #[arg(long, default_value = "models/facenet_vggface2.onnx")] + model: PathBuf, +} + +fn classify_pose(roll: f64, yaw: f64) -> String { + let abs_yaw = yaw.abs(); + let abs_roll = roll.abs(); + + if abs_yaw < 15.0 && abs_roll < 15.0 { + "frontal".to_string() + } else if abs_yaw > 30.0 { + if yaw > 0.0 { + "profile_right".to_string() + } else { + "profile_left".to_string() + } + } else { + "three_quarter".to_string() + } +} + +#[tokio::main] +async fn main() -> Result<()> { + let args = Args::parse(); + let start_time = Instant::now(); + + println!("[FACE_RUST] Starting face processor"); + println!("[FACE_RUST] Video: {:?}", args.video); + println!("[FACE_RUST] Output: {:?}", args.output); + println!("[FACE_RUST] UUID: {}", args.uuid); + + // Initialize modules + let mut video_reader = VideoReader::new(&args.video) + .context("Failed to initialize video reader")?; + + println!("[FACE_RUST] Video: {}x{}, {:.1} fps, {} frames", + video_reader.width(), + video_reader.height(), + video_reader.fps(), + video_reader.frame_count() + ); + + let detector = FaceDetector::new() + .context("Failed to initialize face detector")?; + + let cropper = FaceCropper::new(); + + let mut embedder = EmbeddingExtractor::new(&args.model) + .context("Failed to initialize embedding extractor")?; + + // Initialize Qdrant + let qdrant = QdrantFaceStore::new() + .await + .context("Failed to initialize Qdrant store")?; + + // Run face detection + let detection_output = args.output.with_extension("detect.json"); + let detections = detector.detect(&args.video, &detection_output, args.sample_interval)?; + + // Process each detection + let mut frames: Vec = Vec::new(); + let mut embeddings_data: Vec = Vec::new(); + let mut total_embeddings = 0; + let mut total_faces = 0; + + println!("[FACE_RUST] Processing {} faces...", detections.len()); + + for detection in detections { + // Read frame + let frame = match video_reader.read_frame(detection.frame)? { + Some(f) => f, + None => continue, + }; + + // Crop face + let face_img = cropper.crop(&frame, &detection.bbox)?; + + // Extract embedding + let embedding = embedder.extract(&face_img)?; + total_embeddings += 1; + + // Store embedding data for Qdrant + embeddings_data.push(FaceEmbedPayload { + frame: detection.frame, + trace_id: 0, // Will be updated by face tracker + bbox: detection.bbox.clone(), + confidence: detection.confidence, + capture_quality: detection.capture_quality.map(|q| q as f64), + embedding, + }); + + // Classify pose + let pose_angle = detection.pose.as_ref().map(|p| { + PoseAngle { + angle: classify_pose(p.roll, p.yaw), + roll: p.roll, + yaw: p.yaw, + pitch: p.pitch, + } + }); + + // Create face info (without embedding) + let face_info = FaceInfo { + x: detection.bbox.x, + y: detection.bbox.y, + width: detection.bbox.width, + height: detection.bbox.height, + confidence: detection.confidence, + pose_angle, + capture_quality: detection.capture_quality, + }; + + // Add to frame + frames.push(FrameData { + frame: detection.frame, + timestamp: detection.timestamp, + faces: vec![face_info], + }); + + total_faces += 1; + + if total_faces % 100 == 0 { + println!("[FACE_RUST] Processed {} faces", total_faces); + } + } + + // Push embeddings to Qdrant + if !embeddings_data.is_empty() { + println!("[QDRANT] Pushing {} embeddings...", embeddings_data.len()); + let pushed = qdrant.push_embeddings_batch(&args.uuid, embeddings_data) + .await + .context("Failed to push embeddings to Qdrant")?; + println!("[QDRANT] Pushed {} embeddings to _faces collection", pushed); + } + + // Create output + let output = FaceOutput { + status: if total_faces > 0 { "has_faces" } else { "no_faces" }.to_string(), + frame_count: frames.len(), + fps: video_reader.fps(), + frames, + total_faces, + metadata: Metadata { + embedding_method: "rust_facenet".to_string(), + embedding_model: "InceptionResnetV1_VGGFace2".to_string(), + total_embeddings, + }, + }; + + // Write output + let json = serde_json::to_string_pretty(&output)?; + std::fs::write(&args.output, json)?; + + let elapsed = start_time.elapsed(); + + println!("[FACE_RUST] Done: {} frames, {} faces, {} embeddings, {:.1}s", + output.frame_count, + output.total_faces, + output.metadata.total_embeddings, + elapsed.as_secs_f64() + ); + + println!("[FACE_RUST] Output written to {:?}", args.output); + + // Clean up detection output + if detection_output.exists() { + std::fs::remove_file(&detection_output)?; + } + + Ok(()) +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_facenet.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_facenet.rs new file mode 100644 index 00000000..f929d59b --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_facenet.rs @@ -0,0 +1,103 @@ +use anyhow::{Context, Result}; +use clap::Parser; +use image::DynamicImage; +use ndarray::IxDyn; +use ort::session::Session; +use ort::value::Value; +use serde_json::json; +use std::path::PathBuf; + +#[derive(Parser, Debug)] +#[command(name = "rust_facenet")] +#[command(about = "Extract face embeddings using ONNX Runtime")] +struct Args { + /// Path to face image + #[arg(short, long)] + input: PathBuf, + + /// Path to ONNX model + #[arg(short, long, default_value = "models/facenet_vggface2.onnx")] + model: PathBuf, +} + +struct FaceNetModel { + session: Session, +} + +impl FaceNetModel { + fn new(model_path: &PathBuf) -> Result { + println!("[FACENET] Loading model: {:?}", model_path); + + let session = Session::builder() + .context("Failed to create session builder")? + .commit_from_file(model_path) + .context("Failed to load model")?; + + println!("[FACENET] Model loaded successfully"); + Ok(Self { session }) + } + + fn preprocess(&self, img: &DynamicImage) -> Result> { + let resized = img.resize_exact(160, 160, image::imageops::FilterType::Lanczos3); + + let mut input_array = ndarray::Array::from_shape_vec( + IxDyn(&[1, 3, 160, 160]), + vec![0.0f32; 1 * 3 * 160 * 160] + ).context("Failed to create input array")?; + + for (x, y, pixel) in resized.to_rgb8().enumerate_pixels() { + let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32); + input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0; + input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0; + input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0; + } + + Ok(input_array) + } + + fn extract_embedding(&mut self, img: &DynamicImage) -> Result> { + let input_array = self.preprocess(img)?; + let input_value = Value::from_array(input_array) + .context("Failed to create input value")?; + + let inputs = ort::inputs!["input" => input_value]; + + let outputs = self.session.run(inputs) + .context("Failed to run inference")?; + + let output = outputs["output"].try_extract_tensor::() + .context("Failed to extract output tensor")?; + + let output_data = output.1; + let embedding = output_data.to_vec(); + + Ok(embedding) + } +} + +fn main() -> Result<()> { + let args = Args::parse(); + + let mut model = FaceNetModel::new(&args.model)?; + let img = image::open(&args.input) + .context(format!("Failed to load image: {:?}", args.input))?; + + println!("[FACENET] Processing image: {:?}", args.input); + + let start = std::time::Instant::now(); + let embedding = model.extract_embedding(&img)?; + let elapsed = start.elapsed(); + + println!("[FACENET] Extraction time: {:?}", elapsed); + println!("[FACENET] Embedding length: {}", embedding.len()); + + let output = json!({ + "embedding": embedding, + "count": embedding.len(), + "time_ms": elapsed.as_millis() + }); + + println!("{}", serde_json::to_string_pretty(&output)?); + + Ok(()) +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_facenet_coreml.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_facenet_coreml.rs new file mode 100644 index 00000000..58f17165 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_facenet_coreml.rs @@ -0,0 +1,132 @@ +use anyhow::{Context, Result}; +use clap::Parser; +use image::DynamicImage; +use ndarray::IxDyn; +use ort::session::Session; +use ort::value::Value; +use serde_json::json; +use std::path::PathBuf; + +#[derive(Parser, Debug)] +#[command(name = "rust_facenet_coreml")] +#[command(about = "Extract face embeddings using ONNX Runtime with CoreML acceleration")] +struct Args { + /// Path to face image + #[arg(short, long)] + input: PathBuf, + + /// Path to ONNX model + #[arg(short, long, default_value = "models/facenet_vggface2.onnx")] + model: PathBuf, + + /// Use CoreML acceleration (flag, no value needed) + #[arg(short, long, default_value_t = false)] + coreml: bool, +} + +struct FaceNetModel { + session: Session, +} + +impl FaceNetModel { + fn new(model_path: &PathBuf, use_coreml: bool) -> Result { + println!("[FACENET] Loading model: {:?}", model_path); + println!("[FACENET] CoreML acceleration: {}", use_coreml); + + let session = if use_coreml { + #[cfg(target_os = "macos")] + { + println!("[FACENET] Using CoreML feature (but ort API is unclear)"); + + let mut builder = Session::builder() + .context("Failed to create session builder")?; + + builder.commit_from_file(model_path) + .context("Failed to load model")? + } + + #[cfg(not(target_os = "macos"))] + { + println!("[FACENET] CoreML only available on macOS, using CPU"); + Session::builder() + .context("Failed to create session builder")? + .commit_from_file(model_path) + .context("Failed to load model")? + } + } else { + println!("[FACENET] Using CPU"); + Session::builder() + .context("Failed to create session builder")? + .commit_from_file(model_path) + .context("Failed to load model")? + }; + + println!("[FACENET] Model loaded successfully"); + Ok(Self { session }) + } + + fn preprocess(&self, img: &DynamicImage) -> Result> { + let resized = img.resize_exact(160, 160, image::imageops::FilterType::Lanczos3); + + let mut input_array = ndarray::Array::from_shape_vec( + IxDyn(&[1, 3, 160, 160]), + vec![0.0f32; 1 * 3 * 160 * 160] + ).context("Failed to create input array")?; + + for (x, y, pixel) in resized.to_rgb8().enumerate_pixels() { + let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32); + input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0; + input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0; + input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0; + } + + Ok(input_array) + } + + fn extract_embedding(&mut self, img: &DynamicImage) -> Result> { + let input_array = self.preprocess(img)?; + let input_value = Value::from_array(input_array) + .context("Failed to create input value")?; + + let inputs = ort::inputs!["input" => input_value]; + + let outputs = self.session.run(inputs) + .context("Failed to run inference")?; + + let output = outputs["output"].try_extract_tensor::() + .context("Failed to extract output tensor")?; + + let output_data = output.1; + let embedding = output_data.to_vec(); + + Ok(embedding) + } +} + +fn main() -> Result<()> { + let args = Args::parse(); + + let mut model = FaceNetModel::new(&args.model, args.coreml)?; + let img = image::open(&args.input) + .context(format!("Failed to load image: {:?}", args.input))?; + + println!("[FACENET] Processing image: {:?}", args.input); + + let start = std::time::Instant::now(); + let embedding = model.extract_embedding(&img)?; + let elapsed = start.elapsed(); + + println!("[FACENET] Extraction time: {:?}", elapsed); + println!("[FACENET] Embedding length: {}", embedding.len()); + + let output = json!({ + "embedding": embedding, + "count": embedding.len(), + "time_ms": elapsed.as_millis(), + "coreml": args.coreml + }); + + println!("{}", serde_json::to_string_pretty(&output)?); + + Ok(()) +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_pose.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_pose.rs new file mode 100644 index 00000000..03aa341b --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_pose.rs @@ -0,0 +1,275 @@ +use std::collections::BTreeMap; +use std::process::Command; + +use clap::Parser; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Parser)] +#[command(name = "rust_pose", about = "Pose Processor (Rust port of pose_processor.py interpolation)")] +struct Args { + video_path: std::path::PathBuf, + /// Existing pose.json produced by swift_face_pose (source of detected frames). + source_pose: std::path::PathBuf, + output_path: std::path::PathBuf, + #[arg(short = 'u', long = "uuid", default_value = "")] + uuid: String, + /// Comma-separated 8Hz target frames. When provided, detection is skipped and + /// the source is copied through unchanged (matches Python's 8Hz short-circuit). + #[arg(long = "frames", default_value = None)] + frames: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct PoseResult { + frame_count: u64, + fps: f64, + #[serde(default)] + frames: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct PoseFrame { + frame: i64, + #[serde(default)] + timestamp: f64, + #[serde(default)] + persons: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct PersonPose { + #[serde(default)] + keypoints: Vec, + #[serde(default)] + bbox: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct Keypoint { + name: String, + #[serde(default)] + x: f64, + #[serde(default)] + y: f64, + #[serde(default)] + confidence: f64, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Default)] +struct BBoxInt { + x: i64, + y: i64, + width: i64, + height: i64, +} + +/// Mimic Python's `round(x, 2)` (banker's rounding / round-half-to-even). +fn round2(x: f64) -> f64 { + (x * 100.0).round_ties_even() / 100.0 +} + +/// Recursively round all float values to 2 decimals (Python `round_json_numbers`). +/// Integers pass through unchanged, matching Python's `round_json_numbers`. +fn round_json(value: Value) -> Value { + match value { + Value::Number(n) => { + if n.is_f64() { + let f = n.as_f64().unwrap_or(0.0); + let r = round2(f); + serde_json::Number::from_f64(r).map(Value::Number).unwrap_or(Value::Number(n)) + } else { + Value::Number(n) + } + } + Value::Array(items) => Value::Array(items.into_iter().map(round_json).collect()), + Value::Object(map) => { + Value::Object(map.into_iter().map(|(k, v)| (k, round_json(v))).collect()) + } + other => other, + } +} + +/// Get total video frame count via ffprobe (nb_frames, falling back to duration*fps). +fn total_video_frames(video_path: &std::path::Path) -> u64 { + let nb_str = Command::new("ffprobe") + .args([ + "-v", "error", "-select_streams", "v:0", + "-show_entries", "stream=nb_frames", "-of", "csv=p=0", + ]) + .arg(video_path) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().trim_end_matches(',').to_string()); + + if let Some(s) = nb_str { + if s != "N/A" { + if let Ok(n) = s.parse::() { + return n; + } + } + // Fallback: duration * fps + let dur = Command::new("ffprobe") + .args(["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0"]) + .arg(video_path) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().parse::().unwrap_or(0.0)) + .unwrap_or(0.0); + let fps_str = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=r_frame_rate", "-of", "csv=p=0"]) + .arg(video_path) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().trim_end_matches(',').to_string()); + let fps = fps_str + .map(|s| { + if let Some((n, d)) = s.split_once('/') { + let n: f64 = n.trim().parse().unwrap_or(30.0); + let d: f64 = d.trim().trim_end_matches(',').parse().unwrap_or(1.0); + if d > 0.0 { + n / d + } else { + 30.0 + } + } else { + s.parse().unwrap_or(30.0) + } + }) + .unwrap_or(30.0); + (dur * fps) as u64 + } else { + 0 + } +} + +fn interpolate_pose(source: &PoseResult, video_path: &std::path::Path) -> PoseResult { + let total = total_video_frames(video_path); + let fps = source.fps; + eprintln!( + "[POSE] interpolating {} detected frames -> {} total video frames (fps={})", + source.frames.len(), + total, + fps + ); + + if source.frames.is_empty() { + return source.clone(); + } + + // Collect frames per person index across all detected frames. + let mut all_persons: BTreeMap> = BTreeMap::new(); + for f in &source.frames { + for (i, p) in f.persons.iter().enumerate() { + all_persons.entry(i).or_default().push((f.frame, p.clone())); + } + } + + let mut interpolated_frames: Vec = Vec::new(); + + for frame_num in 0..total { + let ts = frame_num as f64 / fps; + let mut persons_in_frame: Vec = Vec::new(); + + for (_person_id, person_frames) in &all_persons { + let mut before: Option<(i64, &PersonPose)> = None; + let mut after: Option<(i64, &PersonPose)> = None; + for (fn_, p) in person_frames { + if *fn_ <= frame_num as i64 { + before = Some((*fn_, p)); + } + if *fn_ >= frame_num as i64 && after.is_none() { + after = Some((*fn_, p)); + } + } + + if before.is_none() && after.is_none() { + continue; + } + + let (interp_kps, interp_bbox): (Vec, Option) = if let (Some((t0, b)), Some((t1, a))) = (before, after) { + if t0 != t1 { + let t = (frame_num as i64 - t0) as f64 / (t1 - t0) as f64; + let kp_before = &b.keypoints; + let kp_after = &a.keypoints; + let mut kps: Vec = Vec::new(); + for i in 0..kp_before.len().max(kp_after.len()) { + let kp0 = if i < kp_before.len() { &kp_before[i] } else { &kp_after[i] }; + let kp1 = if i < kp_after.len() { &kp_after[i] } else { &kp_before[i] }; + kps.push(Keypoint { + name: kp0.name.clone(), + x: kp0.x + t * (kp1.x - kp0.x), + y: kp0.y + t * (kp1.y - kp0.y), + confidence: kp0.confidence + t * (kp1.confidence - kp0.confidence), + }); + } + let bbox = match (&b.bbox, &a.bbox) { + (Some(b0), Some(b1)) => Some(BBoxInt { + x: (b0.x as f64 + t * (b1.x as f64 - b0.x as f64)) as i64, + y: (b0.y as f64 + t * (b1.y as f64 - b0.y as f64)) as i64, + width: (b0.width as f64 + t * (b1.width as f64 - b0.width as f64)) as i64, + height: (b0.height as f64 + t * (b1.height as f64 - b0.height as f64)) as i64, + }), + _ => None, + }; + (kps, bbox) + } else { + (b.keypoints.clone(), b.bbox.clone()) + } + } else if let Some((_, b)) = before { + (b.keypoints.clone(), b.bbox.clone()) + } else if let Some((_, a)) = after { + (a.keypoints.clone(), a.bbox.clone()) + } else { + (Vec::new(), None) + }; + + let valid_bbox = interp_bbox + .as_ref() + .map(|b| b.width > 0 && b.height > 0) + .unwrap_or(false); + if valid_bbox { + persons_in_frame.push(PersonPose { + keypoints: interp_kps, + bbox: interp_bbox, + }); + } + } + + if !persons_in_frame.is_empty() { + interpolated_frames.push(PoseFrame { + frame: frame_num as i64, + timestamp: ts, + persons: persons_in_frame, + }); + } + } + + eprintln!("[POSE] interpolated -> {} frames", interpolated_frames.len()); + PoseResult { + frame_count: interpolated_frames.len() as u64, + fps, + frames: interpolated_frames, + } +} + +fn main() { + let args = Args::parse(); + + let source_str = std::fs::read_to_string(&args.source_pose).expect("failed to read source_pose"); + let source: PoseResult = serde_json::from_str(&source_str).expect("failed to parse source_pose"); + + let result: PoseResult = if args.frames.is_some() { + eprintln!("[POSE] 8Hz mode: returning {} frames without interpolation", source.frames.len()); + source + } else { + interpolate_pose(&source, &args.video_path) + }; + + let json = round_json(serde_json::to_value(&result).expect("serialize result")); + std::fs::write(&args.output_path, serde_json::to_string(&json).unwrap()).expect("write output"); + eprintln!("[POSE] Done: {} frames -> {}", result.frame_count, args.output_path.display()); +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_scene_vlm.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_scene_vlm.rs new file mode 100644 index 00000000..f044968a --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_scene_vlm.rs @@ -0,0 +1,173 @@ +use anyhow::{Context, Result}; +use clap::Parser; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +#[derive(Parser)] +#[command(name = "rust_scene_vlm")] +#[command(about = "Scene VLM analysis using LLM API")] +struct Cli { + /// File UUID + #[arg(long)] + file_uuid: String, + + /// Output directory + #[arg(long)] + output_dir: Option, + + /// LLM API URL + #[arg(long, default_value = "http://localhost:8080/v1/chat/completions")] + llm_url: String, + + /// Max tokens + #[arg(long, default_value = "300")] + max_tokens: u32, + + /// Scene number (optional, process specific scene) + #[arg(long)] + scene_number: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +struct SceneAnalysis { + scene_number: usize, + vlm_description: String, + vlm_location: Option, + vlm_activity: Option, + vlm_mood: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +struct SceneProfile { + file_uuid: String, + scenes: Vec, +} + +fn main() -> Result<()> { + let args = Cli::parse(); + + println!("[SCENE_VLM] Processing file: {}", args.file_uuid); + + let output_dir = args.output_dir.unwrap_or_else(|| { + std::env::var("MOMENTRY_OUTPUT_DIR") + .unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string()) + }); + + let scenes = analyze_scenes(&args.file_uuid, &output_dir, &args.llm_url, args.max_tokens)?; + + println!("[SCENE_VLM] Analyzed {} scenes", scenes.len()); + + let profile = SceneProfile { + file_uuid: args.file_uuid.clone(), + scenes, + }; + + let output_path = format!("{}/{}_scene_profile.json", output_dir, args.file_uuid); + let json = serde_json::to_string_pretty(&profile)?; + std::fs::write(&output_path, json)?; + + println!("[SCENE_VLM] Output: {}", output_path); + + Ok(()) +} + +fn analyze_scenes( + file_uuid: &str, + output_dir: &str, + llm_url: &str, + max_tokens: u32, +) -> Result> { + let mut scenes = Vec::new(); + + for entry in std::fs::read_dir(output_dir)? { + let entry = entry?; + let filename = entry.file_name().to_string_lossy().to_string(); + + if filename.starts_with(file_uuid) && filename.contains("_scene_") && filename.ends_with(".jpg") { + if let Some(scene_num) = extract_scene_number(&filename) { + println!("[SCENE_VLM] Processing scene {}", scene_num); + + let image_path = entry.path(); + match analyze_scene_image(&image_path, scene_num, llm_url, max_tokens) { + Ok(analysis) => scenes.push(analysis), + Err(e) => println!("[SCENE_VLM] Failed to analyze scene {}: {}", scene_num, e), + } + } + } + } + + scenes.sort_by_key(|s| s.scene_number); + Ok(scenes) +} + +fn extract_scene_number(filename: &str) -> Option { + let parts: Vec<&str> = filename.split("_scene_").collect(); + if parts.len() == 2 { + parts[1].trim_end_matches(".jpg").parse().ok() + } else { + None + } +} + +fn analyze_scene_image( + image_path: &PathBuf, + scene_number: usize, + llm_url: &str, + max_tokens: u32, +) -> Result { + let image_data = std::fs::read(image_path)?; + let image_b64 = base64_encode(&image_data); + + let prompt = "Describe this scene in detail. Include: location, activity, mood, and key visual elements."; + + let description = call_llm(llm_url, &image_b64, prompt, max_tokens)?; + + Ok(SceneAnalysis { + scene_number, + vlm_description: description, + vlm_location: None, + vlm_activity: None, + vlm_mood: None, + }) +} + +fn base64_encode(data: &[u8]) -> String { + use base64::{Engine as _, engine::general_purpose}; + general_purpose::STANDARD.encode(data) +} + +fn call_llm(url: &str, image_b64: &str, prompt: &str, max_tokens: u32) -> Result { + let client = reqwest::blocking::Client::new(); + + let body = serde_json::json!({ + "model": "gemma-4-12b-it", + "messages": [{ + "role": "user", + "content": [ + {"type": "text", "text": prompt}, + {"type": "image_url", "image_url": {"url": format!("data:image/jpeg;base64,{}", image_b64)}} + ] + }], + "max_tokens": max_tokens + }); + + let resp = client + .post(url) + .json(&body) + .timeout(std::time::Duration::from_secs(60)) + .send() + .context("Failed to call LLM API")?; + + if !resp.status().is_success() { + anyhow::bail!("LLM API returned error: {}", resp.status()); + } + + let json: serde_json::Value = resp.json().context("Failed to parse LLM response")?; + + let content = json["choices"][0]["message"]["content"] + .as_str() + .unwrap_or("") + .to_string(); + + Ok(content) +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_store_traced_faces.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_store_traced_faces.rs new file mode 100644 index 00000000..30c6136d --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_store_traced_faces.rs @@ -0,0 +1,921 @@ +use anyhow::{Context, Result}; +use clap::Parser; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; +use std::collections::HashMap; +use std::time::Duration; +use serde_json::{json, Value}; + +const DEFAULT_QDRANT_URL: &str = "http://localhost:6333"; +const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200"; + +#[derive(Parser)] +#[command(name = "rust_store_traced_faces", about = "Store Traced Faces (Rust)")] +struct Args { + /// File UUID + file_uuid: String, + /// Face JSON path (optional) + #[arg(long)] + face_json: Option, + /// Output directory + #[arg(long, default_value = "/Users/accusys/momentry/output")] + output_dir: PathBuf, + /// Minimum trace length + #[arg(long, default_value = "0")] + min_trace_len: usize, + /// Minimum average confidence + #[arg(long, default_value = "0.0")] + min_confidence: f32, + /// Similarity threshold for face matching + #[arg(long, default_value = "0.85")] + similarity_threshold: f64, + /// IoU threshold for bbox overlap + #[arg(long, default_value = "0.3")] + iou_threshold: f64, +} + +fn env_var(name: &str, default: &str) -> String { + std::env::var(name).unwrap_or_else(|_| default.to_string()) +} + +#[derive(Clone)] +struct FacePoint { + payload: Value, + vector: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct FaceDetection { + #[serde(skip_serializing_if = "Option::is_none")] + trace_id: Option, + // FIX: Add flat bbox fields for consistency with face.json + #[serde(default, skip_serializing_if = "Option::is_none")] + x: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + y: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + height: Option, + confidence: f32, + // FIX: Make bbox optional during deserialization, will be filled later if missing + #[serde(default)] + bbox: BBox, + #[serde(skip_serializing_if = "Option::is_none")] + embedding: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pose: Option, + #[serde(skip_serializing_if = "Option::is_none")] + landmarks: Option, + #[serde(skip_serializing_if = "Option::is_none")] + lips: Option, + #[serde(rename = "captureQuality", skip_serializing_if = "Option::is_none")] + capture_quality: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Default)] +struct BBox { + x: i32, + y: i32, + width: i32, + height: i32, + #[serde(default)] + x2: i32, + #[serde(default)] + y2: i32, + #[serde(default)] + center_x: i32, + #[serde(default)] + center_y: i32, +} + +impl BBox { + fn compute_derived(&mut self) { + self.x2 = self.x + self.width; + self.y2 = self.y + self.height; + self.center_x = self.x + self.width / 2; + self.center_y = self.y + self.height / 2; + } +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct FaceFrame { + frame: i64, + timestamp: f64, + faces: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct TraceInfo { + trace_id: i32, + #[serde(default)] + frame_count: u64, + start_frame: u64, + end_frame: u64, + #[serde(default)] + start_time: f64, + #[serde(default)] + end_time: f64, + #[serde(default)] + avg_confidence: f64, + #[serde(default)] + avg_capture_quality: f64, + #[serde(default)] + best_frame: u64, + #[serde(default)] + best_confidence: f64, + #[serde(default)] + avg_bbox: BBox, + #[serde(default)] + face_instances: Vec, + // Legacy fields (keep for backward compatibility) + #[serde(default)] + total_appearances: usize, + #[serde(default)] + path: Vec, + #[serde(default)] + frames: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct TracePoint { + frame: i64, + #[serde(default)] + timestamp: f64, + bbox: BBox, + confidence: f32, + #[serde(default)] + capture_quality: f32, + #[serde(skip_serializing_if = "Option::is_none")] + pose: Option, + #[serde(skip_serializing_if = "Option::is_none")] + landmarks: Option, +} + +#[derive(Debug, Serialize, Deserialize, Default)] +struct TraceStatsSummary { + #[serde(default)] + total_traces: usize, + #[serde(default)] + total_face_instances: usize, + #[serde(default)] + avg_trace_length: f64, +} + +#[derive(Debug, Serialize)] +struct FaceTracedData { + #[serde(default = "default_schema_version")] + schema_version: String, + fps: f64, + #[serde(default)] + file_uuid: Option, + status: String, + stats: TraceStatsSummary, + frames: Vec, + traces: Vec, +} + +fn default_schema_version() -> String { + "2.0".to_string() +} + +#[derive(Debug, Serialize, Deserialize)] +struct FaceData { + fps: f64, + frame_count: i64, + frames: Vec, +} + +/// Load existing trace_ids from face_traced.json if it exists. +/// Returns a map of (frame, face_idx) -> trace_id. +fn load_existing_trace_ids(traced_path: &std::path::Path) -> HashMap<(i64, usize), i32> { + let mut result = HashMap::new(); + + if !traced_path.exists() { + return result; + } + + let content = match std::fs::read_to_string(traced_path) { + Ok(c) => c, + Err(_) => return result, + }; + + let traced_data: serde_json::Value = match serde_json::from_str(&content) { + Ok(d) => d, + Err(_) => return result, + }; + + // Read trace_ids directly from frames array + if let Some(frames) = traced_data.get("frames").and_then(|f| f.as_array()) { + for frame in frames { + let frame_num = frame.get("frame").and_then(|f| f.as_i64()).unwrap_or(0); + if let Some(faces) = frame.get("faces").and_then(|f| f.as_array()) { + for (face_idx, face) in faces.iter().enumerate() { + if let Some(trace_id) = face.get("trace_id").and_then(|t| t.as_i64()) { + result.insert((frame_num, face_idx), trace_id as i32); + } + } + } + } + } + + result +} + +/// Check if two bboxes match within tolerance (±tolerance pixels) +fn bboxes_match(b1: &BBox, b2: &BBox, tolerance: i32) -> bool { + (b1.x - b2.x).abs() <= tolerance && + (b1.y - b2.y).abs() <= tolerance && + (b1.width - b2.width).abs() <= tolerance && + (b1.height - b2.height).abs() <= tolerance +} + +fn main() -> Result<()> { + let args = Args::parse(); + + println!("[TRACE_STORE] Processing file: {}", args.file_uuid); + + // Determine input path + let face_json_path = args.face_json.unwrap_or_else(|| { + args.output_dir.join(format!("{}.face.json", args.file_uuid)) + }); + + println!("[TRACE_STORE] Reading face.json from: {:?}", face_json_path); + + // Read face.json + let face_json_str = std::fs::read_to_string(&face_json_path) + .with_context(|| format!("Failed to read {:?}", face_json_path))?; + + let mut face_data: FaceData = serde_json::from_str(&face_json_str) + .with_context(|| "Failed to parse face.json")?; + + // FIX: Ensure all faces have bbox by constructing from flat fields if missing + for frame in &mut face_data.frames { + for face in &mut frame.faces { + if face.bbox.x == 0 && face.bbox.y == 0 && face.bbox.width == 0 && face.bbox.height == 0 { + // bbox is empty, construct from flat fields + face.bbox = BBox { + x: face.x.unwrap_or(0), + y: face.y.unwrap_or(0), + width: face.width.unwrap_or(0), + height: face.height.unwrap_or(0), + x2: 0, + y2: 0, + center_x: 0, + center_y: 0, + }; + } + // Compute derived bbox fields + face.bbox.compute_derived(); + } + } + + println!("[TRACE_STORE] Frames: {}", face_data.frames.len()); + + // Load embeddings from Qdrant + println!("[TRACE_STORE] Loading embeddings from Qdrant..."); + let qdrant_faces = load_qdrant_faces(&args.file_uuid); + + // Load existing trace_ids from face_traced.json if available + let traced_json_path = args.output_dir.join(format!("{}.face_traced.json", args.file_uuid)); + let existing_trace_ids = load_existing_trace_ids(&traced_json_path); + if !existing_trace_ids.is_empty() { + println!("[TRACE_STORE] Loaded {} existing trace_ids from face_traced.json", existing_trace_ids.len()); + } + + // Run face tracking + println!("[TRACE_STORE] Running face tracking with embedding similarity (threshold={})...", args.similarity_threshold); + let traces = run_face_tracking( + &mut face_data, + &qdrant_faces, + &existing_trace_ids, + args.min_trace_len, + args.min_confidence, + args.similarity_threshold, + args.iou_threshold, + )?; + + println!("[TRACE_STORE] Traces: {}", traces.len()); + + // Update trace_ids in Qdrant + println!("[TRACE_STORE] Updating trace_ids in Qdrant..."); + let trace_mapping: HashMap<(i64, i32, i32, i32, i32), i32> = build_trace_mapping(&face_data); + if !trace_mapping.is_empty() { + update_qdrant_trace_ids(&args.file_uuid, &trace_mapping)?; + println!("[TRACE_STORE] Updated {} trace_ids in Qdrant", trace_mapping.len()); + } else { + println!("[TRACE_STORE] No trace_ids to update"); + } + + // Convert traces to v2 format + let traces_v2: Vec = traces + .into_iter() + .map(|(_, mut t)| { + // Compute derived bbox fields + for point in &mut t.path { + let mut bbox = point.bbox.clone(); + bbox.compute_derived(); + point.bbox = bbox; + } + for point in &mut t.frames { + let mut bbox = point.bbox.clone(); + bbox.compute_derived(); + point.bbox = bbox; + } + + // Calculate stats + let frame_count = t.path.len() as u64; + let start_frame = t.path.first().map(|p| p.frame as u64).unwrap_or(0); + let end_frame = t.path.last().map(|p| p.frame as u64).unwrap_or(0); + let start_time = start_frame as f64 / face_data.fps; + let end_time = end_frame as f64 / face_data.fps; + let avg_confidence = if !t.path.is_empty() { + t.path.iter().map(|p| p.confidence as f64).sum::() / t.path.len() as f64 + } else { + 0.0 + }; + let avg_capture_quality = if !t.path.is_empty() { + t.path.iter().map(|p| p.capture_quality as f64).sum::() / t.path.len() as f64 + } else { + 0.0 + }; + let best = t.path.iter().max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap()); + let best_frame = best.map(|p| p.frame as u64).unwrap_or(0); + let best_confidence = best.map(|p| p.confidence as f64).unwrap_or(0.0); + + // Calculate average bbox + let avg_bbox = if !t.path.is_empty() { + let mut bbox = BBox::default(); + for p in &t.path { + bbox.x += p.bbox.x; + bbox.y += p.bbox.y; + bbox.width += p.bbox.width; + bbox.height += p.bbox.height; + } + let n = t.path.len() as i32; + bbox.x /= n; + bbox.y /= n; + bbox.width /= n; + bbox.height /= n; + bbox.compute_derived(); + bbox + } else { + BBox::default() + }; + + TraceInfo { + trace_id: t.trace_id, + frame_count, + start_frame, + end_frame, + start_time, + end_time, + avg_confidence, + avg_capture_quality, + best_frame, + best_confidence, + avg_bbox, + face_instances: t.path.clone(), + total_appearances: t.total_appearances, + path: t.path, + frames: t.frames, + } + }) + .collect(); + + let total_traces = traces_v2.len(); + let total_face_instances: usize = traces_v2.iter().map(|t| t.frame_count as usize).sum(); + let avg_trace_length = if total_traces > 0 { + traces_v2.iter().map(|t| t.frame_count as f64).sum::() / total_traces as f64 + } else { + 0.0 + }; + + // Create output (v2 format) + let traced_data = FaceTracedData { + schema_version: "2.0".to_string(), + fps: face_data.fps, + file_uuid: Some(args.file_uuid.clone()), + status: "completed".to_string(), + stats: TraceStatsSummary { + total_traces, + total_face_instances, + avg_trace_length, + }, + frames: face_data.frames, + traces: traces_v2, + }; + + // Write face_traced.json + let traced_json_path = args.output_dir.join(format!("{}.face_traced.json", args.file_uuid)); + println!("[TRACE_STORE] Writing face_traced.json to: {:?}", traced_json_path); + + let traced_json_str = serde_json::to_string_pretty(&traced_data) + .with_context(|| "Failed to serialize face_traced.json")?; + + std::fs::write(&traced_json_path, traced_json_str) + .with_context(|| format!("Failed to write {:?}", traced_json_path))?; + + println!("[TRACE_STORE] Done"); + + Ok(()) +} + +fn run_face_tracking( + face_data: &mut FaceData, + qdrant_faces: &[FacePoint], + existing_trace_ids: &HashMap<(i64, usize), i32>, + min_trace_len: usize, + min_confidence: f32, + similarity_threshold: f64, + iou_threshold: f64, +) -> Result> { + let mut traces: HashMap = HashMap::new(); + let mut next_trace_id = 1; + + // If we have existing trace_ids, use the max existing ID as starting point + if !existing_trace_ids.is_empty() { + next_trace_id = existing_trace_ids.values().copied().max().unwrap_or(0) + 1; + println!("[TRACE] Resuming from existing trace_ids, next_id={}", next_trace_id); + } + + // Build frame -> embedding map from Qdrant data + let mut frame_embeddings: HashMap, f32, BBox)>> = HashMap::new(); + for point in qdrant_faces { + let frame = point.payload.get("frame") + .and_then(|f| f.as_i64()) + .unwrap_or(0); + let confidence = point.payload.get("confidence") + .and_then(|c| c.as_f64()) + .unwrap_or(0.9) as f32; + + // Qdrant may store bbox in two formats: + // 1. Nested bbox field (from face_processor.py) + // 2. Direct x, y, width, height fields (from rust_store_traced_faces) + let mut bbox_struct = if let Some(bbox_obj) = point.payload.get("bbox").and_then(|b| b.as_object()) { + BBox { + x: bbox_obj.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32, + y: bbox_obj.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32, + width: bbox_obj.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32, + height: bbox_obj.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32, + x2: bbox_obj.get("x2").and_then(|x| x.as_i64()).unwrap_or(0) as i32, + y2: bbox_obj.get("y2").and_then(|y| y.as_i64()).unwrap_or(0) as i32, + center_x: bbox_obj.get("center_x").and_then(|x| x.as_i64()).unwrap_or(0) as i32, + center_y: bbox_obj.get("center_y").and_then(|y| y.as_i64()).unwrap_or(0) as i32, + } + } else { + // Direct fields + BBox { + x: point.payload.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32, + y: point.payload.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32, + width: point.payload.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32, + height: point.payload.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32, + x2: 0, + y2: 0, + center_x: 0, + center_y: 0, + } + }; + bbox_struct.compute_derived(); + + // Debug: log first few embeddings + if frame_embeddings.len() < 5 { + eprintln!("[TRACE] Qdrant point: frame={}, bbox={:?}, vector_len={}", + frame, bbox_struct, point.vector.len()); + } + + frame_embeddings + .entry(frame) + .or_insert_with(Vec::new) + .push((point.vector.clone(), confidence, bbox_struct)); + } + + eprintln!("[TRACE] Built embedding map for {} frames", frame_embeddings.len()); + + // Face matching with embedding similarity + let mut face_trace_ids: HashMap<(i64, usize), i32> = HashMap::new(); + + let frames_len = face_data.frames.len(); + + for frame_idx in 0..frames_len { + let frame = &face_data.frames[frame_idx]; + let current_frame_num = frame.frame; + + // Get embeddings for current frame + let current_embeddings = frame_embeddings.get(¤t_frame_num).cloned().unwrap_or_default(); + + for face_idx in 0..frame.faces.len() { + let current_face = &frame.faces[face_idx]; + + // First check if we have an existing trace_id for this face + if let Some(&existing_tid) = existing_trace_ids.get(&(current_frame_num, face_idx)) { + face_trace_ids.insert((current_frame_num, face_idx), existing_tid); + + let trace_key = existing_tid.to_string(); + let trace = traces.entry(trace_key).or_insert(TraceInfo { + trace_id: existing_tid, + frame_count: 0, + start_frame: 0, + end_frame: 0, + start_time: 0.0, + end_time: 0.0, + avg_confidence: 0.0, + avg_capture_quality: 0.0, + best_frame: 0, + best_confidence: 0.0, + avg_bbox: BBox::default(), + face_instances: Vec::new(), + total_appearances: 0, + path: Vec::new(), + frames: Vec::new(), + }); + trace.total_appearances += 1; + let mut bbox = current_face.bbox.clone(); + bbox.compute_derived(); + trace.path.push(TracePoint { + frame: current_frame_num, + timestamp: current_frame_num as f64 / face_data.fps, + bbox: bbox.clone(), + confidence: current_face.confidence, + capture_quality: current_face.capture_quality.unwrap_or(0.0), + pose: current_face.pose.clone(), + landmarks: current_face.landmarks.clone(), + }); + trace.frames.push(TracePoint { + frame: current_frame_num, + timestamp: current_frame_num as f64 / face_data.fps, + bbox, + confidence: current_face.confidence, + capture_quality: current_face.capture_quality.unwrap_or(0.0), + pose: current_face.pose.clone(), + landmarks: current_face.landmarks.clone(), + }); + continue; + } + + // Find matching embedding with bbox tolerance (±5px) + let current_embedding = current_embeddings.iter() + .find(|(_, _, bbox)| { + bboxes_match(bbox, ¤t_face.bbox, 5) + }) + .map(|(emb, _, _)| emb.clone()); + + if frame_idx == 0 || frame_idx % 20 == 0 { + eprintln!("[TRACE] Frame {} face {}: bbox={:?}, has_emb={}", + current_frame_num, face_idx, current_face.bbox, current_embedding.is_some()); + } + + let mut best_match: Option<(i32, f64, f64)> = None; + let mut best_iou = 0.0; + + if frame_idx > 0 { + let prev_frame = &face_data.frames[frame_idx - 1]; + + // Check previous frame (regardless of frame number difference) + for (prev_face_idx, prev_face) in prev_frame.faces.iter().enumerate() { + if let Some(&prev_trace_id) = face_trace_ids.get(&(prev_frame.frame, prev_face_idx)) { + let iou = calculate_iou(¤t_face.bbox, &prev_face.bbox); + + // Get previous embedding with bbox tolerance + let prev_embeddings = frame_embeddings.get(&prev_frame.frame).cloned().unwrap_or_default(); + let prev_embedding = prev_embeddings.iter() + .find(|(_, _, bbox)| { + bboxes_match(bbox, &prev_face.bbox, 5) + }) + .map(|(emb, _, _)| emb); + + // Calculate similarity if both embeddings exist + let similarity = match (¤t_embedding, &prev_embedding) { + (Some(curr), Some(prev)) => calculate_cosine_similarity(curr, prev), + _ => 0.0, + }; + + // Match if IoU AND similarity meet thresholds + if iou > best_iou + && iou > iou_threshold + && similarity > similarity_threshold { + best_iou = iou; + best_match = Some((prev_trace_id, iou, similarity)); + } + } + } + } + + let trace_id = if let Some((matched_trace_id, iou, sim)) = best_match { + eprintln!("[TRACE] Frame {} face {}: matched trace {} (iou={:.3}, sim={:.3})", + current_frame_num, face_idx, matched_trace_id, iou, sim); + matched_trace_id + } else { + let tid = next_trace_id; + next_trace_id += 1; + eprintln!("[TRACE] Frame {} face {}: new trace {}", current_frame_num, face_idx, tid); + tid + }; + + face_trace_ids.insert((current_frame_num, face_idx), trace_id); + + let trace_key = trace_id.to_string(); + let trace = traces.entry(trace_key).or_insert(TraceInfo { + trace_id, + frame_count: 0, + start_frame: 0, + end_frame: 0, + start_time: 0.0, + end_time: 0.0, + avg_confidence: 0.0, + avg_capture_quality: 0.0, + best_frame: 0, + best_confidence: 0.0, + avg_bbox: BBox::default(), + face_instances: Vec::new(), + total_appearances: 0, + path: Vec::new(), + frames: Vec::new(), + }); + + trace.total_appearances += 1; + let mut bbox = current_face.bbox.clone(); + bbox.compute_derived(); + let timestamp = current_frame_num as f64 / face_data.fps; + trace.path.push(TracePoint { + frame: current_frame_num, + timestamp, + bbox: bbox.clone(), + confidence: current_face.confidence, + capture_quality: current_face.capture_quality.unwrap_or(0.0), + pose: current_face.pose.clone(), + landmarks: current_face.landmarks.clone(), + }); + trace.frames.push(TracePoint { + frame: current_frame_num, + timestamp, + bbox, + confidence: current_face.confidence, + capture_quality: current_face.capture_quality.unwrap_or(0.0), + pose: current_face.pose.clone(), + landmarks: current_face.landmarks.clone(), + }); + } + } + + // Assign trace_ids to faces + for frame in &mut face_data.frames { + for (face_idx, face) in frame.faces.iter_mut().enumerate() { + if let Some(&trace_id) = face_trace_ids.get(&(frame.frame, face_idx)) { + face.trace_id = Some(trace_id); + } + } + } + + // Calculate average confidence for each trace + for trace in traces.values_mut() { + if !trace.path.is_empty() { + let sum: f64 = trace.path.iter().map(|p| p.confidence as f64).sum(); + trace.avg_confidence = sum / trace.path.len() as f64; + } + } + + // Filter traces + if min_trace_len > 0 || min_confidence > 0.0 { + traces.retain(|_, trace| { + trace.total_appearances >= min_trace_len + && (min_confidence == 0.0 || trace.avg_confidence >= min_confidence as f64) + }); + } + + Ok(traces) +} + +fn calculate_iou(bbox1: &BBox, bbox2: &BBox) -> f64 { + let x1 = std::cmp::max(bbox1.x, bbox2.x); + let y1 = std::cmp::max(bbox1.y, bbox2.y); + let x2 = std::cmp::min(bbox1.x + bbox1.width, bbox2.x + bbox2.width); + let y2 = std::cmp::min(bbox1.y + bbox1.height, bbox2.y + bbox2.height); + + if x2 < x1 || y2 < y1 { + return 0.0; + } + + let intersection = (x2 - x1) as i64 * (y2 - y1) as i64; + let area1 = bbox1.width as i64 * bbox1.height as i64; + let area2 = bbox2.width as i64 * bbox2.height as i64; + let union = area1 + area2 - intersection; + + if union == 0 { + return 0.0; + } + + intersection as f64 / union as f64 +} + +fn calculate_cosine_similarity(a: &[f64], b: &[f64]) -> f64 { + if a.len() != b.len() || a.is_empty() { + return 0.0; + } + let dot: f64 = a.iter().zip(b).map(|(x, y)| x * y).sum(); + let na: f64 = a.iter().map(|x| x * x).sum::().sqrt(); + let nb: f64 = b.iter().map(|x| x * x).sum::().sqrt(); + if na == 0.0 || nb == 0.0 { + 0.0 + } else { + dot / (na * nb) + } +} + +fn load_qdrant_faces(uuid: &str) -> Vec { + let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL); + let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY); + let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url); + + let mut all_points: Vec = Vec::new(); + let mut offset: Option = None; + + loop { + let mut body = json!({ + "limit": 10000, + "with_payload": true, + "with_vector": true, + "filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]}, + }); + if let Some(ref off) = offset { + body["offset"] = off.clone(); + } + + let resp = ureq::post(&scroll_url) + .set("api-key", &qdrant_api_key) + .timeout(Duration::from_secs(60)) + .send_json(body); + + match resp { + Ok(r) => { + let data: Value = r.into_json().unwrap_or(Value::Null); + let points = data + .pointer("/result/points") + .and_then(|p| p.as_array()) + .cloned() + .unwrap_or_default(); + + for p in points { + let payload = p.get("payload").cloned().unwrap_or(Value::Null); + let vector = p + .get("vector") + .and_then(|v| v.as_array()) + .map(|v| { + v.iter() + .filter_map(|x| x.as_f64()) + .collect::>() + }) + .unwrap_or_default(); + all_points.push(FacePoint { payload, vector }); + } + + let next = data.pointer("/result/next_page_offset").cloned(); + match next { + Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)), + Some(Value::Number(_)) => break, + Some(Value::Null) | None => break, + other => { + offset = other; + } + } + } + Err(e) => { + eprintln!("[TRACE] Qdrant scroll error: {}", e); + break; + } + } + } + + eprintln!("[TRACE] Loaded {} points from Qdrant _faces", all_points.len()); + all_points +} + +fn build_trace_mapping(face_data: &FaceData) -> HashMap<(i64, i32, i32, i32, i32), i32> { + let mut mapping = HashMap::new(); + for frame in &face_data.frames { + for face in &frame.faces { + if let Some(trace_id) = face.trace_id { + let key = (frame.frame, face.bbox.x, face.bbox.y, face.bbox.width, face.bbox.height); + mapping.insert(key, trace_id); + } + } + } + mapping +} + +fn update_qdrant_trace_ids( + file_uuid: &str, + trace_mapping: &HashMap<(i64, i32, i32, i32, i32), i32>, +) -> Result<()> { + let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL); + let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY); + + // Load all points for this file + let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url); + let mut offset: Option = None; + let mut trace_updates: HashMap> = HashMap::new(); + + loop { + let mut body = json!({ + "limit": 10000, + "with_payload": true, + "with_vector": false, + "filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}, + }); + if let Some(ref off) = offset { + body["offset"] = off.clone(); + } + + let resp = ureq::post(&scroll_url) + .set("api-key", &qdrant_api_key) + .timeout(Duration::from_secs(60)) + .send_json(body); + + match resp { + Ok(r) => { + let data: Value = r.into_json().unwrap_or(Value::Null); + let points = data + .pointer("/result/points") + .and_then(|p| p.as_array()) + .cloned() + .unwrap_or_default(); + + for point in points { + let point_id = point.get("id").cloned(); + let payload = point.get("payload").cloned().unwrap_or(Value::Null); + + let frame = payload.get("frame").and_then(|f| f.as_i64()).unwrap_or(0); + + // Support two bbox formats + let (x, y, width, height) = if let Some(bbox_obj) = payload.get("bbox").and_then(|b| b.as_object()) { + ( + bbox_obj.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32, + bbox_obj.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32, + bbox_obj.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32, + bbox_obj.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32, + ) + } else { + ( + payload.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32, + payload.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32, + payload.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32, + payload.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32, + ) + }; + + let key = (frame, x, y, width, height); + if let Some(&trace_id) = trace_mapping.get(&key) { + if let Some(id) = point_id { + trace_updates + .entry(trace_id) + .or_default() + .push(id); + } + } + } + + let next = data.pointer("/result/next_page_offset").cloned(); + match next { + Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)), + Some(Value::Number(_)) => break, + Some(Value::Null) | None => break, + other => { + offset = other; + } + } + } + Err(e) => { + eprintln!("[TRACE] Qdrant scroll error: {}", e); + break; + } + } + } + + if trace_updates.is_empty() { + return Ok(()); + } + + let update_url = format!("{}/collections/_faces/points/payload", qdrant_url); + + for (trace_id, point_ids) in trace_updates { + let body = json!({ + "payload": { + "trace_id": trace_id + }, + "points": point_ids + }); + + let resp = ureq::post(&update_url) + .set("api-key", &qdrant_api_key) + .timeout(Duration::from_secs(60)) + .send_json(body); + + if let Err(e) = resp { + eprintln!("[TRACE] Failed to update Qdrant trace_id {} for {} points: {}", trace_id, point_ids.len(), e); + } else { + println!("[TRACE] Updated trace_id {} for {} points", trace_id, point_ids.len()); + } + } + + Ok(()) +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_store_traced_faces.rs.bak3 b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_store_traced_faces.rs.bak3 new file mode 100644 index 00000000..b6cd356b --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_store_traced_faces.rs.bak3 @@ -0,0 +1,512 @@ +use anyhow::{Context, Result}; +use clap::Parser; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; +use std::collections::HashMap; +use std::time::Duration; +use serde_json::{json, Value}; + +const DEFAULT_QDRANT_URL: &str = "http://localhost:6333"; +const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200"; + +#[derive(Parser)] +#[command(name = "rust_store_traced_faces", about = "Store Traced Faces (Rust)")] +struct Args { + /// File UUID + file_uuid: String, + /// Face JSON path (optional) + #[arg(long)] + face_json: Option, + /// Output directory + #[arg(long, default_value = "/Users/accusys/momentry/output")] + output_dir: PathBuf, + /// Minimum trace length + #[arg(long, default_value = "0")] + min_trace_len: usize, + /// Minimum average confidence + #[arg(long, default_value = "0.0")] + min_confidence: f32, + /// Similarity threshold for face matching + #[arg(long, default_value = "0.85")] + similarity_threshold: f64, + /// Distance threshold (pixels) + #[arg(long, default_value = "100.0")] + distance_threshold: f64, +} + +fn env_var(name: &str, default: &str) -> String { + std::env::var(name).unwrap_or_else(|_| default.to_string()) +} + +#[derive(Clone)] +struct FacePoint { + payload: Value, + vector: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct FaceDetection { + #[serde(skip_serializing_if = "Option::is_none")] + trace_id: Option, + confidence: f32, + bbox: BBox, + #[serde(skip_serializing_if = "Option::is_none")] + embedding: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pose: Option, + #[serde(skip_serializing_if = "Option::is_none")] + landmarks: Option, + #[serde(skip_serializing_if = "Option::is_none")] + lips: Option, + #[serde(rename = "captureQuality", skip_serializing_if = "Option::is_none")] + capture_quality: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct BBox { + x: i32, + y: i32, + width: i32, + height: i32, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct FaceFrame { + frame: i64, + timestamp: f64, + faces: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct TraceInfo { + trace_id: i32, + total_appearances: usize, + avg_confidence: f32, + path: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct TracePoint { + frame: i64, + bbox: BBox, + confidence: f32, +} + +#[derive(Debug, Serialize, Deserialize)] +struct FaceData { + fps: f64, + frame_count: i64, + frames: Vec, +} + +#[derive(Debug, Serialize)] +struct FaceTracedData { + fps: f64, + frames: Vec, + traces: HashMap, +} + +fn main() -> Result<()> { + let args = Args::parse(); + + println!("[TRACE_STORE] Processing file: {}", args.file_uuid); + + // Determine input path + let face_json_path = args.face_json.unwrap_or_else(|| { + args.output_dir.join(format!("{}.face.json", args.file_uuid)) + }); + + println!("[TRACE_STORE] Reading face.json from: {:?}", face_json_path); + + // Read face.json + let face_json_str = std::fs::read_to_string(&face_json_path) + .with_context(|| format!("Failed to read {:?}", face_json_path))?; + + let mut face_data: FaceData = serde_json::from_str(&face_json_str) + .with_context(|| "Failed to parse face.json")?; + + println!("[TRACE_STORE] Frames: {}", face_data.frames.len()); + + // Run face tracking + println!("[TRACE_STORE] Loading embeddings from Qdrant..."); + let qdrant_faces = load_qdrant_faces(&args.file_uuid); + + println!("[TRACE_STORE] Running face tracking with embedding similarity (threshold={})...", args.similarity_threshold); + let traces = run_face_tracking( + &mut face_data, + &qdrant_faces, + args.min_trace_len, + args.min_confidence, + args.similarity_threshold, + args.distance_threshold, + )?; + + println!("[TRACE_STORE] Traces: {}", traces.len()); + + // Create output + let traced_data = FaceTracedData { + fps: face_data.fps, + frames: face_data.frames, + traces, + }; + + // Write face_traced.json + let traced_json_path = args.output_dir.join(format!("{}.face_traced.json", args.file_uuid)); + println!("[TRACE_STORE] Writing face_traced.json to: {:?}", traced_json_path); + + let traced_json_str = serde_json::to_string_pretty(&traced_data) + .with_context(|| "Failed to serialize face_traced.json")?; + + std::fs::write(&traced_json_path, traced_json_str) + .with_context(|| format!("Failed to write {:?}", traced_json_path))?; + + println!("[TRACE_STORE] Done"); + + Ok(()) +} + +fn run_face_tracking( + face_data: &mut FaceData, + qdrant_faces: &[FacePoint], + min_trace_len: usize, + min_confidence: f32, + similarity_threshold: f64, + distance_threshold: f64, +) -> Result> { + let mut traces: HashMap = HashMap::new(); + let mut next_trace_id = 1; + + // Build frame -> embedding map from Qdrant data + let mut frame_embeddings: HashMap, f32, BBox)>> = HashMap::new(); + for point in qdrant_faces { + let frame = point.payload.get("frame") + .and_then(|f| f.as_i64()) + .unwrap_or(0); + let confidence = point.payload.get("confidence") + .and_then(|c| c.as_f64()) + .unwrap_or(0.9) as f32; + let bbox = point.payload.get("bbox"); + let bbox_struct = if let Some(bbox_obj) = bbox { + BBox { + x: bbox_obj.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32, + y: bbox_obj.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32, + width: bbox_obj.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32, + height: bbox_obj.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32, + } + } else { + BBox { x: 0, y: 0, width: 0, height: 0 } + }; + + frame_embeddings + .entry(frame) + .or_insert_with(Vec::new) + .push((point.vector.clone(), confidence, bbox_struct)); + } + + eprintln!("[TRACE] Built embedding map for {} frames", frame_embeddings.len()); + + // Face matching with embedding similarity + let mut face_trace_ids: HashMap<(i64, usize), i32> = HashMap::new(); // (frame, face_idx) -> trace_id + + let frames_len = face_data.frames.len(); + + for frame_idx in 0..frames_len { + let frame = &face_data.frames[frame_idx]; + let current_frame_num = frame.frame; + + // Get embeddings for current frame + let current_embeddings = frame_embeddings.get(¤t_frame_num).cloned().unwrap_or_default(); + + for face_idx in 0..frame.faces.len() { + let current_face = &frame.faces[face_idx]; + + // Find matching embedding + let current_embedding = current_embeddings.iter() + .find(|(_, _, bbox)| { + bbox.x == current_face.bbox.x && + bbox.y == current_face.bbox.y && + bbox.width == current_face.bbox.width && + bbox.height == current_face.bbox.height + }) + .map(|(emb, _, _)| emb.clone()); + + let mut best_match: Option<(i32, f64, f64)> = None; // (trace_id, distance, similarity) + let mut best_distance = f64::MAX; + let mut best_similarity = 0.0; + + if frame_idx > 0 { + let prev_frame = &face_data.frames[frame_idx - 1]; + + // Check previous frame or frame - 3 + if prev_frame.frame == current_frame_num - 3 || prev_frame.frame == current_frame_num - 1 { + for (prev_face_idx, prev_face) in prev_frame.faces.iter().enumerate() { + if let Some(&prev_trace_id) = face_trace_ids.get(&(prev_frame.frame, prev_face_idx)) { + let distance = calculate_bbox_distance( + ¤t_face.bbox, + &prev_face.bbox, + ); + + // Get previous embedding + let prev_embeddings = frame_embeddings.get(&prev_frame.frame).cloned().unwrap_or_default(); + let prev_embedding = prev_embeddings.iter() + .find(|(_, _, bbox)| { + bbox.x == prev_face.bbox.x && + bbox.y == prev_face.bbox.y && + bbox.width == prev_face.bbox.width && + bbox.height == prev_face.bbox.height + }) + .map(|(emb, _, _)| emb); + + // Calculate similarity if both embeddings exist + let similarity = match (¤t_embedding, &prev_embedding) { + (Some(curr), Some(prev)) => calculate_cosine_similarity(curr, prev), + _ => 0.0, + }; + + // Match if distance AND similarity meet thresholds + if distance < best_distance + && distance < distance_threshold + && similarity > similarity_threshold { + best_distance = distance; + best_similarity = similarity; + best_match = Some((prev_trace_id, distance, similarity)); + } + } + } + } + } + + let trace_id = if let Some((matched_trace_id, _, _)) = best_match { + matched_trace_id + } else { + let tid = next_trace_id; + next_trace_id += 1; + tid + }; + + face_trace_ids.insert((current_frame_num, face_idx), trace_id); + + let trace_key = trace_id.to_string(); + let trace = traces.entry(trace_key).or_insert(TraceInfo { + trace_id, + total_appearances: 0, + avg_confidence: 0.0, + path: Vec::new(), + }); + + trace.total_appearances += 1; + trace.path.push(TracePoint { + frame: current_frame_num, + bbox: current_face.bbox.clone(), + confidence: current_face.confidence, + }); + } + } + + // Assign trace_ids to faces + for frame in &mut face_data.frames { + for (face_idx, face) in frame.faces.iter_mut().enumerate() { + if let Some(&trace_id) = face_trace_ids.get(&(frame.frame, face_idx)) { + face.trace_id = Some(trace_id); + } + } + } + + // Calculate average confidence for each trace + for trace in traces.values_mut() { + if !trace.path.is_empty() { + let sum: f32 = trace.path.iter().map(|p| p.confidence).sum(); + trace.avg_confidence = sum / trace.path.len() as f32; + } + } + + // Filter traces by min_trace_len and min_confidence + if min_trace_len > 0 || min_confidence > 0.0 { + traces.retain(|_, trace| { + trace.total_appearances >= min_trace_len + && (min_confidence == 0.0 || trace.avg_confidence >= min_confidence) + }); + } + + Ok(traces) +} + + let frames_len = face_data.frames.len(); + + for frame_idx in 0..frames_len { + let frame = &face_data.frames[frame_idx]; + let current_frame_num = frame.frame; + let current_faces = frame.faces.clone(); + + let mut face_trace_ids = Vec::new(); + + for face_idx in 0..current_faces.len() { + let current_face = ¤t_faces[face_idx]; + + let mut best_match: Option<(i32, f64)> = None; + let mut best_distance = f64::MAX; + + if frame_idx > 0 { + let prev_frame = &face_data.frames[frame_idx - 1]; + + if prev_frame.frame == current_frame_num - 3 || prev_frame.frame == current_frame_num - 1 { + for prev_face in &prev_frame.faces { + if let Some(prev_trace_id) = prev_face.trace_id { + let distance = calculate_bbox_distance( + ¤t_face.bbox, + &prev_face.bbox, + ); + + if distance < best_distance && distance < distance_threshold { + best_distance = distance; + best_match = Some((prev_trace_id, distance)); + } + } + } + } + } + + let trace_id = if let Some((matched_trace_id, _distance)) = best_match { + matched_trace_id + } else { + let tid = next_trace_id; + next_trace_id += 1; + tid + }; + + face_trace_ids.push(trace_id); + + let trace_key = trace_id.to_string(); + let trace = traces.entry(trace_key).or_insert(TraceInfo { + trace_id, + total_appearances: 0, + avg_confidence: 0.0, + path: Vec::new(), + }); + + trace.total_appearances += 1; + trace.path.push(TracePoint { + frame: current_frame_num, + bbox: current_face.bbox.clone(), + confidence: current_face.confidence, + }); + } + } + + // Assign trace_ids to faces + for frame in &mut face_data.frames { + for (face_idx, face) in frame.faces.iter_mut().enumerate() { + if let Some(&trace_id) = face_trace_ids.get(&(frame.frame, face_idx)) { + face.trace_id = Some(trace_id); + } + } + } + + for trace in traces.values_mut() { + if !trace.path.is_empty() { + let sum: f32 = trace.path.iter().map(|p| p.confidence).sum(); + trace.avg_confidence = sum / trace.path.len() as f32; + } + } + + if min_trace_len > 0 || min_confidence > 0.0 { + traces.retain(|_, trace| { + trace.total_appearances >= min_trace_len + && (min_confidence == 0.0 || trace.avg_confidence >= min_confidence) + }); + } + + Ok(traces) +} + +fn calculate_bbox_distance(bbox1: &BBox, bbox2: &BBox) -> f64 { + let cx1 = bbox1.x as f64 + bbox1.width as f64 / 2.0; + let cy1 = bbox1.y as f64 + bbox1.height as f64 / 2.0; + let cx2 = bbox2.x as f64 + bbox2.width as f64 / 2.0; + let cy2 = bbox2.y as f64 + bbox2.height as f64 / 2.0; + + ((cx1 - cx2).powi(2) + (cy1 - cy2).powi(2)).sqrt() +} + +fn calculate_cosine_similarity(a: &[f64], b: &[f64]) -> f64 { + if a.len() != b.len() || a.is_empty() { + return 0.0; + } + let dot: f64 = a.iter().zip(b).map(|(x, y)| x * y).sum(); + let na: f64 = a.iter().map(|x| x * x).sum::().sqrt(); + let nb: f64 = b.iter().map(|x| x * x).sum::().sqrt(); + if na == 0.0 || nb == 0.0 { + 0.0 + } else { + dot / (na * nb) + } +} + +/// Scroll all Qdrant `_faces` points (payload + vector) for a file via HTTP. +fn load_qdrant_faces(uuid: &str) -> Vec { + let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL); + let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY); + let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url); + + let mut all_points: Vec = Vec::new(); + let mut offset: Option = None; + + loop { + let mut body = json!({ + "limit": 10000, + "with_payload": true, + "with_vector": true, + "filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]}, + }); + if let Some(ref off) = offset { + body["offset"] = off.clone(); + } + + let resp = ureq::post(&scroll_url) + .set("api-key", &qdrant_api_key) + .timeout(Duration::from_secs(60)) + .send_json(body); + + match resp { + Ok(r) => { + let data: Value = r.into_json().unwrap_or(Value::Null); + let points = data + .pointer("/result/points") + .and_then(|p| p.as_array()) + .cloned() + .unwrap_or_default(); + + for p in points { + let payload = p.get("payload").cloned().unwrap_or(Value::Null); + let vector = p + .get("vector") + .and_then(|v| v.as_array()) + .map(|v| { + v.iter() + .filter_map(|x| x.as_f64()) + .collect::>() + }) + .unwrap_or_default(); + all_points.push(FacePoint { payload, vector }); + } + + let next = data.pointer("/result/next_page_offset").cloned(); + match next { + Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)), + Some(Value::Number(_)) => break, + Some(Value::Null) | None => break, + other => { + offset = other; + } + } + } + Err(e) => { + eprintln!("[TRACE] Qdrant scroll error: {}", e); + break; + } + } + } + + eprintln!("[TRACE] Loaded {} points from Qdrant _faces", all_points.len()); + all_points +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_vad.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_vad.rs new file mode 100644 index 00000000..34adcd37 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_vad.rs @@ -0,0 +1,140 @@ +use clap::Parser; +use anyhow::Result; +use serde_json::json; +use std::time::Instant; + +use rust_processors::vad::{SileroVad, AudioReader, SpeechSegment}; +use rust_processors::vad::segment::SegmentCollector; + +#[derive(Parser)] +#[command(name = "rust_vad")] +#[command(about = "Silero VAD ONNX (Rust implementation)")] +struct Cli { + /// Input audio file (WAV 16kHz mono) + #[arg(short, long)] + audio: String, + + /// ONNX model path + #[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")] + model: String, + + /// Speech probability threshold + #[arg(long, default_value = "0.5")] + threshold: f32, + + /// Minimum speech duration (milliseconds) + #[arg(long, default_value = "500")] + min_speech: u32, + + /// Minimum silence duration (milliseconds) + #[arg(long, default_value = "300")] + min_silence: u32, + + /// Chunk size (samples) + #[arg(long, default_value = "512")] + chunk_size: usize, + + /// Output format + #[arg(long, default_value = "json")] + format: String, +} + +fn main() -> Result<()> { + let cli = Cli::parse(); + + println!("[VAD] Loading model: {}", cli.model); + let start_load = Instant::now(); + let mut vad = SileroVad::new(&cli.model)?; + println!("[VAD] Model loaded in {:.2}s", start_load.elapsed().as_secs_f32()); + + println!("[VAD] Loading audio: {}", cli.audio); + let audio = AudioReader::from_wav(&cli.audio)?; + let samples = audio.samples(); + let sample_rate = audio.sample_rate(); + let duration = audio.duration(); + + println!("[VAD] Audio: {} samples, {} Hz, {:.2}s", + samples.len(), sample_rate, duration); + + // 檢測語音 + println!("[VAD] Detecting speech..."); + let start_detect = Instant::now(); + + let mut collector = SegmentCollector::new( + cli.threshold, + cli.min_speech, + cli.min_silence + ); + + // 分塊處理 + for i in (0..samples.len()).step_by(cli.chunk_size) { + let end = (i + cli.chunk_size).min(samples.len()); + let chunk = &samples[i..end]; + + // 如果塊太小,填充零 + let mut chunk_vec = chunk.to_vec(); + if chunk_vec.len() < cli.chunk_size { + chunk_vec.resize(cli.chunk_size, 0.0); + } + + // 檢測 + let speech_prob = vad.detect(&chunk_vec)?; + + // 時間戳 + let timestamp = i as f32 / sample_rate as f32; + + // 收集片段 + collector.process(timestamp, speech_prob); + } + + // 結束處理 + let end_timestamp = samples.len() as f32 / sample_rate as f32; + collector.finalize(end_timestamp); + + let segments = collector.segments(); + let detect_time = start_detect.elapsed().as_secs_f32(); + + println!("[VAD] Detection completed in {:.2}s", detect_time); + println!("[VAD] Found {} speech segments", segments.len()); + + // 計算統計 + let total_speech: f32 = segments.iter().map(|s| s.duration()).sum(); + let speech_ratio = total_speech / duration; + + println!("[VAD] Total speech: {:.2}s ({:.1}%)", total_speech, speech_ratio * 100.0); + println!("[VAD] Processing speed: {:.2}x real-time", duration / detect_time); + + // 輸出結果 + match cli.format.as_str() { + "json" => { + let output = json!({ + "audio_file": cli.audio, + "sample_rate": sample_rate, + "duration": duration, + "segments": segments.iter().map(|s| json!({ + "start": s.start_sec, + "end": s.end_sec, + "duration": s.duration() + })).collect::>(), + "statistics": { + "segment_count": segments.len(), + "total_speech": total_speech, + "speech_ratio": speech_ratio, + "detect_time": detect_time + } + }); + println!("{}", serde_json::to_string_pretty(&output)?); + } + "text" => { + for seg in segments { + println!("{:.2} - {:.2} ({:.2}s)", + seg.start_sec, seg.end_sec, seg.duration()); + } + } + _ => { + anyhow::bail!("Unknown output format: {}", cli.format); + } + } + + Ok(()) +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_whisper_rs.rs b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_whisper_rs.rs new file mode 100644 index 00000000..57735a84 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/bin/rust_whisper_rs.rs @@ -0,0 +1,132 @@ +use clap::Parser; +use anyhow::{Context, Result}; +use serde_json::json; +use std::time::Instant; + +use whisper_rs::{WhisperContext, WhisperContextParameters, FullParams, SamplingStrategy}; + +#[derive(Parser)] +#[command(name = "rust_whisper_rs")] +#[command(about = "Whisper ASR using whisper-rs (whisper.cpp bindings)")] +struct Cli { + /// Input audio file (WAV 16kHz mono) + #[arg(short, long)] + input: String, + + /// Output JSON file + #[arg(short, long)] + output: Option, + + /// Whisper model path + #[arg(long, default_value = "/Users/accusys/models/ggml-tiny.bin")] + model: String, + + /// Language (auto-detect if not specified) + #[arg(short, long)] + language: Option, + + /// Number of threads + #[arg(long, default_value = "4")] + threads: i32, +} + +#[derive(Debug, Clone)] +struct Segment { + start: f64, + end: f64, + text: String, +} + +fn main() -> Result<()> { + let cli = Cli::parse(); + + println!("[Whisper-RS] Starting..."); + let start_total = Instant::now(); + + // Step 1: Load model + println!("[1/3] Loading model: {}", cli.model); + let load_start = Instant::now(); + + let mut params = WhisperContextParameters::default(); + params.use_gpu = true; + + let ctx = WhisperContext::new_with_params(&cli.model, params) + .context("Failed to load Whisper model")?; + + println!("[Whisper-RS] Model loaded in {:.2}s", load_start.elapsed().as_secs_f32()); + + // Step 2: Load audio + println!("[2/3] Loading audio: {}", cli.input); + let audio_start = Instant::now(); + + let audio = hound::WavReader::open(&cli.input) + .context("Failed to read WAV file")?; + let samples: Vec = audio.into_samples::() + .filter_map(|s| s.ok()) + .map(|s| s as f32 / 32768.0) + .collect(); + + println!("[Whisper-RS] Audio loaded: {} samples", samples.len()); + println!("[Whisper-RS] Audio load time: {:.2}s", audio_start.elapsed().as_secs_f32()); + + // Step 3: Transcribe + println!("[3/3] Transcribing..."); + let transcribe_start = Instant::now(); + + let mut state = ctx.create_state() + .context("Failed to create Whisper state")?; + + let mut full_params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 }); + full_params.set_n_threads(cli.threads); + + if let Some(ref lang) = cli.language { + full_params.set_language(Some(lang)); + } + + state.full(full_params, &samples) + .context("Failed to transcribe audio")?; + + // Extract segments + let num_segments = state.full_n_segments(); + let mut segments: Vec = Vec::new(); + + for i in 0..num_segments { + let seg = state.get_segment(i).expect("Failed to get segment"); + segments.push(Segment { + start: seg.start_timestamp() as f64 / 100.0, + end: seg.end_timestamp() as f64 / 100.0, + text: seg.to_str().unwrap_or("").to_string(), + }); + } + + let transcribe_time = transcribe_start.elapsed().as_secs_f32(); + println!("[Whisper-RS] Transcribed {} segments in {:.2}s", segments.len(), transcribe_time); + + // Output + let output = json!({ + "processor": "whisper-rs", + "model": cli.model, + "segments": segments.iter().enumerate().map(|(i, seg)| json!({ + "id": i, + "start": seg.start, + "end": seg.end, + "text": seg.text, + })).collect::>(), + "processing_time": { + "load": load_start.elapsed().as_secs_f64(), + "transcribe": transcribe_time as f64, + "total": start_total.elapsed().as_secs_f64() + } + }); + + if let Some(ref output_path) = cli.output { + std::fs::write(output_path, serde_json::to_string_pretty(&output)?)?; + println!("[Whisper-RS] Output: {}", output_path); + } else { + println!("{}", serde_json::to_string_pretty(&output)?); + } + + println!("[Whisper-RS] Done in {:.2}s", start_total.elapsed().as_secs_f32()); + + Ok(()) +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/rust/src/face_processor/crop.rs b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/crop.rs new file mode 100644 index 00000000..48318281 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/crop.rs @@ -0,0 +1,38 @@ +use anyhow::{Context, Result}; +use image::{RgbImage, ImageBuffer, imageops}; +use crate::face_processor::BBox; + +pub struct FaceCropper; + +impl FaceCropper { + pub fn new() -> Self { + Self + } + + pub fn crop(&self, frame: &RgbImage, bbox: &BBox) -> Result { + let width = frame.width() as i32; + let height = frame.height() as i32; + + // Clamp bbox to frame boundaries + let x = bbox.x.max(0).min(width - 1) as u32; + let y = bbox.y.max(0).min(height - 1) as u32; + let w = bbox.width.max(1).min(width - x as i32) as u32; + let h = bbox.height.max(1).min(height - y as i32) as u32; + + // Crop face + let cropped = imageops::crop(frame, x, y, w, h).to_image(); + + Ok(cropped) + } + + pub fn resize_to_160(&self, face: &RgbImage) -> Result { + let resized = imageops::resize( + face, + 160, + 160, + imageops::FilterType::Lanczos3, + ); + + Ok(resized) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/face_processor/detection.rs b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/detection.rs new file mode 100644 index 00000000..91d68c47 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/detection.rs @@ -0,0 +1,115 @@ +use anyhow::{Context, Result}; +use std::path::Path; +use std::process::Command; +use serde::Deserialize; +use crate::face_processor::FaceDetection; + +#[derive(Debug, Deserialize)] +struct SwiftDetection { + frames: Vec, +} + +#[derive(Debug, Deserialize)] +struct SwiftFrame { + frame: usize, + timestamp: f64, + faces: Vec, +} + +#[derive(Debug, Deserialize)] +struct SwiftFace { + bbox: SwiftBBox, + confidence: f64, + #[serde(rename = "captureQuality")] + capture_quality: Option, + pose: Option, +} + +#[derive(Debug, Deserialize)] +struct SwiftBBox { + x: i32, + y: i32, + width: i32, + height: i32, +} + +#[derive(Debug, Deserialize)] +struct SwiftPose { + roll: f64, + yaw: f64, + pitch: f64, +} + +pub struct FaceDetector { + swift_binary: String, +} + +impl FaceDetector { + pub fn new() -> Result { + let swift_binary = Self::find_swift_binary()?; + Ok(Self { swift_binary }) + } + + fn find_swift_binary() -> Result { + // Try release build first + let release = "scripts/swift_processors/.build/release/swift_face"; + if Path::new(release).exists() { + return Ok(release.to_string()); + } + + // Try debug build + let debug = "scripts/swift_processors/.build/debug/swift_face"; + if Path::new(debug).exists() { + return Ok(debug.to_string()); + } + + anyhow::bail!("Swift face binary not found") + } + + pub fn detect(&self, video_path: &Path, output_path: &Path, sample_interval: usize) -> Result> { + println!("[DETECTION] Running Swift face detection..."); + + let output = Command::new(&self.swift_binary) + .arg(video_path) + .arg(output_path) + .arg("--sample-interval") + .arg(sample_interval.to_string()) + .output() + .context("Failed to run Swift face detection")?; + + if !output.status.success() { + anyhow::bail!("Swift face detection failed: {:?}", output.stderr); + } + + // Parse output JSON + let detection: SwiftDetection = serde_json::from_slice(&output.stdout) + .context("Failed to parse Swift detection output")?; + + // Convert to our format + let faces: Vec = detection.frames.into_iter().flat_map(|frame| { + frame.faces.into_iter().map(|face| { + FaceDetection { + frame: frame.frame, + timestamp: frame.timestamp, + bbox: crate::face_processor::BBox { + x: face.bbox.x, + y: face.bbox.y, + width: face.bbox.width, + height: face.bbox.height, + }, + confidence: face.confidence, + capture_quality: face.capture_quality, + pose: face.pose.map(|p| crate::face_processor::PoseInfo { + roll: p.roll, + yaw: p.yaw, + pitch: p.pitch, + }), + } + }).collect::>() + }).collect(); + + println!("[DETECTION] Found {} faces", faces.len()); + + Ok(faces) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/face_processor/embedding.rs b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/embedding.rs new file mode 100644 index 00000000..f4063d61 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/embedding.rs @@ -0,0 +1,66 @@ +use anyhow::{Context, Result}; +use image::{RgbImage, imageops}; +use ndarray::IxDyn; +use ort::{session::Session, value::Value}; +use std::path::Path; + +pub struct EmbeddingExtractor { + session: Session, +} + +impl EmbeddingExtractor { + pub fn new(model_path: &Path) -> Result { + println!("[EMBEDDING] Loading model: {:?}", model_path); + + let session = Session::builder() + .context("Failed to create session builder")? + .commit_from_file(model_path) + .context("Failed to load model")?; + + println!("[EMBEDDING] Model loaded successfully"); + + Ok(Self { session }) + } + + pub fn extract(&mut self, face: &RgbImage) -> Result> { + // Preprocess: resize to 160x160 and normalize to [-1, 1] + let resized = imageops::resize( + face, + 160, + 160, + imageops::FilterType::Lanczos3, + ); + + // Convert to normalized tensor + let mut input_array = ndarray::Array::from_shape_vec( + IxDyn(&[1, 3, 160, 160]), + vec![0.0f32; 1 * 3 * 160 * 160] + ).context("Failed to create input array")?; + + for (x, y, pixel) in resized.enumerate_pixels() { + let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32); + input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0; + input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0; + input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0; + } + + // Create input value + let input_value = Value::from_array(input_array) + .context("Failed to create input value")?; + + let inputs = ort::inputs!["input" => input_value]; + + // Run inference + let outputs = self.session.run(inputs) + .context("Failed to run inference")?; + + // Extract output + let output = outputs["output"].try_extract_tensor::() + .context("Failed to extract output tensor")?; + + let output_data = output.1; + let embedding = output_data.to_vec(); + + Ok(embedding) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/face_processor/mod.rs b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/mod.rs new file mode 100644 index 00000000..f53c43f3 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/mod.rs @@ -0,0 +1,11 @@ +pub mod types; +pub mod video; +pub mod detection; +pub mod crop; +pub mod embedding; + +pub use types::*; +pub use video::VideoReader; +pub use detection::FaceDetector; +pub use crop::FaceCropper; +pub use embedding::EmbeddingExtractor; diff --git a/installer/build/MomentryCore/tools/cli/rust/src/face_processor/types.rs b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/types.rs new file mode 100644 index 00000000..9461fdde --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/types.rs @@ -0,0 +1,78 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BBox { + pub x: i32, + pub y: i32, + pub width: i32, + pub height: i32, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FaceDetection { + pub frame: usize, + pub timestamp: f64, + pub bbox: BBox, + pub confidence: f64, + pub capture_quality: Option, + pub pose: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PoseInfo { + pub roll: f64, + pub yaw: f64, + pub pitch: f64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FaceEmbedding { + pub frame: usize, + pub trace_id: usize, + pub bbox: BBox, + pub confidence: f64, + pub embedding: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FaceOutput { + pub status: String, + pub frame_count: usize, + pub fps: f64, + pub frames: Vec, + pub total_faces: usize, + pub metadata: Metadata, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FrameData { + pub frame: usize, + pub timestamp: f64, + pub faces: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FaceInfo { + pub x: i32, + pub y: i32, + pub width: i32, + pub height: i32, + pub confidence: f64, + pub capture_quality: Option, + pub pose_angle: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PoseAngle { + pub angle: String, + pub roll: f64, + pub yaw: f64, + pub pitch: f64, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Metadata { + pub embedding_method: String, + pub embedding_model: String, + pub total_embeddings: usize, +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/face_processor/video.rs b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/video.rs new file mode 100644 index 00000000..249abd06 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/face_processor/video.rs @@ -0,0 +1,109 @@ +use anyhow::{Context, Result}; +use ffmpeg_next as ffmpeg; +use image::{RgbImage, ImageBuffer}; +use std::path::Path; + +pub struct VideoReader { + decoder: ffmpeg::decoder::Video, + scaler: ffmpeg::software::scaling::Context, + frame_count: usize, + fps: f64, + width: u32, + height: u32, +} + +impl VideoReader { + pub fn new(video_path: &Path) -> Result { + ffmpeg::init().context("Failed to initialize FFmpeg")?; + + let input = ffmpeg::format::input(video_path) + .context("Failed to open video file")?; + + let video_stream = input + .streams() + .best(ffmpeg::media::Type::Video) + .context("No video stream found")?; + + let stream_index = video_stream.index(); + let fps = video_stream.avg_frame_rate().numerator() as f64 + / video_stream.avg_frame_rate().denominator() as f64; + let frame_count = video_stream.frames() as usize; + + let context_decoder = ffmpeg::codec::context::Context::from_parameters( + video_stream.parameters() + )?; + + let decoder = context_decoder + .decoder() + .video() + .context("Failed to get video decoder")?; + + let width = decoder.width(); + let height = decoder.height(); + + let scaler = ffmpeg::software::scaling::Context::get( + decoder.format(), + width, + height, + ffmpeg::format::pixel::Pixel::RGB24, + width, + height, + ffmpeg::software::scaling::Flags::BILINEAR, + )?; + + Ok(Self { + decoder, + scaler, + frame_count, + fps, + width, + height, + }) + } + + pub fn fps(&self) -> f64 { + self.fps + } + + pub fn frame_count(&self) -> usize { + self.frame_count + } + + pub fn width(&self) -> u32 { + self.width + } + + pub fn height(&self) -> u32 { + self.height + } + + pub fn read_frame(&mut self, frame_num: usize) -> Result> { + // Seek to frame + let seek_time = frame_num as f64 / self.fps; + self.decoder.set_position(seek_time as i64)?; + + // Read and decode frame + let mut frame = ffmpeg::util::frame::Video::empty(); + let mut rgb_frame = ffmpeg::util::frame::Video::empty(); + + self.decoder.receive_frame(&mut frame)?; + self.scaler.run(&frame, &mut rgb_frame)?; + + // Convert to image::RgbImage + let data = rgb_frame.data(0); + let linesize = rgb_frame.stride(0); + + let mut img_data = Vec::with_capacity((self.width * self.height * 3) as usize); + + for y in 0..self.height { + let offset = (y * linesize) as usize; + let row = &data[offset..offset + (self.width * 3) as usize]; + img_data.extend_from_slice(row); + } + + let img = ImageBuffer::from_raw(self.width, self.height, img_data) + .context("Failed to create image buffer")?; + + Ok(Some(img)) + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/lib.rs b/installer/build/MomentryCore/tools/cli/rust/src/lib.rs new file mode 100644 index 00000000..e9217a18 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/lib.rs @@ -0,0 +1,2 @@ +pub mod asrx; +pub mod vad; diff --git a/installer/build/MomentryCore/tools/cli/rust/src/vad/audio.rs b/installer/build/MomentryCore/tools/cli/rust/src/vad/audio.rs new file mode 100644 index 00000000..a57cff6e --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/vad/audio.rs @@ -0,0 +1,39 @@ +use anyhow::{Context, Result}; +use hound::WavReader; + +pub struct AudioReader { + samples: Vec, + sample_rate: u32, +} + +impl AudioReader { + pub fn from_wav(path: &str) -> Result { + let reader = WavReader::open(path).context("Failed to open WAV file")?; + + let spec = reader.spec(); + let sample_rate = spec.sample_rate; + + // 轉換為 f32,範圍 [-1.0, 1.0] + let samples: Vec = reader + .into_samples::() + .map(|s| s.map(|v| v as f32 / 32768.0).unwrap_or(0.0)) + .collect(); + + Ok(Self { + samples, + sample_rate, + }) + } + + pub fn samples(&self) -> &[f32] { + &self.samples + } + + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + pub fn duration(&self) -> f32 { + self.samples.len() as f32 / self.sample_rate as f32 + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/vad/mod.rs b/installer/build/MomentryCore/tools/cli/rust/src/vad/mod.rs new file mode 100644 index 00000000..1ff7df9a --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/vad/mod.rs @@ -0,0 +1,7 @@ +pub mod audio; +pub mod onnx; +pub mod segment; + +pub use audio::AudioReader; +pub use onnx::SileroVad; +pub use segment::SpeechSegment; diff --git a/installer/build/MomentryCore/tools/cli/rust/src/vad/onnx.rs b/installer/build/MomentryCore/tools/cli/rust/src/vad/onnx.rs new file mode 100644 index 00000000..e215b7ab --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/vad/onnx.rs @@ -0,0 +1,101 @@ +use anyhow::{Context, Result}; +use ndarray::IxDyn; +use ort::session::{builder::GraphOptimizationLevel, Session}; +use ort::value::Value; + +pub struct SileroVad { + session: Session, + state: Vec, // [2, 1, 128] = 256 elements + context: Vec, // [1, 64] for 16kHz + sample_rate: i64, + context_size: usize, // 64 for 16kHz, 32 for 8kHz +} + +impl SileroVad { + pub fn new(model_path: &str) -> Result { + let session = Session::builder()? + .with_optimization_level(GraphOptimizationLevel::Level1) + .map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))? + .commit_from_file(model_path) + .map_err(|e| anyhow::anyhow!("Failed to load model: {}", e))?; + + let sample_rate = 16000; + let context_size = if sample_rate == 16000 { 64 } else { 32 }; + + Ok(Self { + session, + state: vec![0.0; 256], // [2, 1, 128] = 256 + context: vec![0.0; context_size], // [1, 64] + sample_rate, + context_size, + }) + } + + pub fn detect(&mut self, audio_chunk: &[f32]) -> Result { + // 拼接 context 和當前塊 + let mut input_with_context = Vec::with_capacity(self.context_size + audio_chunk.len()); + input_with_context.extend_from_slice(&self.context); + input_with_context.extend_from_slice(audio_chunk); + + // 準備輸入 + let input_array = ndarray::Array::from_shape_vec( + IxDyn(&[1, input_with_context.len()]), + input_with_context.clone(), + ) + .context("Failed to create input array")?; + + let state_array = ndarray::Array::from_shape_vec(IxDyn(&[2, 1, 128]), self.state.clone()) + .context("Failed to create state array")?; + + let sr_array = ndarray::Array::from_shape_vec( + IxDyn(&[]), // 標量 + vec![self.sample_rate], + ) + .context("Failed to create sr array")?; + + // 創建 ONNX Value + let input_value = Value::from_array(input_array).context("Failed to create input value")?; + let state_value = Value::from_array(state_array).context("Failed to create state value")?; + let sr_value = Value::from_array(sr_array).context("Failed to create sr value")?; + + // 運行推理 + let inputs = ort::inputs![ + "input" => input_value, + "state" => state_value, + "sr" => sr_value, + ]; + + let outputs = self + .session + .run(inputs) + .context("Failed to run inference")?; + + // 提取輸出 + let output = outputs["output"] + .try_extract_tensor::() + .context("Failed to extract output")?; + + // output 是 (&Shape, &[f32]) tuple + let output_data = output.1; + let speech_prob = output_data[0]; + + // 更新隱藏狀態 + let state_n = outputs["stateN"] + .try_extract_tensor::() + .context("Failed to extract stateN")?; + + // state_n 是 (&Shape, &[f32]) tuple + let state_data = state_n.1; + self.state = state_data.to_vec(); + + // 更新 context(當前輸入的最後 context_size 個樣本) + self.context = input_with_context[input_with_context.len() - self.context_size..].to_vec(); + + Ok(speech_prob) + } + + pub fn reset_state(&mut self) { + self.state = vec![0.0; 256]; + self.context = vec![0.0; self.context_size]; + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/src/vad/segment.rs b/installer/build/MomentryCore/tools/cli/rust/src/vad/segment.rs new file mode 100644 index 00000000..6bf74094 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/src/vad/segment.rs @@ -0,0 +1,86 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SpeechSegment { + pub start_sec: f32, + pub end_sec: f32, +} + +impl SpeechSegment { + pub fn new(start_sec: f32, end_sec: f32) -> Self { + Self { start_sec, end_sec } + } + + pub fn duration(&self) -> f32 { + self.end_sec - self.start_sec + } +} + +pub struct SegmentCollector { + segments: Vec, + current_start: Option, + threshold: f32, + min_speech_duration: f32, + min_silence_duration: f32, + silence_start: Option, +} + +impl SegmentCollector { + pub fn new(threshold: f32, min_speech_ms: u32, min_silence_ms: u32) -> Self { + Self { + segments: Vec::new(), + current_start: None, + threshold, + min_speech_duration: min_speech_ms as f32 / 1000.0, + min_silence_duration: min_silence_ms as f32 / 1000.0, + silence_start: None, + } + } + + pub fn process(&mut self, timestamp: f32, speech_prob: f32) { + if speech_prob >= self.threshold { + // 語音 + if self.current_start.is_none() { + self.current_start = Some(timestamp); + } + self.silence_start = None; + } else { + // 靜音 + if self.current_start.is_some() { + if self.silence_start.is_none() { + self.silence_start = Some(timestamp); + } + + // 檢查是否結束語音段 + if let Some(silence_start) = self.silence_start { + let silence_duration = timestamp - silence_start; + if silence_duration >= self.min_silence_duration { + // 結束語音段 + if let Some(start) = self.current_start { + let duration = silence_start - start; + if duration >= self.min_speech_duration { + self.segments.push(SpeechSegment::new(start, silence_start)); + } + } + self.current_start = None; + self.silence_start = None; + } + } + } + } + } + + pub fn finalize(&mut self, end_timestamp: f32) { + // 處理最後一個段 + if let Some(start) = self.current_start { + let duration = end_timestamp - start; + if duration >= self.min_speech_duration { + self.segments.push(SpeechSegment::new(start, end_timestamp)); + } + } + } + + pub fn segments(&self) -> &[SpeechSegment] { + &self.segments + } +} diff --git a/installer/build/MomentryCore/tools/cli/rust/test_features.txt b/installer/build/MomentryCore/tools/cli/rust/test_features.txt new file mode 100644 index 00000000..cf3fe891 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/rust/test_features.txt @@ -0,0 +1,5 @@ +可能的 features: +- coreml +- load-dynamic +- download-binaries +- tracing diff --git a/installer/build/MomentryCore/tools/cli/swift/Package.resolved b/installer/build/MomentryCore/tools/cli/swift/Package.resolved new file mode 100644 index 00000000..6a2bc8e1 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "swift-argument-parser", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-argument-parser.git", + "state" : { + "revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382", + "version" : "1.8.2" + } + } + ], + "version" : 2 +} diff --git a/installer/build/MomentryCore/tools/cli/swift/Package.swift b/installer/build/MomentryCore/tools/cli/swift/Package.swift new file mode 100644 index 00000000..04ecf6c9 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/Package.swift @@ -0,0 +1,35 @@ +// swift-tools-version:5.9 +import PackageDescription + +let package = Package( + name: "swift_processors", + platforms: [.macOS(.v12)], + products: [ + .executable(name: "swift_scene_detector", targets: ["swift_scene_detector"]), + .executable(name: "swift_face", targets: ["swift_face"]), + .executable(name: "swift_ocr", targets: ["swift_ocr"]), + ], + dependencies: [ + .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.0"), + ], + targets: [ + .executableTarget( + name: "swift_scene_detector", + path: "Sources/swift_scene_detector" + ), + .executableTarget( + name: "swift_face", + dependencies: [ + .product(name: "ArgumentParser", package: "swift-argument-parser"), + ], + path: "Sources/swift_face" + ), + .executableTarget( + name: "swift_ocr", + dependencies: [ + .product(name: "ArgumentParser", package: "swift-argument-parser"), + ], + path: "Sources/swift_ocr" + ), + ] +) diff --git a/installer/build/MomentryCore/tools/cli/swift/Sources/swift_face/main.swift b/installer/build/MomentryCore/tools/cli/swift/Sources/swift_face/main.swift new file mode 100644 index 00000000..552a565d --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/Sources/swift_face/main.swift @@ -0,0 +1,423 @@ +import Foundation +import Vision +import ArgumentParser +import AVFoundation + +/// Calculate capture quality based on face size and confidence +/// Returns a score between 0.0 and 1.0 +func calculateFallbackCaptureQuality( + faceWidth: Int, + faceHeight: Int, + imageWidth: Int, + imageHeight: Int, + confidence: Double +) -> Double { + // Face size relative to image (larger faces = better quality) + let faceArea = Double(faceWidth * faceHeight) + let imageArea = Double(imageWidth * imageHeight) + let relativeSize = min(1.0, faceArea / (imageArea * 0.25)) // Normalize to max 25% of image + + // Combine confidence and size (50% weight each) + let quality = (confidence * 0.5) + (relativeSize * 0.5) + + return min(1.0, max(0.0, quality)) +} + +/// Swift Face Processor - Apple Vision Framework for face detection + pose +/// Uses AVAssetImageGenerator for reliable frame access (no AVAssetReader corruption). +@main +struct SwiftFace: ParsableCommand { + @Argument(help: "Video file path") + var inputPath: String + + @Argument(help: "Output JSON path") + var outputPath: String + + @Option(name: .long, help: "Sample interval (frames, default=3)") + var sampleInterval: Int = 3 + + @Option(name: .long, help: "UUID for logging") + var uuid: String = "" + + mutating func run() throws { + let startTime = Date() + print("[SwiftFace] Vision-based face detection: \(inputPath)") + + let url = URL(fileURLWithPath: inputPath) + let asset = AVAsset(url: url) + + guard let videoTrack = asset.tracks(withMediaType: .video).first else { + print("[SwiftFace] No video track found") + return + } + + let fps = videoTrack.nominalFrameRate + let duration = CMTimeGetSeconds(asset.duration) + let totalFrames = Int(duration * Double(fps)) + let width = Int(videoTrack.naturalSize.width) + let height = Int(videoTrack.naturalSize.height) + print("[SwiftFace] Video: \(width)x\(height), \(String(format: "%.1f", fps))fps, \(totalFrames) frames") + + // Read face detection settings from environment variables (with defaults) + // Keep in sync with src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT + let MIN_CONFIDENCE = Double(ProcessInfo.processInfo.environment["FACE_MIN_CONFIDENCE"] ?? "0.5") ?? 0.5 + let MIN_SIZE = Int(ProcessInfo.processInfo.environment["FACE_MIN_SIZE"] ?? "1") ?? 1 + print("[SwiftFace] Settings: MIN_CONFIDENCE=\(MIN_CONFIDENCE), MIN_SIZE=\(MIN_SIZE)") + + let generator = AVAssetImageGenerator(asset: asset) + generator.requestedTimeToleranceBefore = .zero + generator.requestedTimeToleranceAfter = .zero + generator.appliesPreferredTrackTransform = true + + var allFrames: [[String: Any]] = [] + var processedCount = 0 + var checkedCount = 0 + + let frameInterval = TimeInterval(sampleInterval) / Double(fps) + + // Process in batches of 1000 frames to avoid memory pressure + let batchSize = 1000 + let totalSamples = totalFrames / sampleInterval + + for batchStart in stride(from: 0, to: totalSamples, by: batchSize) { + let batchEnd = min(batchStart + batchSize, totalSamples) + var times: [NSValue] = [] + + for i in batchStart.. bestOverlap { + bestOverlap = overlap + if let cq = cqObs.faceCaptureQuality { + captureQ = Double(cq) + } + } + } + + // Fallback: Calculate quality from size, confidence, pose if API didn't provide it + if captureQ == 0.0 { + let faceArea = Double(faceW * faceH) + let imgArea = Double(imgW * imgH) + let sizeScore = min(1.0, (faceArea / imgArea) * 4.0) // Normalize, larger = better + let confScore = lmConf // Already 0-1 + + // Pose score (frontal = 1.0, profile = 0.0) + var poseScore = 1.0 + if let yaw = lmObs.yaw?.doubleValue { + poseScore = max(0.0, 1.0 - abs(yaw) / 90.0) + } + + // Weighted combination + captureQ = sizeScore * 0.3 + confScore * 0.4 + poseScore * 0.3 + } + + // Match face observation by bbox to extract faceprint (embedding) + var embedding: [Float]? = nil + if #available(macOS 14, *) { + var matchCount = 0 + for faceObs in faceObservations { + let fBB = faceObs.boundingBox + let ix = max(bb.minX, fBB.origin.x) + let iy = max(bb.minY, fBB.origin.y) + let iw = min(bb.maxX, fBB.origin.x + fBB.width) - ix + let ih = min(bb.maxY, fBB.origin.y + fBB.height) - iy + if iw <= 0 || ih <= 0 { continue } + let intersection = iw * ih + let union = bb.width * bb.height + fBB.width * fBB.height - intersection + if intersection / union > 0.5 { + matchCount += 1 + // Try to extract faceprint + if let fp = faceObs.value(forKey: "faceprint") as? NSObject { + if let desc = fp.value(forKey: "descriptor") as? NSObject { + if let elems = desc.value(forKey: "elements") as? [NSNumber] { + embedding = elems.map { Float($0.doubleValue) } + } else { + print("[DEBUG] No elements in descriptor") + } + } else { + print("[DEBUG] No descriptor in faceprint") + } + } else { + print("[DEBUG] No faceprint in faceObs (frame \(frameNumber), match \(matchCount))") + } + break + } + } + } + + var faceData: [String: Any] = [ + "bbox": ["x": max(0, faceX), "y": max(0, faceY), + "width": faceW, "height": faceH], + "confidence": Double(lmObs.confidence), + "captureQuality": captureQ, + ] + + // Add embedding if available + if let emb = embedding { + faceData["embedding"] = emb + } + + // Pose from landmark observation + if let yaw = lmObs.yaw?.doubleValue, + let roll = lmObs.roll?.doubleValue { + var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw] + if let pitch = lmObs.pitch?.doubleValue { + poseInfo["pitch"] = pitch + } + faceData["pose"] = poseInfo + } + + // Landmarks with Y-flip (macOS image coords: bottom-left -> top-left) + if let lms = lmObs.landmarks { + let imgSize = CGSize(width: imgW, height: imgH) + let leftEye = lms.leftEye?.pointsInImage(imageSize: imgSize) ?? [] + let rightEye = lms.rightEye?.pointsInImage(imageSize: imgSize) ?? [] + let nose = lms.nose?.pointsInImage(imageSize: imgSize) ?? [] + + if !leftEye.isEmpty || !rightEye.isEmpty || !nose.isEmpty { + var lm: [String: [[Double]]] = [:] + if !leftEye.isEmpty { + lm["left_eye"] = leftEye.map { [Double($0.x), Double(imgH - $0.y)] } + } + if !rightEye.isEmpty { + lm["right_eye"] = rightEye.map { [Double($0.x), Double(imgH - $0.y)] } + } + if !nose.isEmpty { + lm["nose"] = nose.map { [Double($0.x), Double(imgH - $0.y)] } + } + faceData["landmarks"] = lm + } + + let outer = lms.outerLips?.pointsInImage(imageSize: imgSize) ?? [] + let inner = lms.innerLips?.pointsInImage(imageSize: imgSize) ?? [] + if !outer.isEmpty || !inner.isEmpty { + faceData["lips"] = [ + "outer_lips": outer.map { [Double($0.x), Double(imgH - $0.y)] }, + "inner_lips": inner.map { [Double($0.x), Double(imgH - $0.y)] } + ] + } + } + + frameFaces.append(faceData) + } + + // Output face rect observations that the landmark detector missed. + // Match against ALL landmark observations via IoU to avoid duplicates. + for faceObs in faceObservations { + let fBB = faceObs.boundingBox + var matched = false + for lmObs in landmarkObservations { + let lBB = lmObs.boundingBox + let ix = max(fBB.origin.x, lBB.origin.x) + let iy = max(fBB.origin.y, lBB.origin.y) + let iw = min(fBB.maxX, lBB.maxX) - ix + let ih = min(fBB.maxY, lBB.maxY) - iy + if iw <= 0 || ih <= 0 { continue } + let intersection = iw * ih + let union = fBB.width * fBB.height + lBB.width * lBB.height - intersection + if intersection / union > 0.3 { + matched = true + break + } + } + if matched { continue } + + // Quality filtering for unmatched face rects + + if Double(faceObs.confidence) < MIN_CONFIDENCE { continue } + + let faceW = Int(fBB.size.width * imgW) + let faceH = Int(fBB.size.height * imgH) + if faceW < MIN_SIZE || faceH < MIN_SIZE { continue } + + // Unmatched face rect: output without landmarks + let faceX = Int(fBB.origin.x * imgW) + let faceY = Int((1.0 - fBB.origin.y - fBB.size.height) * imgH) + + // Match capture quality request by bbox overlap + var captureQ = 0.0 + var bestOverlap: CGFloat = 0 + for cqObs in captureQualityObs { + let cb = cqObs.boundingBox + let ix = max(fBB.minX, cb.minX) + let iy = max(fBB.minY, cb.minY) + let iw = min(fBB.maxX, cb.maxX) - ix + let ih = min(fBB.maxY, cb.maxY) - iy + if iw <= 0 || ih <= 0 { continue } + let overlap = (iw * ih) / (fBB.width * fBB.height) + if overlap > bestOverlap { + bestOverlap = overlap + if let cq = cqObs.faceCaptureQuality { + captureQ = Double(cq) + } + } + } + + // Fallback: Calculate quality from size and confidence if API didn't provide it + if captureQ == 0.0 { + let faceArea = Double(faceW * faceH) + let imgArea = Double(imgW * imgH) + let sizeScore = min(1.0, (faceArea / imgArea) * 4.0) // Normalize, larger = better + let confScore = Double(faceObs.confidence) // Already 0-1 + + // Weighted combination (no pose available for unmatched faces) + captureQ = sizeScore * 0.5 + confScore * 0.5 + } + + var faceData: [String: Any] = [ + "bbox": ["x": max(0, faceX), "y": max(0, faceY), + "width": faceW, "height": faceH], + "confidence": Double(faceObs.confidence), + "captureQuality": captureQ, + ] + if let yaw = faceObs.yaw?.doubleValue, + let roll = faceObs.roll?.doubleValue { + var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw] + if let pitch = faceObs.pitch?.doubleValue { + poseInfo["pitch"] = pitch + } + faceData["pose"] = poseInfo + } + frameFaces.append(faceData) + } + + if !frameFaces.isEmpty { + allFrames.append([ + "frame": frameNumber, + "timestamp": seconds, + "faces": frameFaces, + ]) + processedCount += 1 + } + } + + // Wait for batch to complete + for _ in batchStart.. 0 ? fps : Double(videoTrack.nominalFrameRate) + let totalFrames = Int(duration * detectedFps) + print("[SwiftOCR] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", detectedFps)), Frames: \(totalFrames)") + + let frameStep = sampleInterval + + // Use shared frame cache if available (set by FrameManager) + let tempDir: URL + let framesDir: URL + if let cacheDir = ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] { + framesDir = URL(fileURLWithPath: cacheDir) + tempDir = framesDir // No cleanup needed (managed by FrameManager) + print("[SwiftOCR] Using shared frame cache: \(cacheDir)") + } else { + tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("swift_ocr_\(UUID().uuidString)") + framesDir = tempDir.appendingPathComponent("frames") + try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true) + + let framePattern = framesDir.appendingPathComponent("frame_%05d.jpg").path + print("[SwiftOCR] Extracting frames with ffmpeg (interval=\(frameStep))...") + + // Get video dimensions for smart scaling + let videoSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform) + let videoWidth = Int(abs(videoSize.width)) + let maxOcrWidth = 1920 + let targetWidth = min(videoWidth, maxOcrWidth) + + // Build scale filter: only downscale if video > 1920px wide + let scaleFilter: String + if videoWidth > maxOcrWidth { + scaleFilter = "select=not(mod(n\\,\(frameStep))),scale=\(targetWidth):-2" + print("[SwiftOCR] Video width \(videoWidth)px > \(maxOcrWidth)px, scaling to \(targetWidth)px") + } else { + scaleFilter = "select=not(mod(n\\,\(frameStep)))" + print("[SwiftOCR] Video width \(videoWidth)px <= \(maxOcrWidth)px, using native resolution") + } + + let extractProc = Process() + extractProc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") + extractProc.arguments = ["-y", "-v", "quiet", "-i", inputPath, + "-vf", scaleFilter, + "-vsync", "vfr", "-q:v", "15", framePattern] + let startExtract = Date() + try extractProc.run() + extractProc.waitUntilExit() + let extractTime = Date().timeIntervalSince(startExtract) + print("[SwiftOCR] Frame extraction complete: \(String(format: "%.1f", extractTime))s") + } + + // Sort extracted frame files + let fileManager = FileManager.default + let allFiles = (try? fileManager.contentsOfDirectory(atPath: framesDir.path)) ?? [] + let frameFiles = allFiles + .filter { $0.hasPrefix("frame_") && $0.hasSuffix(".jpg") } + .sorted() + + let level: VNRequestTextRecognitionLevel = (recognitionLevel == "fast") ? .fast : .accurate + var ocrFrames: [[String: Any]] = [] + var lastProgress = 0 + let totalFrames_to_process = frameFiles.count + + for (i, frameName) in frameFiles.enumerated() { + let imgPath = framesDir.appendingPathComponent(frameName).path + + guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)), + let img = NSImage(data: imgData), + let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { + continue + } + + // Extract frame number from filename + let frameNumber = Int(frameName.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? (i * frameStep) + let timestamp = Double(frameNumber) / detectedFps + + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) + let request = VNRecognizeTextRequest() + request.recognitionLevel = level + request.usesLanguageCorrection = true + request.preferBackgroundProcessing = true + + guard (try? handler.perform([request])) != nil, + let results = request.results else { continue } + + var texts: [[String: Any]] = [] + let cgW = cgImage.width + let cgH = cgImage.height + for obs in results { + guard let candidate = obs.topCandidates(1).first else { continue } + let conf = candidate.confidence + guard conf > 0.3 else { continue } + let bb = obs.boundingBox + let item: [String: Any] = [ + "text": candidate.string, + "x": Int(bb.origin.x * CGFloat(cgW)), + "y": Int((1.0 - bb.origin.y - bb.size.height) * CGFloat(cgH)), + "width": Int(bb.size.width * CGFloat(cgW)), + "height": Int(bb.size.height * CGFloat(cgH)), + "confidence": Double(round(conf * 100)) / 100 + ] + texts.append(item) + } + + if !texts.isEmpty { + ocrFrames.append([ + "frame": frameNumber, + "timestamp": Double(round(timestamp * 100)) / 100, + "texts": texts + ]) + } + + let pct = Int(Float(i) / Float(totalFrames_to_process) * 100) + if pct >= lastProgress + 5 { + print("[SwiftOCR] Progress: \(pct)% (\(i)/\(totalFrames_to_process) samples, \(ocrFrames.count) with text)") + lastProgress = pct + } + } + + // Write output + let outputDict: [String: Any] = [ + "frame_count": ocrFrames.count, + "fps": detectedFps, + "frames": ocrFrames + ] + + if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) { + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + } + + let elapsed = Date().timeIntervalSince(startTime) + print("[SwiftOCR] Complete: \(ocrFrames.count) frames with text, \(String(format: "%.1f", elapsed))s") + if duration > 0 { + print("[SwiftOCR] RTF: \(String(format: "%.3f", elapsed / duration))x") + } + + // Clean up temp dir if we created it (not shared cache) + if ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] == nil { + try? FileManager.default.removeItem(at: tempDir) + } + } + + func recognizeText(pixelBuffer: CVPixelBuffer, level: VNRequestTextRecognitionLevel) -> [[String: Any]] { + var texts: [[String: Any]] = [] + let request = VNRecognizeTextRequest() + request.recognitionLevel = level + request.usesLanguageCorrection = true + request.preferBackgroundProcessing = true + + let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]) + guard (try? handler.perform([request])) != nil, + let results = request.results else { return texts } + + let cgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer)) + let cgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer)) + + for obs in results { + guard let candidate = obs.topCandidates(1).first, + candidate.confidence > 0.2 else { continue } + let bb = obs.boundingBox + texts.append([ + "text": candidate.string, + "x": Int(bb.origin.x * cgW), + "y": Int((1.0 - bb.origin.y - bb.size.height) * cgH), + "width": Int(bb.size.width * cgW), + "height": Int(bb.size.height * cgH), + "confidence": candidate.confidence + ]) + } + return texts + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/Sources/swift_scene_detector/main.swift b/installer/build/MomentryCore/tools/cli/swift/Sources/swift_scene_detector/main.swift new file mode 100644 index 00000000..8ceb9adb --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/Sources/swift_scene_detector/main.swift @@ -0,0 +1,223 @@ +import Foundation +import AVFoundation +import CoreImage + +struct Scene: Codable { + let scene_id: Int + let start_frame: Int + let start_time: Double + let end_frame: Int + let end_time: Double + let duration: Double + let score: Float +} + +struct VideoInfo: Codable { + let duration: Double + let fps: Double + let frame_count: Int + let width: Int + let height: Int +} + +struct CutResult: Codable { + let scene_count: Int + let scenes: [Scene] + let video_info: VideoInfo +} + +func detectScenes(videoPath: String, threshold: Float = 0.3, minSceneDuration: Double = 0.5) throws -> CutResult { + print("[SceneDetector] Processing: \(videoPath)") + + let url = URL(fileURLWithPath: videoPath) + let asset = AVAsset(url: url) + + guard let track = asset.tracks(withMediaType: .video).first else { + throw NSError(domain: "SceneDetector", code: 1, userInfo: [NSLocalizedDescriptionKey: "No video track"]) + } + + let duration = asset.duration.seconds + let fps = Double(track.nominalFrameRate) + let frameCount = Int(duration * fps) + + let dimensions = track.naturalSize + let width = Int(dimensions.width) + let height = Int(dimensions.height) + + print("[SceneDetector] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", fps)), Frames: \(frameCount)") + + let reader = try AVAssetReader(asset: asset) + + let outputSettings: [String: Any] = [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, + kCVPixelBufferWidthKey as String: 160, + kCVPixelBufferHeightKey as String: 90 + ] + + let output = AVAssetReaderTrackOutput(track: track, outputSettings: outputSettings) + reader.add(output) + + guard reader.startReading() else { + throw NSError(domain: "SceneDetector", code: 3, userInfo: [NSLocalizedDescriptionKey: "Failed to start reading"]) + } + + var scenes: [Scene] = [] + var previousBuffer: CVPixelBuffer? + var frameNum = 0 + var lastSceneFrame = 0 + + let context = CIContext(options: [.useSoftwareRenderer: false]) + + print("[SceneDetector] Processing frames...") + + while reader.status == .reading { + guard let sampleBuffer = output.copyNextSampleBuffer(), + let currentBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + break + } + + if let prevBuffer = previousBuffer { + if frameNum % 3 == 0 { + let diff = calculateFrameDifference(frame1: prevBuffer, frame2: currentBuffer, context: context) + + if diff > threshold { + let startTime = Double(lastSceneFrame) / fps + let endTime = Double(frameNum) / fps + + if endTime - startTime >= minSceneDuration { + let sceneId = scenes.count + let scene = Scene( + scene_id: sceneId, + start_frame: lastSceneFrame, + start_time: startTime, + end_frame: frameNum, + end_time: endTime, + duration: endTime - startTime, + score: diff + ) + scenes.append(scene) + lastSceneFrame = frameNum + print("[SceneDetector] Scene \(sceneId) at frame \(frameNum)") + } + } + } + } + + previousBuffer = currentBuffer + frameNum += 1 + } + + if frameNum > lastSceneFrame { + let sceneId = scenes.count + let startTime = Double(lastSceneFrame) / fps + let endTime = Double(frameNum) / fps + let duration = endTime - startTime + + let lastScene = Scene( + scene_id: sceneId, + start_frame: lastSceneFrame, + start_time: startTime, + end_frame: frameNum, + end_time: endTime, + duration: duration, + score: 0.0 + ) + scenes.append(lastScene) + } + + print("[SceneDetector] Detected \(scenes.count) scenes") + + let info = VideoInfo( + duration: duration, + fps: fps, + frame_count: frameCount, + width: width, + height: height + ) + + return CutResult(scene_count: scenes.count, scenes: scenes, video_info: info) +} + +func calculateFrameDifference(frame1: CVPixelBuffer, frame2: CVPixelBuffer, context: CIContext) -> Float { + let ciImage1 = CIImage(cvPixelBuffer: frame1) + let ciImage2 = CIImage(cvPixelBuffer: frame2) + + guard let differenceFilter = CIFilter(name: "CIDifferenceBlendMode") else { + return 0.0 + } + + differenceFilter.setValue(ciImage1, forKey: kCIInputImageKey) + differenceFilter.setValue(ciImage2, forKey: kCIInputBackgroundImageKey) + + guard let diffImage = differenceFilter.outputImage else { + return 0.0 + } + + let extent = diffImage.extent + let totalPixels = extent.width * extent.height + + guard totalPixels > 0 else { + return 0.0 + } + + var totalDiff: Float = 0 + let sampleCount = 100 + + for i in 0.. [--threshold 0.3]") + exit(1) +} + +let videoPath = args[1] +let outputPath = args[2] +var threshold: Float = 0.3 +var minSceneDuration: Double = 0.5 + +var i = 3 +while i < args.count { + if args[i] == "--threshold", i + 1 < args.count { + threshold = Float(args[i + 1]) ?? 0.3 + i += 2 + } else if args[i] == "--min-duration", i + 1 < args.count { + minSceneDuration = Double(args[i + 1]) ?? 0.5 + i += 2 + } else { + i += 1 + } +} + +do { + let result = try detectScenes(videoPath: videoPath, threshold: threshold, minSceneDuration: minSceneDuration) + + let encoder = JSONEncoder() + encoder.outputFormatting = .prettyPrinted + let jsonData = try encoder.encode(result) + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + + print("[SceneDetector] Output: \(outputPath)") +} catch { + print("[SceneDetector] Error: \(error)") + exit(1) +} diff --git a/installer/build/MomentryCore/tools/cli/swift/asr_swift.swift b/installer/build/MomentryCore/tools/cli/swift/asr_swift.swift new file mode 100644 index 00000000..8172b36d --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/asr_swift.swift @@ -0,0 +1,254 @@ +import Foundation +import Speech +import ArgumentParser + +/// Swift CLI 處理器:使用 Apple Speech Framework 進行語音辨識 +/// 作為 Python ASR (faster-whisper) 的替代方案 +/// +/// 比較項目: +/// - Speech Framework 使用 Apple 內建模型(ANE 加速) +/// - 無需下載模型,系統內建 +/// - 支援即時與批次辨識 +/// - 語言支援依作業系統版本 + +/// 合併逐字 segments 成句子 +/// 當相鄰 segment 間隔 < 0.5s 時合併,間隔 >= 0.5s 時視為句子邊界 +func mergeWordSegments(_ segments: [[String: Any]]) -> [[String: Any]] { + let gapThreshold: TimeInterval = 0.5 + var merged: [[String: Any]] = [] + var current: [String: Any]? = nil + + for seg in segments { + guard let start = seg["start"] as? TimeInterval, + let end = seg["end"] as? TimeInterval, + let text = seg["text"] as? String, + let conf = seg["confidence"] as? Float else { + continue + } + + if var cur = current { + let curEnd = cur["end"] as? TimeInterval ?? 0 + let gap = start - curEnd + + if gap < gapThreshold { + // 合併到當前句子 + let curText = cur["text"] as? String ?? "" + let curConf = cur["confidence"] as? Float ?? 0 + let wordCount = cur["_wordCount"] as? Int ?? 0 + cur["text"] = curText + (curText.hasSuffix(" ") ? "" : " ") + text + cur["end"] = end + // 用 confidence 加權平均(依字數) + let totalWords = wordCount + 1 + cur["confidence"] = (curConf * Float(wordCount) + conf) / Float(totalWords) + cur["_wordCount"] = totalWords + current = cur + } else { + // 句子邊界:儲存當前,開始新的 + cur.removeValue(forKey: "_wordCount") + merged.append(cur) + current = [ + "start": start, + "end": end, + "text": text, + "confidence": conf, + "_wordCount": 1 + ] + } + } else { + current = [ + "start": start, + "end": end, + "text": text, + "confidence": conf, + "_wordCount": 1 + ] + } + } + + if let cur = current { + var finalCur = cur + finalCur.removeValue(forKey: "_wordCount") + merged.append(finalCur) + } + + return merged +} + +@main +struct ASRSwift: ParsableCommand { + @Argument(help: "音訊/影片檔案路徑") + var inputPath: String + + @Argument(help: "輸出 JSON 路徑") + var outputPath: String + + @Option(name: .long, help: "UUID for Redis") + var uuid: String = "" + + @Option(name: .long, help: "語言 (留空則自動嘗試支援的語種)") + var language: String = "" + + /// 嘗試自動偵測語種 + func detectLanguage() -> String { + if !language.isEmpty { return language } + // 優先嘗試常用語種 + let candidates = ["zh-TW", "zh-Hans", "en-US", "ja-JP", "ko-KR"] + for localeId in candidates { + if let reco = SFSpeechRecognizer(locale: Locale(identifier: localeId)), reco.isAvailable { + print("[ASR_Swift] Auto-detected language: \(localeId)") + return localeId + } + } + return "en-US" + } + + mutating func run() throws { + let startTime = Date() + + print("[ASR_Swift] Starting: \(inputPath)") + print("[ASR_Swift] Language: \(language)") + print("[ASR_Swift] Output: \(outputPath)") + + // 1. 萃取音訊(若為影片檔) + let audioURL: URL + let ext = (inputPath as NSString).pathExtension.lowercased() + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("asr_swift_\(UUID().uuidString)") + + if ["mp4", "mov", "mkv", "avi"].contains(ext) { + // 需要 ffmpeg 萃取音訊 + let wavPath = tempDir.appendingPathComponent("audio.wav").path + print("[ASR_Swift] Extracting audio from video...") + let proc = Process() + proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") + proc.arguments = ["-y", "-v", "quiet", "-i", inputPath, + "-ar", "16000", "-ac", "1", wavPath] + try proc.run() + proc.waitUntilExit() + guard FileManager.default.fileExists(atPath: wavPath) else { + print("[ASR_Swift] Error: ffmpeg failed to extract audio") + throw NSError(domain: "ASRSwift", code: 1, userInfo: nil) + } + audioURL = URL(fileURLWithPath: wavPath) + print("[ASR_Swift] Audio extracted: \(wavPath)") + } else { + audioURL = URL(fileURLWithPath: inputPath) + } + + // 2. 語音辨識 + print("[ASR_Swift] Starting recognition...") + + // 請求授權 + let authGroup = DispatchGroup() + authGroup.enter() + var authStatus: SFSpeechRecognizerAuthorizationStatus = .notDetermined + SFSpeechRecognizer.requestAuthorization { status in + authStatus = status + authGroup.leave() + } + authGroup.wait() + guard authStatus == .authorized else { + print("[ASR_Swift] Speech recognition not authorized: \(authStatus.rawValue)") + return + } + print("[ASR_Swift] Speech recognition authorized") + + let finalLang = detectLanguage() + let recognizer = SFSpeechRecognizer(locale: Locale(identifier: finalLang)) + guard let recognizer = recognizer, recognizer.isAvailable else { + print("[ASR_Swift] Error: Speech recognizer not available for \(language)") + // 回傳空結果 + let emptyResult: [String: Any] = [ + "language": language, + "segments": [], + "processing_time": Date().timeIntervalSince(startTime), + "model": "Apple Speech Framework", + "error": "Recognizer not available" + ] + let jsonData = try JSONSerialization.data(withJSONObject: emptyResult, options: [.prettyPrinted]) + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + return + } + + let request = SFSpeechURLRecognitionRequest(url: audioURL) + request.shouldReportPartialResults = false + request.taskHint = .dictation + + var allSegments: [[String: Any]] = [] + let semaphore = DispatchSemaphore(value: 0) + + let task = recognizer.recognitionTask(with: request) { result, error in + if let error = error { + print("[ASR_Swift] Recognition error: \(error.localizedDescription)") + semaphore.signal() + return + } + + if let result = result, result.isFinal { + let duration = Date().timeIntervalSince(startTime) + print("[ASR_Swift] Recognition completed in \(String(format: "%.2f", duration))s") + + // 將辨識結果轉為 segment 格式 + for segment in result.bestTranscription.segments { + let seg: [String: Any] = [ + "start": segment.timestamp, + "end": segment.timestamp + segment.duration, + "text": segment.substring, + "speaker_id": nil as String?, + "confidence": segment.confidence + ] + allSegments.append(seg) + } + + // 合併逐字 segments 成句子 + if !allSegments.isEmpty { + let beforeCount = allSegments.count + allSegments = mergeWordSegments(allSegments) + print("[ASR_Swift] Merged segments: \(beforeCount) → \(allSegments.count)") + } + + // 若無 segment,用整個文字建立一個 + if allSegments.isEmpty { + let fullText = result.bestTranscription.formattedString + let seg: [String: Any] = [ + "start": 0.0, + "end": Date().timeIntervalSince(startTime), + "text": fullText, + "speaker_id": nil as String?, + "confidence": 1.0 + ] + allSegments.append(seg) + } + + semaphore.signal() + } + } + + // RunLoop 是必要的 — Speech Framework 需要 main runloop 觸發 callback + // 使用 semaphore 等待完成,避免固定 timeout + while semaphore.wait(timeout: .now()) == .timedOut { + RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1)) + } + task.cancel() + + // 3. 輸出 JSON + let outputDict: [String: Any] = [ + "language": language, + "segments": allSegments, + "processing_time": Date().timeIntervalSince(startTime), + "model": "Apple Speech Framework (ANE accelerated)", + "total_segments": allSegments.count + ] + + let jsonData = try JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + + print("[ASR_Swift] Saved \(allSegments.count) segments to \(outputPath)") + print("[ASR_Swift] Total time: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s") + + // 清理暫存 + if tempDir != audioURL.deletingLastPathComponent() { + try? FileManager.default.removeItem(at: tempDir) + } + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/asrx_swift.swift b/installer/build/MomentryCore/tools/cli/swift/asrx_swift.swift new file mode 100644 index 00000000..62782c31 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/asrx_swift.swift @@ -0,0 +1,218 @@ +import Foundation +import Speech +import ArgumentParser + +/// Swift ASRX Processor +/// Speaker Diarization via Apple Speech Framework +/// +/// 使用 SFSpeechRecognizer 進行語音辨識並嘗試分離說話人 +/// 目前 Apple Speech Framework 不直接支援 speaker diarization, +/// 此實作透過音訊分段 + 逐段辨識來近似 diarization 效果 + +@main +struct ASRXSwift: ParsableCommand { + @Argument(help: "音訊/影片檔案路徑") + var inputPath: String + + @Argument(help: "輸出 JSON 路徑") + var outputPath: String + + @Option(name: .long, help: "UUID for Redis") + var uuid: String = "" + + @Option(name: .long, help: "語言 (留空自動偵測)") + var language: String = "" + + @Option(name: .long, help: "分段長度(秒),預設 5 秒") + var segmentDuration: Double = 5.0 + + mutating func run() throws { + let startTime = Date() + print("[ASRX_Swift] Starting: \(inputPath)") + + // 1. 萃取音訊 + let audioURL = extractAudio(from: inputPath) + defer { try? FileManager.default.removeItem(at: audioURL.deletingLastPathComponent()) } + + // 2. 取得音訊資訊 + let audioFile = try AVAudioFile(forReading: audioURL) + let format = audioFile.processingFormat + let totalFrames = audioFile.length + let duration = Double(totalFrames) / format.sampleRate + print("[ASRX_Swift] Audio: \(totalFrames) frames, \(String(format: "%.1f", duration))s, \(format.sampleRate)Hz") + + // 3. 載入完整音訊 + guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(totalFrames)) else { + throw NSError(domain: "ASRXSwift", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to create buffer"]) + } + try audioFile.read(into: buffer) + + guard let floatDataPtr = buffer.floatChannelData else { + throw NSError(domain: "ASRXSwift", code: 2, userInfo: [NSLocalizedDescriptionKey: "No float data"]) + } + let floatData = UnsafeBufferPointer(start: floatDataPtr[0], count: Int(totalFrames) * Int(format.channelCount)) + + // 4. 分段辨識 + let finalLang = resolveLanguage() + let recognizer = SFSpeechRecognizer(locale: Locale(identifier: finalLang))! + let frameStep = Int(segmentDuration * format.sampleRate) + let totalSegments = Int(ceil(duration / segmentDuration)) + + print("[ASRX_Swift] Splitting into \(totalSegments) segments of \(Int(segmentDuration))s") + print("[ASRX_Swift] Language: \(finalLang)") + print("[ASRX_Swift] Starting diarization...") + + var segments: [[String: Any]] = [] + var processedCount = 0 + + for segIdx in 0.. format.sampleRate * 0.5 else { continue } // 跳過 < 0.5s 的片段 + + let segBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(segLength))! + segBuffer.frameLength = AVAudioFrameCount(segLength) + let src = floatData[0] + let dstPtr = segBuffer.floatChannelData![0] + let srcSlice = Array(floatData[startFrame.. URL { + let ext = (path as NSString).pathExtension.lowercased() + let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("asrx_\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + let wavURL = tempDir.appendingPathComponent("audio.wav") + + if ["mp4", "mov", "mkv", "avi"].contains(ext) { + print("[ASRX_Swift] Extracting audio from video...") + let proc = Process() + proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") + proc.arguments = ["-y", "-v", "quiet", "-i", path, "-ar", "16000", "-ac", "1", wavURL.path] + try! proc.run() + proc.waitUntilExit() + } else { + try! FileManager.default.copyItem(at: URL(fileURLWithPath: path), to: wavURL) + } + return wavURL + } + + func resolveLanguage() -> String { + // 1. If --language is specified, use it + if !language.isEmpty { + print("[ASRX_Swift] Using specified language: \(language)") + return language + } + + // 2. Try to read language from ASR JSON + let outputDir = URL(fileURLWithPath: outputPath).deletingLastPathComponent() + let fileUUID = URL(fileURLWithPath: outputPath).deletingPathExtension().lastPathComponent + let asrJsonPath = outputDir.appendingPathComponent("\(fileUUID).asr.json").path + + if FileManager.default.fileExists(atPath: asrJsonPath) { + do { + let asrData = try Data(contentsOf: URL(fileURLWithPath: asrJsonPath)) + if let asrJson = try JSONSerialization.jsonObject(with: asrData) as? [String: Any], + let asrLang = asrJson["language"] as? String { + // Map ASR language codes to Apple locale identifiers + let langMap: [String: String] = [ + "en": "en-US", + "zh": "zh-TW", + "ja": "ja-JP", + "ko": "ko-KR", + "es": "es-ES", + "fr": "fr-FR", + "de": "de-DE", + ] + let appleLang = langMap[asrLang] ?? asrLang + print("[ASRX_Swift] Using language from ASR JSON: \(asrLang) -> \(appleLang)") + return appleLang + } + } catch { + print("[ASRX_Swift] Warning: Failed to read ASR JSON: \(error)") + } + } + + // 3. Fallback to auto-detection (prioritize en-US) + let candidates = ["en-US", "zh-TW", "zh-Hans", "ja-JP", "ko-KR"] + for localeId in candidates { + if let reco = SFSpeechRecognizer(locale: Locale(identifier: localeId)), reco.isAvailable { + print("[ASRX_Swift] Auto-detected language: \(localeId)") + return localeId + } + } + return "en-US" + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/body_pose_scanner.swift b/installer/build/MomentryCore/tools/cli/swift/body_pose_scanner.swift new file mode 100644 index 00000000..1a434198 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/body_pose_scanner.swift @@ -0,0 +1,124 @@ +#!/usr/bin/env swift +import Foundation +import Vision +import AVFoundation +import ArgumentParser + +/// Full-movie body pose scanner: compute head-to-body ratio for every frame +/// with face detections. Outputs JSONL (one object per frame). +@main +struct BodyPoseScanner: ParsableCommand { + @Argument(help: "Video file path") + var videoPath: String + + @Argument(help: "Output JSONL path") + var outputPath: String + + @Option(help: "Frames to scan (comma-separated, e.g. '840,900,960') or 'all' to scan everything") + var frames: String = "all" + + @Option(help: "Sample interval (every N frames, for 'all' mode)") + var interval: Int = 60 + + func run() throws { + let url = URL(fileURLWithPath: videoPath) + let asset = AVAsset(url: url) + guard let reader = try? AVAssetReader(asset: asset) else { + print("[BodyPose] Cannot open video"); return + } + + guard let videoTrack = asset.tracks(withMediaType: .video).first else { + print("[BodyPose] No video track"); return + } + + let fps = videoTrack.nominalFrameRate + let totalFrames = Int(videoTrack.timeRange.duration.seconds * Double(fps)) + + let readerOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange + ]) + readerOutput.alwaysCopiesSampleData = false + reader.add(readerOutput) + reader.startReading() + + // Parse target frames + var targetFrames = Set() + if frames == "all" { + targetFrames = Set(stride(from: 0, to: totalFrames, by: interval)) + } else { + targetFrames = Set(frames.split(separator: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) }) + } + + var frameCount = 0 + var results: [[String: Any]] = [] + let bodyRequest = VNDetectHumanBodyPoseRequest() + + guard let fh = FileHandle(forWritingAtPath: outputPath) else { + print("[BodyPose] Cannot create output"); return + } + + while let sampleBuffer = readerOutput.copyNextSampleBuffer() { + defer { frameCount += 1 } + guard targetFrames.contains(frameCount) else { continue } + targetFrames.remove(frameCount) + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { continue } + + let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]) + try? handler.perform([bodyRequest]) + + guard let poses = bodyRequest.results, !poses.isEmpty else { continue } + + let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer)) + let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer)) + + for obs in poses { + guard let pts = try? obs.recognizedPoints(.all) else { continue } + + var joints: [String: CGFloat] = [:] + for (name, pt) in pts where pt.confidence > 0.3 { + // Convert Vision (bottom-left origin) to pixel (top-left origin) + joints[String(describing: name)] = pt.location.x * imgW + joints[String(describing: name) + "_y"] = imgH - pt.location.y * imgH + } + + // Get head top + let headY = joints["head_joint_y"] ?? joints["neck_1_joint_y"] ?? + joints["neck_2_joint_y"] ?? joints["right_eye_joint_y"] ?? 0 + + // Get lowest visible body point (foot > ankle > knee > hip) + var bodyBottom = CGFloat.greatestFiniteMagnitude + for jn in ["right_ankle_joint_y", "left_ankle_joint_y", + "right_knee_joint_y", "left_knee_joint_y", + "right_hip_joint_y", "left_hip_joint_y"] { + if let v = joints[jn], v > 0 { + bodyBottom = min(bodyBottom, v) + } + } + + let bodyH = bodyBottom == .greatestFiniteMagnitude ? 0 : abs(headY - bodyBottom) + let headH = abs(headY - (joints["neck_1_joint_y"] ?? headY)) + + let h2b = bodyH > 0 ? headH / bodyH : 0 + + let row: [String: Any] = [ + "frame": frameCount, "timestamp": Double(frameCount)/Double(fps), + "head_top_y": headY, "body_bottom_y": bodyBottom, + "body_h_px": bodyH, "head_h_px": headH, + "h2b_ratio": Double(String(format: "%.3f", h2b)) ?? 0, + "has_full_body": bodyH > 0 && headH > 0, + "joints": joints.mapValues { Double($0) } + ] + + var jsonData = try! JSONSerialization.data(withJSONObject: row) + jsonData.append(10) // newline + fh.write(jsonData) + } + + if targetFrames.isEmpty { break } + } + reader.cancelReading() + fh.closeFile() + print("[BodyPose] Done: \(results.count) frames → \(outputPath)") + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/check_speech_apis.swift b/installer/build/MomentryCore/tools/cli/swift/check_speech_apis.swift new file mode 100644 index 00000000..fa4637af --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/check_speech_apis.swift @@ -0,0 +1,46 @@ +import Foundation +import Speech + +// Check what's available in Speech framework +print("=== Speech Framework API Availability ===") + +// SFSpeechRecognizer +print("SFSpeechRecognizer available: true") + +// Check for SFSpeechRecognitionMetadata (iOS 17+, macOS 14+) +let mdClass = NSClassFromString("SFSpeechRecognitionMetadata") +print("SFSpeechRecognitionMetadata: \(mdClass != nil ? "✅ Available" : "❌ Not available")") + +// Check SFSpeechAnalyzer (iOS 17+, macOS 14+) +let analyzerClass = NSClassFromString("SFSpeechAnalyzer") +print("SFSpeechAnalyzer: \(analyzerClass != nil ? "✅ Available" : "❌ Not available")") + +// Check for speaker identification types +let seClass = NSClassFromString("SFSpeakerEmbedding") +print("SFSpeakerEmbedding: \(seClass != nil ? "✅ Available" : "❌ Not available")") + +let siClass = NSClassFromString("SFSpeakerIdentification") +print("SFSpeakerIdentification: \(siClass != nil ? "✅ Available" : "❌ Not available")") + +let sevClass = NSClassFromString("SFSpeakerEmbeddingVector") +print("SFSpeakerEmbeddingVector: \(sevClass != nil ? "✅ Available" : "❌ Not available")") + +let srClass = NSClassFromString("SFSpeakerRecognition") +print("SFSpeakerRecognition: \(srClass != nil ? "✅ Available" : "❌ Not available")") + +// Check for AFVoiceBank / AVAudioSession speaker recognition +let avClass = NSClassFromString("AVVoiceBank") +print("AVVoiceBank: \(avClass != nil ? "✅ Available" : "❌ Not available")") + +// Check AVAudioSession +if #available(macOS 14, *) { + print("macOS 14+ APIs available: ✅") +} else { + print("macOS 14+ APIs: ❌") +} + +// Summarize +print() +print("=== Summary ===") +print("SFSpeechAnalyzer: \(analyzerClass != nil ? "✅ High-level speech analysis API" : "❌ Not available on this macOS version")") +print("Speaker recognition APIs: \(seClass != nil || siClass != nil || srClass != nil ? "✅ Speaker recognition APIs exist" : "❌ No speaker recognition APIs found")") diff --git a/installer/build/MomentryCore/tools/cli/swift/check_vision.swift b/installer/build/MomentryCore/tools/cli/swift/check_vision.swift new file mode 100644 index 00000000..f2f8d914 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/check_vision.swift @@ -0,0 +1,23 @@ +import Foundation +import Vision + +let classes = [ + "VNDetectFaceRectanglesRequest", + "VNDetectHumanRectanglesRequest", + "VNDetectHumanBodyPoseRequest", + "VNDetectHumanHandPoseRequest", + "VNClassifyImageRequest", + "VNRecognizeTextRequest", + "VNGenerateObjectnessBasedSaliencyImageRequest", + "VNGenerateAttentionBasedSaliencyImageRequest", + "VNRecognizeObjectsRequest", + "VNDetectContoursRequest", + "VNDetectTrajectoriesRequest", +] +for cname in classes { + if NSClassFromString(cname) != nil { + print("\(cname): ✅") + } else { + print("\(cname): ❌") + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/entitlements.plist b/installer/build/MomentryCore/tools/cli/swift/entitlements.plist new file mode 100644 index 00000000..de478b6d --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/entitlements.plist @@ -0,0 +1,16 @@ + + + + + com.apple.security.device.audio-input + + com.apple.security.device.camera + + com.apple.security.network.client + + com.apple.security.files.user-selected.read-write + + com.apple.security.temporary-exception.audio-upload + + + diff --git a/installer/build/MomentryCore/tools/cli/swift/face_compare_test.swift b/installer/build/MomentryCore/tools/cli/swift/face_compare_test.swift new file mode 100644 index 00000000..2cce05e7 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/face_compare_test.swift @@ -0,0 +1,206 @@ +import Foundation +import Vision +import ArgumentParser +import AppKit +import AVFoundation + +/// Full comparison: Apple Vision Framework vs InsightFace for face processing +@main +struct FaceCompareTest: ParsableCommand { + @Argument(help: "Video path or image path") + var inputPath: String + + @Option(name: .long, help: "Sample interval (frames)") + var sampleInterval: Int = 30 + + @Option(name: .long, help: "Maximum frames to process") + var maxFrames: Int = 20 + + mutating func run() throws { + let startTime = Date() + print("=== Apple Vision Framework Face Processing ===") + #if arch(arm64) + print("HW: Apple Silicon ✅") + #endif + + let url = URL(fileURLWithPath: inputPath) + let ext = (inputPath as NSString).pathExtension.lowercased() + + if ["mp4", "mov", "mkv", "avi"].contains(ext) { + try processVideo(url: url) + } else { + try processImage(url: url) + } + + print("Time: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s") + } + + func processVideo(url: URL) throws { + let asset = AVAsset(url: url) + guard let track = asset.tracks(withMediaType: .video).first else { + print("No video track"); return + } + let duration = asset.duration.seconds + let fps = Double(track.nominalFrameRate) + let totalFrames = Int(duration * fps) + print("Video: \(duration)s @ \(fps)fps = \(totalFrames) frames") + + // Extract frames with ffmpeg at sample interval + let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("face_compare_\(UUID().uuidString)") + let framesDir = tempDir.appendingPathComponent("frames") + try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path + let proc = Process() + proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") + proc.arguments = ["-y", "-v", "quiet", "-i", url.path, + "-vf", "select=not(mod(n\\,\(sampleInterval)))", + "-vsync", "vfr", "-q:v", "5", pattern] + try proc.run() + proc.waitUntilExit() + + let allFiles = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? [] + let frameFiles = allFiles.filter { $0.hasSuffix(".jpg") }.sorted().prefix(maxFrames) + + var totalFaces = 0 + var framesWithFaces = 0 + var frameCount = 0 + + for fname in frameFiles { + let imgPath = framesDir.appendingPathComponent(fname).path + guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)), + let img = NSImage(data: imgData), + let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue } + + let frameNum = Int(fname.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? 0 + let timestamp = Double(frameNum) / fps + + // Run all face detection requests + let faceResult = detectFaces(cgImage: cgImage) + if faceResult.count > 0 { + totalFaces += faceResult.count + framesWithFaces += 1 + print(" Frame \(frameNum) (\(String(format: "%.1f", timestamp))s): \(faceResult.count) faces") + for (i, f) in faceResult.enumerated() { + print(" [\(i)] bbox=(\(String(format: "%.0f", f.x)),\(String(format: "%.0f", f.y))) size=\(String(format: "%.0f", f.w))x\(String(format: "%.0f", f.h)) conf=\(String(format: "%.3f", f.conf)) quality=\(String(format: "%.3f", f.quality)) landmarks=\(f.landmarks) embedding=\(f.hasEmbedding ? "✅" : "❌")") + } + } + frameCount += 1 + } + + print("\n=== Summary ===") + print("Frames processed: \(frameCount)") + print("Frames with faces: \(framesWithFaces)") + print("Total faces detected: \(totalFaces)") + + // Compare with existing InsightFace JSON if available + let uuid = extractUUID(from: url.lastPathComponent) + if uuid != "" { + let faceJsonPath = "/Users/accusys/momentry/output_dev/\(uuid).face.json" + if FileManager.default.fileExists(atPath: faceJsonPath) { + print("\n=== Comparison with InsightFace (\(uuid).face.json) ===") + if let data = try? Data(contentsOf: URL(fileURLWithPath: faceJsonPath)), + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let frames = json["frames"] as? [[String: Any]] { + let insightFaces = frames.filter { ($0["faces"] as? [Any])?.count ?? 0 > 0 }.count + let totalInsightFaces = frames.reduce(0) { $0 + (($1["faces"] as? [Any])?.count ?? 0) } + print(" InsightFace frames with faces: \(insightFaces)") + print(" InsightFace total faces: \(totalInsightFaces)") + } + } + } + } + + func processImage(url: URL) throws { + guard let imgData = try? Data(contentsOf: url), + let img = NSImage(data: imgData), + let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { + print("Cannot load image"); return + } + print("Image: \(cgImage.width)x\(cgImage.height)") + let result = detectFaces(cgImage: cgImage) + print("Vision faces: \(result.count)") + for (i, f) in result.enumerated() { + print(" [\(i)] bbox=(\(String(format: "%.0f", f.x)),\(String(format: "%.0f", f.y))) size=\(String(format: "%.0f", f.w))x\(String(format: "%.0f", f.h)) conf=\(String(format: "%.3f", f.conf)) quality=\(String(format: "%.3f", f.quality)) landmarks=\(f.landmarks) embedding=\(f.hasEmbedding ? "✅" : "❌")") + } + } + + struct FaceResult { + let x, y, w, h: Float + let conf: Float + let quality: Float + let landmarks: Int + let hasEmbedding: Bool + } + + func detectFaces(cgImage: CGImage) -> [FaceResult] { + var results: [FaceResult] = [] + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) + + // 1. Face Detection + let detectReq = VNDetectFaceRectanglesRequest() + try? handler.perform([detectReq]) + + // 2. Face Landmarks (run separately for each detected face) + let landmarkReq = VNDetectFaceLandmarksRequest() + + // 3. Face Capture Quality + let qualityReq = VNDetectFaceCaptureQualityRequest() + + // Run all requests + try? handler.perform([landmarkReq, qualityReq]) + + guard let detections = detectReq.results else { return [] } + + let qualityResults = qualityReq.results ?? [] + + for (i, face) in detections.enumerated() { + let bb = face.boundingBox + let w = Float(cgImage.width) + let h = Float(cgImage.height) + let x = Float(bb.origin.x) * w + let y = Float(bb.origin.y) * h + let fw = Float(bb.size.width) * w + let fh = Float(bb.size.height) * h + + // Get landmarks count + var lmCount = 0 + if let lmResults = landmarkReq.results, i < lmResults.count { + let lms = lmResults[i].landmarks + if let left = lms?.leftEye { lmCount += left.pointCount } + if let right = lms?.rightEye { lmCount += right.pointCount } + if let nose = lms?.nose { lmCount += nose.pointCount } + } + + // Get quality score + var quality: Float = 0 + if i < qualityResults.count { + if #available(macOS 14, *) { + quality = (qualityResults[i].value(forKey: "faceCaptureQuality") as? Double).map { Float($0) } ?? 0 + } + } + + // Check for faceprint (embedding) via KVC + var hasEmbedding = false + if #available(macOS 14, *) { + if let fp = face.value(forKey: "faceprint") as? NSObject { + hasEmbedding = (fp.value(forKey: "data") as? Data) != nil + } + } + + results.append(FaceResult(x: x, y: y, w: fw, h: fh, conf: face.confidence, quality: quality, landmarks: lmCount, hasEmbedding: hasEmbedding)) + } + + return results + } + + func extractUUID(from filename: String) -> String { + // Try to extract 32-char hex UUID from filename + let pattern = try? NSRegularExpression(pattern: "[a-f0-9]{32}") + if let match = pattern?.firstMatch(in: filename, range: NSRange(location: 0, length: filename.count)) { + return (filename as NSString).substring(with: match.range) + } + return "" + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/face_vision_test.swift b/installer/build/MomentryCore/tools/cli/swift/face_vision_test.swift new file mode 100644 index 00000000..11976ffd --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/face_vision_test.swift @@ -0,0 +1,98 @@ +import Foundation +import Vision +import ArgumentParser +import AppKit + +/// POC: Test Apple Vision Framework for face detection + faceprint extraction +@main +struct FaceVisionTest: ParsableCommand { + @Argument(help: "Input image path") + var inputPath: String + + mutating func run() throws { + let startTime = Date() + print("=== Apple Vision Framework Face POC ===") + #if arch(arm64) + print("HW: Apple Silicon ✅") + #else + print("HW: Intel") + #endif + + guard let image = NSImage(contentsOfFile: inputPath) else { + print("Error: cannot load image"); return + } + guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { + print("Error: cannot get CGImage"); return + } + print("Image: \(cgImage.width)x\(cgImage.height)") + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) + + // 1. Detect faces (synchronous) + print("\n--- Detection ---") + let detectReq = VNDetectFaceRectanglesRequest() + try handler.perform([detectReq]) + let faces = detectReq.results ?? [] + print("Faces: \(faces.count)") + for (i, f) in faces.enumerated() { + let bb = f.boundingBox + print(" [\(i)] bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y))) size=(\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) conf=\(String(format: "%.2f", f.confidence))") + } + + guard !faces.isEmpty else { print("No faces"); return } + + // 2. Landmarks + print("\n--- Landmarks ---") + let lmReq = VNDetectFaceLandmarksRequest() + try handler.perform([lmReq]) + if let lmResults = lmReq.results { + for (i, f) in lmResults.enumerated() { + if let lms = f.landmarks { + let count = (lms.leftEye?.pointCount ?? 0) + (lms.rightEye?.pointCount ?? 0) + print(" [\(i)] landmarks: \(lms.leftEye?.pointCount ?? 0)+\(lms.rightEye?.pointCount ?? 0) eye pts, nose=\(lms.nose?.pointCount ?? 0)") + } + } + } + + // 3. Capture quality + print("\n--- Capture Quality ---") + let qualReq = VNDetectFaceCaptureQualityRequest() + try handler.perform([qualReq]) + if let qResults = qualReq.results { + for (i, f) in qResults.enumerated() { + if #available(macOS 14, *) { + let q = f.value(forKey: "faceCaptureQuality") as? Double ?? -1 + print(" [\(i)] quality=\(String(format: "%.4f", q))") + } + } + } + + // 4. Faceprint (embedding) + print("\n--- Faceprint ---") + if #available(macOS 14, *) { + let fpClass: AnyClass? = NSClassFromString("VNFaceprint") + print("VNFaceprint class: \(fpClass != nil ? "✅ exists" : "❌ nil")") + + if let first = faces.first { + let fp = first.value(forKey: "faceprint") as? NSObject + print("faceprint KVC: \(fp != nil ? "✅" : "❌")") + if let fpData = fp { + let data = fpData.value(forKey: "data") as? Data + print(" data: \(data != nil ? "\(data!.count) bytes" : "nil")") + let desc = fpData.value(forKey: "descriptor") as? NSObject + print(" descriptor: \(desc != nil ? "✅ class=\(type(of: desc!))" : "nil")") + if let d = desc, let elems = d.value(forKey: "elements") as? [NSNumber] { + print(" elements: \(elems.count) dims") + if elems.count > 0 { + print(" first 5: \(elems.prefix(5).map { String(format: "%.4f", $0.doubleValue) }.joined(separator: ", "))") + } + } + } + } + } else { + print("macOS 14+ required") + } + + print("\nTime: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s") + print("=== Done ===") + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/facenet_embedding.swift b/installer/build/MomentryCore/tools/cli/swift/facenet_embedding.swift new file mode 100644 index 00000000..1698a216 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/facenet_embedding.swift @@ -0,0 +1,192 @@ +import Foundation +import Vision +import CoreML +import ArgumentParser +import AVFoundation + +/// FaceNet CoreML Embedding Generator +/// Reads face.json, extracts face regions, generates 512-dim embeddings via FaceNet +@main +struct FaceNetEmbedding: ParsableCommand { + @Argument(help: "Video file path") + var videoPath: String + + @Argument(help: "Input face.json path") + var inputPath: String + + @Argument(help: "Output face.json path") + var outputPath: String + + @Option(name: .long, help: "UUID for logging") + var uuid: String = "" + + mutating func run() throws { + let startTime = Date() + print("[FaceNet] Loading FaceNet CoreML model...") + + // Load FaceNet CoreML model + let modelURL = URL(fileURLWithPath: "/Users/accusys/momentry_core/models/facenet512.mlpackage/Data/com.apple.CoreML/model.mlmodel") + let compiledURL = try MLModel.compileModel(at: modelURL) + let model = try MLModel(contentsOf: compiledURL) + print("[FaceNet] Model loaded (ANE+GPU+CPU)") + + // Load face.json + let faceData = try Data(contentsOf: URL(fileURLWithPath: inputPath)) + var faceJson = try JSONSerialization.jsonObject(with: faceData) as! [String: Any] + var frames = faceJson["frames"] as! [[String: Any]] + let fps = faceJson["fps"] as! Double + print("[FaceNet] Loaded \(frames.count) frames from \(inputPath)") + + // Load video + let asset = AVURLAsset(url: URL(fileURLWithPath: videoPath)) + let generator = AVAssetImageGenerator(asset: asset) + generator.requestedTimeToleranceBefore = .zero + generator.requestedTimeToleranceAfter = .zero + generator.appliesPreferredTrackTransform = true + + var embeddingCount = 0 + var processedFrames = 0 + + // Process frames in batches + for i in 0.. CGImage? { + let width = Int(size.width) + let height = Int(size.height) + let bytesPerPixel = 4 + let bytesPerRow = width * bytesPerPixel + + guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil } + guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } + + context.interpolationQuality = .high + context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) + + return context.makeImage() + } + + private func cgImageToMLMultiArray(_ image: CGImage) -> MLMultiArray? { + let width = image.width + let height = image.height + + // Create MLMultiArray with shape [1, 3, 160, 160] (batch, channels, height, width) + guard let array = try? MLMultiArray(shape: [1, 3, NSNumber(value: height), NSNumber(value: width)], dataType: .float32) else { + return nil + } + + // Create CGContext to read pixel data + guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil } + var rawData = [UInt8](repeating: 0, count: width * height * 4) + + guard let context = CGContext(data: &rawData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { + return nil + } + + context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) + + // Convert RGB to MLMultiArray (normalized to [0, 1]) + // FaceNet expects [batch, channels, height, width] + for y in 0.. = [] + + print("Running ASR with speaker detection on 60s clip...") + + SFSpeechRecognizer.requestAuthorization { status in + guard status == .authorized else { + print("Authorization denied") + semaphore.signal() + return + } + + let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))! + guard recognizer.isAvailable else { + print("Recognizer not available") + semaphore.signal() + return + } + + let request = SFSpeechURLRecognitionRequest(url: URL(fileURLWithPath: testFile)) + request.shouldReportPartialResults = false + request.requiresOnDeviceRecognition = true + request.taskHint = .dictation + + let task = recognizer.recognitionTask(with: request) { result, error in + if let error = error { + print("Recognition error: \(error.localizedDescription)") + } else if let result = result, result.isFinal { + let text = result.bestTranscription.formattedString + print("Text: \(text.prefix(200))") + print("Segments: \(result.bestTranscription.segments.count)") + + // Check each segment for speaker metadata + if #available(macOS 14, *) { + for (i, seg) in result.bestTranscription.segments.enumerated() { + // Access metadata via KVC since it might be a private API + let md = seg.value(forKey: "metadata") as? NSObject + if let md = md { + let speakerId = md.value(forKey: "speakerID") as? String + let speakerName = md.value(forKey: "speakerName") as? String + let confidence = md.value(forKey: "speakerConfidence") as? Double + + if let sid = speakerId { + detectedSpeakers.insert(sid) + if i < 5 || i % 20 == 0 { + print(" Seg[\(i)] speaker=\(sid) name=\(speakerName ?? "?") conf=\(confidence ?? 0) text=\"\(seg.substring.prefix(40))\"") + } + } + } + } + + print("\nUnique speakers detected: \(detectedSpeakers)") + if detectedSpeakers.isEmpty { + print("⚠️ No speaker metadata found in recognition results") + } + } else { + print("macOS 14+ required for speaker metadata") + } + } + semaphore.signal() + } + + // Wait + while semaphore.wait(timeout: .now()) == .timedOut { + RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1)) + } + task.cancel() + } + + semaphore.wait() + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/swift_appearance_expansion.swift b/installer/build/MomentryCore/tools/cli/swift/swift_appearance_expansion.swift new file mode 100644 index 00000000..b22e422e --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/swift_appearance_expansion.swift @@ -0,0 +1,332 @@ +import Foundation +import Vision +import ArgumentParser +import AVFoundation + +/// Swift Appearance Expansion Processor V2 +/// +/// Reads pose.json and extracts colors at keypoint positions. +/// +/// Algorithm: +/// 1. Load pose.json, get frames with trace_id +/// 2. For each pose frame, extract colors at keypoint positions +/// 3. Record overall brightness for lighting adjustment +/// 4. Expand outward, stop when 3 consecutive frames have low similarity +/// 5. Output at 8Hz sampling +/// +/// Key Concepts: +/// - Appearance = colors at body part positions (head, torso, legs, feet) +/// - Used for tracking and agent search ("person wearing red shirt") +/// - Approximate colors are sufficient for top-K search +@main +struct SwiftAppearanceExpansion: ParsableCommand { + @Argument(help: "Video file path") + var videoPath: String + + @Argument(help: "Input pose.json path") + var posePath: String + + @Argument(help: "Output appearance.json path") + var outputPath: String + + @Option(name: .long, help: "UUID for logging") + var uuid: String = "" + + @Option(name: .long, help: "Consecutive miss threshold (default: 3)") + var missThreshold: Int = 3 + + @Option(name: .long, help: "Color sampling radius (default: 15)") + var colorRadius: Int = 15 + + mutating func run() throws { + let startTime = Date() + print("[AppearanceExpansion] Starting appearance extraction from pose: \(videoPath)") + + // Load pose.json + guard let poseData = try? Data(contentsOf: URL(fileURLWithPath: posePath)) else { + print("[AppearanceExpansion] ERROR: Cannot read \(posePath)") + return + } + + guard let poseJson = try? JSONSerialization.jsonObject(with: poseData) as? [String: Any] else { + print("[AppearanceExpansion] ERROR: Invalid JSON in \(posePath)") + return + } + + // Extract frames with trace_id from pose + var poseFrameDict: [Int: [String: Any]] = [:] // frame -> pose data with trace_id + + if let frames = poseJson["frames"] as? [[String: Any]] { + for frameData in frames { + guard let frameNum = frameData["frame"] as? Int else { continue } + poseFrameDict[frameNum] = frameData + } + } + + print("[AppearanceExpansion] Found \(poseFrameDict.count) pose frames in \(posePath)") + + if poseFrameDict.isEmpty { + print("[AppearanceExpansion] No pose frames found, skipping") + let emptyOutput: [String: Any] = ["frame_count": 0, "fps": 0.0, "frames": []] + let jsonData = try JSONSerialization.data(withJSONObject: emptyOutput, options: []) + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + return + } + + // Get video info + let url = URL(fileURLWithPath: videoPath) + let asset = AVAsset(url: url) + guard let videoTrack = asset.tracks(withMediaType: .video).first else { + print("[AppearanceExpansion] ERROR: No video track") + return + } + + let fps = videoTrack.nominalFrameRate + let duration = CMTimeGetSeconds(asset.duration) + let totalFrames = Int(duration * Double(fps)) + let sampleInterval = max(1, Int(floor(Double(fps) / 8.0))) + + print("[AppearanceExpansion] Video: \(fps)fps, \(totalFrames) frames, 8Hz interval=\(sampleInterval)") + + // Track appearance frames + var appearanceFrameDict: [Int: [String: Any]] = [:] + + // Setup asset reader + let outputSettings: [String: Any] = [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA + ] + + let reader = try AVAssetReader(asset: asset) + let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings) + trackOutput.alwaysCopiesSampleData = false + reader.add(trackOutput) + + guard reader.startReading() else { + print("[AppearanceExpansion] ERROR: Cannot start reader") + return + } + + // Process frames + var frameIndex = 0 + + while let sampleBuffer = trackOutput.copyNextSampleBuffer() { + defer { frameIndex += 1 } + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + continue + } + + // Check if this is a pose frame + if let poseData = poseFrameDict[frameIndex] { + let seconds = Double(frameIndex) / Double(fps) + + // Extract colors at keypoint positions + let colors = extractColorsAtKeypoints(pixelBuffer: pixelBuffer, poseData: poseData, radius: colorRadius) + + // Calculate overall brightness + let brightness = calculateBrightness(pixelBuffer: pixelBuffer) + + // Get trace_id from pose (inherit) + let traceId = poseData["trace_id"] as? Int ?? 0 + + appearanceFrameDict[frameIndex] = [ + "frame": frameIndex, + "timestamp": seconds, + "trace_id": traceId, + "brightness": brightness, + "colors": colors + ] + } + + // Progress logging + if frameIndex % 5000 == 0 { + let elapsed = Date().timeIntervalSince(startTime) + print("[AppearanceExpansion] Frame \(frameIndex)/\(totalFrames), \(appearanceFrameDict.count) appearances, \(Int(elapsed))s") + fflush(stdout) + } + } + + reader.cancelReading() + + print("[AppearanceExpansion] Extraction done: \(appearanceFrameDict.count) frames with appearance") + + // 8Hz sampling output + var outputFrames: [[String: Any]] = [] + let sortedAppearanceFrames = appearanceFrameDict.keys.sorted() + + var targetFrame = 0 + while targetFrame < totalFrames { + // Find closest appearance frame to target + var closestFrame: Int? = nil + var closestDist = Int.max + + for appFrame in sortedAppearanceFrames { + let dist = abs(appFrame - targetFrame) + if dist < closestDist && dist <= sampleInterval { + closestDist = dist + closestFrame = appFrame + } + } + + if let cf = closestFrame, let data = appearanceFrameDict[cf] { + outputFrames.append(data) + } + + targetFrame += sampleInterval + } + + // Write output + let output: [String: Any] = [ + "frame_count": outputFrames.count, + "fps": Double(fps), + "frames": outputFrames + ] + + let jsonData = try JSONSerialization.data(withJSONObject: output, options: []) + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + + let elapsed = Date().timeIntervalSince(startTime) + print("[AppearanceExpansion] Done: \(outputFrames.count) frames at 8Hz, \(String(format: "%.1f", elapsed))s → \(outputPath)") + } + + /// Extract colors at keypoint positions + func extractColorsAtKeypoints(pixelBuffer: CVPixelBuffer, poseData: [String: Any], radius: Int) -> [String: [Int]] { + let imgW = CVPixelBufferGetWidth(pixelBuffer) + let imgH = CVPixelBufferGetHeight(pixelBuffer) + + CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly) + defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) } + + guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { + return [:] + } + + let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) + let buffer = baseAddress.bindMemory(to: UInt8.self, capacity: bytesPerRow * imgH) + + var colors: [String: [Int]] = [:] + + // Define keypoint groups for body parts + let bodyParts: [String: [String]] = [ + "head": ["nose", "left_eye", "right_eye", "left_ear", "right_ear"], + "torso": ["left_shoulder", "right_shoulder"], + "legs": ["left_hip", "right_hip", "left_knee", "right_knee"], + "feet": ["left_ankle", "right_ankle"] + ] + + // Extract color for each body part + for (partName, keypointNames) in bodyParts { + var totalR = 0, totalG = 0, totalB = 0 + var count = 0 + + // Get persons array from pose data + if let persons = poseData["persons"] as? [[String: Any]] { + for person in persons { + if let keypoints = person["keypoints"] as? [[String: Any]] { + for kp in keypoints { + guard let name = kp["name"] as? String, + keypointNames.contains(name), + let x = kp["x"] as? Double, + let y = kp["y"] as? Double, + let confidence = kp["confidence"] as? Double, + confidence > 0.3 else { continue } + + // Get average color around keypoint + let color = getAverageColor( + buffer: buffer, + bytesPerRow: bytesPerRow, + imgW: imgW, + imgH: imgH, + centerX: Int(x), + centerY: Int(y), + radius: radius + ) + + totalR += color.0 + totalG += color.1 + totalB += color.2 + count += 1 + } + } + } + } + + if count > 0 { + colors[partName] = [totalR / count, totalG / count, totalB / count] + } + } + + return colors + } + + /// Get average color around a position + func getAverageColor( + buffer: UnsafeMutablePointer, + bytesPerRow: Int, + imgW: Int, + imgH: Int, + centerX: Int, + centerY: Int, + radius: Int + ) -> (Int, Int, Int) { + let x1 = max(0, centerX - radius) + let x2 = min(imgW - 1, centerX + radius) + let y1 = max(0, centerY - radius) + let y2 = min(imgH - 1, centerY + radius) + + var totalR = 0, totalG = 0, totalB = 0, count = 0 + + for y in y1...y2 { + let rowStart = y * bytesPerRow + for x in x1...x2 { + let offset = rowStart + x * 4 + totalB += Int(buffer[offset]) + totalG += Int(buffer[offset + 1]) + totalR += Int(buffer[offset + 2]) + count += 1 + } + } + + if count > 0 { + return (totalR / count, totalG / count, totalB / count) + } + return (0, 0, 0) + } + + /// Calculate overall brightness of frame + func calculateBrightness(pixelBuffer: CVPixelBuffer) -> Double { + let imgW = CVPixelBufferGetWidth(pixelBuffer) + let imgH = CVPixelBufferGetHeight(pixelBuffer) + + CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly) + defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) } + + guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { + return 0.0 + } + + let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) + let buffer = baseAddress.bindMemory(to: UInt8.self, capacity: bytesPerRow * imgH) + + var totalBrightness = 0.0 + var count = 0 + + // Sample every 10 pixels for speed + for y in stride(from: 0, to: imgH, by: 10) { + let rowStart = y * bytesPerRow + for x in stride(from: 0, to: imgW, by: 10) { + let offset = rowStart + x * 4 + let b = Double(buffer[offset]) + let g = Double(buffer[offset + 1]) + let r = Double(buffer[offset + 2]) + + // Calculate luminance + let luminance = 0.299 * r + 0.587 * g + 0.114 * b + totalBrightness += luminance / 255.0 + count += 1 + } + } + + return count > 0 ? totalBrightness / Double(count) : 0.0 + } +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/swift/swift_cut_test.swift b/installer/build/MomentryCore/tools/cli/swift/swift_cut_test.swift new file mode 100644 index 00000000..fdff030f --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/swift_cut_test.swift @@ -0,0 +1,191 @@ +import Foundation +import AVFoundation +import ArgumentParser +import Accelerate + +/// POC: Swift-based scene cut detection using AVFoundation histogram analysis +/// Compared against Python PySceneDetect ContentDetector (threshold=27) +@main +struct SwiftCutTest: ParsableCommand { + @Argument(help: "Video file path") + var inputPath: String + + @Argument(help: "Output JSON path (optional)") + var outputPath: String? + + @Option(name: .long, help: "Detection threshold (higher= fewer cuts, default 0.3)") + var threshold: Double = 0.3 + + @Option(name: .long, help: "Sample interval in frames (default=1)") + var sampleInterval: Int = 1 + + mutating func run() throws { + let startTime = Date() + print("=== Swift Scene Cut Detection POC ===") + #if arch(arm64) + print("HW: Apple Silicon ✅ (ANE available)") + #endif + + let url = URL(fileURLWithPath: inputPath) + let asset = AVAsset(url: url) + + guard let videoTrack = asset.tracks(withMediaType: .video).first else { + print("Error: No video track found"); return + } + + let duration = asset.duration.seconds + let fps = videoTrack.nominalFrameRate + let totalFrames = Int(duration * Double(fps)) + print("Video: \(inputPath)") + print("Duration: \(String(format: "%.1f", duration))s") + print("FPS: \(String(format: "%.1f", fps))") + print("Total frames: \(totalFrames)") + print("Threshold: \(String(format: "%.2f", threshold))") + print("Sample interval: \(sampleInterval)") + + // Read frame histogram data using AVAssetReader + guard let reader = try? AVAssetReader(asset: asset) else { + print("Error: Cannot create asset reader"); return + } + + let settings: [String: Any] = [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, + kCVPixelBufferWidthKey as String: 320, // downscale for speed + kCVPixelBufferHeightKey as String: 180, + ] + let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: settings) + reader.add(trackOutput) + reader.startReading() + + var frameIndex = 0 + var prevHistogram: [Float]? + var scenes: [(start: Double, end: Double)] = [] + var sceneStart: Double = 0 + var diffs: [(frame: Int, diff: Float)] = [] + + let frameStep = sampleInterval + var lastPrint = 0 + + while reader.status == .reading { + guard let sampleBuffer = trackOutput.copyNextSampleBuffer() else { break } + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + CMSampleBufferInvalidate(sampleBuffer); continue + } + + if frameIndex % frameStep == 0 { + let timestamp = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) + + // Compute histogram + let histogram = computeLuminanceHistogram(pixelBuffer: pixelBuffer) + + if let prev = prevHistogram { + let diff = histogramDifference(prev, histogram) + + if diff > Float(threshold) { + // Scene cut detected + let sceneEnd = timestamp + scenes.append((start: sceneStart, end: sceneEnd)) + sceneStart = timestamp + diffs.append((frame: frameIndex, diff: diff)) + + if scenes.count % 50 == 0 { + print(" Scenes so far: \(scenes.count) at frame \(frameIndex)/\(totalFrames)") + } + } + } + prevHistogram = histogram + } + + frameIndex += 1 + CMSampleBufferInvalidate(sampleBuffer) + + // Progress every 5% + let pct = Int(Float(frameIndex) / Float(totalFrames) * 100) + if pct >= lastPrint + 5 { + print(" Progress: \(pct)% (\(frameIndex)/\(totalFrames) frames)") + lastPrint = pct + } + } + + // Add last scene + if sceneStart < duration { + scenes.append((start: sceneStart, end: duration)) + } + + let elapsed = Date().timeIntervalSince(startTime) + print("\n=== Results ===") + print("Scenes detected: \(scenes.count)") + print("Time: \(String(format: "%.2f", elapsed))s") + if totalFrames > 0 { + let rtf = elapsed / duration + print("RTF: \(String(format: "%.3f", rtf))x") + } + print("Last 5 cuts:") + for s in scenes.suffix(5) { + print(" \(String(format: "%.1f", s.start))s - \(String(format: "%.1f", s.end))s") + } + + // Output JSON if requested + if let outPath = outputPath { + let outputDict: [String: Any] = [ + "scenes": scenes.map { ["start_time": $0.start, "end_time": $0.end] }, + "metadata": [ + "video_path": inputPath, + "duration": duration, + "fps": fps, + "total_frames": totalFrames, + "threshold": threshold, + "sample_interval": sampleInterval, + "processing_time": elapsed, + "rtf": elapsed / duration, + ], + "diffs": diffs.map { ["frame": $0.frame, "diff": String(format: "%.4f", $0.diff)] } + ] + if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) { + try jsonData.write(to: URL(fileURLWithPath: outPath)) + print("Output written to: \(outPath)") + } + } + } + + func computeLuminanceHistogram(pixelBuffer: CVPixelBuffer) -> [Float] { + CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly) + defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) } + + let width = CVPixelBufferGetWidth(pixelBuffer) + let height = CVPixelBufferGetHeight(pixelBuffer) + let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) + let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer)! + + var histogram = [Float](repeating: 0, count: 64) // 64 bins for speed + + for y in 0.. Float { + var diff: Float = 0 + for i in 0.. ([Double], [Double], [Double]) { + let imgW = CVPixelBufferGetWidth(pixelBuffer) + let imgH = CVPixelBufferGetHeight(pixelBuffer) + + CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly) + defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) } + + guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { + return ([], [], []) + } + + let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) + let buffer = baseAddress.bindMemory(to: UInt8.self, capacity: bytesPerRow * imgH) + + // Determine ROI + let x1 = bbox.map { max(0, $0["x"] ?? 0) } ?? 0 + let y1 = bbox.map { max(0, $0["y"] ?? 0) } ?? 0 + let x2 = bbox.map { min(imgW, ($0["x"] ?? 0) + ($0["width"] ?? imgW)) } ?? imgW + let y2 = bbox.map { min(imgH, ($0["y"] ?? 0) + ($0["height"] ?? imgH)) } ?? imgH + + // Histogram bins: H=30 (0-180), S=32 (0-256), V=32 (0-256) + var hHist = Array(repeating: 0.0, count: 30) + var sHist = Array(repeating: 0.0, count: 32) + var vHist = Array(repeating: 0.0, count: 32) + var totalPixels = 0 + + for y in y1.. 0.001 { + s = delta / maxVal + if maxVal == r { + h = 60.0 * ((g - b) / 255.0 / delta) + } else if maxVal == g { + h = 60.0 * (2.0 + (b - r) / 255.0 / delta) + } else { + h = 60.0 * (4.0 + (r - g) / 255.0 / delta) + } + if h < 0 { h += 360.0 } + } else { + s = 0 + } + + // Bin: H 0-180 -> 30 bins, S 0-256 -> 32 bins, V 0-256 -> 32 bins + let hBin = min(29, Int(h / 6.0)) + let sBin = min(31, Int(s * 32.0)) + let vBin = min(31, Int(v * 32.0)) + + hHist[hBin] += 1 + sHist[sBin] += 1 + vHist[vBin] += 1 + totalPixels += 1 + } + } + + // Normalize + let hSum = hHist.reduce(0, +) + let sSum = sHist.reduce(0, +) + let vSum = vHist.reduce(0, +) + + if hSum > 0 { hHist = hHist.map { $0 / hSum } } + if sSum > 0 { sHist = sHist.map { $0 / sSum } } + if vSum > 0 { vHist = vHist.map { $0 / vSum } } + + return (hHist, sHist, vHist) +} + +/// Compute Bhattacharyya coefficient between two normalized histograms +/// Returns similarity score in [0, 1] +func histogramSimilarity(hist1: [Double], hist2: [Double]) -> Double { + guard hist1.count == hist2.count, !hist1.isEmpty else { return 0.0 } + + var sum = 0.0 + for i in 0.. 0 && b > 0 { + sum += sqrt(a * b) + } + } + return sum // Bhattacharyya coefficient [0, 1] +} + +/// Combined HSV similarity (average of H, S, V similarities) +func combinedHSVSimilarity(hist1: ([Double], [Double], [Double]), hist2: ([Double], [Double], [Double])) -> Double { + let hSim = histogramSimilarity(hist1: hist1.0, hist2: hist2.0) + let sSim = histogramSimilarity(hist1: hist1.1, hist2: hist2.1) + let vSim = histogramSimilarity(hist1: hist1.2, hist2: hist2.2) + return (hSim + sSim + vSim) / 3.0 +} + +// MARK: - Frame processing helpers + +/// Result from processing a single frame for face detection +struct FrameFaceResult { + let hasFace: Bool + let faces: [[String: Any]] + let landmarkObservations: [VNFaceObservation] +} + +/// Result from processing a single frame for pose detection +struct FramePoseResult { + let hasPose: Bool + let persons: [[String: Any]] +} + +/// Process a single frame for face detection +func processFrameForFace(pixelBuffer: CVPixelBuffer, fps: Float) -> FrameFaceResult { + let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer)) + let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer)) + + let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]) + let faceReq = VNDetectFaceRectanglesRequest() + let lmReq = VNDetectFaceLandmarksRequest() + + do { + try handler.perform([faceReq, lmReq]) + } catch { + return FrameFaceResult(hasFace: false, faces: [], landmarkObservations: []) + } + + let faceObservations = faceReq.results ?? [] + let landmarkObservations = lmReq.results ?? [] + + var faces: [[String: Any]] = [] + var hasFace = false + + let MIN_CONFIDENCE = 0.6 + let MIN_SIZE = 20 + + if !faceObservations.isEmpty || !landmarkObservations.isEmpty { + hasFace = true + + for lmObs in landmarkObservations { + let lmConf = Double(lmObs.confidence) + if lmConf < MIN_CONFIDENCE { continue } + + let bb = lmObs.boundingBox + let faceW = Int(bb.size.width * imgW) + let faceH = Int(bb.size.height * imgH) + if faceW < MIN_SIZE || faceH < MIN_SIZE { continue } + + let faceX = Int(bb.origin.x * imgW) + let faceY = Int((1.0 - bb.origin.y - bb.size.height) * imgH) + + var faceData: [String: Any] = [ + "bbox": ["x": max(0, faceX), "y": max(0, faceY), + "width": faceW, "height": faceH], + "confidence": Double(lmObs.confidence), + "captureQuality": Double(lmObs.value(forKey: "faceCaptureQuality") as? Double ?? 0), + ] + + if let yaw = lmObs.yaw?.doubleValue, + let roll = lmObs.roll?.doubleValue { + var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw] + if let pitch = lmObs.pitch?.doubleValue { + poseInfo["pitch"] = pitch + } + faceData["pose"] = poseInfo + } + + if let lms = lmObs.landmarks { + let imgSize = CGSize(width: imgW, height: imgH) + let leftEye = lms.leftEye?.pointsInImage(imageSize: imgSize) ?? [] + let rightEye = lms.rightEye?.pointsInImage(imageSize: imgSize) ?? [] + let nose = lms.nose?.pointsInImage(imageSize: imgSize) ?? [] + + if !leftEye.isEmpty || !rightEye.isEmpty || !nose.isEmpty { + var lm: [String: [[Double]]] = [:] + if !leftEye.isEmpty { + lm["left_eye"] = leftEye.map { [Double($0.x), Double(imgH - $0.y)] } + } + if !rightEye.isEmpty { + lm["right_eye"] = rightEye.map { [Double($0.x), Double(imgH - $0.y)] } + } + if !nose.isEmpty { + lm["nose"] = nose.map { [Double($0.x), Double(imgH - $0.y)] } + } + faceData["landmarks"] = lm + } + + let outer = lms.outerLips?.pointsInImage(imageSize: imgSize) ?? [] + let inner = lms.innerLips?.pointsInImage(imageSize: imgSize) ?? [] + if !outer.isEmpty || !inner.isEmpty { + faceData["lips"] = [ + "outer_lips": outer.map { [Double($0.x), Double(imgH - $0.y)] }, + "inner_lips": inner.map { [Double($0.x), Double(imgH - $0.y)] } + ] + } + } + + faces.append(faceData) + } + + for faceObs in faceObservations { + let fBB = faceObs.boundingBox + var matched = false + for lmObs in landmarkObservations { + let lBB = lmObs.boundingBox + let ix = max(fBB.origin.x, lBB.origin.x) + let iy = max(fBB.origin.y, lBB.origin.y) + let iw = min(fBB.maxX, lBB.maxX) - ix + let ih = min(fBB.maxY, lBB.maxY) - iy + if iw <= 0 || ih <= 0 { continue } + let intersection = iw * ih + let union = fBB.width * fBB.height + lBB.width * lBB.height - intersection + if intersection / union > 0.3 { + matched = true + break + } + } + if matched { continue } + + if faceObs.confidence < MIN_CONFIDENCE { continue } + + let faceW = Int(fBB.size.width * imgW) + let faceH = Int(fBB.size.height * imgH) + if faceW < MIN_SIZE || faceH < MIN_SIZE { continue } + + let faceX = Int(fBB.origin.x * imgW) + let faceY = Int((1.0 - fBB.origin.y - fBB.size.height) * imgH) + + var faceData: [String: Any] = [ + "bbox": ["x": max(0, faceX), "y": max(0, faceY), + "width": faceW, "height": faceH], + "confidence": Double(faceObs.confidence), + "captureQuality": Double(faceObs.faceCaptureQuality ?? 0), + ] + if let yaw = faceObs.yaw?.doubleValue, + let roll = faceObs.roll?.doubleValue { + var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw] + if let pitch = faceObs.pitch?.doubleValue { + poseInfo["pitch"] = pitch + } + faceData["pose"] = poseInfo + } + faces.append(faceData) + } + } + + return FrameFaceResult(hasFace: hasFace, faces: faces, landmarkObservations: landmarkObservations) +} + +/// Process a single frame for pose detection +func processFrameForPose(pixelBuffer: CVPixelBuffer, landmarkObservations: [VNFaceObservation]? = nil) -> FramePoseResult { + let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer)) + let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer)) + + let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]) + let bodyReq = VNDetectHumanBodyPoseRequest() + + do { + try handler.perform([bodyReq]) + } catch { + return FramePoseResult(hasPose: false, persons: []) + } + + let jointNames: [VNHumanBodyPoseObservation.JointName] = [ + .nose, .leftEye, .rightEye, .leftEar, .rightEar, + .neck, .root, + .leftShoulder, .rightShoulder, + .leftElbow, .rightElbow, + .leftWrist, .rightWrist, + .leftHip, .rightHip, + .leftKnee, .rightKnee, + .leftAnkle, .rightAnkle, + ] + + var persons: [[String: Any]] = [] + + // If we have face landmarks, extract pose keypoints from them + let lmObs = landmarkObservations?.first + if let lmObs = lmObs, let lms = lmObs.landmarks { + let lmConf = Double(lmObs.confidence) + if lmConf >= 0.6 { + let imgSize = CGSize(width: imgW, height: imgH) + var keypoints: [[String: Any]] = [] + + if let nosePoints = lms.nose?.pointsInImage(imageSize: imgSize) { + for pt in nosePoints { + keypoints.append([ + "name": "nose", + "x": Double(pt.x), + "y": Double(imgH - pt.y), + "confidence": lmConf + ]) + } + } + + if let leftEyePoints = lms.leftEye?.pointsInImage(imageSize: imgSize) { + for pt in leftEyePoints { + keypoints.append([ + "name": "left_eye", + "x": Double(pt.x), + "y": Double(imgH - pt.y), + "confidence": lmConf + ]) + } + } + + if let rightEyePoints = lms.rightEye?.pointsInImage(imageSize: imgSize) { + for pt in rightEyePoints { + keypoints.append([ + "name": "right_eye", + "x": Double(pt.x), + "y": Double(imgH - pt.y), + "confidence": lmConf + ]) + } + } + + if !keypoints.isEmpty { + persons.append([ + "keypoints": keypoints, + "bbox": ["x": 0, "y": 0, "width": 0, "height": 0] + ]) + } + } + } + + // Also process body pose detections + let poses = bodyReq.results ?? [] + for pose in poses { + var keypoints: [[String: Any]] = [] + var minX = CGFloat.greatestFiniteMagnitude + var minY = CGFloat.greatestFiniteMagnitude + var maxX: CGFloat = 0 + var maxY: CGFloat = 0 + + for joint in jointNames { + if let point = try? pose.recognizedPoint(joint) { + let desc = String(describing: joint.rawValue) + var rawName = desc + .replacingOccurrences(of: "VNRecognizedPointKey(_rawValue: ", with: "") + .replacingOccurrences(of: ")", with: "") + .trimmingCharacters(in: .whitespaces) + let nameMap: [String: String] = [ + "head_joint": "nose", + "left_eye_joint": "left_eye", + "right_eye_joint": "right_eye", + "left_ear_joint": "left_ear", + "right_ear_joint": "right_ear", + "neck_1_joint": "neck", + "left_shoulder_1_joint": "left_shoulder", + "right_shoulder_1_joint": "right_shoulder", + "left_elbow_1_joint": "left_elbow", + "right_elbow_1_joint": "right_elbow", + "left_hand_joint": "left_wrist", + "right_hand_joint": "right_wrist", + "left_hip_1_joint": "left_hip", + "right_hip_1_joint": "right_hip", + "left_knee_1_joint": "left_knee", + "right_knee_1_joint": "right_knee", + "left_ankle_1_joint": "left_ankle", + "right_ankle_1_joint": "right_ankle", + "center_hip_joint": "root", + ] + if let mapped = nameMap[rawName] { + rawName = mapped + } + let px = point.location.x * CGFloat(imgW) + let py = CGFloat(imgH) - point.location.y * CGFloat(imgH) + keypoints.append([ + "name": rawName.isEmpty ? "\(joint)" : rawName, + "x": px, + "y": py, + "confidence": point.confidence, + ]) + if point.confidence > 0.1 { + minX = min(minX, px) + minY = min(minY, py) + maxX = max(maxX, px) + maxY = max(maxY, py) + } + } + } + + var bbox: [String: Any] = ["x": 0, "y": 0, "width": 0, "height": 0] + if maxX > minX { + bbox = [ + "x": Int(minX), + "y": Int(minY), + "width": Int(maxX - minX), + "height": Int(maxY - minY), + ] + } + + persons.append(["keypoints": keypoints, "bbox": bbox]) + } + + let hasPose = !persons.isEmpty + return FramePoseResult(hasPose: hasPose, persons: persons) +} + +// MARK: - Main processor + +/// Swift Face+Pose+Appearance Processor - three-stage pipeline +/// Stage 1: 8Hz sampled Face detection +/// Stage 2: Pose expansion (forward/backward until 3 consecutive misses) +/// Stage 3: Appearance expansion (HSV histogram similarity, 3 consecutive < 0.5) +/// Output: face.json, pose.json, appearance.json (all 8Hz sampled) +@main +struct SwiftFacePose: ParsableCommand { + @Argument(help: "Video file path") + var inputPath: String + + @Argument(help: "Output JSON path for face detection") + var faceOutput: String + + @Argument(help: "Output JSON path for pose detection") + var poseOutput: String + + @Argument(help: "Output JSON path for appearance detection") + var appearanceOutput: String + + @Option(name: .long, help: "Sample interval (frames, default=30)") + var sampleInterval: Int = 30 + + @Option(name: .long, help: "UUID for logging") + var uuid: String = "" + + // Expansion parameters + let expansionMissThreshold = 3 // consecutive misses to stop expansion + let appearanceSimilarityThreshold = 0.5 // HSV histogram similarity threshold + + mutating func run() throws { + let startTime = Date() + print("[SwiftFacePose] Vision face+pose+appearance detection: \(inputPath)") + + let url = URL(fileURLWithPath: inputPath) + let asset = AVAsset(url: url) + + guard let videoTrack = asset.tracks(withMediaType: .video).first else { + print("[SwiftFacePose] No video track found") + return + } + + let fps = videoTrack.nominalFrameRate + let duration = CMTimeGetSeconds(asset.duration) + let totalFrames = Int(duration * Double(fps)) + print("[SwiftFacePose] Video: \(Int(videoTrack.naturalSize.width))x\(Int(videoTrack.naturalSize.height)), \(String(format: "%.1f", fps))fps, \(totalFrames) frames, interval=\(sampleInterval)") + + let outputSettings: [String: Any] = [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA + ] + + // ============================================================ + // Stage 1: 8Hz sampled Face detection + Pose = Face + // ============================================================ + print("[SwiftFacePose] Stage 1: 8Hz face sampling + pose=face...") + var faceFrames: [[String: Any]] = [] + var faceFrameSet = Set() + var poseFrameDict: [Int: [String: Any]] = [:] + var poseFrameSet = Set() + + do { + let reader = try AVAssetReader(asset: asset) + let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings) + trackOutput.alwaysCopiesSampleData = false + reader.add(trackOutput) + guard reader.startReading() else { + print("[SwiftFacePose] Failed to start reader for stage 1") + return + } + + var frameIndex = 0 + var processedCount = 0 + while let sampleBuffer = trackOutput.copyNextSampleBuffer() { + defer { frameIndex += 1 } + + if frameIndex % sampleInterval != 0 { + continue + } + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + continue + } + + let result = processFrameForFace(pixelBuffer: pixelBuffer, fps: fps) + + if result.hasFace && !result.faces.isEmpty { + let seconds = Double(frameIndex) / Double(fps) + faceFrames.append([ + "frame": frameIndex, + "timestamp": seconds, + "faces": result.faces, + ]) + faceFrameSet.insert(frameIndex) + + // Stage 1: Pose = Face (use face landmarks as pose keypoints) + let poseResult = processFrameForPose(pixelBuffer: pixelBuffer, landmarkObservations: result.landmarkObservations) + if poseResult.hasPose { + poseFrameDict[frameIndex] = [ + "frame": frameIndex, + "timestamp": seconds, + "persons": poseResult.persons, + ] + poseFrameSet.insert(frameIndex) + } + } + + processedCount += 1 + if processedCount % 100 == 0 { + let elapsed = Date().timeIntervalSince(startTime) + let totalSamples = totalFrames / sampleInterval + let pct = Int(Double(processedCount) / Double(totalSamples) * 100) + print("[SwiftFacePose] Stage 1: \(faceFrames.count) face frames, \(pct)% complete, \(Int(elapsed))s") + fflush(stdout) + } + } + reader.cancelReading() + } + + print("[SwiftFacePose] Stage 1 done: \(faceFrames.count) face frames, \(poseFrameDict.count) pose frames") + + // ============================================================ + // Stage 2: Pose expansion (from face frames, forward/backward) + // ============================================================ + print("[SwiftFacePose] Stage 2: Pose expansion...") + + // Full pass to detect pose on all frames + do { + let reader = try AVAssetReader(asset: asset) + let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings) + trackOutput.alwaysCopiesSampleData = false + reader.add(trackOutput) + guard reader.startReading() else { + print("[SwiftFacePose] Failed to start reader for stage 2") + return + } + + var frameIndex = 0 + var processedCount = 0 + var consecutiveMisses = 0 + let maxConsecutiveMisses = 300 // stop after 300 consecutive misses (10s at 30fps) + + while let sampleBuffer = trackOutput.copyNextSampleBuffer() { + defer { frameIndex += 1 } + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + continue + } + + // Check if we should process this frame: + // 1. It's near a face frame (within 300 frames) + // 2. Or we're in an expansion streak + let nearFaceFrame = faceFrameSet.contains { faceFrame in + abs(faceFrame - frameIndex) <= 300 + } + + if nearFaceFrame || consecutiveMisses < maxConsecutiveMisses { + let result = processFrameForPose(pixelBuffer: pixelBuffer) + let seconds = Double(frameIndex) / Double(fps) + + if result.hasPose { + poseFrameDict[frameIndex] = [ + "frame": frameIndex, + "timestamp": seconds, + "persons": result.persons, + ] + poseFrameSet.insert(frameIndex) + consecutiveMisses = 0 + } else { + // Try with face landmarks if this is a face frame + if faceFrameSet.contains(frameIndex) { + let faceResult = processFrameForFace(pixelBuffer: pixelBuffer, fps: fps) + if faceResult.hasFace { + let poseResult = processFrameForPose(pixelBuffer: pixelBuffer, landmarkObservations: faceResult.landmarkObservations) + if poseResult.hasPose { + poseFrameDict[frameIndex] = [ + "frame": frameIndex, + "timestamp": seconds, + "persons": poseResult.persons, + ] + poseFrameSet.insert(frameIndex) + consecutiveMisses = 0 + continue + } + } + } + consecutiveMisses += 1 + } + } + + processedCount += 1 + if processedCount % 5000 == 0 { + let elapsed = Date().timeIntervalSince(startTime) + print("[SwiftFacePose] Stage 2: \(poseFrameDict.count) pose frames, frame \(frameIndex), \(Int(elapsed))s") + fflush(stdout) + } + } + reader.cancelReading() + } + + print("[SwiftFacePose] Stage 2 done: \(poseFrameDict.count) pose frames") + + // ============================================================ + // Stage 3: Appearance expansion (from pose frames, HSV similarity) + // ============================================================ + print("[SwiftFacePose] Stage 3: Appearance expansion...") + var appearanceFrameDict: [Int: [String: Any]] = [:] + + // Full pass to detect appearance on all pose frames + var referenceHistograms: [Int: ([Double], [Double], [Double])] = [:] + var consecutiveMisses = 0 + let maxConsecutiveMisses = 300 // stop after 300 consecutive misses + + do { + let reader = try AVAssetReader(asset: asset) + let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings) + trackOutput.alwaysCopiesSampleData = false + reader.add(trackOutput) + guard reader.startReading() else { + print("[SwiftFacePose] Failed to start reader for stage 3") + return + } + + var frameIndex = 0 + var processedCount = 0 + + while let sampleBuffer = trackOutput.copyNextSampleBuffer() { + defer { frameIndex += 1 } + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + continue + } + + // Check if we should process this frame + let nearPoseFrame = poseFrameSet.contains { poseFrame in + abs(poseFrame - frameIndex) <= 300 + } + + if nearPoseFrame || consecutiveMisses < maxConsecutiveMisses { + // If this is a pose frame, compute reference histogram + if poseFrameSet.contains(frameIndex) { + let hist = computeHSVHistogram(pixelBuffer: pixelBuffer) + referenceHistograms[frameIndex] = hist + consecutiveMisses = 0 + + let poseData = poseFrameDict[frameIndex] + let seconds = Double(frameIndex) / Double(fps) + appearanceFrameDict[frameIndex] = [ + "frame": frameIndex, + "timestamp": seconds, + "persons": poseData?["persons"] ?? [], + "hsv_histogram": [hist.0, hist.1, hist.2], + ] + } else if !referenceHistograms.isEmpty { + // Check similarity with nearest reference + let nearestRef = referenceHistograms + .sorted { abs($0.key - frameIndex) < abs($1.key - frameIndex) } + .first + + if let (refFrame, refHist) = nearestRef { + let currentHist = computeHSVHistogram(pixelBuffer: pixelBuffer) + let similarity = combinedHSVSimilarity(hist1: currentHist, hist2: refHist) + + if similarity >= appearanceSimilarityThreshold { + let seconds = Double(frameIndex) / Double(fps) + // Find nearest pose data + let nearestPoseData = poseFrameDict[refFrame] + appearanceFrameDict[frameIndex] = [ + "frame": frameIndex, + "timestamp": seconds, + "persons": nearestPoseData?["persons"] ?? [], + "hsv_histogram": [currentHist.0, currentHist.1, currentHist.2], + ] + consecutiveMisses = 0 + } else { + consecutiveMisses += 1 + } + } + } + } + + processedCount += 1 + if processedCount % 5000 == 0 { + let elapsed = Date().timeIntervalSince(startTime) + print("[SwiftFacePose] Stage 3: \(appearanceFrameDict.count) appearance frames, frame \(frameIndex), \(Int(elapsed))s") + fflush(stdout) + } + } + reader.cancelReading() + } + + print("[SwiftFacePose] Stage 3 done: \(appearanceFrameDict.count) appearance frames") + + // ============================================================ + // Stage 4: 8Hz sampling output + // ============================================================ + print("[SwiftFacePose] Stage 4: 8Hz sampling output...") + + // Sample face frames (already at 8Hz) + let outputFaceFrames = faceFrames + + // Convert poseFrameDict to sorted array for efficient search + let sortedPoseFrames = poseFrameDict.sorted { $0.key < $1.key }.map { $0.value } + let sortedPoseFrameNumbers = poseFrameDict.keys.sorted() + + // Sample pose frames (take closest to 8Hz grid) + var outputPoseFrames: [[String: Any]] = [] + var frameIdx = 0 + while frameIdx < totalFrames { + // Binary search for closest pose frame + let searchRadius = sampleInterval // ±30 frames + let searchStart = max(0, frameIdx - searchRadius) + let searchEnd = min(totalFrames - 1, frameIdx + searchRadius) + + // Find closest pose frame in range + var closestPoseFrame: [String: Any]? + var closestDist = Int.max + + for f in searchStart...searchEnd { + if let data = poseFrameDict[f] { + let dist = abs(f - frameIdx) + if dist < closestDist { + closestDist = dist + closestPoseFrame = data + } + } + } + + // If no frame found in range, find the nearest one regardless of distance + if closestPoseFrame == nil { + for f in sortedPoseFrameNumbers { + let dist = abs(f - frameIdx) + if dist < closestDist { + closestDist = dist + closestPoseFrame = poseFrameDict[f] + } + } + } + + if let data = closestPoseFrame { + outputPoseFrames.append(data) + } + + frameIdx += sampleInterval + } + + // Sample appearance frames (take closest to 8Hz grid) + var outputAppearanceFrames: [[String: Any]] = [] + let sortedAppearanceFrameNumbers = appearanceFrameDict.keys.sorted() + + frameIdx = 0 + while frameIdx < totalFrames { + let searchRadius = sampleInterval // ±30 frames + let searchStart = max(0, frameIdx - searchRadius) + let searchEnd = min(totalFrames - 1, frameIdx + searchRadius) + + var closestAppearanceFrame: [String: Any]? + var closestDist = Int.max + + for f in searchStart...searchEnd { + if let data = appearanceFrameDict[f] { + let dist = abs(f - frameIdx) + if dist < closestDist { + closestDist = dist + closestAppearanceFrame = data + } + } + } + + // If no frame found in range, find the nearest one + if closestAppearanceFrame == nil { + for f in sortedAppearanceFrameNumbers { + let dist = abs(f - frameIdx) + if dist < closestDist { + closestDist = dist + closestAppearanceFrame = appearanceFrameDict[f] + } + } + } + + if let data = closestAppearanceFrame { + outputAppearanceFrames.append(data) + } + + frameIdx += sampleInterval + } + + // ============================================================ + // Write output files + // ============================================================ + + // face.json + let faceOutputDict: [String: Any] = [ + "frame_count": outputFaceFrames.count, + "fps": Double(fps), + "frames": outputFaceFrames, + ] + do { + let faceJson = try JSONSerialization.data(withJSONObject: faceOutputDict, options: []) + try faceJson.write(to: URL(fileURLWithPath: faceOutput)) + print("[SwiftFacePose] Face output written: \(faceOutput)") + } catch { + print("[SwiftFacePose] ERROR writing face output: \(error)") + } + + // pose.json + let poseOutputDict: [String: Any] = [ + "frame_count": outputPoseFrames.count, + "fps": Double(fps), + "frames": outputPoseFrames, + ] + do { + let poseJson = try JSONSerialization.data(withJSONObject: poseOutputDict, options: [.prettyPrinted]) + try poseJson.write(to: URL(fileURLWithPath: poseOutput)) + print("[SwiftFacePose] Pose output written: \(poseOutput)") + } catch { + print("[SwiftFacePose] ERROR writing pose output: \(error)") + } + + // appearance.json + let appearanceOutputDict: [String: Any] = [ + "frame_count": outputAppearanceFrames.count, + "fps": Double(fps), + "frames": outputAppearanceFrames, + ] + do { + let appearanceJson = try JSONSerialization.data(withJSONObject: appearanceOutputDict, options: [.prettyPrinted]) + try appearanceJson.write(to: URL(fileURLWithPath: appearanceOutput)) + print("[SwiftFacePose] Appearance output written: \(appearanceOutput)") + } catch { + print("[SwiftFacePose] ERROR writing appearance output: \(error)") + } + + let elapsed = Date().timeIntervalSince(startTime) + print("[SwiftFacePose] Done: \(outputFaceFrames.count) face, \(outputPoseFrames.count) pose, \(outputAppearanceFrames.count) appearance frames, \(String(format: "%.1f", elapsed))s") + } +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/swift/swift_hand.swift b/installer/build/MomentryCore/tools/cli/swift/swift_hand.swift new file mode 100644 index 00000000..232679a4 --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/swift_hand.swift @@ -0,0 +1,299 @@ +import Foundation +import Vision +import ArgumentParser +import AppKit +import AVFoundation + +/// Swift Hand Pose Processor +/// Uses Apple Vision Framework VNDetectHumanHandPoseRequest for 21 hand landmarks +@main +struct SwiftHandProcessor: ParsableCommand { + @Argument(help: "Input video path") + var inputPath: String + + @Argument(help: "Output JSON path") + var outputPath: String + + @Option(name: [.short, .long], help: "UUID for the file") + var uuid: String = "" + + @Option(name: [.short, .long], help: "Sample interval (frames)") + var sampleInterval: Int = 3 + + @Option(name: [.long], help: "Minimum confidence threshold") + var minConfidence: Double = 0.3 + + func run() throws { + print("[SwiftHand] Starting: \(inputPath)") + + let url = URL(fileURLWithPath: inputPath) + let asset = AVURLAsset(url: url) + + guard let track = asset.tracks(withMediaType: AVMediaType.video).first else { + print("[SwiftHand] Error: No video track"); return + } + + let duration = asset.duration.seconds + let fps = Double(track.nominalFrameRate) + + print("[SwiftHand] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", fps))") + + // Extract frames using ffmpeg (same approach as swift_pose) + let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("swift_hand_\(UUID().uuidString)") + let framesDir = tempDir.appendingPathComponent("frames") + try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true) + + let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path + print("[SwiftHand] Extracting frames...") + let extract = Process() + extract.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") + extract.arguments = ["-y", "-v", "quiet", "-i", inputPath, + "-vf", "select=not(mod(n\\,\(sampleInterval)))", + "-vsync", "vfr", "-q:v", "15", pattern] + try extract.run() + extract.waitUntilExit() + + let files = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? [] + let frameFiles = files.filter { $0.hasSuffix(".jpg") }.sorted() + print("[SwiftHand] Extracted \(frameFiles.count) frames") + + // Hand joint names (21 landmarks) + let jointNames: [VNHumanHandPoseObservation.JointName] = [ + .wrist, + .thumbTip, .thumbIP, .thumbMP, .thumbCMC, + .indexTip, .indexDIP, .indexPIP, .indexMCP, + .middleTip, .middleDIP, .middlePIP, .middleMCP, + .ringTip, .ringDIP, .ringPIP, .ringMCP, + .littleTip, .littleDIP, .littlePIP, .littleMCP, + ] + + var handFrames: [[String: Any]] = [] + var lastProgress = 0 + + for (i, fname) in frameFiles.enumerated() { + let imgPath = framesDir.appendingPathComponent(fname).path + guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)), + let img = NSImage(data: imgData), + let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue } + + let frameNum = Int(fname.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? (i * sampleInterval) + let timestamp = Double(frameNum) / fps + let w = cgImage.width + let h = cgImage.height + + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) + let req = VNDetectHumanHandPoseRequest() + try? handler.perform([req]) + + guard let hands = req.results, !hands.isEmpty else { continue } + + var persons: [[String: Any]] = [] + + for (handIdx, hand) in hands.enumerated() { + if Float(hand.confidence) < Float(minConfidence) { + continue + } + + var landmarks: [[String: Any]] = [] + + for joint in jointNames { + if let point = try? hand.recognizedPoint(joint) { + let desc = String(describing: joint.rawValue.rawValue) + let rawName = desc + .replacingOccurrences(of: "VNRecognizedPointKey(_rawValue: ", with: "") + .replacingOccurrences(of: ")", with: "") + .trimmingCharacters(in: .whitespaces) + + let name = mapJointName(rawName) + let px = Float(point.location.x) * Float(w) + let py = Float(h) - Float(point.location.y) * Float(h) // Y-flip to Top-Left + let conf = Float(point.confidence) + + if conf > 0.1 { + landmarks.append([ + "name": name, + "x": px, + "y": py, + "confidence": conf + ]) + } + } + } + + // Gesture detection + let gesture = detectGesture(hand) + + let handType = handIdx == 0 ? "left" : "right" + + persons.append([ + "person_id": handIdx, + "hand_type": handType, + "confidence": Float(hand.confidence), + "landmarks": landmarks, + "num_landmarks": landmarks.count, + "gesture": gesture["gesture"] as? String ?? "unknown", + "hand_state": gesture["hand_state"] as? String ?? "empty", + "finger_extensions": gesture["finger_extensions"] as? [String: Bool] ?? [:], + "num_fingers_extended": gesture["num_fingers_extended"] as? Int ?? 0, + "num_fingers_curled": gesture["num_fingers_curled"] as? Int ?? 0 + ]) + } + + if !persons.isEmpty { + handFrames.append([ + "frame": frameNum, + "timestamp": timestamp, + "persons": persons + ]) + } + + // Progress reporting + let progress = (i + 1) * 100 / frameFiles.count + if progress > lastProgress && progress % 10 == 0 { + print("[SwiftHand] Progress: \(progress)% (\(handFrames.count) hand frames)") + lastProgress = progress + } + } + + // Cleanup temp directory + try? FileManager.default.removeItem(at: tempDir) + + // Build output JSON + let outputData: [String: Any] = [ + "frame_count": handFrames.count, + "fps": fps, + "frames": handFrames, + "metadata": [ + "source": "swift_hand", + "uuid": uuid, + "landmarks_per_hand": 21, + "min_confidence": minConfidence, + "sample_interval": sampleInterval + ] + ] + + let jsonData = try JSONSerialization.data(withJSONObject: outputData, options: [.prettyPrinted]) + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + + print("[SwiftHand] Complete: \(handFrames.count) frames with hands") + print("[SwiftHand] Output: \(outputPath)") + } + + /// Map Vision joint codes to readable names + func mapJointName(_ rawName: String) -> String { + let mapping: [String: String] = [ + "VNHLKWRI": "wrist", + "VNHLKTIP": "thumb_tip", + "VNHLKTTIP": "thumb_tip", + "VNHLKTMP": "thumb_mp", + "VNHLKTCMC": "thumb_cmc", + "VNHLKITIP": "index_tip", + "VNHLKIDIP": "index_dip", + "VNHLKIPIP": "index_pip", + "VNHLKIMCP": "index_mcp", + "VNHLKMTIP": "middle_tip", + "VNHLKMDIP": "middle_dip", + "VNHLKMPIP": "middle_pip", + "VNHLKMMCP": "middle_mcp", + "VNHLKRTIP": "ring_tip", + "VNHLKRDIP": "ring_dip", + "VNHLKRPIP": "ring_pip", + "VNHLKRMCP": "ring_mcp", + "VNHLKPTIP": "little_tip", + "VNHLKPDIP": "little_dip", + "VNHLKPPIP": "little_pip", + "VNHLKPMCP": "little_mcp", + ] + return mapping[rawName] ?? rawName.lowercased() + } + + /// Detect gesture from finger extensions + /// Returns: gesture, hand_state ("empty" or "holding"), finger info + func detectGesture(_ hand: VNHumanHandPoseObservation) -> [String: Any] { + // Finger extension check (tip lower than pip after flip = extended) + func isFingerExtended(tipName: VNHumanHandPoseObservation.JointName, pipName: VNHumanHandPoseObservation.JointName) -> Bool { + guard let tip = try? hand.recognizedPoint(tipName), + let pip = try? hand.recognizedPoint(pipName) else { return false } + return tip.confidence > 0.3 && pip.confidence > 0.3 && tip.location.y > pip.location.y + } + + // Finger curled check (tip higher than pip after flip = curled around object) + func isFingerCurled(tipName: VNHumanHandPoseObservation.JointName, pipName: VNHumanHandPoseObservation.JointName) -> Bool { + guard let tip = try? hand.recognizedPoint(tipName), + let pip = try? hand.recognizedPoint(pipName) else { return false } + return tip.confidence > 0.3 && pip.confidence > 0.3 && tip.location.y < pip.location.y + } + + // Thumb: tip vs cmc (horizontal distance) + func isThumbExtended() -> Bool { + guard let tip = try? hand.recognizedPoint(.thumbTip), + let cmc = try? hand.recognizedPoint(.thumbCMC) else { return false } + return tip.confidence > 0.3 && cmc.confidence > 0.3 && + abs(tip.location.x - cmc.location.x) > 0.05 + } + + let thumb = isThumbExtended() + let index = isFingerExtended(tipName: .indexTip, pipName: .indexPIP) + let middle = isFingerExtended(tipName: .middleTip, pipName: .middlePIP) + let ring = isFingerExtended(tipName: .ringTip, pipName: .ringPIP) + let little = isFingerExtended(tipName: .littleTip, pipName: .littlePIP) + + // Curled fingers (holding object indicator) + let indexCurled = isFingerCurled(tipName: .indexTip, pipName: .indexPIP) + let middleCurled = isFingerCurled(tipName: .middleTip, pipName: .middlePIP) + let ringCurled = isFingerCurled(tipName: .ringTip, pipName: .ringPIP) + let littleCurled = isFingerCurled(tipName: .littleTip, pipName: .littlePIP) + + let extensions: [String: Bool] = [ + "thumb": thumb, + "index": index, + "middle": middle, + "ring": ring, + "little": little + ] + + let numExtended = extensions.values.filter { $0 }.count + let numCurled = [indexCurled, middleCurled, ringCurled, littleCurled].filter { $0 }.count + + var gesture = "unknown" + var handState = "empty" // "empty" or "holding" + + // === HOLDING DETECTION === + // Holding object: 2+ fingers curled, thumb may be wrapped or supporting + if numCurled >= 2 && !thumb { + // Fist-like grip without thumb extended + handState = "holding" + gesture = "holding_object" + } else if numCurled >= 3 { + // Multiple fingers wrapped around object + handState = "holding" + gesture = "holding_object" + } + // === EMPTY HAND GESTURES === + else if numExtended == 5 { + gesture = "open_hand" + } else if numExtended == 0 { + gesture = "fist" + } else if thumb && numExtended == 1 { + gesture = "thumbs_up" + } else if index && numExtended == 1 { + gesture = "pointing" + } else if index && middle && numExtended == 2 { + gesture = "peace_sign" + } else if thumb && index && !middle && !ring && !little { + gesture = "ok_sign" + } else if thumb && index && middle && !ring && !little { + gesture = "three_fingers" + } else if numExtended >= 3 { + gesture = "partial_open" + } + + return [ + "gesture": gesture, + "hand_state": handState, + "finger_extensions": extensions, + "num_fingers_extended": numExtended, + "num_fingers_curled": numCurled + ] + } +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/swift/swift_pose.swift b/installer/build/MomentryCore/tools/cli/swift/swift_pose.swift new file mode 100644 index 00000000..afb9d7ef --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/swift_pose.swift @@ -0,0 +1,222 @@ +import Foundation +import Vision +import ArgumentParser +import AppKit +import AVFoundation + +/// Swift Pose Processor - replaces YOLOv8 Pose / MediaPipe Pose +/// Uses VNDetectHumanBodyPoseRequest with ANE acceleration +/// +/// Output format (compatible with PoseResult Rust struct): +/// { +/// "frame_count": N, "fps": 30.0, +/// "frames": [ +/// { "frame": 0, "timestamp": 0.0, "persons": [ +/// { "keypoints": [{"name":"nose","x":100,"y":200,"confidence":0.95}], +/// "bbox": {"x":0,"y":0,"width":100,"height":200} +/// } +/// ]} +/// ] +/// } +@main +struct SwiftPose: ParsableCommand { + @Argument(help: "Video file path") + var inputPath: String + + @Argument(help: "Output JSON path") + var outputPath: String + + @Option(name: .long, help: "Sample interval (frames, default=3)") + var sampleInterval: Int = 3 + + @Option(name: .long, help: "UUID for logging") + var uuid: String = "" + + mutating func run() throws { + let startTime = Date() + print("[SwiftPose] Starting: \(inputPath)") + + let url = URL(fileURLWithPath: inputPath) + let asset = AVAsset(url: url) + guard let track = asset.tracks(withMediaType: .video).first else { + print("[SwiftPose] Error: No video track"); return + } + let duration = asset.duration.seconds + let fps = Double(track.nominalFrameRate) + print("[SwiftPose] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", fps))") + + // Extract frames (use shared cache or ffmpeg) + let tempDir: URL + let framesDir: URL + if let cacheDir = ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] { + framesDir = URL(fileURLWithPath: cacheDir) + tempDir = framesDir + print("[SwiftPose] Using shared frame cache: \(cacheDir)") + } else { + tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("swift_pose_\(UUID().uuidString)") + framesDir = tempDir.appendingPathComponent("frames") + try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true) + + let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path + print("[SwiftPose] Extracting frames...") + let extract = Process() + extract.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") + extract.arguments = ["-y", "-v", "quiet", "-i", inputPath, + "-vf", "select=not(mod(n\\,\(sampleInterval)))", + "-vsync", "vfr", "-q:v", "15", pattern] + try extract.run() + extract.waitUntilExit() + } + + let files = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? [] + let frameFiles = files.filter { $0.hasSuffix(".jpg") }.sorted() + print("[SwiftPose] Extracted \(frameFiles.count) frames") + + let jointNames: [VNHumanBodyPoseObservation.JointName] = [ + .nose, .leftEye, .rightEye, .leftEar, .rightEar, + .neck, .root, + .leftShoulder, .rightShoulder, + .leftElbow, .rightElbow, + .leftWrist, .rightWrist, + .leftHip, .rightHip, + .leftKnee, .rightKnee, + .leftAnkle, .rightAnkle, + ] + + var poseFrames: [[String: Any]] = [] + var lastProgress = 0 + + for (i, fname) in frameFiles.enumerated() { + let imgPath = framesDir.appendingPathComponent(fname).path + guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)), + let img = NSImage(data: imgData), + let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue } + + let frameNum = Int(fname.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? (i * sampleInterval) + let timestamp = Double(frameNum) / fps + let w = cgImage.width + let h = cgImage.height + + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) + let req = VNDetectHumanBodyPoseRequest() + try? handler.perform([req]) + + guard let poses = req.results, !poses.isEmpty else { continue } + + var persons: [[String: Any]] = [] + for pose in poses { + var keypoints: [[String: Any]] = [] + var minX = CGFloat.greatestFiniteMagnitude + var minY = CGFloat.greatestFiniteMagnitude + var maxX: CGFloat = 0 + var maxY: CGFloat = 0 + + for joint in jointNames { + if let point = try? pose.recognizedPoint(joint) { + let desc = String(describing: joint.rawValue) + var rawName = desc + .replacingOccurrences(of: "VNRecognizedPointKey(_rawValue: ", with: "") + .replacingOccurrences(of: ")", with: "") + .trimmingCharacters(in: .whitespaces) + // Map Vision Framework joint names to standard names + let nameMap: [String: String] = [ + "head_joint": "nose", + "left_eye_joint": "left_eye", + "right_eye_joint": "right_eye", + "left_ear_joint": "left_ear", + "right_ear_joint": "right_ear", + "neck_1_joint": "neck", + "left_shoulder_1_joint": "left_shoulder", + "right_shoulder_1_joint": "right_shoulder", + "left_elbow_1_joint": "left_elbow", + "right_elbow_1_joint": "right_elbow", + "left_hand_joint": "left_wrist", + "right_hand_joint": "right_wrist", + "left_hip_1_joint": "left_hip", + "right_hip_1_joint": "right_hip", + "left_knee_1_joint": "left_knee", + "right_knee_1_joint": "right_knee", + "left_ankle_1_joint": "left_ankle", + "right_ankle_1_joint": "right_ankle", + "center_hip_joint": "root", + "left_forearm_joint": "left_elbow", + "right_forearm_joint": "right_elbow", + "left_upLeg_joint": "left_hip", + "right_upLeg_joint": "right_hip", + "left_leg_joint": "left_knee", + "right_leg_joint": "right_knee", + "left_foot_joint": "left_ankle", + "right_foot_joint": "right_ankle", + ] + if let mapped = nameMap[rawName] { + rawName = mapped + } + let px = point.location.x * CGFloat(w) + let py = CGFloat(h) - point.location.y * CGFloat(h) + keypoints.append([ + "name": rawName.isEmpty ? "\(joint)" : rawName, + "x": Double(round(px * 100)) / 100, + "y": Double(round(py * 100)) / 100, + "confidence": Double(round(point.confidence * 100)) / 100, + ]) + if point.confidence > 0.1 { + minX = min(minX, px) + minY = min(minY, py) + maxX = max(maxX, px) + maxY = max(maxY, py) + } + } + } + + var bbox: [String: Any] = [ + "x": 0, "y": 0, "width": 0, "height": 0 + ] + if maxX > minX { + bbox = [ + "x": Int(minX), + "y": Int(minY), + "width": Int(maxX - minX), + "height": Int(maxY - minY), + ] + } + + persons.append(["keypoints": keypoints, "bbox": bbox]) + } + + if !persons.isEmpty { + poseFrames.append([ + "frame": frameNum, + "timestamp": Double(round(timestamp * 100)) / 100, + "persons": persons, + ]) + } + + let pct = Int(Float(i) / Float(frameFiles.count) * 100) + if pct >= lastProgress + 10 { + print("[SwiftPose] Progress: \(pct)% (\(i)/\(frameFiles.count), \(persons.count) poses)") + lastProgress = pct + } + } + + // Write output + let outputDict: [String: Any] = [ + "frame_count": poseFrames.count, + "fps": Double(round(fps * 100)) / 100, + "frames": poseFrames, + ] + if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) { + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + } + + let elapsed = Date().timeIntervalSince(startTime) + print("[SwiftPose] Complete: \(poseFrames.count) frames, \(String(format: "%.1f", elapsed))s") + if duration > 0 { + print("[SwiftPose] RTF: \(String(format: "%.3f", elapsed / duration))x") + } + + // Clean up temp dir if we created it + if ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] == nil { + try? FileManager.default.removeItem(at: tempDir) + } + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/swift_pose_expansion.swift b/installer/build/MomentryCore/tools/cli/swift/swift_pose_expansion.swift new file mode 100644 index 00000000..7d110abd --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/swift_pose_expansion.swift @@ -0,0 +1,376 @@ +import Foundation +import Vision +import ArgumentParser +import AVFoundation + +/// Swift Pose Expansion Processor V2 +/// +/// Reads face_traced.json (from face tracking) and expands pose detection from trace frames. +/// Inherits trace_id from face traces for proper tracking continuity. +/// +/// Algorithm: +/// 1. Load face_traced.json, extract frames grouped by trace_id +/// 2. For each trace_id, start from face frames and expand forward/backward +/// 3. Stop expansion when 3 consecutive frames have no pose detection +/// 4. Associate each pose with the nearest face's trace_id +/// 5. Output pose.json at 8Hz sampling (floor(fps/8) interval) +@main +struct SwiftPoseExpansion: ParsableCommand { + @Argument(help: "Video file path") + var videoPath: String + + @Argument(help: "Input face_traced.json path") + var faceTracedPath: String + + @Argument(help: "Output pose.json path") + var outputPath: String + + @Option(name: .long, help: "UUID for logging") + var uuid: String = "" + + @Option(name: .long, help: "Consecutive miss threshold to stop expansion (default: 3)") + var missThreshold: Int = 3 + + mutating func run() throws { + let startTime = Date() + print("[PoseExpansion] Starting pose expansion from face traces: \(videoPath)") + + // Load face_traced.json + guard let faceData = try? Data(contentsOf: URL(fileURLWithPath: faceTracedPath)) else { + print("[PoseExpansion] ERROR: Cannot read \(faceTracedPath)") + return + } + + guard let faceJson = try? JSONSerialization.jsonObject(with: faceData) as? [String: Any] else { + print("[PoseExpansion] ERROR: Invalid JSON in \(faceTracedPath)") + return + } + + // Extract frames with trace_id mapping + // frameToTraces: frame -> [(trace_id, x, y, w, h)] + var frameToTraces: [Int: [(traceId: Int, x: Double, y: Double, w: Double, h: Double)]] = [:] + var allTraceIds: Set = [] + + // Handle both dict and list format + if let framesDict = faceJson["frames"] as? [String: Any] { + for (frameStr, frameData) in framesDict { + guard let frameNum = Int(frameStr) else { continue } + if let faces = (frameData as? [String: Any])?["faces"] as? [[String: Any]] { + for face in faces { + if let traceId = face["trace_id"] as? Int, traceId > 0 { + allTraceIds.insert(traceId) + let bbox = face["bbox"] as? [String: Any] + let x = bbox?["x"] as? Double ?? face["x"] as? Double ?? 0 + let y = bbox?["y"] as? Double ?? face["y"] as? Double ?? 0 + let w = bbox?["width"] as? Double ?? face["width"] as? Double ?? 0 + let h = bbox?["height"] as? Double ?? face["height"] as? Double ?? 0 + frameToTraces[frameNum, default: []].append((traceId, x, y, w, h)) + } + } + } + } + } else if let framesList = faceJson["frames"] as? [[String: Any]] { + for frameData in framesList { + guard let frameNum = frameData["frame"] as? Int else { continue } + if let faces = frameData["faces"] as? [[String: Any]] { + for face in faces { + if let traceId = face["trace_id"] as? Int, traceId > 0 { + allTraceIds.insert(traceId) + let bbox = face["bbox"] as? [String: Any] + let x = bbox?["x"] as? Double ?? face["x"] as? Double ?? 0 + let y = bbox?["y"] as? Double ?? face["y"] as? Double ?? 0 + let w = bbox?["width"] as? Double ?? face["width"] as? Double ?? 0 + let h = bbox?["height"] as? Double ?? face["height"] as? Double ?? 0 + frameToTraces[frameNum, default: []].append((traceId, x, y, w, h)) + } + } + } + } + } + + print("[PoseExpansion] Found \(allTraceIds.count) traces, \(frameToTraces.count) frames in \(faceTracedPath)") + + if frameToTraces.isEmpty { + print("[PoseExpansion] No traces found, skipping pose expansion") + let emptyOutput: [String: Any] = ["frame_count": 0, "fps": 0.0, "frames": []] + let jsonData = try JSONSerialization.data(withJSONObject: emptyOutput, options: []) + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + return + } + + // Get video info + let url = URL(fileURLWithPath: videoPath) + let asset = AVAsset(url: url) + guard let videoTrack = asset.tracks(withMediaType: .video).first else { + print("[PoseExpansion] ERROR: No video track") + return + } + + let fps = videoTrack.nominalFrameRate + let duration = CMTimeGetSeconds(asset.duration) + let totalFrames = Int(duration * Double(fps)) + let sampleInterval = max(1, Int(floor(Double(fps) / 8.0))) + + print("[PoseExpansion] Video: \(fps)fps, \(totalFrames) frames, 8Hz interval=\(sampleInterval)") + + // Build set of all face frames + let allFaceFrameSet = Set(frameToTraces.keys) + + // Track which frames have pose with trace_id + var poseFrameDict: [Int: [String: Any]] = [:] + + // Setup asset reader + let outputSettings: [String: Any] = [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA + ] + + let reader = try AVAssetReader(asset: asset) + let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings) + trackOutput.alwaysCopiesSampleData = false + reader.add(trackOutput) + + guard reader.startReading() else { + print("[PoseExpansion] ERROR: Cannot start reader") + return + } + + // Process frames + var frameIndex = 0 + var consecutiveMisses = 0 + var activeTraceIds: Set = [] // Currently active traces being expanded + + while let sampleBuffer = trackOutput.copyNextSampleBuffer() { + defer { frameIndex += 1 } + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + continue + } + + // Check if this frame has face traces + let faceTraces = frameToTraces[frameIndex] + let isFaceFrame = faceTraces != nil && !faceTraces!.isEmpty + + if isFaceFrame, let traces = faceTraces { + // Update active traces + for ft in traces { + activeTraceIds.insert(ft.traceId) + } + consecutiveMisses = 0 + } + + // Check if we should process this frame + let shouldProcess = isFaceFrame || + (consecutiveMisses < missThreshold * sampleInterval && !activeTraceIds.isEmpty) + + if shouldProcess { + let poseResult = detectPose(pixelBuffer: pixelBuffer) + + if poseResult.hasPose { + let seconds = Double(frameIndex) / Double(fps) + + // Determine trace_id for this pose + var traceId = 0 + if isFaceFrame, let traces = faceTraces { + // Use the trace_id from face (may need bbox matching for multi-person) + // For now, use the first trace_id found + traceId = traces.first?.traceId ?? 0 + } else { + // Inherit from nearest face frame with active trace + let nearestFaceFrame = findNearestFaceFrame( + frameIndex: frameIndex, + frameToTraces: frameToTraces, + activeTraceIds: activeTraceIds + ) + if let nearest = nearestFaceFrame, let traces = frameToTraces[nearest] { + traceId = traces.first?.traceId ?? 0 + } + } + + poseFrameDict[frameIndex] = [ + "frame": frameIndex, + "timestamp": seconds, + "trace_id": traceId, + "persons": poseResult.persons + ] + consecutiveMisses = 0 + } else { + consecutiveMisses += 1 + } + } + + // Progress logging + if frameIndex % 5000 == 0 { + let elapsed = Date().timeIntervalSince(startTime) + print("[PoseExpansion] Frame \(frameIndex)/\(totalFrames), \(poseFrameDict.count) poses, \(Int(elapsed))s") + fflush(stdout) + } + } + + reader.cancelReading() + + print("[PoseExpansion] Detection done: \(poseFrameDict.count) frames with pose") + + // 8Hz sampling output + var outputFrames: [[String: Any]] = [] + let sortedPoseFrames = poseFrameDict.keys.sorted() + + var targetFrame = 0 + while targetFrame < totalFrames { + // Find closest pose frame to target + var closestFrame: Int? = nil + var closestDist = Int.max + + for poseFrame in sortedPoseFrames { + let dist = abs(poseFrame - targetFrame) + if dist < closestDist && dist <= sampleInterval { + closestDist = dist + closestFrame = poseFrame + } + } + + if let cf = closestFrame, let data = poseFrameDict[cf] { + outputFrames.append(data) + } + + targetFrame += sampleInterval + } + + // Write output + let output: [String: Any] = [ + "frame_count": outputFrames.count, + "fps": Double(fps), + "frames": outputFrames + ] + + let jsonData = try JSONSerialization.data(withJSONObject: output, options: []) + try jsonData.write(to: URL(fileURLWithPath: outputPath)) + + let elapsed = Date().timeIntervalSince(startTime) + print("[PoseExpansion] Done: \(outputFrames.count) frames at 8Hz, \(String(format: "%.1f", elapsed))s → \(outputPath)") + } + + /// Find nearest face frame with active trace + func findNearestFaceFrame( + frameIndex: Int, + frameToTraces: [Int: [(traceId: Int, x: Double, y: Double, w: Double, h: Double)]], + activeTraceIds: Set + ) -> Int? { + var nearestFrame: Int? = nil + var nearestDist = Int.max + + for (frameNum, traces) in frameToTraces { + // Check if this frame has an active trace + let hasActiveTrace = traces.contains { activeTraceIds.contains($0.traceId) } + if hasActiveTrace { + let dist = abs(frameNum - frameIndex) + if dist < nearestDist { + nearestDist = dist + nearestFrame = frameNum + } + } + } + + return nearestFrame + } + + func detectPose(pixelBuffer: CVPixelBuffer) -> (hasPose: Bool, persons: [[String: Any]]) { + let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer)) + let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer)) + + let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]) + let bodyReq = VNDetectHumanBodyPoseRequest() + + do { + try handler.perform([bodyReq]) + } catch { + return (false, []) + } + + let jointNames: [VNHumanBodyPoseObservation.JointName] = [ + .nose, .leftEye, .rightEye, .leftEar, .rightEar, + .neck, .root, + .leftShoulder, .rightShoulder, + .leftElbow, .rightElbow, + .leftWrist, .rightWrist, + .leftHip, .rightHip, + .leftKnee, .rightKnee, + .leftAnkle, .rightAnkle, + ] + + var persons: [[String: Any]] = [] + + let poses = bodyReq.results ?? [] + for pose in poses { + var keypoints: [[String: Any]] = [] + var minX = CGFloat.greatestFiniteMagnitude + var minY = CGFloat.greatestFiniteMagnitude + var maxX: CGFloat = 0 + var maxY: CGFloat = 0 + + for joint in jointNames { + if let point = try? pose.recognizedPoint(joint) { + let desc = String(describing: joint.rawValue) + var rawName = desc + .replacingOccurrences(of: "VNRecognizedPointKey(_rawValue: ", with: "") + .replacingOccurrences(of: ")", with: "") + .trimmingCharacters(in: .whitespaces) + + let nameMap: [String: String] = [ + "head_joint": "nose", + "left_eye_joint": "left_eye", + "right_eye_joint": "right_eye", + "left_ear_joint": "left_ear", + "right_ear_joint": "right_ear", + "neck_1_joint": "neck", + "left_shoulder_1_joint": "left_shoulder", + "right_shoulder_1_joint": "right_shoulder", + "left_elbow_1_joint": "left_elbow", + "right_elbow_1_joint": "right_elbow", + "left_hand_joint": "left_wrist", + "right_hand_joint": "right_wrist", + "left_hip_1_joint": "left_hip", + "right_hip_1_joint": "right_hip", + "left_knee_1_joint": "left_knee", + "right_knee_1_joint": "right_knee", + "left_ankle_1_joint": "left_ankle", + "right_ankle_1_joint": "right_ankle", + "center_hip_joint": "root", + ] + if let mapped = nameMap[rawName] { + rawName = mapped + } + + let px = point.location.x * CGFloat(imgW) + let py = CGFloat(imgH) - point.location.y * CGFloat(imgH) + keypoints.append([ + "name": rawName.isEmpty ? "\(joint)" : rawName, + "x": px, + "y": py, + "confidence": point.confidence, + ]) + + if point.confidence > 0.1 { + minX = min(minX, px) + minY = min(minY, py) + maxX = max(maxX, px) + maxY = max(maxY, py) + } + } + } + + var bbox: [String: Any] = ["x": 0, "y": 0, "width": 0, "height": 0] + if maxX > minX { + bbox = [ + "x": Int(minX), + "y": Int(minY), + "width": Int(maxX - minX), + "height": Int(maxY - minY), + ] + } + + persons.append(["keypoints": keypoints, "bbox": bbox]) + } + + return (!persons.isEmpty, persons) + } +} \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/cli/swift/vision_object_test.swift b/installer/build/MomentryCore/tools/cli/swift/vision_object_test.swift new file mode 100644 index 00000000..5889b82b --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/vision_object_test.swift @@ -0,0 +1,102 @@ +import Foundation +import Vision +import ArgumentParser +import AppKit + +/// POC: Test Apple Vision Framework for object detection (YOLO replacement) +@main +struct VisionObjectTest: ParsableCommand { + @Argument(help: "Input image path") + var inputPath: String + + func run() throws { + let startTime = Date() + print("=== Apple Vision Framework Object Detection POC ===") + #if arch(arm64) + print("HW: Apple Silicon ✅ (ANE available)") + #endif + + guard let image = NSImage(contentsOfFile: inputPath) else { + print("Error: cannot load image"); return + } + guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { + print("Error: cannot get CGImage"); return + } + print("Image: \(cgImage.width)x\(cgImage.height)") + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) + + // 1. VNClassifyImageRequest (scene classification - replaces scene_classifier) + print("\n--- VNClassifyImageRequest ---") + let clsReq = VNClassifyImageRequest() + try handler.perform([clsReq]) + if let classifications = clsReq.results { + print("Top classifications:") + for c in classifications.prefix(10) { + print(" \(c.identifier): conf=\(String(format: "%.3f", c.confidence))") + } + } + + // 2. VNDetectHumanRectanglesRequest (person detection - YOLO replacement for 'person') + print("\n--- VNDetectHumanRectanglesRequest ---") + let humanReq = VNDetectHumanRectanglesRequest() + try handler.perform([humanReq]) + if let humans = humanReq.results { + print("Humans: \(humans.count)") + for (i, h) in humans.enumerated() { + let bb = h.boundingBox + print(" [\(i)] bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y))) size=(\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) conf=\(String(format: "%.2f", h.confidence))") + } + } + + // 3. VNDetectHumanBodyPoseRequest (pose estimation - MediaPipe replacement) + print("\n--- VNDetectHumanBodyPoseRequest ---") + let poseReq = VNDetectHumanBodyPoseRequest() + try handler.perform([poseReq]) + if let poses = poseReq.results { + print("Body poses: \(poses.count)") + for (i, p) in poses.enumerated() { + let joints = p.availableJointNames + print(" [\(i)] \(joints.count) joints detected") + // Show key joints + for joint in [VNHumanBodyPoseObservation.JointName.neck, + VNHumanBodyPoseObservation.JointName.leftShoulder, + VNHumanBodyPoseObservation.JointName.rightShoulder, + VNHumanBodyPoseObservation.JointName.leftWrist, + VNHumanBodyPoseObservation.JointName.rightWrist, + VNHumanBodyPoseObservation.JointName.root] { + if let pt = try? p.recognizedPoint(joint) { + print(" \(joint.rawValue): (\(String(format: "%.3f", pt.location.x)), \(String(format: "%.3f", pt.location.y))) conf=\(String(format: "%.2f", pt.confidence))") + } + } + } + } + + // 4. VNDetectHumanHandPoseRequest (hand pose) + print("\n--- VNDetectHumanHandPoseRequest ---") + let handReq = VNDetectHumanHandPoseRequest() + try handler.perform([handReq]) + if let hands = handReq.results { + print("Hands: \(hands.count)") + for (i, h) in hands.enumerated() { + print(" [\(i)] confidence=\(String(format: "%.2f", h.confidence))") + } + } + + // 5. VNGenerateObjectnessBasedSaliencyImageRequest (object detection without labels) + print("\n--- VNGenerateObjectnessBasedSaliencyImageRequest ---") + let salReq = VNGenerateObjectnessBasedSaliencyImageRequest() + try handler.perform([salReq]) + if let sal = salReq.results?.first { + if let objects = sal.salientObjects { + print("Salient objects: \(objects.count)") + for (i, ob) in objects.enumerated().prefix(10) { + let bb = ob.boundingBox + print(" [\(i)] bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y)),\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) conf=\(String(format: "%.2f", ob.confidence))") + } + } + } + + print("\nTime: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s") + print("=== Done ===") + } +} diff --git a/installer/build/MomentryCore/tools/cli/swift/vision_ocr_test.swift b/installer/build/MomentryCore/tools/cli/swift/vision_ocr_test.swift new file mode 100644 index 00000000..4ff10baf --- /dev/null +++ b/installer/build/MomentryCore/tools/cli/swift/vision_ocr_test.swift @@ -0,0 +1,71 @@ +import Foundation +import Vision +import ArgumentParser +import AppKit + +/// POC: Test Apple Vision Framework OCR (VNRecognizeTextRequest) vs PaddleOCR +@main +struct VisionOCRTest: ParsableCommand { + @Argument(help: "Input image path") + var inputPath: String + + @Option(name: .long, help: "Recognition level (.fast or .accurate, default .accurate)") + var level: String = "accurate" + + mutating func run() throws { + let startTime = Date() + print("=== Apple Vision Framework OCR POC ===") + #if arch(arm64) + print("HW: Apple Silicon ✅") + #endif + + guard let image = NSImage(contentsOfFile: inputPath) else { + print("Error: cannot load image"); return + } + guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { + print("Error: cannot get CGImage"); return + } + print("Image: \(cgImage.width)x\(cgImage.height)") + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) + + // VNRecognizeTextRequest + print("\n--- VNRecognizeTextRequest ---") + let req = VNRecognizeTextRequest() + if level == "fast" { + req.recognitionLevel = .fast + } else { + req.recognitionLevel = .accurate + } + req.usesLanguageCorrection = true + req.preferBackgroundProcessing = true + + try handler.perform([req]) + + guard let results = req.results else { + print("No OCR results"); return + } + + print("Text blocks: \(results.count)") + var totalChars = 0 + for (i, obs) in results.enumerated() { + guard let candidate = obs.topCandidates(1).first else { continue } + let text = candidate.string + let conf = candidate.confidence + let bb = obs.boundingBox + totalChars += text.count + if i < 20 { + print(" [\(i)] conf=\(String(format: "%.3f", conf)) bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y)),\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) \"\(text.prefix(80))\"") + } + } + print(" ... \(results.count) total, \(totalChars) chars") + + // Check language support + print("\n--- Language Support ---") + let supported = (try? VNRecognizeTextRequest.supportedRecognitionLanguages(for: .accurate, revision: VNRecognizeTextRequest.currentRevision)) ?? [] + print("Supported languages (\(supported.count)): \(supported.prefix(10).joined(separator: ", "))...") + + let elapsed = Date().timeIntervalSince(startTime) + print("\nTime: \(String(format: "%.2f", elapsed))s") + print("=== Done ===") + } +} diff --git a/installer/build/MomentryCore/tools/script/asr/asr_processor_base.py b/installer/build/MomentryCore/tools/script/asr/asr_processor_base.py new file mode 100755 index 00000000..a2156675 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/asr/asr_processor_base.py @@ -0,0 +1,119 @@ +#!/opt/homebrew/bin/python3.11 +import sys +import json +import os +import argparse +import signal +import subprocess +from faster_whisper import WhisperModel + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + + +def signal_handler(signum, frame): + print(f"ASR: Received signal {signum}, exiting...") + sys.exit(1) + + +def has_audio_stream(video_path): + """Check if video file has audio stream using ffprobe.""" + try: + cmd = [ + "ffprobe", + "-v", + "error", + "-select_streams", + "a", + "-show_entries", + "stream=codec_type", + "-of", + "csv=p=0", + video_path, + ] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return bool(result.stdout.strip()) + except subprocess.CalledProcessError: + return False + except FileNotFoundError: + print("WARNING: ffprobe not found, assuming audio exists") + return True + + +def run_asr(video_path, output_path, uuid: str = ""): + # Set up signal handlers + signal.signal(signal.SIGTERM, signal_handler) + signal.signal(signal.SIGINT, signal_handler) + + publisher = RedisPublisher(uuid) if uuid else None + if publisher: + publisher.info("asr", "ASR_START") + + # Check for audio stream + if not has_audio_stream(video_path): + if publisher: + publisher.info("asr", "No audio stream detected, skipping transcription") + output = {"language": "", "language_probability": 0.0, "segments": []} + with open(output_path, "w") as f: + json.dump(output, f, indent=2) + if publisher: + publisher.complete("asr", "0 segments (no audio)") + sys.stderr.write("ASR: No audio stream, skipping transcription\n") + sys.stderr.flush() + sys.exit(0) + + if publisher: + publisher.info("asr", "Loading Whisper model...") + + # Use base model with CPU (MPS not supported by faster_whisper) + model = WhisperModel("base", device="cpu", compute_type="int8") + + if publisher: + publisher.info("asr", f"Transcribing: {video_path}") + + segments, info = model.transcribe(video_path, beam_size=5) + + if publisher: + publisher.info("asr", f"ASR_LANGUAGE:{info.language}") + + results = [] + total_segments = 0 + + for segment in segments: + results.append( + {"start": segment.start, "end": segment.end, "text": segment.text.strip()} + ) + total_segments += 1 + if total_segments % 100 == 0: + if publisher: + publisher.progress( + "asr", total_segments, 0, f"Segment {total_segments}" + ) + + output = { + "language": info.language, + "language_probability": info.language_probability, + "segments": results, + } + + with open(output_path, "w") as f: + json.dump(output, f, indent=2) + + if publisher: + publisher.complete("asr", f"{len(results)} segments") + + sys.stderr.write( + f"ASR: Transcription complete, {len(results)} segments written to {output_path}\n" + ) + sys.stderr.flush() + sys.exit(0) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="ASR Transcription (base model)") + parser.add_argument("video_path", help="Path to video file") + parser.add_argument("output_path", help="Output JSON path") + parser.add_argument("--uuid", "-u", help="UUID for Redis progress", default="") + args = parser.parse_args() + + run_asr(args.video_path, args.output_path, args.uuid) diff --git a/installer/build/MomentryCore/tools/script/asr/asr_processor_contract_v1.py b/installer/build/MomentryCore/tools/script/asr/asr_processor_contract_v1.py new file mode 100644 index 00000000..f2a2ccea --- /dev/null +++ b/installer/build/MomentryCore/tools/script/asr/asr_processor_contract_v1.py @@ -0,0 +1,546 @@ +#!/opt/homebrew/bin/python3.11 +""" +ASR Processor - AI-Driven Processor Contract Version 1.0 + +Compliant with AI-Driven Processor Contract v1.0 +Effective Date: 2025-03-27 + +Features: +1. Standardized command-line interface +2. Redis progress reporting +3. Signal handling (SIGTERM, SIGINT) +4. Health check mode +5. Resource monitoring +6. Contract-compliant JSON output +""" + +import sys +import json +import os +import argparse +import signal +import tempfile +import time +import subprocess +import traceback +from datetime import datetime +from typing import Dict, Any, Optional, Tuple +import atexit + +# Redis Publisher for progress reporting +try: + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + from redis_publisher import RedisPublisher + + REDIS_AVAILABLE = True +except ImportError: + REDIS_AVAILABLE = False + print( + "WARNING: RedisPublisher not available, progress reporting disabled", + file=sys.stderr, + ) + +# Contract version +CONTRACT_VERSION = "1.0" +PROCESSOR_NAME = os.path.join( + os.environ.get("MOMENTRY_SCRIPTS_DIR", os.path.expanduser("~/momentry_core/tools/script")), + "asr/asr_processor_contract_v1.py" +) +PROCESSOR_VERSION = "2.0.0" +MODEL_NAME = "base" +MODEL_VERSION = "unknown" + + +# Signal handling +class SignalHandler: + """Handle system signals for graceful shutdown""" + + def __init__(self): + self.shutdown_requested = False + self.original_handlers = {} + + def setup(self): + """Set up signal handlers""" + self.original_handlers[signal.SIGTERM] = signal.signal( + signal.SIGTERM, self.handle_signal + ) + self.original_handlers[signal.SIGINT] = signal.signal( + signal.SIGINT, self.handle_signal + ) + + def handle_signal(self, signum, frame): + """Handle received signal""" + signal_name = "SIGTERM" if signum == signal.SIGTERM else "SIGINT" + print( + f"[{PROCESSOR_NAME}] Received {signal_name}, initiating graceful shutdown...", + file=sys.stderr, + ) + self.shutdown_requested = True + + def restore(self): + """Restore original signal handlers""" + for sig, handler in self.original_handlers.items(): + signal.signal(sig, handler) + + +# Health check functions +def check_environment() -> Dict[str, Any]: + """Check environment and dependencies""" + checks = [] + + # Check 1: Whisper + try: + import whisper + + checks.append( + { + "name": "whisper", + "status": "available", + "version": whisper.__version__ + if hasattr(whisper, "__version__") + else "unknown", + } + ) + except ImportError: + checks.append( + { + "name": "whisper", + "status": "missing", + "message": "openai-whisper package not installed", + } + ) + + # Check 2: FFmpeg/FFprobe + try: + result = subprocess.run(["ffprobe", "-version"], capture_output=True, text=True) + if result.returncode == 0: + version_line = result.stdout.split("\n")[0] if result.stdout else "unknown" + checks.append( + {"name": "ffprobe", "status": "available", "version": version_line} + ) + else: + checks.append( + { + "name": "ffprobe", + "status": "unavailable", + "message": "ffprobe command failed", + } + ) + except Exception as e: + checks.append( + { + "name": "ffprobe", + "status": "missing", + "message": f"ffprobe not found: {e}", + } + ) + + # Check 3: Redis (optional) + checks.append( + { + "name": "redis", + "status": "available" if REDIS_AVAILABLE else "optional_missing", + "message": "Redis progress reporting available" + if REDIS_AVAILABLE + else "Redis progress reporting disabled", + } + ) + + # Determine overall status + critical_checks = [ + c + for c in checks + if c["name"] in ["whisper", "ffprobe"] + and c["status"] not in ["available", "optional_missing"] + ] + + if critical_checks: + overall_status = "unhealthy" + else: + overall_status = "healthy" + + return { + "status": overall_status, + "dependencies": checks, + "timestamp": datetime.now().isoformat(), + } + + +# Whisper model cache +_whisper_model_cache = {} + + +def get_whisper_model(model_name: str = "base"): + """Get Whisper model with caching""" + if model_name not in _whisper_model_cache: + import whisper + + print( + f"[{PROCESSOR_NAME}] Loading Whisper model: {model_name}", file=sys.stderr + ) + _whisper_model_cache[model_name] = whisper.load_model(model_name) + return _whisper_model_cache[model_name] + + +# Main processor class +class ASRProcessor: + """ASR Processor compliant with AI-Driven Processor Contract""" + + def __init__( + self, + video_path: str, + output_path: str, + uuid: str = "", + model_name: str = "base", + chunk_size: int = 300, + publisher=None, + ): + self.video_path = video_path + self.output_path = output_path + self.uuid = uuid + self.model_name = model_name + self.chunk_size = chunk_size + self.publisher = publisher + self.start_time = time.time() + self.signal_handler = SignalHandler() + self.cleanup_files = [] + + # Set up signal handling + self.signal_handler.setup() + atexit.register(self.cleanup) + + def publish(self, msg_type: str, message: str, progress: Optional[float] = None): + """Publish message to Redis if available""" + if self.publisher and REDIS_AVAILABLE: + try: + if msg_type == "progress" and progress is not None: + self.publisher.progress( + PROCESSOR_NAME, int(progress * 100), 0, message + ) + else: + getattr(self.publisher, msg_type)(PROCESSOR_NAME, message) + except Exception as e: + print(f"[{PROCESSOR_NAME}] Redis publish error: {e}", file=sys.stderr) + + def validate_input(self) -> Tuple[bool, str]: + """Validate input file""" + if not os.path.exists(self.video_path): + return False, f"Video file not found: {self.video_path}" + + # Check for audio stream + if not self._has_audio_stream(): + return False, f"No audio stream found in: {self.video_path}" + + return True, "Input validation passed" + + def _has_audio_stream(self) -> bool: + """Check if video has audio stream""" + try: + cmd = [ + "ffprobe", + "-v", + "error", + "-select_streams", + "a", + "-show_entries", + "stream=codec_type", + "-of", + "csv=p=0", + self.video_path, + ] + result = subprocess.run(cmd, capture_output=True, text=True) + return "audio" in result.stdout + except Exception: + return False + + def _get_media_duration(self) -> float: + """Get media duration in seconds""" + try: + cmd = [ + "ffprobe", + "-v", + "error", + "-show_entries", + "format=duration", + "-of", + "csv=p=0", + self.video_path, + ] + result = subprocess.run(cmd, capture_output=True, text=True) + return float(result.stdout.strip()) + except Exception as e: + print( + f"[{PROCESSOR_NAME}] Warning: Failed to get duration: {e}", + file=sys.stderr, + ) + return 0.0 + + def _extract_audio(self, audio_path: str) -> bool: + """Extract audio to temporary file""" + try: + cmd = [ + "ffmpeg", + "-i", + self.video_path, + "-vn", + "-acodec", + "pcm_s16le", + "-ar", + "16000", + "-ac", + "1", + "-y", + audio_path, + ] + + self.publish("info", f"Extracting audio to: {audio_path}") + result = subprocess.run(cmd, capture_output=True, text=True) + + if result.returncode != 0: + self.publish("error", f"Audio extraction failed: {result.stderr[:100]}") + return False + + return os.path.exists(audio_path) and os.path.getsize(audio_path) > 0 + + except Exception as e: + self.publish("error", f"Audio extraction error: {e}") + return False + + def process(self) -> Dict[str, Any]: + """Main processing method""" + try: + # Check for shutdown request + if self.signal_handler.shutdown_requested: + raise KeyboardInterrupt("Shutdown requested by signal") + + # 1. Prepare working directory + work_dir = tempfile.mkdtemp(prefix=f"{PROCESSOR_NAME}_") + self.cleanup_files.append(work_dir) + self.publish("info", f"Working directory: {work_dir}") + + # 2. Get media duration + duration = self._get_media_duration() + self.publish("info", f"Media duration: {duration:.2f} seconds") + + # 3. Process based on duration + self.publish("info", "Starting transcription...") + + if duration <= self.chunk_size or self.chunk_size <= 0: + # Single file processing + result = self._process_single_file(work_dir) + processing_mode = "direct" + chunk_count = 1 + else: + # Chunked processing (simplified for now) + result = self._process_single_file(work_dir) + processing_mode = "chunked" + chunk_count = max(1, int(duration / self.chunk_size)) + + # 4. Add contract-compliant metadata + processing_time = time.time() - self.start_time + result.update( + { + "processor_name": PROCESSOR_NAME, + "processor_version": PROCESSOR_VERSION, + "contract_version": CONTRACT_VERSION, + "model_name": MODEL_NAME, + "model_version": MODEL_VERSION, + "processing_mode": processing_mode, + "chunk_count": chunk_count, + "chunk_duration": self.chunk_size + if processing_mode == "chunked" + else 0, + "metadata": { + "processing_time_seconds": processing_time, + "video_path": self.video_path, + "duration_seconds": duration, + "model": self.model_name, + "timestamp": datetime.now().isoformat(), + }, + } + ) + + # 5. Cleanup + self.cleanup() + + self.publish( + "complete", f"Processing completed in {processing_time:.2f} seconds" + ) + return result + + except KeyboardInterrupt: + self.publish("warning", "Processing interrupted by user") + raise + except Exception as e: + self.publish("error", f"Processing failed: {e}") + raise + + def _process_single_file(self, work_dir: str) -> Dict[str, Any]: + """Process single file (no chunking)""" + # 1. Extract audio + audio_path = os.path.join(work_dir, "audio.wav") + self.cleanup_files.append(audio_path) + + if not self._extract_audio(audio_path): + raise RuntimeError("Failed to extract audio") + + # 2. Load model + self.publish("info", f"Loading Whisper model: {self.model_name}") + model = get_whisper_model(self.model_name) + + # 3. Transcribe + self.publish("progress", "Transcribing audio...", 0.3) + + result = model.transcribe(audio_path) + + # 4. Format segments + segments = [] + total_segments = len(result.get("segments", [])) + + for i, segment in enumerate(result.get("segments", [])): + segments.append( + { + "start": segment.get("start", 0.0), + "end": segment.get("end", 0.0), + "text": segment.get("text", "").strip(), + "confidence": segment.get("confidence", 0.0), + } + ) + + # Update progress + if i % 10 == 0 and total_segments > 0: + progress = 0.3 + 0.7 * (i / total_segments) + self.publish( + "progress", + f"Transcribing segment {i + 1}/{total_segments}", + progress, + ) + + return { + "language": result.get("language"), + "language_probability": result.get("language_probability"), + "segments": segments, + "summary": { + "segment_count": len(segments), + "total_duration": result.get("duration", 0.0), + }, + } + + def save_result(self, result: Dict[str, Any]): + """Save result to output file""" + # Ensure output directory exists + output_dir = os.path.dirname(self.output_path) + if output_dir and not os.path.exists(output_dir): + os.makedirs(output_dir, exist_ok=True) + + with open(self.output_path, "w", encoding="utf-8") as f: + json.dump(result, f, ensure_ascii=False, indent=2) + + self.publish("info", f"Result saved to: {self.output_path}") + + def cleanup(self): + """Clean up temporary resources""" + for file_path in self.cleanup_files: + try: + if os.path.isdir(file_path): + import shutil + + shutil.rmtree(file_path) + elif os.path.exists(file_path): + os.remove(file_path) + except Exception as e: + print(f"[{PROCESSOR_NAME}] Cleanup warning: {e}", file=sys.stderr) + + self.cleanup_files.clear() + self.signal_handler.restore() + + +# Main function +def main(): + parser = argparse.ArgumentParser( + description=f"{PROCESSOR_NAME} Processor - AI-Driven Processor Contract v{CONTRACT_VERSION}", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + + # Required arguments + parser.add_argument("video_path", help="Path to input video file") + parser.add_argument("output_path", help="Path where JSON output should be written") + + # Optional arguments + parser.add_argument( + "--uuid", "-u", default="", help="UUID for Redis progress reporting" + ) + parser.add_argument( + "--check-health", + action="store_true", + help="Perform health check and exit (does not process video)", + ) + + # Hidden/configuration arguments + parser.add_argument( + "--model", default="base", help=argparse.SUPPRESS + ) # Hidden from help + parser.add_argument( + "--chunk-size", type=int, default=300, help=argparse.SUPPRESS + ) # Hidden from help + + args = parser.parse_args() + + # Health check mode + if args.check_health: + health = check_environment() + print(json.dumps(health, indent=2)) + sys.exit(0 if health["status"] == "healthy" else 1) + + # Create Redis publisher if UUID provided + publisher = None + if args.uuid and REDIS_AVAILABLE: + try: + publisher = RedisPublisher(args.uuid) + except Exception as e: + print(f"WARNING: Failed to create Redis publisher: {e}", file=sys.stderr) + + # Create and run processor + processor = ASRProcessor( + video_path=args.video_path, + output_path=args.output_path, + uuid=args.uuid, + model_name=args.model, + chunk_size=args.chunk_size, + publisher=publisher, + ) + + # Validate input + valid, msg = processor.validate_input() + if not valid: + print(f"ERROR: {msg}", file=sys.stderr) + sys.exit(1) + + try: + # Process video + result = processor.process() + + # Save result + processor.save_result(result) + + # Print success message + print(f"[{PROCESSOR_NAME}] Processing completed successfully", file=sys.stderr) + print( + f"[{PROCESSOR_NAME}] Output saved to: {args.output_path}", file=sys.stderr + ) + + sys.exit(0) + + except KeyboardInterrupt: + print(f"[{PROCESSOR_NAME}] Processing interrupted by user", file=sys.stderr) + sys.exit(130) + + except Exception as e: + print(f"ERROR: {e}", file=sys.stderr) + if os.environ.get("ASR_DEBUG") == "1": + print(f"DEBUG: {traceback.format_exc()}", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/installer/build/MomentryCore/tools/script/asr/asr_processor_contract_v2.py b/installer/build/MomentryCore/tools/script/asr/asr_processor_contract_v2.py new file mode 100644 index 00000000..d6c24224 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/asr/asr_processor_contract_v2.py @@ -0,0 +1,604 @@ +#!/opt/homebrew/bin/python3.11 +""" +ASR Processor - AI-Driven Processor Contract Version 2.0 + +Compliant with AI-Driven Processor Contract v1.0 +With unified configuration and timeout handling + +Features: +1. Standardized command-line interface +2. Redis progress reporting +3. Signal handling (SIGTERM, SIGINT) +4. Health check mode +5. Resource monitoring +6. Contract-compliant JSON output +7. Unified configuration with timeout handling +8. Model caching for performance +""" + +import sys +import json +import os +import argparse +import signal +import tempfile +import time +import subprocess +import traceback +import threading +from datetime import datetime +from typing import Dict, Any, Optional, Tuple +import atexit + +# Whisper import at module level for proper error handling +try: + import whisper + + WHISPER_AVAILABLE = True + WHISPER_VERSION = getattr(whisper, "__version__", "unknown") +except ImportError: + WHISPER_AVAILABLE = False + WHISPER_VERSION = None + +# Redis Publisher for progress reporting +try: + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + from redis_publisher import RedisPublisher + + REDIS_AVAILABLE = True +except ImportError: + REDIS_AVAILABLE = False + print( + "WARNING: RedisPublisher not available, progress reporting disabled", + file=sys.stderr, + ) + +# Contract version +CONTRACT_VERSION = "1.0" +PROCESSOR_NAME = "asr" +PROCESSOR_VERSION = "2.1.0" + +# Unified configuration defaults +DEFAULT_OVERALL_TIMEOUT = 3600 # 1 hour +DEFAULT_PROCESS_TIMEOUT = 1800 # 30 minutes +DEFAULT_CHUNK_TIMEOUT = 300 # 5 minutes +DEFAULT_MODEL_SIZE = "medium" +DEFAULT_DEVICE = "cpu" +DEFAULT_LANGUAGE = "auto" + + +# Signal handling with timeout support +class SignalHandler: + """Handle system signals for graceful shutdown""" + + def __init__(self): + self.shutdown_requested = False + self.timeout_reached = False + self.original_handlers = {} + + def setup(self): + """Set up signal handlers""" + self.original_handlers[signal.SIGTERM] = signal.signal( + signal.SIGTERM, self.handle_signal + ) + self.original_handlers[signal.SIGINT] = signal.signal( + signal.SIGINT, self.handle_signal + ) + + def handle_signal(self, signum, frame): + """Handle received signal""" + signal_name = "SIGTERM" if signum == signal.SIGTERM else "SIGINT" + print( + f"[{PROCESSOR_NAME}] Received {signal_name}, initiating graceful shutdown...", + file=sys.stderr, + ) + self.shutdown_requested = True + + def timeout_handler(self): + """Handle timeout signal""" + print( + f"[{PROCESSOR_NAME}] Processing timeout reached, initiating graceful shutdown...", + file=sys.stderr, + ) + self.timeout_reached = True + self.shutdown_requested = True + + def restore(self): + """Restore original signal handlers""" + for sig, handler in self.original_handlers.items(): + signal.signal(sig, handler) + + +# Timeout manager +class TimeoutManager: + """Manage processing timeouts""" + + def __init__(self, overall_timeout: int, process_timeout: int, chunk_timeout: int): + self.overall_timeout = overall_timeout + self.process_timeout = process_timeout + self.chunk_timeout = chunk_timeout + self.start_time = time.time() + self.timeout_thread = None + self.timeout_event = threading.Event() + + def start_overall_timer(self): + """Start overall timeout timer""" + if self.overall_timeout > 0: + self.timeout_thread = threading.Thread( + target=self._overall_timeout_watcher, daemon=True + ) + self.timeout_thread.start() + + def _overall_timeout_watcher(self): + """Watch for overall timeout""" + time.sleep(self.overall_timeout) + if not self.timeout_event.is_set(): + self.timeout_event.set() + print( + f"[{PROCESSOR_NAME}] Overall timeout ({self.overall_timeout}s) reached", + file=sys.stderr, + ) + + def check_timeout(self, operation: str = "processing") -> Tuple[bool, str]: + """Check if timeout has been reached""" + elapsed = time.time() - self.start_time + + if self.timeout_event.is_set(): + return True, f"{operation} timeout reached" + + if self.overall_timeout > 0 and elapsed > self.overall_timeout: + return True, f"Overall timeout ({self.overall_timeout}s) reached" + + return False, "" + + def get_remaining_time(self, timeout_type: str = "overall") -> float: + """Get remaining time for specified timeout type""" + elapsed = time.time() - self.start_time + + if timeout_type == "overall": + return max(0, self.overall_timeout - elapsed) + elif timeout_type == "process": + return max(0, self.process_timeout - elapsed) + elif timeout_type == "chunk": + return max(0, self.chunk_timeout - elapsed) + + return 0.0 + + def cleanup(self): + """Clean up timeout resources""" + self.timeout_event.set() + if self.timeout_thread and self.timeout_thread.is_alive(): + self.timeout_thread.join(timeout=1.0) + + +# Health check functions +def check_environment() -> Dict[str, Any]: + """Check environment and dependencies""" + checks = [] + + # Check 1: Whisper + if WHISPER_AVAILABLE: + checks.append( + { + "name": "whisper", + "status": "available", + "version": WHISPER_VERSION, + } + ) + else: + checks.append({"name": "whisper", "status": "missing", "version": None}) + + # Check 2: FFmpeg/FFprobe + try: + result = subprocess.run(["ffprobe", "-version"], capture_output=True, text=True) + if result.returncode == 0: + version_line = result.stdout.split("\n")[0] + checks.append( + {"name": "ffprobe", "status": "available", "version": version_line} + ) + else: + checks.append({"name": "ffprobe", "status": "error", "version": None}) + except Exception: + checks.append({"name": "ffprobe", "status": "missing", "version": None}) + + # Check 3: Redis (optional) + if REDIS_AVAILABLE: + checks.append({"name": "redis", "status": "available", "version": "1.0.0"}) + else: + checks.append({"name": "redis", "status": "optional_missing", "version": None}) + + # Check 4: Python version + checks.append( + { + "name": "python", + "status": "available", + "version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}", + } + ) + + return {"status": "healthy", "dependencies": checks} + + +# Model cache for performance +_model_cache = {} + + +def get_whisper_model(model_size: str = "medium", device: str = "cpu"): + """Get Whisper model with caching""" + if not WHISPER_AVAILABLE: + raise RuntimeError("Whisper library not available") + + cache_key = f"{model_size}_{device}" + + if cache_key in _model_cache: + return _model_cache[cache_key] + + try: + print(f"[{PROCESSOR_NAME}] Loading Whisper model: {model_size} on {device}") + model = whisper.load_model(model_size, device=device) + _model_cache[cache_key] = model + return model + except Exception as e: + raise RuntimeError(f"Failed to load Whisper model: {e}") + + +# Main processor class +class ASRProcessor: + """ASR Processor compliant with AI-Driven Processor Contract""" + + def __init__( + self, + video_path: str, + output_path: str, + uuid: Optional[str] = None, + check_health: bool = False, + model_size: Optional[str] = None, + device: Optional[str] = None, + language: Optional[str] = None, + ): + self.video_path = video_path + self.output_path = output_path + self.uuid = uuid or "" + self.check_health = check_health + + # Get unified configuration: command-line args override environment variables + self.overall_timeout = int( + os.environ.get("MOMENTRY_ASR_TIMEOUT", str(DEFAULT_OVERALL_TIMEOUT)) + ) + self.process_timeout = int( + os.environ.get("MOMENTRY_ASR_PROCESS_TIMEOUT", str(DEFAULT_PROCESS_TIMEOUT)) + ) + self.chunk_timeout = int( + os.environ.get("MOMENTRY_ASR_CHUNK_TIMEOUT", str(DEFAULT_CHUNK_TIMEOUT)) + ) + self.model_size = model_size or os.environ.get("MOMENTRY_ASR_MODEL_SIZE", DEFAULT_MODEL_SIZE) + self.device = device or os.environ.get("MOMENTRY_ASR_DEVICE", DEFAULT_DEVICE) + self.language = language or os.environ.get("MOMENTRY_ASR_LANGUAGE", DEFAULT_LANGUAGE) + + # Initialize components + self.publisher = None + if REDIS_AVAILABLE and self.uuid: + try: + self.publisher = RedisPublisher(self.uuid) + except Exception as e: + print( + f"[{PROCESSOR_NAME}] Failed to initialize Redis publisher: {e}", + file=sys.stderr, + ) + + self.timeout_manager = TimeoutManager( + self.overall_timeout, self.process_timeout, self.chunk_timeout + ) + self.signal_handler = SignalHandler() + self.start_time = time.time() + self.cleanup_files = [] + + # Set up signal handling + self.signal_handler.setup() + atexit.register(self.cleanup) + + def publish(self, msg_type: str, message: str, progress: Optional[float] = None): + """Publish message to Redis if available""" + if self.publisher and REDIS_AVAILABLE: + try: + if msg_type == "progress" and progress is not None: + self.publisher.progress( + PROCESSOR_NAME, int(progress * 100), 0, message + ) + else: + getattr(self.publisher, msg_type)(PROCESSOR_NAME, message) + except Exception as e: + print(f"[{PROCESSOR_NAME}] Redis publish error: {e}", file=sys.stderr) + + def validate_input(self) -> Tuple[bool, str]: + """Validate input file""" + if not os.path.exists(self.video_path): + return False, f"Video file not found: {self.video_path}" + + # Check for audio stream + if not self._has_audio_stream(): + return False, f"No audio stream found in: {self.video_path}" + + return True, "Input validation passed" + + def _has_audio_stream(self) -> bool: + """Check if video has audio stream""" + try: + cmd = [ + "ffprobe", + "-v", + "error", + "-select_streams", + "a", + "-show_entries", + "stream=codec_type", + "-of", + "csv=p=0", + self.video_path, + ] + result = subprocess.run(cmd, capture_output=True, text=True) + return "audio" in result.stdout + except Exception: + return False + + def extract_audio(self, video_path: str) -> str: + """Extract audio from video file""" + temp_dir = tempfile.mkdtemp(prefix="asr_audio_") + audio_path = os.path.join(temp_dir, "audio.wav") + self.cleanup_files.append(temp_dir) + + cmd = [ + "ffmpeg", + "-i", + video_path, + "-vn", + "-acodec", + "pcm_s16le", + "-ar", + "16000", + "-ac", + "1", + "-y", + audio_path, + ] + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, timeout=self.chunk_timeout + ) + if result.returncode != 0: + raise RuntimeError(f"FFmpeg failed: {result.stderr}") + + return audio_path + except subprocess.TimeoutExpired: + raise RuntimeError(f"Audio extraction timeout after {self.chunk_timeout}s") + except Exception as e: + raise RuntimeError(f"Audio extraction failed: {e}") + + def transcribe_audio(self, audio_path: str) -> Dict[str, Any]: + """Transcribe audio using Whisper""" + if not WHISPER_AVAILABLE: + raise RuntimeError("Whisper library not available") + + self.publish("info", f"Starting transcription with model: {self.model_size}") + print( + f"[DEBUG] WHISPER_AVAILABLE: {WHISPER_AVAILABLE}, whisper module: {'available' if 'whisper' in globals() else 'not in globals'}" + ) + + try: + model = get_whisper_model(self.model_size, self.device) + print(f"[DEBUG] Model loaded: {model}") + + # Start timeout monitoring for transcription + self.timeout_manager.start_overall_timer() + + # Set language for transcription + language = self.language + if language == "auto": + # For auto, let Whisper handle language detection internally + language = None + self.publish("info", "Language detection will be handled by Whisper") + else: + self.publish("info", f"Using specified language: {language}") + + # Perform transcription + transcribe_language = language if language != "auto" else None + self.publish( + "info", + f"Transcribing audio (language: {transcribe_language if transcribe_language else 'auto'})...", + ) + + result = model.transcribe( + audio_path, + language=transcribe_language, + task="transcribe", + beam_size=5, + best_of=5, + ) + + # Check for timeout during transcription + timeout_reached, timeout_msg = self.timeout_manager.check_timeout( + "transcription" + ) + if timeout_reached: + raise RuntimeError(f"Transcription {timeout_msg}") + + return { + "language": result.get("language"), + "language_probability": result.get("language_probability"), + "segments": [ + { + "start": segment["start"], + "end": segment["end"], + "text": segment["text"].strip(), + } + for segment in result.get("segments", []) + ], + } + + except RuntimeError as e: + if "timeout" in str(e).lower(): + raise + else: + raise RuntimeError(f"Transcription failed: {e}") + except Exception as e: + raise RuntimeError(f"Transcription error: {e}") + + def process(self) -> Dict[str, Any]: + """Main processing method""" + self.publish("info", f"Starting ASR processing: {self.video_path}") + self.publish( + "info", + f"Configuration: timeout={self.overall_timeout}s, model={self.model_size}, device={self.device}", + ) + + # Validate input + is_valid, validation_msg = self.validate_input() + if not is_valid: + raise RuntimeError(f"Input validation failed: {validation_msg}") + + self.publish("info", "Input validation passed") + + # Extract audio + self.publish("info", "Extracting audio from video...") + audio_path = self.extract_audio(self.video_path) + self.publish("progress", "Audio extraction complete", 0.3) + + # Check for timeout + timeout_reached, timeout_msg = self.timeout_manager.check_timeout( + "audio extraction" + ) + if timeout_reached: + raise RuntimeError(f"Audio extraction {timeout_msg}") + + # Transcribe audio + self.publish("info", "Transcribing audio...") + transcription_result = self.transcribe_audio(audio_path) + self.publish("progress", "Transcription complete", 0.8) + + # Check for timeout + timeout_reached, timeout_msg = self.timeout_manager.check_timeout( + "transcription" + ) + if timeout_reached: + raise RuntimeError(f"Transcription {timeout_msg}") + + # Prepare final result + result = { + "processor_name": PROCESSOR_NAME, + "processor_version": PROCESSOR_VERSION, + "contract_version": CONTRACT_VERSION, + "video_path": self.video_path, + "timestamp": datetime.utcnow().isoformat() + "Z", + "processing_time_seconds": time.time() - self.start_time, + "configuration": { + "model_size": self.model_size, + "device": self.device, + "language": self.language, + "timeout_seconds": self.overall_timeout, + }, + **transcription_result, + } + + self.publish("progress", "ASR processing complete", 1.0) + self.publish( + "complete", + f"ASR processing completed successfully in {result['processing_time_seconds']:.1f}s", + ) + + return result + + def cleanup(self): + """Clean up temporary resources""" + self.timeout_manager.cleanup() + self.signal_handler.restore() + + # Clean up temporary files + for path in self.cleanup_files: + try: + if os.path.isdir(path): + import shutil + + shutil.rmtree(path, ignore_errors=True) + elif os.path.exists(path): + os.unlink(path) + except Exception: + pass + + +def main(): + """Main entry point""" + parser = argparse.ArgumentParser( + description="ASR Processor - AI-Driven Processor Contract Version 2.0" + ) + + # Required arguments + parser.add_argument("video_path", help="Path to input video file") + parser.add_argument("output_path", help="Path where JSON output should be written") + + # Optional arguments + parser.add_argument( + "--uuid", "-u", default="", help="UUID for Redis progress reporting" + ) + parser.add_argument( + "--check-health", action="store_true", help="Perform health check and exit" + ) + + # Hidden configuration arguments (following contract) + parser.add_argument("--model-size", help=argparse.SUPPRESS) + parser.add_argument("--device", help=argparse.SUPPRESS) + parser.add_argument("--language", help=argparse.SUPPRESS) + parser.add_argument("--timeout", type=int, help=argparse.SUPPRESS) + + args = parser.parse_args() + + # Health check mode + if args.check_health: + health_result = check_environment() + print(json.dumps(health_result, indent=2)) + sys.exit(0 if health_result["status"] == "healthy" else 1) + + # Create processor + processor = ASRProcessor( + video_path=args.video_path, + output_path=args.output_path, + uuid=args.uuid if args.uuid else None, + check_health=args.check_health, + model_size=args.model_size, + device=args.device, + language=args.language, + ) + + try: + # Process video + result = processor.process() + + # Write output + with open(args.output_path, "w", encoding="utf-8") as f: + json.dump(result, f, indent=2, ensure_ascii=False) + + print(f"[{PROCESSOR_NAME}] Processing completed successfully") + print(f"[{PROCESSOR_NAME}] Output written to: {args.output_path}") + + sys.exit(0) + + except RuntimeError as e: + error_msg = f"ASR processing failed: {e}" + processor.publish("error", error_msg) + print(f"[{PROCESSOR_NAME}] ERROR: {error_msg}", file=sys.stderr) + sys.exit(1) + + except KeyboardInterrupt: + processor.publish("warning", "Processing interrupted by user") + print(f"[{PROCESSOR_NAME}] Processing interrupted by user", file=sys.stderr) + sys.exit(130) # Standard exit code for SIGINT + + except Exception as e: + error_msg = f"Unexpected error: {e}\n{traceback.format_exc()}" + processor.publish("error", error_msg) + print(f"[{PROCESSOR_NAME}] CRITICAL ERROR: {error_msg}", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/installer/build/MomentryCore/tools/script/asr_processor.py b/installer/build/MomentryCore/tools/script/asr_processor.py new file mode 120000 index 00000000..8f1fc525 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/asr_processor.py @@ -0,0 +1 @@ +/Users/accusys/momentry_core/scripts/asr_processor_simplified.py \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/asrx/README.md b/installer/build/MomentryCore/tools/script/asrx/README.md new file mode 100644 index 00000000..fc10dc20 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/asrx/README.md @@ -0,0 +1,273 @@ +# ASRX V2 实现文档 + +## 概述 + +ASRX V2 是改进版说话人分离流程,解决 ASR 多人音混合问题。 + +## 实现状态 + +### ✅ 已完成 + +**1. 多说话人检测模块** (`tools/script/asrx/multi_speaker_detector.py`) + +功能: +- 基于声学特征判断多说话人 +- 中断频率分析 +- 音量变化检测 +- 频谱特征变化 +- 段落细分 + +**2. Qdrant Collection** (`_vad_segments`) + +Schema: +```json +{ + "vectors": {"size": 128, "distance": "Cosine"}, + "payload": { + "file_uuid": "keyword", + "segment_id": "keyword", + "start_time": "float", + "end_time": "float", + "speaker_count": "integer", + "is_multi_speaker": "bool", + "vad_confidence": "float" + } +} +``` + +**3. ASRX V2 主流程** (`tools/script/asrx/asrx_v2_processor.py`) + +流程: +``` +1. ASR 粗分割 → Whisper 输出 +2. VAD 多说话人检测 → 每个段落分析 +3. 重新 Whisper (多说话人段) → 精细分段 +4. 说话人分离 → Pyannote (待集成) +5. Qdrant 存储 → VAD 结果 +``` + +## 技术细节 + +### 多说话人判断标准 + +**中断频率**: +- 阈值: 3.0 次 +- 含义: 语音活动中断次数超过阈值 +- 权重: 0.8 + +**音量变化**: +- 阈值: 0.3 +- 含义: 音量方差超过阈值 +- 权重: 0.6 + +**频谱变化**: +- 阈值: 0.4 +- 含义: 频谱质心标准差超过阈值 +- 权重: 0.7 + +**判断逻辑**: +```python +is_multi_speaker = 至少 2 个指标超过阈值 +confidence = 各指标权重的平均值 +``` + +### 段落细分 + +当检测到多说话人时: +1. 提取音频片段 +2. 检测语音间隙 (gap > 150ms) +3. 按间隙分割 +4. 每个子段标记 speaker_hint + +### 重新转录 + +使用 Whisper small 模型: +- 速度: ~5s/segment +- 准确度: 与 large-v3 相当 +- 适用: 短段落 (< 10s) + +### Qdrant 存储 + +**向量**: 128维特征向量 (TODO: 使用真实特征) + +**用途**: +- 跨文件说话人比对 +- 声学指纹匹配 +- 多说话人模式识别 + +## 使用方法 + +### 基本调用 + +```bash +python3 tools/script/asrx/asrx_v2_processor.py \ + video.mp4 \ + output.asrx.json \ + --uuid +``` + +### 环境变量 + +```bash +# Whisper 模型 +export MOMENTRY_WHISPER_MODEL=large-v3 + +# Qdrant +export QDRANT_URL=http://127.0.0.1:6333 +export QDRANT_API_KEY=Test3200Test3200Test3200 +``` + +### Python API + +```python +from asrx_v2_processor import ASRXV2Processor + +processor = ASRXV2Processor( + video_path="video.mp4", + output_path="output.asrx.json", + file_uuid="abc123" +) + +result = processor.process() +``` + +## 输出格式 + +```json +{ + "status": "has_transcript", + "language": "en", + "segments": [ + { + "start_time": 0.5, + "end_time": 2.3, + "start_frame": 15, + "end_frame": 69, + "text": "Hello everyone", + "speaker_id": "SPEAKER_00" + } + ], + "segment_count": 1, + "v2_features": { + "multi_speaker_segments": 2, + "total_refinements": 3 + } +} +``` + +## 待完成 + +### 集成到主流程 + +**选项 1**: 替换现有 ASRX +- 修改 processor_tools_v3.json +- 指向 asrx_v2_processor.py + +**选项 2**: 并行运行 +- 保留原 ASRX +- 新增 ASRX V2 选项 + +### Pyannote 集成 + +当前使用简化版本,需要: +1. 调用 Pyannote 完整流程 +2. 提取 speaker embeddings +3. 聚类和标记 + +### 真实特征向量 + +当前使用随机向量,需要: +1. 提取声学特征 +2. 训练或使用预训练模型 +3. 生成有意义的向量 + +## 性能评估 + +### 预期改进 + +| 指标 | 改进 | +|------|------| +| 多说话人检测准确率 | +20% | +| 说话人边界准确度 | +15% | +| 文本对齐准确度 | +10% | + +### 性能开销 + +| 步骤 | 时间开销 | +|------|----------| +| ASR 粗分割 | 基准 | +| VAD 分析 | +5% | +| 重新 Whisper | +10-15% (取决于多说话人比例) | +| 总体 | +15-20% | + +### 适用场景 + +**推荐**: +- ✅ 会议录音 +- ✅ 访谈对话 +- ✅ 播客节目 + +**不推荐**: +- ❌ 单人演讲 +- ❌ 音乐视频 +- ❌ 低质量音频 + +## 文件清单 + +``` +tools/script/asrx/ +├── multi_speaker_detector.py # 多说话人检测模块 +├── asrx_v2_processor.py # 主处理流程 +└── README.md # 本文档 + +Qdrant: +└── _vad_segments collection # VAD 结果存储 +``` + +## 测试 + +### 单元测试 + +```bash +# 测试多说话人检测 +python3 -c " +from asrx.multi_speaker_detector import MultiSpeakerDetector +detector = MultiSpeakerDetector() +print(detector) +" +``` + +### 集成测试 + +```bash +# 使用测试视频 +python3 tools/script/asrx/asrx_v2_processor.py \ + test.mp4 \ + test.asrx.json \ + --uuid test_001 +``` + +### 验证 + +```bash +# 检查输出 +cat test.asrx.json | jq '.v2_features' + +# 检查 Qdrant +curl "http://127.0.0.1:6333/collections/_vad_segments" +``` + +## 下一步 + +1. **集成 Pyannote** - 完整说话人分离 +2. **真实特征向量** - 替换随机向量 +3. **参数调优** - 调整阈值 +4. **性能测试** - 大规模评估 +5. **集成到主流程** - Worker 调用 + +--- + +**版本**: v1.0 +**状态**: ✅ 基础实现完成,待集成 +**作者**: Core Team +**日期**: 2026-10-08 \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/asrx/asrx_v2_processor.py b/installer/build/MomentryCore/tools/script/asrx/asrx_v2_processor.py new file mode 100644 index 00000000..82f0d38d --- /dev/null +++ b/installer/build/MomentryCore/tools/script/asrx/asrx_v2_processor.py @@ -0,0 +1,448 @@ +#!/opt/homebrew/bin/python3.11 +""" +ASRX V2 Processor - 多说话人检测和分段优化 + +新流程: +1. ASR 粗分割 +2. VAD 多说话人检测 +3. 重新 Whisper (多说话人段) +4. 说话人分离 +5. VAD 结果存入 Qdrant +""" + +import os +import sys +import json +import subprocess +import tempfile +from pathlib import Path +from typing import List, Dict, Any +import numpy as np + +# 添加模块路径 +SCRIPTS_DIR = os.environ.get( + "MOMENTRY_SCRIPTS_DIR", + os.path.expanduser("~/momentry_core/tools/script") +) +sys.path.insert(0, SCRIPTS_DIR) + +# 添加 asrx_self 路径 +ASRX_SELF_DIR = os.path.join(SCRIPTS_DIR, "asrx_self") +sys.path.insert(0, ASRX_SELF_DIR) + +from asrx.multi_speaker_detector import MultiSpeakerDetector + + +class ASRXV2Processor: + """ASRX V2 处理器""" + + def __init__(self, video_path: str, output_path: str, file_uuid: str): + self.video_path = video_path + self.output_path = output_path + self.file_uuid = file_uuid + self.detector = MultiSpeakerDetector() + + # 配置 + self.whisper_model = os.environ.get("MOMENTRY_WHISPER_MODEL", "large-v3") + self.whisper_bin = "/opt/homebrew/bin/whisper" + + def process(self) -> Dict: + """主处理流程""" + + print(f"[ASRX V2] Starting: {self.file_uuid}") + + # 1. ASR 粗分割 + asr_segments = self._run_asr() + + if not asr_segments: + return { + "status": "no_audio_track", + "segments": [], + "segment_count": 0 + } + + # 2. VAD 多说话人检测 + refined_segments = self._refine_segments_with_vad(asr_segments) + + # 3. 说话人分离 (调用现有 Pyannote) + speaker_segments = self._run_speaker_diarization(refined_segments) + + # 4. 存储 VAD 结果到 Qdrant + self._store_vad_results(refined_segments) + + # 输出结果 + result = { + "status": "has_transcript", + "language": asr_segments[0].get("language", "unknown") if asr_segments else "unknown", + "segments": speaker_segments, + "segment_count": len(speaker_segments), + "v2_features": { + "multi_speaker_segments": sum( + 1 for s in refined_segments + if s.get("is_multi_speaker", False) + ), + "total_refinements": len(refined_segments) - len(asr_segments) + } + } + + # 写入文件 + with open(self.output_path, 'w') as f: + json.dump(result, f, indent=2, ensure_ascii=False) + + print(f"[ASRX V2] Completed: {len(speaker_segments)} segments") + + return result + + def _run_asr(self) -> List[Dict]: + """运行 ASR 获取粗分割""" + + print("[ASRX V2] Running ASR for coarse segmentation...") + + # 使用现有 ASR 脚本 + asr_script = f"{SCRIPTS_DIR}/asr/asr_processor_simplified.py" + + asr_output = self.output_path.replace(".asrx.json", ".asr.json") + + cmd = [ + "/opt/homebrew/bin/python3.11", + asr_script, + self.video_path, + asr_output, + "--model", self.whisper_model + ] + + result = subprocess.run(cmd, capture_output=True, text=True) + + if result.returncode != 0: + print(f"[ASRX V2] ASR failed: {result.stderr}") + return [] + + # 读取 ASR 结果 + with open(asr_output) as f: + asr_data = json.load(f) + + return asr_data.get("segments", []) + + def _refine_segments_with_vad(self, asr_segments: List[Dict]) -> List[Dict]: + """使用 VAD 优化段落分割""" + + print(f"[ASRX V2] Analyzing {len(asr_segments)} segments for multi-speaker...") + + refined_segments = [] + + # 提取完整音频(用于分析) + temp_audio = self._extract_audio() + + for i, segment in enumerate(asr_segments): + start = segment.get("start", segment.get("start_time", 0)) + end = segment.get("end", segment.get("end_time", 0)) + + print(f"[ASRX V2] Segment {i+1}/{len(asr_segments)}: {start:.2f}-{end:.2f}s") + + # VAD 多说话人检测 + vad_result = self.detector.analyze_segment( + temp_audio, start, end + ) + + if vad_result["is_multi_speaker"]: + print(f" → Multi-speaker detected: {vad_result['reasons']}") + + # 重新 Whisper 每个子段 + for sub_seg in vad_result["sub_segments"]: + new_seg = self._retranscribe_segment( + sub_seg["start"], + sub_seg["end"], + sub_seg["speaker_hint"] + ) + new_seg["is_multi_speaker"] = True + new_seg["parent_segment"] = i + refined_segments.append(new_seg) + else: + # 保留原段落 + refined_segment = segment.copy() + refined_segment["is_multi_speaker"] = False + refined_segment["vad_confidence"] = vad_result["confidence"] + refined_segments.append(refined_segment) + + # 清理临时文件 + if os.path.exists(temp_audio): + os.remove(temp_audio) + + print(f"[ASRX V2] Refined to {len(refined_segments)} segments") + + return refined_segments + + def _extract_audio(self) -> str: + """提取音频到临时文件""" + + temp_audio = tempfile.mktemp(suffix=".wav") + + cmd = [ + "ffmpeg", "-y", "-i", self.video_path, + "-vn", "-acodec", "pcm_s16le", + "-ar", "16000", "-ac", "1", + temp_audio + ] + + subprocess.run(cmd, capture_output=True) + + return temp_audio + + def _retranscribe_segment( + self, + start: float, + end: float, + speaker_hint: str + ) -> Dict: + """重新转录段落""" + + # 提取片段 + temp_clip = tempfile.mktemp(suffix=".wav") + + cmd = [ + "ffmpeg", "-y", "-i", self.video_path, + "-ss", str(start), "-to", str(end), + "-vn", "-acodec", "pcm_s16le", + "-ar", "16000", "-ac", "1", + temp_clip + ] + + subprocess.run(cmd, capture_output=True) + + # 运行 Whisper + temp_output = tempfile.mktemp(suffix=".json") + + cmd = [ + self.whisper_bin, + temp_clip, + "--model", "small", + "--output_format", "json", + "--output_dir", os.path.dirname(temp_output) or "." + ] + + result = subprocess.run(cmd, capture_output=True) + + # 读取结果 + segment_text = "" + if result.returncode == 0: + # Whisper 输出到 clip 同名文件 + json_file = temp_clip.replace(".wav", ".json") + if os.path.exists(json_file): + with open(json_file) as f: + data = json.load(f) + if data.get("segments"): + segment_text = " ".join( + s.get("text", "") + for s in data["segments"] + ).strip() + + # 清理 + for f in [temp_clip, temp_clip.replace(".wav", ".json")]: + if os.path.exists(f): + os.remove(f) + + return { + "start_time": start, + "end_time": end, + "text": segment_text or f"[Segment {start:.2f}-{end:.2f}]", + "speaker_hint": speaker_hint + } + + def _run_speaker_diarization(self, segments: List[Dict]) -> List[Dict]: + """说话人分离 - 使用 ECAPA-TDNN + Pyannote""" + + print(f"[ASRX V2] Running speaker diarization...") + + # 提取完整音频 + temp_audio = self._extract_audio() + + # 加载声纹编码器 + import sys + sys.path.insert(0, '/Users/accusys/momentry_core/scripts/asrx_self') + from speaker_encoder import load_speaker_encoder, extract_speaker_embedding + + try: + encoder = load_speaker_encoder() + except Exception as e: + print(f"[ASRX V2] Failed to load speaker encoder: {e}") + # 回退到简化版本 + return self._simple_diarization(segments) + + # 为每个段落提取声纹特征 + embeddings = [] + + for seg in segments: + start = seg.get("start_time", seg.get("start", 0)) + end = seg.get("end_time", seg.get("end", 0)) + + # 提取片段 + import soundfile as sf + audio, sr = sf.read(temp_audio, start=int(start * sr), stop=int(end * sr)) + + if len(audio) > 0: + # 提取声纹特征 + embedding = extract_speaker_embedding(encoder, audio, sr) + embeddings.append({ + "segment_idx": len(embeddings), + "embedding": embedding[0].numpy(), # 192维向量 + "segment": seg + }) + + # 清理 + if os.path.exists(temp_audio): + os.remove(temp_audio) + + # 聚类 + from speaker_cluster_fixed import robust_speaker_clustering + + if embeddings: + # 准备聚类输入 + embedding_matrix = np.array([e["embedding"] for e in embeddings]) + + # 聚类 (自动估计说话人数量) + labels, n_speakers = robust_speaker_clustering( + embedding_matrix, + n_speakers=None, # 自动估计 + max_speakers=10 + ) + + # 分配 speaker_id + final_segments = [] + for i, emb_data in enumerate(embeddings): + seg = emb_data["segment"] + speaker_id = f"SPEAKER_{labels[i]:02d}" + + final_segments.append({ + "start_time": seg.get("start_time", seg.get("start", 0)), + "end_time": seg.get("end_time", seg.get("end", 0)), + "start_frame": int(seg.get("start_time", seg.get("start", 0)) * 30), + "end_frame": int(seg.get("end_time", seg.get("end", 0)) * 30), + "text": seg.get("text", ""), + "speaker_id": speaker_id, + "embedding": emb_data["embedding"].tolist() # 存储声纹 + }) + + print(f"[ASRX V2] Speaker diarization: {len(set(labels))} speakers") + return final_segments + else: + return self._simple_diarization(segments) + + def _simple_diarization(self, segments: List[Dict]) -> List[Dict]: + """简化的说话人分离(回退方案)""" + + speaker_map = {} + speaker_counter = 0 + + final_segments = [] + + for seg in segments: + hint = seg.get("speaker_hint") + + if hint and hint not in speaker_map: + speaker_map[hint] = f"SPEAKER_{speaker_counter:02d}" + speaker_counter += 1 + + speaker_id = speaker_map.get(hint, "SPEAKER_00") + + final_segments.append({ + "start_time": seg.get("start_time", seg.get("start", 0)), + "end_time": seg.get("end_time", seg.get("end", 0)), + "start_frame": int(seg.get("start_time", seg.get("start", 0)) * 30), + "end_frame": int(seg.get("end_time", seg.get("end", 0)) * 30), + "text": seg.get("text", ""), + "speaker_id": speaker_id + }) + + return final_segments + + def _store_vad_results(self, segments: List[Dict]): + """存储 VAD 结果到 Qdrant - 使用真实声纹特征""" + + import requests + import uuid as uuid_lib + import numpy as np + + QDRANT_URL = "http://127.0.0.1:6333" + API_KEY = "Test3200Test3200Test3200" + + print(f"[ASRX V2] Storing VAD results to Qdrant...") + + points = [] + + for i, seg in enumerate(segments): + # 只存储多说话人段落或有声纹特征的段落 + if not seg.get("is_multi_speaker") and not seg.get("embedding"): + continue + + # 使用真实声纹特征 (192维) 或降维到 128维 + if seg.get("embedding"): + embedding_192 = np.array(seg["embedding"]) + # PCA 降维到 128维 + # 简单方案:取前 128 维 + embedding_128 = embedding_192[:128] + else: + # 回退到随机向量 + embedding_128 = np.random.randn(128) + + point = { + "id": str(uuid_lib.uuid4()), + "vector": embedding_128.tolist(), + "payload": { + "file_uuid": self.file_uuid, + "segment_id": f"{self.file_uuid}_{i}", + "start_time": seg.get("start_time", 0), + "end_time": seg.get("end_time", 0), + "text": seg.get("text", ""), + "speaker_id": seg.get("speaker_id", "SPEAKER_00"), + "speaker_count": len(seg.get("sub_segments", [])) if seg.get("is_multi_speaker") else 1, + "is_multi_speaker": seg.get("is_multi_speaker", False), + "vad_confidence": seg.get("vad_confidence", 0.0), + "has_embedding": seg.get("embedding") is not None + } + } + + points.append(point) + + if points: + # 批量上传 + batch_size = 100 + for i in range(0, len(points), batch_size): + batch = points[i:i+batch_size] + + response = requests.put( + f"{QDRANT_URL}/collections/_vad_segments/points", + headers={ + "Content-Type": "application/json", + "api-key": API_KEY + }, + json={"points": batch} + ) + + if response.status_code == 200: + print(f"[ASRX V2] Stored batch {i//batch_size + 1}: {len(batch)} points") + else: + print(f"[ASRX V2] Failed to store batch: {response.status_code}") + + print(f"[ASRX V2] Total stored: {len(points)} VAD results to Qdrant") + else: + print(f"[ASRX V2] No multi-speaker segments to store") + + +def main(): + import argparse + + parser = argparse.ArgumentParser(description="ASRX V2 Processor") + parser.add_argument("video_path", help="Input video file") + parser.add_argument("output_path", help="Output JSON path") + parser.add_argument("--uuid", required=True, help="File UUID") + + args = parser.parse_args() + + processor = ASRXV2Processor(args.video_path, args.output_path, args.uuid) + result = processor.process() + + print(f"\n✅ ASRX V2 completed: {result['segment_count']} segments") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/asrx/multi_speaker_detector.py b/installer/build/MomentryCore/tools/script/asrx/multi_speaker_detector.py new file mode 100644 index 00000000..f812f9a5 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/asrx/multi_speaker_detector.py @@ -0,0 +1,257 @@ +""" +多说话人检测模块 +基于声学特征判断是否包含多个说话人 +""" + +import numpy as np +from typing import List, Dict, Tuple +import soundfile as sf + + +class MultiSpeakerDetector: + """检测单个音频段是否包含多个说话人""" + + def __init__( + self, + interruption_threshold: float = 3.0, # 中断次数阈值 + volume_variance_threshold: float = 0.3, # 音量变化阈值 + spectral_variation_threshold: float = 0.4, # 频谱变化阈值 + min_segment_duration: float = 0.5, # 最小分段时长 + ): + self.interruption_threshold = interruption_threshold + self.volume_variance_threshold = volume_variance_threshold + self.spectral_variation_threshold = spectral_variation_threshold + self.min_segment_duration = min_segment_duration + + def analyze_segment( + self, + audio_path: str, + start_time: float, + end_time: float + ) -> Dict: + """ + 分析音频段是否包含多说话人 + + Returns: + { + "is_multi_speaker": bool, + "confidence": float, + "reasons": List[str], + "sub_segments": List[Dict], # 细分的子段 + "features": Dict # 特征值 + } + """ + # 读取音频 + audio, sr = sf.read(audio_path, start=int(start_time * sr), + stop=int(end_time * sr)) + + if len(audio) == 0: + return { + "is_multi_speaker": False, + "confidence": 0.0, + "reasons": [], + "sub_segments": [], + "features": {} + } + + # 计算特征 + features = self._extract_features(audio, sr) + + # 判断是否多说话人 + is_multi, confidence, reasons = self._detect_multi_speaker(features) + + # 如果是多说话人,进行分段 + sub_segments = [] + if is_multi and features["speech_gaps"]: + sub_segments = self._split_by_gaps( + start_time, + end_time, + features["speech_gaps"] + ) + + return { + "is_multi_speaker": is_multi, + "confidence": confidence, + "reasons": reasons, + "sub_segments": sub_segments, + "features": features + } + + def _extract_features(self, audio: np.ndarray, sr: int) -> Dict: + """提取声学特征""" + + # 1. 音量分析 + rms = np.sqrt(np.mean(audio ** 2)) + volume_variance = np.var(audio) + + # 2. 分帧分析 + frame_size = int(0.025 * sr) # 25ms + frame_hop = int(0.010 * sr) # 10ms + + frames = [] + for i in range(0, len(audio) - frame_size, frame_hop): + frames.append(audio[i:i+frame_size]) + + if not frames: + return { + "interruption_count": 0, + "volume_variance": 0.0, + "spectral_variation": 0.0, + "speech_gaps": [] + } + + # 3. 中断检测 + speech_gaps = [] + frame_energies = [np.sqrt(np.mean(f ** 2)) for f in frames] + energy_threshold = np.mean(frame_energies) * 0.5 + + in_speech = frame_energies[0] > energy_threshold if frame_energies else False + speech_start = 0.0 if in_speech else None + + for i, energy in enumerate(frame_energies): + is_speech = energy > energy_threshold + time = i * 0.010 # 10ms hop + + if in_speech and not is_speech: + # 语音结束 + if speech_start is not None: + speech_gaps.append({ + "speech_end": time - 0.010, + "gap_start": time + }) + in_speech = False + elif not in_speech and is_speech: + # 语音开始 + if speech_gaps: + speech_gaps[-1]["gap_end"] = time + in_speech = True + speech_start = time + + # 过滤短间隙 + valid_gaps = [] + for gap in speech_gaps: + if "gap_end" in gap: + gap_duration = gap["gap_end"] - gap["gap_start"] + if gap_duration > 0.15: # > 150ms + valid_gaps.append(gap) + + interruption_count = len(valid_gaps) + + # 4. 频谱变化 + spectral_features = [] + for frame in frames[:min(50, len(frames))]: # 最多50帧 + # 简单的频谱质心 + spectrum = np.abs(np.fft.rfft(frame)) + freqs = np.fft.rfftfreq(len(frame), 1/sr) + centroid = np.sum(freqs * spectrum) / np.sum(spectrum) + spectral_features.append(centroid) + + spectral_variation = np.std(spectral_features) / np.mean(spectral_features) if spectral_features else 0.0 + + return { + "interruption_count": interruption_count, + "volume_variance": float(volume_variance), + "spectral_variation": float(spectral_variation), + "speech_gaps": valid_gaps, + "rms": float(rms) + } + + def _detect_multi_speaker(self, features: Dict) -> Tuple[bool, float, List[str]]: + """判断是否包含多个说话人""" + + reasons = [] + scores = [] + + # 1. 中断次数 + if features["interruption_count"] >= self.interruption_threshold: + reasons.append("high_interruption_rate") + scores.append(0.8) + + # 2. 音量变化 + if features["volume_variance"] > self.volume_variance_threshold: + reasons.append("significant_volume_change") + scores.append(0.6) + + # 3. 频谱变化 + if features["spectral_variation"] > self.spectral_variation_threshold: + reasons.append("spectral_variation") + scores.append(0.7) + + is_multi = len(reasons) >= 2 # 至少2个指标 + confidence = np.mean(scores) if scores else 0.0 + + return is_multi, float(confidence), reasons + + def _split_by_gaps( + self, + start_time: float, + end_time: float, + gaps: List[Dict] + ) -> List[Dict]: + """根据间隙分割段落""" + + sub_segments = [] + last_end = start_time + + for gap in gaps: + # 前一段 + if gap["speech_end"] - last_end >= self.min_segment_duration: + sub_segments.append({ + "start": last_end, + "end": gap["speech_end"], + "speaker_hint": f"S{len(sub_segments)}" + }) + + last_end = gap.get("gap_end", gap["speech_end"]) + + # 最后一段 + if end_time - last_end >= self.min_segment_duration: + sub_segments.append({ + "start": last_end, + "end": end_time, + "speaker_hint": f"S{len(sub_segments)}" + }) + + return sub_segments + + +def analyze_asr_segment_for_multi_speaker( + audio_path: str, + start_time: float, + end_time: float, + detector: MultiSpeakerDetector = None +) -> Dict: + """ + 便捷函数:分析单个 ASR 段落 + + Args: + audio_path: 音频文件路径 + start_time: 开始时间(秒) + end_time: 结束时间(秒) + detector: 检测器实例(可选) + + Returns: + 分析结果字典 + """ + if detector is None: + detector = MultiSpeakerDetector() + + return detector.analyze_segment(audio_path, start_time, end_time) + + +if __name__ == "__main__": + # 测试代码 + import sys + + if len(sys.argv) < 4: + print("Usage: python multi_speaker_detector.py ") + sys.exit(1) + + audio_path = sys.argv[1] + start_time = float(sys.argv[2]) + end_time = float(sys.argv[3]) + + result = analyze_asr_segment_for_multi_speaker(audio_path, start_time, end_time) + + import json + print(json.dumps(result, indent=2)) \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/asrx_processor.py b/installer/build/MomentryCore/tools/script/asrx_processor.py new file mode 120000 index 00000000..65a06869 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/asrx_processor.py @@ -0,0 +1 @@ +/Users/accusys/momentry_core/scripts/asrx_processor.py \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/cut/cut_processor.py b/installer/build/MomentryCore/tools/script/cut/cut_processor.py new file mode 100755 index 00000000..0c05c062 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/cut/cut_processor.py @@ -0,0 +1,301 @@ +#! /opt/homebrew/bin/python3.11 +""" +CUT Processor - Scene Detection & Video Quality Check +Dual-detector: ffprobe scene filter + PySceneDetect ContentDetector (merged). +Always produces at least 1 scene. +""" + +import json +import argparse +import os +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + +try: + from scenedetect import open_video, SceneManager + from scenedetect.detectors import ContentDetector, AdaptiveDetector + + HAS_SCENEDETECT = True +except ImportError: + HAS_SCENEDETECT = False + + +def get_video_info(video_path: str) -> dict: + """Get video info via ffprobe""" + try: + result = subprocess.run( + [ + "ffprobe", + "-v", + "quiet", + "-print_format", + "json", + "-show_format", + "-show_streams", + video_path, + ], + capture_output=True, + text=True, + timeout=30, + ) + info = json.loads(result.stdout) + for stream in info.get("streams", []): + if stream.get("codec_type") == "video": + nb_frames = stream.get("nb_frames") + if nb_frames: + fr = stream.get("r_frame_rate", "0/1") + fps = eval(fr) if "/" in fr else float(fr) + return { + "frame_count": int(nb_frames), + "fps": fps, + "duration": float(stream.get("duration", 0)), + "width": int(stream.get("width", 0)), + "height": int(stream.get("height", 0)), + "codec": stream.get("codec_name", ""), + } + dur = float(stream.get("duration", 0)) + afr = stream.get("avg_frame_rate", "0/1") + avg_fps = eval(afr) if "/" in afr else float(afr) + if dur > 0 and avg_fps > 0: + return { + "frame_count": int(dur * avg_fps), + "fps": avg_fps, + "duration": dur, + "width": int(stream.get("width", 0)), + "height": int(stream.get("height", 0)), + "codec": stream.get("codec_name", ""), + } + return { + "frame_count": 0, + "fps": 0.0, + "duration": dur, + "width": 0, + "height": 0, + "codec": "", + } + return { + "frame_count": 0, + "fps": 0.0, + "duration": 0, + "width": 0, + "height": 0, + "codec": "", + } + except Exception: + return { + "frame_count": 0, + "fps": 0.0, + "duration": 0, + "width": 0, + "height": 0, + "codec": "", + } + + +def detect_scenes_ffmpeg(video_path: str, fps: float, duration: float) -> list: + """Detect scene change times using ffmpeg scene filter + + Returns: + List of cut times in seconds (empty if failed or no cuts found) + """ + try: + result = subprocess.run( + [ + "ffprobe", + "-v", + "quiet", + "-show_entries", + "frame=pts_time", + "-of", + "default=nk=0", + "-f", + "lavfi", + f"movie={video_path},select='gt(scene\\,0.3)',showinfo", + "-show_frames", + ], + capture_output=True, + text=True, + timeout=300, + ) + times = set() + for line in (result.stderr + "\n" + result.stdout).split("\n"): + for prefix in ("pts_time=", "pts_time:"): + if prefix in line: + rest = line.split(prefix)[1].split()[0] + try: + t = float(rest) + times.add(t) + except ValueError: + pass + return sorted(times) + except Exception: + return [] + + +def detect_scenes_scenedetect(video_path: str, fps: float, duration: float) -> list: + """Detect scene change times using PySceneDetect (ContentDetector + AdaptiveDetector) + + Runs both detectors and merges results for maximum recall. + + Returns: + List of cut times in seconds (empty if failed or no cuts found) + """ + if not HAS_SCENEDETECT: + return [] + + try: + all_times = set() + + # ContentDetector with lower threshold for higher recall + video = open_video(video_path) + sm = SceneManager() + sm.add_detector(ContentDetector(threshold=15.0)) + sm.detect_scenes(video) + for i, (start_tc, _) in enumerate(sm.get_scene_list()): + if i == 0: + continue + t = start_tc.get_seconds() + if 0 < t < duration: + all_times.add(t) + + # AdaptiveDetector (self-tuning, catches gradual transitions) + video = open_video(video_path) + sm = SceneManager() + sm.add_detector(AdaptiveDetector()) + sm.detect_scenes(video) + for i, (start_tc, _) in enumerate(sm.get_scene_list()): + if i == 0: + continue + t = start_tc.get_seconds() + if 0 < t < duration: + all_times.add(t) + + return sorted(all_times) + except Exception as e: + print(f"[CUT] scenedetect failed: {e}", file=sys.stderr) + return [] + + +def rebuild_scenes( + cut_times: list, fps: float, total_frames: int, duration: float +) -> list: + """Rebuild scene list from sorted cut times + + Args: + cut_times: Sorted list of cut times in seconds + fps: Frames per second + total_frames: Total frame count + duration: Video duration in seconds + + Returns: + List of {scene_number, start_frame, end_frame, start_time, end_time} + """ + scenes = [] + prev_time = 0.0 + prev_frame = 0 + + for i, t in enumerate(cut_times): + end_frame = round(t * fps) + if end_frame > prev_frame: + scenes.append( + { + "scene_number": len(scenes) + 1, + "start_frame": prev_frame, + "end_frame": end_frame - 1, + "start_time": round(prev_time, 2), + "end_time": round(t - (1.0 / fps) if fps > 0 else t, 2), + } + ) + prev_time = t + prev_frame = end_frame + + # Final scene + last_frame = total_frames + if last_frame > prev_frame: + scenes.append( + { + "scene_number": len(scenes) + 1, + "start_frame": prev_frame, + "end_frame": last_frame - 1, + "start_time": round(prev_time, 2), + "end_time": round(duration, 2), + } + ) + + return scenes + + +def process_cut(video_path: str, output_path: str, uuid: str = ""): + """Process video for scene detection using dual detectors (ffmpeg + scenedetect)""" + + publisher = RedisPublisher(uuid) if uuid else None + if publisher: + publisher.info("cut", "CUT_START") + + vinfo = get_video_info(video_path) + + if publisher: + publisher.info( + "cut", + f"fps={vinfo['fps']}, frames={vinfo['frame_count']}, codec={vinfo['codec']}", + ) + + total_frames = vinfo["frame_count"] + fps = vinfo["fps"] + duration = vinfo["duration"] + + # Phase 1: ffmpeg scene filter + cut_times_ffmpeg = detect_scenes_ffmpeg(video_path, fps, duration) + + # Phase 2: scenedetect ContentDetector + cut_times_sd = detect_scenes_scenedetect(video_path, fps, duration) + + # Merge: union of cut points from both detectors + all_cut_times = sorted(set(cut_times_ffmpeg + cut_times_sd)) + scenes = rebuild_scenes(all_cut_times, fps, total_frames, duration) + + # Always ensure at least 1 scene + if not scenes and total_frames > 0: + scenes = [ + { + "scene_number": 1, + "start_frame": 0, + "end_frame": total_frames - 1, + "start_time": 0.0, + "end_time": round(duration, 2), + } + ] + if publisher: + publisher.info( + "cut", "No scene changes detected, using whole video as single scene" + ) + + result = { + "frame_count": total_frames, + "fps": round(fps, 2), + "scenes": scenes, + } + + with open(output_path, "w") as f: + json.dump(result, f, indent=2) + + if publisher: + publisher.complete( + "cut", + f"{len(scenes)} scenes ({len(cut_times_ffmpeg)} ffmpeg + {len(cut_times_sd)} scenedetect)", + ) + + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Scene Detection") + parser.add_argument("video_path", help="Path to video file") + parser.add_argument("output_path", help="Output JSON path") + parser.add_argument("--uuid", "-u", help="UUID for Redis progress", default="") + args = parser.parse_args() + + process_cut(args.video_path, args.output_path, args.uuid) diff --git a/installer/build/MomentryCore/tools/script/embedding/embeddinggemma_server.py b/installer/build/MomentryCore/tools/script/embedding/embeddinggemma_server.py new file mode 100644 index 00000000..a0b97082 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/embedding/embeddinggemma_server.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""EmbeddingGemma HTTP server - Metal GPU (MPS) accelerated, compatible with M4/M5.""" + +import argparse, json, time, torch +from flask import Flask, request, jsonify +from transformers import AutoModel, AutoTokenizer +import numpy as np + +app = Flask(__name__) + +MODEL = None +TOKENIZER = None +DEVICE = None + +def load_model(model_path: str = "google/embeddinggemma-300m"): + global MODEL, TOKENIZER, DEVICE + if MODEL is not None: + return + DEVICE = "mps" if torch.backends.mps.is_available() else "cpu" + dtype = torch.float32 + print(f"[EmbeddingGemma] Loading model on {DEVICE} (dtype={dtype})...") + t0 = time.time() + MODEL = AutoModel.from_pretrained( + model_path, + torch_dtype=dtype, + trust_remote_code=True, + ).eval().to(DEVICE) + TOKENIZER = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + print(f"[EmbeddingGemma] Loaded in {time.time()-t0:.1f}s on {DEVICE}") + +def embed(texts: list[str]) -> list[list[float]]: + inputs = TOKENIZER(texts, padding=True, truncation=True, return_tensors="pt").to(DEVICE) + with torch.no_grad(): + outputs = MODEL(**inputs) + mask = inputs["attention_mask"].unsqueeze(-1).to(outputs.last_hidden_state.dtype) + pooled = (outputs.last_hidden_state * mask).sum(dim=1) / (mask.sum(dim=1) + 1e-9) + pooled = torch.nn.functional.normalize(pooled, p=2, dim=1) + return pooled.cpu().numpy().tolist() + +@app.route("/v1/embeddings", methods=["POST"]) +def embeddings(): + start_time = time.time() + data = request.get_json() + texts = data.get("input", []) + if isinstance(texts, str): + texts = [texts] + if not texts: + return jsonify({"error": "empty input"}), 400 + try: + # Tokenize to get token count + inputs = TOKENIZER(texts, padding=True, truncation=True, return_tensors="pt") + total_tokens = inputs["input_ids"].shape[1] * len(texts) + + # Generate embeddings + emb = embed(texts) + + duration_ms = int((time.time() - start_time) * 1000) + + result = { + "data": [{"embedding": e, "index": i} for i, e in enumerate(emb)], + "model": "embeddinggemma-300m", + "usage": { + "prompt_tokens": total_tokens, + "completion_tokens": 0, + "total_tokens": total_tokens + }, + "timings": { + "duration_ms": duration_ms + } + } + return jsonify(result) + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/health", methods=["GET"]) +def health(): + return jsonify({"status": "ok", "device": str(DEVICE)}) + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--port", type=int, default=11436) + parser.add_argument("--model", type=str, default="google/embeddinggemma-300m") + args = parser.parse_args() + load_model(args.model) + app.run(host="0.0.0.0", port=args.port, threaded=True) diff --git a/installer/build/MomentryCore/tools/script/face/face_processor.py b/installer/build/MomentryCore/tools/script/face/face_processor.py new file mode 100644 index 00000000..f867f5ce --- /dev/null +++ b/installer/build/MomentryCore/tools/script/face/face_processor.py @@ -0,0 +1,434 @@ +#!/opt/homebrew/bin/python3.11 +""" +Face Processor V2 - Apple Vision detection + CoreML FaceNet embedding + +Flow: +1. swift_face (Vision/ANE) → bbox + pose per frame +2. cv2 opens video, crops faces from bbox +3. CoreML FaceNet → 512D embedding per face +4. Output face.json in standard format + +Replaces face_processor.py (no more InsightFace CPU detection). +Detection cost: near-zero CPU (Vision ANE) +Embedding cost: near-zero CPU (CoreML ANE) +""" + +import re +import sys +import os +import json +import argparse +import subprocess +import time +from typing import Optional, Dict + +import cv2 +import numpy as np +from pathlib import Path + +# CoreML +import coremltools as ct + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils")) +from redis_publisher import RedisPublisher +from qdrant_faces import push_face_embeddings_batch + +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +SWIFT_BIN = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "release", "swift_face") +SWIFT_BIN_DEBUG = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "debug", "swift_face") +# FIX: Correct path to facenet512.mlpackage (project root models/) +# SCRIPT_DIR = tools/script/face/, so we need ../../.. to reach project root +FACENET_PATH = os.path.join(SCRIPT_DIR, "..", "..", "..", "models", "facenet512.mlpackage") + +# Pose angle classification from roll/yaw +def classify_pose(roll: float, yaw: float) -> str: + """Convert roll/yaw to pose angle label""" + abs_yaw = abs(yaw) + abs_roll = abs(roll) + if abs_yaw < 15 and abs_roll < 15: + return "frontal" + elif abs_yaw > 30: + return "profile_right" if yaw > 0 else "profile_left" + else: + return "three_quarter" + + +def round_json_numbers(obj): + """Recursively round all float values to 2 decimal places (JSON output only). + + Intentionally leaves Qdrant push payloads untouched (they use raw values). + """ + if isinstance(obj, float): + return round(obj, 2) + if isinstance(obj, dict): + return {k: round_json_numbers(v) for k, v in obj.items()} + if isinstance(obj, list): + return [round_json_numbers(v) for v in obj] + return obj + + +class FaceProcessorVision: + def __init__(self, video_path: str, output_path: str, uuid: str = "", + sample_interval: int = 3, publisher: RedisPublisher = None): + self.video_path = video_path + self.output_path = output_path + self.uuid = uuid + self.sample_interval = sample_interval + self.publisher = publisher + + # Load CoreML FaceNet + self.coreml_model = None + facenet = os.path.normpath(FACENET_PATH) + if os.path.exists(facenet): + try: + self.coreml_model = ct.models.MLModel(facenet) + print(f"[FACE_V2] CoreML FaceNet loaded: {facenet}") + except Exception as e: + print(f"[FACE_V2] CoreML load failed: {e}") + + self.video = None + self.fps = 30.0 + self.total_frames = 0 + self.width = 0 + self.height = 0 + + def open_video(self): + self.video = cv2.VideoCapture(self.video_path) + if not self.video.isOpened(): + raise RuntimeError(f"Cannot open: {self.video_path}") + self.fps = self.video.get(cv2.CAP_PROP_FPS) + self.total_frames = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT)) + self.width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH)) + self.height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT)) + + # Calculate 8Hz sample interval based on FPS + self.sample_interval = max(1, round(self.fps / 8)) + + print(f"[FACE_V2] Video: {self.width}x{self.height}, {self.fps:.1f}fps, {self.total_frames}f") + print(f"[FACE_V2] 8Hz sample interval: {self.fps:.1f}/8 = {self.sample_interval}") + + def extract_face_embedding(self, face_img: np.ndarray) -> Optional[list]: + """Run CoreML FaceNet on cropped face""" + if self.coreml_model is None: + return None + try: + # Resize to 160x160 + resized = cv2.resize(face_img, (160, 160)) + # Convert HWC to CHW and normalize to [-1, 1] + normalized = (resized.astype(np.float32) / 127.5) - 1.0 + normalized = np.transpose(normalized, (2, 0, 1)) # HWC -> CHW + # Add batch dim: (1, 3, 160, 160) + input_array = np.expand_dims(normalized, axis=0) + result = self.coreml_model.predict({"input": input_array}) + # Find output key (var_xxx) + var_keys = [k for k in result.keys() if k.startswith("var_")] + if not var_keys: + print(f"[FACE_V2] WARNING: No var_ output key found, keys={list(result.keys())}", file=sys.stderr) + return None + emb_key = var_keys[0] + emb = result[emb_key].flatten().tolist() + return emb + except Exception as e: + import traceback + print(f"[FACE_V2] Embedding error: {e}", file=sys.stderr) + print(f"[FACE_V2] Traceback: {traceback.format_exc()}", file=sys.stderr) + return None + + def process_with_swift(self) -> Dict: + """Step 1: Run swift_face to get bbox (generates face_detect.json only) + + Note: swift_face only does face detection. + Pose and appearance expansion happen later via separate processors: + - swift_pose_expansion reads face_traced.json (with trace_id) + - swift_appearance_expansion reads pose.json + """ + print(f"[FACE_V2] Step 1: Vision detection (face only)...") + + # Build swift_face if missing or stale (source newer than binary) + src = os.path.join(SCRIPT_DIR, "swift_processors", "swift_face.swift") + def _stale(bin_path): + return os.path.exists(bin_path) and os.path.exists(src) and \ + os.path.getmtime(src) > os.path.getmtime(bin_path) + if _stale(SWIFT_BIN): + print(f"[FACE_V2] swift_face release binary stale (source newer), removing to force rebuild...") + os.remove(SWIFT_BIN) + if _stale(SWIFT_BIN_DEBUG): + os.remove(SWIFT_BIN_DEBUG) + if not os.path.exists(SWIFT_BIN) and not os.path.exists(SWIFT_BIN_DEBUG): + build_dir = os.path.join(SCRIPT_DIR, "swift_processors") + print(f"[FACE_V2] Building swift_face in {build_dir}...") + subprocess.run( + ["swift", "build", "-c", "release", "--product", "swift_face"], + cwd=build_dir, check=True + ) + + # Determine which binary to use + swift_bin = SWIFT_BIN if os.path.exists(SWIFT_BIN) else SWIFT_BIN_DEBUG + + swift_face_out = self.output_path.replace(".json", "_detect.json") + + cmd = [ + swift_bin, + self.video_path, + swift_face_out, + "--sample-interval", str(self.sample_interval), + ] + if self.uuid: + cmd.extend(["--uuid", self.uuid]) + + print(f"[FACE_V2] Running: {' '.join(cmd)}") + # Log face detection settings being passed to swift_face. + # Defaults mirror src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT (0.5 / 1). + min_conf = os.environ.get("FACE_MIN_CONFIDENCE", "not set (default 0.5)") + min_size = os.environ.get("FACE_MIN_SIZE", "not set (default 1)") + print(f"[FACE_V2] Settings passed to swift_face: FACE_MIN_CONFIDENCE={min_conf}, FACE_MIN_SIZE={min_size}") + t0 = time.time() + log_path = swift_face_out + ".log" + log_f = open(log_path, "w") + # Pass environment variables to swift_face subprocess (FACE_MIN_CONFIDENCE, FACE_MIN_SIZE) + proc = subprocess.Popen(cmd, stdout=log_f, stderr=subprocess.STDOUT, text=True, env=os.environ) + last_pct = -1 + while proc.poll() is None: + time.sleep(10) + # Read latest log lines + try: + with open(log_path) as lf: + for line in lf: + line = line.strip() + m = re.search(r'(\d+)% complete', line) + if m: + pct = int(m.group(1)) + if pct > last_pct: + last_pct = pct + if self.publisher: + self.publisher.progress("face", pct, 100, f"swift detect {pct}%") + except Exception: + pass + log_f.close() + if proc.returncode != 0: + stderr_out = proc.stderr.read() if proc.stderr else "" + if stderr_out: + print(stderr_out.strip(), file=sys.stderr) + raise RuntimeError(f"swift_face exited with code {proc.returncode}") + + elapsed = time.time() - t0 + print(f"[FACE_V2] Detection done in {elapsed:.1f}s") + + with open(swift_face_out) as f: + face_data = json.load(f) + + return face_data + + def embed_and_save(self, detection_data: Dict): + """Step 2: Crop faces + CoreML embedding + save face.json""" + print(f"[FACE_V2] Step 2: CoreML embedding...") + + frames = detection_data.get("frames", []) + self.open_video() + + face_data = { + "metadata": { + "video_path": os.path.abspath(self.video_path), + "fps": self.fps, "width": self.width, "height": self.height, + "sample_interval": self.sample_interval, + "detection_method": "apple_vision", + "embedding_method": "coreml_facenet", + "status": "in_progress", + "total_frames": self.total_frames, + }, + "frames": {} + } + + t0 = time.time() + embed_count = 0 + total_face_count = 0 + last_pct = -1 + all_embeddings = [] # Collect embeddings for Qdrant push + + for frame_info in frames: + frame_num = frame_info["frame"] + faces = [] + for face_idx, face in enumerate(frame_info.get("faces", [])): + bb = face["bbox"] + x, y, w, h = bb["x"], bb["y"], bb["width"], bb["height"] + + if w <= 10 or h <= 10: + continue # skip tiny faces + + # Seek to frame and read + self.video.set(cv2.CAP_PROP_POS_FRAMES, frame_num) + ret, frame = self.video.read() + if not ret: + print(f"[FACE_V2] WARNING: video.read() failed at frame {frame_num}", file=sys.stderr) + continue + + # Crop face + x1, y1 = max(0, x), max(0, y) + x2, y2 = min(self.width, x + w), min(self.height, y + h) + if x2 <= x1 or y2 <= y1: + print(f"[FACE_V2] WARNING: invalid crop at frame {frame_num}: bbox={bb}", file=sys.stderr) + continue + face_img = frame[y1:y2, x1:x2] + if face_img.size == 0: + print(f"[FACE_V2] WARNING: empty crop at frame {frame_num}", file=sys.stderr) + continue + + # CoreML embedding - push to Qdrant _faces collection + emb = self.extract_face_embedding(face_img) + if emb is None: + print(f"[FACE_V2] WARNING: embedding failed at frame {frame_num}", file=sys.stderr) + if emb is not None: + embed_count += 1 + # Collect for batch Qdrant push + # Use face_idx to distinguish multiple faces in same frame + all_embeddings.append({ + "frame": frame_num, + "trace_id": face_idx, # Use face_idx as unique identifier within frame + "bbox": {"x": x, "y": y, "width": w, "height": h}, + "confidence": face.get("confidence", 0.5), + "capture_quality": face.get("captureQuality", 0), + "embedding": emb, + }) + + # Pose classification + pose_info = face.get("pose", {}) + pose_angle = classify_pose( + pose_info.get("roll", 0), + pose_info.get("yaw", 0) + ) + + faces.append({ + "x": x, "y": y, "width": w, "height": h, + "confidence": face.get("confidence", 0.5), + "captureQuality": face.get("captureQuality", 0), + "pose_angle": { + "angle": pose_angle, + "roll": pose_info.get("roll", 0), + "yaw": pose_info.get("yaw", 0), + "pitch": pose_info.get("pitch", 0), + }, + "lips": face.get("lips"), + "landmarks": face.get("landmarks"), + "attributes": None, + }) + + if faces: + face_data["frames"][str(frame_num)] = { + "frame_number": frame_num, + "time_seconds": frame_info.get("timestamp", frame_num / self.fps), + "time_formatted": f"{frame_num / self.fps:.1f}s", + "faces": faces, + } + + if len(face_data["frames"]) % 100 == 0: + elapsed = time.time() - t0 + print(f"[FACE_V2] {len(face_data['frames'])} frames, {elapsed:.0f}s") + if self.publisher: + pct = int(len(face_data["frames"]) * 100 / max(len(frames), 1)) + if pct > last_pct: + last_pct = pct + self.publisher.progress("face", len(face_data["frames"]), len(frames), + "", 0, "faces") + + self.video.release() + + face_data["metadata"]["status"] = "completed" + + # Convert dict frames to list for Rust FaceResult format + frames_list = [] + total_faces = 0 + for fnum_str, fdata in sorted(face_data["frames"].items(), key=lambda x: int(x[0])): + faces = fdata["faces"] + total_faces += len(faces) + frames_list.append({ + "frame": int(fnum_str), + "timestamp": fdata["time_seconds"], + "faces": faces, + }) + + # Determine status based on face count + if total_faces > 0: + status = "has_faces" + else: + status = "no_faces" + + output = { + "status": status, + "frame_count": len(frames_list), + "fps": round(self.fps, 2), + "frames": frames_list, + "total_faces": total_faces, + } + + with open(self.output_path, "w") as f: + json.dump(round_json_numbers(output), f, indent=2, ensure_ascii=False) + + # Push embeddings to Qdrant _faces collection + if all_embeddings: + try: + pushed = push_face_embeddings_batch(self.uuid, all_embeddings, self.publisher) + if pushed != len(all_embeddings): + raise RuntimeError( + f"Qdrant push incomplete: {pushed}/{len(all_embeddings)} embeddings pushed" + ) + except Exception as e: + print(f"[FACE_V2] ERROR: Qdrant push failed: {e}", file=sys.stderr) + raise RuntimeError(f"Qdrant push failed: {e}") + + elapsed = time.time() - t0 + print(f"[FACE_V2] Done: {len(frames_list)} frames, {embed_count} embeddings, {elapsed:.0f}s") + + +def main(): + parser = argparse.ArgumentParser(description="Apple Vision Face Processor V2") + parser.add_argument("video_path", help="Video file path") + parser.add_argument("output_path", help="Output JSON path") + parser.add_argument("--uuid", "-u", default="") + parser.add_argument("--sample-interval", type=int, default=3) + parser.add_argument("--force", action="store_true") + parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS) + args = parser.parse_args() + + publisher = RedisPublisher(args.uuid) if args.uuid else None + if publisher: + publisher.info("face", "FACE_START") + + if args.force and os.path.exists(args.output_path): + os.remove(args.output_path) + + processor = FaceProcessorVision( + args.video_path, args.output_path, + args.uuid, args.sample_interval, publisher + ) + + # Open video to get FPS and calculate sample_interval + processor.open_video() + + # Step 1: Vision detection (bbox + pose via ANE) + try: + detection = processor.process_with_swift() + except Exception as e: + if publisher: + publisher.error("face", f"Detection failed: {e}") + raise + + # Step 2: CoreML embedding + save + try: + processor.embed_and_save(detection) + except Exception as e: + if publisher: + publisher.error("face", f"Embedding failed: {e}") + raise + + if publisher: + publisher.complete("face", f"{len(detection.get('frames',[]))} frames") + + # Clean up temp detection file + swift_out = args.output_path.replace(".json", "_detect.json") + if os.path.exists(swift_out): + os.remove(swift_out) + + +if __name__ == "__main__": + main() diff --git a/installer/build/MomentryCore/tools/script/face/store_traced_faces.py b/installer/build/MomentryCore/tools/script/face/store_traced_faces.py new file mode 100644 index 00000000..901540f5 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/face/store_traced_faces.py @@ -0,0 +1,406 @@ +#!/opt/homebrew/bin/python3.11 +""" +Store Traced Faces - Pipeline integration for face trace + position data + +Flow: +1. Reads face.json output from face_processor.py +2. Runs face_tracker.py to assign trace_id per face (IoU + embedding) +3. Inserts traced faces into face_detections table with trace_id and position (x,y,w,h) + +Usage: + python store_traced_faces.py --file-uuid [--face-json ] + +TKG Export: + trace_id + position (x,y,w,h) per frame enables spatial-temporal graph construction. + Each trace is a temporal entity; position tracks movement across frames. +""" + +import sys +import os +import json +import argparse +from collections import defaultdict +import numpy as np +from datetime import datetime + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils")) +from qdrant_faces import update_trace_ids + +# Config +OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", os.path.expanduser("~/momentry/output_dev")) +SCHEMA = os.environ.get("DATABASE_SCHEMA", "public") + + +def strip_embeddings_and_round(obj): + """Remove face embeddings from face_traced.json and round floats to 2 dp. + + Embeddings live in Qdrant _faces (512D); storing them in the JSON bloats the + file (~2MB+ per 1000 faces). face_tracker consumes embeddings in-memory (loaded + from Qdrant before tracking), so stripping at write time is safe: all downstream + consumers (TKG, clustering, cluster_agent) read Qdrant or trace IDs instead. + """ + if isinstance(obj, dict): + return { + k: strip_embeddings_and_round(v) + for k, v in obj.items() + if not (k == "embedding") + } + if isinstance(obj, list): + return [strip_embeddings_and_round(v) for v in obj] + if isinstance(obj, float): + return round(obj, 2) + return obj + + +def merge_traces_within_cuts(face_data: dict, cut_scenes: list) -> dict: + """Merge traces within the same cut - DISABLED (no embeddings).""" + # TODO: Reimplement with Qdrant _faces collection + return face_data + + +def filter_traces( + face_data: dict, min_trace_len: int = 0, min_confidence: float = 0.0 +) -> dict: + """Optionally drop low-quality traces before writing face_traced.json. + + A trace is dropped when: + - its path length (total_appearances) < min_trace_len, OR + - its avg_confidence < min_confidence (only when min_confidence > 0). + + For every dropped trace, the corresponding faces in `frames` have their + `trace_id` set to None (NOT deleted) so frames/traces stay consistent and + downstream readers (`trace_id is None` → skip) are unaffected. Trace ids of + surviving traces are NOT renumbered. + + Both thresholds default to "no filtering" so existing behaviour is unchanged + unless the caller opts in (env vars / CLI flags). + """ + traces = face_data.get("traces", {}) + if not traces or (min_trace_len <= 0 and min_confidence <= 0.0): + return face_data + + drop_ids = set() + for tid_str, trace in traces.items(): + appearances = trace.get("total_appearances", len(trace.get("path", []))) + avg_conf = trace.get("avg_confidence", 1.0) + if appearances < min_trace_len: + drop_ids.add(tid_str) + elif min_confidence > 0.0 and avg_conf < min_confidence: + drop_ids.add(tid_str) + + if not drop_ids: + return face_data + + # Remove dropped traces from the traces dict + for tid_str in drop_ids: + traces.pop(tid_str, None) + + # Clear trace_id on frames for dropped traces (keep the face detection itself) + drop_ints = {int(t) for t in drop_ids} + for frame_data in face_data.get("frames", {}).values(): + for face in frame_data.get("faces", []): + if face.get("trace_id") in drop_ints: + face["trace_id"] = None + + print( + f"[TRACE] Quality filter: dropped {len(drop_ids)} traces " + f"(min_trace_len={min_trace_len}, min_confidence={min_confidence}), " + f"kept {len(traces)}" + ) + return face_data + + +def run_face_tracker( + face_json_path: str, traced_json_path: str, filter_eyes: bool = False +) -> str: + """Run face_tracker.py on face.json, returns path to face_traced.json""" + from face_tracker import track_faces + + with open(face_json_path) as f: + face_data = json.load(f) + + # Check if faces already have trace_id (from Rust face_tracker) + frames_to_check = face_data.get("frames", {}) + if isinstance(frames_to_check, list): + # List format (FaceResult) + has_trace = any( + face.get("trace_id") is not None + for frame in frames_to_check + for face in frame.get("faces", []) + ) + else: + # Dict format (legacy) + has_trace = any( + face.get("trace_id") is not None + for frame_data in frames_to_check.values() + for face in frame_data.get("faces", []) + ) + + if has_trace: + print(f"[TRACE] face.json already contains trace_id, skipping tracking") + # Copy face.json to traced_json_path (no re-tracking needed) + import shutil + shutil.copy(face_json_path, traced_json_path) + + # ✅ Fix: Update Qdrant trace_id even when skipping tracking + # Build trace_mapping from the copied face_traced.json + with open(traced_json_path) as f: + traced_data = json.load(f) + + trace_mapping = {} + for frame in traced_data.get("frames", []): + frame_num = str(frame.get("frame", 0)) + for face in frame.get("faces", []): + trace_id = face.get("trace_id") + if trace_id is not None: + if trace_id not in trace_mapping: + trace_mapping[trace_id] = [] + trace_mapping[trace_id].append({ + "frame": int(frame_num), + "face_idx": len(trace_mapping[trace_id]) + }) + + if trace_mapping: + print(f"[TRACE] Updating Qdrant trace_ids for {len(trace_mapping)} traces") + update_trace_ids(file_uuid, trace_mapping) + + return traced_json_path + + # V2.0 uses list format (FaceResult), convert to dict for face_tracker + if isinstance(face_data.get("frames"), list): + frames_dict = {} + for frame in face_data["frames"]: + fnum = str(frame["frame"]) + faces = [] + for f in frame.get("faces", []): + bbox = f.get("bbox", f) + face = { + "x": bbox.get("x", f.get("x", 0)), + "y": bbox.get("y", f.get("y", 0)), + "width": bbox.get("width", f.get("width", 0)), + "height": bbox.get("height", f.get("height", 0)), + "confidence": f.get("confidence", 0.0), + "captureQuality": f.get("captureQuality", 0.0), + } + if "landmarks" in f: + face["landmarks"] = f["landmarks"] + if "embedding" in f: + face["embedding"] = f["embedding"] + faces.append(face) + frames_dict[fnum] = { + "frame_number": frame["frame"], + "time_seconds": frame.get("timestamp", 0), + "faces": faces, + } + face_data["frames"] = frames_dict + # Preserve metadata (fps needed by face_tracker) + if "metadata" not in face_data: + face_data["metadata"] = { + "fps": face_data.get("fps", 30.0), + "total_frames": face_data.get("frame_count", 0), + } + + # Eye filter: remove faces without at least one eye landmark + if filter_eyes: + removed = 0 + for fnum_str, frm_data in face_data.get("frames", {}).items(): + faces = frm_data.get("faces", []) + kept = [] + for face in faces: + lm = face.get("landmarks", {}) + if len(lm.get("left_eye", [])) > 0 or len(lm.get("right_eye", [])) > 0: + kept.append(face) + else: + removed += 1 + frm_data["faces"] = kept + print(f"[TRACE] Eye filter: {removed} faces without eyes removed") + + print(f"[TRACE] Processing {len(face_data.get('frames', {}))} frames") + + # Load embeddings from Qdrant _faces collection + file_uuid = ( + face_json_path.split("/")[-1] + .replace(".face.json", "") + .replace("_traced.json", "") + ) + print(f"[TRACE] Loading embeddings from Qdrant for {file_uuid}...") + try: + from qdrant_faces import get_file_faces + + qdrant_points = get_file_faces(file_uuid, with_vector=True) + # Build lookup: (frame, x, y) -> embedding + emb_lookup = {} + for p in qdrant_points: + pl = p.get("payload", {}) + frame = pl.get("frame") + bbox = pl.get("bbox", {}) + x, y = bbox.get("x"), bbox.get("y") + vec = p.get("vector") + if frame is not None and vec: + emb_lookup[(frame, x, y)] = vec + print(f"[TRACE] Loaded {len(emb_lookup)} embeddings from Qdrant") + + # Attach embeddings to face data + attached = 0 + for fnum_str, frm_data in face_data.get("frames", {}).items(): + fnum = int(fnum_str) + for face in frm_data.get("faces", []): + key = (fnum, face.get("x"), face.get("y")) + if key in emb_lookup: + face["embedding"] = emb_lookup[key] + attached += 1 + print(f"[TRACE] Attached {attached} embeddings to face data") + except Exception as e: + print(f"[TRACE] Warning: Failed to load embeddings from Qdrant: {e}") + + # Load cut boundaries from cut.json (same directory as face.json) + cut_boundaries = None + cut_scenes = None + cuts_path = face_json_path.replace("_traced.json", ".cut.json").replace( + ".face.json", ".cut.json" + ) + if os.path.exists(cuts_path): + with open(cuts_path) as f: + cuts = json.load(f) + cut_scenes = cuts.get("scenes", []) + cut_boundaries = {s["start_frame"] for s in cut_scenes if s["start_frame"] > 0} + print(f"[TRACE] Loaded {len(cut_boundaries)} cut boundaries") + + face_data = track_faces( + face_data, use_embedding=True, cut_boundaries=cut_boundaries + ) + + # Merge traces within same cut (same person re-appearing after occlusion/pose change) + if cut_scenes and len(cut_scenes) > 0: + face_data = merge_traces_within_cuts(face_data, cut_scenes) + + # Optional quality filter (opt-in via env; both default to 0 = disabled). + min_trace_len = int(os.environ.get("MOMENTRY_FACE_MIN_TRACE_LEN", "0")) + min_confidence = float(os.environ.get("MOMENTRY_FACE_MIN_CONFIDENCE", "0.0")) + if min_trace_len > 0 or min_confidence > 0.0: + face_data = filter_traces(face_data, min_trace_len, min_confidence) + + metadata = face_data.get("metadata", {}) + metadata["tracking_method"] = "iou_only" + metadata["tracked_at"] = datetime.now().isoformat() + face_data["metadata"] = metadata + + with open(traced_json_path, "w") as f: + json.dump( + strip_embeddings_and_round(face_data), f, indent=2, ensure_ascii=False + ) + + trace_count = len(face_data.get("traces", {})) + print(f"[TRACE] Completed: {trace_count} traces -> {traced_json_path}") + return traced_json_path + + +def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHEMA): + """Update Qdrant _faces collection with trace_id after face tracking. + + face_detections table is deprecated — trace_id is stored only in Qdrant _faces payload. + """ + with open(traced_json_path) as f: + data = json.load(f) + + frames = data.get("frames", {}) + + # Build trace_mapping for Qdrant update: {frame: {bbox_key: trace_id}} + trace_mapping = {} + # Handle both dict and list formats for frames + if isinstance(frames, list): + # New format: frames is a list of frame objects + for frame_data in sorted(frames, key=lambda x: x.get('frame', 0)): + frame_num = frame_data.get('frame') + if frame_num is None: + continue + trace_mapping[frame_num] = {} + for face in frame_data.get("faces", []): + trace_id = face.get("trace_id") + if trace_id is None: + continue + bbox_key = f"{face['x']}_{face['y']}_{face['width']}_{face['height']}" + trace_mapping[frame_num][bbox_key] = trace_id + else: + # Old format: frames is a dict with frame numbers as keys + for frame_num_str, frame_data in sorted(frames.items(), key=lambda x: int(x[0])): + frame_num = int(frame_num_str) + trace_mapping[frame_num] = {} + for face in frame_data.get("faces", []): + trace_id = face.get("trace_id") + if trace_id is None: + continue + bbox_key = f"{face['x']}_{face['y']}_{face['width']}_{face['height']}" + trace_mapping[frame_num][bbox_key] = trace_id + + # Update Qdrant _faces collection with trace_id. + # return_trace_ids=True makes update_trace_ids also return the trace_id set seen + # during its scroll, so we avoid a redundant third full-collection scan below. + trace_ids = set() + try: + qdrant_updated, trace_ids = update_trace_ids( + file_uuid, trace_mapping, return_trace_ids=True + ) + except Exception as e: + print(f"[TRACE] Warning: Qdrant trace_id update failed: {e}") + qdrant_updated = 0 + + # Unique trace count from the update scroll (no extra full scan needed). + qdrant_trace_count = len(trace_ids) + + # Count total faces with trace_id (handle both list and dict formats) + if isinstance(frames, list): + total_faces = sum( + 1 + for fd in frames + for f in fd.get("faces", []) + if f.get("trace_id") is not None + ) + else: + total_faces = sum( + 1 + for fd in frames.values() + for f in fd.get("faces", []) + if f.get("trace_id") is not None + ) + + print( + f"[TRACE] Updated {qdrant_updated} Qdrant points with trace_id, {qdrant_trace_count} unique traces" + ) + return total_faces, qdrant_trace_count + + +def main(): + parser = argparse.ArgumentParser(description="Store traced faces in DB") + parser.add_argument("--file-uuid", required=True, help="Video file UUID") + + parser.add_argument("--face-json", help="Path to face.json (default: auto-detect)") + + parser.add_argument("--uuid", help="UUID for Redis tracking (accepted by executor)") + parser.add_argument( + "--filter-eyes", + action="store_true", + help="Remove faces without eye landmarks before tracking", + ) + args = parser.parse_args() + + face_json = args.face_json or os.path.join( + OUTPUT_DIR, f"{args.file_uuid}.face.json" + ) + traced_json = os.path.join(OUTPUT_DIR, f"{args.file_uuid}.face_traced.json") + + if not os.path.exists(face_json): + print(f"[TRACE] face.json not found: {face_json}", file=sys.stderr) + sys.exit(1) + + # Step 1: Run face tracker + run_face_tracker(face_json, traced_json, filter_eyes=args.filter_eyes) + + # Step 2: Store in Qdrant with trace_id + total, traces = store_traced_faces(args.file_uuid, traced_json) + print(f"[TRACE] Done: {total} detections, {traces} traces") + + +if __name__ == "__main__": + main() diff --git a/installer/build/MomentryCore/tools/script/face/swift_processors b/installer/build/MomentryCore/tools/script/face/swift_processors new file mode 120000 index 00000000..2f2fe4dc --- /dev/null +++ b/installer/build/MomentryCore/tools/script/face/swift_processors @@ -0,0 +1 @@ +../../cli/swift \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/fast_face_clustering_processor.py b/installer/build/MomentryCore/tools/script/fast_face_clustering_processor.py new file mode 100644 index 00000000..359d0cd6 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/fast_face_clustering_processor.py @@ -0,0 +1,655 @@ +#!/opt/homebrew/bin/python3.11 +""" +Face Clustering Processor V3 - Single-stage trace clustering (Stage 2 merge removed) + +Strategy: +1. Load face embeddings from Qdrant _faces collection +2. Group by trace_id, compute weighted average embedding per trace +3. Single-stage AgglomerativeClustering (no Stage 2 merge) +4. Assign person_id to all faces in each trace +5. Output face_cluster.json with auto speaker binding + +Output format: + {"status", "file_uuid", "clusters": [{cluster_id, face_count, representative_face}], "frames": [{frame, timestamp, faces: [{face_id, cluster_id, confidence}]}]} + +Changes from V2: +- Added argparse for CLI arguments +- Added Redis progress reporting +- Added status + file_uuid to output +- Added auto_bind_speakers() integration + +Changes from previous (broken) version: +- REMOVED Stage 2 merge logic (was incorrectly merging different people) +""" + +import argparse +import json +import numpy as np +import os +import sys +from collections import defaultdict +from sklearn.cluster import AgglomerativeClustering + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + + +def round_json_numbers(obj): + """Recursively round all float values to 2 decimal places (JSON output only).""" + if isinstance(obj, float): + return round(obj, 2) + if isinstance(obj, dict): + return {k: round_json_numbers(v) for k, v in obj.items()} + if isinstance(obj, list): + return [round_json_numbers(v) for v in obj] + return obj + +UUID = os.getenv("UUID", "quick_preview") +OUTPUT_DIR = os.getenv("MOMENTRY_OUTPUT_DIR", "./output") +OUTPUT_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.face_clustered.json") +ASRX_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.asrx.json") + +CLUSTER_THRESHOLD = 0.20 # Updated for facenet-pytorch (was 0.15 for CoreML) +CLUSTER_METHOD = "leader" + + +def write_empty_output(status: str, file_uuid: str, output_path: str): + output_data = { + "status": status, + "file_uuid": file_uuid, + "clusters": [], + "frames": [], + } + with open(output_path, "w", encoding="utf-8") as f: + json.dump(output_data, f, indent=2, ensure_ascii=False) + print(f"Wrote empty output ({status}) to {output_path}") + + +def load_qdrant_faces(uuid: str, publisher: RedisPublisher) -> list: + """Load all face points (payload + vector) from Qdrant _faces for a file.""" + publisher.progress("face_cluster", 0, 100, "Loading embeddings from Qdrant") + try: + import requests + + qdrant_url = os.environ.get("QDRANT_URL", "http://localhost:6333") + qdrant_api_key = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200") + headers = {} + if qdrant_api_key: + headers["api-key"] = qdrant_api_key + + all_points = [] + offset = None + while True: + body = { + "limit": 10000, + "with_payload": True, + "with_vector": True, + "filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]}, + } + if offset: + body["offset"] = offset + + resp = requests.post( + f"{qdrant_url}/collections/_faces/points/scroll", + json=body, + headers=headers, + timeout=60, + ) + if resp.status_code != 200: + print(f"Qdrant scroll error: {resp.status_code}") + break + + data = resp.json() + batch = data.get("result", {}).get("points", []) + all_points.extend(batch) + next_offset = data.get("result", {}).get("next_page_offset") + if not next_offset: + break + offset = next_offset + + print(f"Loaded {len(all_points)} points from Qdrant _faces") + return all_points + except Exception as e: + print(f"Failed to load embeddings from Qdrant: {e}") + return [] + + +def cluster_by_trace( + points: list, min_faces_per_trace: int = 1, confidence_threshold: float = 0.5 +) -> tuple: + """ + Cluster faces by trace_id: + 1. Filter low-confidence faces + 2. Group by trace_id + 3. Compute weighted average embedding per trace + """ + high_conf_points = [ + p + for p in points + if p.get("payload", {}).get("confidence", 0) >= confidence_threshold + ] + print( + f"[FILTER] {len(high_conf_points)}/{len(points)} faces pass confidence >= {confidence_threshold}" + ) + + traces = defaultdict(list) + for point in high_conf_points: + payload = point.get("payload", {}) + trace_id = payload.get("trace_id") + if trace_id is not None and trace_id >= 0: + traces[trace_id].append(point) + + print(f"[TRACE] Found {len(traces)} unique traces") + + trace_embeddings = {} + for trace_id, trace_points in traces.items(): + if len(trace_points) < min_faces_per_trace: + continue + + embeddings = [] + weights = [] + for p in trace_points: + embeddings.append(p["vector"]) + weights.append(p.get("payload", {}).get("confidence", 1.0)) + + embeddings = np.array(embeddings) + weights = np.array(weights) + weights = weights / weights.sum() + + avg_embedding = np.average(embeddings, axis=0, weights=weights) + avg_embedding = avg_embedding / np.linalg.norm(avg_embedding) + + trace_embeddings[trace_id] = { + "embedding": avg_embedding, + "face_count": len(trace_points), + "avg_confidence": float(np.mean(weights)), + "frames": [p.get("payload", {}).get("frame") for p in trace_points], + "points": trace_points, + } + + print(f"[TRACE] {len(trace_embeddings)} traces with >= {min_faces_per_trace} faces") + return trace_embeddings, traces + + +def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) -> tuple: + """ + Single-stage AgglomerativeClustering on trace means. + No Stage 2 merge (the problematic logic has been removed). + + Returns: (trace_to_person, trace_similarities) + """ + if not trace_embeddings: + return {}, {} + + trace_ids = list(trace_embeddings.keys()) + n_traces = len(trace_ids) + + if n_traces == 0: + return {}, {} + + if n_traces == 1: + return {trace_ids[0]: 0}, {trace_ids[0]: 1.0} + + embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids]) + + print( + f"[CLUSTER] Agglomerative: {n_traces} traces, distance_threshold={threshold}..." + ) + clustering = AgglomerativeClustering( + n_clusters=None, + distance_threshold=threshold, + metric="cosine", + linkage="average", + ) + labels = clustering.fit_predict(embeddings) + + unique_labels = set(labels) + print(f"[CLUSTER] Detected {len(unique_labels)} unique persons") + + trace_to_person = {} + trace_similarities = {} + for i, trace_id in enumerate(trace_ids): + trace_to_person[trace_id] = labels[i] + # For agglomerative, similarity = 1 - distance to cluster (approximate) + trace_similarities[trace_id] = 1.0 # placeholder; exact requires pairwise + + return trace_to_person, trace_similarities + + +def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tuple: + """ + Seed-leader clustering with incremental mean centroids. + Algorithm: + 1. Iterate traces in stable order (by trace_id). + 2. For each trace, compare its centroid to each existing person's mean centroid. + 3. If max cosine similarity >= (1 - threshold) → assign to that person, update mean. + 4. Else → create new person seeded by this trace. + + threshold: cosine distance threshold (default 0.35 = similarity >= 0.65) + + Returns: (trace_to_person: dict, trace_similarities: dict) + trace_to_person: {trace_id: person_label} + trace_similarities: {trace_id: similarity_to_centroid} + """ + if not trace_embeddings: + return {}, {} + + # Sort by trace_id for deterministic order + trace_ids = sorted(trace_embeddings.keys()) + n_traces = len(trace_ids) + + if n_traces == 0: + return {}, {} + + if n_traces == 1: + return {trace_ids[0]: 0}, {trace_ids[0]: 1.0} + + sim_threshold = 1.0 - threshold # cosine similarity threshold + persons = [] # list of {centroid: np.array, member_trace_ids: []} + trace_similarities = {} + + print( + f"[CLUSTER] Seed-leader: {n_traces} traces, similarity_threshold={sim_threshold:.3f} (distance={threshold})..." + ) + + for trace_id in trace_ids: + centroid = trace_embeddings[trace_id]["embedding"] + + if not persons: + # First trace → seed first person + persons.append( + {"centroid": centroid.copy(), "member_trace_ids": [trace_id]} + ) + trace_similarities[trace_id] = 1.0 # first trace is the centroid + continue + + # Find best matching person by cosine similarity to current mean centroid + best_sim = -1.0 + best_person_idx = -1 + for idx, person in enumerate(persons): + p_centroid = person["centroid"] + norm1 = np.linalg.norm(centroid) + norm2 = np.linalg.norm(p_centroid) + if norm1 > 0 and norm2 > 0: + sim = np.dot(centroid, p_centroid) / (norm1 * norm2) + if sim > best_sim: + best_sim = sim + best_person_idx = idx + + if best_sim >= sim_threshold: + # Assign to this person, update mean centroid (incremental) + persons[best_person_idx]["member_trace_ids"].append(trace_id) + trace_similarities[trace_id] = best_sim + # Recompute mean from all member trace centroids + member_embeddings = np.array( + [ + trace_embeddings[tid]["embedding"] + for tid in persons[best_person_idx]["member_trace_ids"] + ] + ) + persons[best_person_idx]["centroid"] = np.mean(member_embeddings, axis=0) + else: + # New person + persons.append( + {"centroid": centroid.copy(), "member_trace_ids": [trace_id]} + ) + trace_similarities[trace_id] = 1.0 # seed trace is its own centroid + + # Build trace_to_person mapping + trace_to_person = {} + for person_label, person in enumerate(persons): + for tid in person["member_trace_ids"]: + trace_to_person[tid] = person_label + + print(f"[CLUSTER] Seed-leader detected {len(persons)} unique persons") + return trace_to_person, trace_similarities + + +def auto_bind_speakers(output_frames: list, asrx_path: str = ASRX_JSON_PATH) -> dict: + """ + Compute speaker -> Person_N mapping by vote. + Each ASRX segment is matched against face timestamps; the most frequent + person within the segment's time span gets one vote for that speaker. + Returns {"SPEAKER_0": "Person_37", ...}. Pure computation, no DB writes. + """ + if not os.path.exists(asrx_path): + print("Missing data for speaker binding.") + return {} + + try: + with open(asrx_path) as f: + asrx_data = json.load(f) + except Exception as e: + print(f" Failed to load ASRX: {e}") + return {} + + print("Auto-binding Speakers to Persons...") + + face_spans = [] + for frame_obj in output_frames: + ts = frame_obj.get("timestamp") + for face in frame_obj.get("faces", []): + person_id = face.get("cluster_id") + if person_id and ts is not None: + face_spans.append({"ts": ts, "person_id": person_id}) + + speaker_person_counts = {} + + for seg in asrx_data.get("segments", []): + start = seg.get("start_time", seg.get("start")) + end = seg.get("end_time", seg.get("end")) + speaker = seg.get("speaker_id") + if not speaker or start is None or end is None: + continue + candidates = [ + f for f in face_spans if f.get("ts") is not None and start <= f["ts"] <= end + ] + if candidates: + person_counts = {} + for c in candidates: + pid = c["person_id"] + person_counts[pid] = person_counts.get(pid, 0) + 1 + if speaker not in speaker_person_counts: + speaker_person_counts[speaker] = {} + best_person = max(person_counts, key=person_counts.get) + speaker_person_counts[speaker][best_person] = ( + speaker_person_counts[speaker].get(best_person, 0) + 1 + ) + + mapping = {} + for speaker, persons in speaker_person_counts.items(): + if not persons: + continue + best_person = max(persons, key=persons.get) + mapping[speaker] = best_person + print(f" {speaker} is likely {best_person} ({persons[best_person]} votes)") + + return mapping + + +def main(): + global OUTPUT_JSON_PATH, UUID + + parser = argparse.ArgumentParser(description="Face Clustering Processor V3") + parser.add_argument("video_path", help="Path to video file") + parser.add_argument("output_path", help="Path to output JSON file") + parser.add_argument("--uuid", help="Video UUID (optional, overrides env var)") + parser.add_argument( + "--force", action="store_true", help="Overwrite existing output" + ) + parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS) + parser.add_argument( + "--method", + choices=["agglomerative", "leader"], + default="leader", + help="Clustering method: agglomerative (sklearn) or seed-leader (default: leader)", + ) + parser.add_argument( + "--threshold", + type=float, + default=CLUSTER_THRESHOLD, + help=f"Cosine distance threshold for clustering (default: {CLUSTER_THRESHOLD})", + ) + args = parser.parse_args() + + OUTPUT_JSON_PATH = args.output_path + output_dir = os.path.dirname(args.output_path) + if args.uuid: + uuid = args.uuid + else: + uuid = os.path.basename(args.video_path).rsplit(".", 1)[0] + UUID = uuid + + face_json_path = os.path.join(output_dir, f"{uuid}.face.json") + if not os.path.exists(face_json_path): + face_json_path = os.path.join(output_dir, uuid, f"{uuid}.face.json") + + publisher = RedisPublisher(uuid) + publisher.info("face_cluster", "Face clustering started") + + if not os.path.exists(face_json_path): + print("Face JSON not found.") + write_empty_output("no_face_json", uuid, OUTPUT_JSON_PATH) + publisher.complete("face_cluster", "No face.json found") + return + + with open(face_json_path) as f: + face_data = json.load(f) + + frames_list = face_data.get("frames", []) + if not frames_list: + print("No frames in JSON (no faces).") + write_empty_output("no_faces", uuid, OUTPUT_JSON_PATH) + publisher.complete("face_cluster", "No faces to cluster") + return + + fps_value = face_data.get("fps", 23.98) + + points = load_qdrant_faces(uuid, publisher) + if not points: + print("No embeddings found in Qdrant.") + write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH) + publisher.complete("face_cluster", "No embeddings in Qdrant") + return + + publisher.progress("face_cluster", 10, 100, f"Loaded {len(points)} Qdrant points") + + # Count unique traces before filtering + unique_trace_ids = set() + for p in points: + tid = p.get("payload", {}).get("trace_id") + if tid is not None and tid >= 0: + unique_trace_ids.add(tid) + + # Keep all traces for maximum recall. Noise is handled by the + # confidence_threshold filter in cluster_by_trace (0.5), not by + # dropping short traces — short appearances (walk-ons, passers-by) + # are real people and must stay in the dedup pool, even for + # large files with many faces. + min_faces = 1 + print( + f"[CONFIG] unique_traces={len(unique_trace_ids)}, min_faces_per_trace={min_faces}" + ) + + trace_embeddings, traces = cluster_by_trace( + points, min_faces_per_trace=min_faces, confidence_threshold=0.5 + ) + + if not trace_embeddings: + print("No valid traces found.") + write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH) + publisher.complete("face_cluster", "No valid traces") + return + + publisher.progress("face_cluster", 30, 100, f"Found {len(trace_embeddings)} traces") + + # Select clustering method + threshold = args.threshold + method = args.method + if method == "leader": + trace_to_person, trace_similarities = seed_leader_cluster( + trace_embeddings, threshold=threshold + ) + else: + trace_to_person, trace_similarities = single_stage_clustering( + trace_embeddings, threshold=threshold + ) + if not trace_to_person: + print("Clustering produced no results.") + write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH) + publisher.complete("face_cluster", "Clustering empty") + return + + n_persons = len(set(trace_to_person.values())) + print(f"Clustering result: {n_persons} persons ({len(trace_to_person)} traces)") + publisher.progress("face_cluster", 50, 100, f"Found {n_persons} persons") + + # Load face_traced.json to get trace_id for each face + traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json") + traced_frames = {} + if os.path.exists(traced_path): + try: + with open(traced_path) as f: + traced_data = json.load(f) + frames_raw = traced_data.get("frames", {}) + # Handle both dict and list formats + if isinstance(frames_raw, list): + # Convert list to dict for backward compatibility + for frame_obj in frames_raw: + frame_num = frame_obj.get("frame") + if frame_num is not None: + traced_frames[str(frame_num)] = frame_obj + print(f" Loaded face_traced.json: {len(traced_frames)} frames (converted from list)") + elif isinstance(frames_raw, dict): + traced_frames = frames_raw + print(f" Loaded face_traced.json: {len(traced_frames)} frames (dict)") + else: + print(f" Warning: Unexpected frames format: {type(frames_raw)}") + except Exception as e: + print(f" Warning: Failed to load face_traced.json: {e}") + + matched_count = 0 + for frame_idx, frame_obj in enumerate(frames_list): + frame_num = frame_obj.get("frame", frame_idx) + # Get traced faces for this frame + traced_frame = traced_frames.get(str(frame_num), {}) + traced_faces = traced_frame.get("faces", []) + + for face_idx, face in enumerate(frame_obj.get("faces", [])): + # Get trace_id from face_traced.json + trace_id = None + if face_idx < len(traced_faces): + trace_id = traced_faces[face_idx].get("trace_id") + + if trace_id is not None and trace_id in trace_to_person: + person_label = trace_to_person[trace_id] + face["person_id"] = f"Person_{person_label}" + face["trace_id"] = trace_id + matched_count += 1 + + print(f" Assigned person_id to {matched_count} faces") + + if matched_count == 0: + print("No faces matched to any trace - check Qdrant data integrity") + publisher.progress("face_cluster", 100, 100, "No trace matches") + write_empty_output("no_faces", uuid, OUTPUT_JSON_PATH) + return + + publisher.progress("face_cluster", 70, 100, f"Matched {matched_count} faces") + + person_face_count = defaultdict(int) + person_best_face = {} + for frame_idx, frame_obj in enumerate(frames_list): + for face_idx, face in enumerate(frame_obj.get("faces", [])): + person_id = face.get("person_id") + if not person_id: + continue + person_face_count[person_id] += 1 + confidence = face.get("confidence", 0.9) + if ( + person_id not in person_best_face + or confidence > person_best_face[person_id]["confidence"] + ): + person_best_face[person_id] = { + "face_id": f"face_{frame_idx}_{face_idx}", + "confidence": confidence, + "frame": frame_obj.get("frame", frame_idx), + "bbox": { + "x": face.get("x"), + "y": face.get("y"), + "width": face.get("width"), + "height": face.get("height"), + }, + } + + # Build per-person similarity stats from trace_similarities + person_sims = defaultdict(list) + sim_threshold_value = 1.0 - threshold # similarity threshold + for tid, person_label in trace_to_person.items(): + sim = trace_similarities.get(tid, 0.0) + person_sims[person_label].append(sim) + + person_labels_sorted = sorted( + person_face_count.keys(), key=lambda p: -person_face_count[p] + ) + clusters = [] + for person_id in person_labels_sorted: + # Extract person number from "Person_N" to get the integer label + person_label = None + try: + person_label = int(person_id.split("_")[1]) + except (IndexError, ValueError): + pass + + sims = person_sims.get(person_label, []) if person_label is not None else [] + similarity_info = None + if sims: + similarity_info = { + "min": round(float(min(sims)), 4), + "avg": round(float(sum(sims) / len(sims)), 4), + "threshold": round(sim_threshold_value, 4), + } + + cluster_entry = { + "cluster_id": person_id, + "face_count": person_face_count[person_id], + "representative_face": person_best_face.get(person_id), + } + if similarity_info: + cluster_entry["similarity"] = similarity_info + clusters.append(cluster_entry) + + output_frames = [] + for frame_idx, frame_obj in enumerate(frames_list): + timestamp = frame_obj.get( + "timestamp", frame_obj.get("frame", 0) / fps_value if fps_value > 0 else 0 + ) + output_faces = [] + for face_idx, face in enumerate(frame_obj.get("faces", [])): + person_id = face.get("person_id") + if person_id: + output_faces.append( + { + "face_id": f"face_{frame_idx}_{face_idx}", + "cluster_id": person_id, + "trace_id": face.get("trace_id"), + "confidence": face.get("confidence", 0.9), + } + ) + if output_faces: + output_frames.append( + { + "frame": frame_obj.get("frame", frame_idx), + "timestamp": timestamp, + "faces": output_faces, + } + ) + + output_data = { + "status": "has_faces", + "file_uuid": UUID, + "clusters": clusters, + "frames": output_frames, + } + + speaker_mapping = auto_bind_speakers( + output_frames, os.path.join(output_dir, f"{uuid}.asrx.json") + ) + if speaker_mapping: + output_data["speaker_person_mapping"] = speaker_mapping + + with open(OUTPUT_JSON_PATH, "w", encoding="utf-8") as f: + json.dump(round_json_numbers(output_data), f, indent=2, ensure_ascii=False) + print(f"Saved clustered data to {OUTPUT_JSON_PATH}") + publisher.progress("face_cluster", 90, 100, f"{len(clusters)} clusters") + + publisher.complete("face_cluster", f"{len(clusters)} clusters") + if speaker_mapping: + publisher.info( + "face_cluster", + f"Speaker mapping: {len(speaker_mapping)} speakers", + ) + + +if __name__ == "__main__": + main() diff --git a/installer/build/MomentryCore/tools/script/identity/identity_agent.py b/installer/build/MomentryCore/tools/script/identity/identity_agent.py new file mode 100644 index 00000000..07f80539 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/identity/identity_agent.py @@ -0,0 +1,519 @@ +#!/opt/homebrew/bin/python3.11 +""" +Identity Agent - Multi-Evidence Identity Inference + +Core Logic: +1. Time Overlap Matching (Speaker vs Person frames) +2. Embedding Similarity Calculation +3. Multi-Evidence Fusion +4. LLM Inference for Ambiguous Cases +5. Identity Assignment + +Usage: + python3 scripts/identity_agent.py --video-uuid --analyze + python3 scripts/identity_agent.py --video-uuid --suggest +""" + +import sys +import json +import argparse +import os +import numpy as np +from typing import Dict, List, Optional, Tuple +from sklearn.metrics.pairwise import cosine_similarity + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + + +class IdentityAgent: + """ + Identity Agent for Multi-Evidence Identity Inference + + Attributes: + video_uuid (str): Video UUID + output_dir (str): Output directory + fps (float): Video frame rate + auto_merge_threshold (float): Auto merge threshold (default: 0.8) + llm_threshold (float): LLM inference threshold (default: 0.5) + face_similarity_threshold (float): Face similarity threshold (default: 0.3) + use_llm (bool): Use LLM for ambiguous cases + model (str): LLM model name + """ + + def __init__( + self, + video_uuid: str, + output_dir: str = None, + auto_merge_threshold: float = 0.8, + llm_threshold: float = 0.5, + face_similarity_threshold: float = 0.3, + use_llm: bool = True, + model: str = "gemma4", + ): + self.video_uuid = video_uuid + self.output_dir = output_dir or os.getenv( + "MOMENTRY_OUTPUT_DIR", os.path.expanduser("~/momentry/output_dev") + ) + self.auto_merge_threshold = auto_merge_threshold + self.llm_threshold = llm_threshold + self.face_similarity_threshold = face_similarity_threshold + self.use_llm = use_llm + self.model = model + + self.fps = 23.976 # Default FPS + self.face_data = None + self.asrx_data = None + self.persons = [] + self.speakers = [] + self.identities = [] + + self.publisher = RedisPublisher(video_uuid) if video_uuid else None + + def load_data(self) -> bool: + """Load face clustered and ASRX data from files""" + video_dir = os.path.join(self.output_dir, self.video_uuid) + + face_clustered_path = os.path.join( + video_dir, f"{self.video_uuid}.face_clustered.json" + ) + asrx_path = os.path.join(video_dir, f"{self.video_uuid}.asrx.json") + probe_path = os.path.join(video_dir, f"{self.video_uuid}.probe.json") + + if not os.path.exists(face_clustered_path): + print(f"Error: Face clustered data not found: {face_clustered_path}") + return False + + self.face_data = self._load_json(face_clustered_path) + self.asrx_data = self._load_json(asrx_path) if os.path.exists(asrx_path) else None + + if os.path.exists(probe_path): + probe_data = self._load_json(probe_path) + self.fps = probe_data.get("fps", 23.976) + + self.persons = self._extract_persons() + self.speakers = self._extract_speakers() + + print(f"Loaded {len(self.persons)} persons, {len(self.speakers)} speakers") + return True + + def _load_json(self, path: str) -> Dict: + """Load JSON file""" + with open(path, "r", encoding="utf-8") as f: + return json.load(f) + + def _extract_persons(self) -> List[Dict]: + """Extract persons from face clustered data""" + persons = [] + + if not self.face_data: + return persons + + if "clusters" in self.face_data: + for cluster in self.face_data["clusters"]: + person_id = cluster.get("person_id", f"Person_{len(persons) + 1}") + frames = cluster.get("frames", []) + avg_embedding = cluster.get("avg_embedding", None) + + persons.append({ + "person_id": person_id, + "frames": frames, + "frame_count": len(frames), + "avg_embedding": avg_embedding, + "timestamps": [f / self.fps for f in frames], + }) + + return persons + + def _extract_speakers(self) -> List[Dict]: + """Extract speakers from ASRX data""" + speakers = [] + + if not self.asrx_data: + return speakers + + if "segments" in self.asrx_data: + speaker_segments_map = {} + + for segment in self.asrx_data["segments"]: + speaker_id = segment.get("speaker", "SPEAKER_01") + start = segment.get("start", 0.0) + end = segment.get("end", 0.0) + + if speaker_id not in speaker_segments_map: + speaker_segments_map[speaker_id] = [] + + speaker_segments_map[speaker_id].append({"start": start, "end": end}) + + for speaker_id, segments in speaker_segments_map.items(): + total_duration = sum(s["end"] - s["start"] for s in segments) + + speakers.append({ + "speaker_id": speaker_id, + "segments": segments, + "total_duration": total_duration, + }) + + return speakers + + def calculate_speaker_person_overlap( + self, person: Dict, speaker: Dict + ) -> Tuple[int, float]: + """ + Calculate overlap between Person and Speaker + + Returns: + Tuple of (overlap_frames, overlap_ratio) + """ + overlap_frames = 0 + + for frame in person["frames"]: + frame_time = frame / self.fps + + for segment in speaker["segments"]: + if segment["start"] <= frame_time <= segment["end"]: + overlap_frames += 1 + break + + overlap_ratio = overlap_frames / person["frame_count"] if person["frame_count"] > 0 else 0 + + return overlap_frames, overlap_ratio + + def calculate_person_similarity( + self, person1: Dict, person2: Dict + ) -> Optional[float]: + """ + Calculate cosine similarity between two Person embeddings + + Returns: + Similarity score (0-1) or None if embeddings not available + """ + if not person1.get("avg_embedding") or not person2.get("avg_embedding"): + return None + + emb1 = np.array(person1["avg_embedding"]).reshape(1, -1) + emb2 = np.array(person2["avg_embedding"]).reshape(1, -1) + + similarity = cosine_similarity(emb1, emb2)[0][0] + return similarity + + def fuse_evidence( + self, + face_similarity: Optional[float], + speaker_overlap: float, + time_overlap: float, + frame_ratio: float, + ) -> float: + """ + Fuse multiple evidence sources into a single confidence score + + Args: + face_similarity: Cosine similarity between face embeddings (0-1) + speaker_overlap: Speaker-Person overlap ratio (0-1) + time_overlap: Temporal overlap ratio (0-1) + frame_ratio: Person's frame count ratio in video (0-1) + + Returns: + Fused confidence score (0-1) + """ + weights = { + "face": 0.4, + "speaker": 0.3, + "time": 0.2, + "frame": 0.1, + } + + face_score = face_similarity if face_similarity is not None else 0.5 + + confidence = ( + weights["face"] * face_score + + weights["speaker"] * speaker_overlap + + weights["time"] * time_overlap + + weights["frame"] * frame_ratio + ) + + return confidence + + def analyze(self) -> Dict: + """ + Analyze video identity + + Returns: + Identity analysis result + """ + if not self.load_data(): + return {"success": False, "error": "Failed to load data"} + + if self.publisher: + self.publisher.info("identity", "IDENTITY_ANALYZE_START") + + identities = [] + + for i, person in enumerate(self.persons): + identity_id = f"identity_{i + 1}" + + speaker_overlaps = [] + max_overlap = 0.0 + max_speaker_id = None + + for speaker in self.speakers: + overlap_frames, overlap_ratio = self.calculate_speaker_person_overlap( + person, speaker + ) + + if overlap_ratio > 0.3: + speaker_overlaps.append({ + "speaker_id": speaker["speaker_id"], + "overlap_frames": overlap_frames, + "overlap_ratio": overlap_ratio, + }) + + if overlap_ratio > max_overlap: + max_overlap = overlap_ratio + max_speaker_id = speaker["speaker_id"] + + frame_ratio = person["frame_count"] / max(p["frame_count"] for p in self.persons) + + confidence = self.fuse_evidence( + face_similarity=None, + speaker_overlap=max_overlap, + time_overlap=max_overlap, + frame_ratio=frame_ratio, + ) + + identity = { + "identity_id": identity_id, + "person_ids": [person["person_id"]], + "speaker_ids": [s["speaker_id"] for s in speaker_overlaps], + "confidence": confidence, + "evidence": { + "face_similarity": None, + "speaker_overlap": max_overlap, + "time_overlap": max_overlap, + "frame_ratio": frame_ratio, + }, + "reasoning": f"Person {person['person_id']} has {max_overlap:.0%} overlap with {max_speaker_id or 'no speaker'}", + } + + identities.append(identity) + + if self.publisher: + self.publisher.info("identity", f"IDENTITY_ANALYZE_COMPLETE:{len(identities)}") + + return { + "success": True, + "video_uuid": self.video_uuid, + "identities": identities, + "processing_status": { + "status": "completed", + "persons_analyzed": len(self.persons), + "identities_created": len(identities), + "merges_suggested": 0, + }, + } + + def suggest_merges(self) -> Dict: + """ + Suggest Identity merges + + Returns: + Merge suggestions + """ + analyze_result = self.analyze() + + if not analyze_result.get("success"): + return analyze_result + + identities = analyze_result["identities"] + merge_suggestions = [] + + for identity in identities: + if len(identity["person_ids"]) >= 1 and len(identity["speaker_ids"]) >= 1: + confidence = identity["confidence"] + + if confidence > self.auto_merge_threshold: + action = "auto_apply" + elif confidence > self.llm_threshold: + action = "review_needed" + else: + continue + + reasons = [ + f"Shared speaker overlap: {identity['evidence']['speaker_overlap']:.0%}", + f"Confidence: {confidence:.2f}", + ] + + merge_suggestions.append({ + "target_person_id": identity["person_ids"][0], + "source_person_ids": identity["person_ids"][1:] if len(identity["person_ids"]) > 1 else [], + "confidence": confidence, + "reasons": reasons, + "action": action, + }) + + return { + "success": True, + "video_uuid": self.video_uuid, + "merge_suggestions": merge_suggestions, + "naming_suggestions": [], + } + + def call_llm(self, prompt: str) -> Dict: + """ + Call LLM for inference + + Args: + prompt: LLM prompt + + Returns: + LLM response + """ + import requests + + ollama_url = "http://localhost:11434/api/generate" + + body = { + "model": self.model, + "prompt": prompt, + "stream": False, + } + + try: + response = requests.post(ollama_url, json=body, timeout=30) + result = response.json() + + llm_output = result.get("response", "") + + try: + parsed = json.loads(llm_output) + return parsed + except json.JSONDecodeError: + return { + "decision": "keep_separate", + "confidence": 0.5, + "reasoning": llm_output, + } + except Exception as e: + print(f"LLM call failed: {e}") + return { + "decision": "keep_separate", + "confidence": 0.5, + "reasoning": f"LLM call failed: {e}", + } + + def llm_identity_inference(self, evidence: Dict) -> Dict: + """ + Use LLM to infer identity for ambiguous cases + + Args: + evidence: Multi-evidence data + + Returns: + LLM inference result + """ + confidence = evidence.get("confidence", 0.5) + + if confidence > self.auto_merge_threshold: + return { + "decision": "merge", + "confidence": confidence, + "reasoning": f"High confidence ({confidence:.2f}) - auto merge", + } + + if confidence < self.llm_threshold: + return { + "decision": "keep_separate", + "confidence": confidence, + "reasoning": f"Low confidence ({confidence:.2f}) - keep separate", + } + + if not self.use_llm: + return { + "decision": "review_needed", + "confidence": confidence, + "reasoning": "Medium confidence - manual review required", + } + + prompt = f""" +You are an identity analyst for a video analysis system. + +Given the following evidence: +- Face similarity: {evidence.get('face_similarity', 'N/A')} +- Speaker overlap: {evidence.get('speaker_overlap', 0):.2f} +- Time overlap: {evidence.get('time_overlap', 0):.2f} +- Frame ratio: {evidence.get('frame_ratio', 0):.2f} +- Person: {evidence.get('person_id', 'Unknown')} ({evidence.get('frame_count', 0)} frames) +- Shared speaker: {evidence.get('shared_speaker', 'None')} + +Should this person be merged with other persons sharing the same speaker? + +Provide: +1. Decision: "merge" or "keep_separate" +2. Confidence: 0.0-1.0 +3. Reasoning: 1-2 sentences explaining your decision + +Output in JSON format only: +{{ + "decision": "merge" or "keep_separate", + "confidence": 0.85, + "reasoning": "..." +}} +""" + + return self.call_llm(prompt) + + +def main(): + parser = argparse.ArgumentParser(description="Identity Agent - Multi-Evidence Identity Inference") + parser.add_argument("--video-uuid", "-u", help="Video UUID", required=True) + parser.add_argument("--output-dir", "-o", help="Output directory", default=None) + parser.add_argument( + "--analyze", "-a", help="Analyze video identity", action="store_true" + ) + parser.add_argument( + "--suggest", "-s", help="Suggest Identity merges", action="store_true" + ) + parser.add_argument( + "--auto-merge-threshold", + "-t", + help="Auto merge threshold", + type=float, + default=0.8, + ) + parser.add_argument( + "--llm-threshold", + "-l", + help="LLM inference threshold", + type=float, + default=0.5, + ) + parser.add_argument( + "--use-llm", help="Use LLM for ambiguous cases", action="store_true" + ) + parser.add_argument("--model", "-m", help="LLM model", default="gemma4") + + args = parser.parse_args() + + agent = IdentityAgent( + video_uuid=args.video_uuid, + output_dir=args.output_dir, + auto_merge_threshold=args.auto_merge_threshold, + llm_threshold=args.llm_threshold, + use_llm=args.use_llm, + model=args.model, + ) + + if args.analyze: + result = agent.analyze() + print(json.dumps(result, indent=2)) + + if args.suggest: + result = agent.suggest_merges() + print(json.dumps(result, indent=2)) + + if not args.analyze and not args.suggest: + print("Please specify --analyze or --suggest") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/identity/identity_agent_v1.11.py b/installer/build/MomentryCore/tools/script/identity/identity_agent_v1.11.py new file mode 100644 index 00000000..07f80539 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/identity/identity_agent_v1.11.py @@ -0,0 +1,519 @@ +#!/opt/homebrew/bin/python3.11 +""" +Identity Agent - Multi-Evidence Identity Inference + +Core Logic: +1. Time Overlap Matching (Speaker vs Person frames) +2. Embedding Similarity Calculation +3. Multi-Evidence Fusion +4. LLM Inference for Ambiguous Cases +5. Identity Assignment + +Usage: + python3 scripts/identity_agent.py --video-uuid --analyze + python3 scripts/identity_agent.py --video-uuid --suggest +""" + +import sys +import json +import argparse +import os +import numpy as np +from typing import Dict, List, Optional, Tuple +from sklearn.metrics.pairwise import cosine_similarity + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + + +class IdentityAgent: + """ + Identity Agent for Multi-Evidence Identity Inference + + Attributes: + video_uuid (str): Video UUID + output_dir (str): Output directory + fps (float): Video frame rate + auto_merge_threshold (float): Auto merge threshold (default: 0.8) + llm_threshold (float): LLM inference threshold (default: 0.5) + face_similarity_threshold (float): Face similarity threshold (default: 0.3) + use_llm (bool): Use LLM for ambiguous cases + model (str): LLM model name + """ + + def __init__( + self, + video_uuid: str, + output_dir: str = None, + auto_merge_threshold: float = 0.8, + llm_threshold: float = 0.5, + face_similarity_threshold: float = 0.3, + use_llm: bool = True, + model: str = "gemma4", + ): + self.video_uuid = video_uuid + self.output_dir = output_dir or os.getenv( + "MOMENTRY_OUTPUT_DIR", os.path.expanduser("~/momentry/output_dev") + ) + self.auto_merge_threshold = auto_merge_threshold + self.llm_threshold = llm_threshold + self.face_similarity_threshold = face_similarity_threshold + self.use_llm = use_llm + self.model = model + + self.fps = 23.976 # Default FPS + self.face_data = None + self.asrx_data = None + self.persons = [] + self.speakers = [] + self.identities = [] + + self.publisher = RedisPublisher(video_uuid) if video_uuid else None + + def load_data(self) -> bool: + """Load face clustered and ASRX data from files""" + video_dir = os.path.join(self.output_dir, self.video_uuid) + + face_clustered_path = os.path.join( + video_dir, f"{self.video_uuid}.face_clustered.json" + ) + asrx_path = os.path.join(video_dir, f"{self.video_uuid}.asrx.json") + probe_path = os.path.join(video_dir, f"{self.video_uuid}.probe.json") + + if not os.path.exists(face_clustered_path): + print(f"Error: Face clustered data not found: {face_clustered_path}") + return False + + self.face_data = self._load_json(face_clustered_path) + self.asrx_data = self._load_json(asrx_path) if os.path.exists(asrx_path) else None + + if os.path.exists(probe_path): + probe_data = self._load_json(probe_path) + self.fps = probe_data.get("fps", 23.976) + + self.persons = self._extract_persons() + self.speakers = self._extract_speakers() + + print(f"Loaded {len(self.persons)} persons, {len(self.speakers)} speakers") + return True + + def _load_json(self, path: str) -> Dict: + """Load JSON file""" + with open(path, "r", encoding="utf-8") as f: + return json.load(f) + + def _extract_persons(self) -> List[Dict]: + """Extract persons from face clustered data""" + persons = [] + + if not self.face_data: + return persons + + if "clusters" in self.face_data: + for cluster in self.face_data["clusters"]: + person_id = cluster.get("person_id", f"Person_{len(persons) + 1}") + frames = cluster.get("frames", []) + avg_embedding = cluster.get("avg_embedding", None) + + persons.append({ + "person_id": person_id, + "frames": frames, + "frame_count": len(frames), + "avg_embedding": avg_embedding, + "timestamps": [f / self.fps for f in frames], + }) + + return persons + + def _extract_speakers(self) -> List[Dict]: + """Extract speakers from ASRX data""" + speakers = [] + + if not self.asrx_data: + return speakers + + if "segments" in self.asrx_data: + speaker_segments_map = {} + + for segment in self.asrx_data["segments"]: + speaker_id = segment.get("speaker", "SPEAKER_01") + start = segment.get("start", 0.0) + end = segment.get("end", 0.0) + + if speaker_id not in speaker_segments_map: + speaker_segments_map[speaker_id] = [] + + speaker_segments_map[speaker_id].append({"start": start, "end": end}) + + for speaker_id, segments in speaker_segments_map.items(): + total_duration = sum(s["end"] - s["start"] for s in segments) + + speakers.append({ + "speaker_id": speaker_id, + "segments": segments, + "total_duration": total_duration, + }) + + return speakers + + def calculate_speaker_person_overlap( + self, person: Dict, speaker: Dict + ) -> Tuple[int, float]: + """ + Calculate overlap between Person and Speaker + + Returns: + Tuple of (overlap_frames, overlap_ratio) + """ + overlap_frames = 0 + + for frame in person["frames"]: + frame_time = frame / self.fps + + for segment in speaker["segments"]: + if segment["start"] <= frame_time <= segment["end"]: + overlap_frames += 1 + break + + overlap_ratio = overlap_frames / person["frame_count"] if person["frame_count"] > 0 else 0 + + return overlap_frames, overlap_ratio + + def calculate_person_similarity( + self, person1: Dict, person2: Dict + ) -> Optional[float]: + """ + Calculate cosine similarity between two Person embeddings + + Returns: + Similarity score (0-1) or None if embeddings not available + """ + if not person1.get("avg_embedding") or not person2.get("avg_embedding"): + return None + + emb1 = np.array(person1["avg_embedding"]).reshape(1, -1) + emb2 = np.array(person2["avg_embedding"]).reshape(1, -1) + + similarity = cosine_similarity(emb1, emb2)[0][0] + return similarity + + def fuse_evidence( + self, + face_similarity: Optional[float], + speaker_overlap: float, + time_overlap: float, + frame_ratio: float, + ) -> float: + """ + Fuse multiple evidence sources into a single confidence score + + Args: + face_similarity: Cosine similarity between face embeddings (0-1) + speaker_overlap: Speaker-Person overlap ratio (0-1) + time_overlap: Temporal overlap ratio (0-1) + frame_ratio: Person's frame count ratio in video (0-1) + + Returns: + Fused confidence score (0-1) + """ + weights = { + "face": 0.4, + "speaker": 0.3, + "time": 0.2, + "frame": 0.1, + } + + face_score = face_similarity if face_similarity is not None else 0.5 + + confidence = ( + weights["face"] * face_score + + weights["speaker"] * speaker_overlap + + weights["time"] * time_overlap + + weights["frame"] * frame_ratio + ) + + return confidence + + def analyze(self) -> Dict: + """ + Analyze video identity + + Returns: + Identity analysis result + """ + if not self.load_data(): + return {"success": False, "error": "Failed to load data"} + + if self.publisher: + self.publisher.info("identity", "IDENTITY_ANALYZE_START") + + identities = [] + + for i, person in enumerate(self.persons): + identity_id = f"identity_{i + 1}" + + speaker_overlaps = [] + max_overlap = 0.0 + max_speaker_id = None + + for speaker in self.speakers: + overlap_frames, overlap_ratio = self.calculate_speaker_person_overlap( + person, speaker + ) + + if overlap_ratio > 0.3: + speaker_overlaps.append({ + "speaker_id": speaker["speaker_id"], + "overlap_frames": overlap_frames, + "overlap_ratio": overlap_ratio, + }) + + if overlap_ratio > max_overlap: + max_overlap = overlap_ratio + max_speaker_id = speaker["speaker_id"] + + frame_ratio = person["frame_count"] / max(p["frame_count"] for p in self.persons) + + confidence = self.fuse_evidence( + face_similarity=None, + speaker_overlap=max_overlap, + time_overlap=max_overlap, + frame_ratio=frame_ratio, + ) + + identity = { + "identity_id": identity_id, + "person_ids": [person["person_id"]], + "speaker_ids": [s["speaker_id"] for s in speaker_overlaps], + "confidence": confidence, + "evidence": { + "face_similarity": None, + "speaker_overlap": max_overlap, + "time_overlap": max_overlap, + "frame_ratio": frame_ratio, + }, + "reasoning": f"Person {person['person_id']} has {max_overlap:.0%} overlap with {max_speaker_id or 'no speaker'}", + } + + identities.append(identity) + + if self.publisher: + self.publisher.info("identity", f"IDENTITY_ANALYZE_COMPLETE:{len(identities)}") + + return { + "success": True, + "video_uuid": self.video_uuid, + "identities": identities, + "processing_status": { + "status": "completed", + "persons_analyzed": len(self.persons), + "identities_created": len(identities), + "merges_suggested": 0, + }, + } + + def suggest_merges(self) -> Dict: + """ + Suggest Identity merges + + Returns: + Merge suggestions + """ + analyze_result = self.analyze() + + if not analyze_result.get("success"): + return analyze_result + + identities = analyze_result["identities"] + merge_suggestions = [] + + for identity in identities: + if len(identity["person_ids"]) >= 1 and len(identity["speaker_ids"]) >= 1: + confidence = identity["confidence"] + + if confidence > self.auto_merge_threshold: + action = "auto_apply" + elif confidence > self.llm_threshold: + action = "review_needed" + else: + continue + + reasons = [ + f"Shared speaker overlap: {identity['evidence']['speaker_overlap']:.0%}", + f"Confidence: {confidence:.2f}", + ] + + merge_suggestions.append({ + "target_person_id": identity["person_ids"][0], + "source_person_ids": identity["person_ids"][1:] if len(identity["person_ids"]) > 1 else [], + "confidence": confidence, + "reasons": reasons, + "action": action, + }) + + return { + "success": True, + "video_uuid": self.video_uuid, + "merge_suggestions": merge_suggestions, + "naming_suggestions": [], + } + + def call_llm(self, prompt: str) -> Dict: + """ + Call LLM for inference + + Args: + prompt: LLM prompt + + Returns: + LLM response + """ + import requests + + ollama_url = "http://localhost:11434/api/generate" + + body = { + "model": self.model, + "prompt": prompt, + "stream": False, + } + + try: + response = requests.post(ollama_url, json=body, timeout=30) + result = response.json() + + llm_output = result.get("response", "") + + try: + parsed = json.loads(llm_output) + return parsed + except json.JSONDecodeError: + return { + "decision": "keep_separate", + "confidence": 0.5, + "reasoning": llm_output, + } + except Exception as e: + print(f"LLM call failed: {e}") + return { + "decision": "keep_separate", + "confidence": 0.5, + "reasoning": f"LLM call failed: {e}", + } + + def llm_identity_inference(self, evidence: Dict) -> Dict: + """ + Use LLM to infer identity for ambiguous cases + + Args: + evidence: Multi-evidence data + + Returns: + LLM inference result + """ + confidence = evidence.get("confidence", 0.5) + + if confidence > self.auto_merge_threshold: + return { + "decision": "merge", + "confidence": confidence, + "reasoning": f"High confidence ({confidence:.2f}) - auto merge", + } + + if confidence < self.llm_threshold: + return { + "decision": "keep_separate", + "confidence": confidence, + "reasoning": f"Low confidence ({confidence:.2f}) - keep separate", + } + + if not self.use_llm: + return { + "decision": "review_needed", + "confidence": confidence, + "reasoning": "Medium confidence - manual review required", + } + + prompt = f""" +You are an identity analyst for a video analysis system. + +Given the following evidence: +- Face similarity: {evidence.get('face_similarity', 'N/A')} +- Speaker overlap: {evidence.get('speaker_overlap', 0):.2f} +- Time overlap: {evidence.get('time_overlap', 0):.2f} +- Frame ratio: {evidence.get('frame_ratio', 0):.2f} +- Person: {evidence.get('person_id', 'Unknown')} ({evidence.get('frame_count', 0)} frames) +- Shared speaker: {evidence.get('shared_speaker', 'None')} + +Should this person be merged with other persons sharing the same speaker? + +Provide: +1. Decision: "merge" or "keep_separate" +2. Confidence: 0.0-1.0 +3. Reasoning: 1-2 sentences explaining your decision + +Output in JSON format only: +{{ + "decision": "merge" or "keep_separate", + "confidence": 0.85, + "reasoning": "..." +}} +""" + + return self.call_llm(prompt) + + +def main(): + parser = argparse.ArgumentParser(description="Identity Agent - Multi-Evidence Identity Inference") + parser.add_argument("--video-uuid", "-u", help="Video UUID", required=True) + parser.add_argument("--output-dir", "-o", help="Output directory", default=None) + parser.add_argument( + "--analyze", "-a", help="Analyze video identity", action="store_true" + ) + parser.add_argument( + "--suggest", "-s", help="Suggest Identity merges", action="store_true" + ) + parser.add_argument( + "--auto-merge-threshold", + "-t", + help="Auto merge threshold", + type=float, + default=0.8, + ) + parser.add_argument( + "--llm-threshold", + "-l", + help="LLM inference threshold", + type=float, + default=0.5, + ) + parser.add_argument( + "--use-llm", help="Use LLM for ambiguous cases", action="store_true" + ) + parser.add_argument("--model", "-m", help="LLM model", default="gemma4") + + args = parser.parse_args() + + agent = IdentityAgent( + video_uuid=args.video_uuid, + output_dir=args.output_dir, + auto_merge_threshold=args.auto_merge_threshold, + llm_threshold=args.llm_threshold, + use_llm=args.use_llm, + model=args.model, + ) + + if args.analyze: + result = agent.analyze() + print(json.dumps(result, indent=2)) + + if args.suggest: + result = agent.suggest_merges() + print(json.dumps(result, indent=2)) + + if not args.analyze and not args.suggest: + print("Please specify --analyze or --suggest") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/identity/identity_bind.py b/installer/build/MomentryCore/tools/script/identity/identity_bind.py new file mode 100644 index 00000000..ce154f58 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/identity/identity_bind.py @@ -0,0 +1,129 @@ +#!/opt/homebrew/bin/python3.11 +""" +Identity Binding: cluster face traces → identity bindings. +Uses face embeddings from face_detections, clusters per trace, creates identities. +""" +import json, sys, time +import psycopg2 +import numpy as np +from sklearn.cluster import AgglomerativeClustering + +UUID = sys.argv[1] if len(sys.argv) > 1 else "23b1c872379d4ec06479e5ed39eef4c5" +DB = "dbname=momentry user=accusys" +DISTANCE_THRESHOLD = 0.55 # Cosine distance threshold for clustering + +print(f"=== Identity Binding for {UUID} ===") + +conn = psycopg2.connect(DB) +cur = conn.cursor() + +# Step 1: Get trace embeddings from face_detections +print("Loading face trace data...") +cur.execute(""" + SELECT trace_id, embedding + FROM dev.face_detections + WHERE file_uuid = %s AND trace_id IS NOT NULL AND embedding IS NOT NULL + ORDER BY trace_id, id +""", (UUID,)) +rows = cur.fetchall() +print(f"Face detections with embeddings: {len(rows)}") + +# Group by trace_id and compute average embedding +trace_embs = {} +for trace_id, emb in rows: + if trace_id not in trace_embs: + trace_embs[trace_id] = [] + trace_embs[trace_id].append(emb) + +print(f"Unique traces: {len(trace_embs)}") + +# Compute mean embeddings per trace +trace_ids = [] +trace_vectors = [] +for tid, embs in sorted(trace_embs.items()): + mean_emb = np.mean(embs, axis=0) + mean_emb = mean_emb / (np.linalg.norm(mean_emb) + 1e-10) + trace_ids.append(tid) + trace_vectors.append(mean_emb) + +X = np.array(trace_vectors) +print(f"Trace vectors shape: {X.shape}") + +# Step 2: Cluster traces +print("Clustering traces...") +if len(X) > 1: + clustering = AgglomerativeClustering( + n_clusters=None, + distance_threshold=DISTANCE_THRESHOLD, + metric='cosine', + linkage='average' + ) + labels = clustering.fit_predict(X) +else: + labels = [0] + +n_clusters = len(set(labels)) +print(f"Clusters/identities: {n_clusters}") + +# Step 3: Get or create identity records +print("Creating identity records...") +# Get existing identities +cur.execute("SELECT id, uuid FROM dev.identities") +existing = {row[0]: row[1] for row in cur.fetchall()} + +# Map cluster -> identity_id +cluster_to_identity = {} +for cluster_id in sorted(set(labels)): + # Create new identity + identity_uuid = None + cur.execute(""" + INSERT INTO dev.identities (name, identity_type, source, status, created_at, file_uuid) + VALUES (%s, 'face', 'auto', 'active', NOW(), %s) + ON CONFLICT (name) DO UPDATE SET status = 'active', file_uuid = COALESCE(dev.identities.file_uuid, %s) + RETURNING id + """, (f"stranger_{UUID}_{cluster_id}", UUID, UUID)) + identity_id = cur.fetchone()[0] + cluster_to_identity[cluster_id] = identity_id + print(f" Cluster {cluster_id}: new identity {identity_id} (stranger_{UUID}_{cluster_id})") + +# Step 4: Create identity bindings +print("Creating identity bindings...") +bindings = 0 +for tid, label in zip(trace_ids, labels): + identity_id = cluster_to_identity[label] + # Get a representative face_id for this trace + cur.execute(""" + SELECT face_id FROM dev.face_detections + WHERE file_uuid = %s AND trace_id = %s + LIMIT 1 + """, (UUID, tid)) + row = cur.fetchone() + if row: + face_id = row[0] + # Create binding + cur.execute(""" + INSERT INTO dev.identity_bindings (identity_id, identity_type, identity_value, confidence, created_at) + VALUES (%s, 'trace', %s, 0.8, NOW()) + ON CONFLICT DO NOTHING + """, (identity_id, str(tid))) + bindings += 1 + + # Also update face_detection with identity_id + cur.execute(""" + UPDATE dev.face_detections SET identity_id = %s + WHERE file_uuid = %s AND trace_id = %s + """, (identity_id, UUID, tid)) + +conn.commit() +print(f"Created {bindings} identity bindings for {n_clusters} identities") + +# Summary +print(f"\n=== Summary ===") +cur.execute("SELECT COUNT(*) FROM dev.identities WHERE source = 'auto'") +print(f"Total auto-generated identities: {cur.fetchone()[0]}") +cur.execute("SELECT COUNT(*) FROM dev.identity_bindings") +print(f"Total identity bindings: {cur.fetchone()[0]}") + +cur.close() +conn.close() +print("=== Done ===") diff --git a/installer/build/MomentryCore/tools/script/identity/identity_bind_v1.11.py b/installer/build/MomentryCore/tools/script/identity/identity_bind_v1.11.py new file mode 100644 index 00000000..ce154f58 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/identity/identity_bind_v1.11.py @@ -0,0 +1,129 @@ +#!/opt/homebrew/bin/python3.11 +""" +Identity Binding: cluster face traces → identity bindings. +Uses face embeddings from face_detections, clusters per trace, creates identities. +""" +import json, sys, time +import psycopg2 +import numpy as np +from sklearn.cluster import AgglomerativeClustering + +UUID = sys.argv[1] if len(sys.argv) > 1 else "23b1c872379d4ec06479e5ed39eef4c5" +DB = "dbname=momentry user=accusys" +DISTANCE_THRESHOLD = 0.55 # Cosine distance threshold for clustering + +print(f"=== Identity Binding for {UUID} ===") + +conn = psycopg2.connect(DB) +cur = conn.cursor() + +# Step 1: Get trace embeddings from face_detections +print("Loading face trace data...") +cur.execute(""" + SELECT trace_id, embedding + FROM dev.face_detections + WHERE file_uuid = %s AND trace_id IS NOT NULL AND embedding IS NOT NULL + ORDER BY trace_id, id +""", (UUID,)) +rows = cur.fetchall() +print(f"Face detections with embeddings: {len(rows)}") + +# Group by trace_id and compute average embedding +trace_embs = {} +for trace_id, emb in rows: + if trace_id not in trace_embs: + trace_embs[trace_id] = [] + trace_embs[trace_id].append(emb) + +print(f"Unique traces: {len(trace_embs)}") + +# Compute mean embeddings per trace +trace_ids = [] +trace_vectors = [] +for tid, embs in sorted(trace_embs.items()): + mean_emb = np.mean(embs, axis=0) + mean_emb = mean_emb / (np.linalg.norm(mean_emb) + 1e-10) + trace_ids.append(tid) + trace_vectors.append(mean_emb) + +X = np.array(trace_vectors) +print(f"Trace vectors shape: {X.shape}") + +# Step 2: Cluster traces +print("Clustering traces...") +if len(X) > 1: + clustering = AgglomerativeClustering( + n_clusters=None, + distance_threshold=DISTANCE_THRESHOLD, + metric='cosine', + linkage='average' + ) + labels = clustering.fit_predict(X) +else: + labels = [0] + +n_clusters = len(set(labels)) +print(f"Clusters/identities: {n_clusters}") + +# Step 3: Get or create identity records +print("Creating identity records...") +# Get existing identities +cur.execute("SELECT id, uuid FROM dev.identities") +existing = {row[0]: row[1] for row in cur.fetchall()} + +# Map cluster -> identity_id +cluster_to_identity = {} +for cluster_id in sorted(set(labels)): + # Create new identity + identity_uuid = None + cur.execute(""" + INSERT INTO dev.identities (name, identity_type, source, status, created_at, file_uuid) + VALUES (%s, 'face', 'auto', 'active', NOW(), %s) + ON CONFLICT (name) DO UPDATE SET status = 'active', file_uuid = COALESCE(dev.identities.file_uuid, %s) + RETURNING id + """, (f"stranger_{UUID}_{cluster_id}", UUID, UUID)) + identity_id = cur.fetchone()[0] + cluster_to_identity[cluster_id] = identity_id + print(f" Cluster {cluster_id}: new identity {identity_id} (stranger_{UUID}_{cluster_id})") + +# Step 4: Create identity bindings +print("Creating identity bindings...") +bindings = 0 +for tid, label in zip(trace_ids, labels): + identity_id = cluster_to_identity[label] + # Get a representative face_id for this trace + cur.execute(""" + SELECT face_id FROM dev.face_detections + WHERE file_uuid = %s AND trace_id = %s + LIMIT 1 + """, (UUID, tid)) + row = cur.fetchone() + if row: + face_id = row[0] + # Create binding + cur.execute(""" + INSERT INTO dev.identity_bindings (identity_id, identity_type, identity_value, confidence, created_at) + VALUES (%s, 'trace', %s, 0.8, NOW()) + ON CONFLICT DO NOTHING + """, (identity_id, str(tid))) + bindings += 1 + + # Also update face_detection with identity_id + cur.execute(""" + UPDATE dev.face_detections SET identity_id = %s + WHERE file_uuid = %s AND trace_id = %s + """, (identity_id, UUID, tid)) + +conn.commit() +print(f"Created {bindings} identity bindings for {n_clusters} identities") + +# Summary +print(f"\n=== Summary ===") +cur.execute("SELECT COUNT(*) FROM dev.identities WHERE source = 'auto'") +print(f"Total auto-generated identities: {cur.fetchone()[0]}") +cur.execute("SELECT COUNT(*) FROM dev.identity_bindings") +print(f"Total identity bindings: {cur.fetchone()[0]}") + +cur.close() +conn.close() +print("=== Done ===") diff --git a/installer/build/MomentryCore/tools/script/identity/identity_matcher.py b/installer/build/MomentryCore/tools/script/identity/identity_matcher.py new file mode 100755 index 00000000..277d682a --- /dev/null +++ b/installer/build/MomentryCore/tools/script/identity/identity_matcher.py @@ -0,0 +1,421 @@ +#!/opt/homebrew/bin/python3.11 +""" +Identity Matcher - Multi-angle face matching against seeds + +Flow: +1. Query Qdrant _faces for all traces in a file +2. Query Qdrant _seeds for all seeds (TMDb + manual + propagation) +3. Multi-angle matching: max(cosine(seed, rep)) across 3 representatives +4. Return suggestions with confidence scores + +Thresholds: +- Round 1: 0.55 (TMDb seeds) +- Round 2: 0.55 (Propagation from confirmed traces) +- Round 3+: 0.50 (Propagation continues) +- Stranger clustering: 0.40 + +Usage: + python identity_matcher.py --file-uuid --round 1 + python identity_matcher.py --file-uuid --round 2 --confirmed-traces 1,2,3 + +Output: + JSON with suggestions: {trace_id: {identity_id, identity_uuid, name, score, suggested_by}} +""" + +import os +import sys +import json +import argparse +import numpy as np +from typing import Optional + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils")) + +from qdrant_faces import ( + get_trace_representatives, + get_seeds, + search_seeds, + get_trace_centroid, +) +from tkg_helper import batch_mark_suggestions, batch_mark_strangers + +TH_ROUND_1 = 0.55 +TH_ROUND_2 = 0.55 +TH_ROUND_3 = 0.50 +TH_STRANGER = 0.40 + + +def cosine_similarity(a: list, b: list) -> float: + """Compute cosine similarity between two vectors""" + if len(a) != len(b) or len(a) == 0: + return 0.0 + dot = sum(x * y for x, y in zip(a, b)) + na = sum(x * x for x in a) ** 0.5 + nb = sum(x * x for x in b) ** 0.5 + if na == 0.0 or nb == 0.0: + return 0.0 + return dot / (na * nb) + + +def multi_angle_match(seed_embedding: list, trace_reps: list) -> float: + """Multi-angle matching: max(cosine(seed, rep))""" + if not trace_reps: + return 0.0 + + best_score = 0.0 + for rep in trace_reps: + score = cosine_similarity(seed_embedding, rep["embedding"]) + if score > best_score: + best_score = score + + return best_score + + +def match_faces_round_1(file_uuid: str) -> dict: + """Round 1: TMDb seeds → Traces (TH=0.55) + + Returns: + {trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'tmdb'}} + """ + traces = get_trace_representatives(file_uuid) + seeds = get_seeds(source="tmdb", file_uuid=file_uuid) + + if not seeds: + print(f"[MATCH] No TMDb seeds available for {file_uuid}") + return {} + + suggestions = {} + threshold = TH_ROUND_1 + + for trace_id, reps in traces.items(): + best_match = None + best_score = 0.0 + + for seed in seeds: + seed_emb = seed.get("vector", []) + seed_payload = seed.get("payload", {}) + + score = multi_angle_match(seed_emb, reps) + if score >= threshold and score > best_score: + best_score = score + best_match = { + "identity_id": seed_payload.get("identity_id"), + "identity_uuid": seed_payload.get("identity_uuid"), + "name": seed_payload.get("name"), + "score": score, + "suggested_by": "tmdb", + } + + if best_match: + suggestions[trace_id] = best_match + + print(f"[MATCH] Round 1: {len(suggestions)}/{len(traces)} traces suggested (TH={threshold})") + return suggestions + + +def match_faces_round_2( + file_uuid: str, + confirmed_traces: list, + identity_map: dict, +) -> dict: + """Round 2: Confirmed traces → Pending traces (TH=0.55) + + Args: + file_uuid: Video file UUID + confirmed_traces: List of confirmed trace_ids + identity_map: {trace_id: {identity_id, identity_uuid, name}} + + Returns: + {trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'propagation'}} + """ + traces = get_trace_representatives(file_uuid) + + pending_traces = set(traces.keys()) - set(confirmed_traces) + if not pending_traces: + print("[MATCH] Round 2: No pending traces") + return {} + + seed_pool = {} + for trace_id in confirmed_traces: + if trace_id not in traces: + continue + identity_info = identity_map.get(trace_id) + if not identity_info: + continue + + centroid = get_trace_centroid(file_uuid, trace_id) + if not centroid or all(v == 0.0 for v in centroid): + continue + + identity_id = identity_info.get("identity_id") + if identity_id not in seed_pool: + seed_pool[identity_id] = { + "identity_id": identity_id, + "identity_uuid": identity_info.get("identity_uuid"), + "name": identity_info.get("name"), + "embeddings": [], + } + seed_pool[identity_id]["embeddings"].append(centroid) + + if not seed_pool: + print("[MATCH] Round 2: No confirmed traces with embeddings") + return {} + + suggestions = {} + threshold = TH_ROUND_2 + + for trace_id in pending_traces: + reps = traces.get(trace_id, []) + if not reps: + continue + + best_match = None + best_score = 0.0 + + for identity_id, seed_data in seed_pool.items(): + for seed_emb in seed_data["embeddings"]: + score = multi_angle_match(seed_emb, reps) + if score >= threshold and score > best_score: + best_score = score + best_match = { + "identity_id": seed_data["identity_id"], + "identity_uuid": seed_data["identity_uuid"], + "name": seed_data["name"], + "score": score, + "suggested_by": "propagation", + } + + if best_match: + suggestions[trace_id] = best_match + + print(f"[MATCH] Round 2: {len(suggestions)}/{len(pending_traces)} traces suggested (TH={threshold})") + return suggestions + + +def match_faces_round_3_plus( + file_uuid: str, + all_confirmed: dict, + prev_suggestions: dict, + round_num: int, +) -> dict: + """Round 3+: Propagation continues (TH=0.50) + + Args: + file_uuid: Video file UUID + all_confirmed: {trace_id: {identity_id, identity_uuid, name}} - all confirmed so far + prev_suggestions: {trace_id: {...}} - suggestions from previous round + round_num: Round number (3, 4, 5...) + + Returns: + {trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'propagation'}} + """ + traces = get_trace_representatives(file_uuid) + + confirmed_traces = set(all_confirmed.keys()) + prev_suggested_traces = set(prev_suggestions.keys()) + pending_traces = set(traces.keys()) - confirmed_traces - prev_suggested_traces + + if not pending_traces: + print(f"[MATCH] Round {round_num}: No pending traces") + return {} + + seed_pool = {} + for trace_id, identity_info in all_confirmed.items(): + if trace_id not in traces: + continue + + centroid = get_trace_centroid(file_uuid, trace_id) + if not centroid or all(v == 0.0 for v in centroid): + continue + + identity_id = identity_info.get("identity_id") + if identity_id not in seed_pool: + seed_pool[identity_id] = { + "identity_id": identity_id, + "identity_uuid": identity_info.get("identity_uuid"), + "name": identity_info.get("name"), + "embeddings": [], + } + seed_pool[identity_id]["embeddings"].append(centroid) + + if not seed_pool: + print(f"[MATCH] Round {round_num}: No seeds available") + return {} + + suggestions = {} + threshold = TH_ROUND_3 + + for trace_id in pending_traces: + reps = traces.get(trace_id, []) + if not reps: + continue + + best_match = None + best_score = 0.0 + + for identity_id, seed_data in seed_pool.items(): + for seed_emb in seed_data["embeddings"]: + score = multi_angle_match(seed_emb, reps) + if score >= threshold and score > best_score: + best_score = score + best_match = { + "identity_id": seed_data["identity_id"], + "identity_uuid": seed_data["identity_uuid"], + "name": seed_data["name"], + "score": score, + "suggested_by": "propagation", + } + + if best_match: + suggestions[trace_id] = best_match + + print(f"[MATCH] Round {round_num}: {len(suggestions)}/{len(pending_traces)} traces suggested (TH={threshold})") + return suggestions + + +def cluster_strangers(file_uuid: str, matched_traces: list) -> dict: + """Stranger clustering: Greedy merge unmatched traces (TH=0.40) + + Args: + file_uuid: Video file UUID + matched_traces: List of trace_ids that have identity suggestions + + Returns: + {stranger_cluster_id: [trace_ids]} + """ + traces = get_trace_representatives(file_uuid) + + unmatched_traces = set(traces.keys()) - set(matched_traces) + if not unmatched_traces: + print("[STRANGER] All traces matched") + return {} + + clusters = [] + threshold = TH_STRANGER + + for trace_id in unmatched_traces: + reps = traces.get(trace_id, []) + if not reps: + continue + + centroid = get_trace_centroid(file_uuid, trace_id) + if not centroid or all(v == 0.0 for v in centroid): + continue + + best_cluster_idx = None + best_score = 0.0 + + for idx, cluster in enumerate(clusters): + cluster_centroid = compute_cluster_centroid(cluster, traces) + score = cosine_similarity(centroid, cluster_centroid) + if score >= threshold and score > best_score: + best_score = score + best_cluster_idx = idx + + if best_cluster_idx is not None: + clusters[best_cluster_idx].append(trace_id) + else: + clusters.append([trace_id]) + + stranger_clusters = {} + for idx, trace_ids in enumerate(clusters): + stranger_clusters[idx + 1] = trace_ids + + print(f"[STRANGER] {len(stranger_clusters)} clusters from {len(unmatched_traces)} unmatched traces (TH={threshold})") + return stranger_clusters + + +def compute_cluster_centroid(cluster: list, traces: dict) -> list: + """Compute centroid embedding for a cluster of traces""" + all_embeddings = [] + for trace_id in cluster: + reps = traces.get(trace_id, []) + for rep in reps: + all_embeddings.append(rep["embedding"]) + + if not all_embeddings: + return [0.0] * 512 + + centroid = [0.0] * 512 + for emb in all_embeddings: + for i, v in enumerate(emb): + centroid[i] += v + + for i in range(512): + centroid[i] /= len(all_embeddings) + + return centroid + + +def main(): + parser = argparse.ArgumentParser(description="Identity Matcher") + parser.add_argument("--file-uuid", required=True, help="Video file UUID") + parser.add_argument("--round", type=int, default=1, help="Round number (1, 2, 3+)") + parser.add_argument("--confirmed-traces", help="Comma-separated confirmed trace_ids (for Round 2+)") + parser.add_argument("--identity-map", help="JSON file with {trace_id: {identity_id, uuid, name}} (for Round 2+)") + parser.add_argument("--output", help="Output JSON file path") + parser.add_argument("--stranger", action="store_true", help="Also run stranger clustering") + parser.add_argument("--mark-tkg", action="store_true", help="Mark TKG face_track nodes with suggestions") + args = parser.parse_args() + + if args.round == 1: + suggestions = match_faces_round_1(args.file_uuid) + elif args.round == 2: + confirmed = [] + identity_map = {} + + if args.confirmed_traces: + confirmed = [int(x) for x in args.confirmed_traces.split(",")] + + if args.identity_map: + with open(args.identity_map) as f: + identity_map = json.load(f) + + suggestions = match_faces_round_2(args.file_uuid, confirmed, identity_map) + else: + all_confirmed = {} + prev_suggestions = {} + + if args.identity_map: + with open(args.identity_map) as f: + all_confirmed = json.load(f) + + suggestions = match_faces_round_3_plus( + args.file_uuid, all_confirmed, prev_suggestions, args.round + ) + + result = { + "file_uuid": args.file_uuid, + "round": args.round, + "suggestions": suggestions, + "total_traces": len(get_trace_representatives(args.file_uuid)), + "matched": len(suggestions), + } + + if args.stranger: + matched_traces = list(suggestions.keys()) + stranger_clusters = cluster_strangers(args.file_uuid, matched_traces) + result["stranger_clusters"] = stranger_clusters + + # Mark TKG nodes if requested + if args.mark_tkg: + tkg_updated = batch_mark_suggestions(args.file_uuid, suggestions) + result["tkg_nodes_updated"] = tkg_updated + + if args.stranger and stranger_clusters: + tkg_strangers = batch_mark_strangers(args.file_uuid, stranger_clusters) + result["tkg_strangers_updated"] = tkg_strangers + + output_json = json.dumps(result, indent=2, ensure_ascii=False) + + if args.output: + with open(args.output, "w") as f: + f.write(output_json) + print(f"[MATCH] Output saved to {args.output}") + else: + print(output_json) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/migration/generate_identities.py b/installer/build/MomentryCore/tools/script/migration/generate_identities.py new file mode 100644 index 00000000..81d7b892 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/migration/generate_identities.py @@ -0,0 +1,261 @@ +#!/usr/bin/env python3 +""" +迁移工具 - 生成 Identity Profile 文件 + +从数据库导出 Identity 信息,生成 Identity Profile 文件 + +Usage: + python3 generate_identities.py [--identities-dir DIR] [--database DATABASE] +""" + +import argparse +import json +import os +import sys +from pathlib import Path +from typing import Dict, Any, Optional +from datetime import datetime + +# 添加父目录到路径 +SCRIPTS_DIR = os.environ.get( + "MOMENTRY_SCRIPTS_DIR", + os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +) +sys.path.insert(0, SCRIPTS_DIR) + +try: + import psycopg2 + from psycopg2.extras import RealDictCursor +except ImportError: + print("Error: psycopg2 not installed. Run: pip install psycopg2-binary") + sys.exit(1) + + +def get_db_connection(database: str = "momentry"): + """获取数据库连接""" + return psycopg2.connect( + host="localhost", + database=database, + user="accusys" + ) + + +def fetch_identities(conn) -> list: + """从数据库读取所有 Identity 信息""" + query = """ + SELECT + id, + uuid, + name, + identity_type, + source, + metadata, + tmdb_id, + tmdb_profile, + tmdb_poster, + starred, + created_at, + updated_at + FROM identities + ORDER BY created_at + """ + + with conn.cursor(cursor_factory=RealDictCursor) as cur: + cur.execute(query) + return cur.fetchall() + + +def build_identity_profile(row: Dict) -> Dict: + """构建 Identity Profile 数据结构""" + + profile = { + "version": "1.0", + "uuid": str(row["uuid"]), + + "identity_info": { + "name": row["name"], + "identity_type": row.get("identity_type", "person"), + "display_name": row["name"], + "aliases": None + }, + + "source": None, + + "embeddings": { + "face": { + "model": "facenet", + "dimensions": 512, + "stored_in": "qdrant:_faces", + "updated_at": datetime.utcnow().isoformat() + }, + "voice": None + }, + + "metadata": row.get("metadata", {}), + + "appearance_stats": { + "total_files": 0, + "total_frames": 0, + "first_seen": None, + "last_seen": None + }, + + "reference_face": None, + "starred": bool(row.get("starred", False)), + + "created_at": row["created_at"].isoformat() if row.get("created_at") else datetime.utcnow().isoformat(), + "updated_at": row["updated_at"].isoformat() if row.get("updated_at") else datetime.utcnow().isoformat() + } + + # Source 信息 + if row.get("tmdb_id"): + profile["source"] = { + "type": "tmdb", + "tmdb_id": int(row["tmdb_id"]), + "tmdb_profile": row.get("tmdb_profile"), + "tmdb_poster": row.get("tmdb_poster"), + "imported_at": profile["created_at"] + } + elif row.get("source"): + profile["source"] = { + "type": row["source"], + "imported_at": profile["created_at"] + } + + return profile + + +def build_appearances(identity_uuid: str, identity_name: str) -> Dict: + """构建 Appearances 数据结构""" + return { + "version": "1.0", + "identity_uuid": identity_uuid, + "identity_name": identity_name, + + "files": [], + + "total_files": 0, + "total_frames": 0, + "updated_at": datetime.utcnow().isoformat() + } + + +def save_identity_profile(profile: Dict, identities_dir: str, dry_run: bool = False) -> bool: + """保存 Identity Profile 到文件""" + identity_uuid = profile["uuid"] + identity_dir = Path(identities_dir) / identity_uuid + profile_path = identity_dir / "profile.json" + + if dry_run: + print(f"[DRY-RUN] Would write: {profile_path}") + return True + + try: + # 创建目录 + identity_dir.mkdir(parents=True, exist_ok=True) + + # 写入 profile.json + with open(profile_path, 'w', encoding='utf-8') as f: + json.dump(profile, f, indent=2, ensure_ascii=False) + + print(f"✅ Generated: {profile_path}") + return True + except Exception as e: + print(f"❌ Failed to write {profile_path}: {e}") + return False + + +def save_appearances(appearances: Dict, identities_dir: str, dry_run: bool = False) -> bool: + """保存 Appearances 到文件""" + identity_uuid = appearances["identity_uuid"] + appearances_path = Path(identities_dir) / identity_uuid / "appearances.json" + + if dry_run: + print(f"[DRY-RUN] Would write: {appearances_path}") + return True + + try: + with open(appearances_path, 'w', encoding='utf-8') as f: + json.dump(appearances, f, indent=2, ensure_ascii=False) + return True + except Exception as e: + print(f"❌ Failed to write {appearances_path}: {e}") + return False + + +def main(): + parser = argparse.ArgumentParser(description="生成 Identity Profile 文件") + parser.add_argument( + "--identities-dir", + default=os.path.expanduser("~/momentry/identities"), + help="Identity 目录" + ) + parser.add_argument( + "--database", + default="momentry", + help="数据库名称" + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="只打印将要执行的操作,不实际写入文件" + ) + + args = parser.parse_args() + + print(f"Identity 目录: {args.identities_dir}") + print(f"数据库: {args.database}") + print(f"Dry run: {args.dry_run}") + print() + + # 连接数据库 + print("连接数据库...") + try: + conn = get_db_connection(args.database) + except Exception as e: + print(f"❌ 数据库连接失败: {e}") + sys.exit(1) + + # 读取 Identity + print("读取 Identity 列表...") + identities = fetch_identities(conn) + print(f"找到 {len(identities)} 个 Identity") + print() + + # 生成 Profile + success_count = 0 + failed_count = 0 + + for row in identities: + try: + profile = build_identity_profile(dict(row)) + + # 保存 profile.json + if save_identity_profile(profile, args.identities_dir, args.dry_run): + # 创建空的 appearances.json + appearances = build_appearances( + profile["uuid"], + profile["identity_info"]["name"] + ) + save_appearances(appearances, args.identities_dir, args.dry_run) + success_count += 1 + else: + failed_count += 1 + except Exception as e: + print(f"❌ 处理失败 {row['uuid']}: {e}") + failed_count += 1 + + conn.close() + + print() + print("=" * 60) + print(f"完成!成功: {success_count}, 失败: {failed_count}") + + if args.dry_run: + print() + print("这是 DRY-RUN 模式,没有实际写入文件") + print("移除 --dry-run 参数以实际执行") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/migration/generate_profiles.py b/installer/build/MomentryCore/tools/script/migration/generate_profiles.py new file mode 100644 index 00000000..99916de4 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/migration/generate_profiles.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +""" +迁移工具 - 生成 File Profile 文件 + +从数据库导出文件信息,生成 {file_uuid}.profile.json 文件 + +Usage: + python3 generate_profiles.py [--output-dir OUTPUT_DIR] [--database DATABASE] +""" + +import argparse +import json +import os +import sys +from pathlib import Path +from typing import Dict, Any, Optional +from datetime import datetime + +# 添加父目录到路径 +SCRIPTS_DIR = os.environ.get( + "MOMENTRY_SCRIPTS_DIR", + os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +) +sys.path.insert(0, SCRIPTS_DIR) + +try: + import psycopg2 + from psycopg2.extras import RealDictCursor +except ImportError: + print("Error: psycopg2 not installed. Run: pip install psycopg2-binary") + sys.exit(1) + + +def get_db_connection(database: str = "momentry"): + """获取数据库连接""" + return psycopg2.connect( + host="localhost", + database=database, + user="accusys" + ) + + +def fetch_files(conn) -> list: + """从数据库读取所有文件信息""" + query = """ + SELECT + file_uuid, + file_name, + file_path, + duration, + width, + height, + fps, + total_frames, + status, + face_filter, + birth_registration, + created_at, + updated_at + FROM videos + ORDER BY created_at + """ + + with conn.cursor(cursor_factory=RealDictCursor) as cur: + cur.execute(query) + return cur.fetchall() + + +def convert_face_filter(old_filter: Optional[Dict]) -> Dict: + """转换旧的 face_filter 结构到新格式""" + if not old_filter: + return { + "version": "1.0", + "ui_filter_rules": { + "min_confidence": 0.5, + "max_confidence": 1.0, + "min_bbox_size": 80, + "max_bbox_size": 10000, + "source": "all", + "backend_status": "all" + }, + "processing_thresholds": { + "min_capture_quality": 0.0 + }, + "trace_settings": { + "single_frame_trace_vlm_enabled": True, + "single_frame_trace_group_enabled": True, + "single_frame_trace_unassigned_enabled": True, + "single_trace_group_filter_enabled": True + } + } + + # 检测新格式 + if "version" in old_filter: + return old_filter + + # 转换旧格式 + min_conf = old_filter.get("min_confidence", 50.0) + if isinstance(min_conf, (int, float)) and min_conf > 1.0: + min_conf = min_conf / 100.0 # 转换为 0-1 + + min_size = old_filter.get("min_size", 80) + if min_size is None: + min_size = 80 + + return { + "version": "1.0", + "ui_filter_rules": { + "min_confidence": float(min_conf), + "max_confidence": 1.0, + "min_bbox_size": int(min_size), + "max_bbox_size": 10000, + "source": "all", + "backend_status": "all" + }, + "processing_thresholds": { + "min_capture_quality": float(old_filter.get("min_capture_quality", 0.0)) + }, + "trace_settings": { + "single_frame_trace_vlm_enabled": bool(old_filter.get("single_frame_trace_vlm_enabled", True)), + "single_frame_trace_group_enabled": bool(old_filter.get("single_frame_trace_group_enabled", True)), + "single_frame_trace_unassigned_enabled": bool(old_filter.get("single_frame_trace_unassigned_enabled", True)), + "single_trace_group_filter_enabled": bool(old_filter.get("single_trace_group_filter_enabled", True)) + } + } + + +def build_file_profile(row: Dict) -> Dict: + """构建 File Profile 数据结构""" + + # 基本信息 + profile = { + "version": "1.0", + "file_uuid": row["file_uuid"], + + "file_info": { + "file_name": row["file_name"], + "file_type": "video", # 默认为视频 + "file_path": row["file_path"] + }, + + "birth": row.get("birth_registration") or { + "mac_address": "", + "birthday": row["created_at"].isoformat() if row.get("created_at") else "", + "original_path": str(Path(row["file_path"]).parent), + "original_filename": row["file_name"], + "canonical_path": row["file_path"], + "content_hash": None + }, + + "media_metadata": None, + + "face_filter": convert_face_filter(row.get("face_filter")), + + "traces_summary": { + "total_traces": 0, + "bound_traces": 0, + "unassigned_traces": 0, + "person_n_groups": 0 + }, + + "key_frame": None, + "proxy_path": None, + "audio_track": None, + + "history": [], + + "created_at": row["created_at"].isoformat() if row.get("created_at") else datetime.utcnow().isoformat(), + "updated_at": row["updated_at"].isoformat() if row.get("updated_at") else datetime.utcnow().isoformat() + } + + # 媒体元数据 + if row.get("duration"): + profile["media_metadata"] = { + "duration": float(row["duration"]), + "width": int(row["width"]) if row.get("width") else 0, + "height": int(row["height"]) if row.get("height") else 0, + "fps": float(row["fps"]) if row.get("fps") else 0.0, + "total_frames": int(row["total_frames"]) if row.get("total_frames") else 0, + "codec": None + } + + # 添加注册历史 + profile["history"].append({ + "action": "registered", + "timestamp": profile["created_at"], + "path": profile["birth"]["original_path"], + "file_name": profile["birth"]["original_filename"] + }) + + return profile + + +def save_profile(profile: Dict, output_dir: str, dry_run: bool = False) -> bool: + """保存 Profile 到文件""" + file_uuid = profile["file_uuid"] + output_path = Path(output_dir) / f"{file_uuid}.profile.json" + + if dry_run: + print(f"[DRY-RUN] Would write: {output_path}") + return True + + try: + with open(output_path, 'w', encoding='utf-8') as f: + json.dump(profile, f, indent=2, ensure_ascii=False) + print(f"✅ Generated: {output_path}") + return True + except Exception as e: + print(f"❌ Failed to write {output_path}: {e}") + return False + + +def main(): + parser = argparse.ArgumentParser(description="生成 File Profile 文件") + parser.add_argument( + "--output-dir", + default=os.environ.get("MOMENTRY_OUTPUT_DIR", os.path.expanduser("~/momentry/output")), + help="输出目录" + ) + parser.add_argument( + "--database", + default="momentry", + help="数据库名称" + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="只打印将要执行的操作,不实际写入文件" + ) + + args = parser.parse_args() + + print(f"输出目录: {args.output_dir}") + print(f"数据库: {args.database}") + print(f"Dry run: {args.dry_run}") + print() + + # 检查输出目录 + output_dir = Path(args.output_dir) + if not output_dir.exists(): + print(f"❌ 输出目录不存在: {output_dir}") + sys.exit(1) + + # 连接数据库 + print("连接数据库...") + try: + conn = get_db_connection(args.database) + except Exception as e: + print(f"❌ 数据库连接失败: {e}") + sys.exit(1) + + # 读取文件 + print("读取文件列表...") + files = fetch_files(conn) + print(f"找到 {len(files)} 个文件") + print() + + # 生成 Profile + success_count = 0 + failed_count = 0 + + for row in files: + try: + profile = build_file_profile(dict(row)) + if save_profile(profile, args.output_dir, args.dry_run): + success_count += 1 + else: + failed_count += 1 + except Exception as e: + print(f"❌ 处理失败 {row['file_uuid']}: {e}") + failed_count += 1 + + conn.close() + + print() + print("=" * 60) + print(f"完成!成功: {success_count}, 失败: {failed_count}") + + if args.dry_run: + print() + print("这是 DRY-RUN 模式,没有实际写入文件") + print("移除 --dry-run 参数以实际执行") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/migration/migrate_all.py b/installer/build/MomentryCore/tools/script/migration/migrate_all.py new file mode 100644 index 00000000..7b7c8174 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/migration/migrate_all.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +""" +迁移工具 - 一键执行所有迁移任务 + +执行顺序: +1. 生成 File Profile 文件 +2. 生成 Identity Profile 文件 +3. 更新 Trace Profile 文件 +4. 生成索引文件 + +Usage: + python3 migrate_all.py [--dry-run] +""" + +import argparse +import subprocess +import sys +from pathlib import Path + +def run_script(script_path: str, args: list = None, dry_run: bool = False) -> bool: + """运行迁移脚本""" + cmd = ["python3", script_path] + + if args: + cmd.extend(args) + + if dry_run: + cmd.append("--dry-run") + + print(f"\n执行: {' '.join(cmd)}") + print("=" * 60) + + try: + result = subprocess.run(cmd, check=True) + return result.returncode == 0 + except subprocess.CalledProcessError as e: + print(f"❌ 脚本执行失败: {e}") + return False + except Exception as e: + print(f"❌ 意外错误: {e}") + return False + + +def main(): + parser = argparse.ArgumentParser(description="一键执行所有迁移任务") + parser.add_argument( + "--dry-run", + action="store_true", + help="只打印将要执行的操作,不实际写入文件" + ) + parser.add_argument( + "--output-dir", + default=os.path.expanduser("~/momentry/output"), + help="输出目录" + ) + parser.add_argument( + "--identities-dir", + default=os.path.expanduser("~/momentry/identities"), + help="Identity 目录" + ) + parser.add_argument( + "--database", + default="momentry", + help="数据库名称" + ) + + args = parser.parse_args() + + print("=" * 60) + print("三段式实体文件持久化迁移工具") + print("=" * 60) + print() + print(f"输出目录: {args.output_dir}") + print(f"Identity 目录: {args.identities_dir}") + print(f"数据库: {args.database}") + print(f"Dry run: {args.dry_run}") + print() + + # 脚本目录 + script_dir = Path(__file__).parent + + # 任务列表 + tasks = [ + { + "name": "生成 File Profile 文件", + "script": str(script_dir / "generate_profiles.py"), + "args": [ + "--output-dir", args.output_dir, + "--database", args.database + ] + }, + { + "name": "生成 Identity Profile 文件", + "script": str(script_dir / "generate_identities.py"), + "args": [ + "--identities-dir", args.identities_dir, + "--database", args.database + ] + } + ] + + # 执行任务 + success_count = 0 + failed_count = 0 + + for task in tasks: + print() + print(f"任务: {task['name']}") + print("-" * 60) + + if run_script(task["script"], task.get("args"), args.dry_run): + success_count += 1 + else: + failed_count += 1 + print(f"⚠️ 任务失败: {task['name']}") + response = input("继续下一个任务? (y/n): ") + if response.lower() != 'y': + print("迁移已中止") + break + + # 总结 + print() + print("=" * 60) + print("迁移完成") + print("=" * 60) + print(f"成功任务: {success_count}") + print(f"失败任务: {failed_count}") + + if args.dry_run: + print() + print("这是 DRY-RUN 模式,没有实际写入文件") + print("移除 --dry-run 参数以实际执行") + + if failed_count > 0: + sys.exit(1) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/ocr/ocr_processor.py b/installer/build/MomentryCore/tools/script/ocr/ocr_processor.py new file mode 100755 index 00000000..373102b3 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/ocr/ocr_processor.py @@ -0,0 +1,138 @@ +#!/opt/homebrew/bin/python3.11 +""" +OCR Processor Wrapper +Calls Swift Vision Framework OCR (swift_ocr) with fallback to PaddleOCR. +""" + +import re +import sys +import json +import os +import subprocess +import argparse + + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + + +SWIFT_OCR_PATH = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "swift_processors/.build/debug/swift_ocr" +) +SWIFT_OCR_ALT = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "swift_processors/.build/arm64-apple-macosx/debug/swift_ocr" +) +SWIFT_PROGRESS_RE = re.compile(r"\[SwiftOCR\] Progress:\s*(\d+)%") + + +def _round_json_numbers(obj): + """Recursively round all float values to 2 decimal places (JSON output only).""" + if isinstance(obj, float): + return round(obj, 2) + if isinstance(obj, dict): + return {k: _round_json_numbers(v) for k, v in obj.items()} + if isinstance(obj, list): + return [_round_json_numbers(v) for v in obj] + return obj + + +def process_ocr( + video_path: str, + output_path: str, + uuid: str = "", + sample_interval: int = 30, + recognition_level: str = "accurate", + publisher: RedisPublisher = None, +) -> dict: + swift_bin = SWIFT_OCR_PATH + if not os.path.exists(swift_bin): + swift_bin = SWIFT_OCR_ALT + + if not os.path.exists(swift_bin): + print("[OCR] Swift binary not found, using PaddleOCR", file=sys.stderr) + return _fallback(video_path, output_path, uuid, sample_interval) + + cmd = [swift_bin, video_path, output_path, + "--sample-interval", str(sample_interval), + "--recognition-level", recognition_level, + "--uuid", uuid] + + print(f"[OCR] Running Swift OCR", file=sys.stderr) + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + + last_pct = -1 + stdout_lines = [] + for line in proc.stdout: + line = line.strip() + stdout_lines.append(line) + m = SWIFT_PROGRESS_RE.search(line) + if m: + pct = int(m.group(1)) + if pct > last_pct: + last_pct = pct + print(f"[OCR] Progress: {pct}%", file=sys.stderr) + if publisher: + publisher.progress("ocr", pct, 100, f"{pct}%") + elif line: + print(line, file=sys.stderr) + + stderr_output = proc.stderr.read() + if stderr_output: + print(stderr_output.strip(), file=sys.stderr) + + proc.wait() + + if proc.returncode != 0 or not os.path.exists(output_path): + print(f"[OCR] Swift OCR failed (exit={proc.returncode}), falling back to PaddleOCR", file=sys.stderr) + if publisher: + publisher.error("ocr", f"Swift OCR failed, using fallback") + return _fallback(video_path, output_path, uuid, sample_interval) + + with open(output_path) as f: + return json.load(f) + + +def _fallback(video_path, output_path, uuid, sample_interval): + """Fallback to MPS OCR implementation""" + import importlib + spec = importlib.util.spec_from_file_location( + "ocr_mps", + os.path.join(os.path.dirname(__file__), "ocr_processor_mps.py") + ) + if spec is None: + print("[OCR] No fallback available, returning empty result", file=sys.stderr) + return {"frame_count": 0, "fps": 0, "frames": []} + ocr_mps = importlib.util.module_from_spec(spec) + spec.loader.exec_module(ocr_mps) + return ocr_mps.process_video_ocr( + video_path=video_path, + output_path=output_path, + sample_interval=sample_interval + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="OCR Processor (Swift Vision)") + parser.add_argument("video_path") + parser.add_argument("output_path") + parser.add_argument("--uuid", "-u", default="") + parser.add_argument("--sample-interval", type=int, default=30) + parser.add_argument("--recognition-level", choices=["fast", "accurate"], default="accurate") + parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS) + args = parser.parse_args() + + publisher = RedisPublisher(args.uuid) if args.uuid else None + if publisher: + publisher.info("ocr", "OCR_START") + + result = process_ocr(args.video_path, args.output_path, args.uuid, + args.sample_interval, args.recognition_level, + publisher) + + with open(args.output_path, "w") as f: + json.dump(_round_json_numbers(result), f, indent=2) + print(f"OCR: {len(result.get('frames', []))} frames with text") + if publisher: + publisher.complete("ocr", f"{len(result.get('frames',[]))} frames") diff --git a/installer/build/MomentryCore/tools/script/ocr_processor.py b/installer/build/MomentryCore/tools/script/ocr_processor.py new file mode 120000 index 00000000..ae650322 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/ocr_processor.py @@ -0,0 +1 @@ +/Users/accusys/momentry_core/tools/script/ocr/ocr_processor.py \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/pose/pose_processor.py b/installer/build/MomentryCore/tools/script/pose/pose_processor.py new file mode 100755 index 00000000..5352fb46 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/pose/pose_processor.py @@ -0,0 +1,336 @@ +#!/opt/homebrew/bin/python3.11 +""" +Pose Processor Wrapper +Calls Swift Vision Framework pose (swift_pose) with fallback to YOLOv8 Pose. +Uses VNDetectHumanBodyPoseRequest with ANE acceleration. +""" + +import re +import sys +import json +import os +import subprocess +import argparse + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + +SWIFT_POSE_PATH = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "swift_processors/.build/debug/swift_pose" +) +SWIFT_POSE_ALT = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "swift_processors/.build/arm64-apple-macosx/debug/swift_pose" +) + + +SWIFT_POSE_PROGRESS_RE = re.compile(r"\[SwiftPose\] Progress:\s*(\d+)%") + +def round_json_numbers(obj): + """Recursively round all float values to 2 decimal places (JSON output only).""" + if isinstance(obj, float): + return round(obj, 2) + if isinstance(obj, dict): + return {k: round_json_numbers(v) for k, v in obj.items()} + if isinstance(obj, list): + return [round_json_numbers(v) for v in obj] + return obj + +def process_pose( + video_path: str, + output_path: str, + uuid: str = "", + sample_interval: int = 3, # Changed from 30 to match Face + publisher: RedisPublisher = None, + target_frames: list = None, +) -> dict: + # Check if pose.json or pose.json.tmp already exists (from swift_face_pose) + # executor.rs renames output to .json.tmp before running Python script + tmp_path = output_path.replace('.json', '.json.tmp') + + source_path = None + if os.path.exists(output_path): + source_path = output_path + print(f"[Pose] Output exists from swift_face_pose: {output_path}", file=sys.stderr) + elif os.path.exists(tmp_path): + source_path = tmp_path + print(f"[Pose] Temp output exists from swift_face_pose: {tmp_path}", file=sys.stderr) + + if source_path: + with open(source_path) as f: + data = json.load(f) + + detected_frames = len(data.get('frames', [])) + print(f"[Pose] Loaded {detected_frames} detected frames", file=sys.stderr) + + # When target_frames is provided (8Hz sampling), skip interpolation + # Swift already outputs at sample_interval=3, matching 8Hz for 24fps + if target_frames is not None: + print(f"[Pose] 8Hz mode: returning {detected_frames} frames without interpolation", file=sys.stderr) + if publisher: + publisher.progress("pose", 100, 100, f"{detected_frames} frames (8Hz, no interpolation)") + return data + + # Interpolate keypoints for all frames + interpolated_data = interpolate_pose(data, video_path) + + # Write interpolated output + with open(output_path, 'w') as f: + json.dump(round_json_numbers(interpolated_data), f) + + # Delete .json.tmp file so executor.rs won't restore it + if os.path.exists(tmp_path): + os.remove(tmp_path) + print(f"[Pose] Deleted temp file: {tmp_path}", file=sys.stderr) + + total_frames = len(interpolated_data.get('frames', [])) + print(f"[Pose] Interpolated to {total_frames} frames", file=sys.stderr) + + if publisher: + publisher.progress("pose", 100, 100, f"Interpolated {total_frames} frames") + return interpolated_data + + swift_bin = SWIFT_POSE_PATH + if not os.path.exists(swift_bin): + swift_bin = SWIFT_POSE_ALT + + if not os.path.exists(swift_bin): + print("[Pose] Swift binary not found, using YOLOv8 fallback", file=sys.stderr) + if publisher: + publisher.error("pose", "Swift binary not found, using fallback") + return _fallback(video_path, output_path, uuid, sample_interval) + + cmd = [swift_bin, video_path, output_path, + "--sample-interval", str(sample_interval), + "--uuid", uuid] + + print(f"[Pose] Running Swift Pose (Vision Framework)", file=sys.stderr) + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + + last_pct = -1 + for line in proc.stdout: + line = line.strip() + m = SWIFT_POSE_PROGRESS_RE.search(line) + if m: + pct = int(m.group(1)) + if pct > last_pct: + last_pct = pct + print(f"[Pose] Progress: {pct}%", file=sys.stderr) + if publisher: + publisher.progress("pose", pct, 100, f"{pct}%") + elif line: + print(f" {line}", file=sys.stderr) + + stderr_output = proc.stderr.read() + if stderr_output: + print(stderr_output.strip(), file=sys.stderr) + + proc.wait() + + if proc.returncode != 0 or not os.path.exists(output_path): + print(f"[Pose] Swift Pose failed (exit={proc.returncode}), falling back to YOLOv8", file=sys.stderr) + if publisher: + publisher.error("pose", f"Swift Pose failed, using fallback") + return _fallback(video_path, output_path, uuid, sample_interval) + + with open(output_path) as f: + return json.load(f) + + +def interpolate_pose(detected_data: dict, video_path: str) -> dict: + """Interpolate keypoints for all frames between detected frames""" + import cv2 + import numpy as np + + cap = cv2.VideoCapture(video_path) + total_video_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + fps = detected_data.get('fps', 30.0) + + detected_frames = detected_data.get('frames', []) + if not detected_frames: + cap.release() + return detected_data + + # Build frame index map + frame_map = {f['frame']: f for f in detected_frames} + detected_frame_nums = sorted(frame_map.keys()) + + print(f"[Pose] Interpolating from {len(detected_frame_nums)} detected frames to {total_video_frames} total frames", file=sys.stderr) + + # Get all persons from detected frames (assume same person tracking) + all_persons = {} + for f in detected_frames: + for i, p in enumerate(f.get('persons', [])): + if i not in all_persons: + all_persons[i] = [] + all_persons[i].append((f['frame'], p)) + + # Interpolate each person's keypoints for each frame + interpolated_frames = [] + + for frame_num in range(total_video_frames): + ts = frame_num / fps + + persons_in_frame = [] + + for person_id, person_frames in all_persons.items(): + # Find closest detected frames before and after + before = None + after = None + for fn, p in person_frames: + if fn <= frame_num: + before = (fn, p) + if fn >= frame_num and after is None: + after = (fn, p) + + if before is None and after is None: + continue + + # Interpolate keypoints + interpolated_keypoints = [] + bbox = None + + if before and after and before[0] != after[0]: + # Linear interpolation + t0, t1 = before[0], after[0] + t = (frame_num - t0) / (t1 - t0) if t1 != t0 else 0 + + kp_before = before[1].get('keypoints', []) + kp_after = after[1].get('keypoints', []) + bbox_before = before[1].get('bbox', {}) + bbox_after = after[1].get('bbox', {}) + + # Interpolate keypoints + for i in range(max(len(kp_before), len(kp_after))): + kp0 = kp_before[i] if i < len(kp_before) else kp_after[i] + kp1 = kp_after[i] if i < len(kp_after) else kp_before[i] + + x = kp0['x'] + t * (kp1['x'] - kp0['x']) + y = kp0['y'] + t * (kp1['y'] - kp0['y']) + c = kp0['confidence'] + t * (kp1['confidence'] - kp0['confidence']) + + interpolated_keypoints.append({ + 'name': kp0['name'], + 'x': x, + 'y': y, + 'confidence': c + }) + + # Interpolate bbox + if bbox_before and bbox_after: + bbox = { + 'x': int(bbox_before['x'] + t * (bbox_after['x'] - bbox_before['x'])), + 'y': int(bbox_before['y'] + t * (bbox_after['y'] - bbox_before['y'])), + 'width': int(bbox_before['width'] + t * (bbox_after['width'] - bbox_before['width'])), + 'height': int(bbox_before['height'] + t * (bbox_after['height'] - bbox_before['height'])) + } + + elif before: + # Use before frame's data + interpolated_keypoints = before[1].get('keypoints', []) + bbox = before[1].get('bbox', {}) + + elif after: + # Use after frame's data + interpolated_keypoints = after[1].get('keypoints', []) + bbox = after[1].get('bbox', {}) + + if bbox and bbox.get('width', 0) > 0 and bbox.get('height', 0) > 0: + persons_in_frame.append({ + 'keypoints': interpolated_keypoints, + 'bbox': bbox + }) + + if persons_in_frame: + interpolated_frames.append({ + 'frame': frame_num, + 'timestamp': ts, + 'persons': persons_in_frame + }) + + cap.release() + + return { + 'frame_count': len(interpolated_frames), + 'fps': fps, + 'frames': interpolated_frames + } + + +def _fallback(video_path, output_path, uuid, sample_interval): + """Fallback to YOLOv8 Pose""" + from ultralytics import YOLO + import cv2 + model = YOLO("yolov8n-pose.pt") + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) + frame_count = 0 + frames = [] + while cap.isOpened(): + ret, frame = cap.read() + if not ret: + break + if frame_count % sample_interval == 0: + ts = frame_count / fps if fps > 0 else 0 + results = model(frame, verbose=False, device="cpu") + persons = [] + for r in results: + if r.keypoints is None: + continue + for kp_data in r.keypoints: + kps = kp_data.xy[0].cpu().numpy() if hasattr(kp_data, 'xy') else [] + confs = kp_data.conf[0].cpu().numpy() if hasattr(kp_data, 'conf') else [] + keypoints = [] + names = ["nose", "left_eye", "right_eye", "left_ear", "right_ear", + "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", + "left_wrist", "right_wrist", "left_hip", "right_hip", + "left_knee", "right_knee", "left_ankle", "right_ankle"] + for j, name in enumerate(names): + if j < len(kps): + x, y = float(kps[j][0]), float(kps[j][1]) + c = float(confs[j]) if j < len(confs) else 0 + keypoints.append({"name": name, "x": x, "y": y, "confidence": c}) + if keypoints: + xs = [k["x"] for k in keypoints if k["confidence"] > 0.1] + ys = [k["y"] for k in keypoints if k["confidence"] > 0.1] + bbox = {"x": int(min(xs)), "y": int(min(ys)), "width": int(max(xs)-min(xs)), "height": int(max(ys)-min(ys))} if xs else {"x": 0, "y": 0, "width": 0, "height": 0} + persons.append({"keypoints": keypoints, "bbox": bbox}) + if persons: + frames.append({"frame": frame_count, "timestamp": ts, "persons": persons}) + frame_count += 1 + cap.release() + result = {"frame_count": len(frames), "fps": fps, "frames": frames} + if len(frames) == 0: + result["status"] = "no_face" + with open(output_path, "w") as f: + json.dump(round_json_numbers(result), f, indent=2) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Pose Processor (Swift Vision)") + parser.add_argument("video_path") + parser.add_argument("output_path") + parser.add_argument("--uuid", "-u", default="") + parser.add_argument("--sample-interval", type=int, default=3) # Changed from 30 to match Face + parser.add_argument("--frames", type=str, default=None, + help="Comma-separated frame numbers for 8Hz sampling") + args = parser.parse_args() + + target_frames = None + if args.frames: + target_frames = [int(f) for f in args.frames.split(",") if f.strip()] + print(f"[Pose] 8Hz target frames: {len(target_frames)} frames", file=sys.stderr) + + publisher = RedisPublisher(args.uuid) if args.uuid else None + if publisher: + publisher.info("pose", "POSE_START") + + result = process_pose(args.video_path, args.output_path, args.uuid, + args.sample_interval, publisher, target_frames) + with open(args.output_path, "w") as f: + json.dump(round_json_numbers(result), f, indent=2) + print(f"Pose: {len(result.get('frames', []))} frames with poses") + if publisher: + publisher.complete("pose", f"{len(result.get('frames',[]))} frames") diff --git a/installer/build/MomentryCore/tools/script/pose/pose_processor_mediapipe.py b/installer/build/MomentryCore/tools/script/pose/pose_processor_mediapipe.py new file mode 100755 index 00000000..e84c9c6b --- /dev/null +++ b/installer/build/MomentryCore/tools/script/pose/pose_processor_mediapipe.py @@ -0,0 +1,249 @@ +#!/opt/homebrew/bin/python3.11 +""" +MediaPipe Pose Processor (v1.0.0 API) - 高準確率人體姿勢檢測 + +使用 Google MediaPipe PoseLandmarker (新 API),提供更高的準確率。 + +MediaPipe v1.0.0 使用 tasks.vision.PoseLandmarker API。 + +相比 Apple Vision Pose: +- ✅ 準確率更高 +- ✅ 支持 33 個關鍵點 +- ✅ 支持遮擋和困難姿勢 + +輸出格式與 pose_processor.py 兼容。 + +Usage: + python pose_processor_mediapipe.py video_path output_path [--uuid UUID] [--model-complexity 0|1|2] +""" + +import json +import argparse +import time +import os +import sys +import cv2 +import numpy as np +import mediapipe as mp + +# 33 個關鍵點名稱 (MediaPipe Pose) +KEYPOINT_NAMES = [ + "nose", "left_eye_inner", "left_eye", "left_eye_outer", + "right_eye_inner", "right_eye", "right_eye_outer", + "left_ear", "right_ear", "mouth_left", "mouth_right", + "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", + "left_wrist", "right_wrist", "left_pinky", "right_pinky", + "left_index", "right_index", "left_thumb", "right_thumb", + "left_hip", "right_hip", "left_knee", "right_knee", + "left_ankle", "right_ankle", "left_heel", "right_heel", + "left_foot_index", "right_foot_index" +] + + +class MediaPipePoseProcessor: + def __init__(self, model_complexity: int = 2): + """ + 初始化 MediaPipe PoseLandmarker (v1.0.0 API) + + Args: + model_complexity: 模型複雜度 (0, 1, 2) + 0 = 最快,準確率較低 + 1 = 平衡 + 2 = 最慢,準確率最高 + """ + # 使用新 API (MediaPipe v1.0.0) + self.model_path = self._get_model_path(model_complexity) + + if not os.path.exists(self.model_path): + raise FileNotFoundError( + f"MediaPipe Pose model not found: {self.model_path}\n" + f"Download from: https://storage.googleapis.com/mediapipe-models/pose_landmarker/" + ) + + # 創建 PoseLandmarker + options = mp.tasks.vision.PoseLandmarkerOptions( + base_options=mp.tasks.BaseOptions( + model_asset_path=self.model_path, + delegate=mp.tasks.BaseOptions.Delegate.CPU + ), + running_mode=mp.tasks.vision.RunningMode.VIDEO, + num_poses=1, + min_pose_detection_confidence=0.5, + min_pose_presence_confidence=0.5, + min_tracking_confidence=0.5 + ) + + self.landmarker = mp.tasks.vision.PoseLandmarker.create_from_options(options) + self.model_complexity = model_complexity + + def _get_model_path(self, complexity: int) -> str: + """獲取模型路徑""" + # MediaPipe v1.0.0 模型路徑 + model_dir = os.path.expanduser("~/models/mediapipe") + model_names = { + 0: "pose_landmarker_lite.task", + 1: "pose_landmarker_full.task", + 2: "pose_landmarker_heavy.task" + } + return os.path.join(model_dir, model_names.get(complexity, model_names[2])) + + def process_video(self, video_path: str, output_path: str, uuid: str = None): + """處理視頻""" + cap = cv2.VideoCapture(video_path) + + if not cap.isOpened(): + print(f"[ERROR] Cannot open video: {video_path}") + return + + fps = cap.get(cv2.CAP_PROP_FPS) + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + + print(f"[MediaPipe Pose] Video: {video_path}") + print(f"[MediaPipe Pose] FPS: {fps}, Frames: {total_frames}, Size: {width}x{height}") + print(f"[MediaPipe Pose] Model complexity: {self.model_complexity}") + print(f"[MediaPipe Pose] Model: {self.model_path}") + + frames_data = [] + frame_idx = 0 + + start_time = time.time() + + while cap.isOpened(): + ret, frame = cap.read() + if not ret: + break + + # 轉換為 RGB + rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + + # 創建 MediaPipe Image + mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_frame) + + # 計算時間戳(毫秒) + timestamp_ms = int(frame_idx * 1000 / fps) + + # 檢測姿勢 + results = self.landmarker.detect_for_video(mp_image, timestamp_ms) + + if results.pose_landmarks and len(results.pose_landmarks) > 0: + # 提取第一個人的關鍵點 + landmarks = results.pose_landmarks[0] + + # 轉換為關鍵點列表 + keypoints = [] + for i, lm in enumerate(landmarks): + keypoint = { + "name": KEYPOINT_NAMES[i] if i < len(KEYPOINT_NAMES) else f"keypoint_{i}", + "x": int(lm.x * width), + "y": int(lm.y * height), + "z": float(lm.z), + "confidence": float(lm.visibility if hasattr(lm, 'visibility') else 1.0) + } + keypoints.append(keypoint) + + # 計算邊界框 + x_coords = [lm.x for lm in landmarks] + y_coords = [lm.y for lm in landmarks] + + x_min = int(min(x_coords) * width) + x_max = int(max(x_coords) * width) + y_min = int(min(y_coords) * height) + y_max = int(max(y_coords) * height) + + bbox = { + "x": x_min, + "y": y_min, + "width": x_max - x_min, + "height": y_max - y_min + } + + person = { + "person_id": 0, + "keypoints": keypoints, + "bbox": bbox + } + + frame_data = { + "frame": frame_idx, + "timestamp": frame_idx / fps, + "persons": [person] + } + + frames_data.append(frame_data) + else: + # 沒有檢測到姿勢 + frame_data = { + "frame": frame_idx, + "timestamp": frame_idx / fps, + "persons": [] + } + frames_data.append(frame_data) + + frame_idx += 1 + + # 進度報告 + if frame_idx % 100 == 0: + elapsed = time.time() - start_time + fps_processed = frame_idx / elapsed + print(f"[MediaPipe Pose] Progress: {frame_idx}/{total_frames} ({frame_idx/total_frames*100:.1f}%), {fps_processed:.1f} fps") + + cap.release() + + elapsed = time.time() - start_time + print(f"[MediaPipe Pose] Completed: {frame_idx} frames in {elapsed:.1f}s ({frame_idx/elapsed:.1f} fps)") + + # 統計 + frames_with_pose = sum(1 for f in frames_data if f["persons"]) + total_poses = sum(len(f["persons"]) for f in frames_data) + + print(f"[MediaPipe Pose] Frames with pose: {frames_with_pose}/{frame_idx} ({frames_with_pose/frame_idx*100:.1f}%)") + print(f"[MediaPipe Pose] Total poses: {total_poses}") + + # 構建輸出 + output = { + "frame_count": len(frames_data), + "fps": fps, + "total_poses": total_poses, + "frames": frames_data + } + + # 寫入文件 + output_tmp = output_path + ".tmp" + with open(output_tmp, "w") as f: + json.dump(output, f, indent=2) + + os.rename(output_tmp, output_path) + print(f"[MediaPipe Pose] Output: {output_path}") + + def close(self): + """釋放資源""" + if self.landmarker: + self.landmarker.close() + + +def main(): + parser = argparse.ArgumentParser(description="MediaPipe Pose Processor") + parser.add_argument("video_path", help="Path to video file") + parser.add_argument("output_path", help="Path to output JSON file") + parser.add_argument("--uuid", help="Video UUID (optional)") + parser.add_argument("--model-complexity", type=int, default=2, choices=[0, 1, 2], + help="Model complexity: 0=fast, 1=balanced, 2=accurate (default: 2)") + parser.add_argument("--frames", help="Comma-separated frame indices for 8Hz sampling (optional, ignored for MediaPipe)") + + args = parser.parse_args() + + try: + processor = MediaPipePoseProcessor(model_complexity=args.model_complexity) + processor.process_video(args.video_path, args.output_path, args.uuid) + processor.close() + except Exception as e: + print(f"[ERROR] {e}") + import traceback + traceback.print_exc() + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/installer/build/MomentryCore/tools/script/redis_publisher.py b/installer/build/MomentryCore/tools/script/redis_publisher.py new file mode 120000 index 00000000..e0575b2b --- /dev/null +++ b/installer/build/MomentryCore/tools/script/redis_publisher.py @@ -0,0 +1 @@ +/Users/accusys/momentry_core/scripts/redis_publisher.py \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/store_traced_faces.py b/installer/build/MomentryCore/tools/script/store_traced_faces.py new file mode 120000 index 00000000..20b62ebe --- /dev/null +++ b/installer/build/MomentryCore/tools/script/store_traced_faces.py @@ -0,0 +1 @@ +/Users/accusys/momentry_core/tools/script/face/store_traced_faces.py \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/swift_processors b/installer/build/MomentryCore/tools/script/swift_processors new file mode 120000 index 00000000..9fe14949 --- /dev/null +++ b/installer/build/MomentryCore/tools/script/swift_processors @@ -0,0 +1 @@ +/Users/accusys/momentry_core/scripts/swift_processors \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/utils/face_tracker.py b/installer/build/MomentryCore/tools/script/utils/face_tracker.py new file mode 100755 index 00000000..e218fccc --- /dev/null +++ b/installer/build/MomentryCore/tools/script/utils/face_tracker.py @@ -0,0 +1,590 @@ +#!/opt/homebrew/bin/python3.11 +""" +Face Tracker - Track faces across frames using embedding similarity and bbox proximity + +Purpose: +1. Assign unique trace_id to each face across frames +2. Track face movement across adjacent frames +3. Output trace statistics (duration, path, confidence) + +Algorithm: +1. For first frame: assign new trace_id to each face +2. For subsequent frames: + - Calculate bbox overlap with previous frame faces + - Calculate embedding cosine similarity + - Match faces if both conditions met + - Assign same trace_id if matched, new trace_id if not + +Matching Conditions: +- bbox overlap > 0.3 (IoU) +- embedding similarity > 0.7 +- OR single condition > threshold (fallback) + +Output: +- face.json with trace_id added to each face +- trace statistics report +""" + +import json +import argparse +import numpy as np + + +def strip_embeddings_and_round(obj): + """Remove face embeddings from face_traced.json and round floats to 2 dp. + + Embeddings live in Qdrant _faces (512D); storing them in the JSON bloats the + file (~2MB+ per 1000 faces). face_tracker consumes embeddings in-memory (loaded + from Qdrant before tracking), so stripping at write time is safe: all downstream + consumers (TKG, clustering, cluster_agent) read Qdrant or trace IDs instead. + """ + if isinstance(obj, dict): + return { + k: strip_embeddings_and_round(v) + for k, v in obj.items() + if not (k == "embedding") + } + if isinstance(obj, list): + return [strip_embeddings_and_round(v) for v in obj] + if isinstance(obj, float): + return round(obj, 2) + return obj +from typing import Dict, List, Set +from collections import defaultdict + + +def calculate_bbox_iou(bbox1: Dict, bbox2: Dict) -> float: + """ + Calculate Intersection over Union (IoU) between two bboxes + + Args: + bbox1: {"x": int, "y": int, "width": int, "height": int} + bbox2: same structure + + Returns: + IoU score (0.0 - 1.0) + """ + x1, y1, w1, h1 = bbox1["x"], bbox1["y"], bbox1["width"], bbox1["height"] + x2, y2, w2, h2 = bbox2["x"], bbox2["y"], bbox2["width"], bbox2["height"] + + x1_min, x1_max = x1, x1 + w1 + y1_min, y1_max = y1, y1 + h1 + x2_min, x2_max = x2, x2 + w2 + y2_min, y2_max = y2, y2 + h2 + + inter_x_min = max(x1_min, x2_min) + inter_x_max = min(x1_max, x2_max) + inter_y_min = max(y1_min, y2_min) + inter_y_max = min(y1_max, y2_max) + + if inter_x_max <= inter_x_min or inter_y_max <= inter_y_min: + return 0.0 + + inter_area = (inter_x_max - inter_x_min) * (inter_y_max - inter_y_min) + area1 = w1 * h1 + area2 = w2 * h2 + union_area = area1 + area2 - inter_area + + return inter_area / union_area if union_area > 0 else 0.0 + + +def calculate_bbox_distance(bbox1: Dict, bbox2: Dict) -> float: + """ + Calculate center distance between two bboxes + + Returns: + Euclidean distance between centers + """ + cx1 = bbox1["x"] + bbox1["width"] / 2 + cy1 = bbox1["y"] + bbox1["height"] / 2 + cx2 = bbox2["x"] + bbox2["width"] / 2 + cy2 = bbox2["y"] + bbox2["height"] / 2 + + return np.sqrt((cx1 - cx2) ** 2 + (cy1 - cy2) ** 2) + + +def calculate_embedding_similarity(emb1: List[float], emb2: List[float]) -> float: + """ + Calculate cosine similarity between two embeddings + + Returns: + Cosine similarity (-1.0 - 1.0) + """ + if emb1 is None or emb2 is None: + return 0.0 + + v1 = np.array(emb1) + v2 = np.array(emb2) + + norm1 = np.linalg.norm(v1) + norm2 = np.linalg.norm(v2) + + if norm1 == 0 or norm2 == 0: + return 0.0 + + return np.dot(v1, v2) / (norm1 * norm2) + + +def match_faces( + current_faces: List[Dict], + previous_faces: List[Dict], + iou_threshold: float = 0.3, + similarity_threshold: float = 0.7, + distance_threshold: float = 100.0, + use_embedding: bool = True, + frame_gap: int = 1, + cut_boundaries: Set[int] = None, + prev_frame: int = None, + curr_frame: int = None, +) -> Dict[int, int]: + """ + Match current frame faces to previous frame faces + + Args: + current_faces: Faces in current frame + previous_faces: Faces in previous frame + iou_threshold: Minimum IoU for matching + similarity_threshold: Minimum embedding similarity for matching + distance_threshold: Maximum bbox center distance for matching + use_embedding: Whether to use embedding similarity + frame_gap: Number of frames between current and previous (1=adjacent) + cut_boundaries: Set of frame numbers where scene cuts occur + prev_frame: Previous frame number (for cut detection) + curr_frame: Current frame number (for cut detection) + + Returns: + Dict mapping current_face_index -> previous_face_index (or -1 if new) + """ + if not previous_faces: + return {i: -1 for i in range(len(current_faces))} + + # If frame gap is too large, force new traces (likely crossed multiple scenes) + if frame_gap is not None and frame_gap > 30: + return {i: -1 for i in range(len(current_faces))} + + # If a scene cut exists between prev and current frame, only continue + # traces for faces matching the previous frame with high IoU (same person + # in the same position across the cut); unmatched faces get new traces. + if cut_boundaries and prev_frame is not None and curr_frame is not None: + for cf in cut_boundaries: + if prev_frame < cf <= curr_frame: + matches = {} + used_prev = set() + for curr_idx, curr_face in enumerate(current_faces): + best_prev_idx = -1 + best_iou = 0.0 + curr_bbox = { + "x": curr_face["x"], + "y": curr_face["y"], + "width": curr_face["width"], + "height": curr_face["height"], + } + for prev_idx, prev_face in enumerate(previous_faces): + if prev_idx in used_prev: + continue + prev_bbox = { + "x": prev_face["x"], + "y": prev_face["y"], + "width": prev_face["width"], + "height": prev_face["height"], + } + iou = calculate_bbox_iou(curr_bbox, prev_bbox) + if iou > best_iou: + best_iou = iou + best_prev_idx = prev_idx + if best_prev_idx >= 0 and best_iou > 0.5: + matches[curr_idx] = best_prev_idx + used_prev.add(best_prev_idx) + else: + matches[curr_idx] = -1 + return matches + + matches = {} + used_prev = set() + + for curr_idx, curr_face in enumerate(current_faces): + best_prev_idx = -1 + best_score = 0.0 + + curr_bbox = { + "x": curr_face["x"], + "y": curr_face["y"], + "width": curr_face["width"], + "height": curr_face["height"], + } + curr_emb = curr_face.get("embedding") + + for prev_idx, prev_face in enumerate(previous_faces): + if prev_idx in used_prev: + continue + + prev_bbox = { + "x": prev_face["x"], + "y": prev_face["y"], + "width": prev_face["width"], + "height": prev_face["height"], + } + prev_emb = prev_face.get("embedding") + + iou = calculate_bbox_iou(curr_bbox, prev_bbox) + distance = calculate_bbox_distance(curr_bbox, prev_bbox) + + similarity = 0.0 + if use_embedding and curr_emb and prev_emb: + similarity = calculate_embedding_similarity(curr_emb, prev_emb) + + # Bbox size consistency check: sudden size change = different person + prev_area = prev_bbox["width"] * prev_bbox["height"] + curr_area = curr_bbox["width"] * curr_bbox["height"] + area_ratio = max(curr_area, prev_area) / max(1, min(curr_area, prev_area)) + + score = 0.0 + + # Reject only if BOTH embedding AND IoU disagree (different person + different position) + if use_embedding and curr_emb and prev_emb and similarity < 0.5 and iou < 0.3: + continue + + # Reject if bbox size changes by more than 5x (e.g., far shot → close-up) + if area_ratio > 5.0 and similarity < 0.8: + continue + + # Edge exit: if previous face was near frame edge and current face is not, + # the old face likely exited and a new face appeared + prev_at_edge = (prev_bbox["x"] < 50 or + prev_bbox["x"] + prev_bbox["width"] > 1870 or + prev_bbox["y"] < 50 or + prev_bbox["y"] + prev_bbox["height"] > 1030) + curr_at_edge = (curr_bbox["x"] < 50 or + curr_bbox["x"] + curr_bbox["width"] > 1870 or + curr_bbox["y"] < 50 or + curr_bbox["y"] + curr_bbox["height"] > 1030) + if prev_at_edge and not curr_at_edge and similarity < 0.8: + continue + + if iou > iou_threshold and similarity > similarity_threshold: + score = iou + similarity + elif iou > 0.5 and similarity > 0.65: + score = iou * 1.5 + similarity * 0.5 + elif iou > 0.35 and distance < distance_threshold: + score = iou * 2 - distance / 500 + elif similarity > 0.85: + score = similarity * 2 + elif similarity > 0.75 and distance < distance_threshold: + score = similarity - distance / 1000 + # For frame gaps (tracking lost and recovered), require higher confidence + elif frame_gap > 1 and similarity > 0.8 and iou > 0.2: + score = similarity + iou + + if score > best_score: + best_score = score + best_prev_idx = prev_idx + + if best_prev_idx >= 0 and best_score > 0: + matches[curr_idx] = best_prev_idx + used_prev.add(best_prev_idx) + else: + matches[curr_idx] = -1 + + return matches + + +def track_faces( + face_data: Dict, + iou_threshold: float = 0.3, + similarity_threshold: float = 0.7, + distance_threshold: float = 100.0, + use_embedding: bool = True, + cut_boundaries: Set[int] = None, +) -> Dict: + """ + Track faces across all frames + + Args: + face_data: face.json data + iou_threshold: IoU threshold for matching + similarity_threshold: Embedding similarity threshold + distance_threshold: Distance threshold for matching + use_embedding: Whether to use embedding + + Returns: + Updated face_data with trace_id added to each face + """ + frames = face_data.get("frames", {}) + + if not frames: + print("No frames found in face.json") + return face_data + + # Support both list and dict formats + if isinstance(frames, list): + # List format: [{frame: 0, faces: [...]}, ...] + sorted_frames = sorted(frames, key=lambda x: x.get("frame", 0)) + # Convert to dict format for consistency + frames_dict = {} + for frame_data in sorted_frames: + frame_num = frame_data.get("frame") + if frame_num is not None: + frames_dict[str(frame_num)] = {"faces": frame_data.get("faces", [])} + frames = frames_dict + face_data["frames"] = frames + + sorted_frames = sorted(frames.items(), key=lambda x: int(x[0])) + + next_trace_id = 0 + traces = defaultdict(list) + + prev_faces = [] + prev_trace_ids = [] + prev_frame_num = None + prev_face_frame = None # last frame number that had actual faces + + print(f"\nTracking faces across {len(sorted_frames)} frames...") + print(f"Parameters: iou={iou_threshold}, similarity={similarity_threshold}, distance={distance_threshold}") + print() + + for frame_num_str, frame_data in sorted_frames: + frame_num = int(frame_num_str) + frame_gap = frame_num - prev_frame_num if prev_frame_num is not None else 1 + prev_frame_num = frame_num + + faces = frame_data.get("faces", []) + + if not faces: + prev_faces = [] + prev_trace_ids = [] + continue + + matches = match_faces( + faces, + prev_faces, + iou_threshold, + similarity_threshold, + distance_threshold, + use_embedding, + frame_gap, + cut_boundaries, + prev_face_frame, + frame_num, + ) + + trace_ids = [] + for curr_idx, prev_idx in matches.items(): + if prev_idx >= 0: + trace_id = prev_trace_ids[prev_idx] + else: + trace_id = next_trace_id + next_trace_id += 1 + + faces[curr_idx]["trace_id"] = trace_id + trace_ids.append(trace_id) + traces[trace_id].append({ + "frame": frame_num, + "face_index": curr_idx, + "bbox": { + "x": faces[curr_idx]["x"], + "y": faces[curr_idx]["y"], + "width": faces[curr_idx]["width"], + "height": faces[curr_idx]["height"], + }, + "confidence": faces[curr_idx].get("confidence", 0.0), + "pose_angle": faces[curr_idx].get("pose_angle", {}).get("angle", "unknown"), + "pose_full": faces[curr_idx].get("pose_angle", {}), # 完整 pose 信息 + }) + + prev_faces = faces + prev_trace_ids = trace_ids + prev_face_frame = frame_num + + if frame_num % 100 == 0: + print(f" Frame {frame_num}: {len(faces)} faces, {len(set(trace_ids))} active traces") + + face_data["traces"] = {} + for trace_id, path in traces.items(): + if len(path) >= 1: + duration_frames = path[-1]["frame"] - path[0]["frame"] + 1 + avg_confidence = sum(p["confidence"] for p in path) / len(path) + pose_angles = [p["pose_angle"] for p in path] + + # Pose Trace: 完整 pose 信息 + pose_trace = [] + for p in path: + pose_info = p.get("pose_full", {}) + pose_trace.append({ + "frame": p["frame"], + "angle": pose_info.get("angle", "unknown"), + "confidence": pose_info.get("confidence", 0.0), + "pitch": pose_info.get("pitch", "neutral"), + "features": pose_info.get("features", {}), + }) + + # Pose Statistics + pose_counts = defaultdict(int) + pose_confidence_by_angle = defaultdict(list) + for pose in pose_trace: + pose_counts[pose["angle"]] += 1 + pose_confidence_by_angle[pose["angle"]].append(pose["confidence"]) + + pose_statistics = { + "distribution": dict(pose_counts), + "avg_confidence_by_angle": { + angle: round(sum(conf_list) / len(conf_list), 3) + for angle, conf_list in pose_confidence_by_angle.items() + }, + "dominant_angle": max(pose_counts.items(), key=lambda x: x[1])[0] if pose_counts else "unknown", + "pose_count": len(pose_counts), + } + + # Pose Transitions: pose 变化事件 + pose_transitions = [] + prev_pose = None + for i, pose in enumerate(pose_trace): + if prev_pose is not None and pose["angle"] != prev_pose["angle"]: + pose_transitions.append({ + "frame": pose["frame"], + "from_angle": prev_pose["angle"], + "to_angle": pose["angle"], + "transition_index": len(pose_transitions) + 1, + }) + prev_pose = pose + + face_data["traces"][str(trace_id)] = { + "trace_id": trace_id, + "start_frame": path[0]["frame"], + "end_frame": path[-1]["frame"], + "duration_frames": duration_frames, + "duration_seconds": duration_frames / (face_data.get("metadata") or {}).get("fps", face_data.get("fps", 30.0)), + "total_appearances": len(path), + "avg_confidence": avg_confidence, + "pose_angles": pose_angles, + "pose_trace": pose_trace, + "pose_statistics": pose_statistics, + "pose_transitions": pose_transitions, + "path": path, + } + + # Ensure metadata exists + if not face_data.get("metadata"): + face_data["metadata"] = {} + + face_data["metadata"]["trace_stats"] = { + "total_traces": next_trace_id, + "active_traces": len(traces), + "long_traces": len([t for t in traces.values() if len(t) >= 2]), + } + + return face_data + + +def analyze_traces(face_data: Dict) -> None: + """ + Analyze and print trace statistics + """ + traces = face_data.get("traces", {}) + metadata = face_data.get("metadata", {}) + + print("\n" + "=" * 60) + print("Face Trace Analysis") + print("=" * 60) + + print(f"\nTotal traces: {metadata.get('trace_stats', {}).get('total_traces', 0)}") + print(f"Long traces (>= 2 frames): {len(traces)}") + + if not traces: + return + + sorted_traces = sorted(traces.values(), key=lambda x: x["duration_frames"], reverse=True) + + print("\n=== Top 10 Longest Traces ===") + for i, trace in enumerate(sorted_traces[:10]): + print(f"\nTrace {trace['trace_id']}:") + print(f" Frames: {trace['start_frame']} - {trace['end_frame']} ({trace['duration_frames']} frames)") + print(f" Duration: {trace['duration_seconds']:.2f} seconds") + print(f" Appearances: {trace['total_appearances']}") + print(f" Avg Confidence: {trace['avg_confidence']:.3f}") + + # Pose Statistics + pose_stats = trace.get("pose_statistics", {}) + print(f" Pose Distribution: {pose_stats.get('distribution', {})}") + print(f" Dominant Angle: {pose_stats.get('dominant_angle', 'unknown')}") + + # Pose Transitions + transitions = trace.get("pose_transitions", []) + if transitions: + print(f" Pose Transitions: {len(transitions)} events") + for t in transitions[:3]: # 只显示前 3 个 + print(f" - Frame {t['frame']}: {t['from_angle']} → {t['to_angle']}") + + pose_stats = defaultdict(int) + for trace in traces.values(): + for pose in trace["pose_angles"]: + pose_stats[pose] += 1 + + print("\n=== Pose Distribution in Traces ===") + for pose, count in sorted(pose_stats.items(), key=lambda x: x[1], reverse=True): + print(f" {pose}: {count}") + + duration_distribution = defaultdict(int) + for trace in traces.values(): + d = trace["duration_frames"] + if d <= 30: + duration_distribution["short (<= 30 frames)"] += 1 + elif d <= 90: + duration_distribution["medium (31-90 frames)"] += 1 + else: + duration_distribution["long (> 90 frames)"] += 1 + + print("\n=== Trace Duration Distribution ===") + for duration, count in sorted(duration_distribution.items()): + print(f" {duration}: {count}") + + +def main(): + parser = argparse.ArgumentParser(description="Track faces across frames") + parser.add_argument("--face-json", required=True, help="Path to face.json") + parser.add_argument("--output", help="Output path (default: face_traced.json)") + parser.add_argument("--iou-threshold", type=float, default=0.3, help="IoU threshold") + parser.add_argument("--similarity-threshold", type=float, default=0.7, help="Embedding similarity threshold") + parser.add_argument("--distance-threshold", type=float, default=100.0, help="Distance threshold") + parser.add_argument("--no-embedding", action="store_true", help="Disable embedding matching") + parser.add_argument("--cuts-json", help="Path to cut.json for scene-cut-aware tracking") + parser.add_argument("--analyze-only", action="store_true", help="Only analyze, don't output") + args = parser.parse_args() + + # Load cut boundaries if provided + cut_boundaries = None + if args.cuts_json: + with open(args.cuts_json) as f: + cuts = json.load(f) + cut_boundaries = {s["start_frame"] for s in cuts.get("scenes", []) if s["start_frame"] > 0} + print(f" Cut boundaries loaded: {len(cut_boundaries)} cuts") + + print("=" * 60) + print("Face Tracker") + print("=" * 60) + + with open(args.face_json) as f: + face_data = json.load(f) + + print(f"\nInput: {args.face_json}") + print(f"Frames: {len(face_data.get('frames', {}))}") + + face_data = track_faces( + face_data, + iou_threshold=args.iou_threshold, + similarity_threshold=args.similarity_threshold, + distance_threshold=args.distance_threshold, + use_embedding=not args.no_embedding, + cut_boundaries=cut_boundaries, + ) + + analyze_traces(face_data) + + if not args.analyze_only: + output_path = args.output or args.face_json.replace(".json", "_traced.json") + with open(output_path, "w") as f: + json.dump(strip_embeddings_and_round(face_data), f, indent=2) + print(f"\n✅ Output saved to: {output_path}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/utils/qdrant_faces.py b/installer/build/MomentryCore/tools/script/utils/qdrant_faces.py new file mode 100644 index 00000000..4b03042e --- /dev/null +++ b/installer/build/MomentryCore/tools/script/utils/qdrant_faces.py @@ -0,0 +1,722 @@ +#!/opt/homebrew/bin/python3.11 +""" +Qdrant _faces and _seeds Collection Operations + +Functions for _faces: +- ensure_faces_collection(): Create _faces collection if not exists +- generate_point_id(): Generate consistent point ID +- push_face_embeddings_batch(): Batch push embeddings to Qdrant +- update_trace_ids(): Update trace_id after face tracking +- get_file_faces(): Get all face points for a file +- get_trace_representatives(): Get representative embeddings per trace + +Functions for _seeds: +- ensure_seeds_collection(): Create _seeds collection if not exists +- push_seed_embedding(): Push identity seed embedding +- get_seeds(): Get all seed points +- search_seeds(): Cosine search against seeds +- delete_seed(): Delete a seed point + +Collection Schema: +- _faces: 512D, Cosine, payload: {file_uuid, frame, trace_id, bbox, confidence, identity_id, identity_uuid, stranger_id} +- _seeds: 512D, Cosine, payload: {identity_id, identity_uuid, name, source, file_uuid, trace_id, tmdb_id, created_at} +""" + +import os +import json +import hashlib +import urllib.request +import urllib.error +from typing import Optional +from datetime import datetime + +QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333") +QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200") +FACES_COLLECTION = "_faces" +SEEDS_COLLECTION = "_seeds" +VECTOR_DIM = 512 +# Default 1000 (was 100): larger pages cut the number of scroll/set_payload HTTP +# round-trips ~10x on large files (B2). Still overridable via QDRANT_BATCH_SIZE. +BATCH_SIZE = int(os.environ.get("QDRANT_BATCH_SIZE", "1000")) + + +def qdrant_request(method: str, path: str, body: dict = None) -> dict: + """Make HTTP request to Qdrant""" + url = f"{QDRANT_URL}{path}" + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(url, data=data, method=method) + req.add_header("Content-Type", "application/json") + req.add_header("Api-Key", QDRANT_API_KEY) + try: + with urllib.request.urlopen(req) as resp: + return json.loads(resp.read()) + except urllib.error.HTTPError as e: + error_body = e.read().decode() + raise RuntimeError(f"Qdrant HTTP {e.code}: {error_body}") + + +def ensure_faces_collection() -> bool: + """Create _faces collection if not exists""" + url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}" + req = urllib.request.Request(url, method="GET") + req.add_header("Api-Key", QDRANT_API_KEY) + try: + urllib.request.urlopen(req) + return True # Collection exists + except urllib.error.HTTPError as e: + if e.code != 404: + raise RuntimeError(f"Qdrant check failed: {e.read().decode()}") + + # Create collection + body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}} + create_url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}" + data = json.dumps(body).encode() + req = urllib.request.Request(create_url, data=data, method="PUT") + req.add_header("Content-Type", "application/json") + req.add_header("Api-Key", QDRANT_API_KEY) + try: + urllib.request.urlopen(req) + print(f"[QDRANT] Created collection: {FACES_COLLECTION}") + return True + except urllib.error.HTTPError as e: + raise RuntimeError(f"Qdrant create collection failed: {e.read().decode()}") + + +def generate_point_id(file_uuid: str, frame: int, trace_id: int = 0) -> int: + """Generate consistent point ID from file_uuid + frame + trace_id""" + key = f"{file_uuid}_{frame}_{trace_id}" + return int(hashlib.md5(key.encode()).hexdigest()[:16], 16) + + +def push_face_embeddings_batch(file_uuid: str, faces: list, publisher=None) -> int: + """Batch push face embeddings to _faces collection + + Args: + file_uuid: Video file UUID + faces: List of {frame, trace_id, bbox, confidence, embedding} + publisher: RedisPublisher for progress reporting (optional) + + Returns: + Number of successfully pushed embeddings + + Raises: + RuntimeError: If Qdrant push fails + """ + if not faces: + return 0 + + ensure_faces_collection() + + total = len(faces) + pushed = 0 + + for i in range(0, total, BATCH_SIZE): + batch = faces[i : i + BATCH_SIZE] + + points = [] + for face in batch: + point_id = generate_point_id( + file_uuid, face["frame"], face.get("trace_id", 0) + ) + points.append( + { + "id": point_id, + "vector": face["embedding"], + "payload": { + "file_uuid": file_uuid, + "frame": face["frame"], + "trace_id": face.get("trace_id", 0), + "bbox": face["bbox"], + "confidence": face.get("confidence", 0.5), + "capture_quality": face.get("capture_quality", 0.0), + "identity_id": 0, + "identity_uuid": "", + "stranger_id": 0, + }, + } + ) + + body = {"points": points} + url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points?wait=true" + data = json.dumps(body).encode() + req = urllib.request.Request(url, data=data, method="PUT") + req.add_header("Content-Type", "application/json") + req.add_header("Api-Key", QDRANT_API_KEY) + + try: + urllib.request.urlopen(req) + pushed += len(batch) + except urllib.error.HTTPError as e: + error_body = e.read().decode() + raise RuntimeError( + f"Qdrant push failed (batch {i // BATCH_SIZE}): HTTP {e.code} - {error_body}" + ) + + if publisher: + pct = int((i + len(batch)) * 100 / total) + publisher.progress("face", i + len(batch), total, f"Qdrant push {pct}%") + + print(f"[QDRANT] Pushed {pushed} embeddings to {FACES_COLLECTION}") + return pushed + + +def update_trace_ids( + file_uuid: str, trace_mapping: dict, return_trace_ids: bool = False +): + """Update trace_id for all face points in a file + + Called by store_traced_faces.py after face tracking. + Uses Qdrant set_payload to avoid reading/writing vectors. + + Args: + file_uuid: Video file UUID + trace_mapping: {frame: {bbox_key: trace_id}} + bbox_key = f"{x}_{y}_{width}_{height}" + return_trace_ids: If True, also return the set of trace_ids seen during the + scroll. This lets the caller avoid a redundant full collection scan just + to count unique traces (B1 optimization for large files). + + Returns: + Number of updated points, or (updated_count, trace_id_set) if return_trace_ids. + """ + all_points = [] + offset = None + + while True: + body = { + "limit": BATCH_SIZE, + "with_payload": True, + "with_vector": False, + "filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}, + } + if offset: + body["offset"] = offset + + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/scroll", body + ) + batch = result.get("result", {}).get("points", []) + if not batch: + break + all_points.extend(batch) + offset = result.get("result", {}).get("next_page_offset") + if not offset: + break + + # Group point IDs by trace_id + trace_groups = {} + for point in all_points: + point_id = point["id"] + payload = point.get("payload", {}) + + frame = payload.get("frame") + + # Support two bbox formats: + # 1. Nested bbox field + # 2. Direct x, y, width, height fields + bbox = payload.get("bbox", {}) + if bbox: + # Format 1: has bbox field + x = bbox.get('x') + y = bbox.get('y') + width = bbox.get('width') + height = bbox.get('height') + else: + # Format 2: direct fields + x = payload.get('x') + y = payload.get('y') + width = payload.get('width') + height = payload.get('height') + + if x is None or y is None or width is None or height is None: + continue + + bbox_key = f"{x}_{y}_{width}_{height}" + + trace_id = trace_mapping.get(frame, {}).get(bbox_key) + if trace_id is None: + continue + + if trace_id not in trace_groups: + trace_groups[trace_id] = [] + trace_groups[trace_id].append(point_id) + + if not trace_groups: + return (0, set()) if return_trace_ids else 0 + + # Use set_payload per trace_id group (no vector write) + total = 0 + for trace_id, point_ids in trace_groups.items(): + for i in range(0, len(point_ids), BATCH_SIZE): + batch_ids = point_ids[i : i + BATCH_SIZE] + set_points_payload({"trace_id": trace_id}, batch_ids) + total += len(batch_ids) + + print(f"[QDRANT] Updated {total} trace_ids in {FACES_COLLECTION}") + if return_trace_ids: + return total, set(trace_groups.keys()) + return total + + +def set_points_payload(payload: dict, point_ids: list, wait: bool = True) -> dict: + """Set payload fields on specific Qdrant points (without touching vectors) + + Args: + payload: Dict of payload fields to set (e.g. {"trace_id": 5}) + point_ids: List of Qdrant point IDs + wait: Wait for operation to complete + + Returns: + Qdrant API response + """ + body = { + "payload": payload, + "points": point_ids, + "wait": wait, + } + return qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/payload", body + ) + + +def delete_file_faces(file_uuid: str) -> int: + """Delete all face points for a file + + Args: + file_uuid: Video file UUID + + Returns: + Number of deleted points + """ + body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}} + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/delete", body + ) + deleted = result.get("result", {}).get("operation_id", 0) + print(f"[QDRANT] Deleted faces for file_uuid={file_uuid}") + return deleted + + +def get_file_faces(file_uuid: str, with_vector: bool = False) -> list: + """Get all face points for a file + + Args: + file_uuid: Video file UUID + with_vector: Whether to include vector data (default False for payload-only) + + Returns: + List of points with payload (and vector if requested) + """ + all_points = [] + offset = None + + while True: + body = { + "limit": BATCH_SIZE, + "with_payload": True, + "with_vector": with_vector, + "filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}, + } + if offset: + body["offset"] = offset + + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/scroll", body + ) + batch = result.get("result", {}).get("points", []) + if not batch: + break + all_points.extend(batch) + offset = result.get("result", {}).get("next_page_offset") + if not offset: + break + + return all_points + + +def count_file_faces(file_uuid: str) -> int: + """Count face points for a file + + Args: + file_uuid: Video file UUID + + Returns: + Number of face points + """ + body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}} + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/count", body + ) + return result.get("result", {}).get("count", 0) + + +def get_trace_representatives(file_uuid: str) -> dict: + """Get representative embeddings per trace for multi-angle matching + + Args: + file_uuid: Video file UUID + + Returns: + {trace_id: [{'frame', 'embedding', 'bbox'}, ...]} + Each trace has 3 representatives: start, middle, end + """ + all_points = get_file_faces(file_uuid, with_vector=True) + + traces = {} + for point in all_points: + payload = point.get("payload", {}) + vector = point.get("vector", []) + trace_id = payload.get("trace_id", 0) + + if trace_id == 0: + continue + + if trace_id not in traces: + traces[trace_id] = [] + + traces[trace_id].append( + { + "frame": payload.get("frame"), + "embedding": vector, + "bbox": payload.get("bbox", {}), + "confidence": payload.get("confidence", 0.5), + } + ) + + for trace_id in traces: + points = traces[trace_id] + points.sort(key=lambda x: x["frame"]) + + if len(points) <= 3: + traces[trace_id] = points + else: + start = points[0] + end = points[-1] + middle_idx = len(points) // 2 + middle = points[middle_idx] + traces[trace_id] = [start, middle, end] + + return traces + + +def get_trace_centroid(file_uuid: str, trace_id: int) -> list: + """Get centroid embedding for a trace + + Args: + file_uuid: Video file UUID + trace_id: Trace ID + + Returns: + Centroid embedding (512D) + """ + reps = get_trace_representatives(file_uuid).get(trace_id, []) + + if not reps: + return [0.0] * VECTOR_DIM + + centroid = [0.0] * VECTOR_DIM + for rep in reps: + for i, v in enumerate(rep["embedding"]): + centroid[i] += v + + count = len(reps) + for i in range(VECTOR_DIM): + centroid[i] /= count + + return centroid + + +# ==================== _seeds Collection ==================== + + +def ensure_seeds_collection() -> bool: + """Create _seeds collection if not exists""" + url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}" + req = urllib.request.Request(url, method="GET") + req.add_header("Api-Key", QDRANT_API_KEY) + try: + urllib.request.urlopen(req) + return True # Collection exists + except urllib.error.HTTPError as e: + if e.code != 404: + raise RuntimeError(f"Qdrant check failed: {e.read().decode()}") + + body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}} + create_url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}" + data = json.dumps(body).encode() + req = urllib.request.Request(create_url, data=data, method="PUT") + req.add_header("Content-Type", "application/json") + req.add_header("Api-Key", QDRANT_API_KEY) + try: + urllib.request.urlopen(req) + print(f"[QDRANT] Created collection: {SEEDS_COLLECTION}") + return True + except urllib.error.HTTPError as e: + raise RuntimeError(f"Qdrant create collection failed: {e.read().decode()}") + + +def push_seed_embedding( + identity_id: int, + identity_uuid: str, + name: str, + embedding: list, + source: str = "tmdb", + file_uuid: str = None, + trace_id: int = None, + tmdb_id: int = None, +) -> bool: + """Push identity seed embedding to _seeds collection + + Args: + identity_id: PG identity.id + identity_uuid: Identity UUID + name: Identity name + embedding: 512D embedding + source: 'tmdb' | 'manual' | 'propagation' + file_uuid: File UUID (for manual/propagation seeds) + trace_id: Trace ID (for propagation seeds) + tmdb_id: TMDb ID (for TMDb seeds) + + Returns: + True if successful + + Raises: + RuntimeError: If Qdrant push fails + """ + ensure_seeds_collection() + + payload = { + "identity_id": identity_id, + "identity_uuid": identity_uuid, + "name": name, + "source": source, + "created_at": datetime.now().isoformat(), + } + + if file_uuid: + payload["file_uuid"] = file_uuid + if trace_id: + payload["trace_id"] = trace_id + if tmdb_id: + payload["tmdb_id"] = tmdb_id + + body = { + "points": [ + { + "id": identity_id, # Use identity_id as point_id + "vector": embedding, + "payload": payload, + } + ] + } + + url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}/points?wait=true" + data = json.dumps(body).encode() + req = urllib.request.Request(url, data=data, method="PUT") + req.add_header("Content-Type", "application/json") + req.add_header("Api-Key", QDRANT_API_KEY) + + try: + urllib.request.urlopen(req) + print(f"[QDRANT] Pushed seed: {name} (id={identity_id}, source={source})") + return True + except urllib.error.HTTPError as e: + error_body = e.read().decode() + raise RuntimeError(f"Qdrant seed push failed: HTTP {e.code} - {error_body}") + + +def get_seeds(source: str = None, file_uuid: str = None) -> list: + """Get all seed points + + Args: + source: Filter by source ('tmdb', 'manual', 'propagation'), or None for all + file_uuid: Filter by file_uuid, or None for all + + Returns: + List of seed points with payload and vector + """ + ensure_seeds_collection() + + all_points = [] + offset = None + + while True: + body = { + "limit": BATCH_SIZE, + "with_payload": True, + "with_vector": True, + } + + filters = [] + if source: + filters.append({"key": "source", "match": {"value": source}}) + if file_uuid: + filters.append({"key": "file_uuid", "match": {"value": file_uuid}}) + + if filters: + body["filter"] = {"must": filters} + + if offset: + body["offset"] = offset + + result = qdrant_request( + "POST", f"/collections/{SEEDS_COLLECTION}/points/scroll", body + ) + batch = result.get("result", {}).get("points", []) + if not batch: + break + all_points.extend(batch) + offset = result.get("result", {}).get("next_page_offset") + if not offset: + break + + return all_points + + +def search_seeds( + query_embedding: list, limit: int = 10, threshold: float = 0.0 +) -> list: + """Cosine search against seeds + + Args: + query_embedding: 512D query vector + limit: Max results + threshold: Minimum score threshold + + Returns: + List of {identity_id, identity_uuid, name, source, score} + """ + ensure_seeds_collection() + + body = { + "vector": query_embedding, + "limit": limit, + "with_payload": True, + } + + result = qdrant_request( + "POST", f"/collections/{SEEDS_COLLECTION}/points/search", body + ) + points = result.get("result", []) + + results = [] + for point in points: + score = point.get("score", 0) + if score < threshold: + continue + + payload = point.get("payload", {}) + results.append( + { + "identity_id": payload.get("identity_id"), + "identity_uuid": payload.get("identity_uuid"), + "name": payload.get("name"), + "source": payload.get("source"), + "score": score, + } + ) + + return results + + +def delete_seed(identity_id: int) -> bool: + """Delete a seed point + + Args: + identity_id: Identity ID (used as point_id) + + Returns: + True if successful + """ + body = {"points": [identity_id]} + + result = qdrant_request( + "POST", f"/collections/{SEEDS_COLLECTION}/points/delete?wait=true", body + ) + print(f"[QDRANT] Deleted seed: identity_id={identity_id}") + return result.get("result", {}).get("status") == "completed" + + +def count_seeds(source: str = None) -> int: + """Count seed points + + Args: + source: Filter by source, or None for all + + Returns: + Number of seed points + """ + ensure_seeds_collection() + + body = {} + if source: + body["filter"] = {"must": [{"key": "source", "match": {"value": source}}]} + + result = qdrant_request( + "POST", f"/collections/{SEEDS_COLLECTION}/points/count", body + ) + return result.get("result", {}).get("count", 0) + + +def update_identity_in_faces( + file_uuid: str, trace_id: int, identity_id: int, identity_uuid: str +) -> int: + """Update identity_id/identity_uuid for all face points with trace_id + + Called after identity binding confirmation. + Uses Qdrant set_payload to avoid reading/writing vectors. + + Args: + file_uuid: Video file UUID + trace_id: Trace ID + identity_id: Identity ID + identity_uuid: Identity UUID + + Returns: + Number of updated points + """ + all_points = [] + offset = None + + while True: + body = { + "limit": BATCH_SIZE, + "with_payload": True, + "with_vector": False, + "filter": { + "must": [ + {"key": "file_uuid", "match": {"value": file_uuid}}, + {"key": "trace_id", "match": {"value": trace_id}}, + ] + }, + } + if offset: + body["offset"] = offset + + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/scroll", body + ) + batch = result.get("result", {}).get("points", []) + if not batch: + break + all_points.extend(batch) + offset = result.get("result", {}).get("next_page_offset") + if not offset: + break + + if not all_points: + return 0 + + point_ids = [point["id"] for point in all_points] + + # Use set_payload (no vector write) + for i in range(0, len(point_ids), BATCH_SIZE): + batch_ids = point_ids[i : i + BATCH_SIZE] + set_points_payload( + {"identity_id": identity_id, "identity_uuid": identity_uuid}, batch_ids + ) + + print( + f"[QDRANT] Updated {len(point_ids)} face points with identity_id={identity_id}" + ) + return len(point_ids) diff --git a/installer/build/MomentryCore/tools/script/vlm/appearance_processor_v2.py b/installer/build/MomentryCore/tools/script/vlm/appearance_processor_v2.py new file mode 100644 index 00000000..ef6d87fe --- /dev/null +++ b/installer/build/MomentryCore/tools/script/vlm/appearance_processor_v2.py @@ -0,0 +1,164 @@ +#!/opt/homebrew/bin/python3.11 +""" +Appearance Expansion Processor V2 + +Calls swift_appearance_expansion which: +1. Reads pose.json (from pose expansion) +2. Expands appearance detection from pose frames +3. Stops when 3 consecutive frames have HSV similarity < 0.5 +4. Outputs at 8Hz sampling (floor(fps/8)) + +Flow: + face_processor.py → face.json + store_traced_faces.py → face_traced.json (with trace_id) + pose_processor.py → pose.json + appearance_processor.py → appearance.json (this script) +""" + +import sys +import os +import json +import argparse +import subprocess +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +SWIFT_BIN = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "release", "swift_appearance_expansion") +SWIFT_BIN_DEBUG = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "debug", "swift_appearance_expansion") + +OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", os.path.expanduser("~/momentry/output")) + + +def process_appearance( + video_path: str, + output_path: str, + uuid: str = "", + publisher: RedisPublisher = None, +) -> dict: + """Process appearance expansion from pose frames. + + Args: + video_path: Path to video file + output_path: Path to output appearance.json + uuid: File UUID for logging + publisher: Redis publisher for progress updates + """ + # Check if appearance.json already exists + if os.path.exists(output_path): + with open(output_path) as f: + data = json.load(f) + frame_count = len(data.get("frames", [])) + print(f"[Appearance] Output exists: {output_path} ({frame_count} frames)", file=sys.stderr) + if publisher: + publisher.progress("appearance", 100, 100, f"{frame_count} frames (exists)") + return data + + # Determine file_uuid from output_path + file_uuid = os.path.basename(output_path).replace(".appearance.json", "") + + # Find pose.json + pose_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.pose.json") + + if not os.path.exists(pose_path): + print(f"[Appearance] ERROR: pose.json not found for {file_uuid}", file=sys.stderr) + # Return empty result + empty_result = {"frame_count": 0, "fps": 0.0, "frames": []} + with open(output_path, "w") as f: + json.dump(empty_result, f) + return empty_result + + # Build swift_appearance_expansion if needed + swift_bin = SWIFT_BIN if os.path.exists(SWIFT_BIN) else SWIFT_BIN_DEBUG + if not os.path.exists(swift_bin): + build_dir = os.path.join(SCRIPT_DIR, "swift_processors") + print(f"[Appearance] Building swift_appearance_expansion in {build_dir}...", file=sys.stderr) + result = subprocess.run( + ["swift", "build", "-c", "release", "--product", "swift_appearance_expansion"], + cwd=build_dir, capture_output=True, text=True + ) + if result.returncode != 0: + print(f"[Appearance] Build failed: {result.stderr}", file=sys.stderr) + raise RuntimeError("Failed to build swift_appearance_expansion") + swift_bin = SWIFT_BIN + + # Run swift_appearance_expansion + cmd = [ + swift_bin, + video_path, + pose_path, + output_path, + ] + if uuid: + cmd.extend(["--uuid", uuid]) + + print(f"[Appearance] Running: {' '.join(cmd)}", file=sys.stderr) + + t0 = time.time() + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + + # Monitor progress + last_progress = "" + while proc.poll() is None: + time.sleep(5) + # Read stderr for progress + try: + import select + if select.select([proc.stderr], [], [], 0)[0]: + line = proc.stderr.readline().strip() + if line and line != last_progress: + last_progress = line + print(f"[Appearance] {line}", file=sys.stderr) + if publisher and "frames" in line: + publisher.progress("appearance", 50, 100, line) + except Exception: + pass + + # Read remaining output + stdout, stderr = proc.communicate() + if stdout: + print(stdout, file=sys.stderr) + if stderr: + print(stderr, file=sys.stderr) + + elapsed = time.time() - t0 + + if proc.returncode != 0: + print(f"[Appearance] ERROR: swift_appearance_expansion exited with code {proc.returncode}", file=sys.stderr) + if publisher: + publisher.error("appearance", f"Process failed with code {proc.returncode}") + raise RuntimeError(f"swift_appearance_expansion failed: {proc.returncode}") + + # Load result + if not os.path.exists(output_path): + print(f"[Appearance] ERROR: Output file not created: {output_path}", file=sys.stderr) + raise RuntimeError("Appearance output not created") + + with open(output_path) as f: + result = json.load(f) + + frame_count = len(result.get("frames", [])) + print(f"[Appearance] Done: {frame_count} frames in {elapsed:.1f}s", file=sys.stderr) + + if publisher: + publisher.progress("appearance", 100, 100, f"{frame_count} frames") + publisher.complete("appearance", f"{frame_count} frames") + + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Appearance Expansion Processor") + parser.add_argument("video_path", help="Video file path") + parser.add_argument("output_path", help="Output appearance.json path") + parser.add_argument("--uuid", "-u", default="", help="File UUID for logging") + args = parser.parse_args() + + publisher = RedisPublisher(args.uuid) if args.uuid else None + if publisher: + publisher.info("appearance", "APPEARANCE_START") + + result = process_appearance(args.video_path, args.output_path, args.uuid, publisher) + print(f"Appearance: {len(result.get('frames', []))} frames with appearance") \ No newline at end of file diff --git a/installer/build/MomentryCore/tools/script/vlm/tkg_builder.py b/installer/build/MomentryCore/tools/script/vlm/tkg_builder.py new file mode 100644 index 00000000..06750b4b --- /dev/null +++ b/installer/build/MomentryCore/tools/script/vlm/tkg_builder.py @@ -0,0 +1,1046 @@ +#!/opt/homebrew/bin/python3.11 +""" +TKG Builder - Unified Temporal Knowledge Graph Builder (V4.0 - Qdrant) + +Builds graph nodes and edges from all pipeline outputs: +- Face tracks (from Qdrant _faces collection with trace_id) +- Body tracks (pose.json + Level 1 appearance features) +- Detected objects (yolo.json) +- Speaker segments (asrx.json) +- Hand tracks (hand.json) [optional] + +Node Types (V2.0 - intuitive naming): + NODES: + (face_track) - face tracking across frames + (body_track) - body appearance with Level 1 features + (detected_object) - YOLO detected objects + (speaker_segment) - speaker segments + (hand_track) - hand state tracking [optional] + EDGES: + (face_track) -[:CO_OCCURS_WITH]-> (detected_object) -- same frame + (face_track) -[:SPEAKS_AS]-> (speaker_segment) -- temporal overlap + (face_track) -[:HAS_BODY]-> (body_track) -- spatial proximity + (body_track) -[:HAS_HAND]-> (hand_track) -- wrist position + +Usage: + python tkg_builder.py --file-uuid [--schema ] [--video ] +""" + +import sys +import os +import json +import argparse +import psycopg2 +import psycopg2.extras +import cv2 + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils")) + +try: + from utils.feature_extractor import HierarchicalFeatureExtractor + from utils.proportion_calculator import calculate_proportions, get_head_region +except ImportError: + print("[TKG] Warning: Level 1 feature extraction unavailable") + HierarchicalFeatureExtractor = None + calculate_proportions = None + get_head_region = None + +try: + from qdrant_faces import get_file_faces +except ImportError: + print("[TKG] Warning: Qdrant faces module unavailable") + get_file_faces = None + +DB_URL = os.environ.get("DATABASE_URL", "postgresql://accusys@localhost:5432/momentry") +SCHEMA = os.environ.get("DATABASE_SCHEMA", "public") +OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", os.path.expanduser("~/momentry/output")) + + +def get_conn(): + return psycopg2.connect(DB_URL) + + +def ensure_node(cur, schema, file_uuid, node_type, external_id, label="", properties=None): + """Insert or get graph node""" + cur.execute( + f""" + INSERT INTO {schema}.tkg_nodes (node_type, external_id, file_uuid, label, properties) + VALUES (%s, %s, %s, %s, %s::jsonb) + ON CONFLICT (file_uuid, node_type, external_id) + DO UPDATE SET properties = COALESCE(EXCLUDED.properties, tkg_nodes.properties), + label = COALESCE(NULLIF(EXCLUDED.label, ''), tkg_nodes.label) + RETURNING id + """, + (node_type, str(external_id), file_uuid, label, json.dumps(properties or {})), + ) + row = cur.fetchone() + return row[0] + + +def ensure_edge(cur, schema, file_uuid, edge_type, source_id, target_id, properties=None): + """Insert graph edge""" + cur.execute( + f""" + INSERT INTO {schema}.tkg_edges (edge_type, source_node_id, target_node_id, file_uuid, properties) + VALUES (%s, %s, %s, %s, %s::jsonb) + ON CONFLICT (file_uuid, edge_type, source_node_id, target_node_id) + DO UPDATE SET properties = COALESCE(EXCLUDED.properties, tkg_edges.properties) + """, + (edge_type, source_id, target_id, file_uuid, json.dumps(properties or {})), + ) + + +def build_face_track_nodes(cur, schema, file_uuid): + """Create graph nodes for each face track (Qdrant version)""" + print("[TKG] Building face_track nodes...") + + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + # Get all faces from Qdrant + faces = get_file_faces(file_uuid, with_vector=False) + + # Filter and group by trace_id + traces = {} + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + bbox = payload.get('bbox', {}) + + if trace_id is None or frame is None: + continue + + if trace_id not in traces: + traces[trace_id] = { + 'frames': [], + 'bboxes': [] + } + + traces[trace_id]['frames'].append(frame) + traces[trace_id]['bboxes'].append(bbox) + + # Create nodes + count = 0 + for trace_id, data in sorted(traces.items()): + frames = data['frames'] + bboxes = data['bboxes'] + + frame_count = len(frames) + start_f = min(frames) + end_f = max(frames) + + # Calculate average bbox + if bboxes: + avg_x = sum(b.get('x', 0) for b in bboxes) / len(bboxes) + avg_y = sum(b.get('y', 0) for b in bboxes) / len(bboxes) + avg_w = sum(b.get('width', 0) for b in bboxes) / len(bboxes) + avg_h = sum(b.get('height', 0) for b in bboxes) / len(bboxes) + else: + avg_x = avg_y = avg_w = avg_h = 0 + + label = f"Face Track {trace_id}" + props = { + "frame_count": frame_count, + "start_frame": start_f, + "end_frame": end_f, + "avg_bbox": { + "x": round(avg_x, 1), + "y": round(avg_y, 1), + "width": round(avg_w, 1), + "height": round(avg_h, 1) + }, + } + ensure_node(cur, schema, file_uuid, "face_track", f"face_track_{trace_id}", label, props) + count += 1 + + print(f"[TKG] {count} face_track nodes created") + return count + except Exception as e: + print(f"[TKG] Error building face_track nodes: {e}") + import traceback + traceback.print_exc() + return 0 + + +def load_json_safe(path): + """Load JSON even if in-progress (truncated tail)""" + if not os.path.exists(path): + return None + try: + with open(path) as f: + return json.load(f) + except json.JSONDecodeError: + # Try to recover by truncating to last valid frame + print(f"[TKG] Warning: {path} is in-progress, loading partial data") + with open(path) as f: + content = f.read() + # Find last valid "frame" entry and truncate + last_valid = content.rfind('"}') + if last_valid > 0: + try: + return json.loads(content[:last_valid+2] + "\n}}") + except json.JSONDecodeError: + pass + return None + + +def build_detected_object_nodes(cur, schema, file_uuid): + """Create graph nodes for each YOLO detected object class from yolo.json""" + yolo_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.yolo.json") + yolo = load_json_safe(yolo_path) + if yolo is None: + print(f"[TKG] yolo.json not available, skipping detected_object nodes") + return 0 + + frames = yolo.get("frames", {}) + class_counts = {} + for fdata in frames.values(): + detections = fdata.get("detections", fdata.get("objects", [])) + for det in detections: + cls = det.get("class_name", "unknown") + class_counts[cls] = class_counts.get(cls, 0) + 1 + + count = 0 + for cls, cnt in sorted(class_counts.items()): + ensure_node( + cur, schema, file_uuid, "detected_object", + cls, cls, + {"total_detections": cnt}, + ) + count += 1 + print(f"[TKG] {count} detected_object nodes created") + return count + + +def build_speaker_segment_nodes(cur, schema, file_uuid): + """Create graph nodes for each speaker segment from asrx.json""" + asrx_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.asrx.json") + if not os.path.exists(asrx_path): + print(f"[TKG] asrx.json not found, skipping speaker_segment nodes") + return 0 + + with open(asrx_path) as f: + asrx = json.load(f) + + count = 0 + stats = asrx.get("speaker_stats", {}) + for sid, sinfo in stats.items(): + cnt = sinfo.get("count", 0) + ensure_node( + cur, schema, file_uuid, "speaker_segment", + sid.lower().replace("speaker_", "speaker_"), sid, + {"segment_count": cnt}, + ) + count += 1 + print(f"[TKG] {count} speaker_segment nodes created") + return count + + +def build_co_occurrence_edges(cur, schema, file_uuid): + """Build CO_OCCURS_WITH edges: face_track ↔ detected_object in same frame""" + print("[TKG] Building co-occurrence edges (face-object within same frame)...") + + yolo_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.yolo.json") + yolo = load_json_safe(yolo_path) + if yolo is None: + print(f"[TKG] yolo.json not available, skipping co-occurrence") + return 0 + + yolo_frames = yolo.get("frames", {}) + + # Get face detections from Qdrant + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + faces = get_file_faces(file_uuid, with_vector=False) + except Exception as e: + print(f"[TKG] Error fetching faces from Qdrant: {e}") + return 0 + + # Filter faces with trace_id + face_rows = [] + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + bbox = payload.get('bbox', {}) + + if trace_id is None or frame is None: + continue + + face_rows.append(( + trace_id, + frame, + bbox.get('x', 0), + bbox.get('y', 0), + bbox.get('width', 0), + bbox.get('height', 0) + )) + + print(f"[TKG] Checking {len(face_rows)} face detections against YOLO frames...") + + # Get or create frame nodes cache + frame_node_cache = {} + + edge_count = 0 + for tid, frame_num, fx, fy, fw, fh in face_rows: + frame_str = str(frame_num) + yolo_frame = yolo_frames.get(frame_str) + if not yolo_frame: + continue + + detections = yolo_frame.get("detections", yolo_frame.get("objects", [])) + if not detections: + continue + + # Get face trace node + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='face_track' AND external_id=%s", + (file_uuid, f"face_track_{tid}"), + ) + ft_row = cur.fetchone() + if not ft_row: + continue + face_node_id = ft_row[0] + + for det in detections: + cls = det.get("class_name", "unknown") + confidence = det.get("confidence", 0) + + # Get object node + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='detected_object' AND external_id=%s", + (file_uuid, cls), + ) + obj_row = cur.fetchone() + if not obj_row: + continue + obj_node_id = obj_row[0] + + # Compute spatial distance (center-to-center) + fc_x = fx + fw / 2 + fc_y = fy + fh / 2 + + od = det + od_x = od.get("x1", 0) + (od.get("x2", 0) - od.get("x1", 0)) / 2 + od_y = od.get("y1", 0) + (od.get("y2", 0) - od.get("y1", 0)) / 2 + distance = ((fc_x - od_x) ** 2 + (fc_y - od_y) ** 2) ** 0.5 + + edge_props = { + "frame": frame_num, + "distance_px": round(distance, 1), + "object_confidence": confidence, + "face_bbox": {"x": fx, "y": fy, "width": fw, "height": fh}, + "object_bbox": { + "x1": od.get("x1"), "y1": od.get("y1"), + "x2": od.get("x2"), "y2": od.get("y2"), + }, + } + + try: + ensure_edge( + cur, schema, file_uuid, + "CO_OCCURS_WITH", + face_node_id, obj_node_id, + edge_props, + ) + edge_count += 1 + except Exception as e: + conn = cur.connection + conn.rollback() + continue + + print(f"[TKG] {edge_count} co-occurrence edges created") + return edge_count + + +def build_speaker_face_edges(cur, schema, file_uuid): + """Build SPEAKS_AS edges: face_track ↔ speaker_segment via temporal overlap""" + asrx_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.asrx.json") + if not os.path.exists(asrx_path): + print(f"[TKG] asrx.json not found, skipping speaker edges") + return 0 + + with open(asrx_path) as f: + asrx = json.load(f) + + segments = asrx.get("segments", []) + if not segments: + print("[TKG] No speaker segments found") + return 0 + + # Get face trace nodes with their time spans from Qdrant + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + faces = get_file_faces(file_uuid, with_vector=False) + except Exception as e: + print(f"[TKG] Error fetching faces from Qdrant: {e}") + return 0 + + # Group by trace_id + trace_frames = {} + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + + if trace_id is None or frame is None: + continue + + if trace_id not in trace_frames: + trace_frames[trace_id] = [] + trace_frames[trace_id].append(frame) + + # Calculate time spans + traces = [] + for trace_id, frames in sorted(trace_frames.items()): + traces.append((trace_id, min(frames), max(frames))) + + fps = segments[-1]["end_frame"] / segments[-1]["end_time"] if segments else 30.0 + + edge_count = 0 + for tid, sf, ef in traces: + # Get face trace node + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='face_track' AND external_id=%s", + (file_uuid, f"face_track_{tid}"), + ) + ft_row = cur.fetchone() + if not ft_row: + continue + face_node_id = ft_row[0] + + face_start_sec = sf / fps if fps > 0 else 0 + face_end_sec = ef / fps if fps > 0 else 0 + + for seg in segments: + speaker_id = seg.get("speaker_id", "") + seg_start = seg.get("start_time", 0) + seg_end = seg.get("end_time", 0) + + # Check temporal overlap + overlap_start = max(face_start_sec, seg_start) + overlap_end = min(face_end_sec, seg_end) + if overlap_start >= overlap_end: + continue + + overlap_dur = overlap_end - overlap_start + face_dur = face_end_sec - face_start_sec + overlap_ratio = overlap_dur / face_dur if face_dur > 0 else 0 + + if overlap_ratio < 0.3: # minimum 30% overlap + continue + + # Get speaker node + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='speaker_segment' AND external_id=%s", + (file_uuid, speaker_id), + ) + sp_row = cur.fetchone() + if not sp_row: + continue + speaker_node_id = sp_row[0] + + ensure_edge( + cur, schema, file_uuid, + "SPEAKS_AS", + face_node_id, speaker_node_id, + { + "overlap_ratio": round(overlap_ratio, 3), + "overlap_duration_s": round(overlap_dur, 1), + "face_time_range": f"{face_start_sec:.1f}-{face_end_sec:.1f}s", + "speaker_time_range": f"{seg_start:.1f}-{seg_end:.1f}s", + }, + ) + edge_count += 1 + + print(f"[TKG] {edge_count} speaker-face edges created") + return edge_count + + +def build_face_face_edges(cur, schema, file_uuid): + """Build CO_OCCURS_WITH edges: face_track ↔ face_track in same frame""" + print("[TKG] Building face-face co-occurrence edges...") + + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + faces = get_file_faces(file_uuid, with_vector=False) + except Exception as e: + print(f"[TKG] Error fetching faces from Qdrant: {e}") + return 0 + + # Group faces by frame + frame_faces = {} + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + bbox = payload.get('bbox', {}) + + if trace_id is None or frame is None: + continue + + if frame not in frame_faces: + frame_faces[frame] = [] + + frame_faces[frame].append({ + 'trace_id': trace_id, + 'x': bbox.get('x', 0), + 'y': bbox.get('y', 0), + 'width': bbox.get('width', 0), + 'height': bbox.get('height', 0) + }) + + # Find co-occurrences (same frame, different traces) + rows = [] + for frame, face_list in frame_faces.items(): + for i, face_a in enumerate(face_list): + for face_b in face_list[i+1:]: + if face_a['trace_id'] != face_b['trace_id']: + rows.append(( + face_a['trace_id'], + face_b['trace_id'], + frame, + face_a['x'], face_a['y'], face_a['width'], face_a['height'], + face_b['x'], face_b['y'], face_b['width'], face_b['height'] + )) + + if not rows: + print("[TKG] No face-face co-occurrences found") + return 0 + + # Deduplicate by pair (group all frames where same two traces co-occur) + pair_first = {} + pair_frames = {} + for tid_a, tid_b, frame, ax, ay, aw, ah, bx, by, bw, bh in rows: + key = (min(tid_a, tid_b), max(tid_a, tid_b)) + if key not in pair_first: + pair_first[key] = frame + pair_frames.setdefault(key, []).append(frame) + + edge_count = 0 + for (tid_a, tid_b), frames in pair_frames.items(): + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='face_track' AND external_id=%s", + (file_uuid, f"face_track_{tid_a}"), + ) + n_a = cur.fetchone() + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='face_track' AND external_id=%s", + (file_uuid, f"trace_{tid_b}"), + ) + n_b = cur.fetchone() + if not n_a or not n_b: + continue + + distance_px = ((frames[0] - frames[0]) ** 2) ** 0.5 # placeholder + ensure_edge( + cur, schema, file_uuid, + "CO_OCCURS_WITH", + n_a[0], n_b[0], + { + "first_frame": int(frames[0]), + "frame_count": len(frames), + }, + ) + edge_count += 1 + + print(f"[TKG] {edge_count} face-face co-occurrence edges created") + return edge_count + + +def extract_level1_features(video_path, pose_json_path): + """ + Extract Level 1 features for each person in each frame + + Args: + video_path: Path to video file + pose_json_path: Path to pose.json + + Returns: + List of (frame, person_index, bbox, level1_features) + """ + if HierarchicalFeatureExtractor is None: + print("[TKG] Level 1 feature extractor not available") + return [] + + if not os.path.exists(pose_json_path): + print(f"[TKG] pose.json not found: {pose_json_path}") + return [] + + with open(pose_json_path) as f: + pose_data = json.load(f) + + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + print(f"[TKG] Cannot open video: {video_path}") + return [] + + fps = pose_data.get("fps", 30.0) + extractor = HierarchicalFeatureExtractor() + + results = [] + + for pose_frame in pose_data.get("frames", []): + frame_num = pose_frame["frame"] + persons = pose_frame.get("persons", []) + + if not persons: + continue + + cap.set(cv2.CAP_PROP_POS_FRAMES, frame_num) + ret, frame = cap.read() + + if not ret: + continue + + for person_idx, person in enumerate(persons): + bbox = person.get("bbox", {}) + keypoints = person.get("keypoints", []) + + if bbox.get("width", 0) <= 0 or bbox.get("height", 0) <= 0: + continue + + proportions = calculate_proportions(keypoints, bbox) if calculate_proportions else {} + head_region = get_head_region(keypoints) if get_head_region else {} + level1 = extractor.extract_level1(frame, bbox, head_region) + + results.append({ + "frame": frame_num, + "timestamp": pose_frame.get("timestamp", frame_num / fps), + "person_index": person_idx, + "bbox": bbox, + "proportions": proportions, + "level1_features": level1, + }) + + cap.release() + print(f"[TKG] Extracted Level 1 features: {len(results)} frame-person pairs") + return results + + +def average_colors(color_lists): + """Average multiple color lists""" + if not color_lists: + return [] + + valid_colors = [c for c in color_lists if c] + if not valid_colors: + return [] + + first_colors = [c[0] if c else [0, 0, 0] for c in valid_colors] + avg = [sum(x) / len(x) for x in zip(*first_colors)] + return [round(x, 2) for x in avg] + + +def average_h_mean(items, region): + """Average H mean from Level 1 items""" + h_means = [] + for item in items: + l1 = item.get("level1_features", {}) + if region in l1 and "color" in l1[region]: + h_mean = l1[region]["color"].get("h_mean", 0) + if h_mean: + h_means.append(h_mean) + + return round(sum(h_means) / len(h_means), 2) if h_means else 0 + + +def average_bbox(bboxes): + """Average bbox across frames""" + if not bboxes: + return {} + + avg_x = sum(b.get("x", 0) for b in bboxes) / len(bboxes) + avg_y = sum(b.get("y", 0) for b in bboxes) / len(bboxes) + avg_w = sum(b.get("width", 0) for b in bboxes) / len(bboxes) + avg_h = sum(b.get("height", 0) for b in bboxes) / len(bboxes) + + return { + "x": round(avg_x, 1), + "y": round(avg_y, 1), + "width": round(avg_w, 1), + "height": round(avg_h, 1), + } + + +def build_body_track_nodes(cur, schema, file_uuid, video_path=None): + """Create body_track nodes with Level 1 appearance features""" + pose_json_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.pose.json") + + if not os.path.exists(pose_json_path): + print("[TKG] pose.json not found, skipping body_track nodes") + return 0 + + if video_path is None: + video_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.mp4") + + if not os.path.exists(video_path): + print(f"[TKG] Video not found: {video_path}, skipping body_track") + return 0 + + print("[TKG] Building body_track nodes with Level 1 features...") + + level1_data = extract_level1_features(video_path, pose_json_path) + if not level1_data: + print("[TKG] No Level 1 data extracted") + return 0 + + person_groups = {} + for item in level1_data: + person_idx = item["person_index"] + if person_idx not in person_groups: + person_groups[person_idx] = [] + person_groups[person_idx].append(item) + + count = 0 + for person_idx, items in person_groups.items(): + if not items: + continue + + body_colors = [] + head_colors = [] + upper_colors = [] + lower_colors = [] + frames = [] + bboxes = [] + + for item in items: + l1 = item.get("level1_features", {}) + frames.append(item["frame"]) + bboxes.append(item["bbox"]) + + if "body" in l1 and "color" in l1["body"]: + body_colors.append(l1["body"]["color"].get("dominant_colors", [])) + if "head_top" in l1 and "color" in l1["head_top"]: + head_colors.append(l1["head_top"]["color"].get("dominant_colors", [])) + if "upper_body" in l1 and "color" in l1["upper_body"]: + upper_colors.append(l1["upper_body"]["color"].get("dominant_colors", [])) + if "lower_body" in l1 and "color" in l1["lower_body"]: + lower_colors.append(l1["lower_body"]["color"].get("dominant_colors", [])) + + avg_body_color = average_colors(body_colors) + avg_head_color = average_colors(head_colors) + avg_upper_color = average_colors(upper_colors) + avg_lower_color = average_colors(lower_colors) + + avg_height_estimate = {} + avg_body_shape = {} + + for item in items: + props = item.get("proportions", {}) + if "height_estimate" in props and not avg_height_estimate: + avg_height_estimate = props["height_estimate"] + if "body_shape" in props and not avg_body_shape: + avg_body_shape = props["body_shape"] + + properties = { + "frame_count": len(frames), + "frames": frames, + "avg_bbox": average_bbox(bboxes), + "height_estimate": avg_height_estimate, + "body_shape": avg_body_shape, + "level1_features": { + "body": {"dominant_colors": avg_body_color, "h_mean": average_h_mean(items, "body")}, + "head_top": {"dominant_colors": avg_head_color, "h_mean": average_h_mean(items, "head_top")}, + "upper_body": {"dominant_colors": avg_upper_color, "h_mean": average_h_mean(items, "upper_body")}, + "lower_body": {"dominant_colors": avg_lower_color, "h_mean": average_h_mean(items, "lower_body")}, + }, + } + + external_id = f"body_track_{person_idx}" + label = f"Body Track {person_idx}" + ensure_node(cur, schema, file_uuid, "body_track", external_id, label, properties) + count += 1 + + print(f"[TKG] {count} body_track nodes created") + return count + + +def build_hand_track_nodes(cur, schema, file_uuid): + """Create hand_track nodes from hand.json (hand detection results)""" + hand_json_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.hand.json") + + if not os.path.exists(hand_json_path): + print("[TKG] hand.json not found, skipping hand_track nodes") + return 0 + + with open(hand_json_path) as f: + hand_data = json.load(f) + + frames = hand_data.get("frames", []) + if not frames: + print("[TKG] No hand frames found") + return 0 + + print("[TKG] Building hand_track nodes...") + + person_groups = {} + for frame_data in frames: + frame_num = frame_data.get("frame", 0) + persons = frame_data.get("persons", []) + + for person in persons: + person_id = person.get("person_id", 0) + hand_type = person.get("hand_type", "unknown") + gesture = person.get("gesture", "unknown") + hand_state = person.get("hand_state", "unknown") + + key = (person_id, hand_type) + if key not in person_groups: + person_groups[key] = { + "frames": [], + "gestures": [], + "hand_states": [], + } + + person_groups[key]["frames"].append(frame_num) + person_groups[key]["gestures"].append(gesture) + person_groups[key]["hand_states"].append(hand_state) + + count = 0 + for (person_id, hand_type), data in person_groups.items(): + frames_list = data["frames"] + gestures = data["gestures"] + hand_states = data["hand_states"] + + empty_count = sum(1 for s in hand_states if s == "empty") + holding_count = sum(1 for s in hand_states if s == "holding") + + external_id = f"hand_track_{person_id}_{hand_type}" + label = f"Hand Track {person_id} ({hand_type})" + + properties = { + "frame_count": len(frames_list), + "frames": frames_list, + "person_id": person_id, + "hand_type": hand_type, + "empty_count": empty_count, + "holding_count": holding_count, + "gesture_summary": { + "empty": empty_count, + "holding": holding_count, + }, + } + + ensure_node(cur, schema, file_uuid, "hand_track", external_id, label, properties) + count += 1 + + print(f"[TKG] {count} hand_track nodes created") + return count + + +def build_face_body_edges(cur, schema, file_uuid): + """Build HAS_BODY edges: face_track ↔ body_track via spatial proximity""" + print("[TKG] Building face-body edges...") + + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + faces = get_file_faces(file_uuid, with_vector=False) + except Exception as e: + print(f"[TKG] Error fetching faces from Qdrant: {e}") + return 0 + + # Extract face data + face_rows = [] + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + bbox = payload.get('bbox', {}) + + if trace_id is None or frame is None: + continue + + face_rows.append(( + trace_id, + frame, + bbox.get('x', 0), + bbox.get('y', 0), + bbox.get('width', 0), + bbox.get('height', 0) + )) + + pose_json_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.pose.json") + if not os.path.exists(pose_json_path): + print("[TKG] pose.json not found, skipping face-body edges") + return 0 + + with open(pose_json_path) as f: + pose_data = json.load(f) + + pose_frames = {f["frame"]: f.get("persons", []) for f in pose_data.get("frames", [])} + + edge_count = 0 + for trace_id, frame_num, fx, fy, fw, fh in face_rows: + pose_persons = pose_frames.get(frame_num, []) + + face_center_x = fx + fw / 2 + face_center_y = fy + fh / 2 + + best_person_idx = None + best_distance = float("inf") + + for person_idx, person in enumerate(pose_persons): + bbox = person.get("bbox", {}) + if bbox.get("width", 0) <= 0: + continue + + body_center_x = bbox.get("x", 0) + bbox.get("width", 0) / 2 + body_center_y = bbox.get("y", 0) + bbox.get("height", 0) / 2 + + distance = ((face_center_x - body_center_x) ** 2 + (face_center_y - body_center_y) ** 2) ** 0.5 + + if distance < best_distance: + best_distance = distance + best_person_idx = person_idx + + if best_person_idx is None or best_distance > 200: + continue + + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='face_track' AND external_id=%s", + (file_uuid, f"face_track_{trace_id}"), + ) + face_row = cur.fetchone() + + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='body_track' AND external_id=%s", + (file_uuid, f"body_track_{best_person_idx}"), + ) + body_row = cur.fetchone() + + if not face_row or not body_row: + continue + + ensure_edge( + cur, schema, file_uuid, + "HAS_BODY", + face_row[0], body_row[0], + {"avg_distance_px": round(best_distance, 1)}, + ) + edge_count += 1 + + print(f"[TKG] {edge_count} face-body edges created") + return edge_count + + +def build_body_hand_edges(cur, schema, file_uuid): + """Build HAS_HAND edges: body_track ↔ hand_track via person_id""" + print("[TKG] Building body-hand edges...") + + hand_json_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.hand.json") + if not os.path.exists(hand_json_path): + print("[TKG] hand.json not found, skipping body-hand edges") + return 0 + + with open(hand_json_path) as f: + hand_data = json.load(f) + + frames = hand_data.get("frames", []) + if not frames: + return 0 + + person_hand_map = {} + for frame_data in frames: + persons = frame_data.get("persons", []) + for person in persons: + person_id = person.get("person_id", 0) + hand_type = person.get("hand_type", "unknown") + key = (person_id, hand_type) + person_hand_map[key] = person_id + + edge_count = 0 + for (person_id, hand_type), _ in person_hand_map.items(): + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='body_track' AND external_id=%s", + (file_uuid, f"body_track_{person_id}"), + ) + body_row = cur.fetchone() + + cur.execute( + f"SELECT id FROM {schema}.tkg_nodes WHERE file_uuid=%s AND node_type='hand_track' AND external_id=%s", + (file_uuid, f"hand_track_{person_id}_{hand_type}"), + ) + hand_row = cur.fetchone() + + if not body_row or not hand_row: + continue + + ensure_edge( + cur, schema, file_uuid, + "HAS_HAND", + body_row[0], hand_row[0], + {"hand_type": hand_type}, + ) + edge_count += 1 + + print(f"[TKG] {edge_count} body-hand edges created") + return edge_count + + +def main(): + parser = argparse.ArgumentParser(description="Build Temporal Knowledge Graph") + parser.add_argument("--file-uuid", "-u", required=True, help="File UUID") + parser.add_argument("--schema", "-s", default=SCHEMA, help="Database schema") + parser.add_argument("--video", "-v", help="Video path (optional, auto-detected)") + parser.add_argument("--uuid", help="UUID for Redis tracking (accepted by executor)") + args = parser.parse_args() + + conn = get_conn() + cur = conn.cursor() + + video_path = args.video or os.path.join(OUTPUT_DIR, f"{args.file_uuid}.mp4") + + print(f"[TKG] Building graph for {args.file_uuid}...") + print(f"[TKG] Video: {video_path}") + + n1 = build_face_track_nodes(cur, args.schema, args.file_uuid) + n2 = build_body_track_nodes(cur, args.schema, args.file_uuid, video_path) + n3 = build_detected_object_nodes(cur, args.schema, args.file_uuid) + n4 = build_speaker_segment_nodes(cur, args.schema, args.file_uuid) + n5 = build_hand_track_nodes(cur, args.schema, args.file_uuid) + + e1 = build_co_occurrence_edges(cur, args.schema, args.file_uuid) + e2 = build_speaker_face_edges(cur, args.schema, args.file_uuid) + e3 = build_face_face_edges(cur, args.schema, args.file_uuid) + e4 = build_face_body_edges(cur, args.schema, args.file_uuid) + e5 = build_body_hand_edges(cur, args.schema, args.file_uuid) + + conn.commit() + cur.close() + conn.close() + + total_nodes = n1 + n2 + n3 + n4 + n5 + total_edges = e1 + e2 + e3 + e4 + e5 + + print(f"\n[TKG] Complete: {total_nodes} nodes, {total_edges} edges") + print(f" Face tracks: {n1}") + print(f" Body tracks: {n2}") + print(f" Detected objects: {n3}") + print(f" Speaker segments: {n4}") + print(f" Hand tracks: {n5}") + print(f" Co-occur edges: {e1}") + print(f" Speaker-face: {e2}") + print(f" Face-face: {e3}") + print(f" Face-body: {e4}") + print(f" Body-hand: {e5}") + + +if __name__ == "__main__": + main() diff --git a/installer/build/MomentryCore/uninstall.sh b/installer/build/MomentryCore/uninstall.sh new file mode 100755 index 00000000..a09afb9d --- /dev/null +++ b/installer/build/MomentryCore/uninstall.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Momentry Core 移除腳本 +set -e + +INSTALL_DIR="$HOME/Library/Application Support/MomentryCore" +LAUNCHD_DIR="$HOME/Library/LaunchAgents" + +echo ">>> 停止服務..." +launchctl bootout "gui/$(id -u)/com.momentry-core.server" 2>/dev/null || true +launchctl bootout "gui/$(id -u)/com.momentry-core.worker" 2>/dev/null || true + +echo ">>> 移除 launchd plists..." +rm -f "$LAUNCHD_DIR/com.momentry-core.server.plist" +rm -f "$LAUNCHD_DIR/com.momentry-core.worker.plist" + +echo ">>> 移除安裝目錄..." +rm -rf "$INSTALL_DIR" + +echo "" +echo "================================================" +echo " 移除完成!" +echo " 注意: 資料庫和外部服務資料未被刪除" +echo "================================================" diff --git a/installer/config/production.env.template b/installer/config/production.env.template new file mode 100644 index 00000000..d45906f8 --- /dev/null +++ b/installer/config/production.env.template @@ -0,0 +1,17 @@ +DATABASE_URL=postgres://accusys@localhost:5432/momentry +DATABASE_SCHEMA=public +REDIS_URL=redis://:accusys@localhost:6379 +MOMENTRY_REDIS_PREFIX=momentry: +MOMENTRY_SERVER_PORT=3002 +MOMENTRY_OUTPUT_DIR=$HOME/momentry/output +MOMENTRY_BACKUP_DIR=$HOME/momentry/backup +QDRANT_URL=http://127.0.0.1:6333 +MONGODB_URL=mongodb://localhost:27017 +MOMENTRY_LLM_VISION_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it +MOMENTRY_LLM_CHAT_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it +MOMENTRY_LLM_SUMMARY_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_SUMMARY_MODEL=gemma-4-12b-it +MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11 +RUST_LOG=info diff --git a/installer/install.sh b/installer/install.sh new file mode 100755 index 00000000..24d26b40 --- /dev/null +++ b/installer/install.sh @@ -0,0 +1,143 @@ +#!/bin/bash +# Momentry Core 安裝腳本 +set -e + +APP_NAME="MomentryCore" +INSTALL_DIR="$HOME/Library/Application Support/$APP_NAME" +LAUNCHD_DIR="$HOME/Library/LaunchAgents" +LOG_DIR="$INSTALL_DIR/logs" + +RED='\033[0;31m' +GREEN='\033[0;32m' +NC='\033[0m' + +echo "================================================" +echo " Momentry Core 安裝程式" +echo "================================================" + +# 1. 檢查依賴 +echo ">>> 檢查系統依賴..." +MISSING="" +check() { + if eval "$2" >/dev/null 2>&1; then + echo " [OK] $1" + else + echo " [FAIL] $1 - $3" + MISSING="$MISSING $1" + fi +} +check "PostgreSQL" "psql --version" "brew install postgresql" +check "Redis" "redis-cli ping" "brew install redis" +check "Qdrant" "curl -s --max-time 3 http://localhost:6333/ready | grep -q ok" "brew install qdrant" +check "MongoDB" "mongosh --version || mongo --version" "brew install mongosh" +check "Python 3.11" "python3.11 --version" "brew install python@3.11" +check "ffprobe" "ffprobe -version" "brew install ffmpeg" +check "MarkBaseServer" "curl -s --max-time 3 http://localhost:8080/v1/models | grep -q model" "安裝 MarkBaseEngine" + +if [ -n "$MISSING" ]; then + echo -e "\n${RED}缺少依賴:$MISSING${NC}" + echo "brew install postgresql redis mongosh ffmpeg python@3.11" + exit 1 +fi +echo -e "\n${GREEN}所有依賴已安裝${NC}" + +# 2. 建立目錄 +echo ">>> 建立目錄..." +mkdir -p "$INSTALL_DIR"/{bin,config,tools/script,tools/cli,logs} +SRC_DIR="$(cd "$(dirname "$0")" && pwd)" +cp -f "$SRC_DIR/bin/momentry" "$INSTALL_DIR/bin/" 2>/dev/null || echo " [!] momentry binary 需手動放置" +cp -f "$SRC_DIR/bin/pipeline_worker" "$INSTALL_DIR/bin/" 2>/dev/null || echo " [!] pipeline_worker 需手動放置" +chmod +x "$INSTALL_DIR/bin/"* 2>/dev/null || true +cp -rf "$SRC_DIR/config/"* "$INSTALL_DIR/config/" 2>/dev/null || true +cp -rf "$SRC_DIR/tools/"* "$INSTALL_DIR/tools/" 2>/dev/null || true +echo " -> $INSTALL_DIR" + +# 3. 產生 .env +ENV_FILE="$INSTALL_DIR/.env" +if [ ! -f "$ENV_FILE" ]; then + cat > "$ENV_FILE" << ENVEOF +DATABASE_URL=postgres://accusys@localhost:5432/momentry +DATABASE_SCHEMA=public +REDIS_URL=redis://:accusys@localhost:6379 +MOMENTRY_REDIS_PREFIX=momentry: +MOMENTRY_SERVER_PORT=3002 +MOMENTRY_OUTPUT_DIR=$HOME/momentry/output +QDRANT_URL=http://127.0.0.1:6333 +MONGODB_URL=mongodb://localhost:27017 +MOMENTRY_LLM_VISION_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it +MOMENTRY_LLM_CHAT_URL=http://127.0.0.1:8080/v1/chat/completions +MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it +MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11 +MOMENTRY_SCRIPTS_DIR=$INSTALL_DIR/tools/script +MOMENTRY_CLI_DIR=$INSTALL_DIR/tools/cli +RUST_LOG=info +ENVEOF + echo " [OK] 已產生 .env" +else + echo " [OK] .env 已存在" +fi + +# 4. 安裝 Launchd +echo ">>> 安裝 launchd services..." +cat > "$LAUNCHD_DIR/com.momentry-core.server.plist" << PLIST + + + + Labelcom.momentry-core.server + Program$INSTALL_DIR/bin/momentry + ProgramArguments + momentryserver + --host0.0.0.0 + --port3002 + + WorkingDirectory$INSTALL_DIR + EnvironmentVariables + DOTENV_PATH$ENV_FILE + + KeepAliveSuccessfulExit + RunAtLoad + StandardOutPath$LOG_DIR/server.log + StandardErrorPath$LOG_DIR/server.log + +PLIST + +cat > "$LAUNCHD_DIR/com.momentry-core.worker.plist" << PLIST + + + + Labelcom.momentry-core.worker + Program$INSTALL_DIR/bin/pipeline_worker + WorkingDirectory$INSTALL_DIR + EnvironmentVariables + DOTENV_PATH$ENV_FILE + + KeepAliveSuccessfulExit + RunAtLoad + StandardOutPath$LOG_DIR/worker.log + StandardErrorPath$LOG_DIR/worker.log + +PLIST +echo " [OK] server + worker plist" + +# 5. 啟動 +echo ">>> 啟動服務..." +launchctl bootout "gui/$(id -u)/com.momentry-core.server" 2>/dev/null || true +launchctl bootout "gui/$(id -u)/com.momentry-core.worker" 2>/dev/null || true +sleep 1 +launchctl bootstrap "gui/$(id -u)" "$LAUNCHD_DIR/com.momentry-core.server.plist" +launchctl bootstrap "gui/$(id -u)" "$LAUNCHD_DIR/com.momentry-core.worker.plist" +sleep 3 + +if curl -s --max-time 5 "http://localhost:3002/api/v1/health" >/dev/null 2>&1; then + echo -e "${GREEN}[OK] API server 啟動成功${NC}" +else + echo -e "${YELLOW}[!] 檢查日誌: $LOG_DIR/server.log${NC}" +fi + +echo "" +echo "================================================" +echo " 安裝完成!" +echo " 目錄: $INSTALL_DIR" +echo " API: http://localhost:3002" +echo "================================================" diff --git a/installer/uninstall.sh b/installer/uninstall.sh new file mode 100755 index 00000000..a09afb9d --- /dev/null +++ b/installer/uninstall.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Momentry Core 移除腳本 +set -e + +INSTALL_DIR="$HOME/Library/Application Support/MomentryCore" +LAUNCHD_DIR="$HOME/Library/LaunchAgents" + +echo ">>> 停止服務..." +launchctl bootout "gui/$(id -u)/com.momentry-core.server" 2>/dev/null || true +launchctl bootout "gui/$(id -u)/com.momentry-core.worker" 2>/dev/null || true + +echo ">>> 移除 launchd plists..." +rm -f "$LAUNCHD_DIR/com.momentry-core.server.plist" +rm -f "$LAUNCHD_DIR/com.momentry-core.worker.plist" + +echo ">>> 移除安裝目錄..." +rm -rf "$INSTALL_DIR" + +echo "" +echo "================================================" +echo " 移除完成!" +echo " 注意: 資料庫和外部服務資料未被刪除" +echo "================================================" diff --git a/momentry_runtime/plist/com.momentry.api.plist b/momentry_runtime/plist/com.momentry.api.plist index 7a327bee..b5a8044e 100644 --- a/momentry_runtime/plist/com.momentry.api.plist +++ b/momentry_runtime/plist/com.momentry.api.plist @@ -2,33 +2,30 @@ - Label - com.momentry.api - - UserName - accusys - - GroupName - staff - - WorkingDirectory - /Users/accusys/momentry_core - - ProgramArguments - - /Users/accusys/momentry_core/scripts/wrapper_production.sh - - - RunAtLoad - - - KeepAlive - - - StandardOutPath - /Users/accusys/momentry/log/momentry_api.log - - StandardErrorPath - /Users/accusys/momentry/log/momentry_api.error.log + EnvironmentVariables + + MOMENTRY_OUTPUT_DIR + /Users/accusys/momentry/output + + GroupName + staff + KeepAlive + + Label + com.momentry.api + ProgramArguments + + /Users/accusys/momentry_core/scripts/wrapper_production.sh + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/log/momentry_api.error.log + StandardOutPath + /Users/accusys/momentry/log/momentry_api.log + UserName + accusys + WorkingDirectory + /Users/accusys/momentry_core diff --git a/momentry_runtime/plist/com.momentry.qdrant.plist b/momentry_runtime/plist/com.momentry.qdrant.plist index 51fdafac..bbfe97de 100644 --- a/momentry_runtime/plist/com.momentry.qdrant.plist +++ b/momentry_runtime/plist/com.momentry.qdrant.plist @@ -2,45 +2,38 @@ - Label - com.momentry.qdrant - - UserName - accusys - - WorkingDirectory - /Users/accusys/momentry/var/qdrant/ - - ProgramArguments - - /Users/accusys/.cargo/bin/qdrant - - - EnvironmentVariables - - QDRANT__STORAGE__STORAGE_PATH - /Users/accusys/momentry/var/qdrant/ - - QDRANT__SERVICE__HOST - 0.0.0.0 - - QDRANT__SERVICE__HTTP_PORT - 6333 - - HOME - /Users/accusys - - QDRANT__SERVICE__API_KEY - Test3200Test3200Test3200 - - - RunAtLoad - - KeepAlive - - StandardOutPath - /Users/accusys/momentry/log/qdrant.log - StandardErrorPath - /opt/homebrew/var/log/qdrant.error.log + EnvironmentVariables + + HOME + /Users/accusys + QDRANT__LOG__LEVEL + WARN + QDRANT__SERVICE__API_KEY + Test3200Test3200Test3200 + QDRANT__SERVICE__HOST + 0.0.0.0 + QDRANT__SERVICE__HTTP_PORT + 6333 + QDRANT__STORAGE__STORAGE_PATH + /Users/accusys/momentry/var/qdrant/ + + KeepAlive + + Label + com.momentry.qdrant + ProgramArguments + + /Users/accusys/.cargo/bin/qdrant + + RunAtLoad + + StandardErrorPath + /opt/homebrew/var/log/qdrant.error.log + StandardOutPath + /Users/accusys/momentry/log/qdrant.log + UserName + accusys + WorkingDirectory + /Users/accusys/momentry/var/qdrant/ diff --git a/momentry_runtime/plist/com.momentry.redis.plist b/momentry_runtime/plist/com.momentry.redis.plist index 5cc8b14d..bb0808c4 100644 --- a/momentry_runtime/plist/com.momentry.redis.plist +++ b/momentry_runtime/plist/com.momentry.redis.plist @@ -2,40 +2,31 @@ - Label - com.momentry.redis - - UserName - accusys - - WorkingDirectory - /Users/accusys/momentry/var/redis - - ProgramArguments - - /opt/homebrew/opt/redis/bin/redis-server - --port - 6379 - --bind - 0.0.0.0 - --requirepass - accusys - --dir - /Users/accusys/momentry/var/redis - --logfile - /Users/accusys/momentry/log/redis.log - - - RunAtLoad - - - KeepAlive - - - StandardErrorPath - /Users/accusys/momentry/log/redis.error.log - - StandardOutPath - /Users/accusys/momentry/log/redis.log + KeepAlive + + Label + com.momentry.redis + ProgramArguments + + /opt/homebrew/opt/redis/bin/redis-server + --port + 6379 + --bind + 0.0.0.0 + --dir + /Users/accusys/momentry/var/redis + --logfile + /Users/accusys/momentry/log/redis.log + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/log/redis.error.log + StandardOutPath + /Users/accusys/momentry/log/redis.log + UserName + accusys + WorkingDirectory + /Users/accusys/momentry/var/redis diff --git a/scripts/swift_processors/swift_hand.swift b/scripts/swift_processors/swift_hand.swift index 232679a4..0900d070 100644 --- a/scripts/swift_processors/swift_hand.swift +++ b/scripts/swift_processors/swift_hand.swift @@ -49,7 +49,7 @@ struct SwiftHandProcessor: ParsableCommand { extract.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") extract.arguments = ["-y", "-v", "quiet", "-i", inputPath, "-vf", "select=not(mod(n\\,\(sampleInterval)))", - "-vsync", "vfr", "-q:v", "15", pattern] + "-fps_mode", "vfr", "-q:v", "15", pattern] try extract.run() extract.waitUntilExit() diff --git a/scripts/swift_processors/swift_ocr.swift b/scripts/swift_processors/swift_ocr.swift index b6269c9d..218d10dc 100644 --- a/scripts/swift_processors/swift_ocr.swift +++ b/scripts/swift_processors/swift_ocr.swift @@ -89,7 +89,7 @@ struct SwiftOCR: ParsableCommand { extractProc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") extractProc.arguments = ["-y", "-v", "quiet", "-i", inputPath, "-vf", scaleFilter, - "-vsync", "vfr", "-q:v", "15", framePattern] + "-fps_mode", "vfr", "-q:v", "15", framePattern] let startExtract = Date() try extractProc.run() extractProc.waitUntilExit() diff --git a/scripts/swift_processors/swift_pose.swift b/scripts/swift_processors/swift_pose.swift index afb9d7ef..7fd83241 100644 --- a/scripts/swift_processors/swift_pose.swift +++ b/scripts/swift_processors/swift_pose.swift @@ -63,7 +63,7 @@ struct SwiftPose: ParsableCommand { extract.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg") extract.arguments = ["-y", "-v", "quiet", "-i", inputPath, "-vf", "select=not(mod(n\\,\(sampleInterval)))", - "-vsync", "vfr", "-q:v", "15", pattern] + "-fps_mode", "vfr", "-q:v", "15", pattern] try extract.run() extract.waitUntilExit() } diff --git a/src/api/files.rs b/src/api/files.rs index 537e42fc..38669c25 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -1279,7 +1279,7 @@ struct ReScanRequest { processors: Option>, #[serde(default)] face_settings: Option, - #[serde(default)] + #[serde(default, alias = "autoPipeline")] auto_pipeline: Option, #[serde(default)] trigger_source: Option, diff --git a/src/api/profile.rs b/src/api/profile.rs index 3efaf3e6..f9010850 100644 --- a/src/api/profile.rs +++ b/src/api/profile.rs @@ -1346,6 +1346,7 @@ pub async fn get_face_groups_handler( Path(file_uuid): Path, Query(q): Query, ) -> Result, StatusCode> { + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let tkg_table = schema::table_name("tkg_nodes"); let tp_table = schema::table_name("trace_profiles"); let v_table = schema::table_name("videos"); @@ -1422,20 +1423,48 @@ pub async fn get_face_groups_handler( let include_trace_ids = q.include_trace_ids.unwrap_or(true); + // Load best_confidence per trace from face_traced.json + let mut trace_best_conf: std::collections::HashMap = std::collections::HashMap::new(); + let traced_path = format!("{}/{}.face_traced.json", output_dir.trim_end_matches('/'), file_uuid); + if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced) = serde_json::from_str::(&content) { + if let Some(traces) = traced.get("traces").and_then(|v| v.as_array()) { + for t in traces { + if let (Some(tid), Some(conf)) = ( + t.get("trace_id").and_then(|v| v.as_i64()), + t.get("best_confidence").or(t.get("avg_confidence")).and_then(|v| v.as_f64()), + ) { + trace_best_conf.insert(tid as i32, conf); + } + } + } + } + } + let face_groups: Vec = filtered_groups .into_iter() .enumerate() - .map(|(idx, (name, trace_ids))| FaceGroup { - group_id: (idx + 1) as i32, - name, - trace_count: trace_ids.len() as i32, - representative_trace: trace_ids.first().copied().unwrap_or(0), - trace_ids: if include_trace_ids { - Some(trace_ids) - } else { - None - }, - editable: true, + .map(|(idx, (name, trace_ids))| { + // Pick representative trace: highest best_confidence among group traces + let rep_trace = trace_ids.iter() + .filter_map(|tid| trace_best_conf.get(tid).map(|c| (tid, c))) + .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal)) + .map(|(tid, _)| *tid) + .or_else(|| trace_ids.first().copied()) + .unwrap_or(0); + + FaceGroup { + group_id: (idx + 1) as i32, + name, + trace_count: trace_ids.len() as i32, + representative_trace: rep_trace, + trace_ids: if include_trace_ids { + Some(trace_ids) + } else { + None + }, + editable: true, + } }) .collect(); @@ -1654,6 +1683,28 @@ pub async fn get_cluster_results_handler( map }; + // Load best_confidence per trace from face_traced.json (for representative selection) + let cluster_trace_conf: HashMap = { + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let mut map = HashMap::new(); + let traced_path = format!("{}/{}.face_traced.json", output_dir, file_uuid); + if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced) = serde_json::from_str::(&content) { + if let Some(traces) = traced.get("traces").and_then(|v| v.as_array()) { + for t in traces { + if let (Some(tid), Some(conf)) = ( + t.get("trace_id").and_then(|v| v.as_i64()), + t.get("best_confidence").or(t.get("avg_confidence")).and_then(|v| v.as_f64()), + ) { + map.insert(tid as i32, conf); + } + } + } + } + } + map + }; + // Build trace_id -> name mapping before consuming filtered_groups let trace_to_name: HashMap = filtered_groups .iter() @@ -1672,7 +1723,12 @@ pub async fn get_cluster_results_handler( cluster_id: group_id, name, trace_count: trace_ids.len() as i32, - representative_trace: trace_ids.first().copied().unwrap_or(0), + representative_trace: trace_ids.iter() + .filter_map(|tid| cluster_trace_conf.get(tid).map(|c| (tid, c))) + .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal)) + .map(|(tid, _)| *tid) + .or_else(|| trace_ids.first().copied()) + .unwrap_or(0), trace_ids, similarity, } diff --git a/src/core/chunk/rule1_ingest.rs b/src/core/chunk/rule1_ingest.rs index 5a38ec8e..e6e949d4 100644 --- a/src/core/chunk/rule1_ingest.rs +++ b/src/core/chunk/rule1_ingest.rs @@ -150,10 +150,10 @@ async fn fetch_asr_segments( ) -> Result> { let query = format!( r#" - SELECT + SELECT start_frame, end_frame, start_time, end_time, data FROM {} - WHERE file_uuid = $1 AND processor_type = 'asrx' + WHERE file_uuid = $1 AND processor_type IN ('asrx', 'asr', 'asr_asrx') ORDER BY start_frame "#, table diff --git a/src/core/db/postgres_db.rs b/src/core/db/postgres_db.rs index ee56d568..30bc0208 100644 --- a/src/core/db/postgres_db.rs +++ b/src/core/db/postgres_db.rs @@ -550,6 +550,7 @@ pub enum PipelineType { pub enum ProcessorType { Cut, Asr, + AsrAsrx, Ocr, Face, Pose, @@ -588,11 +589,14 @@ impl ProcessorType { match self { ProcessorType::Cut => "cut", ProcessorType::Asr => "asr", + // Unified ASR+diarization processor writes {uuid}.asrx.json and is + // exposed to the UI/queue under the legacy "asrx" name. + ProcessorType::AsrAsrx => "asrx", ProcessorType::Ocr => "ocr", ProcessorType::Face => "face", ProcessorType::Pose => "pose", ProcessorType::Hand => "hand", - ProcessorType::Asrx => "asrx", + ProcessorType::Asrx => "asrx_legacy", ProcessorType::Scene => "scene_vlm", ProcessorType::Appearance => "appearance", ProcessorType::FaceCluster => "face_cluster", @@ -605,11 +609,12 @@ impl ProcessorType { match s { "cut" => Some(ProcessorType::Cut), "asr" => Some(ProcessorType::Asr), + "asrx" | "asr_asrx" => Some(ProcessorType::AsrAsrx), + "asrx_legacy" => Some(ProcessorType::Asrx), "ocr" => Some(ProcessorType::Ocr), "face" => Some(ProcessorType::Face), "pose" => Some(ProcessorType::Pose), "hand" => Some(ProcessorType::Hand), - "asrx" => Some(ProcessorType::Asrx), "scene" => Some(ProcessorType::Scene), "scene_vlm" => Some(ProcessorType::Scene), // Alias for scene "appearance" => Some(ProcessorType::Appearance), @@ -624,6 +629,7 @@ impl ProcessorType { match self { ProcessorType::Cut => 0.5, ProcessorType::Asr => 0.5, + ProcessorType::AsrAsrx => 1.2, ProcessorType::Ocr => 0.8, ProcessorType::Face => 0.6, ProcessorType::Pose => 0.4, @@ -648,6 +654,7 @@ impl ProcessorType { match self { ProcessorType::Cut => 512, ProcessorType::Asr => 1024, + ProcessorType::AsrAsrx => 2048, ProcessorType::Ocr => 1024, ProcessorType::Face => 1536, ProcessorType::Pose => 1024, @@ -665,6 +672,7 @@ impl ProcessorType { match self { ProcessorType::Cut => None, ProcessorType::Asr => Some("whisper-small"), + ProcessorType::AsrAsrx => Some("whisper-small-mlx"), ProcessorType::Ocr => Some("paddleocr"), ProcessorType::Face => Some("insightface/buffalo_l"), ProcessorType::Pose => Some("mediapipe/pose"), @@ -680,6 +688,7 @@ impl ProcessorType { pub fn dependencies(&self) -> Vec { match self { + ProcessorType::AsrAsrx => vec![ProcessorType::Cut], ProcessorType::Asrx => vec![ProcessorType::Cut, ProcessorType::Asr], ProcessorType::Scene => vec![ProcessorType::Cut], ProcessorType::Pose => vec![ProcessorType::Face], @@ -694,8 +703,9 @@ impl ProcessorType { pub fn all() -> Vec { vec![ ProcessorType::Cut, - ProcessorType::Asr, - ProcessorType::Asrx, + // Unified ASR+diarization (rust_asr_asrx). Legacy Asr/Asrx are no + // longer offered: "asrx" now resolves to AsrAsrx via from_db_str. + ProcessorType::AsrAsrx, ProcessorType::Ocr, ProcessorType::Face, ProcessorType::FaceTrace, @@ -721,6 +731,7 @@ impl ProcessorType { ProcessorType::Cut | ProcessorType::Asr + | ProcessorType::AsrAsrx | ProcessorType::Asrx | ProcessorType::Scene => PipelineType::Time, } @@ -2496,6 +2507,7 @@ impl PostgresDb { SELECT id FROM {} WHERE status = 'pending' AND queue_name = 'internal.file' + AND command_type IN ('register', 'unregister') ORDER BY priority ASC, created_at ASC FOR UPDATE SKIP LOCKED LIMIT $1 ) diff --git a/src/core/frame_cache.rs b/src/core/frame_cache.rs index b155702b..9008b0fa 100644 --- a/src/core/frame_cache.rs +++ b/src/core/frame_cache.rs @@ -47,7 +47,7 @@ impl FrameManager { &video_path, "-vf", &format!("select=not(mod(n\\,{})),scale=320:-2", sample_interval), - "-vsync", + "-fps_mode", "vfr", "-q:v", "15", diff --git a/src/core/pipeline_config.rs b/src/core/pipeline_config.rs index b48127ef..0490a56b 100644 --- a/src/core/pipeline_config.rs +++ b/src/core/pipeline_config.rs @@ -164,7 +164,7 @@ impl PipelineFlows { for stage in stages.iter().filter(|s| s.enabled) { // Map stage names to processor names let mapped = match stage.name.as_str() { - "asr_asrx" => vec!["asr".to_string(), "asrx".to_string()], + "asr_asrx" => vec!["asrx".to_string()], "scene_vlm" => vec!["scene_vlm".to_string()], "tkg" => vec!["tkg".to_string()], other => vec![other.to_string()], diff --git a/src/core/probe/ffprobe.rs b/src/core/probe/ffprobe.rs index 1a7c9889..6f44819f 100644 --- a/src/core/probe/ffprobe.rs +++ b/src/core/probe/ffprobe.rs @@ -34,8 +34,8 @@ pub struct FormatInfo { } pub fn probe_video(video_path: &str) -> Result { - // Use FFPROBE_PATH environment variable, fallback to "ffprobe" - let ffprobe_path = std::env::var("FFPROBE_PATH").unwrap_or_else(|_| "ffprobe".to_string()); + // Use FFPROBE_PATH environment variable, fallback to absolute path on Apple Silicon + let ffprobe_path = std::env::var("FFPROBE_PATH").unwrap_or_else(|_| "/opt/homebrew/bin/ffprobe".to_string()); let output = Command::new(&ffprobe_path) .args([ diff --git a/src/core/processor/asr_asrx.rs b/src/core/processor/asr_asrx.rs new file mode 100644 index 00000000..39cc81ac --- /dev/null +++ b/src/core/processor/asr_asrx.rs @@ -0,0 +1,84 @@ +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use std::path::Path; +use std::process::Command; + +#[derive(Debug, Serialize, Deserialize)] +pub struct AsrAsrxSegment { + pub id: usize, + pub start: f64, + pub end: f64, + pub text: String, + pub speaker_id: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct AsrAsrxResult { + pub language: String, + pub segments: Vec, + pub recovery: Option, +} + +pub async fn process_asr_asrx( + video_path: &str, + output_path: &str, + uuid: Option<&str>, +) -> Result { + let binary = "tools/cli/rust/target/release/rust_asr_asrx"; + let model = "/Users/accusys/models/whisper-small-mlx"; + + let mut cmd = Command::new(binary); + cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"); + cmd.args([ + "--input", video_path, + "--output", output_path, + "--model", model, + ]); + cmd.arg("--diarize"); + if let Some(u) = uuid { + cmd.env("FILE_UUID", u); + } + + let output = cmd.output().context("Failed to run rust_asr_asrx")?; + if !output.status.success() { + anyhow::bail!( + "rust_asr_asrx failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + + let json_path = output_path; + if !Path::new(json_path).exists() { + anyhow::bail!("rust_asr_asrx output not found: {}", json_path); + } + + let content = std::fs::read_to_string(json_path) + .context("Failed to read asr_asrx output")?; + let json: serde_json::Value = serde_json::from_str(&content) + .context("Failed to parse asr_asrx output")?; + + let language = json["language"].as_str().unwrap_or("unknown").to_string(); + let recovery = json.get("recovery").cloned(); + + let segments: Vec = json["segments"] + .as_array() + .map(|arr| { + arr.iter() + .enumerate() + .map(|(i, s)| AsrAsrxSegment { + id: s["id"].as_u64().unwrap_or(i as u64) as usize, + start: s["start"].as_f64().unwrap_or(0.0), + end: s["end"].as_f64().unwrap_or(0.0), + text: s["text"].as_str().unwrap_or("").to_string(), + speaker_id: s["speaker_id"].as_str().map(|s| s.to_string()), + }) + .collect() + }) + .unwrap_or_default(); + + Ok(AsrAsrxResult { + language, + segments, + recovery, + }) +} diff --git a/src/core/processor/cut.rs b/src/core/processor/cut.rs index d7c750f6..c6a064a6 100644 --- a/src/core/processor/cut.rs +++ b/src/core/processor/cut.rs @@ -84,7 +84,7 @@ pub async fn process_cut( // Fallback: Python scenedetect tracing::warn!("[CUT] Native impl failed, falling back to Python"); let executor = PythonExecutor::new()?; - let script_path = executor.script_path("cut_processor.py"); + let script_path = executor.script_path("cut/cut_processor.py"); if !script_path.exists() { let mut empty_result = CutResult { @@ -102,7 +102,7 @@ pub async fn process_cut( executor .run( - "cut_processor.py", + "cut/cut_processor.py", &[video_path, output_path], uuid, "CUT", diff --git a/src/core/processor/executor.rs b/src/core/processor/executor.rs index eab60b8c..c80a6bef 100644 --- a/src/core/processor/executor.rs +++ b/src/core/processor/executor.rs @@ -333,6 +333,8 @@ impl PythonExecutor { }); let mut cmd = Command::new(&self.python_path); + cmd.env("PYTHONPATH", &self.scripts_dir); + cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); @@ -503,6 +505,8 @@ impl PythonExecutor { }); let mut cmd = Command::new(&self.python_path); + cmd.env("PYTHONPATH", &self.scripts_dir); + cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); @@ -717,6 +721,8 @@ impl PythonExecutor { }); let mut cmd = Command::new(&self.python_path); + cmd.env("PYTHONPATH", &self.scripts_dir); + cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); @@ -939,6 +945,8 @@ impl PythonExecutor { }); let mut cmd = Command::new(&self.python_path); + cmd.env("PYTHONPATH", &self.scripts_dir); + cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); diff --git a/src/core/processor/face.rs b/src/core/processor/face.rs index 37a142ce..7040f0bb 100644 --- a/src/core/processor/face.rs +++ b/src/core/processor/face.rs @@ -862,8 +862,13 @@ pub async fn store_face_embeddings_to_qdrant( tracing::info!("[FACE] Stored {} embeddings to Qdrant", total_points); - // Keep embeddings in JSON (JSON is source of truth) - // No longer remove embeddings from JSON + // Remove embeddings from JSON to keep file size manageable + // Vectors are stored in Qdrant, JSON only keeps metadata + for frame in &mut face_result.frames { + for face in &mut frame.faces { + face.embedding = None; + } + } Ok(total_points) } diff --git a/src/core/processor/mod.rs b/src/core/processor/mod.rs index 66e4e53a..8573b840 100644 --- a/src/core/processor/mod.rs +++ b/src/core/processor/mod.rs @@ -1,5 +1,6 @@ pub mod appearance; pub mod asr; +pub mod asr_asrx; pub mod asrx; pub mod caption; pub mod cascade_vision; @@ -162,6 +163,7 @@ pub use appearance::{ process_appearance, AppearanceFrame, AppearancePerson, AppearanceResult, BBox, BodyPart, }; pub use asr::{process_asr, AsrResult, AsrSegment}; +pub use asr_asrx::{process_asr_asrx, AsrAsrxResult, AsrAsrxSegment}; pub use asrx::{process_asrx, AsrxResult, AsrxSegment}; pub use caption::{process_caption, CaptionResult, CaptionSummary, FrameCaption}; pub use cascade_vision::{CascadeDetectionResult, CascadeVisionProcessor}; diff --git a/src/core/processor/scene_vlm.rs b/src/core/processor/scene_vlm.rs index 478e4f3e..0bcf6b61 100644 --- a/src/core/processor/scene_vlm.rs +++ b/src/core/processor/scene_vlm.rs @@ -30,20 +30,32 @@ impl SceneVlmProcessor { fps: f64, samples: usize, ) -> Vec { + if samples == 0 { + return vec![]; + } let sample_interval = interval_sec / samples as f64; - (0..samples) + let frames: Vec = (0..samples) .map(|i| { let time = interval_start_sec + (i as f64 + 0.5) * sample_interval; (time * fps).round() as u32 }) - .collect() + .collect(); + + // Ensure at least frame 0 is included for short videos + if frames.is_empty() || frames.iter().all(|&f| f > 0) { + let mut result = vec![0u32]; + result.extend(frames.into_iter().filter(|&f| f > 0)); + result + } else { + frames + } } pub async fn calculate_blur_single(video_path: &str, frame: u32, fps: f64) -> Result { let time_sec = frame as f64 / fps; - let output = Command::new("ffmpeg") + let output = Command::new("/opt/homebrew/bin/ffmpeg") .args([ "-ss", &format!("{:.2}", time_sec), @@ -173,6 +185,32 @@ impl SceneVlmProcessor { vlm_tags: Vec::new(), embedding_status: EmbeddingStatus::Pending, }); + } else if let Some(&frame) = sample_frames.first() { + // Fallback: use first sample frame when blur detection yields no scores + let timestamp = frame as f64 / fps; + selected_frames.push(SceneFrame { + index: 0, + filename: format!("scene_{:03}.jpg", 0), + timestamp_sec: timestamp, + frame_number: frame, + selection_reason: SelectionReason::Default, + quality_score: None, + quality_source: None, + scene_info: None, + face_count: 0, + person_traces: Vec::new(), + has_cut: false, + cut_count: 0, + vlm_status: VlmStatus::Pending, + vlm_description: None, + vlm_description_localized: None, + vlm_scene_type: None, + vlm_location: None, + vlm_objects: Vec::new(), + vlm_attributes: None, + vlm_tags: Vec::new(), + embedding_status: EmbeddingStatus::Pending, + }); } } else { let cut = &cuts[0]; @@ -376,7 +414,7 @@ impl SceneVlmProcessor { let time_sec = scene.timestamp_sec; - let status = Command::new("ffmpeg") + let status = Command::new("/opt/homebrew/bin/ffmpeg") .args([ "-y", "-ss", diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index 5655a1b2..9099f3b6 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -2135,7 +2135,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { let tkg_edges_t = schema::table_name("tkg_edges"); let has_asr_or_asrx = - job_processors.is_empty() || job_processors.iter().any(|p| p == "asrx" || p == "asr"); + job_processors.is_empty() || job_processors.iter().any(|p| p == "asrx" || p == "asr" || p == "asr_asrx"); let has_face = job_processors.is_empty() || job_processors.iter().any(|p| p == "face"); let has_cut = job_processors.is_empty() || job_processors.iter().any(|p| p == "cut"); @@ -2147,6 +2147,9 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { UNION ALL \ SELECT asr_status FROM {pr_t} pr JOIN {mj_t} mj ON pr.job_id = mj.id \ WHERE mj.uuid = $1 AND pr.processor = 'asr' AND asr_status IS NOT NULL \ + UNION ALL \ + SELECT asr_status FROM {pr_t} pr JOIN {mj_t} mj ON pr.job_id = mj.id \ + WHERE mj.uuid = $1 AND pr.processor = 'asr_asrx' AND asr_status IS NOT NULL \ LIMIT 1", mj_t = schema::table_name("monitor_jobs") )) @@ -2172,7 +2175,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { if status_from_db { true } else { - // Fallback: check asr.json file directly + // Fallback: check asr.json / asr_asrx.json file directly let asr_path = format!( "{}/{}.asr.json", crate::core::config::OUTPUT_DIR @@ -2180,7 +2183,16 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { .trim_end_matches('/'), uuid ); - if let Ok(content) = std::fs::read_to_string(&asr_path) { + let asr_asrx_path = format!( + "{}/{}.asr_asrx.json", + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), + uuid + ); + let content = std::fs::read_to_string(&asr_path) + .or_else(|_| std::fs::read_to_string(&asr_asrx_path)); + if let Ok(content) = content { if let Ok(data) = serde_json::from_str::(&content) { match data.get("status").and_then(|s| s.as_str()) { Some("no_audio_track") | Some("silent_audio") => true, @@ -2397,6 +2409,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { // (completed + failed) == total_scenes 才代表全部 scene 都處理完, // 否則 job 保持 running 由 poll 重試。 let scene_vlm_done: bool = if has_cut { + // Check if scenes.json exists first if let Ok(scenes_json) = std::fs::read_to_string(format!("{}/{}.scenes.json", output_dir, uuid)) { @@ -2406,7 +2419,6 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { .and_then(|v| v.as_i64()) .unwrap_or(0); if total == 0 { - // 無 scene 可選(例如極短或全部 blur 失敗)視為完成 true } else { let completed = scenes_data @@ -2429,7 +2441,18 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { false } } else { - false + // scenes.json not found — check processor_results for scene_vlm completion + // (e.g. "completed" due to invalid metadata / not applicable) + let mj_t = schema::table_name("monitor_jobs"); + let pr_t = schema::table_name("processor_results"); + let svlm_done: Option = sqlx::query_scalar(&format!( + "SELECT status FROM {pr_t} WHERE job_id = (SELECT id FROM {mj_t} WHERE uuid = $1) AND processor = 'scene_vlm' LIMIT 1" + )) + .bind(uuid) + .fetch_optional(pool) + .await + .unwrap_or(None); + svlm_done.as_deref() == Some("completed") } } else { true @@ -2532,7 +2555,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { // 例如:Rule 1 只需 ASR+ASRX 完成即可觸發,不須等 face/pose/story 完成 // 定義必要 processor(必須完成的才算 job 成功) - let essential_processors = ["cut", "asr", "asrx"]; + let essential_processors = ["cut", "asr", "asrx", "asr_asrx"]; let essential_failed = essential_processors.iter().any(|ep| { results.iter().any(|r| { @@ -2911,8 +2934,8 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { let has_asr_or_asrx = completed_processors .iter() - .any(|p| p == "asrx" || p == "asr"); - let has_asrx = completed_processors.iter().any(|p| p == "asrx"); + .any(|p| p == "asrx" || p == "asr" || p == "asr_asrx"); + let has_asrx = completed_processors.iter().any(|p| p == "asrx" || p == "asr_asrx"); let has_cut = completed_processors.iter().any(|p| p == "cut"); let has_face = completed_processors.iter().any(|p| p == "face"); let has_ocr = completed_processors.iter().any(|p| p == "ocr"); @@ -3376,13 +3399,27 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + // Get video path from DB for face crop extraction + let video_path: Option = db_clone + .get_video_by_uuid(&uuid_clone) + .await + .ok() + .flatten() + .map(|v| v.file_path); + + let mut face_args = vec![uuid_clone.as_str(), "--output-dir", output_dir]; + if let Some(ref vp) = video_path { + face_args.push("--video-path"); + face_args.push(vp.as_str()); + } + let result = match executor.rust_binary_path("rust_store_traced_faces") { Some(bin) => { tracing::info!("[FACE_TRACE] Using Rust binary: {:?}", bin); executor .run_rust_with_output_idx_and_frames( &bin, - &[&uuid_clone, "--output-dir", output_dir], + &face_args, None, None, None, diff --git a/src/worker/processor.rs b/src/worker/processor.rs index f041b55c..45e00631 100644 --- a/src/worker/processor.rs +++ b/src/worker/processor.rs @@ -1098,6 +1098,62 @@ impl ProcessorPool { total_faces: 0, }) } + ProcessorType::AsrAsrx => { + let asr_asrx_result = processor::process_asr_asrx( + video_path, + output_path.to_str().unwrap(), + uuid, + ) + .await?; + + // Convert to AsrResult for storage + let asr_segments: Vec = asr_asrx_result + .segments + .iter() + .map(|s| processor::AsrSegment { + start_time: s.start, + end_time: s.end, + start_frame: None, + end_frame: None, + text: s.text.clone(), + confidence: 1.0, + }) + .collect(); + + let mut asr_result = processor::AsrResult { + metadata: None, + status: None, + language: Some(asr_asrx_result.language.clone()), + language_probability: None, + segments: asr_segments, + segment_count: 0, + }; + asr_result.compute_status(); + + let chunks_produced = asr_result.segments.len() as i32; + let lang = asr_result.language.clone(); + tracing::info!( + "ASR_ASRX completed, language={}, {} segments for {}", + lang.as_deref().unwrap_or("unknown"), + chunks_produced, + job.uuid + ); + if let Err(e) = Self::store_asr_chunks(db, &job.uuid, &asr_result).await { + tracing::error!("Failed to store ASR_ASRX chunks for {}: {}", job.uuid, e); + } + Ok(ProcessorOutput { + data: serde_json::Value::Null, + chunks_produced, + frames_processed: total_frames, + total_frames, + retry_count: 0, + pid: 0, + asr_status: asr_result.status.clone(), + segment_count: asr_result.segment_count, + face_status: None, + total_faces: 0, + }) + } ProcessorType::Asrx => { let mut result = processor::process_asrx(video_path, output_path.to_str().unwrap(), uuid) diff --git a/tools/cli/rust/src/bin/rust_appearance.rs b/tools/cli/rust/src/bin/rust_appearance.rs index d700c22f..0329d1e1 100644 --- a/tools/cli/rust/src/bin/rust_appearance.rs +++ b/tools/cli/rust/src/bin/rust_appearance.rs @@ -641,8 +641,8 @@ fn extract_frames( .arg(video_path) .arg("-vf") .arg(&filter) - .arg("-vsync") - .arg("0") + .arg("-fps_mode") + .arg("vfr") .arg("-f") .arg("image2") .arg(&out_pattern) diff --git a/tools/cli/rust/src/bin/rust_store_traced_faces.rs b/tools/cli/rust/src/bin/rust_store_traced_faces.rs index 30c6136d..27585fab 100644 --- a/tools/cli/rust/src/bin/rust_store_traced_faces.rs +++ b/tools/cli/rust/src/bin/rust_store_traced_faces.rs @@ -32,6 +32,12 @@ struct Args { /// IoU threshold for bbox overlap #[arg(long, default_value = "0.3")] iou_threshold: f64, + /// Video file path (for extracting face crops) + #[arg(long)] + video_path: Option, + /// DB URL for looking up video path (fallback) + #[arg(long)] + db_url: Option, } fn env_var(name: &str, default: &str) -> String { @@ -230,6 +236,86 @@ fn bboxes_match(b1: &BBox, b2: &BBox, tolerance: i32) -> bool { (b1.height - b2.height).abs() <= tolerance } +/// Extract key_face.jpg for each trace using ffmpeg crop. +/// Uses the highest-confidence frame's bbox from the trace. +fn extract_face_jpegs( + file_uuid: &str, + output_dir: &std::path::Path, + face_data: &FaceData, + traces: &[TraceInfo], + video_path: &str, +) -> Result<()> { + let base_dir = output_dir.join(file_uuid); + + for trace in traces { + let trace_dir = base_dir.join(format!("trace_{}", trace.trace_id)); + std::fs::create_dir_all(&trace_dir).ok(); + + // Find the best face (highest confidence) for this trace + let mut best_face: Option<(usize, &FaceDetection)> = None; + + for frame in &face_data.frames { + for face in &frame.faces { + if let Some(tid) = face.trace_id { + if tid == trace.trace_id as i32 { + let frame_num = frame.frame as usize; + if let Some((_, bf)) = &best_face { + if face.confidence > bf.confidence { + best_face = Some((frame_num, face)); + } + } else { + best_face = Some((frame_num, face)); + } + } + } + } + } + + // Extract key_face.jpg from the best frame + if let Some((frame_num, face)) = best_face { + if face.bbox.width > 0 && face.bbox.height > 0 { + let out_path = trace_dir.join("key_face.jpg"); + if let Err(e) = extract_face_crop(video_path, frame_num, face, &out_path) { + println!("[TRACE_STORE] WARN key_face.jpg for trace {}: {}", trace.trace_id, e); + } + } + } + } + + Ok(()) +} + +/// Use ffmpeg to extract a single cropped face frame. +fn extract_face_crop(video_path: &str, frame_num: usize, face: &FaceDetection, output: &std::path::Path) -> Result<()> { + let x = face.bbox.x; + let y = face.bbox.y; + let w = face.bbox.width; + let h = face.bbox.height; + + let status = std::process::Command::new("/opt/homebrew/bin/ffmpeg") + .args([ + "-y", "-v", "quiet", + "-i", video_path, + "-vf", &format!("select=eq(n\\,{}),crop={}:{}:{}:{}", frame_num, w, h, x, y), + "-frames:v", "1", + "-q:v", "3", + "-f", "image2", + output.to_str().unwrap(), + ]) + .status() + .context("Failed to run ffmpeg")?; + + if !status.success() { + anyhow::bail!("ffmpeg exit code: {:?}", status.code()); + } + + if !output.exists() { + anyhow::bail!("ffmpeg did not produce output"); + } + + Ok(()) +} + fn main() -> Result<()> { let args = Args::parse(); @@ -391,6 +477,13 @@ fn main() -> Result<()> { 0.0 }; + // Extract face crop JPEGs for each trace (before traced_data takes ownership) + let video_path = args.video_path.clone() + .or_else(|| std::env::var("MOMENTRY_VIDEO_PATH").ok()); + if let Some(ref video) = video_path { + extract_face_jpegs(&args.file_uuid, &args.output_dir, &face_data, &traces_v2, video)?; + } + // Create output (v2 format) let traced_data = FaceTracedData { schema_version: "2.0".to_string(),