feat: implement face filter API for GUI filtering mechanism
- Database schema: face_filter_features and filter_rules tables
- Core engine: FilterEngine with 4 filter rules (landmark, mediapipe, embedding, temporal)
- API endpoints:
- GET /faces - Get faces with filtering
- GET /face/{id}/filter-report - Get filter report for single face
- POST /faces/filter - Apply filter rules
- GET /filter-stats - Get filter statistics
- GET/POST /filter-rules - Manage filter rules
- API documentation for Studio team with examples
- Based on FaceNet analysis results from WD and KOBA videos
This commit is contained in:
@@ -0,0 +1,708 @@
|
|||||||
|
# Face Filter API 使用指南 — Studio 團隊參考
|
||||||
|
|
||||||
|
**版本**: v1.0
|
||||||
|
**日期**: 2026-08-09
|
||||||
|
**狀態**: 已實作
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
Face Filter API 提供臉部過濾功能,讓 Studio 前端可以:
|
||||||
|
1. 查詢臉部列表(支持來源過濾)
|
||||||
|
2. 獲取單一臉部過濾報告
|
||||||
|
3. 套用過濾規則
|
||||||
|
4. 獲取過濾統計
|
||||||
|
5. 管理過濾規則
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API 端點
|
||||||
|
|
||||||
|
### 1. 獲取臉部列表
|
||||||
|
|
||||||
|
**端點**: `GET /api/v1/file/{file_uuid}/faces`
|
||||||
|
|
||||||
|
**功能**: 獲取檔案的臉部列表,支持分頁和來源過濾
|
||||||
|
|
||||||
|
**查詢參數**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"source": "all", // "all" | "apple_vision" | "mediapipe"
|
||||||
|
"page": 1, // 頁碼(從 1 開始)
|
||||||
|
"page_size": 50 // 每頁數量
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**回應範例**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"faces": [
|
||||||
|
{
|
||||||
|
"face_id": "face_001",
|
||||||
|
"frame": 671,
|
||||||
|
"primary_source": "apple_vision",
|
||||||
|
"primary_confidence": 0.84,
|
||||||
|
"detection_sources": [
|
||||||
|
{"source_type": "apple_vision", "confidence": 0.84},
|
||||||
|
{"source_type": "mediapipe", "confidence": 0.92}
|
||||||
|
],
|
||||||
|
"filter_features": {
|
||||||
|
"face_id": "face_001",
|
||||||
|
"file_uuid": "0489e104d7d1e11e613da01f7aa130ca",
|
||||||
|
"frame": 671,
|
||||||
|
"eye_ratio": 0.33,
|
||||||
|
"nose_ratio": 0.02,
|
||||||
|
"pose_score": 0.08,
|
||||||
|
"mediapipe_detected": true,
|
||||||
|
"mediapipe_iou": 0.85,
|
||||||
|
"embedding_similarity": 0.82,
|
||||||
|
"consecutive_frames": 15,
|
||||||
|
"total_frames_detected": 15,
|
||||||
|
"apple_vision_confidence": 0.84,
|
||||||
|
"mediapipe_confidence": 0.92,
|
||||||
|
"primary_source": "apple_vision"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pagination": {
|
||||||
|
"page": 1,
|
||||||
|
"page_size": 50,
|
||||||
|
"total": 392,
|
||||||
|
"total_pages": 8
|
||||||
|
},
|
||||||
|
"source_summary": {
|
||||||
|
"apple_vision": 392,
|
||||||
|
"mediapipe": 5,
|
||||||
|
"merged_unique": 392
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Studio 使用範例**:
|
||||||
|
```typescript
|
||||||
|
// 獲取第一頁臉部
|
||||||
|
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
source: 'all',
|
||||||
|
page: 1,
|
||||||
|
page_size: 50
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
console.log(`Total faces: ${data.data.pagination.total}`);
|
||||||
|
console.log(`First face: ${data.data.faces[0].face_id}`);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. 獲取單一臉部過濾報告
|
||||||
|
|
||||||
|
**端點**: `GET /api/v1/file/{file_uuid}/face/{face_id}/filter-report`
|
||||||
|
|
||||||
|
**功能**: 獲取單一臉部的詳細過濾報告
|
||||||
|
|
||||||
|
**回應範例**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"face_id": "face_001",
|
||||||
|
"frame": 671,
|
||||||
|
"overall_confidence": 0.45,
|
||||||
|
"recommendation": "reject",
|
||||||
|
"rule_results": {
|
||||||
|
"landmark_analysis": {
|
||||||
|
"enabled": true,
|
||||||
|
"score": 0.75,
|
||||||
|
"passed": true,
|
||||||
|
"reason": "nose_ratio too low (0.020)"
|
||||||
|
},
|
||||||
|
"mediapipe_verification": {
|
||||||
|
"enabled": true,
|
||||||
|
"score": 1.0,
|
||||||
|
"passed": true,
|
||||||
|
"reason": null
|
||||||
|
},
|
||||||
|
"embedding_similarity": {
|
||||||
|
"enabled": true,
|
||||||
|
"score": 0.21,
|
||||||
|
"passed": false,
|
||||||
|
"reason": "Low embedding similarity (0.150)"
|
||||||
|
},
|
||||||
|
"temporal_consistency": {
|
||||||
|
"enabled": true,
|
||||||
|
"score": 0.33,
|
||||||
|
"passed": false,
|
||||||
|
"reason": "Single frame detection (1)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"reasons": [
|
||||||
|
"nose_ratio too low (0.020)",
|
||||||
|
"Low embedding similarity (0.150)",
|
||||||
|
"Single frame detection (1)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Studio 使用範例**:
|
||||||
|
```typescript
|
||||||
|
// 獲取臉部過濾報告
|
||||||
|
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/face/face_001/filter-report');
|
||||||
|
const report = await response.json();
|
||||||
|
|
||||||
|
console.log(`Recommendation: ${report.recommendation}`);
|
||||||
|
console.log(`Confidence: ${report.overall_confidence}`);
|
||||||
|
console.log(`Reasons: ${report.reasons.join(', ')}`);
|
||||||
|
|
||||||
|
// 顯示每個規則的結果
|
||||||
|
Object.entries(report.rule_results).forEach(([rule, result]) => {
|
||||||
|
console.log(`${rule}: ${result.passed ? '✅' : '❌'} (score: ${result.score})`);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. 套用過濾規則
|
||||||
|
|
||||||
|
**端點**: `POST /api/v1/file/{file_uuid}/faces/filter`
|
||||||
|
|
||||||
|
**功能**: 套用過濾規則到所有臉部,返回過濾結果
|
||||||
|
|
||||||
|
**請求範例**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"rules": {
|
||||||
|
"version": "1.0",
|
||||||
|
"rules": {
|
||||||
|
"landmark_analysis": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.3,
|
||||||
|
"thresholds": {
|
||||||
|
"eye_ratio_min": 0.25,
|
||||||
|
"eye_ratio_max": 0.55,
|
||||||
|
"nose_ratio_min": 0.08,
|
||||||
|
"pose_score_max": 0.8
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"mediapipe_verification": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.2,
|
||||||
|
"thresholds": {
|
||||||
|
"min_iou": 0.3
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"embedding_similarity": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.3,
|
||||||
|
"thresholds": {
|
||||||
|
"min_similarity": 0.70
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"temporal_consistency": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.2,
|
||||||
|
"thresholds": {
|
||||||
|
"min_consecutive_frames": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overall_thresholds": {
|
||||||
|
"auto_accept": 0.7,
|
||||||
|
"auto_reject": 0.3,
|
||||||
|
"review_range": [0.3, 0.7]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**回應範例**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"total_faces": 392,
|
||||||
|
"passed": 385,
|
||||||
|
"filtered": 7,
|
||||||
|
"filtered_faces": [
|
||||||
|
{
|
||||||
|
"face_id": "face_001",
|
||||||
|
"frame": 671,
|
||||||
|
"reasons": [
|
||||||
|
"nose_ratio too low (0.020)",
|
||||||
|
"Low embedding similarity (0.150)",
|
||||||
|
"Single frame detection (1)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"filter_stats": {
|
||||||
|
"landmark": 3,
|
||||||
|
"mediapipe": 1,
|
||||||
|
"embedding": 2,
|
||||||
|
"temporal": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Studio 使用範例**:
|
||||||
|
```typescript
|
||||||
|
// 套用過濾規則
|
||||||
|
const filterConfig = {
|
||||||
|
rules: {
|
||||||
|
landmark_analysis: {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.3,
|
||||||
|
thresholds: {
|
||||||
|
eye_ratio_min: 0.25,
|
||||||
|
eye_ratio_max: 0.55,
|
||||||
|
nose_ratio_min: 0.08,
|
||||||
|
pose_score_max: 0.8
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// ... 其他規則
|
||||||
|
},
|
||||||
|
overall_thresholds: {
|
||||||
|
auto_accept: 0.7,
|
||||||
|
auto_reject: 0.3,
|
||||||
|
review_range: [0.3, 0.7]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ rules: filterConfig })
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
console.log(`Passed: ${result.passed}, Filtered: ${result.filtered}`);
|
||||||
|
|
||||||
|
// 顯示被過濾的臉部
|
||||||
|
result.filtered_faces.forEach(face => {
|
||||||
|
console.log(`Face ${face.face_id} (frame ${face.frame}): ${face.reasons.join(', ')}`);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4. 獲取過濾統計
|
||||||
|
|
||||||
|
**端點**: `GET /api/v1/file/{file_uuid}/filter-stats`
|
||||||
|
|
||||||
|
**功能**: 獲取臉部的過濾統計資訊
|
||||||
|
|
||||||
|
**回應範例**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"total_faces": 392,
|
||||||
|
"by_category": {
|
||||||
|
"total_faces": 392,
|
||||||
|
"by_source": {
|
||||||
|
"apple_vision": 392,
|
||||||
|
"mediapipe": 5
|
||||||
|
},
|
||||||
|
"by_quality": {
|
||||||
|
"avg_eye_ratio": 0.37,
|
||||||
|
"avg_nose_ratio": 0.12,
|
||||||
|
"avg_pose_score": 0.15,
|
||||||
|
"mediapipe_verified": 5,
|
||||||
|
"avg_embedding_similarity": 0.78,
|
||||||
|
"avg_consecutive_frames": 12.5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Studio 使用範例**:
|
||||||
|
```typescript
|
||||||
|
// 獲取過濾統計
|
||||||
|
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-stats');
|
||||||
|
const stats = await response.json();
|
||||||
|
|
||||||
|
console.log(`Total faces: ${stats.total_faces}`);
|
||||||
|
console.log(`Apple Vision faces: ${stats.by_category.by_source.apple_vision}`);
|
||||||
|
console.log(`MediaPipe faces: ${stats.by_category.by_source.mediapipe}`);
|
||||||
|
console.log(`Avg embedding similarity: ${stats.by_category.by_quality.avg_embedding_similarity}`);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5. 管理過濾規則
|
||||||
|
|
||||||
|
#### 5.1 獲取過濾規則
|
||||||
|
|
||||||
|
**端點**: `GET /api/v1/file/{file_uuid}/filter-rules`
|
||||||
|
|
||||||
|
**回應範例**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"rule_name": "default_filter",
|
||||||
|
"rules": {
|
||||||
|
"version": "1.0",
|
||||||
|
"rules": {
|
||||||
|
"landmark_analysis": { ... },
|
||||||
|
"mediapipe_verification": { ... },
|
||||||
|
"embedding_similarity": { ... },
|
||||||
|
"temporal_consistency": { ... }
|
||||||
|
},
|
||||||
|
"overall_thresholds": { ... }
|
||||||
|
},
|
||||||
|
"is_active": true,
|
||||||
|
"created_at": "2026-08-09T12:00:00Z",
|
||||||
|
"updated_at": "2026-08-09T12:00:00Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 5.2 儲存過濾規則
|
||||||
|
|
||||||
|
**端點**: `POST /api/v1/file/{file_uuid}/filter-rules`
|
||||||
|
|
||||||
|
**請求範例**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"rule_name": "strict_filter",
|
||||||
|
"rules": {
|
||||||
|
"version": "1.0",
|
||||||
|
"rules": {
|
||||||
|
"landmark_analysis": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.3,
|
||||||
|
"thresholds": {
|
||||||
|
"eye_ratio_min": 0.30,
|
||||||
|
"eye_ratio_max": 0.50,
|
||||||
|
"nose_ratio_min": 0.10,
|
||||||
|
"pose_score_max": 0.5
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// ... 其他規則
|
||||||
|
},
|
||||||
|
"overall_thresholds": {
|
||||||
|
"auto_accept": 0.8,
|
||||||
|
"auto_reject": 0.2,
|
||||||
|
"review_range": [0.2, 0.8]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"is_active": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Studio 使用範例**:
|
||||||
|
```typescript
|
||||||
|
// 獲取現有規則
|
||||||
|
const getResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules');
|
||||||
|
const rulesData = await getResponse.json();
|
||||||
|
|
||||||
|
// 儲存新規則
|
||||||
|
const strictFilter = {
|
||||||
|
rule_name: "strict_filter",
|
||||||
|
rules: {
|
||||||
|
// ... 規則配置
|
||||||
|
},
|
||||||
|
is_active: true
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(strictFilter)
|
||||||
|
});
|
||||||
|
|
||||||
|
const savedRule = await saveResponse.json();
|
||||||
|
console.log(`Saved rule: ${savedRule.rule_name} (id: ${savedRule.id})`);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 過濾規則說明
|
||||||
|
|
||||||
|
### 規則類型
|
||||||
|
|
||||||
|
#### 1. Landmark 分析 (landmark_analysis)
|
||||||
|
|
||||||
|
**功能**: 檢查臉部 landmark 幾何特徵是否正常
|
||||||
|
|
||||||
|
**閾值**:
|
||||||
|
- `eye_ratio_min`: 眼睛間距比例最小值(預設 0.25)
|
||||||
|
- `eye_ratio_max`: 眼睛間距比例最大值(預設 0.55)
|
||||||
|
- `nose_ratio_min`: 眼睛到鼻子比例最小值(預設 0.08)
|
||||||
|
- `pose_score_max`: Pose 角度評分最大值(預設 0.8)
|
||||||
|
|
||||||
|
**權重**: 0.3
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### 2. MediaPipe 驗證 (mediapipe_verification)
|
||||||
|
|
||||||
|
**功能**: 驗證 MediaPipe 是否也檢測到該臉部
|
||||||
|
|
||||||
|
**值**:
|
||||||
|
- `min_iou`: 最小 IoU 值(預設 0.3)
|
||||||
|
|
||||||
|
**權重**: 0.2
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### 3. Embedding 相似度 (embedding_similarity)
|
||||||
|
|
||||||
|
**功能**: 檢查臉部 embedding 與已知人臉的相似度
|
||||||
|
|
||||||
|
**閾值**:
|
||||||
|
- `min_similarity`: 最小相似度(預設 0.70)
|
||||||
|
|
||||||
|
**權重**: 0.3
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### 4. 時間一致性 (temporal_consistency)
|
||||||
|
|
||||||
|
**功能**: 檢查臉部是否在連續幀中出現
|
||||||
|
|
||||||
|
**閾值**:
|
||||||
|
- `min_consecutive_frames`: 最小連續數(預設 3)
|
||||||
|
|
||||||
|
**權重**: 0.2
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 總體閾值
|
||||||
|
|
||||||
|
**overall_thresholds**:
|
||||||
|
- `auto_accept`: 自動接受閾值(預設 0.7)
|
||||||
|
- `auto_reject`: 自動拒絕閾值(預設 0.3)
|
||||||
|
- `review_range`: 審查範圍(預設 [0.3, 0.7])
|
||||||
|
|
||||||
|
**建議**:
|
||||||
|
- `overall_confidence >= 0.7`: 接受
|
||||||
|
- `overall_confidence <= 0.3`: 拒絕
|
||||||
|
- `0.3 < overall_confidence < 0.7`: 審查
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 預設配置
|
||||||
|
|
||||||
|
API 提供預設過濾規則,可直接使用:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": "1.0",
|
||||||
|
"rules": {
|
||||||
|
"landmark_analysis": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.3,
|
||||||
|
"thresholds": {
|
||||||
|
"eye_ratio_min": 0.25,
|
||||||
|
"eye_ratio_max": 0.55,
|
||||||
|
"nose_ratio_min": 0.08,
|
||||||
|
"pose_score_max": 0.8
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"mediapipe_verification": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.2,
|
||||||
|
"thresholds": {
|
||||||
|
"min_iou": 0.3
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"embedding_similarity": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.3,
|
||||||
|
"thresholds": {
|
||||||
|
"min_similarity": 0.70
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"temporal_consistency": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.2,
|
||||||
|
"thresholds": {
|
||||||
|
"min_consecutive_frames": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overall_thresholds": {
|
||||||
|
"auto_accept": 0.7,
|
||||||
|
"auto_reject": 0.3,
|
||||||
|
"review_range": [0.3, 0.7]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 完整使用範例
|
||||||
|
|
||||||
|
### 場景 1: 過濾低品質臉部
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 1. 獲取臉部列表
|
||||||
|
const facesResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ source: 'all', page: 1, page_size: 100 })
|
||||||
|
});
|
||||||
|
const facesData = await facesResponse.json();
|
||||||
|
|
||||||
|
// 2. 套用過濾規則
|
||||||
|
const filterResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ rules: null }) // 使用預設規則
|
||||||
|
});
|
||||||
|
const filterResult = await filterResponse.json();
|
||||||
|
|
||||||
|
console.log(`Total: ${filterResult.total_faces}`);
|
||||||
|
console.log(`Passed: ${filterResult.passed}`);
|
||||||
|
console.log(`Filtered: ${filterResult.filtered}`);
|
||||||
|
|
||||||
|
// 3. 顯示被過濾的臉部
|
||||||
|
filterResult.filtered_faces.forEach(face => {
|
||||||
|
console.log(`❌ Face ${face.face_id} (frame ${face.frame})`);
|
||||||
|
face.reasons.forEach(reason => {
|
||||||
|
console.log(` - ${reason}`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 場景 2: 自訂嚴格過濾
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 自訂嚴格過濾規則
|
||||||
|
const strictRules = {
|
||||||
|
version: "1.0",
|
||||||
|
rules: {
|
||||||
|
landmark_analysis: {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.3,
|
||||||
|
thresholds: {
|
||||||
|
eye_ratio_min: 0.30, // 更嚴格
|
||||||
|
eye_ratio_max: 0.50, // 更嚴格
|
||||||
|
nose_ratio_min: 0.10, // 更嚴格
|
||||||
|
pose_score_max: 0.5 // 更嚴格
|
||||||
|
}
|
||||||
|
},
|
||||||
|
mediapipe_verification: {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.2,
|
||||||
|
thresholds: {
|
||||||
|
min_iou: 0.5 // 更嚴格
|
||||||
|
}
|
||||||
|
},
|
||||||
|
embedding_similarity: {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.3,
|
||||||
|
thresholds: {
|
||||||
|
min_similarity: 0.80 // 更嚴格
|
||||||
|
}
|
||||||
|
},
|
||||||
|
temporal_consistency: {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.2,
|
||||||
|
thresholds: {
|
||||||
|
min_consecutive_frames: 5 // 更嚴格
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
overall_thresholds: {
|
||||||
|
auto_accept: 0.8, // 更嚴格
|
||||||
|
auto_reject: 0.2, // 更嚴格
|
||||||
|
review_range: [0.2, 0.8]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 儲存規則
|
||||||
|
await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
rule_name: "strict_filter",
|
||||||
|
rules: strictRules,
|
||||||
|
is_active: true
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
// 套用嚴格規則
|
||||||
|
const result = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ rules: strictRules })
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 錯誤處理
|
||||||
|
|
||||||
|
### 常見錯誤
|
||||||
|
|
||||||
|
**404 Not Found**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "Face not found"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
**原因**: 臉部 ID 不存在
|
||||||
|
|
||||||
|
**500 Internal Server Error**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "Database error"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
**原因**: 資料庫查詢失敗
|
||||||
|
|
||||||
|
### 錯誤處理範例
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/face/face_999/filter-report');
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status === 404) {
|
||||||
|
console.error('Face not found');
|
||||||
|
} else {
|
||||||
|
console.error('Server error');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = await response.json();
|
||||||
|
console.log(report);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Request failed:', error);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 最佳實踐
|
||||||
|
|
||||||
|
### 1. 使用預設規則開始
|
||||||
|
|
||||||
|
建議先使用預設規則,再根據實際需求調整。
|
||||||
|
|
||||||
|
### 2. 逐步調整閾值
|
||||||
|
|
||||||
|
不要一次性調整所有值,逐步調整並觀察結果。
|
||||||
|
|
||||||
|
### 3. 監控過濾統計
|
||||||
|
|
||||||
|
定期檢查過濾統計,確保過濾規則合理。
|
||||||
|
|
||||||
|
### 4. 保存多個規則配置
|
||||||
|
|
||||||
|
為不同場景保存不同的規則配置(如:嚴格、平衡、寬鬆)。
|
||||||
|
|
||||||
|
### 5. 使用者自訂
|
||||||
|
|
||||||
|
允許使用者自訂過濾規則,提供預設模板。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 支援與反饋
|
||||||
|
|
||||||
|
如有問題或建議,請聯繫 Core Team。
|
||||||
|
|
||||||
|
**文件版本**: v1.0
|
||||||
|
**最後更新**: 2026-08-09
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
-- Face Filter Features Table
|
||||||
|
-- Stores computed filter features for each detected face
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS face_filter_features (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
face_id VARCHAR(255) NOT NULL,
|
||||||
|
file_uuid VARCHAR(32) NOT NULL,
|
||||||
|
frame INTEGER NOT NULL,
|
||||||
|
|
||||||
|
-- Landmark geometric features
|
||||||
|
eye_ratio FLOAT, -- Eye distance / face width (normal: 0.25-0.55)
|
||||||
|
nose_ratio FLOAT, -- Eye-to-nose distance / face height (normal: 0.08-0.25)
|
||||||
|
pose_score FLOAT, -- Sum of absolute roll, yaw, pitch angles
|
||||||
|
|
||||||
|
-- MediaPipe verification features
|
||||||
|
mediapipe_detected BOOLEAN, -- Whether MediaPipe detected this face
|
||||||
|
mediapipe_iou FLOAT, -- IoU between Apple Vision and MediaPipe bbox
|
||||||
|
|
||||||
|
-- Embedding similarity features
|
||||||
|
embedding_similarity FLOAT, -- Max similarity to known faces
|
||||||
|
|
||||||
|
-- Temporal consistency features
|
||||||
|
consecutive_frames INTEGER, -- Number of consecutive frames this face appears
|
||||||
|
total_frames_detected INTEGER, -- Total frames this face was detected
|
||||||
|
|
||||||
|
-- Source information
|
||||||
|
apple_vision_confidence FLOAT,
|
||||||
|
mediapipe_confidence FLOAT,
|
||||||
|
primary_source VARCHAR(50), -- 'apple_vision' or 'mediapipe'
|
||||||
|
|
||||||
|
-- Computed field
|
||||||
|
multi_source_verified BOOLEAN GENERATED ALWAYS AS (
|
||||||
|
mediapipe_detected = TRUE AND mediapipe_iou > 0.3
|
||||||
|
) STORED,
|
||||||
|
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
UNIQUE(file_uuid, face_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Indexes for efficient querying
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_face_filter_file ON face_filter_features(file_uuid);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_face_filter_face ON face_filter_features(face_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_face_filter_frame ON face_filter_features(file_uuid, frame);
|
||||||
|
|
||||||
|
-- Filter Rules Table
|
||||||
|
-- Stores user-defined filter rules
|
||||||
|
CREATE TABLE IF NOT EXISTS filter_rules (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
file_uuid VARCHAR(32) NOT NULL,
|
||||||
|
rule_name VARCHAR(255) NOT NULL,
|
||||||
|
rules JSONB NOT NULL, -- Filter rule configuration
|
||||||
|
is_active BOOLEAN DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
UNIQUE(file_uuid, rule_name)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Index for efficient querying
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_filter_rules_file ON filter_rules(file_uuid);
|
||||||
|
|
||||||
|
-- Insert default filter rules
|
||||||
|
INSERT INTO filter_rules (file_uuid, rule_name, rules, is_active)
|
||||||
|
SELECT
|
||||||
|
'default',
|
||||||
|
'default_filter',
|
||||||
|
'{
|
||||||
|
"version": "1.0",
|
||||||
|
"rules": {
|
||||||
|
"landmark_analysis": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.3,
|
||||||
|
"thresholds": {
|
||||||
|
"eye_ratio_min": 0.25,
|
||||||
|
"eye_ratio_max": 0.55,
|
||||||
|
"nose_ratio_min": 0.08,
|
||||||
|
"pose_score_max": 0.8
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"mediapipe_verification": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.2,
|
||||||
|
"thresholds": {
|
||||||
|
"min_iou": 0.3
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"embedding_similarity": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.3,
|
||||||
|
"thresholds": {
|
||||||
|
"min_similarity": 0.70
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"temporal_consistency": {
|
||||||
|
"enabled": true,
|
||||||
|
"weight": 0.2,
|
||||||
|
"thresholds": {
|
||||||
|
"min_consecutive_frames": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overall_thresholds": {
|
||||||
|
"auto_accept": 0.7,
|
||||||
|
"auto_reject": 0.3,
|
||||||
|
"review_range": [0.3, 0.7]
|
||||||
|
}
|
||||||
|
}'::jsonb,
|
||||||
|
TRUE
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM filter_rules WHERE file_uuid = 'default' AND rule_name = 'default_filter'
|
||||||
|
);
|
||||||
|
|
||||||
@@ -0,0 +1,541 @@
|
|||||||
|
use axum::{
|
||||||
|
extract::{Path, State},
|
||||||
|
http::StatusCode,
|
||||||
|
response::Json,
|
||||||
|
routing::{get, post},
|
||||||
|
Router,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sqlx::Row;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use super::types::AppState;
|
||||||
|
use crate::core::db::schema;
|
||||||
|
use crate::core::face_filter_engine::{
|
||||||
|
default_filter_config, FaceFilterFeatures, FaceFilterResult, FilterEngine, FilterRecommendation,
|
||||||
|
FilterRuleConfig, RuleResult,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Request to filter faces
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct FilterFacesRequest {
|
||||||
|
pub rules: Option<FilterRuleConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Response for filter faces
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct FilterFacesResponse {
|
||||||
|
pub total_faces: i32,
|
||||||
|
pub passed: i32,
|
||||||
|
pub filtered: i32,
|
||||||
|
pub filtered_faces: Vec<FilteredFaceInfo>,
|
||||||
|
pub filter_stats: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Info about a filtered face
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct FilteredFaceInfo {
|
||||||
|
pub face_id: String,
|
||||||
|
pub frame: i32,
|
||||||
|
pub reasons: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request to get faces with filtering
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct GetFacesRequest {
|
||||||
|
pub source: Option<String>, // "all" | "apple_vision" | "mediapipe"
|
||||||
|
pub page: Option<usize>,
|
||||||
|
pub page_size: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Response for get faces
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct GetFacesResponse {
|
||||||
|
pub faces: Vec<FaceInfo>,
|
||||||
|
pub pagination: PaginationInfo,
|
||||||
|
pub source_summary: SourceSummary,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Face info
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct FaceInfo {
|
||||||
|
pub face_id: String,
|
||||||
|
pub frame: i32,
|
||||||
|
pub primary_source: String,
|
||||||
|
pub primary_confidence: f64,
|
||||||
|
pub detection_sources: Vec<SourceInfo>,
|
||||||
|
pub filter_features: Option<FaceFilterFeatures>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Source info
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct SourceInfo {
|
||||||
|
pub source_type: String,
|
||||||
|
pub confidence: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pagination info
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct PaginationInfo {
|
||||||
|
pub page: usize,
|
||||||
|
pub page_size: usize,
|
||||||
|
pub total: i64,
|
||||||
|
pub total_pages: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Source summary
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct SourceSummary {
|
||||||
|
pub apple_vision: i64,
|
||||||
|
pub mediapipe: i64,
|
||||||
|
pub merged_unique: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter stats response
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct FilterStatsResponse {
|
||||||
|
pub total_faces: i64,
|
||||||
|
by_category: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter rules request
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct SaveFilterRulesRequest {
|
||||||
|
pub rule_name: String,
|
||||||
|
pub rules: FilterRuleConfig,
|
||||||
|
pub is_active: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter rules response
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct FilterRulesResponse {
|
||||||
|
pub rules: Vec<FilterRuleInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter rule info
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct FilterRuleInfo {
|
||||||
|
pub id: i32,
|
||||||
|
pub rule_name: String,
|
||||||
|
pub rules: FilterRuleConfig,
|
||||||
|
pub is_active: bool,
|
||||||
|
pub created_at: String,
|
||||||
|
pub updated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get all faces with optional filtering
|
||||||
|
pub async fn get_faces(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(file_uuid): Path<String>,
|
||||||
|
req: Option<Json<GetFacesRequest>>,
|
||||||
|
) -> Result<Json<GetFacesResponse>, StatusCode> {
|
||||||
|
let req = req.map(|r| r.0).unwrap_or(GetFacesRequest {
|
||||||
|
source: None,
|
||||||
|
page: Some(1),
|
||||||
|
page_size: Some(50),
|
||||||
|
});
|
||||||
|
|
||||||
|
let page = req.page.unwrap_or(1);
|
||||||
|
let page_size = req.page_size.unwrap_or(50);
|
||||||
|
let offset = (page - 1) * page_size;
|
||||||
|
|
||||||
|
// Get total count
|
||||||
|
let filter_table = schema::table_name("face_filter_features");
|
||||||
|
let count_query = format!(
|
||||||
|
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1",
|
||||||
|
filter_table
|
||||||
|
);
|
||||||
|
|
||||||
|
let total: i64 = sqlx::query_scalar(&count_query)
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.fetch_one(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
// Get faces with filter features
|
||||||
|
let faces_query = format!(
|
||||||
|
"SELECT face_id, frame, primary_source, apple_vision_confidence, mediapipe_confidence,
|
||||||
|
eye_ratio, nose_ratio, pose_score, mediapipe_detected, mediapipe_iou,
|
||||||
|
embedding_similarity, consecutive_frames, total_frames_detected
|
||||||
|
FROM {}
|
||||||
|
WHERE file_uuid = $1
|
||||||
|
ORDER BY frame ASC
|
||||||
|
LIMIT $2 OFFSET $3",
|
||||||
|
filter_table
|
||||||
|
);
|
||||||
|
|
||||||
|
let rows = sqlx::query(&faces_query)
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.bind(page_size as i64)
|
||||||
|
.bind(offset as i64)
|
||||||
|
.fetch_all(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
// Build response
|
||||||
|
let faces: Vec<FaceInfo> = rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|row| {
|
||||||
|
let face_id: String = row.get(0);
|
||||||
|
let frame: i32 = row.get(1);
|
||||||
|
let primary_source: Option<String> = row.get(2);
|
||||||
|
let av_conf: Option<f64> = row.get(3);
|
||||||
|
let mp_conf: Option<f64> = row.get(4);
|
||||||
|
|
||||||
|
FaceInfo {
|
||||||
|
face_id: face_id.clone(),
|
||||||
|
frame,
|
||||||
|
primary_source: primary_source.clone().unwrap_or("apple_vision".to_string()),
|
||||||
|
primary_confidence: av_conf.unwrap_or(0.0),
|
||||||
|
detection_sources: vec![
|
||||||
|
SourceInfo {
|
||||||
|
source_type: "apple_vision".to_string(),
|
||||||
|
confidence: av_conf.unwrap_or(0.0),
|
||||||
|
},
|
||||||
|
SourceInfo {
|
||||||
|
source_type: "mediapipe".to_string(),
|
||||||
|
confidence: mp_conf.unwrap_or(0.0),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
filter_features: Some(FaceFilterFeatures {
|
||||||
|
face_id,
|
||||||
|
file_uuid: file_uuid.clone(),
|
||||||
|
frame,
|
||||||
|
eye_ratio: row.get(5),
|
||||||
|
nose_ratio: row.get(6),
|
||||||
|
pose_score: row.get(7),
|
||||||
|
mediapipe_detected: row.get(8),
|
||||||
|
mediapipe_iou: row.get(9),
|
||||||
|
embedding_similarity: row.get(10),
|
||||||
|
consecutive_frames: row.get(11),
|
||||||
|
total_frames_detected: row.get(12),
|
||||||
|
apple_vision_confidence: av_conf,
|
||||||
|
mediapipe_confidence: mp_conf,
|
||||||
|
primary_source,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Get source summary
|
||||||
|
let summary_query = format!(
|
||||||
|
"SELECT
|
||||||
|
COUNT(*) FILTER (WHERE primary_source = 'apple_vision') as apple_vision,
|
||||||
|
COUNT(*) FILTER (WHERE primary_source = 'mediapipe') as mediapipe,
|
||||||
|
COUNT(*) as merged_unique
|
||||||
|
FROM {}
|
||||||
|
WHERE file_uuid = $1",
|
||||||
|
filter_table
|
||||||
|
);
|
||||||
|
|
||||||
|
let summary_row = sqlx::query(&summary_query)
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.fetch_one(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
let apple_vision: i64 = summary_row.get(0);
|
||||||
|
let mediapipe: i64 = summary_row.get(1);
|
||||||
|
let merged_unique: i64 = summary_row.get(2);
|
||||||
|
|
||||||
|
let total_pages = ((total as f64) / (page_size as f64)).ceil() as usize;
|
||||||
|
|
||||||
|
Ok(Json(GetFacesResponse {
|
||||||
|
faces,
|
||||||
|
pagination: PaginationInfo {
|
||||||
|
page,
|
||||||
|
page_size,
|
||||||
|
total,
|
||||||
|
total_pages,
|
||||||
|
},
|
||||||
|
source_summary: SourceSummary {
|
||||||
|
apple_vision,
|
||||||
|
mediapipe,
|
||||||
|
merged_unique,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get filter report for a single face
|
||||||
|
pub async fn get_face_filter_report(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path((file_uuid, face_id)): Path<(String, String)>,
|
||||||
|
) -> Result<Json<FaceFilterResult>, StatusCode> {
|
||||||
|
let filter_table = schema::table_name("face_filter_features");
|
||||||
|
|
||||||
|
let row = sqlx::query(&format!(
|
||||||
|
"SELECT face_id, frame, eye_ratio, nose_ratio, pose_score,
|
||||||
|
mediapipe_detected, mediapipe_iou, embedding_similarity,
|
||||||
|
consecutive_frames, total_frames_detected,
|
||||||
|
apple_vision_confidence, mediapipe_confidence, primary_source
|
||||||
|
FROM {}
|
||||||
|
WHERE file_uuid = $1 AND face_id = $2",
|
||||||
|
filter_table
|
||||||
|
))
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.bind(&face_id)
|
||||||
|
.fetch_optional(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
match row {
|
||||||
|
Some(row) => {
|
||||||
|
let features = FaceFilterFeatures {
|
||||||
|
face_id: row.get(0),
|
||||||
|
file_uuid: file_uuid.clone(),
|
||||||
|
frame: row.get(1),
|
||||||
|
eye_ratio: row.get(2),
|
||||||
|
nose_ratio: row.get(3),
|
||||||
|
pose_score: row.get(4),
|
||||||
|
mediapipe_detected: row.get(5),
|
||||||
|
mediapipe_iou: row.get(6),
|
||||||
|
embedding_similarity: row.get(7),
|
||||||
|
consecutive_frames: row.get(8),
|
||||||
|
total_frames_detected: row.get(9),
|
||||||
|
apple_vision_confidence: row.get(10),
|
||||||
|
mediapipe_confidence: row.get(11),
|
||||||
|
primary_source: row.get(12),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Apply default filter rules
|
||||||
|
let config = default_filter_config();
|
||||||
|
let engine = FilterEngine::new(config);
|
||||||
|
|
||||||
|
let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
None => Err(StatusCode::NOT_FOUND),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply filter rules to all faces
|
||||||
|
pub async fn filter_faces(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(file_uuid): Path<String>,
|
||||||
|
req: Json<FilterFacesRequest>,
|
||||||
|
) -> Result<Json<FilterFacesResponse>, StatusCode> {
|
||||||
|
let filter_table = schema::table_name("face_filter_features");
|
||||||
|
|
||||||
|
// Get all faces for this file
|
||||||
|
let rows = sqlx::query(&format!(
|
||||||
|
"SELECT face_id, frame, eye_ratio, nose_ratio, pose_score,
|
||||||
|
mediapipe_detected, mediapipe_iou, embedding_similarity,
|
||||||
|
consecutive_frames, total_frames_detected,
|
||||||
|
apple_vision_confidence, mediapipe_confidence, primary_source
|
||||||
|
FROM {}
|
||||||
|
WHERE file_uuid = $1",
|
||||||
|
filter_table
|
||||||
|
))
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.fetch_all(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
let total_faces = rows.len() as i32;
|
||||||
|
|
||||||
|
// Use provided rules or default
|
||||||
|
let config = req.0.rules.clone().unwrap_or_else(default_filter_config);
|
||||||
|
let engine = FilterEngine::new(config);
|
||||||
|
|
||||||
|
// Apply filters
|
||||||
|
let mut passed = 0;
|
||||||
|
let mut filtered = 0;
|
||||||
|
let mut filtered_faces = Vec::new();
|
||||||
|
let mut filter_stats: HashMap<String, i64> = HashMap::new();
|
||||||
|
|
||||||
|
for row in rows {
|
||||||
|
let features = FaceFilterFeatures {
|
||||||
|
face_id: row.get(0),
|
||||||
|
file_uuid: file_uuid.clone(),
|
||||||
|
frame: row.get(1),
|
||||||
|
eye_ratio: row.get(2),
|
||||||
|
nose_ratio: row.get(3),
|
||||||
|
pose_score: row.get(4),
|
||||||
|
mediapipe_detected: row.get(5),
|
||||||
|
mediapipe_iou: row.get(6),
|
||||||
|
embedding_similarity: row.get(7),
|
||||||
|
consecutive_frames: row.get(8),
|
||||||
|
total_frames_detected: row.get(9),
|
||||||
|
apple_vision_confidence: row.get(10),
|
||||||
|
mediapipe_confidence: row.get(11),
|
||||||
|
primary_source: row.get(12),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
if result.recommendation == FilterRecommendation::Accept {
|
||||||
|
passed += 1;
|
||||||
|
} else {
|
||||||
|
filtered += 1;
|
||||||
|
|
||||||
|
// Count reasons before moving
|
||||||
|
for reason in &result.reasons {
|
||||||
|
let key = if reason.contains("eye_ratio") || reason.contains("nose_ratio") || reason.contains("pose_score") {
|
||||||
|
"landmark".to_string()
|
||||||
|
} else if reason.contains("MediaPipe") {
|
||||||
|
"mediapipe".to_string()
|
||||||
|
} else if reason.contains("embedding") {
|
||||||
|
"embedding".to_string()
|
||||||
|
} else if reason.contains("frame") {
|
||||||
|
"temporal".to_string()
|
||||||
|
} else {
|
||||||
|
"other".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
*filter_stats.entry(key).or_insert(0) += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
filtered_faces.push(FilteredFaceInfo {
|
||||||
|
face_id: result.face_id,
|
||||||
|
frame: result.frame,
|
||||||
|
reasons: result.reasons,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let filter_stats_json = serde_json::to_value(&filter_stats).unwrap_or_default();
|
||||||
|
|
||||||
|
Ok(Json(FilterFacesResponse {
|
||||||
|
total_faces,
|
||||||
|
passed,
|
||||||
|
filtered,
|
||||||
|
filtered_faces,
|
||||||
|
filter_stats: filter_stats_json,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get filter statistics
|
||||||
|
pub async fn get_filter_stats(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(file_uuid): Path<String>,
|
||||||
|
) -> Result<Json<FilterStatsResponse>, StatusCode> {
|
||||||
|
let filter_table = schema::table_name("face_filter_features");
|
||||||
|
|
||||||
|
let row = sqlx::query(&format!(
|
||||||
|
"SELECT
|
||||||
|
COUNT(*) as total,
|
||||||
|
COUNT(*) FILTER (WHERE primary_source = 'apple_vision') as apple_vision,
|
||||||
|
COUNT(*) FILTER (WHERE primary_source = 'mediapipe') as mediapipe,
|
||||||
|
AVG(eye_ratio) as avg_eye_ratio,
|
||||||
|
AVG(nose_ratio) as avg_nose_ratio,
|
||||||
|
AVG(pose_score) as avg_pose_score,
|
||||||
|
COUNT(*) FILTER (WHERE mediapipe_detected = true) as mediapipe_detected_count,
|
||||||
|
AVG(embedding_similarity) as avg_embedding_similarity,
|
||||||
|
AVG(consecutive_frames) as avg_consecutive_frames
|
||||||
|
FROM {}
|
||||||
|
WHERE file_uuid = $1",
|
||||||
|
filter_table
|
||||||
|
))
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.fetch_one(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
let stats = serde_json::json!({
|
||||||
|
"total_faces": row.get::<i64, _>(0),
|
||||||
|
"by_source": {
|
||||||
|
"apple_vision": row.get::<i64, _>(1),
|
||||||
|
"mediapipe": row.get::<i64, _>(2),
|
||||||
|
},
|
||||||
|
"by_quality": {
|
||||||
|
"avg_eye_ratio": row.get::<Option<f64>, _>(3),
|
||||||
|
"avg_nose_ratio": row.get::<Option<f64>, _>(4),
|
||||||
|
"avg_pose_score": row.get::<Option<f64>, _>(5),
|
||||||
|
"mediapipe_verified": row.get::<i64, _>(6),
|
||||||
|
"avg_embedding_similarity": row.get::<Option<f64>, _>(7),
|
||||||
|
"avg_consecutive_frames": row.get::<Option<f64>, _>(8),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(Json(FilterStatsResponse {
|
||||||
|
total_faces: row.get(0),
|
||||||
|
by_category: stats,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Save filter rules
|
||||||
|
pub async fn save_filter_rules(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(file_uuid): Path<String>,
|
||||||
|
req: Json<SaveFilterRulesRequest>,
|
||||||
|
) -> Result<Json<FilterRuleInfo>, StatusCode> {
|
||||||
|
let rules_table = schema::table_name("filter_rules");
|
||||||
|
|
||||||
|
let is_active = req.is_active.unwrap_or(true);
|
||||||
|
|
||||||
|
let row = sqlx::query(&format!(
|
||||||
|
"INSERT INTO {} (file_uuid, rule_name, rules, is_active)
|
||||||
|
VALUES ($1, $2, $3, $4)
|
||||||
|
ON CONFLICT (file_uuid, rule_name)
|
||||||
|
DO UPDATE SET rules = EXCLUDED.rules, is_active = EXCLUDED.is_active, updated_at = CURRENT_TIMESTAMP
|
||||||
|
RETURNING id, rule_name, rules, is_active, created_at::TEXT, updated_at::TEXT",
|
||||||
|
rules_table
|
||||||
|
))
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.bind(&req.rule_name)
|
||||||
|
.bind(serde_json::to_value(&req.rules).unwrap())
|
||||||
|
.bind(is_active)
|
||||||
|
.fetch_one(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
let rules: FilterRuleConfig = serde_json::from_value(row.get(2)).unwrap();
|
||||||
|
|
||||||
|
Ok(Json(FilterRuleInfo {
|
||||||
|
id: row.get(0),
|
||||||
|
rule_name: row.get(1),
|
||||||
|
rules,
|
||||||
|
is_active: row.get(3),
|
||||||
|
created_at: row.get(4),
|
||||||
|
updated_at: row.get(5),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get filter rules
|
||||||
|
pub async fn get_filter_rules(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(file_uuid): Path<String>,
|
||||||
|
) -> Result<Json<FilterRulesResponse>, StatusCode> {
|
||||||
|
let rules_table = schema::table_name("filter_rules");
|
||||||
|
|
||||||
|
let rows = sqlx::query(&format!(
|
||||||
|
"SELECT id, rule_name, rules, is_active, created_at::TEXT, updated_at::TEXT
|
||||||
|
FROM {}
|
||||||
|
WHERE file_uuid = $1
|
||||||
|
ORDER BY created_at DESC",
|
||||||
|
rules_table
|
||||||
|
))
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.fetch_all(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
let rules: Vec<FilterRuleInfo> = rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|row| {
|
||||||
|
let rules: FilterRuleConfig = serde_json::from_value(row.get(2)).unwrap();
|
||||||
|
FilterRuleInfo {
|
||||||
|
id: row.get(0),
|
||||||
|
rule_name: row.get(1),
|
||||||
|
rules,
|
||||||
|
is_active: row.get(3),
|
||||||
|
created_at: row.get(4),
|
||||||
|
updated_at: row.get(5),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(Json(FilterRulesResponse { rules }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create router for face filter API
|
||||||
|
pub fn face_filter_routes() -> Router<AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/api/v1/file/{file_uuid}/faces", get(get_faces))
|
||||||
|
.route("/api/v1/file/{file_uuid}/face/{face_id}/filter-report", get(get_face_filter_report))
|
||||||
|
.route("/api/v1/file/{file_uuid}/faces/filter", post(filter_faces))
|
||||||
|
.route("/api/v1/file/{file_uuid}/filter-stats", get(get_filter_stats))
|
||||||
|
.route("/api/v1/file/{file_uuid}/filter-rules", get(get_filter_rules))
|
||||||
|
.route("/api/v1/file/{file_uuid}/filter-rules", post(save_filter_rules))
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ pub mod auth;
|
|||||||
pub mod checkin_api;
|
pub mod checkin_api;
|
||||||
pub mod cluster_agent;
|
pub mod cluster_agent;
|
||||||
pub mod docs;
|
pub mod docs;
|
||||||
|
pub mod face_filter;
|
||||||
pub mod files;
|
pub mod files;
|
||||||
pub mod health;
|
pub mod health;
|
||||||
pub mod identities;
|
pub mod identities;
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ use super::auth;
|
|||||||
use super::checkin_api;
|
use super::checkin_api;
|
||||||
use super::cluster_agent;
|
use super::cluster_agent;
|
||||||
use super::docs;
|
use super::docs;
|
||||||
|
use super::face_filter;
|
||||||
use super::files;
|
use super::files;
|
||||||
use super::health;
|
use super::health;
|
||||||
use super::health::{health, health_consistency, health_detailed};
|
use super::health::{health, health_consistency, health_detailed};
|
||||||
@@ -134,6 +135,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
|||||||
.merge(checkin_api::checkin_routes())
|
.merge(checkin_api::checkin_routes())
|
||||||
.merge(cluster_agent::cluster_agent_routes())
|
.merge(cluster_agent::cluster_agent_routes())
|
||||||
.merge(profile::profile_routes())
|
.merge(profile::profile_routes())
|
||||||
|
.merge(face_filter::face_filter_routes())
|
||||||
.layer(axum::middleware::from_fn_with_state(
|
.layer(axum::middleware::from_fn_with_state(
|
||||||
state.api_state.clone(),
|
state.api_state.clone(),
|
||||||
unified_auth,
|
unified_auth,
|
||||||
|
|||||||
@@ -0,0 +1,445 @@
|
|||||||
|
use anyhow::{Context, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Filter feature data for a single face
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct FaceFilterFeatures {
|
||||||
|
pub face_id: String,
|
||||||
|
pub file_uuid: String,
|
||||||
|
pub frame: i32,
|
||||||
|
|
||||||
|
// Landmark geometric features
|
||||||
|
pub eye_ratio: Option<f64>,
|
||||||
|
pub nose_ratio: Option<f64>,
|
||||||
|
pub pose_score: Option<f64>,
|
||||||
|
|
||||||
|
// MediaPipe verification features
|
||||||
|
pub mediapipe_detected: Option<bool>,
|
||||||
|
pub mediapipe_iou: Option<f64>,
|
||||||
|
|
||||||
|
// Embedding similarity features
|
||||||
|
pub embedding_similarity: Option<f64>,
|
||||||
|
|
||||||
|
// Temporal consistency features
|
||||||
|
pub consecutive_frames: Option<i32>,
|
||||||
|
pub total_frames_detected: Option<i32>,
|
||||||
|
|
||||||
|
// Source information
|
||||||
|
pub apple_vision_confidence: Option<f64>,
|
||||||
|
pub mediapipe_confidence: Option<f64>,
|
||||||
|
pub primary_source: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter rule configuration
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct FilterRuleConfig {
|
||||||
|
pub version: String,
|
||||||
|
pub rules: HashMap<String, RuleConfig>,
|
||||||
|
pub overall_thresholds: OverallThresholds,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RuleConfig {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub weight: f64,
|
||||||
|
pub thresholds: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct OverallThresholds {
|
||||||
|
pub auto_accept: f64,
|
||||||
|
pub auto_reject: f64,
|
||||||
|
pub review_range: (f64, f64),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter result for a single face
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct FaceFilterResult {
|
||||||
|
pub face_id: String,
|
||||||
|
pub frame: i32,
|
||||||
|
pub overall_confidence: f64,
|
||||||
|
pub recommendation: FilterRecommendation,
|
||||||
|
pub rule_results: HashMap<String, RuleResult>,
|
||||||
|
pub reasons: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum FilterRecommendation {
|
||||||
|
Accept,
|
||||||
|
Review,
|
||||||
|
Reject,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of applying a single rule
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RuleResult {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub score: f64,
|
||||||
|
pub passed: bool,
|
||||||
|
pub reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter engine for applying rules to face data
|
||||||
|
pub struct FilterEngine {
|
||||||
|
config: FilterRuleConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FilterEngine {
|
||||||
|
/// Create a new filter engine with the given configuration
|
||||||
|
pub fn new(config: FilterRuleConfig) -> Self {
|
||||||
|
Self { config }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply all filter rules to a single face
|
||||||
|
pub fn filter_face(&self, features: &FaceFilterFeatures) -> Result<FaceFilterResult> {
|
||||||
|
let mut rule_results = HashMap::new();
|
||||||
|
let mut total_score: f64 = 0.0;
|
||||||
|
let mut total_weight: f64 = 0.0;
|
||||||
|
let mut reasons = Vec::new();
|
||||||
|
|
||||||
|
// Apply landmark analysis rule
|
||||||
|
if let Some(rule_config) = self.config.rules.get("landmark_analysis") {
|
||||||
|
let result = self.apply_landmark_analysis(features, rule_config);
|
||||||
|
total_score += result.score * rule_config.weight;
|
||||||
|
total_weight += rule_config.weight;
|
||||||
|
if let Some(reason) = &result.reason {
|
||||||
|
reasons.push(reason.clone());
|
||||||
|
}
|
||||||
|
rule_results.insert("landmark_analysis".to_string(), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply MediaPipe verification rule
|
||||||
|
if let Some(rule_config) = self.config.rules.get("mediapipe_verification") {
|
||||||
|
let result = self.apply_mediapipe_verification(features, rule_config);
|
||||||
|
total_score += result.score * rule_config.weight;
|
||||||
|
total_weight += rule_config.weight;
|
||||||
|
if let Some(reason) = &result.reason {
|
||||||
|
reasons.push(reason.clone());
|
||||||
|
}
|
||||||
|
rule_results.insert("mediapipe_verification".to_string(), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply embedding similarity rule
|
||||||
|
if let Some(rule_config) = self.config.rules.get("embedding_similarity") {
|
||||||
|
let result = self.apply_embedding_similarity(features, rule_config);
|
||||||
|
total_score += result.score * rule_config.weight;
|
||||||
|
total_weight += rule_config.weight;
|
||||||
|
if let Some(reason) = &result.reason {
|
||||||
|
reasons.push(reason.clone());
|
||||||
|
}
|
||||||
|
rule_results.insert("embedding_similarity".to_string(), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply temporal consistency rule
|
||||||
|
if let Some(rule_config) = self.config.rules.get("temporal_consistency") {
|
||||||
|
let result = self.apply_temporal_consistency(features, rule_config);
|
||||||
|
total_score += result.score * rule_config.weight;
|
||||||
|
total_weight += rule_config.weight;
|
||||||
|
if let Some(reason) = &result.reason {
|
||||||
|
reasons.push(reason.clone());
|
||||||
|
}
|
||||||
|
rule_results.insert("temporal_consistency".to_string(), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate overall confidence
|
||||||
|
let overall_confidence = if total_weight > 0.0 {
|
||||||
|
total_score / total_weight
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
|
||||||
|
// Determine recommendation
|
||||||
|
let recommendation = if overall_confidence >= self.config.overall_thresholds.auto_accept {
|
||||||
|
FilterRecommendation::Accept
|
||||||
|
} else if overall_confidence <= self.config.overall_thresholds.auto_reject {
|
||||||
|
FilterRecommendation::Reject
|
||||||
|
} else {
|
||||||
|
FilterRecommendation::Review
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(FaceFilterResult {
|
||||||
|
face_id: features.face_id.clone(),
|
||||||
|
frame: features.frame,
|
||||||
|
overall_confidence,
|
||||||
|
recommendation,
|
||||||
|
rule_results,
|
||||||
|
reasons,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply landmark analysis rule
|
||||||
|
fn apply_landmark_analysis(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||||
|
if !config.enabled {
|
||||||
|
return RuleResult {
|
||||||
|
enabled: false,
|
||||||
|
score: 1.0,
|
||||||
|
passed: true,
|
||||||
|
reason: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut score: f64 = 1.0;
|
||||||
|
let mut reasons = Vec::new();
|
||||||
|
|
||||||
|
// Check eye ratio
|
||||||
|
if let Some(eye_ratio) = features.eye_ratio {
|
||||||
|
let min = config.thresholds["eye_ratio_min"].as_f64().unwrap_or(0.25);
|
||||||
|
let max = config.thresholds["eye_ratio_max"].as_f64().unwrap_or(0.55);
|
||||||
|
|
||||||
|
if eye_ratio < min || eye_ratio > max {
|
||||||
|
score -= 0.25;
|
||||||
|
reasons.push(format!("eye_ratio abnormal ({:.3})", eye_ratio));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check nose ratio
|
||||||
|
if let Some(nose_ratio) = features.nose_ratio {
|
||||||
|
let min = config.thresholds["nose_ratio_min"].as_f64().unwrap_or(0.08);
|
||||||
|
|
||||||
|
if nose_ratio < min {
|
||||||
|
score -= 0.25;
|
||||||
|
reasons.push(format!("nose_ratio too low ({:.3})", nose_ratio));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check pose score
|
||||||
|
if let Some(pose_score) = features.pose_score {
|
||||||
|
let max = config.thresholds["pose_score_max"].as_f64().unwrap_or(0.8);
|
||||||
|
|
||||||
|
if pose_score > max {
|
||||||
|
score -= 0.25;
|
||||||
|
reasons.push(format!("pose_score too high ({:.3})", pose_score));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let score = score.max(0.0_f64);
|
||||||
|
let passed = score >= 0.5;
|
||||||
|
|
||||||
|
RuleResult {
|
||||||
|
enabled: true,
|
||||||
|
score,
|
||||||
|
passed,
|
||||||
|
reason: if reasons.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(reasons.join(", "))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply MediaPipe verification rule
|
||||||
|
fn apply_mediapipe_verification(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||||
|
if !config.enabled {
|
||||||
|
return RuleResult {
|
||||||
|
enabled: false,
|
||||||
|
score: 1.0,
|
||||||
|
passed: true,
|
||||||
|
reason: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// If MediaPipe didn't detect this face, lower the score
|
||||||
|
if features.mediapipe_detected == Some(false) {
|
||||||
|
return RuleResult {
|
||||||
|
enabled: true,
|
||||||
|
score: 0.3,
|
||||||
|
passed: false,
|
||||||
|
reason: Some("MediaPipe did not detect this face".to_string()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check IoU if available
|
||||||
|
if let Some(iou) = features.mediapipe_iou {
|
||||||
|
let min_iou = config.thresholds["min_iou"].as_f64().unwrap_or(0.3);
|
||||||
|
|
||||||
|
if iou < min_iou {
|
||||||
|
return RuleResult {
|
||||||
|
enabled: true,
|
||||||
|
score: 0.5,
|
||||||
|
passed: false,
|
||||||
|
reason: Some(format!("MediaPipe IoU too low ({:.3})", iou)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RuleResult {
|
||||||
|
enabled: true,
|
||||||
|
score: 1.0,
|
||||||
|
passed: true,
|
||||||
|
reason: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply embedding similarity rule
|
||||||
|
fn apply_embedding_similarity(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||||
|
if !config.enabled {
|
||||||
|
return RuleResult {
|
||||||
|
enabled: false,
|
||||||
|
score: 1.0,
|
||||||
|
passed: true,
|
||||||
|
reason: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(similarity) = features.embedding_similarity {
|
||||||
|
let min_similarity = config.thresholds["min_similarity"].as_f64().unwrap_or(0.70);
|
||||||
|
|
||||||
|
if similarity < min_similarity {
|
||||||
|
return RuleResult {
|
||||||
|
enabled: true,
|
||||||
|
score: similarity / min_similarity,
|
||||||
|
passed: false,
|
||||||
|
reason: Some(format!("Low embedding similarity ({:.3})", similarity)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RuleResult {
|
||||||
|
enabled: true,
|
||||||
|
score: 1.0,
|
||||||
|
passed: true,
|
||||||
|
reason: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply temporal consistency rule
|
||||||
|
fn apply_temporal_consistency(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
|
||||||
|
if !config.enabled {
|
||||||
|
return RuleResult {
|
||||||
|
enabled: false,
|
||||||
|
score: 1.0,
|
||||||
|
passed: true,
|
||||||
|
reason: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(consecutive) = features.consecutive_frames {
|
||||||
|
let min_consecutive = config.thresholds["min_consecutive_frames"].as_i64().unwrap_or(3) as i32;
|
||||||
|
|
||||||
|
if consecutive < min_consecutive {
|
||||||
|
return RuleResult {
|
||||||
|
enabled: true,
|
||||||
|
score: (consecutive as f64) / (min_consecutive as f64),
|
||||||
|
passed: false,
|
||||||
|
reason: Some(format!("Single frame detection ({})", consecutive)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RuleResult {
|
||||||
|
enabled: true,
|
||||||
|
score: 1.0,
|
||||||
|
passed: true,
|
||||||
|
reason: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Default filter configuration
|
||||||
|
pub fn default_filter_config() -> FilterRuleConfig {
|
||||||
|
let mut rules = HashMap::new();
|
||||||
|
|
||||||
|
rules.insert("landmark_analysis".to_string(), RuleConfig {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.3,
|
||||||
|
thresholds: serde_json::json!({
|
||||||
|
"eye_ratio_min": 0.25,
|
||||||
|
"eye_ratio_max": 0.55,
|
||||||
|
"nose_ratio_min": 0.08,
|
||||||
|
"pose_score_max": 0.8
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
rules.insert("mediapipe_verification".to_string(), RuleConfig {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.2,
|
||||||
|
thresholds: serde_json::json!({
|
||||||
|
"min_iou": 0.3
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
rules.insert("embedding_similarity".to_string(), RuleConfig {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.3,
|
||||||
|
thresholds: serde_json::json!({
|
||||||
|
"min_similarity": 0.70
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
rules.insert("temporal_consistency".to_string(), RuleConfig {
|
||||||
|
enabled: true,
|
||||||
|
weight: 0.2,
|
||||||
|
thresholds: serde_json::json!({
|
||||||
|
"min_consecutive_frames": 3
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
FilterRuleConfig {
|
||||||
|
version: "1.0".to_string(),
|
||||||
|
rules,
|
||||||
|
overall_thresholds: OverallThresholds {
|
||||||
|
auto_accept: 0.7,
|
||||||
|
auto_reject: 0.3,
|
||||||
|
review_range: (0.3, 0.7),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_filter_engine_accept() {
|
||||||
|
let config = default_filter_config();
|
||||||
|
let engine = FilterEngine::new(config);
|
||||||
|
|
||||||
|
let features = FaceFilterFeatures {
|
||||||
|
face_id: "test_001".to_string(),
|
||||||
|
file_uuid: "test".to_string(),
|
||||||
|
frame: 0,
|
||||||
|
eye_ratio: Some(0.37),
|
||||||
|
nose_ratio: Some(0.15),
|
||||||
|
pose_score: Some(0.1),
|
||||||
|
mediapipe_detected: Some(true),
|
||||||
|
mediapipe_iou: Some(0.8),
|
||||||
|
embedding_similarity: Some(0.85),
|
||||||
|
consecutive_frames: Some(15),
|
||||||
|
total_frames_detected: Some(15),
|
||||||
|
apple_vision_confidence: Some(0.85),
|
||||||
|
mediapipe_confidence: Some(0.9),
|
||||||
|
primary_source: Some("apple_vision".to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = engine.filter_face(&features).unwrap();
|
||||||
|
assert_eq!(result.recommendation, FilterRecommendation::Accept);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_filter_engine_reject() {
|
||||||
|
let config = default_filter_config();
|
||||||
|
let engine = FilterEngine::new(config);
|
||||||
|
|
||||||
|
let features = FaceFilterFeatures {
|
||||||
|
face_id: "test_002".to_string(),
|
||||||
|
file_uuid: "test".to_string(),
|
||||||
|
frame: 671,
|
||||||
|
eye_ratio: Some(0.33),
|
||||||
|
nose_ratio: Some(0.02), // Abnormal
|
||||||
|
pose_score: Some(0.08),
|
||||||
|
mediapipe_detected: Some(false), // Not detected
|
||||||
|
mediapipe_iou: Some(0.0),
|
||||||
|
embedding_similarity: Some(0.15), // Low similarity
|
||||||
|
consecutive_frames: Some(1), // Single frame
|
||||||
|
total_frames_detected: Some(1),
|
||||||
|
apple_vision_confidence: Some(0.84),
|
||||||
|
mediapipe_confidence: None,
|
||||||
|
primary_source: Some("apple_vision".to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = engine.filter_face(&features).unwrap();
|
||||||
|
assert_eq!(result.recommendation, FilterRecommendation::Reject);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ pub mod chunk;
|
|||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod db;
|
pub mod db;
|
||||||
pub mod embedding;
|
pub mod embedding;
|
||||||
|
pub mod face_filter_engine;
|
||||||
pub mod file_lifecycle;
|
pub mod file_lifecycle;
|
||||||
pub mod file_profile;
|
pub mod file_profile;
|
||||||
pub mod frame_cache;
|
pub mod frame_cache;
|
||||||
|
|||||||
Reference in New Issue
Block a user