feat: Face JSON v2 schema - add schema_version, bbox x2/y2/center, keep embeddings, update clustering
This commit is contained in:
@@ -0,0 +1,299 @@
|
||||
---
|
||||
title: Auth API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: auth -->
|
||||
<!-- description: Authentication — login, logout, JWT, session cookie, API key -->
|
||||
<!-- depends: -->
|
||||
|
||||
## Base URL
|
||||
|
||||
| Environment | URL | Purpose |
|
||||
|-------------|-----|---------|
|
||||
| Production | `http://localhost:3002` | Production deployment |
|
||||
| External (M5) | `https://m5api.momentry.ddns.net` | Remote access |
|
||||
|
||||
## Variables
|
||||
|
||||
All examples in this documentation use these environment variables:
|
||||
|
||||
```bash
|
||||
API="http://localhost:3002"
|
||||
KEY="your-api-key-here"
|
||||
```
|
||||
|
||||
## Authentication
|
||||
|
||||
All endpoints under `/api/v1/*` require authentication.
|
||||
The following endpoints are public (no auth needed):
|
||||
|
||||
- `GET /health`
|
||||
- `POST /api/v1/auth/login`
|
||||
- `POST /api/v1/auth/logout`
|
||||
|
||||
### Three Authentication Modes
|
||||
|
||||
The system supports three authentication methods, checked in **priority order** by the middleware:
|
||||
|
||||
```
|
||||
Middleware priority:
|
||||
1. Session Cookie (Portal/browser)
|
||||
2. JWT Bearer (API clients, CLI)
|
||||
3. API Key Header (legacy compatibility)
|
||||
4. API Key Query Param (?api_key=)
|
||||
```
|
||||
|
||||
| Mode | Transport | Expiry | Scope | Best for |
|
||||
|------|-----------|--------|-------|----------|
|
||||
| **Session Cookie** | `Cookie: session_id=<session_id>` | 24h | per-browser session | Portal (browser) |
|
||||
| **JWT** | `Authorization: Bearer <token>` | 1h | per-login token | API clients, CLI, scripts |
|
||||
| **API Key** | `X-API-Key: <key>` | 90d | fixed key for automation | Legacy scripts, WordPress |
|
||||
|
||||
---
|
||||
|
||||
### Login
|
||||
|
||||
**Default accounts & API keys:**
|
||||
|
||||
| Username | Password | API Key | Role |
|
||||
|----------|----------|---------|------|
|
||||
| `admin` | `admin` | — | admin |
|
||||
| `demo` | `demo` | `muser_demo_key_32chars_abcdef1234567890` | user |
|
||||
|
||||
The demo API key is set via `MOMENTRY_DEMO_API_KEY` env var and can be used in place of JWT for marcom integrations:
|
||||
|
||||
```bash
|
||||
# Using API key instead of JWT
|
||||
curl -s "$API/api/v1/files/scan" -H "X-API-Key: muser_demo_key_32chars_abcdef1234567890"
|
||||
```
|
||||
|
||||
```bash
|
||||
# Login as admin
|
||||
curl -s -X POST "$API/api/v1/auth/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username": "admin", "password": "admin"}'
|
||||
|
||||
# Login as demo user
|
||||
curl -s -X POST "$API/api/v1/auth/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username": "demo", "password": "demo"}'
|
||||
```
|
||||
|
||||
#### Success Response
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"jwt": "eyJhbGciOiJIUzI1NiIs...",
|
||||
"api_key": "muser_...",
|
||||
"user": {
|
||||
"username": "admin",
|
||||
"role": "admin"
|
||||
},
|
||||
"expires_at": "2026-05-18T13:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `jwt` | string | JWT access token. Use as `Authorization: Bearer <jwt>`. Expires in 1 hour. |
|
||||
| `api_key` | string | Legacy API key. Use as `X-API-Key: <key>`. Good for 90 days. |
|
||||
| `user.username` | string | Username |
|
||||
| `user.role` | string | Role: `admin`, `user`, or `readonly` |
|
||||
| `expires_at` | string | ISO8601 timestamp of JWT expiration |
|
||||
|
||||
The login endpoint also sets a `Set-Cookie` header for browser-based clients:
|
||||
|
||||
```
|
||||
Set-Cookie: session_id=<session_id>; Path=/; HttpOnly; SameSite=Strict; Max-Age=86400
|
||||
```
|
||||
|
||||
#### Error Response (401)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"message": "Invalid username or password"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Using JWT
|
||||
|
||||
JWT is preferred for API clients (CLI scripts, WordPress). It is validated by the middleware without a database lookup (stateless).
|
||||
|
||||
```bash
|
||||
# Login and capture JWT
|
||||
JWT=$(curl -s -X POST "$API/api/v1/auth/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username":"admin","password":"admin"}' | python3 -c "import json,sys;print(json.load(sys.stdin)['jwt'])")
|
||||
|
||||
# Use JWT for all subsequent requests
|
||||
curl -H "Authorization: Bearer $JWT" "$API/api/v1/files/scan"
|
||||
curl -H "Authorization: Bearer $JWT" "$API/api/v1/resource/tmdb"
|
||||
```
|
||||
|
||||
JWT is short-lived (1 hour). When it expires, request a new one via login.
|
||||
|
||||
---
|
||||
|
||||
### Using Session Cookie (Browser)
|
||||
|
||||
Browser-based clients (Portal) get a session cookie automatically after login. The browser sends the cookie with every request—no manual header needed.
|
||||
|
||||
```bash
|
||||
# Login captures the session cookie from Set-Cookie header
|
||||
curl -v -X POST "$API/api/v1/auth/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username":"admin","password":"admin"}' 2>&1 | grep "Set-Cookie"
|
||||
|
||||
# Browser automatically sends: Cookie: session_id=<session_id>
|
||||
# No manual header needed for subsequent requests
|
||||
```
|
||||
|
||||
The session cookie is HttpOnly (not accessible from JavaScript) and SameSite=Strict (protected against CSRF).
|
||||
|
||||
---
|
||||
|
||||
### Using Legacy API Key
|
||||
|
||||
```bash
|
||||
curl -H "X-API-Key: $KEY" "$API/api/v1/files/scan"
|
||||
|
||||
# Also accepted via Bearer header (non-JWT format) or query parameter:
|
||||
curl -H "Authorization: Bearer $KEY" "$API/api/v1/files/scan"
|
||||
curl "$API/api/v1/files/scan?api_key=$KEY"
|
||||
```
|
||||
|
||||
API keys are validated via SHA256 hash lookup in the database. They are long-lived (90 days) and intended for automation.
|
||||
|
||||
### Obtaining an API Key (CLI)
|
||||
|
||||
```bash
|
||||
momentry api-key create "My API Key" --key-type user
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Logout
|
||||
|
||||
```bash
|
||||
# Logout using the session cookie (browser)
|
||||
curl -X POST "$API/api/v1/auth/logout" \
|
||||
-H "Cookie: session_id=<uuid>"
|
||||
```
|
||||
|
||||
#### What logout does
|
||||
|
||||
| Auth mode | Effect |
|
||||
|-----------|--------|
|
||||
| **Session Cookie** | Session deleted from database. Same cookie returns 401 on subsequent requests. |
|
||||
| **JWT** | JWT remains valid until expiry. (JWT is stateless — logout adds JWT to a blacklist only if API key mode is used.) |
|
||||
| **API Key** | API key remains valid. (Legacy keys are shared across sessions — revoking would break other clients.) |
|
||||
|
||||
#### Example: full session lifecycle
|
||||
|
||||
```bash
|
||||
# 1. Login
|
||||
SESSION_ID=$(curl -s -D - -X POST "$API/api/v1/auth/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username":"admin","password":"admin"}' | grep "Set-Cookie" | sed 's/.*session_id=\([^;]*\).*/\1/')
|
||||
|
||||
# 2. Use session (works)
|
||||
curl -s -o /dev/null -w "HTTP %{http_code}\n" "$API/api/v1/resource/tmdb" \
|
||||
-H "Cookie: session_id=$SESSION_ID"
|
||||
# → HTTP 200
|
||||
|
||||
# 3. Logout
|
||||
curl -s -X POST "$API/api/v1/auth/logout" \
|
||||
-H "Cookie: session_id=$SESSION_ID"
|
||||
# → {"success": true}
|
||||
|
||||
# 4. Use session again (rejected)
|
||||
curl -s -o /dev/null -w "HTTP %{http_code}\n" "$API/api/v1/resource/tmdb" \
|
||||
-H "Cookie: session_id=$SESSION_ID"
|
||||
# → HTTP 401
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Authentication Flow Summary
|
||||
|
||||
```
|
||||
Login Request
|
||||
│
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ 1. Check users │ ← users table (argon2 password verify)
|
||||
│ table │
|
||||
└──────┬───────────┘
|
||||
│
|
||||
┌───┴───┐
|
||||
│ match │
|
||||
└───┬───┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ 2. Create JWT │ ← 1h expiry, signed with JWT_SECRET
|
||||
├──────────────────┤
|
||||
│ 3. Create │ ← 24h expiry, stored in sessions table
|
||||
│ session │
|
||||
├──────────────────┤
|
||||
│ 4. Set-Cookie │ ← HttpOnly, SameSite=Strict, Path=/
|
||||
├──────────────────┤
|
||||
│ 5. Return │ ← JWT + api_key + user info to client
|
||||
└──────────────────┘
|
||||
```
|
||||
|
||||
```
|
||||
Protected Request
|
||||
│
|
||||
▼
|
||||
┌──────────────────────┐
|
||||
│ Middleware checks: │
|
||||
│ │
|
||||
│ 1. Cookie session? │ → DB lookup session → get api_key → verify
|
||||
│ │
|
||||
│ 2. JWT Bearer? │ → verify JWT signature → decode claims
|
||||
│ │
|
||||
│ 3. X-API-Key? │ → SHA256 hash → DB lookup → verify
|
||||
│ │
|
||||
│ 4. ?api_key=? │ → same as #3
|
||||
│ │
|
||||
│ 5. None → 401 │
|
||||
└──────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `401` | Missing or invalid authentication |
|
||||
| `401` | Session expired or logged out |
|
||||
| `401` | JWT expired |
|
||||
| `401` | API key revoked or inactive |
|
||||
|
||||
---
|
||||
|
||||
### Related
|
||||
|
||||
- `POST /api/v1/resource/tmdb/check` — test authentication + TMDb API connectivity
|
||||
- `GET /health/detailed` — view auth status (integrations section)
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,206 @@
|
||||
---
|
||||
title: health API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: health -->
|
||||
<!-- description: Health check endpoints -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## Health Check
|
||||
|
||||
### `GET /health`
|
||||
|
||||
**Auth**: Public
|
||||
**Scope**: system-level
|
||||
|
||||
Returns basic server health status — used by load balancers and monitoring.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl "$API/health" | jq '{status, version}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"version": "1.0.0",
|
||||
"build_git_hash": "3a6c1865",
|
||||
"build_timestamp": "2026-05-16T13:38:15Z",
|
||||
"uptime_ms": 3015
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `status` | string | `ok` or `degraded` |
|
||||
| `version` | string | Semver version |
|
||||
| `build_git_hash` | string | Git commit hash |
|
||||
| `build_timestamp` | string | Binary build time |
|
||||
| `uptime_ms` | integer | Milliseconds since server start |
|
||||
|
||||
---
|
||||
|
||||
### `GET /health/detailed`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Returns full system health including each service status, resource utilization, pipeline readiness, schema migration status, identity file sync status, and external integrations.
|
||||
|
||||
> Requires authentication (JWT, session cookie, or API key). The basic `/health` endpoint remains public for load balancer checks.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl "$API/health/detailed" | jq '{status, services, resources: {cpu: .resources.cpu_used_percent, memory: .resources.memory_used_percent}}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"version": "1.0.0",
|
||||
"services": {
|
||||
"postgres": {"status": "ok", "latency_ms": 3},
|
||||
"redis": {"status": "ok", "latency_ms": 1},
|
||||
"qdrant": {"status": "ok", "latency_ms": 5}
|
||||
},
|
||||
"resources": {
|
||||
"cpu_used_percent": 12.5,
|
||||
"memory_available_mb": 32768,
|
||||
"memory_used_percent": 31.7
|
||||
},
|
||||
"pipeline": {
|
||||
"scripts_ready": true,
|
||||
"scripts_count": 345,
|
||||
"processors": {
|
||||
"asr": true,
|
||||
"yolo": true,
|
||||
"face": true,
|
||||
"pose": true,
|
||||
"ocr": true,
|
||||
"cut": true,
|
||||
"scene": true,
|
||||
"asrx": true,
|
||||
"visual_chunk": true
|
||||
},
|
||||
"models_ready": true,
|
||||
"models_count": 42,
|
||||
"scripts_integrity": {"matched": 332, "total": 345, "ok": false},
|
||||
"ffmpeg": true
|
||||
},
|
||||
"schema": {
|
||||
"table_exists": true,
|
||||
"applied": [{"filename": "migrate_add_users_table.sql"}],
|
||||
"required": [],
|
||||
"ok": true
|
||||
},
|
||||
"identities": {
|
||||
"directory_exists": true,
|
||||
"files_count": 3481,
|
||||
"index_ok": true,
|
||||
"db_count": 3481,
|
||||
"synced": true
|
||||
},
|
||||
"integrations": {
|
||||
"tmdb": {
|
||||
"api_key_configured": false,
|
||||
"enabled": false,
|
||||
"api_reachable": null
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Response Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `status` | string | `ok` if all essential services healthy |
|
||||
| `services` | object | Per-service status (postgres, redis, qdrant) |
|
||||
| `services.*.status` | string | `ok`, `error`, or `degraded` |
|
||||
| `services.*.latency_ms` | int | Response time in milliseconds |
|
||||
| `resources` | object | CPU, memory usage |
|
||||
| `pipeline.scripts_ready` | boolean | Scripts directory accessible |
|
||||
| `pipeline.scripts_count` | int | Number of Python processor scripts |
|
||||
| `pipeline.processors` | object | Per-processor availability |
|
||||
| `pipeline.models_ready` | boolean | Models directory accessible |
|
||||
| `pipeline.scripts_integrity` | object | SHA256 checksum verification results |
|
||||
| `schema.ok` | boolean | All required migrations applied |
|
||||
| `identities.synced` | boolean | Identity file count matches DB count |
|
||||
| `config` | object | Runtime toggle states (cache, auto-pipeline, watcher) |
|
||||
| `integrations.tmdb` | object | TMDB API key config and reachability |
|
||||
|
||||
### `GET /health/consistency`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Scans the database for data consistency issues. Reports anomalies without modifying any data.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/health/consistency" -H "X-API-Key: $KEY" | jq '.checks[] | {check, severity, count}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "degraded",
|
||||
"checked_at": "2026-05-18T17:30:00Z",
|
||||
"checks": [
|
||||
{
|
||||
"check": "stale_processing",
|
||||
"severity": "warn",
|
||||
"count": 3,
|
||||
"files": [
|
||||
{"file_name": "video.mp4", "file_uuid": "abc123...", "status": "processing", "detail": "job_id is null"}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Check | Description | Severity |
|
||||
|-------|-------------|---------|
|
||||
| `stale_processing` | Status=processing but job_id is null | `warn` |
|
||||
| `orphaned_processing` | Status=processing but no active monitor_job | `warn` |
|
||||
| `processing_job_done` | Status=processing but job already completed | `warn` |
|
||||
| `unregistered_with_uuid` | Status=unregistered but row still in DB (migration residue) | `info` |
|
||||
|
||||
#### Health status rules
|
||||
|
||||
| Condition | status |
|
||||
|-----------|--------|
|
||||
| All services ok | `ok` |
|
||||
| Any service error | `degraded` |
|
||||
| Postgres or Redis error | `degraded` (server still responds) |
|
||||
|
||||
---
|
||||
|
||||
### Stats Endpoints
|
||||
|
||||
| Method | Endpoint | Auth | Description |
|
||||
|--------|----------|------|-------------|
|
||||
| GET | `/api/v1/stats/sftpgo` | No | SFTPGo service status |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,204 @@
|
||||
---
|
||||
title: register API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: register -->
|
||||
<!-- description: File registration — register, scan -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## File Registration
|
||||
|
||||
### `POST /api/v1/files/register`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Register a video file for processing. Returns the file's metadata and UUID.
|
||||
|
||||
Registration can **automatically trigger the processing pipeline** if the
|
||||
[auto-pipeline toggle](/api/v1/config/auto-pipeline) is enabled (disabled by default). The system will:
|
||||
1. Register the file and run ffprobe
|
||||
2. Auto-run offline TMDb probe (reads local identity files, no API calls)
|
||||
3. Create a monitor job for the worker
|
||||
4. Worker starts all 10 processors (Cut → ASR → ASRX → YOLO → OCR → Face → Pose → VisualChunk → Story → 5W1H)
|
||||
|
||||
If the file already exists (same content hash), returns the existing record with `already_exists: true`.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `file_path` | string | Yes | — | Path to video file on disk |
|
||||
| `pattern` | string | No | — | Regex pattern for batch register (requires `file_path` to be a directory) |
|
||||
| `user_id` | integer | No | — | User ID to associate with registration |
|
||||
| `content_hash` | string | No | — | Pre-computed SHA-256 hash (skips computation) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Register a single file
|
||||
curl -s -X POST "$API/api/v1/files/register" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_path": "/path/to/video.mp4"}'
|
||||
|
||||
# Batch register files matching a pattern in a directory
|
||||
curl -s -X POST "$API/api/v1/files/register" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_path": "/path/to/dir", "pattern": ".*\\.mp4$"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "3a6c1865...",
|
||||
"file_name": "video.mp4",
|
||||
"file_path": "/path/to/video.mp4",
|
||||
"file_type": "video",
|
||||
"duration": 120.5,
|
||||
"width": 1920,
|
||||
"height": 1080,
|
||||
"fps": 24.0,
|
||||
"total_frames": 2892,
|
||||
"already_exists": false,
|
||||
"message": "File registered successfully"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `file_uuid` | string | 32-char hex UUID of the registered file |
|
||||
| `file_name` | string | File name (auto-renamed if name conflict) |
|
||||
| `file_path` | string | Canonical path on disk |
|
||||
| `file_type` | string | `"video"`, `"audio"`, or `"unknown"` |
|
||||
| `duration` | float | Duration in seconds |
|
||||
| `width` | integer | Video width in pixels |
|
||||
| `height` | integer | Video height in pixels |
|
||||
| `fps` | float | Frames per second |
|
||||
| `total_frames` | integer | Total frame count |
|
||||
| `already_exists` | boolean | True if same content was already registered |
|
||||
| `message` | string | Human-readable status |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `401` | Missing or invalid API key |
|
||||
| `400` | Invalid request body |
|
||||
| `404` | File path does not exist |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/files/scan`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Scan the filesystem directory and list all media files, showing which are registered, processing, or unregistered.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number (1-based) |
|
||||
| `page_size` | integer | No | all | Items per page (alias: `limit`) |
|
||||
| `limit` | integer | No | all | Max items (alias for `page_size`) |
|
||||
| `pattern` | string | No | — | Regex filter on file name (e.g., `.*\\.mp4$`) |
|
||||
| `sort_by` | string | No | `name` | Sort field: `name`, `size`, `modified`, `status` |
|
||||
| `sort_order` | string | No | `asc` | Sort direction: `asc` or `desc` |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Full scan
|
||||
curl -s "$API/api/v1/files/scan" -H "X-API-Key: $KEY" | jq '{total, registered_count, unregistered_count}'
|
||||
|
||||
# Paginated (page 1, 5 per page)
|
||||
curl -s "$API/api/v1/files/scan?page=1&page_size=5" -H "X-API-Key: $KEY" | jq '{page, total_pages, files: [.files[].file_name]}'
|
||||
|
||||
# Regex filter: only mp4 files
|
||||
curl -s "$API/api/v1/files/scan?pattern=.*\\.mp4$" -H "X-API-Key: $KEY" | jq '{filtered_total, files: [.files[].file_name]}'
|
||||
|
||||
# Sort by file size (largest first)
|
||||
curl -s "$API/api/v1/files/scan?sort_by=size&sort_order=desc&page_size=5" -H "X-API-Key: $KEY" | jq '[.files[] | {file_name, file_size}]'
|
||||
|
||||
# Sort by modified time (most recent first)
|
||||
curl -s "$API/api/v1/files/scan?sort_by=modified&sort_order=desc&page_size=5" -H "X-API-Key: $KEY" | jq '[.files[] | {file_name, modified_time}]'
|
||||
|
||||
# Sort by status
|
||||
curl -s "$API/api/v1/files/scan?sort_by=status&page_size=5" -H "X-API-Key: $KEY" | jq '[.files[] | {file_name, status}]'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"file_name": "video.mp4",
|
||||
"file_size": 12345678,
|
||||
"is_registered": true,
|
||||
"file_uuid": "3a6c1865...",
|
||||
"status": "completed",
|
||||
"registration_time": "2026-05-16T12:00:00Z",
|
||||
"job_id": 42
|
||||
}
|
||||
],
|
||||
"total": 107,
|
||||
"filtered_total": 80,
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"total_pages": 4,
|
||||
"registered_count": 26,
|
||||
"unregistered_count": 81
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `files` | array | Array of file info objects (paginated) |
|
||||
| `files[].file_name` | string | File name |
|
||||
| `files[].relative_path` | string | Path relative to scan root |
|
||||
| `files[].file_path` | string | Absolute path on disk |
|
||||
| `files[].file_size` | integer | File size in bytes |
|
||||
| `files[].modified_time` | string | Last modified timestamp (ISO8601) |
|
||||
| `files[].is_registered` | boolean | Whether file is registered in DB |
|
||||
| `files[].file_uuid` | string | 32-char hex UUID (only if registered) |
|
||||
| `files[].status` | string | `"completed"`, `"processing"`, `"registered"`, `"unregistered"`, or `null` |
|
||||
| `files[].registration_time` | string | DB registration timestamp (only if registered) |
|
||||
| `files[].job_id` | integer | Processing job ID (only if a job exists) |
|
||||
| `total` | integer | Total files found on disk (unfiltered) |
|
||||
| `filtered_total` | integer | Files matching regex filter |
|
||||
| `page` | integer | Current page number |
|
||||
| `page_size` | integer | Items per page |
|
||||
| `total_pages` | integer | Total pages |
|
||||
| `registered_count` | integer | Files registered in DB |
|
||||
| `unregistered_count` | integer | Files not yet registered |
|
||||
|
||||
#### Notes
|
||||
|
||||
| Feature | Behavior |
|
||||
|---------|----------|
|
||||
| **Regex** | Case-insensitive (`(?i)` prefix auto-applied). Applied to `file_name`. |
|
||||
| **Sort order** | Default (`sort_by=name`): registered files first, then alphabetically. `sort_by=status`: alphabetical by status string. |
|
||||
| **Pagination** | `page_size` and `limit` are aliases. Default: show all results. |
|
||||
| **Processing order** | `pattern` regex filter → `sort_by`/`sort_order` → `page`/`page_size` slice. |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,436 @@
|
||||
---
|
||||
title: lookup API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: lookup -->
|
||||
<!-- description: File listing, lookup by name, file detail, faces, identities, JSON download, unregistration -->
|
||||
<!-- depends: 01_auth, 03_register -->
|
||||
|
||||
## File Lookup
|
||||
|
||||
### `GET /api/v1/files/lookup`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Search registered files by file name. Performs a case-insensitive LIKE search on the file name column. Returns basic info about matching files.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_name` | string | Yes | File name to search for (partial matches supported) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Look up a specific file
|
||||
curl -s "$API/api/v1/files/lookup?file_name=video.mp4" \
|
||||
-H "X-API-Key: $KEY"
|
||||
|
||||
# Partial name search
|
||||
curl -s "$API/api/v1/files/lookup?file_name=charade" \
|
||||
-H "X-API-Key: $KEY" | jq '.matches[].file_name'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_name": "video.mp4",
|
||||
"exists": true,
|
||||
"matches": [
|
||||
{
|
||||
"file_uuid": "a03485a40b2df2d3",
|
||||
"file_name": "video.mp4",
|
||||
"file_type": "video",
|
||||
"status": "completed"
|
||||
}
|
||||
],
|
||||
"next_name": "video (2).mp4"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_name` | string | Searched name |
|
||||
| `exists` | boolean | Exact name match exists |
|
||||
| `matches` | array | Array of matching registered files |
|
||||
| `matches[].file_uuid` | string | 32-char hex UUID |
|
||||
| `matches[].file_name` | string | Registered file name |
|
||||
| `matches[].file_type` | string | `"video"`, `"audio"`, or `null` |
|
||||
| `matches[].status` | string | Registration/processing status |
|
||||
| `next_name` | string | Suggested name for avoiding conflicts |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## File Listing
|
||||
|
||||
### `GET /api/v1/files`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
List all registered files with pagination. Optionally filter by status or fetch a specific file by UUID.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 20 | Items per page |
|
||||
| `status` | string | No | — | Filter by status: `registered`, `processing`, `completed`, `failed`, `indexed`, `checked_out` |
|
||||
| `file_uuid` | string | No | — | Fetch a specific file (returns as single-item list) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# List all files (paginated)
|
||||
curl -s "$API/api/v1/files?page=1&page_size=10" \
|
||||
-H "X-API-Key: $KEY"
|
||||
|
||||
# Filter by status
|
||||
curl -s "$API/api/v1/files?status=completed" \
|
||||
-H "X-API-Key: $KEY"
|
||||
|
||||
# Fetch specific file
|
||||
curl -s "$API/api/v1/files?file_uuid=$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"total": 42,
|
||||
"page": 1,
|
||||
"page_size": 10,
|
||||
"data": [
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"file_name": "video.mp4",
|
||||
"file_path": "/path/to/video.mp4",
|
||||
"status": "completed"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `total` | integer | Total file count |
|
||||
| `page` | integer | Current page |
|
||||
| `page_size` | integer | Items per page |
|
||||
| `data` | array | Array of file items |
|
||||
| `data[].file_uuid` | string | 32-char hex UUID |
|
||||
| `data[].file_name` | string | Registered file name |
|
||||
| `data[].file_path` | string | Full filesystem path |
|
||||
| `data[].status` | string | Processing status |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get detailed info for a specific registered file including metadata, duration, FPS, and probe data.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"file_name": "video.mp4",
|
||||
"file_path": "/path/to/video.mp4",
|
||||
"status": "completed",
|
||||
"duration": 120.5,
|
||||
"fps": 24.0,
|
||||
"metadata": {
|
||||
"format": {"duration": "120.5", "size": "794863677"},
|
||||
"streams": [{"codec_name": "h264", "width": 1920, "height": 1080}]
|
||||
},
|
||||
"created_at": "2026-05-16T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `file_name` | string | Registered file name |
|
||||
| `file_path` | string | Full filesystem path |
|
||||
| `status` | string | Processing status |
|
||||
| `duration` | float | Duration in seconds |
|
||||
| `fps` | float | Frames per second |
|
||||
| `metadata` | object | Full ffprobe metadata (probe.json) |
|
||||
| `created_at` | string | Registration timestamp (ISO 8601) |
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | File UUID not found |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/identities`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get all identities present in a specific file with pagination.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 20 | Items per page |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/identities?page=1&page_size=50" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"fps": 24.0,
|
||||
"total": 5,
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"data": [
|
||||
{
|
||||
"identity_id": 1,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"name": "Audrey Hepburn",
|
||||
"metadata": {"source": "tmdb", "tmdb_id": 1234},
|
||||
"face_count": 142,
|
||||
"speaker_count": 8,
|
||||
"start_frame": 100,
|
||||
"end_frame": 5000,
|
||||
"start_time": 4.17,
|
||||
"end_time": 208.33,
|
||||
"confidence": 0.87
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `data[].identity_id` | integer | Database identity ID |
|
||||
| `data[].identity_uuid` | string/null | Global identity UUID (null if unbound) |
|
||||
| `data[].name` | string | Identity name |
|
||||
| `data[].metadata` | object | Source metadata (TMDb, etc.) |
|
||||
| `data[].face_count` | integer/null | Number of face detections |
|
||||
| `data[].speaker_count` | integer/null | Number of speaker segments |
|
||||
| `data[].start_frame` | integer/null | First appearance frame |
|
||||
| `data[].end_frame` | integer/null | Last appearance frame |
|
||||
| `data[].start_time` | float/null | First appearance time (seconds) |
|
||||
| `data[].end_time` | float/null | Last appearance time (seconds) |
|
||||
| `data[].confidence` | float/null | Average detection confidence |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/faces`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
List all face detections in a specific file with pagination.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 50 | Items per page |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/faces?page=1&page_size=100" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"total": 1420,
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"data": [
|
||||
{
|
||||
"face_id": "face_100",
|
||||
"frame_number": 1200,
|
||||
"timestamp": 50.0,
|
||||
"bbox": [100, 50, 300, 400],
|
||||
"confidence": 0.95,
|
||||
"identity_id": 1,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"trace_id": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `data[].face_id` | string | Face detection ID |
|
||||
| `data[].frame_number` | integer | Frame number in video |
|
||||
| `data[].timestamp` | float | Timestamp in seconds |
|
||||
| `data[].bbox` | array | Bounding box `[x1, y1, x2, y2]` |
|
||||
| `data[].confidence` | float | Detection confidence |
|
||||
| `data[].identity_id` | integer/null | Bound identity ID (null if unbound) |
|
||||
| `data[].identity_uuid` | string/null | Bound identity UUID (null if unbound) |
|
||||
| `data[].trace_id` | integer/null | Face trace ID (null if not traced) |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/json/:processor`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Download raw JSON output for a specific processor.
|
||||
|
||||
#### Path Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `processor` | string | Yes | Processor name: `cut`, `asrx`, `yolo`, `ocr`, `face`, `pose`, `story`, etc. |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/json/face" \
|
||||
-H "X-API-Key: $KEY" | jq '.frames | length'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
Returns the raw JSON output of the specified processor. Structure varies by processor type.
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | JSON file not found |
|
||||
| `500` | Failed to parse JSON |
|
||||
|
||||
---
|
||||
|
||||
## Unregister
|
||||
|
||||
### `POST /api/v1/unregister`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Delete a registered file from the system. Supports single file by UUID, or batch by directory + regex pattern.
|
||||
|
||||
#### What gets deleted
|
||||
|
||||
| Removed (default) | Not removed |
|
||||
|---------|-------------|
|
||||
| Database records (videos, chunks, embeddings, processor_results, pre_chunks) | The original source video file on disk |
|
||||
| Processor output JSON files (`{uuid}.*.json`) — unless `delete_output_files: false` | Temp/working directories |
|
||||
| In-memory cache entries | |
|
||||
| MongoDB cached lists | |
|
||||
|
||||
> ⚠️ Database deletion is **irreversible**. To keep output files, set `"delete_output_files": false`.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
At least one mode must be specified: either `file_uuid` alone, or `file_path` + `pattern` together.
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `file_uuid` | string | * | — | Single file UUID to delete |
|
||||
| `file_path` | string | * | — | Directory path (for batch delete) |
|
||||
| `pattern` | string | * | — | Regex pattern (requires `file_path`) |
|
||||
| `delete_output_files` | boolean | No | `true` | If `true`, also delete processor output JSON files (`{uuid}.*.json`). Set to `false` to keep them. |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Delete a single file by UUID (default: also deletes output JSON files)
|
||||
curl -s -X POST "$API/api/v1/unregister" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'"}'
|
||||
|
||||
# Keep output JSON files, only delete DB records
|
||||
curl -s -X POST "$API/api/v1/unregister" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "delete_output_files": false}'
|
||||
|
||||
# Batch delete all mp4 files in a directory
|
||||
curl -s -X POST "$API/api/v1/unregister" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_path": "/path/to/dir", "pattern": ".*\\.mp4$"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "a03485a40b2df2d3",
|
||||
"message": "Video unregistered successfully"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | True if deletion succeeded |
|
||||
| `file_uuid` | string | UUID of the deleted file (single mode) |
|
||||
| `message` | string | Human-readable status |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `400` | Neither `file_uuid` nor `file_path`+`pattern` provided |
|
||||
| `404` | File UUID not found |
|
||||
| `401` | Missing or invalid API key |
|
||||
|
||||
---
|
||||
*Updated: 2026-06-20 — Added file listing, file detail, file identities, file faces, and JSON download endpoints*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,544 @@
|
||||
---
|
||||
title: process API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: process -->
|
||||
<!-- description: Processing pipeline — trigger, probe, progress, jobs -->
|
||||
<!-- depends: 01_auth, 03_register -->
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/process`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Trigger the processing pipeline for a registered file. Creates a monitor job that the worker picks up and processes sequentially. Returns immediately with the job info—processing runs asynchronously in the background.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `processors` | string[] | No | all | Specific processors to run: `["cut","asr","asrx","yolo","ocr","face","pose","visual_chunk","story","5w1h"]` |
|
||||
| `rules` | string[] | No | all | Rule names to apply (currently unused) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Run all processors
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/process" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" -d '{}'
|
||||
|
||||
# Run specific processors only
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/process" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"processors": ["asr", "face", "yolo"]}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"job_id": 42,
|
||||
"file_uuid": "3a6c1865...",
|
||||
"status": "processing",
|
||||
"pids": [12345, 12346],
|
||||
"message": "Processing triggered for video.mp4"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `job_id` | integer | Monitor job ID (for job tracking) |
|
||||
| `file_uuid` | string | 32-char hex UUID of the file |
|
||||
| `status` | string | `"queued"` — file enters the FIFO queue |
|
||||
| `pids` | integer[] | Process IDs of started processors (empty for queued) |
|
||||
| `message` | string | Human-readable status |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | File UUID not found |
|
||||
| `401` | Missing or invalid API key |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/probe`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get ffprobe metadata for a registered file. Returns video/audio stream info, codec details, duration, resolution, and frame rate.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/probe" -H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"file_name": "video.mp4",
|
||||
"file_size": 794863677,
|
||||
"duration": 120.5,
|
||||
"width": 1920,
|
||||
"height": 1080,
|
||||
"fps": 24.0,
|
||||
"total_frames": 2892,
|
||||
"cached": true,
|
||||
"format": {
|
||||
"filename": "/path/to/video.mp4",
|
||||
"format_name": "mov,mp4,m4a,3gp",
|
||||
"duration": "120.5",
|
||||
"size": "12345678",
|
||||
"bit_rate": "819200"
|
||||
},
|
||||
"streams": [
|
||||
{
|
||||
"index": 0,
|
||||
"codec_name": "h264",
|
||||
"codec_type": "video",
|
||||
"width": 1920,
|
||||
"height": 1080,
|
||||
"r_frame_rate": "24/1",
|
||||
"duration": "120.5"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `file_name` | string | File name |
|
||||
| `file_size` | integer | File size in bytes (from filesystem) |
|
||||
| `duration` | float | Duration in seconds |
|
||||
| `width` | integer | Video width in pixels |
|
||||
| `height` | integer | Video height in pixels |
|
||||
| `fps` | float | Frames per second |
|
||||
| `total_frames` | integer | Estimated total frames |
|
||||
| `cached` | boolean | True if result was from cached probe JSON |
|
||||
| `format` | object | Container format info (ffprobe format section) |
|
||||
| `streams` | array | Array of stream info objects |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/progress/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get real-time processing progress for a file via Redis pub/sub. Includes per-processor status, current/total frames, ETA, and system resource stats.
|
||||
|
||||
**Note**: This endpoint uses **POST** method, not GET. The progress data is stored in Redis as a hash, and POST is used to retrieve the latest state.
|
||||
|
||||
#### Pipeline Order
|
||||
|
||||
| Order | Processor | Dependencies | Description |
|
||||
|-------|-----------|-------------|-------------|
|
||||
| 1 | `cut` | — | Scene detection |
|
||||
| 2 | `asr` | cut | Speech-to-text (per scene) |
|
||||
| 3 | `asrx` | asr | Speaker diarization |
|
||||
| 4 | `yolo` | — | Object detection |
|
||||
| 5 | `ocr` | — | Text recognition |
|
||||
| 6 | `face` | — | Face detection & embedding (8Hz sampling) |
|
||||
| 7 | `face_trace` | face | Face tracking (IoU + embedding, assigns trace_id) |
|
||||
| 8 | `pose` | face_trace | Pose expansion from face traces, inherits trace_id |
|
||||
| 9 | `appearance` | pose | Appearance expansion from pose traces, inherits trace_id |
|
||||
|
||||
**Key Concepts:**
|
||||
- **Face** = Identity anchor (who is this person?) — requires high-quality embedding
|
||||
- **Pose** = Tracking (where is this person?) — extends tracking when face is occluded
|
||||
- **Appearance** = Tracking (what do they look like?) — extends tracking when pose is occluded
|
||||
|
||||
**Trace ID Inheritance:**
|
||||
```
|
||||
Face trace (identity anchor)
|
||||
↓ inherits trace_id
|
||||
Pose expansion (tracking continuity)
|
||||
↓ inherits trace_id
|
||||
Appearance expansion (tracking continuity)
|
||||
```
|
||||
|
||||
**Frame Count Relationship:**
|
||||
```
|
||||
face frames ≤ pose frames ≤ appearance frames
|
||||
```
|
||||
(Each level expands outward from the previous level's traces)
|
||||
|
||||
All processors except `story` and `5w1h` run concurrently when their dependencies are met. Story and 5W1H run sequentially after their prerequisites.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/progress/$FILE_UUID" -H "X-API-Key: $KEY" | jq '{overall_progress, processors: [.processors[] | {name, status}]}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"overall_progress": 71,
|
||||
"cpu_percent": 45.2,
|
||||
"gpu_percent": 30.1,
|
||||
"memory_percent": 62.4,
|
||||
"processors": [
|
||||
{"processor_type": "asr", "status": "complete", "progress": 100},
|
||||
{"processor_type": "yolo", "status": "running", "progress": 65},
|
||||
{"processor_type": "face", "status": "pending", "progress": 0}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `overall_progress` | integer | Overall progress percentage (0–100) |
|
||||
| `processors` | array | Per-processor status list |
|
||||
| `processors[].processor_type` | string | Processor name (`asr`, `cut`, `yolo`, etc.) |
|
||||
| `processors[].status` | string | `"pending"`, `"running"`, `"complete"`, or `"failed"` |
|
||||
| `processors[].progress` | integer | Per-processor progress (0–100) |
|
||||
| `processors[].eta_seconds` | integer | Estimated seconds remaining (running processors) |
|
||||
| `processors[].current` | integer | Current frame count |
|
||||
| `processors[].total` | integer | Total frame count |
|
||||
| `cpu_percent` | float | Current CPU usage |
|
||||
| `gpu_percent` | float | Current GPU utilization |
|
||||
| `memory_percent` | float | Current memory usage |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/jobs`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
List all processing jobs (monitor jobs) in the system. Shows job status, which file each job is processing, and current processor info.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/jobs" -H "X-API-Key: $KEY" | jq '{count, jobs: [.jobs[] | {uuid, status}]}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"jobs": [
|
||||
{
|
||||
"id": 42,
|
||||
"uuid": "3a6c1865...",
|
||||
"status": "running",
|
||||
"current_processor": "yolo",
|
||||
"created_at": "2026-05-16T12:00:00Z",
|
||||
"started_at": "2026-05-16T12:01:00Z"
|
||||
}
|
||||
],
|
||||
"count": 15,
|
||||
"page": 1,
|
||||
"page_size": 20
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `jobs` | array | Array of job info objects |
|
||||
| `jobs[].id` | integer | Job ID |
|
||||
| `jobs[].uuid` | string | File UUID being processed |
|
||||
| `jobs[].status` | string | `"pending"`, `"running"`, `"completed"`, `"failed"` |
|
||||
| `jobs[].current_processor` | string | Currently active processor, or null |
|
||||
| `count` | integer | Total job count |
|
||||
| `page` | integer | Current page number |
|
||||
| `page_size` | integer | Jobs per page |
|
||||
|
||||
### `GET /api/v1/job/:uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get detailed information about a specific processing job, including its queue position.
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 51,
|
||||
"uuid": "c36f35685177c981aa139b66bbbccc5b",
|
||||
"status": "queued",
|
||||
"current_processor": null,
|
||||
"progress_current": 0,
|
||||
"progress_total": 0,
|
||||
"processors": [],
|
||||
"created_at": "2026-06-22 23:08:48.497018",
|
||||
"started_at": null,
|
||||
"updated_at": null,
|
||||
"queue_position": 3
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | integer | Monitor job ID |
|
||||
| `uuid` | string | File UUID |
|
||||
| `status` | string | `"pending"`, `"queued"`, `"running"`, `"completed"`, `"failed"` |
|
||||
| `current_processor` | string | Currently active processor, or null |
|
||||
| `progress_current` | integer | Current progress count |
|
||||
| `progress_total` | integer | Total progress count |
|
||||
| `processors` | array | Processor list |
|
||||
| `created_at` | string | Job creation timestamp |
|
||||
| `started_at` | string | Processing start timestamp, or null |
|
||||
| `updated_at` | string | Last update timestamp, or null |
|
||||
| `queue_position` | integer | Position in FIFO queue (null if not pending/queued) |
|
||||
|
||||
---
|
||||
|
||||
### Status Lifecycle
|
||||
|
||||
```
|
||||
register ──→ pending
|
||||
│
|
||||
trigger (POST /process)
|
||||
│
|
||||
queued ←── queue_position counts jobs ahead
|
||||
│
|
||||
worker picks up
|
||||
│
|
||||
processing
|
||||
│
|
||||
┌────────┴────────┐
|
||||
▼ ▼
|
||||
completed failed
|
||||
│
|
||||
checkin ──→ indexed
|
||||
checkout ──→ checked_out
|
||||
```
|
||||
|
||||
| Status | Meaning |
|
||||
|--------|---------|
|
||||
| `pending` | File registered, not yet triggered |
|
||||
| `queued` | Triggered, waiting for worker in FIFO queue |
|
||||
| `processing` | Worker actively processing |
|
||||
| `completed` | All processors finished successfully |
|
||||
| `failed` | One or more essential processors failed |
|
||||
| `indexed` | Post-processing checkin complete |
|
||||
| `checked_out` | User checked out the file |
|
||||
|
||||
Queue order is FIFO (`created_at ASC`). The `GET /api/v1/job/:uuid` endpoint returns `queue_position` showing how many jobs are ahead.
|
||||
|
||||
### Frontend Status Mapping
|
||||
|
||||
When displaying file status in the frontend list (e.g. after `GET /api/v1/files/scan`), map the `status` field as follows:
|
||||
|
||||
| DB Status | Status Label | Filter: 待處理 | Filter: 處理中 | Count: pendingCount | Count: processingCount |
|
||||
|-----------|-------------|----------------|----------------|---------------------|-----------------------|
|
||||
| `unregistered` | 未註冊 | No | No | No | No |
|
||||
| `registered` | 待處理 | **Yes** | No | **Yes** | No |
|
||||
| `pending` | 待處理 | **Yes** | No | **Yes** | No |
|
||||
| `queued` | 排隊中 | **Yes** | **Yes** | **Yes** | **Yes** |
|
||||
| `processing` | 處理中 | No | **Yes** | No | **Yes** |
|
||||
| `completed` | 已完成 | No | No | No | No |
|
||||
| `failed` | 處理失敗 | No | No | No | No |
|
||||
| `indexed` | 已入庫 | No | No | No | No |
|
||||
|
||||
**`queued` 的特殊處理**:
|
||||
- `statusLabel` → 顯示「排隊中」,加 `ms-badge-warn` 樣式(黃色)
|
||||
- `filterPending` → 應包含 `queued`,讓它在「待處理」filter 可見
|
||||
- `pendingCount` + `processingCount` → 兩者都應包含 `queued`,因它既是「待處理」也是「正在排隊」
|
||||
- 在 `refreshAllStatus` / `loadFiles` 中,如果檔案狀態是 `queued`,應顯示簡單的排隊訊息(無需 polling progress)
|
||||
- 當 worker pickup 後,狀態會變為 `processing`,此時 `refreshAllStatus` 會自動偵測到並開始 polling progress
|
||||
- 也可以提供一個「queue_position」顯示:呼叫 `GET /api/v1/job/:uuid` 取得排在第幾位
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/processor-counts`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get counts of processor JSON output files. See `15_tkg.md` for full documentation.
|
||||
|
||||
---
|
||||
|
||||
## Pipeline Steps (Manual)
|
||||
|
||||
These endpoints execute individual pipeline steps. They are typically called by the worker automatically, but can be invoked manually for debugging or re-processing.
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/store-asrx`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Store ASRX diarization results as chunk records in the database. Converts ASRX segments into searchable chunk entries.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/store-asrx" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "ASRX chunks stored",
|
||||
"file_uuid": "3a6c1865..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/rule1`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Execute Rule 1 pipeline step. Applies rule-based chunking to create structured chunk records from processor outputs.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/rule1" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Rule 1 complete: 45 chunks",
|
||||
"file_uuid": "3a6c1865...",
|
||||
"chunks": 45
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `message` | string | Human-readable completion message |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `chunks` | integer | Number of chunks produced |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/vectorize`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Generate vector embeddings for all chunks of a file and store them in Qdrant for semantic search.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/vectorize" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Vectorization complete",
|
||||
"file_uuid": "3a6c1865..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/phase1`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Execute Phase 1 of the post-processing pipeline. Combines store-asrx, rule1, and vectorize into a single step.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/phase1" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Phase 1 complete",
|
||||
"file_uuid": "3a6c1865..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/complete`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Mark a video as fully processed. Updates the video status to `completed` and finalizes all pipeline state.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/complete" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Video marked as completed",
|
||||
"file_uuid": "3a6c1865..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Pipeline Step Order
|
||||
|
||||
```
|
||||
process (trigger)
|
||||
│
|
||||
├─→ cut, yolo, ocr, face, pose, asrx (parallel processors)
|
||||
│
|
||||
├─→ store-asrx (store diarization as chunks)
|
||||
│
|
||||
├─→ rule1 (rule-based chunking)
|
||||
│
|
||||
├─→ vectorize (embed chunks to Qdrant)
|
||||
│
|
||||
└─→ complete (mark done)
|
||||
```
|
||||
|
||||
Phase 1 (`/phase1`) combines store-asrx + rule1 + vectorize into one call.
|
||||
|
||||
---
|
||||
*Updated: 2026-06-23 — Added queued status, FIFO queue order, queue_position in job detail, frontend status mapping table*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,388 @@
|
||||
---
|
||||
title: search API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: search -->
|
||||
<!-- description: Vector search, BM25, smart search, universal search, LLM reranked search, frame search -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## Search APIs
|
||||
|
||||
### `POST /api/v1/search/smart`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: global / file-level
|
||||
|
||||
Semantic vector search using EmbeddingGemma-300m. Generates a query embedding via EmbeddingGemma (port 11436), then searches pgvector `story_parent` and `llm_parent` chunks by cosine similarity.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `query` | string | Yes | — | Search text |
|
||||
| `file_uuid` | string | No | — | File UUID to search within. If omitted, searches all files (global search) |
|
||||
| `limit` | integer | No | 5 | Max results to return |
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 5 | Items per page |
|
||||
|
||||
#### Example (Global Search)
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/search/smart" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $JWT" \
|
||||
-d '{"query": "Audrey Hepburn"}'
|
||||
```
|
||||
|
||||
#### Example (File-specific Search)
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/search/smart" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $JWT" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "query": "Audrey Hepburn"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "Audrey Hepburn",
|
||||
"results": [
|
||||
{
|
||||
"file_uuid": "a6fb22eebefaef17e62af874997c5944",
|
||||
"parent_id": 1087822,
|
||||
"scene_order": 1087822,
|
||||
"start_frame": 104438,
|
||||
"end_frame": 104538,
|
||||
"fps": 24.0,
|
||||
"start_time": 4351.6,
|
||||
"end_time": 4355.76,
|
||||
"summary": "[4352s-4356s, 4s] Cast: Audrey Hepburn. Total: 2 lines, 10 words. Speakers: Audrey Hepburn (2 lines)",
|
||||
"similarity": 0.67
|
||||
}
|
||||
],
|
||||
"page": 1,
|
||||
"page_size": 5,
|
||||
"strategy": "semantic_vector_search"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `results[].file_uuid` | string | File UUID where result was found |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/search/universal`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: global / file-level
|
||||
|
||||
Multi-type BM25 full-text search across chunks, frames, and persons. Uses PostgreSQL `tsvector`.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `query` | string | Yes | — | Search text |
|
||||
| `file_uuid` | string | No | — | Restrict to specific file. If omitted, searches all files (global search) |
|
||||
| `types` | string[] | No | `["chunk","frame","person"]` | Search types |
|
||||
| `limit` | integer | No | 10 | Max results per type |
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 20 | Items per page |
|
||||
|
||||
#### Example (Global Search)
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/search/universal" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $JWT" \
|
||||
-d '{"query": "Cary Grant"}'
|
||||
```
|
||||
|
||||
#### Example (File-specific Search)
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/search/universal" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $JWT" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "query": "Cary Grant"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"type": "chunk",
|
||||
"file_uuid": "a6fb22eebefaef17e62af874997c5944",
|
||||
"chunk_id": "bd80fec92b0b6963d177a2c55bf713e2_2",
|
||||
"chunk_type": "story_child",
|
||||
"start_frame": 5103,
|
||||
"end_frame": 5127,
|
||||
"start_time": 212.64,
|
||||
"end_time": 213.64,
|
||||
"text": "[213s-214s] Cary Grant: \"Olá!\"",
|
||||
"score": 0.9
|
||||
},
|
||||
{
|
||||
"type": "frame",
|
||||
"file_uuid": "a6fb22eebefaef17e62af874997c5944",
|
||||
"frame_number": 5105,
|
||||
"timestamp": 212.72,
|
||||
"score": 0.7,
|
||||
"objects": null,
|
||||
"ocr_texts": null,
|
||||
"faces": null
|
||||
},
|
||||
{
|
||||
"type": "person",
|
||||
"file_uuid": "a6fb22eebefaef17e62af874997c5944",
|
||||
"identity_id": 12,
|
||||
"identity_uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"name": "Cary Grant",
|
||||
"appearance_count": 542,
|
||||
"score": 0.95
|
||||
}
|
||||
],
|
||||
"total": 20,
|
||||
"took_ms": 18
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `results[].type` | string | Result type: `chunk`, `frame`, or `person` |
|
||||
| `results[].file_uuid` | string | File UUID where result was found (all types) |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/search/frames`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: global / file-level
|
||||
|
||||
Search frames by YOLO objects, OCR text, face IDs, or pose detections. Filters frames based on visual content detected during processing.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `file_uuid` | string | No | — | Restrict to specific file |
|
||||
| `object_class` | string | No | — | Filter by YOLO object class (e.g., `person`, `car`, `dog`) |
|
||||
| `ocr_text` | string | No | — | Filter by OCR text content (ILIKE match) |
|
||||
| `face_id` | string | No | — | Filter by face detection ID |
|
||||
| `time_range` | [float, float] | No | — | Filter by time range `[start_secs, end_secs]` |
|
||||
| `limit` | integer | No | 100 | Max results |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Search for frames containing "person" objects
|
||||
curl -s -X POST "$API/api/v1/search/frames" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "object_class": "person", "limit": 20}'
|
||||
|
||||
# Search for frames with specific OCR text
|
||||
curl -s -X POST "$API/api/v1/search/frames" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "ocr_text": "hello", "time_range": [10.0, 30.0]}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"frames": [
|
||||
{
|
||||
"frame_number": 1200,
|
||||
"timestamp": 50.0,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"objects": [{"class": "person", "confidence": 0.95, "bbox": [100, 50, 300, 400]}],
|
||||
"ocr_texts": ["Hello World"],
|
||||
"faces": [{"face_id": "face_42", "confidence": 0.88}],
|
||||
"pose_persons": [{"trace_id": 2, "bbox": [120, 60, 280, 380]}]
|
||||
}
|
||||
],
|
||||
"total": 15
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `frames` | array | Array of matching frame objects |
|
||||
| `frames[].frame_number` | integer | Frame number in video |
|
||||
| `frames[].timestamp` | float | Timestamp in seconds |
|
||||
| `frames[].file_uuid` | string | File UUID |
|
||||
| `frames[].objects` | array/null | YOLO detections in this frame |
|
||||
| `frames[].ocr_texts` | array/null | OCR text strings in this frame |
|
||||
| `frames[].faces` | array/null | Face detections in this frame |
|
||||
| `frames[].pose_persons` | array/null | Pose-detected persons in this frame |
|
||||
| `total` | integer | Total matching frame count |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/search/llm-smart`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: global / file-level
|
||||
|
||||
Smart search with LLM re-ranking. First fetches candidate results via RRF (Reciprocal Rank Fusion) using the existing smart search, then uses an LLM (Gemma4 on port 8000) to re-rank candidates by relevance to the query.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `query` | string | Yes | — | Search text |
|
||||
| `file_uuid` | string | No | — | File UUID to search within |
|
||||
| `limit` | integer | No | 10 | Max results to return |
|
||||
|
||||
#### Pipeline
|
||||
|
||||
```
|
||||
1. smart_search → fetch N candidates (limit × 3, clamped 10-20)
|
||||
2. LLM rerank → re-order by relevance using Gemma4
|
||||
3. trim → return top `limit` results
|
||||
```
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/search/llm-smart" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"query": "two people having a conversation about business", "limit": 5}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "two people having a conversation about business",
|
||||
"results": [
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"parent_id": 1234,
|
||||
"scene_order": 1234,
|
||||
"start_frame": 5000,
|
||||
"end_frame": 5200,
|
||||
"fps": 24.0,
|
||||
"start_time": 208.3,
|
||||
"end_time": 216.7,
|
||||
"summary": "[208s-217s, 9s] Two people discussing project timeline...",
|
||||
"similarity": 0.72
|
||||
}
|
||||
],
|
||||
"page": 1,
|
||||
"page_size": 5,
|
||||
"strategy": "llm_reranked"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `strategy` | string | Always `"llm_reranked"` for this endpoint |
|
||||
| `results` | array | Re-ranked search results (same format as smart search) |
|
||||
|
||||
#### Fallback
|
||||
|
||||
If LLM reranking fails (model unavailable, timeout), falls back to RRF order without error.
|
||||
|
||||
---
|
||||
|
||||
### Visual Search
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: global / file-level
|
||||
|
||||
Search text chunks → find associated identities. Returns chunks where face detections overlap with text content.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `q` | string | Yes | — | Search text (ILIKE match) |
|
||||
| `file_uuid` | string | No | — | Restrict to specific file. If omitted, searches all files (global search) |
|
||||
| `limit` | integer | No | 50 | Max results |
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 50 | Items per page |
|
||||
|
||||
#### Example (Global Search)
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/search/identity_text?q=love" -H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Example (File-specific Search)
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/search/identity_text?file_uuid=$FILE_UUID&q=love" -H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"total": 5,
|
||||
"results": [
|
||||
{
|
||||
"file_uuid": "a6fb22eebefaef17e62af874997c5944",
|
||||
"chunk_id": "llm_parent_..._256_270",
|
||||
"start_time": 256.256,
|
||||
"end_time": 270.228,
|
||||
"text_content": "...lack of affection...",
|
||||
"identity_id": 9,
|
||||
"identity_name": "Audrey Hepburn",
|
||||
"identity_source": "tmdb",
|
||||
"trace_id": 94
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `results[].file_uuid` | string | File UUID where chunk was found |
|
||||
| `results[].identity_id` | integer | Identity ID if face was detected |
|
||||
| `results[].trace_id` | integer | Face trace ID |
|
||||
|
||||
---
|
||||
|
||||
### Visual Search (Planned)
|
||||
|
||||
| Method | Endpoint | Status | Description |
|
||||
|--------|----------|--------|-------------|
|
||||
| POST | `/api/v1/search/visual` | Not implemented | Search visual chunks |
|
||||
| POST | `/api/v1/search/visual/class` | Not implemented | Search by object class |
|
||||
| POST | `/api/v1/search/visual/density` | Not implemented | Search by object density |
|
||||
| POST | `/api/v1/search/visual/combination` | Not implemented | Search by object combination |
|
||||
| POST | `/api/v1/search/visual/stats` | Not implemented | Visual chunk statistics |
|
||||
|
||||
#### Embedding Model
|
||||
|
||||
| Detail | Value |
|
||||
|--------|-------|
|
||||
| **Model** | EmbeddingGemma-300m |
|
||||
| **Endpoint** | `POST /api/v1/embeddings` on port 11436 |
|
||||
| **Dimension** | 768 |
|
||||
| **Storage** | pgvector (`chunk.embedding` column) |
|
||||
|
||||
---
|
||||
*Updated: 2026-06-20 — Added llm-smart search, completed frames search documentation, marked visual search as planned*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,143 @@
|
||||
---
|
||||
title: identity agent API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: identity_agent -->
|
||||
<!-- description: Identity agent — match from photo, match from trace -->
|
||||
<!-- depends: 01_auth, 07_identity -->
|
||||
|
||||
## Identity Agent
|
||||
|
||||
### `POST /api/v1/agents/identity/match-from-photo`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Upload a face photo to match against known identities. Detects face via InsightFace, extracts 512D embedding via CoreML FaceNet, then searches pgvector for the closest identity.
|
||||
|
||||
#### Request
|
||||
|
||||
`multipart/form-data` with field `image` (JPEG/PNG) and optional `file_uuid`.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/agents/identity/match-from-photo" \
|
||||
-H "Authorization: Bearer $JWT" \
|
||||
-F "image=@/path/to/face.jpg" \
|
||||
-F "file_uuid=$FILE_UUID"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"matches": [
|
||||
{
|
||||
"identity_uuid": "a9a90105...",
|
||||
"name": "Cary Grant",
|
||||
"similarity": 0.87
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/agents/identity/match-from-trace`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Match a face trace (tracked face across frames) against known identities. Samples 3 angles from the trace, generates embeddings, and searches pgvector.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File containing the trace |
|
||||
| `trace_id` | integer | Yes | Face trace ID to match |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/agents/identity/match-from-trace" \
|
||||
-H "Authorization: Bearer $JWT" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "trace_id": 10}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/agents/identity/confirm`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Confirm identity binding for a trace. This marks the trace as confirmed in TKG, updates face_detections, adds to _seeds, and optionally triggers Round 2 propagation.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | Video file UUID |
|
||||
| `trace_id` | integer | Yes | Face trace ID to confirm |
|
||||
| `identity_id` | integer | Yes | Identity internal ID |
|
||||
| `identity_uuid` | string | Yes | Identity UUID |
|
||||
| `name` | string | Yes | Identity name |
|
||||
| `propagate` | boolean | No | Auto-trigger Round 2 matching (default: true) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/agents/identity/confirm" \
|
||||
-H "Authorization: Bearer $JWT" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'", "trace_id": 10, "identity_id": 42, "identity_uuid": "'"$IDENTITY_UUID"'", "name": "Cary Grant", "propagate": false}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"trace_id": 10,
|
||||
"identity_uuid": "a9a90105...",
|
||||
"name": "Cary Grant",
|
||||
"steps": {
|
||||
"tkg_updated": true,
|
||||
"qdrant_updated": 150,
|
||||
"pg_updated": 150,
|
||||
"seed_added": true
|
||||
},
|
||||
"propagation": {
|
||||
"matched": 5,
|
||||
"message": "Propagation completed"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Side Effects
|
||||
|
||||
1. TKG face_track node status → 'confirmed'
|
||||
2. Qdrant _faces: identity_uuid added to payload
|
||||
3. PG face_detections: identity_id set
|
||||
4. Trace centroid added to _seeds (source='propagation')
|
||||
5. Round 2 matching triggered (if propagate=true)
|
||||
|
||||
---
|
||||
*Updated: 2026-06-26 00:30:00*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,553 @@
|
||||
---
|
||||
title: Media API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: media -->
|
||||
<!-- description: Video streaming & frame extraction -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## Video Streaming & Frame Extraction
|
||||
|
||||
All video streaming endpoints support the following common query parameters:
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `mode` | string | No | `normal` | `normal` or `debug` (draws detection overlays) |
|
||||
| `audio` | string | No | `on` | `on` or `off` |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/video`
|
||||
|
||||
Stream the full video file with range support for seeking.
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: Video stream (`Content-Type` based on file extension)
|
||||
- **206**: Partial content (range request)
|
||||
- Supports `Range` header for seeking
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/trace/:trace_id/video`
|
||||
|
||||
Stream video with highlights for a specific face trace (follows a single person across frames with bounding box overlay).
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/trace/:trace_id/representative-face`
|
||||
|
||||
Find the best single face to represent this trace. Uses a two-stage selection: SQL (area × confidence → top 10) then FFmpeg `blurdetect` (sharpness → pick the least blurry).
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/trace/1939/representative-face" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"trace_id": 1939,
|
||||
"face_count": 538,
|
||||
"representative": {
|
||||
"frame_number": 68193,
|
||||
"timestamp_secs": 2727.72,
|
||||
"bbox": { "x": 347, "y": 378, "width": 427, "height": 427 },
|
||||
"confidence": 0.760,
|
||||
"quality_score": 138516,
|
||||
"blur_score": 9.46
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Response Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `trace_id` | integer | Face trace ID |
|
||||
| `face_count` | integer | Total face detections in this trace |
|
||||
| `representative.frame_number` | integer | Frame number of the selected face (primary coordinate) |
|
||||
| `representative.timestamp_secs` | float | Time in seconds (derived from `frame_number / fps`) |
|
||||
| `representative.bbox` | object | Bounding box `{x, y, width, height}` |
|
||||
| `representative.confidence` | float | Detection confidence (0.0–1.0) |
|
||||
| `representative.quality_score` | float | Pre-selection score (`area × confidence`) |
|
||||
| `representative.blur_score` | float | FFmpeg blurdetect result (lower = sharper) |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/trace/:trace_id/thumbnail`
|
||||
|
||||
Extract the best face image for a trace as JPEG (320×320). Internally selects the face using the same two-stage algorithm as `representative-face`, then crops via FFmpeg. The result is cacheable for 24 hours.
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/trace/1939/thumbnail" \
|
||||
-H "X-API-Key: $KEY" -o trace_1939_face.jpg
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: `image/jpeg` binary data (320×320 cropped face)
|
||||
- **404**: File, trace not found, or no suitable face
|
||||
- **500**: FFmpeg or database error
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/identities/:identity_uuid_a/co-occur-with/:identity_uuid_b`
|
||||
|
||||
Find the first frame where two identities appear together, with representative face thumbnails for both.
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Audrey Hepburn & Cary Grant 第一次同框
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/identities/$AUDREY_UUID/co-occur-with/$CARY_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '{identity_a: .identity_a.name, identity_b: .identity_b.name, first_frame: .first_cooccurrence.frame_number}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"identity_a": {
|
||||
"identity_uuid": "c3545906-c82d-4b66-aa1d-150bc02decce",
|
||||
"name": "Audrey Hepburn",
|
||||
"trace_id": 920
|
||||
},
|
||||
"identity_b": {
|
||||
"identity_uuid": "2b0ddefe-e2a9-4533-9308-b375594604d5",
|
||||
"name": "Cary Grant",
|
||||
"trace_id": 919
|
||||
},
|
||||
"first_cooccurrence": {
|
||||
"frame_number": 38165,
|
||||
"timestamp_secs": 1526.60,
|
||||
"total_cooccurrence_frames": 3136,
|
||||
"representative_face_a": {
|
||||
"frame_number": 38199,
|
||||
"bbox": { "x": 122, "y": 339, "width": 176, "height": 176 },
|
||||
"confidence": 0.832,
|
||||
"thumbnail_url": "/api/v1/file/aeed71342.../trace/920/thumbnail"
|
||||
},
|
||||
"representative_face_b": {
|
||||
"frame_number": 38291,
|
||||
"bbox": { "x": 511, "y": 315, "width": 192, "height": 192 },
|
||||
"confidence": 0.791,
|
||||
"thumbnail_url": "/api/v1/file/aeed71342.../trace/919/thumbnail"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Response Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `identity_a.name` | string | First identity name |
|
||||
| `identity_b.name` | string | Second identity name |
|
||||
| `first_cooccurrence.frame_number` | int | First frame where both appear |
|
||||
| `first_cooccurrence.timestamp_secs` | float | Time in seconds |
|
||||
| `first_cooccurrence.total_cooccurrence_frames` | int | Total frames with both present |
|
||||
| `first_cooccurrence.representative_face_a/b` | object | Best face thumbnail data for each identity |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | File or identity not found |
|
||||
| `404` | The two identities never co-occur in this file |
|
||||
| `500` | Database or FFmpeg error |
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/video/bbox`
|
||||
|
||||
Stream video with bounding box overlay for all detected objects/faces.
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Uses a built-in 5×7 bitmap font renderer to draw labels directly on video frames via FFmpeg `drawtext` filter.
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/thumbnail`
|
||||
|
||||
Extract a single frame from a video as JPEG image. Uses FFmpeg `select` filter.
|
||||
|
||||
When `frame` is omitted, the system automatically selects the best representative frame using the TKG bridge (see algorithm below).
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `frame` | integer | No | auto-detect | Zero-based frame number to extract. Omit for auto-detect. |
|
||||
| `x` | integer | No | — | Crop start X (left edge). Requires `y`, `w`, `h`. |
|
||||
| `y` | integer | No | — | Crop start Y (top edge). Requires `x`, `w`, `h`. |
|
||||
| `w` | integer | No | — | Crop width in pixels. Requires `x`, `y`, `h`. |
|
||||
| `h` | integer | No | — | Crop height in pixels. Requires `x`, `y`, `w`. |
|
||||
|
||||
All four crop params (`x`, `y`, `w`, `h`) must be provided together or omitted.
|
||||
|
||||
#### Auto-detect Algorithm
|
||||
|
||||
When `frame` is not provided, the endpoint finds the best frame using this fallback chain:
|
||||
|
||||
1. **Main characters**: find the two identities with the most face detections (TMDb source)
|
||||
2. **Mutual gaze**: if their face traces have a TKG `CO_OCCURS_WITH` edge with `mutual_gaze=true`, take `first_frame`
|
||||
3. **Co-occurrence**: fallback to the first frame where both identities appear together
|
||||
4. **Single identity**: if only one main identity exists, take its highest-quality face frame
|
||||
5. **Any identity**: fallback to the best-quality face frame across all identities
|
||||
6. **Error**: if no face exists, returns `404`
|
||||
|
||||
The selected frame is constrained to the **first half of the video** (`total_frames / 2`).
|
||||
|
||||
#### Examples
|
||||
|
||||
```bash
|
||||
# Auto-detect best representative frame
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/thumbnail" \
|
||||
-H "X-API-Key: $KEY" -o representative.jpg
|
||||
|
||||
# Extract frame 1000 (full frame)
|
||||
curl -s "$API/api/v1/file/bd80fec92b0b6963d177a2c55bf713e2/thumbnail?frame=1000" \
|
||||
-H "Authorization: Bearer $JWT" -o frame_1000.jpg
|
||||
|
||||
# Extract and crop face region (x=320, y=240, w=160, h=160)
|
||||
curl -s "$API/api/v1/file/bd80fec92b0b6963d177a2c55bf713e2/thumbnail?frame=1000&x=320&y=240&w=160&h=160" \
|
||||
-H "Authorization: Bearer $JWT" -o face_crop.jpg
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: `image/jpeg` binary data
|
||||
- **404**: File not found / No faces in file (auto-detect)
|
||||
- **500**: FFmpeg error (e.g., frame number exceeds video duration)
|
||||
|
||||
#### Technical Details
|
||||
|
||||
| Detail | Value |
|
||||
|--------|-------|
|
||||
| **Backend** | FFmpeg (`ffmpeg-full`) |
|
||||
| **Filter** | `select=eq(n\,FRAME)` to select frame, optional `crop=W:H:X:Y` |
|
||||
| **Output** | Single JPEG via pipe (`image2pipe`, `mjpeg` codec) |
|
||||
| **Cache** | `Cache-Control: public, max-age=86400` (24h) |
|
||||
| **Frame number** | Zero-based (`frame=0` = first frame of video) |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/representative-frame`
|
||||
|
||||
Return JSON metadata about the best representative frame for the video. Uses the same auto-detect algorithm as `GET /thumbnail` (without crop support).
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/representative-frame" \
|
||||
-H "X-API-Key: $KEY" | jq '.'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"frame_number": 38165,
|
||||
"timestamp_secs": 1526.6,
|
||||
"face_quality": 37292.97,
|
||||
"main_identities": [
|
||||
{
|
||||
"identity_uuid": "c3545906-c82d-4b66-aa1d-150bc02decce",
|
||||
"name": "Audrey Hepburn",
|
||||
"face_count": 16456
|
||||
},
|
||||
{
|
||||
"identity_uuid": "2b0ddefe-e2a9-4533-9308-b375594604d5",
|
||||
"name": "Cary Grant",
|
||||
"face_count": 10643
|
||||
}
|
||||
],
|
||||
"traces": [
|
||||
{
|
||||
"trace_id": 919,
|
||||
"identity_uuid": "2b0ddefe-e2a9-4533-9308-b375594604d5",
|
||||
"name": "Cary Grant",
|
||||
"x": 764,
|
||||
"y": 237,
|
||||
"width": 199,
|
||||
"height": 199,
|
||||
"confidence": 0.8426
|
||||
},
|
||||
{
|
||||
"trace_id": 920,
|
||||
"identity_uuid": "c3545906-c82d-4b66-aa1d-150bc02decce",
|
||||
"name": "Audrey Hepburn",
|
||||
"x": 1143,
|
||||
"y": 312,
|
||||
"width": 215,
|
||||
"height": 215,
|
||||
"confidence": 0.8068
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Response Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `frame_number` | integer | Selected representative frame number (primary coordinate) |
|
||||
| `timestamp_secs` | float | Time in seconds (derived from `frame_number / fps`) |
|
||||
| `face_quality` | float | Quality score `area × confidence` of the best face at this frame |
|
||||
| `main_identities` | array | Top 2 most frequent TMDb identities in the file |
|
||||
| `main_identities[].name` | string | Identity display name |
|
||||
| `main_identities[].face_count` | integer | Total face detections count |
|
||||
| `traces` | array | All face traces present at the selected frame |
|
||||
| `traces[].trace_id` | integer | Face trace ID |
|
||||
| `traces[].identity_uuid` | string or null | Matched identity UUID |
|
||||
| `traces[].name` | string or null | Identity name |
|
||||
| `traces[].x, y, width, height` | integer | Bounding box coordinates |
|
||||
| `traces[].confidence` | float | Detection confidence (0.0–1.0) |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | File not found / No faces in file |
|
||||
| `500` | Database error |
|
||||
|
||||
Extract a video clip (time range) as MPEG-TS stream. Uses FFmpeg `-ss` fast seek.
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `start_frame` | integer | No* | — | Start frame (zero-based). **Frame-accurate** — use this for precision. |
|
||||
| `end_frame` | integer | No* | — | End frame (zero-based, inclusive). Requires `start_frame`. |
|
||||
| `start_time` | float | No* | — | Start time in seconds. Approximate (FPS-dependent). Fallback if frames not given. |
|
||||
| `end_time` | float | No* | — | End time in seconds. Approximate (FPS-dependent). Fallback if frames not given. |
|
||||
| `fps` | float | No | video FPS | Override frames-per-second for frame↔time calculation. Defaults to video's detected FPS. |
|
||||
| `mode` | string | No | `normal` | `normal` or `debug` (draws "CLIP" overlay) |
|
||||
| `audio` | string | No | `on` | `on` or `off` |
|
||||
|
||||
Either (`start_frame`+`end_frame`) OR (`start_time`+`end_time`) must be provided.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Clip by frame range (primary)
|
||||
curl -s "$API/api/v1/file/bd80fec92b0b6963d177a2c55bf713e2/clip?start_frame=0&end_frame=47" \
|
||||
-H "Authorization: Bearer $JWT" -o clip.ts
|
||||
|
||||
# Clip by time range (fallback)
|
||||
curl -s "$API/api/v1/file/bd80fec92b0b6963d177a2c55bf713e2/clip?start_time=30&end_time=45" \
|
||||
-H "Authorization: Bearer $JWT" -o clip.ts
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: `video/mp2t` MPEG-TS stream
|
||||
- **400**: Missing/invalid range parameters
|
||||
- **404**: File not found
|
||||
- **500**: FFmpeg error
|
||||
|
||||
#### Technical Notes
|
||||
|
||||
| Detail | Value |
|
||||
|--------|-------|
|
||||
| **Backend** | FFmpeg (`ffmpeg-full`) |
|
||||
| **Seek** | `-ss` before `-i` (fast keyframe seek) |
|
||||
| **Format** | MPEG-TS (`mpegts` muxer, pipe-safe) |
|
||||
| **Codec** | H.264 + AAC |
|
||||
| **Cache** | `Cache-Control: public, max-age=86400` (24h) |
|
||||
|
||||
### Video vs Clip: Quality & Format Comparison
|
||||
|
||||
Both endpoints support time range extraction, but serve different use cases:
|
||||
|
||||
| Feature | `/video` | `/clip` |
|
||||
|---------|----------|---------|
|
||||
| **No params** | Streams full file (Range seek) | Returns 400 (params required) |
|
||||
| **HTTP Range** | ✅ Supported | ❌ Not supported |
|
||||
| **Encoding** | `-c copy` (zero encoding) | `-c:v libx264 -c:a aac` (re-encode) |
|
||||
| **Quality** | Original (bit-exact, zero loss) | Compressed (default CRF ≈ 23) |
|
||||
| **Format** | `video/mp4` | `video/mp2t` (MPEG-TS) |
|
||||
| **Speed** | Fast (no computation) | Slower (encoding required) |
|
||||
| **Frame control** | Time-based (`dur = (ef-sf)/fps`) | Precise (`-vframes`) |
|
||||
| **Debug mode** | ❌ | ✅ `mode=debug` overlay |
|
||||
| **Cache** | ❌ | ✅ `max-age=86400` |
|
||||
|
||||
#### Usage Recommendation
|
||||
|
||||
| Scenario | Use |
|
||||
|----------|-----|
|
||||
| Full video streaming / player seek | `/video` |
|
||||
| Quick preview clip (zero quality loss) | `/video?start_frame=...&end_frame=...` |
|
||||
| Debug frame verification / text overlay | `/clip?mode=debug` |
|
||||
| Precise frame count control | `/clip` |
|
||||
| CDN cacheable clip | `/clip` |
|
||||
|
||||
---
|
||||
|
||||
| Detail | Value |
|
||||
|--------|-------|
|
||||
| **Backend** | FFmpeg (`ffmpeg-full`) |
|
||||
| **Filter** | `select=eq(n\,FRAME)` to select frame, optional `crop=W:H:X:Y` |
|
||||
| **Output** | Single JPEG via pipe (`image2pipe`, `mjpeg` codec) |
|
||||
| **Cache** | `Cache-Control: public, max-age=86400` (24h) |
|
||||
| **Frame number** | Zero-based (`frame=0` = first frame of video) |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/stranger/:stranger_id/representative-face`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get the representative face for a stranger (unidentified face trace).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/stranger/1/representative-face" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"stranger_id": 1,
|
||||
"face_count": 85,
|
||||
"representative": {
|
||||
"frame_number": 5000,
|
||||
"timestamp_secs": 208.33,
|
||||
"bbox": {"x": 200, "y": 100, "width": 150, "height": 150},
|
||||
"confidence": 0.92,
|
||||
"quality_score": 20700,
|
||||
"blur_score": 8.5
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/stranger/:stranger_id/thumbnail`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Extract the best face image for a stranger as JPEG (320×320).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/stranger/1/thumbnail" \
|
||||
-H "X-API-Key: $KEY" -o stranger_1_face.jpg
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: `image/jpeg` binary data (320×320 cropped face)
|
||||
- **404**: File or stranger not found
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/chunk/:chunk_id/thumbnail`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get thumbnail for a specific chunk. Extracts the representative frame for the chunk's time range.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/chunk/chunk_1/thumbnail" \
|
||||
-H "X-API-Key: $KEY" -o chunk_1.jpg
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: `image/jpeg` binary data
|
||||
- **404**: File or chunk not found
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/media-proxy`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Proxy request to fetch media from external URLs. Useful for loading profile images or thumbnails from external services (TMDb, etc.) without exposing the external URL to the client.
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `url` | string | Yes | External URL to proxy |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/media-proxy?url=https://image.tmdb.org/t/p/w500/abc123.jpg" \
|
||||
-H "X-API-Key: $KEY" -o tmdb_profile.jpg
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
- **200**: Proxied media data (Content-Type from external source)
|
||||
- **400**: Missing or invalid URL parameter
|
||||
- **500**: External request failed
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
*Updated: 2026-06-20 — Added stranger endpoints, chunk thumbnail, and media proxy*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,217 @@
|
||||
---
|
||||
title: tmdb API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: tmdb -->
|
||||
<!-- description: TMDb enrichment endpoints — prefetch, probe, resource, check -->
|
||||
<!-- depends: 01_auth, 03_register -->
|
||||
|
||||
## TMDb Enrichment
|
||||
|
||||
> **Offline operation**: TMDb prefetch now checks local identity files first (`identities/_index.json` + `*.tmdb.json`).
|
||||
> If local files exist, no external API call is made. Internet is only needed for initial data seeding.
|
||||
|
||||
### Overview
|
||||
|
||||
TMDb enrichment is an optional identity enrichment step that can be run after Pipeline face detection completes. The workflow is:
|
||||
|
||||
1. **Prefetch** (requires internet): Download movie cast data from TMDb API → cache to `{file_uuid}.tmdb.json`
|
||||
2. **Probe**: Read local cache → create identities for **all** cast members (`source='tmdb'`) + save `identity.json` + download profile image to `{OUTPUT}/identities/{uuid}/profile.jpg`
|
||||
3. **Match**: The worker automatically matches video faces against TMDb identities when `MOMENTRY_TMDB_PROBE_ENABLED=true`
|
||||
|
||||
### `POST /api/v1/agents/tmdb/prefetch`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Fetch TMDb cast data for a registered file and cache it locally. This is the only step requiring internet access.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID to enrich |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/agents/tmdb/prefetch" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"file_uuid": "'"$FILE_UUID"'"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{"success": true, "file_uuid": "...", "cache_path": "/output/...tmdb.json"}
|
||||
```
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tmdb-probe`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Read local TMDb cache and create/update identities. Requires prefetch to have been run first.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tmdb-probe" \
|
||||
-H "X-API-Key: $KEY" | jq '{identities_created, movie_title}'
|
||||
```
|
||||
|
||||
#### Response (200 — identities created)
|
||||
|
||||
```json
|
||||
{"success": true, "identities_created": 15, "movie_title": "Charade"}
|
||||
```
|
||||
|
||||
#### Response (200 — no cache)
|
||||
|
||||
```json
|
||||
{"success": false, "message": "No TMDb cache found. Run tmdb-prefetch first."}
|
||||
```
|
||||
|
||||
### `GET /api/v1/resource/tmdb`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
View TMDb resource status including configuration, identity counts, and cache file count.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/resource/tmdb" -H "X-API-Key: $KEY" \
|
||||
| jq '{identities_seeded, cache_files}'
|
||||
```
|
||||
|
||||
### `POST /api/v1/resource/tmdb/check`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Ping the TMDb API to verify connectivity and measure latency.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/resource/tmdb/check" \
|
||||
-H "X-API-Key: $KEY" | jq '.status'
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"api_key_configured": true,
|
||||
"enabled": false,
|
||||
"api_reachable": true,
|
||||
"api_latency_ms": 120
|
||||
}
|
||||
```
|
||||
|
||||
### `POST /api/v1/tmdb/fetch`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Fetch TMDb data by filename, create identities with profile images and embeddings. Similar to prefetch+probe combined, but also downloads profile images and generates embeddings.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `filename` | string | Yes | Movie filename to search TMDb for |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/tmdb/fetch" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"filename": "charade.mp4"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"movie_title": "Charade (1963)",
|
||||
"tmdb_id": 1234,
|
||||
"identities_created": 15,
|
||||
"profile_images_downloaded": 12
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/agents/tmdb/match/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Match TMDb identities to face traces using Qdrant vector similarity. Compares face embeddings against TMDb identity embeddings to find the best matches.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/agents/tmdb/match/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"matches": [
|
||||
{
|
||||
"trace_id": 0,
|
||||
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"identity_name": "Audrey Hepburn",
|
||||
"confidence": 0.92,
|
||||
"tmdb_id": 1234
|
||||
}
|
||||
],
|
||||
"total_matches": 5
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `matches[].trace_id` | integer | Face trace ID |
|
||||
| `matches[].identity_uuid` | string | Matched TMDb identity UUID |
|
||||
| `matches[].identity_name` | string | Identity display name |
|
||||
| `matches[].confidence` | float | Cosine similarity score (0.0–1.0) |
|
||||
| `matches[].tmdb_id` | integer | TMDb person ID |
|
||||
| `total_matches` | integer | Total successful matches |
|
||||
|
||||
---
|
||||
|
||||
### TMDb Auto-Match
|
||||
|
||||
When `MOMENTRY_TMDB_PROBE_ENABLED=true`, the worker automatically runs TMDb matching during the post-process phase:
|
||||
|
||||
1. **Register phase**: Searches TMDb by filename, creates identities with `tmdb_id`/`tmdb_profile`
|
||||
2. **Post-process phase**: Matches detected faces against TMDb identities via cosine similarity using Qdrant
|
||||
|
||||
No manual API call needed if auto-match is enabled.
|
||||
|
||||
---
|
||||
*Updated: 2026-06-20 — Added tmdb/fetch and tmdb/match endpoints*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,144 @@
|
||||
---
|
||||
title: pipeline API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: pipeline -->
|
||||
<!-- description: Pipeline processors, ingestion status, stats endpoints -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## Pipeline
|
||||
|
||||
### Pipeline Completion Flow
|
||||
|
||||
The pipeline is **not complete** until both the 10 processors AND the 入庫 (ingestion) steps have finished. The worker polls every 3 seconds and only marks the job as `completed` when all ingestion steps verify OK.
|
||||
|
||||
```
|
||||
10 processors done
|
||||
↓ (job status stays "running")
|
||||
Algorithm 1 Trigger: Rule 1 + Vectorize + Phase 1 Pack
|
||||
↓ (job runs in parallel)
|
||||
Algorithm 2 Trigger: Face Trace → TKG, Scene Metadata, Identity Agent, 5W1H Agent
|
||||
↓ (poll checks every 3s)
|
||||
Ingestion verification: rule1 ✓ vectorize ✓ rule3 ✓ face_trace ✓ tkg ✓ scene_meta ✓ 5w1h ✓
|
||||
↓
|
||||
job status = "completed"
|
||||
```
|
||||
|
||||
### 10 Processor Stages
|
||||
|
||||
| # | Processor | Depends On | Description |
|
||||
|---|-----------|------------|-------------|
|
||||
| 1 | `Cut` | — | Scene boundary detection (PySceneDetect) |
|
||||
| 2 | `ASR` | Cut | Automatic speech recognition (faster-whisper) |
|
||||
| 3 | `ASRX` | ASR | Speaker diarization + ASR refinement |
|
||||
| 4 | `YOLO` | — | Object detection (YOLOv8) |
|
||||
| 5 | `OCR` | — | Optical character recognition |
|
||||
| 6 | `Face` | — | Face detection + recognition (InsightFace + CoreML) |
|
||||
| 7 | `Pose` | — | Pose estimation |
|
||||
| 8 | `VisualChunk` | YOLO | Visual object chunking |
|
||||
| 9 | `Story` | ASRX + Cut + YOLO + Face | Narrative scene summarization (LLM, with embedding) |
|
||||
| 10 | `5W1H` | Story | Who/What/When/Where/Why extraction (LLM, with embedding) |
|
||||
|
||||
### 入庫 (Post-Processing / Ingestion)
|
||||
|
||||
These steps run after the 10 processors and are **required for pipeline completion**. The worker checks all of them before marking the job as done.
|
||||
|
||||
| # | Step | Triggers When | Verification |
|
||||
|---|------|--------------|-------------|
|
||||
| 1 | **Rule 1 Sentence Chunking** | ASR + ASRX done | `chunk` table has rows with `chunk_type = 'sentence'` |
|
||||
| 1.1 | **Rule 1 OCR Chunks** | OCR done | OCR pre_chunks grouped into sentence chunks |
|
||||
| 2 | **Auto-Vectorize** | Rule 1 done | `chunk.embedding` IS NOT NULL for sentence chunks |
|
||||
| 3 | **Phase 1 Pack** | Rule 1 done | `release_pack.py --phase 1` executed |
|
||||
| 4 | **Rule 3 Scene Chunking** | All 10 processors done + Cut + ASR | `chunk` table has rows with `chunk_type = 'cut'` |
|
||||
| 5 | **Face Trace** | All 10 processors done + Face | `face_detections.trace_id` IS NOT NULL |
|
||||
| 6 | **Qdrant Face Sync** | Face Trace done | Qdrant face_embedding collection populated |
|
||||
| 7 | **Trace Chunks** | Face Trace done | `chunk` table has rows with `chunk_type = 'trace'` |
|
||||
| 8 | **TKG Builder** | Face Trace done | `tkg_nodes` + `tkg_edges` tables have rows |
|
||||
| 9 | **TMDb Face Matching** | TMDb enabled + Face done | `face_detections.identity_id` IS NOT NULL |
|
||||
| 10 | **Heuristic Scene Metadata** | Face + YOLO done | `{file_uuid}.scene_meta.json` exists on disk |
|
||||
| 11 | **Template 5W1H Story Summary (PG)** | Story done | `chunk.embedding` IS NOT NULL for story chunks |
|
||||
| 12 | **LLM 5W1H Summary (PG)** | 5W1H done | `chunk.embedding` IS NOT NULL for llm chunks |
|
||||
| 13 | **Voice Embedding (Qdrant)** | ASRX done | Qdrant voice collection populated |
|
||||
| 14 | **Face Embedding (Qdrant)** | Face done | Qdrant face collection populated |
|
||||
| 15 | **Identity Agent** | Face + ASRX done | `identities` with `source = 'identity_agent'` |
|
||||
| 16 | **5W1H Agent** | Cut + ASR done | `chunk.summary_text` IS NOT NULL for cut chunks |
|
||||
| 17 | **Release Pack** | 5W1H Agent done | `release_pack.py --phase 2` executed |
|
||||
|
||||
### Ingestion Status
|
||||
|
||||
Check real-time ingestion status for a file:
|
||||
|
||||
```bash
|
||||
curl "$API/api/v1/stats/ingestion-status/{file_uuid}"
|
||||
```
|
||||
|
||||
Returns per-step `done` / `pending` status with detail counts.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl "$API/api/v1/stats/ingestion-status/bd80fec9c42afb0307eb28f22c64c76a" | jq '.steps[] | {name, status, detail}'
|
||||
```
|
||||
|
||||
#### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "bd80fec9c42afb0307eb28f22c64c76a",
|
||||
"steps": [
|
||||
{ "name": "rule1_sentence", "status": "done", "detail": "35 sentence chunks" },
|
||||
{ "name": "rule1_ocr", "status": "done", "detail": "30 OCR frames" },
|
||||
{ "name": "rule1_ocr_chunks", "status": "done", "detail": "3 OCR-only chunks" },
|
||||
{ "name": "auto_vectorize", "status": "pending", "detail": "0 embedded" },
|
||||
{ "name": "rule3_scene", "status": "pending", "detail": "0 scene chunks" },
|
||||
{ "name": "face_trace", "status": "pending", "detail": "0 traces" },
|
||||
{ "name": "trace_chunks", "status": "pending", "detail": "0 trace chunks" },
|
||||
{ "name": "tkg", "status": "pending", "detail": "0 nodes, 0 edges" },
|
||||
{ "name": "identity_match", "status": "pending", "detail": "0 identities" },
|
||||
{ "name": "scene_metadata", "status": "pending", "detail": null },
|
||||
{ "name": "5w1h", "status": "pending", "detail": "0 scenes with 5W1H" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Stats Endpoints
|
||||
|
||||
| Method | Endpoint | Auth | Description |
|
||||
|--------|----------|------|-------------|
|
||||
| GET | `/api/v1/stats/sftpgo` | No | SFTPGo service status |
|
||||
| GET | `/api/v1/stats/ingestion-status/:file_uuid` | No | Per-file ingestion checklist |
|
||||
|
||||
### Configuration
|
||||
|
||||
See [13_config.md](13_config.md) for runtime configuration endpoints:
|
||||
|
||||
| Endpoint | Description |
|
||||
|----------|-------------|
|
||||
| `POST /api/v1/config/cache` | Toggle Redis cache |
|
||||
| `POST /api/v1/config/auto-pipeline` | Toggle auto-pipeline on register |
|
||||
| `POST /api/v1/config/watcher-auto-register` | Toggle watcher auto-register |
|
||||
|
||||
### Unmounted Routes
|
||||
|
||||
The following routes are defined in source code but are **NOT** currently mounted in the router:
|
||||
|
||||
| Endpoint | Source file |
|
||||
|----------|-------------|
|
||||
| `/api/v1/search/people` | `universal_search.rs` (mounted) |
|
||||
| `/api/v1/who` | `who.rs` |
|
||||
| `/api/v1/who/candidates` | `who.rs` |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 23:21:51*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: error codes API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: error_codes -->
|
||||
<!-- description: Standard API error codes -->
|
||||
<!-- depends: -->
|
||||
|
||||
## Error Response Format
|
||||
|
||||
All API errors follow this JSON structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": "E001_NOT_FOUND",
|
||||
"message": "Resource not found",
|
||||
"details": {"resource": "file_uuid", "value": "abc"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Code List
|
||||
|
||||
### Generic Errors (E0xx)
|
||||
|
||||
| Code | HTTP | Description |
|
||||
|------|------|-------------|
|
||||
| `E001_NOT_FOUND` | 404 | Resource not found (file, identity, chunk) |
|
||||
| `E002_DUPLICATE` | 409 | Resource already exists |
|
||||
| `E003_VALIDATION` | 400 | Request parameter validation failed |
|
||||
| `E004_UNAUTHORIZED` | 401 | Invalid API key or token |
|
||||
| `E005_INTERNAL` | 500 | Internal server error |
|
||||
|
||||
### Processor Errors (E1xx)
|
||||
|
||||
| Code | HTTP | Description |
|
||||
|------|------|-------------|
|
||||
| `E101_PROCESSOR_FAIL` | 500 | Python script execution failed |
|
||||
| `E102_TIMEOUT` | 504 | Processing timeout |
|
||||
| `E103_RESUME_FAIL` | 500 | Resume failed (checkpoint not found) |
|
||||
| `E104_NO_VIDEO` | 400 | Video file path not found |
|
||||
|
||||
### Identity Errors (E2xx)
|
||||
|
||||
| Code | HTTP | Description |
|
||||
|------|------|-------------|
|
||||
| `E201_FACE_NOT_FOUND` | 404 | Face detection not found |
|
||||
| `E202_MERGE_CONFLICT` | 409 | Identity merge conflict |
|
||||
| `E203_CANDIDATE_EMPTY` | 404 | No candidates available for confirmation |
|
||||
|
||||
### TMDb Errors (E3xx)
|
||||
|
||||
| Code | HTTP | Description |
|
||||
|------|------|-------------|
|
||||
| `E301_TMDB_NO_KEY` | 400 | `TMDB_API_KEY` environment variable not set |
|
||||
| `E302_TMDB_UNREACHABLE` | 502 | TMDb API unreachable or timed out |
|
||||
| `E303_TMDB_CACHE_NOT_FOUND` | 200 | No local TMDb cache; run prefetch first |
|
||||
| `E304_TMDB_PROBE_FAILED` | 500 | TMDb probe execution failed |
|
||||
| `E305_TMDB_MOVIE_NOT_FOUND` | 404 | No matching TMDb movie found from filename |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,227 @@
|
||||
---
|
||||
title: agent API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
# Agent Endpoints
|
||||
|
||||
Agent endpoints provide AI-powered capabilities including translation, identity analysis, and 5W1H extraction.
|
||||
|
||||
## POST /api/v1/agents/translate
|
||||
|
||||
Translate text between languages using Gemma4 (llama.cpp, port 8082).
|
||||
|
||||
### Request
|
||||
|
||||
```json
|
||||
{
|
||||
"text": "Hello, welcome to Momentry Core.",
|
||||
"target_language": "Traditional Chinese",
|
||||
"source_language": "English"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `text` | string | ✅ | Text to translate |
|
||||
| `target_language` | string | ✅ | Target language name (e.g. "Traditional Chinese", "Japanese") |
|
||||
| `source_language` | string | ❌ | Source language (default: "auto") |
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"translated_text": "您好,歡迎使用 Momentry Core。",
|
||||
"source_language_detected": "English",
|
||||
"model_used": "google_gemma-4-26B-A4B-it-Q5_K_M.gguf"
|
||||
}
|
||||
```
|
||||
|
||||
### Supported Language Pairs (tested)
|
||||
|
||||
| Source | Target | Quality |
|
||||
|--------|--------|---------|
|
||||
| English | Traditional Chinese | ✅ |
|
||||
| English | Japanese | ✅ |
|
||||
| Chinese | English | ✅ |
|
||||
| English | French | ✅ |
|
||||
| Chinese | Japanese | ✅ |
|
||||
|
||||
### Model
|
||||
|
||||
- **Model**: Gemma4 26B (Q5_K_M)
|
||||
- **Engine**: llama.cpp at `localhost:8082`
|
||||
- **Endpoint**: `/v1/chat/completions` (OpenAI-compatible)
|
||||
- **Temperature**: 0.1
|
||||
- **Max tokens**: 1024
|
||||
|
||||
### Errors
|
||||
|
||||
| Status | Condition |
|
||||
|--------|-----------|
|
||||
| 500 | LLM unreachable or response parse failure |
|
||||
| 401 | Missing/invalid auth |
|
||||
|
||||
---
|
||||
|
||||
## POST /api/v1/agents/5w1h/analyze
|
||||
|
||||
Extract 5W1H (Who, What, When, Where, Why, How) from a scene. Uses Gemma4 LLM on port 8082.
|
||||
|
||||
### Request
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3abeee81d94597629ed8cb943f182e94",
|
||||
"scene_id": 42
|
||||
}
|
||||
```
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"5w1h": {
|
||||
"who": ["Cary Grant"],
|
||||
"what": ["discussing plans"],
|
||||
"when": ["1963"],
|
||||
"where": ["Paris"],
|
||||
"why": ["vacation"],
|
||||
"how": ["in person"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## POST /api/v1/agents/5w1h/batch
|
||||
|
||||
Batch analyze all scenes in a file for 5W1H extraction. Uses the pipeline's `parent_chunk_5w1h.py --mode llm`.
|
||||
|
||||
### Request
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3abeee81d94597629ed8cb943f182e94"
|
||||
}
|
||||
```
|
||||
|
||||
## GET /api/v1/agents/5w1h/status
|
||||
|
||||
Get status of the 5W1H agent pipeline for a file.
|
||||
|
||||
---
|
||||
|
||||
## Embedding Model
|
||||
|
||||
| Detail | Value |
|
||||
|--------|-------|
|
||||
| **Model** | EmbeddingGemma-300m |
|
||||
| **Endpoint** | `POST /v1/embeddings` on port 11436 |
|
||||
| **Dimension** | 768 |
|
||||
| **Used by** | `parent_chunk_5w1h.py --embed`, story, 5W1H, search |
|
||||
|
||||
---
|
||||
|
||||
## POST /api/v1/agents/search
|
||||
|
||||
Conversational search assistant. Uses Gemma4 function calling to automatically decide which tools to call based on the user's natural language query. Supports multi-turn conversation.
|
||||
|
||||
### Request
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "Audrey Hepburn 和 Cary Grant 第一次同框在哪個 frame?",
|
||||
"conversation_id": null,
|
||||
"file_uuid": null
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `query` | string | ✅ | 自然語言查詢 |
|
||||
| `conversation_id` | string | ❌ | 延續對話時傳入;新對話不傳 |
|
||||
| `file_uuid` | string | ❌ | Portal 有選中檔案時可指定 |
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"conversation_id": "conv_abc123",
|
||||
"answer": "在 Charade (1963) 中,Audrey Hepburn 與 Cary Grant 第一次同框在第 38619 幀(約 1544.76 秒)。",
|
||||
"need_input": false,
|
||||
"sources": [
|
||||
{
|
||||
"tool": "tkg_query",
|
||||
"result": "{\"first_cooccurrence\":{\"frame\":38619,\"timestamp_secs\":1544.76}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `conversation_id` | string | 後續對話需要傳入此 ID |
|
||||
| `answer` | string | Agent 的自然語言回答(或反問) |
|
||||
| `need_input` | boolean | `true` 表示 agent 需要更多資訊才能回答 |
|
||||
| `suggestions` | string[] | 建議用戶提供的線索(當 `need_input=true`) |
|
||||
| `sources` | array | 引用的工具執行結果 |
|
||||
|
||||
### Conversation Flow
|
||||
|
||||
```
|
||||
Round 1: POST /agents/search { query: "我想看男女主角同框" }
|
||||
→ need_input: true, suggestions: ["片名", "演員", "年代"]
|
||||
→ answer: "請問是哪部電影?請提供更多線索"
|
||||
|
||||
Round 2: POST /agents/search { query: "奧黛麗赫本", conversation_id: "..." }
|
||||
→ need_input: false
|
||||
→ answer: "找到 Charade (1963),Audrey Hepburn 和 Cary Grant..."
|
||||
```
|
||||
|
||||
### Available Tools
|
||||
|
||||
Agent 內部使用 Gemma4 function calling 自動調用以下工具:
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `find_file` | 透過片名/演員/年份關鍵字搜尋影片,回傳 file_uuid + has_data 狀態 |
|
||||
| `list_files` | 列出近期註冊的影片 |
|
||||
| `tkg_query` | 查詢人物互動資料(7 種子類型:top_identities、first_cooccurrence、identity_details、mutual_gaze、interaction_network、identity_traces、file_info) |
|
||||
| `smart_search` | 文字內容 ILIKE 搜尋 chunk(可指定 file_uuid 限制範圍) |
|
||||
| `get_identity_detail` | 查詢單一身份的詳細資料(角色、TMDb 資訊) |
|
||||
| `get_file_info` | 查詢影片基本資訊(片長、解析度) |
|
||||
| `get_representative_frame` | 查詢影片最具代表性的 frame 資訊 |
|
||||
|
||||
### Design Principles
|
||||
|
||||
- **用戶不需要知道 file_uuid** — Agent 會自動用 `find_file` 搜尋或反問
|
||||
- **不推薦無資料的影片** — `has_data=false` 的影片不會被推薦給用戶
|
||||
- **多輪對話** — 透過 `conversation_id` 延續上下文,agent 會記得之前的交流
|
||||
- **並行工具呼叫** — Gemma4 可以一次呼叫多個工具再綜合回答
|
||||
|
||||
### Model
|
||||
|
||||
| Detail | Value |
|
||||
|--------|-------|
|
||||
| **LLM** | Gemma4 26B (Q5_K_M) |
|
||||
| **Engine** | llama.cpp at `localhost:8082` |
|
||||
| **Endpoint** | `/v1/chat/completions` (OpenAI-compatible) |
|
||||
| **Temperature** | 0.1 |
|
||||
| **Max rounds** | 5 (tool call iterations) |
|
||||
| **Conversation TTL** | 30 minutes |
|
||||
|
||||
---
|
||||
*Updated: 2026-05-22*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
title: config API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: config -->
|
||||
<!-- description: System configuration — cache, auto-pipeline, watcher-auto-register toggles -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## System Configuration
|
||||
|
||||
Runtime configuration toggles for system behavior. All endpoints require authentication and system-level scope.
|
||||
|
||||
### `POST /api/v1/config/cache`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Toggle the Redis cache on or off.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `enabled` | boolean | Yes | `true` to enable, `false` to disable |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/config/cache" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"enabled": false}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/config/auto-pipeline`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Toggle automatic processing pipeline trigger on file registration (disabled by default).
|
||||
When enabled, registering a video file automatically creates a monitor job and starts processing.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `enabled` | boolean | Yes | `true` to enable auto-pipeline, `false` to disable |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Enable auto-pipeline
|
||||
curl -s -X POST "$API/api/v1/config/auto-pipeline" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"enabled": true}'
|
||||
|
||||
# Disable auto-pipeline
|
||||
curl -s -X POST "$API/api/v1/config/auto-pipeline" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"enabled": false}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/config/watcher-auto-register`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Toggle automatic registration of newly detected files in the watcher (disabled by default).
|
||||
When enabled, the file watcher automatically pre-processes and registers new files into the database.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `enabled` | boolean | Yes | `true` to enable watcher auto-register, `false` to disable |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Enable watcher auto-register
|
||||
curl -s -X POST "$API/api/v1/config/watcher-auto-register" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-d '{"enabled": true}'
|
||||
```
|
||||
|
||||
---
|
||||
*Updated: 2026-05-19 12:49:24*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,712 @@
|
||||
---
|
||||
title: identity history API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: identity_history -->
|
||||
<!-- description: Identity operation history, undo, and redo (PATCH, bind, unbind, bind_trace, mergeinto) -->
|
||||
<!-- depends: 01_auth, 07_identity -->
|
||||
|
||||
## Identity Operation History
|
||||
|
||||
Every mutation on an identity automatically records a before/after snapshot. Use undo/redo to revert or reapply changes, and history to inspect the operation log.
|
||||
|
||||
Three independent undo/redo systems exist:
|
||||
|
||||
| System | Storage | Operations Covered |
|
||||
|--------|---------|-------------------|
|
||||
| **PATCH** | PostgreSQL `identity_history` | `update` |
|
||||
| **Bind** | PostgreSQL `identity_history` | `bind`, `unbind`, `bind_trace` |
|
||||
| **Merge** | MongoDB `identity_merge_history` | mergeinto |
|
||||
| **Delete** | PostgreSQL `identity_history` | `delete` |
|
||||
|
||||
---
|
||||
|
||||
### 1. PATCH History & Undo/Redo
|
||||
|
||||
#### Overview
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Storage | PostgreSQL `identity_history` table |
|
||||
| Snapshot | Full identity record (all fields) before and after each PATCH |
|
||||
| Max records | 256 per identity (oldest auto-deleted when limit exceeded) |
|
||||
| Undo steps | Unlimited (no expiry, no step limit) |
|
||||
| Redo stack | Cleared on new PATCH (`is_undone=true` + `operation='update'` records are deleted) |
|
||||
|
||||
##### Stack Model
|
||||
|
||||
```
|
||||
PATCH 1 → PATCH 2 → PATCH 3 (undo stack, is_undone=false)
|
||||
↓ undo
|
||||
PATCH 1 → PATCH 2 (undo stack)
|
||||
PATCH 3 (redo stack, is_undone=true)
|
||||
↓ redo
|
||||
PATCH 1 → PATCH 2 → PATCH 3 (undo stack)
|
||||
```
|
||||
|
||||
A new PATCH after undo clears only the operation='update' redo stack (PATCH 3 is lost). Bind/merge redo stacks are not affected.
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/identity/:identity_uuid/undo`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Undo the most recent PATCH operations. Restores the identity's `before_snapshot` and marks the history records as undone.
|
||||
|
||||
##### Request (JSON)
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `steps` | integer | No | `1` | Number of undo steps to apply (max records undone in one call) |
|
||||
|
||||
##### Behavior
|
||||
|
||||
- Queries `is_undone=false` records with `operation='update'`, ordered by `created_at DESC`
|
||||
- Restores `name`, `identity_type`, `source`, `status`, `metadata`, `tmdb_id`, `tmdb_profile` from the last record's `before_snapshot`
|
||||
- Marks the undone records as `is_undone=true` with `undone_at=NOW()`
|
||||
- Syncs `identity.json` to disk
|
||||
- Updates `_index.json` if name changed
|
||||
|
||||
##### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/identity/$IDENTITY_UUID/undo" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"steps": 1}'
|
||||
```
|
||||
|
||||
##### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"undone_count": 1,
|
||||
"current_state": {
|
||||
"id": 9,
|
||||
"uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"name": "Cary Grant",
|
||||
"identity_type": "people",
|
||||
"source": "tmdb",
|
||||
"status": "confirmed",
|
||||
"metadata": {},
|
||||
"tmdb_id": 112,
|
||||
"tmdb_profile": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `undone_count` | integer | Number of history records undone |
|
||||
| `current_state` | object | Full identity state after undo |
|
||||
|
||||
##### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `400` | No undo operations available |
|
||||
| `404` | Identity not found |
|
||||
| `500` | Database error |
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/identity/:identity_uuid/redo`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Redo previously undone PATCH operations. Restores the identity's `after_snapshot` and marks the history records as no longer undone.
|
||||
|
||||
##### Request (JSON)
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `steps` | integer | No | `1` | Number of redo steps to apply |
|
||||
|
||||
##### Behavior
|
||||
|
||||
- Queries `is_undone=true` records with `operation='update'`, ordered by `created_at DESC`
|
||||
- Restores all identity fields from the last record's `after_snapshot`
|
||||
- Marks records as `is_undone=false` with `undone_at=NULL`
|
||||
- Syncs `identity.json` to disk
|
||||
- Updates `_index.json` if name changed
|
||||
|
||||
##### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/identity/$IDENTITY_UUID/redo" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"steps": 1}'
|
||||
```
|
||||
|
||||
##### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"redone_count": 1,
|
||||
"current_state": {
|
||||
"id": 9,
|
||||
"uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"name": "John Smith",
|
||||
"identity_type": "people",
|
||||
"source": "tmdb",
|
||||
"status": "confirmed",
|
||||
"metadata": { "aliases": [...] },
|
||||
"tmdb_id": 112,
|
||||
"tmdb_profile": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `redone_count` | integer | Number of history records redone |
|
||||
| `current_state` | object | Full identity state after redo |
|
||||
|
||||
##### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `400` | No redo operations available |
|
||||
| `404` | Identity not found |
|
||||
| `500` | Database error |
|
||||
|
||||
---
|
||||
|
||||
#### `GET /api/v1/identity/:identity_uuid/history`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Query the PATCH operation history for an identity. Returns paginated records with undo/redo stack counts (filtered to `operation='update'`).
|
||||
|
||||
##### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | `1` | Page number (1-indexed) |
|
||||
| `limit` | integer | No | `20` | Items per page (max 100) |
|
||||
|
||||
##### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"total": 5,
|
||||
"undo_stack_count": 3,
|
||||
"redo_stack_count": 2,
|
||||
"results": [
|
||||
{
|
||||
"history_id": 42,
|
||||
"operation": "update",
|
||||
"is_undone": false,
|
||||
"created_at": "2026-05-27T12:00:00Z",
|
||||
"undone_at": null
|
||||
},
|
||||
{
|
||||
"history_id": 41,
|
||||
"operation": "update",
|
||||
"is_undone": true,
|
||||
"created_at": "2026-05-27T11:30:00Z",
|
||||
"undone_at": "2026-05-27T13:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `total` | integer | Total PATCH history records for this identity |
|
||||
| `undo_stack_count` | integer | Records available for undo (`is_undone=false`) |
|
||||
| `redo_stack_count` | integer | Records available for redo (`is_undone=true`) |
|
||||
| `results[].history_id` | integer | History record ID |
|
||||
| `results[].operation` | string | Operation type (`"update"` for PATCH) |
|
||||
| `results[].is_undone` | boolean | Whether the operation has been undone |
|
||||
| `results[].created_at` | string | When the PATCH was applied |
|
||||
| `results[].undone_at` | string | When the undo occurred (null if not undone) |
|
||||
|
||||
##### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/identity/$IDENTITY_UUID/history?page=1&limit=10" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
##### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | Identity not found |
|
||||
| `500` | Database error |
|
||||
|
||||
---
|
||||
|
||||
### 2. Bind/Unbind/Trace History & Undo/Redo
|
||||
|
||||
All three operations (`bind`, `unbind`, `bind_trace`) share a single history table and undo/redo stack.
|
||||
|
||||
#### Bind Operation Overview
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Storage | PostgreSQL `identity_history` table (same table as PATCH) |
|
||||
| Snapshot | `{"file_uuid", "face_id" (or "trace_id"), "identity_id_before/after"}` |
|
||||
| Max records | 256 per identity (shared limit across all operation types) |
|
||||
| Undo steps | Unlimited (`steps` param) |
|
||||
| Redo stack | Cleared on new bind/unbind/bind_trace (`operation IN ('bind','unbind','bind_trace')` + `is_undone=true` records deleted) |
|
||||
| Stack isolation | Bind redo stack is **independent** from PATCH redo stack — clearing one does not affect the other |
|
||||
|
||||
##### Stack Model
|
||||
|
||||
```
|
||||
bind face_1 (to id=9) → unbind face_1 → bind trace 906 (to id=9)
|
||||
(undo stack, is_undone=false) (undo stack) (undo stack)
|
||||
↓ undo (first undone: bind_trace)
|
||||
bind trace 906 (is_undone=true)
|
||||
(redo stack)
|
||||
↓ redo
|
||||
bind face_1 → unbind face_1 → bind trace 906
|
||||
(undo stack)
|
||||
```
|
||||
|
||||
A new bind/unbind/trace after undo clears only the bind redo stack (operations with `IN ('bind','unbind','bind_trace')`).
|
||||
|
||||
##### Snapshot Format
|
||||
|
||||
**Before (bind):**
|
||||
```json
|
||||
{
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"face_id": "1_5",
|
||||
"identity_id_before": null
|
||||
}
|
||||
```
|
||||
|
||||
**After (bind):**
|
||||
```json
|
||||
{
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"face_id": "1_5",
|
||||
"identity_id_after": 9
|
||||
}
|
||||
```
|
||||
|
||||
**Before (unbind) — binding existed before:**
|
||||
```json
|
||||
{
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"face_id": "1_5",
|
||||
"identity_id_before": 9
|
||||
}
|
||||
```
|
||||
|
||||
**After (unbind):**
|
||||
```json
|
||||
{
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"face_id": "1_5",
|
||||
"identity_id_after": null
|
||||
}
|
||||
```
|
||||
|
||||
For `bind_trace`, the snapshot uses `trace_id` instead of `face_id`, with `identity_id_before` capturing the first face's identity in that trace.
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/identity/:identity_uuid/bind/undo`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Undo the most recent bind/unbind/bind_trace operations. Restores `identity_id_before` from the snapshot and marks records as undone.
|
||||
|
||||
##### Request (JSON)
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `steps` | integer | No | `1` | Number of undo steps to apply |
|
||||
|
||||
##### Behavior
|
||||
|
||||
- Queries `is_undone=false` records with `operation IN ('bind','unbind','bind_trace')`, ordered by `created_at DESC`
|
||||
- Restores `identity_id_before` — for bind this is `null` (face was unbound), for unbind this is the original identity (face goes back), for bind_trace this is the trace's previous identity
|
||||
- Marks the undone records as `is_undone=true` with `undone_at=NOW()`
|
||||
|
||||
##### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/identity/$IDENTITY_UUID/bind/undo" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"steps": 1}'
|
||||
```
|
||||
|
||||
##### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"operation": "bind",
|
||||
"undone_count": 1,
|
||||
"affected_rows": 53
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `operation` | string | The actual operation undone (`bind`, `unbind`, or `bind_trace`) |
|
||||
| `undone_count` | integer | Number of history records undone |
|
||||
| `affected_rows` | integer | Number of `face_detections` rows updated |
|
||||
|
||||
##### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `400` | No bind undo operations available |
|
||||
| `404` | Identity not found |
|
||||
| `500` | Database error |
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/identity/:identity_uuid/bind/redo`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Redo previously undone bind/unbind/bind_trace operations. Restores `identity_id_after` from the snapshot.
|
||||
|
||||
##### Request (JSON)
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `steps` | integer | No | `1` | Number of redo steps to apply |
|
||||
|
||||
##### Behavior
|
||||
|
||||
- Queries `is_undone=true` records with `operation IN ('bind','unbind','bind_trace')`, ordered by `created_at DESC`
|
||||
- Restores `identity_id_after` — for bind this is the identity the face was bound to, for unbind this is `null`
|
||||
- Marks records as `is_undone=false` with `undone_at=NULL`
|
||||
|
||||
##### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/identity/$IDENTITY_UUID/bind/redo" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"steps": 1}'
|
||||
```
|
||||
|
||||
##### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"operation": "unbind",
|
||||
"redone_count": 1,
|
||||
"affected_rows": 1
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `operation` | string | The actual operation redone (`bind`, `unbind`, or `bind_trace`) |
|
||||
| `redone_count` | integer | Number of history records redone |
|
||||
| `affected_rows` | integer | Number of `face_detections` rows updated |
|
||||
|
||||
##### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `400` | No bind redo operations available |
|
||||
| `404` | Identity not found |
|
||||
| `500` | Database error |
|
||||
|
||||
---
|
||||
|
||||
#### `GET /api/v1/identity/:identity_uuid/bind/history`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Query the bind/unbind/bind_trace operation history for an identity. Returns paginated records with undo/redo stack counts.
|
||||
|
||||
##### Query Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | No | `1` | Page number (1-indexed) |
|
||||
| `limit` | integer | No | `20` | Items per page (max 100) |
|
||||
|
||||
##### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"identity_uuid": "a9a901056d6b46ff92da0c3c1a57dff4",
|
||||
"total": 3,
|
||||
"undo_stack_count": 2,
|
||||
"redo_stack_count": 1,
|
||||
"results": [
|
||||
{
|
||||
"history_id": 52,
|
||||
"operation": "bind_trace",
|
||||
"is_undone": false,
|
||||
"created_at": "2026-05-27T14:00:00Z",
|
||||
"undone_at": null
|
||||
},
|
||||
{
|
||||
"history_id": 51,
|
||||
"operation": "unbind",
|
||||
"is_undone": true,
|
||||
"created_at": "2026-05-27T13:00:00Z",
|
||||
"undone_at": "2026-05-27T14:30:00Z"
|
||||
},
|
||||
{
|
||||
"history_id": 50,
|
||||
"operation": "bind",
|
||||
"is_undone": false,
|
||||
"created_at": "2026-05-27T12:00:00Z",
|
||||
"undone_at": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `total` | integer | Total bind history records for this identity |
|
||||
| `undo_stack_count` | integer | Records available for undo (`is_undone=false`) |
|
||||
| `redo_stack_count` | integer | Records available for redo (`is_undone=true`) |
|
||||
| `results[].history_id` | integer | History record ID |
|
||||
| `results[].operation` | string | Operation type (`bind`, `unbind`, or `bind_trace`) |
|
||||
| `results[].is_undone` | boolean | Whether the operation has been undone |
|
||||
| `results[].created_at` | string | When the operation was applied |
|
||||
| `results[].undone_at` | string | When the undo occurred (null if not undone) |
|
||||
|
||||
##### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/identity/$IDENTITY_UUID/bind/history?page=1&limit=10" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
##### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | Identity not found |
|
||||
| `500` | Database error |
|
||||
|
||||
---
|
||||
|
||||
### 3. Merge History & Undo/Redo
|
||||
|
||||
Merge operations use MongoDB for richer record-keeping, with a 24-hour undo deadline.
|
||||
|
||||
#### Merge Operation Overview
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Storage | MongoDB `identity_merge_history` collection |
|
||||
| Snapshot | Full source identity state + target identity state + aliases/metadata diffs |
|
||||
| Trigger | Every mergeinto with `keep_history=true` |
|
||||
| Undo deadline | 24 hours (renewed on redo) |
|
||||
| Redo support | Yes — restores undone merges with new 24hr deadline |
|
||||
| Max records | Unlimited |
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/identity/merge/:merge_id/undo`
|
||||
|
||||
Already documented in [`07_identity.md`](07_identity.md#post-apiv1identitymergemerge_idundo). See that document for full details.
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/identity/merge/:merge_id/redo`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Redo a previously undone merge operation within the renewed 24-hour deadline.
|
||||
|
||||
##### Request
|
||||
|
||||
No body required. The merge ID is taken from the URL path.
|
||||
|
||||
##### Behavior
|
||||
|
||||
1. Validates the merge record exists and `undone=true` (not already active)
|
||||
2. Checks the 24-hour undo deadline (if expired, the redo is rejected)
|
||||
3. Restores face bindings: moves all faces from `target_identity` back to `source_identity`
|
||||
4. Re-adds aliases that were removed by the undo (aliases with `source: "merge"` tag)
|
||||
5. Re-adds metadata fields that were removed by the undo
|
||||
6. If `keep_history=true`: sets `source_identity.status = 'merged'` again
|
||||
7. If `keep_history=false`: recreates source identity from the `undone_snapshot` stored at undo time
|
||||
8. Syncs both identity JSON files to disk
|
||||
9. Sets `undone=false`, clears `undone_snapshot`, renews `undo_deadline = NOW() + 24h`
|
||||
10. Records `redone_by` user for audit
|
||||
|
||||
##### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/identity/merge/550e8400-e29b-41d4-a716-446655440000/redo" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
##### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Redo merge completed: merged 'stranger_13894' into 'Louis Viret' (52 faces transferred)",
|
||||
"data": {
|
||||
"merge_id": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"faces_transferred": 52,
|
||||
"aliases_re_added": 1,
|
||||
"metadata_fields_re_added": 2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `merge_id` | string | The merge operation ID |
|
||||
| `faces_transferred` | integer | Number of faces transferred from source to target |
|
||||
| `aliases_re_added` | integer | Number of aliases restored to target |
|
||||
| `metadata_fields_re_added` | integer | Number of metadata fields restored to target |
|
||||
|
||||
##### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `400` | Merge not undone, deadline expired, or cannot redo |
|
||||
| `404` | Merge record not found |
|
||||
| `500` | Database error |
|
||||
|
||||
---
|
||||
|
||||
### 4. Delete History & Undo/Redo
|
||||
|
||||
#### Delete Operation Overview
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Storage | PostgreSQL `identity_history` table |
|
||||
| Snapshot | `{"identity": {...full row...}, "unbound_faces": [{file_uuid, face_id, trace_id}, ...]}` |
|
||||
| Max records | 1 active delete record per identity (redo stack cleared on new delete) |
|
||||
| Undo support | Yes — recreates identity row, re-binds faces |
|
||||
| Redo support | Yes — re-deletes the identity |
|
||||
| Identity file | Deleted on delete, recreated on undo |
|
||||
|
||||
#### Snapshot Format
|
||||
|
||||
```json
|
||||
{
|
||||
"identity": {
|
||||
"id": 9,
|
||||
"uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
|
||||
"name": "Cary Grant",
|
||||
"identity_type": "people",
|
||||
"source": "tmdb",
|
||||
"status": "confirmed",
|
||||
"metadata": {},
|
||||
"tmdb_id": 112,
|
||||
"tmdb_profile": null
|
||||
},
|
||||
"unbound_faces": [
|
||||
{
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"face_id": "1_5",
|
||||
"trace_id": null
|
||||
},
|
||||
{
|
||||
"file_uuid": "aeed71342a899fe4b4c57b7d41bcb692",
|
||||
"face_id": "1_6",
|
||||
"trace_id": 906
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Stack Model
|
||||
|
||||
```
|
||||
DELETE identity (undo stack, is_undone=false)
|
||||
↓ undo
|
||||
Identity recreated, faces re-bound
|
||||
→ delete history marked is_undone=true
|
||||
↓ redo (re-delete)
|
||||
Identity deleted again, faces unbound
|
||||
→ delete history marked is_undone=false
|
||||
```
|
||||
|
||||
A new delete after an undo clears the delete redo stack (no redo possible for the old delete).
|
||||
|
||||
#### Undo Behavior (via existing `POST /api/v1/identity/:identity_uuid/undo`)
|
||||
|
||||
1. Normal identity lookup fails (row was deleted)
|
||||
2. Checks `identity_history` for `operation='delete' AND is_undone=false` matching the UUID in the snapshot
|
||||
3. Recreates the identity row (new internal `id`, same UUID)
|
||||
4. Re-binds all faces listed in `unbound_faces` to the new identity
|
||||
5. Deletes the `identity_history` delete record as `is_undone=true` with `undone_at=NOW()`
|
||||
6. Syncs `identity.json` to disk
|
||||
7. Updates `_index.json`
|
||||
|
||||
#### Redo Behavior (via existing `POST /api/v1/identity/:identity_uuid/redo`)
|
||||
|
||||
1. Identity lookup succeeds (identity was restored by prior undo)
|
||||
2. Checks `identity_history` for `operation='delete' AND is_undone=true` matching the identity_id
|
||||
3. Deletes `identity.json` from disk
|
||||
4. Unbinds all faces (`identity_id = NULL`)
|
||||
5. Deletes the identity row
|
||||
6. Marks the delete history record as `is_undone=false`
|
||||
7. Returns success
|
||||
|
||||
#### Error Responses (delete undo/redo)
|
||||
|
||||
| HTTP | Scenario |
|
||||
|------|----------|
|
||||
| `400` | No delete history available (either no delete or already undone/redone) |
|
||||
| `404` | Identity not found (for redo — identity wasn't restored) |
|
||||
| `500` | Database error |
|
||||
|
||||
---
|
||||
|
||||
### Comparison: PATCH vs Bind vs Merge vs Delete Undo/Redo
|
||||
|
||||
| Aspect | PATCH Undo/Redo | Bind Undo/Redo | Merge Undo/Redo | Delete Undo/Redo |
|
||||
|--------|----------------|----------------|-----------------|------------------|
|
||||
| Storage | PostgreSQL `identity_history` | PostgreSQL `identity_history` | MongoDB `identity_merge_history` | PostgreSQL `identity_history` |
|
||||
| Operation filter | `operation='update'` | `operation IN ('bind','unbind','bind_trace')` | — | `operation='delete'` |
|
||||
| Trigger | Every PATCH | Every bind/unbind/bind_trace | Every mergeinto with `keep_history=true` | Every DELETE |
|
||||
| Undo deadline | None (unlimited) | None (unlimited) | 24 hours (renewed on redo) | None (unlimited) |
|
||||
| Redo support | Yes | Yes | Yes | Yes |
|
||||
| Step undo | Yes (`steps` param) | Yes (`steps` param) | No (full undo/redo only) | No (single record) |
|
||||
| Max records | 256 per identity | 256 per identity (shared) | Unlimited | 256 per identity (shared) |
|
||||
| User tracking | `user_id` + `user_source` | `user_id` + `user_source` | `performed_by_user` + `undone_by` / `redone_by` | `user_id` + `user_source` |
|
||||
|
||||
---
|
||||
|
||||
*Updated: 2026-05-28*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,550 @@
|
||||
---
|
||||
title: tkg API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: tkg -->
|
||||
<!-- description: Temporal Knowledge Graph — rebuild, nodes, edges, processor counts -->
|
||||
<!-- depends: 05_process, 07_identity -->
|
||||
|
||||
## Temporal Knowledge Graph (TKG)
|
||||
|
||||
TKG is a time-aligned knowledge graph built from multi-processor outputs (face, yolo, ocr, pose, asrx, gaze, lip, appearance). It produces 9 node types and 14 edge types stored in `dev.tkg_nodes` and `dev.tkg_edges`.
|
||||
|
||||
**Node naming convention:** All trace types use `_track` suffix. Text uses `_region` (non-temporal).
|
||||
|
||||
**See also:** `docs_v1.0/DESIGN/TKG_FORMATION_V1.0.md` for formation phases, flow diagrams, and query examples.
|
||||
|
||||
### Node Types
|
||||
|
||||
| Node Type | External ID Format | Description | Key Properties |
|
||||
|-----------|-------------------|-------------|----------------|
|
||||
| `face_track` | `trace_{trace_id}` | A tracked face identity over time | `trace_id`, `frame_count`, `status`, `avg_bbox`, `avg_yaw`, `avg_pitch`, `avg_roll`, `start_frame`, `end_frame`, `pose_count` |
|
||||
| `gaze_track` | `gaze_track_{id}` | Gaze direction over time | `direction` (frontal/left/right/up/down + diagonals) |
|
||||
| `lip_track` | `lip_track_{id}` | Lip movement synced with speech | `speaker_id`, `lip_area_range` |
|
||||
| `text_region` | `text_region_{id}` | Spoken text aligned to time | `speaker_id`, `text`, `start_time`, `end_time` |
|
||||
| `appearance_trace` | `appearance_{trace_id}` | Human appearance (clothing) over time | `clothing_color`, `upper_cloth`, `lower_cloth` |
|
||||
| `accessory` | `accessory_{id}` | Detected accessories | `type` (glasses/hat/etc.), `confidence` |
|
||||
| `object` | `object_{class}_{id}` | YOLO-detected object | `class`, `confidence`, `frame_count` |
|
||||
| `speaker` | `speaker_{speaker_id}` | ASRX speaker segment | `speaker_id`, `segment_count`, `total_duration` |
|
||||
|
||||
---
|
||||
|
||||
### Identity Agent Integration (face_track nodes)
|
||||
|
||||
Identity Agent marks face_track nodes with identity binding status.
|
||||
|
||||
#### face_track Status Values
|
||||
|
||||
| Status | Description | Properties |
|
||||
|--------|-------------|------------|
|
||||
| `pending` | No identity suggestion | Default state |
|
||||
| `suggested` | Identity Agent suggested | `pending_identity_name`, `pending_identity_uuid`, `suggested_by`, `confidence` |
|
||||
| `confirmed` | User confirmed binding | `identity_uuid`, `identity_id`, `identity_ref`, `identity_name` |
|
||||
| `stranger` | Stranger cluster member | `stranger_id`, `stranger_ref` |
|
||||
|
||||
#### Suggested By Values
|
||||
|
||||
| Value | Description |
|
||||
|-------|-------------|
|
||||
| `tmdb` | TMDb seed matched |
|
||||
| `propagation` | Confirmed trace propagation |
|
||||
| `manual` | User manual selection |
|
||||
|
||||
#### Example face_track Node
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "face_track",
|
||||
"external_id": "face_track_1",
|
||||
"label": "Face Track 1",
|
||||
"properties": {
|
||||
"trace_id": 1,
|
||||
"frame_count": 45,
|
||||
"start_frame": 100,
|
||||
"end_frame": 300,
|
||||
"avg_bbox": {"x": 100, "y": 200, "width": 80, "height": 100},
|
||||
"status": "suggested",
|
||||
"pending_identity_name": "Tom Hanks",
|
||||
"pending_identity_uuid": "xxx-xxx",
|
||||
"suggested_by": "tmdb",
|
||||
"confidence": 0.91
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Edge Types
|
||||
|
||||
| Edge Type | Storage Name | Source → Target | Description |
|
||||
|-----------|--------------|-----------------|-------------|
|
||||
| `co_occurs` | `CO_OCCURS_WITH` | object ↔ object | Two objects appear together in same frame |
|
||||
| `speaker_face` | `SPEAKS_AS` | speaker → face_track | Speaker matched to face track via lip sync |
|
||||
| `face_face` | `INTERACTS_WITH` | face_track ↔ face_track | Two face tracks interact (mutual gaze) |
|
||||
| `mutual_gaze` | `MUTUAL_GAZE` | gaze_track ↔ gaze_track | Two people looking at each other |
|
||||
| `lip_sync` | `LIP_SYNC` | lip_track → text_region | Lip movement aligned with spoken text |
|
||||
| `has_appearance` | `HAS_APPEARANCE` | face_track → appearance_trace | Face has specific appearance |
|
||||
| `wears` | `WEARS` | face_track → accessory | Face wears an accessory |
|
||||
| `hand_object` | `HOLDS` | hand → object | Hand holding object |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/rebuild`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Rebuild the Temporal Knowledge Graph for a file. Reads processor JSON outputs (face, yolo, ocr, pose, asrx, gaze, lip, appearance) and generates TKG nodes and edges. Clears existing nodes/edges for the file first, then rebuilds from scratch.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/rebuild" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"result": {
|
||||
"face_track_nodes": 16,
|
||||
"gaze_track_nodes": 16,
|
||||
"lip_track_nodes": 12,
|
||||
"text_region_nodes": 24,
|
||||
"appearance_trace_nodes": 8,
|
||||
"skin_tone_trace_nodes": 5,
|
||||
"accessory_nodes": 3,
|
||||
"object_nodes": 26,
|
||||
"speaker_nodes": 4,
|
||||
"co_occurrence_edges": 94,
|
||||
"speaker_face_edges": 12,
|
||||
"face_face_edges": 8,
|
||||
"mutual_gaze_edges": 2,
|
||||
"lip_sync_edges": 10,
|
||||
"has_appearance_edges": 16,
|
||||
"wears_edges": 3
|
||||
},
|
||||
"error": null
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | True if rebuild completed |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `result` | object | Node and edge counts by type |
|
||||
| `error` | string/null | Error message if failed |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/nodes`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Query TKG nodes with pagination and optional type filter.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `node_type` | string | No | all | Filter by node type: `face_track`, `gaze_track`, `lip_track`, `text_region`, `appearance_trace`, `skin_tone_trace`, `accessory`, `object`, `speaker` |
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 100 | Items per page (max 500) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get all face_track nodes
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/nodes" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"node_type": "face_track", "page": 1, "page_size": 50}'
|
||||
|
||||
# Get all nodes
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/nodes" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"total": 16,
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"nodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"node_type": "face_track",
|
||||
"external_id": "face_track_0",
|
||||
"label": "Face Track 0",
|
||||
"properties": {
|
||||
"trace_id": 0,
|
||||
"frame_count": 142,
|
||||
"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}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `total` | integer | Total matching node count |
|
||||
| `page` | integer | Current page |
|
||||
| `page_size` | integer | Items per page |
|
||||
| `nodes` | array | Array of node objects |
|
||||
| `nodes[].id` | integer | Database primary key |
|
||||
| `nodes[].node_type` | string | Node type (see table above) |
|
||||
| `nodes[].external_id` | string | External identifier (e.g., `trace_0`, `gaze_1`) |
|
||||
| `nodes[].label` | string | Human-readable label |
|
||||
| `nodes[].properties` | object | Type-specific properties as JSON |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/edges`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Query TKG edges with pagination and optional filters.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `edge_type` | string | No | all | Filter by edge type: `co_occurs`, `speaker_face`, `face_face`, `mutual_gaze`, `lip_sync`, `has_appearance`, `wears` |
|
||||
| `source_type` | string | No | — | Filter by source node type |
|
||||
| `target_type` | string | No | — | Filter by target node type |
|
||||
| `page` | integer | No | 1 | Page number |
|
||||
| `page_size` | integer | No | 100 | Items per page (max 500) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get all co_occurs edges
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/edges" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"edge_type": "co_occurs"}'
|
||||
|
||||
# Get edges between face_track and speaker nodes
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/edges" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"source_type": "speaker", "target_type": "face_track"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"total": 94,
|
||||
"page": 1,
|
||||
"page_size": 100,
|
||||
"edges": [
|
||||
{
|
||||
"id": 1,
|
||||
"edge_type": "co_occurs",
|
||||
"source_node_id": 10,
|
||||
"target_node_id": 15,
|
||||
"properties": {
|
||||
"frame_count": 45,
|
||||
"confidence": 0.92
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `total` | integer | Total matching edge count |
|
||||
| `page` | integer | Current page |
|
||||
| `page_size` | integer | Items per page |
|
||||
| `edges` | array | Array of edge objects |
|
||||
| `edges[].id` | integer | Database primary key |
|
||||
| `edges[].edge_type` | string | Edge type |
|
||||
| `edges[].source_node_id` | integer | Source node ID (FK to tkg_nodes) |
|
||||
| `edges[].target_node_id` | integer | Target node ID (FK to tkg_nodes) |
|
||||
| `edges[].properties` | object | Edge-specific properties as JSON |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/tkg/node/:node_id`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get detail for a specific TKG node including its connected edges.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/tkg/node/1" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"node": {
|
||||
"id": 1,
|
||||
"node_type": "face_track",
|
||||
"external_id": "face_track_0",
|
||||
"label": "Face Track 0",
|
||||
"properties": {
|
||||
"trace_id": 0,
|
||||
"frame_count": 142,
|
||||
"avg_confidence": 0.87
|
||||
}
|
||||
},
|
||||
"connected_edges": [
|
||||
{
|
||||
"id": 5,
|
||||
"edge_type": "co_occurs",
|
||||
"source_node_id": 1,
|
||||
"target_node_id": 10,
|
||||
"properties": {"frame_count": 45}
|
||||
}
|
||||
],
|
||||
"edge_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
| `node` | object | Node detail (same format as nodes query) |
|
||||
| `connected_edges` | array | Edges connected to this node |
|
||||
| `edge_count` | integer | Total connected edge count |
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | Node not found |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/processor-counts`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get counts of processor JSON output files for a file. Scans the output directory for `{file_uuid}.{processor}.json` files and extracts frame counts, segment counts, and chunk counts from each file.
|
||||
|
||||
Supports short UUID prefix matching (e.g., `d3f9ae8e` → resolves to full `d3f9ae8e471a1fc4d47022c66091b920`).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/processor-counts" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"output_dir": "/Users/accusys/momentry/output_dev",
|
||||
"processors": [
|
||||
{
|
||||
"processor": "cut",
|
||||
"has_json": true,
|
||||
"frame_count": 5391,
|
||||
"segment_count": null,
|
||||
"chunk_count": null,
|
||||
"last_modified": "2026-06-16T18:48:01.987241061+00:00"
|
||||
},
|
||||
{
|
||||
"processor": "face",
|
||||
"has_json": true,
|
||||
"frame_count": 1112,
|
||||
"segment_count": null,
|
||||
"chunk_count": null,
|
||||
"last_modified": "2026-06-18T17:21:37.408383765+00:00"
|
||||
},
|
||||
{
|
||||
"processor": "asrx",
|
||||
"has_json": true,
|
||||
"frame_count": null,
|
||||
"segment_count": 6,
|
||||
"chunk_count": null,
|
||||
"last_modified": "2026-06-18T17:21:40.872063642+00:00"
|
||||
},
|
||||
{
|
||||
"processor": "story",
|
||||
"has_json": true,
|
||||
"frame_count": null,
|
||||
"segment_count": null,
|
||||
"chunk_count": 12,
|
||||
"last_modified": "2026-06-18T17:22:00.000000000+00:00"
|
||||
},
|
||||
{
|
||||
"processor": "mediapipe",
|
||||
"has_json": false,
|
||||
"frame_count": null,
|
||||
"segment_count": null,
|
||||
"chunk_count": null,
|
||||
"last_modified": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | Full 32-char hex UUID (resolved from prefix) |
|
||||
| `output_dir` | string | Output directory scanned |
|
||||
| `processors` | array | Per-processor output info |
|
||||
| `processors[].processor` | string | Processor name |
|
||||
| `processors[].has_json` | boolean | Whether JSON file exists |
|
||||
| `processors[].frame_count` | integer/null | Total frames processed (frame-based processors) |
|
||||
| `processors[].segment_count` | integer/null | Segment count (ASRX segments, etc.) |
|
||||
| `processors[].chunk_count` | integer/null | Chunk count (Story chunks, etc.) |
|
||||
| `processors[].last_modified` | string/null | ISO 8601 timestamp of last modification |
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | File UUID not found in database |
|
||||
|
||||
---
|
||||
|
||||
### Trace Management
|
||||
|
||||
Endpoints for managing face traces: list, delete, restore, and merge.
|
||||
|
||||
#### `DELETE /api/v1/file/:file_uuid/trace/:trace_id`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
Soft-delete a face trace (default) or hard-delete with `{"hard_delete": true}`.
|
||||
|
||||
Soft delete marks Qdrant points with `status: "deleted"` and TKG nodes with `status: "deleted"` in properties. Deleted traces are excluded from the traces list.
|
||||
|
||||
Hard delete permanently removes Qdrant points and TKG nodes.
|
||||
|
||||
**Request Body** (optional):
|
||||
|
||||
| Field | Type | Default | Description |
|
||||
|-------|------|---------|-------------|
|
||||
| `hard_delete` | boolean | `false` | Permanently delete instead of marking |
|
||||
|
||||
**Example**:
|
||||
```bash
|
||||
# Soft delete
|
||||
curl -X DELETE "$API/api/v1/file/$FILE_UUID/trace/8" \
|
||||
-H "X-API-Key: $KEY" -H "Content-Type: application/json" -d '{}'
|
||||
|
||||
# Hard delete
|
||||
curl -X DELETE "$API/api/v1/file/$FILE_UUID/trace/8" \
|
||||
-H "X-API-Key: $KEY" -H "Content-Type: application/json" \
|
||||
-d '{"hard_delete": true}'
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 8,
|
||||
"hard_delete": false,
|
||||
"qdrant_marked": true,
|
||||
"tkg_nodes_marked": 1
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/file/:file_uuid/trace/:trace_id/restore`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
Undo a soft-deleted trace. Clears `status: "deleted"` from Qdrant points and TKG node properties.
|
||||
|
||||
**Example**:
|
||||
```bash
|
||||
curl -X POST "$API/api/v1/file/$FILE_UUID/trace/8/restore" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 8,
|
||||
"qdrant_restored": true,
|
||||
"tkg_nodes_restored": 1
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### `POST /api/v1/file/:file_uuid/trace/:source_trace_id/merge/:target_trace_id`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
Merge all face points from source trace into target trace. Updates Qdrant `trace_id` and deletes source TKG node.
|
||||
|
||||
**Example**:
|
||||
```bash
|
||||
curl -X POST "$API/api/v1/file/$FILE_UUID/trace/16/merge/3" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"source_trace_id": 16,
|
||||
"target_trace_id": 3,
|
||||
"points_moved": 58,
|
||||
"tkg_nodes_deleted": 1
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
*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*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,164 @@
|
||||
---
|
||||
title: workspace API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: workspace -->
|
||||
<!-- description: Workspace checkout/checkin — lock, clear, restore file data -->
|
||||
<!-- depends: 04_lookup, 05_process -->
|
||||
|
||||
## Workspace Checkin/Checkout
|
||||
|
||||
Workspace checkin/checkout provides a transactional editing model for file data:
|
||||
- **Checkout**: Clears PG tables (face_detections, speaker_detections, pre_chunks) and Qdrant vectors, creating an isolated workspace SQLite for editing.
|
||||
- **Checkin**: Restores data from the workspace SQLite back to PG and Qdrant, marking the file as `Indexed`.
|
||||
|
||||
This allows safe concurrent editing — while a file is checked out, its main database records are cleared, preventing conflicts.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/checkout`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Checkout a file workspace. Clears face detections, speaker detections, pre_chunks from PostgreSQL, deletes Qdrant vectors, and creates a workspace SQLite database for isolated editing.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/checkout" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"rows_deleted": 1523,
|
||||
"status": "checked_out"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `rows_deleted` | integer | Total rows cleared from PG tables |
|
||||
| `status` | string | `"checked_out"` |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `500` | Checkout failed (DB error, workspace creation error) |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/checkin`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Checkin a file workspace. Restores face detections, speaker detections, pre_chunks from workspace SQLite back to PostgreSQL, re-indexes vectors to Qdrant, and sets video status to `Indexed`.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/checkin" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"pre_chunks_moved": 45,
|
||||
"face_detections_moved": 1200,
|
||||
"speaker_detections_moved": 320,
|
||||
"vectors_moved": 45,
|
||||
"status": "indexed"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `pre_chunks_moved` | integer | Pre-chunks restored from workspace |
|
||||
| `face_detections_moved` | integer | Face detections restored from workspace |
|
||||
| `speaker_detections_moved` | integer | Speaker detections restored from workspace |
|
||||
| `vectors_moved` | integer | Vectors re-indexed to Qdrant |
|
||||
| `status` | string | `"indexed"` |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `500` | Checkin failed (DB error, workspace not found, vector index error) |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/workspace`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Check if a workspace SQLite database exists for a file.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/workspace" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "d3f9ae8e471a1fc4d47022c66091b920",
|
||||
"exists": true
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `exists` | boolean | True if workspace SQLite exists |
|
||||
|
||||
---
|
||||
|
||||
### Workflow
|
||||
|
||||
```
|
||||
REGISTERED ──→ CHECKED_OUT ──→ INDEXED
|
||||
│ │ │
|
||||
│ checkout checkin
|
||||
│ │ │
|
||||
│ clear PG + Qdrant restore from SQLite
|
||||
│ create workspace re-index vectors
|
||||
│ set status set status
|
||||
```
|
||||
|
||||
1. **Register** file → status: `REGISTERED`
|
||||
2. **Process** file → processors run, data stored in PG + Qdrant
|
||||
3. **Checkout** file → clear editable data, create workspace SQLite → status: `CHECKED_OUT`
|
||||
4. **Edit** workspace via Agent Search / identity binding
|
||||
5. **Checkin** file → restore from workspace SQLite → status: `INDEXED`
|
||||
6. **Rebuild TKG** if needed after checkin
|
||||
|
||||
---
|
||||
|
||||
*Updated: 2026-06-20 12:00:00*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,561 @@
|
||||
---
|
||||
title: progress API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: progress -->
|
||||
<!-- description: Real-time progress tracking for processing pipeline, TKG build, and identity agent -->
|
||||
<!-- depends: 01_auth, 03_register, 05_process -->
|
||||
|
||||
# Progress Tracking — API Workspace Module
|
||||
|
||||
## Overview
|
||||
|
||||
The progress tracking system provides real-time visibility into all processing stages:
|
||||
|
||||
| System | Redis Key | Coverage |
|
||||
|--------|-----------|----------|
|
||||
| **Processor Progress** | `{prefix}progress:{file_uuid}` | 7 main processors (cut, asr, asrx, ocr, face, pose, appearance) |
|
||||
| **TKG Progress** | `{prefix}progress:{file_uuid}:tkg` | 18 TKG build phases (9 node types + 8 edge types + face_tracing) |
|
||||
| **Agent Progress** | `{prefix}progress:{file_uuid}:agent` | 5 Identity Agent phases |
|
||||
|
||||
---
|
||||
|
||||
## `POST /api/v1/progress/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get real-time processing progress including processor status, TKG build phases, and identity agent phases.
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/progress/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '.'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"overall_progress": 71,
|
||||
"cpu_percent": 45.2,
|
||||
"gpu_percent": 30.1,
|
||||
"memory_percent": 62.4,
|
||||
"processors": [
|
||||
{"name": "asr", "status": "complete", "progress": 100, "current": 0, "total": 0, "message": "done"},
|
||||
{"name": "face", "status": "complete", "progress": 100, "current": 0, "total": 0, "message": "done"},
|
||||
{"name": "pose", "status": "complete", "progress": 100, "current": 0, "total": 0, "message": "done"}
|
||||
],
|
||||
"tkg_progress": {
|
||||
"file_uuid": "3a6c1865...",
|
||||
"phase": "mutual_gaze_edges",
|
||||
"phase_index": 13,
|
||||
"total_phases": 18,
|
||||
"phase_progress": 0.8,
|
||||
"overall_progress": 0.72,
|
||||
"stats": {
|
||||
"total_faces": 1250,
|
||||
"traced_faces": 1250,
|
||||
"total_traces": 45,
|
||||
"face_track_nodes": 45,
|
||||
"gaze_track_nodes": 45,
|
||||
"lip_track_nodes": 12,
|
||||
"text_region_nodes": 8,
|
||||
"appearance_nodes": 38,
|
||||
"accessory_nodes": 5,
|
||||
"object_nodes": 156,
|
||||
"hand_nodes": 22,
|
||||
"speaker_nodes": 14,
|
||||
"co_occurrence_edges": 890,
|
||||
"speaker_face_edges": 120,
|
||||
"face_face_edges": 234,
|
||||
"mutual_gaze_edges": 67,
|
||||
"total_nodes": 345,
|
||||
"total_edges": 1311
|
||||
},
|
||||
"message": "67 mutual gaze edges",
|
||||
"updated_at": "2026-07-02T10:30:00Z"
|
||||
},
|
||||
"agent_progress": {
|
||||
"file_uuid": "3a6c1865...",
|
||||
"phase": "completed",
|
||||
"phase_index": 5,
|
||||
"total_phases": 5,
|
||||
"phase_progress": 1.0,
|
||||
"overall_progress": 1.0,
|
||||
"stats": {
|
||||
"total_faces": 1250,
|
||||
"total_traces": 45,
|
||||
"clusters": 18,
|
||||
"identities_created": 18,
|
||||
"tmdb_matches": 5,
|
||||
"speaker_bindings": 12,
|
||||
"confirmations": 18
|
||||
},
|
||||
"message": "Identity Agent processing completed",
|
||||
"updated_at": "2026-07-02T10:28:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Field Descriptions
|
||||
|
||||
#### Top Level
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `overall_progress` | integer | Overall processor progress (0–100) |
|
||||
| `processors` | array | Per-processor status |
|
||||
| `tkg_progress` | object | TKG build progress (null if not started) |
|
||||
| `agent_progress` | object | Identity Agent progress (null if not started) |
|
||||
|
||||
#### TKG Progress Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `phase` | string | Current phase name (see TKG Phases below) |
|
||||
| `phase_index` | integer | Current phase index (0–17) |
|
||||
| `total_phases` | integer | Total phases: 18 |
|
||||
| `phase_progress` | float | Progress within current phase (0.0–1.0) |
|
||||
| `overall_progress` | float | Overall TKG progress (0.0–1.0) |
|
||||
| `stats` | object | Counts for all node and edge types |
|
||||
| `message` | string | Human-readable status message |
|
||||
|
||||
#### TKG Phases (18 total)
|
||||
|
||||
| Index | Phase | Description |
|
||||
|-------|-------|-------------|
|
||||
| 0 | `face_tracing` | Populate trace_id from face.json |
|
||||
| 1 | `face_track_nodes` | Build face_track nodes |
|
||||
| 2 | `gaze_track_nodes` | Build gaze_track nodes |
|
||||
| 3 | `lip_track_nodes` | Build lip_track nodes |
|
||||
| 4 | `text_region_nodes` | Build text_region nodes |
|
||||
| 5 | `appearance_nodes` | Build appearance_trace nodes |
|
||||
| 6 | `accessory_nodes` | Build accessory nodes |
|
||||
| 7 | `object_nodes` | Build yolo_object nodes |
|
||||
| 8 | `hand_nodes` | Build hand nodes |
|
||||
| 9 | `speaker_nodes` | Build speaker nodes |
|
||||
| 10 | `co_occurrence_edges` | Build co_occurrence edges |
|
||||
| 11 | `speaker_face_edges` | Build speaker_face edges |
|
||||
| 12 | `face_face_edges` | Build face_face edges |
|
||||
| 13 | `mutual_gaze_edges` | Build mutual_gaze edges |
|
||||
| 14 | `lip_sync_edges` | Build lip_sync edges |
|
||||
| 15 | `has_appearance_edges` | Build has_appearance edges |
|
||||
| 16 | `wears_edges` | Build wears edges |
|
||||
| 17 | `hand_object_edges` | Build hand_object edges |
|
||||
|
||||
#### TKG Stats Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `total_faces` | integer | Total face detections |
|
||||
| `traced_faces` | integer | Faces with trace_id assigned |
|
||||
| `total_traces` | integer | Unique trace count |
|
||||
| `face_track_nodes` | integer | Face track nodes created |
|
||||
| `gaze_track_nodes` | integer | Gaze track nodes created |
|
||||
| `lip_track_nodes` | integer | Lip track nodes created |
|
||||
| `text_region_nodes` | integer | Text region nodes created |
|
||||
| `appearance_nodes` | integer | Appearance trace nodes created |
|
||||
| `accessory_nodes` | integer | Accessory nodes created |
|
||||
| `object_nodes` | integer | YOLO object nodes created |
|
||||
| `hand_nodes` | integer | Hand nodes created |
|
||||
| `speaker_nodes` | integer | Speaker nodes created |
|
||||
| `co_occurrence_edges` | integer | Co-occurrence edges created |
|
||||
| `speaker_face_edges` | integer | Speaker-face edges created |
|
||||
| `face_face_edges` | integer | Face-face edges created |
|
||||
| `mutual_gaze_edges` | integer | Mutual gaze edges created |
|
||||
| `lip_sync_edges` | integer | Lip sync edges created |
|
||||
| `has_appearance_edges` | integer | Has-appearance edges created |
|
||||
| `wears_edges` | integer | Wears edges created |
|
||||
| `hand_object_edges` | integer | Hand-object edges created |
|
||||
| `total_nodes` | integer | Total nodes (sum of all node types) |
|
||||
| `total_edges` | integer | Total edges (sum of all edge types) |
|
||||
|
||||
---
|
||||
|
||||
## `GET /api/v1/stats/ingestion-status/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get detailed ingestion status showing completion of all 24 processing steps.
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/stats/ingestion-status/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '.steps[] | {name, status, detail}'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"steps": [
|
||||
{"name": "rule1_sentence", "status": "done", "detail": "156 sentence chunks"},
|
||||
{"name": "auto_vectorize", "status": "done", "detail": "156 embedded"},
|
||||
{"name": "face_track", "status": "done", "detail": "45 traces / 1250 detections"},
|
||||
{"name": "trace_chunks", "status": "done", "detail": "45 trace chunks"},
|
||||
{"name": "tkg_face_track", "status": "done", "detail": "45 nodes"},
|
||||
{"name": "tkg_gaze_track", "status": "done", "detail": "45 nodes"},
|
||||
{"name": "tkg_lip_track", "status": "done", "detail": "12 nodes"},
|
||||
{"name": "tkg_text_region", "status": "done", "detail": "8 nodes"},
|
||||
{"name": "tkg_appearance", "status": "done", "detail": "38 nodes"},
|
||||
{"name": "tkg_accessory", "status": "done", "detail": "5 nodes"},
|
||||
{"name": "tkg_object", "status": "done", "detail": "156 nodes"},
|
||||
{"name": "tkg_hand", "status": "done", "detail": "22 nodes"},
|
||||
{"name": "tkg_speaker", "status": "done", "detail": "14 nodes"},
|
||||
{"name": "tkg_co_occurrence", "status": "done", "detail": "890 edges"},
|
||||
{"name": "tkg_speaker_face", "status": "done", "detail": "120 edges"},
|
||||
{"name": "tkg_face_face", "status": "done", "detail": "234 edges"},
|
||||
{"name": "tkg_mutual_gaze", "status": "done", "detail": "67 edges"},
|
||||
{"name": "tkg_lip_sync", "status": "done", "detail": "12 edges"},
|
||||
{"name": "tkg_has_appearance", "status": "done", "detail": "38 edges"},
|
||||
{"name": "tkg_wears", "status": "done", "detail": "22 edges"},
|
||||
{"name": "tkg_hand_object", "status": "done", "detail": "18 edges"},
|
||||
{"name": "rule2_relationship", "status": "done", "detail": "1331 relationship chunks"},
|
||||
{"name": "identity_match", "status": "done", "detail": "18 identities matched"},
|
||||
{"name": "scene_metadata", "status": "done", "detail": null}
|
||||
],
|
||||
"related_identities": [
|
||||
{"uuid": "a9a901056d6b46ff92da0c3c1a57dff4", "name": "John Smith"}
|
||||
],
|
||||
"strangers": 3
|
||||
}
|
||||
```
|
||||
|
||||
### Step Descriptions
|
||||
|
||||
| Step | Status When Done |
|
||||
|------|-----------------|
|
||||
| `rule1_sentence` | sentence_count > 0 |
|
||||
| `auto_vectorize` | sentence_embedded > 0 |
|
||||
| `face_track` | trace_count > 0 |
|
||||
| `trace_chunks` | trace_chunks > 0 |
|
||||
| `tkg_face_track` → `tkg_speaker` | Node count > 0 (9 steps) |
|
||||
| `tkg_co_occurrence` → `tkg_hand_object` | Edge count > 0 (8 steps) |
|
||||
| `rule2_relationship` | relationship_chunks > 0 |
|
||||
| `identity_match` | identity_count > 0 |
|
||||
| `scene_metadata` | scene_meta.json exists |
|
||||
|
||||
---
|
||||
|
||||
## `POST /api/v1/file/:file_uuid/tkg/rebuild`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Manually trigger TKG rebuild. Automatically triggers Rule 2 ingestion after TKG completes.
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/rebuild" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" -d '{}'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "TKG rebuild started",
|
||||
"nodes": 345,
|
||||
"edges": 1311
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## `POST /api/v1/file/:file_uuid/rule2`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Manually trigger Rule 2 ingestion (TKG edges → relationship chunks).
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/rule2" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" -d '{}'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Rule 2 ingestion: 1331 relationship chunks created",
|
||||
"rule2_count": 1331
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Processing Pipeline Flow
|
||||
|
||||
```
|
||||
1. Processors (concurrent)
|
||||
├── cut, asr, ocr, face, pose, appearance → complete
|
||||
└── asrx → after cut+asr
|
||||
|
||||
2. Post-Processor Triggers (automatic)
|
||||
├── Rule 1 Ingestion (ASR+OCR → sentence chunks)
|
||||
├── Face Trace + DB Store (face_traced.json → Qdrant trace_id)
|
||||
├── TMDb Face Matching (if enabled)
|
||||
├── Heuristic Scene Metadata
|
||||
├── Identity Agent (face + ASRX)
|
||||
└── TKG Build (automatic after processors complete)
|
||||
└── Rule 2 Ingestion (automatic after TKG)
|
||||
└── Relationship chunks vectorized
|
||||
|
||||
3. Completion
|
||||
└── Job marked completed when all ingestion steps done
|
||||
```
|
||||
|
||||
## Error Codes
|
||||
|
||||
| Code | HTTP | When |
|
||||
|------|------|------|
|
||||
| E001 | 400 | Invalid file_uuid format |
|
||||
| E002 | 404 | File not found |
|
||||
| E003 | 404 | No TKG data available |
|
||||
| E010 | 500 | Qdrant connection failed |
|
||||
| E011 | 500 | Database connection failed |
|
||||
|
||||
---
|
||||
|
||||
## `GET /api/v1/stats/pipeline/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get segmented pipeline progress with weighted stage breakdown. Shows overall progress as weighted sum of all pipeline stages.
|
||||
|
||||
### Pipeline Stages and Weights
|
||||
|
||||
| Stage | Weight | Description |
|
||||
|-------|--------|-------------|
|
||||
| `processors` | 30% | 7 concurrent processors (cut, asr, asrx, ocr, face, pose, appearance) |
|
||||
| `rule1_ingestion` | 5% | ASR+OCR → sentence chunks |
|
||||
| `face_tracing` | 5% | Face trace_id assignment |
|
||||
| `identity_agent` | 10% | Identity creation, TMDb matching, speaker binding |
|
||||
| `tkg_nodes` | 20% | TKG node building (9 node types) |
|
||||
| `tkg_edges` | 15% | TKG edge building (8 edge types) |
|
||||
| `rule2_ingestion` | 15% | TKG edges → relationship chunks |
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/stats/pipeline/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '.'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"overall_progress": 0.65,
|
||||
"stages": [
|
||||
{"name": "processors", "weight": 0.30, "progress": 1.0, "status": "completed", "detail": "7/7 complete"},
|
||||
{"name": "rule1_ingestion", "weight": 0.05, "progress": 1.0, "status": "completed", "detail": "156 chunks"},
|
||||
{"name": "face_tracing", "weight": 0.05, "progress": 1.0, "status": "completed", "detail": "45 traces"},
|
||||
{"name": "identity_agent", "weight": 0.10, "progress": 1.0, "status": "completed", "detail": "18 identities"},
|
||||
{"name": "tkg_nodes", "weight": 0.20, "progress": 1.0, "status": "completed", "detail": "345 nodes"},
|
||||
{"name": "tkg_edges", "weight": 0.15, "progress": 0.5, "status": "running", "detail": "mutual_gaze_edges: 67/8 expected"},
|
||||
{"name": "rule2_ingestion", "weight": 0.15, "progress": 0.0, "status": "pending", "detail": null}
|
||||
],
|
||||
"updated_at": "2026-07-02T10:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### Field Descriptions
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `overall_progress` | float | Weighted sum of all stage progress (0.0–1.0) |
|
||||
| `stages` | array | Per-stage progress breakdown |
|
||||
| `stages[].name` | string | Stage name |
|
||||
| `stages[].weight` | float | Stage weight in overall progress |
|
||||
| `stages[].progress` | float | Stage completion (0.0–1.0) |
|
||||
| `stages[].status` | string | `"pending"`, `"running"`, `"completed"`, `"failed"` |
|
||||
| `stages[].detail` | string | Human-readable detail (optional) |
|
||||
| `updated_at` | string | ISO 8601 timestamp |
|
||||
|
||||
### Overall Progress Calculation
|
||||
|
||||
```
|
||||
overall_progress = Σ(stage.weight × stage.progress) for all stages
|
||||
```
|
||||
|
||||
Example calculation:
|
||||
- processors: 0.30 × 1.0 = 0.30
|
||||
- rule1_ingestion: 0.05 × 1.0 = 0.05
|
||||
- face_tracing: 0.05 × 1.0 = 0.05
|
||||
- identity_agent: 0.10 × 1.0 = 0.10
|
||||
- tkg_nodes: 0.20 × 1.0 = 0.20
|
||||
- tkg_edges: 0.15 × 0.5 = 0.075
|
||||
- rule2_ingestion: 0.15 × 0.0 = 0.0
|
||||
- **Total: 0.775 (77.5%)**
|
||||
|
||||
---
|
||||
|
||||
## `GET /api/v1/stats/file/:file_uuid`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get comprehensive file statistics from all data sources: JSON processing status, PostgreSQL counts, Qdrant collections, TKG nodes/edges, and Identity Agent stats.
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/stats/file/$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY" | jq '.'
|
||||
```
|
||||
|
||||
### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "3a6c1865...",
|
||||
"file_name": "video.mp4",
|
||||
"status": "processing",
|
||||
"processors": [
|
||||
{"name": "asr", "status": "complete", "progress": 100, "message": "done"},
|
||||
{"name": "face", "status": "complete", "progress": 100, "message": "done"}
|
||||
],
|
||||
"postgres": {
|
||||
"sentence_chunks": 156,
|
||||
"trace_chunks": 45,
|
||||
"relationship_chunks": 1331,
|
||||
"identities": 18,
|
||||
"file_identities": 18
|
||||
},
|
||||
"qdrant": {
|
||||
"faces": 1250,
|
||||
"face_traces": 45,
|
||||
"face_identities": 18,
|
||||
"text_chunks": 4562,
|
||||
"speakers": 434
|
||||
},
|
||||
"tkg": {
|
||||
"total_nodes": 345,
|
||||
"total_edges": 1311,
|
||||
"face_track_nodes": 45,
|
||||
"gaze_track_nodes": 45,
|
||||
"lip_track_nodes": 12,
|
||||
"text_region_nodes": 8,
|
||||
"appearance_nodes": 38,
|
||||
"accessory_nodes": 5,
|
||||
"object_nodes": 156,
|
||||
"hand_nodes": 22,
|
||||
"speaker_nodes": 14,
|
||||
"co_occurrence_edges": 890,
|
||||
"speaker_face_edges": 120,
|
||||
"face_face_edges": 234,
|
||||
"mutual_gaze_edges": 67,
|
||||
"lip_sync_edges": 12,
|
||||
"has_appearance_edges": 38,
|
||||
"wears_edges": 22,
|
||||
"hand_object_edges": 18
|
||||
},
|
||||
"identity_agent": {
|
||||
"clusters": 18,
|
||||
"identities_created": 18,
|
||||
"tmdb_matches": 5,
|
||||
"speaker_bindings": 12,
|
||||
"confirmations": 18
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Field Descriptions
|
||||
|
||||
#### Top Level
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | 32-char hex UUID |
|
||||
| `file_name` | string | Original filename |
|
||||
| `status` | string | File status: `registered`, `processing`, `completed`, `failed` |
|
||||
| `processors` | array | Per-processor status from processing_status JSONB |
|
||||
| `postgres` | object | PostgreSQL table counts |
|
||||
| `qdrant` | object | Qdrant collection point counts |
|
||||
| `tkg` | object | TKG node and edge counts by type |
|
||||
| `identity_agent` | object | Identity Agent statistics |
|
||||
|
||||
#### PostgreSQL Stats
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `sentence_chunks` | integer | Rule 1 sentence chunks count |
|
||||
| `trace_chunks` | integer | Face trace chunks count |
|
||||
| `relationship_chunks` | integer | Rule 2 relationship chunks count |
|
||||
| `identities` | integer | Unique identities bound to this file |
|
||||
| `file_identities` | integer | File-identity mapping records |
|
||||
|
||||
#### Qdrant Stats
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `faces` | integer | Total face points in `_faces` collection |
|
||||
| `face_traces` | integer | Unique trace IDs in `_faces` |
|
||||
| `face_identities` | integer | Unique identity IDs bound in `_faces` |
|
||||
| `text_chunks` | integer | Text chunk vectors in `momentry_*_rule1_v2` |
|
||||
| `speakers` | integer | Speaker segments in `momentry_*_speaker` |
|
||||
|
||||
#### TKG Stats
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `total_nodes` | integer | Sum of all node types |
|
||||
| `total_edges` | integer | Sum of all edge types |
|
||||
| `face_track_nodes` | integer | Face track nodes |
|
||||
| `gaze_track_nodes` | integer | Gaze track nodes |
|
||||
| `lip_track_nodes` | integer | Lip track nodes |
|
||||
| `text_region_nodes` | integer | Text region nodes |
|
||||
| `appearance_nodes` | integer | Appearance trace nodes |
|
||||
| `accessory_nodes` | integer | Accessory nodes |
|
||||
| `object_nodes` | integer | YOLO object nodes |
|
||||
| `hand_nodes` | integer | Hand nodes |
|
||||
| `speaker_nodes` | integer | Speaker nodes |
|
||||
| `co_occurrence_edges` | integer | Co-occurrence edges |
|
||||
| `speaker_face_edges` | integer | Speaker-face edges |
|
||||
| `face_face_edges` | integer | Face-face edges |
|
||||
| `mutual_gaze_edges` | integer | Mutual gaze edges |
|
||||
| `lip_sync_edges` | integer | Lip sync edges |
|
||||
| `has_appearance_edges` | integer | Has-appearance edges |
|
||||
| `wears_edges` | integer | Wears edges |
|
||||
| `hand_object_edges` | integer | Hand-object edges |
|
||||
|
||||
#### Identity Agent Stats
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `clusters` | integer | Face clusters from face_clustered.json |
|
||||
| `identities_created` | integer | Identities created from clusters |
|
||||
| `tmdb_matches` | integer | TMDb identity matches |
|
||||
| `speaker_bindings` | integer | Speaker-to-identity bindings |
|
||||
| `confirmations` | integer | Confirmed identity bindings |
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,492 @@
|
||||
---
|
||||
title: profile API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: profile -->
|
||||
<!-- description: Trace profile and file profile management — read/update face trace names, key frames, aliases, and file paths -->
|
||||
<!-- depends: 01_auth, 07_identity, 15_tkg -->
|
||||
|
||||
## Profile Management
|
||||
|
||||
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
|
||||
**Scope**: file-level
|
||||
|
||||
Read a single face trace's profile including name, key frame, key face, and multi-language aliases.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `trace_id` | integer | Yes | Trace ID (numeric) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/trace-profile?file_uuid=$FILE_UUID&trace_id=7" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 7,
|
||||
"name": "John Doe",
|
||||
"key_frame": 640,
|
||||
"key_face": "face_12345",
|
||||
"aliases": {
|
||||
"en": "John Doe",
|
||||
"zh": "約翰"
|
||||
},
|
||||
"properties": {
|
||||
"status": "bound",
|
||||
"avg_bbox": {"x": 899, "y": 212, "width": 342, "height": 342},
|
||||
"start_frame": 624,
|
||||
"end_frame": 669,
|
||||
"frame_count": 5
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | File UUID |
|
||||
| `trace_id` | integer | Trace ID |
|
||||
| `name` | string | Display name (from `tkg_nodes.label`) |
|
||||
| `key_frame` | integer | Representative frame number, or null |
|
||||
| `key_face` | string | Representative face ID, or null |
|
||||
| `aliases` | object | Multi-language name aliases |
|
||||
| `properties` | object | Full TKG node properties (bbox, frames, etc.) |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| `404` | Trace not found |
|
||||
| `401` | Missing or invalid API key |
|
||||
|
||||
---
|
||||
|
||||
### `PUT /api/v1/trace-profile`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Update a single face trace's profile fields. Only provided fields are updated; others remain unchanged.
|
||||
|
||||
#### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `trace_id` | integer | Yes | Trace ID to update |
|
||||
| `name` | string | No | New display name |
|
||||
| `key_frame` | integer | No | Representative frame number |
|
||||
| `key_face` | string | No | Representative face ID |
|
||||
| `aliases` | object | No | Multi-language aliases `{"en": "...", "zh": "..."}` |
|
||||
| `properties` | object | No | Additional properties to merge into existing JSONB |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X PUT "$API/api/v1/trace-profile" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 7,
|
||||
"name": "John Doe",
|
||||
"key_frame": 640,
|
||||
"key_face": "face_12345",
|
||||
"aliases": {"en": "John Doe", "zh": "約翰"}
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Trace profile updated",
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_id": 7
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `PUT /api/v1/trace-profile/group`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Batch update the `name` (label) for multiple traces in a face group. Used when renaming a group.
|
||||
|
||||
#### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `trace_ids` | integer[] | Yes | List of trace IDs to update |
|
||||
| `name` | string | Yes | New group name for all traces |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X PUT "$API/api/v1/trace-profile/group" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"trace_ids": [7, 2, 13],
|
||||
"name": "Group A"
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Updated 3 traces in group",
|
||||
"file_uuid": "9f6a9cd55a5809f977f5a6589b9045c5",
|
||||
"updated_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `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
|
||||
**Scope**: file-level
|
||||
|
||||
Read a file's metadata including path, name, status, and technical details.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file-profile?file_uuid=$FILE_UUID" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "49884ce1c341953d1ad7bf67a77c30cc",
|
||||
"file_name": "Dedicatoria.mp4",
|
||||
"file_path": "/Users/accusys/momentry/var/sftpgo/data/demo/Dedicatoria.mp4",
|
||||
"status": "completed",
|
||||
"duration": 93.33,
|
||||
"width": 1280,
|
||||
"height": 720,
|
||||
"fps": 30.0,
|
||||
"total_frames": 0
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `file_uuid` | string | File UUID |
|
||||
| `file_name` | string | File name |
|
||||
| `file_path` | string | Full filesystem path |
|
||||
| `status` | string | `pending`, `processing`, `completed`, `failed` |
|
||||
| `duration` | float | Duration in seconds |
|
||||
| `width` | integer | Video width in pixels |
|
||||
| `height` | integer | Video height in pixels |
|
||||
| `fps` | float | Frames per second |
|
||||
| `total_frames` | integer | Total frame count |
|
||||
|
||||
---
|
||||
|
||||
### `PUT /api/v1/file-profile`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Update file metadata, typically used when a file is moved to a new location.
|
||||
|
||||
#### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `file_path` | string | No | New filesystem path |
|
||||
| `file_name` | string | No | New file name |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s -X PUT "$API/api/v1/file-profile" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"file_uuid": "49884ce1c341953d1ad7bf67a77c30cc",
|
||||
"file_path": "/new/location/Dedicatoria.mp4"
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "File profile updated",
|
||||
"file_uuid": "49884ce1c341953d1ad7bf67a77c30cc"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Data Storage
|
||||
|
||||
| Profile Type | Storage | Table |
|
||||
|-------------|---------|-------|
|
||||
| **trace_profile** | PostgreSQL (TKG) | `tkg_nodes` where `node_type='face_track'` |
|
||||
| **file_profile** | PostgreSQL | `videos` |
|
||||
|
||||
### Trace Profile Fields
|
||||
|
||||
| Field | TKG Column | Description |
|
||||
|-------|-----------|-------------|
|
||||
| `name` | `label` | Display name for the trace |
|
||||
| `key_frame` | `properties->'key_frame'` | Representative frame number |
|
||||
| `key_face` | `properties->'key_face'` | Representative face ID |
|
||||
| `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)*
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,416 @@
|
||||
---
|
||||
title: people api API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
# 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_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 <api_key>" \
|
||||
-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 <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 > 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 |
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,387 @@
|
||||
---
|
||||
title: Service Management API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: service_management -->
|
||||
<!-- description: Service lifecycle management endpoints -->
|
||||
<!-- depends: health -->
|
||||
|
||||
# Service Management API
|
||||
|
||||
Manage Momentry core services, including start, stop, and health check operations.
|
||||
|
||||
## Overview
|
||||
|
||||
Service Management API provides endpoints for:
|
||||
- **Start Service**: Launch inference services (e.g., MBE)
|
||||
- **Stop Service**: Terminate running services
|
||||
- **Health Check**: Monitor service status
|
||||
|
||||
## Endpoints
|
||||
|
||||
### `POST /api/v2/service/start`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: system-level
|
||||
|
||||
Start a Momentry service.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `name` | string | Yes | — | Service name (e.g., `"mbe"`) |
|
||||
| `model` | string | No | — | Model path or name |
|
||||
| `port` | number | No | 8080 | Service port |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Start MBE service with default model
|
||||
curl -s -X POST "$API/api/v2/service/start" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "mbe"}'
|
||||
```
|
||||
|
||||
```bash
|
||||
# Start MBE service with custom model and port
|
||||
curl -s -X POST "$API/api/v2/service/start" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "mbe",
|
||||
"model": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf",
|
||||
"port": 8080
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"result": "started",
|
||||
"pid": 12345
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `result` | string | `"started"` or `"failed"` |
|
||||
| `pid` | number | Process ID if successful |
|
||||
| `error` | string | Error message if failed |
|
||||
|
||||
#### Implementation Details
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/src/api/service_management.rs`
|
||||
|
||||
**Process**:
|
||||
1. Validates service name (currently only `"mbe"` supported)
|
||||
2. Checks if port is already in use
|
||||
3. Stops existing process on that port
|
||||
4. Spawns llama-server with specified model
|
||||
5. Waits up to 60 seconds for service to be ready
|
||||
6. Returns process ID on success
|
||||
|
||||
**Supported Services**:
|
||||
- `"mbe"` - MarkBase Engine (llama.cpp server)
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v2/service/stop`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: system-level
|
||||
|
||||
Stop a running service.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `name` | string | Yes | — | Service name (e.g., `"mbe"`) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Stop MBE service
|
||||
curl -s -X POST "$API/api/v2/service/stop" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "mbe"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
**Success**:
|
||||
```json
|
||||
{
|
||||
"result": "stopped"
|
||||
}
|
||||
```
|
||||
|
||||
**Failure**:
|
||||
```json
|
||||
{
|
||||
"result": "failed",
|
||||
"error": "No service running on port 8080"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `result` | string | `"stopped"` or `"failed"` |
|
||||
| `error` | string | Error message if failed |
|
||||
|
||||
#### Implementation Details
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/src/api/service_management.rs`
|
||||
|
||||
**Process**:
|
||||
1. Validates service name
|
||||
2. Finds process ID by port (8080)
|
||||
3. Sends kill signal
|
||||
4. Returns success/failure
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/mbe/health`
|
||||
|
||||
**Auth**: Public
|
||||
|
||||
**Scope**: system-level
|
||||
|
||||
Check MBE (MarkBase Engine) health status.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
None
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Check MBE health
|
||||
curl -s "$API/api/v1/mbe/health"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
**Online**:
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"model": "gemma-4-12b-it-Q4_K_M.gguf",
|
||||
"uptime": 3600
|
||||
}
|
||||
```
|
||||
|
||||
**Offline**:
|
||||
```json
|
||||
{
|
||||
"status": "offline"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `status` | string | `"ok"` or `"offline"` |
|
||||
| `model` | string | Model name if online |
|
||||
| `uptime` | number | Uptime in seconds (currently always 0) |
|
||||
|
||||
#### Implementation Details
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/src/api/service_management.rs`
|
||||
|
||||
**Process**:
|
||||
1. Checks if port 8080 is in use
|
||||
2. Calls `/v1/models` endpoint
|
||||
3. Extracts model name from response
|
||||
4. Returns health status
|
||||
|
||||
**Health Check Endpoint**: `http://127.0.0.1:8080/v1/models`
|
||||
|
||||
---
|
||||
|
||||
## Error Codes
|
||||
|
||||
| Code | HTTP | When |
|
||||
|------|------|------|
|
||||
| E401 | 401 | Missing or invalid API key |
|
||||
| E400 | 400 | Invalid service name |
|
||||
| E500 | 500 | Service start/stop failed |
|
||||
|
||||
---
|
||||
|
||||
## Usage Patterns
|
||||
|
||||
### Start Service → Check Health
|
||||
|
||||
```bash
|
||||
# Start MBE
|
||||
curl -s -X POST "$API/api/v2/service/start" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "mbe"}'
|
||||
|
||||
# Wait a few seconds
|
||||
sleep 5
|
||||
|
||||
# Check health
|
||||
curl -s "$API/api/v1/mbe/health"
|
||||
```
|
||||
|
||||
### Stop Service → Verify Stopped
|
||||
|
||||
```bash
|
||||
# Stop MBE
|
||||
curl -s -X POST "$API/api/v2/service/stop" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "mbe"}'
|
||||
|
||||
# Check health (should be offline)
|
||||
curl -s "$API/api/v1/mbe/health"
|
||||
```
|
||||
|
||||
### Restart Service
|
||||
|
||||
```bash
|
||||
# Stop if running
|
||||
curl -s -X POST "$API/api/v2/service/stop" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "mbe"}'
|
||||
|
||||
# Wait for cleanup
|
||||
sleep 3
|
||||
|
||||
# Start with new configuration
|
||||
curl -s -X POST "$API/api/v2/service/start" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "mbe", "port": 8080}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Default Settings
|
||||
|
||||
**MBE (llama-server)**:
|
||||
- **Port**: 8080
|
||||
- **Model**: `/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf`
|
||||
- **mmproj**: `/Users/accusys/models/mmproj-F16.gguf`
|
||||
- **Binary**: `/Users/accusys/llama.cpp/build/bin/llama-server`
|
||||
|
||||
**Launch Parameters**:
|
||||
```bash
|
||||
llama-server \
|
||||
-m <model_path> \
|
||||
--mmproj <mmproj_path> \
|
||||
--host 0.0.0.0 \
|
||||
--port 8080 \
|
||||
-ngl 99 \
|
||||
-c 8192 \
|
||||
--temp 0.1 \
|
||||
-b 4096 \
|
||||
-ub 4096
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
The start process sets:
|
||||
- `PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Health API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/02_health.md)
|
||||
- [MarkBase Documentation](/Users/accusys/markbase/README.md)
|
||||
- [LLM Services Guide](/Users/accusys/momentry_core/docs_v1.0/OPERATIONS/LLM_SERVICES/)
|
||||
|
||||
---
|
||||
|
||||
## Common Issues
|
||||
|
||||
### Service Fails to Start
|
||||
|
||||
**Symptoms**: `{"result": "failed", "error": "..."}`
|
||||
|
||||
**Possible Causes**:
|
||||
1. Model file not found
|
||||
2. Port already in use by another process
|
||||
3. Insufficient permissions
|
||||
4. Binary not found
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
# Check model file exists
|
||||
ls -la /Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf
|
||||
|
||||
# Check port availability
|
||||
lsof -i :8080
|
||||
|
||||
# Check binary exists
|
||||
ls -la /Users/accusys/llama.cpp/build/bin/llama-server
|
||||
```
|
||||
|
||||
### Health Check Returns "offline"
|
||||
|
||||
**Symptoms**: `{"status": "offline"}`
|
||||
|
||||
**Possible Causes**:
|
||||
1. Service not started
|
||||
2. Service crashed after startup
|
||||
3. Network/firewall issue
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
# Start service
|
||||
curl -s -X POST "$API/api/v2/service/start" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "mbe"}'
|
||||
|
||||
# Check process status
|
||||
ps aux | grep llama-server
|
||||
|
||||
# Check logs
|
||||
tail -f ~/momentry_core/logs/momentry_3002.log
|
||||
```
|
||||
|
||||
### Service Keeps Restarting
|
||||
|
||||
**Symptoms**: PID changes frequently, service unstable
|
||||
|
||||
**Possible Causes**:
|
||||
1. Out of memory
|
||||
2. Model too large
|
||||
3. Hardware issue
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
# Check memory usage
|
||||
top -pid $(pgrep -f llama-server)
|
||||
|
||||
# Try smaller model or reduce parameters
|
||||
curl -s -X POST "$API/api/v2/service/start" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "mbe", "model": "<smaller_model_path>"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,397 @@
|
||||
---
|
||||
title: Monitor API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: monitor -->
|
||||
<!-- description: Queue/Worker/Pipeline monitoring endpoints -->
|
||||
<!-- depends: health -->
|
||||
|
||||
# Monitor API
|
||||
|
||||
Monitor Momentry's job queue, worker status, and processing pipeline in real-time.
|
||||
|
||||
## Overview
|
||||
|
||||
Monitor API provides endpoints for:
|
||||
- **Queue Statistics**: Job counts by status
|
||||
- **Running Jobs**: Detailed view of active jobs with processor progress
|
||||
- **Worker Status**: System resources and worker process health
|
||||
|
||||
## Endpoints
|
||||
|
||||
### `GET /api/v1/monitor/queue_stats`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: system-level
|
||||
|
||||
Get job queue statistics grouped by status.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
None
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get queue statistics
|
||||
curl -s "$API/api/v1/monitor/queue_stats" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"pending": 5,
|
||||
"running": 2,
|
||||
"completed": 150,
|
||||
"failed": 3
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `pending` | number | Jobs waiting to be processed |
|
||||
| `running` | number | Jobs currently being processed |
|
||||
| `completed` | number | Jobs successfully completed |
|
||||
| `failed` | number | Jobs that failed |
|
||||
|
||||
#### Implementation Details
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/src/api/monitor.rs`
|
||||
|
||||
**Database Query**:
|
||||
```sql
|
||||
SELECT status, COUNT(*) as count
|
||||
FROM monitor_jobs
|
||||
GROUP BY status
|
||||
```
|
||||
|
||||
**Status Values**:
|
||||
- `"pending"` - Queued for processing
|
||||
- `"running"` - Currently being processed
|
||||
- `"completed"` - Successfully finished
|
||||
- `"failed"` - Processing failed
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/monitor/running_jobs`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: system-level
|
||||
|
||||
Get detailed information about currently running jobs, including processor progress.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
None
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get running jobs
|
||||
curl -s "$API/api/v1/monitor/running_jobs" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"jobs": [
|
||||
{
|
||||
"job_id": 123,
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"file_name": "video.mp4",
|
||||
"status": "running",
|
||||
"started_at": "2026-10-24T15:30:00Z",
|
||||
"duration_secs": 120,
|
||||
"processors": [
|
||||
{
|
||||
"name": "asr",
|
||||
"phase": 2,
|
||||
"status": "running",
|
||||
"progress": 75,
|
||||
"duration": 45.3
|
||||
},
|
||||
{
|
||||
"name": "face",
|
||||
"phase": 2,
|
||||
"status": "pending",
|
||||
"progress": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `jobs` | array | List of running jobs |
|
||||
| `jobs[].job_id` | number | Job ID |
|
||||
| `jobs[].file_uuid` | string | File UUID |
|
||||
| `jobs[].file_name` | string | File name |
|
||||
| `jobs[].status` | string | Job status (`"running"`) |
|
||||
| `jobs[].started_at` | string | ISO 8601 timestamp |
|
||||
| `jobs[].duration_secs` | number | Duration in seconds |
|
||||
| `jobs[].processors` | array | List of processors for this job |
|
||||
| `jobs[].processors[].name` | string | Processor type |
|
||||
| `jobs[].processors[].phase` | number | Processing phase (1-4) |
|
||||
| `jobs[].processors[].status` | string | Processor status |
|
||||
| `jobs[].processors[].progress` | number | Progress percentage (0-100) |
|
||||
| `jobs[].processors[].duration` | number | Duration in seconds (optional) |
|
||||
|
||||
#### Implementation Details
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/src/api/monitor.rs`
|
||||
|
||||
**Database Query**:
|
||||
```sql
|
||||
SELECT j.id, j.uuid, j.status, j.started_at, v.file_name
|
||||
FROM monitor_jobs j
|
||||
LEFT JOIN videos v ON v.file_uuid = j.uuid
|
||||
WHERE j.status = 'running'
|
||||
ORDER BY j.started_at DESC
|
||||
```
|
||||
|
||||
**Processor Phases**:
|
||||
| Phase | Processors | Description |
|
||||
|-------|-----------|-------------|
|
||||
| 1 | `cut` | Video segmentation |
|
||||
| 2 | `asr`, `asr_asrx`, `face`, `ocr` | Core processing |
|
||||
| 3 | `scene`, `face_trace`, `face_cluster` | Analysis & clustering |
|
||||
| 4 | `tkg` | Knowledge graph |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/monitor/worker_status`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: system-level
|
||||
|
||||
Get worker process status and system resource usage.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
None
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get worker status
|
||||
curl -s "$API/api/v1/monitor/worker_status" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"cpu_percent": 45.5,
|
||||
"gpu_percent": 60.0,
|
||||
"memory_mb": 8192,
|
||||
"memory_percent": 52.3,
|
||||
"active_processors": 3,
|
||||
"max_processors": 6,
|
||||
"processors": [
|
||||
{
|
||||
"name": "asr",
|
||||
"job_id": 123,
|
||||
"status": "running"
|
||||
},
|
||||
{
|
||||
"name": "face",
|
||||
"job_id": 124,
|
||||
"status": "running"
|
||||
}
|
||||
],
|
||||
"worker_pid": 12345,
|
||||
"uptime_secs": 3600,
|
||||
"last_poll_at": "2026-10-24T15:30:00Z",
|
||||
"poll_interval_secs": 5,
|
||||
"is_alive": true
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `cpu_percent` | number | CPU usage percentage |
|
||||
| `gpu_percent` | number | GPU utilization percentage |
|
||||
| `memory_mb` | number | Memory used in MB |
|
||||
| `memory_percent` | number | Memory usage percentage |
|
||||
| `active_processors` | number | Number of active processors |
|
||||
| `max_processors` | number | Maximum concurrent processors |
|
||||
| `processors` | array | List of active processors |
|
||||
| `processors[].name` | string | Processor type |
|
||||
| `processors[].job_id` | number | Job ID being processed |
|
||||
| `processors[].status` | string | Processor status |
|
||||
| `worker_pid` | number | Worker process ID |
|
||||
| `uptime_secs` | number | Worker uptime in seconds |
|
||||
| `last_poll_at` | string | Last activity timestamp (optional) |
|
||||
| `poll_interval_secs` | number | Expected poll interval |
|
||||
| `is_alive` | boolean | Worker process is running |
|
||||
|
||||
#### Implementation Details
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/src/api/monitor.rs`
|
||||
|
||||
**Data Sources**:
|
||||
- System resources: `SystemResources::check()`
|
||||
- Worker PID: `pgrep -f "momentry worker"`
|
||||
- Active processors: `processor_results` table
|
||||
- Last activity: `monitor_jobs` table
|
||||
|
||||
**Resource Monitoring**:
|
||||
- CPU: System-wide usage
|
||||
- GPU: Metal/ANE utilization (macOS)
|
||||
- Memory: Used vs total memory
|
||||
|
||||
---
|
||||
|
||||
## Usage Patterns
|
||||
|
||||
### Dashboard Monitoring
|
||||
|
||||
```bash
|
||||
# Get all monitoring data
|
||||
curl -s "$API/api/v1/monitor/queue_stats" -H "X-API-Key: $KEY" | jq
|
||||
curl -s "$API/api/v1/monitor/running_jobs" -H "X-API-Key: $KEY" | jq
|
||||
curl -s "$API/api/v1/monitor/worker_status" -H "X-API-Key: $KEY" | jq
|
||||
```
|
||||
|
||||
### Real-time Updates
|
||||
|
||||
```bash
|
||||
# Poll every 5 seconds
|
||||
watch -n 5 'curl -s "$API/api/v1/monitor/queue_stats" -H "X-API-Key: $KEY" | jq'
|
||||
```
|
||||
|
||||
### Health Check
|
||||
|
||||
```bash
|
||||
# Check if worker is alive
|
||||
curl -s "$API/api/v1/monitor/worker_status" -H "X-API-Key: $KEY" | jq '.is_alive'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error Codes
|
||||
|
||||
| Code | HTTP | When |
|
||||
|------|------|------|
|
||||
| E401 | 401 | Missing or invalid API key |
|
||||
| E500 | 500 | Database query failed |
|
||||
|
||||
---
|
||||
|
||||
## Database Tables
|
||||
|
||||
### `monitor_jobs`
|
||||
|
||||
Primary job queue table.
|
||||
|
||||
| Column | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `id` | integer | Job ID |
|
||||
| `uuid` | string | File UUID |
|
||||
| `status` | string | Job status |
|
||||
| `started_at` | timestamp | Start time |
|
||||
| `updated_at` | timestamp | Last update |
|
||||
|
||||
### `processor_results`
|
||||
|
||||
Processor execution results.
|
||||
|
||||
| Column | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `job_id` | integer | Job ID |
|
||||
| `processor_type` | string | Processor name |
|
||||
| `status` | string | Processor status |
|
||||
| `progress_current` | integer | Current progress |
|
||||
| `progress_total` | integer | Total steps |
|
||||
| `duration_secs` | float | Duration in seconds |
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Health API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/02_health.md)
|
||||
- [Pipeline API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/10_pipeline.md)
|
||||
- [Job Management](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/17_progress.md)
|
||||
|
||||
---
|
||||
|
||||
## Common Issues
|
||||
|
||||
### Worker Shows as Not Alive
|
||||
|
||||
**Symptoms**: `is_alive: false`
|
||||
|
||||
**Possible Causes**:
|
||||
1. Worker process not running
|
||||
2. Worker crashed
|
||||
3. `pgrep` command failed
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
# Check worker process
|
||||
ps aux | grep momentry
|
||||
|
||||
# Start worker
|
||||
momentry worker
|
||||
|
||||
# Check logs
|
||||
tail -f ~/momentry_core/logs/worker_3002.log
|
||||
```
|
||||
|
||||
### Queue Has Stuck Jobs
|
||||
|
||||
**Symptoms**: Jobs stuck in "running" status
|
||||
|
||||
**Possible Causes**:
|
||||
1. Worker crashed
|
||||
2. Processor timeout
|
||||
3. Database lock
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
# Check running jobs
|
||||
curl -s "$API/api/v1/monitor/running_jobs" -H "X-API-Key: $KEY"
|
||||
|
||||
# Reset stuck jobs (requires database access)
|
||||
# UPDATE monitor_jobs SET status = 'pending' WHERE status = 'running' AND updated_at < NOW() - INTERVAL '1 hour';
|
||||
```
|
||||
|
||||
### High Resource Usage
|
||||
|
||||
**Symptoms**: `cpu_percent` or `memory_percent` very high
|
||||
|
||||
**Possible Causes**:
|
||||
1. Too many concurrent jobs
|
||||
2. Large video files
|
||||
3. Memory leak
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
# Check active processors
|
||||
curl -s "$API/api/v1/monitor/worker_status" -H "X-API-Key: $KEY" | jq '.processors'
|
||||
|
||||
# Reduce max_processors if needed
|
||||
# Restart worker
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,199 @@
|
||||
# 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 team** | Momentry Core 後端 | `~/momentry_core/` |
|
||||
| **Studio team** | Momentry Studio 前端 | `~/momentry_studio/` |
|
||||
| **Marcom team** | WordPress 網站 | `/Users/accusys/wordpress/` |
|
||||
|
||||
---
|
||||
|
||||
## 3. API 變更
|
||||
|
||||
### `/api/v1/file/{file_uuid}/sync-status` 回傳格式
|
||||
|
||||
**POST** `/api/v1/file/{file_uuid}/sync-status`
|
||||
|
||||
```json
|
||||
{
|
||||
"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 的檔案:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "...",
|
||||
"status": "registered",
|
||||
"processors_complete": 0,
|
||||
"processors_total": 5,
|
||||
"worker": {
|
||||
"has_job": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Worker 狀態說明
|
||||
|
||||
| 欄位 | 說明 |
|
||||
|------|------|
|
||||
| `has_job` | 是否有 monitor_job 紀錄 |
|
||||
| `job_status` | pending / running / completed / failed |
|
||||
| `current_processor` | 目前正在執行的 processor |
|
||||
| `progress_total` | 總 processor 數量 |
|
||||
| `progress_current` | 已完成的 processor 數量 |
|
||||
| `completed_processors` | 已完成的 processor 列表 |
|
||||
| `failed_processors` | 失敗的 processor 列表 |
|
||||
| `updated_at` | 最後更新時間 |
|
||||
|
||||
### 使用者可區分的情境
|
||||
|
||||
| 情境 | `job_status` | `current_processor` | 顯示建議 |
|
||||
|------|-------------|-------------------|---------|
|
||||
| **正在處理** | `running` | `face` | 🔄 正在執行 Face |
|
||||
| **排隊等待** | `pending` | `null` | ⏳ 等待處理 |
|
||||
| **已完成** | `completed` | `null` | ✅ Processor 完成 |
|
||||
| **處理失敗** | `failed` | `face` | ❌ 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_ready` | Agent 可用 | 🤖 | tkg_edges > 0 |
|
||||
| `completed` | 已完成 | ✅ | 全部就緒 |
|
||||
|
||||
### 已移除的舊狀態
|
||||
|
||||
| 舊狀態 | 新狀態 |
|
||||
|--------|--------|
|
||||
| `pending` | `registered` |
|
||||
| `processing` | `scanning` |
|
||||
|
||||
---
|
||||
|
||||
## 4. Studio 前端需修改項目
|
||||
|
||||
### 4.1 狀態顯示邏輯
|
||||
|
||||
**位置:** `~/momentry_studio/` 中處理檔案狀態顯示的元件
|
||||
|
||||
**修改前:**
|
||||
```javascript
|
||||
switch (file.status) {
|
||||
case 'completed': return '✅ 已完成';
|
||||
case 'processing': return '🔄 處理中';
|
||||
case 'pending': return '⏳ 待處理';
|
||||
default: return '📦 未註冊';
|
||||
}
|
||||
```
|
||||
|
||||
**修改後:**
|
||||
```javascript
|
||||
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 points | Face embeddings 已存入 Qdrant |
|
||||
| **Face Trace Ready** | `face_traced.json` 存在且有 traces | Face tracking 已完成 |
|
||||
| **Face Profile Ready** | `trace_profiles` 有紀錄 | Profile 資料已建立 |
|
||||
| **Face TKG Node Ready** | `tkg_nodes` 有 `face_track` nodes | TKG 圖譜節點已建立 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 狀態依賴關係
|
||||
|
||||
```
|
||||
registered → scanning → keyword_ready → semantic_ready
|
||||
↓
|
||||
face_mgmt_ready → agent_ready → completed
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 測試 API
|
||||
|
||||
```bash
|
||||
# 取得所有檔案
|
||||
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` |
|
||||
@@ -0,0 +1,207 @@
|
||||
# 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_ready` | Agent 可用 | 🤖 | TKG edges 存在 |
|
||||
|
||||
### 已移除的狀態
|
||||
|
||||
| 舊狀態 | 新狀態 | 說明 |
|
||||
|--------|--------|------|
|
||||
| `processing` | `scanning` | 更明確表示正在處理 |
|
||||
| `pending` | `registered` | 尚未開始 |
|
||||
| `face_mgmt_ready` | `completed` | 最終狀態統一為 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`
|
||||
|
||||
**回傳格式變更:**
|
||||
|
||||
**修改前:**
|
||||
```json
|
||||
{
|
||||
"status": "face_mgmt_ready",
|
||||
"processors_complete": 5,
|
||||
"processors_total": 5,
|
||||
"worker": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
**修改後:**
|
||||
```json
|
||||
{
|
||||
"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`
|
||||
|
||||
**回傳格式變更:**
|
||||
|
||||
**修改前:**
|
||||
```json
|
||||
{
|
||||
"identity_agent": {
|
||||
"clusters": 0,
|
||||
"identities_created": 0,
|
||||
"tmdb_matches": 0,
|
||||
"speaker_bindings": 0,
|
||||
"confirmations": 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**修改後:**
|
||||
```json
|
||||
{
|
||||
"face_dedup": {
|
||||
"clusters": 5,
|
||||
"face_tracks": 24,
|
||||
"consistent": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Studio 前端需修改項目
|
||||
|
||||
### 5.1 狀態顯示邏輯
|
||||
|
||||
**位置:** Studio 前端檔案列表元件
|
||||
|
||||
**修改前:**
|
||||
```javascript
|
||||
const statusLabels = {
|
||||
'completed': '✅ 已完成',
|
||||
'processing': '🔄 處理中',
|
||||
'pending': '⏳ 待處理',
|
||||
'face_mgmt_ready': '🎭 臉部管理可用',
|
||||
'agent_ready': '🤖 Agent 可用'
|
||||
};
|
||||
```
|
||||
|
||||
**修改後:**
|
||||
```javascript
|
||||
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` |
|
||||
@@ -0,0 +1,373 @@
|
||||
---
|
||||
title: Trace Agent API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: trace_agent -->
|
||||
<!-- description: Face trace and TKG (Temporal Knowledge Graph) operations -->
|
||||
<!-- depends: identity, profile -->
|
||||
|
||||
# Trace Agent API
|
||||
|
||||
Manage face traces, temporal knowledge graphs, and trace-related operations.
|
||||
|
||||
## Overview
|
||||
|
||||
Trace Agent API provides endpoints for:
|
||||
- **Trace Management**: List, query, and analyze face traces
|
||||
- **Face Retrieval**: Get faces from traces, representative faces
|
||||
- **Thumbnails**: Generate and retrieve trace thumbnails
|
||||
- **TKG Operations**: Build, query, and manage Temporal Knowledge Graphs
|
||||
- **Co-occurrence**: Analyze identity co-occurrence in videos
|
||||
|
||||
## Endpoints
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/traces`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
List all traces for a file, sorted by various criteria.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `file_uuid` | string | Yes | — | File UUID (path parameter) |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# List traces for a file
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/traces" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"traces": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"face_count": 50,
|
||||
"first_frame": 100,
|
||||
"last_frame": 1500,
|
||||
"identity_uuid": "a9a90105-..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/trace/:trace_id/faces`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Get all faces for a specific trace.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `trace_id` | number | Yes | Trace ID |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get faces for trace 1
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/trace/1/faces" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/trace/:trace_id/representative-face`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Get the representative (best quality) face for a trace.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get representative face
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/trace/1/representative-face" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/trace/:trace_id/thumbnail`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Get thumbnail for a trace.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get trace thumbnail
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/trace/1/thumbnail" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/stranger/:stranger_id/representative-face`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Get representative face for a stranger (unidentified person).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get stranger representative face
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/stranger/1/representative-face" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/stranger/:stranger_id/thumbnail`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Get thumbnail for a stranger.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get stranger thumbnail
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/stranger/1/thumbnail" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/identities/:identity_uuid_a/co-occur-with/:identity_uuid_b`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Get co-occurrence information between two identities in a file.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
| `identity_uuid_a` | string | Yes | First identity UUID |
|
||||
| `identity_uuid_b` | string | Yes | Second identity UUID |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Check co-occurrence
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/identities/$IDENTITY_UUID_A/co-occur-with/$IDENTITY_UUID_B" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/rebuild`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Rebuild Temporal Knowledge Graph for a file.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Rebuild TKG
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/rebuild" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/tkg`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Get TKG operations for a file.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get TKG operations
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/tkg" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `DELETE /api/v1/file/:file_uuid/tkg`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Delete TKG for a file.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Delete TKG
|
||||
curl -s -X DELETE "$API/api/v1/file/$FILE_UUID/tkg" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/rule2`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Ingest Rule 2 for TKG.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Ingest Rule 2
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/rule2" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/representative-frame`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Get representative frame for a file.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Get representative frame
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/representative-frame" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/nodes`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Query TKG nodes.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Query TKG nodes
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/nodes" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/file/:file_uuid/tkg/edges`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level
|
||||
|
||||
Query TKG edges.
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Query TKG edges
|
||||
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/edges" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Details
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/src/api/trace_agent_api.rs` (2918 lines)
|
||||
|
||||
**Data Structures**:
|
||||
- `Trace` - Face trace object
|
||||
- `Face` - Single face detection
|
||||
- `TKG` - Temporal Knowledge Graph
|
||||
- `Stranger` - Unidentified person
|
||||
|
||||
**Database Tables**:
|
||||
- `face_detections` - Face detection records
|
||||
- `traces` - Trace metadata
|
||||
- `tkg_nodes` - TKG nodes
|
||||
- `tkg_edges` - TKG edges
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Identity API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/07_identity.md)
|
||||
- [Profile API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/18_profile.md)
|
||||
- [TKG API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/15_tkg.md)
|
||||
|
||||
---
|
||||
|
||||
## Common Issues
|
||||
|
||||
### Trace Not Found
|
||||
|
||||
**Symptoms**: 404 error when accessing trace
|
||||
|
||||
**Solution**: Check if trace exists in database or re-process the file
|
||||
|
||||
### TKG Build Failed
|
||||
|
||||
**Symptoms**: TKG rebuild returns error
|
||||
|
||||
**Solution**: Check file processing status and logs
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation (summary) |
|
||||
|
||||
**Note**: This is a summary documentation. Full endpoint details require additional work.
|
||||
@@ -0,0 +1,114 @@
|
||||
# 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/group` | `trace_profiles.name` |
|
||||
| **讀取 (卡片顯示)** | `GET /api/v1/file/:uuid/face-groups` | `tkg_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
|
||||
```sql
|
||||
SELECT label, properties FROM tkg_nodes
|
||||
WHERE file_uuid = $1 AND node_type = 'face_track'
|
||||
ORDER BY (properties->>'trace_id')::int
|
||||
```
|
||||
|
||||
### 改後 SQL
|
||||
```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 程式碼變更
|
||||
```diff
|
||||
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. **建議**:如果 `tkg_nodes.label` 和 `trace_profiles.name` 應該保持一致,可以考慮:
|
||||
- 方案 A(目前做法):讀取端用 `COALESCE` 優先取 `trace_profiles.name`
|
||||
- 方案 B:寫入端同時更新兩個欄位(需要改 `update_trace_profile_group_handler`)
|
||||
3. **`merge_groups_handler`** 目前同時更新 `trace_profiles.name` 和 `tkg_nodes.label`(line 278-310),行為正確,不需要改
|
||||
|
||||
---
|
||||
|
||||
## 驗證
|
||||
|
||||
```bash
|
||||
# 測試 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 }
|
||||
```
|
||||
@@ -0,0 +1,347 @@
|
||||
---
|
||||
title: VLM Search API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: vlm_search -->
|
||||
<!-- description: Vision Language Model search for scenes and traces -->
|
||||
<!-- depends: search, profile -->
|
||||
|
||||
# VLM Search API
|
||||
|
||||
Search video scenes and traces using Vision Language Model (VLM) descriptions and tags.
|
||||
|
||||
## Overview
|
||||
|
||||
VLM Search API provides endpoints for:
|
||||
- **Scene Search**: Search scenes by VLM-generated descriptions and objects
|
||||
- **Trace Search**: Search face traces by VLM descriptions
|
||||
- **Debug Search**: Debug VLM search functionality
|
||||
|
||||
## Endpoints
|
||||
|
||||
### `POST /api/v1/search/vlm/scenes`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level or global
|
||||
|
||||
Search scenes using VLM-generated content and metadata.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `query` | string | Yes | — | Search query text |
|
||||
| `file_uuid` | string | No | — | Limit to specific file |
|
||||
| `filters` | object | No | — | Search filters |
|
||||
| `page` | number | No | 1 | Page number |
|
||||
| `page_size` | number | No | 20 | Results per page |
|
||||
| `min_score` | number | No | 0.0 | Minimum relevance score |
|
||||
|
||||
#### Filters Object
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `vlm_objects` | array | Filter by detected objects |
|
||||
| `vlm_tags` | array | Filter by VLM tags |
|
||||
| `time_range` | object | Filter by time range |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Search scenes for "dog playing"
|
||||
curl -s -X POST "$API/api/v1/search/vlm/scenes" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"query": "dog playing in the park",
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"min_score": 0.5
|
||||
}'
|
||||
```
|
||||
|
||||
```bash
|
||||
# Search scenes with filters
|
||||
curl -s -X POST "$API/api/v1/search/vlm/scenes" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"query": "outdoor scene",
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"filters": {
|
||||
"vlm_objects": ["dog", "tree"],
|
||||
"time_range": {
|
||||
"start_sec": 60.0,
|
||||
"end_sec": 120.0
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"file_name": "video.mp4",
|
||||
"scene_index": 5,
|
||||
"timestamp_sec": 125.5,
|
||||
"frame_number": 3750,
|
||||
"thumbnail_url": "/api/v1/media/384b0ff44aaaa1f1/scene/5/thumbnail",
|
||||
"vlm_description": "A dog playing in a sunny park",
|
||||
"vlm_description_localized": "陽光下的公園裡有隻狗在玩耍",
|
||||
"vlm_objects": ["dog", "grass", "tree", "park"],
|
||||
"vlm_tags": [
|
||||
{"en": "dog", "local": "犬"},
|
||||
{"en": "outdoor", "local": "戶外"},
|
||||
{"en": "sunny", "local": "晴天"}
|
||||
],
|
||||
"score": 0.92,
|
||||
"source": "vlm"
|
||||
}
|
||||
],
|
||||
"total": 15,
|
||||
"page": 1,
|
||||
"page_size": 20
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `results` | array | Search results |
|
||||
| `results[].file_uuid` | string | File UUID |
|
||||
| `results[].file_name` | string | File name |
|
||||
| `results[].scene_index` | number | Scene index |
|
||||
| `results[].timestamp_sec` | number | Scene timestamp |
|
||||
| `results[].frame_number` | number | Frame number |
|
||||
| `results[].thumbnail_url` | string | Thumbnail URL |
|
||||
| `results[].vlm_description` | string | VLM-generated description |
|
||||
| `results[].vlm_description_localized` | string | Localized description (optional) |
|
||||
| `results[].vlm_objects` | array | Detected objects |
|
||||
| `results[].vlm_tags` | array | VLM tags (bilingual) |
|
||||
| `results[].score` | number | Relevance score (0-1) |
|
||||
| `results[].source` | string | Search source (`"vlm"`) |
|
||||
| `total` | number | Total results |
|
||||
| `page` | number | Current page |
|
||||
| `page_size` | number | Page size |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/search/vlm/traces`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: file-level or global
|
||||
|
||||
Search face traces using VLM descriptions.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `query` | string | Yes | — | Search query text |
|
||||
| `file_uuid` | string | No | — | Limit to specific file |
|
||||
| `filters` | object | No | — | Search filters |
|
||||
| `page` | number | No | 1 | Page number |
|
||||
| `page_size` | number | No | 20 | Results per page |
|
||||
| `min_score` | number | No | 0.0 | Minimum relevance score |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Search traces for "person wearing red shirt"
|
||||
curl -s -X POST "$API/api/v1/search/vlm/traces" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"query": "person wearing red shirt",
|
||||
"page": 1,
|
||||
"page_size": 20
|
||||
}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"trace_id": 2,
|
||||
"identity_uuid": "a9a90105-...",
|
||||
"vlm_description": "A person wearing a red t-shirt and blue jeans",
|
||||
"vlm_tags": [
|
||||
{"en": "red shirt", "local": "紅色上衣"},
|
||||
{"en": "blue jeans", "local": "藍色牛仔褲"}
|
||||
],
|
||||
"score": 0.88
|
||||
}
|
||||
],
|
||||
"total": 3,
|
||||
"page": 1,
|
||||
"page_size": 20
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/search/vlm/debug`
|
||||
|
||||
**Auth**: Required
|
||||
|
||||
**Scope**: system-level
|
||||
|
||||
Debug VLM search functionality (for development).
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# Debug VLM search
|
||||
curl -s -X POST "$API/api/v1/search/vlm/debug" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"query": "test query"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Details
|
||||
|
||||
**File**: `/Users/accusys/momentry_core/src/api/vlm_search.rs` (773 lines)
|
||||
|
||||
**Data Structures**:
|
||||
- `SceneSearchRequest` - Scene search parameters
|
||||
- `TraceSearchRequest` - Trace search parameters
|
||||
- `VlmTagValue` - Bilingual tag structure
|
||||
|
||||
**VLM Tags Structure**:
|
||||
```json
|
||||
{
|
||||
"en": "dog",
|
||||
"local": "犬"
|
||||
}
|
||||
```
|
||||
|
||||
**Search Process**:
|
||||
1. Parse query and filters
|
||||
2. Generate embedding for query text
|
||||
3. Search Qdrant for matching scenes/traces
|
||||
4. Apply filters (objects, tags, time range)
|
||||
5. Sort by relevance score
|
||||
6. Return paginated results
|
||||
|
||||
---
|
||||
|
||||
## VLM Integration
|
||||
|
||||
### Description Generation
|
||||
|
||||
VLM descriptions are generated during file processing:
|
||||
- **Scene VLM**: Analyzes scene frames
|
||||
- **Trace VLM**: Analyzes face trace appearances
|
||||
|
||||
### Tag Structure
|
||||
|
||||
Bilingual tags enable multilingual search:
|
||||
- **English tag**: Primary search key
|
||||
- **Local tag**: Native language display
|
||||
|
||||
### Objects vs Tags
|
||||
|
||||
- **Objects**: Detected physical objects (dog, car, tree)
|
||||
- **Tags**: Semantic concepts (outdoor, sunny, daytime)
|
||||
|
||||
---
|
||||
|
||||
## Search Tips
|
||||
|
||||
### Effective Queries
|
||||
|
||||
✅ **Good**:
|
||||
- "dog playing in the park"
|
||||
- "person wearing red shirt"
|
||||
- "outdoor sunny scene"
|
||||
|
||||
❌ **Less Effective**:
|
||||
- "video" (too generic)
|
||||
- "frame 100" (technical reference)
|
||||
|
||||
### Filter Usage
|
||||
|
||||
Use filters to narrow results:
|
||||
- `vlm_objects`: Specific objects
|
||||
- `vlm_tags`: Specific concepts
|
||||
- `time_range`: Specific time period
|
||||
|
||||
### Score Thresholds
|
||||
|
||||
- `> 0.8`: Highly relevant
|
||||
- `0.5-0.8`: Moderately relevant
|
||||
- `< 0.5`: Low relevance
|
||||
|
||||
---
|
||||
|
||||
## Error Codes
|
||||
|
||||
| Code | HTTP | When |
|
||||
|------|------|------|
|
||||
| E401 | 401 | Missing or invalid API key |
|
||||
| E400 | 400 | Invalid query or parameters |
|
||||
| E500 | 500 | Search failed |
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Search API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/06_search.md)
|
||||
- [Profile API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/18_profile.md)
|
||||
- [Scene VLM Stats](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/scene_vlm_stats_api.md)
|
||||
|
||||
---
|
||||
|
||||
## Common Issues
|
||||
|
||||
### No Results Found
|
||||
|
||||
**Symptoms**: Empty results array
|
||||
|
||||
**Possible Causes**:
|
||||
1. Query too specific
|
||||
2. Low `min_score` threshold
|
||||
3. No matching scenes/traces
|
||||
|
||||
**Solution**:
|
||||
- Simplify query
|
||||
- Lower `min_score`
|
||||
- Check file processing status
|
||||
|
||||
### Low Relevance Scores
|
||||
|
||||
**Symptoms**: All results have low scores (< 0.5)
|
||||
|
||||
**Possible Causes**:
|
||||
1. Query doesn't match content
|
||||
2. VLM descriptions not generated
|
||||
3. Embedding quality issue
|
||||
|
||||
**Solution**:
|
||||
- Rephrase query
|
||||
- Verify VLM processing completed
|
||||
- Check VLM model configuration
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,182 @@
|
||||
---
|
||||
title: Pose & Appearance API
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: Core Team
|
||||
status: Active
|
||||
---
|
||||
|
||||
<!-- module: pose_appearance -->
|
||||
<!-- description: Pose skeleton and appearance color endpoints for face detail display -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## Pose & Appearance
|
||||
|
||||
Endpoints for retrieving pose keypoints and appearance color data for face detail modal display.
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/pose`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get pose keypoints for a specific frame. Returns 17 COCO keypoints with deduplication (highest confidence selected for each keypoint name).
|
||||
|
||||
#### Path Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `frame` | integer | Yes | Frame number |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/pose?frame=303" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"frame": 303,
|
||||
"keypoints": [
|
||||
{"name": "nose", "x": 315.91, "y": 364.25, "confidence": 0.616},
|
||||
{"name": "left_eye", "x": 312.45, "y": 362.80, "confidence": 0.616},
|
||||
{"name": "right_eye", "x": 316.21, "y": 361.38, "confidence": 0.616},
|
||||
{"name": "left_ear", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "right_ear", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "left_shoulder", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "right_shoulder", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "left_elbow", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "right_elbow", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "left_wrist", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "right_wrist", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "left_hip", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "right_hip", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "left_knee", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "right_knee", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "left_ankle", "x": 0.0, "y": 0.0, "confidence": 0.0},
|
||||
{"name": "right_ankle", "x": 0.0, "y": 0.0, "confidence": 0.0}
|
||||
],
|
||||
"pose_class": "unknown",
|
||||
"confidence": null
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `frame` | integer | Frame number |
|
||||
| `keypoints` | array | 17 COCO keypoints (deduplicated) |
|
||||
| `keypoints[].name` | string | Keypoint name |
|
||||
| `keypoints[].x` | float | X coordinate in pixels |
|
||||
| `keypoints[].y` | float | Y coordinate in pixels |
|
||||
| `keypoints[].confidence` | float | Detection confidence 0-1 (0 means not detected) |
|
||||
| `pose_class` | string | Always `"unknown"` in POC |
|
||||
| `confidence` | null | Always `null` in POC |
|
||||
|
||||
#### COCO-17 Keypoint Names
|
||||
|
||||
```
|
||||
nose, left_eye, right_eye, left_ear, right_ear,
|
||||
left_shoulder, right_shoulder, left_elbow, right_elbow,
|
||||
left_wrist, right_wrist, left_hip, right_hip,
|
||||
left_knee, right_knee, left_ankle, right_ankle
|
||||
```
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| 404 | Frame not found or pose.json not found |
|
||||
| 401 | Missing or invalid API key |
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/file/:file_uuid/appearance`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Get appearance color data for a specific frame. Returns HSV histogram for color analysis.
|
||||
|
||||
#### Path Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File UUID |
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `frame` | integer | Yes | Frame number |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
curl -s "$API/api/v1/file/$FILE_UUID/appearance?frame=303" \
|
||||
-H "X-API-Key: $KEY"
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{
|
||||
"frame": 303,
|
||||
"dominant_colors": [],
|
||||
"hsv_histogram": [
|
||||
[0.59, 0.0, 0.0, ...],
|
||||
[0.97, 0.02, 0.01, ...],
|
||||
[0.004, 0.02, 0.03, ...]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `frame` | integer | Frame number |
|
||||
| `dominant_colors` | array | Empty array in POC (`[]`) |
|
||||
| `hsv_histogram` | array | 3x30 HSV histogram bins (H, S, V channels) |
|
||||
|
||||
#### Error Responses
|
||||
|
||||
| HTTP | When |
|
||||
|------|------|
|
||||
| 404 | Frame not found or appearance.json not found |
|
||||
| 401 | Missing or invalid API key |
|
||||
|
||||
---
|
||||
|
||||
## Data Source
|
||||
|
||||
| Processor | File | Location |
|
||||
|-----------|------|----------|
|
||||
| Pose | `{file_uuid}.pose.json` | `{OUTPUT_DIR}/` |
|
||||
| Appearance | `{file_uuid}.appearance.json` | `{OUTPUT_DIR}/` |
|
||||
|
||||
---
|
||||
|
||||
## POC Limitations
|
||||
|
||||
| Feature | POC Status | Future |
|
||||
|---------|------------|--------|
|
||||
| Pose classification | `"unknown"` | ML model for standing/sitting/etc. |
|
||||
| Dominant colors | Empty array `[]` | HSV extraction algorithm |
|
||||
| Multiple persons | First person only | Match by trace_id |
|
||||
| Confidence | `null` | Aggregated confidence score |
|
||||
|
||||
---
|
||||
*Updated: 2026-07-19 — New pose and appearance endpoints for face detail display*
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial documentation |
|
||||
@@ -0,0 +1,138 @@
|
||||
# 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
|
||||
```bash
|
||||
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(❌ 仍是舊名)
|
||||
```bash
|
||||
GET /api/v1/trace-profile?file_uuid=...&trace_id=1
|
||||
```
|
||||
回傳:`{"name": "Person_0"}` ← **錯誤,應為 "SusanTest"**
|
||||
|
||||
### 3. 讀取 face groups(✅ 是新名)
|
||||
```bash
|
||||
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):
|
||||
```sql
|
||||
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):
|
||||
```sql
|
||||
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):
|
||||
```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'
|
||||
```
|
||||
使用 `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
|
||||
|
||||
```rust
|
||||
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(¶ms.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-groups` | `COALESCE(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 修復
|
||||
@@ -0,0 +1,750 @@
|
||||
# Face Filter API 使用指南 — Studio 團隊參考
|
||||
|
||||
**版本**: v1.0
|
||||
**日期**: 2026-08-09
|
||||
**狀態**: 已實作
|
||||
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
Face Filter API 提供臉部過濾功能,讓 Studio 前端可以:
|
||||
1. 查詢臉部列表(支持來源過濾)
|
||||
2. 獲取單一臉部過濾報告
|
||||
3. 套用過濾規則
|
||||
4. 獲取過濾統計
|
||||
5. 管理過濾規則
|
||||
|
||||
---
|
||||
|
||||
## API 端點
|
||||
|
||||
### 1. 獲取臉部列表
|
||||
|
||||
**端點**: `GET /api/v1/file/{file_uuid}/faces`
|
||||
|
||||
**功能**: 獲取檔案的臉部列表,支持分頁和來源過濾
|
||||
|
||||
**查詢參數**:
|
||||
```json
|
||||
{
|
||||
"source": "all", // "all" | "apple_vision" | "mediapipe"
|
||||
"page": 1, // 頁碼(從 1 開始)
|
||||
"page_size": 50 // 每頁數量
|
||||
}
|
||||
```
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"faces": [
|
||||
{
|
||||
"face_id": "face_001",
|
||||
"frame": 671,
|
||||
"primary_source": "apple_vision",
|
||||
"primary_confidence": 0.84,
|
||||
"detection_sources": [
|
||||
{"source_type": "apple_vision", "confidence": 0.84},
|
||||
{"source_type": "mediapipe", "confidence": 0.92}
|
||||
],
|
||||
"filter_features": {
|
||||
"face_id": "face_001",
|
||||
"file_uuid": "0489e104d7d1e11e613da01f7aa130ca",
|
||||
"frame": 671,
|
||||
"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 使用範例**:
|
||||
```typescript
|
||||
// 獲取第一頁臉部
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
source: 'all',
|
||||
page: 1,
|
||||
page_size: 50
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log(`Total faces: ${data.data.pagination.total}`);
|
||||
console.log(`First face: ${data.data.faces[0].face_id}`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 獲取單一臉部過濾報告
|
||||
|
||||
**端點**: `GET /api/v1/file/{file_uuid}/face/{face_id}/filter-report`
|
||||
|
||||
**功能**: 獲取單一臉部的詳細過濾報告
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"face_id": "face_001",
|
||||
"frame": 671,
|
||||
"overall_confidence": 0.45,
|
||||
"recommendation": "reject",
|
||||
"rule_results": {
|
||||
"landmark_analysis": {
|
||||
"enabled": true,
|
||||
"score": 0.75,
|
||||
"passed": true,
|
||||
"reason": "nose_ratio too low (0.020)"
|
||||
},
|
||||
"mediapipe_verification": {
|
||||
"enabled": true,
|
||||
"score": 1.0,
|
||||
"passed": true,
|
||||
"reason": null
|
||||
},
|
||||
"embedding_similarity": {
|
||||
"enabled": true,
|
||||
"score": 0.21,
|
||||
"passed": false,
|
||||
"reason": "Low embedding similarity (0.150)"
|
||||
},
|
||||
"temporal_consistency": {
|
||||
"enabled": true,
|
||||
"score": 0.33,
|
||||
"passed": false,
|
||||
"reason": "Single frame detection (1)"
|
||||
}
|
||||
},
|
||||
"reasons": [
|
||||
"nose_ratio too low (0.020)",
|
||||
"Low embedding similarity (0.150)",
|
||||
"Single frame detection (1)"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 獲取臉部過濾報告
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/face/face_001/filter-report');
|
||||
const report = await response.json();
|
||||
|
||||
console.log(`Recommendation: ${report.recommendation}`);
|
||||
console.log(`Confidence: ${report.overall_confidence}`);
|
||||
console.log(`Reasons: ${report.reasons.join(', ')}`);
|
||||
|
||||
// 顯示每個規則的結果
|
||||
Object.entries(report.rule_results).forEach(([rule, result]) => {
|
||||
console.log(`${rule}: ${result.passed ? '✅' : '❌'} (score: ${result.score})`);
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. 套用過濾規則
|
||||
|
||||
**端點**: `POST /api/v1/file/{file_uuid}/faces/filter`
|
||||
|
||||
**功能**: 套用過濾規則到所有臉部,返回過濾結果
|
||||
|
||||
**請求範例**:
|
||||
```json
|
||||
{
|
||||
"rules": {
|
||||
"version": "1.0",
|
||||
"rules": {
|
||||
"landmark_analysis": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"eye_ratio_min": 0.25,
|
||||
"eye_ratio_max": 0.55,
|
||||
"nose_ratio_min": 0.08,
|
||||
"pose_score_max": 0.8
|
||||
}
|
||||
},
|
||||
"mediapipe_verification": {
|
||||
"enabled": true,
|
||||
"weight": 0.2,
|
||||
"thresholds": {
|
||||
"min_iou": 0.3
|
||||
}
|
||||
},
|
||||
"embedding_similarity": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"min_similarity": 0.70
|
||||
}
|
||||
},
|
||||
"temporal_consistency": {
|
||||
"enabled": true,
|
||||
"weight": 0.2,
|
||||
"thresholds": {
|
||||
"min_consecutive_frames": 3
|
||||
}
|
||||
}
|
||||
},
|
||||
"overall_thresholds": {
|
||||
"auto_accept": 0.7,
|
||||
"auto_reject": 0.3,
|
||||
"review_range": [0.3, 0.7]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"total_faces": 392,
|
||||
"passed": 385,
|
||||
"filtered": 7,
|
||||
"filtered_faces": [
|
||||
{
|
||||
"face_id": "face_001",
|
||||
"frame": 671,
|
||||
"reasons": [
|
||||
"nose_ratio too low (0.020)",
|
||||
"Low embedding similarity (0.150)",
|
||||
"Single frame detection (1)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"filter_stats": {
|
||||
"landmark": 3,
|
||||
"mediapipe": 1,
|
||||
"embedding": 2,
|
||||
"temporal": 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 套用過濾規則
|
||||
const filterConfig = {
|
||||
rules: {
|
||||
landmark_analysis: {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: {
|
||||
eye_ratio_min: 0.25,
|
||||
eye_ratio_max: 0.55,
|
||||
nose_ratio_min: 0.08,
|
||||
pose_score_max: 0.8
|
||||
}
|
||||
},
|
||||
// ... 其他規則
|
||||
},
|
||||
overall_thresholds: {
|
||||
auto_accept: 0.7,
|
||||
auto_reject: 0.3,
|
||||
review_range: [0.3, 0.7]
|
||||
}
|
||||
};
|
||||
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ rules: filterConfig })
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
console.log(`Passed: ${result.passed}, Filtered: ${result.filtered}`);
|
||||
|
||||
// 顯示被過濾的臉部
|
||||
result.filtered_faces.forEach(face => {
|
||||
console.log(`Face ${face.face_id} (frame ${face.frame}): ${face.reasons.join(', ')}`);
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 獲取過濾統計
|
||||
|
||||
**端點**: `GET /api/v1/file/{file_uuid}/filter-stats`
|
||||
|
||||
**功能**: 獲取臉部的過濾統計資訊
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"total_faces": 392,
|
||||
"by_category": {
|
||||
"total_faces": 392,
|
||||
"by_source": {
|
||||
"apple_vision": 392,
|
||||
"mediapipe": 5
|
||||
},
|
||||
"by_quality": {
|
||||
"avg_eye_ratio": 0.37,
|
||||
"avg_nose_ratio": 0.12,
|
||||
"avg_pose_score": 0.15,
|
||||
"mediapipe_verified": 5,
|
||||
"avg_embedding_similarity": 0.78,
|
||||
"avg_consecutive_frames": 12.5
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 獲取過濾統計
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-stats');
|
||||
const stats = await response.json();
|
||||
|
||||
console.log(`Total faces: ${stats.total_faces}`);
|
||||
console.log(`Apple Vision faces: ${stats.by_category.by_source.apple_vision}`);
|
||||
console.log(`MediaPipe faces: ${stats.by_category.by_source.mediapipe}`);
|
||||
console.log(`Avg embedding similarity: ${stats.by_category.by_quality.avg_embedding_similarity}`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 管理過濾規則
|
||||
|
||||
#### 5.1 獲取過濾規則
|
||||
|
||||
**端點**: `GET /api/v1/file/{file_uuid}/filter-rules`
|
||||
|
||||
**回應範例**:
|
||||
```json
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"id": 1,
|
||||
"rule_name": "default_filter",
|
||||
"rules": {
|
||||
"version": "1.0",
|
||||
"rules": {
|
||||
"landmark_analysis": { ... },
|
||||
"mediapipe_verification": { ... },
|
||||
"embedding_similarity": { ... },
|
||||
"temporal_consistency": { ... }
|
||||
},
|
||||
"overall_thresholds": { ... }
|
||||
},
|
||||
"is_active": true,
|
||||
"created_at": "2026-08-09T12:00:00Z",
|
||||
"updated_at": "2026-08-09T12:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 5.2 儲存過濾規則
|
||||
|
||||
**端點**: `POST /api/v1/file/{file_uuid}/filter-rules`
|
||||
|
||||
**請求範例**:
|
||||
```json
|
||||
{
|
||||
"rule_name": "strict_filter",
|
||||
"rules": {
|
||||
"version": "1.0",
|
||||
"rules": {
|
||||
"landmark_analysis": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"eye_ratio_min": 0.30,
|
||||
"eye_ratio_max": 0.50,
|
||||
"nose_ratio_min": 0.10,
|
||||
"pose_score_max": 0.5
|
||||
}
|
||||
},
|
||||
// ... 其他規則
|
||||
},
|
||||
"overall_thresholds": {
|
||||
"auto_accept": 0.8,
|
||||
"auto_reject": 0.2,
|
||||
"review_range": [0.2, 0.8]
|
||||
}
|
||||
},
|
||||
"is_active": true
|
||||
}
|
||||
```
|
||||
|
||||
**Studio 使用範例**:
|
||||
```typescript
|
||||
// 獲取現有規則
|
||||
const getResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules');
|
||||
const rulesData = await getResponse.json();
|
||||
|
||||
// 儲存新規則
|
||||
const strictFilter = {
|
||||
rule_name: "strict_filter",
|
||||
rules: {
|
||||
// ... 規則配置
|
||||
},
|
||||
is_active: true
|
||||
};
|
||||
|
||||
const saveResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(strictFilter)
|
||||
});
|
||||
|
||||
const savedRule = await saveResponse.json();
|
||||
console.log(`Saved rule: ${savedRule.rule_name} (id: ${savedRule.id})`);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 過濾規則說明
|
||||
|
||||
### 規則類型
|
||||
|
||||
#### 1. Landmark 分析 (landmark_analysis)
|
||||
|
||||
**功能**: 檢查臉部 landmark 幾何特徵是否正常
|
||||
|
||||
**閾值**:
|
||||
- `eye_ratio_min`: 眼睛間距比例最小值(預設 0.25)
|
||||
- `eye_ratio_max`: 眼睛間距比例最大值(預設 0.55)
|
||||
- `nose_ratio_min`: 眼睛到鼻子比例最小值(預設 0.08)
|
||||
- `pose_score_max`: Pose 角度評分最大值(預設 0.8)
|
||||
|
||||
**權重**: 0.3
|
||||
|
||||
---
|
||||
|
||||
#### 2. MediaPipe 驗證 (mediapipe_verification)
|
||||
|
||||
**功能**: 驗證 MediaPipe 是否也檢測到該臉部
|
||||
|
||||
**值**:
|
||||
- `min_iou`: 最小 IoU 值(預設 0.3)
|
||||
|
||||
**權重**: 0.2
|
||||
|
||||
---
|
||||
|
||||
#### 3. Embedding 相似度 (embedding_similarity)
|
||||
|
||||
**功能**: 檢查臉部 embedding 與已知人臉的相似度
|
||||
|
||||
**閾值**:
|
||||
- `min_similarity`: 最小相似度(預設 0.70)
|
||||
|
||||
**權重**: 0.3
|
||||
|
||||
---
|
||||
|
||||
#### 4. 時間一致性 (temporal_consistency)
|
||||
|
||||
**功能**: 檢查臉部是否在連續幀中出現
|
||||
|
||||
**閾值**:
|
||||
- `min_consecutive_frames`: 最小連續數(預設 3)
|
||||
|
||||
**權重**: 0.2
|
||||
|
||||
---
|
||||
|
||||
### 總體閾值
|
||||
|
||||
**overall_thresholds**:
|
||||
- `auto_accept`: 自動接受閾值(預設 0.7)
|
||||
- `auto_reject`: 自動拒絕閾值(預設 0.3)
|
||||
- `review_range`: 審查範圍(預設 [0.3, 0.7])
|
||||
|
||||
**建議**:
|
||||
- `overall_confidence >= 0.7`: 接受
|
||||
- `overall_confidence <= 0.3`: 拒絕
|
||||
- `0.3 < overall_confidence < 0.7`: 審查
|
||||
|
||||
---
|
||||
|
||||
### Bbox Size 說明
|
||||
|
||||
**欄位**: `bbox_size`
|
||||
|
||||
**計算方式**: `min(width, height)`
|
||||
|
||||
**說明**:
|
||||
- 預先計算並儲存於後端
|
||||
- 用於前端即時過濾
|
||||
- 維持當前 Swift 實作的計算方式
|
||||
|
||||
**前端過濾範例**:
|
||||
```typescript
|
||||
// 前端即時過濾
|
||||
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 提供預設過濾規則,可直接使用:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"rules": {
|
||||
"landmark_analysis": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"eye_ratio_min": 0.25,
|
||||
"eye_ratio_max": 0.55,
|
||||
"nose_ratio_min": 0.08,
|
||||
"pose_score_max": 0.8
|
||||
}
|
||||
},
|
||||
"mediapipe_verification": {
|
||||
"enabled": true,
|
||||
"weight": 0.2,
|
||||
"thresholds": {
|
||||
"min_iou": 0.3
|
||||
}
|
||||
},
|
||||
"embedding_similarity": {
|
||||
"enabled": true,
|
||||
"weight": 0.3,
|
||||
"thresholds": {
|
||||
"min_similarity": 0.70
|
||||
}
|
||||
},
|
||||
"temporal_consistency": {
|
||||
"enabled": true,
|
||||
"weight": 0.2,
|
||||
"thresholds": {
|
||||
"min_consecutive_frames": 3
|
||||
}
|
||||
}
|
||||
},
|
||||
"overall_thresholds": {
|
||||
"auto_accept": 0.7,
|
||||
"auto_reject": 0.3,
|
||||
"review_range": [0.3, 0.7]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 完整使用範例
|
||||
|
||||
### 場景 1: 過濾低品質臉部
|
||||
|
||||
```typescript
|
||||
// 1. 獲取臉部列表
|
||||
const facesResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source: 'all', page: 1, page_size: 100 })
|
||||
});
|
||||
const facesData = await facesResponse.json();
|
||||
|
||||
// 2. 套用過濾規則
|
||||
const filterResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ rules: null }) // 使用預設規則
|
||||
});
|
||||
const filterResult = await filterResponse.json();
|
||||
|
||||
console.log(`Total: ${filterResult.total_faces}`);
|
||||
console.log(`Passed: ${filterResult.passed}`);
|
||||
console.log(`Filtered: ${filterResult.filtered}`);
|
||||
|
||||
// 3. 顯示被過濾的臉部
|
||||
filterResult.filtered_faces.forEach(face => {
|
||||
console.log(`❌ Face ${face.face_id} (frame ${face.frame})`);
|
||||
face.reasons.forEach(reason => {
|
||||
console.log(` - ${reason}`);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### 場景 2: 自訂嚴格過濾
|
||||
|
||||
```typescript
|
||||
// 自訂嚴格過濾規則
|
||||
const strictRules = {
|
||||
version: "1.0",
|
||||
rules: {
|
||||
landmark_analysis: {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: {
|
||||
eye_ratio_min: 0.30, // 更嚴格
|
||||
eye_ratio_max: 0.50, // 更嚴格
|
||||
nose_ratio_min: 0.10, // 更嚴格
|
||||
pose_score_max: 0.5 // 更嚴格
|
||||
}
|
||||
},
|
||||
mediapipe_verification: {
|
||||
enabled: true,
|
||||
weight: 0.2,
|
||||
thresholds: {
|
||||
min_iou: 0.5 // 更嚴格
|
||||
}
|
||||
},
|
||||
embedding_similarity: {
|
||||
enabled: true,
|
||||
weight: 0.3,
|
||||
thresholds: {
|
||||
min_similarity: 0.80 // 更嚴格
|
||||
}
|
||||
},
|
||||
temporal_consistency: {
|
||||
enabled: true,
|
||||
weight: 0.2,
|
||||
thresholds: {
|
||||
min_consecutive_frames: 5 // 更嚴格
|
||||
}
|
||||
}
|
||||
},
|
||||
overall_thresholds: {
|
||||
auto_accept: 0.8, // 更嚴格
|
||||
auto_reject: 0.2, // 更嚴格
|
||||
review_range: [0.2, 0.8]
|
||||
}
|
||||
};
|
||||
|
||||
// 儲存規則
|
||||
await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
rule_name: "strict_filter",
|
||||
rules: strictRules,
|
||||
is_active: true
|
||||
})
|
||||
});
|
||||
|
||||
// 套用嚴格規則
|
||||
const result = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/faces/filter', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ rules: strictRules })
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 錯誤處理
|
||||
|
||||
### 常見錯誤
|
||||
|
||||
**404 Not Found**:
|
||||
```json
|
||||
{
|
||||
"error": "Face not found"
|
||||
}
|
||||
```
|
||||
**原因**: 臉部 ID 不存在
|
||||
|
||||
**500 Internal Server Error**:
|
||||
```json
|
||||
{
|
||||
"error": "Database error"
|
||||
}
|
||||
```
|
||||
**原因**: 資料庫查詢失敗
|
||||
|
||||
### 錯誤處理範例
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/face/face_999/filter-report');
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
console.error('Face not found');
|
||||
} else {
|
||||
console.error('Server error');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const report = await response.json();
|
||||
console.log(report);
|
||||
} catch (error) {
|
||||
console.error('Request failed:', error);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 最佳實踐
|
||||
|
||||
### 1. 使用預設規則開始
|
||||
|
||||
建議先使用預設規則,再根據實際需求調整。
|
||||
|
||||
### 2. 逐步調整閾值
|
||||
|
||||
不要一次性調整所有值,逐步調整並觀察結果。
|
||||
|
||||
### 3. 監控過濾統計
|
||||
|
||||
定期檢查過濾統計,確保過濾規則合理。
|
||||
|
||||
### 4. 保存多個規則配置
|
||||
|
||||
為不同場景保存不同的規則配置(如:嚴格、平衡、寬鬆)。
|
||||
|
||||
### 5. 使用者自訂
|
||||
|
||||
允許使用者自訂過濾規則,提供預設模板。
|
||||
|
||||
---
|
||||
|
||||
## 支援與反饋
|
||||
|
||||
如有問題或建議,請聯繫 Core Team。
|
||||
|
||||
**文件版本**: v1.0
|
||||
**最後更新**: 2026-08-09
|
||||
@@ -0,0 +1,114 @@
|
||||
# Trace Thumbnail Regenerate API 使用指南 — Studio 團隊參考
|
||||
|
||||
**版本**: v1.0
|
||||
**日期**: 2026-08-12
|
||||
**狀態**: 已實作(Core)
|
||||
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
修復「key_frame 正常、key_face bbox 正常、但 key_face 縮圖異常」之現象。
|
||||
|
||||
**根因**: bbox 部分越過 frame 邊界(如 trace 355b 案例)時,crop 未 clamp 到 frame 尺寸,ffmpeg 靜默 clamp/位移,導致縮圖內容錯位。由於縮圖端點優先回傳 `key_face.jpg` cache,異常內容被持久化顯示。
|
||||
|
||||
**修復**: 本端點重新選取該 trace 之 best-confidence face,將 bbox clamp 至影片尺寸後重新裁切,覆寫 `key_face.jpg`,並同步更新 `.faces` cache。
|
||||
|
||||
---
|
||||
|
||||
## API 端點
|
||||
|
||||
### POST `/api/v1/file/{file_uuid}/trace/{trace_id}/regenerate-thumbnail`
|
||||
|
||||
**功能**: 重新產生單一 trace 的 face thumbnail(覆寫 cache)
|
||||
**Auth**: Required
|
||||
**Body**: 可為空。
|
||||
|
||||
**Response 200**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "...",
|
||||
"trace_id": 355,
|
||||
"frame": 1835,
|
||||
"bbox": { "x": 65, "y": 301, "width": 70, "height": 59 }
|
||||
}
|
||||
```
|
||||
- `frame` / `bbox` 為重新裁切使用的(clamp 後)frame 與 bbox。
|
||||
|
||||
**Error Responses**:
|
||||
| Status | 說明 |
|
||||
|--------|------|
|
||||
| 404 | Video not found(該 file_uuid 無影片)或 No face found for this trace(該 trace 無 face 資料) |
|
||||
| 400 | Video width/height unavailable — 影片未記錄尺寸,無法 clamp,拒絕重切 |
|
||||
|
||||
---
|
||||
|
||||
## 行為說明
|
||||
|
||||
1. 讀取該 trace 最高 confidence 的 frame + bbox(**不**重跑 blur 優化,取既有 best face 復原同一區域)
|
||||
2. 將 bbox clamp 到影片 width/height 內(`clamp_crop`)
|
||||
3. ffmpeg 自影片以 decoded frame index 切出該 frame → crop face 區域
|
||||
4. 覆寫 `{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}/key_face.jpg`
|
||||
5. 若 `.faces/{file_uuid}/{trace_id}/{frame}.jpg` 已存在則同步覆寫
|
||||
|
||||
**不影響**: Qdrant、`trace_profiles` DB、`tkg_nodes`、影片檔 — 僅重寫縮圖 cache。
|
||||
|
||||
---
|
||||
|
||||
## Studio 整合步驟
|
||||
|
||||
### 1. apiCall (`src/api/index.ts`)
|
||||
|
||||
新增 case:
|
||||
```ts
|
||||
case 'regenerate_trace_thumbnail': {
|
||||
return { url: `/api/v1/file/${a.fileUuid}/trace/${a.traceId}/regenerate-thumbnail`, method: 'POST' }
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Face detail modal 加「Re-gen」按鈕 (`src/views/PeopleView.vue`)
|
||||
|
||||
於 `ms-face-detail-thumb` 附近加入按鈕,呼叫上方 apiCall,in-flight 時 disabled。
|
||||
|
||||
### 3. 觸發後 refresh(重要)
|
||||
|
||||
Face detail 縮圖顯示的是 `faceThumbsCache`(key = `${file_uuid}-${trace_id}`)。`loadTraceThumb` 對已有 cache 的 key 會直接 return,**單獨 `bumpThumbCacheBust()` 無法刷新 face detail 縮圖**。正確順序:
|
||||
|
||||
```ts
|
||||
await apiCall('regenerate_trace_thumbnail', { fileUuid, traceId }) // 1. 呼叫 regenerate
|
||||
delete faceThumbsCache.value[`${fileUuid}-${traceId}`] // 2. 清除該 key 的 blob cache
|
||||
bumpThumbCacheBust() // 3. bump 版本(避 HTTP cache)
|
||||
loadTraceThumb({ file_uuid: fileUuid, trace_id: traceId }) // 4. 重新載入縮圖
|
||||
```
|
||||
|
||||
> `candidateThumbs` 即 `faceThumbsCache` 的 alias(PeopleView.vue:722),delete 後無需額外處理。
|
||||
> 若想一次清空全部縮圖可用 `clearFaceThumbs()`(較重,不建議單一 trace 場景)。
|
||||
|
||||
---
|
||||
|
||||
## 測試指示
|
||||
|
||||
```bash
|
||||
# 使用已知越界案例(trace 355b 一類)驗證:
|
||||
# 1) regenerate 前:GET thumbnail 顯示位移內容
|
||||
# 2) 呼叫 regenerate → 回 success,含 clamp 後 bbox
|
||||
# 3) 再次 GET thumbnail → 內容正確對齊 bbox
|
||||
curl -X POST "http://localhost:3002/api/v1/file/<FILE_UUID>/trace/<TRACE_ID>/regenerate-thumbnail" \
|
||||
-H "X-API-Key: <KEY>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 參考
|
||||
|
||||
- 根因 crop 修正:`src/core/thumbnail/validator.rs::clamp_crop`、`src/core/processor/tkg.rs`
|
||||
- 端點 handler:`src/api/trace_agent_api.rs::regenerate_trace_thumbnail`
|
||||
|
||||
---
|
||||
|
||||
## 版本歷史
|
||||
|
||||
| 版本 | 日期 | 變更 |
|
||||
|------|------|------|
|
||||
| v1.0 | 2026-08-12 | 初版 |
|
||||
@@ -0,0 +1,188 @@
|
||||
<!-- module: incomplete -->
|
||||
<!-- description: Incomplete, stub, or undocumented API endpoints — tracking list -->
|
||||
<!-- depends: 01_auth -->
|
||||
|
||||
## Incomplete / Undocumented APIs
|
||||
|
||||
This module tracks API endpoints that exist in the codebase but are either undocumented, partially documented, or stubs.
|
||||
|
||||
> **Note**: Endpoints listed here should be fully documented and moved to their appropriate module once implemented.
|
||||
|
||||
---
|
||||
|
||||
## Identity Binding
|
||||
|
||||
### `POST /api/v1/identity/:identity_uuid/bind`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: identity-level
|
||||
|
||||
Bind a single face detection to an identity. Unlike `bind/trace` which binds all faces in a trace, this binds one specific face.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuid` | string | Yes | File containing the face |
|
||||
| `face_id` | string | Yes | Face detection ID to bind |
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Undocumented** — exists in code but no full request/response documentation.
|
||||
|
||||
---
|
||||
|
||||
## Resource Management
|
||||
|
||||
### `POST /api/v1/resource/register`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Register an external resource (e.g., storage backend, API service).
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Undocumented** — endpoint exists but no documentation.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/resource/heartbeat`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Send heartbeat for a registered resource to verify it's still alive.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Undocumented** — endpoint exists but no documentation.
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/resources`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
List all registered resources with their status.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Undocumented** — endpoint exists but no documentation.
|
||||
|
||||
---
|
||||
|
||||
## 5W1H Agent
|
||||
|
||||
### `POST /api/v1/agents/5w1h/analyze`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Run 5W1H analysis on all cut scenes for a file. Uses LLM (Gemma4) to summarize each scene with who/what/where/when/why/how.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — listed in `12_agent.md` but missing full request/response examples.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/agents/5w1h/batch`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Run 5W1H analysis on multiple files at once.
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `file_uuids` | string[] | Yes | Array of file UUIDs to analyze |
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — listed in `12_agent.md` but missing full request/response examples.
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/agents/5w1h/status`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Get 5W1H analysis status across all videos (which files have been analyzed, which are pending).
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — listed in `12_agent.md` but missing full response schema.
|
||||
|
||||
---
|
||||
|
||||
## Identity Agent
|
||||
|
||||
### `POST /api/v1/agents/identity/match-from-photo`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: system-level
|
||||
|
||||
Match an identity using an uploaded photo. Extracts face embedding, finds best trace match.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — exists in `08_identity_agent.md` but missing full response schema and error cases.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/agents/identity/match-from-trace`
|
||||
|
||||
**Auth**: Required
|
||||
**Scope**: file-level
|
||||
|
||||
Match an identity using a trace. Multi-angle embedding comparison with propagation.
|
||||
|
||||
#### Status
|
||||
|
||||
⚠️ **Partially documented** — exists in `08_identity_agent.md` but missing full response schema and error cases.
|
||||
|
||||
---
|
||||
|
||||
## Stubs / Not Implemented
|
||||
|
||||
### Visual Search Endpoints
|
||||
|
||||
| Method | Endpoint | Status |
|
||||
|--------|----------|--------|
|
||||
| POST | `/api/v1/search/visual` | Stub — defined but not functional |
|
||||
| POST | `/api/v1/search/visual/class` | Stub — defined but not functional |
|
||||
| POST | `/api/v1/search/visual/density` | Stub — defined but not functional |
|
||||
| POST | `/api/v1/search/visual/combination` | Stub — defined but not functional |
|
||||
| POST | `/api/v1/search/visual/stats` | Stub — defined but not functional |
|
||||
|
||||
### Unmounted Routes
|
||||
|
||||
These endpoints are defined in source code but not mounted in the router:
|
||||
|
||||
| Endpoint | Notes |
|
||||
|----------|-------|
|
||||
| `/api/v1/search/people` | ✅ Mounted |
|
||||
| `/api/v1/who` | Defined but not mounted |
|
||||
| `/api/v1/who/candidates` | Defined but not mounted |
|
||||
|
||||
---
|
||||
|
||||
## Tracking
|
||||
|
||||
| Count | Status |
|
||||
|-------|--------|
|
||||
| Undocumented | 3 (resource management) |
|
||||
| Partially documented | 5 (5W1H ×3, identity agent ×2) |
|
||||
| Stub/not functional | 5 (visual search) |
|
||||
| Defined but unmounted | 2 (who, who/candidates) |
|
||||
| **Total** | **16** |
|
||||
|
||||
---
|
||||
|
||||
*Created: 2026-06-20 — Gap analysis from core API vs doc_wasm sync*
|
||||
*Updated: 2026-06-20 — Initial tracking list*
|
||||
@@ -0,0 +1,63 @@
|
||||
# {Module Name} — API Workspace Module
|
||||
|
||||
> Use this template when adding or editing API endpoint documentation modules.
|
||||
|
||||
## Module Metadata
|
||||
|
||||
Every module MUST start with:
|
||||
|
||||
```markdown
|
||||
<!-- module: <short_name> -->
|
||||
<!-- description: One-line description of what this module covers -->
|
||||
<!-- depends: <comma-separated list of dependency module names> -->
|
||||
```
|
||||
|
||||
## Endpoint Template
|
||||
|
||||
Each endpoint MUST use this structure:
|
||||
|
||||
### `METHOD /path/to/endpoint`
|
||||
|
||||
**Auth**: Required / Optional / Public
|
||||
|
||||
**Scope**: file-level / identity-level / system-level
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `param1` | string | Yes | — | Description |
|
||||
|
||||
#### Example
|
||||
|
||||
```bash
|
||||
# brief description of what this example demonstrates
|
||||
curl -s -X METHOD "$API/path" \
|
||||
-H "X-API-Key: $KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"param1": "value"}'
|
||||
```
|
||||
|
||||
#### Response (200)
|
||||
|
||||
```json
|
||||
{ "success": true }
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `success` | boolean | Always true on 200 |
|
||||
|
||||
#### Error Codes
|
||||
|
||||
| Code | HTTP | When |
|
||||
|------|------|------|
|
||||
| E0xx | 4xx | Description |
|
||||
|
||||
## Rules
|
||||
|
||||
1. Each module file covers ONE topic group (e.g., `09_tmdb.md` = all TMDb endpoints)
|
||||
2. Use `$API` and `$KEY` in all curl examples
|
||||
3. Use `$FILE_UUID`, `$IDENTITY_UUID` variables for UUID examples
|
||||
4. Module filename = `NN_topic.md` (NN = execution order, 01-99)
|
||||
5. `depends` metadata = which modules must be assembled before this one
|
||||
@@ -0,0 +1,218 @@
|
||||
---
|
||||
title: Scene VLM Stats API
|
||||
version: 1.0.0
|
||||
date: 2026-10-14
|
||||
author: Core Team
|
||||
status: active
|
||||
---
|
||||
|
||||
# Scene VLM Stats API
|
||||
|
||||
**Endpoint**: `/api/v1/file/{file_uuid}/scene-vlm-stats`
|
||||
**Method**: `GET`
|
||||
**Purpose**: 快速获取文件的 Scene VLM 统计数据
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
**Scope**: File processing statistics
|
||||
**Status**: Active
|
||||
**Applicable to**: All registered files with Scene VLM processing
|
||||
|
||||
---
|
||||
|
||||
## Request
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Location | Required | Description |
|
||||
|-----------|------|----------|----------|-------------|
|
||||
| `file_uuid` | String | Path | Yes | File UUID |
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl http://localhost:3002/api/v1/file/dac75694ee550ff57d74f26391fcc751/scene-vlm-stats
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Response
|
||||
|
||||
### Success (200 OK)
|
||||
|
||||
```json
|
||||
{
|
||||
"total_scenes": 2,
|
||||
"status": "completed",
|
||||
"vlm_done": 2,
|
||||
"vlm_total": 2
|
||||
}
|
||||
```
|
||||
|
||||
### Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `total_scenes` | i64 | Total number of scenes detected |
|
||||
| `status` | String | Scene VLM processing status (`pending`, `processing`, `completed`) |
|
||||
| `vlm_done` | i64 | Number of scenes with VLM descriptions completed |
|
||||
| `vlm_total` | i64 | Total scenes needing VLM processing |
|
||||
|
||||
### Default Response
|
||||
|
||||
If the file has no scenes file:
|
||||
|
||||
```json
|
||||
{
|
||||
"total_scenes": 0,
|
||||
"status": "",
|
||||
"vlm_done": 0,
|
||||
"vlm_total": 0
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance
|
||||
|
||||
**Response Time**: < 10ms
|
||||
|
||||
**Why Fast**:
|
||||
- Directly reads `{file_uuid}.scenes.json`
|
||||
- No database queries
|
||||
- No complex calculations
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
### 1. UI Display
|
||||
|
||||
Display Scene VLM progress in Library view:
|
||||
```typescript
|
||||
const stats = await loadSceneVlmStats(fileUuid)
|
||||
console.log(`${stats.vlm_done}/${stats.vlm_total} scenes completed`)
|
||||
```
|
||||
|
||||
### 2. Performance Optimization
|
||||
|
||||
Replace expensive `get_file_stats` call:
|
||||
- **Old**: `get_file_stats` - 100-500ms
|
||||
- **New**: `scene-vlm-stats` - < 10ms
|
||||
- **Improvement**: 10-50x faster
|
||||
|
||||
### 3. Real-time Updates
|
||||
|
||||
Poll for Scene VLM progress without heavy API load:
|
||||
```typescript
|
||||
setInterval(() => {
|
||||
loadSceneVlmStats(fileUuid)
|
||||
}, 5000)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Backend
|
||||
|
||||
**File**: `src/api/scan.rs:1647`
|
||||
|
||||
**Logic**:
|
||||
1. Check if `{file_uuid}.scenes.json` exists
|
||||
2. Read JSON file
|
||||
3. Parse and count scenes
|
||||
4. Return statistics
|
||||
|
||||
**Code**:
|
||||
```rust
|
||||
async fn get_scene_vlm_stats(
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Result<Json<SceneVlmStats>, StatusCode> {
|
||||
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
|
||||
|
||||
if !Path::new(&scenes_path).exists() {
|
||||
return Ok(Json(SceneVlmStats::default()));
|
||||
}
|
||||
|
||||
let scenes_json = std::fs::read_to_string(&scenes_path)?;
|
||||
let scenes_data: Value = serde_json::from_str(&scenes_json)?;
|
||||
|
||||
// ... parse and return stats
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
### File Not Found
|
||||
|
||||
**Status**: 200 OK
|
||||
**Response**: Default values (all zeros)
|
||||
|
||||
### Parse Error
|
||||
|
||||
**Status**: 500 Internal Server Error
|
||||
|
||||
**Note**: Rare case, indicates corrupted JSON file
|
||||
|
||||
---
|
||||
|
||||
## Related APIs
|
||||
|
||||
- `GET /api/v1/file/{file_uuid}` - Full file info (slower)
|
||||
- `GET /api/v1/file/{file_uuid}/processor-counts` - Processor counts
|
||||
- `GET /api/v1/stats/file/{file_uuid}` - Detailed stats (slower)
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Use for Scene VLM Progress
|
||||
|
||||
**Recommended**: Use this API for Scene VLM progress display
|
||||
**Avoid**: Using `get_file_stats` for simple Scene VLM stats
|
||||
|
||||
### 2. Caching
|
||||
|
||||
Frontend should cache results:
|
||||
```typescript
|
||||
if (fileStatsCache.value[fileUuid].scene_vlm) {
|
||||
return fileStatsCache.value[fileUuid].scene_vlm
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Error Handling
|
||||
|
||||
Always handle failures gracefully:
|
||||
```typescript
|
||||
try {
|
||||
const stats = await loadSceneVlmStats(fileUuid)
|
||||
} catch (e) {
|
||||
console.warn('Scene VLM stats failed:', e)
|
||||
// Use cached data or show 'Unknown'
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0.0 | 2026-10-14 | Initial API endpoint |
|
||||
|
||||
---
|
||||
|
||||
## Cross-References
|
||||
|
||||
- **Frontend Integration**: Studio team commit 3e7eba0
|
||||
- **Test Script**: `momentry_studio/scripts/test_scene_vlm_api.sh`
|
||||
- **Backend Code**: `src/api/scan.rs:1647`
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2026-10-14
|
||||
Reference in New Issue
Block a user