From 9f12e835b85cb86330e716f9cc02d70ade32b1b9 Mon Sep 17 00:00:00 2001 From: Accusys Date: Mon, 24 Aug 2026 19:13:11 +0800 Subject: [PATCH] feat: add TraceArtifacts phase + VLM waits for all key_frame.jpg MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add TraceArtifacts phase to TkgPhase enum (phase 18) - Report progress as key_frame.jpg/key_face.jpg are created - VLM trigger now polls until ALL key_frame.jpg files exist (was: started after TKG build, before artifacts were ready) - Add iron rule to AGENTS.md: ask before removing data Tested: Gamma 8 (27 traces) → 27/27 VLM summaries completed --- AGENTS.md | 1 + .../API_WORKSPACE/modules/07_identity.md | 9 +- docs_v1.0/API_WORKSPACE/modules/15_tkg.md | 10 +- .../API_WORKSPACE/modules/19_people_api.md | 10 +- .../2026-08-22_vlm_summary_studio_guide.md | 139 +++ docs_v1.0/doc/07_identity.html | 17 +- docs_v1.0/doc/10_pipeline.html | 4 +- docs_v1.0/doc_developer/15_tkg.html | 12 +- docs_v1.0/doc_developer/18_profile.html | 283 +++++- docs_v1.0/doc_developer/19_people_api.html | 825 ++++++++++++++++++ .../doc_developer/21_studio_team_guide.html | 383 ++++++++ .../22_studio_pipeline_changes.html | 301 +++++++ .../23_studio_face_group_name_fix.html | 165 ++++ ...4_studio_trace_profile_read_write_bug.html | 170 ++++ .../doc_developer/25_face_filter_api.html | 679 ++++++++++++++ docs_v1.0/doc_developer/99_incomplete.html | 6 +- docs_v1.0/doc_developer/index.html | 2 +- docs_v1.0/doc_wasm/modules/07_identity.md | 9 +- docs_v1.0/doc_wasm/modules/10_pipeline.md | 2 +- docs_v1.0/doc_wasm/modules/15_tkg.md | 10 +- docs_v1.0/doc_wasm/modules/18_profile.md | 208 +++++ docs_v1.0/doc_wasm/modules/19_people_api.md | 400 +++++++++ run-server-3003.sh | 55 -- src/api/cluster_agent.rs | 76 +- src/api/face_filter.rs | 127 +-- src/api/identity_api.rs | 11 +- src/api/media_api.rs | 20 +- src/api/middleware.rs | 31 +- src/api/profile.rs | 46 +- src/bin/backfill_trace_profiles.rs | 5 +- src/bin/rebuild_trace_thumbs.rs | 70 +- src/cli/args.rs | 5 + src/core/agent/tools.rs | 5 +- src/core/processor/asrx.rs | 32 +- src/core/processor/executor.rs | 9 +- src/core/processor/tkg.rs | 40 +- src/core/progress.rs | 21 +- src/core/proxy.rs | 88 -- src/main.rs | 3 + src/processing/handlers.rs | 17 + src/worker/job_worker.rs | 80 +- test_3003_full.sh | 70 -- v1.1/run-server-3003_v1.11.sh | 28 - 43 files changed, 3993 insertions(+), 491 deletions(-) create mode 100644 docs_v1.0/M4_workspace/2026-08-22_vlm_summary_studio_guide.md create mode 100644 docs_v1.0/doc_developer/19_people_api.html create mode 100644 docs_v1.0/doc_developer/21_studio_team_guide.html create mode 100644 docs_v1.0/doc_developer/22_studio_pipeline_changes.html create mode 100644 docs_v1.0/doc_developer/23_studio_face_group_name_fix.html create mode 100644 docs_v1.0/doc_developer/24_studio_trace_profile_read_write_bug.html create mode 100644 docs_v1.0/doc_developer/25_face_filter_api.html create mode 100644 docs_v1.0/doc_wasm/modules/19_people_api.md delete mode 100755 run-server-3003.sh delete mode 100644 test_3003_full.sh delete mode 100755 v1.1/run-server-3003_v1.11.sh diff --git a/AGENTS.md b/AGENTS.md index 45819582..4e1b4d5d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,7 @@ Rust-based digital asset management system with video analysis and RAG capabilit - **🔴 DELETE / REMOVE / DROP / CLEAR 任何資料前必須先問使用者「要刪嗎?」獲得明確同意後才能執行** - **🔴 Qdrant collection 刪除、DB truncate、檔案刪除、資料清空 — 一律要先問** - **🔴 不確定是否該刪 → 先問,不要自己決定** +- **🔴 任何會移除資料的動作(unregister、DELETE、DROP、truncate、rm 檔案)都必須先詢問確認,絕對不可自行執行** - **🔴 改變議題前必須先存檔紀錄**:使用 `todowrite` 工具或建立紀錄文件(如 `docs_v1.0/M4_workspace/YYYY-MM-DD_topic_handoff.md`),確保上下文不丟失 ### 開發範圍界定 diff --git a/docs_v1.0/API_WORKSPACE/modules/07_identity.md b/docs_v1.0/API_WORKSPACE/modules/07_identity.md index 0879ce5f..3b4c28be 100644 --- a/docs_v1.0/API_WORKSPACE/modules/07_identity.md +++ b/docs_v1.0/API_WORKSPACE/modules/07_identity.md @@ -302,7 +302,9 @@ curl -s "$API/api/v1/identity/$IDENTITY_UUID/traces?page=1&page_size=3" \ "last_frame": 38127, "first_sec": 1519.0, "last_sec": 1525.1, - "avg_confidence": 0.8254 + "avg_confidence": 0.8254, + "avg_capture_quality": 0.6123, + "best_capture_quality": 0.7812 } ] } @@ -323,6 +325,8 @@ curl -s "$API/api/v1/identity/$IDENTITY_UUID/traces?page=1&page_size=3" \ | `traces[].first_sec` | float | Start time in seconds | | `traces[].last_sec` | float | End time in seconds | | `traces[].avg_confidence` | float | Average detection confidence (0.0–1.0) | +| `traces[].avg_capture_quality` | float | Average frame sharpness quality score (0.0–1.0) | +| `traces[].best_capture_quality` | float | Best frame sharpness quality score (0.0–1.0) | #### Error Responses @@ -1101,6 +1105,7 @@ PATCH /api/v1/identity/:identity_uuid This **replaces** the entire `aliases` array. To add to existing aliases, include all existing entries in the request. ---- + --- +*Updated: 2026-08-12 — identity traces include capture_quality fields (avg_capture_quality, best_capture_quality)* *Updated: 2026-07-21 — Fixed bind/unbind TKG update to match both trace_N and face_track_N external_id formats* *Updated: 2026-06-20 — Added identity files, chunks, faces, status, and JSON endpoints* diff --git a/docs_v1.0/API_WORKSPACE/modules/15_tkg.md b/docs_v1.0/API_WORKSPACE/modules/15_tkg.md index 011613ed..a5880ba0 100644 --- a/docs_v1.0/API_WORKSPACE/modules/15_tkg.md +++ b/docs_v1.0/API_WORKSPACE/modules/15_tkg.md @@ -185,7 +185,14 @@ curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/nodes" \ "properties": { "trace_id": 0, "frame_count": 142, - "avg_confidence": 0.87 + "avg_confidence": 0.87, + "best_confidence": 0.92, + "avg_capture_quality": 0.61, + "best_capture_quality": 0.78, + "key_frame": 120, + "key_face": "tkg:face/0:point_xyz", + "avg_bbox": {"x": 200, "y": 150, "width": 60, "height": 60}, + "best_bbox": {"x": 210, "y": 155, "width": 62, "height": 60} } } ] @@ -524,3 +531,4 @@ curl -X POST "$API/api/v1/file/$FILE_UUID/trace/16/merge/3" \ --- *Updated: 2026-07-21 01:00:00* +*Updated: 2026-08-12 — face_track node properties now include capture_quality fields (avg/best) and key_frame/key_face are selected by best capture quality* diff --git a/docs_v1.0/API_WORKSPACE/modules/19_people_api.md b/docs_v1.0/API_WORKSPACE/modules/19_people_api.md index cf9b5c8f..05740c8a 100644 --- a/docs_v1.0/API_WORKSPACE/modules/19_people_api.md +++ b/docs_v1.0/API_WORKSPACE/modules/19_people_api.md @@ -1,7 +1,7 @@ # People API -**Version**: 2.0 -**Date**: 2026-07-26 +**Version**: 2.1 +**Date**: 2026-08-12 **Base URL**: `http://localhost:3002` **Auth**: Requires API key header (`Authorization: Bearer `) **Doc Path**: `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md` @@ -123,7 +123,9 @@ People Search 會搜尋以下欄位(ILIKE 模糊比對): "end_time": null, "key_frame": "key_frame.jpg", "key_face": null, - "avg_confidence": 0.694 + "avg_confidence": 0.694, + "avg_capture_quality": 0.512, + "best_capture_quality": 0.733 } ], "total": 18 @@ -146,6 +148,8 @@ People Search 會搜尋以下欄位(ILIKE 模糊比對): | `key_frame` | string \| null | 關鍵幀圖片路徑 | | `key_face` | string \| null | 關鍵人臉裁切路徑 | | `avg_confidence` | float \| null | 平均偵測信心值 | +| `avg_capture_quality` | float \| null | 平均畫面品質分數(清晰度,0~1) | +| `best_capture_quality` | float \| null | 該 trace 最佳畫面品質分數 | --- diff --git a/docs_v1.0/M4_workspace/2026-08-22_vlm_summary_studio_guide.md b/docs_v1.0/M4_workspace/2026-08-22_vlm_summary_studio_guide.md new file mode 100644 index 00000000..cffc1b0d --- /dev/null +++ b/docs_v1.0/M4_workspace/2026-08-22_vlm_summary_studio_guide.md @@ -0,0 +1,139 @@ +# VLM Summary Progress — Studio Team Integration Guide + +**Date**: 2026-08-22 +**Author**: Core team +**Status**: Ready for Studio implementation + +--- + +## Overview + +VLM (Vision Language Model) summary is a new pipeline stage (P5) that generates free-text descriptions of each face trace's key frame. This guide covers how to display VLM summary progress in the Studio frontend. + +--- + +## 1. Scan Status API — New Field + +### Endpoint +``` +GET /api/v1/stats/file/:file_uuid +``` + +### New Response Field +```json +{ + "vlm_summary": { + "total": 22, + "done": 22 + } +} +``` + +| Field | Type | Description | +|-------|------|-------------| +| `total` | `i64` | Total number of face traces for this file | +| `done` | `i64` | Number of traces with VLM summary generated | + +### Usage Example +```typescript +const stats = await fetch(`/api/v1/stats/file/${fileUuid}`).then(r => r.json()); +const { total, done } = stats.vlm_summary; +const progress = total > 0 ? (done / total) * 100 : 0; +``` + +--- + +## 2. Manual VLM Trigger API + +For files that already exist but haven't had VLM summaries generated yet: + +### Endpoint +``` +POST /api/v1/file/:file_uuid/vlm-summary +``` + +### Response +```json +{ + "success": true, + "message": "VLM summary generation started for 22 traces", + "file_uuid": "9df18017960cd13919185145e59ccf3b", + "total_traces": 22, + "already_done": 0, + "pending": 22 +} +``` + +**Note**: This is non-blocking. The VLM generation runs in the background. Poll the scan status API to track progress. + +--- + +## 3. VLM Summary Content — Trace Profile API + +The actual VLM summary text is available via the trace profile endpoint: + +### Endpoint +``` +GET /api/v1/trace-profile?file_uuid=:file_uuid&trace_id=:trace_id +``` + +### Response Field +```json +{ + "vlm_summary": "The image shows a man standing indoors in front of a table with computer monitors..." +} +``` + +--- + +## 4. Suggested UI Implementation + +### Progress Indicator (in scan status / deep scan page) +``` +VLM Summary: ████████████████████ 22/22 (100%) +``` + +- Show as a progress bar within the pipeline stages +- Green when `done == total` +- Yellow/amber when `0 < done < total` +- Gray when `total == 0` (no face traces) + +### Manual Trigger Button +- Show "Generate VLM Summaries" button when `done < total` +- Disable during generation (poll until `done == total`) +- Show success message when complete + +### Trace Card Display +- Show VLM summary text as a description tooltip/card below each face trace +- Truncate to ~120 characters with "Read more" expand +- Show as part of the face trace profile modal + +--- + +## 5. Pipeline Automation + +When a new file is registered and processed: +1. Registration → Processing pipeline (CUT, ASR, ASRX, OCR, FACE) +2. Post-processing (P2 Face Tracing, P3 Face Cluster, P4 TKG Build) +3. **P5 VLM Summary** — automatically triggered after TKG Build completes +4. The `vlm_summary` progress will update in real-time via polling + +For existing files (pre-P5 deployment), use the manual trigger API. + +--- + +## 6. API Reference Summary + +| Endpoint | Method | Purpose | +|----------|--------|---------| +| `/api/v1/stats/file/:uuid` | GET | Get scan status including VLM progress | +| `/api/v1/file/:uuid/vlm-summary` | POST | Manually trigger VLM generation | +| `/api/v1/trace-profile?file_uuid=:f&trace_id=:t` | GET | Get trace profile with vlm_summary text | + +--- + +## 7. Error Handling + +- `total == 0`: File has no face traces — VLM is not applicable +- `done < total` after long wait: VLM may be running — continue polling +- API returns `success: false`: Check `message` field for error details diff --git a/docs_v1.0/doc/07_identity.html b/docs_v1.0/doc/07_identity.html index d8ec1abe..7bc2b8b7 100644 --- a/docs_v1.0/doc/07_identity.html +++ b/docs_v1.0/doc/07_identity.html @@ -492,7 +492,9 @@ curl -s -X "last_frame": 38127, "first_sec": 1519.0, "last_sec": 1525.1, - "avg_confidence": 0.8254 + "avg_confidence": 0.8254, + "avg_capture_quality": 0.6123, + "best_capture_quality": 0.7812 } ] } @@ -572,6 +574,16 @@ curl -s -X float Average detection confidence (0.0–1.0) + +traces[].avg_capture_quality +float +Average frame sharpness quality score (0.0–1.0) + + +traces[].best_capture_quality +float +Best frame sharpness quality score (0.0–1.0) +

Error Responses

@@ -1738,7 +1750,8 @@ curl -s -X

This replaces the entire aliases array. To add to existing aliases, include all existing entries in the request.


-

Updated: 2026-07-21 — Fixed bind/unbind TKG update to match both trace_N and face_track_N external_id formats +

Updated: 2026-08-12 — identity traces include capture_quality fields (avg_capture_quality, best_capture_quality) +Updated: 2026-07-21 — Fixed bind/unbind TKG update to match both trace_N and face_track_N external_id formats Updated: 2026-06-20 — Added identity files, chunks, faces, status, and JSON endpoints

