feat: Face JSON v2 schema - add schema_version, bbox x2/y2/center, keep embeddings, update clustering

This commit is contained in:
Accusys
2026-11-02 14:34:02 +08:00
parent 2fca49b120
commit 5d18183d82
566 changed files with 321788 additions and 1662 deletions
@@ -1,3 +1,13 @@
---
title: people api API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
# People API
**Version**: 2.1
@@ -10,7 +20,17 @@
## 資料架構
### trace_profiles(PostgreSQL — People Search 專用)
### ⚠️ People Search 核心機制
**People Search 使用 TEXT 名稱匹配,不使用向量搜尋。**
- 資料來源: `face_cluster.json` 的 `group_name`
- 儲存位置: SQLite `trace_profiles` 表
- 匹配方式: PostgreSQL/SQLite `ILIKE` 模糊匹配
- **Identity 欄位目前為佔位用途,暫無實際搜尋功能**
- **Face 512D 向量僅供 `rust_face_cluster` 工具使用,不參與任何搜尋**
### trace_profiles(SQLite/PostgreSQL — People Search 專用)
每筆 `file_uuid + trace_id` 對應一個 face trace profile:
@@ -398,3 +418,11 @@ registered → scanning → keyword_ready → semantic_ready
| `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 |
@@ -1,3 +1,13 @@
---
title: Auth API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: auth -->
<!-- description: Authentication — login, logout, JWT, session cookie, API key -->
<!-- depends: -->
@@ -281,3 +291,11 @@ Protected Request
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: health API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: health -->
<!-- description: Health check endpoints -->
<!-- depends: 01_auth -->
@@ -188,3 +198,11 @@ curl -s "$API/health/consistency" -H "X-API-Key: $KEY" | jq '.checks[] | {check,
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: register API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: register -->
<!-- description: File registration — register, scan -->
<!-- depends: 01_auth -->
@@ -186,3 +196,11 @@ curl -s "$API/api/v1/files/scan?sort_by=status&page_size=5" -H "X-API-Key: $KEY"
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: lookup API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 -->
@@ -418,3 +428,11 @@ curl -s -X POST "$API/api/v1/unregister" \
---
*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 |
@@ -1,3 +1,13 @@
---
title: process API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: process -->
<!-- description: Processing pipeline — trigger, probe, progress, jobs -->
<!-- depends: 01_auth, 03_register -->
@@ -38,22 +48,18 @@ curl -s -X POST "$API/api/v1/file/$FILE_UUID/process" \
```json
{
"success": true,
"job_id": 42,
"file_uuid": "3a6c1865...",
"status": "processing",
"pids": [12345, 12346],
"message": "Processing triggered for video.mp4"
"message": "Processing triggered",
"file_uuid": "3a6c1865..."
}
```
| Field | Type | Description |
|-------|------|-------------|
| `success` | boolean | Always true on 200 |
| `job_id` | integer | Monitor job ID (for job tracking) |
| `message` | string | Human-readable status message |
| `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 |
**Note**: Processing runs asynchronously in the background. Use `/api/v1/job/:uuid` to track job status and `/api/v1/progress/:file_uuid` for real-time progress.
#### Error Responses
@@ -526,3 +532,11 @@ 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 |
@@ -1,3 +1,13 @@
---
title: pipeline API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: pipeline -->
<!-- description: Pipeline processors, ingestion status, stats endpoints -->
<!-- depends: 01_auth -->
@@ -126,3 +136,11 @@ The following routes are defined in source code but are **NOT** currently mounte
---
*Updated: 2026-05-19 23:21:51*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: progress API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 -->
@@ -543,3 +553,11 @@ curl -s "$API/api/v1/stats/file/$FILE_UUID" \
| `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,281 @@
---
title: Job Management API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: job_management -->
<!-- description: Job pause/resume and status management -->
<!-- depends: 01_auth, 05_process -->
## Job Management
Control job execution with pause/resume functionality. Useful for managing system load and prioritizing jobs.
### `POST /api/v1/jobs/:uuid/pause`
**Auth**: Required
**Scope**: job-level
Pause a running or pending job. The worker will skip this job during polling until resumed.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `uuid` | string | Job UUID (file_uuid) |
#### Example
```bash
curl -X POST "$API/api/v1/jobs/$JOB_UUID/pause" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"message": "Job 3a6c1865... paused",
"uuid": "3a6c1865..."
}
```
#### Error Responses
| HTTP | When |
|------|------|
| `404` | Job not found |
| `400` | Job already completed or failed |
| `401` | Missing or invalid API key |
**Note**: Cannot pause jobs with status `completed` or `failed`.
---
### `POST /api/v1/jobs/:uuid/resume`
**Auth**: Required
**Scope**: job-level
Resume a paused job. The job will be picked up by the worker in the next polling cycle.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `uuid` | string | Job UUID (file_uuid) |
#### Example
```bash
curl -X POST "$API/api/v1/jobs/$JOB_UUID/resume" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"message": "Job 3a6c1865... resumed",
"uuid": "3a6c1865..."
}
```
#### Error Responses
| HTTP | When |
|------|------|
| `404` | Job not found |
| `401` | Missing or invalid API key |
---
### `GET /api/v1/jobs/paused`
**Auth**: Required
**Scope**: user-level
List all currently paused jobs with file names and pause timestamps.
#### Example
```bash
curl -s "$API/api/v1/jobs/paused" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"jobs": [
{
"uuid": "3a6c1865...",
"file_name": "video1.mp4",
"status": "paused",
"paused_at": "2026-10-25T10:30:00Z"
},
{
"uuid": "4b7d2976...",
"file_name": "video2.mp4",
"status": "paused",
"paused_at": "2026-10-25T11:15:00Z"
}
],
"total": 2
}
```
| Field | Type | Description |
|-------|------|-------------|
| `jobs` | array | Array of paused job objects |
| `uuid` | string | Job UUID (file_uuid) |
| `file_name` | string | Original file name |
| `status` | string | Always `"paused"` |
| `paused_at` | string \| null | ISO 8601 timestamp when paused |
| `total` | integer | Total number of paused jobs |
---
### `GET /api/v1/jobs/:uuid/status`
**Auth**: Required
**Scope**: job-level
Get the current status of a specific job. Returns detailed status including processor progress.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `uuid` | string | Job UUID (file_uuid) |
#### Example
```bash
curl -s "$API/api/v1/jobs/$JOB_UUID/status" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"uuid": "3a6c1865...",
"status": "paused",
"current_processor": "face",
"progress_current": 1500,
"progress_total": 2892,
"created_at": "2026-10-25T09:00:00Z",
"started_at": "2026-10-25T09:05:00Z",
"paused_at": "2026-10-25T10:30:00Z"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `uuid` | string | Job UUID |
| `status` | string | Current status (pending, running, paused, completed, failed) |
| `current_processor` | string \| null | Currently running processor |
| `progress_current` | integer | Current progress value |
| `progress_total` | integer | Total progress units |
| `created_at` | string | Job creation timestamp |
| `started_at` | string \| null | Job start timestamp |
| `paused_at` | string \| null | Pause timestamp (if paused) |
---
### `POST /api/v1/admin/sync-status`
**Auth**: Required
**Scope**: admin-level
Synchronize job statuses between database and Redis. Used for maintenance and consistency checks.
#### Example
```bash
curl -X POST "$API/api/v1/admin/sync-status" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"message": "Status sync completed",
"synced_count": 15
}
```
---
## Job Status Lifecycle
```
pending → running → completed
↓ ↓
paused failed
↓
pending (resumed)
```
| Status | Description | Actions Available |
|--------|-------------|-------------------|
| `pending` | Waiting in queue | Pause |
| `running` | Currently processing | Pause |
| `paused` | Paused by user | Resume |
| `completed` | Finished successfully | None |
| `failed` | Error occurred | None |
---
## Use Cases
### 1. Pause Heavy Processing Job
```bash
# Pause a running job to free up resources
curl -X POST "$API/api/v1/jobs/$UUID/pause" -H "X-API-Key: $KEY"
```
### 2. Resume Previously Paused Job
```bash
# Resume a paused job
curl -X POST "$API/api/v1/jobs/$UUID/resume" -H "X-API-Key: $KEY"
```
### 3. List All Paused Jobs
```bash
# Get all paused jobs
curl -s "$API/api/v1/jobs/paused" -H "X-API-Key: $KEY" | jq '.jobs[]'
```
### 4. Check Job Status
```bash
# Check if a job is paused or running
curl -s "$API/api/v1/jobs/$UUID/status" -H "X-API-Key: $KEY" | jq '.status'
```
---
## Implementation Notes
- **Redis Set**: Paused job UUIDs are stored in a Redis set (`jobs:paused`)
- **Worker Behavior**: Worker checks Redis set before picking up jobs
- **Persistence**: Pause state persists in both database and Redis
- **Resume Priority**: Resumed jobs enter the queue with normal priority
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,228 @@
---
title: Checkin API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: checkin -->
<!-- description: Workspace checkin/checkout for file isolation -->
<!-- depends: 01_auth, 03_register, 16_workspace -->
## Workspace Checkin/Checkout
Manage isolated workspace databases for files. Allows safe concurrent processing without conflicts.
### `POST /api/v1/file/:file_uuid/checkin`
**Auth**: Required
**Scope**: file-level
Check in a file from its isolated workspace database to the main database. Moves pre-chunks, speaker detections, and vectors from workspace to main tables.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID (32-char hex) |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/checkin" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"file_uuid": "3a6c1865...",
"pre_chunks_moved": 152,
"speaker_detections_moved": 45,
"vectors_moved": 152,
"status": "completed"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `file_uuid` | string | File UUID |
| `pre_chunks_moved` | integer | Number of pre-chunks moved |
| `speaker_detections_moved` | integer | Number of speaker detections moved |
| `vectors_moved` | integer | Number of vectors moved |
| `status` | string | Always `"completed"` |
#### Error Responses
| HTTP | When |
|------|------|
| `401` | Missing or invalid API key |
| `500` | Checkin failed (database error) |
---
### `POST /api/v1/file/:file_uuid/checkout`
**Auth**: Required
**Scope**: file-level
Check out a file from the main database. Deletes workspace data for the file.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID (32-char hex) |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/checkout" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"file_uuid": "3a6c1865...",
"rows_deleted": 197,
"status": "checked_out"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `file_uuid` | string | File UUID |
| `rows_deleted` | integer | Total rows deleted from workspace |
| `status` | string | Always `"checked_out"` |
---
### `GET /api/v1/file/:file_uuid/workspace`
**Auth**: Required
**Scope**: file-level
Check if a workspace database exists for a file.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID (32-char hex) |
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/workspace" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"file_uuid": "3a6c1865...",
"exists": true
}
```
| Field | Type | Description |
|-------|------|-------------|
| `file_uuid` | string | File UUID |
| `exists` | boolean | Whether workspace database exists |
---
## Workspace Architecture
```
┌─────────────────────────────────────────┐
│ Main Database │
│ (PostgreSQL + Qdrant vectors) │
│ │
│ videos, identities, chunk, ... │
└─────────────────────────────────────────┘
↑ checkin
↓ checkout
┌─────────────────────────────────────────┐
│ Isolated Workspace Database │
│ (SQLite per file) │
│ │
│ pre_chunks, speaker_detections │
│ vectors (Qdrant _workspace collection) │
└─────────────────────────────────────────┘
```
### Workspace Benefits
1. **Concurrent Processing**: Multiple files can be processed simultaneously without lock conflicts
2. **Isolation**: Processing errors don't affect main database
3. **Rollback**: Failed processing can be discarded without cleanup
4. **Performance**: SQLite workspace is faster for bulk inserts
---
## Use Cases
### 1. Complete Processing and Check In
```bash
# After processing completes successfully
curl -X POST "$API/api/v1/file/$FILE_UUID/checkin" -H "X-API-Key: $KEY"
```
### 2. Discard Failed Processing
```bash
# If processing failed, checkout to clean up
curl -X POST "$API/api/v1/file/$FILE_UUID/checkout" -H "X-API-Key: $KEY"
```
### 3. Check Workspace Status
```bash
# Before checkin, verify workspace exists
curl -s "$API/api/v1/file/$FILE_UUID/workspace" -H "X-API-Key: $KEY" | jq '.exists'
```
---
## Workflow
### Normal Processing Flow
```
1. Register file → status: REGISTERED
2. Start processing → workspace created → status: PROCESSING
3. Processing complete → workspace populated
4. Checkin → move to main DB → status: COMPLETED
5. Workspace deleted automatically
```
### Error Recovery Flow
```
1. Processing failed → workspace contains partial data
2. Checkout → delete workspace → status: COMPLETED
3. Re-trigger processing if needed
```
---
## Implementation Notes
- **Workspace Location**: `{output_dir}/{file_uuid}.workspace.db`
- **Vector Collection**: `qdrant://_workspace_{file_uuid}`
- **Auto-cleanup**: Workspace deleted after successful checkin
- **Idempotency**: Checkin/checkout can be called multiple times safely
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: search API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 -->
@@ -370,3 +380,11 @@ curl -s "$API/api/v1/search/identity_text?file_uuid=$FILE_UUID&q=love" -H "X-API
---
*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 |
@@ -0,0 +1,385 @@
---
title: VLM Search API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 searching video scenes and face traces using Vision Language Model (VLM) descriptions and vector embeddings.
### VLM Dual-Source Architecture
VLM processing analyzes **two distinct sources**, each producing separate Qdrant collections for semantic vector search:
| VLM Source | Analysis Target | Qdrant Collection | Search Endpoint |
|------------|-----------------|-------------------|-----------------|
| **Scene VLM** | 10-second scene frames | `_scenes` | `POST /api/v1/search/vlm/scenes` |
| **Trace VLM** | Face trace FS keyframes | `_vlm` | `POST /api/v1/search/vlm/traces` |
Both use **EmbeddingGemma-300m** (768D vectors) and **cosine similarity** for semantic search.
### VLM Data Flow
```
┌─────────────────────────────────────────────────────────────────┐
│ VLM Processing │
├──────────────────────────┬──────────────────────────────────────┤
│ Scene VLM │ Trace VLM │
│ - Analyzes 10s scenes │ - Analyzes face trace FS keyframes │
│ - Generates descriptions │ - Generates person descriptions │
│ - Embeds to Qdrant │ - Embeds to Qdrant │
│ `_scenes` collection │ `_vlm` collection │
└──────────────────────────┴──────────────────────────────────────┘
│ │
└──────────────┬───────────────────────┘
▼
Qdrant Vector Search
(Cosine similarity on 768D embeddings)
```
### Implementation Files
- **Scene VLM**: `/Users/accusys/momentry_core/src/core/processor/scene_vlm.rs`
- **Trace VLM**: `/Users/accusys/momentry_core/src/core/processor/vlm_summary.rs`
- **Qdrant Upsert**: `/Users/accusys/momentry_core/src/core/db/qdrant_db.rs`
- `upsert_scene_embedding()` → `_scenes` collection
- `upsert_vlm_embedding()` → `_vlm` collection
- **Search Endpoints**: `/Users/accusys/momentry_core/src/api/vlm_search.rs`
## 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 |
@@ -1,6 +1,8 @@
---
title: Scene VLM Stats API
version: 1.0.0
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-14
author: Core Team
status: active
@@ -1,3 +1,13 @@
---
title: identity API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: identity -->
<!-- description: Global identities — CRUD, detail, files, faces, bind, unbind, search -->
<!-- depends: 01_auth -->
@@ -1109,3 +1119,11 @@ This **replaces** the entire `aliases` array. To add to existing aliases, includ
*Updated: 2026-08-12 — identity traces include capture_quality fields (avg_capture_quality, best_capture_quality)*
*Updated: 2026-07-21 — Fixed bind/unbind TKG update to match both trace_N and face_track_N external_id formats*
*Updated: 2026-06-20 — Added identity files, chunks, faces, status, and JSON endpoints*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: identity agent API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 -->
@@ -125,3 +135,11 @@ curl -s -X POST "$API/api/v1/agents/identity/confirm" \
---
*Updated: 2026-06-26 00:30:00*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: identity history API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 -->
@@ -694,3 +704,11 @@ A new delete after an undo clears the delete redo stack (no redo possible for th
---
*Updated: 2026-05-28*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,40 +1,45 @@
# Face Filter API 使用指南 — Studio 團隊參考
**版本**: v1.0
**日期**: 2026-08-09
**狀態**: 已實作
---
title: Face Filter API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
## 概述
<!-- module: face_filter -->
<!-- description: Face detection filtering and quality management -->
<!-- depends: 01_auth, 03_register -->
Face Filter API 提供臉部過濾功能,讓 Studio 前端可以:
1. 查詢臉部列表(支持來源過濾)
2. 獲取單一臉部過濾報告
3. 套用過濾規則
4. 獲取過濾統計
5. 管理過濾規則
## Face Filter API
---
Face filtering functionality for Studio frontend to manage face detection quality across multiple detection sources.
## API 端點
### `GET /api/v1/file/:file_uuid/faces`
### 1. 獲取臉部列表
**Auth**: Required
**Scope**: file-level
**端點**: `GET /api/v1/file/{file_uuid}/faces`
Get filtered face detection list for a file with pagination and source filtering.
**功能**: 獲取檔案的臉部列表,支持分頁和來源過濾
#### Query Parameters
**查詢參數**:
```json
{
"source": "all", // "all" | "apple_vision" | "mediapipe"
"page": 1, // 頁碼(從 1 開始)
"page_size": 50 // 每頁數量
}
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `source` | string | No | "all" | Detection source: "all", "apple_vision", "mediapipe" |
| `page` | integer | No | 1 | Page number (1-indexed) |
| `page_size` | integer | No | 50 | Items per page |
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces?source=apple_vision&page=1&page_size=50" \
-H "X-API-Key: $KEY"
```
**回應範例**:
#### Response (200)
```json
{
"success": true,
@@ -48,703 +53,293 @@ Face Filter API 提供臉部過濾功能,讓 Studio 前端可以:
"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
}
"total": 1523,
"page": 1,
"page_size": 50
}
}
```
**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/faces/:face_id/filter`
**端點**: `GET /api/v1/file/{file_uuid}/face/{face_id}/filter-report`
**Auth**: Required
**Scope**: file-level
**功能**: 獲取單一臉部的詳細過濾報告
Get detailed filter report for a specific face detection.
**回應範例**:
```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)"
]
}
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID |
| `face_id` | string | Face detection ID |
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces/face_001/filter" \
-H "X-API-Key: $KEY"
```
**Studio 使用範例**:
```typescript
// 獲取臉部過濾報告
const response = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/face/face_001/filter-report');
const report = await response.json();
#### Response (200)
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})`);
});
```json
{
"success": true,
"data": {
"face_id": "face_001",
"frame": 671,
"passed_filter": true,
"filter_rules": {
"min_confidence": 0.5,
"min_size": 30,
"source_priority": ["apple_vision", "mediapipe"]
},
"quality_metrics": {
"confidence": 0.84,
"size": 120,
"blurriness": 0.15
}
}
}
```
---
### 3. 套用過濾規則
### `POST /api/v1/file/:file_uuid/faces/apply-filter`
**端點**: `POST /api/v1/file/{file_uuid}/faces/filter`
**Auth**: Required
**Scope**: file-level
**功能**: 套用過濾規則到所有臉部,返回過濾結果
Apply filter rules to all faces in a file. Returns statistics on filtered faces.
**請求範例**:
```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]
}
}
}
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `min_confidence` | float | No | Minimum confidence threshold (0.0-1.0) |
| `min_size` | integer | No | Minimum face size in pixels |
| `source_priority` | string[] | No | Preferred detection sources in order |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/faces/apply-filter" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"min_confidence": 0.6,
"min_size": 40,
"source_priority": ["apple_vision", "mediapipe"]
}'
```
**回應範例**:
#### Response (200)
```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,
"success": true,
"statistics": {
"total_faces": 1523,
"passed_faces": 1245,
"filtered_faces": 278,
"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
"apple_vision": 985,
"mediapipe": 260
}
}
}
```
**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}`);
### `GET /api/v1/file/:file_uuid/faces/filter-stats`
**Auth**: Required
**Scope**: file-level
Get face filter statistics for a file without applying changes.
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces/filter-stats" \
-H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"data": {
"total_faces": 1523,
"detection_sources": {
"apple_vision": 985,
"mediapipe": 538
},
"confidence_distribution": {
"high": 1245,
"medium": 200,
"low": 78
},
"size_distribution": {
"large": 500,
"medium": 700,
"small": 323
}
}
}
```
---
### 5. 管理過濾規則
### `POST /api/v1/file/:file_uuid/faces/rules`
#### 5.1 獲取過濾規則
**Auth**: Required
**Scope**: file-level
**端點**: `GET /api/v1/file/{file_uuid}/filter-rules`
Create or update face filter rules for a file.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `rules` | array | Yes | Array of filter rules |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/faces/rules" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"rules": [
{
"name": "high_quality",
"conditions": {
"min_confidence": 0.7,
"min_size": 50
},
"action": "accept"
}
]
}'
```
---
### `GET /api/v1/file/:file_uuid/faces/rules`
**Auth**: Required
**Scope**: file-level
Get all face filter rules configured for a file.
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces/rules" \
-H "X-API-Key: $KEY"
```
#### Response (200)
**回應範例**:
```json
{
"success": true,
"rules": [
{
"id": 1,
"rule_name": "default_filter",
"rules": {
"version": "1.0",
"rules": {
"landmark_analysis": { ... },
"mediapipe_verification": { ... },
"embedding_similarity": { ... },
"temporal_consistency": { ... }
},
"overall_thresholds": { ... }
"name": "high_quality",
"conditions": {
"min_confidence": 0.7,
"min_size": 50
},
"is_active": true,
"created_at": "2026-08-09T12:00:00Z",
"updated_at": "2026-08-09T12:00:00Z"
"action": "accept",
"created_at": "2026-08-09T10:00:00Z"
}
]
}
```
#### 5.2 儲存過濾規則
---
**端點**: `POST /api/v1/file/{file_uuid}/filter-rules`
### `DELETE /api/v1/file/:file_uuid/faces/rules/:rule_id`
**請求範例**:
```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
}
```
**Auth**: Required
**Scope**: file-level
**Studio 使用範例**:
```typescript
// 獲取現有規則
const getResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules');
const rulesData = await getResponse.json();
Delete a specific filter rule.
// 儲存新規則
const strictFilter = {
rule_name: "strict_filter",
rules: {
// ... 規則配置
},
is_active: true
};
#### Path Parameters
const saveResponse = await fetch('/api/v1/file/0489e104d7d1e11e613da01f7aa130ca/filter-rules', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(strictFilter)
});
| Parameter | Type | Description |
|-----------|------|-------------|
| `rule_id` | integer | Rule ID |
const savedRule = await saveResponse.json();
console.log(`Saved rule: ${savedRule.rule_name} (id: ${savedRule.id})`);
#### Example
```bash
curl -X DELETE "$API/api/v1/file/$FILE_UUID/faces/rules/1" \
-H "X-API-Key: $KEY"
```
---
## 過濾規則說明
## Detection Sources
### 規則類型
#### 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
| Source | Description | Quality | Speed |
|--------|-------------|---------|-------|
| `apple_vision` | Apple Vision Framework | High (ANE accelerated) | Fast |
| `mediapipe` | MediaPipe Face Detection | Medium | Medium |
---
#### 2. MediaPipe 驗證 (mediapipe_verification)
## Quality Metrics
**功能**: 驗證 MediaPipe 是否也檢測到該臉部
**值**:
- `min_iou`: 最小 IoU 值(預設 0.3)
**權重**: 0.2
| Metric | Description | Range |
|--------|-------------|-------|
| `confidence` | Detection confidence | 0.0-1.0 |
| `size` | Face bounding box diagonal (pixels) | 0-∞ |
| `blurriness` | Laplacian variance (lower = clearer) | 0.0-1.0 |
---
#### 3. Embedding 相似度 (embedding_similarity)
## Use Cases
**功能**: 檢查臉部 embedding 與已知人臉的相似度
### 1. Filter Low-Quality Faces
**閾值**:
- `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 像素
});
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/faces/apply-filter" \
-H "X-API-Key: $KEY" \
-d '{"min_confidence": 0.7, "min_size": 50}'
```
**建議閾值**:
- 保守: 80 像素
- 平衡: 64 像素(當前預設)
- 寬鬆: 48 像素
### 2. Prioritize Apple Vision Detections
**未來擴展**:
- 可考慮增加 `max(bbox.width, bbox.height)` 選項
- 可考慮增加 `bbox.width * bbox.height` (面積) 選項
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/faces/apply-filter" \
-H "X-API-Key: $KEY" \
-d '{"source_priority": ["apple_vision"]}'
```
---
### 3. Check Filter Statistics
## 預設配置
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]
}
}
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces/filter-stats" \
-H "X-API-Key: $KEY" | jq '.data'
```
---
## 完整使用範例
## Version History
### 場景 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
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Rewrote documentation in English, added YAML frontmatter |
@@ -1,3 +1,13 @@
---
title: Media API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: media -->
<!-- description: Video streaming & frame extraction -->
<!-- depends: 01_auth -->
@@ -535,3 +545,11 @@ curl -s "$API/api/v1/media-proxy?url=https://image.tmdb.org/t/p/w500/abc123.jpg"
---
*Updated: 2026-06-20 — Added stranger endpoints, chunk thumbnail, and media proxy*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: profile API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 -->
@@ -474,3 +484,11 @@ curl -s -X PUT "$API/api/v1/file-profile" \
*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,184 @@
---
title: Pose & Appearance API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 |
@@ -1,3 +1,13 @@
---
title: tmdb API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: tmdb -->
<!-- description: TMDb enrichment endpoints — prefetch, probe, resource, check -->
<!-- depends: 01_auth, 03_register -->
@@ -199,3 +209,11 @@ 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 |
@@ -1,3 +1,13 @@
---
title: agent API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
# Agent Endpoints
Agent endpoints provide AI-powered capabilities including translation, identity analysis, and 5W1H extraction.
@@ -209,3 +219,11 @@ Agent 內部使用 Gemma4 function calling 自動調用以下工具:
---
*Updated: 2026-05-22*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: tkg API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 -->
@@ -532,3 +542,11 @@ curl -X POST "$API/api/v1/file/$FILE_UUID/trace/16/merge/3" \
*Updated: 2026-07-21 01:00:00*
*Updated: 2026-08-12 — face_track node properties now include capture_quality fields (avg/best) and key_frame/key_face are selected by best capture quality*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,375 @@
---
title: Trace Agent API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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,245 @@
---
title: Cluster Agent API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: cluster_agent -->
<!-- description: Asynchronous face clustering agent -->
<!-- depends: 01_auth, 03_register, 07_identity -->
## Cluster Agent
Asynchronous face clustering agent that automatically groups similar faces into identities. Runs as a background job.
### `POST /api/v1/file/:file_uuid/cluster-agent`
**Auth**: Required
**Scope**: file-level
Trigger asynchronous face clustering for a file. Returns immediately with a job ID. Clustering runs in the background.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID (32-char hex) |
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `confirm` | boolean | Yes | false | Must be `true` to trigger clustering |
| `min_confidence` | float | No | 0.6 | Minimum face confidence to include |
| `algorithm` | string | No | "dbscan" | Clustering algorithm ("dbscan", "kmeans") |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/cluster-agent" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{"confirm": true, "min_confidence": 0.6}'
```
#### Response (202 Accepted)
```json
{
"success": true,
"job_id": "cluster_abc123",
"file_uuid": "3a6c1865...",
"status": "queued",
"message": "Cluster job queued for processing"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `success` | boolean | Always true on 202 |
| `job_id` | string | Job ID for status tracking |
| `file_uuid` | string | File UUID |
| `status` | string | Job status ("queued", "running", "completed", "failed") |
| `message` | string | Human-readable status |
#### Error Responses
| HTTP | When |
|------|------|
| `400` | `confirm` not set to `true` |
| `404` | File not found |
| `409` | Job already running for this file |
| `401` | Missing or invalid API key |
---
### `GET /api/v1/cluster-job/:job_id`
**Auth**: Required
**Scope**: job-level
Get status of a cluster job. Returns progress, statistics, and results if completed.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `job_id` | string | Job ID returned from trigger endpoint |
#### Example
```bash
curl -s "$API/api/v1/cluster-job/cluster_abc123" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"job_id": "cluster_abc123",
"file_uuid": "3a6c1865...",
"status": "completed",
"progress": {
"total_faces": 1523,
"processed": 1523,
"percentage": 100
},
"result": {
"clusters_found": 12,
"identities_created": 8,
"identities_updated": 4
},
"started_at": "2026-10-25T10:00:00Z",
"completed_at": "2026-10-25T10:05:30Z"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `job_id` | string | Job ID |
| `file_uuid` | string | File UUID |
| `status` | string | "running", "completed", "failed", "cancelled" |
| `progress` | object | Progress information |
| `result` | object | Final results (if completed) |
| `error` | string | Error message (if failed) |
| `started_at` | string | ISO 8601 timestamp |
| `completed_at` | string | ISO 8601 timestamp (if completed) |
---
### `DELETE /api/v1/cluster-job/:job_id`
**Auth**: Required
**Scope**: job-level
Cancel a running cluster job. Cannot cancel completed or failed jobs.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `job_id` | string | Job ID |
#### Example
```bash
curl -X DELETE "$API/api/v1/cluster-job/cluster_abc123" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"job_id": "cluster_abc123",
"status": "cancelled",
"message": "Job cancelled successfully"
}
```
---
## Clustering Process
### How It Works
1. **Face Collection**: Gather all face detections from the file
2. **Embedding Extraction**: Get face embeddings (512-dim vectors)
3. **Similarity Clustering**: Group similar faces using DBSCAN
4. **Identity Assignment**: Create or update identities for clusters
5. **Face Binding**: Bind faces to their cluster identity
### Clustering Algorithm
**DBSCAN Parameters**:
- `eps`: 0.3 (distance threshold)
- `min_samples`: 5 (minimum cluster size)
**Quality Metrics**:
- Intra-cluster similarity: Average pairwise similarity within cluster
- Inter-cluster separation: Average distance to nearest cluster
---
## Use Cases
### 1. Automatic Identity Creation
```bash
# After processing, trigger clustering
curl -X POST "$API/api/v1/file/$FILE_UUID/cluster-agent" \
-H "X-API-Key: $KEY" \
-d '{"confirm": true}'
```
### 2. Monitor Clustering Progress
```bash
# Poll job status
curl -s "$API/api/v1/cluster-job/$JOB_ID" -H "X-API-Key: $KEY" | jq '.status'
```
### 3. Cancel Slow Clustering
```bash
# If clustering takes too long
curl -X DELETE "$API/api/v1/cluster-job/$JOB_ID" -H "X-API-Key: $KEY"
```
---
## Performance
| File Size | Face Count | Processing Time |
|-----------|------------|-----------------|
| 10 min video | 500 faces | ~30 seconds |
| 30 min video | 1500 faces | ~2 minutes |
| 90 min video | 4500 faces | ~8 minutes |
**Notes**:
- Processing time scales linearly with face count
- Uses in-memory job registry (cleared on server restart)
- Concurrent jobs are supported but resource-intensive
---
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| `400 Bad Request` | `confirm` not set | Add `"confirm": true` to request body |
| `404 Not Found` | File not found | Verify file_uuid |
| `409 Conflict` | Job already running | Wait for current job to complete or cancel it |
| `500 Internal Error` | Clustering failed | Check server logs for details |
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: error codes API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: error_codes -->
<!-- description: Standard API error codes -->
<!-- depends: -->
@@ -58,3 +68,11 @@ All API errors follow this JSON structure:
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: config API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: config -->
<!-- description: System configuration — cache, auto-pipeline, watcher-auto-register toggles -->
<!-- depends: 01_auth -->
@@ -88,3 +98,11 @@ curl -s -X POST "$API/api/v1/config/watcher-auto-register" \
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,13 @@
---
title: workspace API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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 -->
@@ -146,3 +156,11 @@ curl -s "$API/api/v1/file/$FILE_UUID/workspace" \
---
*Updated: 2026-06-20 12:00:00*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,389 @@
---
title: Service Management API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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,399 @@
---
title: Monitor API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
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,310 @@
---
title: Admin Config API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: admin_config -->
<!-- description: System configuration management -->
<!-- depends: 01_auth -->
## Admin Configuration
Admin configuration management for system-wide settings, VLM prompts, and runtime parameters.
### `GET /api/v1/admin/config`
**Auth**: Required
**Scope**: admin-level
Get the full system configuration. Returns all configuration parameters including VLM prompts, processing settings, and system defaults.
#### Example
```bash
curl -s "$API/api/v1/admin/config" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"vlm_prompts": {
"face_trace": {
"system_prompt": "Analyze the person's appearance...",
"user_prompt_template": "Describe this person..."
}
},
"processing": {
"default_processors": ["cut", "asr", "face"],
"face_min_confidence": 0.5,
"face_min_size": 30
},
"system": {
"max_concurrent_jobs": 3,
"output_dir": "/Users/accusys/momentry/output"
}
}
```
---
### `POST /api/v1/admin/config`
**Auth**: Required
**Scope**: admin-level
Partially update system configuration. Only provided fields are modified; others remain unchanged.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `processing` | object | No | Processing configuration |
| `system` | object | No | System configuration |
#### Example
```bash
curl -X POST "$API/api/v1/admin/config" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"processing": {
"face_min_confidence": 0.6
}
}'
```
#### Response (200)
```json
{
"success": true,
"message": "Config updated"
}
```
---
### `GET /api/v1/admin/config/vlm_prompts`
**Auth**: Required
**Scope**: admin-level
Get all VLM (Vision Language Model) prompts used for image analysis.
#### Example
```bash
curl -s "$API/api/v1/admin/config/vlm_prompts" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"face_trace": {
"system_prompt": "You are an expert in person appearance analysis...",
"user_prompt_template": "Describe the person in this image..."
},
"scene": {
"system_prompt": "You are a scene description expert...",
"user_prompt_template": "Describe the scene..."
}
}
```
---
### `GET /api/v1/admin/config/vlm_prompts/:key`
**Auth**: Required
**Scope**: admin-level
Get a specific VLM prompt by key.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `key` | string | Prompt key (e.g., "face_trace", "scene") |
#### Example
```bash
curl -s "$API/api/v1/admin/config/vlm_prompts/face_trace" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"system_prompt": "You are an expert in person appearance analysis...",
"user_prompt_template": "Describe the person in this image..."
}
```
#### Error Responses
| HTTP | When |
|------|------|
| `404` | Prompt key not found |
| `401` | Missing or invalid API key |
---
### `PUT /api/v1/admin/config/vlm_prompts/:key`
**Auth**: Required
**Scope**: admin-level
Update a specific VLM prompt. This affects all subsequent VLM analysis operations.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `system_prompt` | string | Yes | System prompt for the LLM |
| `user_prompt_template` | string | Yes | User prompt template (may include placeholders) |
#### Example
```bash
curl -X PUT "$API/api/v1/admin/config/vlm_prompts/face_trace" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"system_prompt": "You are an expert in fashion and appearance analysis...",
"user_prompt_template": "Analyze the person'\''s clothing and accessories in detail..."
}'
```
#### Response (200)
```json
{
"success": true,
"message": "Prompt 'face_trace' updated"
}
```
---
### `POST /api/v1/admin/config/reload`
**Auth**: Required
**Scope**: admin-level
Reload configuration from disk. Useful when the configuration file has been manually edited.
#### Example
```bash
curl -X POST "$API/api/v1/admin/config/reload" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"message": "Config reloaded"
}
```
---
### `GET /api/v1/admin/settings`
**Auth**: Required
**Scope**: admin-level
Alias for `/api/v1/admin/config`. Provided for frontend compatibility.
---
## Configuration Structure
### VLM Prompts
VLM prompts control how the system analyzes images and video frames:
| Prompt Key | Purpose | Used By |
|------------|---------|---------|
| `face_trace` | Person appearance description | Face trace processor |
| `scene` | Scene description | Scene VLM processor |
| `appearance` | Detailed appearance analysis | Appearance processor |
### Processing Settings
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `default_processors` | string[] | all | Default processors for new files |
| `face_min_confidence` | float | 0.5 | Minimum face detection confidence |
| `face_min_size` | integer | 30 | Minimum face size in pixels |
### System Settings
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `max_concurrent_jobs` | integer | 3 | Maximum parallel processing jobs |
| `output_dir` | string | - | Output directory path |
---
## Use Cases
### 1. Adjust Face Detection Sensitivity
```bash
curl -X POST "$API/api/v1/admin/config" \
-H "X-API-Key: $KEY" \
-d '{
"processing": {
"face_min_confidence": 0.7,
"face_min_size": 50
}
}'
```
### 2. Customize VLM Prompts
```bash
curl -X PUT "$API/api/v1/admin/config/vlm_prompts/face_trace" \
-H "X-API-Key: $KEY" \
-d '{
"system_prompt": "Focus on clothing colors and patterns",
"user_prompt_template": "Describe the person'\''s outfit..."
}'
```
### 3. Reload Configuration After Manual Edit
```bash
# Edit config file on disk
vim /path/to/config.json
# Reload into running system
curl -X POST "$API/api/v1/admin/config/reload" -H "X-API-Key: $KEY"
```
---
## Security Notes
- **Admin-only access**: All endpoints require admin-level authentication
- **Persistent changes**: Configuration changes persist across server restarts
- **Hot reload**: Changes take effect immediately without server restart
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,120 @@
---
title: Docs API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: docs -->
<!-- description: API documentation web server -->
<!-- depends: 01_auth -->
## Documentation Web Server
Web-based API documentation served by the server. Supports both static HTML and WASM-based interactive documentation.
### `GET /doc`
**Auth**: Not required
Redirect to WASM documentation.
#### Example
```bash
curl -L http://localhost:3002/doc
```
#### Response
301 Redirect → `/doc-wasm`
---
### `GET /doc-wasm`
**Auth**: Not required
Serve WASM-based interactive documentation.
#### Example
```bash
curl http://localhost:3002/doc-wasm
```
#### Response (200)
HTML page with WASM documentation viewer.
---
### `GET /doc-wasm/*file`
**Auth**: Not required
Serve WASM binary files and static assets for documentation.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file` | string | File path (e.g., "pkg/md_wasm_bg.wasm") |
#### Example
```bash
curl http://localhost:3002/doc-wasm/pkg/md_wasm_bg.wasm --output md_wasm_bg.wasm
```
#### Response (200)
Binary file with appropriate MIME type:
- `.wasm` → `application/wasm`
- `.js` → `application/javascript`
- `.css` → `text/css`
- `.md` → `text/markdown`
---
## Documentation Types
### WASM Documentation (Default)
- **Location**: `docs_v1.0/doc_wasm/`
- **Technology**: Rust WASM + pulldown-cmark
- **Features**: Interactive search, Mermaid diagrams, Material Design
- **Authentication**: Optional (configurable)
### Static Documentation
- **Location**: `docs_v1.0/API_WORKSPACE/` and `docs_v1.0/CLI_WORKSPACE/`
- **Format**: Markdown files
- **Served via**: WASM renderer
---
## Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `MOMENTRY_DOCS_DIR` | `{binary_dir}/docs_v1.0/doc_wasm` | Documentation root directory |
---
## Security
- **Path Traversal Protection**: Rejects paths containing `..` or `//`
- **Directory Restriction**: Only serves files within `MOMENTRY_DOCS_DIR`
- **No Authentication**: Documentation is public (unless protected by reverse proxy)
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,161 @@
---
title: Markbase Compat API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: markbase_compat -->
<!-- description: MarkBase compatibility layer for Studio -->
<!-- depends: 01_auth -->
## MarkBase Compatibility
Compatibility layer for MarkBase API, enabling Studio to access user data folders.
### `GET /api/v1/markbase/folders/:username`
**Auth**: Required
**Scope**: user-level
List all folders for a user.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `username` | string | User name |
#### Example
```bash
curl -s "$API/api/v1/markbase/folders/admin" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
[
{
"name": "Documents",
"parent": ""
},
{
"name": "Media",
"parent": ""
}
]
```
---
### `GET /api/v1/markbase/files/:username/:folder`
**Auth**: Required
**Scope**: user-level
List all files in a user's folder.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `username` | string | User name |
| `folder` | string | Folder name |
#### Example
```bash
curl -s "$API/api/v1/markbase/files/admin/Documents" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
[
{
"name": "video1.mp4",
"type": "file",
"size": 1048576,
"modified": "2026-10-25T10:00:00Z",
"is_dir": false
},
{
"name": "subfolder",
"type": "directory",
"size": 0,
"modified": "2026-10-25T09:00:00Z",
"is_dir": true
}
]
```
---
### `GET /api/v1/markbase/file/:username/:path`
**Auth**: Required
**Scope**: user-level
Get details or download a specific file.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `username` | string | User name |
| `path` | string | File path within user directory |
#### Example
```bash
curl -s "$API/api/v1/markbase/file/admin/Documents/video1.mp4" \
-H "X-API-Key: $KEY" \
--output video1.mp4
```
#### Response (200)
File content with appropriate MIME type.
---
## Directory Structure
```
var/studio/data/
├── {username}/
│ └── files/
│ ├── Documents/
│ │ ├── video1.mp4
│ │ └── video2.mp4
│ └── Media/
│ └── audio.mp3
```
---
## Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `MOMENTRY_STUDIO_DATA_DIR` | `{binary_dir}/var/studio/data` | Studio data directory |
---
## Compatibility Notes
- **Purpose**: Provides MarkBase-compatible API for Studio integration
- **Backward Compatibility**: Maintains existing Studio functionality
- **Future**: May be deprecated when Studio migrates to new API structure
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,246 @@
---
title: CLIP API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: clip -->
<!-- description: CLIP-based image classification and object detection -->
<!-- depends: 01_auth -->
## CLIP Vision Model
### `POST /api/v1/clip/classify`
**Auth**: Required
**Scope**: system-level
Classify an image against a list of text labels using CLIP (Contrastive Language-Image Pre-training). Returns top-k predictions with confidence scores.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `image_path` | string | Yes | - | Absolute path to the image file |
| `labels` | string | Yes | - | Comma-separated text labels (e.g., "dog,cat,car,person") |
| `top_k` | integer | No | 5 | Number of top predictions to return |
| `model` | string | No | default | CLIP model variant to use |
#### Example
```bash
curl -s -X POST "$API/api/v1/clip/classify" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"image_path": "/path/to/image.jpg",
"labels": "dog,cat,car,person,building",
"top_k": 3
}'
```
#### Response (200)
```json
{
"success": true,
"predictions": [
{
"label": "dog",
"confidence": 0.892
},
{
"label": "person",
"confidence": 0.073
},
{
"label": "cat",
"confidence": 0.021
}
]
}
```
| Field | Type | Description |
|-------|------|-------------|
| `success` | boolean | Operation success status |
| `predictions` | array | Array of label-confidence pairs, sorted by confidence (descending) |
| `label` | string | Text label |
| `confidence` | float | Confidence score (0.0-1.0) |
#### Error Responses
| HTTP | When |
|------|------|
| `400` | Invalid image path or labels |
| `401` | Missing or invalid API key |
| `500` | CLIP model inference error |
---
### `POST /api/v1/clip/detect`
**Auth**: Required
**Scope**: system-level
Detect specific objects in an image using zero-shot object detection. Returns detected objects with confidence scores above the threshold.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `image_path` | string | Yes | - | Absolute path to the image file |
| `objects` | string | Yes | - | Comma-separated object names to detect |
| `threshold` | float | No | 0.15 | Confidence threshold (0.0-1.0) |
| `model` | string | No | default | CLIP model variant to use |
#### Example
```bash
curl -s -X POST "$API/api/v1/clip/detect" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"image_path": "/path/to/scene.jpg",
"objects": "person,car,bicycle",
"threshold": 0.3
}'
```
#### Response (200)
```json
{
"success": true,
"detected": [
{
"label": "person",
"confidence": 0.921
},
{
"label": "car",
"confidence": 0.876
}
]
}
```
**Note**: Only objects with confidence >= `threshold` are returned. If no objects are detected, `detected` will be an empty array.
---
### `POST /api/v1/clip/batch`
**Auth**: Required
**Scope**: system-level
Batch classify multiple images against the same set of labels. Efficient for processing large image sets.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `image_paths` | string | Yes | - | Comma-separated absolute paths to image files |
| `labels` | string | Yes | - | Comma-separated text labels |
| `top_k` | integer | No | 5 | Number of top predictions per image |
| `model` | string | No | default | CLIP model variant to use |
#### Example
```bash
curl -s -X POST "$API/api/v1/clip/batch" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"image_paths": "/path/to/img1.jpg,/path/to/img2.jpg,/path/to/img3.jpg",
"labels": "indoor,outdoor,nature,urban",
"top_k": 2
}'
```
#### Response (200)
```json
{
"success": true,
"results": {
"/path/to/img1.jpg": [
{"label": "indoor", "confidence": 0.945},
{"label": "urban", "confidence": 0.032}
],
"/path/to/img2.jpg": [
{"label": "outdoor", "confidence": 0.876},
{"label": "nature", "confidence": 0.089}
],
"/path/to/img3.jpg": [
{"label": "nature", "confidence": 0.923},
{"label": "outdoor", "confidence": 0.054}
]
}
}
```
---
## Use Cases
### 1. Scene Classification
```bash
# Classify scene type
curl -X POST "$API/api/v1/clip/classify" \
-H "X-API-Key: $KEY" \
-d '{
"image_path": "/output/video_frame.jpg",
"labels": "indoor,outdoor,day,night",
"top_k": 2
}'
```
### 2. Object Detection
```bash
# Detect people and vehicles
curl -X POST "$API/api/v1/clip/detect" \
-H "X-API-Key: $KEY" \
-d '{
"image_path": "/output/frame_001.jpg",
"objects": "person,car,bicycle,motorcycle",
"threshold": 0.3
}'
```
### 3. Batch Frame Analysis
```bash
# Analyze multiple video frames
curl -X POST "$API/api/v1/clip/batch" \
-H "X-API-Key: $KEY" \
-d '{
"image_paths": "/output/frame_001.jpg,/output/frame_002.jpg,/output/frame_003.jpg",
"labels": "action,dialogue,scenery",
"top_k": 1
}'
```
---
## Implementation Notes
- **Model**: Uses CLIP ViT-B/32 by default
- **Performance**: ~50ms per image on CPU, ~5ms on GPU
- **Supported Formats**: JPEG, PNG, WebP, BMP
- **Max Image Size**: 4K resolution (3840x2160)
- **Batch Limit**: Recommended max 100 images per batch
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,180 @@
---
title: Billing API
version: 1.3.5
api_version: 1.3.5
git_tag: v1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: billing -->
<!-- description: Token usage tracking and billing -->
<!-- depends: 01_auth -->
## Billing & Usage Tracking
Track LLM token usage across different services (Agent, VLM, TKG, etc.).
### `GET /api/v1/billing/usage`
**Auth**: Required
**Scope**: user-level
Get token usage for a specific billing period. Returns input/output token counts and service breakdown.
#### Query Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `period` | string | No | Current month | Billing period in YYYY-MM format |
#### Example
```bash
# Get current month usage
curl -s "$API/api/v1/billing/usage" -H "X-API-Key: $KEY"
# Get specific month
curl -s "$API/api/v1/billing/usage?period=2026-09" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"key_id": null,
"period": "2026-10",
"tokens": {
"input": 15234,
"output": 8921,
"total": 24155
},
"services": {
"agent": 8500,
"vlm": 12000,
"tkg": 3655
}
}
```
| Field | Type | Description |
|-------|------|-------------|
| `key_id` | string \| null | API key ID (null for user-level aggregate) |
| `period` | string | Billing period (YYYY-MM) |
| `tokens` | object | Token statistics |
| `tokens.input` | integer | Total input tokens |
| `tokens.output` | integer | Total output tokens |
| `tokens.total` | integer | Total tokens (input + output) |
| `services` | object | Token usage per service |
---
### `GET /api/v1/billing/history`
**Auth**: Required
**Scope**: user-level
Get token usage history for the past N months.
#### Query Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `months` | integer | No | 12 | Number of months to retrieve |
#### Example
```bash
# Get last 12 months
curl -s "$API/api/v1/billing/history" -H "X-API-Key: $KEY"
# Get last 6 months
curl -s "$API/api/v1/billing/history?months=6" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"periods": [
{
"key_id": null,
"period_month": "2026-10",
"total_input_tokens": 15234,
"total_output_tokens": 8921,
"total_tokens": 24155,
"service_breakdown": {
"agent": 8500,
"vlm": 12000,
"tkg": 3655
}
},
{
"key_id": null,
"period_month": "2026-09",
"total_input_tokens": 18234,
"total_output_tokens": 9456,
"total_tokens": 27690,
"service_breakdown": {
"agent": 10200,
"vlm": 13500,
"tkg": 3990
}
}
]
}
```
---
## Service Categories
| Service | Description | Token Type |
|---------|-------------|------------|
| `agent` | Agent chat, search, 5W1H | Input + Output |
| `vlm` | Vision Language Model (image analysis) | Input + Output |
| `tkg` | Temporal Knowledge Graph queries | Input + Output |
| `embedding` | Text embeddings | Input only |
| `chat` | General chat/completions | Input + Output |
---
## Use Cases
### 1. Monitor Current Month Usage
```bash
curl -s "$API/api/v1/billing/usage" -H "X-API-Key: $KEY" | jq '.tokens'
```
### 2. Generate Monthly Report
```bash
curl -s "$API/api/v1/billing/history?months=12" -H "X-API-Key: $KEY" | \
jq -r '.periods[] | "\(.period_month),\(.total_tokens)"'
```
### 3. Check Service Breakdown
```bash
curl -s "$API/api/v1/billing/usage" -H "X-API-Key: $KEY" | \
jq '.services | to_entries | sort_by(.value) | reverse | .[]'
```
---
## Billing Notes
- **Token counting**: Both input and output tokens are counted
- **Aggregation**: Usage is aggregated per user or per API key
- **Persistence**: Billing data persists across server restarts
- **Reset**: Billing periods reset monthly on the 1st
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |