Files
momentry_core/FACE_RECOGNITION_DEPLOYMENT.md
Warren b54c2def30 feat: add migrations, test scripts, and utility tools
- Add database migrations (006-028) for face recognition, identity, file_uuid
- Add test scripts for ASR, face, search, processing
- Add portal frontend (Tauri)
- Add config, benchmark, and monitoring utilities
- Add model checkpoints and pretrained model references
2026-04-30 15:11:53 +08:00

8.7 KiB
Raw Blame History

臉部辨識系統部署指南

系統概述

Momentry Core 的臉部辨識系統是一個完整的本地化解決方案,具有以下特點:

  • 100% 本地運算:無雲端依賴,保護隱私
  • Apple Silicon 優化:支援 MPS 加速CoreMLExecutionProvider
  • 向量相似度搜尋:使用 pgvector 進行臉部比對
  • 即時學習:可註冊新臉部並在未來識別
  • 影片分析:自動分析影片中的臉部

系統架構

┌─────────────────────────────────────────────────────────────┐
│                   臉部辨識系統架構                           │
├─────────────────────────────────────────────────────────────┤
│ 前端應用/API 客戶端                                          │
│  ↓                                                          │
│  Momentry API 伺服器 (Rust/Axum)                            │
│  ↓                                                          │
│ 臉部辨識處理器 (Python/InsightFace)                         │
│  ↓                                                          │
│  PostgreSQL + pgvector 資料庫                               │
│  ↓                                                          │
│  ONNX Runtime + Apple MPS 加速                              │
└─────────────────────────────────────────────────────────────┘

部署步驟

1. 環境準備

# 安裝系統依賴
brew install postgresql@18 redis mongodb-community ffmpeg

# 安裝 Python 依賴
pip install insightface onnxruntime-coreml opencv-python pillow psycopg2-binary requests

# 安裝 Rust 工具鏈
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

2. 資料庫設定

# 啟動 PostgreSQL
brew services start postgresql@18

# 建立資料庫和使用者
createdb momentry
createuser -s accusys

# 啟用 pgvector 擴展
psql -d momentry -c "CREATE EXTENSION IF NOT EXISTS vector;"

# 執行遷移腳本
psql -d momentry -f migrations/006_face_recognition_tables.sql

3. 模型下載

# 下載 InsightFace buffalo_l 模型
python3 -c "
import insightface
app = insightface.app.FaceAnalysis(name='buffalo_l')
app.prepare(ctx_id=0, det_size=(640, 640))
print('✅ Model downloaded successfully')
"

4. 伺服器部署

# 編譯生產版本
cd /Users/accusys/momentry_core_0.1
cargo build --release --bin momentry

# 啟動伺服器
./target/release/momentry server --port 3002

# 或使用 systemd 服務Linux
sudo cp deploy/momentry.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable momentry
sudo systemctl start momentry

5. API 金鑰管理

# 建立 API 金鑰
./target/release/momentry api-key create "face_recognition_app" --key-type user

# 列出金鑰
./target/release/momentry api-key list

# 驗證金鑰
./target/release/momentry api-key validate --key "YOUR_API_KEY"

API 端點

臉部辨識 API

端點 方法 功能 認證
/api/v1/face/recognize POST 識別圖片中的臉部 X-API-Key
/api/v1/face/register POST 註冊新臉部 X-API-Key
/api/v1/face/list GET 列出已註冊臉部 X-API-Key
/api/v1/face/results/{uuid} GET 取得影片分析結果 X-API-Key
/api/v1/face/search POST 搜尋相似臉部 X-API-Key

使用範例

1. 註冊新臉部(學習)

curl -X POST http://localhost:3002/api/v1/face/register \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "video_uuid": "384b0ff44aaaa1f1",
    "frame_number": 19778,
    "face_index": 0,
    "person_name": "張三",
    "metadata": {
      "gender": "male",
      "age": 35,
      "notes": "公司員工"
    }
  }'

2. 識別臉部

curl -X POST http://localhost:3002/api/v1/face/recognize \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "image=@photo.jpg"

3. 取得影片分析結果

curl -X GET "http://localhost:3002/api/v1/face/results/384b0ff44aaaa1f1" \
  -H "X-API-Key: YOUR_API_KEY"

影片分析流程

1. 分析影片中的臉部

# 使用 Python 腳本分析影片
python3 scripts/analyze_video_faces.py \
  --video-path "/path/to/video.mp4" \
  --output-dir "/tmp/face_analysis" \
  --sample-rate 30

2. 遷移分析結果到資料庫

