22 Commits

Author SHA1 Message Date
Accusys 083d73d287 feat: real service test endpoints (proxy 7-route round-trip, core/chat/vlm/markbase/embedding), unified log paths + errorLog, pipeline tools/import/export/folder APIs, face pipeline check, dynamic concurrency tuning
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-16 18:16:46 +08:00
Accusys d21d1ab960 fix: Library Re-run 完整重建搜尋索引 (ASR/ASRX/OCR/Scene VLM)
- trigger_processing: force 時僅刪除指定 processor 的輸出檔與 processor_results
  (其他 processor 資料保留),並設定 rerun_rebuild Redis flag 要求重建索引
- worker: 單一 processor Re-run 時強制 Rule 1 重新 chunk + vectorize
  (清除 momentry_rule1 舊 vectors,避免 stale 搜尋結果)
- Scene VLM Re-run: job_processors 含 scene_vlm 即 dispatch,
  scene-only job 完成條件改以 scenes.json 完整度判定
- 前端 redoProcessor 傳 force=true,Scene VLM 新增 🔄 Re-run 按鈕
2026-11-10 07:59:31 +08:00
Accusys 043dbbf24a fix: swift_ocr 支援日文識別
Cross-Project Integration / integration (push) Has been cancelled
- 加入 recognitionLanguages = ["ja", "en"] 使 Apple Vision Framework
  能識別日文和中文文字
- 使用 #available(macOS 12.0, *) 確保向後相容
- 兩處 VNRecognizeTextRequest 都已修改(主循環 + recognizeText 函式)

驗證: 065.mp4 從 0 幀 → 75 幀,1559 個日文文字區塊
(松原徳洲会病院、ここで検索、吹田市、寝屋川市 等)
2026-11-09 17:16:37 +08:00
Accusys 3d7ec83ec9 fix: Qdrant collection ensure + self-healing on clean install
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- qdrant_db.rs: ensure_collection now uses PUT /collections/{name}
  (was POST /collections without name) and checks response status.
  Previous code silently no-op'd, so every upsert got 404 on clean
  installs with empty Qdrant.
- face.rs: store_face_embeddings_to_qdrant ensures _faces (512D)
  collection exists before upsert (fixes face→facenet→Qdrant broken
  link on fresh machines).
- pipeline/mod.rs: vectorize_chunks ensures main text collection
  (768D) before upserts.
- job_worker.rs: vectorize_chunks ensures main collection (768D)
  before upserts; also 3 additional lines of job_worker WIP fixes.

Verified: after these fixes, Qdrant collections are auto-created
on first upsert, resolving the face embedding + rule1 vectorize
failures on 203.
2026-11-09 15:55:01 +08:00
Accusys 70f5667adc fix: processor-counts resolves face_trace -> face_traced.json
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
get_processor_counts built the filename from the queue name
(face_trace.json) while rust_store_traced_faces writes face_traced.json
(per processor_tools_v3 output_file), so the API/UI reported
face_trace has_json=false and face_traced data was unreachable for
existing files. Map face_trace -> face_traced in both
get_processor_counts and get_processor_json.

Verified: dev (201) & 203 processor-counts now report face_trace
has_json=true and /api/v1/processor-json?processor=face_trace returns 200.
2026-11-09 12:39:44 +08:00
Accusys 8ff77d7dba fix: rust_asr_asrx extracts audio into ~/momentry/temp, auto-cleans
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
The extracted wav used to be written next to the source video
(<video>.wav), polluting the /library listing (002.wav, 025.wav leftovers).
- extract_audio now writes into MOMENTRY_TEMP_DIR (default ~/momentry/temp)
  with a unique per-run name (<stem>_asr_<millis>.wav) so concurrent jobs
  with the same basename cannot collide and mlx_whisper sidecar JSON is
  unique as well.
- TempAudioGuard removes the temp wav + /tmp/<stem>.json sidecar on every
  exit path (success, early bail, error).
- Verified: /library source dir stays clean, temp dir empty after run.
2026-11-09 12:15:30 +08:00
Accusys c1ede4ade8 fix: rust_asr_asrx handles MLX Whisper non-finite JSON literals
- MLX Whisper emits 'avg_logprob: NaN' / 'compression_ratio: Infinity' when a
  clip has no intelligible audio (e.g. near-silent test clips). serde_json
  strictly refuses those literals, so rust_asr_asrx failed with
  'expected value at line 1 column 151' and asrx never completed.
- Sanitize NaN / Infinity / -Infinity literals outside strings into null
  before parsing (sanitize_json_nonfinite).
- Add no-audio-track early-out. Clean up .wav byproduct after success.

Verified on dev (m5max48): 002.mp4 asrx re-scan now completes and produces
output/df6376c8....asrx.json; processor_results asrx = completed.
2026-11-09 12:02:19 +08:00
Accusys 5caecb887f fix: rebuild binary without MongoDB health check dependency
- Removed check_mongodb() from health.rs
- Health endpoint now depends only on PostgreSQL + Redis + Qdrant
- Regenerated .sqlx offline query cache (was incomplete, only 3 files)
- Binary rebuilt: target/release/momentry (47M, arm64)
- Deployed to 203 (m4promini)

Full clean-install + sample data install verified:
- clean-install.sh: ✅ (23 PASS / 0 FAIL)
- sample data: ✅ 100 videos, 899 processor_results, 100 monitor_jobs
- Health endpoint: status=ok (no MongoDB hang)
2026-11-08 23:39:53 +08:00
Accusys 4f4aa27da8 refactor: remove MongoDB from health check
- Removed check_mongodb() function from health.rs
- Health endpoint no longer requires MongoDB (status depends on PG+Redis+Qdrant only)
- ServiceHealth struct: mongodb field commented out
- Both health() and health_detailed() updated
- Removed MongoCache import

Note: Binary rebuild blocked by missing .sqlx cache files for
command/queue.rs and vlm/consumer.rs. Once build env is fixed:
  cd momentry_core && SQLX_OFFLINE=true cargo build --release
  cp target/release/momentry ../momentry/bin/momentry
2026-11-08 23:24:02 +08:00
Accusys c6cbb5d1fb feat: asrx recovery + pipeline fixes + face trace improvements
- ASR-ASRX unified processor (asr_asrx → asrx), output .asrx.json
- ffmpeg -vsync → -fps_mode (swift_ocr, swift_hand, swift_pose, frame_cache)
- ffprobe absolute path for probe
- PYTHONPATH + PATH added to executor subprocesses
- cut processor path fix (cut/cut_processor.py)
- scene_vlm fallback when blur_scores empty + ffmpeg absolute path
- rust_store_traced_faces generates key_face.jpg with --video-path
- face group representative trace picks highest best_confidence
- Studio: move FS doesn't remove from unassigned, always reload after move
- Studio: confirmMoveFaceToNewGroup simplified to just rename
- Studio: scene_vlm added to processors list
- Studio: scene_vlm shows (0) when ready but no scenes
- admin_config asr_config block added
2026-11-06 10:00:24 +08:00
Accusys e56e2892d0 docs: gitea sync section - correct repo to m4mini warren/momentry_core (110.200 host defunct) 2026-11-05 16:14:22 +08:00
Accusys be3837ff06 feat: asrx garbled text recovery - first-sentence trigger, config-driven language rotation, VLM audio rescue
- rust_asr_asrx: 3-layer recovery (auto → language rotation → VLM second
  reference via llama.cpp input_audio); rotation order loaded from
  admin_config.json asr_config block (no hard code); skips silent retry
  when asr_config absent (= current behavior)
