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
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled

This commit is contained in:
Accusys
2026-11-16 18:16:46 +08:00
parent d21d1ab960
commit 083d73d287
88 changed files with 12216 additions and 1096 deletions
Generated
+24
View File
@@ -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"
+3
View File
@@ -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
+228 -90
View File
@@ -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": {}
"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
},
"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
{
"name": "cut",
"processor_type": "cut",
"required": true,
"enabled": true,
"timeout_secs": 3600
},
"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
{
"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
}
]
}
}
}
}
@@ -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
<!-- PeopleView.vue -->
<div class="ms-ppl-section-title">
Face Group:
<span class="ms-ppl-section-count ms-clickable"
@click="openFaceGroupsJson"
title="查看 face_groups.json">
({{ faceGroups.length }})
</span>
</div>
```
### 4.2 JSON 檢視器 Modal
```html
<!-- 點擊後彈出 modal 顯示 face_groups.json 內容 -->
<div v-if="showFaceGroupsJson" class="ms-modal-overlay">
<div class="ms-modal-box ms-modal-wide">
<div class="ms-modal-header">
<span class="ms-modal-title">face_groups.json — {{ fileUuid }}</span>
<button class="ms-modal-close" @click="showFaceGroupsJson = false">✕</button>
</div>
<div class="ms-modal-body">
<pre class="ms-json-view">{{ faceGroupsJsonContent }}</pre>
</div>
</div>
</div>
```
---
## 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 匹配介面(未來) | 待定 |
@@ -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 未消費。
@@ -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 <uuid> [--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
```
+22 -30
View File
@@ -2,46 +2,38 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>EnvironmentVariables</key>
<dict>
<key>DATABASE_URL</key>
<string>postgres://accusys@localhost:5432/momentry</string>
<key>HOME</key>
<string>/Users/accusys</string>
<key>OLLAMA_HOST</key>
<string>http://localhost:11434</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/Users/accusys/.cargo/bin</string>
<key>REDIS_URL</key>
<string>redis://accusys:accusys@localhost:6379</string>
<key>USER</key>
<string>accusys</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.agent</string>
<key>ProcessType</key>
<string>Interactive</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry_core_0.1/momentry_runtime/start.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
<string>/Users/accusys</string>
<key>USER</key>
<string>accusys</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/Users/accusys/.cargo/bin</string>
<key>DATABASE_URL</key>
<string>postgres://accusys@localhost:5432/momentry</string>
<key>REDIS_URL</key>
<string>redis://accusys:accusys@localhost:6379</string>
<key>OLLAMA_HOST</key>
<string>http://localhost:11434</string>
</dict>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry_core_0.1/momentry_runtime/logs/stdout.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry_core_0.1/momentry_runtime/logs/stderr.log</string>
<string>/Users/accusys/momentry/logs/agent.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/agent.log</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry_core_0.1</string>
<key>ProcessType</key>
<string>Interactive</string>
</dict>
</plist>
@@ -5,7 +5,9 @@
<key>EnvironmentVariables</key>
<dict>
<key>MOMENTRY_OUTPUT_DIR</key>
<string>/Users/accusys/momentry/output</string>
<string>/Users/accusys/momentry/output/demo</string>
<key>MOMENTRY_SFTP_ROOT</key>
<string>/Users/accusys/momentry/var/sftpgo/data/demo</string>
</dict>
<key>GroupName</key>
<string>staff</string>
@@ -20,9 +22,9 @@
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/momentry_api.error.log</string>
<string>/Users/accusys/momentry/logs/core_api.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/momentry_api.log</string>
<string>/Users/accusys/momentry/logs/core_api.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
+10 -18
View File
@@ -2,12 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.caddy</string>
<key>UserName</key>
<string>root</string>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
@@ -15,10 +9,10 @@
<key>XDG_DATA_HOME</key>
<string>/opt/homebrew/var/lib</string>
</dict>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/caddy</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.caddy</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/caddy/bin/caddy</string>
@@ -26,17 +20,15 @@
<string>--config</string>
<string>/Users/accusys/momentry/etc/Caddyfile</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/caddy.error.log</string>
<string>/Users/accusys/momentry/logs/caddy.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/caddy.log</string>
<string>/Users/accusys/momentry/logs/caddy.log</string>
<key>UserName</key>
<string>root</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/caddy</string>
</dict>
</plist>
+18 -26
View File
@@ -2,15 +2,19 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>EnvironmentVariables</key>
<dict>
<key>GITEA_WORK_DIR</key>
<string>/Users/accusys/momentry/var/gitea</string>
<key>HOME</key>
<string>/Users/accusys</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.gitea</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/gitea</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/gitea/bin/gitea</string>
@@ -18,27 +22,15 @@
<string>--config</string>
<string>/Users/accusys/momentry/etc/gitea/app.ini</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
<string>/Users/accusys</string>
<key>GITEA_WORK_DIR</key>
<string>/Users/accusys/momentry/var/gitea</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/gitea.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/gitea.error.log</string>
<string>/Users/accusys/momentry/logs/gitea.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/gitea.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/gitea</string>
</dict>
</plist>
@@ -2,31 +2,24 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.mariadb</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/mariadb</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/mariadb/bin/mariadbd-safe</string>
<string>--datadir=/Users/accusys/momentry/var/mariadb</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/mariadb.error.log</string>
<string>/Users/accusys/momentry/logs/mariadb.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/mariadb.log</string>
<string>/Users/accusys/momentry/logs/mariadb.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/mariadb</string>
</dict>
</plist>
@@ -2,15 +2,20 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
</dict>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>Label</key>
<string>com.momentry.monitor</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry_core_0.1/monitor</string>
<key>ProcessType</key>
<string>Background</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
@@ -18,32 +23,17 @@
<string>check</string>
<string>all</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
</dict>
<key>RunAtLoad</key>
<false/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/monitor.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/monitor.log</string>
<key>StartInterval</key>
<integer>300</integer>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/monitor/monitor.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/monitor/monitor.error.log</string>
<key>ProcessType</key>
<string>Background</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry_core_0.1/monitor</string>
</dict>
</plist>
@@ -2,43 +2,35 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.ollama</string>
<key>UserName</key>
<string>accusys</string>
<key>EnvironmentVariables</key>
<dict>
<key>OLLAMA_HOST</key>
<string>0.0.0.0:11434</string>
<key>OLLAMA_MODELS</key>
<string>/Users/accusys/momentry/var/ollama/models</string>
<key>OLLAMA_FLASH_ATTENTION</key>
<string>1</string>
<key>OLLAMA_HOST</key>
<string>0.0.0.0:11434</string>
<key>OLLAMA_KV_CACHE_TYPE</key>
<string>q8_0</string>
<key>OLLAMA_MODELS</key>
<string>/Users/accusys/momentry/var/ollama/models</string>
</dict>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/ollama</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.ollama</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/ollama/bin/ollama</string>
<string>serve</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/ollama.error.log</string>
<string>/Users/accusys/momentry/logs/ollama.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/ollama.log</string>
<string>/Users/accusys/momentry/logs/ollama.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/ollama</string>
</dict>
</plist>
@@ -2,38 +2,30 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.postgresql</string>
<key>UserName</key>
<string>accusys</string>
<key>EnvironmentVariables</key>
<dict>
<key>LC_ALL</key>
<string>en_US.UTF-8</string>
</dict>
<key>WorkingDirectory</key>
<string>/Users/accusys</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.postgresql</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/pgsql/18.3/bin/postgres</string>
<string>-D</string>
<string>/Users/accusys/pgsql/data</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/postgresql.error.log</string>
<string>/Users/accusys/momentry/logs/postgresql.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/postgresql.log</string>
<string>/Users/accusys/momentry/logs/postgresql.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys</string>
</dict>
</plist>
@@ -28,9 +28,9 @@
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/opt/homebrew/var/log/qdrant.error.log</string>
<string>/Users/accusys/momentry/logs/qdrant.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/qdrant.log</string>
<string>/Users/accusys/momentry/logs/qdrant.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
@@ -11,22 +11,18 @@
<string>/opt/homebrew/opt/redis/bin/redis-server</string>
<string>--port</string>
<string>6379</string>
<string>--bind</string>
<string>0.0.0.0</string>
<string>--requirepass</string>
<string>accusys</string>
<string>--appendonly</string>
<string>yes</string>
<string>--dir</string>
<string>/Users/accusys/momentry/var/redis</string>
<string>--logfile</string>
<string>/Users/accusys/momentry/log/redis.log</string>
<string>/Users/accusys/momentry/var</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/redis.error.log</string>
<string>/Users/accusys/momentry/logs/redis.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/redis.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/redis</string>
<string>/Users/accusys/momentry/logs/redis.log</string>
</dict>
</plist>
+4 -1
View File
@@ -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
);
+13 -6
View File
@@ -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)
+143 -30
View File
@@ -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", [])):
+360
View File
@@ -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 <uuid> [--api-key KEY] [--api-url URL]
python3.11 face_pipeline_check.py <uuid> -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())
+242
View File
@@ -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<String>,
}
#[derive(Deserialize)]
struct CleanupRequest {
cleanup_type: String,
dry_run: Option<bool>,
}
// 清理垃圾檔案
async fn cleanup_garbage(
State(state): State<crate::api::types::AppState>,
Json(req): Json<CleanupRequest>,
) -> Result<Json<CleanupReport>, 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<String> = 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<crate::api::types::AppState>,
Json(req): Json<CleanupRequest>,
) -> Result<Json<serde_json::Value>, 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<crate::api::types::AppState>,
) -> Result<Json<serde_json::Value>, 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)
}
+207 -2
View File
File diff suppressed because one or more lines are too long
+35 -25
View File
@@ -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<ToolDef> {
@@ -527,18 +518,37 @@ async fn agent_search(
) -> Result<Json<AgentSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
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 {
+31 -2
View File
@@ -31,8 +31,29 @@ struct UserInfo {
async fn login(
State(state): State<AppState>,
axum::extract::ConnectInfo(addr): axum::extract::ConnectInfo<std::net::SocketAddr>,
headers: axum::http::HeaderMap,
Json(req): Json<LoginRequest>,
) -> Result<axum::response::Response<axum::body::Body>, (StatusCode, Json<serde_json::Value>)> {
// ── 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();
+21
View File
@@ -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::<Vec<i32>>())
.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);
}
}
}
+338
View File
@@ -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<u64>,
pub entry_type: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct BrowseQuery {
pub path: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct DiscoveredHost {
pub name: String,
pub hostname: String,
pub ip: Option<String>,
pub service_type: String,
pub protocol: String,
}
#[derive(Debug, Deserialize)]
pub struct MountRequest {
pub url: String,
pub username: Option<String>,
pub password: Option<String>,
pub mount_point: Option<String>,
}
pub fn directory_browser_routes() -> Router<AppState> {
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<BrowseQuery>,
) -> Result<Json<Vec<DirEntry>>, 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<DirEntry> {
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<DirEntry> {
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<AppState>,
) -> Result<Json<Vec<DiscoveredHost>>, StatusCode> {
let mut hosts: HashMap<String, DiscoveredHost> = 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<AppState>,
Json(req): Json<MountRequest>,
) -> Result<Json<serde_json::Value>, 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<AppState>,
Query(params): Query<HashMap<String, String>>,
) -> Result<Json<Vec<ShareInfo>>, 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))
}
+208
View File
@@ -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<String>,
}
#[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<AppState>,
Path(uuid): Path<String>,
Query(params): Query<ExportQuery>,
) -> Result<Json<ExportResponse>, (StatusCode, Json<serde_json::Value>)> {
// 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<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<ExportStatusResponse>, (StatusCode, Json<serde_json::Value>)> {
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<String>>(
"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<AppState> {
Router::new()
.route("/api/v1/file/:uuid/export", post(export_file_handler))
.route("/api/v1/file/:uuid/export-status", get(export_status_handler))
}
+255
View File
@@ -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<String>,
pub is_primary: bool,
pub is_available: bool,
pub file_size: Option<i64>,
pub checksum: Option<String>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct CreateReplicaRequest {
pub file_uuid: String,
pub replica_path: String,
pub replica_name: Option<String>,
pub is_primary: Option<bool>,
pub file_size: Option<i64>,
pub checksum: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct ListReplicasQuery {
pub file_uuid: Option<String>,
pub replica_name: Option<String>,
}
// ── Routes ──────────────────────────────────────────────────────────
pub fn file_replica_routes() -> Router<AppState> {
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<AppState>,
Query(params): Query<ListReplicasQuery>,
) -> Result<Json<Vec<FileReplica>>, StatusCode> {
let pool = get_pool(&state);
let query = match (&params.file_uuid, &params.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<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<Vec<FileReplica>>, 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<AppState>,
Json(req): Json<CreateReplicaRequest>,
) -> Result<Json<FileReplica>, 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<AppState>,
Path(id): Path<i32>,
) -> Result<Json<serde_json::Value>, 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<AppState>,
Path(id): Path<i32>,
) -> Result<Json<FileReplica>, 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))
}
+85 -5
View File
@@ -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<String> = 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<String> = 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,
+201
View File
@@ -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<String>,
#[serde(default)]
pub library_name: Option<String>,
}
#[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<String>,
#[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<AppState>,
Query(params): Query<FolderExportQuery>,
) -> Result<Json<FolderExportResponse>, (StatusCode, Json<serde_json::Value>)> {
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(&params.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(), &params.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(),
&params.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<AppState>,
Query(params): Query<FolderImportQuery>,
) -> Result<Json<FolderImportResponse>, (StatusCode, Json<serde_json::Value>)> {
let pkg_path = PathBuf::from(&params.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(),
&params.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<Vec<FileInfo>, (StatusCode, Json<serde_json::Value>)> {
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<AppState> {
Router::new()
.route("/api/v1/folder/export", post(folder_export_handler))
.route("/api/v1/folder/import", post(folder_import_handler))
}
+49 -19
View File
@@ -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<crate::api::types::AppState> {
Router::new()
.route("/api/v1/files", get(list_files))
@@ -79,6 +85,7 @@ pub fn identity_routes() -> Router<crate::api::types::AppState> {
#[derive(Debug, Deserialize)]
pub struct FilesQuery {
pub page: Option<usize>,
#[serde(alias = "pageSize")]
pub page_size: Option<usize>,
pub status: Option<String>,
pub file_uuid: Option<String>,
@@ -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<MarkBaseFile> = client
.get(markbase_url)
.send()
// 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
.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)))?;
.unwrap_or_default();
let mut markbase_files: Vec<MarkBaseFile> = 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::<Vec<MarkBaseFile>>().await {
markbase_files.extend(files);
}
}
}
let mut all_files: Vec<FileItem> = 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")
// Not registered: use MarkBase file_path if available
let file_path = mb_file.file_path.clone()
.filter(|p| !p.is_empty())
.unwrap_or_else(|| {
// Fallback: synthesize path from SFTP root
std::env::var("MOMENTRY_SFTP_ROOT")
.ok()
.map(|root| format!("{}/{}", root.trim_end_matches('/'), name))
.unwrap_or_else(|| {
// Default SFTP root if not configured
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<String> = all_files.iter().map(|f| f.file_name.clone()).collect();
for (name, (uuid, path, status, size, mtime)) in &registered_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::<chrono::Utc>::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<FileItem>,
}
#[derive(Debug, Serialize)]
#[derive(Debug, Serialize, Deserialize)]
pub struct FileItem {
pub file_uuid: String,
pub file_name: String,
+478
View File
@@ -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<String>,
#[serde(default)]
pub target_video_path: Option<String>,
#[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<AppState>,
Query(params): Query<ImportQuery>,
) -> Result<Json<ImportResponse>, (StatusCode, Json<serde_json::Value>)> {
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<ListQuery>,
) -> Result<Json<ListResponse>, (StatusCode, Json<serde_json::Value>)> {
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<String>,
}
#[derive(Debug, Serialize)]
pub struct ListResponse {
pub success: bool,
pub packages: Vec<PackageInfo>,
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<ImportResponse> {
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<Vec<PackageInfo>> {
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<PackageInfo> {
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<usize> {
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::Value> = 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<String> = record.as_object().unwrap().keys()
.map(|k| format!("\"{}\"", k)).collect();
let cols_str = columns.join(", ");
// Build values with proper type handling
let values: Vec<String> = 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<usize> {
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<AppState> {
Router::new()
.route("/api/v1/import", post(import_file_handler))
.route("/api/v1/import/list", post(list_packages_handler))
}
+50 -1
View File
@@ -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<crate::api::types::AppState> {
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<String>,
}
pub async fn preview_file_by_path(
Query(params): Query<PreviewQuery>,
) -> Result<axum::response::Response, StatusCode> {
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),
}
}
+67 -11
View File
@@ -88,10 +88,6 @@ pub fn bbox_routes() -> Router<crate::api::types::AppState> {
"/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=<abs_path>&frame=<n>
async fn thumbnail_by_path(
State(state): State<crate::api::types::AppState>,
Query(q): Query<ThumbnailByPathQuery>,
) -> Result<impl IntoResponse, StatusCode> {
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 在 <root>/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<crate::api::types::AppState>,
Path((file_uuid, filename)): Path<(String, String)>,
) -> Result<impl IntoResponse, StatusCode> {
+20 -2
View File
@@ -177,13 +177,31 @@ fn extract_api_key(headers: &HeaderMap, uri: &axum::http::Uri) -> Result<String,
Err(StatusCode::UNAUTHORIZED)
}
/// Derive the inbound client IP, preferring proxy headers (Caddy / momentry
/// proxy / reverse proxies set X-Forwarded-For) then falling back to the
/// direct socket address.
fn client_ip(headers: &axum::http::HeaderMap, addr: Option<std::net::SocketAddr>) -> 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<ApiState>,
axum::extract::ConnectInfo(addr): axum::extract::ConnectInfo<std::net::SocketAddr>,
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);
}
+10
View File
@@ -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;
+182
View File
@@ -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<String>,
pub enabled: bool,
pub created_at: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, FromRow)]
pub struct MountReplica {
pub id: i32,
pub mount_id: i32,
pub replica_id: i32,
pub display_name: Option<String>,
pub display_order: i32,
pub file_uuid: String,
pub replica_path: String,
pub replica_name: Option<String>,
pub is_primary: bool,
}
#[derive(Debug, Deserialize)]
pub struct CreateMountRequest {
pub name: String,
pub mount_path: String,
pub description: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct AddReplicaToMountRequest {
pub replica_id: i32,
pub display_name: Option<String>,
pub display_order: Option<i32>,
}
pub fn mount_point_routes() -> Router<AppState> {
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<AppState>) -> Result<Json<Vec<MountPoint>>, 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<AppState>,
Json(req): Json<CreateMountRequest>,
) -> Result<Json<MountPoint>, 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<AppState>,
Path(id): Path<i32>,
) -> Result<Json<serde_json::Value>, 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<AppState>,
Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<Vec<MountReplica>>, 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<AppState>,
Path(id): Path<i32>,
Json(req): Json<AddReplicaToMountRequest>,
) -> Result<Json<serde_json::Value>, 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<AppState>,
Path((id, replica_id)): Path<(i32, i32)>,
) -> Result<Json<serde_json::Value>, 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<AppState>,
Path(id): Path<i32>,
) -> Result<Json<MountPoint>, 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))
}
+280
View File
@@ -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<ToolInfo>,
asr: Vec<ToolInfo>,
face: Vec<ToolInfo>,
services: Vec<ToolInfo>,
worker: Option<ToolInfo>,
}
/// 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<String> {
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<ToolInfo> {
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<AppState>,
) -> Result<Json<Value>, 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<AppState>,
) -> Result<Json<Value>, 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<AppState> {
Router::new()
.route("/api/v1/admin/pipeline-tools", get(probe_pipeline_tools))
.route("/api/v1/admin/release-tools", get(probe_release_tools))
}
+98
View File
@@ -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<String>,
}
async fn get_output_completeness(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, 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::<serde_json::Value>(&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<std::collections::HashMap<String, String>>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
@@ -1156,6 +1253,7 @@ async fn trigger_vlm_summary(
pub fn processing_routes() -> Router<AppState> {
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",
+638 -201
View File
File diff suppressed because it is too large Load Diff
+177 -6
View File
@@ -250,12 +250,12 @@ async fn scan_files(
State(state): State<AppState>,
Query(params): Query<ScanFilesQuery>,
) -> Result<Json<ScanFilesResponse>, StatusCode> {
// 用 momentry root 而非 current_exe(部署時 binary 在 <root>/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<AppState> {
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<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<SceneVlmStats>, 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<std::path::PathBuf>) {
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<AppState>,
axum::extract::ConnectInfo(_addr): axum::extract::ConnectInfo<std::net::SocketAddr>,
Query(params): Query<ScanPathQuery>,
) -> Result<Json<ScanPathResponse>, StatusCode> {
use std::collections::HashSet;
let scan_root = std::path::Path::new(&params.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<String> = sqlx::query_scalar(&format!("SELECT file_path FROM {}", table))
.fetch_all(state.db.pool())
.await
.unwrap_or_default();
let registered_set: HashSet<String> = 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 = <upload>/<name>)
let mut username: Option<String> = 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::<Vec<serde_json::Value>>().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,
}))
}
+114 -17
View File
@@ -112,7 +112,29 @@ async fn enrich_from_pg(
qdrant_score: f32,
) -> Option<SearchResult> {
match db.get_chunk_by_file_and_chunk_id(file_uuid, chunk_id).await {
Ok(Some(p)) => Some(SearchResult {
Ok(Some(p)) => {
// Get file_name from videos table — return None if video doesn't exist (orphaned)
let file_name: Option<String> = 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,
@@ -127,11 +149,12 @@ async fn enrich_from_pg(
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,
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<String> = 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<String> = 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)),
});
}
+28 -2
View File
@@ -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::<std::net::SocketAddr>(),
)
.await?;
Ok(())
}
File diff suppressed because it is too large Load Diff
+46 -3
View File
@@ -2117,6 +2117,17 @@ async fn delete_trace(
)
.await;
// 3b. Face-groups normalization (V1.0 §7 G1): unassigning a trace must
// detach it from its group (I4: assigned ⇔ group_id IS NOT NULL),
// otherwise the trace keeps appearing as a group member.
let _ = sqlx::query(&format!(
"UPDATE {tp_table} SET group_id = NULL WHERE {tp_table}.file_uuid = $1 AND {tp_table}.trace_id = $2"
))
.bind(&file_uuid)
.bind(trace_id)
.execute(state.db.pool())
.await;
// 4. Keep _faces points intact (do NOT delete)
// 5. Save operation snapshot for undo
@@ -2643,6 +2654,24 @@ async fn restore_trace(
)
.await;
// Face-groups normalization (V1.0 §7 G6): re-attach the restored trace
// to the group matching its restored name (recreates the group row if
// it no longer exists).
let tp_table = crate::core::db::schema::table_name("trace_profiles");
if let Ok(gid) =
crate::core::db::schema::get_or_create_group(state.db.pool(), &file_uuid, &profile_name)
.await
{
let _ = sqlx::query(&format!(
"UPDATE {tp_table} SET group_id = $1 WHERE {tp_table}.file_uuid = $2 AND {tp_table}.trace_id = $3"
))
.bind(gid)
.bind(&file_uuid)
.bind(trace_id)
.execute(state.db.pool())
.await;
}
// Clear any legacy deleted status markers
let legacy_filter = serde_json::json!({
"must": [
@@ -2815,13 +2844,27 @@ async fn get_trace_profile_file(
Some(profile) => (StatusCode::OK, Json(profile)),
None => {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let expected_path = format!("{}/{}/trace_{}/trace_profile.json", output_dir, file_uuid, trace_id);
let attempted = std::path::PathBuf::from(output_dir)
.join(&file_uuid)
.join(format!("trace_{}", trace_id))
.join("trace_profile.json");
// 檔案可能不存在,改用父目錄 canonicalize 取得絕對位置
let absolute_path = attempted
.parent()
.and_then(|p| std::fs::canonicalize(p).ok())
.map(|p| p.join("trace_profile.json").to_string_lossy().to_string())
.unwrap_or_else(|| attempted.to_string_lossy().to_string());
tracing::warn!(
"[TraceProfile] 404: file_uuid={} trace_id={} attempted_path={}",
file_uuid, trace_id, absolute_path
);
(StatusCode::NOT_FOUND, Json(serde_json::json!({
"error": "Trace profile file not found",
"error": format!("Trace profile file not found: {}", absolute_path),
"file_uuid": file_uuid,
"trace_id": trace_id,
"output_dir": output_dir,
"expected_path": expected_path
"expected_path": absolute_path,
"absolute_path": absolute_path
})))
}
}
+248
View File
@@ -0,0 +1,248 @@
/// Unregister API - remove files from system (optionally export first)
use axum::{
extract::{Path, Query, State},
http::StatusCode,
routing::post,
Json, Router,
};
use serde::{Deserialize, Serialize};
use crate::api::types::AppState;
// ─── Request/Response Structures ──────────────────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct UnregisterQuery {
#[serde(default)]
pub export_first: bool,
/// 預設保留影片檔:unregister → register → deep scan 的用戶流程需要原檔。
/// 只有明確帶 keep_video=false(或 keep_video=0)才會刪除影片。
#[serde(default = "default_true")]
pub keep_video: bool,
#[serde(default)]
pub export_dir: Option<String>,
}
fn default_true() -> bool {
true
}
#[derive(Debug, Serialize)]
pub struct UnregisterResponse {
pub success: bool,
pub file_uuid: String,
pub exported: bool,
pub package_path: Option<String>,
pub deleted_records: usize,
pub message: String,
}
// ─── API Handlers ────────────────────────────────────────────────────────────
/// POST /api/v1/file/:uuid/unregister
/// Remove a file from the system (optionally export first)
pub async fn unregister_file_handler(
State(state): State<AppState>,
Path(uuid): Path<String>,
Query(params): Query<UnregisterQuery>,
) -> Result<Json<UnregisterResponse>, (StatusCode, Json<serde_json::Value>)> {
// Verify 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 video = video.unwrap();
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let export_dir = params.export_dir.unwrap_or_else(|| {
"/Users/accusys/momentry/offline_storage/files".to_string()
});
let mut exported = false;
let mut package_path = None;
// Optional: Export first
if params.export_first {
// 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)})),
));
}
match crate::core::export::export_file(
state.db.pool(),
&uuid,
&output_dir,
&export_dir,
)
.await
{
Ok(pkg_path) => {
exported = true;
package_path = Some(pkg_path.to_string_lossy().to_string());
}
Err(e) => {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Export failed: {}", e)})),
));
}
}
}
// Perform unregister
let deleted_records = unregister_file_from_system(
state.db.pool(),
&uuid,
&video.file_path,
&output_dir,
params.keep_video,
)
.await?;
let message = if exported {
let pkg = package_path.as_deref().unwrap_or("N/A");
format!(
"Exported and unregistered. {} records removed. Package: {}",
deleted_records, pkg
)
} else {
format!("Unregistered. {} records removed.", deleted_records)
};
Ok(Json(UnregisterResponse {
success: true,
file_uuid: uuid,
exported,
package_path,
deleted_records,
message,
}))
}
// ─── Unregister Logic ────────────────────────────────────────────────────────
async fn unregister_file_from_system(
pool: &sqlx::PgPool,
uuid: &str,
file_path: &str,
output_dir: &str,
keep_video: bool,
) -> Result<usize, (StatusCode, Json<serde_json::Value>)> {
let mut deleted = 0;
// 1. Delete from Qdrant (best effort)
// TODO: Implement Qdrant deletion
// 2. Delete output files
delete_output_files(uuid, output_dir);
// 3. Delete original video (if not keeping)
if !keep_video {
if let Err(e) = std::fs::remove_file(file_path) {
tracing::warn!("[Unregister] Failed to remove video {}: {}", file_path, e);
}
}
// 4. Get file_path before deleting video (for command_queue cleanup)
let file_path: Option<String> = sqlx::query_scalar(
"SELECT file_path FROM videos WHERE file_uuid = $1"
)
.bind(uuid)
.fetch_optional(pool)
.await
.unwrap_or(None);
// 5. Delete DB records (in order to respect foreign keys)
let tables_to_delete = [
("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"),
];
// Mark video as unregistered before deleting related records
let update_result = sqlx::query("UPDATE videos SET status='unregistered' WHERE file_uuid = $1")
.bind(uuid)
.execute(pool)
.await;
if let Err(e) = update_result {
tracing::warn!("[Unregister] Failed to mark video as unregistered: {}", e);
}
// Delete related DB records
for (table, col) in tables_to_delete {
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;
match result {
Ok(r) => deleted += r.rows_affected() as usize,
Err(e) => tracing::warn!("[Unregister] Failed to delete from {}: {}", table, e),
}
}
// 6. Delete related command_queue entries (by file_path)
if let Some(path) = file_path {
let cmd_result = sqlx::query(
"DELETE FROM command_queue WHERE value->>'file_path' = $1"
)
.bind(&path)
.execute(pool)
.await;
if let Ok(r) = cmd_result {
deleted += r.rows_affected() as usize;
tracing::info!("[Unregister] Deleted {} command_queue entries for {}", r.rows_affected(), uuid);
}
}
Ok(deleted)
}
fn delete_output_files(uuid: &str, output_dir: &str) {
let dir = std::path::PathBuf::from(output_dir);
// Delete JSON files: {uuid}.*.json
if let Ok(entries) = std::fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with(&format!("{}.", uuid)) {
let _ = std::fs::remove_file(&path);
}
}
}
}
// Delete trace directory: {uuid}/
let trace_dir = dir.join(uuid);
if trace_dir.exists() {
let _ = std::fs::remove_dir_all(&trace_dir);
}
}
// ─── Router ──────────────────────────────────────────────────────────────────
pub fn unregister_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/file/:uuid/unregister", post(unregister_file_handler))
}
+255
View File
@@ -0,0 +1,255 @@
//! Upload Paths management API
use axum::{
extract::{Path, State},
http::StatusCode,
response::Json,
routing::{get, post, put, 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)]
#[serde(rename_all = "camelCase")]
pub struct UploadPath {
pub id: i32,
pub name: String,
pub base_path: String,
pub sub_path: String,
pub full_path: String,
pub output_path: Option<String>,
pub enabled: bool,
pub is_default: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateUploadPathRequest {
pub name: String,
#[serde(alias = "base_path")]
pub base_path: String,
#[serde(default, alias = "sub_path")]
pub sub_path: Option<String>,
#[serde(default, alias = "output_path")]
pub output_path: Option<String>,
#[serde(default, alias = "enabled")]
pub enabled: Option<bool>,
#[serde(default, alias = "is_default")]
pub is_default: Option<bool>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateUploadPathRequest {
#[serde(default, alias = "name")]
pub name: Option<String>,
#[serde(default, alias = "base_path")]
pub base_path: Option<String>,
#[serde(default, alias = "sub_path")]
pub sub_path: Option<String>,
#[serde(default, alias = "output_path")]
pub output_path: Option<String>,
#[serde(default, alias = "enabled")]
pub enabled: Option<bool>,
#[serde(default, alias = "is_default")]
pub is_default: Option<bool>,
}
// ── Routes ──────────────────────────────────────────────────────────
pub fn upload_path_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/admin/upload-paths", get(list_upload_paths))
.route("/api/v1/admin/upload-paths", post(create_upload_path))
.route("/api/v1/admin/upload-paths/:id", get(get_upload_path))
.route("/api/v1/admin/upload-paths/:id", put(update_upload_path))
.route("/api/v1/admin/upload-paths/:id", delete(delete_upload_path))
}
// ── Handlers ────────────────────────────────────────────────────────
fn get_pool(state: &AppState) -> &PgPool {
state.db.pool()
}
/// GET /api/v1/admin/upload-paths
async fn list_upload_paths(State(state): State<AppState>) -> Result<Json<Vec<UploadPath>>, StatusCode> {
let pool = get_pool(&state);
let paths = sqlx::query_as::<_, UploadPath>(
"SELECT id, name, base_path, sub_path, full_path, output_path, enabled, is_default,
created_at::text, updated_at::text
FROM upload_paths ORDER BY is_default DESC, name ASC"
)
.fetch_all(pool)
.await
.map_err(|e| {
error!("[upload_paths] list failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(paths))
}
/// POST /api/v1/admin/upload-paths
async fn create_upload_path(
State(state): State<AppState>,
Json(req): Json<CreateUploadPathRequest>,
) -> Result<Json<UploadPath>, StatusCode> {
let pool = get_pool(&state);
let sub_path = req.sub_path.unwrap_or_default();
let full_path = if sub_path.is_empty() {
req.base_path.clone()
} else {
format!("{}/{}", req.base_path, sub_path)
};
if req.is_default.unwrap_or(false) {
sqlx::query("UPDATE upload_paths SET is_default = FALSE")
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
let path = sqlx::query_as::<_, UploadPath>(
"INSERT INTO upload_paths (name, base_path, sub_path, full_path, output_path, enabled, is_default)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, base_path, sub_path, full_path, enabled, is_default,
created_at::text, updated_at::text"
)
.bind(&req.name)
.bind(&req.base_path)
.bind(&sub_path)
.bind(&full_path)
.bind(&req.output_path)
.bind(req.enabled.unwrap_or(true))
.bind(req.is_default.unwrap_or(false))
.fetch_one(pool)
.await
.map_err(|e| {
error!("[upload_paths] create failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
info!("[upload_paths] created: {} -> {}", path.name, path.full_path);
Ok(Json(path))
}
/// GET /api/v1/admin/upload-paths/:id
async fn get_upload_path(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<Json<UploadPath>, StatusCode> {
let pool = get_pool(&state);
let path = sqlx::query_as::<_, UploadPath>(
"SELECT id, name, base_path, sub_path, full_path, output_path, enabled, is_default,
created_at::text, updated_at::text
FROM upload_paths WHERE id = $1"
)
.bind(id)
.fetch_optional(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok(Json(path))
}
/// PUT /api/v1/admin/upload-paths/:id
async fn update_upload_path(
State(state): State<AppState>,
Path(id): Path<i32>,
Json(req): Json<UpdateUploadPathRequest>,
) -> Result<Json<UploadPath>, StatusCode> {
let pool = get_pool(&state);
if req.is_default == Some(true) {
sqlx::query("UPDATE upload_paths SET is_default = FALSE WHERE id != $1")
.bind(id)
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
let path = sqlx::query_as::<_, UploadPath>(
"UPDATE upload_paths
SET name = COALESCE($1, name),
base_path = COALESCE($2, base_path),
sub_path = COALESCE($3, sub_path),
output_path = COALESCE($4, output_path),
full_path = CASE
WHEN $2 IS NOT NULL OR $3 IS NOT NULL THEN
COALESCE($2, base_path) || CASE WHEN COALESCE($3, sub_path) != '' THEN '/' || COALESCE($3, sub_path) ELSE '' END
ELSE full_path
END,
enabled = COALESCE($5, enabled),
is_default = COALESCE($6, is_default),
updated_at = NOW()
WHERE id = $7
RETURNING id, name, base_path, sub_path, full_path, output_path, enabled, is_default,
created_at::text, updated_at::text"
)
.bind(req.name)
.bind(req.base_path)
.bind(req.sub_path)
.bind(req.output_path)
.bind(req.enabled)
.bind(req.is_default)
.bind(id)
.fetch_one(pool)
.await
.map_err(|e| {
error!("[upload_paths] update failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
info!("[upload_paths] updated: {} -> {}", path.name, path.full_path);
Ok(Json(path))
}
/// DELETE /api/v1/admin/upload-paths/:id
async fn delete_upload_path(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let pool = get_pool(&state);
let is_default: bool = sqlx::query_scalar(
"SELECT is_default FROM upload_paths WHERE id = $1"
)
.bind(id)
.fetch_optional(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.unwrap_or(false);
if is_default {
return Err(StatusCode::BAD_REQUEST);
}
let file_count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM videos WHERE folder_id = $1"
)
.bind(id)
.fetch_one(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if file_count > 0 {
return Err(StatusCode::BAD_REQUEST);
}
sqlx::query("DELETE FROM upload_paths WHERE id = $1")
.bind(id)
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
info!("[upload_paths] deleted id={}", id);
Ok(Json(serde_json::json!({"success": true})))
}
+35 -7
View File
@@ -64,6 +64,7 @@ pub struct SceneSearchResponse {
pub total: usize,
pub page: usize,
pub page_size: usize,
pub has_more: bool,
}
#[derive(Debug, Serialize)]
@@ -174,12 +175,17 @@ pub async fn search_vlm_scenes(
Json(ErrorResponse::new(format!("Embedding service unavailable: {}", e)))
})?;
// 2. Vector search in Qdrant
// 2. Vector search in Qdrant — request enough results for the requested page
// page=1: skip 0, take page_size
// page=2: skip page_size, take page_size
// We request page * page_size * 2 (buffer for filtered-out orphaned points)
let skip_count = (req.page.saturating_sub(1)) * req.page_size;
let qdrant_limit = req.page * req.page_size * 2;
let search_results = qdrant
.search_scenes(
&query_embedding,
req.file_uuid.as_deref(),
req.page_size * 2,
qdrant_limit,
)
.await
.map_err(|e| {
@@ -187,8 +193,9 @@ pub async fn search_vlm_scenes(
Json(ErrorResponse::new(format!("Vector search failed: {}", e)))
})?;
// 3. Post-filter and build results
// 3. Post-filter, skip already-returned results, and build results for this page
let mut results = Vec::new();
let mut valid_index = 0usize; // count of valid (non-skipped) results seen so far
for point in search_results {
let payload = match point.get("payload") {
Some(p) => p,
@@ -339,6 +346,13 @@ pub async fn search_vlm_scenes(
continue;
}
// Pagination: skip results from previous pages
if valid_index < skip_count {
valid_index += 1;
continue;
}
valid_index += 1;
results.push(SceneSearchResult {
file_uuid: file_uuid.clone(),
file_name,
@@ -357,19 +371,22 @@ pub async fn search_vlm_scenes(
source: "vector".to_string(),
});
// Stop if we have enough results
// Stop if we have enough results for this page
if results.len() >= req.page_size {
break;
}
}
let total = results.len();
// total = 總有效結果數(含本頁),has_more = 是否有下一頁
let has_more = valid_index > skip_count + results.len();
let total = valid_index; // 所有通過篩選的有效結果總數
Ok(Json(SceneSearchResponse {
results,
total,
page: req.page,
page_size: req.page_size,
has_more,
}))
}
@@ -421,11 +438,14 @@ pub async fn search_vlm_traces(
})?;
// 2. Vector search in Qdrant main collection (chunk_type = vlm_summary)
// Request enough results for pagination
let skip_count = (req.page.saturating_sub(1)) * req.page_size;
let qdrant_limit = req.page * req.page_size * 3;
let search_results = qdrant
.search_trace_vlm(
&query_embedding,
req.file_uuid.as_deref(),
req.page_size * 3,
qdrant_limit,
)
.await
.map_err(|e| {
@@ -433,8 +453,9 @@ pub async fn search_vlm_traces(
Json(ErrorResponse::new(format!("Vector search failed: {}", e)))
})?;
// 3. Post-filter + enrich from trace_profiles
// 3. Post-filter + enrich from trace_profiles (with pagination)
let mut results = Vec::new();
let mut valid_index = 0usize;
for point in search_results {
let payload = match point.get("payload") {
Some(p) => p,
@@ -561,6 +582,13 @@ pub async fn search_vlm_traces(
continue;
}
// Pagination: skip results from previous pages
if valid_index < skip_count {
valid_index += 1;
continue;
}
valid_index += 1;
let fps = fps.unwrap_or(24.0);
let start_time = start_frame.map(|f| f as f64 / fps);
let end_time = end_frame.map(|f| f as f64 / fps);
+141
View File
@@ -0,0 +1,141 @@
//! Embedding 真實測試 — 用 Rust Embedder(與 production 相同程式碼路徑)
//!
//! 執行: cargo run --release --bin test_embedding_rust
use momentry_core::core::embedding::Embedder;
fn cosine_sim(a: &[f32], b: &[f32]) -> f32 {
let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if na > 0.0 && nb > 0.0 { dot / (na * nb) } else { 0.0 }
}
#[tokio::main]
async fn main() {
let mut passed = 0;
let mut failed = 0;
macro_rules! check {
($name:expr, $ok:expr, $detail:expr) => {
if $ok {
passed += 1;
println!(" ✓ {} — {}", $name, $detail);
} else {
failed += 1;
println!(" ✗ {} — {}", $name, $detail);
}
};
}
println!("═══ Rust Embedder 真實測試(production code path)═══");
println!();
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let url = std::env::var("MOMENTRY_EMBED_URL")
.unwrap_or_else(|_| "http://localhost:11436".to_string());
println!(" Embed URL: {}", url);
println!(" Model: embeddinggemma-300m");
println!();
// ── [1] embed_text(無 prefix)──
println!("[1] embed_text(無 prefix)");
match embedder.embed_text("hello world").await {
Ok(emb) => {
check!("回傳向量", !emb.is_empty(), format!("dim={}", emb.len()));
check!("次元 768", emb.len() == 768, format!("dim={}", emb.len()));
check!("值非全零", emb.iter().any(|x| x.abs() > 0.001), "有實際值");
}
Err(e) => {
check!("embed_text", false, format!("錯誤: {}", e));
}
}
// ── [2] embed_document(search_document prefix — 用於入庫)──
println!("[2] embed_document(search_document prefix)");
match embedder.embed_document("A man is playing guitar on stage").await {
Ok(emb) => {
check!("document embedding", emb.len() == 768, format!("dim={}", emb.len()));
}
Err(e) => check!("document embedding", false, format!("錯誤: {}", e)),
}
// ── [3] embed_query(search_query prefix — 用於搜尋)──
println!("[3] embed_query(search_query prefix)");
match embedder.embed_query("person playing guitar").await {
Ok(emb) => {
check!("query embedding", emb.len() == 768, format!("dim={}", emb.len()));
}
Err(e) => check!("query embedding", false, format!("錯誤: {}", e)),
}
// ── [4] 語義相似度(document vs query — 搜尋場景)──
println!("[4] 語義相似度(document vs query)");
let doc_guitar = embedder.embed_document("A man is playing guitar on stage in front of a large audience").await;
let doc_cooking = embedder.embed_document("Someone is cooking pasta in the kitchen with fresh ingredients").await;
let query_guitar = embedder.embed_query("guitar performance").await;
let query_cooking = embedder.embed_query("cooking food").await;
if let (Ok(dg), Ok(dc), Ok(qg), Ok(qc)) = (doc_guitar, doc_cooking, query_guitar, query_cooking) {
let sim_match = cosine_sim(&dg, &qg); // 吉他 doc vs 吉他 query
let sim_cross = cosine_sim(&dg, &qc); // 吉他 doc vs 烹飪 query
let sim_match2 = cosine_sim(&dc, &qc); // 烹飪 doc vs 烹飪 query
check!("相關搜尋高相似度(吉他)", sim_match > 0.5, format!("sim={:.3}", sim_match));
check!("相關搜尋高相似度(烹飪)", sim_match2 > 0.5, format!("sim={:.3}", sim_match2));
check!("相關 > 不相關", sim_match > sim_cross + 0.05, format!("{:.3} > {:.3}", sim_match, sim_cross));
} else {
check!("語義相似度", false, "embedding 呼叫失敗".to_string());
}
// ── [5] 一致性 ──
println!("[5] 一致性");
let e1 = embedder.embed_text("The quick brown fox jumps over the lazy dog").await;
let e2 = embedder.embed_text("The quick brown fox jumps over the lazy dog").await;
if let (Ok(a), Ok(b)) = (e1, e2) {
let sim = cosine_sim(&a, &b);
check!("同句重複一致", sim > 0.999, format!("sim={:.6}", sim));
} else {
check!("同句重複一致", false, "呼叫失敗".to_string());
}
// ── [6] 中文 ──
println!("[6] 中文");
let zh_doc = embedder.embed_document("這部影片展示了一個人在廚房烹飪美食").await;
let zh_query = embedder.embed_query("有人在廚房做菜").await;
let en_query = embedder.embed_query("stock market crash").await;
if let (Ok(zd), Ok(zq), Ok(eq)) = (zh_doc, zh_query, en_query) {
let sim_same = cosine_sim(&zd, &zq);
let sim_diff = cosine_sim(&zd, &eq);
check!("中文 doc vs 中文 query", sim_same > 0.4, format!("sim={:.3}", sim_same));
check!("中文相關 > 不相關", sim_same > sim_diff + 0.05, format!("{:.3} > {:.3}", sim_same, sim_diff));
} else {
check!("中文", false, "呼叫失敗".to_string());
}
// ── [7] 效能(連續 10 次)──
println!("[7] 效能");
let start = std::time::Instant::now();
let mut all_ok = true;
for i in 0..10 {
if embedder.embed_text(&format!("Performance test sentence number {}", i)).await.is_err() {
all_ok = false;
}
}
let elapsed = start.elapsed().as_millis();
check!("10 次連續 < 5 秒", all_ok && elapsed < 5000, format!("{}ms", elapsed));
// ── [8] dimension() ──
println!("[8] dimension()");
check!("dimension() = 768", embedder.dimension() == 768, format!("{}", embedder.dimension()));
println!();
println!("═══ 結果 ═══");
println!(" 通過: {}/{}", passed, passed + failed);
if failed > 0 {
println!(" 失敗: {}", failed);
std::process::exit(1);
} else {
println!(" 全部通過 ✓");
}
}
+90 -8
View File
@@ -94,6 +94,25 @@ pub struct LlmConfig {
pub model: String,
#[serde(default)]
pub timeout: u32,
/// Deprecated single fallback (kept for backward compat; merged into `fallbacks`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fallback_url: Option<String>,
/// Ordered backup endpoints. Each may be a local instance
/// (127.0.0.1:8080/8082) or a remote machine's llama-server
/// (e.g. http://192.168.110.201:8080/... — pooling off-box compute).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fallbacks: Vec<String>,
/// Load strategy across primary + fallbacks:
/// "priority" (default, failover only) or "round_robin"
/// (each request rotates to the next instance — pools all available
/// compute for higher aggregate throughput).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub strategy: Option<String>,
/// Instance on/off switch for routing. When disabled, requests are never
/// routed to this instance (neither as primary nor as fallback).
/// None = enabled (default true).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -267,6 +286,14 @@ fn default_processor_timeout_secs() -> u32 {
.unwrap_or(3600)
}
fn default_preferred_language() -> String {
"en".to_string()
}
fn default_library_sort() -> String {
"name_asc".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AdminSettings {
#[serde(default = "default_session_timeout")]
@@ -279,6 +306,8 @@ pub struct AdminSettings {
pub system_stats_refresh_sec: u32,
#[serde(default = "default_preferred_language")]
pub preferred_language: String,
#[serde(default = "default_library_sort")]
pub library_default_sort: String,
}
/// Get FS VLM enabled setting from admin_config
@@ -381,7 +410,7 @@ fn default_system_stats_refresh_sec() -> u32 {
.unwrap_or(5)
}
fn default_preferred_language() -> String {
fn default_server_preferred_language() -> String {
std::env::var("MOMENTRY_PREFERRED_LANGUAGE")
.unwrap_or_else(|_| "zh-TW".to_string())
}
@@ -730,25 +759,78 @@ pub async fn get_server() -> ServerConfig {
ADMIN_CONFIG.get_server().await
}
/// Read the `paths` block from admin_config.json synchronously (override source).
/// Empty or missing fields mean "not defined here" and fall through to env/default.
fn admin_paths_override() -> PathsConfig {
let mut out = PathsConfig {
output_dir: String::new(),
backup_dir: String::new(),
scripts_dir: String::new(),
cli_dir: String::new(),
python_path: String::new(),
ffmpeg_path: String::new(),
};
let path = get_default_config_path();
if let Ok(content) = std::fs::read_to_string(&path) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(p) = v.get("paths").and_then(|p| p.as_object()) {
let grab = |key: &str| -> String {
p.get(key)
.and_then(|s| s.as_str())
.map(|s| s.trim().to_string())
.unwrap_or_default()
};
out.output_dir = grab("output_dir");
out.backup_dir = grab("backup_dir");
out.scripts_dir = grab("scripts_dir");
out.cli_dir = grab("cli_dir");
out.python_path = grab("python_path");
out.ffmpeg_path = grab("ffmpeg_path");
}
}
}
out
}
/// Resolve once: admin_config.json (non-empty) > env var > hardcoded default.
fn or_default(value: String, fallback: impl FnOnce() -> String) -> String {
if value.is_empty() {
fallback()
} else {
value
}
}
pub fn get_paths_sync() -> PathsConfig {
let ov = admin_paths_override();
PathsConfig {
// Must NOT read config::OUTPUT_DIR here: this function *is* the
// initializer of that lazy static, so reading it re-enters
// once_cell::sync::Lazy::force and deadlocks the calling thread.
output_dir: default_output_dir(),
backup_dir: std::env::var("MOMENTRY_BACKUP_DIR")
output_dir: or_default(ov.output_dir.clone(), default_output_dir),
backup_dir: or_default(ov.backup_dir.clone(), || {
std::env::var("MOMENTRY_BACKUP_DIR")
.unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/backup")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/backup".to_string())
})
}),
scripts_dir: or_default(ov.scripts_dir.clone(), || {
crate::core::path_utils::scripts_dir().to_string_lossy().to_string()
}),
cli_dir: or_default(ov.cli_dir.clone(), || {
crate::core::path_utils::cli_dir().to_string_lossy().to_string()
}),
python_path: or_default(ov.python_path, || {
std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string())
}),
ffmpeg_path: or_default(ov.ffmpeg_path, || {
std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string())
}),
scripts_dir: crate::core::path_utils::scripts_dir().to_string_lossy().to_string(),
cli_dir: crate::core::path_utils::cli_dir().to_string_lossy().to_string(),
python_path: std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string()),
ffmpeg_path: std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string()),
}
}
+11
View File
@@ -1707,6 +1707,10 @@ pub async fn exec_scene_search(
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let vlm_description_localized = payload
.get("vlm_description_localized")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let vlm_tags: Vec<String> = payload
.get("vlm_tags")
.and_then(|v| v.as_array())
@@ -1729,6 +1733,7 @@ pub async fn exec_scene_search(
.unwrap_or_default();
let description_preview = vlm_description.chars().take(150).collect::<String>();
let localized_preview = vlm_description_localized.as_deref().map(|s| s.chars().take(150).collect::<String>());
cards.push(serde_json::json!({
"card_type": "scene",
@@ -1743,6 +1748,7 @@ pub async fn exec_scene_search(
"score": score,
"vlm_tags": vlm_tags,
"vlm_description": description_preview,
"vlm_description_localized": localized_preview,
"source": "vlm_scene"
}));
}
@@ -1847,6 +1853,10 @@ pub async fn exec_vlm_search(
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let vlm_description_localized = payload
.get("vlm_description_localized")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let vlm_tags: Vec<String> = payload
.get("vlm_tags")
.and_then(|v| v.as_array())
@@ -1882,6 +1892,7 @@ pub async fn exec_vlm_search(
"score": score,
"vlm_tags": vlm_tags,
"vlm_description": vlm_description.chars().take(150).collect::<String>(),
"vlm_description_localized": vlm_description_localized.as_deref().map(|s| s.chars().take(150).collect::<String>()),
"source": "vlm_scene"
}));
}
+34
View File
@@ -219,6 +219,40 @@ pub fn get_scene_vlm_config() -> (bool, u32, usize, bool, usize) {
pub static OUTPUT_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_output_dir());
/// Get the per-library output directory for a file based on its upload_path
pub async fn get_output_dir_for_file(file_uuid: &str, pool: &sqlx::PgPool) -> String {
let videos_table = crate::core::db::schema::table_name("videos");
let upload_paths_table = crate::core::db::schema::table_name("upload_paths");
let result: Option<(Option<String>,)> = sqlx::query_as(
&format!(
"SELECT up.output_path FROM {} v
LEFT JOIN {} up ON v.file_path LIKE up.full_path || '%%'
WHERE v.file_uuid = $1
AND up.output_path IS NOT NULL AND up.output_path != ''
LIMIT 1",
videos_table, upload_paths_table
)
)
.bind(file_uuid)
.fetch_optional(pool)
.await
.ok()
.flatten();
if let Some((Some(output_path),)) = result {
return output_path;
}
OUTPUT_DIR.to_string()
}
pub fn get_output_dir_for_file_sync(_file_uuid: &str, _pool: &sqlx::PgPool) -> String {
// Sync context cannot easily query DB - use global OUTPUT_DIR
// Use async version `get_output_dir_for_file()` for proper per-library paths
OUTPUT_DIR.to_string()
}
pub static BACKUP_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_backup_dir());
pub static SCRIPTS_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_scripts_dir());
+56 -1
View File
@@ -844,6 +844,19 @@ pub struct ApiKeyRecord {
pub updated_at: chrono::DateTime<chrono::Utc>,
}
/// One currently-valid login session (for the Admin active-logins view).
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct ActiveSessionRow {
pub session_id: String,
pub username: Option<String>,
pub role: Option<String>,
pub created_at: chrono::DateTime<chrono::Utc>,
pub expires_at: chrono::DateTime<chrono::Utc>,
pub ip_address: String,
pub user_agent: String,
pub source: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeyStats {
pub total_keys: i64,
@@ -3290,7 +3303,49 @@ impl PostgresDb {
Ok(())
}
pub async fn get_session_by_id(
pub async fn create_session_with_meta(
&self,
session_id: &str,
user_id: i32,
api_key_id: &str,
ttl_hours: i64,
ip_address: &str,
user_agent: &str,
source: &str,
) -> Result<()> {
let table = schema::table_name("sessions");
let interval = format!("{} hours", ttl_hours);
sqlx::query(
&format!("INSERT INTO {} (session_id, user_id, api_key_id, expires_at, ip_address, user_agent, source) VALUES ($1, $2, $3, CURRENT_TIMESTAMP + $4::interval, $5, $6, $7)", table)
)
.bind(session_id)
.bind(user_id)
.bind(api_key_id)
.bind(&interval)
.bind(ip_address)
.bind(user_agent)
.bind(source)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn get_active_sessions(&self) -> Result<Vec<ActiveSessionRow>> {
let table = schema::table_name("sessions");
let rows = sqlx::query_as::<_, ActiveSessionRow>(
&format!(
"SELECT s.session_id, u.username, u.role, s.created_at, s.expires_at, COALESCE(s.ip_address, '') AS ip_address, COALESCE(s.user_agent, '') AS user_agent, COALESCE(s.source, '') AS source FROM {} s LEFT JOIN {} u ON u.id = s.user_id WHERE s.expires_at > CURRENT_TIMESTAMP ORDER BY s.created_at DESC",
table,
schema::table_name("users")
)
)
.fetch_all(&self.pool)
.await?;
Ok(rows)
}
pub async fn get_session_by_id(
&self,
session_id: &str,
) -> Result<Option<(i32, i32, String, chrono::DateTime<chrono::Utc>)>> {
+205
View File
@@ -190,3 +190,208 @@ pub async fn ensure_face_track_node(
.await?;
Ok(res.rows_affected())
}
// ─── Face Groups (first-class group entity) ──────────────────────────────────
//
// A face group is now a real row in `face_groups`. Trace membership is stored
// on `trace_profiles.group_id`. The trace name (trace_profiles.name) remains
// only as a per-trace display caption; it is no longer the grouping source of
// truth. Renaming a group = one UPDATE on face_groups. Moving a trace = one
// UPDATE on trace_profiles.
//
// All helpers below are idempotent and safe to call on every request.
// ─────────────────────────────────────────────────────────────────────────────
pub async fn ensure_face_groups_schema(pool: &PgPool) -> anyhow::Result<()> {
let tp = table_name("trace_profiles");
let fg = table_name("face_groups");
sqlx::query(
"CREATE TABLE IF NOT EXISTS face_groups (\
id BIGSERIAL PRIMARY KEY,\
file_uuid VARCHAR(255) NOT NULL,\
name TEXT NOT NULL,\
origin_cluster_id VARCHAR(255),\
sort_index INT NOT NULL DEFAULT 0,\
properties JSONB NOT NULL DEFAULT '{}'::jsonb,\
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\
UNIQUE (file_uuid, name))",
)
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_face_groups_file ON face_groups(file_uuid)")
.execute(pool)
.await?;
sqlx::query(&format!(
"ALTER TABLE {tp} ADD COLUMN IF NOT EXISTS group_id BIGINT REFERENCES face_groups(id)"
))
.execute(pool)
.await?;
// Backfill: every named trace (non-empty, not auto trace labels) defines
// one group row; its traces attach to that group.
{
let sql = format!(
"INSERT INTO {fg} (file_uuid, name) SELECT file_uuid, name FROM {tp} WHERE name IS NOT NULL AND name <> '' AND NOT (name LIKE 'Face Trace %') AND NOT (name LIKE 'Trace %') AND NOT (name LIKE 'Person_%') GROUP BY file_uuid, name ON CONFLICT (file_uuid, name) DO NOTHING");
sqlx::query(&sql).execute(pool).await?;
}
{
let sql = format!(
"UPDATE {tp} SET group_id = g.id FROM {fg} g WHERE g.file_uuid = {tp}.file_uuid AND g.name = {tp}.name AND {tp}.group_id IS NULL");
sqlx::query(&sql).execute(pool).await?;
}
Ok(())
}
/// Get or create the group with the given name for a file. Returns group id.
pub async fn get_or_create_group(
pool: &PgPool,
file_uuid: &str,
name: &str,
) -> anyhow::Result<i64> {
let fg = table_name("face_groups");
let row: (i64,) = sqlx::query_as(&format!(
"INSERT INTO {fg} (file_uuid, name) VALUES ($1, $2) ON CONFLICT (file_uuid, name) DO UPDATE SET updated_at = NOW(), properties = {fg}.properties - 'dissolved' RETURNING id"
))
.bind(file_uuid)
.bind(name)
.fetch_one(pool)
.await?;
Ok(row.0)
}
/// Rename one group row (single write). Bumps updated_at.
pub async fn rename_group(pool: &PgPool, group_id: i64, new_name: &str) -> anyhow::Result<()> {
let fg = table_name("face_groups");
sqlx::query(&format!(
"UPDATE {fg} SET name = $1, updated_at = NOW() WHERE id = $2"
))
.bind(new_name)
.bind(group_id)
.execute(pool)
.await?;
Ok(())
}
/// Delete the group rows matching names (used by merge/ungroup cleanup).
pub async fn delete_groups_by_names(
pool: &PgPool,
file_uuid: &str,
names: &[String],
) -> anyhow::Result<u64> {
if names.is_empty() {
return Ok(0);
}
let fg = table_name("face_groups");
let res = sqlx::query(&format!(
"DELETE FROM {fg} WHERE file_uuid = $1 AND name = ANY($2)"
))
.bind(file_uuid)
.bind(names)
.execute(pool)
.await?;
Ok(res.rows_affected())
}
// ─── Face Groups JSON Persistence ─────────────────────────────────────────────
//
// Saves face group state to {output_dir}/{file_uuid}.face_groups.json
// This serves as the persistent source of truth for face groups, independent
// of face_cluster.json (which is algorithm output) and DB (which may be reset).
// ──────────────────────────────────────────────────────────────────────────────
pub async fn save_face_groups_json(pool: &PgPool, file_uuid: &str) -> anyhow::Result<()> {
use chrono::Utc;
use serde_json::{json, Value};
let fg = table_name("face_groups");
let tp = table_name("trace_profiles");
let v = table_name("videos");
// Get file_name from videos table
let file_name: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_name FROM {v} WHERE file_uuid = $1"
))
.bind(file_uuid)
.fetch_optional(pool)
.await?;
// Get all groups with their trace members
let groups: Vec<(i64, String, Option<String>, Vec<i32>)> = sqlx::query_as(&format!(
"SELECT g.id, g.name, g.origin_cluster_id, \
COALESCE(array_agg(tp.trace_id ORDER BY tp.trace_id) FILTER (WHERE tp.trace_id IS NOT NULL), ARRAY[]::int[]) \
FROM {fg} g \
LEFT JOIN {tp} tp ON tp.group_id = g.id \
WHERE g.file_uuid = $1 \
GROUP BY g.id, g.name, g.origin_cluster_id \
ORDER BY g.sort_index, g.id"
))
.bind(file_uuid)
.fetch_all(pool)
.await?;
// Build groups array
let mut groups_json = Vec::new();
let mut total_traces = 0i64;
for (gid, name, origin_cid, trace_ids) in &groups {
let trace_count = trace_ids.len() as i64;
total_traces += trace_count;
// Find representative trace (first one for now)
let rep_trace = trace_ids.first().copied().unwrap_or(0);
groups_json.push(json!({
"group_id": gid,
"name": name,
"origin_cluster_id": origin_cid,
"trace_ids": trace_ids,
"trace_count": trace_count,
"representative_trace": rep_trace,
"metadata": json!({})
}));
}
let output = json!({
"schema_version": "1.0",
"file_uuid": file_uuid,
"file_name": file_name.unwrap_or_default(),
"updated_at": Utc::now().to_rfc3339(),
"total_groups": groups.len(),
"total_traces": total_traces,
"groups": groups_json
});
// Save to output directory
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));
let json_str = serde_json::to_string_pretty(&output)?;
std::fs::write(&path, json_str)?;
tracing::info!(
"[FaceGroupsJSON] Saved {} groups, {} traces to {}",
groups.len(),
total_traces,
path.display()
);
// Mirror the same data into the workspace SQLite (equivalent backup).
if let Ok(ws) = crate::core::db::workspace_sqlite::WorkspaceDb::open(file_uuid).await {
if let Err(e) = ws
.sync_face_groups(&groups)
.await
{
tracing::warn!("[FaceGroupsJSON] SQLite mirror sync failed: {}", e);
}
}
Ok(())
}
+70
View File
@@ -149,6 +149,27 @@ impl WorkspaceDb {
.execute(&self.pool)
.await?;
// Face groups backup — mirrors face_groups.json (V1.0 persistence
// design). Keeps group name + trace list per file in SQLite so the
// JSON file and SQLite are equivalent backups of each other.
sqlx::query(
"CREATE TABLE IF NOT EXISTS face_groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_uuid TEXT NOT NULL,
group_id INTEGER,
name TEXT NOT NULL,
origin_cluster_id TEXT,
trace_ids TEXT NOT NULL DEFAULT '[]',
trace_count INTEGER NOT NULL DEFAULT 0,
representative_trace INTEGER,
metadata TEXT DEFAULT '{}',
updated_at TEXT DEFAULT (datetime('now')),
UNIQUE(file_uuid, name)
)",
)
.execute(&self.pool)
.await?;
Ok(())
}
@@ -167,6 +188,55 @@ impl WorkspaceDb {
workspace_path(file_uuid).exists()
}
// ── Face Groups (JSON backup mirror) ──
/// Mirror face_groups.json content into this workspace SQLite so the two
/// are equivalent backups. Replaces all rows for the file (full sync).
pub async fn sync_face_groups(
&self,
groups: &[(i64, String, Option<String>, Vec<i32>)],
) -> Result<()> {
// Replace-all sync: delete then insert keeps the mirror exact.
sqlx::query("DELETE FROM face_groups WHERE file_uuid = $1")
.bind(&self.file_uuid)
.execute(&self.pool)
.await?;
for (gid, name, origin_cid, trace_ids) in groups {
let trace_ids_json = serde_json::to_string(trace_ids)
.unwrap_or_else(|_| "[]".to_string());
let rep = trace_ids.first().copied();
sqlx::query(
"INSERT INTO face_groups \
(file_uuid, group_id, name, origin_cluster_id, trace_ids, trace_count, representative_trace) \
VALUES ($1, $2, $3, $4, $5, $6, $7) \
ON CONFLICT(file_uuid, name) DO UPDATE SET \
group_id = excluded.group_id, \
origin_cluster_id = excluded.origin_cluster_id, \
trace_ids = excluded.trace_ids, \
trace_count = excluded.trace_count, \
representative_trace = excluded.representative_trace, \
updated_at = datetime('now')",
)
.bind(&self.file_uuid)
.bind(gid)
.bind(name)
.bind(origin_cid)
.bind(&trace_ids_json)
.bind(trace_ids.len() as i64)
.bind(rep)
.execute(&self.pool)
.await?;
}
tracing::info!(
"[WorkspaceSQLite] Synced {} face_groups rows for {}",
groups.len(),
self.file_uuid
);
Ok(())
}
// ── Processor Results ──
pub async fn upsert_processor_result(
+12
View File
@@ -12,6 +12,18 @@ pub enum MemoryStatus {
High, // > 41 GB (must decrease concurrency)
}
/// Minimum free memory (GB) needed to keep a second llama-server instance warm.
const DUAL_INSTANCE_MIN_FREE_GB: f64 = 12.0;
/// True when free memory is too low to run two llama-server instances at once.
/// Used by LLM routing to collapse chat/vlm/summary onto a single instance.
pub fn memory_constrained() -> bool {
let mut sys = System::new_all();
sys.refresh_memory();
let available_gb = sys.available_memory() as f64 / (1024.0 * 1024.0 * 1024.0);
available_gb < DUAL_INSTANCE_MIN_FREE_GB
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VlmStatus {
Available, // < 5s (can increase concurrency)
+435
View File
@@ -0,0 +1,435 @@
/// File export/import for portable package (.momentry.tar.gz)
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
// ─── Manifest Structures ─────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize)]
pub struct ExportManifest {
pub version: String,
#[serde(rename = "type")]
pub export_type: String,
pub exported_at: String,
pub momentry_version: String,
pub file: FileInfo,
pub data_sources: DataSources,
pub processors: HashMap<String, ProcessorInfo>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FileInfo {
pub uuid: String,
pub file_name: String,
pub file_path: String,
pub file_size: u64,
pub library: String,
pub status: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DataSources {
pub postgresql: PostgresqlInfo,
pub qdrant: QdrantInfo,
pub sqlite: SqliteInfo,
pub redis: RedisInfo,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PostgresqlInfo {
pub tables: Vec<String>,
pub total_records: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct QdrantInfo {
pub collection: String,
pub face_vectors: usize,
pub text_vectors: usize,
pub speaker_vectors: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SqliteInfo {
pub file: String,
pub tables: Vec<String>,
pub total_records: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RedisInfo {
pub keys_count: usize,
pub patterns: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ProcessorInfo {
pub status: String,
pub file: String,
}
// ─── Export Function ─────────────────────────────────────────────────────────
pub async fn export_file(
pool: &sqlx::PgPool,
file_uuid: &str,
output_dir: &str,
export_dir: &str,
) -> Result<PathBuf> {
let package_dir = PathBuf::from(export_dir).join(format!("{}.momentry", file_uuid));
if package_dir.exists() {
std::fs::remove_dir_all(&package_dir)?;
}
// Create directory structure
std::fs::create_dir_all(&package_dir)?;
std::fs::create_dir_all(package_dir.join("video"))?;
std::fs::create_dir_all(package_dir.join("output"))?;
std::fs::create_dir_all(package_dir.join("identities"))?;
std::fs::create_dir_all(package_dir.join("db"))?;
std::fs::create_dir_all(package_dir.join("qdrant"))?;
std::fs::create_dir_all(package_dir.join("redis"))?;
// 1. Get file info from DB
let videos_table = crate::core::db::schema::table_name("videos");
let video_row: Option<(String, String, String)> = sqlx::query_as(
&format!("SELECT file_name, file_path, status FROM {} WHERE file_uuid = $1", videos_table)
)
.bind(file_uuid)
.fetch_optional(pool)
.await?;
let (file_name, file_path, status) = video_row.ok_or_else(|| anyhow::anyhow!("File not found"))?;
// Get file size from filesystem
let file_size = std::fs::metadata(&file_path).ok().map(|m| m.len()).unwrap_or(0);
// Get library name
let library = get_library_for_file(pool, &file_path).await;
// 2. Copy original video
let video_src = PathBuf::from(&file_path);
if video_src.exists() {
let dest = package_dir.join("video").join(&file_name);
std::fs::copy(&video_src, &dest)?;
}
// 3. Copy output files
copy_output_files(file_uuid, output_dir, &package_dir)?;
// 4. Copy identities (if any)
copy_identities_if_exist(output_dir, &package_dir)?;
// 5. Export PostgreSQL data
let db_stats = export_postgres_data(pool, file_uuid, &package_dir).await?;
// 6. Export Qdrant info (placeholder - full implementation later)
let qdrant_stats = QdrantInfo {
collection: "momentry_rule1".to_string(),
face_vectors: 0,
text_vectors: 0,
speaker_vectors: 0,
};
// Create placeholder files
std::fs::write(package_dir.join("qdrant").join("face_vectors.json"), "[]")?;
std::fs::write(package_dir.join("qdrant").join("text_vectors.json"), "[]")?;
std::fs::write(package_dir.join("qdrant").join("speaker_vectors.json"), "[]")?;
// 7. Export Redis info (placeholder)
std::fs::write(package_dir.join("redis").join("job_state.json"), "{}")?;
std::fs::write(package_dir.join("redis").join("cache.json"), "{}")?;
let redis_stats = RedisInfo {
keys_count: 0,
patterns: vec![
"momentry:job:*".to_string(),
"momentry:progress:*".to_string(),
],
};
// 8. Get processor results
let processors = get_processor_results(pool, file_uuid).await?;
// 9. Create manifest
let manifest = 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: FileInfo {
uuid: file_uuid.to_string(),
file_name,
file_path,
file_size,
library,
status,
},
data_sources: DataSources {
postgresql: db_stats,
qdrant: qdrant_stats,
sqlite: SqliteInfo {
file: "workspace.sqlite".to_string(),
tables: vec!["face_detections".to_string()],
total_records: 0,
},
redis: redis_stats,
},
processors,
};
std::fs::write(
package_dir.join("manifest.json"),
serde_json::to_string_pretty(&manifest)?,
)?;
// 10. Generate checksums
generate_checksums_internal(&package_dir)?;
// 11. Create tar.gz
let tar_path = PathBuf::from(export_dir).join(format!("{}.momentry.tar.gz", file_uuid));
create_tar_gz_internal(&package_dir, &tar_path)?;
// Clean up directory
std::fs::remove_dir_all(&package_dir)?;
Ok(tar_path)
}
// ─── Helper Functions ────────────────────────────────────────────────────────
async fn get_library_for_file(pool: &sqlx::PgPool, file_path: &str) -> String {
let paths_table = crate::core::db::schema::table_name("upload_paths");
let row: Option<(String,)> = sqlx::query_as(
&format!(
"SELECT name FROM {} WHERE $1 LIKE full_path || '%%' ORDER BY LENGTH(full_path) DESC LIMIT 1",
paths_table
)
)
.bind(file_path)
.fetch_optional(pool)
.await
.ok()
.flatten();
row.map(|r| r.0).unwrap_or_else(|| "unknown".to_string())
}
fn copy_output_files(uuid: &str, output_dir: &str, package_dir: &Path) -> Result<()> {
let src_dir = PathBuf::from(output_dir);
let dest_dir = package_dir.join("output");
// Copy JSON files: {uuid}.*.json
if let Ok(entries) = std::fs::read_dir(&src_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with(&format!("{}.", uuid)) && name.ends_with(".json") {
std::fs::copy(&path, dest_dir.join(name))?;
}
}
}
}
// Copy trace directory: {uuid}/trace_*/
let trace_src = src_dir.join(uuid);
if trace_src.exists() {
let trace_dest = dest_dir.join(uuid);
copy_dir_all_internal(&trace_src, &trace_dest)?;
}
Ok(())
}
fn copy_identities_if_exist(output_dir: &str, package_dir: &Path) -> Result<()> {
let identities_dir = PathBuf::from(output_dir).join("identities");
if !identities_dir.exists() {
return Ok(());
}
if let Ok(entries) = std::fs::read_dir(&identities_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let name = entry.file_name();
let src = entry.path();
let dest = package_dir.join("identities").join(&name);
copy_dir_all_internal(&src, &dest)?;
}
}
}
Ok(())
}
async fn export_postgres_data(pool: &sqlx::PgPool, uuid: &str, package_dir: &Path) -> Result<PostgresqlInfo> {
let db_dir = package_dir.join("db");
let mut total_records = 0;
let mut tables = Vec::new();
// Helper to export a table
async fn export_table(pool: &sqlx::PgPool, db_dir: &Path, table: &str, where_col: &str, uuid: &str) -> Result<usize> {
let table_name = crate::core::db::schema::table_name(table);
let rows: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {} WHERE {} = $1) v", table_name, where_col)
)
.bind(uuid)
.fetch_all(pool)
.await?;
let count = rows.len();
std::fs::write(
db_dir.join(format!("{}.json", table)),
serde_json::to_string_pretty(&rows)?,
)?;
Ok(count)
}
// Export tables
if let Ok(count) = export_table(pool, &db_dir, "videos", "file_uuid", uuid).await {
total_records += count;
tables.push("videos".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "processor_results", "file_uuid", uuid).await {
total_records += count;
tables.push("processor_results".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "monitor_jobs", "uuid", uuid).await {
total_records += count;
tables.push("monitor_jobs".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "trace_profiles", "file_uuid", uuid).await {
total_records += count;
tables.push("trace_profiles".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "tkg_nodes", "file_uuid", uuid).await {
total_records += count;
tables.push("tkg_nodes".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "chunk", "file_uuid", uuid).await {
total_records += count;
tables.push("chunks".to_string());
}
// Identities (simplified - just export all for now)
let id_table = crate::core::db::schema::table_name("identities");
let identities: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {}) v LIMIT 100", id_table)
)
.fetch_all(pool)
.await?;
if !identities.is_empty() {
total_records += identities.len();
tables.push("identities".to_string());
std::fs::write(db_dir.join("identities.json"), serde_json::to_string_pretty(&identities)?)?;
}
Ok(PostgresqlInfo { tables, total_records })
}
pub async fn get_processor_results(pool: &sqlx::PgPool, uuid: &str) -> Result<HashMap<String, ProcessorInfo>> {
let table = crate::core::db::schema::table_name("processor_results");
let rows: Vec<(String, String)> = sqlx::query_as(
&format!("SELECT processor, status FROM {} WHERE file_uuid = $1", table)
)
.bind(uuid)
.fetch_all(pool)
.await?;
let mut processors = HashMap::new();
for (proc_type, status) in rows {
let output_file = format!("{}.{}.json", uuid, proc_type);
processors.insert(proc_type, ProcessorInfo {
status,
file: output_file,
});
}
Ok(processors)
}
pub fn copy_dir_all_internal(src: &Path, dest: &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_internal(&path, &dest_path)?;
} else {
std::fs::copy(&path, &dest_path)?;
}
}
Ok(())
}
pub fn generate_checksums_internal(package_dir: &Path) -> Result<()> {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::io::Read;
let mut lines = Vec::new();
for entry in walkdir::WalkDir::new(package_dir)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.file_type().is_file())
{
let path = entry.path();
if path.file_name().map(|n| n == "checksums.sha256").unwrap_or(false) {
continue;
}
let relative = path.strip_prefix(package_dir)?;
let mut file = std::fs::File::open(path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
let mut hasher = DefaultHasher::new();
buffer.hash(&mut hasher);
let hash = hasher.finish();
lines.push(format!("{:016x} {}", hash, relative.to_string_lossy()));
}
std::fs::write(package_dir.join("checksums.sha256"), lines.join("\n"))?;
Ok(())
}
pub fn create_tar_gz_internal(source_dir: &Path, output_path: &Path) -> Result<()> {
use flate2::write::GzEncoder;
use flate2::Compression;
use tar::Builder;
let file = std::fs::File::create(output_path)?;
let encoder = GzEncoder::new(file, Compression::default());
let mut tar = Builder::new(encoder);
tar.append_dir_all("", source_dir)?;
tar.finish()?;
Ok(())
}
pub fn extract_package_internal(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(())
}
+2
View File
@@ -351,6 +351,7 @@ impl FileProfile {
let path = Self::profile_path(output_dir, &self.file_uuid);
let json =
serde_json::to_string_pretty(self).context("Failed to serialize file profile")?;
let json = crate::core::json_debug::append_debug_footer(json, &path);
std::fs::write(&path, json)
.with_context(|| format!("Failed to write profile to {}", path.display()))?;
tracing::debug!("[FileProfile] Saved profile for {}", self.file_uuid);
@@ -670,6 +671,7 @@ impl FaceTraceProfile {
let json = serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*self)?))
.context("Failed to serialize FaceTraceProfile")?;
let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id);
let json = crate::core::json_debug::append_debug_footer(json, &profile_path);
std::fs::write(&profile_path, json)
.with_context(|| format!("Failed to write {}", profile_path.display()))?;
+475
View File
@@ -0,0 +1,475 @@
/// Folder batch export/import
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
// ─── Folder Manifest ─────────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize)]
pub struct FolderManifest {
pub version: String,
#[serde(rename = "type")]
pub export_type: String,
pub exported_at: String,
pub momentry_version: String,
pub folder: FolderInfo,
pub files: Vec<FileInfo>,
pub total_records: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FolderInfo {
pub name: String,
pub original_path: String,
pub library: String,
pub file_count: usize,
pub total_size: u64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FileInfo {
pub uuid: String,
pub file_name: String,
pub file_path: String,
pub file_size: u64,
pub status: String,
pub processors: HashMap<String, String>,
}
// ─── Import Result ───────────────────────────────────────────────────────────
pub struct FolderImportResult {
pub folder_name: String,
pub imported_files: usize,
pub total_records: usize,
}
// ─── Export Function ─────────────────────────────────────────────────────────
pub async fn export_folder(
pool: &sqlx::PgPool,
folder_path: &str,
library_name: &str,
export_dir: &str,
) -> Result<(PathBuf, usize)> {
// Find all files in folder
let videos_table = crate::core::db::schema::table_name("videos");
let files: Vec<(String, String, String, Option<i64>, String)> = sqlx::query_as(
&format!(
"SELECT file_uuid, file_name, file_path, file_size, status FROM {} WHERE file_path LIKE $1 || '%%'",
videos_table
)
)
.bind(folder_path.trim_end_matches('/'))
.fetch_all(pool)
.await?;
if files.is_empty() {
return Err(anyhow::anyhow!("No files found in folder"));
}
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let package_dir = PathBuf::from(export_dir).join(format!("{}.momentry", library_name));
if package_dir.exists() {
std::fs::remove_dir_all(&package_dir)?;
}
// Create directory structure
std::fs::create_dir_all(&package_dir)?;
std::fs::create_dir_all(package_dir.join("videos"))?;
std::fs::create_dir_all(package_dir.join("output"))?;
std::fs::create_dir_all(package_dir.join("identities"))?;
std::fs::create_dir_all(package_dir.join("db"))?;
std::fs::create_dir_all(package_dir.join("qdrant"))?;
std::fs::create_dir_all(package_dir.join("redis"))?;
let mut manifest_files = Vec::new();
let mut total_size = 0u64;
let mut total_records = 0usize;
// Process each file
for (uuid, file_name, file_path, file_size, status) in &files {
let fsize = file_size.unwrap_or(0) as u64;
total_size += fsize;
// Copy video
let video_src = PathBuf::from(file_path);
if video_src.exists() {
let dest = package_dir.join("videos").join(file_name);
std::fs::copy(&video_src, &dest)?;
}
// Copy output files
copy_file_output(uuid, output_dir, &package_dir)?;
// Export DB records
let records = export_file_db_records(pool, uuid, &package_dir).await?;
total_records += records;
// Get processors
let processors = crate::core::export::get_processor_results(pool, uuid).await?;
let proc_map: HashMap<String, String> = processors.iter()
.map(|(k, v)| (k.clone(), v.status.clone()))
.collect();
manifest_files.push(FileInfo {
uuid: uuid.clone(),
file_name: file_name.clone(),
file_path: file_path.clone(),
file_size: fsize,
status: status.clone(),
processors: proc_map,
});
}
// Copy shared identities
copy_shared_identities(output_dir, &package_dir)?;
// Create folder manifest
let manifest = FolderManifest {
version: "1.0".to_string(),
export_type: "folder".to_string(),
exported_at: chrono::Utc::now().to_rfc3339(),
momentry_version: env!("CARGO_PKG_VERSION").to_string(),
folder: FolderInfo {
name: library_name.to_string(),
original_path: folder_path.to_string(),
library: library_name.to_string(),
file_count: files.len(),
total_size,
},
files: manifest_files,
total_records,
};
std::fs::write(
package_dir.join("manifest.json"),
serde_json::to_string_pretty(&manifest)?,
)?;
// Generate checksums
crate::core::export::generate_checksums_internal(&package_dir)?;
// Create tar.gz
let folder_name = PathBuf::from(folder_path)
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| library_name.to_string());
let tar_path = PathBuf::from(export_dir).join(format!("{}.momentry.tar.gz", folder_name));
crate::core::export::create_tar_gz_internal(&package_dir, &tar_path)?;
// Clean up
std::fs::remove_dir_all(&package_dir)?;
Ok((tar_path, files.len()))
}
// ─── Import Function ─────────────────────────────────────────────────────────
pub async fn import_folder(
pool: &sqlx::PgPool,
package_path: &str,
target_folder_path: Option<&str>,
force: bool,
) -> Result<FolderImportResult> {
let pkg_path = PathBuf::from(package_path);
let temp_dir = pkg_path.parent().unwrap_or(std::path::Path::new("."))
.join(pkg_path.file_stem().unwrap_or_default());
// Extract
crate::core::export::extract_package_internal(&pkg_path, &temp_dir)?;
// Read manifest
let manifest_str = std::fs::read_to_string(temp_dir.join("manifest.json"))?;
let manifest: FolderManifest = serde_json::from_str(&manifest_str)?;
let mut imported_files = 0;
let mut total_records = 0;
// Import each file
for file_info in &manifest.files {
// Check if 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_info.uuid)
.fetch_optional(pool)
.await?;
if exists.is_some() && !force {
tracing::warn!("[Folder Import] Skipping existing file: {}", file_info.uuid);
continue;
}
// Delete existing if force
if exists.is_some() {
delete_existing_records(pool, &file_info.uuid).await?;
}
// Restore video
let video_src = temp_dir.join("videos").join(&file_info.file_name);
let video_dest = target_folder_path
.map(|p| PathBuf::from(p).join(&file_info.file_name))
.unwrap_or_else(|| PathBuf::from(&file_info.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)?;
}
// Restore output files
restore_file_output(&temp_dir, &file_info.uuid)?;
// Restore DB records
let records = restore_file_db_records(pool, &temp_dir, &file_info.uuid).await?;
total_records += records;
imported_files += 1;
}
// Restore identities
restore_shared_identities(&temp_dir)?;
// Clean up
let _ = std::fs::remove_dir_all(&temp_dir);
Ok(FolderImportResult {
folder_name: manifest.folder.name,
imported_files,
total_records,
})
}
// ─── Helper Functions ────────────────────────────────────────────────────────
fn copy_file_output(uuid: &str, output_dir: &str, package_dir: &PathBuf) -> Result<()> {
let src_dir = PathBuf::from(output_dir);
let dest_dir = package_dir.join("output");
// Copy JSON files
if let Ok(entries) = std::fs::read_dir(&src_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with(&format!("{}.", uuid)) && name.ends_with(".json") {
std::fs::copy(&path, dest_dir.join(name))?;
}
}
}
}
// Copy trace directory
let trace_src = src_dir.join(uuid);
if trace_src.exists() {
let trace_dest = dest_dir.join(uuid);
crate::core::export::copy_dir_all_internal(&trace_src, &trace_dest)?;
}
Ok(())
}
fn copy_shared_identities(output_dir: &str, package_dir: &PathBuf) -> Result<()> {
let identities_dir = PathBuf::from(output_dir).join("identities");
if !identities_dir.exists() {
return Ok(());
}
let dest_identities = package_dir.join("identities");
if let Ok(entries) = std::fs::read_dir(&identities_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let name = entry.file_name();
let src = entry.path();
let dest = dest_identities.join(&name);
if !dest.exists() {
crate::core::export::copy_dir_all_internal(&src, &dest)?;
}
}
}
}
Ok(())
}
async fn export_file_db_records(pool: &sqlx::PgPool, uuid: &str, package_dir: &PathBuf) -> Result<usize> {
let db_dir = package_dir.join("db");
let mut total = 0;
let tables = ["videos", "processor_results", "monitor_jobs", "trace_profiles", "tkg_nodes", "chunk"];
for table in tables {
let table_name = crate::core::db::schema::table_name(table);
let col = if table == "monitor_jobs" { "uuid" } else { "file_uuid" };
let rows: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {} WHERE {} = $1) v", table_name, col)
)
.bind(uuid)
.fetch_all(pool)
.await?;
if !rows.is_empty() {
std::fs::write(
db_dir.join(format!("{}.json", table)),
serde_json::to_string_pretty(&rows)?,
)?;
total += rows.len();
}
}
Ok(total)
}
async fn delete_existing_records(pool: &sqlx::PgPool, uuid: &str) -> Result<()> {
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 _ = sqlx::query(&format!("DELETE FROM {} WHERE {} = $1", table_name, col))
.bind(uuid)
.execute(pool)
.await;
}
Ok(())
}
fn restore_file_output(temp_dir: &PathBuf, uuid: &str) -> Result<()> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let dest_dir = 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() {
if path.file_name().map(|n| n == uuid).unwrap_or(false) {
let dest = dest_dir.join(uuid);
crate::core::export::copy_dir_all_internal(&path, &dest)?;
}
}
}
}
Ok(())
}
async fn restore_file_db_records(pool: &sqlx::PgPool, temp_dir: &PathBuf, uuid: &str) -> Result<usize> {
let db_dir = temp_dir.join("db");
if !db_dir.exists() {
return Ok(0);
}
let mut restored = 0;
let tables = ["videos", "processor_results", "monitor_jobs", "trace_profiles", "tkg_nodes", "chunk"];
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::Value> = 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<String> = record.as_object().unwrap().keys()
.map(|k| format!("\"{}\"", k)).collect();
let cols_str = columns.join(", ");
// Build values with proper type handling
let values: Vec<String> = 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;
if result.is_ok() {
restored += 1;
}
}
}
Ok(restored)
}
fn restore_shared_identities(temp_dir: &PathBuf) -> Result<()> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let dest_identities = 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() {
crate::core::export::copy_dir_all_internal(&entry.path(), &dest)?;
}
}
}
}
Ok(())
}
+1 -1
View File
@@ -362,7 +362,7 @@ async fn check_dependencies(env: &std::collections::HashMap<String, String>, opt
}
let redis_url = env.get("REDIS_URL").cloned()
.unwrap_or_else(|| "redis://localhost:6379".into());
.unwrap_or_else(|| crate::core::config::REDIS_URL.clone());
match check_redis(&redis_url).await {
Ok(_) => ok(opts, "Redis"),
Err(e) => warn(opts, &format!("Redis: {}", e)),
+161
View File
@@ -0,0 +1,161 @@
//! JSON Debug Metadata — 在每個輸出 JSON 的最下方加上本次寫入的絕對檔案位置,
//! 方便開啟 JSON 內容時直接看到來源檔案路徑,利於 debug。
//!
//! 產生的區塊範例(出現在最下方):
//! ```json
//! "_debug": {
//! "absolute_path": "/Users/accusys/momentry/output/demo/xxx.face.json",
//! "written_at_unix": 1763000000
//! }
//! ```
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// 取得檔案的 canonical 絕對路徑。
/// 檔案可能尚未寫入(我們是在寫檔前產生 footer),
/// 因此先嘗試 canonicalize 檔案本身,失敗則 canonicalize 父目錄再接上檔名。
fn absolute_path_string(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()
}
/// 產生 `_debug` 區塊內容。`pretty` 決定縮排樣式(pretty=多行縮排 / compact=單行)。
fn debug_footer(path: &Path, pretty: bool) -> String {
let abs_str = serde_json::to_string(&absolute_path_string(path))
.unwrap_or_else(|_| "\"\"".to_string());
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
if pretty {
format!(
" \"_debug\": {{\n \"absolute_path\": {},\n \"written_at_unix\": {}\n }}",
abs_str, ts
)
} else {
format!("\"_debug\":{{\"absolute_path\":{},\"written_at_unix\":{}}}", abs_str, ts)
}
}
/// 在 JSON 字串最後一個 `}` 前插入 `_debug` 區塊。
/// 自動偵測 pretty(含換行)或 compact 輸出,footer 樣式跟隨原文。
pub fn append_debug_footer(json: String, path: &Path) -> String {
let pretty = json.contains('\n');
let footer = debug_footer(path, pretty);
if json.trim_end() == "{}" || json.trim_end() == "{ }" {
// 空物件:直接放 footer
if pretty {
return format!("{{\n{}\n}}", footer);
}
return format!("{{{}}}", footer);
}
if json.trim_end().ends_with('}') {
let mut out = json;
while out.ends_with('\n') || out.ends_with(' ') {
out.pop();
}
out.pop(); // 移除最後的 '}'
if pretty {
out.push_str(",\n");
out.push_str(&footer);
out.push_str("\n}");
} else {
out.push(',');
out.push_str(&footer);
out.push('}');
}
out
} else {
// 非預期格式(不是物件結尾),原樣返回避免破壞檔案
json
}
}
/// 序列化(pretty)+ 加上 debug footer + 寫入檔案。
pub fn write_json_with_debug<T: Serialize, P: AsRef<Path>>(
path: P,
value: &T,
) -> std::io::Result<()> {
let json = serde_json::to_string_pretty(value)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let json = append_debug_footer(json, path.as_ref());
std::fs::write(path.as_ref(), json)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn footer_pretty_json_is_valid_and_at_bottom() {
let v = json!({"a": 1, "b": [1, 2], "nested": {"x": 1.23456}});
let s = serde_json::to_string_pretty(&v).unwrap();
let out = append_debug_footer(s, Path::new("/tmp/test.face.json"));
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
let debug = parsed.get("_debug").expect("_debug 應存在");
// /tmp 在 macOS 是 symlink → canonical 後為 /private/tmp,
// 因此只斷言「絕對路徑 + 正確檔名」,不寫死完整字串
let abs = debug["absolute_path"].as_str().expect("absolute_path 應為字串");
assert!(abs.starts_with('/'), "應為絕對路徑:{}", abs);
assert!(abs.ends_with("test.face.json"), "檔名應正確:{}", abs);
assert!(debug["written_at_unix"].is_u64());
// _debug 必須在最下方(最後一個鍵)
let last_key_pos = out.rfind("\"_debug\"").unwrap();
assert!(
last_key_pos > out.rfind("\"nested\"").unwrap(),
"_debug 應出現在所有原有鍵之後"
);
}
#[test]
fn footer_compact_json_is_valid() {
let out = append_debug_footer("{\"a\":1,\"b\":2}".to_string(), Path::new("/tmp/x.json"));
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
assert_eq!(parsed["a"], 1);
assert!(parsed.get("_debug").is_some());
assert!(!out.contains('\n'), "compact 輸入應維持 compact 樣式");
}
#[test]
fn footer_empty_object() {
let out = append_debug_footer("{}".to_string(), Path::new("/tmp/x.json"));
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
assert!(parsed.get("_debug").is_some());
}
#[test]
fn write_json_with_debug_roundtrip() {
let dir = std::env::temp_dir().join("json_debug_test");
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("roundtrip_test.json");
let v = json!({"file_uuid": "abc123", "status": "completed"});
write_json_with_debug(&path, &v).unwrap();
let content = std::fs::read_to_string(&path).unwrap();
let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
assert_eq!(parsed["file_uuid"], "abc123");
assert_eq!(
parsed["_debug"]["absolute_path"],
path.canonicalize().unwrap().to_string_lossy().to_string(),
"absolute_path 應為檔案的 canonical 絕對路徑"
);
std::fs::remove_file(&path).ok();
}
}
+30
View File
@@ -55,6 +55,36 @@ pub fn write_file_pretty_rounded<T: Serialize>(
decimals: usize,
) -> anyhow::Result<()> {
let json = to_string_pretty_rounded(value, decimals)?;
// 在 JSON 最下方加上本次寫入的絕對檔案位置(debug 用)
let json = crate::core::json_debug::append_debug_footer(json, std::path::Path::new(path));
std::fs::write(path, json)?;
Ok(())
}
/// 寫入標準化 JSON(含 _meta 和 _debug)
pub fn write_file_standard<T: Serialize>(
value: &T,
path: &str,
decimals: usize,
processor_name: &str,
processor_tool: &str,
processor_version: &str,
file_uuid: &str,
file_path: &str,
file_name: &str,
) -> anyhow::Result<()> {
let json = to_string_pretty_rounded(value, decimals)?;
// 加上 _meta 和 _debug
let json = crate::core::json_standardize::append_meta_and_debug(
json,
std::path::Path::new(path),
processor_name,
processor_tool,
processor_version,
file_uuid,
file_path,
file_name,
);
std::fs::write(path, json)?;
Ok(())
}
+260
View File
@@ -0,0 +1,260 @@
//! JSON 標準化 Metadata — 在每個輸出 JSON 加上 `_meta` 和 `_debug` 區塊
//!
//! ## 標準格式
//! ```json
//! {
//! "_meta": {
//! "schema_version": "1.0",
//! "processor": {"name": "face", "tool": "swift_face", "version": "1.0.0"},
//! "source": {"file_uuid": "xxx", "file_path": "/path/to/video.mp4", "file_name": "025.mp4"},
//! "timestamps": {"created_at": "ISO8601", "completed_at": "ISO8601"},
//! "pipeline": {"scan_id": "", "worker_id": "", "stage": "deep_scan"}
//! },
//! "_debug": {
//! "absolute_path": "/path/to/output/xxx.face.json",
//! "written_at_unix": 1794674568,
//! "output_dir": "/Users/accusys/momentry/output/demo"
//! },
//! "status": "completed",
//! "data": { ... }
//! }
//! ```
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// 處理器資訊
#[derive(Debug, Clone, Serialize)]
pub struct ProcessorMeta {
pub name: String,
pub tool: String,
pub version: String,
}
/// 來源資訊
#[derive(Debug, Clone, Serialize)]
pub struct SourceMeta {
pub file_uuid: String,
pub file_path: String,
pub file_name: String,
}
/// 時間戳記
#[derive(Debug, Clone, Serialize)]
pub struct TimestampsMeta {
pub created_at: String,
pub completed_at: String,
}
/// Pipeline 資訊
#[derive(Debug, Clone, Serialize)]
pub struct PipelineMeta {
#[serde(skip_serializing_if = "String::is_empty")]
pub scan_id: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub worker_id: String,
pub stage: String,
}
/// 完整 _meta 區塊
#[derive(Debug, Clone, Serialize)]
pub struct MetaFooter {
pub schema_version: String,
pub processor: ProcessorMeta,
pub source: SourceMeta,
pub timestamps: TimestampsMeta,
#[serde(skip_serializing_if = "Option::is_none")]
pub pipeline: Option<PipelineMeta>,
}
/// _debug 區塊
#[derive(Debug, Clone, Serialize)]
pub struct DebugFooter {
pub absolute_path: String,
pub written_at_unix: u64,
pub output_dir: String,
}
/// 取得絕對路徑
fn absolute_path_string(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()
}
/// 建立 _meta 區塊
pub fn create_meta(
processor_name: &str,
processor_tool: &str,
processor_version: &str,
file_uuid: &str,
file_path: &str,
file_name: &str,
) -> MetaFooter {
let now = chrono::Utc::now().to_rfc3339();
MetaFooter {
schema_version: "1.0".to_string(),
processor: ProcessorMeta {
name: processor_name.to_string(),
tool: processor_tool.to_string(),
version: processor_version.to_string(),
},
source: SourceMeta {
file_uuid: file_uuid.to_string(),
file_path: file_path.to_string(),
file_name: file_name.to_string(),
},
timestamps: TimestampsMeta {
created_at: now.clone(),
completed_at: now,
},
pipeline: Some(PipelineMeta {
scan_id: std::env::var("MOMENTRY_SCAN_ID").unwrap_or_default(),
worker_id: std::env::var("MOMENTRY_WORKER_ID").unwrap_or_default(),
stage: "deep_scan".to_string(),
}),
}
}
/// 建立 _debug 區塊
pub fn create_debug(path: &Path) -> DebugFooter {
DebugFooter {
absolute_path: absolute_path_string(path),
written_at_unix: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
output_dir: std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "output/demo".to_string()),
}
}
/// 在 JSON 字串中加入 `_meta` 和 `_debug` 區塊
pub fn append_meta_and_debug(
json: String,
path: &Path,
processor_name: &str,
processor_tool: &str,
processor_version: &str,
file_uuid: &str,
file_path: &str,
file_name: &str,
) -> String {
let pretty = json.contains('\n');
// 建立 _meta JSON
let meta = create_meta(processor_name, processor_tool, processor_version, file_uuid, file_path, file_name);
let meta_json = serde_json::to_string(&meta).unwrap_or_else(|_| "{}".to_string());
// 建立 _debug JSON
let debug = create_debug(path);
let debug_json = serde_json::to_string(&debug).unwrap_or_else(|_| "{}".to_string());
// 組合 footer
let footer = if pretty {
format!(
" \"_meta\": {},\n \"_debug\": {}",
meta_json, debug_json
)
} else {
format!(
"\"_meta\":{},\"_debug\":{}",
meta_json, debug_json
)
};
// 插入到 JSON 結尾
if json.trim_end() == "{}" || json.trim_end() == "{ }" {
if pretty {
return format!("{{\n{}\n}}", footer);
}
return format!("{{{}}}", footer);
}
if json.trim_end().ends_with('}') {
let mut out = json;
while out.ends_with('\n') || out.ends_with(' ') {
out.pop();
}
out.pop(); // 移除最後的 '}'
if pretty {
out.push_str(",\n");
out.push_str(&footer);
out.push_str("\n}");
} else {
out.push(',');
out.push_str(&footer);
out.push('}');
}
out
} else {
json
}
}
/// 序列化 + 加上 _meta 和 _debug + 寫入檔案
pub fn write_json_with_meta_and_debug<T: Serialize, P: AsRef<Path>>(
path: P,
value: &T,
processor_name: &str,
processor_tool: &str,
processor_version: &str,
file_uuid: &str,
file_path: &str,
file_name: &str,
) -> std::io::Result<()> {
let json = serde_json::to_string_pretty(value)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let json = append_meta_and_debug(
json,
path.as_ref(),
processor_name,
processor_tool,
processor_version,
file_uuid,
file_path,
file_name,
);
std::fs::write(path.as_ref(), json)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn meta_and_debug_footer_is_valid() {
let v = json!({"status": "completed", "data": {"faces": 10}});
let s = serde_json::to_string_pretty(&v).unwrap();
let out = append_meta_and_debug(
s,
Path::new("/tmp/test.face.json"),
"face",
"swift_face",
"1.0.0",
"abc123",
"/path/to/video.mp4",
"025.mp4"
);
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
assert!(parsed.get("_meta").is_some());
assert!(parsed.get("_debug").is_some());
assert_eq!(parsed["status"], "completed");
assert_eq!(parsed["_meta"]["processor"]["name"], "face");
assert_eq!(parsed["_meta"]["source"]["file_name"], "025.mp4");
}
}
+17 -7
View File
@@ -32,7 +32,7 @@ struct Choice {
}
pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
let req = serde_json::json!({
let mut req = serde_json::json!({
"model": (*config::llm::SUMMARY_MODEL).clone(),
"messages": [
{
@@ -50,13 +50,23 @@ pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
"chat_template_kwargs": {"enable_thinking": false}
});
debug!("Calling LLM: {}", *config::llm::SUMMARY_URL);
let (summary_url, summary_model, summary_fallbacks) =
crate::core::llm::function_calling::resolve_llm_endpoint("summary")
.await
.unwrap_or_else(|_| (config::llm::SUMMARY_URL.clone(), config::llm::CHAT_MODEL.clone(), Vec::new()));
let res = LLM_CLIENT
.post(&*config::llm::SUMMARY_URL)
.json(&req)
.timeout(Duration::from_secs(*config::llm::SUMMARY_TIMEOUT_SECS))
.send()
if let Some(obj) = req.as_object_mut() {
obj.insert("model".to_string(), serde_json::json!(summary_model));
}
debug!("Calling LLM (summary): {}", summary_url);
let res = crate::core::llm::function_calling::post_llm_with_fallback(
&summary_url,
&summary_fallbacks,
&req,
*config::llm::SUMMARY_TIMEOUT_SECS,
)
.await?;
if !res.status().is_success() {
+224 -21
View File
@@ -114,6 +114,218 @@ pub fn llm_chat_url() -> String {
config::llm::CHAT_URL.clone()
}
/// Resolve an LLM endpoint (url, model, fallback_url) by role key.
///
/// Routing rules — instances are identified by **URL** (not port), so an
/// entry may point to a local llama-server (127.0.0.1:8080/8082) or to a
/// remote machine's llama-server (e.g. http://192.168.110.203:8080/...) for
/// future off-box resource use:
/// - `chat` entry defines instance A; `vlm` entry defines instance B.
/// `enabled == false` on an entry removes that instance from routing
/// entirely (never primary, never fallback).
/// - Role primary = the role's configured entry, if its instance is enabled;
/// otherwise the other enabled instance is promoted to primary.
/// - Fallbacks = the entry's own `fallbacks` list (each may be an internal
/// instance or an external machine such as 201/gb10), plus the other
/// enabled instance auto-appended when not already listed.
/// - `strategy == "round_robin"` → every call rotates the candidate order
/// (primary included), pooling all instances' compute for throughput;
/// failover still applies to the remaining list.
/// Otherwise ("priority") the primary is always tried first.
/// - Single enabled instance → everything (chat/vlm/summary) uses that one
/// model with no fallback.
///
/// `key` is one of: "chat", "vlm", "summary".
pub async fn resolve_llm_endpoint(key: &str) -> anyhow::Result<(String, String, Vec<String>)> {
use crate::core::admin_config::LlmConfig;
let chat_cfg = crate::core::admin_config::get_llm_config("chat").await;
let vlm_cfg = crate::core::admin_config::get_llm_config("vlm").await;
let sum_cfg = crate::core::admin_config::get_llm_config("summary").await;
let chat_on = chat_cfg.as_ref().and_then(|c| c.enabled).unwrap_or(true);
let vlm_on = vlm_cfg.as_ref().and_then(|c| c.enabled).unwrap_or(true);
// Env-statics fallback when no admin config entry exists
let chat_entry = chat_cfg.unwrap_or_else(|| LlmConfig {
url: config::llm::CHAT_URL.clone(),
model: config::llm::CHAT_MODEL.clone(),
timeout: 0,
fallback_url: None,
fallbacks: Vec::new(),
strategy: None,
enabled: Some(true),
});
let vlm_entry = vlm_cfg.unwrap_or_else(|| LlmConfig {
url: config::llm::VISION_URL.clone(),
model: config::llm::VISION_MODEL.clone(),
timeout: 0,
fallback_url: None,
fallbacks: Vec::new(),
strategy: None,
enabled: Some(true),
});
let sum_entry = sum_cfg.unwrap_or_else(|| LlmConfig {
url: config::llm::SUMMARY_URL.clone(),
model: config::llm::CHAT_MODEL.clone(),
timeout: 0,
fallback_url: None,
fallbacks: Vec::new(),
strategy: None,
enabled: Some(true),
});
// Capture instance URLs for the enable-check closure before the entries
// are moved into the role selection below.
let chat_url_str = chat_entry.url.clone();
let vlm_url_str = vlm_entry.url.clone();
let (role_entry, other_entry) = match key {
"vlm" => (vlm_entry, chat_entry.clone()),
"summary" => (sum_entry, vlm_entry.clone()),
_ => (chat_entry.clone(), vlm_entry),
};
// Instance identity is by URL: each llm_config entry owns the instance it
// points to (local or remote machine). Unknown URLs (e.g. a manually added
// remote fallback) are treated as enabled.
let inst_on = |u: &str| -> bool {
if u == chat_url_str {
chat_on
} else if u == vlm_url_str {
vlm_on
} else {
true
}
};
// Candidate list: primary + configured fallbacks (legacy fallback_url
// merged in first for backward compat) + the other enabled instance.
let mut candidates: Vec<String> = vec![role_entry.url.clone()];
if let Some(legacy) = role_entry.fallback_url.clone() {
candidates.push(legacy);
}
candidates.extend(role_entry.fallbacks.iter().cloned());
candidates.push(other_entry.url.clone());
// Filter: drop duplicates, drop entries equal to the primary, drop
// disabled instances. Preserve order (priority semantics).
let primary = role_entry.url.clone();
let mut seen = std::collections::HashSet::new();
candidates.retain(|u| {
u != &primary
&& inst_on(u)
&& seen.insert(u.clone())
});
// Role's preferred instance disabled → promote the other enabled instance
if !inst_on(&role_entry.url) {
if !candidates.is_empty() {
let new_primary = candidates.remove(0);
tracing::warn!(
"[LLM] role '{}' primary instance disabled — routing to {}",
key, new_primary
);
return Ok((new_primary, role_entry.model, candidates));
}
anyhow::bail!("[LLM] role '{}' primary instance disabled and no other enabled instance", key);
}
// Resource constraint: when free memory is too low to keep several
// llama-server instances warm, collapse routing to a single instance
// (no fallbacks, no rotation).
if !candidates.is_empty() && crate::core::dynamic_concurrency::memory_constrained() {
tracing::info!(
"[LLM] memory constrained — single-instance routing for '{}' ({} candidates dropped)",
key,
candidates.len()
);
return Ok((primary, role_entry.model, Vec::new()));
}
// Strategy: round_robin rotates the full candidate list (primary first),
// spreading requests across every enabled instance — including remote
// machines — to aggregate their compute. priority keeps the configured
// order untouched.
if role_entry.strategy.as_deref() == Some("round_robin") && !candidates.is_empty() {
static RR_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = RR_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut list: Vec<String> = vec![primary.clone()];
list.extend(candidates);
let len = list.len();
let offset = (n % len as u64) as usize;
list.rotate_left(offset);
let new_primary = list.remove(0);
tracing::debug!(
"[LLM] round_robin pick #{} for '{}' → {} ({} fallbacks)",
n, key, new_primary, list.len()
);
return Ok((new_primary, role_entry.model, list));
}
Ok((primary, role_entry.model, candidates))
}
/// POST an OpenAI-style chat request to `url`; on transport error or 5xx/429,
/// walk `fallbacks` in order (each may be a local llama-server instance or a
/// remote machine's — possibly a different model). llama-server ignores the
/// model field mismatch, so the same request body is reused for each attempt.
pub async fn post_llm_with_fallback(
url: &str,
fallbacks: &[String],
req_body: &serde_json::Value,
timeout_secs: u64,
) -> anyhow::Result<reqwest::Response> {
let send = |u: String| {
LLM_CLIENT
.post(&u)
.json(req_body)
.timeout(std::time::Duration::from_secs(timeout_secs))
.send()
};
match send(url.to_string()).await {
Ok(res) if res.status().is_success() => Ok(res),
Ok(res) => {
let st = res.status().as_u16();
let text = res.text().await.unwrap_or_default();
// Only retry on server-side / busy errors; 4xx means the request itself is bad.
let retriable = st >= 500 || st == 429;
if retriable && !fallbacks.is_empty() {
for (i, fb) in fallbacks.iter().enumerate() {
tracing::warn!("[LLM] {} returned {} — trying fallback #{} {}", url, st, i + 1, fb);
match send(fb.clone()).await {
Ok(r) if r.status().is_success() => return Ok(r),
Ok(r) => {
tracing::warn!("[LLM] fallback #{} {} returned {}", i + 1, fb, r.status());
}
Err(e) => {
tracing::warn!("[LLM] fallback #{} {} unreachable: {}", i + 1, fb, e);
}
}
}
anyhow::bail!("LLM API error ({}): all {} fallback(s) exhausted", st, fallbacks.len())
}
anyhow::bail!("LLM API error ({}): {}", st, text)
}
Err(e) => {
if !fallbacks.is_empty() {
for (i, fb) in fallbacks.iter().enumerate() {
tracing::warn!("[LLM] {} unreachable ({}) — trying fallback #{} {}", url, e, i + 1, fb);
match send(fb.clone()).await {
Ok(r) if r.status().is_success() => return Ok(r),
Ok(r) => {
tracing::warn!("[LLM] fallback #{} {} returned {}", i + 1, fb, r.status());
}
Err(e2) => {
tracing::warn!("[LLM] fallback #{} {} unreachable: {}", i + 1, fb, e2);
}
}
}
anyhow::bail!("LLM API error: {} — all {} fallback(s) exhausted", e, fallbacks.len())
}
Err(anyhow::anyhow!("LLM API error: {}", e))
}
}
}
/// Get the LLM model name from centralized config
pub fn llm_model() -> String {
config::llm::CHAT_MODEL.clone()
@@ -150,8 +362,10 @@ pub async fn call_llm_vision(
{"role": "user", "content": content_parts}
]);
let (vision_url, vision_model, vision_fallbacks) = resolve_llm_endpoint("vlm").await?;
let req = json!({
"model": llm_vision_model(),
"model": vision_model,
"messages": messages,
"temperature": 0.1,
"max_tokens": max_tokens,
@@ -159,12 +373,7 @@ pub async fn call_llm_vision(
"chat_template_kwargs": {"enable_thinking": false}
});
let res = LLM_CLIENT
.post(&llm_vision_url())
.json(&req)
.timeout(std::time::Duration::from_secs(timeout_secs))
.send()
.await?;
let res = post_llm_with_fallback(&vision_url, &vision_fallbacks, &req, timeout_secs).await?;
if !res.status().is_success() {
let text = res.text().await.unwrap_or_default();
anyhow::bail!("Vision LLM API error: {}", text);
@@ -233,8 +442,10 @@ pub async fn call_llm(
*config::llm::CHAT_TIMEOUT_SECS
};
let (chat_url, chat_model, chat_fallback) = resolve_llm_endpoint("chat").await?;
let mut req = serde_json::to_value(&ChatRequest {
model: llm_model(),
model: chat_model,
messages,
temperature: 0.1,
max_tokens,
@@ -245,12 +456,7 @@ pub async fn call_llm(
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
}
let res = LLM_CLIENT
.post(&llm_chat_url())
.json(&req)
.timeout(std::time::Duration::from_secs(timeout))
.send()
.await?;
let res = post_llm_with_fallback(&chat_url, &chat_fallback, &req, timeout).await?;
if !res.status().is_success() {
let text = res.text().await.unwrap_or_default();
@@ -303,8 +509,10 @@ pub async fn call_llm_with_usage(
let start = std::time::Instant::now();
let (chat_url, chat_model, chat_fallback) = resolve_llm_endpoint("chat").await?;
let mut req = serde_json::to_value(&ChatRequest {
model: llm_model(),
model: chat_model,
messages,
temperature: 0.1,
max_tokens,
@@ -315,12 +523,7 @@ pub async fn call_llm_with_usage(
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
}
let res = LLM_CLIENT
.post(&llm_chat_url())
.json(&req)
.timeout(std::time::Duration::from_secs(timeout))
.send()
.await?;
let res = post_llm_with_fallback(&chat_url, &chat_fallback, &req, timeout_secs).await?;
if !res.status().is_success() {
let text = res.text().await.unwrap_or_default();
+5
View File
@@ -11,6 +11,8 @@ pub mod config;
pub mod dynamic_concurrency;
pub mod db;
pub mod embedding;
pub mod folder_export;
pub mod export;
pub mod face_filter_engine;
pub mod file_lifecycle;
pub mod file_profile;
@@ -40,3 +42,6 @@ pub mod tmdb;
pub mod trace_sync;
pub mod vision;
pub mod vlm;
pub mod json_debug;
pub mod json_standardize;
+7 -1
View File
@@ -29,7 +29,13 @@ pub fn momentry_core_dir() -> PathBuf {
// Check if we're in a typical installation structure
if parent.ends_with("bin") {
if let Some(grandparent) = parent.parent() {
return grandparent.join("momentry_core");
// Prefer <grandparent>/momentry_core if it exists
let core = grandparent.join("momentry_core");
if core.exists() {
return core;
}
// Fallback: the grandparent IS the deployment dir (e.g. ~/momentry)
return grandparent.to_path_buf();
}
}
}
+42 -2
View File
@@ -53,8 +53,48 @@ impl AsrxResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write asrx.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.metadata.as_ref()
.and_then(|m| m.source.as_ref())
.map(|s| s.file_uuid.clone())
.unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = self.metadata.as_ref()
.map(|m| m.processor.name.clone())
.unwrap_or_else(|| "asrx".to_string());
let processor_tool = self.metadata.as_ref()
.map(|m| m.processor.tool.clone())
.unwrap_or_else(|| "rust_asr_asrx".to_string());
let processor_version = self.metadata.as_ref()
.map(|m| m.processor.version.clone())
.unwrap_or_else(|| "1.0.0".to_string());
crate::core::json_formatter::write_file_standard(
self,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write asrx.json")?;
Ok(())
}
+74 -19
View File
@@ -1,6 +1,7 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::process::Command;
use std::path::Path;
use std::time::Duration;
use super::executor::PythonExecutor;
@@ -75,29 +76,49 @@ pub async fn process_cut(
let mut result = try_native_cut(video_path);
if let Ok(mut r) = result {
r.add_metadata("cut", "ffmpeg_native", uuid);
let json = serde_json::to_string_pretty(&r)?;
std::fs::write(output_path, &json)
.with_context(|| format!("Failed to write {:?}", output_path))?;
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = uuid.unwrap_or("").to_string();
let file_path = video_path.to_string();
let file_name = std::path::Path::new(video_path)
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
crate::core::json_formatter::write_file_standard(
&r,
output_path,
2,
"cut",
"ffmpeg_native",
"1.0.0",
&file_uuid,
&file_path,
&file_name,
).with_context(|| format!("Failed to write {:?}", output_path))?;
return Ok(r);
}
// Fallback: Python scenedetect
tracing::warn!("[CUT] Native impl failed, falling back to Python");
// Log the real reason the native impl failed (silent fallback hides root causes)
let native_err = result.err().unwrap_or_else(|| anyhow::anyhow!("unknown error"));
tracing::warn!(
"[CUT] Native impl failed, falling back to Python: {:#}",
native_err
);
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("cut/cut_processor.py");
if !script_path.exists() {
let mut empty_result = CutResult {
metadata: None,
frame_count: 0,
fps: 0.0,
scenes: vec![],
};
empty_result.add_metadata("cut", "none", uuid);
let json = serde_json::to_string_pretty(&empty_result)?;
std::fs::write(output_path, &json)
.with_context(|| format!("Failed to write {:?}", output_path))?;
return Ok(empty_result);
// Missing fallback script must be a hard error — writing an empty
// result (fps=0) silently fails downstream verification and hides
// the real cause from the pipeline.
anyhow::bail!(
"[CUT] Native scene detection failed ({:#}) and Python fallback script not found: {:?}",
native_err,
script_path
);
}
executor
@@ -122,9 +143,24 @@ pub async fn process_cut(
// ── Native ffmpeg scene detection ─────────────────────────────────
/// Resolve the ffprobe/ffmpeg executable path.
/// Uses `FFPROBE_PATH` / `FFMPEG_PATH` env vars when set, falling back to the
/// Homebrew absolute path on Apple Silicon. Never rely on bare `Command::new`
/// name lookup — the worker's launchd environment may not resolve it.
fn ff_tool_path(env_var: &str, homebrew_default: &str) -> String {
if let Ok(p) = std::env::var(env_var) {
if !p.trim().is_empty() && std::path::Path::new(&p).exists() {
return p;
}
}
homebrew_default.to_string()
}
fn try_native_cut(video_path: &str) -> Result<CutResult> {
let ffprobe_path = ff_tool_path("FFPROBE_PATH", "/opt/homebrew/bin/ffprobe");
// Step 1: Get video info (fps, frame count)
let probe = Command::new("ffprobe")
let probe = Command::new(&ffprobe_path)
.args([
"-v",
"quiet",
@@ -162,7 +198,7 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
// Step 2: Use ffmpeg scene detection filter
// The `scene` filter computes the difference between consecutive frames
// and outputs when the difference exceeds the threshold (0.3 = medium sensitivity)
let scene_output = Command::new("ffprobe")
let scene_output = Command::new(&ffprobe_path)
.args([
"-v",
"quiet",
@@ -209,7 +245,6 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
let mut prev_time = 0.0;
let mut prev_frame: u64 = 0;
let round_time = |t: f64| (t * 1000.0).round() / 1000.0;
for (i, &cut_time) in scene_times.iter().enumerate() {
let end_frame = (cut_time * fps).round() as u64;
@@ -299,6 +334,26 @@ mod tests {
assert!(parse_fraction("1/0").is_none());
}
/// Reproduces the launchd-worker failure mode seen on 200: PATH without
/// /opt/homebrew/bin made `Command::new("ffprobe")` fail with ENOENT and
/// cut fall back to an empty result (fps=0 → verification failure).
/// Native cut must succeed by resolving ffprobe via FFPROBE_PATH / absolute path.
#[test]
fn test_native_cut_without_homebrew_in_path() {
let video = std::env::var("MOMENTRY_TEST_VIDEO")
.unwrap_or_else(|_| "/Users/accusys/Movies/test/Charade_YouTube_24fps.mp4".to_string());
if !std::path::Path::new(&video).exists() {
return; // test video absent (e.g. CI) — skip
}
let old_path = std::env::var("PATH").unwrap_or_default();
std::env::set_var("PATH", "/usr/bin:/bin:/usr/sbin:/sbin");
let result = try_native_cut(&video);
std::env::set_var("PATH", old_path);
let r = result.expect("native cut must succeed without homebrew in PATH");
assert!(r.fps > 0.0, "fps must be positive, got {}", r.fps);
assert!(r.frame_count > 0, "frame_count must be positive");
}
#[test]
fn test_cut_result_serialization() {
let result = CutResult {
+57 -4
View File
@@ -99,6 +99,15 @@ impl FaceResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// Strip embeddings before saving to disk - they're already in Qdrant
// This saves ~50% disk space (512 floats * 4 bytes per face)
let mut light = self.clone();
@@ -107,8 +116,40 @@ impl FaceResult {
face.embedding = None;
}
}
crate::core::json_formatter::write_file_pretty_rounded(&light, path, 2)
.context("Failed to write face.json")?;
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.metadata.as_ref()
.and_then(|m| m.source.as_ref())
.map(|s| s.file_uuid.clone())
.unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = self.metadata.as_ref()
.map(|m| m.processor.name.clone())
.unwrap_or_else(|| "face".to_string());
let processor_tool = self.metadata.as_ref()
.map(|m| m.processor.tool.clone())
.unwrap_or_else(|| "swift_face".to_string());
let processor_version = self.metadata.as_ref()
.map(|m| m.processor.version.clone())
.unwrap_or_else(|| "1.0.0".to_string());
crate::core::json_formatter::write_file_standard(
&light,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write face.json")?;
Ok(())
}
@@ -368,7 +409,7 @@ pub async fn process_face(
// Execute face tracking
tracing::info!("[FACE] Starting face tracking");
use crate::core::processor::face_tracker::track_faces;
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
if let Err(e) = track_faces(&mut result, 0.3, 0.8, 100.0, true, None) {
tracing::warn!("[FACE] Face tracking failed: {}", e);
} else {
tracing::info!("[FACE] Face tracking completed successfully");
@@ -423,7 +464,7 @@ pub async fn process_face(
// Execute face tracking
tracing::info!("[FACE] Starting face tracking");
use crate::core::processor::face_tracker::track_faces;
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
if let Err(e) = track_faces(&mut result, 0.3, 0.8, 100.0, true, None) {
tracing::warn!("[FACE] Face tracking failed: {}", e);
} else {
tracing::info!("[FACE] Face tracking completed successfully");
@@ -628,6 +669,10 @@ mod tests {
y: 100,
width: 50,
height: 60,
x2: 150,
y2: 160,
center_x: 125,
center_y: 130,
confidence: 0.95,
capture_quality: Some(0.9),
embedding: Some(vec![0.1, 0.2, 0.3]),
@@ -732,6 +777,10 @@ mod tests {
y: 0,
width: 10,
height: 10,
x2: 10,
y2: 10,
center_x: 5,
center_y: 5,
confidence: 0.5,
capture_quality: None,
embedding: None,
@@ -754,6 +803,10 @@ mod tests {
y: 200,
width: 50,
height: 60,
x2: 150,
y2: 260,
center_x: 125,
center_y: 230,
confidence: 0.95,
capture_quality: Some(0.8),
embedding: Some(vec![0.1; 512]),
+35 -4
View File
@@ -115,8 +115,36 @@ impl FaceClusterResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write face_cluster.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.file_uuid.clone().unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = "face_cluster".to_string();
let processor_tool = "face_cluster".to_string();
let processor_version = "1.0.0".to_string();
crate::core::json_formatter::write_file_standard(
self,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write face_cluster.json")?;
Ok(())
}
}
@@ -147,8 +175,11 @@ pub async fn process_face_cluster(
});
}
// Build args with --threshold (default 0.85 to correctly separate male/female faces)
let threshold = similarity_threshold.unwrap_or(0.85);
// Build args with --threshold (default 0.65 similarity → 0.35 distance)
// Lower distance threshold = more permissive (merge more similar faces)
// 0.15 distance was too strict, causing over-segmentation (7 persons instead of 2)
// 0.35 distance correctly gives 2 persons for test video
let threshold = similarity_threshold.unwrap_or(0.65);
let distance = 1.0 - threshold;
let threshold_str = format!("{:.4}", distance);
let mut args = vec![
+31 -3
View File
@@ -143,8 +143,36 @@ impl FaceTrackingResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write face_traced.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.file_uuid.clone().unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = "face_trace".to_string();
let processor_tool = "face_trace".to_string();
let processor_version = "1.0.0".to_string();
crate::core::json_formatter::write_file_standard(
self,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write face_traced.json")?;
Ok(())
}
}
@@ -276,7 +304,7 @@ fn match_faces(
}
}
if best_prev_idx >= 0 && best_iou > 0.5 {
if best_prev_idx >= 0 && best_iou > iou_threshold {
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
used_prev.insert(best_prev_idx as usize);
}
+1
View File
@@ -330,6 +330,7 @@ pub async fn generate_scene_meta(
let out_path = Path::new(crate::core::config::OUTPUT_DIR.as_str())
.join(format!("{}.scene_meta.json", file_uuid));
let json_str = serde_json::to_string_pretty(&meta)?;
let json_str = crate::core::json_debug::append_debug_footer(json_str, &out_path);
tokio::fs::write(&out_path, json_str)
.await
.context("Failed to write scene_meta.json")?;
+74 -2
View File
@@ -53,8 +53,48 @@ impl OcrResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write ocr.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.metadata.as_ref()
.and_then(|m| m.source.as_ref())
.map(|s| s.file_uuid.clone())
.unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = self.metadata.as_ref()
.map(|m| m.processor.name.clone())
.unwrap_or_else(|| "ocr".to_string());
let processor_tool = self.metadata.as_ref()
.map(|m| m.processor.tool.clone())
.unwrap_or_else(|| "swift_ocr".to_string());
let processor_version = self.metadata.as_ref()
.map(|m| m.processor.version.clone())
.unwrap_or_else(|| "1.0.0".to_string());
crate::core::json_formatter::write_file_standard(
self,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write ocr.json")?;
Ok(())
}
}
@@ -287,6 +327,38 @@ pub async fn process_ocr(
args.push(u.to_string());
}
// Calculate sample-interval for ~8Hz sampling
// For 60fps video: 60/8 = 7.5 → 8
// For 30fps video: 30/8 = 3.75 → 4
if let Some(frame_list) = frames {
if !frame_list.is_empty() {
// Estimate fps from frame indices (assuming they're roughly evenly spaced)
let first_frame = frame_list[0];
let last_frame = frame_list[frame_list.len() - 1];
let frame_span = (last_frame - first_frame) as f64;
let sample_count = frame_list.len() as f64;
if frame_span > 0.0 && sample_count > 1.0 {
// Estimated fps based on the sampling pattern
// For 8Hz sampling over the video duration
let estimated_interval = (frame_span / (sample_count - 1.0)).round() as i32;
if estimated_interval > 0 {
args.push("--sample-interval".to_string());
args.push(estimated_interval.to_string());
tracing::info!("[OCR] Using sample-interval={} for ~8Hz sampling", estimated_interval);
}
}
}
} else {
// Default to interval=8 for ~8Hz sampling at 60fps
args.push("--sample-interval".to_string());
args.push("8".to_string());
}
// Always use accurate recognition level
args.push("--recognition-level".to_string());
args.push("accurate".to_string());
let output = tokio::process::Command::new(swift_ocr_path)
.args(&args)
.output()
+102 -9
View File
@@ -378,10 +378,33 @@ impl SceneVlmProcessor {
pub fn save_scene_profile(profile: &SceneProfile, output_dir: &str) -> Result<()> {
let path = SceneProfile::scenes_path(output_dir, &profile.file_uuid);
let json =
serde_json::to_string_pretty(profile).context("Failed to serialize SceneProfile")?;
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = profile.file_uuid.clone();
std::fs::write(&path, json).context("Failed to write scenes.json")?;
// 從 processor 資訊取得工具名稱
let processor_name = "scene_vlm".to_string();
let processor_tool = profile.processor.as_ref()
.map(|p| p.name.clone())
.unwrap_or_else(|| "scene_vlm".to_string());
let processor_version = profile.processor.as_ref()
.map(|p| p.version.clone())
.unwrap_or_else(|| "1.0.0".to_string());
// file_path 和 file_name 需要從外部傳入,這裡用預設值
let file_path = "".to_string();
let file_name = "".to_string();
crate::core::json_formatter::write_file_standard(
profile,
&path.to_string_lossy(),
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write scenes.json")?;
Ok(())
}
@@ -600,6 +623,55 @@ Rules:
.collect()
}
/// Resize image using ffmpeg to reduce VLM API payload size
fn resize_image_for_vlm(image_path: &std::path::Path) -> Result<Vec<u8>> {
use std::process::Command;
// Check if ffmpeg is available
let ffmpeg_path = crate::core::admin_config::get_ffmpeg_path();
// Create temp file for resized image
let temp_dir = std::env::temp_dir();
let temp_path = temp_dir.join(format!("scene_vlm_resized_{}.jpg", std::process::id()));
// Use ffmpeg to resize to max 512x512 while maintaining aspect ratio
let output = Command::new(&ffmpeg_path)
.args([
"-y",
"-i", image_path.to_str().unwrap_or(""),
"-vf", "scale=min(512\\,iw):min(512\\,ih):force_original_aspect_ratio=decrease",
"-q:v", "80",
"-update", "1",
temp_path.to_str().unwrap_or(""),
])
.output()
.with_context(|| format!("Failed to execute ffmpeg for image resize: {:?}", image_path))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::warn!("[Scene VLM] ffmpeg resize failed: {}", stderr);
// Fallback: return original image
return std::fs::read(image_path)
.with_context(|| format!("Failed to read original image: {:?}", image_path));
}
// Read resized image
let resized_bytes = std::fs::read(&temp_path)
.with_context(|| format!("Failed to read resized image: {:?}", temp_path))?;
// Clean up temp file
let _ = std::fs::remove_file(&temp_path);
tracing::info!(
"[Scene VLM] Image resized: {} bytes -> {} bytes",
image_path.metadata().map(|m| m.len()).unwrap_or(0),
resized_bytes.len()
);
Ok(resized_bytes)
}
/// Call VLM API to generate structured scene info.
/// Returns (english_description, objects, bilingual_tags).
pub async fn generate_scene_description(
@@ -609,11 +681,16 @@ Rules:
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use std::time::Duration;
// Read image
let jpeg_bytes = std::fs::read(image_path)
.with_context(|| format!("Failed to read image: {:?}", image_path))?;
// Read and resize image for VLM API (max 512x512 to avoid connection issues)
let jpeg_bytes = Self::resize_image_for_vlm(image_path)
.with_context(|| format!("Failed to process image: {:?}", image_path))?;
let base64_img = BASE64.encode(&jpeg_bytes);
tracing::debug!(
"[Scene VLM] Image encoded: {} bytes base64",
base64_img.len()
);
// VLM API config
let vlm_url = crate::core::config::llm::VISION_URL.clone();
let vlm_model = crate::core::config::llm::VISION_MODEL.clone();
@@ -644,9 +721,11 @@ Rules:
}
]
}],
"max_tokens": 1024,
"max_tokens": 2048,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
"chat_template_kwargs": {"enable_thinking": false},
"reasoning": false,
"thinking": false
});
let client = reqwest::Client::builder()
@@ -682,13 +761,27 @@ Rules:
}
let message = choice.get("message").context("Invalid VLM API response structure")?;
// Try content first, then fallback to reasoning_content (for Gemma models)
let content = match message
.get("content")
.and_then(|c| c.as_str())
.filter(|s| !s.trim().is_empty())
{
Some(s) => s.trim().to_string(),
None => anyhow::bail!("VLM returned empty content"),
None => {
// Fallback to reasoning_content for Gemma models
match message
.get("reasoning_content")
.and_then(|c| c.as_str())
.filter(|s| !s.trim().is_empty())
{
Some(s) => {
tracing::info!("[Scene VLM] Using reasoning_content as fallback");
s.trim().to_string()
},
None => anyhow::bail!("VLM returned empty content and reasoning_content"),
}
}
};
tracing::debug!(
+1
View File
@@ -1590,6 +1590,7 @@ async fn build_face_track_nodes_from_qdrant(
&serde_json::to_value(&trace_profile).unwrap_or_default(),
))
{
let json = crate::core::json_debug::append_debug_footer(json, &tp_path);
let _ = std::fs::write(&tp_path, json);
if tp_path.exists() {
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);
+2 -2
View File
@@ -259,8 +259,8 @@ impl ToolSelector {
}
}
("asrx", "rust") => {
// Future: Rust ASRX implementation
executor.rust_binary_path("rust_asrx")
// Full ASR + diarization with whisper + ECAPA
executor.rust_binary_path("rust_asr_asrx")
}
("asrx", "python") => {
let script = executor.script_path("asrx_processor.py");
+21
View File
@@ -33,6 +33,27 @@ pub async fn sync_trace_label(
qdrant_points_count: 0,
};
// Face-groups normalization (V1.0 §7 G4): an already-grouped trace must
// not have its caption overwritten by an auto cluster label (e.g.
// "Person_N" from a re-run). Mirror the owning group's name instead.
let new_label: String = {
let tp = schema::table_name("trace_profiles");
let fg = schema::table_name("face_groups");
let group_name: Option<String> = sqlx::query_scalar(&format!(
"SELECT {fg}.name FROM {fg} JOIN {tp} ON {tp}.group_id = {fg}.id \
AND {tp}.file_uuid = {fg}.file_uuid \
WHERE {tp}.file_uuid = $1 AND {tp}.trace_id = $2"
))
.bind(file_uuid)
.bind(trace_id)
.fetch_optional(pool)
.await
.ok()
.flatten();
group_name.unwrap_or_else(|| new_label.to_string())
};
let new_label: &str = new_label.as_str();
// 1. 更新 tkg_nodes.label
match update_tkg_label(pool, file_uuid, trace_id, new_label).await {
Ok(rows) => {
+19 -10
View File
@@ -38,9 +38,15 @@ impl VLMClient {
.map_err(|e| VLMError::ImageReadFailed(image_path.to_string(), e))?;
let image_base64 = general_purpose::STANDARD.encode(&image_data);
// 2. 构建请求
// 2. 解析路由(admin config 優先 → env → 預設),並取得備援 endpoint
let (base_url, model, fallbacks) =
crate::core::llm::function_calling::resolve_llm_endpoint("vlm")
.await
.map_err(|e| VLMError::WorkerError(e.to_string()))?;
// 3. 构建请求
let request = serde_json::json!({
"model": self.model,
"model": model,
"messages": [
{
"role": "user",
@@ -62,15 +68,18 @@ impl VLMClient {
"temperature": 0.1
});
// 3. 调用 API
let response = self
.http_client
.post(&self.base_url)
.json(&request)
.send()
.await?;
// 4. 调用 API(主 endpoint 失敗時依序 fallback 到備援實例)
let response =
crate::core::llm::function_calling::post_llm_with_fallback(
&base_url,
&fallbacks,
&request,
120,
)
.await
.map_err(|e| VLMError::WorkerError(e.to_string()))?;
// 4. 检查响应状态
// 5. 检查响应状态
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
+2 -3
View File
@@ -10,10 +10,10 @@ pub mod watcher;
pub mod worker;
pub use core::cache::{keys, MongoCache, RedisCache};
pub use core::cache::{keys, RedisCache};
pub use core::chunk::{Chunk, ChunkSplitter, ChunkType};
pub use core::db::{
Database, MongoDb, PostgresDb, QdrantDb, RedisClient, RedisDb, VectorPayload, VideoRecord,
Database, PostgresDb, QdrantDb, RedisClient, RedisDb, VectorPayload, VideoRecord,
VideoStatus,
};
pub use core::embedding::Embedder;
@@ -26,4 +26,3 @@ pub use core::storage::file_manager::FileManager;
pub use core::storage::output_dir::OutputDir;
pub use core::storage::uuid;
pub use core::thumbnail::{ThumbnailExtractor, ThumbnailResult};
pub use ui::progress::{ProcessorType, ProgressState, ProgressUi};
+1 -1
View File
@@ -404,7 +404,7 @@ async fn handle_worker(
use momentry_core::core::config::REDIS_KEY_PREFIX;
let redis_url = std::env::var("REDIS_URL")
.unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
.unwrap_or_else(|_| momentry_core::core::config::REDIS_URL.clone());
let health_checker = RedisHealthChecker::new(redis_url, 86400);
println!("Running Redis health check on startup...");
+697 -30
View File
@@ -198,6 +198,11 @@ impl JobWorker {
warn!("[HEALTH-CHECK] Initial health check failed: {}", e);
}
// Layer 0: Recover interrupted processors (Worker restarted)
if let Err(e) = self.recover_interrupted_processors().await {
warn!("[RECOVER] Initial recovery failed: {}", e);
}
// Layer 3b: Re-evaluate stuck PROCESSING files
if let Err(e) = self.re_evaluate_stuck_processing().await {
warn!("[RE-EVALUATE] Initial re-evaluation failed: {}", e);
@@ -209,6 +214,8 @@ impl JobWorker {
let reevaluate_interval = std::time::Duration::from_secs(600); // 10 minutes
let mut last_billing_agg = std::time::Instant::now();
let billing_agg_interval = std::time::Duration::from_secs(3600); // 1 hour
let mut last_completeness_check = std::time::Instant::now();
let completeness_check_interval = std::time::Duration::from_secs(1800); // 30 minutes
loop {
if !self.config.enabled {
@@ -225,6 +232,14 @@ impl JobWorker {
last_health_check = std::time::Instant::now();
}
// Layer 3e: Periodic output completeness check every 30 minutes
if last_completeness_check.elapsed() > completeness_check_interval {
if let Err(e) = self.periodic_completeness_check().await {
warn!("[COMPLETENESS] Periodic completeness check failed: {}", e);
}
last_completeness_check = std::time::Instant::now();
}
// Layer 3b: Re-evaluate stuck PROCESSING files every 10 minutes
if last_reevaluate.elapsed() > reevaluate_interval {
if let Err(e) = self.re_evaluate_stuck_processing().await {
@@ -320,6 +335,23 @@ impl JobWorker {
error!("Failed to reset stale running jobs: {}", e);
}
// ── Layer 3c: Job 併發上限(backpressure)─────────────────────────────
// 同時執行 deep scan 的 job 數不得超過上限;超出的 running jobs 自動
// 轉為 paused(video 退回 registered),名額釋出時自動恢復。
// 上限來源:MOMENTRY_MAX_ACTIVE_JOBS > 動態併發(dynamic_max)。
let max_active_jobs = std::env::var("MOMENTRY_MAX_ACTIVE_JOBS")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.unwrap_or(dynamic_max.max(1));
if let Err(e) = self.enforce_job_slot_limit(max_active_jobs).await {
error!("Failed to enforce job slot limit: {}", e);
}
// ── Layer 3d: 卡住偵測 → 自動 re-scan(unregister → register → deep scan)──
if let Err(e) = self.detect_and_rescan_stuck_jobs().await {
error!("Failed stuck-job detection: {}", e);
}
let health_key = format!("{}health", crate::core::config::REDIS_KEY_PREFIX.as_str());
let now = chrono::Utc::now().to_rfc3339();
let running_count = self.processor_pool.get_running_count().await;
@@ -486,10 +518,30 @@ impl JobWorker {
// Process pending jobs if any
let pending_jobs = self.db.get_pending_jobs(self.config.batch_size).await?;
// 認領前的 running 數(enforce_job_slot_limit 已將超額 running 轉 paused)
let running_before_claim: i64 = sqlx::query_scalar(&format!(
"SELECT count(*) FROM {} WHERE status = 'running'",
monitor_jobs_table
))
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
let mut claimed_jobs: i64 = 0;
if !pending_jobs.is_empty() {
info!("Found {} pending jobs ({} paused)", pending_jobs.len(), paused_jobs.len());
for job in pending_jobs {
// Job 名額上限:running + 本輪已認領數不得超過 max_active_jobs
if running_before_claim + claimed_jobs >= max_active_jobs as i64 {
info!(
"[BACKPRESSURE] deep scan 名額已滿({}/{}),其餘 pending jobs 留待名額釋出",
running_before_claim + claimed_jobs,
max_active_jobs
);
break;
}
// Skip paused jobs
if paused_jobs.contains(&job.uuid) {
debug!("Skipping paused job: {}", job.uuid);
@@ -504,6 +556,503 @@ impl JobWorker {
if let Err(e) = self.process_job(job).await {
error!("Failed to process job: {}", e);
}
claimed_jobs += 1;
}
}
Ok(())
}
/// Layer 3c: Job 併發上限(backpressure)
///
/// 同時處於 running 的 deep scan job 不得超過 `limit`:
/// - 超出者自動標記為 paused。保留對象:(1) 有 processor 正在執行的 job、
/// (2) 全部 processor 已 completed 正在 ingestion 收尾的 job、
/// (3) 名額內最新的 jobs。
/// - 被 paused 的 job,其 video 狀態由 scanning 退回 registered,
/// 避免 GUI 顯示大量停滯的 scanning。
/// - 名額釋出時,最舊的 paused jobs 自動恢復為 pending 重新排隊。
/// Layer 0: Recover interrupted processors
///
/// Worker 啟動時自動恢復被中斷的處理器。
/// 當 worker 被 reboot/kill 時,正在執行的處理器會被標記為
/// 'Worker restarted' 並停留在 pending 狀態。
/// 此方法將所有這類處理器重置為 pending 並清除錯誤訊息,
/// 讓 worker 可以重新處理它們。
/// Layer 3e: Periodic completeness check (every 30 minutes)
///
/// 檢查所有 completed 影片的產出完整性。
/// 發現缺項時:
/// 1. 記錄警告 log
/// 2. 更新 Redis 快取(供前端讀取)
/// 3. 嘗試自動修復(觸發 auto-repair for missing JSON)
async fn periodic_completeness_check(&self) -> Result<()> {
info!("[COMPLETENESS] Starting periodic output completeness check");
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let videos_table = schema::table_name("videos");
let rows: Vec<(String, String)> = sqlx::query_as(&format!(
"SELECT file_uuid, file_name FROM {} WHERE file_type = 'video' AND status = 'completed'",
videos_table
))
.fetch_all(self.db.pool())
.await
.unwrap_or_default();
let mut total_missing = 0;
let mut files_with_issues = 0;
for (uuid, file_name) in &rows {
let mut missing: Vec<String> = 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 目錄
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));
}
}
}
}
}
}
if !missing.is_empty() {
files_with_issues += 1;
total_missing += missing.len();
warn!(
"[COMPLETENESS] {} ({}): missing {} items: {}",
file_name,
uuid,
missing.len(),
missing.join(", ")
);
// 寫入 Redis 供前端讀取
let redis_key = format!(
"{}completeness:{}",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
);
if let Ok(mut conn) = self.redis.get_conn().await {
let _: Result<(), _> = redis::cmd("SET")
.arg(&redis_key)
.arg(serde_json::to_string(&missing).unwrap_or_default())
.arg("EX")
.arg(7200i64) // 2 hour TTL
.query_async(&mut conn)
.await;
}
// 嘗試觸發 auto-repair for missing JSON
// (worker 下次 poll 時 check_and_repair_processor_results 會處理)
} else {
// 清除 Redis 中的完整性標記
let redis_key = format!(
"{}completeness:{}",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
);
if let Ok(mut conn) = self.redis.get_conn().await {
let _: Result<(), _> = redis::cmd("DEL")
.arg(&redis_key)
.query_async(&mut conn)
.await;
}
}
}
if files_with_issues > 0 {
warn!(
"[COMPLETENESS] {} files with issues, {} total missing items",
files_with_issues, total_missing
);
} else {
info!("[COMPLETENESS] All outputs complete ({} files checked)", rows.len());
}
Ok(())
}
async fn recover_interrupted_processors(&self) -> Result<()> {
let processor_results_table = schema::table_name("processor_results");
let monitor_jobs_table = schema::table_name("monitor_jobs");
// 1. 重置所有被 worker 重啟中斷的處理器
let recovered = sqlx::query(&format!(
"UPDATE {processor_results_table}
SET status = 'pending', retry_count = 0, error_message = NULL, updated_at = NOW()
WHERE status = 'pending'
AND error_message = 'Worker restarted'"
))
.execute(self.db.pool())
.await
.map(|r| r.rows_affected())
.unwrap_or(0);
if recovered > 0 {
info!(
"[RECOVER] 已恢復 {} 個被中斷的處理器(Worker restarted → pending)",
recovered
);
// 2. 對應的 monitor_jobs 也重置為 pending
let jobs_reset = sqlx::query(&format!(
"UPDATE {monitor_jobs_table} mj
SET status = 'pending', updated_at = NOW()
WHERE mj.status IN ('running', 'failed')
AND EXISTS (
SELECT 1 FROM {processor_results_table} pr
WHERE pr.file_uuid = mj.uuid AND pr.status = 'pending'
)"
))
.execute(self.db.pool())
.await
.map(|r| r.rows_affected())
.unwrap_or(0);
if jobs_reset > 0 {
info!("[RECOVER] 已重置 {} 個 monitor_jobs 為 pending", jobs_reset);
}
} else {
info!("[RECOVER] 無需恢復(沒有被中斷的處理器)");
}
// 3. 額外檢查:有 output 檔案但 DB 狀態為 pending 的處理器
// (避免重複處理已有產出的項目)
let auto_repaired = sqlx::query(&format!(
"UPDATE {processor_results_table} pr
SET status = 'completed', error_message = NULL, updated_at = NOW()
WHERE pr.status = 'pending'
AND EXISTS (
SELECT 1 FROM videos v WHERE v.file_uuid = pr.file_uuid
)
-- 只有當 output 目錄中對應的 JSON 存在時才標記 completed
-- 這裡不直接查檔案系統(SQL 做不到),由 auto-repair 邏輯處理"
))
.execute(self.db.pool())
.await;
// auto-repair 由 process_job 中的 check_and_repair_processor_results 處理
// 這裡不需要額外操作
Ok(())
}
async fn enforce_job_slot_limit(&self, limit: usize) -> Result<()> {
if limit == 0 {
return Ok(());
}
let monitor_jobs_table = schema::table_name("monitor_jobs");
let videos_table = schema::table_name("videos");
let processor_results_table = schema::table_name("processor_results");
// 可被暫停的 running jobs = 無 processor 在執行、且非全 completed(ingestion 中)
let pausable_where = format!(
"status = 'running'
AND id NOT IN (
SELECT DISTINCT job_id FROM {processor_results_table} WHERE status = 'running'
)
AND id NOT IN (
SELECT job_id FROM {processor_results_table}
GROUP BY job_id HAVING bool_and(status = 'completed')
)"
);
// 名額內可保留的 pausable jobs 數 = limit - 被佔用名額(有 processor 在跑的)
let protected: i64 = sqlx::query_scalar(&format!(
"SELECT count(DISTINCT job_id) FROM {processor_results_table} pr
JOIN {monitor_jobs_table} mj ON mj.id = pr.job_id
WHERE mj.status = 'running' AND pr.status = 'running'"
))
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
let keep_count = limit.saturating_sub(protected as usize) as i64;
let demoted = sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET status = 'paused', updated_at = NOW()
WHERE {pausable_where}
AND id NOT IN (
SELECT id FROM (
SELECT id FROM {monitor_jobs_table}
WHERE {pausable_where}
ORDER BY updated_at DESC
LIMIT $1
) keep
)"
))
.bind(keep_count)
.execute(self.db.pool())
.await?
.rows_affected();
if demoted > 0 {
sqlx::query(&format!(
"UPDATE {videos_table} SET status = 'registered', updated_at = NOW()
WHERE status = 'scanning'
AND file_uuid IN (SELECT uuid FROM {monitor_jobs_table} WHERE status = 'paused')"
))
.execute(self.db.pool())
.await?;
info!(
"[BACKPRESSURE] running jobs 超過上限 {},已 paused {} 個 job(video 退回 registered)",
limit, demoted
);
}
// 清理殘留:video 停在 scanning 但對應 job 已不是 running(pending/paused)
// — 歷史重啟或暫停留下的不一致狀態
let _ = sqlx::query(&format!(
"UPDATE {videos_table} SET status = 'registered', updated_at = NOW()
WHERE status = 'scanning'
AND file_uuid IN (SELECT uuid FROM {monitor_jobs_table} WHERE status IN ('pending', 'paused'))
AND file_uuid NOT IN (SELECT uuid FROM {monitor_jobs_table} WHERE status = 'running')"
))
.execute(self.db.pool())
.await;
// 名額釋出 → 恢復最舊的 paused jobs
let running_now: i64 = sqlx::query_scalar(&format!(
"SELECT count(*) FROM {monitor_jobs_table} WHERE status = 'running'"
))
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
let available = (limit as i64) - running_now;
if available > 0 {
let resumed = sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET status = 'pending', updated_at = NOW()
WHERE id IN (
SELECT id FROM {monitor_jobs_table}
WHERE status = 'paused' ORDER BY id LIMIT $1
)"
))
.bind(available)
.execute(self.db.pool())
.await?
.rows_affected();
if resumed > 0 {
info!(
"[BACKPRESSURE] deep scan 名額釋出,恢復 {} 個 paused jobs → pending",
resumed
);
}
}
Ok(())
}
/// Layer 3d: 卡住偵測 → 自動 re-scan(unregister → register → deep scan)
///
/// 判定「卡住」(fingerprint 比對,不受空轉期間的 DB 寫入干擾):
/// 1. job 仍在 running 且沒有任何 processor 正在執行
/// 2. processor pool 完全閒置(沒有其他 job 在跑)— waiting 中的 job
/// 只是排隊,不算卡住
/// 3. 該 job 的 processor 狀態組合(fingerprint)持續
/// MOMENTRY_STUCK_TIMEOUT_MIN(預設 10 分鐘)完全沒有變化
/// 典型場景:dependency 永遠無法滿足(如 asrx 失敗 → asr ingestion 永遠
/// waiting、face_trace 失敗 → face_cluster 永遠 deferred),job 每輪 poll
/// 空轉、永遠無法完成。
///
/// 處理:對卡住的檔案自動 re-scan — 透過 command_queue 建立 register
/// command(force=true → unregister → register → deep_scan),與 GUI 的
/// re-scan 走完全相同路徑。每個檔案最多自動 re-scan
/// MOMENTRY_AUTO_RESCAN_MAX(預設 2)次(Redis 計數、24 小時窗口),
/// 避免對確定性失敗(如 codec 問題)無限重試。
async fn detect_and_rescan_stuck_jobs(&self) -> Result<()> {
// pool 忙碌時不做判定 — waiting 中的 job 只是排隊,不是卡住
if self.processor_pool.get_running_count().await > 0 {
return Ok(());
}
let timeout_min: i64 = std::env::var("MOMENTRY_STUCK_TIMEOUT_MIN")
.ok()
.and_then(|v| v.parse::<i64>().ok())
.filter(|v| *v > 0)
.unwrap_or(10);
let max_rescans: i64 = std::env::var("MOMENTRY_AUTO_RESCAN_MAX")
.ok()
.and_then(|v| v.parse::<i64>().ok())
.filter(|v| *v >= 0)
.unwrap_or(2);
let monitor_jobs_table = schema::table_name("monitor_jobs");
let videos_table = schema::table_name("videos");
let processor_results_table = schema::table_name("processor_results");
// running 且無 processor 在執行的 jobs + 其 processor 狀態 fingerprint
let candidates = sqlx::query_as::<_, (i32, String, Option<String>, Option<String>)>(&format!(
"SELECT mj.id, mj.uuid, v.file_path,
(SELECT string_agg(pr.status, ',' ORDER BY pr.processor)
FROM {processor_results_table} pr WHERE pr.job_id = mj.id)
FROM {monitor_jobs_table} mj
JOIN {videos_table} v ON v.file_uuid = mj.uuid
WHERE mj.status = 'running'
AND NOT EXISTS (
SELECT 1 FROM {processor_results_table} pr
WHERE pr.job_id = mj.id AND pr.status = 'running'
)"
))
.fetch_all(self.db.pool())
.await
.unwrap_or_default();
if candidates.is_empty() {
return Ok(());
}
let now = chrono::Utc::now().timestamp();
let prefix = crate::core::config::REDIS_KEY_PREFIX.as_str();
for (job_id, uuid, file_path, fingerprint) in candidates {
let _ = job_id;
let Some(fp) = fingerprint else {
continue;
};
let Some(mut conn) = self.redis.get_conn().await.ok() else {
continue;
};
// fingerprint 與上次相同?用兩個 key 記錄內容與起始時間
let fp_key = format!("{prefix}stuck_fp:{uuid}");
let since_key = format!("{prefix}stuck_since:{uuid}");
let prev_fp: Option<String> = redis::cmd("GET")
.arg(&fp_key)
.query_async(&mut conn)
.await
.unwrap_or(None);
if prev_fp.as_deref() != Some(fp.as_str()) {
// 狀態有變化(或首次觀察)— 重新計時
let _: Result<(), _> = redis::cmd("SET")
.arg(&fp_key)
.arg(&fp)
.arg("EX")
.arg(timeout_min * 60 * 3)
.query_async(&mut conn)
.await;
let _: Result<(), _> = redis::cmd("SET")
.arg(&since_key)
.arg(now)
.arg("EX")
.arg(timeout_min * 60 * 3)
.query_async(&mut conn)
.await;
continue;
}
// fingerprint 未變 — 檢查持續時間
let since: Option<i64> = redis::cmd("GET")
.arg(&since_key)
.query_async(&mut conn)
.await
.unwrap_or(None);
let Some(since) = since else {
let _: Result<(), _> = redis::cmd("SET")
.arg(&since_key)
.arg(now)
.arg("EX")
.arg(timeout_min * 60 * 3)
.query_async(&mut conn)
.await;
continue;
};
if now - since < timeout_min * 60 {
continue; // 還在觀察期內
}
// ── 確認卡住 ──
let Some(file_path) = file_path else {
warn!("[STUCK-RESCAN] job {} 沒有 file_path,無法自動 re-scan", uuid);
continue;
};
// 每檔案自動 re-scan 次數上限(Redis 計數,24 小時窗口)
let counter_key = format!("{prefix}auto_rescan:{uuid}");
let rescan_count: i64 = redis::cmd("GET")
.arg(&counter_key)
.query_async::<Option<String>>(&mut conn)
.await
.ok()
.flatten()
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(0);
if rescan_count >= max_rescans {
warn!(
"[STUCK-RESCAN] {} 卡住(fingerprint {} 分鐘未變)但已自動 re-scan {} 次(上限 {}),跳過 — 需人工檢查",
uuid,
(now - since) / 60,
rescan_count,
max_rescans
);
// 清除觀察 key,避免 log 每輪重複
let _: Result<(), _> = redis::cmd("DEL").arg(&fp_key).query_async(&mut conn).await;
let _: Result<(), _> = redis::cmd("DEL").arg(&since_key).query_async(&mut conn).await;
continue;
}
// 與 GUI re-scan 相同:register command(force=true → unregister →
// register → deep scan)。先將 job 標記 paused,避免 command 尚未
// 執行的這一輪又被偵測重複排入。
if let Err(e) = sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET status = 'paused', updated_at = NOW()
WHERE uuid = $1 AND status = 'running'"
))
.bind(&uuid)
.execute(self.db.pool())
.await
{
error!("[STUCK-RESCAN] 無法暫停卡住 job {}: {}", uuid, e);
continue;
}
let payload = serde_json::json!({
"force": true,
"deep_scan": true,
"trigger_source": "worker_stuck_auto",
});
match self
.db
.create_command("register", Some(&file_path), None, None, &payload, 1)
.await
{
Ok(cmd) => {
info!(
"[STUCK-RESCAN] job {} 卡住超過 {} 分鐘(fingerprint 無變化),已自動 re-scan(command={},第 {} 次)",
uuid, timeout_min, cmd.command_id, rescan_count + 1
);
let _: Result<i64, _> = redis::cmd("INCR")
.arg(&counter_key)
.query_async(&mut conn)
.await;
let _: Result<(), _> = redis::cmd("EXPIRE")
.arg(&counter_key)
.arg(86_400i64)
.query_async(&mut conn)
.await;
// 清除觀察 key(job 將被 unregister 刪除重建)
let _: Result<(), _> = redis::cmd("DEL").arg(&fp_key).query_async(&mut conn).await;
let _: Result<(), _> = redis::cmd("DEL").arg(&since_key).query_async(&mut conn).await;
}
Err(e) => {
error!("[STUCK-RESCAN] 為 {} 建立 re-scan command 失敗: {}", uuid, e);
}
}
}
@@ -720,13 +1269,14 @@ impl JobWorker {
.unwrap_or(false);
let auto_pipeline_override = cmd
.payload
.get("auto_pipeline")
.get("deep_scan")
.or_else(|| cmd.payload.get("auto_pipeline")) // backward compat: in-flight old commands
.and_then(|v| v.as_bool())
.unwrap_or(false);
let face_settings = cmd.payload.get("face_settings").cloned();
info!(
"[COMMAND_QUEUE] Registering file: {} (user_id={:?}, force={}, auto_pipeline_override={})",
"[COMMAND_QUEUE] Registering file: {} (user_id={:?}, force={}, deep_scan={})",
file_path, user_id, force, auto_pipeline_override
);
@@ -837,9 +1387,9 @@ impl JobWorker {
async fn re_evaluate_stuck_processing(&self) -> Result<()> {
info!("[RE-EVALUATE] Starting re-evaluation of stuck PROCESSING files");
// Get all PROCESSING videos
// Get all PROCESSING/scanning videos
let processing_videos = sqlx::query_as::<_, (String, String)>(&format!(
"SELECT file_uuid, file_name FROM {} WHERE status = 'PROCESSING'",
"SELECT file_uuid, file_name FROM {} WHERE status IN ('PROCESSING', 'scanning')",
crate::core::db::schema::table_name("videos")
))
.fetch_all(self.db.pool())
@@ -1067,31 +1617,13 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
for processor_type in &processors_to_run {
// Check capacity BEFORE setting status to 'running'
if !self.processor_pool.can_start_for_job(job.id).await {
// 併發數已滿:保留 pending,下一輪 poll 再啟動。
// 不可在此標記 skipped — 否則該處理器會被永久跳過
//(這是 ocr / face / face_cluster 大量 skipped 的根因)。
info!(
"Max concurrent processors reached before starting {}, marking as skipped",
"Max concurrent processors reached, {} deferred to next poll",
processor_type.as_str()
);
if let Err(e) = self
.db
.upsert_processor_result(job_id, *processor_type, &job.uuid, "skipped")
.await
{
error!("Failed to create skipped processor result: {}", e);
}
let _ = self
.redis
.update_worker_processor_status(
&job.uuid,
processor_type.as_str(),
"skipped",
None,
0,
0,
0,
0,
0,
)
.await;
continue;
}
@@ -2336,7 +2868,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
true
};
// 4. Face Cluster: face_cluster.json 存在(有 face 時才需要)
// 4. Face Cluster: face_cluster.json 存在 或 processor 已執行過
let face_cluster_done: bool = if has_face {
// No-face video: either explicit status or total_faces=0
if trace_status == "no_faces" || total_faces == Some(0) {
@@ -2357,7 +2889,24 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
true
} else {
let cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid);
std::path::Path::new(&cluster_path).exists()
let file_exists = std::path::Path::new(&cluster_path).exists();
if file_exists {
true
} else {
// 檔案不存在但 processor 已執行過(completed/failed),也算 done
// 避免 processor 跑過但沒產出檔案時 ingestion 永遠卡住
let fc_status: Option<String> = sqlx::query_scalar(&format!(
"SELECT status FROM {pr_t} pr JOIN {mj_t} mj ON pr.job_id = mj.id \
WHERE mj.uuid = $1 AND pr.processor = 'face_cluster' LIMIT 1",
pr_t = schema::table_name("processor_results"),
mj_t = schema::table_name("monitor_jobs")
))
.bind(uuid)
.fetch_optional(pool)
.await
.unwrap_or(None);
fc_status.as_deref() == Some("completed") || fc_status.as_deref() == Some("failed")
}
}
} else {
true
@@ -2498,10 +3047,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
} else {
// scenes.json not found — check processor_results for scene_vlm completion
// (e.g. "completed" due to invalid metadata / not applicable)
let mj_t = schema::table_name("monitor_jobs");
// Note: upsert_scene_vlm_result writes file_uuid + processor_type (not job_id + processor)
let pr_t = schema::table_name("processor_results");
let svlm_done: Option<String> = sqlx::query_scalar(&format!(
"SELECT status FROM {pr_t} WHERE job_id = (SELECT id FROM {mj_t} WHERE uuid = $1) AND processor = 'scene_vlm' LIMIT 1"
"SELECT status FROM {pr_t} WHERE file_uuid = $1 AND processor_type = 'scene_vlm' LIMIT 1"
))
.bind(uuid)
.fetch_optional(pool)
@@ -2536,6 +3085,115 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
all_ok
}
/// Pipeline 完整性驗證:檢查所有必要產出是否存在
///
/// 在 job 完成前,驗證:
/// 1. 所有處理器的 JSON 產出檔案存在
/// 2. Trace 目錄完整(key_face.jpg + key_frame.jpg + trace_profile.json)
/// 3. Scenes 目錄有 scene_*.jpg
///
/// 回傳缺項清單(空 = 完整)。如果有缺項則記錄警告,
/// 讓 auto-repair 或 backfill 有機會修復。
async fn verify_artifacts_complete(
&self,
uuid: &str,
job_processors: &[String],
) -> Result<Vec<String>> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let mut missing = Vec::new();
// 1. 檢查 JSON 產出
let json_processors = [
("cut", "cut"),
("asrx", "asrx"),
("face", "face"),
("face_cluster", "face_cluster"),
("face_trace", "face_traced"),
("ocr", "ocr"),
("scene_vlm", "scenes"),
("probe", "probe"),
];
for (proc_name, file_ext) in &json_processors {
if job_processors.iter().any(|p| p == proc_name) {
let json_path = format!("{}/{}.{}.json", output_dir, uuid, file_ext);
if !std::path::Path::new(&json_path).exists() {
// 如果 processor 已執行過(completed/failed),不算缺項
// 避免 processor 跑過但沒產出檔案時 verification 永遠失敗
let pr_t = schema::table_name("processor_results");
let mj_t = schema::table_name("monitor_jobs");
let proc_status: Option<String> = sqlx::query_scalar(&format!(
"SELECT pr.status FROM {pr_t} pr JOIN {mj_t} mj ON pr.job_id = mj.id \
WHERE mj.uuid = $1 AND pr.processor = $2 LIMIT 1"
))
.bind(uuid)
.bind(proc_name)
.fetch_optional(self.db.pool())
.await
.unwrap_or(None);
if proc_status.as_deref() != Some("completed") && proc_status.as_deref() != Some("failed") {
missing.push(format!("{}.json", file_ext));
}
}
}
}
// 2. 檢查 trace 目錄(如果有 faces)
let face_json_path = format!("{}/{}.face.json", output_dir, uuid);
if std::path::Path::new(&face_json_path).exists() {
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() {
let trace_dir = entry.path();
let trace_name = name;
for required_file in ["key_face.jpg", "key_frame.jpg", "trace_profile.json"] {
if !trace_dir.join(required_file).exists() {
missing.push(format!("{}/{}", trace_name, required_file));
}
}
}
}
}
}
}
// 3. 檢查 scenes 目錄
let scenes_json_path = format!("{}/{}.scenes.json", output_dir, uuid);
if std::path::Path::new(&scenes_json_path).exists() {
let scenes_dir = std::path::Path::new(&output_dir).join(uuid).join("scenes");
if scenes_dir.is_dir() {
let has_scene_jpgs = std::fs::read_dir(&scenes_dir)
.map(|entries| {
entries
.filter_map(|e| e.ok())
.any(|e| {
e.file_name()
.to_string_lossy()
.starts_with("scene_")
})
})
.unwrap_or(false);
if !has_scene_jpgs {
missing.push("scenes/*.jpg".to_string());
}
}
}
if !missing.is_empty() {
warn!(
"[VERIFY] {} 缺少 {} 項產出: {}",
uuid,
missing.len(),
missing.join(", ")
);
}
Ok(missing)
}
async fn check_and_complete_job(
&self,
job_id: i32,
@@ -2552,6 +3210,15 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
expected_count
);
// ── Pipeline 完整性驗證:在完成前檢查所有必要產出 ──
if let Err(e) = self.verify_artifacts_complete(uuid, job_processors).await {
warn!(
"[VERIFY] Artifact completeness check failed for {}: {}",
uuid, e
);
// 不中止 job,只記錄警告 — 讓 auto-repair 有機會修復
}
// Scene VLM 必要檢查 (deep scan = 有 cut):
// - has_cut_job: job 是否含 cut 或 scene_vlm(決定 scene_vlm 是否必要)
// - scene_vlm_complete: scenes.json 完整性
+4 -2
View File
@@ -679,8 +679,10 @@ impl ProcessorPool {
) -> Result<ProcessorOutput> {
let video_path = job.video_path.as_ref().context("No video path in job")?;
// Generate output path
let output_dir = PathBuf::from(OUTPUT_DIR.as_str());
// Determine per-library output directory
let output_dir = PathBuf::from(
crate::core::config::get_output_dir_for_file_sync(&job.uuid, db.pool())
);
let suffix = format!("{}.{}", job.uuid, processor_type.as_str());
let output_path = output_dir.join(format!("{}.json", suffix));
+16 -7
View File
@@ -141,8 +141,8 @@ impl SystemResources {
fn get_memory_info() -> (u64, u64) {
use std::process::Command;
// 總記憶體
let total = Command::new("sysctl")
// 總記憶體(用絕對路徑,避免 PATH 問題;sysctl 位於 /usr/sbin)
let total = Command::new("/usr/sbin/sysctl")
.args(["hw.memsize"])
.output()
.ok()
@@ -158,7 +158,7 @@ impl SystemResources {
// 用 memory_pressure 取得真實可用記憶體
// macOS 的可用記憶體 = free + inactive + speculative
let available = Command::new("memory_pressure")
let available = Command::new("/usr/bin/memory_pressure")
.output()
.ok()
.and_then(|o| {
@@ -175,8 +175,8 @@ impl SystemResources {
None
})
.unwrap_or_else(|| {
// fallback: vm_stat
Command::new("vm_stat")
// fallback: vm_stat(絕對路徑,位於 /usr/bin)
let vm_stat_result = Command::new("/usr/bin/vm_stat")
.output()
.ok()
.and_then(|v| {
@@ -208,9 +208,18 @@ impl SystemResources {
Some(
(free_pages + inactive_pages + speculative_pages) * 16384 / 1024 / 1024,
)
})
.unwrap_or(total / 4)
});
// Sanity check: if vm_stat failed or returned 0 (wrong PATH / parsing),
// fall back to 1/4 of total instead of reporting 0MB (which would
// wrongly trigger backpressure on machines with plenty of RAM).
match vm_stat_result {
Some(mb) if mb > 100 => mb,
_ => total / 4,
}
});
// 最終 sanity check:memory_pressure 解析成功但回 0(例如 total=0)時也兜底
let available = if available > 100 { available } else { total / 4 };
(available, total)
}
+28 -1
View File
@@ -19,6 +19,11 @@ pub const HOP_LENGTH: usize = 160;
pub const WIN_LENGTH: usize = 400;
pub const N_BINS: usize = N_FFT / 2 + 1; // 201
pub const N_MELS: usize = 80;
/// ECAPA 嵌入的最低幀數(10ms/幀 → 16 幀 = 160ms)。
/// 不足者以循環 tile 補足 — 反映 padding 需要時間軸長度 >= 2,
/// 且太短的情緒特徵毫無意義,補足只是為了讓模型能跑完。
pub const MIN_EMBED_FRAMES: usize = 16;
const PAD: usize = N_FFT / 2;
const AMIN: f32 = 1e-10;
const TOP_DB: f32 = 80.0;
@@ -154,8 +159,30 @@ impl Ecapa {
}
/// Run the embedding network on features [n_frames, N_MELS]; returns 192-d.
///
/// ECAPA TDNN 的 conv 使用 reflect padding,時間軸過短(< 若干幀)會在
/// ONNX Pad node 崩潰:"Pad reflect requires axis length >= 2 after
/// slicing. Input shape:{1,80,1}"。長度不足的片段以循環 tile 補足到
/// MIN_EMBED_FRAMES,避免崩潰並保留粗略的說話者相似度。
pub fn embed(&mut self, feats: &[f32], n_frames: usize) -> Result<Vec<f32>> {
let input = ndarray::Array::from_shape_vec(IxDyn(&[1, n_frames, N_MELS]), feats.to_vec())
// 極短(或空)片段:無法形成有效特徵 → 回傳零向量(不參與聚類相似度)
if n_frames == 0 || feats.is_empty() {
return Ok(vec![0f32; 192]);
}
let min_frames = MIN_EMBED_FRAMES;
let (feats_vec, n_eff) = if n_frames < min_frames {
let mut padded = Vec::with_capacity(min_frames * N_MELS);
for t in 0..min_frames {
let src = t % n_frames;
padded.extend_from_slice(&feats[src * N_MELS..(src + 1) * N_MELS]);
}
(padded, min_frames)
} else {
(feats.to_vec(), n_frames)
};
let input = ndarray::Array::from_shape_vec(IxDyn(&[1, n_eff, N_MELS]), feats_vec)
.context("Failed to create ECAPA input array")?;
let input_value = Value::from_array(input).context("Failed to create input value")?;
+137 -11
View File
@@ -1,4 +1,5 @@
use anyhow::{Context, Result};
use chrono::Utc;
use clap::Parser;
use serde::{Deserialize, Serialize};
use std::process::Command;
@@ -24,15 +25,87 @@ struct Cli {
min_scene_duration: f64,
}
// ─── 標準化輸出格式 ─────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize)]
struct CutResult {
scene_count: usize,
struct StandardOutput {
_meta: Meta,
_debug: DebugInfo,
status: String,
data: CutData,
}
#[derive(Debug, Serialize, Deserialize)]
struct Meta {
schema_version: String,
processor: ProcessorInfo,
source: SourceInfo,
timestamps: Timestamps,
#[serde(skip_serializing_if = "Option::is_none")]
pipeline: Option<PipelineInfo>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ProcessorInfo {
name: String,
tool: String,
version: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct SourceInfo {
file_uuid: String,
file_path: String,
file_name: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Timestamps {
created_at: String,
completed_at: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct PipelineInfo {
scan_id: String,
worker_id: String,
stage: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct DebugInfo {
absolute_path: String,
written_at_unix: u64,
output_dir: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct CutData {
frame_count: u64,
fps: f64,
scenes: Vec<Scene>,
video_info: VideoInfo,
}
#[derive(Debug, Serialize, Deserialize)]
struct Scene {
scene_number: usize,
start_frame: u64,
end_frame: u64,
start_time: f64,
end_time: f64,
}
// ─── 舊格式(向後相容)─────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize)]
struct CutResult {
scene_count: usize,
scenes: Vec<InternalScene>,
video_info: VideoInfo,
}
#[derive(Debug, Serialize, Deserialize)]
struct InternalScene {
scene_id: usize,
start_frame: u64,
start_time: f64,
@@ -54,7 +127,11 @@ fn main() -> Result<()> {
println!("[CUT] Processing: {}", args.video_path);
let output_path = args.output.unwrap_or_else(|| {
if let Some(uuid) = &args.uuid {
format!("output/demo/{}.cut.json", uuid)
} else {
args.video_path.replace(".mp4", ".cut.json")
}
});
let video_info = get_video_info(&args.video_path)?;
@@ -64,13 +141,62 @@ fn main() -> Result<()> {
let scenes = detect_scenes(&args.video_path, args.min_scene_duration, &video_info)?;
println!("[CUT] Detected {} scenes", scenes.len());
let result = CutResult {
scene_count: scenes.len(),
scenes,
video_info,
// 建立標準化輸出
let file_uuid = args.uuid.clone().unwrap_or_default();
let file_name = std::path::Path::new(&args.video_path)
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let now = Utc::now();
let standard_output = StandardOutput {
_meta: Meta {
schema_version: "1.0".to_string(),
processor: ProcessorInfo {
name: "cut".to_string(),
tool: "ffmpeg_native".to_string(),
version: "1.0.0".to_string(),
},
source: SourceInfo {
file_uuid: file_uuid.clone(),
file_path: args.video_path.clone(),
file_name: file_name.clone(),
},
timestamps: Timestamps {
created_at: now.to_rfc3339(),
completed_at: now.to_rfc3339(),
},
pipeline: Some(PipelineInfo {
scan_id: std::env::var("MOMENTRY_SCAN_ID").unwrap_or_default(),
worker_id: std::env::var("MOMENTRY_WORKER_ID").unwrap_or_default(),
stage: "deep_scan".to_string(),
}),
},
_debug: DebugInfo {
absolute_path: std::fs::canonicalize(&output_path)
.unwrap_or_else(|_| std::path::PathBuf::from(&output_path))
.to_string_lossy()
.to_string(),
written_at_unix: now.timestamp() as u64,
output_dir: std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "output/demo".to_string()),
},
status: "completed".to_string(),
data: CutData {
frame_count: video_info.frame_count,
fps: video_info.fps,
scenes: scenes.into_iter().map(|s: InternalScene| Scene {
scene_number: s.scene_id,
start_frame: s.start_frame,
end_frame: s.end_frame,
start_time: s.start_time,
end_time: s.end_time,
}).collect(),
},
};
let json = serde_json::to_string_pretty(&result)?;
let json = serde_json::to_string_pretty(&standard_output)?;
std::fs::write(&output_path, json)?;
println!("[CUT] Output: {}", output_path);
@@ -122,7 +248,7 @@ fn get_video_info(video_path: &str) -> Result<VideoInfo> {
})
}
fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) -> Result<Vec<Scene>> {
fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) -> Result<Vec<InternalScene>> {
let output = Command::new("ffmpeg")
.args([
"-i", video_path,
@@ -147,7 +273,7 @@ fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) ->
let start_frame = (last_time * video_info.fps) as u64;
let end_frame = (time * video_info.fps) as u64;
scenes.push(Scene {
scenes.push(InternalScene {
scene_id,
start_frame,
start_time: last_time,
@@ -165,7 +291,7 @@ fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) ->
}
if scenes.is_empty() {
scenes.push(Scene {
scenes.push(InternalScene {
scene_id: 0,
start_frame: 0,
start_time: 0.0,
+195 -1
View File
@@ -528,6 +528,138 @@ fn stage2_merge_clusters(
trace_to_person
}
/// Apply co-occurrence constraints: split traces that appear in same frame but are assigned to same person
fn apply_cooccurrence_constraints(
trace_to_person: std::collections::BTreeMap<i64, i64>,
trace_embeddings: &std::collections::BTreeMap<i64, Vec<f64>>,
constraints: &std::collections::HashSet<(i64, i64)>,
) -> std::collections::BTreeMap<i64, i64> {
let mut trace_to_person: std::collections::HashMap<i64, i64> = trace_to_person.into_iter().collect();
let mut next_person_id = trace_to_person.values().max().copied().unwrap_or(0) + 1;
let mut split_count = 0;
for (tid_a, tid_b) in constraints.iter() {
let person_a = trace_to_person.get(tid_a).copied();
let person_b = trace_to_person.get(tid_b).copied();
if let (Some(pa), Some(pb)) = (person_a, person_b) {
if pa == pb {
// Same person but shouldn't be - split trace_b to new person
trace_to_person.insert(*tid_b, next_person_id);
next_person_id += 1;
split_count += 1;
eprintln!(" [SPLIT] Trace {} from Person_{} (co-occurs with trace {})", tid_b, pa, tid_a);
}
}
}
if split_count > 0 {
eprintln!("[CONSTRAINT] Split {} traces due to co-occurrence", split_count);
}
// Re-index person IDs to be contiguous
let unique_pids: std::collections::BTreeSet<i64> = trace_to_person.values().copied().collect();
let pid_map: std::collections::HashMap<i64, i64> = unique_pids.into_iter().enumerate().map(|(new, old)| (old, new as i64)).collect();
let trace_to_person: std::collections::BTreeMap<i64, i64> = trace_to_person.into_iter().map(|(tid, pid)| (tid, *pid_map.get(&pid).unwrap())).collect();
trace_to_person
}
/// Merge small clusters into the most similar large cluster
fn merge_small_clusters(
trace_to_person: std::collections::BTreeMap<i64, i64>,
trace_embeddings: &std::collections::BTreeMap<i64, Vec<f64>>,
trace_similarities: &std::collections::BTreeMap<i64, f64>,
min_large_cluster_size: usize,
merge_similarity_threshold: f64,
) -> std::collections::BTreeMap<i64, i64> {
let mut trace_to_person = trace_to_person;
// Count traces per person
let mut person_trace_count: std::collections::HashMap<i64, usize> = std::collections::HashMap::new();
for (_, pid) in &trace_to_person {
*person_trace_count.entry(*pid).or_insert(0) += 1;
}
// Identify large clusters (seeds) and small clusters
let mut large_clusters: std::collections::HashSet<i64> = std::collections::HashSet::new();
let mut small_clusters: std::collections::HashSet<i64> = std::collections::HashSet::new();
for (pid, count) in &person_trace_count {
if *count >= min_large_cluster_size {
large_clusters.insert(*pid);
} else {
small_clusters.insert(*pid);
}
}
if small_clusters.is_empty() || large_clusters.is_empty() {
return trace_to_person;
}
eprintln!("[MERGE] Large clusters: {:?}, Small clusters: {:?}", large_clusters, small_clusters);
// Compute mean embedding for each person
let mut person_embeddings: std::collections::HashMap<i64, Vec<f64>> = std::collections::HashMap::new();
for (tid, pid) in &trace_to_person {
if let Some(emb) = trace_embeddings.get(tid) {
person_embeddings.entry(*pid).or_insert_with(|| vec![0.0; emb.len()]);
let pe = person_embeddings.get_mut(pid).unwrap();
for (i, &v) in emb.iter().enumerate() {
pe[i] += v;
}
}
}
// Normalize
for (pid, traces) in &person_trace_count {
if let Some(pe) = person_embeddings.get_mut(pid) {
let count = *traces as f64;
for v in pe.iter_mut() {
*v /= count;
}
}
}
// Merge each small cluster into most similar large cluster
for small_pid in small_clusters {
let mut best_sim = -1.0;
let mut best_large_pid: Option<i64> = None;
for large_pid in &large_clusters {
if let (Some(emb_small), Some(emb_large)) = (person_embeddings.get(&small_pid), person_embeddings.get(large_pid)) {
let sim = cosine_similarity(emb_small, emb_large);
if sim > best_sim {
best_sim = sim;
best_large_pid = Some(*large_pid);
}
}
}
if let Some(target_pid) = best_large_pid {
if best_sim >= merge_similarity_threshold {
eprintln!(" [MERGE] Person_{} ({} traces) -> Person_{} (sim={:.3})",
small_pid, person_trace_count.get(&small_pid).unwrap_or(&0), target_pid, best_sim);
// Reassign all traces from small to large
for (tid, pid) in trace_to_person.iter_mut() {
if *pid == small_pid {
*pid = target_pid;
}
}
} else {
eprintln!(" [SKIP] Person_{} not similar enough to any large cluster (best sim={:.3})", small_pid, best_sim);
}
}
}
// Re-index person IDs
let unique_pids: std::collections::BTreeSet<i64> = trace_to_person.values().copied().collect();
let pid_map: std::collections::HashMap<i64, i64> = unique_pids.into_iter().enumerate().map(|(new, old)| (old, new as i64)).collect();
trace_to_person = trace_to_person.into_iter().map(|(tid, pid)| (tid, *pid_map.get(&pid).unwrap())).collect();
trace_to_person
}
fn main() {
let args = Args::parse();
@@ -619,9 +751,11 @@ fn main() {
let n_persons: usize = trace_to_person.values().collect::<std::collections::HashSet<_>>().len();
eprintln!("Clustering result: {} persons ({} traces)", n_persons, trace_to_person.len());
// Load face_traced.json to get trace_id for each face.
// Load face_traced.json to get trace_id for each face AND build co-occurrence constraints
let traced_path = output_dir.join(format!("{}.face_traced.json", uuid));
let mut traced_frames: Value = Value::Object(Default::default());
let mut cooccurrence_constraints: std::collections::HashSet<(i64, i64)> = std::collections::HashSet::new();
if traced_path.exists() {
if let Ok(s) = std::fs::read_to_string(&traced_path) {
if let Ok(v) = serde_json::from_str::<Value>(&s) {
@@ -634,12 +768,49 @@ fn main() {
if let Some(obj) = traced_frames.as_object_mut() {
obj.insert(frame_num.to_string(), frame_obj.clone());
}
// Build co-occurrence constraints: traces in same frame must be different persons
if let Some(faces) = frame_obj.get("faces").and_then(|f| f.as_array()) {
let mut frame_trace_ids: Vec<i64> = Vec::new();
for face in faces {
if let Some(tid) = face.get("trace_id").and_then(|t| t.as_i64()) {
frame_trace_ids.push(tid);
}
}
// Add all pairs
for i in 0..frame_trace_ids.len() {
for j in (i+1)..frame_trace_ids.len() {
let a = frame_trace_ids[i];
let b = frame_trace_ids[j];
cooccurrence_constraints.insert((a.min(b), a.max(b)));
}
}
}
}
}
eprintln!(" Loaded face_traced.json: {} frames (converted from array)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0));
} else if frames_raw.is_object() {
traced_frames = frames_raw;
eprintln!(" Loaded face_traced.json: {} frames (dict)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0));
// Build co-occurrence constraints from object format
for (_frame_key, frame_obj) in traced_frames.as_object().unwrap() {
if let Some(faces) = frame_obj.get("faces").and_then(|f| f.as_array()) {
let mut frame_trace_ids: Vec<i64> = Vec::new();
for face in faces {
if let Some(tid) = face.get("trace_id").and_then(|t| t.as_i64()) {
frame_trace_ids.push(tid);
}
}
for i in 0..frame_trace_ids.len() {
for j in (i+1)..frame_trace_ids.len() {
let a = frame_trace_ids[i];
let b = frame_trace_ids[j];
cooccurrence_constraints.insert((a.min(b), a.max(b)));
}
}
}
}
} else {
eprintln!(" Warning: Unexpected frames format: {:?}", frames_raw);
}
@@ -647,6 +818,29 @@ fn main() {
}
}
eprintln!("[CONSTRAINT] Built {} co-occurrence constraints", cooccurrence_constraints.len());
// Apply co-occurrence constraints: split traces that are in same frame but same person
let mut trace_to_person = apply_cooccurrence_constraints(
trace_to_person,
&trace_embeddings,
&cooccurrence_constraints
);
eprintln!("[CONSTRAINT] After constraints: {} persons", n_persons);
// Post-process: merge small clusters into most similar large cluster
let trace_to_person = merge_small_clusters(
trace_to_person,
&trace_embeddings,
&trace_similarities,
5, // min traces to be considered a "large" cluster
0.7 // similarity threshold for merging
);
let n_persons: usize = trace_to_person.values().collect::<std::collections::HashSet<_>>().len();
eprintln!("[MERGE] After merging small clusters: {} persons", n_persons);
let mut matched_count = 0_i64;
let mut frames_list = frames_list;
for (frame_idx, frame_obj) in frames_list.iter_mut().enumerate() {
+207 -15
View File
@@ -236,8 +236,8 @@ fn bboxes_match(b1: &BBox, b2: &BBox, tolerance: i32) -> bool {
(b1.height - b2.height).abs() <= tolerance
}
/// Extract key_face.jpg for each trace using ffmpeg crop.
/// Uses the highest-confidence frame's bbox from the trace.
/// Extract complete trace artifacts: key_face.jpg, key_frame.jpg, trace_profile.json
/// Uses face_data directly (faces with trace_id set by tracking) to avoid trace_id mismatch after merge.
fn extract_face_jpegs(
file_uuid: &str,
output_dir: &std::path::Path,
@@ -247,44 +247,138 @@ fn extract_face_jpegs(
) -> Result<()> {
let base_dir = output_dir.join(file_uuid);
for trace in traces {
let trace_dir = base_dir.join(format!("trace_{}", trace.trace_id));
std::fs::create_dir_all(&trace_dir).ok();
// Find the best face (highest confidence) for this trace
let mut best_face: Option<(usize, &FaceDetection)> = None;
// Build a map: trace_id → best face (highest confidence)
use std::collections::HashMap;
let mut best_faces: HashMap<i32, (usize, &FaceDetection)> = HashMap::new();
for frame in &face_data.frames {
for face in &frame.faces {
if let Some(tid) = face.trace_id {
if tid == trace.trace_id as i32 {
let frame_num = frame.frame as usize;
if let Some((_, bf)) = &best_face {
if face.confidence > bf.confidence {
best_face = Some((frame_num, face));
let entry = best_faces.entry(tid);
match entry {
std::collections::hash_map::Entry::Occupied(mut occ) => {
if face.confidence > occ.get().1.confidence {
*occ.get_mut() = (frame_num, face);
}
} else {
best_face = Some((frame_num, face));
}
std::collections::hash_map::Entry::Vacant(vac) => {
vac.insert((frame_num, face));
}
}
}
}
}
// For each trace, extract artifacts using the best face
for trace in traces {
let trace_dir = base_dir.join(format!("trace_{}", trace.trace_id));
std::fs::create_dir_all(&trace_dir).ok();
// Find the best face for this trace from the map
if let Some((frame_num, face)) = best_faces.get(&trace.trace_id) {
let frame_num = *frame_num;
// Extract key_face.jpg from the best frame
if let Some((frame_num, face)) = best_face {
if face.bbox.width > 0 && face.bbox.height > 0 {
let out_path = trace_dir.join("key_face.jpg");
if !out_path.exists() {
if let Err(e) = extract_face_crop(video_path, frame_num, face, &out_path) {
println!("[TRACE_STORE] WARN key_face.jpg for trace {}: {}", trace.trace_id, e);
}
}
}
// Extract key_frame.jpg (full frame at best_face frame)
let key_frame_path = trace_dir.join("key_frame.jpg");
if !key_frame_path.exists() {
if let Err(e) = extract_full_frame(video_path, frame_num, &key_frame_path) {
println!("[TRACE_STORE] WARN key_frame.jpg for trace {}: {}", trace.trace_id, e);
}
}
} else {
// Fallback: use trace's best_frame if available
if trace.best_frame > 0 {
let key_frame_path = trace_dir.join("key_frame.jpg");
if !key_frame_path.exists() {
if let Err(e) = extract_full_frame(video_path, trace.best_frame as usize, &key_frame_path) {
println!("[TRACE_STORE] WARN key_frame.jpg for trace {}: {}", trace.trace_id, e);
}
}
}
}
// Write trace_profile.json
let profile_path = trace_dir.join("trace_profile.json");
if !profile_path.exists() {
write_trace_profile(trace, file_uuid, &profile_path);
}
}
Ok(())
}
/// Use ffmpeg to extract a full frame (no crop).
fn extract_full_frame(video_path: &str, frame_num: usize, output: &std::path::Path) -> Result<()> {
let status = std::process::Command::new("ffmpeg")
.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin")
.args([
"-y", "-v", "quiet",
"-i", video_path,
"-vf", &format!("select=eq(n\\,{})", frame_num),
"-frames:v", "1",
"-q:v", "3",
"-f", "image2",
output.to_str().unwrap(),
])
.status()
.context("Failed to run ffmpeg for key_frame")?;
if !status.success() {
anyhow::bail!("ffmpeg exit code: {:?}", status.code());
}
if !output.exists() {
anyhow::bail!("ffmpeg did not produce key_frame output");
}
Ok(())
}
/// Write trace_profile.json with trace metadata.
fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::Path) {
use std::io::Write;
let best_confidence = trace.best_confidence;
let avg_confidence = trace.avg_confidence;
let best_frame = trace.best_frame;
let profile = serde_json::json!({
"version": "1.0",
"file_uuid": file_uuid,
"trace_id": trace.trace_id,
"label": null,
"frame_count": trace.frame_count,
"start_frame": trace.start_frame,
"end_frame": trace.end_frame,
"best_frame": best_frame,
"avg_confidence": avg_confidence,
"best_confidence": best_confidence,
"avg_capture_quality": null,
"best_capture_quality": null,
"avg_bbox": null,
"best_bbox": null,
"key_frame": "key_frame.jpg",
"key_face": "key_face.jpg",
"status": "pending",
"vlm_summary": null,
});
if let Ok(mut f) = std::fs::File::create(output) {
let _ = writeln!(f, "{}", serde_json::to_string_pretty(&profile).unwrap_or_default());
}
}
/// Use ffmpeg to extract a single cropped face frame.
fn extract_face_crop(video_path: &str, frame_num: usize, face: &FaceDetection, output: &std::path::Path) -> Result<()> {
let x = face.bbox.x;
@@ -383,6 +477,19 @@ fn main() -> Result<()> {
println!("[TRACE_STORE] Traces: {}", traces.len());
// Post-process: merge short traces with similar longer traces
let min_merge_len = 5; // Merge traces with < 5 frames
let merge_similarity = 0.75; // Cosine similarity threshold for merging
println!("[TRACE_STORE] Merging short traces (<{} frames, sim>{})...", min_merge_len, merge_similarity);
println!("[DEBUG] Before merge: {} traces", traces.len());
for (tid, t) in &traces {
if t.frame_count < 10 {
println!("[DEBUG] Trace '{}': frame_count={}", tid, t.frame_count);
}
}
let traces = merge_short_traces(traces, min_merge_len, merge_similarity);
println!("[TRACE_STORE] After merge: {} traces", traces.len());
// Update trace_ids in Qdrant
println!("[TRACE_STORE] Updating trace_ids in Qdrant...");
let trace_mapping: HashMap<(i64, i32, i32, i32, i32), i32> = build_trace_mapping(&face_data);
@@ -815,6 +922,91 @@ fn calculate_cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
}
}
/// Merge short traces with temporally close longer traces
fn merge_short_traces(
traces: HashMap<String, TraceInfo>,
min_len: usize,
_similarity_threshold: f64,
) -> HashMap<String, TraceInfo> {
let mut traces = traces;
// Find short traces (use face_instances since frame_count is 0 at this point)
let short_traces: Vec<String> = traces.iter()
.filter(|(_, t)| t.face_instances.len() < min_len)
.map(|(tid, _)| tid.clone())
.collect();
if short_traces.is_empty() {
return traces;
}
// Merge each short trace to the temporally closest long trace
for short_tid in short_traces {
let short_trace = match traces.get(&short_tid) {
Some(t) => t.clone(),
None => continue,
};
// Find the closest long trace by time overlap or proximity
let mut best_score = -1.0;
let mut best_tid: Option<String> = None;
for (tid, trace) in &traces {
if *tid == short_tid { continue; }
if trace.frame_count < min_len as u64 { continue; }
// Calculate temporal overlap/proximity score
let overlap_start = short_trace.start_frame.max(trace.start_frame);
let overlap_end = short_trace.end_frame.min(trace.end_frame);
let overlap = if overlap_end > overlap_start {
(overlap_end - overlap_start) as f64
} else {
// Calculate gap
let gap = if short_trace.end_frame < trace.start_frame {
trace.start_frame - short_trace.end_frame
} else if trace.end_frame < short_trace.start_frame {
short_trace.start_frame - trace.end_frame
} else {
0
} as f64;
-gap.max(1.0) // Negative score for gap
};
// Normalize by short trace length
let score = overlap / short_trace.frame_count.max(1) as f64;
if score > best_score {
best_score = score;
best_tid = Some(tid.clone());
}
}
// Merge if there's overlap or small gap (< 10 frames)
if let Some(target_tid) = best_tid {
if best_score > -10.0 {
println!(" Merging trace {} ({} faces) into trace {} (score={:.1})",
short_tid, short_trace.frame_count as usize, target_tid, best_score);
// Move face instances from short to target
if let Some(mut short_trace) = traces.remove(&short_tid) {
if let Some(target_trace) = traces.get_mut(&target_tid) {
for point in short_trace.face_instances.drain(..) {
target_trace.face_instances.push(point);
}
// Update stats
target_trace.frame_count += short_trace.frame_count;
target_trace.start_frame = target_trace.start_frame.min(short_trace.start_frame);
target_trace.end_frame = target_trace.end_frame.max(short_trace.end_frame);
target_trace.start_time = target_trace.start_time.min(short_trace.start_time);
target_trace.end_time = target_trace.end_time.max(short_trace.end_time);
}
}
}
}
}
traces
}
fn load_qdrant_faces(uuid: &str) -> Vec<FacePoint> {
let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL);
let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY);