feat: face clustering pipeline improvements and Rust/Swift face processing

- Add Rust face processor module (detection, embedding, tracking, qdrant)
- Add Facenet CoreML/ONNX conversion scripts and tests
- Refactor swift_face into Sources/swift_face with ArgumentParser support
- Update store_traced_faces to handle face.json correctly
- Fix ASRX parsing and TKG bbox reading from Qdrant
- Improve admin_config and trace_agent APIs
- Add M4 workspace docs for face clustering, dedup, and Facenet validation
- Fix worker heartbeat TTL (poll_interval x 3, min 60s) for offline detection
This commit is contained in:
Accusys
2026-10-02 12:24:55 +08:00
parent e987fb8119
commit e0d04e242f
87 changed files with 11668 additions and 302 deletions
@@ -0,0 +1,585 @@
---
title: Face Dedup Flow Analysis
version: 1.0
date: 2026-10-01
author: OpenCode
status: active
---
## 概述
Face Dedup(人物去重)是 Momentry 的核心功能,負責將影片中偵測到的多個臉部軌跡(face traces)聚類成不同的人物(persons)。
**關鍵概念**:
- **Face Detection**: 單一幀中的臉部偵測結果
- **Face Trace**: 跨多幀追蹤的同一臉部軌跡(由 Face Tracker 生成)
- **Person Identity**: 全局唯一的人物身份(跨檔案)
---
## 數據流程圖
```
┌─────────────────┐
│ Video File │
└────────┬────────┘
│
├─> [Face Detection] ─> face.json
│ │
│ ├─> frame, bbox, confidence
│ └─> face_id
│
├─> [Face Tracking] ─> face_traced.json
│ │
│ ├─> trace_id (追蹤 ID)
│ └─> 關聯 face_id
│
└─> [Face Embedding] ─> Qdrant _faces
│
├─> vector (512-dim embedding)
├─> file_uuid, frame, trace_id
└─> confidence
┌──────────────────────────────┐
│ Face Dedup (Clustering) │
└──────────────────────────────┘
│
┌───────────────────────┼───────────────────────┐
│ │ │
▼ ▼ ▼
[Load Faces] [Group by Trace] [Cluster Traces]
│ │ │
└───────────────────────┼───────────────────────┘
│
▼
face_cluster.json
│
├─> clusters: [{person_id, face_count}]
└─> frames: [{frame, faces: [{person_id}]}]
```
---
## 詳細步驟分析
### Step 1: 加載臉部數據
**來源**: Qdrant `_faces` collection
**代碼位置**:
- Python: `scripts/face_clustering_processor.py:95`
- Rust: `tools/cli/rust/src/bin/rust_face_cluster.rs:85`
**數據結構**:
```json
{
"id": "face_123_0",
"vector": [0.123, 0.456, ...], // 512-dim embedding
"payload": {
"file_uuid": "7a1523df...",
"frame": 123,
"trace_id": 5,
"confidence": 0.89,
"bbox": {"x": 100, "y": 200, "width": 150, "height": 150}
}
}
```
**關鍵操作**:
```python
# Python
points = load_qdrant_faces(uuid) # 從 Qdrant scroll 所有 points
print(f"Loaded {len(points)} points from Qdrant _faces")
# Rust
let points = load_qdrant_faces(uuid);
eprintln!("Loaded {} points from Qdrant _faces", points.len());
```
---
### Step 2: 按 Trace 分組
**目的**: 將同一 trace 的多個 face embeddings 合併為單一表示
**代碼位置**:
- Python: `scripts/face_clustering_processor.py:117`
- Rust: `tools/cli/rust/src/bin/rust_face_cluster.rs:184`
**核心邏輯**:
```python
# 1. 按 trace_id 分組
traces = defaultdict(list)
for p in points:
trace_id = p.get("payload", {}).get("trace_id", -1)
traces[trace_id].append(p)
# 2. 計算加權平均 embedding
for trace_id, trace_points in traces.items():
embeddings = [p["vector"] for p in trace_points]
weights = [p.get("payload", {}).get("confidence", 1.0) for p in trace_points]
# 歸一化權重
weights = weights / sum(weights)
# 加權平均
avg_embedding = np.average(embeddings, axis=0, weights=weights)
# L2 正規化
avg_embedding = avg_embedding / np.linalg.norm(avg_embedding)
trace_embeddings[trace_id] = {
"embedding": avg_embedding,
"face_count": len(trace_points),
"avg_confidence": mean(weights)
}
```
**為何需要加權平均**:
- 高 confidence 的 face 更可靠
- 減少雜訊影響
- 提升 trace 表示的準確性
**輸出範例**:
```
[TRACE] 16 unique traces
[TRACE] 16 traces with >= 1 faces
```
---
### Step 3: 聚類(Clustering)
**目的**: 將相似的 traces 聚類成同一 person
**兩種方法**:
#### 方法 1: Seed-Leader (默認,推薦)
**特點**:
- 增量式,確定性
- 按 trace_id 順序處理
- 實時計算 cluster centroid
**算法**:
```
1. 初始化: persons = []
2. 對每個 trace (按 trace_id 排序):
a. 計算與所有現有 person centroid 的 cosine similarity
b. 找到最高相似度 best_sim
c. 如果 best_sim >= (1 - threshold):
- 分配到該 person
- 更新該 person 的 centroid (重新計算 mean)
d. 否則:
- 創建新 person (seeded by this trace)
```
**代碼位置**:
- Python: `scripts/face_clustering_processor.py:219`
- Rust: `tools/cli/rust/src/bin/rust_face_cluster.rs:241`
**關鍵代碼**:
```python
sim_threshold = 1.0 - threshold # distance -> similarity
persons = [] # [(centroid, member_trace_ids)]
for trace_id in sorted(trace_ids):
centroid = trace_embeddings[trace_id]["embedding"]
# 找最相似的 person
best_sim = -1.0
best_person_idx = None
for idx, (person_centroid, _) in enumerate(persons):
sim = cosine_similarity(centroid, person_centroid)
if sim > best_sim:
best_sim = sim
best_person_idx = idx
# 決定: 加入現有 person 或創建新 person
if best_person_idx is not None and best_sim >= sim_threshold:
# 加入現有 person
persons[best_person_idx][1].append(trace_id)
# 更新 centroid
new_centroid = mean([trace_embeddings[tid]["embedding"]
for tid in persons[best_person_idx][1]])
persons[best_person_idx][0] = new_centroid
else:
# 創建新 person
persons.append((centroid, [trace_id]))
```
**Threshold 含義**:
- `threshold` = 距離閾值 (distance threshold)
- `sim_threshold` = 1.0 - threshold = 相似度閾值
- 例如: threshold = 0.15 → sim_threshold = 0.85
**推薦值**:
- 一般用途: `threshold = 0.15` (similarity >= 0.85)
- 嚴格去重: `threshold = 0.10` (similarity >= 0.90)
- 寬鬆去重: `threshold = 0.20` (similarity >= 0.80)
---
#### 方法 2: Agglomerative Clustering
**特點**:
- sklearn 實現
- 層次聚類
- 需要指定 distance_threshold
**代碼位置**:
- Python: `scripts/face_clustering_processor.py:174`
**關鍵代碼**:
```python
from sklearn.cluster import AgglomerativeClustering
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=threshold,
metric="cosine",
linkage="average"
)
labels = clustering.fit_predict(embeddings)
```
**缺點**:
- 非確定性(依賴 sklearn 實現)
- 需要所有數據才能聚類
- 記憶體占用較高
---
### Step 4: 分配 Person ID
**目的**: 將每個 face 分配到對應的 person
**代碼位置**:
- Python: `scripts/face_clustering_processor.py:485`
**核心邏輯**:
```python
# trace_to_person: {trace_id: person_label}
# 例如: {5: 0, 6: 0, 7: 1, 8: 2}
# 為每個 face 分配 person_id
for frame_data in frames:
for face in frame_data["faces"]:
trace_id = face["trace_id"]
person_label = trace_to_person[trace_id]
face["cluster_id"] = f"Person_{person_label}"
```
**輸出格式**:
```json
{
"clusters": [
{
"cluster_id": "Person_0",
"face_count": 186,
"representative_face": {...},
"similarity": {
"avg": 0.92,
"min": 0.85,
"threshold": 0.85
}
}
],
"frames": [
{
"frame": 0,
"timestamp": 0.0,
"faces": [
{
"face_id": "face_0_0",
"cluster_id": "Person_0",
"confidence": 0.89,
"trace_id": 5
}
]
}
]
}
```
---
### Step 5: 自動綁定 Speaker
**目的**: 根據時間對齊,推測 person 與 speaker 的對應關係
**代碼位置**:
- Python: `scripts/face_clustering_processor.py:308`
**前提條件**:
- 需要有 ASRX 結果(speaker segments)
- 需要有 faceCluster 結果(person faces)
**核心邏輯**:
```python
def auto_bind_speakers(output_frames, asrx_path):
# 1. 載入 ASRX segments
asrx_data = load_json(asrx_path)
segments = asrx_data.get("segments", [])
# 2. 統計每個 (speaker, person) 的共同出現次數
votes = defaultdict(lambda: defaultdict(int))
for frame_data in output_frames:
frame = frame_data["frame"]
timestamp = frame_data["timestamp"]
# 找出該時間點的 speakers
active_speakers = [
seg["speaker_id"]
for seg in segments
if seg["start"] <= timestamp < seg["end"]
]
# 找出該幀的 persons
active_persons = [
face["cluster_id"]
for face in frame_data["faces"]
]
# 投票
for speaker in active_speakers:
for person in active_persons:
votes[speaker][person] += 1
# 3. 選擇票數最高的配對
speaker_mapping = {}
for speaker, person_votes in votes.items():
best_person = max(person_votes.items(), key=lambda x: x[1])
speaker_mapping[speaker] = best_person[0]
print(f" {speaker} is likely {best_person[0]} ({best_person[1]} votes)")
return speaker_mapping
```
**輸出範例**:
```
Auto-binding Speakers to Persons...
SPEAKER_2 is likely Person_2 (8 votes)
SPEAKER_3 is likely Person_2 (1 votes)
SPEAKER_7 is likely Person_2 (1 votes)
SPEAKER_8 is likely Person_2 (1 votes)
```
---
## 輸出結果
### 文件位置
```
/Users/accusys/momentry/output/{uuid}.face_cluster.json
```
### 數據結構
```json
{
"status": "success",
"file_uuid": "7a1523df...",
"clusters": [
{
"cluster_id": "Person_0",
"face_count": 186,
"representative_face": {
"face_id": "face_123_0",
"confidence": 0.89,
"frame": 123,
"bbox": {"x": 100, "y": 200, "width": 150, "height": 150}
},
"similarity": {
"avg": 0.92,
"min": 0.85,
"threshold": 0.85
}
},
{
"cluster_id": "Person_1",
"face_count": 174,
...
}
],
"frames": [
{
"frame": 0,
"timestamp": 0.0,
"faces": [
{
"face_id": "face_0_0",
"cluster_id": "Person_0",
"confidence": 0.89,
"trace_id": 5
}
]
},
...
]
}
```
---
## 關鍵參數
### Threshold 選擇
| Threshold | Similarity | 用途 | 說明 |
|-----------|------------|------|------|
| 0.10 | 0.90 | 嚴格去重 | 需要極高相似度,適合同一人多角度 |
| 0.15 | 0.85 | 一般用途 | 平衡準確度和召回率(**推薦**) |
| 0.20 | 0.80 | 寬鬆去重 | 允許較大差異,適合低質量影片 |
| 0.35 | 0.65 | ❌ 不推薦 | 太寬鬆,會將不同人聚成同一人 |
### Min Faces Per Trace
**默認值**: 1
**建議**:
- 一般影片: 1-3
- 長影片: 5-10
**作用**: 過濾掉 trace 中 face 數量太少的 trace,避免雜訊
---
## 性能優化
### Rust vs Python
| 指標 | Python | Rust | 提升 |
|------|--------|------|------|
| 執行時間 | ~5s | ~0.5s | 10x |
| 記憶體 | ~200MB | ~50MB | 4x |
| 確定性 | 依賴 sklearn | ✅ 確定性 | - |
**Rust 優勢**:
- 編譯優化
- 無 GC 開銷
- 更好的並行化
---
## 常見問題
### 1. 為何會將不同人聚成同一人?
**原因**:
- Threshold 太高(distance 太大)
- Embedding 質量差
- 臉部角度變化大
**解決**:
- 降低 threshold(例如 0.15 → 0.10)
- 提升 face detection 質量
- 使用更好的 embedding 模型
---
### 2. 為何同一人被拆成多個 persons?
**原因**:
- Threshold 太低(distance 太小)
- Trace 中斷(遮擋、轉身)
- 光線變化大
**解決**:
- 提高 threshold(例如 0.15 → 0.20)
- 改善 face tracking 連續性
- 增強 trace merging 邏輯
---
### 3. Speaker binding 準確度如何?
**依賴因素**:
- ASRX segment 準確度
- Face 出現時間與說話時間的重疊度
- 多人同時說話的情況
**改進**:
- 結合唇部運動檢測
- 使用音視頻同步信號
- 加入主動學習機制
---
## 檔案參考
### 核心實現
| 文件 | 語言 | 用途 |
|------|------|------|
| `/Users/accusys/momentry_core/tools/cli/rust/src/bin/rust_face_cluster.rs` | Rust | Rust 實現(推薦) |
| `/Users/accusys/momentry_core/scripts/face_clustering_processor.py` | Python | Python 實現 |
| `/Users/accusys/momentry_core/src/core/processor/face_clustering.rs` | Rust | Worker 調用邏輯 |
### 配置文檔
| 文件 | 用途 |
|------|------|
| `/Users/accusys/momentry_core/docs_v1.0/M4_workspace/2026-10-01_face_dedup_postmortem.md` | 問題檢討報告 |
| `/Users/accusys/momentry_core/docs_v1.0/DESIGN/Face_Clustering_Config_Unification.md` | 配置統一方案 |
### 測試腳本
| 文件 | 用途 |
|------|------|
| `/Users/accusys/momentry_core/scripts/test_face_cluster.sh` | 快速測試腳本 |
| `/Users/accusys/momentry_core/scripts/check_toolchain.sh` | 編譯檢查腳本 |
---
## 開發指南
### 快速測試
```bash
# 測試單一影片
./scripts/test_face_cluster.sh /path/to/video.mp4
# 檢查 binary 是否最新
./scripts/check_toolchain.sh
```
### 修改 Threshold
**方法 1: 環境變數**
```bash
export MOMENTRY_FACE_CLUSTER_THRESHOLD=0.10
```
**方法 2: 命令行參數**
```bash
rust_face_cluster video.mp4 output.json --threshold 0.10
```
**方法 3: 修改源碼**
```rust
// src/core/config.rs
pub const FACE_CLUSTER_DISTANCE_THRESHOLD: f64 = 0.10;
```
---
## 版本歷史
| 版本 | 日期 | 變更 |
|------|------|------|
| 1.0 | 2026-10-01 | 初始版本,完整流程分析 |
---
## 相關主題
- [Face Detection](./Face_Detection_Guide.md)
- [Face Tracking](./Face_Tracking_Guide.md)
- [Face Embedding](./Face_Embedding_Guide.md)
- [Identity Management](./Identity_Management_Guide.md)