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
@@ -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
```