- output adds recovery{} block (attempts/final_result/no_intelligible_speech)
- pipeline_flows: fix skip_if_exists *.asr_asrx.json -> *.asrx.json
  (actual output name; prevents redundant re-ASR on reprocess)
- design note: docs_v1.0/DESIGN/ASRX_Garbled_Text_Language_Rotation_V1.0.md
- verified on demo 004 (auto_ok, zero cost) / 020 (rotation_hit ja) /
  forced all-miss rotation (no_intelligible_speech via VLM refusal signal)
2026-11-05 16:13:55 +08:00
Accusys 0cbb024411 feat: add ASR garbled text detection and retry mechanism
- Add is_garbled() function to detect transcription errors:
  * Repetitive character detection (>40% same char)
  * Language-script mismatch detection
  * Compression ratio check for long text
- Expand COMMON_LANGUAGES fallback list: ja, en, zh, ko, th, vi, fr, de, es
- Add get_vad_settings() to disable VAD for short audio (<15s)
- Fix VAD filter causing 0 segments for short clips
- Improve language detection retry logic with garbled output check

Fixes: ASR producing garbled Sinhala text for Japanese audio
2026-11-05 04:52:32 +08:00
Accusys ada49d3491 fix: add DISTINCT ON to cluster-results handler to prevent duplicate group cards 2026-11-02 18:59:54 +08:00
Accusys eebaa11bfb fix: prevent duplicate face group cards - deduplicate tkg_nodes and DISTINCT ON in get_face_groups_handler 2026-11-02 17:30:29 +08:00
Accusys 6c85d2e871 feat: add upgrade_face_json_v2.sh and sync_face_data.sh scripts, fix SQLite path 2026-11-02 17:00:20 +08:00
Accusys f67219fe02 feat: add face_operations.rs SQLite module for face pipeline state management 2026-11-02 16:50:54 +08:00
Accusys 774ad4d820 feat: rust_store_traced_faces v2 schema - FaceTracedData with schema_version, stats, traces as Vec, TracePoint with timestamp/pose/landmarks 2026-11-02 15:52:11 +08:00
Accusys adcc5a1dc1 feat: face_tracker v2 schema - add schema_version, TraceBBox with x2/y2/center, TracePoint with pose/landmarks 2026-11-02 14:51:31 +08:00
Accusys 5d18183d82 feat: Face JSON v2 schema - add schema_version, bbox x2/y2/center, keep embeddings, update clustering 2026-11-02 14:34:02 +08:00
Accusys 2fca49b120 fix: update tkg_nodes.label when face_track node already exists
- ensure_face_track_node now UPDATEs label instead of returning early
- Fixes rename persistence - names are now stored in database
- Enables consistent names across all access points (localhost, DDNS)
2026-10-30 22:47:16 +08:00
Accusys b1bc83586f fix: fallback to MarkBase data for file_size and modified_time
- When videos table has null values, use MarkBase file info as fallback
- Ensures registered files display correct size and date
- Fixes issue where registered files showed '0B' and no date
2026-10-30 12:50:58 +08:00
801 changed files with 364496 additions and 2925 deletions
+5
View File
@@ -0,0 +1,5 @@
# Docserver Configuration
DOCSERVER_PORT=8000
DOCSERVER_USER=admin
DOCSERVER_PASSWORD=admin123
MOMENTRY_DOCS_DIR=/Users/accusys/momentry_core/docs_v1.0/doc_wasm
+46
View File
@@ -0,0 +1,46 @@
---
name: Cross-Project Bug
about: 跨專案 Bug 會診
title: ''
labels: type:bug, cross-project
assignees: ''
---
## Bug 描述
## 影響專案
- [ ] markbase
- [ ] MarkBaseEngine
- [ ] momentry_core
- [ ] momentry_studio
## 重現步驟
1.
2.
3.
## 預期行為
## 實際行為
## 影響分析
| 層級 | 影響 | 緊急度 |
|------|------|--------|
| 使用者 | | 🔴/🟡/🟢 |
| 資料 | | 🔴/🟡/🟢 |
| 服務 | | 🔴/🟡/🟢 |
## 會診團隊
| 專案 | 負責人 | 狀態 |
|------|--------|------|
| markbase | @ | |
| MarkBaseEngine | @ | |
| momentry_core | @ | |
| momentry_studio | @ | |
## 修復方案
## 驗證結果
- [ ] Sandbox 測試通過
- [ ] CI/CD 通過
- [ ] 手動測試通過
+17
View File
@@ -0,0 +1,17 @@
---
name: Feature Request
about: 新功能需求
title: ''
labels: type:feature
assignees: ''
---
## 功能描述
## 使用場景
## 驗收標準
- [ ] 標準 1
- [ ] 標準 2
## 技術方案 (可選)
+29
View File
@@ -0,0 +1,29 @@
---
name: Requirement
about: 跨專案需求
title: ''
labels: type:requirement
assignees: ''
---
## 需求名稱
## 影響專案
- [ ] markbase
- [ ] MarkBaseEngine
- [ ] momentry_core
- [ ] momentry_studio
## 需求描述
## API 變更 (如適用)
## 資料庫變更 (如適用)
## 驗收標準
- [ ] 標準 1
- [ ] 標準 2
## 依賴 Issue
- Blocks #
- Related to #
+20
View File
@@ -0,0 +1,20 @@
name: Core Test
on:
push:
branches: [main, develop]
paths: ['src/**', 'Cargo.toml']
pull_request:
branches: [main]
jobs:
lint-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@stable
- name: Cargo fmt
run: cargo fmt -- --check
- name: Cargo clippy
run: cargo clippy -- -D warnings
- name: Cargo test
run: cargo test --lib
+23
View File
@@ -0,0 +1,23 @@
name: Cross-Project Integration
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
integration:
runs-on: self-hosted
steps:
- uses: actions/checkout@v3
- name: Setup Sandbox
run: ./scripts/setup_sandbox.sh
- name: Build All
run: ./scripts/build_all.sh
- name: Start Services
run: ./scripts/start_services.sh
- name: Run Integration Tests
run: ./scripts/run_integration_tests.sh
- name: Cleanup
if: always()
run: ./scripts/cleanup_sandbox.sh
+22
View File
@@ -0,0 +1,22 @@
name: Release
on:
push:
tags: ['v*']
jobs:
build-and-release:
runs-on: self-hosted
steps:
- uses: actions/checkout@v3
- name: Build Release
run: cargo build --release
- name: Run Full Tests
run: cargo test
- name: Create Release
run: |
cp target/release/momentry ./momentry-${{ github.ref_name }}
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: momentry-${{ github.ref_name }}
path: momentry-${{ github.ref_name }}
@@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_requests\n SET \n status = 'completed',\n result = $1,\n processing_time_ms = $2,\n completed_at = NOW()\n WHERE id = $3\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Int8",
"Int8"
]
},
"nullable": []
},
"hash": "0373b02cc8de069f6e964bc023c4e29497cb66f8b0a181bafa73f175454e6903"
}
@@ -0,0 +1,27 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO command_queue (\n message_id, queue_name, queue_type,\n command_type, command_category,\n key, value, priority,\n request_id, key_id, billing_context,\n scheduled_at, max_retries,\n created_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Jsonb",
"Int2",
"Varchar",
"Varchar",
"Jsonb",
"Timestamptz",
"Int4",
"Timestamptz"
]
},
"nullable": []
},
"hash": "08adb7aafb3214ab7740baabcb6db8901c80dc5357008cd984f50d497fd416a2"
}
@@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT status, result, error\n FROM vlm_requests\n WHERE id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "status",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "result",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "error",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
true,
true
]
},
"hash": "1083cb140d49eed76e1f5081b88cbdca34f59052571490635dc8b1fdca3b1bd3"
}
@@ -1,15 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE dev.videos SET processing_status = $1 WHERE uuid = $2",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Jsonb",
"Text"
]
},
"nullable": []
},
"hash": "2d61eacd106ad5144c99a85c84f070924af9b29103a507e115674d1b14b77181"
}
@@ -1,14 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE dev.jobs SET status = 'COMPLETED', processed_frames = total_frames, updated_at = NOW() WHERE id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": []
},
"hash": "345d912734b063a7b30d52c066045553964d0a55453a7e26a4d8b8d758be3857"
}
@@ -0,0 +1,50 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT command_type, command_category, queue_name, handler, priority, billing_required\n FROM queue_routes\n WHERE active = true\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "command_type",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "command_category",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "queue_name",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "handler",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "priority",
"type_info": "Int2"
},
{
"ordinal": 5,
"name": "billing_required",
"type_info": "Bool"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
false,
false,
true,
true
]
},
"hash": "392a5b8ec9b3f9cf1736d47eeecaa1fe87ffa62024146c3d2c37bf028d954b3f"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_consumer_offsets\n SET current_offset = $1, last_poll_at = NOW()\n WHERE consumer_id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "3d7027dffb815b8a40e5525c9065bdd3173ff567cf8b7b299ad56f5b4cfb49de"
}
@@ -0,0 +1,18 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE command_queue\n SET status = $2,\n processing_completed_at = $3,\n token_usage = $4,\n cost_usd = $5\n WHERE message_id = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Varchar",
"Timestamptz",
"Jsonb",
"Float8"
]
},
"nullable": []
},
"hash": "4580e475bf8395911bbf9b36660094cf4483a4d4dcbe3dc7b5437904aeb86780"
}
@@ -0,0 +1,24 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO vlm_requests (request_type, priority, payload, status)\n VALUES ($1, $2, $3, 'pending')\n RETURNING id\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Varchar",
"Int4",
"Jsonb"
]
},
"nullable": [
false
]
},
"hash": "5bc08af47af66dc518afee2939f2fb33ea3384c63226fc474043346225923fcc"
}
@@ -0,0 +1,164 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE command_queue\n SET status = 'processing',\n consumer_group = $1,\n consumer_id = $2,\n processing_started_at = NOW(),\n timeout_at = NOW() + ($5::bigint * INTERVAL '1 second')\n WHERE message_id IN (\n SELECT message_id\n FROM command_queue\n WHERE queue_name = $3\n AND status = 'pending'\n AND (scheduled_at IS NULL OR scheduled_at <= NOW())\n ORDER BY priority ASC, created_at ASC\n LIMIT $4\n FOR UPDATE SKIP LOCKED\n )\n RETURNING\n message_id, queue_name, queue_type,\n command_type, command_category, command_action,\n key, value, priority,\n request_id, key_id, billing_context, token_usage, cost_usd,\n status, consumer_group, consumer_id,\n retry_count, max_retries, last_error,\n created_at, scheduled_at, processing_started_at, processing_completed_at\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "message_id",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "queue_name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "queue_type",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "command_type",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "command_category",
"type_info": "Varchar"
},
{
"ordinal": 5,
"name": "command_action",
"type_info": "Varchar"
},
{
"ordinal": 6,
"name": "key",
"type_info": "Varchar"
},
{
"ordinal": 7,
"name": "value",
"type_info": "Jsonb"
},
{
"ordinal": 8,
"name": "priority",
"type_info": "Int2"
},
{
"ordinal": 9,
"name": "request_id",
"type_info": "Varchar"
},
{
"ordinal": 10,
"name": "key_id",
"type_info": "Varchar"
},
{
"ordinal": 11,
"name": "billing_context",
"type_info": "Jsonb"
},
{
"ordinal": 12,
"name": "token_usage",
"type_info": "Jsonb"
},
{
"ordinal": 13,
"name": "cost_usd",
"type_info": "Float8"
},
{
"ordinal": 14,
"name": "status",
"type_info": "Varchar"
},
{
"ordinal": 15,
"name": "consumer_group",
"type_info": "Varchar"
},
{
"ordinal": 16,
"name": "consumer_id",
"type_info": "Varchar"
},
{
"ordinal": 17,
"name": "retry_count",
"type_info": "Int4"
},
{
"ordinal": 18,
"name": "max_retries",
"type_info": "Int4"
},
{
"ordinal": 19,
"name": "last_error",
"type_info": "Text"
},
{
"ordinal": 20,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 21,
"name": "scheduled_at",
"type_info": "Timestamptz"
},
{
"ordinal": 22,
"name": "processing_started_at",
"type_info": "Timestamptz"
},
{
"ordinal": 23,
"name": "processing_completed_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Text",
"Int8",
"Int8"
]
},
"nullable": [
false,
false,
false,
false,
true,
true,
true,
false,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true
]
},
"hash": "5f27ef47fc166a0bb8f8a26ccbd7418710e3bbb280af10935ffb2eddffcd33e4"
}
@@ -1,15 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE dev.jobs SET status = 'FAILED', error_message = $2, updated_at = NOW() WHERE id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Text"
]
},
"nullable": []
},
"hash": "60cc008705cfea3a4532b9496db8f6ed0e3023436660bdf8ee81fe78fe270971"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_requests\n SET status = 'processing', started_at = NOW()\n WHERE id = ANY($1)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8Array"
]
},
"nullable": []
},
"hash": "66ef83b7ad3fe95922fb2aa9a083ed55b14c5b4d7dd6b9ada1659d6060780533"
}
@@ -0,0 +1,24 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO vlm_requests (request_type, priority, payload, status)\n VALUES ($1, $2, $3, 'pending')\n RETURNING id\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Varchar",
"Int4",
"Jsonb"
]
},
"nullable": [
false
]
},
"hash": "748de226872459680cdd121b4b27369b73ae2edfeb9c75c03f1b8e240cb55f0c"
}
@@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO command_execution_log (\n message_id, handler, action, status,\n result, error_message,\n duration_ms, tokens_used, cost_usd,\n executed_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Jsonb",
"Text",
"Int4",
"Int4",
"Float8",
"Timestamptz"
]
},
"nullable": []
},
"hash": "7b3d7e7af47f2f91193229925454e22e1ef1a8fec81174092b926880ca36a118"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_requests\n SET status = 'failed', error = $1, completed_at = NOW()\n WHERE id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Int8"
]
},
"nullable": []
},
"hash": "7d4e34cc4505455b678b45b2f884021a6cf786e0e86d8f15f1b324e6a8bcfac9"
}
@@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE command_queue\n SET status = 'failed',\n processing_completed_at = $3,\n last_error = $2,\n retry_count = retry_count + 1\n WHERE message_id = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text",
"Timestamptz"
]
},
"nullable": []
},
"hash": "89d0f71757cf23b1a02923e97ed0c1921cafbdd69844e43c41c00222d5595f18"
}
@@ -0,0 +1,17 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_consumer_offsets\n SET \n total_processed = total_processed + $1,\n total_succeeded = total_succeeded + $2,\n total_failed = total_failed + $3\n WHERE consumer_id = $4\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8",
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "8fb9ba962eb0fc70bca83f7523afe081285a79aacaf5821d2e41f7539c57ced6"
}
@@ -0,0 +1,19 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO vlm_dlq (original_id, original_request_type, original_priority, original_payload, error, retry_count)\n VALUES ($1, $2, $3, $4, $5, $6)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Varchar",
"Int4",
"Jsonb",
"Text",
"Int4"
]
},
"nullable": []
},
"hash": "961e59ccb11c4e1674573d1e55e61dea1aa9eb9c78e506ba42aa1a42b891bf27"
}
@@ -0,0 +1,160 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n message_id, queue_name, queue_type,\n command_type, command_category, command_action,\n key, value, priority,\n request_id, key_id, billing_context, token_usage, cost_usd,\n status, consumer_group, consumer_id,\n retry_count, max_retries, last_error,\n created_at, scheduled_at, processing_started_at, processing_completed_at\n FROM command_queue\n WHERE message_id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "message_id",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "queue_name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "queue_type",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "command_type",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "command_category",
"type_info": "Varchar"
},
{
"ordinal": 5,
"name": "command_action",
"type_info": "Varchar"
},
{
"ordinal": 6,
"name": "key",
"type_info": "Varchar"
},
{
"ordinal": 7,
"name": "value",
"type_info": "Jsonb"
},
{
"ordinal": 8,
"name": "priority",
"type_info": "Int2"
},
{
"ordinal": 9,
"name": "request_id",
"type_info": "Varchar"
},
{
"ordinal": 10,
"name": "key_id",
"type_info": "Varchar"
},
{
"ordinal": 11,
"name": "billing_context",
"type_info": "Jsonb"
},
{
"ordinal": 12,
"name": "token_usage",
"type_info": "Jsonb"
},
{
"ordinal": 13,
"name": "cost_usd",
"type_info": "Float8"
},
{
"ordinal": 14,
"name": "status",
"type_info": "Varchar"
},
{
"ordinal": 15,
"name": "consumer_group",
"type_info": "Varchar"
},
{
"ordinal": 16,
"name": "consumer_id",
"type_info": "Varchar"
},
{
"ordinal": 17,
"name": "retry_count",
"type_info": "Int4"
},
{
"ordinal": 18,
"name": "max_retries",
"type_info": "Int4"
},
{
"ordinal": 19,
"name": "last_error",
"type_info": "Text"
},
{
"ordinal": 20,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 21,
"name": "scheduled_at",
"type_info": "Timestamptz"
},
{
"ordinal": 22,
"name": "processing_started_at",
"type_info": "Timestamptz"
},
{
"ordinal": 23,
"name": "processing_completed_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false,
false,
true,
true,
true,
false,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true
]
},
"hash": "a09f617a37776df57c4e711b25e62075db983095764bb5f2bae1e3dfddc3b243"
}
@@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT \n id as offset,\n request_type,\n priority,\n payload\n FROM vlm_requests\n WHERE status = 'pending'\n ORDER BY priority ASC, created_at ASC\n LIMIT $1\n FOR UPDATE SKIP LOCKED\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "offset",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "request_type",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "priority",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "payload",
"type_info": "Jsonb"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
true,
false
]
},
"hash": "ab09a5b7e35daf5fa5085ce9a986c9d58de60f4b9ffc0a127a7d17694d42277a"
}
@@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, request_type, payload, retry_count, priority\n FROM vlm_requests\n WHERE id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "request_type",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "payload",
"type_info": "Jsonb"
},
{
"ordinal": 3,
"name": "retry_count",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "priority",
"type_info": "Int4"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
false,
true,
true
]
},
"hash": "ec65769979d98dae69f4bb8ef280bb55ec401b86eaa01e80e63833654125733d"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_requests\n SET \n status = 'pending',\n retry_count = retry_count + 1,\n error = $1\n WHERE id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Int8"
]
},
"nullable": []
},
"hash": "fff0adae6b82b647111a1d27ac7c0a9e15311a8bacd4c1a5b7229e511df45954"
}
+12 -7
View File
@@ -936,14 +936,19 @@ shellcheck scripts/*.sh monitor/**/*.sh
## Gitea Sync
主要 sync 管道為 Gitea:`http://192.168.110.200:3000/admin/momentry_core.git`
主要 sync 管道為 Gitea:`http://192.168.110.210:3000/warren/momentry_core.git`(m4mini)
> **2026-11-05 更正**:舊文檔記載的 `http://192.168.110.200:3000/admin/momentry_core.git`
> 已失效(主機無回應)。本機實際 remote 為 m4mini 的 `warren/momentry_core`,分支
> `feature/dynamic-concurrency-*` 為進行中工作分支。可用測試:
> `curl -s -u "warren:<TOKEN>" http://192.168.110.210:3000/api/v1/repos/warren/momentry_core`
### 產生 Access Token(首次設定)
```bash
# admin 帳號密碼為 AccusysTest!
TOKEN=$(curl -s -X POST "http://192.168.110.200:3000/api/v1/users/admin/tokens" \
-u "admin:AccusysTest!" \
# 登入 warren 帳號後於 API 產生 token(scopes: write:repository)
TOKEN=$(curl -s -X POST "http://192.168.110.210:3000/api/v1/users/warren/tokens" \
-u "warren:<PASSWORD>" \
-H "Content-Type: application/json" \
-d '{"name":"m5max128_push","scopes":["write:repository"]}' | jq -r '.sha1')
echo $TOKEN
@@ -953,11 +958,11 @@ echo $TOKEN
```bash
# 用 token 取代密碼
git remote add origin http://admin:TOKEN@192.168.110.200:3000/admin/momentry_core.git
git remote add origin http://warren:TOKEN@192.168.110.210:3000/warren/momentry_core.git
# 同步
git pull origin main
git push origin main
git pull origin feature/dynamic-concurrency-v1.3.4
git push origin feature/dynamic-concurrency-v1.3.4
```
### Token 記錄
Generated
+24
View File
@@ -2470,6 +2470,7 @@ dependencies = [
"dotenv",
"env_logger",
"ferrous-opencc",
"flate2",
"futures-util",
"hex",
"jieba-rs",
@@ -2494,6 +2495,7 @@ dependencies = [
"sqlx 0.8.6",
"subtle",
"sysinfo",
"tar",
"tempfile",
"thiserror 1.0.69",
"tokio",
@@ -2506,6 +2508,7 @@ dependencies = [
"utoipa",
"utoipa-swagger-ui",
"uuid",
"walkdir",
]
[[package]]
@@ -4625,6 +4628,17 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -6029,6 +6043,16 @@ dependencies = [
"tap",
]
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.4",
]
[[package]]
name = "xxhash-rust"
version = "0.8.15"
+7
View File
@@ -86,6 +86,9 @@ crossterm = "0.28"
# Terminal
atty = "0.2"
tokio-util = { version = "0.7.18", features = ["io"] }
walkdir = "2.5.0"
flate2 = "1.0"
tar = "0.4"
# System
@@ -133,6 +136,10 @@ path = "src/bin/test_bm25_simple.rs"
name = "integrated_player"
path = "src/bin/integrated_player.rs"
[[bin]]
name = "docserver"
path = "src/bin/docserver/main.rs"
[[bin]]
name = "pipeline_worker"
path = "src/bin/pipeline_worker.rs"
+59
View File
@@ -0,0 +1,59 @@
# 移除 MongoDB 依賴 — 變更說明
## 問題
m5max128 (192.168.110.200) 的 `/api/v1/health` 端點掛住,因為 health check
等待 MongoDB 連線回應,但該機器未安裝 MongoDB。
## 修改內容
### `src/api/health.rs`
| 變更 | 說明 |
|---|---|
| 移除 `MongoCache` import | 不再需要 MongoDB 型別 |
| 移除 `check_mongodb()` 函數 | 不再檢查 MongoDB 健康狀態 |
| `health()` 函數 | `all_ok` 條件改為只檢查 PostgreSQL + Redis + Qdrant |
| `health_detailed()` 函數 | 同上,移除 MongoDB 檢查 |
| `ServiceHealth` struct | `mongodb` 欄位註解化 |
### 影響範圍
- Health 端點不再依賴 MongoDB
- `AppState` 中的 `mongo_cache` 欄位仍保留(供其他功能使用)
- server.rs 中的 MongoDB 初始化(5 秒 timeout → disabled fallback)維持原樣
## 重新編譯
### 目前阻礙
`.sqlx/` 目錄只有 3 個查詢快取檔案,缺少:
- `command/queue.rs` 的查詢快取
- `vlm/consumer.rs` 的查詢快取
### 解決步驟
```bash
# 方法 1: 完整 .sqlx 快取(需要連線到 DB)
cd /Users/accusys/momentry_core
export DATABASE_URL="postgres://accusys@localhost:5432/momentry"
cargo sqlx prepare
SQLX_OFFLINE=true cargo build --release
# 方法 2: 修復現有查詢錯誤後再編譯
# 檢查 src/core/command/queue.rs 和 src/core/vlm/consumer.rs 的 sqlx 巨集
# 編譯完成後替換 binary
cp target/release/momentry ../momentry/bin/momentry
```
### 部署到 203 (m4promini)
```bash
scp target/release/momentry accusys@192.168.110.203:~/momentry/bin/momentry
ssh accusys@192.168.110.203 'launchctl stop com.momentry.server && launchctl start com.momentry.server'
```
## 驗證
重啟後測試:
```bash
curl -s -m 10 http://localhost:3002/api/v1/health
# 應回傳: {"status":"ok", ...} 而不是超時
```
## Git commit
`4f4aa27d` on branch `feature/dynamic-concurrency-v1.3.4`
Symlink
+1
View File
@@ -0,0 +1 @@
/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE
Symlink
+1
View File
@@ -0,0 +1 @@
/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE
+304 -103
View File
@@ -1,154 +1,355 @@
{
"filter_config": {
"face": {
"min_confidence": 0.5,
"min_size": 30
"version": "1.3.5",
"updated_at": "2026-11-15T12:00:00+0800",
"updated_by": "admin",
"vlm_prompts": {
"scene_vlm": {
"system_prompt": "You are a helpful assistant that analyzes video scenes.",
"user_prompt": "Describe this scene. What is happening? What objects and people are visible?",
"max_tokens": 200,
"description": "Scene analysis VLM prompt"
},
"rust_vlm_summary": {
"system_prompt": "You are a helpful assistant that describes people in images.",
"user_prompt": "Describe the person in this image. Focus on clothing, accessories, and distinctive features.",
"max_tokens": 300,
"description": "Face trace VLM prompt for person description"
},
"garbled_recovery": {
"system_prompt": "You are a helpful assistant that verifies speech transcription quality.",
"user_prompt": "Analyze this transcript for garbled text. Is it intelligible?",
"max_tokens": 100,
"description": "ASR garbled text recovery prompt"
}
},
"llm_config": {
"chat": {
"model": "gemma-4-12b-it",
"timeout": 30,
"url": "http://localhost:8080/v1/chat/completions"
},
"summary": {
"url": "http://127.0.0.1:8080/v1/chat/completions",
"model": "gemma-4-12b-it",
"timeout": 60,
"url": "http://localhost:8080/v1/chat/completions"
"fallbacks": [
"http://127.0.0.1:8082/v1/chat/completions"
],
"strategy": "priority",
"enabled": true
},
"vlm": {
"url": "http://127.0.0.1:8082/v1/chat/completions",
"model": "gemma-4-12b-it",
"timeout": 120,
"fallbacks": [
"http://127.0.0.1:8080/v1/chat/completions"
],
"strategy": "priority",
"enabled": false
},
"chat": {
"url": "http://127.0.0.1:8080/v1/chat/completions",
"model": "gemma-4-12b-it",
"timeout": 30,
"fallbacks": [
"http://127.0.0.1:8082/v1/chat/completions"
],
"strategy": "priority",
"enabled": true
},
"embedding": {
"url": "http://127.0.0.1:11436/v1/embeddings",
"model": "embeddinggemma",
"timeout": 60,
"fallbacks": [],
"strategy": "priority",
"enabled": true
}
},
"processor_config": {
"ASRX": {
"default_tool": "swift",
"enabled": true,
"timeout": 3600,
"tools": [
{
"enabled": true,
"name": "swift",
"parameters": {},
"priority": 0
}
]
},
"CUT": {
"default_tool": "rust",
"enabled": true,
"timeout": 3600,
"tools": [
{
"enabled": true,
"name": "rust",
"parameters": {},
"priority": 0
},
{
"enabled": true,
"name": "python",
"parameters": {},
"priority": 2
}
]
},
"FACE": {
"default_tool": "swift",
"enabled": true,
"timeout": 3600,
"enabled": true,
"tools": [
{
"enabled": true,
"name": "swift",
"parameters": {},
"priority": 0
"priority": 0,
"enabled": true,
"parameters": {}
},
{
"enabled": true,
"name": "python",
"parameters": {},
"priority": 2
}
]
},
"FACE_TRACE": {
"default_tool": "rust",
"enabled": true,
"timeout": 3600,
"tools": [
{
"priority": 2,
"enabled": true,
"name": "rust",
"parameters": {},
"priority": 0
},
{
"enabled": true,
"name": "python",
"parameters": {},
"priority": 1
"parameters": {}
}
]
],
"default_tool": "swift"
},
"OCR": {
"default_tool": "swift",
"enabled": true,
"timeout": 3600,
"enabled": true,
"tools": [
{
"enabled": true,
"name": "swift",
"parameters": {},
"priority": 0
"priority": 0,
"enabled": true,
"parameters": {}
}
]
],
"default_tool": "swift"
},
"CUT": {
"timeout": 3600,
"enabled": true,
"tools": [
{
"name": "rust",
"priority": 0,
"enabled": true,
"parameters": {}
},
{
"name": "python",
"priority": 2,
"enabled": true,
"parameters": {}
}
],
"default_tool": "rust"
},
"ASRX": {
"timeout": 3600,
"enabled": true,
"tools": [
{
"name": "swift",
"priority": 0,
"enabled": true,
"parameters": {}
}
],
"default_tool": "swift"
},
"FACE_TRACE": {
"timeout": 3600,
"enabled": true,
"tools": [
{
"name": "rust",
"priority": 0,
"enabled": true,
"parameters": {}
},
{
"name": "python",
"priority": 1,
"enabled": true,
"parameters": {}
}
],
"default_tool": "rust"
},
"FACE_CLUSTER": {
"timeout": 3600,
"enabled": true,
"tools": [
{
"name": "rust",
"priority": 0,
"enabled": true,
"parameters": {}
}
],
"default_tool": "rust"
},
"SCENE_VLM": {
"timeout": 7200,
"enabled": true,
"tools": [
{
"name": "python",
"priority": 0,
"enabled": true,
"parameters": {}
}
],
"default_tool": "python"
},
"POSE": {
"default_tool": "swift",
"enabled": true,
"timeout": 3600,
"enabled": true,
"tools": [
{
"enabled": true,
"name": "swift",
"parameters": {},
"priority": 0
"priority": 0,
"enabled": true,
"parameters": {}
},
{
"enabled": true,
"name": "rust",
"parameters": {},
"priority": 1
"priority": 1,
"enabled": true,
"parameters": {}
},
{
"enabled": true,
"name": "mediapipe",
"priority": 2,
"enabled": true,
"parameters": {
"min_confidence": 0.5,
"model_complexity": 2
},
"priority": 2
}
}
]
],
"default_tool": "swift"
}
},
"filter_config": {
"face": {
"min_confidence": 0.5,
"min_size": 30,
"min_capture_quality": 0.25
}
},
"face_filter_defaults": {
"min_confidence": 50.0,
"min_size": 1,
"min_capture_quality": 0.25
},
"paths": {
"output_dir": "/Users/accusys/momentry/output/demo",
"backup_dir": "/Users/accusys/momentry/var/backup",
"scripts_dir": "/Users/accusys/momentry/scripts",
"cli_dir": "/Users/accusys/momentry/tools/cli",
"python_path": "/opt/homebrew/bin/python3.11",
"ffmpeg_path": "/opt/homebrew/bin/ffmpeg"
},
"concurrency": {
"max_concurrent_jobs": 2,
"poll_interval": 5,
"batch_size": 5,
"processor_timeout_secs": 3600
},
"feature_flags": {
"cache_enabled": true,
"auto_pipeline_enabled": false,
"watcher_auto_register": false,
"summary_enabled": true
},
"server": {
"port": 3002,
"media_base_url": "http://localhost:8888",
"serve_base_url": "http://localhost:8888",
"storage_root": "/Users/accusys/momentry/var/sftpgo/data",
"timezone": "Asia/Taipei"
},
"admin_settings": {
"session_timeout": 3600,
"max_login_attempts": 5,
"api_key_expiry_days": 365,
"system_stats_refresh_sec": 5,
"preferred_language": "en",
"library_default_sort": "name_asc"
},
"search": {
"vlm_max_results": 5,
"vlm_min_score": 0,
"vlm_min_score": 0.0,
"vlm_output_language": "ja"
},
"system_config": {},
"version": "1.0.0",
"vlm_prompts": {
"rust_vlm_summary": {
"description": "Face trace VLM prompt for person description",
"max_tokens": 300,
"system_prompt": "You are a helpful assistant that describes people in images.",
"user_prompt": "Describe the person in this image. Focus on clothing, accessories, and distinctive features."
},
"scene_vlm": {
"description": "Scene analysis VLM prompt",
"max_tokens": 200,
"system_prompt": "You are a helpful assistant that analyzes video scenes.",
"user_prompt": "Describe this scene. What is happening? What objects and people are visible?"
"pipeline": {
"enabled": true,
"max_concurrent_stages": 5,
"default_timeout_secs": 7200,
"flows": {
"register": {
"name": "register",
"description": "Full registration pipeline: all processors",
"version": "1.0",
"enabled": true,
"stages": [
{
"name": "probe",
"processor_type": "probe",
"required": false,
"enabled": true,
"timeout_secs": 300
},
{
"name": "cut",
"processor_type": "cut",
"required": true,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "face",
"processor_type": "face",
"required": false,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "ocr",
"processor_type": "ocr",
"required": false,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "asrx",
"processor_type": "asrx",
"required": false,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "scene_vlm",
"processor_type": "scene_vlm",
"required": false,
"enabled": true,
"timeout_secs": 7200
},
{
"name": "face_trace",
"processor_type": "face_trace",
"required": false,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "face_cluster",
"processor_type": "face_cluster",
"required": false,
"enabled": true,
"timeout_secs": 3600
}
]
},
"reindex": {
"name": "reindex",
"description": "Re-index pipeline: chunks + vectors + TKG",
"version": "1.0",
"enabled": true,
"stages": [
{
"name": "chunk",
"processor_type": "chunk",
"required": true,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "vectorize",
"processor_type": "vectorize",
"required": true,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "tkg",
"processor_type": "tkg",
"required": false,
"enabled": true,
"timeout_secs": 7200
}
]
}
}
}
}
+1 -1
View File
@@ -120,7 +120,7 @@
"usage_notes": "Combines ASR and Diarization in one processor. Uses verified whisper-small-mlx model."
},
"condition": {
"skip_if_exists": "*.asr_asrx.json"
"skip_if_exists": "*.asrx.json"
},
"on_failure": "continue"
},
+4 -2
View File
@@ -80,7 +80,7 @@
"parameters": {
"model_dir": "/Users/accusys/models/whisper-small-mlx"
},
"output_file": "{file_uuid}.asr_asrx.json",
"output_file": "{file_uuid}.asrx.json",
"timeout": 3600
}
],
@@ -158,7 +158,9 @@
"--min-trace-len",
"{min_trace_len}",
"--min-confidence",
"{min_confidence}"
"{min_confidence}",
"--video-path",
"{video_path}"
]
},
"parameters": {
+3 -3
View File
@@ -8,6 +8,6 @@ deploy:
@echo "Building WASM doc..."
cd ../../md_wasm && wasm-pack build --target no-modules --no-opt 2>&1 | tail -2
cp ../../md_wasm/pkg/md_wasm_bg.wasm ../doc_wasm/pkg/
cp ../../docs_v1.0/API_WORKSPACE/modules/0*.md ../doc_wasm/modules/
cp ../../docs_v1.0/API_WORKSPACE/modules/1*.md ../doc_wasm/modules/
@echo " ✅ Updated ../doc_wasm/ (WASM docs)"
@echo "Syncing ALL API modules..."
cp ../../docs_v1.0/API_WORKSPACE/modules/*.md ../doc_wasm/modules/
@echo " ✅ Updated ../doc_wasm/ (WASM docs) - ALL modules included"
+196 -48
View File
@@ -1,60 +1,208 @@
# API Workspace
---
title: API Documentation Index
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
## Purpose
# API Documentation Index
This directory is the **single source of truth** for all API documentation modules.
Generated outputs go to `../GUIDES/` as assembled deliverable documents.
Complete API reference for Momentry Core. All endpoints are documented with request/response formats, examples, and error handling.
## Workflow
---
## 📋 Module Overview
### Core APIs (01-19)
| Module | File | Description |
|--------|------|-------------|
| **01** | [auth.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/01_auth.md) | Authentication - login, logout, JWT, API key |
| **02** | [health.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/02_health.md) | Health check endpoints |
| **03** | [register.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/03_register.md) | File registration |
| **04** | [lookup.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/04_lookup.md) | File lookup and metadata |
| **05** | [process.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/05_process.md) | Video processing pipeline |
| **06** | [search.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/06_search.md) | Search operations |
| **07** | [identity.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/07_identity.md) | Identity management |
| **08** | [identity_agent.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/08_identity_agent.md) | Identity agent operations |
| **08** | [media.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/08_media.md) | Media access and proxy |
| **09** | [tmdb.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/09_tmdb.md) | TMDb integration |
| **10** | [pipeline.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/10_pipeline.md) | Pipeline management |
| **11** | [error_codes.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/11_error_codes.md) | Error code reference |
| **12** | [agent.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/12_agent.md) | Agent API |
| **13** | [config.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/13_config.md) | Configuration management |
| **14** | [identity_history.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/14_identity_history.md) | Identity history tracking |
| **15** | [tkg.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/15_tkg.md) | Temporal Knowledge Graph |
| **16** | [workspace.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/16_workspace.md) | Workspace management |
| **17** | [progress.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/17_progress.md) | Progress tracking |
| **18** | [profile.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/18_profile.md) | File profile and metadata |
| **19** | [people_api.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md) | People management API |
---
### New APIs (20-24)
| Module | File | Description | Status |
|--------|------|-------------|--------|
| **20** | [service_management_api.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/20_service_management_api.md) | Service start/stop/health | ✅ P0 - Critical |
| **21** | [monitor_api.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_monitor_api.md) | Queue/Worker/Pipeline monitoring | ✅ P1 - Important |
| **22** | [trace_agent_api.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_trace_agent_api.md) | Trace and TKG operations | ✅ P1 - Important |
| **23** | [vlm_search_api.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/23_vlm_search_api.md) | Vision Language Model search | ✅ P1 - Important |
| **24** | [pose_appearance_api.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/24_pose_appearance_api.md) | Pose keypoints and appearance colors | ✅ P2 - Standard |
---
### Studio Team Guides (21-26)
| Module | File | Description |
|--------|------|-------------|
| **21** | [studio_team_guide.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md) | Integration guide for Studio team |
| **22** | [studio_pipeline_changes.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_studio_pipeline_changes.md) | Pipeline changes documentation |
| **23** | [studio_face_group_name_fix.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/23_studio_face_group_name_fix.md) | Face group name fix guide |
| **24** | [studio_trace_profile_read_write_bug.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/24_studio_trace_profile_read_write_bug.md) | Trace profile bug documentation |
| **25** | [face_filter_api.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/25_face_filter_api.md) | Face filtering API |
| **26** | [trace_thumbnail_regenerate.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/26_trace_thumbnail_regenerate.md) | Thumbnail regeneration |
---
### Additional Modules
| File | Description |
|------|-------------|
| [scene_vlm_stats_api.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/scene_vlm_stats_api.md) | Scene VLM statistics API |
| [99_incomplete.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/99_incomplete.md) | Incomplete features reference |
| [_template.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/_template.md) | Documentation template |
---
## 🔍 Quick Reference by Category
### Authentication & Security
- [Auth API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/01_auth.md) - Login, logout, JWT tokens, API keys
### File Operations
- [Register](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/03_register.md) - Register new files
- [Lookup](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/04_lookup.md) - File metadata and lookup
- [Process](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/05_process.md) - Video processing
- [Profile](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/18_profile.md) - File profile
### Search & Query
- [Search](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/06_search.md) - General search
- [VLM Search](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/23_vlm_search_api.md) - Vision Language Model search
- [TKG](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/15_tkg.md) - Temporal Knowledge Graph
### Identity & People
- [Identity](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/07_identity.md) - Identity management
- [Identity Agent](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/08_identity_agent.md) - Agent operations
- [Identity History](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/14_identity_history.md) - History tracking
- [People API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md) - People management
- [Trace Agent](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_trace_agent_api.md) - Trace operations
- [Pose & Appearance](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/24_pose_appearance_api.md) - Pose and appearance data
### System & Monitoring
- [Health](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/02_health.md) - Health checks
- [Service Management](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/20_service_management_api.md) - Service control
- [Monitor](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_monitor_api.md) - System monitoring
- [Progress](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/17_progress.md) - Progress tracking
- [Pipeline](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/10_pipeline.md) - Pipeline management
### Media & Content
- [Media](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/08_media.md) - Media access
- [TMDb](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/09_tmdb.md) - TMDb integration
### Configuration & Management
- [Config](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/13_config.md) - Configuration
- [Workspace](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/16_workspace.md) - Workspace management
- [Agent](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/12_agent.md) - Agent API
---
## 📖 Usage Guidelines
### Authentication
Most API endpoints require authentication via API key:
```bash
# 1. Edit a module
vim modules/09_tmdb.md
# 2. Preview the generated output
make _build/API_ENDPOINTS.md
# 3. Check diff against current GUIDES/ content
make check
# 4. Deploy to GUIDES/
make deploy
# 5. Regenerate all
make all
curl -H "X-API-Key: your-api-key" \
http://localhost:3002/api/v1/...
```
## Directory Structure
See [Auth API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/01_auth.md) for details.
```
API_WORKSPACE/
├── modules/ ← 11 module files (01_auth ... 11_error_codes)
├── configs/ ← 7 assembly recipies (.toml)
├── narratives/ ← narrative intros for specific output files
├── _build/ ← generated output (gitignored)
├── Makefile ← build targets
├── assemble_docs.sh ← assembly engine
└── README.md
```
### Base URLs
## Available `make` Targets
| Environment | Base URL |
|------------|----------|
| Production | `http://localhost:3002` |
| External | `https://m5api.momentry.ddns.net` |
| Development | `http://localhost:3003` |
| Target | Output |
|--------|--------|
| `make reference` | `_build/API_REFERENCE.md` |
| `make endpoints` | `_build/API_ENDPOINTS.md` |
| `make quickref` | `_build/API_QUICK_REFERENCE.md` |
| `make errors` | `_build/API_ERROR_CODES.md` |
| `make index` | `_build/API_INDEX.md` |
| `make marcom` | `_build/API_TRAINING_MARCOM.md` |
| `make tmdb` | `_build/TMDb_User_Guide.md` |
| `make all` | All of the above |
| `make deploy` | Copy `_build/*` → `../GUIDES/` |
| `make check` | `diff` against existing `../GUIDES/` files |
### Common Patterns
## Adding a New Endpoint
#### File Processing
1. Add the endpoint to the appropriate module (e.g., `modules/XX_files.md`)
2. Follow the template in `modules/_template.md`
3. `make all && make check`
4. `make deploy`
1. Register file: `POST /api/v1/register`
2. Process file: `POST /api/v1/process`
3. Check progress: `GET /api/v1/progress/{file_uuid}`
4. Search results: `GET /api/v1/search`
#### Identity Management
1. List identities: `GET /api/v1/identities`
2. Bind faces: `POST /api/v1/identities/{identity_uuid}/bind`
3. Search identities: `GET /api/v1/search/identities`
---
## 🔧 Development
### Adding New Endpoints
1. Use [_template.md](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/_template.md)
2. Follow naming convention: `NN_topic.md`
3. Add YAML frontmatter
4. Include complete examples
5. Add to this index
### Documentation Standards
All modules must include:
- ✅ YAML frontmatter
- ✅ Module metadata (module, description, depends)
- ✅ Endpoint documentation with examples
- ✅ Error codes
- ✅ Version history
---
## 📊 Statistics
| Metric | Count |
|--------|-------|
| **Total API Modules** | 31 |
| **Core APIs** | 20 |
| **New APIs** | 5 |
| **Studio Guides** | 6 |
| **Total Endpoints** | 100+ |
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial comprehensive API index |
---
**Last Updated**: 2026-10-24
**Maintained By**: Core Team
@@ -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 |
+1
View File
@@ -0,0 +1 @@
# This file ensures the CLI_WORKSPACE directory is tracked by Git
+116
View File
@@ -0,0 +1,116 @@
---
title: CLI Documentation
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
# Momentry CLI Documentation
## Overview
Momentry CLI provides command-line tools for video processing, identity management, search, and system administration.
## Command Categories
### File Processing
| Command | Module | Description |
|---------|--------|-------------|
| `register` | [101_CLI_Register.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/101_CLI_Register.md) | Register video files |
| `process` | [102_CLI_Process.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/102_CLI_Process.md) | Process registered files |
| `chunk` | [103_CLI_Chunk.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/103_CLI_Chunk.md) | Chunk processing |
| `store-asrx` | [104_CLI_StoreAsrx.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/104_CLI_StoreAsrx.md) | Store ASRX data |
| `story` | [105_CLI_Story.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/105_CLI_Story.md) | Story generation |
### Vision & Detection
| Command | Module | Description |
|---------|--------|-------------|
| `detect` | [106_CLI_Detect.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/106_CLI_Detect.md) | Object detection |
| `vision` | [107_CLI_Vision.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/107_CLI_Vision.md) | Vision processing |
| `vectorize` | [108_CLI_Vectorize.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/108_CLI_Vectorize.md) | Vectorization |
### Pipeline & Execution
| Command | Module | Description |
|---------|--------|-------------|
| `phase1` | [109_CLI_Phase1.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/109_CLI_Phase1.md) | Phase 1 pipeline |
| `complete` | [110_CLI_Complete.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/110_CLI_Complete.md) | Complete processing |
### Media & Playback
| Command | Module | Description |
|---------|--------|-------------|
| `play` | [111_CLI_Play.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/111_CLI_Play.md) | Media playback |
| `watch` | [112_CLI_Watch.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/112_CLI_Watch.md) | File watching |
### System & Administration
| Command | Module | Description |
|---------|--------|-------------|
| `system` | [113_CLI_System.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/113_CLI_System.md) | System commands |
| `server` | [114_CLI_Server.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/114_CLI_Server.md) | Server management |
| `worker` | [115_CLI_Worker.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/115_CLI_Worker.md) | Worker management |
| `query` | [116_CLI_Query.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/116_CLI_Query.md) | Query operations |
| `status` | [120_CLI_Status.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/120_CLI_Status.md) | Status checks |
| `backup` | [121_CLI_Backup.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/121_CLI_Backup.md) | Backup operations |
| `api-key` | [122_CLI_ApiKey.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/122_CLI_ApiKey.md) | API key management |
| `gitea` | [123_CLI_Gitea.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/123_CLI_Gitea.md) | Gitea operations |
### Lookup & Resolution
| Command | Module | Description |
|---------|--------|-------------|
| `lookup` | [117_CLI_Lookup.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/117_CLI_Lookup.md) | Lookup operations |
| `resolve` | [118_CLI_Resolve.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/118_CLI_Resolve.md) | Resolution |
| `thumbnails` | [119_CLI_Thumbnails.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/119_CLI_Thumbnails.md) | Thumbnail generation |
### Agent
| Command | Module | Description |
|---------|--------|-------------|
| `agent` | [124_CLI_Agent.md](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/124_CLI_Agent.md) | Agent operations |
## Usage Patterns
### Basic Pattern
```bash
momentry <command> [options] [arguments]
```
### Common Options
- `--help` - Show help for a command
- `--verbose` - Enable verbose output
- `--dry-run` - Preview without execution
### Examples
```bash
# Register a video
momentry register /path/to/video.mp4
# Process a registered file
momentry process --file-uuid <uuid>
# Start the server
momentry server --port 3002
# Query identities
momentry query identities --name "John"
```
## Related Documentation
- [API Documentation](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/README.md)
- [User Guides](/Users/accusys/momentry_core/docs_v1.0/GUIDES/)
- [Reference Documentation](/Users/accusys/momentry_core/docs_v1.0/REFERENCE/)
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial CLI documentation structure |
+140
View File
@@ -0,0 +1,140 @@
---
title: CLI Command Template
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
# {Command Name} — CLI Command Documentation
> Use this template when adding or editing CLI command documentation.
## Command Metadata
Every CLI command doc MUST start with:
```markdown
<!-- command: <command_name> -->
<!-- category: file_processing | vision_detection | pipeline | media | system | lookup | agent -->
<!-- related_api: <comma-separated list of related API endpoints> -->
```
## Command Template
### `momentry <command> [options] [arguments]`
**Category**: file_processing | vision_detection | pipeline | media | system | lookup | agent
**Purpose**: One-line description of what this command does.
#### Syntax
```bash
momentry <command> [required-args] [options]
```
#### Arguments
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `<arg1>` | string | Yes | Description |
| `<arg2>` | number | No | Description |
#### Options
| Option | Short | Type | Default | Description |
|--------|-------|------|---------|-------------|
| `--option1` | `-o` | string | — | Description |
| `--verbose` | `-v` | flag | false | Enable verbose output |
| `--dry-run` | `-d` | flag | false | Preview without execution |
| `--help` | `-h` | flag | — | Show help |
#### Examples
##### Basic Usage
```bash
# brief description
momentry <command> <argument>
```
##### With Options
```bash
# brief description
momentry <command> <argument> --option1 value
```
##### Common Patterns
```bash
# Pattern 1: Common use case
momentry <command> <arg1>
# Pattern 2: With verbose output
momentry <command> <arg1> --verbose
```
#### Output
**Success**:
```
Expected output format on success
```
**Error**:
```
Expected error message format
```
#### Exit Codes
| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General error |
| 2 | Invalid arguments |
| 3 | File not found |
#### Related API Endpoints
- `POST /api/v1/...` - Brief description
- `GET /api/v1/...` - Brief description
See also:
- [Related Command 1](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/XXX_CLI_Command1.md)
- [Related Command 2](/Users/accusys/momentry_core/docs_v1.0/CLI_WORKSPACE/modules/XXX_CLI_Command2.md)
#### Common Issues
##### Issue 1: Description
**Symptoms**: Error message or unexpected behavior
**Solution**: Steps to resolve
##### Issue 2: Description
**Symptoms**: Error message or unexpected behavior
**Solution**: Steps to resolve
## Rules
1. **Absolute Paths**: Use absolute paths in all examples
- ✅ `/Users/accusys/momentry_core/src/...`
- ❌ `src/...`
2. **Variables**: Use clear variable names in examples
- ✅ `$FILE_UUID`, `$IDENTITY_UUID`
- ❌ `$1`, `$2`
3. **Examples**: Include at least 3 examples
- Basic usage
- With options
- Common patterns
4. **Related Docs**: Link to related API and CLI docs using absolute paths
5. **File Naming**: `NNN_CLI_CommandName.md` where NNN = execution order (101-999)

Some files were not shown because too many files have changed in this diff Show More