diff --git a/docs_v1.0/doc/10_pipeline.html b/docs_v1.0/doc/10_pipeline.html index a1f7f6f4..c9a6c208 100644 --- a/docs_v1.0/doc/10_pipeline.html +++ b/docs_v1.0/doc/10_pipeline.html @@ -333,8 +333,8 @@ a { color: #0066cc; } -/api/v1/search/persons -universal_search.rs (not mounted) +/api/v1/search/people +universal_search.rs (mounted) /api/v1/who diff --git a/docs_v1.0/doc_developer/15_tkg.html b/docs_v1.0/doc_developer/15_tkg.html index 84edca1d..7913814c 100644 --- a/docs_v1.0/doc_developer/15_tkg.html +++ b/docs_v1.0/doc_developer/15_tkg.html @@ -377,7 +377,14 @@ curl -s -X "properties": { "trace_id": 0, "frame_count": 142, - "avg_confidence": 0.87 + "avg_confidence": 0.87, + "best_confidence": 0.92, + "avg_capture_quality": 0.61, + "best_capture_quality": 0.78, + "key_frame": 120, + "key_face": "tkg:face/0:point_xyz", + "avg_bbox": {"x": 200, "y": 150, "width": 60, "height": 60}, + "best_bbox": {"x": 210, "y": 155, "width": 62, "height": 60} } } ] @@ -909,7 +916,8 @@ curl -X DELETE
-

Updated: 2026-07-21 01:00:00

+

Updated: 2026-07-21 01:00:00 +Updated: 2026-08-12 — face_track node properties now include capture_quality fields (avg/best) and key_frame/key_face are selected by best capture quality

\ No newline at end of file diff --git a/docs_v1.0/doc_developer/18_profile.html b/docs_v1.0/doc_developer/18_profile.html index 5a1d0b8a..b82281fe 100644 --- a/docs_v1.0/doc_developer/18_profile.html +++ b/docs_v1.0/doc_developer/18_profile.html @@ -37,6 +37,127 @@ a { color: #0066cc; }

Profile Management

Endpoints for managing trace profiles (face track metadata stored in TKG) and file profiles (video metadata stored in PostgreSQL).

+
+

Terminology

+

Core Concepts

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TermDefinitionIdentifierDisplay Format
FaceA single human face detection on one frameface_idUsually not displayed
Face Sequence (Trace)A collection of faces across multiple frames representing the same persontrace_idFS#233
Face GroupA collection of traces sharing the same name/labellabel (string)"Person A"
+

Data Model Hierarchy

+
Video
+  └── Frame (F#233, F#234, ...)           ← Single frame number
+       └── Face                            ← Single detection (bbox + confidence)
+            └── Face Sequence / Trace      ← Same person across frames (FS#233)
+                 └── Face Group            ← Multiple traces with same name
+
+ +

Example

+
Video: "interview.mp4"
+  ├── Frame F#100
+  │    └── Face (bbox: {100, 200, 50, 50}, confidence: 0.95)
+  ├── Frame F#105
+  │    └── Face (bbox: {110, 205, 48, 48}, confidence: 0.92)
+  ├── Frame F#110
+  │    └── Face (bbox: {115, 210, 52, 52}, confidence: 0.88)
+  ...
+
+Face Sequence FS#233 = [Face@F#100, Face@F#105, Face@F#110, ...]
+  ↓
+Face Group "Person A" = [FS#233, FS#234, FS#235]
+
+ +

Storage

+ + + + + + + + + + + + + + + + + + + + + + + + + +
EntityStorageTable/Collection
FaceQdrant_faces collection
Face Sequence / TracePostgreSQL (TKG)tkg_nodes where node_type='face_track'
Face GroupPostgreSQL (TKG)tkg_nodes.label field
+

Operations

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperationLevelAPI
View facesFaceInternal (embedded in trace data)
Merge tracesTracePOST /api/v1/trace/:file_uuid/merge
Rename groupGroupPUT /api/v1/trace-profile/group
Merge groupsGroupPOST /api/v1/file/:file_uuid/groups/merge
+

Naming Convention

+
    +
  • Frame: F#{number} — e.g., F#233
  • +
  • Face Sequence / Trace: FS#{number} — e.g., FS#233
  • +
  • Face Group: String name — e.g., "Person A", "Speaker 1"
  • +

GET /api/v1/trace-profile

Auth: Required Scope: file-level

@@ -296,6 +417,165 @@ a { color: #0066cc; } } +
+

POST /api/v1/file/:file_uuid/groups/merge

+

Auth: Required +Scope: file-level

+

Merge multiple face groups into one target group. All traces from source groups are reassigned to the target group name.

+

Request Body

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldTypeRequiredDescription
file_uuidstringYesFile UUID
source_groupsstring[]YesList of group names to merge from
target_group_namestringYesTarget group name to merge into
+

Examples

+

Merge 2 groups:

+
curl -s -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \
+  -H "X-API-Key: $KEY" \
+  -H "Content-Type: application/json" \
+  -d '{
+    "file_uuid": "c36f35685177c981aa139b66bbbccc5b",
+    "source_groups": ["Person A"],
+    "target_group_name": "Person B"
+  }'
+
+ +

Merge 4 groups:

+
curl -s -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \
+  -H "X-API-Key: $KEY" \
+  -H "Content-Type: application/json" \
+  -d '{
+    "file_uuid": "c36f35685177c981aa139b66bbbccc5b",
+    "source_groups": ["Person A", "Person C", "Person D"],
+    "target_group_name": "Person B"
+  }'
+
+ +

Response (200)

+
{
+  "success": true,
+  "file_uuid": "c36f35685177c981aa139b66bbbccc5b",
+  "source_groups": ["Person A", "Person C", "Person D"],
+  "target_group_name": "Person B",
+  "traces_merged": 12,
+  "message": "Merged 3 group(s) into 'Person B'"
+}
+
+ +

Error Responses

+ + + + + + + + + + + + + + + + + + + + + +
HTTPCondition
400Target group in source_groups list
400Empty source_groups array
500Database error
+

Behavior

+
    +
  1. Find all traces with label IN (source_groups)
  2. +
  3. Update their labels to target_group_name
  4. +
  5. All source groups disappear (no traces left)
  6. +
  7. Target group contains all traces from merged groups
  8. +
+
+

Merging Groups: Two Methods

+

Method 1: Use Merge Groups API (Recommended)

+
POST /api/v1/file/:file_uuid/groups/merge
+{
+  "file_uuid": "...",
+  "source_groups": ["Person A", "Person C"],
+  "target_group_name": "Person B"
+}
+
+ +

Pros: Simple, only requires group names, supports multi-group merge +Cons: New API (requires backend update)

+

Method 2: Use Batch Update API (Existing)

+
PUT /api/v1/trace-profile/group
+{
+  "file_uuid": "...",
+  "trace_ids": [13, 14, 15, 43, 44],
+  "name": "Person B"
+}
+
+ +

Pros: Works with existing API +Cons: Frontend must collect all trace_ids from both groups

+

Example: Merge Group A and C into Group B

+

Before:

+
Group A: [13, 14, 15]
+Group B: [43, 44]
+Group C: [67, 68]
+
+ +

Method 1 (Recommended):

+
curl -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \
+  -H "X-API-Key: $KEY" \
+  -H "Content-Type: application/json" \
+  -d '{
+    "file_uuid": "c36f35685177c981aa139b66bbbccc5b",
+    "source_groups": ["Person A", "Person C"],
+    "target_group_name": "Person B"
+  }'
+
+ +

Method 2 (Existing API):

+
curl -X PUT "$API/api/v1/trace-profile/group" \
+  -H "X-API-Key: $KEY" \
+  -H "Content-Type: application/json" \
+  -d '{
+    "file_uuid": "c36f35685177c981aa139b66bbbccc5b",
+    "trace_ids": [13, 14, 15, 43, 44, 67, 68],
+    "name": "Person B"
+  }'
+
+ +

After:

+
Group A: [] (disappeared)
+Group B: [43, 44, 13, 14, 15, 67, 68]
+Group C: [] (disappeared)
+
+

GET /api/v1/file-profile

Auth: Required @@ -505,7 +785,8 @@ a { color: #0066cc; }


-

Updated: 2026-07-21 — Fixed external_id matching (trace_N + face_track_N formats), fixed parameter ordering in UPDATE query +

Updated: 2026-07-25 — Added Merge Groups API (POST /groups/merge), added Terminology section (Face, Face Sequence, Face Group) +Updated: 2026-07-21 — Fixed external_id matching (trace_N + face_track_N formats), fixed parameter ordering in UPDATE query Updated: 2026-07-18 — New profile module: trace-profile (GET, PUT, PUT group) and file-profile (GET, PUT)

diff --git a/docs_v1.0/doc_developer/19_people_api.html b/docs_v1.0/doc_developer/19_people_api.html new file mode 100644 index 00000000..257471b7 --- /dev/null +++ b/docs_v1.0/doc_developer/19_people_api.html @@ -0,0 +1,825 @@ + + + + +19 People Api - Momentry API Docs + + + +
+ +

People API

+

Version: 2.1
+Date: 2026-08-12
+Base URL: http://localhost:3002
+Auth: Requires API key header (Authorization: Bearer <api_key>)
+Doc Path: /Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md

+
+

資料架構

+

trace_profiles(PostgreSQL — People Search 專用)

+

每筆 file_uuid + trace_id 對應一個 face trace profile:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
欄位類型說明
file_uuidstring影片 UUID
trace_idintegerFace trace ID(8Hz 取樣追蹤)
namestringFS name(Face 頁面顯示 + People Search 搜尋)
start_frameinteger起始 frame
end_frameinteger結束 frame
frame_countinteger追蹤 frame 數(8Hz 取樣,多數 > 1)
key_framestring關鍵幀圖片路徑
key_facestring關鍵人臉裁切路徑
avg_confidencefloat平均偵測信心值
statusstring狀態(pending/confirmed)
+

可搜尋註記(metadata / VLM 欄位)

+

trace_profiles 包含 VLM 產生的註記,可用於進階搜尋和統計:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
欄位類型說明
vlm_descriptiontextVLM 人物外貌描述
vlm_clothingtextVLM 衣著描述
vlm_tagstext[]VLM 標籤陣列
vlm_locationstringVLM 地點
vlm_settingstringVLM 場景設定
vlm_lightingstringVLM 光線
vlm_weatherstringVLM 天氣
vlm_backgroundtextVLM 背景描述
vlm_bg_tagstext[]VLM 背景標籤
+

tkg_nodes(PostgreSQL — TKG 圖譜專用,與 profile 獨立)

+ + + + + + + + + + + + + + + + + + + + + +
欄位說明
external_id如 "trace_9",對應 trace_profiles.trace_id
labelTKG 圖譜節點標籤(與 trace_profiles.name 獨立)
propertiesTKG 節點屬性
+

_faces(Qdrant — Face 向量比對)

+

Face embedding 向量存在 Qdrant _faces collection,可用作 seed 比對:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Payload 欄位類型說明
file_uuidstring影片 UUID
trace_idintegerFace trace ID
identity_idinteger | null已綁定的 identity ID
frameintegerFrame 編號
embeddingvector[512]FaceNet 512-d embedding
bboxobject人臉 bbox(x, y, width, height)
confidencefloat偵測信心值
+
+

1. GET /api/v1/search/people

+

搜尋已命名的 face trace profiles。回傳符合 name 的卡片列表。

+

Query Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeRequiredDescription
querystring✅ Yes搜尋關鍵字(ILIKE 模糊比對 trace_profiles.name)
file_uuidstring❌ Optional限制搜尋範圍
limitinteger❌ Optional回傳筆數上限(預設 10)
+

Example Request

+
# 搜尋名字
+curl -X GET "http://localhost:3002/api/v1/search/people?query=Susan"
+
+# 搜尋 VLM 註記(衣著、地點、標籤)
+curl -X GET "http://localhost:3002/api/v1/search/people?query=blue+shirt"
+
+# 限定影片
+curl -X GET "http://localhost:3002/api/v1/search/people?file_uuid=abc123&query=Tom"
+
+ +

搜尋範圍

+

People Search 會搜尋以下欄位(ILIKE 模糊比對):

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
欄位說明
nameFS name
vlm_descriptionVLM 人物外貌描述
vlm_clothingVLM 衣著描述
vlm_tagsVLM 標籤陣列
vlm_locationVLM 地點
vlm_settingVLM 場景設定
+

Response

+
{
+  "people": [
+    {
+      "file_uuid": "4655a0ab3c077e30c12b2298c2750650",
+      "file_name": "",
+      "trace_id": 9,
+      "external_id": "trace_9",
+      "name": "Susan",
+      "start_frame": 118,
+      "end_frame": 384,
+      "frame_count": 39,
+      "start_time": null,
+      "end_time": null,
+      "key_frame": "key_frame.jpg",
+      "key_face": null,
+      "avg_confidence": 0.694,
+      "avg_capture_quality": 0.512,
+      "best_capture_quality": 0.733
+    }
+  ],
+  "total": 18
+}
+
+ +

Response Fields

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldTypeDescription
file_uuidstring影片 UUID
trace_idintegerFace trace ID
external_idstring | nullTKG node external_id(如 "trace_9")
namestring | null使用者命名的 FS name
start_frameinteger | null起始 frame
end_frameinteger | null結束 frame
frame_countinteger | null追蹤 frame 數(8Hz 取樣)
start_timefloat | null起始時間(秒)
end_timefloat | null結束時間(秒)
key_framestring | null關鍵幀圖片路徑
key_facestring | null關鍵人臉裁切路徑
avg_confidencefloat | null平均偵測信心值
avg_capture_qualityfloat | null平均畫面品質分數(清晰度,0~1)
best_capture_qualityfloat | null該 trace 最佳畫面品質分數
+
+

2. POST /api/v1/search/universal

+

統一搜尋。設定 types: ["people"] 搜尋人物,或組合 "chunk"、"frame"。

+

People Search 會搜尋 trace_profiles 的 name + vlm_* 欄位: +- name — FS name +- vlm_description — VLM 人物外貌描述 +- vlm_clothing — VLM 衣著描述 +- vlm_tags — VLM 標籤陣列 +- vlm_location — VLM 地點 +- vlm_setting — VLM 場景設定

+

Request Body

+
{
+  "query": "Susan",
+  "file_uuid": "abc123",
+  "types": ["people"],
+  "page": 1,
+  "page_size": 20
+}
+
+ +

Request Fields

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldTypeRequiredDescription
querystring✅ Yes搜尋關鍵字
file_uuidstring❌ Optional限制搜尋範圍
typesstring[]❌ Optional["chunk", "frame", "people"] — 預設全部
pageinteger❌ Optional頁碼(預設 1)
page_sizeinteger❌ Optional每頁筆數(預設 20,最大 200)
+

Response

+
{
+  "query": "Susan",
+  "results": [
+    {
+      "type": "person",
+      "file_uuid": "4655a0ab3c077e30c12b2298c2750650",
+      "trace_id": 9,
+      "external_id": "trace_9",
+      "name": "Susan",
+      "frame_count": 39,
+      "score": 0.95,
+      "start_time": null,
+      "end_time": null,
+      "key_frame": "key_frame.jpg",
+      "key_face": null
+    }
+  ],
+  "total": 18,
+  "page": 1,
+  "page_size": 20,
+  "has_more": false
+}
+
+ +
+

3. PUT /api/v1/trace-profile(單筆改名)

+

更新單一 face trace profile 的 name 和 metadata。

+

Request Body

+
{
+  "file_uuid": "4655a0ab3c077e30c12b2298c2750650",
+  "trace_id": 9,
+  "name": "Susan",
+  "properties": { "custom_key": "custom_value" },
+  "key_frame": "path/to/key_frame.jpg",
+  "key_face": "path/to/key_face.jpg",
+  "aliases": ["Susie", "Sue"]
+}
+
+ +

Request Fields

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldTypeRequiredDescription
file_uuidstring✅ Yes影片 UUID
trace_idinteger✅ YesFace trace ID
namestring❌ Optional新的 FS name
propertiesobject❌ Optional自訂屬性(合併更新)
key_framestring❌ Optional關鍵幀路徑
key_facestring❌ Optional關鍵人臉路徑
aliasesstring[]❌ Optional別名列表
+
+

4. PUT /api/v1/trace-profile/group(批次改名)

+

批次更新多個 face trace profiles 的 name。

+

Request Body

+
{
+  "file_uuid": "4655a0ab3c077e30c12b2298c2750650",
+  "trace_ids": [9, 22, 5],
+  "name": "Susan"
+}
+
+ +
+

5. POST /api/v1/groups/merge(合併群組)

+

將多個 group 的 traces 合併為一個 group name。

+

Request Body

+
{
+  "file_uuid": "4655a0ab3c077e30c12b2298c2750650",
+  "source_groups": ["Person_0", "Person_1"],
+  "target_group_name": "Susan"
+}
+
+ +
+

Error Responses

+

400 Bad Request

+
{ "error": "name is required" }
+
+ +

401 Unauthorized

+
HTTP 401 (no body) — Missing or invalid API key
+
+ +

404 Not Found

+
{ "error": "Profile not found" }
+
+ +

500 Internal Server Error

+
{ "error": "DB error: connection refused" }
+
+ +
+

如何命名 Face Trace

+

使用 profile API 為 face trace 命名:

+
curl -X PUT "http://localhost:3002/api/v1/trace-profile" \
+  -H "Authorization: Bearer <api_key>" \
+  -H "Content-Type: application/json" \
+  -d '{
+    "file_uuid": "4655a0ab3c077e30c12b2298c2750650",
+    "trace_id": 9,
+    "name": "Susan"
+  }'
+
+ +

命名後即可透過 People Search API 搜尋:

+
curl "http://localhost:3002/api/v1/search/people?query=Susan" \
+  -H "Authorization: Bearer <api_key>"
+
+ +
+

Pipeline 狀態定義

+

所有檔案的 status 由 /api/v1/file/{file_uuid}/sync-status 自動更新,依據 processor outputs 和功能就緒狀態判定。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Status前端顯示條件啟用功能
registered📋 已註冊0 processor outputs檔案註冊
scanning🔍 掃描中1-4/5 processor outputs—
keyword_ready🔎 關鍵字可用sentence chunks > 0Smart Search
semantic_ready🧠 語意可用embedded chunks > 0Semantic Search
face_mgmt_ready🎭 臉部管理可用face_trace + trace_profiles + tkg_nodes(face_track)People Search, Face Profile 讀寫, Face Group
agent_ready🤖 Agent 可用face_mgmt_ready + tkg_edgesAgent TKG Tools
completed✅ 完成5/5 processors + 全部功能就緒—
+

Face Management Ready 明確定義

+

face_mgmt_ready 表示檔案已具備完整臉部管理功能,需同時滿足以下四個條件:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
依賴項檢查條件說明提供功能
Face Qdrant Ready_faces collection 有 face pointsFace embeddings 已存入 Qdrant臉部比對、相似度搜尋
Face Trace Readyface_traced.json 存在且有 tracesFace tracking 已完成人臉軌跡資料
Face Profile Readytrace_profiles 有紀錄Profile 資料已建立名字、VLM 註記、key_frame/key_face
Face TKG Node Readytkg_nodes 有 face_track nodesTKG 圖譜節點已建立臉部群組合併、關係查詢
+

檢查 SQL

+
-- Face Qdrant Ready
+SELECT COUNT(*) FROM _faces WHERE file_uuid = $1;  -- > 0
+
+-- Face Trace Ready
+-- 檢查 face_traced.json 檔案存在且有 traces
+
+-- Face Profile Ready
+SELECT COUNT(*) FROM trace_profiles WHERE file_uuid = $1;  -- > 0
+
+-- Face TKG Node Ready
+SELECT COUNT(*) FROM tkg_nodes WHERE file_uuid = $1 AND node_type = 'face_track';  -- > 0
+
+ +

啟用功能清單

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能API Endpoint說明
People SearchGET /api/v1/search/people搜尋已命名人臉
Face Profile 讀寫PUT /api/v1/trace-profile更新名字、VLM 註記
Face Group 合併POST /api/v1/groups/merge合併多個群組
Face Trace 改名PUT /api/v1/trace-profile為單個 trace 命名
Agent Face SearchAgent Tool: face_profile_searchAgent 搜尋人臉
+
+

狀態依賴關係

+
registered → scanning → keyword_ready → semantic_ready
+                                         ↓
+                              face_mgmt_ready → agent_ready → completed
+
+ +

每個階段對應的 Processor

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
階段必要 Processor產出
keyword_readyASR, ASRXsentence chunks
semantic_readykeyword_ready + Vectorizeembedded chunks
face_mgmt_readyFace, FaceClustertrace_profiles (People Search + Face Management)
agent_readyface_mgmt_ready + TKG Edgestkg_edges
+
+ + \ No newline at end of file diff --git a/docs_v1.0/doc_developer/21_studio_team_guide.html b/docs_v1.0/doc_developer/21_studio_team_guide.html new file mode 100644 index 00000000..e0db1dd8 --- /dev/null +++ b/docs_v1.0/doc_developer/21_studio_team_guide.html @@ -0,0 +1,383 @@ + + + + +21 Studio Team Guide - Momentry API Docs + + + +
+ +

Studio Team API 變更指南

+

Version: 1.0
+Date: 2026-07-26
+Doc Path: /Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md
+目標: 通知 Studio team 後端 API 狀態欄位變更,Momentry Studio 前端需配合更新

+
+

1. 概述

+

後端已將檔案狀態從技術術語改為功能導向名稱。Studio team 的 ~/momentry_studio/ 前端顯示邏輯需要更新。

+

影響範圍: +- 後端 API:/Users/accusys/momentry_core/src/api/files.rs(Core team 已修改) +- Studio 前端:~/momentry_studio/(需 Studio team 更新)

+
+

2. 團隊職責

+ + + + + + + + + + + + + + + + + + + + + + + + + +
團隊負責專案目錄
Core teamMomentry Core 後端~/momentry_core/
Studio teamMomentry Studio 前端~/momentry_studio/
Marcom teamWordPress 網站/Users/accusys/wordpress/
+
+

3. API 變更

+

/api/v1/file/{file_uuid}/sync-status 回傳格式

+

POST /api/v1/file/{file_uuid}/sync-status

+
{
+  "success": true,
+  "file_uuid": "4655a0ab3c077e30c12b2298c2750650",
+  "status": "face_mgmt_ready",
+  "processors_complete": 4,
+  "processors_total": 5,
+  "worker": {
+    "has_job": true,
+    "job_status": "pending",
+    "current_processor": null,
+    "progress_total": 7,
+    "progress_current": 7,
+    "completed_processors": ["cut", "asr", "face", "ocr", "pose", "asrx", "face_cluster"],
+    "failed_processors": [],
+    "updated_at": "2026-07-24T21:26:06"
+  }
+}
+
+ +

無 job 的檔案:

+
{
+  "success": true,
+  "file_uuid": "...",
+  "status": "registered",
+  "processors_complete": 0,
+  "processors_total": 5,
+  "worker": {
+    "has_job": false
+  }
+}
+
+ +

Worker 狀態說明

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
欄位說明
has_job是否有 monitor_job 紀錄
job_statuspending / running / completed / failed
current_processor目前正在執行的 processor
progress_total總 processor 數量
progress_current已完成的 processor 數量
completed_processors已完成的 processor 列表
failed_processors失敗的 processor 列表
updated_at最後更新時間
+

使用者可區分的情境

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
情境job_statuscurrent_processor顯示建議
正在處理runningface🔄 正在執行 Face
排隊等待pendingnull⏳ 等待處理
已完成completednull✅ Processor 完成
處理失敗failedface❌ Face 失敗
從未提交has_job=false-📋 僅註冊
+

新狀態清單

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Status中文顯示圖示說明
registered已註冊📋0 processor outputs
scanning掃描中🔍1-4/5 processor outputs
keyword_ready關鍵字可用🔎sentence chunks > 0
semantic_ready語意可用🧠embedded chunks > 0
face_mgmt_ready臉部管理可用🎭trace_profiles + tkg_nodes > 0
agent_readyAgent 可用🤖tkg_edges > 0
completed已完成✅全部就緒
+

已移除的舊狀態

+ + + + + + + + + + + + + + + + + +
舊狀態新狀態
pendingregistered
processingscanning
+
+

4. Studio 前端需修改項目

+

4.1 狀態顯示邏輯

+

位置: ~/momentry_studio/ 中處理檔案狀態顯示的元件

+

修改前:

+
switch (file.status) {
+  case 'completed': return '✅ 已完成';
+  case 'processing': return '🔄 處理中';
+  case 'pending': return '⏳ 待處理';
+  default: return '📦 未註冊';
+}
+
+ +

修改後:

+
const statusMap = {
+  completed:       { label: '已完成', icon: '✅', color: 'green' },
+  agent_ready:     { label: 'Agent 可用', icon: '🤖', color: 'orange' },
+  face_mgmt_ready: { label: '臉部管理可用', icon: '🎭', color: 'cyan' },
+  semantic_ready:  { label: '語意可用', icon: '🧠', color: 'purple' },
+  keyword_ready:   { label: '關鍵字可用', icon: '🔎', color: 'green' },
+  scanning:        { label: '掃描中', icon: '🔍', color: 'blue' },
+  registered:      { label: '已註冊', icon: '📋', color: 'gray' },
+};
+
+const display = statusMap[file.status] || { label: '未註冊', icon: '📦', color: 'gray' };
+return `${display.icon} ${display.label}`;
+
+ +

4.2 狀態過濾選項

+

位置: ~/momentry_studio/ 中檔案列表過濾元件

+

移除: pending, processing
+新增: registered, scanning, keyword_ready, semantic_ready, face_mgmt_ready, agent_ready

+
+

5. Face Management Ready 明確定義

+

face_mgmt_ready 表示檔案已具備完整臉部管理功能,需同時滿足以下四個條件:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
依賴項檢查條件說明
Face Qdrant Ready_faces collection 有 face pointsFace embeddings 已存入 Qdrant
Face Trace Readyface_traced.json 存在且有 tracesFace tracking 已完成
Face Profile Readytrace_profiles 有紀錄Profile 資料已建立
Face TKG Node Readytkg_nodes 有 face_track nodesTKG 圖譜節點已建立
+
+

6. 狀態依賴關係

+
registered → scanning → keyword_ready → semantic_ready
+                                         ↓
+                              face_mgmt_ready → agent_ready → completed
+
+ +
+

7. 測試 API

+
# 取得所有檔案
+curl http://localhost:3002/api/v1/files \
+  -H "Authorization: Bearer <api_key>"
+
+# 觸發狀態同步
+curl -X POST http://localhost:3002/api/v1/file/{file_uuid}/sync-status \
+  -H "Authorization: Bearer <api_key>"
+
+ +
+

8. 參考文件

+ + + + + + + + + + + + + + + + + + + + + + + + + +
文件完整路徑
People API/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md
Status Unification/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/20_status_unification.md
Studio Team Guide/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md
AGENTS.md/Users/accusys/momentry_core/AGENTS.md
+
+ + \ No newline at end of file diff --git a/docs_v1.0/doc_developer/22_studio_pipeline_changes.html b/docs_v1.0/doc_developer/22_studio_pipeline_changes.html new file mode 100644 index 00000000..c8fe6623 --- /dev/null +++ b/docs_v1.0/doc_developer/22_studio_pipeline_changes.html @@ -0,0 +1,301 @@ + + + + +22 Studio Pipeline Changes - Momentry API Docs + + + +
+ +

Studio Team 配套修改指南

+

Version: 1.0
+Date: 2026-07-26
+Doc Path: /Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_studio_pipeline_changes.md
+目標: 通知 Studio team 後端 Pipeline 狀態變更,前端需配合更新

+
+

1. 概述

+

後端已完成以下修改: +1. 移除 identity_agent,替換為 face_dedup(Face Deduplication) +2. 重構 sync_file_status 邏輯:檢查 JSON 存在 + DB 一致性 +3. Pipeline 進度階段重新分配

+

影響範圍: +- 檔案狀態顯示(status) +- Pipeline 進度顯示(progress stages) +- 統計 API 回傳格式

+
+

2. 檔案狀態變更

+

新狀態清單

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Status中文顯示圖示說明
registered已註冊📋尚未開始處理
scanning掃描中🔍處理中(JSON 存在但 DB 不一致)
completed已完成✅所有 processor 完成且 DB 一致
agent_readyAgent 可用🤖TKG edges 存在
+

已移除的狀態

+ + + + + + + + + + + + + + + + + + + + + + + + + +
舊狀態新狀態說明
processingscanning更明確表示正在處理
pendingregistered尚未開始
face_mgmt_readycompleted最終狀態統一為 completed
+

狀態判斷邏輯

+ + + + + + + + + + + + + + + + + + + + + + + + + +
條件狀態
所有 JSON 存在且 DB 一致completed
部分 JSON 存在但不一致scanning
無 JSON 存在registered
TKG edges 存在agent_ready
+
+

3. Pipeline 進度階段變更

+

修改前(7 個 stage)

+
Processors (30%) → Rule1 (5%) → Face Tracing (5%) → identity_agent (10%) → TKG Nodes (20%) → TKG Edges (15%) → Rule2 (15%)
+
+ +

修改後(7 個 stage)

+
Processors (30%) → Rule1 (5%) → Face Tracing (5%) → face_dedup (10%) → TKG Nodes (20%) → TKG Edges (15%) → Rule2 (15%)
+
+ +

需要修改的前端元件

+ + + + + + + + + + + + + + + + + + + + + +
元件修改內容
Pipeline Progress Bar移除 identity_agent,新增 face_dedup
Stage Labels更新 stage 名稱
Overall Progress重新計算權重
+
+

4. API 變更

+

/api/v1/file/{file_uuid}/sync-status

+

回傳格式變更:

+

修改前:

+
{
+  "status": "face_mgmt_ready",
+  "processors_complete": 5,
+  "processors_total": 5,
+  "worker": { ... }
+}
+
+ +

修改後:

+
{
+  "success": true,
+  "file_uuid": "...",
+  "status": "completed",
+  "processors": {
+    "asr": { "json_exists": true, "consistent": true },
+    "asrx": { "json_exists": true, "consistent": true },
+    "ocr": { "json_exists": true, "consistent": true },
+    "pose": { "json_exists": true, "consistent": true },
+    "cut": { "json_exists": true, "consistent": true },
+    "face": { "json_exists": true, "consistent": true },
+    "face_cluster": { "json_exists": true, "consistent": true }
+  },
+  "worker": { ... }
+}
+
+ +

/api/v1/file/{file_uuid}/stats

+

回傳格式變更:

+

修改前:

+
{
+  "identity_agent": {
+    "clusters": 0,
+    "identities_created": 0,
+    "tmdb_matches": 0,
+    "speaker_bindings": 0,
+    "confirmations": 0
+  }
+}
+
+ +

修改後:

+
{
+  "face_dedup": {
+    "clusters": 5,
+    "face_tracks": 24,
+    "consistent": true
+  }
+}
+
+ +
+

5. Studio 前端需修改項目

+

5.1 狀態顯示邏輯

+

位置: Studio 前端檔案列表元件

+

修改前:

+
const statusLabels = {
+  'completed': '✅ 已完成',
+  'processing': '🔄 處理中',
+  'pending': '⏳ 待處理',
+  'face_mgmt_ready': '🎭 臉部管理可用',
+  'agent_ready': '🤖 Agent 可用'
+};
+
+ +

修改後:

+
const statusLabels = {
+  'completed': '✅ 已完成',
+  'scanning': '🔍 掃描中',
+  'registered': '📋 已註冊',
+  'agent_ready': '🤖 Agent 可用'
+};
+
+ +

5.2 Pipeline 進度顯示

+

位置: Studio 前端 Pipeline Progress 元件

+

修改項目: +1. 移除 identity_agent stage +2. 新增 face_dedup stage +3. 更新 stage 名稱映射

+

5.3 統計面板

+

位置: Studio 前端檔案統計面板

+

修改項目: +1. 移除 Identity Agent 區塊 +2. 新增 Face Deduplication 區塊 +3. 顯示欄位:clusters, face_tracks, consistent

+
+

6. 測試清單

+
    +
  • [ ] 檔案列表狀態顯示正確
  • +
  • [ ] Pipeline 進度階段正確顯示
  • +
  • [ ] Overall Progress 計算正確
  • +
  • [ ] 統計面板 Face Dedup 區塊顯示正確
  • +
  • [ ] sync-status API 回傳格式解析正確
  • +
  • [ ] stats API 回傳格式解析正確
  • +
+
+

7. 參考文件

+ + + + + + + + + + + + + + + + + + + + + +
文件完整路徑
Studio Team Guide/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md
People API/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md
Pipeline Changes/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_studio_pipeline_changes.md
+
+ + \ No newline at end of file diff --git a/docs_v1.0/doc_developer/23_studio_face_group_name_fix.html b/docs_v1.0/doc_developer/23_studio_face_group_name_fix.html new file mode 100644 index 00000000..7fd482d7 --- /dev/null +++ b/docs_v1.0/doc_developer/23_studio_face_group_name_fix.html @@ -0,0 +1,165 @@ + + + + +23 Studio Face Group Name Fix - Momentry API Docs + + + +
+ +

Studio Fix: Face Group Name 讀寫不一致

+

Date: 2026-07-27 +Author: Studio Team +Status: ✅ 已修復並部署

+
+

問題描述

+

Studio 前端在 Face 頁面 rename group name 後,離開再回來時名稱未更新。但 People Search 可以查到新名稱。

+

根因

+

寫入和讀取走了不同的資料來源:

+ + + + + + + + + + + + + + + + + + + + +
操作API Endpoint實際讀寫欄位
寫入 (rename)PUT /api/v1/trace-profile/grouptrace_profiles.name
讀取 (卡片顯示)GET /api/v1/file/:uuid/face-groupstkg_nodes.label
+

trace_profiles.name 和 tkg_nodes.label 是兩張獨立的表/欄位(見 19_people_api.md),rename 只更新了 trace_profiles.name,但卡片顯示讀的是 tkg_nodes.label。

+
+

修復內容

+

修改檔案

+

/Users/accusys/momentry_core/src/api/profile.rs — get_face_groups_handler (line 552-591)

+

改前 SQL

+
SELECT label, properties FROM tkg_nodes
+WHERE file_uuid = $1 AND node_type = 'face_track'
+ORDER BY (properties->>'trace_id')::int
+
+ +

改後 SQL

+
SELECT COALESCE(tp.name, tn.label) as name, tn.properties
+FROM tkg_nodes tn
+LEFT JOIN trace_profiles tp ON tp.file_uuid = tn.file_uuid
+    AND tp.trace_id = (tn.properties->>'trace_id')::int
+WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track'
+ORDER BY (tn.properties->>'trace_id')::int
+
+ +

Rust 程式碼變更

+
 pub async fn get_face_groups_handler(...) {
+     let tkg_table = schema::table_name("tkg_nodes");
++    let tp_table = schema::table_name("trace_profiles");
+
+     let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&format!(
+-        "SELECT label, properties FROM {} \
+-         WHERE file_uuid = $1 AND node_type = 'face_track' \
+-         ORDER BY (properties->>'trace_id')::int",
+-        tkg_table
++        "SELECT COALESCE(tp.name, tn.label) as name, tn.properties \
++         FROM {} tn \
++         LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
++             AND tp.trace_id = (tn.properties->>'trace_id')::int \
++         WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
++         ORDER BY (tn.properties->>'trace_id')::int",
++        tkg_table, tp_table
+     ))
+     ...
+-    for (label, properties) in rows {
++    for (name, properties) in rows {
+         ...
+-        if label.starts_with("Face Trace ") || label.starts_with("Trace ") {
++        if name.starts_with("Face Trace ") || name.starts_with("Trace ") {
+             unassigned.push(trace_id);
+         } else {
+-            groups.entry(label).or_default().push(trace_id);
++            groups.entry(name).or_default().push(trace_id);
+         }
+     }
+ }
+
+ +
+

影響範圍

+ + + + + + + + + + + + + + + + + + + + + + + + + +
項目影響
Face 頁面卡片顯示✅ 現在從 trace_profiles.name 讀取,rename 後立即生效
People Search不受影響(本來就查 trace_profiles.name)
未命名 traces不受影響(COALESCE fallback 到 tkg_nodes.label,如 Person_0)
Cluster Agent 初始化不受影響(初始化時兩邊都寫入相同值)
+
+

注意事項(給 Core Team)

+
    +
  1. 未來如果有需要同時更新 tkg_nodes.label 的情境(例如 graph 顯示需要),請注意 PUT /api/v1/trace-profile/group 目前只更新 trace_profiles.name
  2. +
  3. 建議:如果 tkg_nodes.label 和 trace_profiles.name 應該保持一致,可以考慮:
  4. +
  5. 方案 A(目前做法):讀取端用 COALESCE 優先取 trace_profiles.name
  6. +
  7. 方案 B:寫入端同時更新兩個欄位(需要改 update_trace_profile_group_handler)
  8. +
  9. merge_groups_handler 目前同時更新 trace_profiles.name 和 tkg_nodes.label(line 278-310),行為正確,不需要改
  10. +
+
+

驗證

+
# 測試 face-groups endpoint 正確回傳 rename 後的名稱
+curl -s "http://localhost:3002/api/v1/file/4655a0ab3c077e30c12b2298c2750650/face-groups" \
+  -H "X-API-Key: <key>" | jq '.face_groups[] | {name, trace_count}'
+
+# 預期輸出包含 "Susan"(已 rename 的 group)
+# { "name": "Susan", "trace_count": 7 }
+
+
+ + \ No newline at end of file diff --git a/docs_v1.0/doc_developer/24_studio_trace_profile_read_write_bug.html b/docs_v1.0/doc_developer/24_studio_trace_profile_read_write_bug.html new file mode 100644 index 00000000..f8a2127f --- /dev/null +++ b/docs_v1.0/doc_developer/24_studio_trace_profile_read_write_bug.html @@ -0,0 +1,170 @@ + + + + +24 Studio Trace Profile Read Write Bug - Momentry API Docs + + + +
+ +

Studio Bug Report: get_trace_profile 讀寫不一致

+

Date: 2026-07-27 +Author: Studio Team +Status: 🔴 待修復 +Priority: High

+
+

問題描述

+

Studio 前端 rename face group 後,離開再回來選同一個檔案,名稱變回舊的。

+

影響

+

使用者 rename 的變更無法持久顯示。雖然 trace_profiles.name 已更新,但 get_trace_profile API 回傳的是舊的 tkg_nodes.label,導致前端 loadClusterNames() 用舊名覆蓋新名。

+
+

測試驗證

+

1. Rename

+
curl -X PUT "http://localhost:3002/api/v1/trace-profile/group" \
+  -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
+  -d '{"file_uuid": "9cbeb112fcc5452e869755a539478061", "trace_ids": [1], "name": "SusanTest"}'
+
+ +

回傳:{"success": true, "updated_count": 1} ✅

+

2. 讀取單筆 profile(❌ 仍是舊名)

+
GET /api/v1/trace-profile?file_uuid=...&trace_id=1
+
+ +

回傳:{"name": "Person_0"} ← 錯誤,應為 "SusanTest"

+

3. 讀取 face groups(✅ 是新名)

+
GET /api/v1/file/{uuid}/face-groups
+
+ +

回傳:{"name": "SusanTest", "trace_ids": [1]} ← 正確

+
+

根因分析

+

寫入路徑(正確)

+

PUT /api/v1/trace-profile/group → update_trace_profile_group_handler(profile.rs:228):

+
UPDATE trace_profiles SET name = $1 WHERE file_uuid = $2 AND trace_id = $3
+
+ +

寫入 trace_profiles.name ✅

+

讀取路徑 — 單筆(❌ 錯誤)

+

GET /api/v1/trace-profile → get_trace_profile_handler(profile.rs:78-81):

+
SELECT label, external_id, properties FROM tkg_nodes
+WHERE file_uuid = $1 AND node_type = 'face_track'
+  AND (external_id = $2 OR external_id = $3)
+
+ +

讀取 tkg_nodes.label,沒有 JOIN trace_profiles ❌

+

讀取路徑 — 群組(✅ 正確)

+

GET /api/v1/file/{uuid}/face-groups → get_face_groups_handler(profile.rs:560-566):

+
SELECT COALESCE(tp.name, tn.label) as name, tn.properties
+FROM tkg_nodes tn
+LEFT JOIN trace_profiles tp ON tp.file_uuid = tn.file_uuid
+    AND tp.trace_id = (tn.properties->>'trace_id')::int
+WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track'
+
+ +

使用 COALESCE(tp.name, tn.label),優先取 trace_profiles.name ✅

+
+

前端影響流程

+
User rename group → updateTraceProfileGroup() → PUT /trace-profile/group
+                  → trace_profiles.name = "SusanTest" ✅
+
+User refresh → loadClusterResults() → GET /face-groups
+            → cluster.name = "SusanTest" ✅
+            → loadClusterNames() → GET /trace-profile
+                                 → profile.name = "Person_0" ❌ (tkg_nodes.label)
+                                 → c.name = profile.name → "Person_0" ❌ 覆蓋了新名
+
+ +
+

建議修復

+

方案:改 get_trace_profile_handler 使用 JOIN

+
pub async fn get_trace_profile_handler(...) {
+    let tkg_table = schema::table_name("tkg_nodes");
+    let tp_table = schema::table_name("trace_profiles");
+
+    let row: Option<(String, String, serde_json::Value)> = sqlx::query_as(&format!(
+        "SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, tn.properties \
+         FROM {} tn \
+         LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
+             AND tp.trace_id = (tn.properties->>'trace_id')::int \
+         WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
+             AND (tn.external_id = $2 OR tn.external_id = $3)",
+        tkg_table, tp_table
+    ))
+    .bind(&params.file_uuid)
+    .bind(&external_id_face)
+    .bind(&external_id_trace)
+    .fetch_optional(state.db.pool())
+    .await?;
+
+    let (name, _ext_id, properties) = row.ok_or(StatusCode::NOT_FOUND)?;
+
+    Ok(Json(TraceProfile {
+        file_uuid: params.file_uuid,
+        trace_id: params.trace_id,
+        name,  // 改為使用 JOIN 後的 name
+        // ... 其他欄位不變
+    }))
+}
+
+ +

一致性保證

+ + + + + + + + + + + + + + + + + + + + + + + + + +
API讀取欄位修復後
PUT /trace-profile/group寫入 trace_profiles.name不變
GET /trace-profile~~tkg_nodes.label~~ → COALESCE(tp.name, tn.label)✅ 一致
GET /file/{uuid}/face-groupsCOALESCE(tp.name, tn.label)不變
+
+

相關文件

+
    +
  • 18_profile.md — Profile API 文件
  • +
  • 19_people_api.md — People API 文件
  • +
  • 23_studio_face_group_name_fix.md — Studio face-groups JOIN 修復
  • +
+
+ + \ No newline at end of file diff --git a/docs_v1.0/doc_developer/25_face_filter_api.html b/docs_v1.0/doc_developer/25_face_filter_api.html new file mode 100644 index 00000000..715d1862 --- /dev/null +++ b/docs_v1.0/doc_developer/25_face_filter_api.html @@ -0,0 +1,679 @@ + + + + +25 Face Filter Api - Momentry API Docs + + + +
+ +

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

+

功能: 獲取檔案的臉部列表,支持分頁和來源過濾

+

查詢參數:

+
{
+  "source": "all",           // "all" | "apple_vision" | "mediapipe"
+  "page": 1,                 // 頁碼(從 1 開始)
+  "page_size": 50            // 每頁數量
+}
+
+ +

回應範例:

+
{
+  "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,
+          "bbox_size": 336,              // 新增:min(width, height)
+          "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 使用範例:

+
// 獲取第一頁臉部
+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

+

功能: 獲取單一臉部的詳細過濾報告

+

回應範例:

+
{
+  "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 使用範例:

+
// 獲取臉部過濾報告
+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

+

功能: 套用過濾規則到所有臉部,返回過濾結果

+

請求範例:

+
{
+  "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]
+    }
+  }
+}
+
+ +

回應範例:

+
{
+  "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 使用範例:

+
// 套用過濾規則
+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

+

功能: 獲取臉部的過濾統計資訊

+

回應範例:

+
{
+  "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 使用範例:

+
// 獲取過濾統計
+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

+

回應範例:

+
{
+  "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

+

請求範例:

+
{
+  "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 使用範例:

+
// 獲取現有規則
+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: 審查

+
+

Bbox Size 說明

+

欄位: bbox_size

+

計算方式: min(width, height)

+

說明: +- 預先計算並儲存於後端 +- 用於前端即時過濾 +- 維持當前 Swift 實作的計算方式

+

前端過濾範例:

+
// 前端即時過濾
+const quickFilter = (faces, rules) => {
+  return faces.filter(face => {
+    // Bbox size 過濾
+    if (rules.min_bbox_size && face.filter_features.bbox_size < rules.min_bbox_size) {
+      return false;
+    }
+    return true;
+  });
+};
+
+// 使用範例
+const filtered = quickFilter(allFaces, {
+  min_bbox_size: 80  // 最小 80 像素
+});
+
+ +

建議閾值: +- 保守: 80 像素 +- 平衡: 64 像素(當前預設) +- 寬鬆: 48 像素

+

未來擴展: +- 可考慮增加 max(bbox.width, bbox.height) 選項 +- 可考慮增加 bbox.width * bbox.height (面積) 選項

+
+

預設配置

+

API 提供預設過濾規則,可直接使用:

+
{
+  "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: 過濾低品質臉部

+
// 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: 自訂嚴格過濾

+
// 自訂嚴格過濾規則
+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:

+
{
+  "error": "Face not found"
+}
+
+ +

原因: 臉部 ID 不存在

+

500 Internal Server Error:

+
{
+  "error": "Database error"
+}
+
+ +

原因: 資料庫查詢失敗

+

錯誤處理範例

+
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

+
+ + \ No newline at end of file diff --git a/docs_v1.0/doc_developer/99_incomplete.html b/docs_v1.0/doc_developer/99_incomplete.html index 0940dd93..b34b6c13 100644 --- a/docs_v1.0/doc_developer/99_incomplete.html +++ b/docs_v1.0/doc_developer/99_incomplete.html @@ -201,8 +201,8 @@ a { color: #0066cc; } -/api/v1/search/persons -Defined but not mounted +/api/v1/search/people +✅ Mounted /api/v1/who @@ -238,7 +238,7 @@ a { color: #0066cc; } Defined but unmounted -3 (persons, who, who/candidates) +2 (who, who/candidates) Total diff --git a/docs_v1.0/doc_developer/index.html b/docs_v1.0/doc_developer/index.html index e26f011e..fa90d225 100644 --- a/docs_v1.0/doc_developer/index.html +++ b/docs_v1.0/doc_developer/index.html @@ -29,7 +29,7 @@ a:hover td { background: #f8f8f8; border-radius: 4px; } Logout

API 參考手冊 — 登入後可瀏覽各模組文件

-
錯誤碼Error Codes
14 Identity History
15 Tkg
16 Workspace
17 Progress
18 Profile
99 Incomplete
+
錯誤碼Error Codes
14 Identity History
15 Tkg
16 Workspace
17 Progress
18 Profile
19 People Api
21 Studio Team Guide
22 Studio Pipeline Changes
23 Studio Face Group Name Fix
24 Studio Trace Profile Read Write Bug
25 Face Filter Api
26 Trace Thumbnail Regenerate
99 Incomplete
\ No newline at end of file diff --git a/docs_v1.0/doc_wasm/modules/07_identity.md b/docs_v1.0/doc_wasm/modules/07_identity.md index 0879ce5f..3b4c28be 100644 --- a/docs_v1.0/doc_wasm/modules/07_identity.md +++ b/docs_v1.0/doc_wasm/modules/07_identity.md @@ -302,7 +302,9 @@ curl -s "$API/api/v1/identity/$IDENTITY_UUID/traces?page=1&page_size=3" \ "last_frame": 38127, "first_sec": 1519.0, "last_sec": 1525.1, - "avg_confidence": 0.8254 + "avg_confidence": 0.8254, + "avg_capture_quality": 0.6123, + "best_capture_quality": 0.7812 } ] } @@ -323,6 +325,8 @@ curl -s "$API/api/v1/identity/$IDENTITY_UUID/traces?page=1&page_size=3" \ | `traces[].first_sec` | float | Start time in seconds | | `traces[].last_sec` | float | End time in seconds | | `traces[].avg_confidence` | float | Average detection confidence (0.0–1.0) | +| `traces[].avg_capture_quality` | float | Average frame sharpness quality score (0.0–1.0) | +| `traces[].best_capture_quality` | float | Best frame sharpness quality score (0.0–1.0) | #### Error Responses @@ -1101,6 +1105,7 @@ PATCH /api/v1/identity/:identity_uuid This **replaces** the entire `aliases` array. To add to existing aliases, include all existing entries in the request. ---- + --- +*Updated: 2026-08-12 — identity traces include capture_quality fields (avg_capture_quality, best_capture_quality)* *Updated: 2026-07-21 — Fixed bind/unbind TKG update to match both trace_N and face_track_N external_id formats* *Updated: 2026-06-20 — Added identity files, chunks, faces, status, and JSON endpoints* diff --git a/docs_v1.0/doc_wasm/modules/10_pipeline.md b/docs_v1.0/doc_wasm/modules/10_pipeline.md index b4bd39ff..6a4b9288 100644 --- a/docs_v1.0/doc_wasm/modules/10_pipeline.md +++ b/docs_v1.0/doc_wasm/modules/10_pipeline.md @@ -120,7 +120,7 @@ The following routes are defined in source code but are **NOT** currently mounte | Endpoint | Source file | |----------|-------------| -| `/api/v1/search/persons` | `universal_search.rs` (not mounted) | +| `/api/v1/search/people` | `universal_search.rs` (mounted) | | `/api/v1/who` | `who.rs` | | `/api/v1/who/candidates` | `who.rs` | diff --git a/docs_v1.0/doc_wasm/modules/15_tkg.md b/docs_v1.0/doc_wasm/modules/15_tkg.md index 011613ed..a5880ba0 100644 --- a/docs_v1.0/doc_wasm/modules/15_tkg.md +++ b/docs_v1.0/doc_wasm/modules/15_tkg.md @@ -185,7 +185,14 @@ curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/nodes" \ "properties": { "trace_id": 0, "frame_count": 142, - "avg_confidence": 0.87 + "avg_confidence": 0.87, + "best_confidence": 0.92, + "avg_capture_quality": 0.61, + "best_capture_quality": 0.78, + "key_frame": 120, + "key_face": "tkg:face/0:point_xyz", + "avg_bbox": {"x": 200, "y": 150, "width": 60, "height": 60}, + "best_bbox": {"x": 210, "y": 155, "width": 62, "height": 60} } } ] @@ -524,3 +531,4 @@ curl -X POST "$API/api/v1/file/$FILE_UUID/trace/16/merge/3" \ --- *Updated: 2026-07-21 01:00:00* +*Updated: 2026-08-12 — face_track node properties now include capture_quality fields (avg/best) and key_frame/key_face are selected by best capture quality* diff --git a/docs_v1.0/doc_wasm/modules/18_profile.md b/docs_v1.0/doc_wasm/modules/18_profile.md index b9c594b9..c4995da5 100644 --- a/docs_v1.0/doc_wasm/modules/18_profile.md +++ b/docs_v1.0/doc_wasm/modules/18_profile.md @@ -6,6 +6,68 @@ Endpoints for managing trace profiles (face track metadata stored in TKG) and file profiles (video metadata stored in PostgreSQL). +--- + +## Terminology + +### Core Concepts + +| Term | Definition | Identifier | Display Format | +|------|------------|------------|----------------| +| **Face** | A single human face detection on one frame | `face_id` | Usually not displayed | +| **Face Sequence (Trace)** | A collection of faces across multiple frames representing the same person | `trace_id` | `FS#233` | +| **Face Group** | A collection of traces sharing the same name/label | `label` (string) | `"Person A"` | + +### Data Model Hierarchy + +``` +Video + └── Frame (F#233, F#234, ...) ← Single frame number + └── Face ← Single detection (bbox + confidence) + └── Face Sequence / Trace ← Same person across frames (FS#233) + └── Face Group ← Multiple traces with same name +``` + +### Example + +``` +Video: "interview.mp4" + ├── Frame F#100 + │ └── Face (bbox: {100, 200, 50, 50}, confidence: 0.95) + ├── Frame F#105 + │ └── Face (bbox: {110, 205, 48, 48}, confidence: 0.92) + ├── Frame F#110 + │ └── Face (bbox: {115, 210, 52, 52}, confidence: 0.88) + ... + +Face Sequence FS#233 = [Face@F#100, Face@F#105, Face@F#110, ...] + ↓ +Face Group "Person A" = [FS#233, FS#234, FS#235] +``` + +### Storage + +| Entity | Storage | Table/Collection | +|--------|---------|------------------| +| Face | Qdrant | `_faces` collection | +| Face Sequence / Trace | PostgreSQL (TKG) | `tkg_nodes` where `node_type='face_track'` | +| Face Group | PostgreSQL (TKG) | `tkg_nodes.label` field | + +### Operations + +| Operation | Level | API | +|-----------|-------|-----| +| View faces | Face | Internal (embedded in trace data) | +| Merge traces | Trace | `POST /api/v1/trace/:file_uuid/merge` | +| Rename group | Group | `PUT /api/v1/trace-profile/group` | +| Merge groups | Group | `POST /api/v1/file/:file_uuid/groups/merge` | + +### Naming Convention + +- **Frame**: `F#{number}` — e.g., `F#233` +- **Face Sequence / Trace**: `FS#{number}` — e.g., `FS#233` +- **Face Group**: String name — e.g., `"Person A"`, `"Speaker 1"` + ### `GET /api/v1/trace-profile` **Auth**: Required @@ -158,6 +220,151 @@ curl -s -X PUT "$API/api/v1/trace-profile/group" \ --- +### `POST /api/v1/file/:file_uuid/groups/merge` + +**Auth**: Required +**Scope**: file-level + +Merge multiple face groups into one target group. All traces from source groups are reassigned to the target group name. + +#### Request Body + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `file_uuid` | string | Yes | File UUID | +| `source_groups` | string[] | Yes | List of group names to merge from | +| `target_group_name` | string | Yes | Target group name to merge into | + +#### Examples + +**Merge 2 groups**: + +```bash +curl -s -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \ + -H "X-API-Key: $KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "file_uuid": "c36f35685177c981aa139b66bbbccc5b", + "source_groups": ["Person A"], + "target_group_name": "Person B" + }' +``` + +**Merge 4 groups**: + +```bash +curl -s -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \ + -H "X-API-Key: $KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "file_uuid": "c36f35685177c981aa139b66bbbccc5b", + "source_groups": ["Person A", "Person C", "Person D"], + "target_group_name": "Person B" + }' +``` + +#### Response (200) + +```json +{ + "success": true, + "file_uuid": "c36f35685177c981aa139b66bbbccc5b", + "source_groups": ["Person A", "Person C", "Person D"], + "target_group_name": "Person B", + "traces_merged": 12, + "message": "Merged 3 group(s) into 'Person B'" +} +``` + +#### Error Responses + +| HTTP | Condition | +|------|-----------| +| `400` | Target group in source_groups list | +| `400` | Empty source_groups array | +| `500` | Database error | + +#### Behavior + +1. Find all traces with `label IN (source_groups)` +2. Update their labels to `target_group_name` +3. All source groups disappear (no traces left) +4. Target group contains all traces from merged groups + +--- + +### Merging Groups: Two Methods + +#### Method 1: Use Merge Groups API (Recommended) + +```bash +POST /api/v1/file/:file_uuid/groups/merge +{ + "file_uuid": "...", + "source_groups": ["Person A", "Person C"], + "target_group_name": "Person B" +} +``` + +**Pros**: Simple, only requires group names, supports multi-group merge +**Cons**: New API (requires backend update) + +#### Method 2: Use Batch Update API (Existing) + +```bash +PUT /api/v1/trace-profile/group +{ + "file_uuid": "...", + "trace_ids": [13, 14, 15, 43, 44], + "name": "Person B" +} +``` + +**Pros**: Works with existing API +**Cons**: Frontend must collect all trace_ids from both groups + +#### Example: Merge Group A and C into Group B + +**Before**: +``` +Group A: [13, 14, 15] +Group B: [43, 44] +Group C: [67, 68] +``` + +**Method 1 (Recommended)**: +```bash +curl -X POST "$API/api/v1/file/$FILE_UUID/groups/merge" \ + -H "X-API-Key: $KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "file_uuid": "c36f35685177c981aa139b66bbbccc5b", + "source_groups": ["Person A", "Person C"], + "target_group_name": "Person B" + }' +``` + +**Method 2 (Existing API)**: +```bash +curl -X PUT "$API/api/v1/trace-profile/group" \ + -H "X-API-Key: $KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "file_uuid": "c36f35685177c981aa139b66bbbccc5b", + "trace_ids": [13, 14, 15, 43, 44, 67, 68], + "name": "Person B" + }' +``` + +**After**: +``` +Group A: [] (disappeared) +Group B: [43, 44, 13, 14, 15, 67, 68] +Group C: [] (disappeared) +``` + +--- + ### `GET /api/v1/file-profile` **Auth**: Required @@ -264,5 +471,6 @@ curl -s -X PUT "$API/api/v1/file-profile" \ | `aliases` | `properties->'aliases'` | Multi-language name aliases | --- +*Updated: 2026-07-25 — Added Merge Groups API (POST /groups/merge), added Terminology section (Face, Face Sequence, Face Group)* *Updated: 2026-07-21 — Fixed external_id matching (trace_N + face_track_N formats), fixed parameter ordering in UPDATE query* *Updated: 2026-07-18 — New profile module: trace-profile (GET, PUT, PUT group) and file-profile (GET, PUT)* diff --git a/docs_v1.0/doc_wasm/modules/19_people_api.md b/docs_v1.0/doc_wasm/modules/19_people_api.md new file mode 100644 index 00000000..05740c8a --- /dev/null +++ b/docs_v1.0/doc_wasm/modules/19_people_api.md @@ -0,0 +1,400 @@ +# People API + +**Version**: 2.1 +**Date**: 2026-08-12 +**Base URL**: `http://localhost:3002` +**Auth**: Requires API key header (`Authorization: Bearer `) +**Doc Path**: `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md` + +--- + +## 資料架構 + +### trace_profiles(PostgreSQL — People Search 專用) + +每筆 `file_uuid + trace_id` 對應一個 face trace profile: + +| 欄位 | 類型 | 說明 | +|------|------|------| +| `file_uuid` | string | 影片 UUID | +| `trace_id` | integer | Face trace ID(8Hz 取樣追蹤) | +| `name` | string | FS name(Face 頁面顯示 + People Search 搜尋) | +| `start_frame` | integer | 起始 frame | +| `end_frame` | integer | 結束 frame | +| `frame_count` | integer | 追蹤 frame 數(8Hz 取樣,多數 > 1) | +| `key_frame` | string | 關鍵幀圖片路徑 | +| `key_face` | string | 關鍵人臉裁切路徑 | +| `avg_confidence` | float | 平均偵測信心值 | +| `status` | string | 狀態(pending/confirmed) | + +### 可搜尋註記(metadata / VLM 欄位) + +`trace_profiles` 包含 VLM 產生的註記,可用於進階搜尋和統計: + +| 欄位 | 類型 | 說明 | +|------|------|------| +| `vlm_description` | text | VLM 人物外貌描述 | +| `vlm_clothing` | text | VLM 衣著描述 | +| `vlm_tags` | text[] | VLM 標籤陣列 | +| `vlm_location` | string | VLM 地點 | +| `vlm_setting` | string | VLM 場景設定 | +| `vlm_lighting` | string | VLM 光線 | +| `vlm_weather` | string | VLM 天氣 | +| `vlm_background` | text | VLM 背景描述 | +| `vlm_bg_tags` | text[] | VLM 背景標籤 | + +### tkg_nodes(PostgreSQL — TKG 圖譜專用,與 profile 獨立) + +| 欄位 | 說明 | +|------|------| +| `external_id` | 如 "trace_9",對應 `trace_profiles.trace_id` | +| `label` | TKG 圖譜節點標籤(與 `trace_profiles.name` 獨立) | +| `properties` | TKG 節點屬性 | + +### _faces(Qdrant — Face 向量比對) + +Face embedding 向量存在 Qdrant `_faces` collection,可用作 seed 比對: + +| Payload 欄位 | 類型 | 說明 | +|-------------|------|------| +| `file_uuid` | string | 影片 UUID | +| `trace_id` | integer | Face trace ID | +| `identity_id` | integer \| null | 已綁定的 identity ID | +| `frame` | integer | Frame 編號 | +| `embedding` | vector[512] | FaceNet 512-d embedding | +| `bbox` | object | 人臉 bbox(x, y, width, height) | +| `confidence` | float | 偵測信心值 | + +--- + +## 1. GET /api/v1/search/people + +搜尋已命名的 face trace profiles。回傳符合 name 的卡片列表。 + +### Query Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `query` | string | ✅ Yes | 搜尋關鍵字(ILIKE 模糊比對 `trace_profiles.name`) | +| `file_uuid` | string | ❌ Optional | 限制搜尋範圍 | +| `limit` | integer | ❌ Optional | 回傳筆數上限(預設 10) | + +### Example Request + +```bash +# 搜尋名字 +curl -X GET "http://localhost:3002/api/v1/search/people?query=Susan" + +# 搜尋 VLM 註記(衣著、地點、標籤) +curl -X GET "http://localhost:3002/api/v1/search/people?query=blue+shirt" + +# 限定影片 +curl -X GET "http://localhost:3002/api/v1/search/people?file_uuid=abc123&query=Tom" +``` + +### 搜尋範圍 + +People Search 會搜尋以下欄位(ILIKE 模糊比對): + +| 欄位 | 說明 | +|------|------| +| `name` | FS name | +| `vlm_description` | VLM 人物外貌描述 | +| `vlm_clothing` | VLM 衣著描述 | +| `vlm_tags` | VLM 標籤陣列 | +| `vlm_location` | VLM 地點 | +| `vlm_setting` | VLM 場景設定 | + +### Response + +```json +{ + "people": [ + { + "file_uuid": "4655a0ab3c077e30c12b2298c2750650", + "file_name": "", + "trace_id": 9, + "external_id": "trace_9", + "name": "Susan", + "start_frame": 118, + "end_frame": 384, + "frame_count": 39, + "start_time": null, + "end_time": null, + "key_frame": "key_frame.jpg", + "key_face": null, + "avg_confidence": 0.694, + "avg_capture_quality": 0.512, + "best_capture_quality": 0.733 + } + ], + "total": 18 +} +``` + +### Response Fields + +| Field | Type | Description | +|-------|------|-------------| +| `file_uuid` | string | 影片 UUID | +| `trace_id` | integer | Face trace ID | +| `external_id` | string \| null | TKG node external_id(如 "trace_9") | +| `name` | string \| null | 使用者命名的 FS name | +| `start_frame` | integer \| null | 起始 frame | +| `end_frame` | integer \| null | 結束 frame | +| `frame_count` | integer \| null | 追蹤 frame 數(8Hz 取樣) | +| `start_time` | float \| null | 起始時間(秒) | +| `end_time` | float \| null | 結束時間(秒) | +| `key_frame` | string \| null | 關鍵幀圖片路徑 | +| `key_face` | string \| null | 關鍵人臉裁切路徑 | +| `avg_confidence` | float \| null | 平均偵測信心值 | +| `avg_capture_quality` | float \| null | 平均畫面品質分數(清晰度,0~1) | +| `best_capture_quality` | float \| null | 該 trace 最佳畫面品質分數 | + +--- + +## 2. POST /api/v1/search/universal + +統一搜尋。設定 `types: ["people"]` 搜尋人物,或組合 `"chunk"`、`"frame"`。 + +People Search 會搜尋 `trace_profiles` 的 `name` + `vlm_*` 欄位: +- `name` — FS name +- `vlm_description` — VLM 人物外貌描述 +- `vlm_clothing` — VLM 衣著描述 +- `vlm_tags` — VLM 標籤陣列 +- `vlm_location` — VLM 地點 +- `vlm_setting` — VLM 場景設定 + +### Request Body + +```json +{ + "query": "Susan", + "file_uuid": "abc123", + "types": ["people"], + "page": 1, + "page_size": 20 +} +``` + +### Request Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `query` | string | ✅ Yes | 搜尋關鍵字 | +| `file_uuid` | string | ❌ Optional | 限制搜尋範圍 | +| `types` | string[] | ❌ Optional | `["chunk", "frame", "people"]` — 預設全部 | +| `page` | integer | ❌ Optional | 頁碼(預設 1) | +| `page_size` | integer | ❌ Optional | 每頁筆數(預設 20,最大 200) | + +### Response + +```json +{ + "query": "Susan", + "results": [ + { + "type": "person", + "file_uuid": "4655a0ab3c077e30c12b2298c2750650", + "trace_id": 9, + "external_id": "trace_9", + "name": "Susan", + "frame_count": 39, + "score": 0.95, + "start_time": null, + "end_time": null, + "key_frame": "key_frame.jpg", + "key_face": null + } + ], + "total": 18, + "page": 1, + "page_size": 20, + "has_more": false +} +``` + +--- + +## 3. PUT /api/v1/trace-profile(單筆改名) + +更新單一 face trace profile 的 name 和 metadata。 + +### Request Body + +```json +{ + "file_uuid": "4655a0ab3c077e30c12b2298c2750650", + "trace_id": 9, + "name": "Susan", + "properties": { "custom_key": "custom_value" }, + "key_frame": "path/to/key_frame.jpg", + "key_face": "path/to/key_face.jpg", + "aliases": ["Susie", "Sue"] +} +``` + +### Request Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `file_uuid` | string | ✅ Yes | 影片 UUID | +| `trace_id` | integer | ✅ Yes | Face trace ID | +| `name` | string | ❌ Optional | 新的 FS name | +| `properties` | object | ❌ Optional | 自訂屬性(合併更新) | +| `key_frame` | string | ❌ Optional | 關鍵幀路徑 | +| `key_face` | string | ❌ Optional | 關鍵人臉路徑 | +| `aliases` | string[] | ❌ Optional | 別名列表 | + +--- + +## 4. PUT /api/v1/trace-profile/group(批次改名) + +批次更新多個 face trace profiles 的 name。 + +### Request Body + +```json +{ + "file_uuid": "4655a0ab3c077e30c12b2298c2750650", + "trace_ids": [9, 22, 5], + "name": "Susan" +} +``` + +--- + +## 5. POST /api/v1/groups/merge(合併群組) + +將多個 group 的 traces 合併為一個 group name。 + +### Request Body + +```json +{ + "file_uuid": "4655a0ab3c077e30c12b2298c2750650", + "source_groups": ["Person_0", "Person_1"], + "target_group_name": "Susan" +} +``` + +--- + +## Error Responses + +### 400 Bad Request +```json +{ "error": "name is required" } +``` + +### 401 Unauthorized +``` +HTTP 401 (no body) — Missing or invalid API key +``` + +### 404 Not Found +```json +{ "error": "Profile not found" } +``` + +### 500 Internal Server Error +```json +{ "error": "DB error: connection refused" } +``` + +--- + +## 如何命名 Face Trace + +使用 profile API 為 face trace 命名: + +```bash +curl -X PUT "http://localhost:3002/api/v1/trace-profile" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{ + "file_uuid": "4655a0ab3c077e30c12b2298c2750650", + "trace_id": 9, + "name": "Susan" + }' +``` + +命名後即可透過 People Search API 搜尋: + +```bash +curl "http://localhost:3002/api/v1/search/people?query=Susan" \ + -H "Authorization: Bearer " +``` + +--- + +## Pipeline 狀態定義 + +所有檔案的 status 由 `/api/v1/file/{file_uuid}/sync-status` 自動更新,依據 processor outputs 和功能就緒狀態判定。 + +| Status | 前端顯示 | 條件 | 啟用功能 | +|--------|---------|------|---------| +| `registered` | 📋 已註冊 | 0 processor outputs | 檔案註冊 | +| `scanning` | 🔍 掃描中 | 1-4/5 processor outputs | — | +| `keyword_ready` | 🔎 關鍵字可用 | sentence chunks > 0 | Smart Search | +| `semantic_ready` | 🧠 語意可用 | embedded chunks > 0 | Semantic Search | +| `face_mgmt_ready` | 🎭 臉部管理可用 | face_trace + trace_profiles + tkg_nodes(face_track) | People Search, Face Profile 讀寫, Face Group | +| `agent_ready` | 🤖 Agent 可用 | face_mgmt_ready + tkg_edges | Agent TKG Tools | +| `completed` | ✅ 完成 | 5/5 processors + 全部功能就緒 | — | + +### Face Management Ready 明確定義 + +`face_mgmt_ready` 表示檔案已具備完整臉部管理功能,需同時滿足以下四個條件: + +| 依賴項 | 檢查條件 | 說明 | 提供功能 | +|--------|---------|------|---------| +| **Face Qdrant Ready** | `_faces` collection 有 face points | Face embeddings 已存入 Qdrant | 臉部比對、相似度搜尋 | +| **Face Trace Ready** | `face_traced.json` 存在且有 traces | Face tracking 已完成 | 人臉軌跡資料 | +| **Face Profile Ready** | `trace_profiles` 有紀錄 | Profile 資料已建立 | 名字、VLM 註記、key_frame/key_face | +| **Face TKG Node Ready** | `tkg_nodes` 有 `face_track` nodes | TKG 圖譜節點已建立 | 臉部群組合併、關係查詢 | + +#### 檢查 SQL + +```sql +-- Face Qdrant Ready +SELECT COUNT(*) FROM _faces WHERE file_uuid = $1; -- > 0 + +-- Face Trace Ready +-- 檢查 face_traced.json 檔案存在且有 traces + +-- Face Profile Ready +SELECT COUNT(*) FROM trace_profiles WHERE file_uuid = $1; -- > 0 + +-- Face TKG Node Ready +SELECT COUNT(*) FROM tkg_nodes WHERE file_uuid = $1 AND node_type = 'face_track'; -- > 0 +``` + +#### 啟用功能清單 + +| 功能 | API Endpoint | 說明 | +|------|-------------|------| +| People Search | `GET /api/v1/search/people` | 搜尋已命名人臉 | +| Face Profile 讀寫 | `PUT /api/v1/trace-profile` | 更新名字、VLM 註記 | +| Face Group 合併 | `POST /api/v1/groups/merge` | 合併多個群組 | +| Face Trace 改名 | `PUT /api/v1/trace-profile` | 為單個 trace 命名 | +| Agent Face Search | Agent Tool: `face_profile_search` | Agent 搜尋人臉 | + +--- + +### 狀態依賴關係 + +``` +registered → scanning → keyword_ready → semantic_ready + ↓ + face_mgmt_ready → agent_ready → completed +``` + +### 每個階段對應的 Processor + +| 階段 | 必要 Processor | 產出 | +|------|---------------|------| +| `keyword_ready` | ASR, ASRX | sentence chunks | +| `semantic_ready` | keyword_ready + Vectorize | embedded chunks | +| `face_mgmt_ready` | Face, FaceCluster | trace_profiles (People Search + Face Management) | +| `agent_ready` | face_mgmt_ready + TKG Edges | tkg_edges | + diff --git a/run-server-3003.sh b/run-server-3003.sh deleted file mode 100755 index b93f17dd..00000000 --- a/run-server-3003.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash -# Start playground server on port 3003 -# Logs to logs/momentry_3003.log - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -cd "$SCRIPT_DIR" - -mkdir -p logs - -# Ensure development environment variables -export DATABASE_SCHEMA=dev -export MOMENTRY_SERVER_PORT=3003 -export MOMENTRY_REDIS_PREFIX=momentry_dev: -export MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output_dev - -# Kill existing server on port 3003 -PID=$(lsof -ti :3003 2>/dev/null || true) -if [ -n "$PID" ]; then - echo "Killing existing server on port 3003 (PID: $PID)" - kill "$PID" 2>/dev/null || true - sleep 2 -fi - -# Kill existing worker via PID file -if [ -f logs/worker_3003.pid ]; then - WPID=$(cat logs/worker_3003.pid) - if kill -0 "$WPID" 2>/dev/null; then - echo "Killing existing worker (PID: $WPID)" - kill "$WPID" 2>/dev/null || true - sleep 1 - fi - rm -f logs/worker_3003.pid -fi - -# Build if needed -if [ ! -f target/debug/momentry_playground ]; then - echo "Building playground binary..." - cargo build --bin momentry_playground -fi - -# Start server -echo "Starting momentry_playground server on port 3003 (DATABASE_SCHEMA=${DATABASE_SCHEMA})..." -./target/debug/momentry_playground server --port 3003 > logs/momentry_3003.log 2>&1 & -echo "Server started (PID: $!)" -echo "Logs: logs/momentry_3003.log" - -# Start companion worker -echo "Starting momentry_playground worker (DATABASE_SCHEMA=${DATABASE_SCHEMA})..." -nohup ./target/debug/momentry_playground worker --max-concurrent 6 --poll-interval 10 --batch-size 5 > logs/worker_3003.log 2>&1 & -WPID=$! -echo "$WPID" > logs/worker_3003.pid -echo "Worker started (PID: $WPID)" -echo "Worker logs: logs/worker_3003.log" diff --git a/src/api/cluster_agent.rs b/src/api/cluster_agent.rs index 26a54ade..29b36a21 100644 --- a/src/api/cluster_agent.rs +++ b/src/api/cluster_agent.rs @@ -148,9 +148,7 @@ pub async fn trigger_cluster_agent( // Check for existing running job for this file let registry = CLUSTER_JOB_REGISTRY.read().await; for (job_id, handle) in registry.iter() { - if handle.file_uuid == file_uuid - && matches!(handle.status, ClusterJobStatus::Running) - { + if handle.file_uuid == file_uuid && matches!(handle.status, ClusterJobStatus::Running) { return Ok(Json(ClusterAgentResponse { success: false, job_id: job_id.clone(), @@ -215,7 +213,14 @@ pub async fn trigger_cluster_agent( let total_traces = count_total_traces(&state, &file_uuid).await.unwrap_or(0); - let job_id = format!("cluster_{}_{}", file_uuid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs()); + let job_id = format!( + "cluster_{}_{}", + file_uuid, + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + ); let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid)); let cancel_token = tokio_util::sync::CancellationToken::new(); @@ -307,9 +312,10 @@ pub async fn trigger_cluster_agent( // Build frames list let frames = if total_frames > 0 { let fps_val = if fps > 0.0 { fps } else { 30.0 }; - Some( - crate::core::processor::PythonExecutor::compute_8hz_frames(total_frames, fps_val), - ) + Some(crate::core::processor::PythonExecutor::compute_8hz_frames( + total_frames, + fps_val, + )) } else { None }; @@ -340,12 +346,9 @@ pub async fn trigger_cluster_agent( } // Update trace labels - let _ = update_trace_labels_from_cluster( - &db_clone, - &file_uuid_clone, - &cluster_result, - ) - .await; + let _ = + update_trace_labels_from_cluster(&db_clone, &file_uuid_clone, &cluster_result) + .await; handle.status = ClusterJobStatus::Completed; handle.progress = 1.0; @@ -371,7 +374,10 @@ pub async fn trigger_cluster_agent( let job_id_for_cleanup = job_id_clone.clone(); tokio::spawn(async move { tokio::time::sleep(std::time::Duration::from_secs(300)).await; - CLUSTER_JOB_REGISTRY.write().await.remove(&job_id_for_cleanup); + CLUSTER_JOB_REGISTRY + .write() + .await + .remove(&job_id_for_cleanup); }); }); @@ -401,10 +407,16 @@ pub async fn get_cluster_job_status( })?; let (status_str, message) = match &handle.status { - ClusterJobStatus::Running => ("running".to_string(), Some("Clustering in progress".to_string())), + ClusterJobStatus::Running => ( + "running".to_string(), + Some("Clustering in progress".to_string()), + ), ClusterJobStatus::Completed => ("completed".to_string(), None), ClusterJobStatus::Failed(msg) => ("failed".to_string(), Some(msg.clone())), - ClusterJobStatus::Cancelled => ("cancelled".to_string(), Some("Job was cancelled".to_string())), + ClusterJobStatus::Cancelled => ( + "cancelled".to_string(), + Some("Job was cancelled".to_string()), + ), }; Ok(Json(ClusterJobStatusResponse { @@ -414,7 +426,11 @@ pub async fn get_cluster_job_status( progress: if matches!(handle.status, ClusterJobStatus::Running) { Some(handle.progress) } else { - Some(if matches!(handle.status, ClusterJobStatus::Completed) { 1.0 } else { handle.progress }) + Some(if matches!(handle.status, ClusterJobStatus::Completed) { + 1.0 + } else { + handle.progress + }) }, message, clusters: handle.clusters, @@ -524,14 +540,8 @@ async fn update_trace_labels_from_cluster( .await?; } - let _ = schema::upsert_trace_profile( - db.pool(), - file_uuid, - *trace_id as i32, - &label, - None, - ) - .await; + let _ = schema::upsert_trace_profile(db.pool(), file_uuid, *trace_id as i32, &label, None) + .await; } if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) { @@ -539,14 +549,9 @@ async fn update_trace_labels_from_cluster( for tid in &all_trace_ids { if !trace_to_cluster.contains_key(tid) { let name = format!("Person_{}", tid); - let _ = schema::upsert_trace_profile( - db.pool(), - file_uuid, - *tid as i32, - &name, - None, - ) - .await; + let _ = + schema::upsert_trace_profile(db.pool(), file_uuid, *tid as i32, &name, None) + .await; updated_count += 1; } } @@ -587,10 +592,7 @@ fn get_all_trace_ids(file_uuid: &str) -> Option> { } } -async fn count_total_traces( - state: &AppState, - file_uuid: &str, -) -> anyhow::Result { +async fn count_total_traces(state: &AppState, file_uuid: &str) -> anyhow::Result { let tkg_table = schema::table_name("tkg_nodes"); let count: (i64,) = sqlx::query_as(&format!( "SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND node_type = 'face_track'", diff --git a/src/api/face_filter.rs b/src/api/face_filter.rs index 54fea865..361a06f6 100644 --- a/src/api/face_filter.rs +++ b/src/api/face_filter.rs @@ -12,8 +12,8 @@ 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, + default_filter_config, FaceFilterFeatures, FaceFilterResult, FilterEngine, + FilterRecommendation, FilterRuleConfig, RuleResult, }; /// Request to filter faces @@ -43,7 +43,7 @@ pub struct FilteredFaceInfo { /// Request to get faces with filtering #[derive(Debug, Deserialize)] pub struct GetFacesRequest { - pub source: Option, // "all" | "apple_vision" | "mediapipe" + pub source: Option, // "all" | "apple_vision" | "mediapipe" pub page: Option, pub page_size: Option, } @@ -134,24 +134,21 @@ pub async fn get_faces( 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 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, @@ -163,7 +160,7 @@ pub async fn get_faces( LIMIT $2 OFFSET $3", filter_table ); - + let rows = sqlx::query(&faces_query) .bind(&file_uuid) .bind(page_size as i64) @@ -171,7 +168,7 @@ pub async fn get_faces( .fetch_all(state.db.pool()) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - + // Build response let faces: Vec = rows .into_iter() @@ -182,7 +179,7 @@ pub async fn get_faces( let av_conf: Option = row.get(3); let mp_conf: Option = row.get(4); let bbox_size: Option = row.get(5); - + FaceInfo { face_id: face_id.clone(), frame, @@ -218,7 +215,7 @@ pub async fn get_faces( } }) .collect(); - + // Get source summary let summary_query = format!( "SELECT @@ -229,19 +226,19 @@ pub async fn get_faces( 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 { @@ -264,7 +261,7 @@ pub async fn get_face_filter_report( Path((file_uuid, face_id)): Path<(String, String)>, ) -> Result, StatusCode> { let filter_table = schema::table_name("face_filter_features"); - + let row = sqlx::query(&format!( "SELECT face_id, frame, bbox_size, eye_ratio, nose_ratio, pose_score, mediapipe_detected, mediapipe_iou, embedding_similarity, @@ -279,7 +276,7 @@ pub async fn get_face_filter_report( .fetch_optional(state.db.pool()) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - + match row { Some(row) => { let features = FaceFilterFeatures { @@ -299,13 +296,15 @@ pub async fn get_face_filter_report( mediapipe_confidence: row.get(12), primary_source: row.get(13), }; - + // 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)?; - + + let result = engine + .filter_face(&features) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(result)) } None => Err(StatusCode::NOT_FOUND), @@ -319,7 +318,7 @@ pub async fn filter_faces( req: Json, ) -> Result, 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, bbox_size, eye_ratio, nose_ratio, pose_score, @@ -334,19 +333,19 @@ pub async fn filter_faces( .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 = HashMap::new(); - + for row in rows { let features = FaceFilterFeatures { face_id: row.get(0), @@ -365,17 +364,22 @@ pub async fn filter_faces( mediapipe_confidence: row.get(12), primary_source: row.get(13), }; - - let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - + + 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") { + 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() @@ -386,10 +390,10 @@ pub async fn filter_faces( } else { "other".to_string() }; - + *filter_stats.entry(key).or_insert(0) += 1; } - + filtered_faces.push(FilteredFaceInfo { face_id: result.face_id, frame: result.frame, @@ -397,9 +401,9 @@ pub async fn filter_faces( }); } } - + let filter_stats_json = serde_json::to_value(&filter_stats).unwrap_or_default(); - + Ok(Json(FilterFacesResponse { total_faces, passed, @@ -415,7 +419,7 @@ pub async fn get_filter_stats( Path(file_uuid): Path, ) -> Result, StatusCode> { let filter_table = schema::table_name("face_filter_features"); - + let row = sqlx::query(&format!( "SELECT COUNT(*) as total, @@ -435,7 +439,7 @@ pub async fn get_filter_stats( .fetch_one(state.db.pool()) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - + let stats = serde_json::json!({ "total_faces": row.get::(0), "by_source": { @@ -451,7 +455,7 @@ pub async fn get_filter_stats( "avg_consecutive_frames": row.get::, _>(8), } }); - + Ok(Json(FilterStatsResponse { total_faces: row.get(0), by_category: stats, @@ -465,9 +469,9 @@ pub async fn save_filter_rules( req: Json, ) -> Result, 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) @@ -483,9 +487,9 @@ pub async fn save_filter_rules( .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), @@ -502,7 +506,7 @@ pub async fn get_filter_rules( Path(file_uuid): Path, ) -> Result, 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 {} @@ -514,7 +518,7 @@ pub async fn get_filter_rules( .fetch_all(state.db.pool()) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - + let rules: Vec = rows .into_iter() .map(|row| { @@ -529,7 +533,7 @@ pub async fn get_filter_rules( } }) .collect(); - + Ok(Json(FilterRulesResponse { rules })) } @@ -537,9 +541,24 @@ pub async fn get_filter_rules( pub fn face_filter_routes() -> Router { Router::new() .route("/api/v1/file/:file_uuid/face-filter/faces", get(get_faces)) - .route("/api/v1/file/:file_uuid/face-filter/:face_id/report", get(get_face_filter_report)) - .route("/api/v1/file/:file_uuid/face-filter/apply", post(filter_faces)) - .route("/api/v1/file/:file_uuid/face-filter/stats", get(get_filter_stats)) - .route("/api/v1/file/:file_uuid/face-filter/rules", get(get_filter_rules)) - .route("/api/v1/file/:file_uuid/face-filter/rules", post(save_filter_rules)) + .route( + "/api/v1/file/:file_uuid/face-filter/:face_id/report", + get(get_face_filter_report), + ) + .route( + "/api/v1/file/:file_uuid/face-filter/apply", + post(filter_faces), + ) + .route( + "/api/v1/file/:file_uuid/face-filter/stats", + get(get_filter_stats), + ) + .route( + "/api/v1/file/:file_uuid/face-filter/rules", + get(get_filter_rules), + ) + .route( + "/api/v1/file/:file_uuid/face-filter/rules", + post(save_filter_rules), + ) } diff --git a/src/api/identity_api.rs b/src/api/identity_api.rs index 02501151..501e08fd 100644 --- a/src/api/identity_api.rs +++ b/src/api/identity_api.rs @@ -1062,10 +1062,7 @@ async fn search_file_faces( let where_sql = where_clauses.join(" AND "); // Count total - let count_sql = format!( - "SELECT COUNT(*) FROM {} tp WHERE {}", - tp_table, where_sql - ); + let count_sql = format!("SELECT COUNT(*) FROM {} tp WHERE {}", tp_table, where_sql); let mut count_query = sqlx::query_scalar::<_, i64>(&count_sql).bind(&file_uuid); if let Some(ref q) = params.q { @@ -1110,7 +1107,11 @@ async fn search_file_faces( WHERE {} \ ORDER BY tp.start_frame ASC \ LIMIT ${} OFFSET ${}", - tp_table, video_table, where_sql, param_idx, param_idx + 1 + tp_table, + video_table, + where_sql, + param_idx, + param_idx + 1 ); let mut data_query = sqlx::query(&data_sql).bind(&file_uuid); diff --git a/src/api/media_api.rs b/src/api/media_api.rs index 13a5a221..658d10e9 100644 --- a/src/api/media_api.rs +++ b/src/api/media_api.rs @@ -1773,7 +1773,10 @@ async fn get_face_landmarks_handler( let face_path = std::path::Path::new(output_dir).join(format!("{}.face.json", file_uuid)); if !face_path.exists() { - tracing::error!("[get_face_landmarks] File not found: {}", face_path.display()); + tracing::error!( + "[get_face_landmarks] File not found: {}", + face_path.display() + ); return Err(StatusCode::NOT_FOUND); } @@ -1840,7 +1843,10 @@ async fn get_face_landmarks_handler( y: face.get("y").and_then(|v| v.as_i64()).unwrap_or(0), width: face.get("width").and_then(|v| v.as_i64()).unwrap_or(0), height: face.get("height").and_then(|v| v.as_i64()).unwrap_or(0), - confidence: face.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0), + confidence: face + .get("confidence") + .and_then(|v| v.as_f64()) + .unwrap_or(0.0), }) .collect(); @@ -1850,8 +1856,14 @@ async fn get_face_landmarks_handler( y: selected.get("y").and_then(|v| v.as_i64()).unwrap_or(0), width: selected.get("width").and_then(|v| v.as_i64()).unwrap_or(0), height: selected.get("height").and_then(|v| v.as_i64()).unwrap_or(0), - confidence: selected.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0), - pose_angle: selected.get("pose_angle").cloned().or_else(|| selected.get("pose").cloned()), + confidence: selected + .get("confidence") + .and_then(|v| v.as_f64()) + .unwrap_or(0.0), + pose_angle: selected + .get("pose_angle") + .cloned() + .or_else(|| selected.get("pose").cloned()), landmarks: selected .get("landmarks") .cloned() diff --git a/src/api/middleware.rs b/src/api/middleware.rs index a38adaae..0def8d9f 100644 --- a/src/api/middleware.rs +++ b/src/api/middleware.rs @@ -267,15 +267,21 @@ pub async fn request_logger(request: Request, next: Next) -> Response { let query = request.uri().query().unwrap_or("").to_string(); // Skip health checks and static files to reduce noise - if path == "/api/v1/health" - || path.starts_with("/static") - || path.starts_with("/favicon") - { + if path == "/api/v1/health" || path.starts_with("/static") || path.starts_with("/favicon") { return next.run(request).await; } let start = std::time::Instant::now(); - tracing::info!("[API Request] {} {}{}", method, path, if query.is_empty() { String::new() } else { format!("?{}", query) }); + tracing::info!( + "[API Request] {} {}{}", + method, + path, + if query.is_empty() { + String::new() + } else { + format!("?{}", query) + } + ); let response = next.run(request).await; let duration = start.elapsed(); @@ -286,17 +292,26 @@ pub async fn request_logger(request: Request, next: Next) -> Response { if status.is_server_error() { tracing::error!( "[API Response] {} {} -> {} ({}ms)", - method, path, status, duration_ms + method, + path, + status, + duration_ms ); } else if status.is_client_error() { tracing::warn!( "[API Response] {} {} -> {} ({}ms)", - method, path, status, duration_ms + method, + path, + status, + duration_ms ); } else { tracing::info!( "[API Response] {} {} -> {} ({}ms)", - method, path, status, duration_ms + method, + path, + status, + duration_ms ); } diff --git a/src/api/profile.rs b/src/api/profile.rs index f3da720d..f38cadc6 100644 --- a/src/api/profile.rs +++ b/src/api/profile.rs @@ -120,31 +120,36 @@ pub async fn get_trace_profile_handler( let external_id_face = format!("face_track_{}", params.trace_id); let external_id_trace = format!("trace_{}", params.trace_id); - let row: Option<(String, String, Option, Option)> = - sqlx::query_as(&format!( - "SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \ + let row: Option<( + String, + String, + Option, + Option, + )> = sqlx::query_as(&format!( + "SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \ tp.properties, tn.properties \ FROM {} tn \ LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \ AND tp.trace_id = (tn.properties->>'trace_id')::int \ WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \ AND (tn.external_id = $2 OR tn.external_id = $3)", - tkg_table, tp_table - )) - .bind(¶ms.file_uuid) - .bind(&external_id_face) - .bind(&external_id_trace) - .fetch_optional(state.db.pool()) - .await - .map_err(|e| { - tracing::error!("[TraceProfile] DB error: {}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + tkg_table, tp_table + )) + .bind(¶ms.file_uuid) + .bind(&external_id_face) + .bind(&external_id_trace) + .fetch_optional(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[TraceProfile] DB error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?; // Merge properties: tp_props takes precedence, tn_props as fallback - let mut properties = tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new())); + let mut properties = + tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new())); if let Some(tp_obj) = tp_props.as_ref().and_then(|v| v.as_object()) { if let Some(props_obj) = properties.as_object_mut() { for (k, v) in tp_obj { @@ -1243,17 +1248,10 @@ pub async fn get_face_groups_handler( } } - // Filter out single-trace "groups" — only auto-generated Person_N names. - // User-named groups (even with 1 trace) are kept. + // All Person_N groups are shown as face groups regardless of trace count. let mut filtered_groups: HashMap> = HashMap::new(); for (name, trace_ids) in groups { - let is_auto_name = name.starts_with("Person_"); - if trace_ids.len() > 1 || !is_auto_name { - filtered_groups.insert(name, trace_ids); - } else { - // Single-trace auto-generated group → treat as unassigned - unassigned.extend(trace_ids); - } + filtered_groups.insert(name, trace_ids); } let include_trace_ids = q.include_trace_ids.unwrap_or(true); diff --git a/src/bin/backfill_trace_profiles.rs b/src/bin/backfill_trace_profiles.rs index c1f80219..c3cc1321 100644 --- a/src/bin/backfill_trace_profiles.rs +++ b/src/bin/backfill_trace_profiles.rs @@ -41,7 +41,10 @@ async fn main() -> Result<()> { } } - println!("\nDone! Total updated: {}, Errors: {}", total_updated, total_errors); + println!( + "\nDone! Total updated: {}, Errors: {}", + total_updated, total_errors + ); Ok(()) } diff --git a/src/bin/rebuild_trace_thumbs.rs b/src/bin/rebuild_trace_thumbs.rs index 7c179cfc..005bba7e 100644 --- a/src/bin/rebuild_trace_thumbs.rs +++ b/src/bin/rebuild_trace_thumbs.rs @@ -69,10 +69,7 @@ async fn main() -> Result<()> { Ok(()) } -async fn rebuild_file_thumbs( - qdrant: &QdrantDb, - file_uuid: &str, -) -> Result<(usize, usize)> { +async fn rebuild_file_thumbs(qdrant: &QdrantDb, file_uuid: &str) -> Result<(usize, usize)> { // Get all face points for this file let filter = json!({ "must": [ @@ -88,13 +85,12 @@ async fn rebuild_file_thumbs( // Get video path from DB let db = PostgresDb::new(&config::DATABASE_URL).await?; - let video_path: Option = sqlx::query_scalar( - "SELECT file_path FROM videos WHERE file_uuid = $1", - ) - .bind(file_uuid) - .fetch_optional(db.pool()) - .await? - .flatten(); + let video_path: Option = + sqlx::query_scalar("SELECT file_path FROM videos WHERE file_uuid = $1") + .bind(file_uuid) + .fetch_optional(db.pool()) + .await? + .flatten(); let video_path = match video_path { Some(p) => p, @@ -116,7 +112,9 @@ async fn rebuild_file_thumbs( let w = bbox["width"].as_f64().unwrap_or(0.0); let h = bbox["height"].as_f64().unwrap_or(0.0); - let entry = best_faces.entry(tid as i32).or_insert((0.0, 0, 0.0, 0.0, 0.0, 0.0)); + let entry = best_faces + .entry(tid as i32) + .or_insert((0.0, 0, 0.0, 0.0, 0.0, 0.0)); if conf > entry.0 { *entry = (conf, frame, x, y, w, h); } @@ -161,11 +159,20 @@ async fn rebuild_file_thumbs( let output = Command::new("ffmpeg") .args([ - "-y", "-v", "quiet", - "-i", &video_path, - "-vf", &format!("select=eq(n\\,{}),crop={}:{}:{}:{}", frame_num, size, size, crop_x, crop_y), - "-frames:v", "1", - "-q:v", "2", + "-y", + "-v", + "quiet", + "-i", + &video_path, + "-vf", + &format!( + "select=eq(n\\,{}),crop={}:{}:{}:{}", + frame_num, size, size, crop_x, crop_y + ), + "-frames:v", + "1", + "-q:v", + "2", key_face_path.to_str().unwrap(), ]) .output(); @@ -179,11 +186,17 @@ async fn rebuild_file_thumbs( let tmp_frame = trace_dir.join("tmp_frame.jpg"); let _ = Command::new("ffmpeg") .args([ - "-y", "-v", "quiet", - "-i", &video_path, - "-vf", &select_filter, - "-frames:v", "1", - "-q:v", "2", + "-y", + "-v", + "quiet", + "-i", + &video_path, + "-vf", + &select_filter, + "-frames:v", + "1", + "-q:v", + "2", tmp_frame.to_str().unwrap(), ]) .output(); @@ -191,10 +204,15 @@ async fn rebuild_file_thumbs( if tmp_frame.exists() { let _ = Command::new("ffmpeg") .args([ - "-y", "-v", "quiet", - "-i", tmp_frame.to_str().unwrap(), - "-vf", &format!("crop={}:{}:{}:{}", size, size, crop_x, crop_y), - "-q:v", "2", + "-y", + "-v", + "quiet", + "-i", + tmp_frame.to_str().unwrap(), + "-vf", + &format!("crop={}:{}:{}:{}", size, size, crop_x, crop_y), + "-q:v", + "2", key_face_path.to_str().unwrap(), ]) .output(); diff --git a/src/cli/args.rs b/src/cli/args.rs index fbbf0e5d..6e068461 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -45,6 +45,11 @@ pub enum Commands { /// File UUID uuid: String, }, + /// Backfill missing TKG trace artifact dirs (skips existing dirs) + TkgBackfill { + /// File UUID + file_uuid: String, + }, /// Detect objects in an image using CLIP or Qwen3-VL Detect { /// Image path diff --git a/src/core/agent/tools.rs b/src/core/agent/tools.rs index 3c2f09c4..baeb3df2 100644 --- a/src/core/agent/tools.rs +++ b/src/core/agent/tools.rs @@ -931,10 +931,7 @@ pub async fn exec_analyze_frame( // Use select=eq(n\,frame) for VFR compatibility (decoded index, not time-based) let select = format!("select=eq(n\\,{})", frame_number); let output = tokio::process::Command::new(&ffmpeg_path) - .args([ - "-i", - &video_path, - ]) + .args(["-i", &video_path]) .args([ "-vf", &select, diff --git a/src/core/processor/asrx.rs b/src/core/processor/asrx.rs index 444f793f..86874e97 100644 --- a/src/core/processor/asrx.rs +++ b/src/core/processor/asrx.rs @@ -1,15 +1,10 @@ use anyhow::{Context, Result}; -use libc; use serde::{Deserialize, Serialize}; -use std::time::Duration; use tokio::process::Command; -use tokio::time::timeout; use super::executor::PythonExecutor; use super::AsrStatus; -const ASRX_TIMEOUT: Duration = Duration::from_secs(7200); - #[derive(Debug, Serialize, Deserialize)] pub struct AsrxResult { #[serde(default)] @@ -125,27 +120,12 @@ pub async fn process_asrx( .kill_on_drop(true) .process_group(0); - let child = cmd.spawn().context("Failed to run ASRX processor")?; - let child_pid = child.id(); - - let output = match timeout(ASRX_TIMEOUT, child.wait_with_output()).await { - Ok(Ok(output)) => output, - Ok(Err(e)) => { - let _ = std::fs::rename(&tmp_path, output_path_obj.with_extension("json.err")); - return Err(e).context("Failed to run ASRX processor"); - } - Err(_) => { - // Timeout: kill process group, rename .tmp → .err - if let Some(pid) = child_pid { - let pgid = pid as i32; - unsafe { - libc::killpg(pgid, libc::SIGKILL); - } - } - let _ = std::fs::rename(&tmp_path, output_path_obj.with_extension("json.err")); - anyhow::bail!("ASRX processing timed out after {:?}", ASRX_TIMEOUT); - } - }; + let output = cmd + .spawn() + .context("Failed to run ASRX processor")? + .wait_with_output() + .await + .context("Failed to run ASRX processor")?; let stderr = String::from_utf8_lossy(&output.stderr); diff --git a/src/core/processor/executor.rs b/src/core/processor/executor.rs index 70ee78dc..cffc74ae 100644 --- a/src/core/processor/executor.rs +++ b/src/core/processor/executor.rs @@ -1037,7 +1037,10 @@ impl PythonExecutor { let mut partial_path = out.to_path_buf(); partial_path.set_extension("json.partial"); let _ = std::fs::rename(tmp, &partial_path); - tracing::warn!("[Executor] Partial output preserved: {:?}", partial_path); + tracing::warn!( + "[Executor] Partial output preserved: {:?}", + partial_path + ); } else { let mut err_path = out.to_path_buf(); err_path.set_extension("json.err"); @@ -1058,7 +1061,9 @@ impl PythonExecutor { Err(_) => { mark_failed(); if let Some(pid) = child_pid { - unsafe { libc::killpg(pid as i32, libc::SIGKILL); } + unsafe { + libc::killpg(pid as i32, libc::SIGKILL); + } } child.kill().await.context("Failed to kill process")?; anyhow::bail!("{} timed out after {:?}", script_name, duration); diff --git a/src/core/processor/tkg.rs b/src/core/processor/tkg.rs index 8b276974..0b9d3c72 100644 --- a/src/core/processor/tkg.rs +++ b/src/core/processor/tkg.rs @@ -766,7 +766,7 @@ pub async fn build_tkg( if let Some(r) = redis.as_ref() { publish_tkg_progress(r, file_uuid, &progress).await; } - let n_face = build_face_track_nodes(pool, file_uuid, &pose_data, &face_points, false).await?; + let n_face = build_face_track_nodes(pool, file_uuid, &pose_data, &face_points, false, &mut progress, &redis).await?; progress.stats.face_track_nodes = n_face as i64; progress.update_phase( TkgPhase::FaceTrackNodes, @@ -1130,7 +1130,7 @@ pub async fn backfill_trace_dirs( ); let n = - build_face_track_nodes_from_qdrant(pool, file_uuid, &pose_data, &face_points, true).await?; + build_face_track_nodes_from_qdrant(pool, file_uuid, &pose_data, &face_points, true, &mut TkgProgress::new(file_uuid), &None).await?; tracing::info!( "[TKG-BACKFILL] backfilled {} face_track artifact dirs for {}", n, @@ -1145,8 +1145,10 @@ async fn build_face_track_nodes( pose_data: &[FacePose], face_points: &[FacePoint], skip_existing: bool, + progress: &mut TkgProgress, + redis: &Option>, ) -> Result { - build_face_track_nodes_from_qdrant(pool, file_uuid, pose_data, face_points, skip_existing).await + build_face_track_nodes_from_qdrant(pool, file_uuid, pose_data, face_points, skip_existing, progress, redis).await } async fn build_face_track_nodes_from_qdrant( @@ -1155,6 +1157,8 @@ async fn build_face_track_nodes_from_qdrant( pose_data: &[FacePose], face_points: &[FacePoint], skip_existing: bool, + progress: &mut TkgProgress, + redis: &Option>, ) -> Result { let nodes_table = t("tkg_nodes"); @@ -1234,7 +1238,18 @@ async fn build_face_track_nodes_from_qdrant( } let mut count = 0; + let total_traces = traces.len(); for (tid, agg) in &traces { + // Report trace artifact progress + progress.update_phase( + TkgPhase::TraceArtifacts, + count as f64 / total_traces as f64, + &format!("{}/{} traces", count, total_traces), + ); + if let Some(ref r) = redis { + publish_tkg_progress(r, file_uuid, &progress).await; + } + // Skip traces whose artifacts already exist on disk (backfill/resume mode) if skip_existing { let output_dir = crate::core::config::OUTPUT_DIR.as_str(); @@ -1607,11 +1622,11 @@ async fn build_face_track_nodes_from_qdrant( if kface_path.exists() { trace_profile.key_face = Some("key_face.jpg".to_string()); } - if let Ok(json) = serde_json::to_string_pretty( - &crate::core::file_profile::round_json_value( + if let Ok(json) = + serde_json::to_string_pretty(&crate::core::file_profile::round_json_value( &serde_json::to_value(&trace_profile).unwrap_or_default(), - ), - ) { + )) + { let _ = std::fs::write(&tp_path, json); if tp_path.exists() { tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid); @@ -1678,6 +1693,17 @@ async fn build_face_track_nodes_from_qdrant( count, file_uuid ); + + // Report trace artifacts complete + progress.update_phase( + TkgPhase::TraceArtifacts, + 1.0, + &format!("{}/{} traces complete", count, total_traces), + ); + if let Some(ref r) = redis { + publish_tkg_progress(r, file_uuid, &progress).await; + } + Ok(count) } diff --git a/src/core/progress.rs b/src/core/progress.rs index cb8291f3..4fcdab2b 100644 --- a/src/core/progress.rs +++ b/src/core/progress.rs @@ -84,10 +84,18 @@ impl PipelineProgress { status: "pending".into(), detail: None, }, - // Rule 2 Ingestion (15%) + // Rule 2 Ingestion (10%) PipelineStage { name: "rule2_ingestion".into(), - weight: 0.15, + weight: 0.10, + progress: 0.0, + status: "pending".into(), + detail: None, + }, + // VLM Summary (5%) + PipelineStage { + name: "vlm_summary".into(), + weight: 0.05, progress: 0.0, status: "pending".into(), detail: None, @@ -158,12 +166,13 @@ pub enum TkgPhase { HasAppearanceEdges = 15, // Build has_appearance edges WearsEdges = 16, // Build wears edges HandObjectEdges = 17, // Build hand_object edges - Completed = 18, - Failed = 19, + TraceArtifacts = 18, // Save key_frame.jpg, key_face.jpg, trace_profile.json + Completed = 19, + Failed = 20, } impl TkgPhase { - pub const TOTAL: usize = 18; // phases 0-17 + pub const TOTAL: usize = 19; // phases 0-18 pub fn name(&self) -> &'static str { match self { @@ -185,6 +194,7 @@ impl TkgPhase { TkgPhase::HasAppearanceEdges => "has_appearance_edges", TkgPhase::WearsEdges => "wears_edges", TkgPhase::HandObjectEdges => "hand_object_edges", + TkgPhase::TraceArtifacts => "trace_artifacts", TkgPhase::Completed => "completed", TkgPhase::Failed => "failed", } @@ -210,6 +220,7 @@ impl TkgPhase { 15 => TkgPhase::HasAppearanceEdges, 16 => TkgPhase::WearsEdges, 17 => TkgPhase::HandObjectEdges, + 18 => TkgPhase::TraceArtifacts, _ => TkgPhase::Completed, } } diff --git a/src/core/proxy.rs b/src/core/proxy.rs index ce4ed179..062ef432 100644 --- a/src/core/proxy.rs +++ b/src/core/proxy.rs @@ -178,91 +178,3 @@ pub async fn probe_audio_track(file_path: &str) -> Result Result> { - let cut_json = PathBuf::from(output_dir).join(format!("{}.cut.json", file_uuid)); - - if !cut_json.exists() { - tracing::warn!("[CUT_KEY_FRAME] cut.json not found: {}", cut_json.display()); - return Ok(vec![]); - } - - let script = std::path::Path::new("/Users/accusys/momentry_core/scripts/cut_key_frame.py"); - - if !script.exists() { - tracing::warn!("[CUT_KEY_FRAME] Script not found: {}", script.display()); - return Ok(vec![]); - } - - let file_uuid_owned = file_uuid.to_string(); - let video_path_owned = video_path.to_string(); - let cut_json_str = cut_json.to_string_lossy().to_string(); - let output_dir_owned = output_dir.to_string(); - let script_str = script.to_string_lossy().to_string(); - let python_path = PYTHON_PATH.as_str().to_string(); - - let output = tokio::task::spawn_blocking(move || { - Command::new(&python_path) - .arg(&script_str) - .arg("--file-uuid") - .arg(&file_uuid_owned) - .arg("--video") - .arg(&video_path_owned) - .arg("--cut-json") - .arg(&cut_json_str) - .arg("--output-dir") - .arg(&output_dir_owned) - .arg("--json") - .output() - }) - .await - .context("Spawn blocking failed")? - .context("Failed to spawn python")?; - - if !output.status.success() { - tracing::warn!( - "[CUT_KEY_FRAME] Extraction failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - return Ok(vec![]); - } - - let stdout = String::from_utf8_lossy(&output.stdout); - let json: serde_json::Value = match serde_json::from_str(&stdout) { - Ok(v) => v, - Err(e) => { - tracing::warn!("[CUT_KEY_FRAME] JSON parse error: {}", e); - return Ok(vec![]); - } - }; - - let scenes: Vec = json - .get("scenes") - .and_then(|s| s.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|s| { - if s.get("success").and_then(|b| b.as_bool()) == Some(true) { - s.get("output_path") - .and_then(|p| p.as_str().map(|p| p.to_string())) - } else { - None - } - }) - .collect() - }) - .unwrap_or_default(); - - tracing::info!( - "[CUT_KEY_FRAME] Extracted {} scene key frames for {}", - scenes.len(), - file_uuid - ); - - Ok(scenes) -} diff --git a/src/main.rs b/src/main.rs index c2380ff0..5b448ec0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,6 +50,9 @@ async fn main() -> Result<()> { Commands::StoreAsrx { uuid } => { handle_store_asrx(&uuid).await?; } + Commands::TkgBackfill { file_uuid } => { + handle_tkg_backfill(&file_uuid).await?; + } Commands::Vectorize { uuid } => { handle_vectorize(&uuid).await?; } diff --git a/src/processing/handlers.rs b/src/processing/handlers.rs index 3f805bf0..a129018d 100644 --- a/src/processing/handlers.rs +++ b/src/processing/handlers.rs @@ -404,6 +404,23 @@ pub async fn handle_phase1(uuid: &str) -> Result<()> { momentry_core::core::pipeline::run_phase1(uuid).await } +/// Handle tkg-backfill command +pub async fn handle_tkg_backfill(file_uuid: &str) -> Result<()> { + let db = momentry_core::core::db::postgres_db::PostgresDb::new( + &momentry_core::core::config::DATABASE_URL, + ) + .await?; + let output_dir = momentry_core::core::config::OUTPUT_DIR.as_str(); + let n = momentry_core::core::processor::tkg::backfill_trace_dirs(&db, file_uuid, output_dir) + .await?; + tracing::info!( + "[tkg-backfill] built {} trace artifact dirs for {}", + n, + file_uuid + ); + Ok(()) +} + /// Handle complete command pub async fn handle_complete(uuid: &str) -> Result<()> { let db = momentry_core::core::db::postgres_db::PostgresDb::new( diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index 8c1971e1..814c0a89 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -2665,32 +2665,6 @@ impl JobWorker { uuid_clone, e ), } - - // P5: VLM Summary — after face dedup writes trace_profiles - let face_count = Self::verify_traces_ready(&db_clone.pool(), &uuid_clone).await; - if face_count > 0 { - info!("[VLM] Starting for {}: {} traces verified", uuid_clone, face_count); - let db_p5 = db_clone.clone(); - let redis_p5 = redis_clone.clone(); - let uuid_p5 = uuid_clone.clone(); - let output_dir_p5 = output_dir.clone(); - tokio::spawn(async move { - let result = tokio::time::timeout( - std::time::Duration::from_secs(300), - crate::core::processor::vlm_summary::generate_vlm_summaries( - &db_p5, &uuid_p5, &output_dir_p5, Some(redis_p5), - ), - ) - .await; - match result { - Ok(stats) => info!( - "[VLM] Completed for {}: {}/{} summarized, {} embedded", - uuid_p5, stats.summarized, stats.total, stats.embedded - ), - Err(_) => error!("[VLM] Timed out after 5 min for {}", uuid_p5), - } - }); - } }); } else { warn!("Failed to parse face_cluster.json for {}", uuid); @@ -2938,6 +2912,60 @@ impl JobWorker { ) .await; + // P5: VLM Summary — wait for ALL key_frame.jpg files to be ready + let face_count = r.face_track_nodes; + if face_count > 0 { + let output_dir_wait = output_dir_clone.clone(); + let uuid_wait = uuid_clone.clone(); + let db_wait = db_clone.clone(); + let redis_wait = redis_clone.clone(); + tokio::spawn(async move { + // Poll until ALL key_frame.jpg files exist (max 10 min) + let max_attempts = 600; // 10 min / 1s + let mut ready_count = 0i64; + for attempt in 0..max_attempts { + // Count traces with key_frame.jpg on disk + let output_dir = output_dir_wait.as_str(); + let trace_dir = std::path::PathBuf::from(output_dir) + .join(&uuid_wait); + ready_count = if trace_dir.exists() { + std::fs::read_dir(&trace_dir) + .ok() + .map(|entries| { + entries.filter_map(|e| e.ok()).filter(|e| { + e.path().join("key_frame.jpg").exists() + }).count() as i64 + }) + .unwrap_or(0) + } else { + 0 + }; + + if ready_count >= face_count as i64 && ready_count > 0 { + info!("[VLM-wait] All {}/{} key_frame.jpg ready for {}", ready_count, face_count, uuid_wait); + break; + } + if attempt % 30 == 0 { + info!("[VLM-wait] {}/{} key_frame.jpg ready for {} (waiting...)", ready_count, face_count, uuid_wait); + } + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + } + + if ready_count >= face_count as i64 { + info!("[VLM] Starting for {}: {} traces verified", uuid_wait, ready_count); + let db_p5 = db_wait.clone(); + let redis_p5 = redis_wait.clone(); + let uuid_p5 = uuid_wait.clone(); + let output_dir_p5 = output_dir_wait.clone(); + crate::core::processor::vlm_summary::generate_vlm_summaries( + &db_p5, &uuid_p5, &output_dir_p5, Some(redis_p5), + ).await; + } else { + warn!("[VLM] Skipping for {} (only {}/{} key_frame.jpg ready)", uuid_wait, ready_count, face_count); + } + }); + } + // Trigger Rule 2 ingestion after TKG complete if total_edges > 0 { // Mark rule2_ingestion as running diff --git a/test_3003_full.sh b/test_3003_full.sh deleted file mode 100644 index 729f8d38..00000000 --- a/test_3003_full.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/bash -# 3003 Full Functionality Test - -API_KEY="muser_68600856036340bcafc01930eb4bd839_1774418104_97221b69" -BASE_URL="http://localhost:3003" -FILE_UUID="d3f9ae8e471a1fc4d47022c66091b920" - -echo "=== 3003 Playground 功能完整测试 ===" -echo "" - -# 1. Health Check -echo "【1】Health Check" -curl -s "$BASE_URL/api/v1/identities" \ - -H "X-API-Key: $API_KEY" 2>&1 | jq '.identities | length' -echo "" - -# 2. File Info -echo "【2】File Info" -curl -s "$BASE_URL/api/v1/file/$FILE_UUID" \ - -H "X-API-Key: $API_KEY" 2>&1 | jq '{success, file_name, status, fps}' -echo "" - -# 3. TKG Rebuild (Phase 2.5) -echo "【3】TKG Rebuild (Phase 2.5)" -time curl -s -X POST "$BASE_URL/api/v1/file/$FILE_UUID/tkg/rebuild" \ - -H "X-API-Key: $API_KEY" 2>&1 | jq '.result | {face_trace_nodes, gaze_trace_nodes, lip_trace_nodes, text_trace_nodes, object_nodes}' -echo "" - -# 4. Phase 2.5 Logs -echo "【4】Phase 2.5 Logs Verification" -grep "Phase2\.5" logs/momentry_3003.log | tail -5 -echo "" -sleep 5 - -# 5. Rule2 Relationship Chunks -echo "【5】Rule2 Relationship Chunks" -time curl -s -X POST "$BASE_URL/api/v1/file/$FILE_UUID/rule2" \ - -H "X-API-Key: $API_KEY" 2>&1 | jq '{success, rule2_chunks}' -echo "" - -# 6. Identities -echo "【6】Identities" -curl -s "$BASE_URL/api/v1/identities" \ - -H "X-API-Key: $API_KEY" 2>&1 | jq '.identities[0:3] | .[] | {id, name}' -echo "" - -# 7. Qdrant Embeddings Count -echo "【7】Qdrant Embeddings" -curl -s "$BASE_URL/api/v1/file/$FILE_UUID/tkg/stats" \ - -H "X-API-Key: $API_KEY" 2>&1 | jq '.embeddings_count' 2>&1 || echo "TKG stats API not available" -echo "" - -# 8. Database Schema -echo "【8】Database Schema" -ps aux | grep momentry_playground | grep -v grep | grep -o "DATABASE_SCHEMA=[^ ]*" -echo "" - -# 9. Redis Prefix -echo "【9】Redis Prefix" -ps aux | grep momentry_playground | grep -v grep | grep -o "REDIS_PREFIX=[^ ]*" || echo "REDIS_PREFIX not in process" -echo "" - -# 10. Performance Summary -echo "【10】Performance Summary" -echo "TKG rebuild time: ~4s" -echo "Rule2 time: ~0.03s" -echo "Phase 2.5: All nodes from Qdrant" -echo "" - -echo "=== 测试完成 ===" diff --git a/v1.1/run-server-3003_v1.11.sh b/v1.1/run-server-3003_v1.11.sh deleted file mode 100755 index 9cfc6b4e..00000000 --- a/v1.1/run-server-3003_v1.11.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bash -# Start playground server on port 3003 -# Logs to logs/momentry_3003.log - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -cd "$SCRIPT_DIR" - -# Kill existing server on port 3003 -PID=$(lsof -ti :3003 2>/dev/null || true) -if [ -n "$PID" ]; then - echo "Killing existing server on port 3003 (PID: $PID)" - kill "$PID" 2>/dev/null || true - sleep 2 -fi - -# Build if needed -if [ ! -f target/debug/momentry_playground ]; then - echo "Building playground binary..." - cargo build --bin momentry_playground -fi - -# Start server -echo "Starting momentry_playground server on port 3003..." -./target/debug/momentry_playground server --port 3003 > logs/momentry_3003.log 2>&1 & -echo "Server started (PID: $!)" -echo "Logs: logs/momentry_3003.log"