# 遷移結果到 face_recognition_results 表
python3 scripts/migrate_face_results.py

3. 提取特定臉部(如女性臉部)

# 提取女性臉部
python3 scripts/extract_female_faces.py \
  --video-uuid "384b0ff44aaaa1f1" \
  --output-dir "/tmp/female_faces"

監控與日誌

日誌位置

# API 伺服器日誌
/Users/accusys/momentry/log/momentry_api.log
/Users/accusys/momentry/log/momentry_api.error.log

# 資料庫日誌
/Users/accusys/momentry/var/postgresql/logfile

# 處理器日誌
/tmp/face_analysis/analysis.log

健康檢查

# 檢查伺服器狀態
curl -X GET "http://localhost:3002/api/v1/face/list" \
  -H "X-API-Key: YOUR_API_KEY"

# 檢查資料庫連接
psql -d momentry -c "SELECT COUNT(*) FROM face_identities;"

# 檢查模型載入
python3 scripts/test_face_processor.py

效能優化

1. Apple Silicon MPS 加速

# 在 Python 腳本中啟用 MPS
import onnxruntime as ort

providers = ['CoreMLExecutionProvider', 'CPUExecutionProvider']
session = ort.InferenceSession('model.onnx', providers=providers)

2. 資料庫索引優化

-- 建立臉部搜尋索引
CREATE INDEX idx_face_identities_embedding 
ON face_identities USING ivfflat (embedding vector_cosine_ops);

-- 建立影片查詢索引
CREATE INDEX idx_face_detections_video_frame 
ON face_detections (video_uuid, frame_number);

3. 批次處理

# 批次分析多個影片
python3 scripts/batch_analyze_videos.py \
  --input-dir "/path/to/videos" \
  --workers 4 \
  --batch-size 10

故障排除

常見問題

1. API 認證失敗 (401)

# 檢查 API 金鑰格式
# 正確X-API-Key: muser_xxx_xxx_xxx
# 錯誤Authorization: Bearer xxx

curl -X GET "http://localhost:3002/api/v1/face/list" \
  -H "X-API-Key: YOUR_API_KEY"

2. 資料庫連接超時

# 檢查 PostgreSQL 服務
brew services list | grep postgresql

# 增加連接池大小
export DATABASE_MAX_CONNECTIONS=100

3. 模型載入失敗

# 檢查模型檔案
ls -la ~/.insightface/models/buffalo_l/

# 重新下載模型
rm -rf ~/.insightface/models/buffalo_l/
python3 -c "import insightface; app = insightface.app.FaceAnalysis(name='buffalo_l')"

4. MPS 加速不工作

# 檢查 Apple Silicon 支援
python3 -c "import platform; print(f'Architecture: {platform.machine()}')"

# 檢查 ONNX Runtime 提供者
python3 -c "import onnxruntime as ort; print(f'Available providers: {ort.get_available_providers()}')"

安全考量

1. API 金鑰安全

  • 使用環境變數儲存 API 金鑰
  • 定期輪換金鑰(每 90 天)
  • 限制金鑰權限(最小權限原則)
  • 記錄所有 API 使用記錄

2. 資料保護

  • 所有臉部資料本地儲存
  • 臉部嵌入向量加密儲存
  • 敏感資訊不記錄到日誌
  • 定期備份資料庫

3. 網路安全

  • 使用 HTTPS 生產環境
  • 啟用 API 速率限制
  • 設定防火牆規則
  • 定期安全掃描

擴展功能

1. 自訂模型

# 使用自訂 InsightFace 模型
app = insightface.app.FaceAnalysis(
    name='custom_model',
    root='~/.insightface/models/custom/'
)

2. 即時串流分析

# 即時攝影機臉部辨識
python3 scripts/realtime_face_recognition.py \
  --camera 0 \
  --model buffalo_l \
  --output-display

3. 批次註冊

# 批次註冊臉部資料庫
python3 scripts/batch_register_faces.py \
  --dataset "/path/to/face_dataset" \
  --metadata "/path/to/metadata.csv"

聯絡與支援

問題回報

  1. 檢查日誌檔案
  2. 提供重現步驟
  3. 包含系統資訊
  4. 提交到 GitHub Issues

效能問題

  • 影片分析速度慢:調整 sample-rate 參數
  • 記憶體使用過高:減少批次大小
  • 資料庫查詢慢:優化索引

功能請求

  • 新增臉部屬性分析
  • 支援更多影片格式
  • 增加匯出功能
  • 改進使用者介面

版本: 1.0.0
最後更新: 2026-03-30
作者: Momentry Core 團隊
文件狀態: 生產就緒