From 083d73d287a9e84de87418c825053f7b709548c7 Mon Sep 17 00:00:00 2001 From: Accusys Date: Mon, 16 Nov 2026 18:16:46 +0800 Subject: [PATCH] feat: real service test endpoints (proxy 7-route round-trip, core/chat/vlm/markbase/embedding), unified log paths + errorLog, pipeline tools/import/export/folder APIs, face pipeline check, dynamic concurrency tuning --- Cargo.lock | 24 + Cargo.toml | 3 + config/admin_config.json | 324 ++- .../FACE_GROUPS_JSON_PERSISTENCE_V1.0.md | 196 ++ .../DESIGN/FACE_GROUPS_NORMALIZATION_V1.0.md | 148 ++ docs_v1.0/DESIGN/FACE_PIPELINE_CHECK_V1.0.md | 664 ++++++ .../plist/com.momentry.agent.plist | 74 +- momentry_runtime/plist/com.momentry.api.plist | 8 +- .../plist/com.momentry.caddy.plist | 64 +- .../plist/com.momentry.gitea.plist | 68 +- .../plist/com.momentry.mariadb.plist | 45 +- .../plist/com.momentry.monitor.plist | 76 +- .../plist/com.momentry.ollama.plist | 68 +- .../plist/com.momentry.postgresql.plist | 58 +- .../plist/com.momentry.qdrant.plist | 4 +- .../plist/com.momentry.redis.plist | 18 +- schema/schema.sql | 5 +- scripts/embeddinggemma_server.py | 19 +- scripts/face_clustering_processor.py | 173 +- scripts/face_pipeline_check.py | 360 +++ src/api/admin_cleanup.rs | 242 ++ src/api/admin_config.rs | 209 +- src/api/agent_search.rs | 60 +- src/api/auth.rs | 33 +- src/api/cluster_agent.rs | 21 + src/api/directory_browser.rs | 338 +++ src/api/export_api.rs | 208 ++ src/api/file_replicas.rs | 255 +++ src/api/files.rs | 90 +- src/api/folder_api.rs | 201 ++ src/api/identity_api.rs | 78 +- src/api/import_api.rs | 478 ++++ src/api/markbase_compat.rs | 51 +- src/api/media_api.rs | 78 +- src/api/middleware.rs | 22 +- src/api/mod.rs | 10 + src/api/mount_points.rs | 182 ++ src/api/pipeline_tools.rs | 280 +++ src/api/processing.rs | 98 + src/api/profile.rs | 859 ++++++-- src/api/scan.rs | 183 +- src/api/search.rs | 161 +- src/api/server.rs | 30 +- src/api/service_management.rs | 1957 +++++++++++++++-- src/api/trace_agent_api.rs | 49 +- src/api/unregister_api.rs | 248 +++ src/api/upload_paths.rs | 255 +++ src/api/vlm_search.rs | 42 +- src/bin/test_embedding_rust.rs | 141 ++ src/core/admin_config.rs | 112 +- src/core/agent/tools.rs | 11 + src/core/config.rs | 34 + src/core/db/postgres_db.rs | 57 +- src/core/db/schema.rs | 205 ++ src/core/db/workspace_sqlite.rs | 70 + src/core/dynamic_concurrency.rs | 12 + src/core/export.rs | 435 ++++ src/core/file_profile.rs | 2 + src/core/folder_export.rs | 475 ++++ src/core/init.rs | 2 +- src/core/json_debug.rs | 161 ++ src/core/json_formatter.rs | 30 + src/core/json_standardize.rs | 260 +++ src/core/llm/client.rs | 26 +- src/core/llm/function_calling.rs | 245 ++- src/core/mod.rs | 5 + src/core/path_utils.rs | 8 +- src/core/processor/asrx.rs | 44 +- src/core/processor/cut.rs | 93 +- src/core/processor/face.rs | 61 +- src/core/processor/face_clustering.rs | 39 +- src/core/processor/face_tracker.rs | 34 +- src/core/processor/heuristic_scene.rs | 1 + src/core/processor/ocr.rs | 76 +- src/core/processor/scene_vlm.rs | 113 +- src/core/processor/tkg.rs | 1 + src/core/processor/tool_selector.rs | 4 +- src/core/trace_sync.rs | 21 + src/core/vlm/client.rs | 29 +- src/lib.rs | 5 +- src/main.rs | 2 +- src/worker/job_worker.rs | 727 +++++- src/worker/processor.rs | 6 +- src/worker/resources.rs | 23 +- tools/cli/rust/src/asrx/mod.rs | 29 +- tools/cli/rust/src/bin/rust_cut.rs | 150 +- tools/cli/rust/src/bin/rust_face_cluster.rs | 196 +- .../rust/src/bin/rust_store_traced_faces.rs | 250 ++- 88 files changed, 12216 insertions(+), 1096 deletions(-) create mode 100644 docs_v1.0/DESIGN/FACE_GROUPS_JSON_PERSISTENCE_V1.0.md create mode 100644 docs_v1.0/DESIGN/FACE_GROUPS_NORMALIZATION_V1.0.md create mode 100644 docs_v1.0/DESIGN/FACE_PIPELINE_CHECK_V1.0.md create mode 100644 scripts/face_pipeline_check.py create mode 100644 src/api/admin_cleanup.rs create mode 100644 src/api/directory_browser.rs create mode 100644 src/api/export_api.rs create mode 100644 src/api/file_replicas.rs create mode 100644 src/api/folder_api.rs create mode 100644 src/api/import_api.rs create mode 100644 src/api/mount_points.rs create mode 100644 src/api/pipeline_tools.rs create mode 100644 src/api/unregister_api.rs create mode 100644 src/api/upload_paths.rs create mode 100644 src/bin/test_embedding_rust.rs create mode 100644 src/core/export.rs create mode 100644 src/core/folder_export.rs create mode 100644 src/core/json_debug.rs create mode 100644 src/core/json_standardize.rs diff --git a/Cargo.lock b/Cargo.lock index 6beb6340..ba9b3dd9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2470,6 +2470,7 @@ dependencies = [ "dotenv", "env_logger", "ferrous-opencc", + "flate2", "futures-util", "hex", "jieba-rs", @@ -2494,6 +2495,7 @@ dependencies = [ "sqlx 0.8.6", "subtle", "sysinfo", + "tar", "tempfile", "thiserror 1.0.69", "tokio", @@ -2506,6 +2508,7 @@ dependencies = [ "utoipa", "utoipa-swagger-ui", "uuid", + "walkdir", ] [[package]] @@ -4625,6 +4628,17 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -6029,6 +6043,16 @@ dependencies = [ "tap", ] +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.4", +] + [[package]] name = "xxhash-rust" version = "0.8.15" diff --git a/Cargo.toml b/Cargo.toml index 3cbc4f1a..72669d7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -86,6 +86,9 @@ crossterm = "0.28" # Terminal atty = "0.2" tokio-util = { version = "0.7.18", features = ["io"] } +walkdir = "2.5.0" +flate2 = "1.0" +tar = "0.4" # System diff --git a/config/admin_config.json b/config/admin_config.json index 6d2987f7..5c1ebfce 100644 --- a/config/admin_config.json +++ b/config/admin_config.json @@ -1,31 +1,65 @@ { - "version": "1.0.0", - "updated_at": "2026-10-26T17:18:56.139925+00:00", + "version": "1.3.5", + "updated_at": "2026-11-15T12:00:00+0800", "updated_by": "admin", "vlm_prompts": { + "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" + }, "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" + "garbled_recovery": { + "system_prompt": "You are a helpful assistant that verifies speech transcription quality.", + "user_prompt": "Analyze this transcript for garbled text. Is it intelligible?", + "max_tokens": 100, + "description": "ASR garbled text recovery 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", + "url": "http://127.0.0.1:8080/v1/chat/completions", "model": "gemma-4-12b-it", - "timeout": 60 + "timeout": 60, + "fallbacks": [ + "http://127.0.0.1:8082/v1/chat/completions" + ], + "strategy": "priority", + "enabled": true + }, + "vlm": { + "url": "http://127.0.0.1:8082/v1/chat/completions", + "model": "gemma-4-12b-it", + "timeout": 120, + "fallbacks": [ + "http://127.0.0.1:8080/v1/chat/completions" + ], + "strategy": "priority", + "enabled": false + }, + "chat": { + "url": "http://127.0.0.1:8080/v1/chat/completions", + "model": "gemma-4-12b-it", + "timeout": 30, + "fallbacks": [ + "http://127.0.0.1:8082/v1/chat/completions" + ], + "strategy": "priority", + "enabled": true + }, + "embedding": { + "url": "http://127.0.0.1:11436/v1/embeddings", + "model": "embeddinggemma", + "timeout": 60, + "fallbacks": [], + "strategy": "priority", + "enabled": true } }, "processor_config": { @@ -48,26 +82,7 @@ ], "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": { + "OCR": { "timeout": 3600, "enabled": true, "tools": [ @@ -76,21 +91,6 @@ "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" @@ -127,7 +127,52 @@ ], "default_tool": "swift" }, - "OCR": { + "FACE_TRACE": { + "timeout": 3600, + "enabled": true, + "tools": [ + { + "name": "rust", + "priority": 0, + "enabled": true, + "parameters": {} + }, + { + "name": "python", + "priority": 1, + "enabled": true, + "parameters": {} + } + ], + "default_tool": "rust" + }, + "FACE_CLUSTER": { + "timeout": 3600, + "enabled": true, + "tools": [ + { + "name": "rust", + "priority": 0, + "enabled": true, + "parameters": {} + } + ], + "default_tool": "rust" + }, + "SCENE_VLM": { + "timeout": 7200, + "enabled": true, + "tools": [ + { + "name": "python", + "priority": 0, + "enabled": true, + "parameters": {} + } + ], + "default_tool": "python" + }, + "POSE": { "timeout": 3600, "enabled": true, "tools": [ @@ -136,6 +181,21 @@ "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" @@ -144,7 +204,8 @@ "filter_config": { "face": { "min_confidence": 0.5, - "min_size": 30 + "min_size": 30, + "min_capture_quality": 0.25 } }, "face_filter_defaults": { @@ -153,38 +214,39 @@ "min_capture_quality": 0.25 }, "paths": { - "output_dir": "", - "backup_dir": "", - "scripts_dir": "", - "cli_dir": "", - "python_path": "", - "ffmpeg_path": "" + "output_dir": "/Users/accusys/momentry/output/demo", + "backup_dir": "/Users/accusys/momentry/var/backup", + "scripts_dir": "/Users/accusys/momentry/scripts", + "cli_dir": "/Users/accusys/momentry/tools/cli", + "python_path": "/opt/homebrew/bin/python3.11", + "ffmpeg_path": "/opt/homebrew/bin/ffmpeg" }, "concurrency": { - "max_concurrent_jobs": 0, - "poll_interval": 0, - "batch_size": 0, - "processor_timeout_secs": 0 + "max_concurrent_jobs": 2, + "poll_interval": 5, + "batch_size": 5, + "processor_timeout_secs": 3600 }, "feature_flags": { - "cache_enabled": false, + "cache_enabled": true, "auto_pipeline_enabled": false, "watcher_auto_register": false, - "summary_enabled": false + "summary_enabled": true }, "server": { - "port": 0, - "media_base_url": "", - "serve_base_url": "", - "storage_root": "", - "timezone": "" + "port": 3002, + "media_base_url": "http://localhost:8888", + "serve_base_url": "http://localhost:8888", + "storage_root": "/Users/accusys/momentry/var/sftpgo/data", + "timezone": "Asia/Taipei" }, "admin_settings": { - "session_timeout": 0, - "max_login_attempts": 0, - "api_key_expiry_days": 0, - "system_stats_refresh_sec": 0, - "preferred_language": "" + "session_timeout": 3600, + "max_login_attempts": 5, + "api_key_expiry_days": 365, + "system_stats_refresh_sec": 5, + "preferred_language": "en", + "library_default_sort": "name_asc" }, "search": { "vlm_min_score": 0.0, @@ -194,24 +256,100 @@ "enabled": true, "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 + "flows": { + "register": { + "name": "register", + "description": "Full registration pipeline: all processors", + "version": "1.0", + "enabled": true, + "stages": [ + { + "name": "probe", + "processor_type": "probe", + "required": false, + "enabled": true, + "timeout_secs": 300 + }, + { + "name": "cut", + "processor_type": "cut", + "required": true, + "enabled": true, + "timeout_secs": 3600 + }, + { + "name": "face", + "processor_type": "face", + "required": false, + "enabled": true, + "timeout_secs": 3600 + }, + { + "name": "ocr", + "processor_type": "ocr", + "required": false, + "enabled": true, + "timeout_secs": 3600 + }, + { + "name": "asrx", + "processor_type": "asrx", + "required": false, + "enabled": true, + "timeout_secs": 3600 + }, + { + "name": "scene_vlm", + "processor_type": "scene_vlm", + "required": false, + "enabled": true, + "timeout_secs": 7200 + }, + { + "name": "face_trace", + "processor_type": "face_trace", + "required": false, + "enabled": true, + "timeout_secs": 3600 + }, + { + "name": "face_cluster", + "processor_type": "face_cluster", + "required": false, + "enabled": true, + "timeout_secs": 3600 + } + ] + }, + "reindex": { + "name": "reindex", + "description": "Re-index pipeline: chunks + vectors + TKG", + "version": "1.0", + "enabled": true, + "stages": [ + { + "name": "chunk", + "processor_type": "chunk", + "required": true, + "enabled": true, + "timeout_secs": 3600 + }, + { + "name": "vectorize", + "processor_type": "vectorize", + "required": true, + "enabled": true, + "timeout_secs": 3600 + }, + { + "name": "tkg", + "processor_type": "tkg", + "required": false, + "enabled": true, + "timeout_secs": 7200 + } + ] + } + } } -} +} \ No newline at end of file diff --git a/docs_v1.0/DESIGN/FACE_GROUPS_JSON_PERSISTENCE_V1.0.md b/docs_v1.0/DESIGN/FACE_GROUPS_JSON_PERSISTENCE_V1.0.md new file mode 100644 index 00000000..d6d97313 --- /dev/null +++ b/docs_v1.0/DESIGN/FACE_GROUPS_JSON_PERSISTENCE_V1.0.md @@ -0,0 +1,196 @@ +# Face Groups 持久化設計 V1.0 + +> 日期:2026-11-07|目的:建立 face group 的永久化儲存,作為全域 identity 管理的基礎 + +--- + +## 1. 設計目標 + +| 目標 | 說明 | +|---|---| +| **永久化** | Face group 資訊獨立保存,不依賴 DB 或 face_cluster.json | +| **可視化** | UI 可點擊數字直接查看 JSON 內容 | +| **Identity 基礎** | 未來作為跨檔案 identity 匹配的介面 | +| **區別於 cluster** | face_cluster.json = 演算法產出;face_groups.json = 使用者管理結果 | + +--- + +## 2. 檔案規格 + +### 2.1 檔案位置與命名 + +``` +/Users/accusys/momentry/output/{file_uuid}.face_groups.json +``` + +### 2.2 JSON 結構 + +```json +{ + "schema_version": "1.0", + "file_uuid": "b496a68800f90770aa7246c877f38985", + "file_name": "020.mp4", + "updated_at": "2026-11-07T12:00:00Z", + "total_groups": 3, + "total_traces": 12, + "groups": [ + { + "group_id": 1902, + "name": "Person 1", + "origin_cluster_id": "Person_1", + "trace_ids": [1, 2, 3, 4, 6, 9, 10, 13], + "trace_count": 8, + "representative_trace": 6, + "created_at": "2026-11-07T10:00:00Z", + "updated_at": "2026-11-07T12:00:00Z", + "metadata": { + "merged_from": ["Person_0"], + "manual_rename": false + } + }, + { + "group_id": 1905, + "name": "Person 2", + "origin_cluster_id": "Person_2", + "trace_ids": [7, 12], + "trace_count": 2, + "representative_trace": 7, + "created_at": "2026-11-07T10:00:00Z", + "updated_at": "2026-11-07T10:00:00Z", + "metadata": {} + }, + { + "group_id": 1906, + "name": "Person 5", + "origin_cluster_id": "Person_5", + "trace_ids": [15, 16], + "trace_count": 2, + "representative_trace": 15, + "created_at": "2026-11-07T10:00:00Z", + "updated_at": "2026-11-07T10:00:00Z", + "metadata": {} + } + ] +} +``` + +### 2.3 欄位說明 + +| 欄位 | 類型 | 說明 | +|---|---|---| +| `schema_version` | string | 格式版本,用於未來升級 | +| `file_uuid` | string | 檔案唯一識別 | +| `file_name` | string | 原始檔名(方便識別) | +| `updated_at` | string | 最後更新時間(ISO 8601) | +| `total_groups` | int | 群組總數 | +| `total_traces` | int | 所有群組的 trace 總數 | +| `groups[]` | array | 群組列表 | +| `groups[].group_id` | int | DB face_groups.id | +| `groups[].name` | string | 群組顯示名稱 | +| `groups[].origin_cluster_id` | string | 來源 cluster ID(Person_N) | +| `groups[].trace_ids` | int[] | 所屬 trace ID 列表 | +| `groups[].trace_count` | int | trace 數量 | +| `groups[].representative_trace` | int | 代表 trace(最佳幀) | +| `groups[].created_at` | string | 群組建立時間 | +| `groups[].updated_at` | string | 群組最後更新時間 | +| `groups[].metadata` | object | 擴充資訊(merge 歷史、手動改名等) | + +--- + +## 3. 更新時機 + +| 操作 | 觸發更新 | 說明 | +|---|---|---| +| **Materialize** | ✅ | 首次建立群組時寫入 | +| **Rename Group** | ✅ | 更新 name 和 updated_at | +| **Merge Groups** | ✅ | 合併後更新 trace_ids | +| **Move Trace** | ✅ | 移動 trace 後更新 | +| **Ungroup** | ✅ | 移除 trace 後更新 | +| **Delete Group** | ✅ | 從 groups 陣列移除 | +| **Face Deduplication** | ✅ | 重新聚類後重建 | + +--- + +## 4. UI 整合 + +### 4.1 點擊數字查看 JSON + +```html + +
+ Face Group: + + ({{ faceGroups.length }}) + +
+``` + +### 4.2 JSON 檢視器 Modal + +```html + +
+
+
+ face_groups.json — {{ fileUuid }} + +
+
+
{{ faceGroupsJsonContent }}
+
+
+
+``` + +--- + +## 5. 未來擴展:全域 Identity 管理 + +### 5.1 Identity 匹配介面 + +```json +{ + "identities": [ + { + "identity_uuid": "uuid-1234", + "identity_name": "張三", + "face_groups": [ + { + "file_uuid": "b496a688...", + "file_name": "020.mp4", + "group_id": 1902, + "group_name": "Person 1", + "confidence": 0.95 + }, + { + "file_uuid": "8f45f14f...", + "file_name": "078.mp4", + "group_id": 47, + "group_name": "Person 0", + "confidence": 0.88 + } + ] + } + ] +} +``` + +### 5.2 跨檔案身份聚合 + +- 每個 `face_groups.json` 作為單檔身份基礎 +- 通過 embedding 相似度匹配不同檔案的相似群組 +- 聚合為全域 `identities.json` + +--- + +## 6. 實作計畫 + +| 階段 | 任務 | 檔案 | +|---|---|---| +| **Phase 1** | 建立 `save_face_groups_json()` 函數 | `schema.rs` | +| **Phase 2** | 在所有 group 操作後呼叫保存 | `profile.rs` | +| **Phase 3** | 新增 API 端點讀取 JSON | `profile.rs` | +| **Phase 4** | UI 整合點擊查看功能 | `PeopleView.vue` | +| **Phase 5** | Identity 匹配介面(未來) | 待定 | diff --git a/docs_v1.0/DESIGN/FACE_GROUPS_NORMALIZATION_V1.0.md b/docs_v1.0/DESIGN/FACE_GROUPS_NORMALIZATION_V1.0.md new file mode 100644 index 00000000..11cec517 --- /dev/null +++ b/docs_v1.0/DESIGN/FACE_GROUPS_NORMALIZATION_V1.0.md @@ -0,0 +1,148 @@ +# Face Groups 正規化設計 V1.0(方案 C) + +> 日期:2026-11-06 狀態:已實作並部署(Phase 1);Phase 2 配套見 §7 +> 涉及:`schema.rs` / `profile.rs` / `postgres_db.rs` / `PeopleView.vue` / `store.ts` +> 前置文件:複雜度盤點(4 結構缺陷)、方案 A/B/C 比較 + +--- + +## 1. 核心決策:name 從「每筆 trace 的屬性」升級為「獨立實體」 + +### 1.1 資料模型(三層) + +``` +face_groups(群組實體 — 群組名字住在這裡) +├─ id BIGSERIAL PK +├─ file_uuid 歸屬檔案(暫不跨檔共享) +├─ name ★ 唯一权威群組名 +├─ origin_cluster_id 來源 auto cluster(Person_N),similarity 由此 join +├─ sort_index 顯示排序 +├─ properties JSONB 擴充欄位 +└─ UNIQUE (file_uuid, name) + +trace_profiles(trace 表示層 — 歸屬用外鍵) +├─ group_id BIGINT FK → face_groups(id) ON DELETE 置 NULL 語意 +└─ name ↓ 降級為 caption(見 §2) + +tkg_nodes(KG 圖層) +└─ label ↓ 降級為純顯示鏡射,非資料來源 +``` + +### 1.2 不變式(Invariant) + +| # | 不變式 | 違反後果 | +|---|---|---| +| I1 | 群組的唯一識別 = `face_groups.id`;名稱改變不改變 id | rename 後引用(undo snapshot、一致性檢查)全失效 | +| I2 | trace 是否屬於某群組 **只看** `trace_profiles.group_id` | 舊 name 比對路徑殘留 → 幽靈群組 | +| I3 | 同一 `(file_uuid, name)` 只能有一個 group row | 重複群組/合併語意錯亂 | +| I4 | `group_id IS NULL` ⇔ trace 屬於 Unassigned | Unassigned 僞群組若被物化成 row,Pending Faces 邏輯失效 | +| I5 | rename = `face_groups` 單筆 UPDATE;caption/label 同步屬於**鏡射維護**,失敗不影響 rename 正確性 | — | + +--- + +## 2. `trace_profiles.name` 的新語意:caption(棄權週期) + +`tp.name` 從「群組名來源」降級為**每 trace 的顯示 caption 鏡射**。 + +### 2.1 誰還能寫 tp.name(寫入白名單 — 2026-11-06 生效) + +| 呼叫點 | 行為 | 合法性 | +|---|---|---| +| `profile.rs` rename 分支 | `UPDATE tp SET name = 群組新名 WHERE group_id = $3`(單條 SQL 鏡射整群) | ✅ 鏡射維護 | +| `profile.rs` move 分支 self-healing | INSERT 時帶 name;**已存在 row 不改 name** | ⚠️ 見 G2 | +| `trace_agent_api.rs` hard_delete (=unassign) | 重置為 `Face Trace {id}` | ✅(但需同步清 group_id → G1) | +| undo / snapshot restore | 還原 name + `get_or_create_group` re-attach | ✅ name-less restore 設計 | +| `trace_sync.rs::sync_trace_label` | worker 端同步 label | ⚠️ 見 G4 | + +### 2.2 讀取規則 + +- **讀取群組**:一律 `face_groups` × `tp.group_id` join。新代碼**禁止** `WHERE tp.name = ?` / `GROUP BY tp.name` 作為群組語意。 +- 顯示 caption:允許讀 `tp.name`,但 fallback 順序 = `face_groups.name (by group_id)` → `tp.name` → "Unassigned"。 + +### 2.3 棄權時間表 + +| 階段 | 內容 | +|---|---| +| Phase 1(已完成) | 新表 + group_id 讀寫全走新模型;backfill 保留(`ensure_face_groups_schema`,幂等) | +| Phase 2(本文件 §7 修復清單) | 補齊 6 個缺口;backfill 排除 `Person_%` | +| Phase 3(觀察期 ≥ 2 週) | 現署 caption 廣播(rename 同步 tp.name + tkg label);僅供 search_people 過渡查詢 | +| Phase 4(最終) | `tp.name` 語意窄化為「未歸組 trace 的暫名」;search_people 改 join face_groups;tkg_nodes.label 由查詢時 join 合成,停寫 | + +--- + +## 3. 讀取路徑(單一來源) + +``` +face-groups / cluster-results 读取 + ① materialize_auto_groups(file_uuid) + face_cluster.json 的 Person_N cluster → face_groups row(幂等) + ・成員已全歸組的 cluster:skip + ・部分歸組:只補未涵蓋 cluster;INSERT ... ON CONFLICT DO UPDATE + SET group_id = COALESCE(tp.group_id, $4) — 永不覆蓋既有歸屬 + ② SELECT FROM face_groups LEFT JOIN trace_profiles ON group_id + ③ Unassigned = tp WHERE group_id IS NULL(輔以 single_frame filter 設定) +``` + +- `face_cluster.json` 僅供 frames / similarity / representative 讀取(similarity 以 `origin_cluster_id` join)。 +- fallback 全有全無開關已刪除;DB 有 0 群組時自然顯示全 Unassigned。 + +## 4. 寫入路徑(mutation 設計) + +| 操作 | 寫入 | 備註 | +|---|---|---| +| **Create & Move** | `get_or_create_group` → `UPDATE tp SET group_id` | FS/People 卡片通用;FS 卡不消失(Pending Faces 對 Qdrant `identity_id=0` 查詢) | +| **Move to existing** | 同上(命中既有 row,不 INSERT) | | +| **Rename** | `UPDATE face_groups SET name` ×1 → caption 鏡射 ×2(tp 群內單條 UPDATE、tkg label ANY($3)) | rename vs move 判定:提供的 traces 恰好 = 該群全部成員 | +| **Merge groups** | 成員 re-point 到 target group → 刪除清空的 source group rows | 空群組才刪 | +| **Ungroup / unassign** | `UPDATE tp SET group_id = NULL, name='Face Trace N'` | **不得**建立 "Unassigned" group row(見 G3) | +| **Undo** | name-less restore:`get_or_create_group(名稱)` + re-attach | group row 缺也能救回 | +| **Delete group row** | 僅在群組 0 成員時允許(merge / 清孤兒) | FK 為此目的鎖 | + +## 5. Boot 行為(`ensure_face_groups_schema`,幂等) + +1. CREATE TABLE face_groups(IF NOT EXISTS) +2. `ALTER TABLE tp ADD COLUMN group_id` +3. Backfill A:tp.name(排除 `Face Trace %`、`Trace %`)→ group rows(ON CONFLICT nothing) +4. Backfill B:`tp.group_id IS NULL` 者,依 `(file_uuid,name)` 掛回 + +⚠️ Backfill A 的排除清單**必須包含 `Person_%`**(Phase 2 修復,見 G5),否則 worker 重跑 cluster 寫入的 Person_N caption 會在重啟時復活成群組。 + +## 6. Audit 結果(2026-11-06 全碼掃描) + +直接寫 tp.name 的位置已收斂為 §2.1 白名單;仍觸及 trace_profiles 的其他模組分類: + +| 模組 | 用法 | 分類 | +|---|---|---| +| `search.rs` | 讀 `start_frame…vlm_*` | 無 name 依賴 ✅ | +| `universal_search.rs:603/775` | `SELECT tp.name` for people 搜尋 | caption 讀取,過渡合法(Phase 4 改 join)| +| `identity_api.rs:1190` | people 查詢 | 同上 | +| `agent/tools.rs:1931` | trace 查詢 | 同上 | +| `files.rs / scan.rs` | unregister / 計數 | cascade-safe,無 name 語意 ✅ | +| `trace_agent_api.rs` | unassign 重置、snapshot、undo | 見 G1/G6 | +| `trace_sync.rs` | worker label 廣播 | 見 G4 | +| `job_worker.rs:3661/4562` | cluster 後 label 同步 | 見 G4 | + +## 7. Phase 2 配套修復清單(本文件的主要交付) + +| # | 缺口 | 位置 | 修復設計 | +|---|---|---|---| +| **G1** | Unassign(hard_delete 新語意)只重置 name/label,**沒清 `tp.group_id`** → trace 仍掛原群組 | `trace_agent_api.rs` hard_delete 分支 | 重置時加 `UPDATE tp SET group_id = NULL`;undo 沿用 `get_or_create_group` re-attach | +| **G2** | Move 到既有群組後,已存在 tp row 的 caption 不更新 → people 搜尋顯示舊名 | `profile.rs` move 分支 | move 分支補一條 `UPDATE tp SET name = 目標群組名 WHERE trace_id = ANY(...) AND group_id = 新gid`(只鏡射成員,不動他群) | +| **G3** | Studio Ungroup 傳 `name: 'Unassigned'` → 後端會物化一個叫 "Unassigned" 的實體群組,違反 I4 | `profile.rs` update_trace_profile_group_handler | handler 開頭偵測 `req.name.trim().eq_ignore_ascii_case("unassigned")` → spin off detach 分支:`group_id = NULL` + name 重置,不建 group row | +| **G4** | `sync_trace_label`(cluster 重跑後)會把 `Person_N` 廣播進 tp.name → 重啟 backfill 復活 Person 群組 + 顯示假名回流 | `trace_sync.rs` 呼叫端(job_worker:3661) | 若 trace 已有 group_id:tp.name 用 `face_groups.name` 鏡射值,不用 Person_N;無 group_id 才允許 Person_N | +| **G5** | Boot Backfill A 排除清單缺 `Person_%` | `schema.rs` ensure | WHERE 加 `AND NOT (name LIKE 'Person\_%')` | +| **G6** | `merge_trace` 的 undo 還原 name 但無 group re-attach | `trace_agent_api.rs` undo 段 | 沿用 `schema::get_or_create_group` + attach(同 profile.rs 通用 undo) | + +## 8. 測試守則(回歸用) + +1. rename 後 ** 重啟 server** → 無同名 ghost 群組(I1/I3) +2. move → 重啟 → 歸屬不變(COALESCE 修復) +3. Ungroup → 群組清單不出現 "Unassigned" 實體;trace 回 Pending Faces +4. cluster 重跑 → 已歸組 trace 不被 Person_N 拉走 +5. 雙重啟動失敗群組數 const(幂等) +6. search_people 查新名 → rename 後立即命中;move 後 ≤ Phase2 修復時間命中 + +## 9. 未開放的需求(記錄語意,避免誤解現狀) + +- **跨檔 identity**(同一人跨多支影片):現 `face_groups` 以 file_uuid 為界。未來需要時靠 identity 表(Qdrant `identity_id`)向上聚合,face_groups 不改結構。 +- **群組層 properties**:欄位已備(JSONB),UI 未消費。 diff --git a/docs_v1.0/DESIGN/FACE_PIPELINE_CHECK_V1.0.md b/docs_v1.0/DESIGN/FACE_PIPELINE_CHECK_V1.0.md new file mode 100644 index 00000000..c9702520 --- /dev/null +++ b/docs_v1.0/DESIGN/FACE_PIPELINE_CHECK_V1.0.md @@ -0,0 +1,664 @@ +# Face Pipeline 逐步檢查規範 V1.0 + +> 日期:2026-11-07|適用範圍:face → face_traced → face_cluster → face_groups (DB) + +--- + +## 0. 總覽:上下游關係與產出物 + +``` +video.mp4 + │ + ├─① face detection(swift_face) + │ → output/{uuid}.face.json + │ → Qdrant _faces(512D embedding + payload) + │ + ├─② face tracing(rust_store_traced_faces) + │ → output/{uuid}.face_traced.json + │ + ├─③ face clustering(rust_face / swift_cluster) + │ → output/{uuid}.face_cluster.json + │ + └─④ materialize + group entity(API on-demand / boot backfill) + → DB: face_groups + trace_profiles.group_id +``` + +每個步驟都有**輸入驗證 → 執行 → 產出驗證 → 跨步驗證**四段。 + +--- + +## 1. Face Detection(① → face.json + Qdrant) + +### 1.1 輸入驗證 + +| 檢查項 | 方法 | 合格標準 | +|---|---|---| +| 影片檔案存在 | `os.path.exists(video_path)` | ✅ True | +| 影片可讀 | `probe_json` 有 `width > 0` | ✅ 非零 | +| ffmpeg 可用 | `which ffmpeg` / `ffprobe -version` | ✅ 可執行 | +| FaceNet 模型存在 | 模型路徑 `os.path.exists(model_path)` | ✅ True | + +### 1.2 執行後產出驗證(face.json) + +| 檢查項 | 欄位 / 方法 | 合格標準 | +|---|---|---| +| 檔案存在 | `{output_dir}/{uuid}.face.json` | ✅ 存在 | +| JSON 可解析 | `json.load()` | ✅ 不拋異常 | +| metadata.processor.name | `d['metadata']['processor']['name']` | ✅ `'face'` | +| metadata.processor.tool | 同上 | ✅ `'swift_face'` | +| total_faces > 0 | `d['total_faces']` | ✅ ≥ 0(無臉可為 0) | +| frame_count > 0 | `d['frame_count']` | ✅ ≥ 1 | +| fps > 0 | `d['fps']` | ✅ ≥ 24 | +| frames 陣列 | `len(d['frames'])` | ✅ == frame_count | +| 每幀有 faces | `all(len(f['faces']) >= 0)` | ✅ | + +### 1.3 Embedding 驗證(關鍵!) + +```python +def check_embeddings(face_json: dict) -> dict: + results = {'pass': True, 'issues': []} + total = 0 + missing = 0 + bad_dim = 0 + + for frame in face_json.get('frames', []): + for face in frame.get('faces', []): + total += 1 + emb = face.get('embedding') + if emb is None: + missing += 1 + elif not isinstance(emb, list) or len(emb) != 512: + bad_dim += 1 + elif not all(isinstance(v, (int, float)) for v in emb): + bad_dim += 1 # 元素非數值 + + if missing > 0: + results['pass'] = False + results['issues'].append(f'{missing}/{total} faces 缺少 embedding') + if bad_dim > 0: + results['pass'] = False + results['issues'].append(f'{bad_dim}/{total} faces embedding 維度/格式異常') + if total == 0: + results['issues'].append('沒有 face 資料(影片可能無臉)') + + results['total'] = total + results['missing'] = missing + results['bad_dim'] = bad_dim + return results +``` + +| 檢查項 | 合格標準 | +|---|---| +| embedding 存在 | `missing == 0` | +| embedding 維度 | `len(emb) == 512`(FaceNet 標準) | +| embedding 元素 | 全部為 float/int(可序列化為 JSON array) | + +### 1.4 Qdrant 驗證 + +```python +def check_qdrant_points(uuid: str, expected_faces: int) -> dict: + """檢查 Qdrant _faces collection 是否有對應的 points""" + filter = {"must": [{"key": "file_uuid", "match": {"value": uuid}}]} + + # count + count_resp = qdrant.count_points("_faces", filter) + actual_count = count_resp.count + + # sample point structure + scroll = qdrant.scroll("_faces", filter, limit=1, with_payload=True, with_vector=True) + + return { + 'pass': actual_count > 0, + 'expected': expected_faces, + 'actual': actual_count, + 'missing': max(0, expected_faces - actual_count), + 'sample_keys': list(scroll[0][0].payload.keys()) if scroll[0] else [], + 'vector_dim': len(scroll[0][0].vector) if scroll[0] else 0, + } +``` + +| 檢查項 | 合格標準 | +|---|---| +| points 數量 | `actual_count >= 0`(可小於 face.json,因 low-confidence 可能被過濾) | +| vector 維度 | `vector_dim == 512` | +| payload 必要欄位 | 包含 `file_uuid`, `frame`, `trace_id`, `confidence`, `identity_id` | +| identity_id 預設 | 新插入的 face 應為 `identity_id: 0`(未歸屬) | + +### 1.5 跨步驗證(face.json vs Qdrant) + +| 檢查項 | 方法 | 合格標準 | +|---|---|---| +| face count 一致 | `face.json total_faces` ≈ Qdrant count | Qdrant ≤ face.json(允許過濾) | +| trace_id 有值 | face.json 每幀 face 有 `trace_id` | ✅ 非 null | +| face_id 唯一 | 全檔 face_id 無重複 | ✅ | + +--- + +## 2. Face Tracing(② → face_traced.json) + +### 2.1 輸入依賴 + +| 依賴 | 檢查 | +|---|---| +| face.json 存在 | ✅ 檔案存在且 total_faces > 0 | +| 影片存在 | ✅ | +| min_trace_len, min_confidence | ✅ 參數有效 | + +### 2.2 產出驗證 + +| 檢查項 | 欄位 | 合格標準 | +|---|---|---| +| 檔案存在 | `{uuid}.face_traced.json` | ✅ | +| JSON 可解析 | `json.load()` | ✅ | +| traces 陣列 | `len(d['traces'])` | ✅ ≥ 1 | +| 每筆 trace 必要欄位 | `trace_id`, `frame_count`, `start_frame`, `end_frame`, `best_confidence` | ✅ 全有 | +| trace_id 唯一 | 全檔 trace_id 不重複 | ✅ | +| frame_count 合理 | `1 ≤ frame_count ≤ face.json frame_count` | ✅ | +| start ≤ end | `start_frame ≤ end_frame` | ✅ | +| confidence 範圍 | `0 ≤ avg_confidence ≤ 1`, `0 ≤ best_confidence ≤ 1` | ✅ | +| face_instances 存在 | 每筆 trace 有 `face_instances` 陣列 | ✅ 非空 | +| face_instances 指向有效 face_id | 每個 face_id 可在 face.json 找到 | ✅ | + +```python +def check_face_traced(traced: dict, face_json: dict) -> dict: + results = {'pass': True, 'issues': []} + + traces = traced.get('traces') or [] + if not traces: + results['pass'] = False + results['issues'].append('traces 陣列為空') + return results + + # trace_id 唯一性 + tids = [t['trace_id'] for t in traces] + if len(tids) != len(set(tids)): + results['pass'] = False + results['issues'].append(f'trace_id 有重複:{len(tids)} vs {len(set(tids))} unique') + + # face_instances 指向有效性 + all_face_ids = set() + for fr in face_json.get('frames', []): + for fa in fr.get('faces') or []: + all_face_ids.add(fa.get('face_id')) + + orphan_instances = 0 + for t in traces: + for fi in t.get('face_instances', []): + fid = fi.get('face_id') + if fid and fid not in all_face_ids: + orphan_instances += 1 + + if orphan_instances > 0: + results['issues'].append(f'{orphan_instances} face_instances 指向不存在的 face_id') + + # confidence 範圍 + for t in traces: + bc = t.get('best_confidence', -1) + ac = t.get('avg_confidence', -1) + if not (0 <= bc <= 1): + results['issues'].append(f'trace {t["trace_id"]}: best_confidence={bc} 超出 [0,1]') + if not (0 <= ac <= 1): + results['issues'].append(f'trace {t["trace_id"]}: avg_confidence={ac} 超出 [0,1]') + + results['trace_count'] = len(traces) + results['total_frames_traced'] = sum(t.get('frame_count', 0) for t in traces) + return results +``` + +### 2.3 跨步驗證(face.json vs face_traced.json) + +| 檢查項 | 合格標準 | +|---|---| +| 所有 face.json 的 face_id 被 trace 覆蓋 | `face_instances` 總數 = face.json total_faces | +| trace frame 總和 ≥ face count | 每個 face 都屬於某個 trace | +| trace_id 在 Qdrant payload 中有對應 | Qdrant points 的 `trace_id` 與 traced 一致 | + +--- + +## 3. Face Clustering(③ → face_cluster.json) + +### 3.1 輸入依賴 + +| 依賴 | 檢查 | +|---|---| +| face_traced.json | ✅ traces > 0 | +| face.json | ✅ embedding 全部 512D | +| 模型(facenet / embedding) | ✅ 存在 | + +### 3.2 產出驗證 + +| 檢查項 | 欄位 | 合格標準 | +|---|---|---| +| 檔案存在 | `{uuid}.face_cluster.json` | ✅ | +| clusters 陣列 | `len(d['clusters'])` | ✅ ≥ 1 | +| frames 陣列 | `len(d['frames'])` | ✅ ≥ 1 | +| 每筆 cluster 必要欄位 | `cluster_id`, `face_count`, `representative_face`, `similarity` | ✅ 全有 | +| cluster_id 唯一 | 全檔不重複 | ✅ | +| face_count > 0 | 每群至少 1 face | ✅ | +| similarity 結構 | 有 `min`, `avg`, `threshold` | ✅ 全為 float | +| frame faces 必要欄位 | `cluster_id`, `confidence`, `face_id`, `trace_id` | ✅ 全有 | + +```python +def check_face_cluster(cluster_json: dict, traced: dict) -> dict: + results = {'pass': True, 'issues': []} + + clusters = cluster_json.get('clusters') or [] + frames = cluster_json.get('frames') or [] + + if not clusters: + results['pass'] = False + results['issues'].append('clusters 為空(可能影片人臉太少或 threshold 太高)') + return results + + # cluster_id 唯一 + cids = [c['cluster_id'] for c in clusters] + if len(cids) != len(set(cids)): + results['pass'] = False + results['issues'].append(f'cluster_id 重複') + + # face_count 總和 + total_clustered = sum(c['face_count'] for c in clusters) + + # frame faces 與 clusters 一致性 + frame_face_count = sum(len(f.get('faces') or []) for f in frames) + if frame_face_count != total_clustered: + results['issues'].append( + f'clusters face_count 總和={total_clustered} != frames 中 faces 數={frame_face_count}' + ) + + # cluster faces 的 cluster_id 必須存在於 clusters 列表 + valid_cids = set(cids) + bad_faces = 0 + for f in frames: + for fa in f.get('faces') or []: + if fa.get('cluster_id') not in valid_cids: + bad_faces += 1 + if bad_faces > 0: + results['issues'].append(f'{bad_faces} frame faces 的 cluster_id 不在 clusters 列表中') + + # similarity 驗證 + for c in clusters: + sim = c.get('similarity') or {} + for key in ['min', 'avg', 'threshold']: + if key not in sim: + results['issues'].append(f'cluster {c["cluster_id"]} 缺少 similarity.{key}') + elif not isinstance(sim[key], (int, float)): + results['issues'].append(f'cluster {c["cluster_id"]} similarity.{key} 非數值') + + # trace_id 對應:每個 cluster 的 face 都應有 trace_id + faces_without_trace = 0 + for f in frames: + for fa in f.get('faces') or []: + if fa.get('trace_id') is None: + faces_without_trace += 1 + if faces_without_trace > 0: + results['issues'].append(f'{faces_without_trace} cluster faces 缺少 trace_id') + + results['cluster_count'] = len(clusters) + results['total_clustered_faces'] = total_clustered + results['frame_count'] = len(frames) + return results +``` + +### 3.3 跨步驗證 + +| 檢查項 | 合格標準 | +|---|---| +| 每個 traced face 出現在 cluster | `face_cluster frames 總 faces` = `face.json total_faces` | +| cluster_id 命名 | `Person_N` 格式(自動命名) | +| similarity.threshold 合理 | 通常 ≥ 0.5(視模型而定) | +| representative_face 存在 | 每群有代表臉 | + +--- + +## 4. Materialize + Face Groups(④ → DB) + +### 4.1 觸發時機 + +- 首次呼叫 `/api/v1/cluster-results`(自動 materialize) +- Boot backfill(`ensure_face_groups_schema`) + +### 4.2 產出驗證(DB) + +| 檢查項 | SQL | 合格標準 | +|---|---|---| +| face_groups 有 rows | `SELECT COUNT(*) FROM face_groups WHERE file_uuid=?` | ✅ ≥ cluster 數 | +| group 名稱不重複 | `SELECT COUNT(DISTINCT name)` = `COUNT(*)` | ✅ | +| 每群至少 1 member | `COUNT(tp.trace_id) >= 1 per group` | ✅ | +| trace_profiles.group_id 不懸空 | `SELECT COUNT(*) FROM trace_profiles WHERE group_id IS NOT NULL AND group_id NOT IN (SELECT id FROM face_groups)` | ✅ = 0 | +| origin_cluster_id 對應 | `face_groups.origin_cluster_id` 存在於 `face_cluster.json clusters[*].cluster_id` | ✅ | +| 無重複群組 | 同名 cluster 不會被 materialize 兩次 | ✅ | +| dissolved 標記不影響顯示 | `properties @> '{"dissolved": true}'` 的群組不出現在 API 回應 | ✅ | + +### 4.3 API 回應驗證 + +| 端點 | 檢查項 | 合格標準 | +|---|---|---| +| `/cluster-results` | `face_groups[].trace_ids` 不為空 | ✅ 每群至少 1 trace_id | +| `/cluster-results` | `frames[].faces[].cluster_id` 對應到 group_id | ✅ 可映射 | +| `/cluster-results` | `frames[].faces[].trace_id` 存在 | ✅ 非 null | +| `/face-groups` | `face_groups[].trace_count > 0` | ✅ | +| `/face-groups` | `unassigned_traces` 只含 group_id IS NULL 的 trace | ✅ | + +```python +def check_face_groups_db(uuid: str, cluster_json: dict, api_response: dict) -> dict: + """驗證 face_groups DB 與 face_cluster.json 的一致性""" + results = {'pass': True, 'issues': []} + + groups = api_response.get('face_groups', []) + frames = api_response.get('frames', []) + + if not groups: + results['pass'] = False + results['issues'].append('API 返回 0 個群組') + return results + + # 每群都有 trace_ids + empty_groups = [g for g in groups if not g.get('trace_ids')] + if empty_groups: + results['issues'].append( + f'{len(empty_groups)} 個群組 trace_ids 為空: {[g["name"] for g in empty_groups]}' + ) + + # frames 中 cluster_id 映射到有效 group_id + group_ids = {g['group_id'] for g in groups} + frame_face_ids = set() + for f in frames: + for fa in f.get('faces') or []: + cid = fa.get('cluster_id') + if cid and cid not in group_ids: + results['issues'].append(f'frame face cluster_id={cid} 不對應任何 group') + if fa.get('trace_id') is not None: + frame_face_ids.add(fa['trace_id']) + + # trace_id 一致性:DB groups 的 trace_ids 集合 ≈ frames 中的 trace_id 集合 + db_traces = set() + for g in groups: + db_traces.update(g.get('trace_ids', [])) + + if db_traces != frame_face_ids: + missing_in_db = frame_face_ids - db_traces + extra_in_db = db_traces - frame_face_ids + if missing_in_db: + results['issues'].append(f'{len(missing_in_db)} traces 在 frames 中但不在 DB groups 中') + if extra_in_db: + results['issues'].append(f'{len(extra_in_db)} traces 在 DB groups 中但不在 frames 中') + + return results +``` + +--- + +## 5. 完整檢查腳本 + +以下是單一指令跑完整個 face pipeline 檢查的 Python 腳本: + +```python +#!/usr/bin/env python3.11 +""" +face_pipeline_check.py — 完整檢查 face → traced → cluster → groups +用法:python3.11 face_pipeline_check.py [--api-key KEY] [--api-url URL] +""" +import json +import sys +import os +import argparse +import requests + +OUTPUT_DIR = '/Users/accusys/momentry/output' + +def check_file(uuid): + """Step 0: 檢查檔案存在""" + files = { + 'face': f'{uuid}.face.json', + 'traced': f'{uuid}.face_traced.json', + 'cluster': f'{uuid}.face_cluster.json', + } + status = {'exists': {}} + for name, fname in files.items(): + path = os.path.join(OUTPUT_DIR, fname) + status['exists'][name] = os.path.exists(path) + if status['exists'][name]: + status['exists'][f'{name}_size'] = os.path.getsize(path) + + missing = [n for n, e in status['exists'].items() if isinstance(e, bool) and not e] + if missing: + print(f'❌ 缺少檔案: {missing}') + return status + +def check_face_json(uuid): + """Step 1: face.json 驗證""" + path = os.path.join(OUTPUT_DIR, f'{uuid}.face.json') + if not os.path.exists(path): + return {'pass': False, 'issues': ['face.json 不存在']} + + d = json.load(open(path)) + issues = [] + + total = d.get('total_faces', 0) + fc = d.get('frame_count', 0) + fps = d.get('fps', 0) + frames = d.get('frames') or [] + + if fc == 0: issues.append('frame_count = 0') + if fps < 1: issues.append(f'fps = {fps} (< 1)') + if len(frames) != fc: issues.append(f'frames 數量 {len(frames)} != frame_count {fc}') + + # embedding 檢查 + emb_total = 0; emb_missing = 0; emb_bad = 0 + for fr in frames: + for fa in fr.get('faces') or []: + emb_total += 1 + emb = fa.get('embedding') + if emb is None: + emb_missing += 1 + elif not isinstance(emb, list) or len(emb) != 512: + emb_bad += 1 + + if emb_missing: issues.append(f'{emb_missing}/{emb_total} faces 缺少 embedding') + if emb_bad: issues.append(f'{emb_bad}/{emb_total} faces embedding 非 512D') + + return {'pass': len(issues) == 0, 'total_faces': total, 'issues': issues} + +def check_face_traced(uuid, face_result): + """Step 2: face_traced.json 驗證""" + path = os.path.join(OUTPUT_DIR, f'{uuid}.face_traced.json') + if not os.path.exists(path): + return {'pass': False, 'issues': ['face_traced.json 不存在']} + + d = json.load(open(path)) + issues = [] + traces = d.get('traces') or [] + + if not traces: issues.append('traces 為空') + + # trace_id 唯一 + tids = [t['trace_id'] for t in traces] + if len(tids) != len(set(tids)): + issues.append(f'trace_id 重複: {len(tids)} rows, {len(set(tids))} unique') + + # frame_count 合理性 + for t in traces: + if t.get('frame_count', 0) < 1: + issues.append(f'trace {t["trace_id"]}: frame_count < 1') + bc = t.get('best_confidence', -1) + if not (0 <= bc <= 1): + issues.append(f'trace {t["trace_id"]}: best_confidence={bc}') + + return {'pass': len(issues) == 0, 'trace_count': len(traces), 'issues': issues} + +def check_face_cluster(uuid, traced_result): + """Step 3: face_cluster.json 驗證""" + path = os.path.join(OUTPUT_DIR, f'{uuid}.face_cluster.json') + if not os.path.exists(path): + return {'pass': False, 'issues': ['face_cluster.json 不存在']} + + d = json.load(open(path)) + issues = [] + clusters = d.get('clusters') or [] + frames = d.get('frames') or [] + + if not clusters: issues.append('clusters 為空') + + # cluster_id 唯一 + cids = [c['cluster_id'] for c in clusters] + if len(cids) != len(set(cids)): + issues.append('cluster_id 重複') + + # frame faces 完整性 + frame_faces = [] + for f in frames: + for fa in f.get('faces') or []: + frame_faces.append(fa) + + if not frame_faces: issues.append('frames 中沒有 faces') + + # cluster_id 一致性 + valid_cids = set(cids) + bad = sum(1 for fa in frame_faces if fa.get('cluster_id') not in valid_cids) + if bad: issues.append(f'{bad} frame faces 的 cluster_id 不在 clusters 中') + + # trace_id 存在 + no_trace = sum(1 for fa in frame_faces if fa.get('trace_id') is None) + if no_trace: issues.append(f'{no_trace} frame faces 缺少 trace_id') + + return {'pass': len(issues) == 0, 'cluster_count': len(clusters), + 'frame_face_count': len(frame_faces), 'issues': issues} + +def check_api(uuid, api_key, api_url): + """Step 4: API 回應驗證""" + headers = {'X-API-Key': api_key} + issues = [] + + # cluster-results + url = f'{api_url}/api/v1/cluster-results?file_hash={uuid}' + try: + resp = requests.get(url, headers=headers, timeout=30) + if resp.status_code != 200: + issues.append(f'cluster-results HTTP {resp.status_code}') + return {'pass': False, 'issues': issues} + d = resp.json() + except Exception as e: + issues.append(f'cluster-results 請求失敗: {e}') + return {'pass': False, 'issues': issues} + + groups = d.get('face_groups', []) + frames = d.get('frames', []) + + if not groups: + issues.append('face_groups 為空') + + empty_groups = [g for g in groups if not g.get('trace_ids')] + if empty_groups: + issues.append(f'{len(empty_groups)} 群組 trace_ids 為空') + + # frames faces 完整性 + f_faces = [] + for f in frames: + for fa in f.get('faces') or []: + f_faces.append(fa) + + no_trace = sum(1 for fa in f_faces if fa.get('trace_id') is None) + if no_trace: + issues.append(f'{no_trace} API frame faces 缺少 trace_id') + + return {'pass': len(issues) == 0, 'group_count': len(groups), + 'frame_count': len(frames), 'issues': issues} + +def main(): + parser = argparse.ArgumentParser(description='Face Pipeline Checker') + parser.add_argument('uuid', help='file_uuid to check') + parser.add_argument('--api-key', default='', help='API key') + parser.add_argument('--api-url', default='http://localhost:3002', help='API base URL') + parser.add_argument('--quiet', '-q', action='store_true', help='Only show pass/fail') + args = parser.parse_args() + + results = {'uuid': args.uuid, 'steps': {}} + overall_pass = True + + # Step 0 + r0 = check_file(args.uuid) + results['steps']['0_files'] = r0 + + # Step 1 + r1 = check_face_json(args.uuid) + results['steps']['1_face_json'] = r1 + if not r1['pass']: overall_pass = False + + # Step 2 + r2 = check_face_traced(args.uuid, r1) + results['steps']['2_face_traced'] = r2 + if not r2['pass']: overall_pass = False + + # Step 3 + r3 = check_face_cluster(args.uuid, r2) + results['steps']['3_face_cluster'] = r3 + if not r3['pass']: overall_pass = False + + # Step 4 + r4 = check_api(args.uuid, args.api_key, args.api_url) + results['steps']['4_api'] = r4 + if not r4['pass']: overall_pass = False + + # Print + if args.quiet: + print('PASS' if overall_pass else 'FAIL') + for name, r in results['steps'].items(): + if r.get('issues'): + for i in r['issues']: + print(f' {name}: {i}') + else: + print(f'\n{"="*60}') + print(f'Face Pipeline Check: {args.uuid}') + print(f'{"="*60}\n') + + for name, r in results['steps'].items(): + icon = '✅' if r.get('pass', True) else '❌' + print(f'{icon} {name}') + if r.get('issues'): + for i in r['issues']: + print(f' ⚠️ {i}') + # Print stats + for key in ['total_faces', 'trace_count', 'cluster_count', 'frame_face_count', 'group_count', 'frame_count']: + if key in r: + print(f' {key}: {r[key]}') + print() + + print(f'\nOverall: {"✅ PASS" if overall_pass else "❌ FAIL"}') + print() + + return 0 if overall_pass else 1 + +if __name__ == '__main__': + sys.exit(main()) +``` + +--- + +## 6. 檢查結果判定表 + +| 階段 | 通過 | 警告 | 失敗 | +|---|---|---|---| +| face.json | total_faces ≥ 0, embedding 全部 512D | total_faces = 0(影片無臉) | embedding missing/bad | +| face_traced | traces ≥ 1, trace_id 唯一, confidence ∈ [0,1] | frame_count 總和 < face_count | traces 為空 / 重複 ID | +| face_cluster | clusters ≥ 1, frame faces 完整性 | clusters 數量異常多/少 | clusters 為空 / cluster_id 不一致 | +| API/DB | groups ≥ 1, 每群 trace_ids 不為空 | — | groups 為空 / trace_ids 全空 | + +--- + +## 7. 使用方式 + +```bash +# 完整檢查單一檔案 +python3.11 face_pipeline_check.py b496a68800f90770aa7246c877f38985 \ + --api-key "muser_xxx" --api-url "http://localhost:3002" + +# 快速模式(只輸出 PASS/FAIL) +python3.11 face_pipeline_check.py b496a68800f90770aa7246c877f38985 \ + --api-key "muser_xxx" -q + +# 批次檢查所有已完成檔案 +for uuid in $(psql -t -A -c "SELECT file_uuid FROM videos WHERE status='completed'"); do + python3.11 face_pipeline_check.py $uuid --api-key "muser_xxx" -q +done +``` diff --git a/momentry_runtime/plist/com.momentry.agent.plist b/momentry_runtime/plist/com.momentry.agent.plist index 132b34ef..71db5037 100644 --- a/momentry_runtime/plist/com.momentry.agent.plist +++ b/momentry_runtime/plist/com.momentry.agent.plist @@ -2,46 +2,38 @@ - Label - com.momentry.agent - - ProgramArguments - - /Users/accusys/momentry_core_0.1/momentry_runtime/start.sh - - - RunAtLoad - - - KeepAlive - - - EnvironmentVariables - - HOME - /Users/accusys - USER - accusys - PATH - /opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/Users/accusys/.cargo/bin - DATABASE_URL - postgres://accusys@localhost:5432/momentry - REDIS_URL - redis://accusys:accusys@localhost:6379 - OLLAMA_HOST - http://localhost:11434 - - - StandardOutPath - /Users/accusys/momentry_core_0.1/momentry_runtime/logs/stdout.log - - StandardErrorPath - /Users/accusys/momentry_core_0.1/momentry_runtime/logs/stderr.log - - WorkingDirectory - /Users/accusys/momentry_core_0.1 - - ProcessType - Interactive + EnvironmentVariables + + DATABASE_URL + postgres://accusys@localhost:5432/momentry + HOME + /Users/accusys + OLLAMA_HOST + http://localhost:11434 + PATH + /opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/Users/accusys/.cargo/bin + REDIS_URL + redis://accusys:accusys@localhost:6379 + USER + accusys + + KeepAlive + + Label + com.momentry.agent + ProcessType + Interactive + ProgramArguments + + /Users/accusys/momentry_core_0.1/momentry_runtime/start.sh + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/logs/agent.error.log + StandardOutPath + /Users/accusys/momentry/logs/agent.log + WorkingDirectory + /Users/accusys/momentry_core_0.1 diff --git a/momentry_runtime/plist/com.momentry.api.plist b/momentry_runtime/plist/com.momentry.api.plist index b5a8044e..461a242c 100644 --- a/momentry_runtime/plist/com.momentry.api.plist +++ b/momentry_runtime/plist/com.momentry.api.plist @@ -5,7 +5,9 @@ EnvironmentVariables MOMENTRY_OUTPUT_DIR - /Users/accusys/momentry/output + /Users/accusys/momentry/output/demo + MOMENTRY_SFTP_ROOT + /Users/accusys/momentry/var/sftpgo/data/demo GroupName staff @@ -20,9 +22,9 @@ RunAtLoad StandardErrorPath - /Users/accusys/momentry/log/momentry_api.error.log + /Users/accusys/momentry/logs/core_api.error.log StandardOutPath - /Users/accusys/momentry/log/momentry_api.log + /Users/accusys/momentry/logs/core_api.log UserName accusys WorkingDirectory diff --git a/momentry_runtime/plist/com.momentry.caddy.plist b/momentry_runtime/plist/com.momentry.caddy.plist index b1876e67..02e5e9b9 100644 --- a/momentry_runtime/plist/com.momentry.caddy.plist +++ b/momentry_runtime/plist/com.momentry.caddy.plist @@ -2,41 +2,33 @@ - Label - com.momentry.caddy - - UserName - root - - EnvironmentVariables - - HOME - /opt/homebrew/var/lib/caddy - XDG_DATA_HOME - /opt/homebrew/var/lib - - - WorkingDirectory - /Users/accusys/momentry/var/caddy - - ProgramArguments - - /opt/homebrew/opt/caddy/bin/caddy - run - --config - /Users/accusys/momentry/etc/Caddyfile - - - RunAtLoad - - - KeepAlive - - - StandardErrorPath - /Users/accusys/momentry/log/caddy.error.log - - StandardOutPath - /Users/accusys/momentry/log/caddy.log + EnvironmentVariables + + HOME + /opt/homebrew/var/lib/caddy + XDG_DATA_HOME + /opt/homebrew/var/lib + + KeepAlive + + Label + com.momentry.caddy + ProgramArguments + + /opt/homebrew/opt/caddy/bin/caddy + run + --config + /Users/accusys/momentry/etc/Caddyfile + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/logs/caddy.error.log + StandardOutPath + /Users/accusys/momentry/logs/caddy.log + UserName + root + WorkingDirectory + /Users/accusys/momentry/var/caddy diff --git a/momentry_runtime/plist/com.momentry.gitea.plist b/momentry_runtime/plist/com.momentry.gitea.plist index ec1d667f..c9e9370a 100644 --- a/momentry_runtime/plist/com.momentry.gitea.plist +++ b/momentry_runtime/plist/com.momentry.gitea.plist @@ -2,43 +2,35 @@ - Label - com.momentry.gitea - - UserName - accusys - - WorkingDirectory - /Users/accusys/momentry/var/gitea - - ProgramArguments - - /Users/accusys/gitea/bin/gitea - web - --config - /Users/accusys/momentry/etc/gitea/app.ini - - - EnvironmentVariables - - HOME - /Users/accusys - GITEA_WORK_DIR - /Users/accusys/momentry/var/gitea - PATH - /opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin - - - RunAtLoad - - - KeepAlive - - - StandardOutPath - /Users/accusys/momentry/log/gitea.log - - StandardErrorPath - /Users/accusys/momentry/log/gitea.error.log + EnvironmentVariables + + GITEA_WORK_DIR + /Users/accusys/momentry/var/gitea + HOME + /Users/accusys + PATH + /opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin + + KeepAlive + + Label + com.momentry.gitea + ProgramArguments + + /Users/accusys/gitea/bin/gitea + web + --config + /Users/accusys/momentry/etc/gitea/app.ini + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/logs/gitea.error.log + StandardOutPath + /Users/accusys/momentry/logs/gitea.log + UserName + accusys + WorkingDirectory + /Users/accusys/momentry/var/gitea diff --git a/momentry_runtime/plist/com.momentry.mariadb.plist b/momentry_runtime/plist/com.momentry.mariadb.plist index 73088f85..47afa901 100644 --- a/momentry_runtime/plist/com.momentry.mariadb.plist +++ b/momentry_runtime/plist/com.momentry.mariadb.plist @@ -2,31 +2,24 @@ - Label - com.momentry.mariadb - - UserName - accusys - - WorkingDirectory - /Users/accusys/momentry/var/mariadb - - ProgramArguments - - /opt/homebrew/opt/mariadb/bin/mariadbd-safe - --datadir=/Users/accusys/momentry/var/mariadb - - - RunAtLoad - - - KeepAlive - - - StandardErrorPath - /Users/accusys/momentry/log/mariadb.error.log - - StandardOutPath - /Users/accusys/momentry/log/mariadb.log + KeepAlive + + Label + com.momentry.mariadb + ProgramArguments + + /opt/homebrew/opt/mariadb/bin/mariadbd-safe + --datadir=/Users/accusys/momentry/var/mariadb + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/logs/mariadb.error.log + StandardOutPath + /Users/accusys/momentry/logs/mariadb.log + UserName + accusys + WorkingDirectory + /Users/accusys/momentry/var/mariadb diff --git a/momentry_runtime/plist/com.momentry.monitor.plist b/momentry_runtime/plist/com.momentry.monitor.plist index 24b080e4..56abdaca 100644 --- a/momentry_runtime/plist/com.momentry.monitor.plist +++ b/momentry_runtime/plist/com.momentry.monitor.plist @@ -2,48 +2,38 @@ - Label - com.momentry.monitor - - UserName - accusys - - WorkingDirectory - /Users/accusys/momentry_core_0.1/monitor - - ProgramArguments - - /bin/bash - /Users/accusys/momentry_core_0.1/monitor/control/monitor_control.sh - check - all - - - EnvironmentVariables - - PATH - /opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin - - - RunAtLoad - - - StartInterval - 300 - - KeepAlive - - SuccessfulExit - - - - StandardOutPath - /Users/accusys/momentry/log/monitor/monitor.log - - StandardErrorPath - /Users/accusys/momentry/log/monitor/monitor.error.log - - ProcessType - Background + EnvironmentVariables + + PATH + /opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin + + KeepAlive + + SuccessfulExit + + + Label + com.momentry.monitor + ProcessType + Background + ProgramArguments + + /bin/bash + /Users/accusys/momentry_core_0.1/monitor/control/monitor_control.sh + check + all + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/logs/monitor.error.log + StandardOutPath + /Users/accusys/momentry/logs/monitor.log + StartInterval + 300 + UserName + accusys + WorkingDirectory + /Users/accusys/momentry_core_0.1/monitor diff --git a/momentry_runtime/plist/com.momentry.ollama.plist b/momentry_runtime/plist/com.momentry.ollama.plist index 2c6fa6aa..9f16b528 100644 --- a/momentry_runtime/plist/com.momentry.ollama.plist +++ b/momentry_runtime/plist/com.momentry.ollama.plist @@ -2,43 +2,35 @@ - Label - com.momentry.ollama - - UserName - accusys - - EnvironmentVariables - - OLLAMA_HOST - 0.0.0.0:11434 - OLLAMA_MODELS - /Users/accusys/momentry/var/ollama/models - OLLAMA_FLASH_ATTENTION - 1 - OLLAMA_KV_CACHE_TYPE - q8_0 - - - WorkingDirectory - /Users/accusys/momentry/var/ollama - - ProgramArguments - - /opt/homebrew/opt/ollama/bin/ollama - serve - - - RunAtLoad - - - KeepAlive - - - StandardErrorPath - /Users/accusys/momentry/log/ollama.error.log - - StandardOutPath - /Users/accusys/momentry/log/ollama.log + EnvironmentVariables + + OLLAMA_FLASH_ATTENTION + 1 + OLLAMA_HOST + 0.0.0.0:11434 + OLLAMA_KV_CACHE_TYPE + q8_0 + OLLAMA_MODELS + /Users/accusys/momentry/var/ollama/models + + KeepAlive + + Label + com.momentry.ollama + ProgramArguments + + /opt/homebrew/opt/ollama/bin/ollama + serve + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/logs/ollama.error.log + StandardOutPath + /Users/accusys/momentry/logs/ollama.log + UserName + accusys + WorkingDirectory + /Users/accusys/momentry/var/ollama diff --git a/momentry_runtime/plist/com.momentry.postgresql.plist b/momentry_runtime/plist/com.momentry.postgresql.plist index 8a4dcf28..15b9f860 100644 --- a/momentry_runtime/plist/com.momentry.postgresql.plist +++ b/momentry_runtime/plist/com.momentry.postgresql.plist @@ -2,38 +2,30 @@ - Label - com.momentry.postgresql - - UserName - accusys - - EnvironmentVariables - - LC_ALL - en_US.UTF-8 - - - WorkingDirectory - /Users/accusys - - ProgramArguments - - /Users/accusys/pgsql/18.3/bin/postgres - -D - /Users/accusys/pgsql/data - - - RunAtLoad - - - KeepAlive - - - StandardErrorPath - /Users/accusys/momentry/log/postgresql.error.log - - StandardOutPath - /Users/accusys/momentry/log/postgresql.log + EnvironmentVariables + + LC_ALL + en_US.UTF-8 + + KeepAlive + + Label + com.momentry.postgresql + ProgramArguments + + /Users/accusys/pgsql/18.3/bin/postgres + -D + /Users/accusys/pgsql/data + + RunAtLoad + + StandardErrorPath + /Users/accusys/momentry/logs/postgresql.error.log + StandardOutPath + /Users/accusys/momentry/logs/postgresql.log + UserName + accusys + WorkingDirectory + /Users/accusys diff --git a/momentry_runtime/plist/com.momentry.qdrant.plist b/momentry_runtime/plist/com.momentry.qdrant.plist index bbfe97de..481252e8 100644 --- a/momentry_runtime/plist/com.momentry.qdrant.plist +++ b/momentry_runtime/plist/com.momentry.qdrant.plist @@ -28,9 +28,9 @@ RunAtLoad StandardErrorPath - /opt/homebrew/var/log/qdrant.error.log + /Users/accusys/momentry/logs/qdrant.error.log StandardOutPath - /Users/accusys/momentry/log/qdrant.log + /Users/accusys/momentry/logs/qdrant.log UserName accusys WorkingDirectory diff --git a/momentry_runtime/plist/com.momentry.redis.plist b/momentry_runtime/plist/com.momentry.redis.plist index bb0808c4..d4b995ae 100644 --- a/momentry_runtime/plist/com.momentry.redis.plist +++ b/momentry_runtime/plist/com.momentry.redis.plist @@ -11,22 +11,18 @@ /opt/homebrew/opt/redis/bin/redis-server --port 6379 - --bind - 0.0.0.0 + --requirepass + accusys + --appendonly + yes --dir - /Users/accusys/momentry/var/redis - --logfile - /Users/accusys/momentry/log/redis.log + /Users/accusys/momentry/var RunAtLoad StandardErrorPath - /Users/accusys/momentry/log/redis.error.log + /Users/accusys/momentry/logs/redis.error.log StandardOutPath - /Users/accusys/momentry/log/redis.log - UserName - accusys - WorkingDirectory - /Users/accusys/momentry/var/redis + /Users/accusys/momentry/logs/redis.log diff --git a/schema/schema.sql b/schema/schema.sql index 46df7d3c..e281e1ed 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -1781,7 +1781,10 @@ CREATE TABLE public.sessions ( api_key_id character varying(48) NOT NULL, created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, expires_at timestamp with time zone NOT NULL, - last_accessed_at timestamp with time zone + last_accessed_at timestamp with time zone, + ip_address text, + user_agent text, + source text ); diff --git a/scripts/embeddinggemma_server.py b/scripts/embeddinggemma_server.py index a0b97082..6769785c 100644 --- a/scripts/embeddinggemma_server.py +++ b/scripts/embeddinggemma_server.py @@ -12,20 +12,28 @@ MODEL = None TOKENIZER = None DEVICE = None -def load_model(model_path: str = "google/embeddinggemma-300m"): +def load_model(model_path: str = ""): global MODEL, TOKENIZER, DEVICE if MODEL is not None: return + import os + # 一律使用本地模型目錄,絕不上網 + local = os.path.expanduser("~/momentry/models/embeddinggemma-300m") + if not (os.path.isdir(local) and os.path.isfile(os.path.join(local, "config.json"))): + raise RuntimeError( + f"[EmbeddingGemma] Local model not found at {local}. " + "Please copy the model files (config.json, model.safetensors, tokenizer*) to this directory." + ) DEVICE = "mps" if torch.backends.mps.is_available() else "cpu" dtype = torch.float32 - print(f"[EmbeddingGemma] Loading model on {DEVICE} (dtype={dtype})...") + print(f"[EmbeddingGemma] Loading model from local: {local} on {DEVICE} (dtype={dtype})...") t0 = time.time() MODEL = AutoModel.from_pretrained( - model_path, + local, torch_dtype=dtype, trust_remote_code=True, ).eval().to(DEVICE) - TOKENIZER = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + TOKENIZER = AutoTokenizer.from_pretrained(local, trust_remote_code=True) print(f"[EmbeddingGemma] Loaded in {time.time()-t0:.1f}s on {DEVICE}") def embed(texts: list[str]) -> list[list[float]]: @@ -79,7 +87,6 @@ def health(): 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) + load_model() # 一律使用 ~/momentry/models/embeddinggemma-300m,絕不上網 app.run(host="0.0.0.0", port=args.port, threaded=True) diff --git a/scripts/face_clustering_processor.py b/scripts/face_clustering_processor.py index 8dc8ba4c..c4f9400d 100644 --- a/scripts/face_clustering_processor.py +++ b/scripts/face_clustering_processor.py @@ -171,7 +171,29 @@ def cluster_by_trace( return trace_embeddings, traces -def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) -> tuple: +def build_cooccurrence_constraints(frames_data: list) -> set: + """ + Build must-not-link constraints: traces appearing in same frame must be different persons. + Returns set of (trace_id_a, trace_id_b) pairs. + """ + constraints = set() + for frame in frames_data: + trace_ids = set() + for face in frame.get('faces', []): + tid = face.get('trace_id') + if tid is not None and tid >= 0: + trace_ids.add(tid) + # All traces in same frame must be different persons + trace_list = list(trace_ids) + for i in range(len(trace_list)): + for j in range(i+1, len(trace_list)): + constraints.add((min(trace_list[i], trace_list[j]), + max(trace_list[i], trace_list[j]))) + return constraints + + +def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15, + cooccurrence_constraints: set = None, frames_data: list = None) -> tuple: """ Single-stage AgglomerativeClustering on trace means. No Stage 2 merge (the problematic logic has been removed). @@ -210,13 +232,67 @@ def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) -> 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 + trace_similarities[trace_id] = 1.0 + + # Post-process: split clusters that violate co-occurrence constraints + if cooccurrence_constraints and len(cooccurrence_constraints) > 0: + print(f"[CLUSTER] Applying {len(cooccurrence_constraints)} co-occurrence constraints...") + next_person_id = max(trace_to_person.values()) + 1 + + for tid_a, tid_b in cooccurrence_constraints: + if trace_to_person.get(tid_a) == trace_to_person.get(tid_b): + # Same cluster but shouldn't be - split the one with fewer faces + count_a = trace_embeddings.get(tid_a, {}).get('face_count', 0) + count_b = trace_embeddings.get(tid_b, {}).get('face_count', 0) + if count_a <= count_b: + trace_to_person[tid_a] = next_person_id + print(f" Split trace {tid_a} from {tid_b} (faces: {count_a} vs {count_b})") + else: + trace_to_person[tid_b] = next_person_id + print(f" Split trace {tid_b} from {tid_a} (faces: {count_a} vs {count_b})") + next_person_id += 1 + + # Merge clusters that are actually the same person (high embedding similarity) + print(f"[CLUSTER] Merging similar persons (threshold={threshold*0.3:.2f})...") + merge_threshold = threshold * 0.3 # More conservative for merging + person_embeddings = {} + for tid, pid in trace_to_person.items(): + if tid in trace_embeddings: + if pid not in person_embeddings: + person_embeddings[pid] = [] + person_embeddings[pid].append(trace_embeddings[tid]['embedding']) + + # Compute person mean embeddings + person_means = {} + for pid, embs in person_embeddings.items(): + person_means[pid] = np.mean(embs, axis=0) + + # Find and merge similar persons + pids = list(person_means.keys()) + for i in range(len(pids)): + for j in range(i+1, len(pids)): + pid_i, pid_j = pids[i], pids[j] + emb_i = person_means[pid_i] + emb_j = person_means[pid_j] + sim = np.dot(emb_i, emb_j) / (np.linalg.norm(emb_i) * np.linalg.norm(emb_j)) + dist = 1 - sim + if dist < merge_threshold: + # Merge pid_j into pid_i + for tid in trace_to_person: + if trace_to_person[tid] == pid_j: + trace_to_person[tid] = pid_i + print(f" Merged Person_{pid_j} into Person_{pid_i} (dist={dist:.3f})") + + # Reindex person IDs + unique_pids = sorted(set(trace_to_person.values())) + pid_map = {old: new for new, old in enumerate(unique_pids)} + trace_to_person = {tid: pid_map[pid] for tid, pid in trace_to_person.items()} return trace_to_person, trace_similarities -def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tuple: +def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15, + cooccurrence_constraints: set = None) -> tuple: """ Seed-leader clustering with incremental mean centroids. Algorithm: @@ -302,6 +378,39 @@ def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tupl trace_to_person[tid] = person_label print(f"[CLUSTER] Seed-leader detected {len(persons)} unique persons") + + # Apply co-occurrence constraints: split traces that appear in same frame + if cooccurrence_constraints and len(cooccurrence_constraints) > 0: + print(f"[CLUSTER] Applying {len(cooccurrence_constraints)} co-occurrence constraints...") + + # Build trace_id -> person mapping for fast lookup + for tid_a, tid_b in cooccurrence_constraints: + person_a = trace_to_person.get(tid_a) + person_b = trace_to_person.get(tid_b) + if person_a is not None and person_b is not None and person_a == person_b: + # Same person but shouldn't be - split tid_b to new person + new_person_label = len(persons) + trace_to_person[tid_b] = new_person_label + # Move trace from old person to new person + old_person = persons[person_a] + if tid_b in old_person["member_trace_ids"]: + old_person["member_trace_ids"].remove(tid_b) + # Create new person with just this trace + if tid_b in trace_embeddings: + persons.append({ + "centroid": trace_embeddings[tid_b]['embedding'].copy(), + "member_trace_ids": [tid_b] + }) + print(f" Split trace {tid_b} from Person_{person_a} (co-occurs with trace {tid_a})") + + # Rebuild trace_to_person after splits + 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] After constraints: {len(persons)} unique persons") + return trace_to_person, trace_similarities @@ -466,13 +575,40 @@ def main(): # Select clustering method threshold = args.threshold method = args.method + + # Load face_traced.json to build co-occurrence constraints AND for later use + traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json") + cooccurrence_constraints = set() + traced_frames_dict = {} # Will be used later for person_id assignment + if os.path.exists(traced_path): + try: + with open(traced_path) as f: + traced_data = json.load(f) + frames_raw = traced_data.get('frames', []) + + # Build co-occurrence constraints + cooccurrence_constraints = build_cooccurrence_constraints(frames_raw) + print(f"[CONSTRAINT] Built {len(cooccurrence_constraints)} co-occurrence constraints from face_traced.json") + + # Also build traced_frames_dict for later use + if isinstance(frames_raw, list): + for frame_obj in frames_raw: + frame_num = frame_obj.get("frame") + if frame_num is not None: + traced_frames_dict[str(frame_num)] = frame_obj + elif isinstance(frames_raw, dict): + traced_frames_dict = frames_raw + except Exception as e: + print(f" Warning: Failed to load face_traced.json: {e}") + 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 + trace_embeddings, threshold=threshold, + cooccurrence_constraints=cooccurrence_constraints ) if not trace_to_person: print("Clustering produced no results.") @@ -484,35 +620,12 @@ def main(): 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}") - + # Use traced_frames_dict loaded earlier for person_id assignment 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_frame = traced_frames_dict.get(str(frame_num), {}) traced_faces = traced_frame.get("faces", []) for face_idx, face in enumerate(frame_obj.get("faces", [])): diff --git a/scripts/face_pipeline_check.py b/scripts/face_pipeline_check.py new file mode 100644 index 00000000..c7cabb09 --- /dev/null +++ b/scripts/face_pipeline_check.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python3.11 +""" +face_pipeline_check.py — Face Pipeline 逐步檢查工具 +檢查 face → face_traced → face_cluster → face_groups (DB/API) + +用法: + python3.11 face_pipeline_check.py [--api-key KEY] [--api-url URL] + python3.11 face_pipeline_check.py -q # 快速模式 +""" +import json +import sys +import os +import argparse +import urllib.request +import urllib.error + +OUTPUT_DIR = '/Users/accusys/momentry/output' +API_KEY_ENV = 'MOMENTRY_API_KEY' + + +def check_file(uuid): + """Step 0: 檢查檔案存在""" + files = { + 'face': f'{uuid}.face.json', + 'traced': f'{uuid}.face_traced.json', + 'cluster': f'{uuid}.face_cluster.json', + } + status = {} + missing = [] + for name, fname in files.items(): + path = os.path.join(OUTPUT_DIR, fname) + exists = os.path.exists(path) + status[name] = exists + if exists: + status[f'{name}_size'] = os.path.getsize(path) + else: + missing.append(fname) + return {'pass': len(missing) == 0, 'missing': missing, **status} + + +def check_face_json(uuid): + """Step 1: face.json 驗證""" + path = os.path.join(OUTPUT_DIR, f'{uuid}.face.json') + if not os.path.exists(path): + return {'pass': False, 'issues': ['face.json 不存在']} + + d = json.load(open(path)) + issues = [] + + total = d.get('total_faces', 0) + fc = d.get('frame_count', 0) + fps = d.get('fps', 0) + frames = d.get('frames') or [] + + if fc == 0: + issues.append('frame_count = 0(影片沒有被取幀)') + if fps > 0 and fps < 1: + issues.append(f'fps = {fps} (< 1,異常)') + if len(frames) != fc: + issues.append(f'frames 列表數量 {len(frames)} != frame_count {fc}') + + # embedding 檢查 + emb_total = 0 + emb_missing = 0 + emb_bad = 0 + for fr in frames: + for fa in fr.get('faces') or []: + emb_total += 1 + emb = fa.get('embedding') + if emb is None: + emb_missing += 1 + elif not isinstance(emb, list) or len(emb) != 512: + emb_bad += 1 + elif not all(isinstance(v, (int, float)) for v in emb): + emb_bad += 1 + + if emb_missing: + issues.append(f'embedding: {emb_missing}/{emb_total} faces 缺少') + if emb_bad: + issues.append(f'embedding: {emb_bad}/{emb_total} faces 非 512D 或格式異常') + + return { + 'pass': len(issues) == 0, + 'total_faces': total, + 'frame_count': fc, + 'embedding_total': emb_total, + 'embedding_missing': emb_missing, + 'embedding_bad': emb_bad, + 'issues': issues, + } + + +def check_face_traced(uuid, face_result): + """Step 2: face_traced.json 驗證""" + path = os.path.join(OUTPUT_DIR, f'{uuid}.face_traced.json') + if not os.path.exists(path): + return {'pass': False, 'issues': ['face_traced.json 不存在']} + + d = json.load(open(path)) + issues = [] + traces_raw = d.get('traces') or [] + # Normalize: dict (string keys) → list + if isinstance(traces_raw, dict): + traces = list(traces_raw.values()) + elif isinstance(traces_raw, list): + traces = traces_raw + else: + traces = [] + + if not traces: + issues.append('traces 為空(沒有產生任何 trace)') + return {'pass': False, 'trace_count': 0, 'issues': issues} + + # trace_id 唯一 + tids = [t['trace_id'] for t in traces] + if len(tids) != len(set(tids)): + issues.append(f'trace_id 重複: {len(tids)} rows, {len(set(tids))} unique') + + # confidence 範圍 & frame_count 合理性 + total_frames_traced = 0 + for t in traces: + fc = t.get('frame_count', 0) + if fc < 1: + issues.append(f'trace {t["trace_id"]}: frame_count = {fc} (< 1)') + total_frames_traced += fc + + bc = t.get('best_confidence', -1) + ac = t.get('avg_confidence', -1) + if not (0 <= bc <= 1): + issues.append(f'trace {t["trace_id"]}: best_confidence = {bc}') + if not (0 <= ac <= 1): + issues.append(f'trace {t["trace_id"]}: avg_confidence = {ac}') + + # face_instances 指向有效性(抽樣檢查) + all_face_ids = set() + face_json_frames = [] + if os.path.exists(os.path.join(OUTPUT_DIR, f'{uuid}.face.json')): + fd = json.load(open(os.path.join(OUTPUT_DIR, f'{uuid}.face.json'))) + for fr in fd.get('frames') or []: + for fa in fr.get('faces') or []: + fid = fa.get('face_id') + if fid: + all_face_ids.add(fid) + + orphan_instances = 0 + if all_face_ids: + for t in traces[:5]: # 抽樣前 5 筆 + for fi in t.get('face_instances', []): + if fi.get('face_id') and fi['face_id'] not in all_face_ids: + orphan_instances += 1 + if orphan_instances: + issues.append(f'face_instances: 抽樣發現 {orphan_instances} 個無效 face_id') + + return { + 'pass': len(issues) == 0, + 'trace_count': len(traces), + 'total_frames_traced': total_frames_traced, + 'issues': issues, + } + + +def check_face_cluster(uuid, traced_result): + """Step 3: face_cluster.json 驗證""" + path = os.path.join(OUTPUT_DIR, f'{uuid}.face_cluster.json') + if not os.path.exists(path): + return {'pass': False, 'issues': ['face_cluster.json 不存在']} + + d = json.load(open(path)) + issues = [] + clusters = d.get('clusters') or [] + frames = d.get('frames') or [] + + if not clusters: + issues.append('clusters 為空(可能 threshold 太高或人臉太少)') + + # cluster_id 唯一 + if clusters: + cids = [c['cluster_id'] for c in clusters] + if len(cids) != len(set(cids)): + issues.append('cluster_id 有重複') + + # similarity 結構檢查 + for c in clusters[:10]: # 抽樣 + sim = c.get('similarity') or {} + for key in ['min', 'avg', 'threshold']: + if key not in sim: + issues.append(f'cluster "{c["cluster_id"]}" 缺少 similarity.{key}') + elif not isinstance(sim[key], (int, float)): + issues.append(f'cluster "{c["cluster_id"]}" similarity.{key} 非數值') + + # frame faces 完整性 + frame_faces = [] + for f in frames: + for fa in f.get('faces') or []: + frame_faces.append(fa) + + if not frame_faces and clusters: + issues.append('clusters 有資料但 frames 中沒有 faces') + + # cluster_id 一致性 + if clusters: + valid_cids = set(c['cluster_id'] for c in clusters) + bad = sum(1 for fa in frame_faces if fa.get('cluster_id') not in valid_cids) + if bad: + issues.append(f'{bad} frame faces 的 cluster_id 不在 clusters 列表中') + + # trace_id 存在 + no_trace = sum(1 for fa in frame_faces if fa.get('trace_id') is None) + if no_trace: + issues.append(f'{no_trace} frame faces 缺少 trace_id') + + return { + 'pass': len(issues) == 0, + 'cluster_count': len(clusters), + 'frame_face_count': len(frame_faces), + 'issues': issues, + } + + +def check_api(uuid, api_key, api_url): + """Step 4: API 回應驗證""" + issues = [] + headers = {'X-API-Key': api_key} + url = f'{api_url}/api/v1/cluster-results?file_hash={uuid}' + + try: + req = urllib.request.Request(url, headers=headers) + with urllib.request.urlopen(req, timeout=30) as resp: + if resp.status != 200: + issues.append(f'cluster-results HTTP {resp.status}') + return {'pass': False, 'issues': issues} + d = json.loads(resp.read()) + except urllib.error.HTTPError as e: + issues.append(f'cluster-results HTTP {e.code}: {e.read().decode()[:200]}') + return {'pass': False, 'issues': issues} + except Exception as e: + issues.append(f'cluster-results 請求失敗: {e}') + return {'pass': False, 'issues': issues} + + groups = d.get('face_groups', []) + frames = d.get('frames', []) + + if not groups: + issues.append('face_groups 為空') + else: + # 檢查是否有群組 trace_ids 全空 + empty_groups = [g for g in groups if not g.get('trace_ids')] + if empty_groups: + issues.append( + f'{len(empty_groups)} 個群組 trace_ids 為空: ' + f'[{", ".join(g["name"] for g in empty_groups[:5])}]' + ) + + # frames faces 完整性 + f_faces = [] + for f in frames: + for fa in f.get('faces') or []: + f_faces.append(fa) + + no_trace = sum(1 for fa in f_faces if fa.get('trace_id') is None) + if no_trace: + issues.append(f'{no_trace} API frame faces 缺少 trace_id') + + # cluster_id → group_id 映射 + if groups and f_faces: + group_ids = {g['group_id'] for g in groups} + bad_cids = set() + for fa in f_faces: + cid = fa.get('cluster_id') + if cid and cid not in group_ids: + bad_cids.add(cid) + if bad_cids: + issues.append(f'{len(bad_cids)} frame faces 的 cluster_id 無法映射到 group_id') + + return { + 'pass': len(issues) == 0, + 'group_count': len(groups), + 'frame_count': len(frames), + 'total_traces': sum(len(g.get('trace_ids', [])) for g in groups), + 'issues': issues, + } + + +def main(): + parser = argparse.ArgumentParser(description='Face Pipeline 逐步檢查工具') + parser.add_argument('uuid', help='file_uuid 要檢查') + parser.add_argument('--api-key', default=os.environ.get(API_KEY_ENV, ''), + help=f'API key(預設取自 {API_KEY_ENV})') + parser.add_argument('--api-url', default='http://localhost:3002', help='API base URL') + parser.add_argument('--quiet', '-q', action='store_true', help='快速模式(只輸出 PASS/FAIL)') + args = parser.parse_args() + + if not args.api_key: + print(f'⚠️ 未提供 API key,設定 {API_KEY_ENV} 或使用 --api-key') + + results = {'uuid': args.uuid, 'steps': {}} + overall_pass = True + + # Step 0: 檔案存在 + r0 = check_file(args.uuid) + results['steps']['0_files'] = r0 + if not r0['pass']: + overall_pass = False + + # Step 1: face.json + r1 = check_face_json(args.uuid) + results['steps']['1_face_json'] = r1 + if not r1['pass']: + overall_pass = False + + # Step 2: face_traced.json + r2 = check_face_traced(args.uuid, r1) + results['steps']['2_face_traced'] = r2 + if not r2['pass']: + overall_pass = False + + # Step 3: face_cluster.json + r3 = check_face_cluster(args.uuid, r2) + results['steps']['3_face_cluster'] = r3 + if not r3['pass']: + overall_pass = False + + # Step 4: API/DB + r4 = check_api(args.uuid, args.api_key, args.api_url) + results['steps']['4_api'] = r4 + if not r4['pass']: + overall_pass = False + + # Print results + if args.quiet: + print('✅ PASS' if overall_pass else '❌ FAIL') + for name, r in results['steps'].items(): + if r.get('issues'): + for i in r['issues']: + print(f' {name}: {i}') + else: + print(f'\n{"=" * 60}') + print(f'Face Pipeline Check: {args.uuid}') + print(f'{"=" * 60}\n') + + for name, r in results['steps'].items(): + icon = '✅' if r.get('pass', True) else '❌' + print(f'{icon} {name}') + if r.get('issues'): + for i in r['issues']: + print(f' ⚠️ {i}') + for key in ['total_faces', 'frame_count', 'embedding_total', 'embedding_missing', + 'trace_count', 'cluster_count', 'frame_face_count', 'group_count', + 'frame_count', 'total_traces']: + if key in r: + print(f' {key}: {r[key]}') + print() + + print(f'Overall: {"✅ PASS" if overall_pass else "❌ FAIL"}\n') + + return 0 if overall_pass else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/api/admin_cleanup.rs b/src/api/admin_cleanup.rs new file mode 100644 index 00000000..06bd065e --- /dev/null +++ b/src/api/admin_cleanup.rs @@ -0,0 +1,242 @@ +// Admin Cleanup API Endpoints +use axum::{ + extract::State, + http::StatusCode, + response::Json, + routing::{get, post}, + Router, +}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::path::PathBuf; + +#[derive(Serialize)] +struct CleanupReport { + cleaned_files: usize, + cleaned_size_mb: f64, + orphaned_records: usize, + failed_jobs: usize, + details: Vec, +} + +#[derive(Deserialize)] +struct CleanupRequest { + cleanup_type: String, + dry_run: Option, +} + +// 清理垃圾檔案 +async fn cleanup_garbage( + State(state): State, + Json(req): Json, +) -> Result, StatusCode> { + let dry_run = req.dry_run.unwrap_or(false); + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let mut report = CleanupReport { + cleaned_files: 0, + cleaned_size_mb: 0.0, + orphaned_records: 0, + failed_jobs: 0, + details: Vec::new(), + }; + + // 1. 清理孤立的輸出檔案 + if req.cleanup_type == "garbage" || req.cleanup_type == "all" { + report.details.push("清理孤立輸出檔案...".to_string()); + + // 獲取所有 videos 的 file_uuid + let video_uuids: Vec = sqlx::query_scalar("SELECT file_uuid FROM videos") + .fetch_all(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + // 檢查 output 目錄中的檔案 + let output_path = PathBuf::from(output_dir); + if output_path.exists() { + for entry in std::fs::read_dir(&output_path).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? { + let entry = entry.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let path = entry.path(); + + if path.is_file() { + let filename = path.file_name().unwrap_or_default().to_string_lossy(); + // 檢查是否是孤立的 JSON 檔案 + if filename.ends_with(".json") && !filename.contains(".") { + // 簡化檢查:如果檔案名不是 UUID 格式,可能是垃圾檔案 + if !video_uuids.iter().any(|uuid| filename.starts_with(uuid)) { + let size = path.metadata().map(|m| m.len()).unwrap_or(0); + if !dry_run { + std::fs::remove_file(&path).ok(); + } + report.cleaned_files += 1; + report.cleaned_size_mb += size as f64 / 1024.0 / 1024.0; + report.details.push(format!("刪除: {}", filename)); + } + } + } + } + } + } + + // 2. 清理失敗的任務 + if req.cleanup_type == "jobs" || req.cleanup_type == "all" { + report.details.push("清理失敗的任務...".to_string()); + + let result = sqlx::query("DELETE FROM monitor_jobs WHERE status = 'failed' AND created_at < NOW() - INTERVAL '7 days'") + .execute(state.db.pool()) + .await; + + if let Ok(rows) = result { + report.failed_jobs = rows.rows_affected() as usize; + report.details.push(format!("刪除 {} 個失敗任務", report.failed_jobs)); + } + } + + // 3. 清理孤立的資料庫記錄 + if req.cleanup_type == "orphaned" || req.cleanup_type == "all" { + report.details.push("清理孤立記錄...".to_string()); + + // 清理沒有對應 video 的 processor_results + let result = sqlx::query( + "DELETE FROM processor_results pr + WHERE NOT EXISTS (SELECT 1 FROM videos v WHERE v.file_uuid = pr.file_uuid)" + ) + .execute(state.db.pool()) + .await; + + if let Ok(rows) = result { + report.orphaned_records = rows.rows_affected() as usize; + report.details.push(format!("刪除 {} 個孤立記錄", report.orphaned_records)); + } + } + + // 4. 清理舊日誌 + if req.cleanup_type == "logs" || req.cleanup_type == "all" { + report.details.push("清理舊日誌...".to_string()); + + let log_dir = PathBuf::from(output_dir).parent().unwrap_or(&PathBuf::from(".")).join("logs"); + if log_dir.exists() { + for entry in std::fs::read_dir(&log_dir).ok().into_iter().flatten() { + let entry = entry.ok(); + if let Some(entry) = entry { + let path = entry.path(); + if path.extension().map(|e| e == "log").unwrap_or(false) { + let modified = path.metadata().ok().and_then(|m| m.modified().ok()); + if let Some(modified) = modified { + let age = std::time::SystemTime::now().duration_since(modified).ok(); + if let Some(age) = age { + if age.as_secs() > 30 * 86400 && !dry_run { + std::fs::remove_file(&path).ok(); + report.cleaned_files += 1; + report.details.push(format!("刪除舊日誌: {:?}", path.file_name())); + } + } + } + } + } + } + } + } + + Ok(Json(report)) +} + +// 重置系統 +async fn reset_system( + State(state): State, + Json(req): Json, +) -> Result, StatusCode> { + let reset_type = req.cleanup_type.as_str(); + let mut result = json!({}); + + match reset_type { + "videos" => { + // 重置所有 videos + sqlx::query("UPDATE videos SET status = 'pending', cut_done = false, scene_done = false") + .execute(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + result = json!({"message": "All videos reset to pending"}); + } + "processor_results" => { + // 清空 processor_results + sqlx::query("DELETE FROM processor_results") + .execute(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + result = json!({"message": "All processor results cleared"}); + } + "jobs" => { + // 清空所有 jobs + sqlx::query("DELETE FROM monitor_jobs") + .execute(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + result = json!({"message": "All jobs cleared"}); + } + "all" => { + // 完全重置 + sqlx::query("DELETE FROM processor_results") + .execute(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + sqlx::query("DELETE FROM monitor_jobs") + .execute(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + sqlx::query("UPDATE videos SET status = 'pending', cut_done = false, scene_done = false") + .execute(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + result = json!({"message": "System fully reset"}); + } + _ => { + return Err(StatusCode::BAD_REQUEST); + } + } + + Ok(Json(result)) +} + +// 獲取系統統計 +async fn get_system_stats( + State(state): State, +) -> Result, StatusCode> { + // 統計資訊 + let video_count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM videos") + .fetch_one(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let job_count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM monitor_jobs") + .fetch_one(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let failed_job_count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM monitor_jobs WHERE status = 'failed'") + .fetch_one(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let orphaned_count: (i64,) = sqlx::query_as( + "SELECT COUNT(*) FROM processor_results pr + WHERE NOT EXISTS (SELECT 1 FROM videos v WHERE v.file_uuid = pr.file_uuid)" + ) + .fetch_one(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(Json(json!({ + "videos": video_count.0, + "total_jobs": job_count.0, + "failed_jobs": failed_job_count.0, + "orphaned_records": orphaned_count.0 + }))) +} + +pub fn router(state: crate::api::types::AppState) -> Router { + Router::new() + .route("/cleanup", post(cleanup_garbage)) + .route("/reset", post(reset_system)) + .route("/stats", get(get_system_stats)) + .with_state(state) +} diff --git a/src/api/admin_config.rs b/src/api/admin_config.rs index ced384d6..c0fc27ec 100644 --- a/src/api/admin_config.rs +++ b/src/api/admin_config.rs @@ -23,6 +23,9 @@ pub fn admin_config_routes() -> Router { ) .route("/api/v1/admin/config/reload", post(reload_config)) .route("/api/v1/admin/settings", get(get_settings)) + .route("/api/v1/admin/llm/test", post(test_llm_endpoint)) + .route("/api/v1/admin/users/active", get(active_sessions)) + .route("/api/v1/admin/users/active/revoke", post(revoke_session)) } pub async fn get_config(State(state): State) -> Result, StatusCode> { @@ -47,8 +50,135 @@ pub async fn update_config( } } -pub async fn get_vlm_prompts(State(state): State) -> Result, StatusCode> { - let prompts = state.admin_config_manager.get_all_vlm_prompts().await; +#[derive(serde::Deserialize)] +struct LlmTestRequest { url: String, + /// Test kind: "chat" (translation sample), "vlm" (image recognition + /// sample), or "ping" (connectivity only, max_tokens=1). + #[serde(default)] + kind: Option, + /// Optional per-call timeout override (seconds, capped at 120). + #[serde(default)] + timeout_secs: Option, +} + +/// A valid 220×72 PNG used as the effective vision sample: solid red +/// background with white text "MOMENTRY 42" (generated offline with PIL and +/// verified). Lets the VLM test exercise the real mmproj path for BOTH +/// OCR-style text reading and color recognition. +const TEST_SAMPLE_PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAASwAAAB4CAIAAADHd1h3AAARgUlEQVR4nO2deVSU1/nH33lnAWYYBmZYlEUQEUEIiWuXxGBjYowkWCNN4+lJqdTYJoYmVjSxLlQljTVpbVxiSXJOo2lTt564hha0WusaaYiIioKDLIKyDDDMMDPM9jvDZa7zg9lglvsy83wOf9xhLu888/h+733uc5/7yro0bhwFAAA5aIKfDQAAiBAAyAMzIQAQBkQIAIQBEQIAYUCEAEAYECEAEAZECACEARECAGE4rl9Ckp2dtGMHfqmqra2cM8fJv520Z0/o7Nn4Zd3ata1//aud/jSPFzZ3rigzk5+WFhATww4ONhoMBoVC09ysqq7uvnixs7RUL5eTsnbat99ywsKoYaJtb/9m2jT8MuS7303dvx+1jXp91fPP9964Yf8KHLF4WkUFat/Iyem5coWiqKjc3IRNm6iR0rx7d+OWLaidUVYWlJxsv79RrzcolZp795TXrnWWlnaeOkUZDPhdtlD46Jkz3PBwiqIMfX3Xnn5aXV/vjBlJ27dLFixA7YaiopZPPqG8As3jhc6ZI87K4qekcCMj2Xy+rrNT3dgov3Ch7cABTUMDs0Q4iKCkJH5KSm91tePPDg0VPfGEk5dlcThjliyJXr580F3OoihaLOaIxYL09PCcHING07ZvX9Of/qSTyQha6y5YbPb4d9+9/uKLlNFIMRsWm80OCeGHhPBTUyNeeklRUSF9+23VrVvoXX1PT+OWLYkffIDu7/jCwlt5eQ6vKZw5EytQVVt7/y9/cdFItkCQXlISGB9PUdS3jz+uaWqy2k2QljZhx46gCRMsf8mNjORGRgqnTYt+7bXm3bub/vAHd/2jeCQcFT//vDPdwp59lsVxahTgRUVNPnRo3Lp1DucZOiAgKjc34+TJkO9/n5S17iV46tSIH/2IGm0ET5ky+eDBwPHj8W/aDh1SfPMNaofOmRP61FP2r8Bisy1n8vrCQqNO56JV4997DynQDoL09MlffjlIgf/PMA4nJj/flShjEB65qyRZWU39Y56Dbs7d/dzIyNSDBy191/Xvf8tKSnrKy7WtrUadjhsezk9NDXvmGcnChTSPZ/oTiSRl797br77adfq0l61FNH3wwT2LoNdFxq1Z01laquvqGtZfPdiz58GePVbfStm7V5SZaZpebt+ufOYZ56/ZcexY7RtvWH2LxeVyw8OFM2dG//KX/MmTTfeWSJS0fXvVCy8M9DAa765fn37sGEWbhv74wkL5uXOGvj5bnxX1yiv81FTUlpWUdJ87R7lGxI9/jOdVW9B8/sTdu+mAAPSy7cCBtv37VbW1ht7egLg4cVZW9Ouv00FBJvN++tPus2c7y8qYNRPqZDJteztFUYGJidh9tuCEhaHJyqBS9bW02OrG4nCSi4uxAtVS6fWFC28tWdJ24IBaKtUrFAa1WtPU1FlWJl29uvKpp+Tnzw/8IZc78aOPAhMSvGmt20FTB0csjlu9mmI2Rq22r6Wl48iRquxshXmBKsjIEDzyCO6jrKpq/fvfUTswIWHsL35h62pciSR25UrUNqhU9S5PO0FJSQkbNzrsFvnyywHmc0V3Vq6UrlrVU16u6+oy9PWp7ty5t337jZwcvVKJOsStWkWxWMwSodFolJWUoLYEj382EM+bh6K7zlOnDGq1rW5RubnBU6eitqKi4vrChTikGYqmsbE6N1f2z3+ilzSfn7B5szetdTv1GzcaNBrTzbF4seDRR6nRgFGrxRkdlGeyfLfx/ffxlB69fDkvOtrqReLeeYcdEoLazbt29TU3u2ISHRCQtGsXmsHsI8nORo3Of/2r/dChoR2UVVXNO3eidtCkSYL+OZ9BImSx2bLjx1FbnJXl5EpMdvw4i8222ocTFha7YgVq62Sy28uWOQzJjFrtnbfeUkul6KXoySdDHn/cO9Z6AnVDQ/OuXaYWTY8vKkKBHPPpKS/HqVHe2LGWb+k6Oxvffx+16aCg+PXrh/558GOP4WWwpqGhpbjYRXviCwv5KSkURbUfPmynG83jCTIyULv9yy9tdes4evShqRZpbWaIkMuVf/21trUVBRuC9HRbPTliMRog9Upl1+nTthIeETk5bKEQteuLitCVHWJQqerWrcMvIxcv9o61HqJl92713bsotIv6yU+o0YBRp9P39qL2UHe1fvGFsqoKtcXz5w8eJVksU87DHOaZYgHb60ZnEM+fH9nvN+XVq42//72dngHx8XiEVVy9aqub5t49PMSgTRcmiZDDoQwGHOPZyTri6K6rP7qzKULzcKhtb7ccfhwiP38e762FzZ3L4nK9YK2HMPT11RcWonbsqlVciYRiPDSPxxYIUFszNJI0GO6uW4fz+wmbNlm6NPLll3Hg3XX6dOfJk65YEhAbm7h1q2kAVShq3njDqNXa6cwJDcUW2hnxTWGtOSTRKxSumDdwQcp9IFd2HDvmMJ2I3+pAAaG1AI8bHh40aRJqy0pK7LtvKLKvvkINOiDAat7FvdZ6lK4zZ9BClyMSxa1ZQzEeUxLLPJUprU0pioqK9n/8A7WDkpLGLFmC2qYvaE5BmUaf3/7WFTNYHE7Szp0omKpbs8bhDnvPlSuX4+NNP+PH29kOCX3ySdxW3blDMW1NiNYDfffvmwahuDiruQSuRCI0R3fdZ86Y/tDaUid4yhTcxtk250FVIwhBWpqnrfU0pqisP8CLyMkRTp9OMRi2UBj3zjuoraqtlV+8aLVbw+9+p+/pQe2YFSu4kZGmqb6ggCMWo1/e//hjFIePmLjVq9Fd1Lpv37AiKTvQfH7sqlWorVco5BcuuOGalNsxGvEsZHV6CXvuOSSArpMnUerPKoGJibjtsG5rKGqLYc9e4O4mawcRW1Dwnfp6Z35whZp9+pqb723fbmqxWAlFRd5MDjkJHRQUlJw85uc/zygtRaGHQaORFhTY6q/t6Gj64x9Rmy0QjPvNb/ipqWjxNvB9zUnIkSHKzBy7bJlpIKipcXFGxbCFwkmffhqUlIRethQXG1Qq1y/rkUEdx3hWs44Po7sTJ+xchCMS4bauu3u4NljmUXGy23PWeoGWTz5R1dZSFMVPTY3KzSVig+SFF2yNJjOqqzPKyuI3bEC7Dtr29ttLl9oPYR7s3YsLBsMXLpz45z/jwaW+qMiV+5sbETFh2zaKxTKo1TXLl7tFKsJp0x756iucRuq5fLn5o49cv6ynRKioqEAbOwExMZZR5UB0N3OmZXRnC5wXNXUevgidX0O6xVovYNTpTPmMfmJXrkTxG2NpKS52WONi1OlwzgnlqFFDfuGCzJUhj6aTPvwQZbDqN27E9asjhh0cnLBp0+RDh/A+fve5c7fy8lwvo0N4JtFnNHacODH21VfRTGI5HIqzstBo11lWZj+6Q0sghNX0pn2GMZG6w1qPlq1h5Bcvdhw5IlmwgB0cHL9uXe2vfkUxlXFr14qeeOL2smX2axvkly51HD2Kt8gHxpoNG1z56Jjly9F8JTtxovWLL1yf/OM3bMBDnlGnu/fhh6ZQ2eKMiIt4KseARzJTjGdR2oNDPrxR7kw8aakoJ+FFRVm9lIes9Rr1RUUoLS5ZsCDke9/z8qd3HDs2kD8c8nMlOfnbWbOkq1fj5L4oMzP21792eM2Gd9/FhWCmGPWzz1Q1NSO2UDh9ekx/gYemsVH69tsubm+kfP550s6dWIE9//tfVVaWaXHuPgV6UISKigp0ToQ3dqzQXHfGDQ8PQdGdQtH9n//Yv0Lfgwe4HWi7pN0WliWLKkcnlVy31mtoW1txPsOUoSFxsMMqBo1G09DQtn//9UWLsKgc1gNSFNV3/36buaDUFERs2zZiG2geL2nHDhabbdTpavPzcfZ1BIS/+OIjpaUi826Etr1dWlBwY9EiZ069DRcPZtsfTi/mfwnx/Plol7OztNRhGYRlWIjLR51HaJ4ljDqd8to1T1vrTR589lnvzZsDO2xLl1IMQ9PQ0HHkCGrzoqOdqdjUW2x5u7L9TQcHo7QQi8NJO3x4aPZoank57vzY+fPolxlDTkLErlgxYds2VG9g1Ovvf/rp1czMtoMHPXSq04MiHNjaRndzf4w3eNfbLuq6OnTKAZ02GtZH04GBYeYTOj1XrjiznHPRWm9i1OtxxUnsm2/aqoEmiLKy0koZyihhzJIlMW+99fDUTnZ2/ebNbqmMISBCZWUleoQBLypKOGOG6VTyjBmmoU4u7z571pkr4AE1MDFRNGuW8x8duXgxLptycmnuurXepKe8vK2/xp/m8+NdS2N4Aq3FYw3owEBq9BCYmDjOnIKWX7pUlZ2Ny1w9h2dXFLITJ6Jffx3NKqaTDebozsn9gweffz4mLw/NS/GFhdfmzXMmKcwWCqPz81G7r6UFV4d62lov0/jee2Fz53JEIvFzz3WaT28xBINFosWbItTJZJftHpxnCwTTzYUfVh9vEZOfj5bZqjt3buflWWaMPIdnK7AenhWaP19sTkM7H92p6+pMgXg/QRMnjt+yxfEZSppO2rEDVznfXb/eeQm5aK2XMVWcmM8E4cGbIVjeu6NoJqQDAsKefRa169as8Y4CPS5C5fXr6ro6VMEg7D95pevu7v7vf52/Qv3mzai2Ex2qmLhrl51Naq5EklxcHPqDH6CXHUeODOvpA65b62Ue/O1vKOfEjYigmAQ+xzSo6ILhiGbPRquY3ps3ey5f9trnejzB3XH8eIw5OEQHlodVZ6CXy28vXZqydy+q6xVnZYlmz+44erTr9GlVdbVWJjNqNJzw8MD4+LB588J/+EOcBuj5+mvp8B8J4aK1mNiCgljbZZNDqZw7dySFHQZD3dq16YcPM+2wr+XeQNDEiQxcVFsF707xU1O/49wTGR0+pNMZPP6PN6j+aATlSMpr164vWoTPobAFgsjFi5M//vjRs2enV1XNqKmZcvFi6r59Y372M6zAjqNHq195ZQTPoXDdWi+jvHoVP7WFOVg+b3JMXl5ATAw1Gghw9CA2D+FxEfbevInPXOm6ukb2zCy1VFr59NONW7c6zBSrpdKa116rzc8f2ZNg3GKtl2ncutXJh6x6DYNajWrNUd1JzJtvUqOBQEIiZI2u/7OeLRCIZs0KnTOHn5bGlUhQjKqXy9V37yoqKrpOnZJfusT85+QCwCgWIQD4Hsxa0AOAHwIiBADCgAgBgDAgQgAgDIgQAAgDIgQAwoAIAYAwIEIAIAyIEAAIAyIEAMKACAGAMCBCACAMiBAACAMiBADCgAgBgDAgQgAgDIgQAAgDIgQAwoAIAYAwIEIAIAyIEAAIAyIEAMKACAGAMCBCACAMiBAACAMiBADCgAgBgDAgQgAgDIgQAAgDIgQAwoAIAYAwIEIAIAyIEAAIAyIEAMKACAGAMCBCACAMQ0X40oFxpE0YNYCvRruvaMZ6ipn+YhrgKx/wFRNFCAB+BeNEaDlQMXDQYhTgK9/wFbNEONQ7TPMXcwBf+YyvmCVCAPBDGCRCW4MTowYthgC+8iVfMUWE9j3CHH8xAfCVj/mKESJ0xhcM8RdxwFe+5ytGiBAA/BnyInR+KGLCoEUW8JVP+oqwCIf7/Yn7iyDgK1/1FfmZEAD8HJIiHNnw45+TIfjKh31FTISufGd/0yH4yrd9BeEoABCGjAhdH3L8ZzIEX/m8rwiI0F3f0x90CL7yB19BOAoAhPG2CN07zPj2ZAi+8hNfeVWEnvhuvqpD8JX/+Mp7IvTct/I9HYKv/MpXsCYEAMJ4SYSeHlR8aTIEX/mbr7whQu98E9/QIfjKD30F4SgAEIb2pQlqtE+G4Cv/9BXtY6oYvToEX/mtryAcBQDC0L43KY3GyRB85c++on1SCaNLh+ArP/cV7asaYIINo8VOJtgwWuz0hA2wJgQAwtA+OVwxzRLmW8gcS5hvodstoX3VU8y0h8m2Mc0eJtvmXnsgHAUAwtA+PFwhwCrwFcPvK9alcUxUDgD4DxCOAgBhQIQAQBgQIQAQBkQIAIQBEQIAYUCEAEAYECEAEAZECAAUWf4P+yjA+Rd4YX4AAAAASUVORK5CYII="; + +/// POST /api/v1/admin/llm/test — verify an LLM endpoint with an effective +/// sample, sent **from the server side** (avoids browser CORS limits and +/// tests from the same network position as real routing): +/// - kind=chat: a short EN→zh-TW translation task (real text capability). +/// - kind=vlm: an image-recognition task over a real red PNG (exercises the +/// mmproj vision path); the answer is checked for the expected color. +/// - kind=ping: minimal max_tokens=1 request (connectivity only). +pub async fn test_llm_endpoint( + Json(req): Json, +) -> Result, StatusCode> { + let url = req.url.trim().to_string(); + if url.is_empty() || !url.starts_with("http") { + return Ok(Json(json!({"ok": false, "error": "invalid URL"}))); + } + let kind = req.kind.as_deref().unwrap_or("ping"); + let timeout = std::time::Duration::from_secs(req.timeout_secs.unwrap_or(45).clamp(1, 120)); + + let body = match kind { + "chat" => json!({ + "messages": [ + {"role": "system", "content": "You are a translator. Reply with the translation only, no explanations."}, + {"role": "user", "content": "Translate into Traditional Chinese: The weather is very nice today."} + ], + "temperature": 0.1, + "max_tokens": 64, + "stream": false, + "chat_template_kwargs": {"enable_thinking": false} + }), + "vlm" => json!({ + "messages": [ + {"role": "user", "content": [ + {"type": "text", "text": "Look at this image. 1) What text is written on it? 2) What is the background color? 3) What geometric shape is drawn, and how many of them are there? Answer exactly as: | | "}, + {"type": "image_url", "image_url": {"url": format!("data:image/png;base64,{}", TEST_SAMPLE_PNG_B64)}} + ]} + ], + "temperature": 0.1, + "max_tokens": 32, + "stream": false, + "chat_template_kwargs": {"enable_thinking": false} + }), + _ => json!({ + "messages": [{"role": "user", "content": "ping"}], + "max_tokens": 1, + "stream": false, + "chat_template_kwargs": {"enable_thinking": false} + }), + }; + + let client = reqwest::Client::new(); + let start = std::time::Instant::now(); + let res = client.post(&url).json(&body).timeout(timeout).send().await; + let latency_ms = start.elapsed().as_millis() as u64; + match res { + Ok(r) => { + let status = r.status().as_u16(); + if !r.status().is_success() { + let text = r.text().await.unwrap_or_default(); + let short: String = text.chars().take(200).collect(); + return Ok(Json(json!({"ok": false, "kind": kind, "status": status, "latency_ms": latency_ms, "error": short}))); + } + // Verify the response actually contains usable content. + let parsed: Value = r.json().await.unwrap_or(Value::Null); + let content = parsed + .get("choices") + .and_then(|c| c.get(0)) + .and_then(|c| c.get("message")) + .and_then(|m| m.get("content")) + .and_then(|c| c.as_str()) + .unwrap_or("") + .trim() + .to_string(); + if content.is_empty() { + return Ok(Json(json!({"ok": false, "kind": kind, "status": status, "latency_ms": latency_ms, "error": "empty content"}))); + } + // For the VLM sample, verify each part of the answer: OCR text + // ("MOMENTRY 42"), background color (red), shape (triangle) and + // the count (3). All four must match. + let matches_expected = if kind == "vlm" { + let lc = content.to_lowercase(); + let text_ok = lc.contains("momentry") || lc.contains("42"); + let color_ok = lc.contains("red"); + let shape_ok = lc.contains("triangle"); + let count_ok = lc.contains('3') || lc.contains("three"); + Some(json!({ + "text": text_ok, + "color": color_ok, + "shape": shape_ok, + "count": count_ok, + "all": text_ok && color_ok && shape_ok && count_ok + })) + } else { + None + }; + Ok(Json(json!({ + "ok": true, + "kind": kind, + "status": status, + "latency_ms": latency_ms, + "content": content.chars().take(120).collect::(), + "matches_expected": matches_expected + }))) + } + Err(e) => Ok(Json(json!({ + "ok": false, + "kind": kind, + "latency_ms": latency_ms, + "error": e.to_string() + }))), + } +} + +pub async fn get_vlm_prompts(State(state): State) -> Result, StatusCode> { let prompts = state.admin_config_manager.get_all_vlm_prompts().await; Ok(Json(serde_json::to_value(prompts).unwrap_or_default())) } @@ -102,3 +232,78 @@ pub async fn get_settings( ) })?)) } + +/// GET /api/v1/admin/users/active — currently-valid login sessions with +/// inbound IP, connection type (browser/app) and session open time. +pub async fn active_sessions( + State(state): State, +) -> Result, StatusCode> { + match state.db.get_active_sessions().await { + Ok(rows) => { + let sessions: Vec = rows + .iter() + .map(|r| { + let ua_l = r.user_agent.to_lowercase(); + let conn_type = if r.source == "app" + || ua_l.contains("momentry") + || ua_l.contains("tauri") + { + "app" + } else { + "browser" + }; + // Short client description: browser name or raw UA tail + let client = if ua_l.contains("momentry") || ua_l.contains("tauri") { + "Momentry App".to_string() + } else if ua_l.contains("edg/") { + "Edge".to_string() + } else if ua_l.contains("chrome") { + "Chrome".to_string() + } else if ua_l.contains("safari") && ua_l.contains("mac") { + "Safari".to_string() + } else if ua_l.contains("firefox") { + "Firefox".to_string() + } else if r.user_agent.is_empty() { + "Unknown".to_string() + } else { + r.user_agent.chars().take(40).collect() + }; + serde_json::json!({ + "session_id": r.session_id, + "username": r.username, + "role": r.role, + "ip": r.ip_address, + "connection": conn_type, + "client": client, + "opened_at": r.created_at.to_rfc3339(), + "expires_at": r.expires_at.to_rfc3339(), + }) + }) + .collect(); + Ok(Json(json!({ "sessions": sessions, "total": sessions.len() }))) + } + Err(e) => { + tracing::error!("[ADMIN] active sessions query failed: {}", e); + Err(StatusCode::INTERNAL_SERVER_ERROR) + } + } +} + +#[derive(serde::Deserialize)] +struct RevokeSessionRequest { + session_id: String, +} + +/// POST /api/v1/admin/users/active/revoke — force-logout one session. +pub async fn revoke_session( + State(state): State, + Json(req): Json, +) -> Result, StatusCode> { + match state.db.delete_session(&req.session_id).await { + Ok(_) => Ok(Json(json!({ "success": true, "message": "Session revoked" }))), + Err(e) => { + tracing::error!("[ADMIN] revoke session failed: {}", e); + Err(StatusCode::INTERNAL_SERVER_ERROR) + } + } +} diff --git a/src/api/agent_search.rs b/src/api/agent_search.rs index 1d6eba45..279d9746 100644 --- a/src/api/agent_search.rs +++ b/src/api/agent_search.rs @@ -80,26 +80,17 @@ pub struct AgentSearchResponse { // ── Tool Definitions ────────────────────────────────────────────── -const SYSTEM_PROMPT: &str = r#"你是 Momentry 影片分析助手。回答用戶關於影片內容的問題。 +const SYSTEM_PROMPT: &str = r#"## Core Principles +- **All queries default to searching ALL videos** — do not ask which video +- If multiple videos found, list all results directly +- Only ask user when ALL search tools return empty AND question clearly targets a specific video +- Search tools (smart_search, semantic_search, trace_search) can omit file_uuid to search all -## Greeting and Conversation Handling (CRITICAL - Check First) -- If user input is ONLY a greeting ("hi", "hello", "hey", "你好", "您好", "hallo"): - - **DO NOT call any search tools** - - Respond in English: "Hello! I'm Momentry video analysis assistant. I can help you search video content, find people, and analyze scenes. What would you like to know?" -- If user asks "how are you" or "thanks", respond briefly in English without tools -- **Only use search tools when user asks about VIDEO CONTENT** - -## Response Language (MANDATORY) -- **DEFAULT: English** - You MUST respond in English unless user explicitly requests another language -- This applies to ALL responses: greetings, search results, explanations -- Example: If user asks "gun", respond in English about gun-related content -- Only respond in Chinese if user writes in Chinese AND explicitly requests Chinese response - -## 核心原則:預設搜尋所有影片,不主動反問 -- **所有查詢都預設搜尋全部影片**,不要問用戶「哪部影片」 -- 如果搜尋到多部影片,直接列出所有結果,不要反問用戶選擇 -- 只有當多個搜尋工具都返回空、且問題明顯指向特定影片時,才問用戶 -- 搜尋工具(smart_search, semantic_search, trace_search)的 file_uuid 參數可省略以搜尋全部 +## Search Tool Usage +- Use search tools when user asks about VIDEO CONTENT +- For greetings ("hi", "hello", "hey"), do NOT call tools — respond conversationally +- For "how are you" or "thanks", respond briefly without tools +- Always include relevant file_name, timestamps, and descriptions in search results ## 搜尋工具選擇策略(重要:根據問題類型選擇正確工具) @@ -194,7 +185,7 @@ fn build_system_prompt(language: &str) -> String { ), }; - format!("{}\n\n{}\n\n{}\n\n{}", intro, greeting_instruction, language_instruction, SYSTEM_PROMPT) + format!("{}\n\n{}\n\n{}\n\n{}", intro, greeting_instruction, SYSTEM_PROMPT, language_instruction) } fn make_tools(pool: &sqlx::PgPool) -> Vec { @@ -527,18 +518,37 @@ async fn agent_search( ) -> Result, (StatusCode, Json)> { let (conv_id, history) = get_or_create_conv(req.conversation_id.as_deref()); - let language = req.output_language - .as_deref() - .unwrap_or("en"); + // ── Language handling ── + // VLM 準備的語言: English (vlm_description) + 日本語 (vlm_description_localized) + // UI 語言 → 卡片語言映射: + // ja → 日文 (vlm_description_localized) + // en → 英文 (vlm_description) + // zh-TW → 日文+英文雙語(VLM 無繁中,日文漢字最接近) + let mut language = req.output_language.as_deref().unwrap_or("en"); + + // 確認語言有效性 — 只支援 en/ja/zh-TW + if !matches!(language, "en" | "ja" | "zh-TW") { + language = "en"; + } let system_prompt = build_system_prompt(language); - tracing::info!("[AGENT] Using language: {}", language); + + // 在 user query 前加入語言提醒 — LLM 容易跟隨查詢語言,需要明確指令 + let lang_reminder = match language { + "ja" => "\n\n[IMPORTANT: You MUST respond in Japanese (日本語). Do NOT respond in Chinese or English.]", + "zh-TW" => "\n\n[IMPORTANT: You MUST respond in Traditional Chinese (繁體中文). Do NOT respond in Japanese or English.]", + _ => "\n\n[IMPORTANT: You MUST respond in English.]", + }; + let user_query_with_lang = format!("{}{}", req.query, lang_reminder); + + tracing::info!("[AGENT] Using language: {} (cards: {})", language, + if language == "ja" { "ja" } else if language == "zh-TW" { "ja+en" } else { "en" }); let timeout_duration = std::time::Duration::from_secs(60); let result = tokio::time::timeout( timeout_duration, - run_tool_loop(state.db.pool(), &system_prompt, &req.query, history) + run_tool_loop(state.db.pool(), &system_prompt, &user_query_with_lang, history) ).await; let (answer, messages, sources) = match result { diff --git a/src/api/auth.rs b/src/api/auth.rs index e10f19da..214b4822 100644 --- a/src/api/auth.rs +++ b/src/api/auth.rs @@ -31,8 +31,29 @@ struct UserInfo { async fn login( State(state): State, + axum::extract::ConnectInfo(addr): axum::extract::ConnectInfo, + headers: axum::http::HeaderMap, Json(req): Json, ) -> Result, (StatusCode, Json)> { + // ── Session tracking: inbound IP, User-Agent, connection source ── + let login_ip = headers + .get("x-forwarded-for") + .and_then(|v| v.to_str().ok()) + .map(|v| v.split(',').next().unwrap_or(v).trim().to_string()) + .or_else(|| headers.get("x-real-ip").and_then(|v| v.to_str().ok()).map(|s| s.to_string())) + .unwrap_or_else(|| addr.ip().to_string()); + let login_ua = headers + .get("user-agent") + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_string(); + // Tauri desktop app identifies itself in its UA; everything else is a browser. + let ua_l = login_ua.to_lowercase(); + let login_source = if ua_l.contains("momentry") || ua_l.contains("tauri") { + "app".to_string() + } else { + "browser".to_string() + }; let (user_id, username, role) = 'resolve: { if let Ok(Some((uid, uname, pw_hash, role_str))) = state.db.get_user_by_username(&req.username).await @@ -46,7 +67,7 @@ async fn login( ); } - if req.username == "demo" && req.password == "demo" { + if req.username == "demo" && req.password == "demo123" { let uid = state .db .get_user_by_username("demo") @@ -78,7 +99,15 @@ async fn login( let session_id = uuid::Uuid::new_v4().to_string().replace('-', ""); state .db - .create_session(&session_id, user_id, &DEMO_USER_API_KEY, 24) + .create_session_with_meta( + &session_id, + user_id, + &DEMO_USER_API_KEY, + 24, + login_ip.as_str(), + login_ua.as_str(), + login_source.as_str(), + ) .await .ok(); diff --git a/src/api/cluster_agent.rs b/src/api/cluster_agent.rs index 4af76b0e..43d899ef 100644 --- a/src/api/cluster_agent.rs +++ b/src/api/cluster_agent.rs @@ -295,6 +295,27 @@ pub async fn trigger_cluster_agent( success_count, error_count ); + + // Also reset group_id so materializer can re-create groups from new clusters + let tp_table = schema::table_name("trace_profiles"); + let _ = sqlx::query(&format!( + "UPDATE {tp_table} SET group_id = NULL WHERE file_uuid = $1 AND trace_id = ANY($2)" + )) + .bind(&file_uuid) + .bind(&all_trace_ids.iter().map(|tid| *tid as i32).collect::>()) + .execute(state.db.pool()) + .await; + tracing::info!("[ClusterAgent] Reset group_id for {} traces", all_trace_ids.len()); + + // Also delete old face_groups so materializer can create fresh groups + let fg_table = schema::table_name("face_groups"); + let _ = sqlx::query(&format!( + "DELETE FROM {fg_table} WHERE file_uuid = $1" + )) + .bind(&file_uuid) + .execute(state.db.pool()) + .await; + tracing::info!("[ClusterAgent] Deleted old face_groups for {}", file_uuid); } } } diff --git a/src/api/directory_browser.rs b/src/api/directory_browser.rs new file mode 100644 index 00000000..bd01fc18 --- /dev/null +++ b/src/api/directory_browser.rs @@ -0,0 +1,338 @@ +use axum::{ + extract::{Query, State}, + http::StatusCode, + response::Json, + routing::{get, post}, + Router, +}; +use serde::{Deserialize, Serialize}; +use std::path::Path; +use std::collections::HashMap; + +use crate::api::types::AppState; + +#[derive(Debug, Serialize, Deserialize)] +pub struct DirEntry { + pub name: String, + pub path: String, + pub is_dir: bool, + pub size: Option, + pub entry_type: Option, +} + +#[derive(Debug, Deserialize)] +pub struct BrowseQuery { + pub path: Option, +} + +#[derive(Debug, Serialize)] +pub struct DiscoveredHost { + pub name: String, + pub hostname: String, + pub ip: Option, + pub service_type: String, + pub protocol: String, +} + +#[derive(Debug, Deserialize)] +pub struct MountRequest { + pub url: String, + pub username: Option, + pub password: Option, + pub mount_point: Option, +} + +pub fn directory_browser_routes() -> Router { + Router::new() + .route("/api/v1/admin/browse", get(browse_directory)) + .route("/api/v1/admin/browse/mount", post(mount_path)) + .route("/api/v1/admin/browse/scan", get(scan_network)) + .route("/api/v1/admin/browse/shares", get(list_shares)) +} + +async fn browse_directory( + Query(params): Query, +) -> Result>, StatusCode> { + let base_path = params.path.unwrap_or_else(|| "/".to_string()); + + match base_path.as_str() { + "/" => return Ok(Json(get_root_entries())), + "/Network" => return Ok(Json(get_network_entries())), + _ => {} + } + + let path = Path::new(&base_path); + if !path.exists() || !path.is_dir() { + return Err(StatusCode::NOT_FOUND); + } + + let mut entries = Vec::new(); + + if base_path != "/" { + entries.push(DirEntry { + name: "/".to_string(), + path: "/".to_string(), + is_dir: true, + size: None, + entry_type: Some("local".to_string()), + }); + } + + if let Some(parent) = path.parent() { + let parent_str = parent.to_string_lossy().to_string(); + if parent_str != base_path { + entries.push(DirEntry { + name: "..".to_string(), + path: parent_str, + is_dir: true, + size: None, + entry_type: Some("local".to_string()), + }); + } + } + + match std::fs::read_dir(path) { + Ok(read_dir) => { + for entry in read_dir.filter_map(|e| e.ok()) { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with('.') && name != ".." { + continue; + } + + let entry_path = entry.path(); + let entry_path_str = entry_path.to_string_lossy().to_string(); + + if let Ok(metadata) = entry.metadata() { + let entry_type = if entry_path_str.starts_with("/Volumes") || + entry_path_str.starts_with("/Network") { + "network" + } else { + "local" + }; + + entries.push(DirEntry { + name, + path: entry_path_str, + is_dir: metadata.is_dir(), + size: if metadata.is_file() { Some(metadata.len()) } else { None }, + entry_type: Some(entry_type.to_string()), + }); + } + } + } + Err(_) => {} + } + + entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then(a.name.cmp(&b.name))); + Ok(Json(entries)) +} + +fn get_root_entries() -> Vec { + vec![ + DirEntry { name: "💻 Computer".to_string(), path: "/".to_string(), is_dir: true, size: None, entry_type: Some("local".to_string()) }, + DirEntry { name: "🌐 Network".to_string(), path: "/Network".to_string(), is_dir: true, size: None, entry_type: Some("network".to_string()) }, + DirEntry { name: "📁 Users".to_string(), path: "/Users".to_string(), is_dir: true, size: None, entry_type: Some("local".to_string()) }, + DirEntry { name: "💾 Volumes".to_string(), path: "/Volumes".to_string(), is_dir: true, size: None, entry_type: Some("network".to_string()) }, + DirEntry { name: "📦 Applications".to_string(), path: "/Applications".to_string(), is_dir: true, size: None, entry_type: Some("local".to_string()) }, + ] +} + +fn get_network_entries() -> Vec { + let mut entries = vec![ + DirEntry { name: "/".to_string(), path: "/".to_string(), is_dir: true, size: None, entry_type: Some("local".to_string()) }, + ]; + + if let Ok(read_dir) = std::fs::read_dir("/Volumes") { + for entry in read_dir.filter_map(|e| e.ok()) { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with('.') || name == "Macintosh HD" { + continue; + } + let path = entry.path().to_string_lossy().to_string(); + entries.push(DirEntry { + name: format!("🖥️ {}", name), + path, + is_dir: true, + size: None, + entry_type: Some("network".to_string()), + }); + } + } + + entries.push(DirEntry { + name: "➕ Connect to Server...".to_string(), + path: "connect://".to_string(), + is_dir: true, + size: None, + entry_type: Some("network".to_string()), + }); + + entries +} + +async fn scan_network( + State(_state): State, +) -> Result>, StatusCode> { + let mut hosts: HashMap = HashMap::new(); + + // 掃描 SMB 服務 + if let Ok(output) = std::process::Command::new("sh") + .arg("-c") + .arg("timeout 5 dns-sd -B _smb._tcp local. 2>/dev/null | grep 'Add' | awk '{print $NF}'") + .output() { + + let smb_hosts = String::from_utf8_lossy(&output.stdout); + for line in smb_hosts.lines() { + let name = line.trim().to_string(); + if name.is_empty() { continue; } + + let hostname = format!("{}.local", name); + + let ip = std::process::Command::new("sh") + .arg("-c") + .arg(format!("dig +short {} 2>/dev/null | head -1", hostname)) + .output() + .ok() + .and_then(|o| { + let s = String::from_utf8_lossy(&o.stdout).trim().to_string(); + if s.is_empty() { None } else { Some(s) } + }); + + hosts.insert(name.clone(), DiscoveredHost { + name: name.clone(), + hostname, + ip, + service_type: "SMB".to_string(), + protocol: "smb".to_string(), + }); + } + } + + // 掃描 AFP 服務 + if let Ok(output) = std::process::Command::new("sh") + .arg("-c") + .arg("timeout 5 dns-sd -B _afpovertcp._tcp local. 2>/dev/null | grep 'Add' | awk '{print $NF}'") + .output() { + + let afp_hosts = String::from_utf8_lossy(&output.stdout); + for line in afp_hosts.lines() { + let name = line.trim().to_string(); + if name.is_empty() || hosts.contains_key(&name) { continue; } + + hosts.insert(name.clone(), DiscoveredHost { + name: name.clone(), + hostname: format!("{}.local", name), + ip: None, + service_type: "AFP".to_string(), + protocol: "afp".to_string(), + }); + } + } + + Ok(Json(hosts.into_values().collect())) +} + +async fn mount_path( + State(_state): State, + Json(req): Json, +) -> Result, StatusCode> { + let url = req.url.trim_end_matches('/'); + + let (mount_cmd, mount_point) = if url.starts_with("smb://") { + let server_path = url.trim_start_matches("smb://"); + let mp = req.mount_point.clone().unwrap_or_else(|| { + format!("/Volumes/smb_{}", server_path.split('/').last().unwrap_or("share")) + }); + + let cred = if let (Some(user), Some(pass)) = (&req.username, &req.password) { + format!("{}:{}@", user, pass) + } else { + String::new() + }; + + (format!("mount_smbfs '//{}{}' '{}", cred, server_path, mp), mp) + } else if url.starts_with("nfs://") { + let server_path = url.trim_start_matches("nfs://"); + let mp = req.mount_point.clone().unwrap_or_else(|| { + format!("/Volumes/nfs_{}", server_path.split('/').last().unwrap_or("export")) + }); + (format!("mount_nfs '{}' '{}", server_path, mp), mp) + } else if url.starts_with("http://") || url.starts_with("https://") { + return Ok(Json(serde_json::json!({ + "success": false, + "message": "Cloud storage requires rclone. Please mount manually first." + }))); + } else { + return Err(StatusCode::BAD_REQUEST); + }; + + // 建立 mount point + let _ = std::fs::create_dir_all(&mount_point); + + let output = std::process::Command::new("sh") + .arg("-c") + .arg(&mount_cmd) + .output() + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + if output.status.success() { + Ok(Json(serde_json::json!({ + "success": true, + "mount_point": mount_point, + "message": "Mounted successfully" + }))) + } else { + let error = String::from_utf8_lossy(&output.stderr); + Ok(Json(serde_json::json!({ + "success": false, + "message": format!("Mount failed: {}", error) + }))) + } +} + +// 列出主機上的共享資源 +#[derive(Debug, Serialize)] +pub struct ShareInfo { + pub name: String, + pub path: String, + pub share_type: String, +} + +async fn list_shares( + State(_state): State, + Query(params): Query>, +) -> Result>, StatusCode> { + let hostname = params.get("host").ok_or(StatusCode::BAD_REQUEST)?; + + // 使用 smbutil 列出共享 + let output = std::process::Command::new("sh") + .arg("-c") + .arg(format!("smbutil view //{} 2>/dev/null | grep -v 'Share' | awk '{{print $1}}'", hostname)) + .output() + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let shares = String::from_utf8_lossy(&output.stdout); + let mut result = Vec::new(); + + for line in shares.lines() { + let name = line.trim().to_string(); + if name.is_empty() || name.starts_with("IPC") { continue; } + + result.push(ShareInfo { + name: name.clone(), + path: format!("smb://{}/{}", hostname, name), + share_type: "SMB".to_string(), + }); + } + + // 如果 smbutil 失敗,回傳預設共享 + if result.is_empty() { + result.push(ShareInfo { + name: "Home".to_string(), + path: format!("smb://{}/home", hostname), + share_type: "SMB".to_string(), + }); + } + + Ok(Json(result)) +} diff --git a/src/api/export_api.rs b/src/api/export_api.rs new file mode 100644 index 00000000..87f1c068 --- /dev/null +++ b/src/api/export_api.rs @@ -0,0 +1,208 @@ +/// Export/Import API endpoints for portable file packages + +use axum::{ + extract::{Path, Query, State}, + http::StatusCode, + routing::{get, post}, + Json, Router, +}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +use crate::api::types::AppState; +use crate::core::export; + +// ─── Request/Response Structures ────────────────────────────────────────────── + +#[derive(Debug, Deserialize)] +pub struct ExportQuery { + pub export_dir: Option, +} + +#[derive(Debug, Serialize)] +pub struct ExportResponse { + pub success: bool, + pub file_uuid: String, + pub package_path: String, + pub package_size: u64, + pub message: String, +} + +#[derive(Debug, Serialize)] +pub struct ExportStatusResponse { + pub success: bool, + pub file_uuid: String, + pub manifest: export::ExportManifest, +} + +// ─── API Handlers ──────────────────────────────────────────────────────────── + +/// POST /api/v1/files/:uuid/export +/// Export a single file as a portable .momentry.tar.gz package +pub async fn export_file_handler( + State(state): State, + Path(uuid): Path, + Query(params): Query, +) -> Result, (StatusCode, Json)> { + // Validate file exists + let video = state.db.get_video_by_uuid(&uuid).await.map_err(|e| { + ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": format!("File not found: {}", e)})), + ) + })?; + + if video.is_none() { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "File not found"})), + )); + } + + let export_dir = params.export_dir.unwrap_or_else(|| { + "/Users/accusys/momentry/offline_storage/files".to_string() + }); + + // Create export directory if it doesn't exist + if let Err(e) = std::fs::create_dir_all(&export_dir) { + return Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("Failed to create export dir: {}", e)})), + )); + } + + // Get config paths + let output_dir = crate::core::config::OUTPUT_DIR.to_string(); + + // Perform export + match export::export_file( + state.db.pool(), + &uuid, + &output_dir, + &export_dir, + ) + .await + { + Ok(package_path) => { + let package_size = std::fs::metadata(&package_path) + .map(|m| m.len()) + .unwrap_or(0); + + Ok(Json(ExportResponse { + success: true, + file_uuid: uuid, + package_path: package_path.to_string_lossy().to_string(), + package_size, + message: format!( + "Exported successfully: {} ({:.2} MB)", + package_path.file_name().unwrap_or_default().to_string_lossy(), + package_size as f64 / 1024.0 / 1024.0 + ), + })) + } + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("Export failed: {}", e)})), + )), + } +} + +/// GET /api/v1/files/:uuid/export-status +/// Get export manifest for a file (read from existing package or generate info) +pub async fn export_status_handler( + State(state): State, + Path(uuid): Path, +) -> Result, (StatusCode, Json)> { + use crate::core::config::OUTPUT_DIR; + + // Build manifest from current data + let video = state.db.get_video_by_uuid(&uuid).await.map_err(|e| { + ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": format!("File not found: {}", e)})), + ) + })?; + + if video.is_none() { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "File not found"})), + )); + } + + let video = video.unwrap(); + + // Get library + let library = sqlx::query_scalar::<_, Option>( + "SELECT up.name FROM upload_paths up WHERE $1 LIKE up.full_path || '%' ORDER BY LENGTH(up.full_path) DESC LIMIT 1" + ) + .bind(&video.file_path) + .fetch_optional(state.db.pool()) + .await + .ok() + .flatten() + .flatten() + .unwrap_or_else(|| "unknown".to_string()); + + // Get file size from filesystem + let file_size = std::fs::metadata(&video.file_path) + .ok() + .map(|m| m.len()) + .unwrap_or(0); + + // Get processor results + let processors = export::get_processor_results(state.db.pool(), &uuid) + .await + .unwrap_or_default(); + + let manifest = export::ExportManifest { + version: "1.0".to_string(), + export_type: "file".to_string(), + exported_at: chrono::Utc::now().to_rfc3339(), + momentry_version: env!("CARGO_PKG_VERSION").to_string(), + file: export::FileInfo { + uuid: uuid.clone(), + file_name: video.file_name.clone(), + file_path: video.file_path.clone(), + file_size, + library, + status: format!("{:?}", video.status), + }, + data_sources: export::DataSources { + postgresql: export::PostgresqlInfo { + tables: vec![], + total_records: 0, + }, + qdrant: export::QdrantInfo { + collection: "momentry_rule1".to_string(), + face_vectors: 0, + text_vectors: 0, + speaker_vectors: 0, + }, + sqlite: export::SqliteInfo { + file: "workspace.sqlite".to_string(), + tables: vec![], + total_records: 0, + }, + redis: export::RedisInfo { + keys_count: 0, + patterns: vec![], + }, + }, + processors, + }; + + Ok(Json(ExportStatusResponse { + success: true, + file_uuid: uuid, + manifest, + })) +} + +// ─── Router ────────────────────────────────────────────────────────────────── + +pub fn export_routes() -> Router { + Router::new() + .route("/api/v1/file/:uuid/export", post(export_file_handler)) + .route("/api/v1/file/:uuid/export-status", get(export_status_handler)) +} diff --git a/src/api/file_replicas.rs b/src/api/file_replicas.rs new file mode 100644 index 00000000..b0c8c530 --- /dev/null +++ b/src/api/file_replicas.rs @@ -0,0 +1,255 @@ +//! File Replicas management API +//! +//! Manages multiple copies/replicas of files at different locations. +//! Frontend identifies files by UUID, system selects appropriate replica. + +use axum::{ + extract::{Path, State, Query}, + http::StatusCode, + response::Json, + routing::{get, post, delete}, + Router, +}; +use serde::{Deserialize, Serialize}; +use sqlx::{PgPool, FromRow}; +use tracing::{error, info}; + +use crate::api::types::AppState; + +// ── Models ────────────────────────────────────────────────────────── + +#[derive(Debug, Serialize, Deserialize, FromRow)] +pub struct FileReplica { + pub id: i32, + pub file_uuid: String, + pub replica_path: String, + pub replica_name: Option, + pub is_primary: bool, + pub is_available: bool, + pub file_size: Option, + pub checksum: Option, + pub created_at: Option, + pub updated_at: Option, +} + +#[derive(Debug, Deserialize)] +pub struct CreateReplicaRequest { + pub file_uuid: String, + pub replica_path: String, + pub replica_name: Option, + pub is_primary: Option, + pub file_size: Option, + pub checksum: Option, +} + +#[derive(Debug, Deserialize)] +pub struct ListReplicasQuery { + pub file_uuid: Option, + pub replica_name: Option, +} + +// ── Routes ────────────────────────────────────────────────────────── + +pub fn file_replica_routes() -> Router { + Router::new() + .route("/api/v1/files/replicas", get(list_replicas)) + .route("/api/v1/files/replicas", post(create_replica)) + .route("/api/v1/file-replicas/by-uuid/:uuid", get(get_replicas_by_uuid)) + .route("/api/v1/files/replicas/:id", delete(delete_replica)) + .route("/api/v1/files/replicas/:id/toggle", post(toggle_replica)) +} + +// ── Helpers ───────────────────────────────────────────────────────── + +fn get_pool(state: &AppState) -> &PgPool { + state.db.pool() +} + +// ── Handlers ──────────────────────────────────────────────────────── + +/// GET /api/v1/files/replicas?[file_uuid=X]&[replica_name=Y] +async fn list_replicas( + State(state): State, + Query(params): Query, +) -> Result>, StatusCode> { + let pool = get_pool(&state); + + let query = match (¶ms.file_uuid, ¶ms.replica_name) { + (Some(uuid), Some(name)) => { + sqlx::query_as::<_, FileReplica>( + "SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available, + file_size, checksum, created_at::text, updated_at::text + FROM file_replicas WHERE file_uuid = $1 AND replica_name = $2 + ORDER BY is_primary DESC, created_at ASC" + ).bind(uuid).bind(name) + } + (Some(uuid), None) => { + sqlx::query_as::<_, FileReplica>( + "SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available, + file_size, checksum, created_at::text, updated_at::text + FROM file_replicas WHERE file_uuid = $1 + ORDER BY is_primary DESC, created_at ASC" + ).bind(uuid) + } + (None, Some(name)) => { + sqlx::query_as::<_, FileReplica>( + "SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available, + file_size, checksum, created_at::text, updated_at::text + FROM file_replicas WHERE replica_name = $1 + ORDER BY file_uuid, is_primary DESC" + ).bind(name) + } + (None, None) => { + sqlx::query_as::<_, FileReplica>( + "SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available, + file_size, checksum, created_at::text, updated_at::text + FROM file_replicas ORDER BY file_uuid, is_primary DESC, created_at ASC" + ) + } + }; + + let replicas = query.fetch_all(pool).await.map_err(|e| { + error!("[replicas] list failed: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + Ok(Json(replicas)) +} + +/// GET /api/v1/file-replicas/by-uuid/:uuid +async fn get_replicas_by_uuid( + State(state): State, + Path(uuid): Path, +) -> Result>, StatusCode> { + let pool = get_pool(&state); + let replicas = sqlx::query_as::<_, FileReplica>( + "SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available, + file_size, checksum, created_at::text, updated_at::text + FROM file_replicas WHERE file_uuid = $1 + ORDER BY is_primary DESC, created_at ASC" + ) + .bind(&uuid) + .fetch_all(pool) + .await + .map_err(|e| { + error!("[replicas] get_replicas_by_uuid failed: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + Ok(Json(replicas)) +} + +/// POST /api/v1/files/replicas +async fn create_replica( + State(state): State, + Json(req): Json, +) -> Result, StatusCode> { + let pool = get_pool(&state); + + // Verify file exists + let file_exists: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM videos WHERE file_uuid = $1)" + ) + .bind(&req.file_uuid) + .fetch_one(pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + if !file_exists { + return Err(StatusCode::NOT_FOUND); + } + + // If setting as primary, unset other primaries for this file + if req.is_primary.unwrap_or(false) { + sqlx::query("UPDATE file_replicas SET is_primary = FALSE WHERE file_uuid = $1") + .bind(&req.file_uuid) + .execute(pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + } + + let replica = sqlx::query_as::<_, FileReplica>( + "INSERT INTO file_replicas (file_uuid, replica_path, replica_name, is_primary, is_available, file_size, checksum) + VALUES ($1, $2, $3, $4, TRUE, $5, $6) + ON CONFLICT (file_uuid, replica_path) DO UPDATE SET + replica_name = EXCLUDED.replica_name, + is_primary = EXCLUDED.is_primary, + file_size = EXCLUDED.file_size, + checksum = EXCLUDED.checksum, + is_available = TRUE, + updated_at = NOW() + RETURNING id, file_uuid, replica_path, replica_name, is_primary, is_available, + file_size, checksum, created_at::text, updated_at::text" + ) + .bind(&req.file_uuid) + .bind(&req.replica_path) + .bind(&req.replica_name) + .bind(req.is_primary.unwrap_or(false)) + .bind(req.file_size) + .bind(&req.checksum) + .fetch_one(pool) + .await + .map_err(|e| { + error!("[replicas] create failed: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + info!("[replicas] created: {} -> {}", replica.file_uuid, replica.replica_path); + Ok(Json(replica)) +} + +/// DELETE /api/v1/files/replicas/:id +async fn delete_replica( + State(state): State, + Path(id): Path, +) -> Result, StatusCode> { + let pool = get_pool(&state); + + // Don't allow deleting primary replica + let is_primary: bool = sqlx::query_scalar( + "SELECT is_primary FROM file_replicas WHERE id = $1" + ) + .bind(id) + .fetch_optional(pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .unwrap_or(false); + + if is_primary { + return Err(StatusCode::BAD_REQUEST); + } + + sqlx::query("DELETE FROM file_replicas WHERE id = $1") + .bind(id) + .execute(pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + info!("[replicas] deleted id={}", id); + Ok(Json(serde_json::json!({"success": true}))) +} + +/// POST /api/v1/files/replicas/:id/toggle +async fn toggle_replica( + State(state): State, + Path(id): Path, +) -> Result, StatusCode> { + let pool = get_pool(&state); + let replica = sqlx::query_as::<_, FileReplica>( + "UPDATE file_replicas + SET is_available = NOT is_available, updated_at = NOW() + WHERE id = $1 + RETURNING id, file_uuid, replica_path, replica_name, is_primary, is_available, + file_size, checksum, created_at::text, updated_at::text" + ) + .bind(id) + .fetch_one(pool) + .await + .map_err(|e| { + error!("[replicas] toggle failed: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + info!("[replicas] toggled: {} available={}", replica.replica_path, replica.is_available); + Ok(Json(replica)) +} diff --git a/src/api/files.rs b/src/api/files.rs index 38669c25..c0f50126 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -1491,6 +1491,62 @@ async fn re_scan( reason ); + // Step 0: Pre-scan check and repair + tracing::info!("[RE-SCAN] Pre-scan check for {}", file_uuid); + + // Clean up stuck jobs + let _ = sqlx::query( + "UPDATE monitor_jobs SET status='completed' WHERE uuid = $1 AND status IN ('running','processing')" + ) + .bind(&file_uuid) + .execute(state.db.pool()) + .await; + + // Fix stuck scene_vlm + let _ = sqlx::query( + "UPDATE processor_results SET status='completed' WHERE file_uuid = $1 AND processor='scene_vlm' AND status='running'" + ) + .bind(&file_uuid) + .execute(state.db.pool()) + .await; + + // Fix failed face_cluster + let _ = sqlx::query( + "UPDATE processor_results SET status='completed' WHERE file_uuid = $1 AND processor='face_cluster' AND status='failed'" + ) + .bind(&file_uuid) + .execute(state.db.pool()) + .await; + + // Clean duplicate processor_results + let _ = sqlx::query( + "DELETE FROM processor_results WHERE file_uuid = $1 AND ctid NOT IN (SELECT max(ctid) FROM processor_results WHERE file_uuid = $1 GROUP BY processor)" + ) + .bind(&file_uuid) + .execute(state.db.pool()) + .await; + + // Clean up old command_queue entries for this file + let file_path_for_cleanup: Option = sqlx::query_scalar( + "SELECT file_path FROM videos WHERE file_uuid = $1" + ) + .bind(&file_uuid) + .fetch_optional(state.db.pool()) + .await + .ok() + .flatten(); + + if let Some(path) = &file_path_for_cleanup { + let _ = sqlx::query( + "DELETE FROM command_queue WHERE value->>'file_path' = $1" + ) + .bind(path) + .execute(state.db.pool()) + .await; + } + + tracing::info!("[RE-SCAN] Pre-scan cleanup completed for {}", file_uuid); + // Step 1: Get file path from database let videos_table = schema::table_name("videos"); let file_path: Option = sqlx::query_scalar(&format!( @@ -1517,13 +1573,37 @@ async fn re_scan( } }; + // Step 0.5: 清掉同 file_path 的舊 rows(避免 re-scan 產生重複 uuid) + let videos_table = schema::table_name("videos"); + let processor_table = schema::table_name("processor_results"); + if let Ok(result) = sqlx::query(&format!( + "DELETE FROM {videos_table} + WHERE file_path = $1 AND file_uuid <> $2 + AND NOT EXISTS ( + SELECT 1 FROM {processor_table} pr WHERE pr.file_uuid = {videos_table}.file_uuid + )" + )) + .bind(&file_path) + .bind(&file_uuid) + .execute(state.db.pool()) + .await + { + let cleaned = result.rows_affected(); + if cleaned > 0 { + tracing::info!("[RE-SCAN] 清掉 {cleaned} 筆同路徑重複 rows({file_path})"); + } + } + // Step 2: Create register command with force=true // Note: force=true will automatically unregister existing file if needed - let auto_pipeline = req.auto_pipeline.unwrap_or(false); + // deep_scan=true tells the worker to start the full scan pipeline right + // after registration completes (unregister → register → deep scan). + // This is independent of the global auto-pipeline setting. + let deep_scan = req.auto_pipeline.unwrap_or(true); let register_payload = serde_json::json!({ "force": true, - "auto_pipeline": auto_pipeline, + "deep_scan": deep_scan, "content_hash": null, "face_settings": req.face_settings.as_ref().map(|fs| { serde_json::json!({ @@ -1562,10 +1642,10 @@ async fn re_scan( // Note: Register command with force=true will: // 1. Unregister existing file if needed // 2. Register the file - // 3. Trigger auto-pipeline only if auto_pipeline=true (default: false) + // 3. Start the deep scan pipeline when deep_scan=true - let mode = if auto_pipeline { "auto" } else { "manual" }; - tracing::info!("[RE-SCAN] Mode: {} (auto_pipeline={})", mode, auto_pipeline); + let mode = if deep_scan { "auto" } else { "manual" }; + tracing::info!("[RE-SCAN] Mode: {} (deep_scan={})", mode, deep_scan); Ok(Json(ReScanResponse { success: true, diff --git a/src/api/folder_api.rs b/src/api/folder_api.rs new file mode 100644 index 00000000..b33fd8cb --- /dev/null +++ b/src/api/folder_api.rs @@ -0,0 +1,201 @@ +/// Folder batch export/import API + +use axum::{ + extract::{Query, State}, + http::StatusCode, + routing::post, + Json, Router, +}; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +use crate::api::types::AppState; + +// ─── Request/Response Structures ────────────────────────────────────────────── + +#[derive(Debug, Deserialize)] +pub struct FolderExportQuery { + pub folder_path: String, + #[serde(default)] + pub export_dir: Option, + #[serde(default)] + pub library_name: Option, +} + +#[derive(Debug, Serialize)] +pub struct FolderExportResponse { + pub success: bool, + pub folder_name: String, + pub file_count: usize, + pub package_path: String, + pub package_size: u64, + pub message: String, +} + +#[derive(Debug, Deserialize)] +pub struct FolderImportQuery { + pub package_path: String, + #[serde(default)] + pub target_folder_path: Option, + #[serde(default)] + pub force: bool, +} + +#[derive(Debug, Serialize)] +pub struct FolderImportResponse { + pub success: bool, + pub folder_name: String, + pub imported_files: usize, + pub total_records: usize, + pub message: String, +} + +// ─── API Handlers ──────────────────────────────────────────────────────────── + +/// POST /api/v1/folder/export +/// Export all files in a folder as a single .momentry.tar.gz package +pub async fn folder_export_handler( + State(state): State, + Query(params): Query, +) -> Result, (StatusCode, Json)> { + let export_dir = params.export_dir.unwrap_or_else(|| { + "/Users/accusys/momentry/offline_storage/folders".to_string() + }); + + // Create export directory + if let Err(e) = std::fs::create_dir_all(&export_dir) { + return Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("Failed to create export dir: {}", e)})), + )); + } + + // Get library name + let library_name = params.library_name.unwrap_or_else(|| { + // Extract from folder path + PathBuf::from(¶ms.folder_path) + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_else(|| "unknown".to_string()) + }); + + // Find all files in this folder + let files = get_files_in_folder(state.db.pool(), ¶ms.folder_path).await?; + if files.is_empty() { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "No files found in folder"})), + )); + } + + // Export folder + match crate::core::folder_export::export_folder( + state.db.pool(), + ¶ms.folder_path, + &library_name, + &export_dir, + ) + .await + { + Ok((package_path, file_count)) => { + let package_size = std::fs::metadata(&package_path) + .map(|m| m.len()) + .unwrap_or(0); + + Ok(Json(FolderExportResponse { + success: true, + folder_name: library_name.clone(), + file_count, + package_path: package_path.to_string_lossy().to_string(), + package_size, + message: format!( + "Exported {} files from {}. Package: {} ({:.2} MB)", + file_count, + library_name, + package_path.file_name().unwrap_or_default().to_string_lossy(), + package_size as f64 / 1024.0 / 1024.0 + ), + })) + } + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("Export failed: {}", e)})), + )), + } +} + +/// POST /api/v1/folder/import +/// Import a folder package +pub async fn folder_import_handler( + State(state): State, + Query(params): Query, +) -> Result, (StatusCode, Json)> { + let pkg_path = PathBuf::from(¶ms.package_path); + if !pkg_path.exists() { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "Package not found"})), + )); + } + + match crate::core::folder_export::import_folder( + state.db.pool(), + ¶ms.package_path, + params.target_folder_path.as_deref(), + params.force, + ) + .await + { + Ok(result) => Ok(Json(FolderImportResponse { + success: true, + folder_name: result.folder_name, + imported_files: result.imported_files, + total_records: result.total_records, + message: format!( + "Imported {} files, {} records restored.", + result.imported_files, result.total_records + ), + })), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("Import failed: {}", e)})), + )), + } +} + +// ─── Helper Functions ──────────────────────────────────────────────────────── + +struct FileInfo { + uuid: String, + file_name: String, + file_path: String, +} + +async fn get_files_in_folder(pool: &sqlx::PgPool, folder_path: &str) -> Result, (StatusCode, Json)> { + let videos_table = crate::core::db::schema::table_name("videos"); + + let rows: Vec<(String, String, String)> = sqlx::query_as( + &format!("SELECT file_uuid, file_name, file_path FROM {} WHERE file_path LIKE $1 || '%%'", videos_table) + ) + .bind(folder_path.trim_end_matches('/')) + .fetch_all(pool) + .await + .map_err(|e| ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("DB error: {}", e)})), + ))?; + + Ok(rows.into_iter().map(|r| FileInfo { + uuid: r.0, + file_name: r.1, + file_path: r.2, + }).collect()) +} + +// ─── Router ────────────────────────────────────────────────────────────────── + +pub fn folder_routes() -> Router { + Router::new() + .route("/api/v1/folder/export", post(folder_export_handler)) + .route("/api/v1/folder/import", post(folder_import_handler)) +} diff --git a/src/api/identity_api.rs b/src/api/identity_api.rs index 4dde12e9..c99788a6 100644 --- a/src/api/identity_api.rs +++ b/src/api/identity_api.rs @@ -11,6 +11,12 @@ use std::process::Command; use crate::core::db::{QdrantDb, ResourceRecord}; +/// 檔案是否已納入管理(unregistered/pending = 掃描發現但尚未註冊)。 +/// registered / completed / scanning / keyword_ready 等 pipeline 狀態都算已註冊。 +fn status_is_registered(status: &str) -> bool { + !matches!(status, "" | "unregistered" | "pending") +} + pub fn identity_routes() -> Router { Router::new() .route("/api/v1/files", get(list_files)) @@ -79,6 +85,7 @@ pub fn identity_routes() -> Router { #[derive(Debug, Deserialize)] pub struct FilesQuery { pub page: Option, + #[serde(alias = "pageSize")] pub page_size: Option, pub status: Option, pub file_uuid: Option, @@ -110,7 +117,7 @@ async fn list_files( .await .unwrap_or(0); - let is_registered = v.status.as_str() != "pending"; + let is_registered = status_is_registered(v.status.as_str()); vec![FileItem { file_uuid: v.file_uuid, @@ -136,18 +143,28 @@ async fn list_files( })); } - // Call MarkBase API to get file list - let markbase_url = "http://localhost:11438/api/v2/myfiles/demo/files"; + // Call MarkBase API for each enabled upload_path let client = reqwest::Client::new(); - let markbase_files: Vec = client - .get(markbase_url) - .send() - .await - .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("MarkBase API error: {}", e)))? - .json() - .await - .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("MarkBase API parse error: {}", e)))?; + // Get enabled upload paths + let up_table = crate::core::db::schema::table_name("upload_paths"); + let upload_paths: Vec<(String, String)> = sqlx::query_as(&format!( + "SELECT name, full_path FROM {} WHERE enabled = true ORDER BY id", + up_table + )) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default(); + + let mut markbase_files: Vec = Vec::new(); + for (mb_user, _full_path) in &upload_paths { + let url = format!("http://localhost:11438/api/v2/myfiles/{}/files", mb_user); + if let Ok(resp) = client.get(&url).send().await { + if let Ok(files) = resp.json::>().await { + markbase_files.extend(files); + } + } + } let mut all_files: Vec = Vec::new(); @@ -199,26 +216,30 @@ async fn list_files( file_name: name, file_path: path.clone(), status: status.clone(), - is_registered: status != "pending", + is_registered: status_is_registered(status.as_str()), total_chunks: 0, file_size, modified_time, thumbnail_url: None, }); } else { - // Not registered: synthesize a path so the client can still preview it - let synth_path = std::env::var("MOMENTRY_SFTP_ROOT") - .ok() - .map(|root| format!("{}/{}", root.trim_end_matches('/'), name)) + // Not registered: use MarkBase file_path if available + let file_path = mb_file.file_path.clone() + .filter(|p| !p.is_empty()) .unwrap_or_else(|| { - // Default SFTP root if not configured - let default_root = "/Users/accusys/momentry/var/sftpgo/data/demo"; - format!("{}/{}", default_root, name) + // Fallback: synthesize path from SFTP root + std::env::var("MOMENTRY_SFTP_ROOT") + .ok() + .map(|root| format!("{}/{}", root.trim_end_matches('/'), name)) + .unwrap_or_else(|| { + let default_root = "/Users/accusys/momentry/var/sftpgo/data/demo"; + format!("{}/{}", default_root, name) + }) }); all_files.push(FileItem { file_uuid: mb_file.file_uuid.unwrap_or_default(), file_name: name, - file_path: synth_path, + file_path, status: "unregistered".to_string(), is_registered: false, total_chunks: 0, @@ -234,15 +255,24 @@ async fn list_files( let all_names: std::collections::HashSet = all_files.iter().map(|f| f.file_name.clone()).collect(); for (name, (uuid, path, status, size, mtime)) in ®istered_by_name { if !all_names.contains(name) && !all_paths.contains(path) { + // Fallback to filesystem for size/mtime when DB has NULL + let file_size = size.map(|s| s as u64).or_else(|| { + std::fs::metadata(path).ok().map(|m| m.len()) + }); + let modified_time = mtime.clone().or_else(|| { + std::fs::metadata(path).ok() + .and_then(|m| m.modified().ok()) + .map(|t| chrono::DateTime::::from(t).to_rfc3339()) + }); all_files.push(FileItem { file_uuid: uuid.clone(), file_name: name.clone(), file_path: path.clone(), status: status.clone(), - is_registered: status != "pending", + is_registered: status_is_registered(status.as_str()), total_chunks: 0, - file_size: size.map(|s| s as u64), - modified_time: mtime.clone(), + file_size, + modified_time, thumbnail_url: None, }); } @@ -323,7 +353,7 @@ pub struct FilesResponse { pub data: Vec, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct FileItem { pub file_uuid: String, pub file_name: String, diff --git a/src/api/import_api.rs b/src/api/import_api.rs new file mode 100644 index 00000000..f89b990c --- /dev/null +++ b/src/api/import_api.rs @@ -0,0 +1,478 @@ +/// Import API - restore files from .momentry.tar.gz packages + +use axum::{ + extract::{Multipart, Query, State}, + http::StatusCode, + routing::post, + Json, Router, +}; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +use crate::api::types::AppState; + +// ─── Request/Response Structures ────────────────────────────────────────────── + +#[derive(Debug, Deserialize)] +pub struct ImportQuery { + #[serde(default)] + pub package_path: Option, + #[serde(default)] + pub target_video_path: Option, + #[serde(default)] + pub force: bool, +} + +#[derive(Debug, Serialize)] +pub struct ImportResponse { + pub success: bool, + pub file_uuid: String, + pub video_path: String, + pub restored_records: usize, + pub message: String, +} + +// ─── API Handlers ──────────────────────────────────────────────────────────── + +/// POST /api/v1/import +/// Import a file from a .momentry.tar.gz package +/// +/// Query params: +/// - package_path: Path to the .momentry.tar.gz file +/// - target_video_path: Where to restore the video (default: original path from manifest) +/// - force: Overwrite if file already exists +pub async fn import_file_handler( + State(state): State, + Query(params): Query, +) -> Result, (StatusCode, Json)> { + let package_path = params.package_path.ok_or(( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "Missing package_path parameter"})), + ))?; + + let pkg_path = std::path::PathBuf::from(&package_path); + if !pkg_path.exists() { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": format!("Package not found: {}", package_path)})), + )); + } + + // Perform import + match import_file( + state.db.pool(), + &package_path, + params.target_video_path.as_deref(), + params.force, + ) + .await + { + Ok(result) => Ok(Json(result)), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("Import failed: {}", e)})), + )), + } +} + +/// POST /api/v1/import/list +/// List available packages in offline_storage +pub async fn list_packages_handler( + Query(params): Query, +) -> Result, (StatusCode, Json)> { + let storage_dir = params.storage_dir.unwrap_or_else(|| { + "/Users/accusys/momentry/offline_storage/files".to_string() + }); + + let packages = list_packages(&storage_dir).map_err(|e| ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("Failed to list packages: {}", e)})), + ))?; + + let total = packages.len(); + + Ok(Json(ListResponse { + success: true, + packages, + total, + })) +} + +#[derive(Debug, Deserialize)] +pub struct ListQuery { + pub storage_dir: Option, +} + +#[derive(Debug, Serialize)] +pub struct ListResponse { + pub success: bool, + pub packages: Vec, + pub total: usize, +} + +#[derive(Debug, Serialize)] +pub struct PackageInfo { + pub path: String, + pub file_uuid: String, + pub file_name: String, + pub library: String, + pub size: u64, + pub exported_at: String, +} + +// ─── Import Logic ──────────────────────────────────────────────────────────── + +pub async fn import_file( + pool: &sqlx::PgPool, + package_path: &str, + target_video_path: Option<&str>, + force: bool, +) -> Result { + let pkg_path = PathBuf::from(package_path); + let temp_dir = pkg_path.with_extension(""); // Remove .tar.gz + + // 1. Extract package + extract_package(&pkg_path, &temp_dir)?; + + // 2. Read manifest + let manifest_path = temp_dir.join("manifest.json"); + let manifest_str = std::fs::read_to_string(&manifest_path)?; + let manifest: crate::core::export::ExportManifest = serde_json::from_str(&manifest_str)?; + + let file_uuid = &manifest.file.uuid; + + // 3. Check if file already exists + let videos_table = crate::core::db::schema::table_name("videos"); + let exists: Option<(i32,)> = sqlx::query_as( + &format!("SELECT id FROM {} WHERE file_uuid = $1", videos_table) + ) + .bind(file_uuid) + .fetch_optional(pool) + .await?; + + if exists.is_some() && !force { + return Err(anyhow::anyhow!( + "File {} already exists. Use force=true to overwrite.", + file_uuid + )); + } + + // 4. Delete existing records if force + if exists.is_some() { + delete_existing_records(pool, file_uuid).await?; + } + + // 5. Restore video file + let video_src = temp_dir.join("video").join(&manifest.file.file_name); + let video_dest = target_video_path + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(&manifest.file.file_path)); + + if video_src.exists() { + if let Some(parent) = video_dest.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::copy(&video_src, &video_dest)?; + } + + // 6. Restore output files + restore_output_files(&temp_dir, &manifest.file.uuid)?; + + // 7. Restore identities + restore_identities(&temp_dir)?; + + // 8. Restore DB records + let restored_records = restore_db_records(pool, &temp_dir, file_uuid).await?; + + // 9. Clean up temp dir + let _ = std::fs::remove_dir_all(&temp_dir); + + Ok(ImportResponse { + success: true, + file_uuid: file_uuid.clone(), + video_path: video_dest.to_string_lossy().to_string(), + restored_records, + message: format!( + "Imported {} successfully. {} records restored.", + manifest.file.file_name, restored_records + ), + }) +} + +fn list_packages(storage_dir: &str) -> Result> { + let mut packages = Vec::new(); + + let dir = std::path::PathBuf::from(storage_dir); + if !dir.exists() { + return Ok(packages); + } + + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let path = entry.path(); + + if path.to_string_lossy().ends_with(".tar.gz") { + // Try to read manifest from package + if let Ok(info) = read_package_info(&path) { + packages.push(info); + } + } + } + + Ok(packages) +} + +fn read_package_info(package_path: &std::path::Path) -> Result { + use std::os::unix::fs::MetadataExt; + + // Extract to temp to read manifest + let temp_dir = package_path.with_extension(""); + extract_package(package_path, &temp_dir)?; + + let manifest_path = temp_dir.join("manifest.json"); + let manifest_str = std::fs::read_to_string(&manifest_path)?; + let manifest: crate::core::export::ExportManifest = serde_json::from_str(&manifest_str)?; + + let size = std::fs::metadata(package_path)?.size(); + + // Clean up + let _ = std::fs::remove_dir_all(&temp_dir); + + Ok(PackageInfo { + path: package_path.to_string_lossy().to_string(), + file_uuid: manifest.file.uuid, + file_name: manifest.file.file_name, + library: manifest.file.library, + size, + exported_at: manifest.exported_at, + }) +} + +fn extract_package(package_path: &std::path::Path, dest_dir: &std::path::Path) -> Result<()> { + use flate2::read::GzDecoder; + use tar::Archive; + + if dest_dir.exists() { + std::fs::remove_dir_all(dest_dir)?; + } + + let tar_gz = std::fs::File::open(package_path)?; + let tar = GzDecoder::new(tar_gz); + let mut archive = Archive::new(tar); + + archive.unpack(dest_dir)?; + + Ok(()) +} + +fn restore_output_files(temp_dir: &std::path::Path, uuid: &str) -> Result<()> { + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let dest_dir = std::path::PathBuf::from(output_dir); + + let src_output = temp_dir.join("output"); + if !src_output.exists() { + return Ok(()); + } + + // Copy JSON files + if let Ok(entries) = std::fs::read_dir(&src_output) { + for entry in entries.flatten() { + let path = entry.path(); + if path.is_file() { + let dest = dest_dir.join(path.file_name().unwrap()); + std::fs::copy(&path, &dest)?; + } else if path.is_dir() { + // Copy trace directories + if path.file_name().map(|n| n == uuid).unwrap_or(false) { + let dest = dest_dir.join(uuid); + copy_dir_all(&path, &dest)?; + } + } + } + } + + Ok(()) +} + +fn restore_identities(temp_dir: &std::path::Path) -> Result<()> { + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let dest_identities = std::path::PathBuf::from(output_dir).join("identities"); + + let src_identities = temp_dir.join("identities"); + if !src_identities.exists() { + return Ok(()); + } + + if !dest_identities.exists() { + std::fs::create_dir_all(&dest_identities)?; + } + + if let Ok(entries) = std::fs::read_dir(&src_identities) { + for entry in entries.flatten() { + if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) { + let name = entry.file_name(); + let dest = dest_identities.join(&name); + if !dest.exists() { + copy_dir_all(&entry.path(), &dest)?; + } + } + } + } + + Ok(()) +} + +async fn restore_db_records(pool: &sqlx::PgPool, temp_dir: &std::path::Path, uuid: &str) -> Result { + let db_dir = temp_dir.join("db"); + if !db_dir.exists() { + return Ok(0); + } + + let mut restored = 0; + + // Restore each table + let tables = [ + "videos", + "processor_results", + "monitor_jobs", + "trace_profiles", + "tkg_nodes", + "chunk", + "identities", + ]; + + for table in tables { + let json_path = db_dir.join(format!("{}.json", table)); + if !json_path.exists() { + continue; + } + + let json_str = std::fs::read_to_string(&json_path)?; + let records: Vec = serde_json::from_str(&json_str)?; + + let table_name = crate::core::db::schema::table_name(table); + + for record in records { + // Remove id column (auto-increment with NOT NULL) + let mut record = record.clone(); + if let Some(obj) = record.as_object_mut() { + obj.remove("id"); + } + + if record.as_object().map(|o| o.is_empty()).unwrap_or(true) { + continue; + } + + // Build explicit INSERT with columns (excluding id) + let columns: Vec = record.as_object().unwrap().keys() + .map(|k| format!("\"{}\"", k)).collect(); + let cols_str = columns.join(", "); + + // Build values with proper type handling + let values: Vec = record.as_object().unwrap().values() + .map(|v| match v { + serde_json::Value::Null => "NULL".to_string(), + serde_json::Value::Bool(b) => b.to_string(), + serde_json::Value::Number(n) => n.to_string(), + serde_json::Value::String(s) => format!("'{}'", s.replace("'", "''")), + serde_json::Value::Array(_) | serde_json::Value::Object(_) => { + format!("'{}'::jsonb", serde_json::to_string(v).unwrap_or_else(|_| "null".to_string()).replace("'", "''")) + } + }) + .collect(); + let vals_str = values.join(", "); + + let sql = format!( + "INSERT INTO {} ({}) VALUES ({})", + table_name, cols_str, vals_str + ); + + let result = sqlx::query(&sql) + .execute(pool) + .await; + + match result { + Ok(_) => restored += 1, + Err(e) => { + tracing::warn!("[Import] Failed to insert into {}: {}", table, e); + // Try alternative approach: column-by-column insert + if let Err(e2) = insert_record_fallback(pool, &table_name, &record).await { + tracing::warn!("[Import] Fallback also failed: {}", e2); + } else { + restored += 1; + } + } + } + } + } + + Ok(restored) +} + +async fn insert_record_fallback(pool: &sqlx::PgPool, table: &str, record: &serde_json::Value) -> Result<()> { + // Use jsonb_to_record approach + let json_str = serde_json::to_string(record)?; + sqlx::query(&format!( + "INSERT INTO {} SELECT * FROM jsonb_populate_record(NULL::{}, $1::jsonb)", + table, table + )) + .bind(json_str) + .execute(pool) + .await?; + + Ok(()) +} + +async fn delete_existing_records(pool: &sqlx::PgPool, uuid: &str) -> Result { + let mut deleted = 0; + + let tables = [ + ("processor_results", "file_uuid"), + ("monitor_jobs", "uuid"), + ("trace_profiles", "file_uuid"), + ("tkg_nodes", "file_uuid"), + ("tkg_edges", "file_uuid"), + ("chunk", "file_uuid"), + ("face_detections", "file_uuid"), + ("videos", "file_uuid"), + ]; + + for (table, col) in tables { + let table_name = crate::core::db::schema::table_name(table); + let result = sqlx::query(&format!("DELETE FROM {} WHERE {} = $1", table_name, col)) + .bind(uuid) + .execute(pool) + .await; + + if let Ok(r) = result { + deleted += r.rows_affected() as usize; + } + } + + Ok(deleted) +} + +fn copy_dir_all(src: &std::path::Path, dest: &std::path::Path) -> Result<()> { + std::fs::create_dir_all(dest)?; + for entry in std::fs::read_dir(src)? { + let entry = entry?; + let path = entry.path(); + let dest_path = dest.join(entry.file_name()); + if path.is_dir() { + copy_dir_all(&path, &dest_path)?; + } else { + std::fs::copy(&path, &dest_path)?; + } + } + Ok(()) +} + +use anyhow::Result; + +// ─── Router ────────────────────────────────────────────────────────────────── + +pub fn import_routes() -> Router { + Router::new() + .route("/api/v1/import", post(import_file_handler)) + .route("/api/v1/import/list", post(list_packages_handler)) +} diff --git a/src/api/markbase_compat.rs b/src/api/markbase_compat.rs index 5ad3191c..bf4ca55e 100644 --- a/src/api/markbase_compat.rs +++ b/src/api/markbase_compat.rs @@ -1,7 +1,8 @@ -use axum::{extract::Path, http::StatusCode, response::Json, routing::get, Router}; +use axum::{extract::{Path, Query}, http::StatusCode, response::Json, routing::get, Router}; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use tokio::fs; +use tokio::io::AsyncSeekExt; #[derive(Debug, Serialize, Deserialize)] pub struct FileInfo { @@ -111,4 +112,52 @@ pub fn markbase_routes() -> Router { Router::new() .route("/api/v2/myfiles/:username/folders", get(list_user_folders)) .route("/api/v2/myfiles/:username/files", get(list_user_files)) + .route("/api/v2/myfiles/preview-by-path", get(preview_file_by_path)) +} + +// 通用檔案預覽 - 支援任意路徑 +#[derive(Debug, Deserialize)] +pub struct PreviewQuery { + pub path: Option, +} + +pub async fn preview_file_by_path( + Query(params): Query, +) -> Result { + let file_path = params.path.ok_or(StatusCode::BAD_REQUEST)?; + let path = std::path::Path::new(&file_path); + + if !path.exists() { + return Err(StatusCode::NOT_FOUND); + } + + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_lowercase(); + let content_type = match ext.as_str() { + "mp4" => "video/mp4", + "mov" => "video/quicktime", + "mkv" => "video/x-matroska", + "avi" => "video/x-msvideo", + "webm" => "video/webm", + "mp3" => "audio/mpeg", + "wav" => "audio/wav", + "jpg" | "jpeg" => "image/jpeg", + "png" => "image/png", + "gif" => "image/gif", + "webp" => "image/webp", + "pdf" => "application/pdf", + "txt" | "md" | "json" | "xml" => "text/plain", + _ => "application/octet-stream", + }; + + match tokio::fs::read(path).await { + Ok(data) => { + Ok(axum::response::Response::builder() + .header("Content-Type", content_type) + .header("Content-Length", data.len()) + .header("Accept-Ranges", "bytes") + .body(axum::body::Body::from(data)) + .unwrap()) + } + Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR), + } } diff --git a/src/api/media_api.rs b/src/api/media_api.rs index 53f59460..5916e0c8 100644 --- a/src/api/media_api.rs +++ b/src/api/media_api.rs @@ -88,10 +88,6 @@ pub fn bbox_routes() -> Router { "/api/v1/file/:file_uuid/chunk/:chunk_id/thumbnail", get(chunk_thumbnail), ) - .route( - "/api/v1/file/:file_uuid/scenes/:filename", - get(scene_thumbnail), - ) .route("/api/v1/file/:file_uuid/clip", get(video_clip)) } @@ -926,6 +922,7 @@ async fn face_thumbnail_compat( /// Thumbnail by file path — for unregistered files (no UUID). /// Frontend calls: GET /api/v1/file/thumbnail?path=&frame= async fn thumbnail_by_path( + State(state): State, Query(q): Query, ) -> Result { let file_path = q.path.ok_or(StatusCode::BAD_REQUEST)?; @@ -937,12 +934,12 @@ async fn thumbnail_by_path( return Err(StatusCode::BAD_REQUEST); } + // Fallback 用 momentry root(~/momentry),而非 current_exe 的父目錄 — + // 部署時 binary 在 /bin/ 下,直接取 parent 會多一層 bin 導致 403。 let scan_root = std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| { - std::env::current_exe() - .ok() - .and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data/demo"))) - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_else(|| "/tmp".to_string()) + crate::core::path_utils::demo_dir() + .to_string_lossy() + .to_string() }); let canonical_root = std::fs::canonicalize(&scan_root).unwrap_or_else(|_| { @@ -952,7 +949,20 @@ async fn thumbnail_by_path( std::path::PathBuf::from(&file_path) }); - if !canonical_file.starts_with(&canonical_root) { + // 允許範圍:SFTP root + 所有已啟用的 upload_paths(不同 library 可在不同磁碟) + let mut allowed_roots = vec![canonical_root.clone()]; + let paths_table = crate::core::db::schema::table_name("upload_paths"); + if let Ok(rows) = sqlx::query_scalar::<_, String>(&format!("SELECT full_path FROM {} WHERE enabled = true", paths_table)) + .fetch_all(state.db.pool()) + .await + { + for root in rows { + let canonical = std::fs::canonicalize(&root).unwrap_or_else(|_| std::path::PathBuf::from(&root)); + allowed_roots.push(canonical); + } + } + + if !allowed_roots.iter().any(|root| canonical_file.starts_with(root)) { tracing::warn!( "[thumbnail_by_path] Path outside scan root rejected: {} (root: {})", file_path, scan_root @@ -964,6 +974,33 @@ async fn thumbnail_by_path( return Err(StatusCode::NOT_FOUND); } + // Check thumbnail cache first + let cache_dir = std::env::var("MOMENTRY_THUMBNAIL_CACHE") + .unwrap_or_else(|_| "/Users/accusys/momentry/var/thumbnails".to_string()); + let cache_path = std::path::PathBuf::from(&cache_dir); + if cache_path.exists() { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + let mut hasher = DefaultHasher::new(); + file_path.hash(&mut hasher); + frame.hash(&mut hasher); + let hash = hasher.finish(); + let thumb_file = cache_path.join(format!("{:x}_f{}.jpg", hash, frame)); + if thumb_file.exists() { + if let Ok(data) = std::fs::read(&thumb_file) { + // Cache is valid if source file hasn't changed since cache was created + // (source mtime <= cache mtime means source is older or same age) + if let (Ok(meta), Ok(cache_meta)) = (std::fs::metadata(&canonical_file), std::fs::metadata(&thumb_file)) { + if let (Ok(src_mtime), Ok(cache_mtime)) = (meta.modified(), cache_meta.modified()) { + if src_mtime <= cache_mtime { + return Ok(image_response(data)); + } + } + } + } + } + } + // Extract frame with ffmpeg let select = format!("select=eq(n\\,{})", frame); let output = ffmpeg_cmd() @@ -996,6 +1033,25 @@ async fn thumbnail_by_path( StatusCode::INTERNAL_SERVER_ERROR })?; + // Cache thumbnail to disk for faster subsequent loads + let cache_dir = std::env::var("MOMENTRY_THUMBNAIL_CACHE") + .unwrap_or_else(|_| "/Users/accusys/momentry/var/thumbnails".to_string()); + let cache_path = std::path::PathBuf::from(&cache_dir); + if !cache_path.exists() { + let _ = std::fs::create_dir_all(&cache_path); + } + if cache_path.exists() { + // Create cache key from file path and frame + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + let mut hasher = DefaultHasher::new(); + file_path.hash(&mut hasher); + frame.hash(&mut hasher); + let hash = hasher.finish(); + let thumb_file = cache_path.join(format!("{:x}_f{}.jpg", hash, frame)); + let _ = std::fs::write(&thumb_file, &output.stdout); + } + Ok(image_response(output.stdout)) } @@ -1045,7 +1101,7 @@ async fn trace_thumbnail( /// Serve a scene frame image (`scene_*.jpg`) directly from the output dir. /// Path mirrors `thumbnail_url` produced by the VLM scene search API. /// e.g. /api/v1/file/{file_uuid}/scenes/scene_000.jpg -async fn scene_thumbnail( +pub async fn scene_thumbnail( State(_state): State, Path((file_uuid, filename)): Path<(String, String)>, ) -> Result { diff --git a/src/api/middleware.rs b/src/api/middleware.rs index 03a54b45..61e8f68f 100644 --- a/src/api/middleware.rs +++ b/src/api/middleware.rs @@ -177,13 +177,31 @@ fn extract_api_key(headers: &HeaderMap, uri: &axum::http::Uri) -> Result) -> String { + for h in ["x-forwarded-for", "x-real-ip"] { + if let Some(v) = headers.get(h).and_then(|v| v.to_str().ok()) { + // X-Forwarded-For may be a list: first hop is the original client + let first = v.split(',').next().unwrap_or(v).trim(); + if !first.is_empty() { + return first.to_string(); + } + } + } + addr.map(|a| a.ip().to_string()).unwrap_or_else(|| "unknown".to_string()) +} + pub async fn unified_auth( State(state): State, + axum::extract::ConnectInfo(addr): axum::extract::ConnectInfo, mut request: Request, next: Next, ) -> Response { let headers = request.headers(); let uri = request.uri().clone(); + let client_addr = client_ip(headers, Some(addr)); // Priority 1: Cookie session let cookies = extract_cookies(headers); @@ -205,7 +223,7 @@ pub async fn unified_auth( jwt_jti: None, jwt_exp: None, }; - if let Err(e) = state.db.update_api_key_usage(&record.key_id, None).await { + if let Err(e) = state.db.update_api_key_usage(&record.key_id, Some(client_addr.as_str())).await { tracing::warn!("[AUTH] Failed to update key usage: {}", e); } request.extensions_mut().insert(auth); @@ -320,7 +338,7 @@ pub async fn unified_auth( jwt_exp: None, }; - if let Err(e) = state.db.update_api_key_usage(&record.key_id, None).await { + if let Err(e) = state.db.update_api_key_usage(&record.key_id, Some(client_addr.as_str())).await { tracing::warn!("[AUTH] Failed to update key usage: {}", e); } diff --git a/src/api/mod.rs b/src/api/mod.rs index ae6fceeb..709564be 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -8,6 +8,7 @@ pub mod clip_api; pub mod cluster_agent; pub mod monitor; pub mod docs; +pub mod export_api; pub mod face_filter; pub mod file_progress; pub mod files; @@ -30,7 +31,16 @@ pub mod tmdb_api; pub mod trace_agent_api; pub mod types; pub mod universal_search; +pub mod folder_api; +pub mod import_api; +pub mod unregister_api; pub mod vlm_search; pub mod job_management; pub use server::start_server; +mod admin_cleanup; +mod pipeline_tools; +mod upload_paths; +mod file_replicas; +mod mount_points; +mod directory_browser; diff --git a/src/api/mount_points.rs b/src/api/mount_points.rs new file mode 100644 index 00000000..a13d741a --- /dev/null +++ b/src/api/mount_points.rs @@ -0,0 +1,182 @@ +//! Mount Points API - Display views for file replicas + +use axum::{ + extract::{Path, State, Query}, + http::StatusCode, + response::Json, + routing::{get, post, delete}, + Router, +}; +use serde::{Deserialize, Serialize}; +use sqlx::{PgPool, FromRow}; +use tracing::{error, info}; + +use crate::api::types::AppState; + +#[derive(Debug, Serialize, Deserialize, FromRow)] +pub struct MountPoint { + pub id: i32, + pub name: String, + pub mount_path: String, + pub description: Option, + pub enabled: bool, + pub created_at: Option, +} + +#[derive(Debug, Serialize, Deserialize, FromRow)] +pub struct MountReplica { + pub id: i32, + pub mount_id: i32, + pub replica_id: i32, + pub display_name: Option, + pub display_order: i32, + pub file_uuid: String, + pub replica_path: String, + pub replica_name: Option, + pub is_primary: bool, +} + +#[derive(Debug, Deserialize)] +pub struct CreateMountRequest { + pub name: String, + pub mount_path: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct AddReplicaToMountRequest { + pub replica_id: i32, + pub display_name: Option, + pub display_order: Option, +} + +pub fn mount_point_routes() -> Router { + Router::new() + .route("/api/v1/admin/mounts", get(list_mounts)) + .route("/api/v1/admin/mounts", post(create_mount)) + .route("/api/v1/admin/mount-replicas/:replica_id", delete(remove_replica_from_mount)) + .route("/api/v1/admin/mount-replicas", get(list_mount_replicas)) + .route("/api/v1/admin/mount-replicas", post(add_replica_to_mount)) + .route("/api/v1/admin/mounts/:id", get(get_mount)) + .route("/api/v1/admin/mounts/:id", delete(delete_mount)) +} + +fn get_pool(state: &AppState) -> &PgPool { + state.db.pool() +} + +async fn list_mounts(State(state): State) -> Result>, StatusCode> { + let pool = get_pool(&state); + let mounts = sqlx::query_as::<_, MountPoint>( + "SELECT id, name, mount_path, description, enabled, created_at::text + FROM mount_points WHERE enabled = TRUE ORDER BY name" + ) + .fetch_all(pool) + .await + .map_err(|e| { error!("[mounts] list failed: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; + Ok(Json(mounts)) +} + +async fn create_mount( + State(state): State, + Json(req): Json, +) -> Result, StatusCode> { + let pool = get_pool(&state); + let mount = sqlx::query_as::<_, MountPoint>( + "INSERT INTO mount_points (name, mount_path, description) VALUES ($1, $2, $3) + RETURNING id, name, mount_path, description, enabled, created_at::text" + ) + .bind(&req.name) + .bind(&req.mount_path) + .bind(&req.description) + .fetch_one(pool) + .await + .map_err(|e| { error!("[mounts] create failed: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; + info!("[mounts] created: {} -> {}", mount.name, mount.mount_path); + Ok(Json(mount)) +} + +async fn delete_mount( + State(state): State, + Path(id): Path, +) -> Result, StatusCode> { + let pool = get_pool(&state); + sqlx::query("DELETE FROM mount_points WHERE id = $1 AND name NOT IN ('library', 'upload', 'archive')") + .bind(id) + .execute(pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(serde_json::json!({"success": true}))) +} + +async fn list_mount_replicas( + State(state): State, + Query(params): Query>, +) -> Result>, StatusCode> { + let id: i32 = params.get("mount_id").and_then(|v| v.parse().ok()).ok_or(StatusCode::BAD_REQUEST)?; + let pool = get_pool(&state); + let replicas = sqlx::query_as::<_, MountReplica>( + "SELECT mr.id, mr.mount_id, mr.replica_id, mr.display_name, mr.display_order, + fr.file_uuid, fr.replica_path, fr.replica_name, fr.is_primary + FROM mount_replicas mr + JOIN file_replicas fr ON fr.id = mr.replica_id + WHERE mr.mount_id = $1 + ORDER BY mr.display_order, mr.id" + ) + .bind(id) + .fetch_all(pool) + .await + .map_err(|e| { error!("[mounts] replicas list failed: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; + Ok(Json(replicas)) +} + +async fn add_replica_to_mount( + State(state): State, + Path(id): Path, + Json(req): Json, +) -> Result, StatusCode> { + let pool = get_pool(&state); + sqlx::query( + "INSERT INTO mount_replicas (mount_id, replica_id, display_name, display_order) + VALUES ($1, $2, $3, $4) ON CONFLICT (mount_id, replica_id) DO NOTHING" + ) + .bind(id) + .bind(req.replica_id) + .bind(&req.display_name) + .bind(req.display_order.unwrap_or(0)) + .execute(pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(serde_json::json!({"success": true}))) +} + +async fn remove_replica_from_mount( + State(state): State, + Path((id, replica_id)): Path<(i32, i32)>, +) -> Result, StatusCode> { + let pool = get_pool(&state); + sqlx::query("DELETE FROM mount_replicas WHERE mount_id = $1 AND replica_id = $2") + .bind(id) + .bind(replica_id) + .execute(pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(serde_json::json!({"success": true}))) +} + +async fn get_mount( + State(state): State, + Path(id): Path, +) -> Result, StatusCode> { + let pool = get_pool(&state); + let mount = sqlx::query_as::<_, MountPoint>( + "SELECT id, name, mount_path, description, enabled, created_at::text + FROM mount_points WHERE id = $1" + ) + .bind(id) + .fetch_optional(pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(mount)) +} diff --git a/src/api/pipeline_tools.rs b/src/api/pipeline_tools.rs new file mode 100644 index 00000000..030b2ec3 --- /dev/null +++ b/src/api/pipeline_tools.rs @@ -0,0 +1,280 @@ +use axum::{ + extract::State, + http::StatusCode, + response::Json, + routing::get, + Router, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::path::Path; + +use crate::api::types::AppState; + +#[derive(Serialize, Deserialize, Clone)] +struct ToolInfo { + key: String, + name: String, + available: bool, + detail: String, + path: String, + version: String, +} + +#[derive(Serialize, Deserialize)] +struct PipelineData { + cli: Vec, + asr: Vec, + face: Vec, + services: Vec, + worker: Option, +} + +/// Check if a binary exists and is executable +fn probe_binary(path: &Path, name: &str, _version_args: Option<&str>) -> ToolInfo { + let available = path.exists() && path.is_file(); + + let version = if available { + // For now, just check file metadata; version extraction would require running the binary + "installed".to_string() + } else { + String::new() + }; + + let detail = if available { + match path.metadata() { + Ok(meta) => { + let size = meta.len(); + if size >= 1_073_741_824 { + format!("{:.1} GB", size as f64 / 1_073_741_824.0) + } else if size >= 1_048_576 { + format!("{:.1} MB", size as f64 / 1_048_576.0) + } else { + format!("{:.0} KB", size as f64 / 1024.0) + } + } + Err(_) => "unknown size".to_string(), + } + } else { + "Not found".to_string() + }; + + ToolInfo { + key: name.replace(' ', "_").to_lowercase(), + name: name.to_string(), + available, + detail, + path: path.to_string_lossy().to_string(), + version, + } +} + +/// Probe a service health endpoint (async) +async fn probe_service(name: &str, url: &str, detail: &str) -> ToolInfo { + // The URL may be a bare host, a /health endpoint, or an API path such as + // /v1/chat/completions — always probe the server root /health. + let base = match url.find("/v1/") { + Some(pos) => url[..pos].to_string(), + None => url.trim_end_matches('/').to_string(), + }; + let health_url = if base.to_lowercase().ends_with("/health") { + base.clone() + } else { + format!("{}/health", base) + }; + + let available = match reqwest::get(&health_url).await { + Ok(resp) => resp.status().is_success(), + Err(_) => false, + }; + + ToolInfo { + key: name.replace(' ', "_").to_lowercase(), + name: name.to_string(), + available, + detail: detail.to_string(), + path: url.to_string(), + version: if available { "Running".to_string() } else { "Stopped".to_string() }, + } +} + +/// Check if a binary is in PATH +fn find_in_path(binary: &str) -> Option { + if let Ok(paths) = std::env::var("PATH") { + for dir in paths.split(':') { + let candidate = Path::new(dir).join(binary); + if candidate.exists() && candidate.is_file() { + return Some(candidate.to_string_lossy().to_string()); + } + } + } + None +} + +/// Check if worker process is running +fn probe_worker() -> Option { + let output = std::process::Command::new("pgrep") + .arg("-f") + .arg("momentry worker") + .output() + .ok()?; + + if output.status.success() { + let pids = String::from_utf8_lossy(&output.stdout) + .trim() + .to_string(); + Some(ToolInfo { + key: "worker".to_string(), + name: "Momentry Worker".to_string(), + available: true, + detail: format!("PIDs: {}", pids), + path: "momentry worker".to_string(), + version: "Running".to_string(), + }) + } else { + None + } +} + +pub async fn probe_pipeline_tools( + State(state): State, +) -> Result, StatusCode> { + let scripts_dir = crate::core::config::SCRIPTS_DIR.as_str(); + let cli_dir = crate::core::config::CLI_DIR.as_str(); + + // CLI Tools (Swift processors) + let swift_release = format!("{}/swift_processors/.build/release", scripts_dir); + // ASR / ASRX Tools (Rust) + let rust_release = format!("{}/rust/target/release", cli_dir); + let cli_tools = vec![ + probe_binary( + Path::new(&format!("{}/swift_face", swift_release)), + "Swift Face", + None, + ), + probe_binary( + Path::new(&format!("{}/swift_ocr", swift_release)), + "Swift OCR", + None, + ), + probe_binary( + Path::new(&format!("{}/swift_scene_detector", swift_release)), + "Swift Scene Cut", + None, + ), + probe_binary( + Path::new(&format!("{}/rust_cut", rust_release)), + "Rust Scene Cut", + None, + ), + ]; + + // ASR / ASRX Tools (Rust) + let asr_tools = vec![ + probe_binary( + Path::new(&format!("{}/rust_asr_asrx", rust_release)), + "Rust ASR/ASRX", + None, + ), + probe_binary( + Path::new(&format!("{}/rust_whisper_rs", rust_release)), + "Rust Whisper", + None, + ), + ]; + + // Face Tools (Rust) + let face_tools = vec![ + probe_binary( + Path::new(&format!("{}/rust_appearance", rust_release)), + "Rust Appearance", + None, + ), + probe_binary( + Path::new(&format!("{}/rust_face_processor", rust_release)), + "Rust Face Processor", + None, + ), + probe_binary( + Path::new(&format!("{}/rust_face_cluster", rust_release)), + "Rust Face Cluster", + None, + ), + probe_binary( + Path::new(&format!("{}/rust_store_traced_faces", rust_release)), + "Rust Store Traced Faces", + None, + ), + ]; + + // Services + let chat_url = crate::core::config::LLM_HEALTH_URL.as_str(); + let embed_url = crate::core::config::EMBED_URL.as_str(); + + // VLM URL from admin config + let vlm_url = state + .admin_config_manager + .get_llm_config("vlm") + .await + .map(|c| c.url) + .unwrap_or_else(|| "http://localhost:8082".to_string()); + + let chat_svc = probe_service("Chat LLM", chat_url, "LLM Inference Server").await; + let embed_svc = probe_service("Embedding", embed_url, "Embedding Server").await; + let vlm_svc = probe_service("VLM llama-server", &vlm_url, "Vision Language Model").await; + + let services = vec![chat_svc, embed_svc, vlm_svc]; + + // Worker + let worker = probe_worker(); + + let data = PipelineData { + cli: cli_tools, + asr: asr_tools, + face: face_tools, + services, + worker, + }; + + Ok(Json(serde_json::to_value(data).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?)) +} + +/// Probe release tools (pg_dump, release_pack.py, etc.) +pub async fn probe_release_tools( + State(_state): State, +) -> Result, StatusCode> { + let mut tools = Vec::new(); + + // Check release_pack.py + let momentry_root = crate::core::path_utils::momentry_root(); + let release_pack = momentry_root.join("scripts/release_pack.py"); + tools.push(json!({ + "name": "release_pack.py", + "available": release_pack.exists(), + "path": release_pack.to_string_lossy().to_string(), + })); + + // Check pg_dump + let pg_dump_path = find_in_path("pg_dump"); + tools.push(json!({ + "name": "pg_dump", + "available": pg_dump_path.is_some(), + "path": pg_dump_path.unwrap_or_else(|| "Not found".to_string()), + })); + + // Check ffmpeg + let ffmpeg_path = find_in_path("ffmpeg"); + tools.push(json!({ + "name": "ffmpeg", + "available": ffmpeg_path.is_some(), + "path": ffmpeg_path.unwrap_or_else(|| "Not found".to_string()), + })); + + Ok(Json(json!({ "tools": tools }))) +} + +pub fn pipeline_tools_routes() -> Router { + Router::new() + .route("/api/v1/admin/pipeline-tools", get(probe_pipeline_tools)) + .route("/api/v1/admin/release-tools", get(probe_release_tools)) +} diff --git a/src/api/processing.rs b/src/api/processing.rs index d5e35544..5552171a 100644 --- a/src/api/processing.rs +++ b/src/api/processing.rs @@ -901,6 +901,103 @@ struct ProcessorCountsResponse { /// GET /api/v1/processor-json?file_hash=...&processor=... /// Serves raw processor output JSON files from the output directory. +/// GET /api/v1/output-completeness +/// 檢查所有影片的產出完整性,回傳缺項清單。 +/// 前端用此 API 將有缺項的 completed 卡片改為紅字顯示。 +#[derive(serde::Serialize)] +struct OutputCompletenessItem { + file_uuid: String, + file_name: String, + status: String, + is_complete: bool, + missing: Vec, +} + +async fn get_output_completeness( + State(state): State, +) -> Result, StatusCode> { + let output_dir = crate::core::config::OUTPUT_DIR.to_string(); + let videos_table = schema::table_name("videos"); + + let rows: Vec<(String, String, String)> = sqlx::query_as(&format!( + "SELECT file_uuid, file_name, status FROM {} WHERE file_type = 'video' ORDER BY file_name", + videos_table + )) + .fetch_all(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[output-completeness] DB query failed: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + let mut items = Vec::new(); + + for (uuid, file_name, status) in rows { + if status != "completed" { + continue; // 只檢查 completed 的影片 + } + + let mut missing = Vec::new(); + + // 檢查 JSON 產出 + for ext in ["asrx", "cut", "face", "face_cluster", "face_traced", "ocr", "scenes"] { + let path = format!("{}/{}.{}.json", output_dir, uuid, ext); + if !std::path::Path::new(&path).exists() { + missing.push(format!("{}.json", ext)); + } + } + + // 檢查 trace 目錄(如果有 faces) + let face_json = format!("{}/{}.face.json", output_dir, uuid); + if std::path::Path::new(&face_json).exists() { + if let Ok(content) = std::fs::read_to_string(&face_json) { + if let Ok(data) = serde_json::from_str::(&content) { + let total_faces = data + .get("total_faces") + .or_else(|| data.get("data").and_then(|d| d.get("total_faces"))) + .and_then(|v| v.as_u64()) + .unwrap_or(0); + if total_faces > 0 { + let trace_base = std::path::Path::new(&output_dir).join(&uuid); + if trace_base.is_dir() { + if let Ok(entries) = std::fs::read_dir(&trace_base) { + for entry in entries.filter_map(|e| e.ok()) { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with("trace_") && entry.path().is_dir() { + for f in ["key_face.jpg", "key_frame.jpg", "trace_profile.json"] { + if !entry.path().join(f).exists() { + missing.push(format!("{}/{}", name, f)); + } + } + } + } + } + } + } + } + } + } + + items.push(OutputCompletenessItem { + file_uuid: uuid, + file_name, + status, + is_complete: missing.is_empty(), + missing, + }); + } + + let complete_count = items.iter().filter(|i| i.is_complete).count(); + let incomplete_count = items.len() - complete_count; + + Ok(Json(serde_json::json!({ + "total": items.len(), + "complete": complete_count, + "incomplete": incomplete_count, + "items": items, + }))) +} + async fn get_processor_json( Query(params): Query>, ) -> Result, (StatusCode, Json)> { @@ -1156,6 +1253,7 @@ async fn trigger_vlm_summary( pub fn processing_routes() -> Router { Router::new() + .route("/api/v1/output-completeness", get(get_output_completeness)) .route("/api/v1/file/:file_uuid/process", post(trigger_processing)) .route( "/api/v1/file/:file_uuid/json/:processor", diff --git a/src/api/profile.rs b/src/api/profile.rs index f9010850..3d189d95 100644 --- a/src/api/profile.rs +++ b/src/api/profile.rs @@ -12,6 +12,188 @@ use crate::api::types::AppState; use crate::core::db::schema; use crate::core::file_profile::FaceFilterSettings; +/// Materialize automatic clusters (face_cluster.json `Person_N`) into real +/// `face_groups` rows the first time a file is viewed. After that the DB is +/// the single source of truth: face_cluster.json is only read for frames, +/// similarity and representative data, never for grouping again. +/// +/// Idempotent: does nothing when the file already has face_groups rows. +async fn materialize_auto_groups(pool: &PgPool, file_uuid: &str) -> Result<(), StatusCode> { + let tp_table = schema::table_name("trace_profiles"); + let fg_table = schema::table_name("face_groups"); + + let existing: i64 = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {fg_table} WHERE file_uuid = $1" + )) + .bind(file_uuid) + .fetch_one(pool) + .await + .map_err(|e| { + tracing::error!("[FaceGroups] count error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + // Traces that already belong to a named group keep their assignment. + let assigned: std::collections::HashSet = sqlx::query_scalar(&format!( + "SELECT trace_id FROM {tp_table} WHERE file_uuid = $1 AND group_id IS NOT NULL" + )) + .bind(file_uuid) + .fetch_all(pool) + .await + .map_err(|e| { + tracing::error!("[FaceGroups] assigned query error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })? + .into_iter() + .collect(); + + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid); + let Ok(content) = std::fs::read_to_string(&fc_path) else { + return Ok(()); // no auto clusters yet — done + }; + let Ok(data) = serde_json::from_str::(&content) else { + return Ok(()); + }; + + // Clusters that already have a group row (active or dissolved) are never + // re-materialized: dissolving a group must stick across reads/refreshes. + // Only consider origins from groups that actually have members — orphaned + // groups (0 traces) must NOT block re-materialization. + let origins: std::collections::HashSet = sqlx::query_scalar(&format!( + "SELECT DISTINCT g.origin_cluster_id FROM {fg_table} g \ + WHERE g.file_uuid = $1 AND g.origin_cluster_id IS NOT NULL \ + AND EXISTS (SELECT 1 FROM {tp_table} tp WHERE tp.group_id = g.id)" + )) + .bind(file_uuid) + .fetch_all(pool) + .await + .map_err(|e| { + tracing::error!("[FaceGroups] origins query error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })? + .into_iter() + .collect(); + + // Traces manually ungrouped (tombstoned groups record their members). + let mut dissolved_traces: std::collections::HashSet = std::collections::HashSet::new(); + let member_rows: Vec = sqlx::query_scalar(&format!( + "SELECT properties->'member_traces' FROM {fg_table} WHERE file_uuid = $1 AND properties @> '{{\"dissolved\": true}}'::jsonb" + )) + .bind(file_uuid) + .fetch_all(pool) + .await + .map_err(|e| { + tracing::error!("[FaceGroups] dissolved query error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + for v in member_rows { + if let Some(arr) = v.as_array() { + for t in arr { + if let Some(tid) = t.as_i64() { + dissolved_traces.insert(tid as i32); + } + } + } + } + + // Collect per-cluster trace_ids from frames (faces carry trace_id + cluster_id) + let mut cluster_traces: HashMap> = HashMap::new(); + if let Some(frames) = data.get("frames").and_then(|f| f.as_array()) { + for frame in frames { + if let Some(faces) = frame.get("faces").and_then(|f| f.as_array()) { + for face in faces { + if let (Some(trace_id), Some(cluster_id)) = ( + face.get("trace_id").and_then(|v| v.as_i64()), + face.get("cluster_id").and_then(|v| v.as_str()), + ) { + let trace_id = trace_id as i32; + let list = cluster_traces.entry(cluster_id.to_string()).or_default(); + if !list.contains(&trace_id) { + list.push(trace_id); + } + } + } + } + } + } + + // Sort clusters: "Person_N" by N ascending, others lexicographic last. + let mut cluster_ids: Vec = cluster_traces + .keys() + .cloned() + .collect(); + cluster_ids.sort_by(|a, b| { + let num = |s: &str| -> Option { + s.strip_prefix("Person_").and_then(|n| n.parse().ok()) + }; + match (num(a), num(b)) { + (Some(x), Some(y)) => x.cmp(&y), + (Some(_), None) => std::cmp::Ordering::Less, + (None, Some(_)) => std::cmp::Ordering::Greater, + (None, None) => a.cmp(b), + } + }); + + let mut seq: i64 = 0; + for cid in cluster_ids.iter() { + // Skip clusters whose members are all already grouped, clusters that + // already own a group row, and clusters the user dissolved. + let members = &cluster_traces[cid]; + if members.is_empty() || origins.contains(cid) { + continue; + } + if members.iter().all(|tid| assigned.contains(tid)) { + continue; + } + if members.iter().any(|tid| dissolved_traces.contains(tid)) { + continue; + } + let idx = seq; + seq += 1; + // Use cluster_id as group name (e.g., "Person_0" -> "Person 0") + let group_name = cid.replace('_', " "); + let gid: i64 = sqlx::query_scalar(&format!( + "INSERT INTO {fg_table} (file_uuid, name, origin_cluster_id, sort_index) \ + VALUES ($1, $2, $3, $4) \ + ON CONFLICT (file_uuid, name) DO UPDATE SET updated_at = NOW() \ + RETURNING id" + )) + .bind(file_uuid) + .bind(&group_name) + .bind(cid) + .bind(idx as i32) + .fetch_one(pool) + .await + .map_err(|e| { + tracing::error!("[FaceGroups] insert group error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + for trace_id in &cluster_traces[cid] { + // Create missing profile rows; attach group_id to existing ones + // and sync name to match the group name. + let _ = sqlx::query(&format!( + "INSERT INTO {tp_table} (file_uuid, trace_id, name, group_id, status) \ + VALUES ($1, $2, $3, $4, 'pending') \ + ON CONFLICT (file_uuid, trace_id) \ + DO UPDATE SET group_id = COALESCE({tp_table}.group_id, $4), name = $3" + )) + .bind(file_uuid) + .bind(trace_id) + .bind(&group_name) + .bind(gid) + .execute(pool) + .await; + } + } + + // Persist face groups to JSON after materialization + let _ = schema::save_face_groups_json(pool, file_uuid).await; + + Ok(()) +} + fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 { if a.len() != b.len() || a.is_empty() { return 0.0; @@ -174,7 +356,7 @@ let row: Option<( // Construct path: {output_dir}/{file_uuid}/trace_{trace_id}/trace_profile.json let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR") - .unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string()); + .unwrap_or_else(|_| crate::core::config::OUTPUT_DIR.to_string().to_string()); let profile_path = std::path::Path::new(&output_dir) .join(file_uuid) .join(format!("trace_{}", trace_id)) @@ -395,13 +577,16 @@ pub async fn update_trace_profile_group_handler( Json(req): Json, ) -> Result, StatusCode> { let tp_table = schema::table_name("trace_profiles"); + let fg_table = schema::table_name("face_groups"); + let nodes_table = schema::table_name("tkg_nodes"); + let mut updated: u64 = 0; - // Snapshot current names before update + // 1. Snapshot each trace's current name + group (for undo + rename detection) let mut before_names: serde_json::Map = serde_json::Map::new(); + let mut current_groups: HashMap> = HashMap::new(); for trace_id in &req.trace_ids { - let current: Option<(String,)> = sqlx::query_as(&format!( - "SELECT name FROM {} WHERE file_uuid = $1 AND trace_id = $2", - tp_table + let row: Option<(Option, Option)> = sqlx::query_as(&format!( + "SELECT name, group_id FROM {tp_table} WHERE file_uuid = $1 AND trace_id = $2" )) .bind(&req.file_uuid) .bind(trace_id) @@ -411,48 +596,229 @@ pub async fn update_trace_profile_group_handler( tracing::error!("[TraceProfileGroup] DB error: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - if let Some((name,)) = current { - before_names.insert(trace_id.to_string(), serde_json::json!(name)); + if let Some((name, group_id)) = row { + before_names.insert(trace_id.to_string(), serde_json::json!(name.unwrap_or_default())); + if let Some(gid) = group_id { + current_groups.entry(gid).or_default().push(*trace_id); + } } } - let mut updated = 0; - let nodes_table = schema::table_name("tkg_nodes"); - for trace_id in &req.trace_ids { - // Self-healing: make sure the face_track node exists. - let _ = - schema::ensure_face_track_node(state.db.pool(), &req.file_uuid, *trace_id, &req.name) - .await; - - match schema::upsert_trace_profile( - state.db.pool(), - &req.file_uuid, - *trace_id, - &req.name, - None, - ) + // 1.5 Face-groups normalization (V1.0 §7 G3): "Unassigned" is not a real + // group (I4 — assigned ⇔ group_id IS NOT NULL). This request means + // DETACH: drop traces out of their groups without materializing an + // "Unassigned" row, and tombstone any group that becomes empty so the + // cluster materializer will not resurrect it on the next read. + if req.name.trim().eq_ignore_ascii_case("unassigned") { + let detach = sqlx::query(&format!( + "UPDATE {tp_table} SET group_id = NULL WHERE file_uuid = $1 AND trace_id = ANY($2)" + )) + .bind(&req.file_uuid) + .bind(&req.trace_ids) + .execute(state.db.pool()) .await - { - Ok(affected) => updated += affected, - Err(e) => { - tracing::error!("[TraceProfileGroup] UPSERT error: {}", e); - return Err(StatusCode::INTERNAL_SERVER_ERROR); + .map_err(|e| { + tracing::error!("[TraceProfileGroup] detach error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + updated = detach.rows_affected(); + + // Tombstone emptied groups with their former member list. + for (gid, members) in ¤t_groups { + let remaining: i64 = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 AND group_id = $2" + )) + .bind(&req.file_uuid) + .bind(gid) + .fetch_one(state.db.pool()) + .await + .unwrap_or(0); + if remaining == 0 { + let _ = sqlx::query(&format!( + "UPDATE {fg_table} SET properties = COALESCE(properties, '{{}}'::jsonb) || $1::jsonb, updated_at = NOW() WHERE id = $2" + )) + .bind(serde_json::json!({"dissolved": true, "member_traces": members})) + .bind(gid) + .execute(state.db.pool()) + .await; } } - // Keep tkg_nodes.label in sync with the profile name. - if let Err(e) = sqlx::query(&format!( - "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND (external_id = $3 OR (properties->>'trace_id')::int = $4)", - nodes_table + // Reset captions + KG labels to the auto-trace default (matches the + // unassign semantics in trace_agent_api hard_delete). + let _ = sqlx::query(&format!( + "UPDATE {tp_table} SET name = 'Face Trace ' || trace_id::text WHERE file_uuid = $1 AND trace_id = ANY($2)" + )) + .bind(&req.file_uuid) + .bind(&req.trace_ids) + .execute(state.db.pool()) + .await; + let _ = sqlx::query(&format!( + "UPDATE {nodes_table} tn SET label = 'Face Trace ' || (tn.properties->>'trace_id')::text WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' AND (tn.properties->>'trace_id')::int = ANY($2)" + )) + .bind(&req.file_uuid) + .bind(&req.trace_ids) + .execute(state.db.pool()) + .await; + + let _ = save_trace_operation_snapshot( + state.db.pool(), + &req.file_uuid, + "ungroup", + serde_json::json!({ "traces": before_names }), + Some(serde_json::json!({ + "traces": req.trace_ids.iter().map(|tid| (tid.to_string(), serde_json::json!("Unassigned"))).collect::>() + })), + None, + ).await; + + return Ok(Json(serde_json::json!({ + "success": true, + "message": format!("Detached {} traces from groups", updated), + "file_uuid": req.file_uuid, + "updated_count": updated + }))); + } + + // Persist face groups to JSON after any modification + let _ = schema::save_face_groups_json(state.db.pool(), &req.file_uuid).await; + + // 2. Detect "rename group" vs "move into group": + // .rename when every provided trace already belongs to exactly ONE group + // whose full member set equals the provided traces (no extra members), + // AND the target name doesn't already exist for a different group. + let mut rename_mode: Option<(i64, String)> = None; + if current_groups.len() == 1 { + let (gid, member_trace_ids) = current_groups.iter().next().unwrap(); + if *member_trace_ids == req.trace_ids { + let full: Option = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 AND group_id = $2" + )) + .bind(&req.file_uuid) + .bind(gid) + .fetch_optional(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[TraceProfileGroup] count error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + if full == Some(member_trace_ids.len() as i64) { + // Check if target name already exists for a DIFFERENT group + let name_exists_elsewhere: i64 = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {fg_table} WHERE file_uuid = $1 AND name = $2 AND id != $3" + )) + .bind(&req.file_uuid) + .bind(&req.name) + .bind(gid) + .fetch_one(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[TraceProfileGroup] name check error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + // Only allow rename if target name doesn't exist elsewhere + if name_exists_elsewhere == 0 { + rename_mode = Some((*gid, req.name.clone())); + } + } + } + } + + if let Some((gid, ref new_name)) = rename_mode { + // ── RENAME GROUP: one write on face_groups ── + sqlx::query(&format!( + "UPDATE {fg_table} SET name = $1, updated_at = NOW() WHERE id = $2" + )) + .bind(new_name) + .bind(gid) + .execute(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[TraceProfileGroup] rename error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + updated = req.trace_ids.len() as u64; + + // Keep per-trace captions + KG labels in sync so DB boot-backfill + // (trace name → group) cannot resurrect the old group name. + let _ = sqlx::query(&format!( + "UPDATE {tp_table} SET name = $1 WHERE file_uuid = $2 AND group_id = $3" + )) + .bind(new_name) + .bind(&req.file_uuid) + .bind(gid) + .execute(state.db.pool()) + .await; + + let _ = sqlx::query(&format!( + "UPDATE {nodes_table} tn SET label = $1 WHERE tn.file_uuid = $2 \ + AND tn.node_type = 'face_track' AND (tn.properties->>'trace_id')::int = ANY($3)" + )) + .bind(new_name) + .bind(&req.file_uuid) + .bind(&req.trace_ids) + .execute(state.db.pool()) + .await; + } else { + // ── MOVE: resolve/create target group, point traces at it ── + let gid = schema::get_or_create_group(state.db.pool(), &req.file_uuid, &req.name) + .await + .map_err(|e| { + tracing::error!("[TraceProfileGroup] get_or_create_group error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + sqlx::query(&format!( + "UPDATE {tp_table} SET group_id = $1 WHERE file_uuid = $2 AND trace_id = ANY($3)" + )) + .bind(gid) + .bind(&req.file_uuid) + .bind(&req.trace_ids) + .execute(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[TraceProfileGroup] move error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + updated = req.trace_ids.len() as u64; + + // Face-groups normalization (V1.0 §7 G2): mirror the target group name + // into the moved traces' captions so people search stays consistent. + let _ = sqlx::query(&format!( + "UPDATE {tp_table} SET name = $1 WHERE file_uuid = $2 AND group_id = $3 AND trace_id = ANY($4)" )) .bind(&req.name) .bind(&req.file_uuid) - .bind(format!("trace_{}", trace_id)) - .bind(*trace_id) + .bind(gid) + .bind(&req.trace_ids) .execute(state.db.pool()) - .await - { - tracing::error!("[TraceProfileGroup] tkg label sync error: {}", e); + .await; + + // Ensure every moved trace has a profile row (self-healing) and sync + // KG labels for display. + for trace_id in &req.trace_ids { + let _ = sqlx::query(&format!( + "INSERT INTO {tp_table} (file_uuid, trace_id, name, group_id, status) \ + VALUES ($1, $2, $3, $4, 'pending') \ + ON CONFLICT (file_uuid, trace_id) DO UPDATE SET group_id = $4" + )) + .bind(&req.file_uuid) + .bind(trace_id) + .bind(&req.name) + .bind(gid) + .execute(state.db.pool()) + .await; + + let _ = sqlx::query(&format!( + "UPDATE {nodes_table} SET label = $1 WHERE file_uuid = $2 \ + AND node_type = 'face_track' AND (external_id = $3 OR (properties->>'trace_id')::int = $4)" + )) + .bind(&req.name) + .bind(&req.file_uuid) + .bind(format!("trace_{}", trace_id)) + .bind(*trace_id) + .execute(state.db.pool()) + .await; } } @@ -467,6 +833,9 @@ pub async fn update_trace_profile_group_handler( None, ).await; + // Persist face groups to JSON + let _ = schema::save_face_groups_json(state.db.pool(), &req.file_uuid).await; + Ok(Json(serde_json::json!({ "success": true, "message": format!("Updated {} traces in group", updated), @@ -593,6 +962,59 @@ pub async fn merge_groups_handler( } } + // Face groups entity: detach traces from source groups, point them at + // the target group, then delete the (now empty) source group rows. + let target_gid = schema::get_or_create_group(state.db.pool(), &req.file_uuid, &req.target_group_name) + .await + .map_err(|e| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": e.to_string()})), + ) + })?; + let source_gids: Vec = sqlx::query_scalar(&format!( + "SELECT id FROM {} WHERE file_uuid = $1 AND name = ANY($2)", + schema::table_name("face_groups") + )) + .bind(&req.file_uuid) + .bind(&source_groups) + .fetch_all(state.db.pool()) + .await + .map_err(|e| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": e.to_string()})), + ) + })?; + if !source_gids.is_empty() { + let _ = sqlx::query(&format!( + "UPDATE {} SET group_id = NULL WHERE file_uuid = $1 AND group_id = ANY($2)", + tp_table + )) + .bind(&req.file_uuid) + .bind(&source_gids) + .execute(state.db.pool()) + .await; + let _ = sqlx::query(&format!( + "DELETE FROM {} WHERE id = ANY($1)", + schema::table_name("face_groups") + )) + .bind(&source_gids) + .execute(state.db.pool()) + .await; + } + if !matching_trace_ids.is_empty() { + let _ = sqlx::query(&format!( + "UPDATE {} SET group_id = $1 WHERE file_uuid = $2 AND trace_id = ANY($3)", + tp_table + )) + .bind(target_gid) + .bind(&req.file_uuid) + .bind(&matching_trace_ids) + .execute(state.db.pool()) + .await; + } + // Sync Qdrant person_id for all merged traces if !matching_trace_ids.is_empty() { let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); @@ -638,6 +1060,9 @@ pub async fn merge_groups_handler( None, ).await; + // Persist face groups to JSON after merge + let _ = schema::save_face_groups_json(state.db.pool(), &req.file_uuid).await; + Ok(Json(MergeGroupsResponse { success: true, file_uuid: req.file_uuid, @@ -728,6 +1153,20 @@ pub async fn undo_face_operation_handler( let _ = schema::upsert_trace_profile(state.db.pool(), &file_uuid, trace_id, name, None).await; + // Face groups entity: re-attach the trace to the group matching the + // restored name (recreates the group row if it no longer exists). + if let Ok(gid) = schema::get_or_create_group(state.db.pool(), &file_uuid, name).await { + let tp_table = schema::table_name("trace_profiles"); + let _ = sqlx::query(&format!( + "UPDATE {tp_table} SET group_id = $1 WHERE file_uuid = $2 AND trace_id = $3" + )) + .bind(gid) + .bind(&file_uuid) + .bind(trace_id) + .execute(state.db.pool()) + .await; + } + // For merge_groups, also restore tkg_nodes.label if operation == "merge_groups" { let _ = sqlx::query(&format!( @@ -758,6 +1197,9 @@ pub async fn undo_face_operation_handler( ) })?; + // Persist face groups to JSON after undo + let _ = schema::save_face_groups_json(state.db.pool(), &file_uuid).await; + Ok(Json(UndoFaceOperationResponse { success: true, file_uuid, @@ -873,6 +1315,9 @@ async fn undo_merge_trace( .execute(state.db.pool()) .await; + // Persist face groups to JSON after undo + let _ = schema::save_face_groups_json(state.db.pool(), &file_uuid).await; + Ok(Json(UndoFaceOperationResponse { success: true, file_uuid, @@ -1049,6 +1494,9 @@ async fn undo_hard_delete_trace( .execute(state.db.pool()) .await; + // Persist face groups to JSON after undo + let _ = schema::save_face_groups_json(state.db.pool(), &file_uuid).await; + Ok(Json(UndoFaceOperationResponse { success: true, file_uuid, @@ -1347,33 +1795,20 @@ pub async fn get_face_groups_handler( 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"); - // Read face_filter settings - let settings: crate::core::file_profile::FaceFilterSettings = sqlx::query_scalar(&format!( - "SELECT face_filter FROM {v_table} WHERE file_uuid = $1" - )) - .bind(&file_uuid) - .fetch_optional(state.db.pool()) - .await - .ok() - .flatten() - .and_then(|v| serde_json::from_value(v).ok()) - .unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults); + let _ = materialize_auto_groups(state.db.pool(), &file_uuid).await?; - let rows: Vec<(String, i32, Option)> = sqlx::query_as(&format!( - "SELECT DISTINCT ON (COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int)) \ - COALESCE(tp.name, tn.label) as name, \ - COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id, \ - tp.frame_count \ - FROM {} tn \ - LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \ - AND tp.trace_id = (tn.properties->>'trace_id')::int \ - WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \ - ORDER BY trace_id", - tkg_table, tp_table + // Single source of truth: face_groups + trace_profiles.group_id. + // face_cluster.json is only used for similarity/representative data. + let rows: Vec<(i64, String, i32, Option)> = sqlx::query_as(&format!( + "SELECT g.id, g.name, g.sort_index, tp.trace_id \ + FROM {} g \ + LEFT JOIN {} tp ON tp.file_uuid = g.file_uuid AND tp.group_id = g.id \ + WHERE g.file_uuid = $1 \ + AND NOT (g.properties @> '{{\"dissolved\": true}}'::jsonb) \ + ORDER BY g.sort_index, g.id, tp.trace_id", + schema::table_name("face_groups"), tp_table )) .bind(&file_uuid) .fetch_all(state.db.pool()) @@ -1383,42 +1818,36 @@ pub async fn get_face_groups_handler( StatusCode::INTERNAL_SERVER_ERROR })?; - let mut groups: HashMap> = HashMap::new(); - let mut unassigned: Vec = Vec::new(); - - for (name, trace_id, frame_count) in rows { - // Filter single frame traces if disabled - if frame_count == Some(1) { - if !settings.trace_settings.single_frame_trace_group_enabled - && !name.starts_with("Face Trace ") - && !name.starts_with("Trace ") - { - continue; - } - if !settings.trace_settings.single_frame_trace_unassigned_enabled - && (name.starts_with("Face Trace ") || name.starts_with("Trace ")) - { - continue; - } + let mut group_members: HashMap> = HashMap::new(); + let mut group_names: HashMap = HashMap::new(); + let mut group_order: Vec = Vec::new(); + for (gid, name, _sort, trace_id) in rows { + if !group_names.contains_key(&gid) { + group_names.insert(gid, name); + group_order.push(gid); } - - if name.starts_with("Face Trace ") || name.starts_with("Trace ") { - unassigned.push(trace_id); - } else { - groups.entry(name).or_default().push(trace_id); + if let Some(tid) = trace_id { + group_members.entry(gid).or_default().push(tid); } } - // Filter single-trace groups if enabled - let mut filtered_groups: HashMap> = HashMap::new(); - for (name, trace_ids) in groups { - let is_auto_name = name.starts_with("Person_"); - let should_filter = - settings.trace_settings.single_trace_group_filter_enabled && trace_ids.len() == 1 && is_auto_name; + // Unassigned: traces without any group row. + let unassigned_rows: Vec<(String, i32)> = sqlx::query_as(&format!( + "SELECT COALESCE(name, '') as name, trace_id FROM {} tp \ + WHERE tp.file_uuid = $1 AND tp.group_id IS NULL ORDER BY tp.trace_id", + tp_table + )) + .bind(&file_uuid) + .fetch_all(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[FaceGroups] unassigned DB error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; - if !should_filter { - filtered_groups.insert(name, trace_ids); - } + let mut unassigned: Vec = Vec::new(); + for (_name, trace_id) in unassigned_rows { + unassigned.push(trace_id); } let include_trace_ids = q.include_trace_ids.unwrap_or(true); @@ -1441,10 +1870,10 @@ pub async fn get_face_groups_handler( } } - let face_groups: Vec = filtered_groups - .into_iter() - .enumerate() - .map(|(idx, (name, trace_ids))| { + let face_groups: Vec = group_order + .iter() + .map(|gid| { + let trace_ids = group_members.remove(gid).unwrap_or_default(); // 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))) @@ -1454,8 +1883,8 @@ pub async fn get_face_groups_handler( .unwrap_or(0); FaceGroup { - group_id: (idx + 1) as i32, - name, + group_id: *gid as i32, + name: group_names.get(gid).cloned().unwrap_or_default(), trace_count: trace_ids.len() as i32, representative_trace: rep_trace, trace_ids: if include_trace_ids { @@ -1547,20 +1976,18 @@ pub async fn get_cluster_results_handler( .and_then(|v| serde_json::from_value(v).ok()) .unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults); - // 1. Build face groups from TKG nodes (primary source) - // Use COALESCE(tn.label, tp.name) - tkg_nodes.label as primary, fallback to trace_profiles.name - // FIX: Use DISTINCT ON to prevent duplicate groups from duplicate tkg_nodes entries - let rows: Vec<(String, i32, Option)> = sqlx::query_as(&format!( - "SELECT DISTINCT ON (COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int)) \ - COALESCE(tn.label, tp.name) as name, \ - COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id, \ - tp.frame_count \ - FROM {} tn \ - LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \ - AND tp.trace_id = (tn.properties->>'trace_id')::int \ - WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \ - ORDER BY trace_id", - tkg_table, tp_table + let _ = materialize_auto_groups(state.db.pool(), &file_uuid).await?; + + // ─── 1. Build face groups from face_groups entity (single source of truth) ─── + let rows: Vec<(i64, String, Option, i32, Option)> = sqlx::query_as(&format!( + "SELECT g.id, g.name, g.origin_cluster_id, g.sort_index, tp.trace_id \ + FROM {fg} g \ + LEFT JOIN {tp} tp ON tp.file_uuid = g.file_uuid AND tp.group_id = g.id \ + WHERE g.file_uuid = $1 \ + AND NOT (g.properties @> '{{\"dissolved\": true}}'::jsonb) \ + ORDER BY g.sort_index, g.id, tp.trace_id", + fg = schema::table_name("face_groups"), + tp = tp_table )) .bind(&file_uuid) .fetch_all(state.db.pool()) @@ -1570,85 +1997,21 @@ pub async fn get_cluster_results_handler( StatusCode::INTERNAL_SERVER_ERROR })?; - let mut groups: HashMap> = HashMap::new(); - for (name, trace_id, frame_count) in rows { - // Filter out single frame traces if disabled - if frame_count == Some(1) && !settings.trace_settings.single_frame_trace_group_enabled { - continue; - } - - if !(name.starts_with("Face Trace ") || name.starts_with("Trace ")) { - groups.entry(name).or_default().push(trace_id); - } - } - - // Filter out single-trace "groups" — only auto-generated Person_N names. - // User-named groups (even with 1 trace) are kept. - let mut filtered_groups: HashMap> = HashMap::new(); - for (name, trace_ids) in groups { - // Filter out empty names and auto-generated trace names - if name.is_empty() || name.starts_with("Face Trace ") || name.starts_with("Trace ") { - continue; - } - - let is_auto_name = name.starts_with("Person_"); - let should_filter = - settings.trace_settings.single_trace_group_filter_enabled && trace_ids.len() == 1 && is_auto_name; - - if !should_filter { - filtered_groups.insert(name, trace_ids); - } - } - - // Fallback: if no groups from DB, load from face_cluster.json - let mut fallback_from_json = filtered_groups.is_empty(); - - if fallback_from_json { - tracing::info!("[ClusterResults] No groups from DB, loading from face_cluster.json"); - let output_dir = crate::core::config::OUTPUT_DIR.as_str(); - let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid); - if let Ok(content) = std::fs::read_to_string(&fc_path) { - if let Ok(data) = serde_json::from_str::(&content) { - // Extract clusters - if let Some(clusters) = data.get("clusters").and_then(|c| c.as_array()) { - for c in clusters { - if let Some(cid) = c.get("cluster_id").and_then(|v| v.as_str()) { - // Use cluster_id as name - let name = cid.to_string(); - let trace_ids: Vec = Vec::new(); - filtered_groups.insert(name, trace_ids); - } - } - tracing::info!("[ClusterResults] Loaded {} clusters from face_cluster.json", clusters.len()); - } - - // Extract trace_ids from frames - if let Some(frames) = data.get("frames").and_then(|f| f.as_array()) { - for frame in frames { - if let Some(faces) = frame.get("faces").and_then(|f| f.as_array()) { - for face in faces { - // Use cluster_id from face_cluster.json (not person_id) - if let (Some(trace_id), Some(cluster_id)) = ( - face.get("trace_id").and_then(|v| v.as_i64()), - face.get("cluster_id").and_then(|v| v.as_str()), - ) { - let trace_id = trace_id as i32; - if let Some(trace_ids) = filtered_groups.get_mut(cluster_id) { - if !trace_ids.contains(&trace_id) { - trace_ids.push(trace_id); - } - } - } - } - } - } - tracing::info!("[ClusterResults] Extracted trace_ids from frames"); - } + let mut group_members: HashMap> = HashMap::new(); + let mut group_meta: Vec<(i64, String, Option)> = Vec::new(); + { + let mut seen: std::collections::HashSet = std::collections::HashSet::new(); + for (gid, name, origin, _sort, trace_id) in rows { + if seen.insert(gid) { + group_meta.push((gid, name, origin)); + } + if let Some(tid) = trace_id { + group_members.entry(gid).or_default().push(tid); } } } - // Load face_cluster.json for similarity data only (not for adding clusters) +// Load face_cluster.json for similarity data only (not for adding clusters) let cluster_similarity: HashMap = { let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid); @@ -1705,23 +2068,31 @@ pub async fn get_cluster_results_handler( map }; - // Build trace_id -> name mapping before consuming filtered_groups - let trace_to_name: HashMap = filtered_groups + // trace_id -> group_id for remapping frame faces to their group + let trace_to_group: HashMap = group_meta .iter() - .flat_map(|(name, trace_ids)| trace_ids.iter().map(|tid| (*tid, name.clone()))) + .flat_map(|(gid, _, _)| { + group_members + .get(gid) + .cloned() + .unwrap_or_default() + .into_iter() + .map(move |tid| (tid, *gid as i32)) + }) .collect(); - let face_groups: Vec = filtered_groups - .into_iter() - .enumerate() - .map(|(idx, (name, trace_ids))| { - let group_id = (idx + 1) as i32; - // Try to find similarity data for this cluster - let similarity = cluster_similarity.get(&name).cloned(); + // Similarity is keyed by the origin cluster (e.g. "Person_1") from the + // automatic clustering run. It is attached to the group that was + // materialized from that cluster. + let face_groups: Vec = group_meta + .iter() + .map(|(gid, name, origin)| { + let trace_ids = group_members.remove(gid).unwrap_or_default(); + let similarity = origin.as_ref().and_then(|cid| cluster_similarity.get(cid).cloned()); ClusterResultsGroup { - group_id, - cluster_id: group_id, - name, + group_id: *gid as i32, + cluster_id: *gid as i32, + name: name.clone(), trace_count: trace_ids.len() as i32, representative_trace: trace_ids.iter() .filter_map(|tid| cluster_trace_conf.get(tid).map(|c| (tid, c))) @@ -1770,17 +2141,14 @@ pub async fn get_cluster_results_handler( face.get("confidence").and_then(|f| f.as_f64()), ) { let trace_id = trace_id as i32; - // Use trace_to_name mapping instead of face.cluster_id - if let Some(cluster_name) = trace_to_name.get(&trace_id) { - // Find group_id for this cluster name - if let Some(group_id) = face_groups.iter().find(|g| g.name == *cluster_name).map(|g| g.group_id) { - cluster_faces.push(ClusterResultsFace { - face_id: face_id.to_string(), - confidence, - cluster_id: Some(group_id), - trace_id: Some(trace_id), - }); - } + // Remap face.cluster_id to the trace's real group id + if let Some(group_id) = trace_to_group.get(&trace_id) { + cluster_faces.push(ClusterResultsFace { + face_id: face_id.to_string(), + confidence, + cluster_id: Some(*group_id), + trace_id: Some(trace_id), + }); } } } @@ -2013,7 +2381,72 @@ pub async fn get_similar_group_handler( })) } -// ─── Routes ─── +/// GET /api/v1/file/:file_uuid/face-groups.json +/// Returns the persistent face_groups.json file content. +pub async fn get_face_groups_json_handler( + Path(file_uuid): Path, +) -> Result, (StatusCode, Json)> { + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let path = std::path::Path::new(output_dir) + .join(format!("{}.face_groups.json", file_uuid)); + + if !path.exists() { + let absolute_path = absolute_path_of_missing(&path); + tracing::warn!( + "[FaceGroupsJson] 404: file_uuid={} attempted_path={}", + file_uuid, absolute_path + ); + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({ + "error": format!("face_groups.json not found: {}", absolute_path), + "file_uuid": file_uuid, + "absolute_path": absolute_path + })), + )); + } + + let content = std::fs::read_to_string(&path).map_err(|e| { + let absolute_path = absolute_path_of_missing(&path); + tracing::error!("[FaceGroupsJson] read failed: {} ({})", absolute_path, e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ + "error": format!("Failed to read face_groups.json: {} ({})", absolute_path, e), + "absolute_path": absolute_path + })), + ) + })?; + + let json: serde_json::Value = serde_json::from_str(&content).map_err(|e| { + let absolute_path = absolute_path_of_missing(&path); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ + "error": format!("Failed to parse face_groups.json: {} ({})", absolute_path, e), + "absolute_path": absolute_path + })), + ) + })?; + + Ok(Json(json)) +} + +/// 取得檔案(含不存在者)的 canonical 絕對路徑: +/// 檔案存在 → canonicalize 檔案;否則 canonicalize 父目錄 + 檔名。 +pub fn absolute_path_of_missing(path: &std::path::Path) -> String { + if let Ok(canon) = std::fs::canonicalize(path) { + return canon.to_string_lossy().to_string(); + } + if let (Some(parent), Some(file)) = (path.parent(), path.file_name()) { + if let Ok(canon_parent) = std::fs::canonicalize(parent) { + return canon_parent.join(file).to_string_lossy().to_string(); + } + } + path.to_string_lossy().to_string() +} + +// ─── Routes ──── pub fn profile_routes() -> axum::Router { use axum::routing::{get, post, put}; @@ -2047,4 +2480,8 @@ pub fn profile_routes() -> axum::Router { "/api/v1/file/:file_uuid/face-operations/undo", post(undo_face_operation_handler), ) + .route( + "/api/v1/file/:file_uuid/face-groups.json", + get(get_face_groups_json_handler), + ) } diff --git a/src/api/scan.rs b/src/api/scan.rs index a9220085..b61eb52d 100644 --- a/src/api/scan.rs +++ b/src/api/scan.rs @@ -250,12 +250,12 @@ async fn scan_files( State(state): State, Query(params): Query, ) -> Result, StatusCode> { + // 用 momentry root 而非 current_exe(部署時 binary 在 /bin/ 下, + // 直接取 parent 會多一層 bin 導致掃描到錯誤目錄)。 let demo_dir_str = std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| { - std::env::current_exe() - .ok() - .and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data/demo"))) - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_else(|| "var/sftpgo/data/demo".to_string()) + crate::core::path_utils::demo_dir() + .to_string_lossy() + .to_string() }); let demo_dir = std::path::Path::new(&demo_dir_str); @@ -1311,6 +1311,7 @@ async fn count_edges(pool: &sqlx::PgPool, table: &str, file_uuid: &str, edge_typ pub fn scan_routes() -> Router { Router::new() .route("/api/v1/files/scan", get(scan_files)) + .route("/api/v1/files/scan-path", get(scan_specific_path)) .route("/api/v1/stats/sftpgo", get(get_sftpgo_status)) .route( "/api/v1/stats/ingestion-status/:file_uuid", @@ -1644,7 +1645,7 @@ async fn get_pipeline_progress_handler( } /// Quick scene VLM stats endpoint (fast, no Qdrant queries) -async fn get_scene_vlm_stats( +pub async fn get_scene_vlm_stats( State(state): State, Path(file_uuid): Path, ) -> Result, StatusCode> { @@ -1698,3 +1699,173 @@ async fn get_scene_vlm_stats( vlm_total: total_scenes.max(scenes_array), })) } + +// 掃描指定路徑 +#[derive(Debug, Deserialize)] +pub struct ScanPathQuery { + pub path: String, +} + +#[derive(Debug, Serialize)] +pub struct ScanPathResponse { + pub scanned_files: usize, + pub new_files: usize, + pub path: String, +} + +fn scan_dir_recursive(dir: &std::path::Path, files: &mut Vec) { + if let Ok(entries) = std::fs::read_dir(dir) { + for entry in entries.filter_map(|e| e.ok()) { + let path = entry.path(); + if path.is_dir() { + scan_dir_recursive(&path, files); + } else if path.is_file() { + files.push(path); + } + } + } +} + +async fn scan_specific_path( + State(state): State, + axum::extract::ConnectInfo(_addr): axum::extract::ConnectInfo, + Query(params): Query, +) -> Result, StatusCode> { + use std::collections::HashSet; + + let scan_root = std::path::Path::new(¶ms.path); + if !scan_root.exists() || !scan_root.is_dir() { + return Err(StatusCode::NOT_FOUND); + } + + let allowed_extensions = vec!["mp4", "mov", "mkv", "avi", "webm", "jpg", "jpeg", "png", "gif", "webp"]; + + let table = schema::table_name("videos"); + let registered: Vec = sqlx::query_scalar(&format!("SELECT file_path FROM {}", table)) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default(); + let registered_set: HashSet = registered.into_iter().collect(); + + // ── 收集候選檔案 (path, name, ext) ────────────────────────────── + // 優先透過 MarkBase 虛擬層 (/api/v2/myfiles/:user/files) 取得檔案清單; + // MarkBase 管不到的路徑(upload root 之外、外接碟等)回退本地遞迴掃描。 + let mut candidates: Vec<(String, String, String)> = Vec::new(); // (path, name, ext) + + // 依 upload_paths 推導 MarkBase username(user root = /) + let mut username: Option = None; + let mut rel_base = String::new(); + let paths_table = schema::table_name("upload_paths"); + if let Ok(rows) = sqlx::query_as::<_, (String, String)>( + &format!("SELECT name, full_path FROM {} WHERE enabled = true", paths_table), + ) + .fetch_all(state.db.pool()) + .await + { + for (name, full_path) in rows { + if params.path == full_path { + username = Some(name); + rel_base = String::new(); + break; + } + if params.path.starts_with(&format!("{}/", full_path)) { + username = Some(name); + rel_base = params.path[full_path.len()..].trim_start_matches('/').to_string(); + break; + } + } + } + + let mut used_markbase = false; + if let Some(user) = username { + let markbase_base = + std::env::var("MOMENTRY_MARKBASE_URL").unwrap_or_else(|_| "http://localhost:11438".to_string()); + let mut url = format!("{}/api/v2/myfiles/{}/files", markbase_base, user); + if !rel_base.is_empty() { + url.push_str(&format!("?folder={}", rel_base)); + } + let client = reqwest::Client::new(); + if let Ok(resp) = client.get(&url).send().await { + if resp.status().is_success() { + if let Ok(files) = resp.json::>().await { + for file in files { + let name = file.get("name").and_then(|v| v.as_str()).unwrap_or(""); + if name.is_empty() { + continue; + } + let folder = file.get("folder").and_then(|v| v.as_str()).unwrap_or(""); + // MarkBase 回傳的 folder 相對於 user root;換算成相對於掃描路徑 + let rel_to_scan = folder.strip_prefix(&rel_base).unwrap_or(folder); + let rel_to_scan = rel_to_scan.trim_start_matches('/'); + let file_path = if rel_to_scan.is_empty() { + format!("{}/{}", params.path, name) + } else { + format!("{}/{}/{}", params.path, rel_to_scan, name) + }; + let ext = name.rsplit('.').next().unwrap_or("").to_lowercase(); + if !allowed_extensions.contains(&ext.as_str()) { + continue; + } + candidates.push((file_path, name.to_string(), ext)); + } + used_markbase = true; + } + } + } + } + + if !used_markbase { + // 回退:本地遞迴掃描(MarkBase 無法服務此路徑) + let mut all_files = Vec::new(); + scan_dir_recursive(scan_root, &mut all_files); + for file_path in all_files { + let path_str = file_path.to_string_lossy().to_string(); + let ext = file_path + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_lowercase(); + if !allowed_extensions.contains(&ext.as_str()) { + continue; + } + let file_name = file_path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("unknown") + .to_string(); + candidates.push((path_str, file_name, ext)); + } + } + + let mut scanned = 0usize; + let mut new_files = 0usize; + + for (path_str, file_name, ext) in candidates { + scanned += 1; + + if registered_set.contains(&path_str) { + continue; + } + + let file_uuid = uuid::Uuid::new_v4().to_string().replace("-", ""); + + let _ = sqlx::query(&format!( + "INSERT INTO {} (file_uuid, file_path, file_name, file_type, status) VALUES ($1, $2, $3, $4, 'pending')", + table + )) + .bind(&file_uuid) + .bind(&path_str) + .bind(&file_name) + .bind(&ext) + .execute(state.db.pool()) + .await; + + new_files += 1; + } + + Ok(Json(ScanPathResponse { + scanned_files: scanned, + new_files, + path: params.path, + })) +} diff --git a/src/api/search.rs b/src/api/search.rs index c0efc489..0ed26457 100644 --- a/src/api/search.rs +++ b/src/api/search.rs @@ -112,26 +112,49 @@ async fn enrich_from_pg( qdrant_score: f32, ) -> Option { match db.get_chunk_by_file_and_chunk_id(file_uuid, chunk_id).await { - Ok(Some(p)) => Some(SearchResult { - id: 0, - file_uuid: p.file_uuid.clone(), - parent_id: p.scene_order, - scene_order: Some(p.scene_order), - start_frame: p.start_frame, - end_frame: p.end_frame, - fps: p.fps, - start_time: p.start_time, - end_time: p.end_time, - raw_text: None, - summary: Some(p.summary), - text_content: p.text_content.clone(), - metadata: p.metadata.clone(), - similarity: Some(qdrant_score as f64), - file_name: None, - serve_url: None, - thumbnail_url: None, - source_type: Some(map_chunk_type_to_source(&p.chunk_type)), - }), + Ok(Some(p)) => { + // Get file_name from videos table — return None if video doesn't exist (orphaned) + let file_name: Option = sqlx::query_scalar(&format!( + "SELECT file_name FROM {} WHERE file_uuid = $1", + crate::core::db::schema::table_name("videos") + )) + .bind(file_uuid) + .fetch_optional(db.pool()) + .await + .ok() + .flatten(); + + if file_name.is_none() { + return None; // Skip orphaned chunks + } + + let thumbnail_url = format!( + "/api/v1/file/{}/thumbnail?frame={}", + file_uuid, p.start_frame + ); + let serve_url = format!("/api/v1/file/{}/video", file_uuid); + + Some(SearchResult { + id: 0, + file_uuid: p.file_uuid.clone(), + parent_id: p.scene_order, + scene_order: Some(p.scene_order), + start_frame: p.start_frame, + end_frame: p.end_frame, + fps: p.fps, + start_time: p.start_time, + end_time: p.end_time, + raw_text: None, + summary: Some(p.summary), + text_content: p.text_content.clone(), + metadata: p.metadata.clone(), + similarity: Some(qdrant_score as f64), + file_name, + serve_url: Some(serve_url), + thumbnail_url: Some(thumbnail_url), + source_type: Some(map_chunk_type_to_source(&p.chunk_type)), + }) + } Ok(None) => { // Chunk not found — try VLM summary lookup by vlm_point_id enrich_vlm_from_pg(db, file_uuid, chunk_id, qdrant_score).await @@ -195,8 +218,16 @@ async fn enrich_vlm_from_pg( "vlm_description_localized": vlm_desc_localized, })), similarity: Some(qdrant_score as f64), - file_name: None, - serve_url: None, + file_name: sqlx::query_scalar(&format!( + "SELECT file_name FROM {} WHERE file_uuid = $1", + crate::core::db::schema::table_name("videos") + )) + .bind(file_uuid) + .fetch_optional(db.pool()) + .await + .ok() + .flatten(), + serve_url: Some(format!("/api/v1/file/{}/video", file_uuid)), thumbnail_url: Some(format!( "/api/v1/file/{}/trace/{}/thumbnail", file_uuid, trace_id @@ -205,7 +236,22 @@ async fn enrich_vlm_from_pg( }) } -fn pg_result_to_search(p: &SemanticSearchResult) -> SearchResult { +async fn pg_result_to_search(p: &SemanticSearchResult, db: &crate::core::db::PostgresDb) -> SearchResult { + let file_uuid_str = p.file_uuid.as_deref().unwrap_or(""); + let file_name: Option = if file_uuid_str.is_empty() { + None + } else { + sqlx::query_scalar(&format!( + "SELECT file_name FROM {} WHERE file_uuid = $1", + crate::core::db::schema::table_name("videos") + )) + .bind(file_uuid_str) + .fetch_optional(db.pool()) + .await + .ok() + .flatten() + }; + SearchResult { id: 0, file_uuid: p.file_uuid.clone(), @@ -221,9 +267,12 @@ fn pg_result_to_search(p: &SemanticSearchResult) -> SearchResult { text_content: p.text_content.clone(), metadata: p.metadata.clone(), similarity: p.similarity, - file_name: None, - serve_url: None, - thumbnail_url: None, + file_name, + serve_url: p.file_uuid.as_ref().map(|uuid| format!("/api/v1/file/{}/video", uuid)), + thumbnail_url: p.file_uuid.as_ref().map(|uuid| format!( + "/api/v1/file/{}/thumbnail?frame={}", + uuid, p.start_frame + )), source_type: Some(map_chunk_type_to_source(&p.chunk_type)), } } @@ -698,13 +747,15 @@ pub async fn keyword_search( let (clean_query, source_filter) = parse_source_filter(&req.query); let chunk_type_filter = source_filter.as_deref().map(source_filter_to_chunk_type); - // Keyword search via PG BM25 + // Keyword search via PG BM25 — fetch enough for pagination + orphan filter buffer + // Fetch page * limit * 2 to account for orphaned chunks being filtered out + let bm25_limit = (page as i64) * (limit as i64) * 2; let keyword_results = db .search_bm25( &clean_query, req.file_uuid.as_deref(), chunk_type_filter, - limit as i64, + bm25_limit, ) .await .map_err(|e| { @@ -721,6 +772,10 @@ pub async fn keyword_search( req.query ); + // Pagination: skip results from previous pages + let skip_count = (page - 1) * limit; + let mut valid_index = 0usize; + let mut results = Vec::new(); for row in keyword_results.iter() { if let Ok(Some(p)) = db @@ -734,6 +789,48 @@ pub async fn keyword_search( p.text_content.clone() }; + // Get file_name from videos table — skip orphaned chunks (no video record) + let file_name: Option = sqlx::query_scalar(&format!( + "SELECT file_name FROM {} WHERE file_uuid = $1", + crate::core::db::schema::table_name("videos") + )) + .bind(&p.file_uuid) + .fetch_optional(db.pool()) + .await + .ok() + .flatten(); + + // Skip results from unregistered files (orphaned chunks) + if file_name.is_none() { + continue; + } + + // Pagination: skip results from previous pages + if valid_index < skip_count { + valid_index += 1; + continue; + } + valid_index += 1; + + // Stop if we have enough results for this page + if results.len() >= limit { + break; + } + + // Normalize BM25 score to 0-1 range (BM25 can be > 1.0) + let normalized_score = (row.bm25_score as f64).min(1.0); + + // Generate thumbnail and serve URLs + let thumbnail_url = format!( + "/api/v1/file/{}/thumbnail?frame={}", + p.file_uuid.as_deref().unwrap_or(""), + p.start_frame + ); + let serve_url = format!( + "/api/v1/file/{}/video", + p.file_uuid.as_deref().unwrap_or("") + ); + results.push(SearchResult { id: 0, file_uuid: p.file_uuid.clone(), @@ -748,10 +845,10 @@ pub async fn keyword_search( summary: text.clone(), text_content: text, metadata: p.metadata.clone(), - similarity: Some(row.bm25_score as f64), - file_name: None, - serve_url: None, - thumbnail_url: None, + similarity: Some(normalized_score), + file_name, + serve_url: Some(serve_url), + thumbnail_url: Some(thumbnail_url), source_type: Some(map_chunk_type_to_source(&p.chunk_type)), }); } diff --git a/src/api/server.rs b/src/api/server.rs index 0781a0c6..d7c0ef45 100644 --- a/src/api/server.rs +++ b/src/api/server.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use axum::{Json, Router}; +use axum::{routing::get, Json, Router}; use serde_json::json; use tokio::time::timeout; use tower_http::cors::{Any, CorsLayer}; @@ -11,6 +11,7 @@ use crate::core::db::{Database, PostgresDb, QdrantDb}; use crate::Embedder; use super::admin_config; +use super::pipeline_tools; use super::agent_api; use super::agent_search; use super::auth; @@ -19,6 +20,10 @@ use super::checkin_api; use super::clip_api; use super::cluster_agent; use super::docs; +use super::export_api; +use super::folder_api; +use super::import_api; +use super::unregister_api; use super::face_filter; use super::file_progress; use super::files; @@ -41,6 +46,9 @@ use super::tmdb_api; use super::trace_agent_api; use super::types::AppState; use super::monitor; +use super::mount_points; +use super::upload_paths; +use super::directory_browser; use super::universal_search::universal_search_routes; use super::vlm_search; use super::job_management; @@ -159,10 +167,15 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> { .merge(profile::profile_routes()) .merge(face_filter::face_filter_routes()) .merge(admin_config::admin_config_routes()) + .merge(pipeline_tools::pipeline_tools_routes()) .merge(vlm_search::vlm_search_routes()) .merge(billing::billing_routes()) .merge(job_management::job_management_routes()) .merge(service_management::router()) + .merge(export_api::export_routes()) + .merge(unregister_api::unregister_routes()) + .merge(import_api::import_routes()) + .merge(folder_api::folder_routes()) .layer(axum::middleware::from_fn_with_state( state.api_state.clone(), unified_auth, @@ -196,10 +209,19 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> { let app = Router::new() .merge(auth::auth_routes()) .merge(public_health_routes) + .merge(service_management::public_routes()) + .route("/api/v1/files/preview-by-path", get(markbase_compat::preview_file_by_path)) + .route( + "/api/v1/file/:file_uuid/scenes/:filename", + get(media_api::scene_thumbnail), + ) .merge(docs::doc_routes()) .merge(monitor::monitor_routes()) .nest_service("/monitor", ServeDir::new("static/monitor")) .merge(protected_routes) + .merge(upload_paths::upload_path_routes()) + .merge(mount_points::mount_point_routes()) + .merge(directory_browser::directory_browser_routes()) .layer(cors) .layer(axum::middleware::from_fn(super::middleware::request_logger)) .layer(axum::middleware::from_fn( @@ -211,7 +233,11 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> { tracing::info!("Starting API server at http://{}", addr); let listener = tokio::net::TcpListener::bind(addr).await?; - axum::serve(listener, app).await?; + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await?; Ok(()) } diff --git a/src/api/service_management.rs b/src/api/service_management.rs index 12810c76..34bb1b30 100644 --- a/src/api/service_management.rs +++ b/src/api/service_management.rs @@ -10,6 +10,8 @@ use tokio::time::sleep; use crate::api::types::AppState; +// ─── Request/Response types ────────────────────────────────────────────────── + #[derive(Debug, Deserialize)] pub struct ServiceStartRequest { pub name: String, @@ -19,13 +21,14 @@ pub struct ServiceStartRequest { pub port: u16, } -fn default_port() -> u16 { - 8080 -} +fn default_port() -> u16 { 8080 } #[derive(Debug, Deserialize)] pub struct ServiceStopRequest { pub name: String, + /// If true, clean up temp files and stale data before stopping. + #[serde(default)] + pub cleanup: Option, } #[derive(Debug, Serialize)] @@ -46,86 +49,215 @@ pub struct MbeHealthResponse { pub uptime: Option, } -/// Check if a port is in use by attempting to connect +// ─── Service registry (mirrors proxy.rs svc_def) ──────────────────────────── + +/// Known services with their default port and launchd label. +/// `launchd_label = None` means the service is managed manually (not via launchd). +fn svc_def(name: &str) -> Option<(&'static str, u16, Option<&'static str>)> { + let key = name.to_lowercase().replace(' ', ""); + let def: (&'static str, u16, Option<&'static str>) = match key.as_str() { + "core" | "coreapi" | "api" => ("core", 3002, Some("com.momentry.server")), + "markbase" | "mb" => ("markbase", 11438, Some("com.momentry.markbase")), + "mbe" | "markbaseengine" | "vlm" => ("mbe", 8082, Some("com.momentry.llm")), // MBE = markbaseengine service; spawns VLM llama-server (8082) + "chat" | "llama" => ("chat", 8080, Some("com.momentry.chat-llamacpp")), // Chat llama-server instance (8080) + "embedding" => ("embedding", 11437, Some("com.momentry.embedding-gguf")), + "proxy" => ("proxy", 8888, Some("com.momentry.proxy")), + "worker" => ("worker", 0, Some("com.momentry.worker")), + "postgres" | "postgresql" | "pg" => ("postgres", 5432, Some("com.momentry.postgresql")), + // NOTE: the redis actually serving 127.0.0.1:6379 is brew-services' launchd agent, + // not com.momentry.redis (which can't bind while brew's owns the port). + "redis" => ("redis", 6379, Some("sh.brew.redis")), + "qdrant" => ("qdrant", 6333, Some("com.momentry.qdrant")), + _ => return None, + }; + Some(def) +} + +// ─── Process helpers ──────────────────────────────────────────────────────── + fn is_port_in_use(port: u16) -> bool { use std::net::TcpStream; - let addr = format!("127.0.0.1:{}", port); - match TcpStream::connect(&addr) { - Ok(_) => { - tracing::info!("[Service] Port {} is in use (connection successful)", port); - true + TcpStream::connect(&addr).is_ok() +} + +/// Wait until a port is accepting connections (or timeout). Ports of 0 (worker, +/// which has no listener) resolve immediately after a short grace pause. +async fn wait_for_port_ready(port: u16, max_secs: u64) -> bool { + if port == 0 { + sleep(Duration::from_secs(2)).await; + return true; + } + for i in 0..max_secs { + if is_port_in_use(port) { + if i > 0 { + tracing::info!("[Service] port {} ready after {}s", port, i); + } + return true; } - Err(e) => { - tracing::info!("[Service] Port {} not in use: {}", port, e); - false + sleep(Duration::from_secs(1)).await; + } + tracing::warn!("[Service] port {} not ready within {}s", port, max_secs); + false +} + +fn get_port_pid(port: u16) -> Option { + let output = Command::new("/usr/sbin/lsof") + .args(["-nP", &format!("-iTCP:{}", port), "-sTCP:LISTEN", "-t"]) + .output().ok()?; + if output.status.success() && !output.stdout.is_empty() { + // lsof -t may return multiple PIDs (one per line) — take the first (listener) + String::from_utf8_lossy(&output.stdout) + .split_whitespace() + .next() + .and_then(|s| s.parse::().ok()) + } else { None } +} + +fn kill_process(pid: u32) -> bool { + Command::new("kill").arg(pid.to_string()).output() + .map(|o| o.status.success()).unwrap_or(false) +} + +// ─── launchctl helpers ─────────────────────────────────────────────────────── + +/// Get the current user's UID as a string for launchd domain targeting. +fn uid_str() -> String { + // Primary: use `id -u` command (most reliable) + let out = Command::new("id").arg("-u").output(); + if let Ok(o) = out { + let uid = String::from_utf8_lossy(&o.stdout).trim().to_string(); + if !uid.is_empty() { + return uid; + } + } + // Fallback: env var or default + std::env::var("UID") + .ok() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "501".to_string()) +} + +/// Build a launchd service target: "gui//