Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 083d73d287 | |||
| d21d1ab960 | |||
| 043dbbf24a | |||
| 3d7ec83ec9 | |||
| 70f5667adc | |||
| 8ff77d7dba | |||
| c1ede4ade8 | |||
| 5caecb887f | |||
| 4f4aa27da8 | |||
| c6cbb5d1fb | |||
| e56e2892d0 | |||
| be3837ff06 |
+16
@@ -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"
|
||||
}
|
||||
+27
@@ -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"
|
||||
}
|
||||
+34
@@ -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"
|
||||
}
|
||||
-15
@@ -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"
|
||||
}
|
||||
-14
@@ -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"
|
||||
}
|
||||
+50
@@ -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"
|
||||
}
|
||||
+15
@@ -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"
|
||||
}
|
||||
+18
@@ -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"
|
||||
}
|
||||
+24
@@ -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"
|
||||
}
|
||||
+164
@@ -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"
|
||||
}
|
||||
-15
@@ -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"
|
||||
}
|
||||
+14
@@ -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"
|
||||
}
|
||||
+24
@@ -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"
|
||||
}
|
||||
+23
@@ -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"
|
||||
}
|
||||
+15
@@ -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"
|
||||
}
|
||||
+16
@@ -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"
|
||||
}
|
||||
+17
@@ -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"
|
||||
}
|
||||
+19
@@ -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"
|
||||
}
|
||||
+160
@@ -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"
|
||||
}
|
||||
+40
@@ -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"
|
||||
}
|
||||
+46
@@ -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"
|
||||
}
|
||||
+15
@@ -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"
|
||||
}
|
||||
@@ -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
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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`
|
||||
+230
-74
@@ -1,31 +1,65 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"updated_at": "2026-10-26T17:18:56.139925+00:00",
|
||||
"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"
|
||||
},
|
||||
"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"
|
||||
"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": {
|
||||
"url": "http://localhost:8080/v1/chat/completions",
|
||||
"model": "gemma-4-12b-it",
|
||||
"timeout": 30
|
||||
},
|
||||
"summary": {
|
||||
"url": "http://localhost:8080/v1/chat/completions",
|
||||
"url": "http://127.0.0.1:8080/v1/chat/completions",
|
||||
"model": "gemma-4-12b-it",
|
||||
"timeout": 60
|
||||
"timeout": 60,
|
||||
"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": {
|
||||
@@ -48,26 +82,7 @@
|
||||
],
|
||||
"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"
|
||||
},
|
||||
"POSE": {
|
||||
"OCR": {
|
||||
"timeout": 3600,
|
||||
"enabled": true,
|
||||
"tools": [
|
||||
@@ -76,21 +91,6 @@
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "mediapipe",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"min_confidence": 0.5,
|
||||
"model_complexity": 2
|
||||
}
|
||||
}
|
||||
],
|
||||
"default_tool": "swift"
|
||||
@@ -127,7 +127,52 @@
|
||||
],
|
||||
"default_tool": "swift"
|
||||
},
|
||||
"OCR": {
|
||||
"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": {
|
||||
"timeout": 3600,
|
||||
"enabled": true,
|
||||
"tools": [
|
||||
@@ -136,6 +181,21 @@
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "mediapipe",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"min_confidence": 0.5,
|
||||
"model_complexity": 2
|
||||
}
|
||||
}
|
||||
],
|
||||
"default_tool": "swift"
|
||||
@@ -144,7 +204,8 @@
|
||||
"filter_config": {
|
||||
"face": {
|
||||
"min_confidence": 0.5,
|
||||
"min_size": 30
|
||||
"min_size": 30,
|
||||
"min_capture_quality": 0.25
|
||||
}
|
||||
},
|
||||
"face_filter_defaults": {
|
||||
@@ -153,38 +214,39 @@
|
||||
"min_capture_quality": 0.25
|
||||
},
|
||||
"paths": {
|
||||
"output_dir": "",
|
||||
"backup_dir": "",
|
||||
"scripts_dir": "",
|
||||
"cli_dir": "",
|
||||
"python_path": "",
|
||||
"ffmpeg_path": ""
|
||||
"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": 0,
|
||||
"poll_interval": 0,
|
||||
"batch_size": 0,
|
||||
"processor_timeout_secs": 0
|
||||
"max_concurrent_jobs": 2,
|
||||
"poll_interval": 5,
|
||||
"batch_size": 5,
|
||||
"processor_timeout_secs": 3600
|
||||
},
|
||||
"feature_flags": {
|
||||
"cache_enabled": false,
|
||||
"cache_enabled": true,
|
||||
"auto_pipeline_enabled": false,
|
||||
"watcher_auto_register": false,
|
||||
"summary_enabled": false
|
||||
"summary_enabled": true
|
||||
},
|
||||
"server": {
|
||||
"port": 0,
|
||||
"media_base_url": "",
|
||||
"serve_base_url": "",
|
||||
"storage_root": "",
|
||||
"timezone": ""
|
||||
"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": 0,
|
||||
"max_login_attempts": 0,
|
||||
"api_key_expiry_days": 0,
|
||||
"system_stats_refresh_sec": 0,
|
||||
"preferred_language": ""
|
||||
"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_min_score": 0.0,
|
||||
@@ -194,6 +256,100 @@
|
||||
"enabled": true,
|
||||
"max_concurrent_stages": 5,
|
||||
"default_timeout_secs": 7200,
|
||||
"flows": {}
|
||||
"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
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
# ASRX Garbled Text Recovery via Language Rotation + VLM Second Reference — V1.0
|
||||
|
||||
| 項目 | 內容 |
|
||||
|------|------|
|
||||
| **範圍** | ASR / ASRX 轉錄亂碼偵測與恢復機制:第一句觸發 → 語種輪詢 → VLM 第二參考 |
|
||||
| **狀態** | **Draft — 待確認** |
|
||||
| **適用版本** | Momentry Core V4.0+ |
|
||||
| **作者** | OpenCode / Warren |
|
||||
| **建立日期** | 2026-11-05 |
|
||||
| **相關檔案** | `/Users/accusys/momentry_core/tools/cli/rust/src/bin/rust_asr_asrx.rs`、`/Users/accusys/momentry_core/tools/cli/rust/src/bin/rust_asrx.rs`、`/Users/accusys/momentry_core/config/pipeline_flows.json`、`/Users/accusys/momentry/config/admin_config.json` |
|
||||
|
||||
---
|
||||
|
||||
## 1. 問題
|
||||
|
||||
### 1.1 現有問題
|
||||
|
||||
`rust_asr_asrx`(MLX Whisper)在語言 auto-detect 失誤時,會輸出**無意義的亂碼幻覺**,而且
|
||||
一次轉錄直接寫入 `.asr_asrx.json`,沒有任何品質檢查與恢復機制。
|
||||
|
||||
**真實案例(demo 影片 020.mp4,本機驗證)**:
|
||||
|
||||
| 步驟 | 結果 |
|
||||
|------|------|
|
||||
| Whisper auto-detect | 偵測語言 = `nn`(Nynorsk),text = `වවවවවව…`(同一僧伽羅字符重複 100 次)|
|
||||
| 生產管線產物 | `/Users/accusys/momentry/output/04be89357fb83d91ce3a0eef0579fd04.asrx.json` 即此亂碼 |
|
||||
| 強制 `--language ja` 重轉 | `"ご視聴ありがとうございました"`(有意義日文)✅ |
|
||||
| 強制 `--language en` | 空字串 |
|
||||
|
||||
**現行程式行為**(`/Users/accusys/momentry_core/tools/cli/rust/src/bin/rust_asr_asrx.rs`):
|
||||
|
||||
- `--language <L>` 參數存在,未指定時 auto-detect,**只跑一次**
|
||||
- 轉錄結果無任何「是否為亂碼」判定 → 亂碼直接落到下游 `tkg`
|
||||
|
||||
### 1.2 影響
|
||||
|
||||
| 影響 | 說明 |
|
||||
|------|------|
|
||||
| `tkg` 知識圖譜污染 | 亂碼字幕進入 `tkg`(依賴 asr_asrx),造成無意義時序知識 |
|
||||
| 搜尋索引污染 | 亂碼進入 chunk 嵌入,降低 smart search 品質 |
|
||||
| Speaker diarization 失效場景 | 亂碼 segment 仍佔用 speaker 標籤,誤導聲紋對應 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 實測驗證摘要(2026-11-05 smoke test)
|
||||
|
||||
| 測試 | 結果 |
|
||||
|------|------|
|
||||
| llama.cpp `:8080`(gemma-4-12b-it + mmproj,build 11173)audio 輸入模組 | ✅ `init_audio` 啟用(官方 experimental) |
|
||||
| OpenAI `input_audio` 格式(base64 wav) | ✅ HTTP 200,audio token 實際餵入(10 秒音訊 ≈ 250–285 tokens) |
|
||||
| `audio_url` 格式 | ❌ 400 `unsupported content[].type` |
|
||||
| 004.mp4(清晰日語)VLM 直聽 | ✅ 轉出有意義日文,與 whisper ground truth 幾乎逐字一致,3/3 穩定(temp 0.1) |
|
||||
| 020.mp4(亂碼案例)VLM 直聽 | ❌ 回答「無音訊可辨」——模型判定此音訊**無可辨語音**(與 whisper 失效模式不同) |
|
||||
| English prompt | 穩定(3/3 一致);日文 prompt 曾出現近空回應 |
|
||||
| max_tokens | 900 以內安全(含思考模式預算) |
|
||||
|
||||
**啟示**:VLM 直聽與 whisper 的失效模式互補——004 型(whisper 失效但語音清晰)VLM 可救;
|
||||
020 型(BGM 重到模型判定無語音)VLM 拒答本身是**有用的負向訊號**(此段無可辨語音)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 設計
|
||||
|
||||
### 3.1 決策規則總覽(已與需求方確認的定案)
|
||||
|
||||
```
|
||||
Whisper auto-detect 轉錄(一次)
|
||||
│
|
||||
├─ 第一句有意義 → 直接採用,結束(零額外成本)
|
||||
│
|
||||
└─ 第一句無意義(亂碼)→ 丟棄整份 auto 結果
|
||||
→ 語種輪詢:← 候選序由 config 下發,預設 ja → zh → en
|
||||
每輪指定 --language 重跑,**第一個「第一句有意義」者採用即停**(短路)
|
||||
│
|
||||
├─ 某語種命中 → 採用該輪結果 → 結束
|
||||
│
|
||||
└─ 全部輪完仍無意義 → VLM 第二參考
|
||||
├─ audio 直餵 gemma `:8080`(input_audio)→ 產生替代轉錄,有效即採用
|
||||
│ (VLM 回答「無音訊」= 負向訊號:標記為 no_intelligible_speech)
|
||||
└─ 全部恢復手段都失敗 → 保留原 auto 結果 + garbled 標記(不回傳空)
|
||||
```
|
||||
|
||||
**DAG 不變**:三層恢復全部封閉在 asrx stage 的 tool 內部;stage 仍為 Phase 2 平行無依賴,
|
||||
`tkg` 的阻塞點(`asr_asrx` + `face_cluster`)不變。
|
||||
|
||||
### 3.2 第一句亂碼判定(garbled check)
|
||||
|
||||
判定物件 = **轉錄第一個 segment 的 text**。單句測試,任一命中即判亂碼:
|
||||
|
||||
| # | 指標 | 亂碼特徵 | 閾值(預設,config 可調) |
|
||||
|---|------|----------|--------------------------|
|
||||
| 1 | 空回應 | text 去除空白後為空 | 直接觸發輪詢 |
|
||||
| 2 | 重複字符率 | top-1 字符出現次數 / 長度 | > 0.6 |
|
||||
| 3 | 重複片段 | 同一 3+ 字符片段連續重複 5 次以上 | 觸發 |
|
||||
| 4 | 語言置信度 | JSON 欄位 `lang_prob` < 0.4(MLX whisper 已回報) | 觸發 |
|
||||
| 5 | 幻覺字符集 | text 全部由同一類 CJK/稀有字構成且長度 ≥ 20 | 觸發 |
|
||||
|
||||
> 註:020 案例同時命中 #2/#3/#4/#5;004 正常案例全部通過。指標刻意保守(寧可多輪詢、
|
||||
> 不要漏判),因為輪詢成本與 whisper 轉錄本身同級,且短路設計讓命中的第一輪就停。
|
||||
|
||||
### 3.3 語種輪詢(language rotation)
|
||||
|
||||
> **🔴 2026-11-05 需求方追加定案:輪詢順序全部由 `admin_config.json` 定義,程式零 hard code。**
|
||||
|
||||
| 項目 | 設計 |
|
||||
|------|------|
|
||||
|
||||
| 項目 | 設計 |
|
||||
|------|------|
|
||||
| 候選序 | 預設 `["ja", "zh", "en"]`,config 下發可改 |
|
||||
| 停止條件 | **短路式**:第一個「第一句有意義」的輪即採用,不求最優 |
|
||||
| 重跑方式 | 同一個 MLX whisper 命令,僅加 `--language <L>`;音訊不重擷取 |
|
||||
| 成本 | 每輪與 ASR 本身同級(small 模型 10 秒音訊 < 1 秒 CPU/GPU);stage timeout 3600s 可容納 |
|
||||
| 命中結果 | 該輪完整 transcript + diarization 全部採用 |
|
||||
|
||||
### 3.4 VLM 第二參考(second reference)
|
||||
|
||||
| 項目 | 設計 |
|
||||
|------|------|
|
||||
| 觸發條件 | 僅**所有語種輪完仍無意義**(成本後置,正常與可恢復案例不消耗 :8080 資源) |
|
||||
| 呼叫方式 | HTTP POST `http://localhost:8080/v1/chat/completions`,content part:
|
||||
`[{"type":"text","text":"<固定英文轉錄指令>"},{"type":"input_audio","input_audio":{"data":"<base64>","format":"wav"}}]` |
|
||||
| 參數 | `max_tokens=500`、`temperature=0.1`(實測 3/3 穩定的組合) |
|
||||
| 有效判定 | 對 VLM 回覆的 text 比照 3.2 第一句判定;通過則採用為 transcript(speaker 延用 diarization 段落切分) |
|
||||
| 負向訊號 | VLM 回答「沒有音訊/無法聽」→ 標記 `no_intelligible_speech: true`(提供 tkg 過濾) |
|
||||
| 音訊格式 | 16kHz mono WAV,分段後的音訊直接 base64(實測 10 秒 ≈ 160KB) |
|
||||
| 失效模式 | VLM 服務不可用 / 超時 → 跳過此層,落入 3.1 最後分支(保留 auto + garbled 標記) |
|
||||
|
||||
### 3.5 輸出 schema 擴充(`.asr_asrx.json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"language": "ja",
|
||||
"garbled_fallback": false,
|
||||
"recovery": {
|
||||
"triggered": true,
|
||||
"first_sentence_check": {"meaningful": false, "reasons": ["high_repeat_char", "low_lang_prob"]},
|
||||
"attempts": [
|
||||
{"language": "auto", "result": "rejected"},
|
||||
{"language": "ja", "result": "accepted", "first_sentence": "ご視聴ありがとうございました"}
|
||||
],
|
||||
"vlm_reference": {
|
||||
"used": false,
|
||||
"mode": "audio_direct",
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"decision_reason": null,
|
||||
"supplementary_text": null
|
||||
},
|
||||
"no_intelligible_speech": false,
|
||||
"final_result": "rotation_hit"
|
||||
},
|
||||
"segments": [ ...(現行欄位不變)]
|
||||
}
|
||||
```
|
||||
|
||||
| 情境 | `final_result` |
|
||||
|------|----------------|
|
||||
| auto 第一句即有意義 | `auto_ok` |
|
||||
| 輪詢第 N 語種命中 | `rotation_hit` |
|
||||
| VLM 直聽 rescue | `vlm_rescue` |
|
||||
| VLM 判定無可辨語音 | `no_intelligible_speech` |
|
||||
| 全部失敗保留原結果 | `garbled_retained` |
|
||||
|
||||
下游 `tkg` 可依 `recovery.final_result` / `no_intelligible_speech` 選擇性過濾該檔字幕。
|
||||
|
||||
### 3.6 Config 下發(`admin_config.json` 新增區塊)
|
||||
|
||||
```json
|
||||
"asr_config": {
|
||||
"garbled_check_enabled": true,
|
||||
"first_sentence_thresholds": {
|
||||
"max_top_char_ratio": 0.6,
|
||||
"min_lang_prob": 0.4,
|
||||
"min_repeat_slice_repeat": 5
|
||||
},
|
||||
"language_candidates": ["ja", "zh", "en"],
|
||||
"vlm_rescue_enabled": true,
|
||||
"vlm_max_tokens": 500,
|
||||
"vlm_temperature": 0.1,
|
||||
"vlm_timeout_secs": 120
|
||||
}
|
||||
```
|
||||
|
||||
**讀取機制(確保非 hard code)**:
|
||||
|
||||
| 項目 | 設計 |
|
||||
|------|------|
|
||||
| 讀取者 | `rust_asr_asrx` 每次啟動**直接讀 `admin_config.json`**(fresh process → 每次都拿到最新值,admin API `reload` 後下一個 job 即生效,無需重啟 worker) |
|
||||
| 檔案路徑 | 環境變數 `MOMENTRY_ADMIN_CONFIG` 優先;未設定時沿用與 `AdminConfigManager` 相同的預設(`config/admin_config.json` 解析邏輯) |
|
||||
| 覆寫方式 | CLI `--languages "ja,zh,en"`、`--no-vlm` 僅供手動測試覆寫,**非程式主路徑** |
|
||||
| 缺 config 時 | 退回編譯期預設(`ja,zh,en` + 文件所述閾值)並印 warning——僅為保底,不算 hard code 主路徑 |
|
||||
| 缺 `asr_config` 區塊 | `garbled_check_enabled` 視為 `false`(關閉 = 回到現行行為),其餘用預設值 |
|
||||
|
||||
| 項目 | 說明 |
|
||||
|------|------|
|
||||
| `garbled_check_enabled` | **總開關;false 時行為回到現行(純 auto,零改動風險)** |
|
||||
| `language_candidates` | 語種輪詢候選序 |
|
||||
| `vlm_rescue_enabled` | 第三層獨立開關(會佔用 :8080 資源) |
|
||||
|
||||
### 3.7 適用工具與後續推廣
|
||||
|
||||
| 工具 | 本版本 | 後續 |
|
||||
|------|--------|------|
|
||||
| `rust_asr_asrx` | ✅ 實作(asr+diarize 是 pipeline 主力) | - |
|
||||
| `rust_asrx` / `rust_whisper` | ❌ 不動 | 之後套用同一共用判邏輯(抽出共享函式) |
|
||||
|
||||
### 3.8 順手修正(同 PR)
|
||||
|
||||
| 項目 | 現況 | 修正 |
|
||||
|------|------|------|
|
||||
| skip 條件不一致 | pipeline_flows 找 `*.asr_asrx.json`,實際產出 `.asrx.json` | 對齊為實際產出 `*.asrx.json`,否則每次重跑會重做一輪 ASR |
|
||||
|
||||
---
|
||||
|
||||
## 4. 實作計畫
|
||||
|
||||
| # | 步驟 | 驗證 |
|
||||
|---|------|------|
|
||||
| 1 | 新增第一句亂碼判定(3.2 五項指標) | 單元測試 020 亂碼文字 → 全命中、004 正常文字 → 通過 |
|
||||
| 2 | 語種輪詢 loop + 短路(3.3) | `cargo test`;以 020.wav 實跑驗證 rotation_hit |
|
||||
| 3 | VLM rescue(3.4):HTTP client + response 判定 | mock HTTP 服務單元測試;disable 時不發請求 |
|
||||
| 4 | 輸出 schema 擴充(3.5) | diff 檢查產出 json |
|
||||
| 5 | config 下發(3.6)+ 總開關 | 開/關往返測試(關閉 = 行為與現在完全相同) |
|
||||
| 6 | pipeline skip 條件對齊(3.8) | 重跑同一影片不重做 ASR |
|
||||
| 7 | 回歸:demo 002-020 實跑 | 004 不丟不重試、020 `rotation_hit(ja)`、亂碼不落 tkg |
|
||||
|
||||
**不做範圍**:rust_asrx / rust_whisper 同步改造、場景幀/OCR 型 VLM 裁決(Mode B)、
|
||||
POSE 恢復——後續版本。
|
||||
|
||||
---
|
||||
|
||||
## 5. 風險與開放問題
|
||||
|
||||
| # | 風險 | 對策 |
|
||||
|---|------|------|
|
||||
| 1 | 判定過緊誤開輪詢(正常句被誤判) | 閾值保守 + 總開關可關;誤判樣本只在觸發時多付輪詢成本 |
|
||||
| 2 | 輪詢全部 miss 進 VLM 增加 :8080 負載 | 只在輪詢全失敗後觸發(成本後置);併發受 worker 現行控制限制 |
|
||||
| 3 | llama.cpp audio 為 experimental,品質可能隨版本變動 | 升級 llama.cpp 時回歸測試:004 → 日文轉錄、020 → 拒答 |
|
||||
| 4 | `vlm_llm_url` 設定錯誤 | 連線失敗即跳過 rescue 層,不影響主要輸出 |
|
||||
| 5 | 超長 audio(>ctx) | 本次僅做第一句判定;輪詢重轉音訊同現行,不產生新限制 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 版本歷史
|
||||
|
||||
| 版本 | 日期 | 變更 |
|
||||
|------|------|------|
|
||||
| 1.0 | 2026-11-05 | 初版:判定規則(第一句觸發)、語種輪詢、VLM 直聽 rescue、輸出 schema、config 區塊、實作計畫(OpenCode / Warren)|
|
||||
| 1.1 | 2026-11-05 | 實作完成(`rust_asr_asrx.rs`):020 → `rotation_hit(ja)`、004 → `auto_ok`(零成本)、輪詢全 miss → `no_intelligible_speech`;pipeline skip 條件對齊 `*.asrx.json`。偏備註:`final_result` 另有 `forced_language`(`--language` 強制時跳過 recovery);VLM 拒答判定用協議字串組(非可調參數);`lang_prob` 僅在 MLX 輸出含此欄位時使用 |
|
||||
@@ -0,0 +1,196 @@
|
||||
# Face Groups 持久化設計 V1.0
|
||||
|
||||
> 日期:2026-11-07|目的:建立 face group 的永久化儲存,作為全域 identity 管理的基礎
|
||||
|
||||
---
|
||||
|
||||
## 1. 設計目標
|
||||
|
||||
| 目標 | 說明 |
|
||||
|---|---|
|
||||
| **永久化** | Face group 資訊獨立保存,不依賴 DB 或 face_cluster.json |
|
||||
| **可視化** | UI 可點擊數字直接查看 JSON 內容 |
|
||||
| **Identity 基礎** | 未來作為跨檔案 identity 匹配的介面 |
|
||||
| **區別於 cluster** | face_cluster.json = 演算法產出;face_groups.json = 使用者管理結果 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 檔案規格
|
||||
|
||||
### 2.1 檔案位置與命名
|
||||
|
||||
```
|
||||
/Users/accusys/momentry/output/{file_uuid}.face_groups.json
|
||||
```
|
||||
|
||||
### 2.2 JSON 結構
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"file_uuid": "b496a68800f90770aa7246c877f38985",
|
||||
"file_name": "020.mp4",
|
||||
"updated_at": "2026-11-07T12:00:00Z",
|
||||
"total_groups": 3,
|
||||
"total_traces": 12,
|
||||
"groups": [
|
||||
{
|
||||
"group_id": 1902,
|
||||
"name": "Person 1",
|
||||
"origin_cluster_id": "Person_1",
|
||||
"trace_ids": [1, 2, 3, 4, 6, 9, 10, 13],
|
||||
"trace_count": 8,
|
||||
"representative_trace": 6,
|
||||
"created_at": "2026-11-07T10:00:00Z",
|
||||
"updated_at": "2026-11-07T12:00:00Z",
|
||||
"metadata": {
|
||||
"merged_from": ["Person_0"],
|
||||
"manual_rename": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"group_id": 1905,
|
||||
"name": "Person 2",
|
||||
"origin_cluster_id": "Person_2",
|
||||
"trace_ids": [7, 12],
|
||||
"trace_count": 2,
|
||||
"representative_trace": 7,
|
||||
"created_at": "2026-11-07T10:00:00Z",
|
||||
"updated_at": "2026-11-07T10:00:00Z",
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"group_id": 1906,
|
||||
"name": "Person 5",
|
||||
"origin_cluster_id": "Person_5",
|
||||
"trace_ids": [15, 16],
|
||||
"trace_count": 2,
|
||||
"representative_trace": 15,
|
||||
"created_at": "2026-11-07T10:00:00Z",
|
||||
"updated_at": "2026-11-07T10:00:00Z",
|
||||
"metadata": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3 欄位說明
|
||||
|
||||
| 欄位 | 類型 | 說明 |
|
||||
|---|---|---|
|
||||
| `schema_version` | string | 格式版本,用於未來升級 |
|
||||
| `file_uuid` | string | 檔案唯一識別 |
|
||||
| `file_name` | string | 原始檔名(方便識別) |
|
||||
| `updated_at` | string | 最後更新時間(ISO 8601) |
|
||||
| `total_groups` | int | 群組總數 |
|
||||
| `total_traces` | int | 所有群組的 trace 總數 |
|
||||
| `groups[]` | array | 群組列表 |
|
||||
| `groups[].group_id` | int | DB face_groups.id |
|
||||
| `groups[].name` | string | 群組顯示名稱 |
|
||||
| `groups[].origin_cluster_id` | string | 來源 cluster ID(Person_N) |
|
||||
| `groups[].trace_ids` | int[] | 所屬 trace ID 列表 |
|
||||
| `groups[].trace_count` | int | trace 數量 |
|
||||
| `groups[].representative_trace` | int | 代表 trace(最佳幀) |
|
||||
| `groups[].created_at` | string | 群組建立時間 |
|
||||
| `groups[].updated_at` | string | 群組最後更新時間 |
|
||||
| `groups[].metadata` | object | 擴充資訊(merge 歷史、手動改名等) |
|
||||
|
||||
---
|
||||
|
||||
## 3. 更新時機
|
||||
|
||||
| 操作 | 觸發更新 | 說明 |
|
||||
|---|---|---|
|
||||
| **Materialize** | ✅ | 首次建立群組時寫入 |
|
||||
| **Rename Group** | ✅ | 更新 name 和 updated_at |
|
||||
| **Merge Groups** | ✅ | 合併後更新 trace_ids |
|
||||
| **Move Trace** | ✅ | 移動 trace 後更新 |
|
||||
| **Ungroup** | ✅ | 移除 trace 後更新 |
|
||||
| **Delete Group** | ✅ | 從 groups 陣列移除 |
|
||||
| **Face Deduplication** | ✅ | 重新聚類後重建 |
|
||||
|
||||
---
|
||||
|
||||
## 4. UI 整合
|
||||
|
||||
### 4.1 點擊數字查看 JSON
|
||||
|
||||
```html
|
||||
<!-- PeopleView.vue -->
|
||||
<div class="ms-ppl-section-title">
|
||||
Face Group:
|
||||
<span class="ms-ppl-section-count ms-clickable"
|
||||
@click="openFaceGroupsJson"
|
||||
title="查看 face_groups.json">
|
||||
({{ faceGroups.length }})
|
||||
</span>
|
||||
</div>
|
||||
```
|
||||
|
||||
### 4.2 JSON 檢視器 Modal
|
||||
|
||||
```html
|
||||
<!-- 點擊後彈出 modal 顯示 face_groups.json 內容 -->
|
||||
<div v-if="showFaceGroupsJson" class="ms-modal-overlay">
|
||||
<div class="ms-modal-box ms-modal-wide">
|
||||
<div class="ms-modal-header">
|
||||
<span class="ms-modal-title">face_groups.json — {{ fileUuid }}</span>
|
||||
<button class="ms-modal-close" @click="showFaceGroupsJson = false">✕</button>
|
||||
</div>
|
||||
<div class="ms-modal-body">
|
||||
<pre class="ms-json-view">{{ faceGroupsJsonContent }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 未來擴展:全域 Identity 管理
|
||||
|
||||
### 5.1 Identity 匹配介面
|
||||
|
||||
```json
|
||||
{
|
||||
"identities": [
|
||||
{
|
||||
"identity_uuid": "uuid-1234",
|
||||
"identity_name": "張三",
|
||||
"face_groups": [
|
||||
{
|
||||
"file_uuid": "b496a688...",
|
||||
"file_name": "020.mp4",
|
||||
"group_id": 1902,
|
||||
"group_name": "Person 1",
|
||||
"confidence": 0.95
|
||||
},
|
||||
{
|
||||
"file_uuid": "8f45f14f...",
|
||||
"file_name": "078.mp4",
|
||||
"group_id": 47,
|
||||
"group_name": "Person 0",
|
||||
"confidence": 0.88
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 跨檔案身份聚合
|
||||
|
||||
- 每個 `face_groups.json` 作為單檔身份基礎
|
||||
- 通過 embedding 相似度匹配不同檔案的相似群組
|
||||
- 聚合為全域 `identities.json`
|
||||
|
||||
---
|
||||
|
||||
## 6. 實作計畫
|
||||
|
||||
| 階段 | 任務 | 檔案 |
|
||||
|---|---|---|
|
||||
| **Phase 1** | 建立 `save_face_groups_json()` 函數 | `schema.rs` |
|
||||
| **Phase 2** | 在所有 group 操作後呼叫保存 | `profile.rs` |
|
||||
| **Phase 3** | 新增 API 端點讀取 JSON | `profile.rs` |
|
||||
| **Phase 4** | UI 整合點擊查看功能 | `PeopleView.vue` |
|
||||
| **Phase 5** | Identity 匹配介面(未來) | 待定 |
|
||||
@@ -0,0 +1,148 @@
|
||||
# Face Groups 正規化設計 V1.0(方案 C)
|
||||
|
||||
> 日期:2026-11-06 狀態:已實作並部署(Phase 1);Phase 2 配套見 §7
|
||||
> 涉及:`schema.rs` / `profile.rs` / `postgres_db.rs` / `PeopleView.vue` / `store.ts`
|
||||
> 前置文件:複雜度盤點(4 結構缺陷)、方案 A/B/C 比較
|
||||
|
||||
---
|
||||
|
||||
## 1. 核心決策:name 從「每筆 trace 的屬性」升級為「獨立實體」
|
||||
|
||||
### 1.1 資料模型(三層)
|
||||
|
||||
```
|
||||
face_groups(群組實體 — 群組名字住在這裡)
|
||||
├─ id BIGSERIAL PK
|
||||
├─ file_uuid 歸屬檔案(暫不跨檔共享)
|
||||
├─ name ★ 唯一权威群組名
|
||||
├─ origin_cluster_id 來源 auto cluster(Person_N),similarity 由此 join
|
||||
├─ sort_index 顯示排序
|
||||
├─ properties JSONB 擴充欄位
|
||||
└─ UNIQUE (file_uuid, name)
|
||||
|
||||
trace_profiles(trace 表示層 — 歸屬用外鍵)
|
||||
├─ group_id BIGINT FK → face_groups(id) ON DELETE 置 NULL 語意
|
||||
└─ name ↓ 降級為 caption(見 §2)
|
||||
|
||||
tkg_nodes(KG 圖層)
|
||||
└─ label ↓ 降級為純顯示鏡射,非資料來源
|
||||
```
|
||||
|
||||
### 1.2 不變式(Invariant)
|
||||
|
||||
| # | 不變式 | 違反後果 |
|
||||
|---|---|---|
|
||||
| I1 | 群組的唯一識別 = `face_groups.id`;名稱改變不改變 id | rename 後引用(undo snapshot、一致性檢查)全失效 |
|
||||
| I2 | trace 是否屬於某群組 **只看** `trace_profiles.group_id` | 舊 name 比對路徑殘留 → 幽靈群組 |
|
||||
| I3 | 同一 `(file_uuid, name)` 只能有一個 group row | 重複群組/合併語意錯亂 |
|
||||
| I4 | `group_id IS NULL` ⇔ trace 屬於 Unassigned | Unassigned 僞群組若被物化成 row,Pending Faces 邏輯失效 |
|
||||
| I5 | rename = `face_groups` 單筆 UPDATE;caption/label 同步屬於**鏡射維護**,失敗不影響 rename 正確性 | — |
|
||||
|
||||
---
|
||||
|
||||
## 2. `trace_profiles.name` 的新語意:caption(棄權週期)
|
||||
|
||||
`tp.name` 從「群組名來源」降級為**每 trace 的顯示 caption 鏡射**。
|
||||
|
||||
### 2.1 誰還能寫 tp.name(寫入白名單 — 2026-11-06 生效)
|
||||
|
||||
| 呼叫點 | 行為 | 合法性 |
|
||||
|---|---|---|
|
||||
| `profile.rs` rename 分支 | `UPDATE tp SET name = 群組新名 WHERE group_id = $3`(單條 SQL 鏡射整群) | ✅ 鏡射維護 |
|
||||
| `profile.rs` move 分支 self-healing | INSERT 時帶 name;**已存在 row 不改 name** | ⚠️ 見 G2 |
|
||||
| `trace_agent_api.rs` hard_delete (=unassign) | 重置為 `Face Trace {id}` | ✅(但需同步清 group_id → G1) |
|
||||
| undo / snapshot restore | 還原 name + `get_or_create_group` re-attach | ✅ name-less restore 設計 |
|
||||
| `trace_sync.rs::sync_trace_label` | worker 端同步 label | ⚠️ 見 G4 |
|
||||
|
||||
### 2.2 讀取規則
|
||||
|
||||
- **讀取群組**:一律 `face_groups` × `tp.group_id` join。新代碼**禁止** `WHERE tp.name = ?` / `GROUP BY tp.name` 作為群組語意。
|
||||
- 顯示 caption:允許讀 `tp.name`,但 fallback 順序 = `face_groups.name (by group_id)` → `tp.name` → "Unassigned"。
|
||||
|
||||
### 2.3 棄權時間表
|
||||
|
||||
| 階段 | 內容 |
|
||||
|---|---|
|
||||
| Phase 1(已完成) | 新表 + group_id 讀寫全走新模型;backfill 保留(`ensure_face_groups_schema`,幂等) |
|
||||
| Phase 2(本文件 §7 修復清單) | 補齊 6 個缺口;backfill 排除 `Person_%` |
|
||||
| Phase 3(觀察期 ≥ 2 週) | 現署 caption 廣播(rename 同步 tp.name + tkg label);僅供 search_people 過渡查詢 |
|
||||
| Phase 4(最終) | `tp.name` 語意窄化為「未歸組 trace 的暫名」;search_people 改 join face_groups;tkg_nodes.label 由查詢時 join 合成,停寫 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 讀取路徑(單一來源)
|
||||
|
||||
```
|
||||
face-groups / cluster-results 读取
|
||||
① materialize_auto_groups(file_uuid)
|
||||
face_cluster.json 的 Person_N cluster → face_groups row(幂等)
|
||||
・成員已全歸組的 cluster:skip
|
||||
・部分歸組:只補未涵蓋 cluster;INSERT ... ON CONFLICT DO UPDATE
|
||||
SET group_id = COALESCE(tp.group_id, $4) — 永不覆蓋既有歸屬
|
||||
② SELECT FROM face_groups LEFT JOIN trace_profiles ON group_id
|
||||
③ Unassigned = tp WHERE group_id IS NULL(輔以 single_frame filter 設定)
|
||||
```
|
||||
|
||||
- `face_cluster.json` 僅供 frames / similarity / representative 讀取(similarity 以 `origin_cluster_id` join)。
|
||||
- fallback 全有全無開關已刪除;DB 有 0 群組時自然顯示全 Unassigned。
|
||||
|
||||
## 4. 寫入路徑(mutation 設計)
|
||||
|
||||
| 操作 | 寫入 | 備註 |
|
||||
|---|---|---|
|
||||
| **Create & Move** | `get_or_create_group` → `UPDATE tp SET group_id` | FS/People 卡片通用;FS 卡不消失(Pending Faces 對 Qdrant `identity_id=0` 查詢) |
|
||||
| **Move to existing** | 同上(命中既有 row,不 INSERT) | |
|
||||
| **Rename** | `UPDATE face_groups SET name` ×1 → caption 鏡射 ×2(tp 群內單條 UPDATE、tkg label ANY($3)) | rename vs move 判定:提供的 traces 恰好 = 該群全部成員 |
|
||||
| **Merge groups** | 成員 re-point 到 target group → 刪除清空的 source group rows | 空群組才刪 |
|
||||
| **Ungroup / unassign** | `UPDATE tp SET group_id = NULL, name='Face Trace N'` | **不得**建立 "Unassigned" group row(見 G3) |
|
||||
| **Undo** | name-less restore:`get_or_create_group(名稱)` + re-attach | group row 缺也能救回 |
|
||||
| **Delete group row** | 僅在群組 0 成員時允許(merge / 清孤兒) | FK 為此目的鎖 |
|
||||
|
||||
## 5. Boot 行為(`ensure_face_groups_schema`,幂等)
|
||||
|
||||
1. CREATE TABLE face_groups(IF NOT EXISTS)
|
||||
2. `ALTER TABLE tp ADD COLUMN group_id`
|
||||
3. Backfill A:tp.name(排除 `Face Trace %`、`Trace %`)→ group rows(ON CONFLICT nothing)
|
||||
4. Backfill B:`tp.group_id IS NULL` 者,依 `(file_uuid,name)` 掛回
|
||||
|
||||
⚠️ Backfill A 的排除清單**必須包含 `Person_%`**(Phase 2 修復,見 G5),否則 worker 重跑 cluster 寫入的 Person_N caption 會在重啟時復活成群組。
|
||||
|
||||
## 6. Audit 結果(2026-11-06 全碼掃描)
|
||||
|
||||
直接寫 tp.name 的位置已收斂為 §2.1 白名單;仍觸及 trace_profiles 的其他模組分類:
|
||||
|
||||
| 模組 | 用法 | 分類 |
|
||||
|---|---|---|
|
||||
| `search.rs` | 讀 `start_frame…vlm_*` | 無 name 依賴 ✅ |
|
||||
| `universal_search.rs:603/775` | `SELECT tp.name` for people 搜尋 | caption 讀取,過渡合法(Phase 4 改 join)|
|
||||
| `identity_api.rs:1190` | people 查詢 | 同上 |
|
||||
| `agent/tools.rs:1931` | trace 查詢 | 同上 |
|
||||
| `files.rs / scan.rs` | unregister / 計數 | cascade-safe,無 name 語意 ✅ |
|
||||
| `trace_agent_api.rs` | unassign 重置、snapshot、undo | 見 G1/G6 |
|
||||
| `trace_sync.rs` | worker label 廣播 | 見 G4 |
|
||||
| `job_worker.rs:3661/4562` | cluster 後 label 同步 | 見 G4 |
|
||||
|
||||
## 7. Phase 2 配套修復清單(本文件的主要交付)
|
||||
|
||||
| # | 缺口 | 位置 | 修復設計 |
|
||||
|---|---|---|---|
|
||||
| **G1** | Unassign(hard_delete 新語意)只重置 name/label,**沒清 `tp.group_id`** → trace 仍掛原群組 | `trace_agent_api.rs` hard_delete 分支 | 重置時加 `UPDATE tp SET group_id = NULL`;undo 沿用 `get_or_create_group` re-attach |
|
||||
| **G2** | Move 到既有群組後,已存在 tp row 的 caption 不更新 → people 搜尋顯示舊名 | `profile.rs` move 分支 | move 分支補一條 `UPDATE tp SET name = 目標群組名 WHERE trace_id = ANY(...) AND group_id = 新gid`(只鏡射成員,不動他群) |
|
||||
| **G3** | Studio Ungroup 傳 `name: 'Unassigned'` → 後端會物化一個叫 "Unassigned" 的實體群組,違反 I4 | `profile.rs` update_trace_profile_group_handler | handler 開頭偵測 `req.name.trim().eq_ignore_ascii_case("unassigned")` → spin off detach 分支:`group_id = NULL` + name 重置,不建 group row |
|
||||
| **G4** | `sync_trace_label`(cluster 重跑後)會把 `Person_N` 廣播進 tp.name → 重啟 backfill 復活 Person 群組 + 顯示假名回流 | `trace_sync.rs` 呼叫端(job_worker:3661) | 若 trace 已有 group_id:tp.name 用 `face_groups.name` 鏡射值,不用 Person_N;無 group_id 才允許 Person_N |
|
||||
| **G5** | Boot Backfill A 排除清單缺 `Person_%` | `schema.rs` ensure | WHERE 加 `AND NOT (name LIKE 'Person\_%')` |
|
||||
| **G6** | `merge_trace` 的 undo 還原 name 但無 group re-attach | `trace_agent_api.rs` undo 段 | 沿用 `schema::get_or_create_group` + attach(同 profile.rs 通用 undo) |
|
||||
|
||||
## 8. 測試守則(回歸用)
|
||||
|
||||
1. rename 後 ** 重啟 server** → 無同名 ghost 群組(I1/I3)
|
||||
2. move → 重啟 → 歸屬不變(COALESCE 修復)
|
||||
3. Ungroup → 群組清單不出現 "Unassigned" 實體;trace 回 Pending Faces
|
||||
4. cluster 重跑 → 已歸組 trace 不被 Person_N 拉走
|
||||
5. 雙重啟動失敗群組數 const(幂等)
|
||||
6. search_people 查新名 → rename 後立即命中;move 後 ≤ Phase2 修復時間命中
|
||||
|
||||
## 9. 未開放的需求(記錄語意,避免誤解現狀)
|
||||
|
||||
- **跨檔 identity**(同一人跨多支影片):現 `face_groups` 以 file_uuid 為界。未來需要時靠 identity 表(Qdrant `identity_id`)向上聚合,face_groups 不改結構。
|
||||
- **群組層 properties**:欄位已備(JSONB),UI 未消費。
|
||||
@@ -0,0 +1,664 @@
|
||||
# Face Pipeline 逐步檢查規範 V1.0
|
||||
|
||||
> 日期:2026-11-07|適用範圍:face → face_traced → face_cluster → face_groups (DB)
|
||||
|
||||
---
|
||||
|
||||
## 0. 總覽:上下游關係與產出物
|
||||
|
||||
```
|
||||
video.mp4
|
||||
│
|
||||
├─① face detection(swift_face)
|
||||
│ → output/{uuid}.face.json
|
||||
│ → Qdrant _faces(512D embedding + payload)
|
||||
│
|
||||
├─② face tracing(rust_store_traced_faces)
|
||||
│ → output/{uuid}.face_traced.json
|
||||
│
|
||||
├─③ face clustering(rust_face / swift_cluster)
|
||||
│ → output/{uuid}.face_cluster.json
|
||||
│
|
||||
└─④ materialize + group entity(API on-demand / boot backfill)
|
||||
→ DB: face_groups + trace_profiles.group_id
|
||||
```
|
||||
|
||||
每個步驟都有**輸入驗證 → 執行 → 產出驗證 → 跨步驗證**四段。
|
||||
|
||||
---
|
||||
|
||||
## 1. Face Detection(① → face.json + Qdrant)
|
||||
|
||||
### 1.1 輸入驗證
|
||||
|
||||
| 檢查項 | 方法 | 合格標準 |
|
||||
|---|---|---|
|
||||
| 影片檔案存在 | `os.path.exists(video_path)` | ✅ True |
|
||||
| 影片可讀 | `probe_json` 有 `width > 0` | ✅ 非零 |
|
||||
| ffmpeg 可用 | `which ffmpeg` / `ffprobe -version` | ✅ 可執行 |
|
||||
| FaceNet 模型存在 | 模型路徑 `os.path.exists(model_path)` | ✅ True |
|
||||
|
||||
### 1.2 執行後產出驗證(face.json)
|
||||
|
||||
| 檢查項 | 欄位 / 方法 | 合格標準 |
|
||||
|---|---|---|
|
||||
| 檔案存在 | `{output_dir}/{uuid}.face.json` | ✅ 存在 |
|
||||
| JSON 可解析 | `json.load()` | ✅ 不拋異常 |
|
||||
| metadata.processor.name | `d['metadata']['processor']['name']` | ✅ `'face'` |
|
||||
| metadata.processor.tool | 同上 | ✅ `'swift_face'` |
|
||||
| total_faces > 0 | `d['total_faces']` | ✅ ≥ 0(無臉可為 0) |
|
||||
| frame_count > 0 | `d['frame_count']` | ✅ ≥ 1 |
|
||||
| fps > 0 | `d['fps']` | ✅ ≥ 24 |
|
||||
| frames 陣列 | `len(d['frames'])` | ✅ == frame_count |
|
||||
| 每幀有 faces | `all(len(f['faces']) >= 0)` | ✅ |
|
||||
|
||||
### 1.3 Embedding 驗證(關鍵!)
|
||||
|
||||
```python
|
||||
def check_embeddings(face_json: dict) -> dict:
|
||||
results = {'pass': True, 'issues': []}
|
||||
total = 0
|
||||
missing = 0
|
||||
bad_dim = 0
|
||||
|
||||
for frame in face_json.get('frames', []):
|
||||
for face in frame.get('faces', []):
|
||||
total += 1
|
||||
emb = face.get('embedding')
|
||||
if emb is None:
|
||||
missing += 1
|
||||
elif not isinstance(emb, list) or len(emb) != 512:
|
||||
bad_dim += 1
|
||||
elif not all(isinstance(v, (int, float)) for v in emb):
|
||||
bad_dim += 1 # 元素非數值
|
||||
|
||||
if missing > 0:
|
||||
results['pass'] = False
|
||||
results['issues'].append(f'{missing}/{total} faces 缺少 embedding')
|
||||
if bad_dim > 0:
|
||||
results['pass'] = False
|
||||
results['issues'].append(f'{bad_dim}/{total} faces embedding 維度/格式異常')
|
||||
if total == 0:
|
||||
results['issues'].append('沒有 face 資料(影片可能無臉)')
|
||||
|
||||
results['total'] = total
|
||||
results['missing'] = missing
|
||||
results['bad_dim'] = bad_dim
|
||||
return results
|
||||
```
|
||||
|
||||
| 檢查項 | 合格標準 |
|
||||
|---|---|
|
||||
| embedding 存在 | `missing == 0` |
|
||||
| embedding 維度 | `len(emb) == 512`(FaceNet 標準) |
|
||||
| embedding 元素 | 全部為 float/int(可序列化為 JSON array) |
|
||||
|
||||
### 1.4 Qdrant 驗證
|
||||
|
||||
```python
|
||||
def check_qdrant_points(uuid: str, expected_faces: int) -> dict:
|
||||
"""檢查 Qdrant _faces collection 是否有對應的 points"""
|
||||
filter = {"must": [{"key": "file_uuid", "match": {"value": uuid}}]}
|
||||
|
||||
# count
|
||||
count_resp = qdrant.count_points("_faces", filter)
|
||||
actual_count = count_resp.count
|
||||
|
||||
# sample point structure
|
||||
scroll = qdrant.scroll("_faces", filter, limit=1, with_payload=True, with_vector=True)
|
||||
|
||||
return {
|
||||
'pass': actual_count > 0,
|
||||
'expected': expected_faces,
|
||||
'actual': actual_count,
|
||||
'missing': max(0, expected_faces - actual_count),
|
||||
'sample_keys': list(scroll[0][0].payload.keys()) if scroll[0] else [],
|
||||
'vector_dim': len(scroll[0][0].vector) if scroll[0] else 0,
|
||||
}
|
||||
```
|
||||
|
||||
| 檢查項 | 合格標準 |
|
||||
|---|---|
|
||||
| points 數量 | `actual_count >= 0`(可小於 face.json,因 low-confidence 可能被過濾) |
|
||||
| vector 維度 | `vector_dim == 512` |
|
||||
| payload 必要欄位 | 包含 `file_uuid`, `frame`, `trace_id`, `confidence`, `identity_id` |
|
||||
| identity_id 預設 | 新插入的 face 應為 `identity_id: 0`(未歸屬) |
|
||||
|
||||
### 1.5 跨步驗證(face.json vs Qdrant)
|
||||
|
||||
| 檢查項 | 方法 | 合格標準 |
|
||||
|---|---|---|
|
||||
| face count 一致 | `face.json total_faces` ≈ Qdrant count | Qdrant ≤ face.json(允許過濾) |
|
||||
| trace_id 有值 | face.json 每幀 face 有 `trace_id` | ✅ 非 null |
|
||||
| face_id 唯一 | 全檔 face_id 無重複 | ✅ |
|
||||
|
||||
---
|
||||
|
||||
## 2. Face Tracing(② → face_traced.json)
|
||||
|
||||
### 2.1 輸入依賴
|
||||
|
||||
| 依賴 | 檢查 |
|
||||
|---|---|
|
||||
| face.json 存在 | ✅ 檔案存在且 total_faces > 0 |
|
||||
| 影片存在 | ✅ |
|
||||
| min_trace_len, min_confidence | ✅ 參數有效 |
|
||||
|
||||
### 2.2 產出驗證
|
||||
|
||||
| 檢查項 | 欄位 | 合格標準 |
|
||||
|---|---|---|
|
||||
| 檔案存在 | `{uuid}.face_traced.json` | ✅ |
|
||||
| JSON 可解析 | `json.load()` | ✅ |
|
||||
| traces 陣列 | `len(d['traces'])` | ✅ ≥ 1 |
|
||||
| 每筆 trace 必要欄位 | `trace_id`, `frame_count`, `start_frame`, `end_frame`, `best_confidence` | ✅ 全有 |
|
||||
| trace_id 唯一 | 全檔 trace_id 不重複 | ✅ |
|
||||
| frame_count 合理 | `1 ≤ frame_count ≤ face.json frame_count` | ✅ |
|
||||
| start ≤ end | `start_frame ≤ end_frame` | ✅ |
|
||||
| confidence 範圍 | `0 ≤ avg_confidence ≤ 1`, `0 ≤ best_confidence ≤ 1` | ✅ |
|
||||
| face_instances 存在 | 每筆 trace 有 `face_instances` 陣列 | ✅ 非空 |
|
||||
| face_instances 指向有效 face_id | 每個 face_id 可在 face.json 找到 | ✅ |
|
||||
|
||||
```python
|
||||
def check_face_traced(traced: dict, face_json: dict) -> dict:
|
||||
results = {'pass': True, 'issues': []}
|
||||
|
||||
traces = traced.get('traces') or []
|
||||
if not traces:
|
||||
results['pass'] = False
|
||||
results['issues'].append('traces 陣列為空')
|
||||
return results
|
||||
|
||||
# trace_id 唯一性
|
||||
tids = [t['trace_id'] for t in traces]
|
||||
if len(tids) != len(set(tids)):
|
||||
results['pass'] = False
|
||||
results['issues'].append(f'trace_id 有重複:{len(tids)} vs {len(set(tids))} unique')
|
||||
|
||||
# face_instances 指向有效性
|
||||
all_face_ids = set()
|
||||
for fr in face_json.get('frames', []):
|
||||
for fa in fr.get('faces') or []:
|
||||
all_face_ids.add(fa.get('face_id'))
|
||||
|
||||
orphan_instances = 0
|
||||
for t in traces:
|
||||
for fi in t.get('face_instances', []):
|
||||
fid = fi.get('face_id')
|
||||
if fid and fid not in all_face_ids:
|
||||
orphan_instances += 1
|
||||
|
||||
if orphan_instances > 0:
|
||||
results['issues'].append(f'{orphan_instances} face_instances 指向不存在的 face_id')
|
||||
|
||||
# confidence 範圍
|
||||
for t in traces:
|
||||
bc = t.get('best_confidence', -1)
|
||||
ac = t.get('avg_confidence', -1)
|
||||
if not (0 <= bc <= 1):
|
||||
results['issues'].append(f'trace {t["trace_id"]}: best_confidence={bc} 超出 [0,1]')
|
||||
if not (0 <= ac <= 1):
|
||||
results['issues'].append(f'trace {t["trace_id"]}: avg_confidence={ac} 超出 [0,1]')
|
||||
|
||||
results['trace_count'] = len(traces)
|
||||
results['total_frames_traced'] = sum(t.get('frame_count', 0) for t in traces)
|
||||
return results
|
||||
```
|
||||
|
||||
### 2.3 跨步驗證(face.json vs face_traced.json)
|
||||
|
||||
| 檢查項 | 合格標準 |
|
||||
|---|---|
|
||||
| 所有 face.json 的 face_id 被 trace 覆蓋 | `face_instances` 總數 = face.json total_faces |
|
||||
| trace frame 總和 ≥ face count | 每個 face 都屬於某個 trace |
|
||||
| trace_id 在 Qdrant payload 中有對應 | Qdrant points 的 `trace_id` 與 traced 一致 |
|
||||
|
||||
---
|
||||
|
||||
## 3. Face Clustering(③ → face_cluster.json)
|
||||
|
||||
### 3.1 輸入依賴
|
||||
|
||||
| 依賴 | 檢查 |
|
||||
|---|---|
|
||||
| face_traced.json | ✅ traces > 0 |
|
||||
| face.json | ✅ embedding 全部 512D |
|
||||
| 模型(facenet / embedding) | ✅ 存在 |
|
||||
|
||||
### 3.2 產出驗證
|
||||
|
||||
| 檢查項 | 欄位 | 合格標準 |
|
||||
|---|---|---|
|
||||
| 檔案存在 | `{uuid}.face_cluster.json` | ✅ |
|
||||
| clusters 陣列 | `len(d['clusters'])` | ✅ ≥ 1 |
|
||||
| frames 陣列 | `len(d['frames'])` | ✅ ≥ 1 |
|
||||
| 每筆 cluster 必要欄位 | `cluster_id`, `face_count`, `representative_face`, `similarity` | ✅ 全有 |
|
||||
| cluster_id 唯一 | 全檔不重複 | ✅ |
|
||||
| face_count > 0 | 每群至少 1 face | ✅ |
|
||||
| similarity 結構 | 有 `min`, `avg`, `threshold` | ✅ 全為 float |
|
||||
| frame faces 必要欄位 | `cluster_id`, `confidence`, `face_id`, `trace_id` | ✅ 全有 |
|
||||
|
||||
```python
|
||||
def check_face_cluster(cluster_json: dict, traced: dict) -> dict:
|
||||
results = {'pass': True, 'issues': []}
|
||||
|
||||
clusters = cluster_json.get('clusters') or []
|
||||
frames = cluster_json.get('frames') or []
|
||||
|
||||
if not clusters:
|
||||
results['pass'] = False
|
||||
results['issues'].append('clusters 為空(可能影片人臉太少或 threshold 太高)')
|
||||
return results
|
||||
|
||||
# cluster_id 唯一
|
||||
cids = [c['cluster_id'] for c in clusters]
|
||||
if len(cids) != len(set(cids)):
|
||||
results['pass'] = False
|
||||
results['issues'].append(f'cluster_id 重複')
|
||||
|
||||
# face_count 總和
|
||||
total_clustered = sum(c['face_count'] for c in clusters)
|
||||
|
||||
# frame faces 與 clusters 一致性
|
||||
frame_face_count = sum(len(f.get('faces') or []) for f in frames)
|
||||
if frame_face_count != total_clustered:
|
||||
results['issues'].append(
|
||||
f'clusters face_count 總和={total_clustered} != frames 中 faces 數={frame_face_count}'
|
||||
)
|
||||
|
||||
# cluster faces 的 cluster_id 必須存在於 clusters 列表
|
||||
valid_cids = set(cids)
|
||||
bad_faces = 0
|
||||
for f in frames:
|
||||
for fa in f.get('faces') or []:
|
||||
if fa.get('cluster_id') not in valid_cids:
|
||||
bad_faces += 1
|
||||
if bad_faces > 0:
|
||||
results['issues'].append(f'{bad_faces} frame faces 的 cluster_id 不在 clusters 列表中')
|
||||
|
||||
# similarity 驗證
|
||||
for c in clusters:
|
||||
sim = c.get('similarity') or {}
|
||||
for key in ['min', 'avg', 'threshold']:
|
||||
if key not in sim:
|
||||
results['issues'].append(f'cluster {c["cluster_id"]} 缺少 similarity.{key}')
|
||||
elif not isinstance(sim[key], (int, float)):
|
||||
results['issues'].append(f'cluster {c["cluster_id"]} similarity.{key} 非數值')
|
||||
|
||||
# trace_id 對應:每個 cluster 的 face 都應有 trace_id
|
||||
faces_without_trace = 0
|
||||
for f in frames:
|
||||
for fa in f.get('faces') or []:
|
||||
if fa.get('trace_id') is None:
|
||||
faces_without_trace += 1
|
||||
if faces_without_trace > 0:
|
||||
results['issues'].append(f'{faces_without_trace} cluster faces 缺少 trace_id')
|
||||
|
||||
results['cluster_count'] = len(clusters)
|
||||
results['total_clustered_faces'] = total_clustered
|
||||
results['frame_count'] = len(frames)
|
||||
return results
|
||||
```
|
||||
|
||||
### 3.3 跨步驗證
|
||||
|
||||
| 檢查項 | 合格標準 |
|
||||
|---|---|
|
||||
| 每個 traced face 出現在 cluster | `face_cluster frames 總 faces` = `face.json total_faces` |
|
||||
| cluster_id 命名 | `Person_N` 格式(自動命名) |
|
||||
| similarity.threshold 合理 | 通常 ≥ 0.5(視模型而定) |
|
||||
| representative_face 存在 | 每群有代表臉 |
|
||||
|
||||
---
|
||||
|
||||
## 4. Materialize + Face Groups(④ → DB)
|
||||
|
||||
### 4.1 觸發時機
|
||||
|
||||
- 首次呼叫 `/api/v1/cluster-results`(自動 materialize)
|
||||
- Boot backfill(`ensure_face_groups_schema`)
|
||||
|
||||
### 4.2 產出驗證(DB)
|
||||
|
||||
| 檢查項 | SQL | 合格標準 |
|
||||
|---|---|---|
|
||||
| face_groups 有 rows | `SELECT COUNT(*) FROM face_groups WHERE file_uuid=?` | ✅ ≥ cluster 數 |
|
||||
| group 名稱不重複 | `SELECT COUNT(DISTINCT name)` = `COUNT(*)` | ✅ |
|
||||
| 每群至少 1 member | `COUNT(tp.trace_id) >= 1 per group` | ✅ |
|
||||
| trace_profiles.group_id 不懸空 | `SELECT COUNT(*) FROM trace_profiles WHERE group_id IS NOT NULL AND group_id NOT IN (SELECT id FROM face_groups)` | ✅ = 0 |
|
||||
| origin_cluster_id 對應 | `face_groups.origin_cluster_id` 存在於 `face_cluster.json clusters[*].cluster_id` | ✅ |
|
||||
| 無重複群組 | 同名 cluster 不會被 materialize 兩次 | ✅ |
|
||||
| dissolved 標記不影響顯示 | `properties @> '{"dissolved": true}'` 的群組不出現在 API 回應 | ✅ |
|
||||
|
||||
### 4.3 API 回應驗證
|
||||
|
||||
| 端點 | 檢查項 | 合格標準 |
|
||||
|---|---|---|
|
||||
| `/cluster-results` | `face_groups[].trace_ids` 不為空 | ✅ 每群至少 1 trace_id |
|
||||
| `/cluster-results` | `frames[].faces[].cluster_id` 對應到 group_id | ✅ 可映射 |
|
||||
| `/cluster-results` | `frames[].faces[].trace_id` 存在 | ✅ 非 null |
|
||||
| `/face-groups` | `face_groups[].trace_count > 0` | ✅ |
|
||||
| `/face-groups` | `unassigned_traces` 只含 group_id IS NULL 的 trace | ✅ |
|
||||
|
||||
```python
|
||||
def check_face_groups_db(uuid: str, cluster_json: dict, api_response: dict) -> dict:
|
||||
"""驗證 face_groups DB 與 face_cluster.json 的一致性"""
|
||||
results = {'pass': True, 'issues': []}
|
||||
|
||||
groups = api_response.get('face_groups', [])
|
||||
frames = api_response.get('frames', [])
|
||||
|
||||
if not groups:
|
||||
results['pass'] = False
|
||||
results['issues'].append('API 返回 0 個群組')
|
||||
return results
|
||||
|
||||
# 每群都有 trace_ids
|
||||
empty_groups = [g for g in groups if not g.get('trace_ids')]
|
||||
if empty_groups:
|
||||
results['issues'].append(
|
||||
f'{len(empty_groups)} 個群組 trace_ids 為空: {[g["name"] for g in empty_groups]}'
|
||||
)
|
||||
|
||||
# frames 中 cluster_id 映射到有效 group_id
|
||||
group_ids = {g['group_id'] for g in groups}
|
||||
frame_face_ids = set()
|
||||
for f in frames:
|
||||
for fa in f.get('faces') or []:
|
||||
cid = fa.get('cluster_id')
|
||||
if cid and cid not in group_ids:
|
||||
results['issues'].append(f'frame face cluster_id={cid} 不對應任何 group')
|
||||
if fa.get('trace_id') is not None:
|
||||
frame_face_ids.add(fa['trace_id'])
|
||||
|
||||
# trace_id 一致性:DB groups 的 trace_ids 集合 ≈ frames 中的 trace_id 集合
|
||||
db_traces = set()
|
||||
for g in groups:
|
||||
db_traces.update(g.get('trace_ids', []))
|
||||
|
||||
if db_traces != frame_face_ids:
|
||||
missing_in_db = frame_face_ids - db_traces
|
||||
extra_in_db = db_traces - frame_face_ids
|
||||
if missing_in_db:
|
||||
results['issues'].append(f'{len(missing_in_db)} traces 在 frames 中但不在 DB groups 中')
|
||||
if extra_in_db:
|
||||
results['issues'].append(f'{len(extra_in_db)} traces 在 DB groups 中但不在 frames 中')
|
||||
|
||||
return results
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 完整檢查腳本
|
||||
|
||||
以下是單一指令跑完整個 face pipeline 檢查的 Python 腳本:
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3.11
|
||||
"""
|
||||
face_pipeline_check.py — 完整檢查 face → traced → cluster → groups
|
||||
用法:python3.11 face_pipeline_check.py <uuid> [--api-key KEY] [--api-url URL]
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
import requests
|
||||
|
||||
OUTPUT_DIR = '/Users/accusys/momentry/output'
|
||||
|
||||
def check_file(uuid):
|
||||
"""Step 0: 檢查檔案存在"""
|
||||
files = {
|
||||
'face': f'{uuid}.face.json',
|
||||
'traced': f'{uuid}.face_traced.json',
|
||||
'cluster': f'{uuid}.face_cluster.json',
|
||||
}
|
||||
status = {'exists': {}}
|
||||
for name, fname in files.items():
|
||||
path = os.path.join(OUTPUT_DIR, fname)
|
||||
status['exists'][name] = os.path.exists(path)
|
||||
if status['exists'][name]:
|
||||
status['exists'][f'{name}_size'] = os.path.getsize(path)
|
||||
|
||||
missing = [n for n, e in status['exists'].items() if isinstance(e, bool) and not e]
|
||||
if missing:
|
||||
print(f'❌ 缺少檔案: {missing}')
|
||||
return status
|
||||
|
||||
def check_face_json(uuid):
|
||||
"""Step 1: face.json 驗證"""
|
||||
path = os.path.join(OUTPUT_DIR, f'{uuid}.face.json')
|
||||
if not os.path.exists(path):
|
||||
return {'pass': False, 'issues': ['face.json 不存在']}
|
||||
|
||||
d = json.load(open(path))
|
||||
issues = []
|
||||
|
||||
total = d.get('total_faces', 0)
|
||||
fc = d.get('frame_count', 0)
|
||||
fps = d.get('fps', 0)
|
||||
frames = d.get('frames') or []
|
||||
|
||||
if fc == 0: issues.append('frame_count = 0')
|
||||
if fps < 1: issues.append(f'fps = {fps} (< 1)')
|
||||
if len(frames) != fc: issues.append(f'frames 數量 {len(frames)} != frame_count {fc}')
|
||||
|
||||
# embedding 檢查
|
||||
emb_total = 0; emb_missing = 0; emb_bad = 0
|
||||
for fr in frames:
|
||||
for fa in fr.get('faces') or []:
|
||||
emb_total += 1
|
||||
emb = fa.get('embedding')
|
||||
if emb is None:
|
||||
emb_missing += 1
|
||||
elif not isinstance(emb, list) or len(emb) != 512:
|
||||
emb_bad += 1
|
||||
|
||||
if emb_missing: issues.append(f'{emb_missing}/{emb_total} faces 缺少 embedding')
|
||||
if emb_bad: issues.append(f'{emb_bad}/{emb_total} faces embedding 非 512D')
|
||||
|
||||
return {'pass': len(issues) == 0, 'total_faces': total, 'issues': issues}
|
||||
|
||||
def check_face_traced(uuid, face_result):
|
||||
"""Step 2: face_traced.json 驗證"""
|
||||
path = os.path.join(OUTPUT_DIR, f'{uuid}.face_traced.json')
|
||||
if not os.path.exists(path):
|
||||
return {'pass': False, 'issues': ['face_traced.json 不存在']}
|
||||
|
||||
d = json.load(open(path))
|
||||
issues = []
|
||||
traces = d.get('traces') or []
|
||||
|
||||
if not traces: issues.append('traces 為空')
|
||||
|
||||
# trace_id 唯一
|
||||
tids = [t['trace_id'] for t in traces]
|
||||
if len(tids) != len(set(tids)):
|
||||
issues.append(f'trace_id 重複: {len(tids)} rows, {len(set(tids))} unique')
|
||||
|
||||
# frame_count 合理性
|
||||
for t in traces:
|
||||
if t.get('frame_count', 0) < 1:
|
||||
issues.append(f'trace {t["trace_id"]}: frame_count < 1')
|
||||
bc = t.get('best_confidence', -1)
|
||||
if not (0 <= bc <= 1):
|
||||
issues.append(f'trace {t["trace_id"]}: best_confidence={bc}')
|
||||
|
||||
return {'pass': len(issues) == 0, 'trace_count': len(traces), 'issues': issues}
|
||||
|
||||
def check_face_cluster(uuid, traced_result):
|
||||
"""Step 3: face_cluster.json 驗證"""
|
||||
path = os.path.join(OUTPUT_DIR, f'{uuid}.face_cluster.json')
|
||||
if not os.path.exists(path):
|
||||
return {'pass': False, 'issues': ['face_cluster.json 不存在']}
|
||||
|
||||
d = json.load(open(path))
|
||||
issues = []
|
||||
clusters = d.get('clusters') or []
|
||||
frames = d.get('frames') or []
|
||||
|
||||
if not clusters: issues.append('clusters 為空')
|
||||
|
||||
# cluster_id 唯一
|
||||
cids = [c['cluster_id'] for c in clusters]
|
||||
if len(cids) != len(set(cids)):
|
||||
issues.append('cluster_id 重複')
|
||||
|
||||
# frame faces 完整性
|
||||
frame_faces = []
|
||||
for f in frames:
|
||||
for fa in f.get('faces') or []:
|
||||
frame_faces.append(fa)
|
||||
|
||||
if not frame_faces: issues.append('frames 中沒有 faces')
|
||||
|
||||
# cluster_id 一致性
|
||||
valid_cids = set(cids)
|
||||
bad = sum(1 for fa in frame_faces if fa.get('cluster_id') not in valid_cids)
|
||||
if bad: issues.append(f'{bad} frame faces 的 cluster_id 不在 clusters 中')
|
||||
|
||||
# trace_id 存在
|
||||
no_trace = sum(1 for fa in frame_faces if fa.get('trace_id') is None)
|
||||
if no_trace: issues.append(f'{no_trace} frame faces 缺少 trace_id')
|
||||
|
||||
return {'pass': len(issues) == 0, 'cluster_count': len(clusters),
|
||||
'frame_face_count': len(frame_faces), 'issues': issues}
|
||||
|
||||
def check_api(uuid, api_key, api_url):
|
||||
"""Step 4: API 回應驗證"""
|
||||
headers = {'X-API-Key': api_key}
|
||||
issues = []
|
||||
|
||||
# cluster-results
|
||||
url = f'{api_url}/api/v1/cluster-results?file_hash={uuid}'
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
issues.append(f'cluster-results HTTP {resp.status_code}')
|
||||
return {'pass': False, 'issues': issues}
|
||||
d = resp.json()
|
||||
except Exception as e:
|
||||
issues.append(f'cluster-results 請求失敗: {e}')
|
||||
return {'pass': False, 'issues': issues}
|
||||
|
||||
groups = d.get('face_groups', [])
|
||||
frames = d.get('frames', [])
|
||||
|
||||
if not groups:
|
||||
issues.append('face_groups 為空')
|
||||
|
||||
empty_groups = [g for g in groups if not g.get('trace_ids')]
|
||||
if empty_groups:
|
||||
issues.append(f'{len(empty_groups)} 群組 trace_ids 為空')
|
||||
|
||||
# frames faces 完整性
|
||||
f_faces = []
|
||||
for f in frames:
|
||||
for fa in f.get('faces') or []:
|
||||
f_faces.append(fa)
|
||||
|
||||
no_trace = sum(1 for fa in f_faces if fa.get('trace_id') is None)
|
||||
if no_trace:
|
||||
issues.append(f'{no_trace} API frame faces 缺少 trace_id')
|
||||
|
||||
return {'pass': len(issues) == 0, 'group_count': len(groups),
|
||||
'frame_count': len(frames), 'issues': issues}
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Face Pipeline Checker')
|
||||
parser.add_argument('uuid', help='file_uuid to check')
|
||||
parser.add_argument('--api-key', default='', help='API key')
|
||||
parser.add_argument('--api-url', default='http://localhost:3002', help='API base URL')
|
||||
parser.add_argument('--quiet', '-q', action='store_true', help='Only show pass/fail')
|
||||
args = parser.parse_args()
|
||||
|
||||
results = {'uuid': args.uuid, 'steps': {}}
|
||||
overall_pass = True
|
||||
|
||||
# Step 0
|
||||
r0 = check_file(args.uuid)
|
||||
results['steps']['0_files'] = r0
|
||||
|
||||
# Step 1
|
||||
r1 = check_face_json(args.uuid)
|
||||
results['steps']['1_face_json'] = r1
|
||||
if not r1['pass']: overall_pass = False
|
||||
|
||||
# Step 2
|
||||
r2 = check_face_traced(args.uuid, r1)
|
||||
results['steps']['2_face_traced'] = r2
|
||||
if not r2['pass']: overall_pass = False
|
||||
|
||||
# Step 3
|
||||
r3 = check_face_cluster(args.uuid, r2)
|
||||
results['steps']['3_face_cluster'] = r3
|
||||
if not r3['pass']: overall_pass = False
|
||||
|
||||
# Step 4
|
||||
r4 = check_api(args.uuid, args.api_key, args.api_url)
|
||||
results['steps']['4_api'] = r4
|
||||
if not r4['pass']: overall_pass = False
|
||||
|
||||
# Print
|
||||
if args.quiet:
|
||||
print('PASS' if overall_pass else 'FAIL')
|
||||
for name, r in results['steps'].items():
|
||||
if r.get('issues'):
|
||||
for i in r['issues']:
|
||||
print(f' {name}: {i}')
|
||||
else:
|
||||
print(f'\n{"="*60}')
|
||||
print(f'Face Pipeline Check: {args.uuid}')
|
||||
print(f'{"="*60}\n')
|
||||
|
||||
for name, r in results['steps'].items():
|
||||
icon = '✅' if r.get('pass', True) else '❌'
|
||||
print(f'{icon} {name}')
|
||||
if r.get('issues'):
|
||||
for i in r['issues']:
|
||||
print(f' ⚠️ {i}')
|
||||
# Print stats
|
||||
for key in ['total_faces', 'trace_count', 'cluster_count', 'frame_face_count', 'group_count', 'frame_count']:
|
||||
if key in r:
|
||||
print(f' {key}: {r[key]}')
|
||||
print()
|
||||
|
||||
print(f'\nOverall: {"✅ PASS" if overall_pass else "❌ FAIL"}')
|
||||
print()
|
||||
|
||||
return 0 if overall_pass else 1
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 檢查結果判定表
|
||||
|
||||
| 階段 | 通過 | 警告 | 失敗 |
|
||||
|---|---|---|---|
|
||||
| face.json | total_faces ≥ 0, embedding 全部 512D | total_faces = 0(影片無臉) | embedding missing/bad |
|
||||
| face_traced | traces ≥ 1, trace_id 唯一, confidence ∈ [0,1] | frame_count 總和 < face_count | traces 為空 / 重複 ID |
|
||||
| face_cluster | clusters ≥ 1, frame faces 完整性 | clusters 數量異常多/少 | clusters 為空 / cluster_id 不一致 |
|
||||
| API/DB | groups ≥ 1, 每群 trace_ids 不為空 | — | groups 為空 / trace_ids 全空 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 使用方式
|
||||
|
||||
```bash
|
||||
# 完整檢查單一檔案
|
||||
python3.11 face_pipeline_check.py b496a68800f90770aa7246c877f38985 \
|
||||
--api-key "muser_xxx" --api-url "http://localhost:3002"
|
||||
|
||||
# 快速模式(只輸出 PASS/FAIL)
|
||||
python3.11 face_pipeline_check.py b496a68800f90770aa7246c877f38985 \
|
||||
--api-key "muser_xxx" -q
|
||||
|
||||
# 批次檢查所有已完成檔案
|
||||
for uuid in $(psql -t -A -c "SELECT file_uuid FROM videos WHERE status='completed'"); do
|
||||
python3.11 face_pipeline_check.py $uuid --api-key "muser_xxx" -q
|
||||
done
|
||||
```
|
||||
@@ -0,0 +1,23 @@
|
||||
# FS Count Display Issue
|
||||
|
||||
## Problem
|
||||
Face group cards sometimes don't show the FS count number.
|
||||
|
||||
## Root Cause
|
||||
`src/views/PeopleView.vue:1153` - `faceGroups` computed property:
|
||||
```javascript
|
||||
trace_count: c.trace_count, // no fallback
|
||||
```
|
||||
|
||||
When `c.trace_count` is `undefined` (e.g., old cache data), the card shows empty.
|
||||
|
||||
## Proposed Fix
|
||||
```javascript
|
||||
trace_count: c.trace_count ?? traceIds.length,
|
||||
```
|
||||
|
||||
## Files to Modify
|
||||
- `/Users/accusys/momentry_studio/src/views/PeopleView.vue`
|
||||
|
||||
## Assigned to
|
||||
Studio team
|
||||
@@ -0,0 +1,94 @@
|
||||
# launchd 服務全面盤點與管理改善方案 — 2026-11-05
|
||||
|
||||
| 項目 | 內容 |
|
||||
|------|------|
|
||||
| **範圍** | 本機(m5max128, macOS, arm64)全部 LaunchAgents 服務盤點、發現的漂移與重複、治理建議 |
|
||||
| **方法** | `plutil` 逐 plist 解析欄位 + `launchctl list` 對照 + `lsof`/`ps` 埠層核對 |
|
||||
| **狀態** | §3 行動清單已核可執行(1.1 版) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 服務清單與現況
|
||||
|
||||
### 1.1 momentry 核心鏈
|
||||
|
||||
| Service | 狀態 | Port | Binary | 註記 |
|
||||
|---|---|---|---|---|
|
||||
| `com.momentry.api` | 🟢 PID 857 | 3002 | ✅ `momentry_core/target/release/momentry` | wrapper_production.sh exec target/release;**初版誤判為 /tmp,已更正**——從未使用 /tmp(對 /health 需 API key,正常) |
|
||||
| `com.momentry.pipeline_worker` | 🟢 PID 63939 | - | ✅ `momentry_core/target/release/pipeline_worker` | 實際處理任務的 worker |
|
||||
| `com.momentry.worker` | ⚪ 未註冊(備用) | - | ✅(已修)`momentry_core/target/release/momentry` | plist 已改指 target/release;**保持未註冊**避免與 pipeline_worker 雙跑,需要時再 bootstrap |
|
||||
| `com.momentry.proxy` | 🟢 PID 64947 | 8888 | ✅(已修)`/Users/accusys/momentry/bin/momentry-proxy` | **本次修復**——此前由 studio 的 `npm run dev` 附帶 spawn(debug build、kill -9 搶 8888);package.json dev script 已改純 `vite`、plist 改 release binary 並 bootstrap |
|
||||
| `com.momentry.embedding` | 🟢 PID 896 | 11436 | wrapper_embedding.sh | OK |
|
||||
| `com.momentry.chat-llamacpp` | 🟢 PID 56973 | 8080 | ✅ `~/llama.cpp/build/bin/llama-server` | **本次修復註冊**(gemma4 + mmproj;語音轉錄 004/020 已驗證) |
|
||||
| `com.momentry.markbase` | 🟢 PID 904 | 11438 | ✅ `~/markbase/target/release/markbase-core` | OK |
|
||||
| `com.momentry.markbaseengine` | 🟢 PID 891 | 8089 | `~/markbaseengine_service` | OK |
|
||||
| `com.momentry.sftpgo` | 🟢 PID 882 | 2022/8081/8090 | `~/bin/sftpgo` | OK |
|
||||
| `com.momentry.gitea` | 🟢 PID 865 | 3000 | `~/gitea/bin/gitea` | OK |
|
||||
| `com.momentry.studio` | 🟢 PID 888 | 3200/5173 | npm | OK |
|
||||
|
||||
### 1.2 基礎設施
|
||||
|
||||
| Service | 狀態 | Port | 註記 |
|
||||
|---|---|---|---|
|
||||
| PostgreSQL(自管版) | 🟢 PID 414 | 5432 | `/Users/accusys/pgsql/18.3/bin/postgres`;launchctl 上 `com.momentry.postgresql` 顯示 EXIT=0,實際行程非該 plist 巢管(來源待查) |
|
||||
| Redis | 🟢 單一(本次裁減後) | 6379 | **原雙活已裁減**:pid 833(手動裸啟、無 config、無資料、cwd=/)已終止;保留 `sh.brew.redis` pid 885(382 keys 完好)。⚠️ 兩者皆未設密碼,而 AGENTS 連線字串含 `:accusys@`——建議補 `requirepass` 對齊 |
|
||||
| MongoDB | 🟢 PID 856 | 27017 | 跑的是 `homebrew.mxcl.mongodb-community`;`com.momentry.mongodb` EXIT=100 |
|
||||
| MariaDB | 🟢 PID 901 | 3306 | 跑的是 `homebrew.mxcl.mariadb`(WordPress legacy) |
|
||||
| 反向代理 | ⚠️ | 9001/9002 | `homebrew.mxcl.nginx` 在跑;`com.momentry.caddy` EXIT=0 未啟動 → 80/443 對外層缺位 |
|
||||
| Ollama | 🟢 PID 880 | 11434 | `homebrew.mxcl.ollama`(port_registry 有列,用途待確認) |
|
||||
|
||||
### 1.3 重複/歧義服務(治理第一刀)
|
||||
|
||||
| 領域 | 兩個來源 | 建議 |
|
||||
|---|---|---|
|
||||
| PHP-FPM | ~~`com.momentry.php`(PID 861)~~ + `homebrew.mxcl.php@8.4`(PID 884) | ✅ **已裁減**(2026-11-05):bootout `com.momentry.php`、plist 改名 `.disabled`;9100 pool 由 brew php@8.4 續服 |
|
||||
| Ollama | `homebrew.mxcl.ollama` + `com.momentry.ollama` | 保 homebrew 版,刪 momentry plist |
|
||||
| MariaDB | `homebrew.mxcl.mariadb` + `com.momentry.mariadb` | 保 homebrew 版,刪 momentry plist |
|
||||
| MongoDB | `homebrew.mxcl.mongodb-community` + `com.momentry.mongodb` | 保 homebrew 版 |
|
||||
| 舊 LLM 服務 | `com.momentry.llamacpp` / `llamacpp-a4b` / `llamacpp-e4b` | ✅ **已下架**(2026-11-05):bootout + plist 改名 `.disabled`;統一由 `com.momentry.chat-llamacpp` 服務 |
|
||||
| 反向代理 | caddy(不跑)vs nginx(:9001/9002) | 依 port_registry 決定一人(80/443 → Caddy 為文件設計) |
|
||||
|
||||
### 1.4 本次已修復
|
||||
|
||||
| 修復 | 結果 |
|
||||
|---|---|
|
||||
| `com.momentry.chat-llamacpp` 處於 disabled 狀態(`launchctl print-disabled` 可見),導致 `bootstrap` 回 error 5 | `launchctl enable` → `bootstrap` 成功;:8080 回歸 launchd 管理,KeepAlive 看門狗生效,健康檢查 200 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 治理方案(建議,按優先級)
|
||||
|
||||
| # | 提案 | 理由 |
|
||||
|---|------|------|
|
||||
| P1 | **生產 binary 移出 `/tmp/final_install`**:api / worker / proxy 的 plist 與始動路徑改到 `/Users/accusys/momentry_core/target/release/` | /tmp 在重開機可能被清空;且與 AGENTS.md 記載(target/release/momentry)一致 |
|
||||
| P2 | **plist 單一來源**:以 `momentry_core/momentry_runtime/plist/` 為唯一母本,提供 install 腳本布林部署到 `~/Library/LaunchAgents`;一律 `launchctl bootstrap` / `bootout`(不再用 `load` / `unload`) | 現況多處漂移(/tmp、EXIT=0 仍掛空 plist) |
|
||||
| P3 | **port 單一擁有者**:以 `config/port_registry.tsv` 為 source of truth,新增服務前先查是否已有人佔用同一 port | 現況雙 redis、雙 php 已是第一梯队撞名 |
|
||||
| P4 | **重複服務裁減**:PHP / Ollama / MariaDB / MongoDB 依 §1.3 建議二擇一 | 消除行為歧義 |
|
||||
| P5 | **日誌統一 + rotation**:各 plist 統一輸出到 momentry_core/logs/\<service\>.log,加大小/時間輪替策略 | 現況分散(~/momentry/log、logs、temp 皆有) |
|
||||
| P6 | **KeepAlive 政策**:核心服務(api/worker/llama/qdrant/redis/pg)= true;週邊輔助 = 依任務性質 | 失敗自動復活,本次 chat-llamacpp 即靠此修復 |
|
||||
| P7 | **啟動依賴順序**:infra(pg→redis→qdrant→mongo)→ LLM(8080→11436)→ app(api→worker)在 plist 加 `AssociatedBundleIdentifiers`-無效者改以 start script 排程 | 避免 app 起來但 data layer 未就緒 |
|
||||
| P8 | **定期健康快照**:腳本比對 `launchctl list` 與 port_registry,輸出偏差報告(EXIT 非 0、未註冊、雙活) | 將本份盤點自動化 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 立即行動清單(2026-11-05 已核可執行)
|
||||
|
||||
| # | 動作 | 結果 |
|
||||
|---|------|------|
|
||||
| 1 | api / worker / proxy plist binary 移出 `/tmp/final_install` | ✅ 完成。api 原本就正確(wrapper → target/release,初版報告誤判已更正);worker plist 已改 target/release + WD `momentry_core`(保持未註冊備用);proxy plist 已改 `/Users/accusys/momentry/bin/momentry-proxy` |
|
||||
| 2 | `com.momentry.proxy` 納回 launchd 管理 | ✅ 完成。PID 64947、:8888 正常;衝突源已消除——`momentry_studio/package.json` 的 `dev` script 移除「kill -9 8888 + spawn debug proxy」段落,改純 `vite` |
|
||||
| 3 | redis pid 833 裁掉 | ✅ 完成。確認 833 = 手動裸啟、無密碼、無任何資料庫檔、cwd=/;終止後 brew 885 單獨服務,DBSIZE 382 無損、PING OK |
|
||||
| 4 | PHP 二擇一 → homebrew php@8.4;停 `com.momentry.php` | ✅ 完成。bootout 後 9000 pool 由 884(brew php@8.4)續服;plist 改名 `.disabled` |
|
||||
| 5 | caddy vs nginx:80/443 歸 caddy | ⏸ 未執行(本次未核可) |
|
||||
| 6 | 舊 llamacpp plist ×3 移除 | ✅ 完成。bootout + 改名 `*.plist.disabled`(重開機不會復活) |
|
||||
|
||||
> rollback 方式:`.disabled` 檔案改回原名 + `launchctl bootstrap` 即可。
|
||||
|
||||
---
|
||||
|
||||
## 4. 版本歷史
|
||||
|
||||
| 版本 | 日期 | 變更 |
|
||||
|------|------|------|
|
||||
| 1.0 | 2026-11-05 | 初版盤點;修復 chat-llamacpp disabled 狀態並註冊回 launchd;提出 P1–P8 治理方案(OpenCode) |
|
||||
| 1.1 | 2026-11-05 | §3 行動清單核可執行(#1/2/3/4/6 完成,#5 待議):proxy 納回 launchd(PID 64947)、redis 雙活裁減、php/舊 llamacpp plist 下架;更正 api 誤判與 proxy 脫管根因(studio dev script 搶 8888) |
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
#!/bin/bash
|
||||
# 打包 MomentryCore.dmg
|
||||
set -e
|
||||
|
||||
SRC="/Users/accusys/momentry_core"
|
||||
BUILD="$SRC/installer/build"
|
||||
APP="$BUILD/MomentryCore"
|
||||
|
||||
echo ">>> 清理舊 build..."
|
||||
rm -rf "$BUILD"
|
||||
mkdir -p "$APP"/{bin,config,tools,logs}
|
||||
|
||||
echo ">>> 複製 binaries..."
|
||||
cp "$SRC/target/release/momentry" "$APP/bin/" 2>/dev/null || echo " [!] momentry 不存在,執行: cargo build --release"
|
||||
cp "$SRC/target/release/pipeline_worker" "$APP/bin/" 2>/dev/null || echo " [!] pipeline_worker 不存在"
|
||||
chmod +x "$APP/bin/"* 2>/dev/null || true
|
||||
|
||||
echo ">>> 複製 config..."
|
||||
cp "$SRC/installer/config/"* "$APP/config/"
|
||||
cp "$SRC/config/pipeline_flows.json" "$APP/config/" 2>/dev/null || true
|
||||
cp "$SRC/config/processor_tools_v3.json" "$APP/config/" 2>/dev/null || true
|
||||
cp "$SRC/config/admin_config.json" "$APP/config/" 2>/dev/null || true
|
||||
|
||||
echo ">>> 複製 tools (排除 .build, __pycache__)..."
|
||||
rsync -av --exclude='.build' --exclude='__pycache__' --exclude='*.pyc' \
|
||||
"$SRC/tools/" "$APP/tools/" 2>/dev/null || \
|
||||
cp -rf "$SRC/tools/"* "$APP/tools/" 2>/dev/null || true
|
||||
|
||||
echo ">>> 複製 install.sh..."
|
||||
cp "$SRC/installer/install.sh" "$APP/"
|
||||
cp "$SRC/installer/uninstall.sh" "$APP/"
|
||||
chmod +x "$APP/install.sh" "$APP/uninstall.sh"
|
||||
|
||||
echo ">>> 建立 README..."
|
||||
cat > "$APP/README.txt" << 'README'
|
||||
Momentry Core 安裝說明
|
||||
|
||||
1. 確認依賴已安裝:
|
||||
brew install postgresql redis mongodb-mongosh qdrant ffmpeg python@3.11
|
||||
|
||||
2. 啟動外部服務:
|
||||
brew services start postgresql
|
||||
brew services start redis
|
||||
brew services start mongodb-community
|
||||
brew services start qdrant
|
||||
|
||||
3. 執行安裝腳本:
|
||||
./install.sh
|
||||
|
||||
4. 驗證:
|
||||
curl http://localhost:3002/api/v1/health
|
||||
README
|
||||
|
||||
echo ">>> 建立 .dmg..."
|
||||
DMG="$BUILD/MomentryCore.dmg"
|
||||
hdiutil create -volname "MomentryCore" \
|
||||
-srcfolder "$APP" \
|
||||
-ov -format UDZO "$DMG"
|
||||
|
||||
echo ""
|
||||
echo "================================================"
|
||||
echo " DMG 建立完成!"
|
||||
echo " 位置: $DMG"
|
||||
echo " 大小: $(du -h "$DMG" | cut -f1)"
|
||||
echo "================================================"
|
||||
Binary file not shown.
@@ -0,0 +1,16 @@
|
||||
Momentry Core 安裝說明
|
||||
|
||||
1. 確認依賴已安裝:
|
||||
brew install postgresql redis mongodb-mongosh qdrant ffmpeg python@3.11
|
||||
|
||||
2. 啟動外部服務:
|
||||
brew services start postgresql
|
||||
brew services start redis
|
||||
brew services start mongodb-community
|
||||
brew services start qdrant
|
||||
|
||||
3. 執行安裝腳本:
|
||||
./install.sh
|
||||
|
||||
4. 驗證:
|
||||
curl http://localhost:3002/api/v1/health
|
||||
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,199 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"updated_at": "2026-10-26T17:18:56.139925+00:00",
|
||||
"updated_by": "admin",
|
||||
"vlm_prompts": {
|
||||
"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"
|
||||
},
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"llm_config": {
|
||||
"chat": {
|
||||
"url": "http://localhost:8080/v1/chat/completions",
|
||||
"model": "gemma-4-12b-it",
|
||||
"timeout": 30
|
||||
},
|
||||
"summary": {
|
||||
"url": "http://localhost:8080/v1/chat/completions",
|
||||
"model": "gemma-4-12b-it",
|
||||
"timeout": 60
|
||||
}
|
||||
},
|
||||
"processor_config": {
|
||||
"FACE": {
|
||||
"timeout": 3600,
|
||||
"enabled": true,
|
||||
"tools": [
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "python",
|
||||
"priority": 2,
|
||||
"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"
|
||||
},
|
||||
"POSE": {
|
||||
"timeout": 3600,
|
||||
"enabled": true,
|
||||
"tools": [
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"priority": 1,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
},
|
||||
{
|
||||
"name": "mediapipe",
|
||||
"priority": 2,
|
||||
"enabled": true,
|
||||
"parameters": {
|
||||
"min_confidence": 0.5,
|
||||
"model_complexity": 2
|
||||
}
|
||||
}
|
||||
],
|
||||
"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"
|
||||
},
|
||||
"OCR": {
|
||||
"timeout": 3600,
|
||||
"enabled": true,
|
||||
"tools": [
|
||||
{
|
||||
"name": "swift",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"parameters": {}
|
||||
}
|
||||
],
|
||||
"default_tool": "swift"
|
||||
}
|
||||
},
|
||||
"filter_config": {
|
||||
"face": {
|
||||
"min_confidence": 0.5,
|
||||
"min_size": 30
|
||||
}
|
||||
},
|
||||
"face_filter_defaults": {
|
||||
"min_confidence": 50.0,
|
||||
"min_size": 1,
|
||||
"min_capture_quality": 0.25
|
||||
},
|
||||
"paths": {
|
||||
"output_dir": "",
|
||||
"backup_dir": "",
|
||||
"scripts_dir": "",
|
||||
"cli_dir": "",
|
||||
"python_path": "",
|
||||
"ffmpeg_path": ""
|
||||
},
|
||||
"concurrency": {
|
||||
"max_concurrent_jobs": 0,
|
||||
"poll_interval": 0,
|
||||
"batch_size": 0,
|
||||
"processor_timeout_secs": 0
|
||||
},
|
||||
"feature_flags": {
|
||||
"cache_enabled": false,
|
||||
"auto_pipeline_enabled": false,
|
||||
"watcher_auto_register": false,
|
||||
"summary_enabled": false
|
||||
},
|
||||
"server": {
|
||||
"port": 0,
|
||||
"media_base_url": "",
|
||||
"serve_base_url": "",
|
||||
"storage_root": "",
|
||||
"timezone": ""
|
||||
},
|
||||
"admin_settings": {
|
||||
"session_timeout": 0,
|
||||
"max_login_attempts": 0,
|
||||
"api_key_expiry_days": 0,
|
||||
"system_stats_refresh_sec": 0,
|
||||
"preferred_language": ""
|
||||
},
|
||||
"search": {
|
||||
"vlm_min_score": 0.0,
|
||||
"vlm_output_language": "ja"
|
||||
},
|
||||
"pipeline": {
|
||||
"enabled": true,
|
||||
"max_concurrent_stages": 5,
|
||||
"default_timeout_secs": 7200,
|
||||
"flows": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"updated_at": "2026-10-16T17:00:00Z",
|
||||
"updated_by": "core_team",
|
||||
"enabled": true,
|
||||
"max_concurrent_stages": 3,
|
||||
"default_timeout_secs": 3600,
|
||||
"phases": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "基础分析",
|
||||
"name_en": "Foundation",
|
||||
"description": "场景切分与分析",
|
||||
"progress_weight": 0.15,
|
||||
"color": "#4CAF50",
|
||||
"icon": "foundation",
|
||||
"parallel_strategy": "sequential",
|
||||
"processors": ["cut"]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "核心处理",
|
||||
"name_en": "Core Processing",
|
||||
"description": "语音识别、人脸检测、文字识别",
|
||||
"progress_weight": 0.60,
|
||||
"color": "#2196F3",
|
||||
"icon": "processing",
|
||||
"parallel_strategy": "limited_parallel",
|
||||
"max_concurrent": 3,
|
||||
"processors": ["asr_asrx", "face", "ocr"]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "深度分析",
|
||||
"name_en": "Deep Analysis",
|
||||
"description": "说话人识别、场景描述、人脸聚类",
|
||||
"progress_weight": 0.20,
|
||||
"color": "#9C27B0",
|
||||
"icon": "analysis",
|
||||
"parallel_strategy": "limited_parallel",
|
||||
"max_concurrent": 3,
|
||||
"processors": ["scene_vlm", "face_trace", "face_cluster"]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"name": "知识构建",
|
||||
"name_en": "Knowledge Building",
|
||||
"description": "时序知识图谱构建",
|
||||
"progress_weight": 0.05,
|
||||
"color": "#FF9800",
|
||||
"icon": "knowledge",
|
||||
"parallel_strategy": "sequential",
|
||||
"processors": ["tkg"]
|
||||
}
|
||||
],
|
||||
"flows": {
|
||||
"register": {
|
||||
"name": "Video Registration Pipeline",
|
||||
"description": "Complete video processing pipeline for new video files",
|
||||
"version": "2.0.0",
|
||||
"enabled": true,
|
||||
"stages": [
|
||||
{
|
||||
"name": "cut",
|
||||
"processor_type": "cut",
|
||||
"phase": 1,
|
||||
"phase_name": "基础分析",
|
||||
"phase_name_en": "Foundation",
|
||||
"progress_weight": 1.0,
|
||||
"display_name": "场景切分",
|
||||
"display_name_en": "Scene Cut Detection",
|
||||
"description": "Scene cut detection using ffmpeg or Python scenedetect",
|
||||
"required": true,
|
||||
"enabled": true,
|
||||
"timeout_secs": 3600,
|
||||
"parallel": false,
|
||||
"estimated_time_secs": 5,
|
||||
"resource_type": "cpu",
|
||||
"dependencies": [],
|
||||
"tool": {
|
||||
"name": "rust_cut",
|
||||
"priority": 0,
|
||||
"description": "High-performance Rust-based scene detection",
|
||||
"parameters": {
|
||||
"min_scene_duration": 0.5,
|
||||
"threshold": 0.3
|
||||
},
|
||||
"usage_notes": "Uses ffmpeg for native detection. Falls back to Python scenedetect if unavailable."
|
||||
},
|
||||
"condition": {
|
||||
"skip_if_exists": "*.cut.json"
|
||||
},
|
||||
"on_failure": "continue"
|
||||
},
|
||||
{
|
||||
"name": "asr_asrx",
|
||||
"processor_type": "asr_asrx",
|
||||
"phase": 2,
|
||||
"phase_name": "核心处理",
|
||||
"phase_name_en": "Core Processing",
|
||||
"progress_weight": 0.35,
|
||||
"display_name": "語音識別與說話人分離",
|
||||
"display_name_en": "ASR + Speaker Diarization",
|
||||
"description": "Automatic Speech Recognition with Speaker Diarization using Rust + MLX Whisper",
|
||||
"required": false,
|
||||
"enabled": true,
|
||||
"timeout_secs": 3600,
|
||||
"parallel": true,
|
||||
"estimated_time_secs": 25,
|
||||
"resource_type": "gpu",
|
||||
"dependencies": [],
|
||||
"tool": {
|
||||
"name": "rust_asr_asrx",
|
||||
"priority": 0,
|
||||
"description": "High-performance Rust ASR + Diarization with MLX Whisper",
|
||||
"parameters": {
|
||||
"model": "/Users/accusys/models/whisper-small-mlx",
|
||||
"diarize": true
|
||||
},
|
||||
"usage_notes": "Combines ASR and Diarization in one processor. Uses verified whisper-small-mlx model."
|
||||
},
|
||||
"condition": {
|
||||
"skip_if_exists": "*.asr_asrx.json"
|
||||
},
|
||||
"on_failure": "continue"
|
||||
},
|
||||
{
|
||||
"name": "face",
|
||||
"processor_type": "face",
|
||||
"phase": 2,
|
||||
"phase_name": "核心处理",
|
||||
"phase_name_en": "Core Processing",
|
||||
"progress_weight": 0.35,
|
||||
"display_name": "人脸检测",
|
||||
"display_name_en": "Face Detection",
|
||||
"description": "Face detection and tracking",
|
||||
"required": false,
|
||||
"enabled": true,
|
||||
"timeout_secs": 7200,
|
||||
"parallel": true,
|
||||
"estimated_time_secs": 15,
|
||||
"resource_type": "ane",
|
||||
"dependencies": [],
|
||||
"tool": {
|
||||
"name": "swift_face",
|
||||
"priority": 0,
|
||||
"description": "Apple Vision framework face detection (ANE accelerated)",
|
||||
"parameters": {
|
||||
"min_confidence": 0.5,
|
||||
"min_size": 1
|
||||
},
|
||||
"usage_notes": "Uses Apple Neural Engine for acceleration. Falls back to Python InsightFace if unavailable."
|
||||
},
|
||||
"condition": {
|
||||
"skip_if_exists": "*.face.json"
|
||||
},
|
||||
"on_failure": "continue"
|
||||
},
|
||||
{
|
||||
"name": "ocr",
|
||||
"processor_type": "ocr",
|
||||
"phase": 2,
|
||||
"phase_name": "核心处理",
|
||||
"phase_name_en": "Core Processing",
|
||||
"progress_weight": 0.30,
|
||||
"display_name": "文字识别",
|
||||
"display_name_en": "OCR",
|
||||
"description": "OCR text extraction using Apple Vision Framework",
|
||||
"required": false,
|
||||
"enabled": true,
|
||||
"timeout_secs": 7200,
|
||||
"parallel": true,
|
||||
"estimated_time_secs": 10,
|
||||
"resource_type": "ane",
|
||||
"dependencies": [],
|
||||
"tool": {
|
||||
"name": "swift_ocr",
|
||||
"priority": 0,
|
||||
"description": "Apple Vision VNRecognizeTextRequest (ANE accelerated)",
|
||||
"parameters": {
|
||||
"recognition_level": "accurate",
|
||||
"uses_language_correction": true
|
||||
},
|
||||
"usage_notes": "Uses Apple Neural Engine for acceleration. Supports multiple languages with real-time recognition. 2.5x faster than Python (2s vs 5s)."
|
||||
},
|
||||
"condition": {
|
||||
"skip_if_exists": "*.ocr.json"
|
||||
},
|
||||
"on_failure": "continue"
|
||||
},
|
||||
{
|
||||
"name": "scene_vlm",
|
||||
"processor_type": "scene_vlm",
|
||||
"phase": 3,
|
||||
"phase_name": "深度分析",
|
||||
"phase_name_en": "Deep Analysis",
|
||||
"progress_weight": 0.35,
|
||||
"display_name": "场景描述",
|
||||
"display_name_en": "Scene Description",
|
||||
"description": "Scene VLM analysis for scene descriptions",
|
||||
"required": false,
|
||||
"enabled": true,
|
||||
"timeout_secs": 7200,
|
||||
"parallel": true,
|
||||
"estimated_time_secs": 10,
|
||||
"resource_type": "gpu",
|
||||
"dependencies": ["cut"],
|
||||
"tool": {
|
||||
"name": "gemma_vlm",
|
||||
"priority": 0,
|
||||
"description": "Gemma 4 12B with mmproj for vision-language analysis",
|
||||
"parameters": {
|
||||
"max_tokens": 900,
|
||||
"temperature": 0.1
|
||||
},
|
||||
"usage_notes": "Generates scene descriptions in multiple languages. Requires mmproj loaded."
|
||||
},
|
||||
"condition": {
|
||||
"depends_on": "cut",
|
||||
"skip_if_exists": "*.scenes.json"
|
||||
},
|
||||
"on_failure": "continue"
|
||||
},
|
||||
{
|
||||
"name": "face_trace",
|
||||
"processor_type": "face_trace",
|
||||
"phase": 3,
|
||||
"phase_name": "深度分析",
|
||||
"phase_name_en": "Deep Analysis",
|
||||
"progress_weight": 0.20,
|
||||
"display_name": "人脸追踪",
|
||||
"display_name_en": "Face Tracing",
|
||||
"description": "Face tracking to generate face traces using IoU + Embedding Similarity",
|
||||
"required": false,
|
||||
"enabled": true,
|
||||
"timeout_secs": 3600,
|
||||
"parallel": true,
|
||||
"estimated_time_secs": 5,
|
||||
"resource_type": "cpu",
|
||||
"dependencies": ["face"],
|
||||
"tool": {
|
||||
"name": "rust_face_trace",
|
||||
"priority": 0,
|
||||
"description": "Rust-based face tracking with IoU + Embedding similarity matching",
|
||||
"parameters": {
|
||||
"similarity_threshold": 0.85,
|
||||
"iou_threshold": 0.3
|
||||
},
|
||||
"usage_notes": "Uses Qdrant _faces collection for embeddings. Matches faces based on IoU (bbox overlap) and embedding similarity. Traces are continuous face sequences; same person may have multiple traces due to cuts or temporary exits."
|
||||
},
|
||||
"condition": {
|
||||
"depends_on": "face",
|
||||
"skip_if_exists": "*.face_traced.json"
|
||||
},
|
||||
"on_failure": "continue"
|
||||
},
|
||||
{
|
||||
"name": "face_cluster",
|
||||
"processor_type": "face_cluster",
|
||||
"phase": 3,
|
||||
"phase_name": "深度分析",
|
||||
"phase_name_en": "Deep Analysis",
|
||||
"progress_weight": 0.25,
|
||||
"display_name": "人脸聚类",
|
||||
"display_name_en": "Face Clustering",
|
||||
"description": "Face clustering and grouping with improved threshold",
|
||||
"required": false,
|
||||
"enabled": true,
|
||||
"timeout_secs": 3600,
|
||||
"parallel": true,
|
||||
"estimated_time_secs": 5,
|
||||
"resource_type": "cpu",
|
||||
"dependencies": ["face_trace"],
|
||||
"tool": {
|
||||
"name": "rust_face_cluster",
|
||||
"priority": 0,
|
||||
"description": "Rust-based face clustering with Stage 2 merge support",
|
||||
"parameters": {
|
||||
"threshold": 0.15,
|
||||
"stage2": false,
|
||||
"method": "leader",
|
||||
"min_face_count": 20,
|
||||
"max_bbox_area": 150000
|
||||
},
|
||||
"usage_notes": "Uses Qdrant _faces collection for embeddings. Threshold=0.15 to correctly separate male/female faces. Stage 2 merge disabled to prevent over-merging. Auto-filters low-quality clusters: face_count<20 or bbox_area>150000 (hand/object detections)."
|
||||
},
|
||||
"condition": {
|
||||
"depends_on": "face_trace",
|
||||
"skip_if_exists": "*.face_cluster.json"
|
||||
},
|
||||
"on_failure": "continue"
|
||||
},
|
||||
{
|
||||
"name": "tkg",
|
||||
"processor_type": "tkg",
|
||||
"phase": 4,
|
||||
"phase_name": "知识构建",
|
||||
"phase_name_en": "Knowledge Building",
|
||||
"progress_weight": 1.0,
|
||||
"display_name": "知识图谱",
|
||||
"display_name_en": "Knowledge Graph",
|
||||
"description": "Temporal knowledge graph construction",
|
||||
"required": false,
|
||||
"enabled": true,
|
||||
"timeout_secs": 3600,
|
||||
"parallel": false,
|
||||
"estimated_time_secs": 5,
|
||||
"resource_type": "cpu",
|
||||
"dependencies": ["asr_asrx", "face_cluster"],
|
||||
"condition": {
|
||||
"depends_on": ["asr_asrx", "face_cluster"],
|
||||
"skip_if_exists": "*.tkg.json"
|
||||
},
|
||||
"on_failure": "continue"
|
||||
}
|
||||
]
|
||||
},
|
||||
"reprocess": {
|
||||
"name": "Reprocessing Pipeline",
|
||||
"description": "Selective reprocessing of specific processors",
|
||||
"version": "2.0.0",
|
||||
"enabled": true,
|
||||
"stages": []
|
||||
},
|
||||
"phase1_pack": {
|
||||
"name": "Phase 1 Packaging Pipeline",
|
||||
"description": "Package Phase 1 results for delivery",
|
||||
"version": "2.0.0",
|
||||
"enabled": true,
|
||||
"stages": [
|
||||
{
|
||||
"name": "pack",
|
||||
"processor_type": "pack",
|
||||
"phase": 4,
|
||||
"phase_name": "知识构建",
|
||||
"phase_name_en": "Knowledge Building",
|
||||
"progress_weight": 1.0,
|
||||
"display_name": "打包",
|
||||
"display_name_en": "Pack",
|
||||
"description": "Create release package with all Phase 1 outputs",
|
||||
"required": true,
|
||||
"enabled": true,
|
||||
"timeout_secs": 600,
|
||||
"parallel": false,
|
||||
"estimated_time_secs": 10,
|
||||
"resource_type": "cpu",
|
||||
"dependencies": [],
|
||||
"parameters": {
|
||||
"phase": 1,
|
||||
"include_metadata": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
{
|
||||
"processor_config": {
|
||||
"face": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_face",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.face.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"asr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_whisper",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--model",
|
||||
"{model_size}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_size": "base"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": "whisper"
|
||||
}
|
||||
},
|
||||
"asr_asrx": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "whisper",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_asr_asrx",
|
||||
"args": [
|
||||
"--input",
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--model",
|
||||
"/Users/accusys/models/whisper-small-mlx",
|
||||
"--diarize",
|
||||
"true"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"output_file": "{file_uuid}.asr_asrx.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": "whisper"
|
||||
}
|
||||
},
|
||||
"asrx": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_asrx",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.asrx.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"ocr": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "swift",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "scripts/swift_processors/.build/release/swift_ocr",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.ocr.json",
|
||||
"timeout": 3600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "swift",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"face_trace": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_store_traced_faces",
|
||||
"args": [
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--min-trace-len",
|
||||
"{min_trace_len}",
|
||||
"--min-confidence",
|
||||
"{min_confidence}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"min_trace_len": 0,
|
||||
"min_confidence": 0.0
|
||||
},
|
||||
"output_file": "{file_uuid}.face_traced.json",
|
||||
"timeout": 600
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"scene_vlm_summary": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": "gemma-4-12b-it",
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_scene_vlm",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}",
|
||||
"--llm-url",
|
||||
"{llm_url}",
|
||||
"--max-tokens",
|
||||
"{max_tokens}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions",
|
||||
"max_tokens": 900
|
||||
},
|
||||
"output_file": "{file_uuid}.scene_vlm.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"tkg": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_tkg",
|
||||
"args": [
|
||||
"--file-uuid",
|
||||
"{file_uuid}",
|
||||
"--output-dir",
|
||||
"{output_dir}"
|
||||
]
|
||||
},
|
||||
"parameters": {},
|
||||
"output_file": "{file_uuid}.tkg.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
},
|
||||
"cut": {
|
||||
"implementations": [
|
||||
{
|
||||
"tool": "rust",
|
||||
"model": null,
|
||||
"priority": 0,
|
||||
"enabled": true,
|
||||
"command": {
|
||||
"executable": "tools/cli/rust/target/release/rust_cut",
|
||||
"args": [
|
||||
"{video_path}",
|
||||
"--output",
|
||||
"{output_path}",
|
||||
"--uuid",
|
||||
"{file_uuid}",
|
||||
"--min-scene-duration",
|
||||
"{min_scene_duration}"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
"use_ffmpeg": true,
|
||||
"min_scene_duration": 0.5
|
||||
},
|
||||
"output_file": "{file_uuid}.cut.json",
|
||||
"timeout": 1800
|
||||
}
|
||||
],
|
||||
"default": {
|
||||
"tool": "rust",
|
||||
"model": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"variables": {
|
||||
"video_path": "Full path to video file",
|
||||
"output_path": "Full path to output JSON file",
|
||||
"output_dir": "Output directory (default: /Users/accusys/momentry/output)",
|
||||
"file_uuid": "Video file UUID",
|
||||
"face_json": "Path to face.json file"
|
||||
},
|
||||
"environment": {
|
||||
"MOMENTRY_OUTPUT_DIR": "/Users/accusys/momentry/output",
|
||||
"MOMENTRY_SCRIPTS_DIR": "tools/script/",
|
||||
"MOMENTRY_CLI_DIR": "tools/cli/",
|
||||
"MOMENTRY_PYTHON_PATH": "/opt/homebrew/bin/python3.11",
|
||||
"DATABASE_SCHEMA": "public",
|
||||
"DATABASE_URL": "postgres://accusys@localhost:5432/momentry",
|
||||
"REDIS_URL": "redis://:accusys@localhost:6379"
|
||||
},
|
||||
"models": {
|
||||
"whisper": {
|
||||
"description": "OpenAI Whisper ASR model",
|
||||
"sizes": [
|
||||
"tiny",
|
||||
"base",
|
||||
"small",
|
||||
"medium",
|
||||
"large",
|
||||
"large-v3"
|
||||
],
|
||||
"default_size": "large-v3",
|
||||
"model_dir": "/Users/accusys/models/whisper-small-mlx"
|
||||
},
|
||||
"mediapipe": {
|
||||
"description": "MediaPipe Pose estimation",
|
||||
"model_path": "/Users/accusys/models/mediapipe/pose_landmarker_heavy.task",
|
||||
"complexity_levels": [
|
||||
0,
|
||||
1,
|
||||
2
|
||||
],
|
||||
"default_complexity": 2
|
||||
},
|
||||
"facenet": {
|
||||
"description": "FaceNet 512D embedding model",
|
||||
"model_path": "/Users/accusys/models/facenet512.mlpackage"
|
||||
},
|
||||
"gemma-4-12b-it": {
|
||||
"description": "Gemma 4 12B instruct model for VLM/LLM",
|
||||
"model_path": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf",
|
||||
"mmproj_path": "/Users/accusys/models/mmproj-F16.gguf",
|
||||
"llm_url": "http://localhost:8080/v1/chat/completions"
|
||||
},
|
||||
"embeddinggemma-300m": {
|
||||
"description": "Embedding Gemma 300M for vector embeddings",
|
||||
"model_path": "/Users/accusys/models/embeddinggemma-300M-Q8_0.gguf",
|
||||
"embedding_url": "http://localhost:11436/embed"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"version": "3.0",
|
||||
"description": "Processor configuration - CLI tools (rust/swift) prioritized",
|
||||
"priority_policy": "rust/swift CLI (priority 0) > python (priority 1+)",
|
||||
"last_updated": "2026-09-27"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
DATABASE_URL=postgres://accusys@localhost:5432/momentry
|
||||
DATABASE_SCHEMA=public
|
||||
REDIS_URL=redis://:accusys@localhost:6379
|
||||
MOMENTRY_REDIS_PREFIX=momentry:
|
||||
MOMENTRY_SERVER_PORT=3002
|
||||
MOMENTRY_OUTPUT_DIR=$HOME/momentry/output
|
||||
MOMENTRY_BACKUP_DIR=$HOME/momentry/backup
|
||||
QDRANT_URL=http://127.0.0.1:6333
|
||||
MONGODB_URL=mongodb://localhost:27017
|
||||
MOMENTRY_LLM_VISION_URL=http://127.0.0.1:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it
|
||||
MOMENTRY_LLM_CHAT_URL=http://127.0.0.1:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it
|
||||
MOMENTRY_LLM_SUMMARY_URL=http://127.0.0.1:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_SUMMARY_MODEL=gemma-4-12b-it
|
||||
MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11
|
||||
RUST_LOG=info
|
||||
Executable
+143
@@ -0,0 +1,143 @@
|
||||
#!/bin/bash
|
||||
# Momentry Core 安裝腳本
|
||||
set -e
|
||||
|
||||
APP_NAME="MomentryCore"
|
||||
INSTALL_DIR="$HOME/Library/Application Support/$APP_NAME"
|
||||
LAUNCHD_DIR="$HOME/Library/LaunchAgents"
|
||||
LOG_DIR="$INSTALL_DIR/logs"
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
NC='\033[0m'
|
||||
|
||||
echo "================================================"
|
||||
echo " Momentry Core 安裝程式"
|
||||
echo "================================================"
|
||||
|
||||
# 1. 檢查依賴
|
||||
echo ">>> 檢查系統依賴..."
|
||||
MISSING=""
|
||||
check() {
|
||||
if eval "$2" >/dev/null 2>&1; then
|
||||
echo " [OK] $1"
|
||||
else
|
||||
echo " [FAIL] $1 - $3"
|
||||
MISSING="$MISSING $1"
|
||||
fi
|
||||
}
|
||||
check "PostgreSQL" "psql --version" "brew install postgresql"
|
||||
check "Redis" "redis-cli ping" "brew install redis"
|
||||
check "Qdrant" "curl -s --max-time 3 http://localhost:6333/ready | grep -q ok" "brew install qdrant"
|
||||
check "MongoDB" "mongosh --version || mongo --version" "brew install mongosh"
|
||||
check "Python 3.11" "python3.11 --version" "brew install python@3.11"
|
||||
check "ffprobe" "ffprobe -version" "brew install ffmpeg"
|
||||
check "MarkBaseServer" "curl -s --max-time 3 http://localhost:8080/v1/models | grep -q model" "安裝 MarkBaseEngine"
|
||||
|
||||
if [ -n "$MISSING" ]; then
|
||||
echo -e "\n${RED}缺少依賴:$MISSING${NC}"
|
||||
echo "brew install postgresql redis mongosh ffmpeg python@3.11"
|
||||
exit 1
|
||||
fi
|
||||
echo -e "\n${GREEN}所有依賴已安裝${NC}"
|
||||
|
||||
# 2. 建立目錄
|
||||
echo ">>> 建立目錄..."
|
||||
mkdir -p "$INSTALL_DIR"/{bin,config,tools/script,tools/cli,logs}
|
||||
SRC_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
cp -f "$SRC_DIR/bin/momentry" "$INSTALL_DIR/bin/" 2>/dev/null || echo " [!] momentry binary 需手動放置"
|
||||
cp -f "$SRC_DIR/bin/pipeline_worker" "$INSTALL_DIR/bin/" 2>/dev/null || echo " [!] pipeline_worker 需手動放置"
|
||||
chmod +x "$INSTALL_DIR/bin/"* 2>/dev/null || true
|
||||
cp -rf "$SRC_DIR/config/"* "$INSTALL_DIR/config/" 2>/dev/null || true
|
||||
cp -rf "$SRC_DIR/tools/"* "$INSTALL_DIR/tools/" 2>/dev/null || true
|
||||
echo " -> $INSTALL_DIR"
|
||||
|
||||
# 3. 產生 .env
|
||||
ENV_FILE="$INSTALL_DIR/.env"
|
||||
if [ ! -f "$ENV_FILE" ]; then
|
||||
cat > "$ENV_FILE" << ENVEOF
|
||||
DATABASE_URL=postgres://accusys@localhost:5432/momentry
|
||||
DATABASE_SCHEMA=public
|
||||
REDIS_URL=redis://:accusys@localhost:6379
|
||||
MOMENTRY_REDIS_PREFIX=momentry:
|
||||
MOMENTRY_SERVER_PORT=3002
|
||||
MOMENTRY_OUTPUT_DIR=$HOME/momentry/output
|
||||
QDRANT_URL=http://127.0.0.1:6333
|
||||
MONGODB_URL=mongodb://localhost:27017
|
||||
MOMENTRY_LLM_VISION_URL=http://127.0.0.1:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it
|
||||
MOMENTRY_LLM_CHAT_URL=http://127.0.0.1:8080/v1/chat/completions
|
||||
MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it
|
||||
MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11
|
||||
MOMENTRY_SCRIPTS_DIR=$INSTALL_DIR/tools/script
|
||||
MOMENTRY_CLI_DIR=$INSTALL_DIR/tools/cli
|
||||
RUST_LOG=info
|
||||
ENVEOF
|
||||
echo " [OK] 已產生 .env"
|
||||
else
|
||||
echo " [OK] .env 已存在"
|
||||
fi
|
||||
|
||||
# 4. 安裝 Launchd
|
||||
echo ">>> 安裝 launchd services..."
|
||||
cat > "$LAUNCHD_DIR/com.momentry-core.server.plist" << PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>Label</key><string>com.momentry-core.server</string>
|
||||
<key>Program</key><string>$INSTALL_DIR/bin/momentry</string>
|
||||
<key>ProgramArguments</key><array>
|
||||
<string>momentry</string><string>server</string>
|
||||
<string>--host</string><string>0.0.0.0</string>
|
||||
<string>--port</string><string>3002</string>
|
||||
</array>
|
||||
<key>WorkingDirectory</key><string>$INSTALL_DIR</string>
|
||||
<key>EnvironmentVariables</key><dict>
|
||||
<key>DOTENV_PATH</key><string>$ENV_FILE</string>
|
||||
</dict>
|
||||
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>StandardOutPath</key><string>$LOG_DIR/server.log</string>
|
||||
<key>StandardErrorPath</key><string>$LOG_DIR/server.log</string>
|
||||
</dict></plist>
|
||||
PLIST
|
||||
|
||||
cat > "$LAUNCHD_DIR/com.momentry-core.worker.plist" << PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>Label</key><string>com.momentry-core.worker</string>
|
||||
<key>Program</key><string>$INSTALL_DIR/bin/pipeline_worker</string>
|
||||
<key>WorkingDirectory</key><string>$INSTALL_DIR</string>
|
||||
<key>EnvironmentVariables</key><dict>
|
||||
<key>DOTENV_PATH</key><string>$ENV_FILE</string>
|
||||
</dict>
|
||||
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>StandardOutPath</key><string>$LOG_DIR/worker.log</string>
|
||||
<key>StandardErrorPath</key><string>$LOG_DIR/worker.log</string>
|
||||
</dict></plist>
|
||||
PLIST
|
||||
echo " [OK] server + worker plist"
|
||||
|
||||
# 5. 啟動
|
||||
echo ">>> 啟動服務..."
|
||||
launchctl bootout "gui/$(id -u)/com.momentry-core.server" 2>/dev/null || true
|
||||
launchctl bootout "gui/$(id -u)/com.momentry-core.worker" 2>/dev/null || true
|
||||
sleep 1
|
||||
launchctl bootstrap "gui/$(id -u)" "$LAUNCHD_DIR/com.momentry-core.server.plist"
|
||||
launchctl bootstrap "gui/$(id -u)" "$LAUNCHD_DIR/com.momentry-core.worker.plist"
|
||||
sleep 3
|
||||
|
||||
if curl -s --max-time 5 "http://localhost:3002/api/v1/health" >/dev/null 2>&1; then
|
||||
echo -e "${GREEN}[OK] API server 啟動成功${NC}"
|
||||
else
|
||||
echo -e "${YELLOW}[!] 檢查日誌: $LOG_DIR/server.log${NC}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "================================================"
|
||||
echo " 安裝完成!"
|
||||
echo " 目錄: $INSTALL_DIR"
|
||||
echo " API: http://localhost:3002"
|
||||
echo "================================================"
|
||||
@@ -0,0 +1,179 @@
|
||||
---
|
||||
title: Tools Directory
|
||||
version: 1.1
|
||||
date: 2026-09-27
|
||||
author: OpenCode
|
||||
status: migrated
|
||||
---
|
||||
|
||||
## 目錄結構
|
||||
|
||||
```
|
||||
tools/
|
||||
├── script/ # Python 處理器腳本
|
||||
│ ├── asr/ # ASR 處理器
|
||||
│ ├── face/ # Face 處理器
|
||||
│ ├── pose/ # Pose 處理器
|
||||
│ ├── cut/ # Cut 處理器
|
||||
│ ├── ocr/ # OCR 處理器
|
||||
│ ├── vlm/ # VLM 處理器
|
||||
│ ├── embedding/ # Embedding 服務器
|
||||
│ ├── identity/ # Identity 處理器
|
||||
│ └── utils/ # 工具腳本
|
||||
└── cli/ # Swift/Rust CLI 工具
|
||||
├── swift/ # Swift 處理器
|
||||
└── rust/ # Rust 處理器
|
||||
```
|
||||
|
||||
## Python 腳本 (script/)
|
||||
|
||||
### ASR
|
||||
- `asr_processor_base.py` - ASR 基礎類
|
||||
- `asr_processor_contract_v1.py` - ASR V1 合約
|
||||
- `asr_processor_contract_v2.py` - ASR V2 合約
|
||||
|
||||
### Face
|
||||
- `face_processor.py` - Face 處理器
|
||||
- `store_traced_faces.py` - Face 追蹤存儲
|
||||
|
||||
### Pose
|
||||
- `pose_processor.py` - Pose 處理器
|
||||
|
||||
### Cut
|
||||
- `cut_processor.py` - Cut 處理器
|
||||
|
||||
### OCR
|
||||
- `ocr_processor.py` - OCR 處理器
|
||||
|
||||
### VLM
|
||||
- `tkg_builder.py` - TKG Builder
|
||||
- `appearance_processor_v2.py` - Appearance 處理器
|
||||
|
||||
### Embedding
|
||||
- `embeddinggemma_server.py` - Embedding 服務器
|
||||
|
||||
### Identity
|
||||
- `identity_agent.py` - Identity Agent
|
||||
- `identity_bind.py` - Identity 綁定
|
||||
- `identity_matcher.py` - Identity 匹配
|
||||
|
||||
## CLI 工具 (cli/)
|
||||
|
||||
### Swift
|
||||
|
||||
**處理器**:
|
||||
- `asr_swift.swift` - ASR Swift 處理器
|
||||
- `asrx_swift.swift` - ASRX Swift 處理器
|
||||
- `swift_face.swift` - Face Swift 處理器
|
||||
- `swift_pose.swift` - Pose Swift 處理器
|
||||
- `swift_ocr.swift` - OCR Swift 處理器
|
||||
- `swift_hand.swift` - Hand Swift 處理器
|
||||
- `swift_face_pose.swift` - Face+Pose Swift 處理器
|
||||
|
||||
**擴展**:
|
||||
- `swift_appearance_expansion.swift` - Appearance 擴展
|
||||
- `swift_pose_expansion.swift` - Pose 擴展
|
||||
|
||||
**測試**:
|
||||
- `face_vision_test.swift`
|
||||
- `pose_benchmark.swift`
|
||||
- `speaker_test.swift`
|
||||
|
||||
### Rust
|
||||
|
||||
獨立的 Rust CLI 工具項目,包含:
|
||||
- Face Cluster
|
||||
- Appearance
|
||||
- Pose
|
||||
|
||||
## 使用方式
|
||||
|
||||
### Python 腳本
|
||||
|
||||
```bash
|
||||
# ASR
|
||||
python3 tools/script/asr/asr_processor_contract_v2.py
|
||||
|
||||
# Face
|
||||
python3 tools/script/face/face_processor.py
|
||||
|
||||
# TKG
|
||||
python3 tools/script/vlm/tkg_builder.py
|
||||
```
|
||||
|
||||
### Swift CLI
|
||||
|
||||
```bash
|
||||
# 編譯
|
||||
cd tools/cli/swift
|
||||
swift build
|
||||
|
||||
# 運行
|
||||
swift run asr_swift
|
||||
swift run swift_face
|
||||
```
|
||||
|
||||
### Rust CLI
|
||||
|
||||
```bash
|
||||
# 編譯
|
||||
cd tools/cli/rust
|
||||
cargo build --release
|
||||
|
||||
# 運行
|
||||
./target/release/face_cluster
|
||||
./target/release/appearance
|
||||
```
|
||||
|
||||
## 環境變數配置
|
||||
|
||||
### 腳本路徑
|
||||
|
||||
```bash
|
||||
# Python 腳本路徑
|
||||
export MOMENTRY_SCRIPTS_DIR=/Users/accusys/momentry_core/tools/script
|
||||
|
||||
# CLI 工具路徑
|
||||
export MOMENTRY_CLI_DIR=/Users/accusys/momentry_core/tools/cli
|
||||
```
|
||||
|
||||
### 其他路徑
|
||||
|
||||
```bash
|
||||
# 輸出路徑
|
||||
export MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output
|
||||
|
||||
# Python 路徑
|
||||
export MOMENTRY_PYTHON_PATH=/opt/homebrew/bin/python3.11
|
||||
```
|
||||
|
||||
## Rust 代碼中使用
|
||||
|
||||
```rust
|
||||
use crate::core::config::{SCRIPTS_DIR, CLI_DIR};
|
||||
|
||||
// 獲取腳本路徑
|
||||
let scripts_dir = SCRIPTS_DIR.as_str();
|
||||
|
||||
// 獲取 CLI 路徑
|
||||
let cli_dir = CLI_DIR.as_str();
|
||||
```
|
||||
|
||||
## 遷移說明
|
||||
|
||||
### 來源
|
||||
|
||||
- Python: `scripts/` → `tools/script/`
|
||||
- Swift: `scripts/swift_processors/` → `tools/cli/swift/`
|
||||
- Rust: `scripts/rust_processors/` → `tools/cli/rust/`
|
||||
|
||||
### 原路徑保留
|
||||
|
||||
舊路徑 `scripts/` 仍然存在,可以繼續使用。
|
||||
|
||||
新代碼建議使用 `tools/` 路徑。
|
||||
|
||||
## 相關文檔
|
||||
|
||||
- `/Users/accusys/momentry_core/docs_v1.0/DESIGN/Tools_Directory_Restructure.md`
|
||||
- `/Users/accusys/momentry_core/AGENTS.md` - 環境變數配置
|
||||
@@ -0,0 +1,2 @@
|
||||
/target
|
||||
Cargo.lock.orig
|
||||
+3144
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,78 @@
|
||||
[package]
|
||||
name = "rust_processors"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_vad"
|
||||
path = "src/bin/rust_vad.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_appearance"
|
||||
path = "src/bin/rust_appearance.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_pose"
|
||||
path = "src/bin/rust_pose.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_cut"
|
||||
path = "src/bin/rust_cut.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_face_cluster"
|
||||
path = "src/bin/rust_face_cluster.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_store_traced_faces"
|
||||
path = "src/bin/rust_store_traced_faces.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_scene_vlm"
|
||||
path = "src/bin/rust_scene_vlm.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_facenet"
|
||||
path = "src/bin/rust_facenet.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_facenet_coreml"
|
||||
path = "src/bin/rust_facenet_coreml.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_face_processor"
|
||||
path = "src/bin/rust_face_processor.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_asrx"
|
||||
path = "src/bin/rust_asrx.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_asr_asrx"
|
||||
path = "src/bin/rust_asr_asrx.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_whisper_rs"
|
||||
path = "src/bin/rust_whisper_rs.rs"
|
||||
|
||||
[dependencies]
|
||||
ort = { version = "2.0.0-rc.13", features = ["download-binaries"] }
|
||||
hound = "3.5"
|
||||
ndarray = "0.17"
|
||||
rustfft = "6.4"
|
||||
anyhow = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
clap = { version = "4.0", features = ["derive"] }
|
||||
image = "0.25"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
async-trait = "0.1"
|
||||
reqwest = { version = "0.12", features = ["json", "blocking"] }
|
||||
base64 = "0.22"
|
||||
regex = "1.0"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.0", features = ["v4"] }
|
||||
ureq = { version = "2.9", features = ["json"] }
|
||||
whisper-rs = { version = "0.16", features = ["metal"] }
|
||||
|
||||
[workspace]
|
||||
@@ -0,0 +1,59 @@
|
||||
[package]
|
||||
name = "rust_processors"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_vad"
|
||||
path = "src/bin/rust_vad.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_appearance"
|
||||
path = "src/bin/rust_appearance.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_pose"
|
||||
path = "src/bin/rust_pose.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_cut"
|
||||
path = "src/bin/rust_cut.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_face_cluster"
|
||||
path = "src/bin/rust_face_cluster.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_store_traced_faces"
|
||||
path = "src/bin/rust_store_traced_faces.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_scene_vlm"
|
||||
path = "src/bin/rust_scene_vlm.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_facenet"
|
||||
path = "src/bin/rust_facenet.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_facenet_coreml"
|
||||
path = "src/bin/rust_facenet_coreml.rs"
|
||||
|
||||
[dependencies]
|
||||
ort = { version = "2.0.0-rc.13", features = ["download-binaries", "coreml"] }
|
||||
hound = "3.5"
|
||||
ndarray = "0.17"
|
||||
anyhow = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
clap = { version = "4.0", features = ["derive"] }
|
||||
image = "0.25"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
async-trait = "0.1"
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
base64 = "0.22"
|
||||
regex = "1.0"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.0", features = ["v4"] }
|
||||
|
||||
[workspace]
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Speaker clustering: faithful port of `speaker_cluster_fixed.py`
|
||||
//! (agglomerative average-linkage with cosine distance).
|
||||
|
||||
/// Cosine distance matrix `[n][n]` for L2-normalized embeddings.
|
||||
/// `dist[i][j] = 1 - dot(e_i, e_j)`.
|
||||
pub fn cosine_distances(embeddings: &[Vec<f32>]) -> Vec<Vec<f32>> {
|
||||
let n = embeddings.len();
|
||||
let mut d = vec![vec![0f32; n]; n];
|
||||
for i in 0..n {
|
||||
for j in (i + 1)..n {
|
||||
let dot: f32 = embeddings[i]
|
||||
.iter()
|
||||
.zip(embeddings[j].iter())
|
||||
.map(|(a, b)| a * b)
|
||||
.sum();
|
||||
let v = 1.0 - dot;
|
||||
d[i][j] = v;
|
||||
d[j][i] = v;
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Port of `estimate_n_speakers_from_embeddings`; result clamped to `[2, max]`.
|
||||
pub fn estimate_n_speakers(distances: &[Vec<f32>], max_speakers: usize) -> usize {
|
||||
let n = distances.len();
|
||||
if n < 2 {
|
||||
return 2;
|
||||
}
|
||||
let sample = n.min(200);
|
||||
let mut min_distances = Vec::with_capacity(sample);
|
||||
for i in 0..sample {
|
||||
let mut row = distances[i].clone();
|
||||
row.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
if row.len() > 1 {
|
||||
min_distances.push(row[1]);
|
||||
}
|
||||
}
|
||||
if min_distances.is_empty() {
|
||||
return 2;
|
||||
}
|
||||
let avg = min_distances.iter().sum::<f32>() / min_distances.len() as f32;
|
||||
let threshold = avg * 1.5;
|
||||
|
||||
let m = min_distances.len();
|
||||
let mut assigned = vec![false; m];
|
||||
let mut n_speakers = 1usize;
|
||||
for i in 0..m {
|
||||
if assigned[i] {
|
||||
continue;
|
||||
}
|
||||
n_speakers += 1;
|
||||
for j in (i + 1)..m {
|
||||
if assigned[j] {
|
||||
continue;
|
||||
}
|
||||
let idx_i = if n > 200 { i * (n / 200) } else { i };
|
||||
let idx_j = if n > 200 { j * (n / 200) } else { j };
|
||||
if idx_i < n && idx_j < n && distances[idx_i][idx_j] < threshold {
|
||||
assigned[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
n_speakers.clamp(2, max_speakers.max(2))
|
||||
}
|
||||
|
||||
/// Agglomerative clustering (average linkage) using a precomputed distance
|
||||
/// matrix, stopping at `k` clusters. Returns a label per point.
|
||||
pub fn agglomerative(distances: &[Vec<f32>], k: usize) -> Vec<usize> {
|
||||
let n = distances.len();
|
||||
if n == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
if k >= n {
|
||||
return (0..n).collect();
|
||||
}
|
||||
let mut d = distances.to_vec();
|
||||
let mut root: Vec<usize> = (0..n).collect(); // union-find representative
|
||||
let mut active = vec![true; n];
|
||||
let mut size = vec![1usize; n];
|
||||
let mut remaining = n;
|
||||
|
||||
while remaining > k {
|
||||
let mut best_i = 0;
|
||||
let mut best_j = 1;
|
||||
let mut best = f32::INFINITY;
|
||||
for i in 0..n {
|
||||
if !active[i] {
|
||||
continue;
|
||||
}
|
||||
for j in (i + 1)..n {
|
||||
if active[j] && d[i][j] < best {
|
||||
best = d[i][j];
|
||||
best_i = i;
|
||||
best_j = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge best_j into best_i (UPGMA average linkage update).
|
||||
let (i, j) = (best_i, best_j);
|
||||
let si = size[i] as f32;
|
||||
let sj = size[j] as f32;
|
||||
for x in 0..n {
|
||||
if x == i || x == j || !active[x] {
|
||||
continue;
|
||||
}
|
||||
let v = (si * d[i][x] + sj * d[j][x]) / (si + sj);
|
||||
d[i][x] = v;
|
||||
d[x][i] = v;
|
||||
}
|
||||
size[i] += size[j];
|
||||
active[j] = false;
|
||||
root[j] = i;
|
||||
remaining -= 1;
|
||||
}
|
||||
|
||||
let find = |root: &Vec<usize>, mut x: usize| -> usize {
|
||||
while root[x] != x {
|
||||
x = root[x];
|
||||
}
|
||||
x
|
||||
};
|
||||
|
||||
let mut label_of: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
|
||||
let mut labels = vec![0usize; n];
|
||||
let mut next = 0usize;
|
||||
for p in 0..n {
|
||||
let r = find(&root, p);
|
||||
let label = *label_of.entry(r).or_insert_with(|| {
|
||||
let l = next;
|
||||
next += 1;
|
||||
l
|
||||
});
|
||||
labels[p] = label;
|
||||
}
|
||||
labels
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! Rust-native speaker diarization (ASRX) building blocks.
|
||||
//!
|
||||
//! - `Frontend`: speechbrain-compatible fbank frontend (framing, STFT via
|
||||
//! rustfft, mel filterbank, log-dB, sentence mean-normalization).
|
||||
//! - `Ecapa`: ECAPA-TDNN speaker-embedding network (ONNX, `feats -> embedding`).
|
||||
|
||||
pub mod cluster;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use ndarray::IxDyn;
|
||||
use ort::session::{builder::GraphOptimizationLevel, Session};
|
||||
use ort::value::Value;
|
||||
use rustfft::num_complex::Complex;
|
||||
use rustfft::FftPlanner;
|
||||
|
||||
pub const SAMPLE_RATE: usize = 16000;
|
||||
pub const N_FFT: usize = 400;
|
||||
pub const HOP_LENGTH: usize = 160;
|
||||
pub const WIN_LENGTH: usize = 400;
|
||||
pub const N_BINS: usize = N_FFT / 2 + 1; // 201
|
||||
pub const N_MELS: usize = 80;
|
||||
const PAD: usize = N_FFT / 2;
|
||||
const AMIN: f32 = 1e-10;
|
||||
const TOP_DB: f32 = 80.0;
|
||||
const MULTIPLIER: f32 = 10.0;
|
||||
|
||||
/// speechbrain-compatible log-mel frontend.
|
||||
pub struct Frontend {
|
||||
window: Vec<f32>,
|
||||
mel: Vec<f32>, // [N_BINS * N_MELS], row-major (freq-major)
|
||||
planner: FftPlanner<f32>,
|
||||
}
|
||||
|
||||
impl Frontend {
|
||||
/// Load the hamming window (400 f32) and the mel matrix (201x80 f32).
|
||||
pub fn new(window_path: &str, mel_path: &str) -> Result<Self> {
|
||||
let window = read_f32_file(window_path)?;
|
||||
if window.len() != WIN_LENGTH {
|
||||
anyhow::bail!(
|
||||
"window file has {} values, expected {}",
|
||||
window.len(),
|
||||
WIN_LENGTH
|
||||
);
|
||||
}
|
||||
let mel = read_f32_file(mel_path)?;
|
||||
if mel.len() != N_BINS * N_MELS {
|
||||
anyhow::bail!(
|
||||
"mel file has {} values, expected {}",
|
||||
mel.len(),
|
||||
N_BINS * N_MELS
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
window,
|
||||
mel,
|
||||
planner: FftPlanner::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Compute log-mel features [n_frames, N_MELS] (flattened) for a waveform.
|
||||
///
|
||||
/// Mirrors speechbrain `Fbank` with `mean_var_norm(norm_type="sentence",
|
||||
/// std_norm=False)`: center-padded framing, power spectrum, mel matmul,
|
||||
/// amplitude-to-dB with top_db clipping, then per-utterance mean removal.
|
||||
pub fn compute_feats(&mut self, samples: &[f32]) -> (Vec<f32>, usize) {
|
||||
let n = samples.len();
|
||||
if n == 0 {
|
||||
return (Vec::new(), 0);
|
||||
}
|
||||
let n_frames = 1 + n / HOP_LENGTH;
|
||||
let mut fbank = vec![0f32; n_frames * N_MELS];
|
||||
|
||||
let fft = self.planner.plan_fft_forward(N_FFT);
|
||||
let mut buffer = vec![Complex::new(0f32, 0f32); N_FFT];
|
||||
|
||||
for t in 0..n_frames {
|
||||
let base = t * HOP_LENGTH;
|
||||
for k in 0..N_FFT {
|
||||
let idx = base + k;
|
||||
let s = if idx >= PAD {
|
||||
let si = idx - PAD;
|
||||
if si < n {
|
||||
samples[si]
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
buffer[k] = Complex::new(s * self.window[k], 0.0);
|
||||
}
|
||||
fft.process(&mut buffer);
|
||||
|
||||
let row = &mut fbank[t * N_MELS..(t + 1) * N_MELS];
|
||||
for m in 0..N_MELS {
|
||||
let mut acc = 0.0f32;
|
||||
for b in 0..N_BINS {
|
||||
let p = buffer[b].re * buffer[b].re + buffer[b].im * buffer[b].im;
|
||||
acc += self.mel[b * N_MELS + m] * p;
|
||||
}
|
||||
row[m] = acc;
|
||||
}
|
||||
}
|
||||
|
||||
// amplitude_to_DB: 10*log10(clamp(x, amin)) with db_multiplier = 0.
|
||||
let mut db_max = f32::NEG_INFINITY;
|
||||
for v in fbank.iter_mut() {
|
||||
*v = MULTIPLIER * v.max(AMIN).log10();
|
||||
if *v > db_max {
|
||||
db_max = *v;
|
||||
}
|
||||
}
|
||||
let floor = db_max - TOP_DB;
|
||||
for v in fbank.iter_mut() {
|
||||
if *v < floor {
|
||||
*v = floor;
|
||||
}
|
||||
}
|
||||
|
||||
// sentence mean normalization (std_norm=False -> subtract mean only)
|
||||
let mut mean = vec![0f32; N_MELS];
|
||||
for t in 0..n_frames {
|
||||
for m in 0..N_MELS {
|
||||
mean[m] += fbank[t * N_MELS + m];
|
||||
}
|
||||
}
|
||||
let inv = 1.0 / n_frames as f32;
|
||||
for m in 0..N_MELS {
|
||||
mean[m] *= inv;
|
||||
}
|
||||
for t in 0..n_frames {
|
||||
for m in 0..N_MELS {
|
||||
fbank[t * N_MELS + m] -= mean[m];
|
||||
}
|
||||
}
|
||||
|
||||
(fbank, n_frames)
|
||||
}
|
||||
}
|
||||
|
||||
/// ECAPA-TDNN speaker embedding network (ONNX).
|
||||
pub struct Ecapa {
|
||||
session: Session,
|
||||
}
|
||||
|
||||
impl Ecapa {
|
||||
pub fn new(model_path: &str) -> Result<Self> {
|
||||
let session = Session::builder()?
|
||||
.with_optimization_level(GraphOptimizationLevel::Level1)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))?
|
||||
.commit_from_file(model_path)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to load ECAPA model: {}", e))?;
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
/// Run the embedding network on features [n_frames, N_MELS]; returns 192-d.
|
||||
pub fn embed(&mut self, feats: &[f32], n_frames: usize) -> Result<Vec<f32>> {
|
||||
let input = ndarray::Array::from_shape_vec(IxDyn(&[1, n_frames, N_MELS]), feats.to_vec())
|
||||
.context("Failed to create ECAPA input array")?;
|
||||
|
||||
let input_value = Value::from_array(input).context("Failed to create input value")?;
|
||||
let inputs = ort::inputs!["feats" => input_value];
|
||||
|
||||
let outputs = self.session.run(inputs).context("Failed to run ECAPA")?;
|
||||
let out = outputs["embedding"]
|
||||
.try_extract_tensor::<f32>()
|
||||
.context("Failed to extract embedding")?;
|
||||
Ok(out.1.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
fn read_f32_file(path: &str) -> Result<Vec<f32>> {
|
||||
let bytes = std::fs::read(path).with_context(|| format!("Failed to read {}", path))?;
|
||||
if bytes.len() % 4 != 0 {
|
||||
anyhow::bail!("{} length not a multiple of 4", path);
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() / 4);
|
||||
for chunk in bytes.chunks_exact(4) {
|
||||
out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// L2-normalize a vector in place.
|
||||
pub fn l2_normalize(v: &mut [f32]) {
|
||||
let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
|
||||
if norm > 0.0 {
|
||||
for x in v.iter_mut() {
|
||||
*x /= norm;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, imageops};
|
||||
use crate::face_processor::BBox;
|
||||
|
||||
pub struct FaceCropper;
|
||||
|
||||
impl FaceCropper {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
pub fn crop(&self, frame: &RgbImage, bbox: &BBox) -> Result<RgbImage> {
|
||||
let width = frame.width() as i32;
|
||||
let height = frame.height() as i32;
|
||||
|
||||
// Clamp bbox to frame boundaries
|
||||
let x = bbox.x.max(0).min(width - 1) as u32;
|
||||
let y = bbox.y.max(0).min(height - 1) as u32;
|
||||
let w = bbox.width.max(1).min(width - x as i32) as u32;
|
||||
let h = bbox.height.max(1).min(height - y as i32) as u32;
|
||||
|
||||
// Clone frame for cropping (imageops::crop needs mutable reference)
|
||||
let mut frame_clone = frame.clone();
|
||||
|
||||
// Crop face
|
||||
let cropped = imageops::crop(&mut frame_clone, x, y, w, h).to_image();
|
||||
|
||||
Ok(cropped)
|
||||
}
|
||||
|
||||
pub fn resize_to_160(&self, face: &RgbImage) -> Result<RgbImage> {
|
||||
let resized = imageops::resize(
|
||||
face,
|
||||
160,
|
||||
160,
|
||||
imageops::FilterType::Lanczos3,
|
||||
);
|
||||
|
||||
Ok(resized)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::fs;
|
||||
use serde::Deserialize;
|
||||
use crate::face_processor::{FaceDetection, BBox, PoseInfo};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftOutput {
|
||||
#[serde(default)]
|
||||
fps: f64,
|
||||
#[serde(default)]
|
||||
frame_count: usize,
|
||||
frames: Vec<SwiftFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftFrame {
|
||||
frame: usize,
|
||||
#[serde(default)]
|
||||
timestamp: f64,
|
||||
faces: Vec<SwiftFace>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftFace {
|
||||
bbox: Option<SwiftBBox>,
|
||||
confidence: f64,
|
||||
#[serde(rename = "captureQuality")]
|
||||
capture_quality: Option<f64>,
|
||||
pose: Option<SwiftPose>,
|
||||
landmarks: Option<SwiftLandmarks>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Clone)]
|
||||
struct SwiftBBox {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftPose {
|
||||
roll: f64,
|
||||
yaw: f64,
|
||||
pitch: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftLandmarks {
|
||||
face_oval: Option<Vec<Vec<f64>>>,
|
||||
left_eye: Option<Vec<Vec<f64>>>,
|
||||
right_eye: Option<Vec<Vec<f64>>>,
|
||||
nose: Option<Vec<Vec<f64>>>,
|
||||
lips: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl SwiftFace {
|
||||
fn get_bbox(&self) -> Option<SwiftBBox> {
|
||||
// If bbox is directly provided
|
||||
if let Some(ref bbox) = self.bbox {
|
||||
return Some(bbox.clone());
|
||||
}
|
||||
|
||||
// Otherwise, derive from landmarks
|
||||
if let Some(ref landmarks) = self.landmarks {
|
||||
if let Some(ref face_oval) = landmarks.face_oval {
|
||||
if !face_oval.is_empty() {
|
||||
let mut min_x = f64::MAX;
|
||||
let mut min_y = f64::MAX;
|
||||
let mut max_x = f64::MIN;
|
||||
let mut max_y = f64::MIN;
|
||||
|
||||
for point in face_oval {
|
||||
if point.len() >= 2 {
|
||||
min_x = min_x.min(point[0]);
|
||||
min_y = min_y.min(point[1]);
|
||||
max_x = max_x.max(point[0]);
|
||||
max_y = max_y.max(point[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return Some(SwiftBBox {
|
||||
x: min_x,
|
||||
y: min_y,
|
||||
width: max_x - min_x,
|
||||
height: max_y - min_y,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FaceDetector {
|
||||
swift_binary: String,
|
||||
}
|
||||
|
||||
impl FaceDetector {
|
||||
pub fn new() -> Result<Self> {
|
||||
let swift_binary = Self::find_swift_binary()?;
|
||||
Ok(Self { swift_binary })
|
||||
}
|
||||
|
||||
fn find_swift_binary() -> Result<String> {
|
||||
// Try release build first
|
||||
let release = "scripts/swift_processors/.build/release/swift_face";
|
||||
if Path::new(release).exists() {
|
||||
return Ok(release.to_string());
|
||||
}
|
||||
|
||||
// Try debug build
|
||||
let debug = "scripts/swift_processors/.build/debug/swift_face";
|
||||
if Path::new(debug).exists() {
|
||||
return Ok(debug.to_string());
|
||||
}
|
||||
|
||||
anyhow::bail!("Swift face binary not found")
|
||||
}
|
||||
|
||||
pub fn detect(&self, video_path: &Path, output_path: &Path, sample_interval: usize) -> Result<Vec<FaceDetection>> {
|
||||
println!("[DETECTION] Running Swift face detection...");
|
||||
|
||||
// Swift writes to file, not stdout
|
||||
let output = Command::new(&self.swift_binary)
|
||||
.arg(video_path)
|
||||
.arg(output_path)
|
||||
.arg("--sample-interval")
|
||||
.arg(sample_interval.to_string())
|
||||
.output()
|
||||
.context("Failed to run Swift face detection")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
anyhow::bail!("Swift face detection failed: {}", stderr);
|
||||
}
|
||||
|
||||
// Read JSON from output file
|
||||
let json_content = fs::read_to_string(output_path)
|
||||
.context("Failed to read Swift detection output file")?;
|
||||
|
||||
// Parse Swift output: {"frames": [...], "fps": ..., "frame_count": ...}
|
||||
let swift_output: SwiftOutput = serde_json::from_str(&json_content)
|
||||
.context("Failed to parse Swift detection JSON")?;
|
||||
|
||||
println!("[DETECTION] Swift fps: {}, frame_count: {}", swift_output.fps, swift_output.frame_count);
|
||||
|
||||
// Convert to our format
|
||||
let faces: Vec<FaceDetection> = swift_output.frames.into_iter().flat_map(|frame| {
|
||||
frame.faces.into_iter().filter_map(|face| {
|
||||
let swift_bbox = face.get_bbox()?;
|
||||
|
||||
Some(FaceDetection {
|
||||
frame: frame.frame,
|
||||
timestamp: frame.timestamp,
|
||||
bbox: BBox {
|
||||
x: swift_bbox.x as i32,
|
||||
y: swift_bbox.y as i32,
|
||||
width: swift_bbox.width as i32,
|
||||
height: swift_bbox.height as i32,
|
||||
},
|
||||
confidence: face.confidence,
|
||||
capture_quality: face.capture_quality,
|
||||
pose: face.pose.map(|p| PoseInfo {
|
||||
roll: p.roll,
|
||||
yaw: p.yaw,
|
||||
pitch: p.pitch,
|
||||
}),
|
||||
})
|
||||
}).collect::<Vec<_>>()
|
||||
}).collect();
|
||||
|
||||
println!("[DETECTION] Found {} faces", faces.len());
|
||||
|
||||
Ok(faces)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, imageops};
|
||||
use ndarray::IxDyn;
|
||||
use ort::{session::Session, value::Value};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct EmbeddingExtractor {
|
||||
session: Session,
|
||||
}
|
||||
|
||||
impl EmbeddingExtractor {
|
||||
pub fn new(model_path: &Path) -> Result<Self> {
|
||||
println!("[EMBEDDING] Loading model: {:?}", model_path);
|
||||
|
||||
let session = Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?;
|
||||
|
||||
println!("[EMBEDDING] Model loaded successfully");
|
||||
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
pub fn extract(&mut self, face: &RgbImage) -> Result<Vec<f32>> {
|
||||
// Preprocess: resize to 160x160 and normalize to [-1, 1]
|
||||
let resized = imageops::resize(
|
||||
face,
|
||||
160,
|
||||
160,
|
||||
imageops::FilterType::Lanczos3,
|
||||
);
|
||||
|
||||
// Convert to normalized tensor
|
||||
let mut input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, 3, 160, 160]),
|
||||
vec![0.0f32; 1 * 3 * 160 * 160]
|
||||
).context("Failed to create input array")?;
|
||||
|
||||
for (x, y, pixel) in resized.enumerate_pixels() {
|
||||
let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32);
|
||||
input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0;
|
||||
input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0;
|
||||
input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0;
|
||||
}
|
||||
|
||||
// Create input value
|
||||
let input_value = Value::from_array(input_array)
|
||||
.context("Failed to create input value")?;
|
||||
|
||||
let inputs = ort::inputs!["input" => input_value];
|
||||
|
||||
// Run inference
|
||||
let outputs = self.session.run(inputs)
|
||||
.context("Failed to run inference")?;
|
||||
|
||||
// Extract output
|
||||
let output = outputs["output"].try_extract_tensor::<f32>()
|
||||
.context("Failed to extract output tensor")?;
|
||||
|
||||
let output_data = output.1;
|
||||
let embedding = output_data.to_vec();
|
||||
|
||||
Ok(embedding)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
pub mod types;
|
||||
pub mod video;
|
||||
pub mod qdrant;
|
||||
pub mod detection;
|
||||
pub mod crop;
|
||||
pub mod embedding;
|
||||
|
||||
pub use types::*;
|
||||
pub use video::VideoReader;
|
||||
pub use qdrant::{QdrantFaceStore, FaceEmbedPayload};
|
||||
pub use detection::FaceDetector;
|
||||
pub use crop::FaceCropper;
|
||||
pub use embedding::EmbeddingExtractor;
|
||||
@@ -0,0 +1,141 @@
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::json;
|
||||
|
||||
const COLLECTION_NAME: &str = "_faces";
|
||||
const VECTOR_SIZE: usize = 512;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FaceEmbedPayload {
|
||||
pub frame: usize,
|
||||
pub trace_id: i64,
|
||||
pub bbox: crate::face_processor::BBox,
|
||||
pub confidence: f64,
|
||||
pub capture_quality: Option<f64>,
|
||||
pub embedding: Vec<f32>,
|
||||
}
|
||||
|
||||
pub struct QdrantFaceStore {
|
||||
url: String,
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
impl QdrantFaceStore {
|
||||
pub async fn new() -> Result<Self> {
|
||||
let url = std::env::var("QDRANT_URL")
|
||||
.unwrap_or_else(|_| "http://localhost:6333".to_string());
|
||||
|
||||
let api_key = std::env::var("QDRANT_API_KEY")
|
||||
.unwrap_or_else(|_| "Test3200Test3200Test3200".to_string());
|
||||
|
||||
let store = Self { url, api_key };
|
||||
store.ensure_collection().await?;
|
||||
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
async fn ensure_collection(&self) -> Result<()> {
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let url = format!("{}/collections/{}", self.url, COLLECTION_NAME);
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.header("Api-Key", &self.api_key)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if resp.status() == 404 {
|
||||
println!("[QDRANT] Creating collection: {}", COLLECTION_NAME);
|
||||
|
||||
let create_url = format!("{}/collections/{}", self.url, COLLECTION_NAME);
|
||||
let body = json!({
|
||||
"vectors": {
|
||||
"size": VECTOR_SIZE,
|
||||
"distance": "Cosine"
|
||||
}
|
||||
});
|
||||
|
||||
client
|
||||
.put(&create_url)
|
||||
.header("Api-Key", &self.api_key)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
println!("[QDRANT] Collection created");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_point_id(file_uuid: &str, frame: usize, trace_id: i64) -> u64 {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
let key = format!("{}_{}_{}", file_uuid, frame, trace_id);
|
||||
let mut hasher = DefaultHasher::new();
|
||||
key.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
pub async fn push_embeddings_batch(
|
||||
&self,
|
||||
file_uuid: &str,
|
||||
faces: Vec<FaceEmbedPayload>,
|
||||
) -> Result<usize> {
|
||||
if faces.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
println!("[QDRANT] Pushing {} embeddings", faces.len());
|
||||
|
||||
let points: Vec<_> = faces
|
||||
.iter()
|
||||
.map(|face| {
|
||||
let point_id = Self::generate_point_id(file_uuid, face.frame, face.trace_id);
|
||||
json!({
|
||||
"id": point_id,
|
||||
"vector": &face.embedding,
|
||||
"payload": {
|
||||
"file_uuid": file_uuid,
|
||||
"frame": face.frame,
|
||||
"trace_id": face.trace_id,
|
||||
"bbox": {
|
||||
"x": face.bbox.x,
|
||||
"y": face.bbox.y,
|
||||
"width": face.bbox.width,
|
||||
"height": face.bbox.height,
|
||||
},
|
||||
"confidence": face.confidence,
|
||||
"capture_quality": face.capture_quality.unwrap_or(0.0),
|
||||
"identity_id": 0,
|
||||
"identity_uuid": "",
|
||||
"stranger_id": 0,
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let body = json!({"points": points});
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let url = format!("{}/collections/{}/points?wait=true", self.url, COLLECTION_NAME);
|
||||
|
||||
let resp = client
|
||||
.put(&url)
|
||||
.header("Api-Key", &self.api_key)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let status = resp.status();
|
||||
let response_text = resp.text().await?;
|
||||
|
||||
if !status.is_success() {
|
||||
bail!("Qdrant upsert failed ({}): {}", status, response_text);
|
||||
}
|
||||
|
||||
println!("[QDRANT] Pushed {} embeddings successfully", faces.len());
|
||||
|
||||
Ok(faces.len())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BBox {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceDetection {
|
||||
pub frame: usize,
|
||||
pub timestamp: f64,
|
||||
pub bbox: BBox,
|
||||
pub confidence: f64,
|
||||
pub capture_quality: Option<f64>,
|
||||
pub pose: Option<PoseInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PoseInfo {
|
||||
pub roll: f64,
|
||||
pub yaw: f64,
|
||||
pub pitch: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceEmbedding {
|
||||
pub frame: usize,
|
||||
pub trace_id: usize,
|
||||
pub bbox: BBox,
|
||||
pub confidence: f64,
|
||||
pub embedding: Vec<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FaceOutput {
|
||||
pub status: String,
|
||||
pub frame_count: usize,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<FrameData>,
|
||||
pub total_faces: usize,
|
||||
pub metadata: Metadata,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FrameData {
|
||||
pub frame: usize,
|
||||
pub timestamp: f64,
|
||||
pub faces: Vec<FaceInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FaceInfo {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub confidence: f64,
|
||||
pub pose_angle: Option<PoseAngle>,
|
||||
pub capture_quality: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct PoseAngle {
|
||||
pub angle: String,
|
||||
pub roll: f64,
|
||||
pub yaw: f64,
|
||||
pub pitch: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Metadata {
|
||||
pub embedding_method: String,
|
||||
pub embedding_model: String,
|
||||
pub total_embeddings: usize,
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, ImageBuffer};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
pub struct VideoReader {
|
||||
video_path: String,
|
||||
fps: f64,
|
||||
frame_count: usize,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
impl VideoReader {
|
||||
pub fn new(video_path: &Path) -> Result<Self> {
|
||||
// Use ffprobe to get video info
|
||||
let output = Command::new("ffprobe")
|
||||
.args(&[
|
||||
"-v", "error",
|
||||
"-select_streams", "v:0",
|
||||
"-count_packets",
|
||||
"-show_entries", "stream=width,height,r_frame_rate,nb_read_packets",
|
||||
"-of", "csv=p=0",
|
||||
video_path.to_str().unwrap()
|
||||
])
|
||||
.output()
|
||||
.context("Failed to run ffprobe")?;
|
||||
|
||||
let info = String::from_utf8_lossy(&output.stdout);
|
||||
let parts: Vec<&str> = info.trim().split(',').collect();
|
||||
|
||||
if parts.len() < 4 {
|
||||
anyhow::bail!("Invalid ffprobe output");
|
||||
}
|
||||
|
||||
let width: u32 = parts[0].parse()?;
|
||||
let height: u32 = parts[1].parse()?;
|
||||
|
||||
let fps_parts: Vec<&str> = parts[2].split('/').collect();
|
||||
let fps = if fps_parts.len() == 2 {
|
||||
fps_parts[0].parse::<f64>()? / fps_parts[1].parse::<f64>()?
|
||||
} else {
|
||||
parts[2].parse()?
|
||||
};
|
||||
|
||||
let frame_count: usize = parts[3].parse()?;
|
||||
|
||||
Ok(Self {
|
||||
video_path: video_path.to_str().unwrap().to_string(),
|
||||
fps,
|
||||
frame_count,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fps(&self) -> f64 {
|
||||
self.fps
|
||||
}
|
||||
|
||||
pub fn frame_count(&self) -> usize {
|
||||
self.frame_count
|
||||
}
|
||||
|
||||
pub fn width(&self) -> u32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
pub fn height(&self) -> u32 {
|
||||
self.height
|
||||
}
|
||||
|
||||
pub fn read_frame(&mut self, frame_num: usize) -> Result<Option<RgbImage>> {
|
||||
// Use ffmpeg to extract a specific frame
|
||||
let output = Command::new("ffmpeg")
|
||||
.args(&[
|
||||
"-i", &self.video_path,
|
||||
"-vf", &format!("select=eq(n\\,{})", frame_num),
|
||||
"-vframes", "1",
|
||||
"-f", "image2pipe",
|
||||
"-pix_fmt", "rgb24",
|
||||
"-vcodec", "rawvideo",
|
||||
"-"
|
||||
])
|
||||
.output()
|
||||
.context("Failed to run ffmpeg")?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let data = output.stdout;
|
||||
|
||||
// Create image from raw RGB data
|
||||
let img = ImageBuffer::from_raw(self.width, self.height, data)
|
||||
.context("Failed to create image buffer")?;
|
||||
|
||||
Ok(Some(img))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,817 @@
|
||||
use std::process::Command;
|
||||
|
||||
use image::GenericImageView;
|
||||
use clap::Parser;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_appearance", about = "Appearance Processor (Rust port of appearance_processor.py)")]
|
||||
struct Args {
|
||||
video_path: std::path::PathBuf,
|
||||
pose_json: std::path::PathBuf,
|
||||
output_path: std::path::PathBuf,
|
||||
#[arg(short = 'u', long = "uuid", default_value = "")]
|
||||
uuid: String,
|
||||
#[arg(long = "frames", default_value = None)]
|
||||
frames: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Keypoint {
|
||||
name: String,
|
||||
x: f64,
|
||||
y: f64,
|
||||
#[serde(default = "default_conf")]
|
||||
confidence: f64,
|
||||
}
|
||||
|
||||
fn default_conf() -> f64 {
|
||||
1.0
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone)]
|
||||
#[serde(default)]
|
||||
struct BBox {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
}
|
||||
|
||||
impl Default for BBox {
|
||||
fn default() -> Self {
|
||||
Self { x: 0.0, y: 0.0, width: 0.0, height: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Person {
|
||||
bbox: BBox,
|
||||
#[serde(default)]
|
||||
keypoints: Vec<Keypoint>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PoseFrame {
|
||||
frame: i64,
|
||||
#[serde(default)]
|
||||
timestamp: Option<f64>,
|
||||
#[serde(default)]
|
||||
persons: Vec<Person>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PoseData {
|
||||
#[serde(default)]
|
||||
fps: f64,
|
||||
#[serde(default)]
|
||||
frames: Vec<PoseFrame>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct FaceData {
|
||||
#[serde(default)]
|
||||
frames: Vec<FaceFrame>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct FaceFrame {
|
||||
frame: i64,
|
||||
#[serde(default)]
|
||||
faces: Vec<FaceBBox>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone)]
|
||||
struct FaceBBox {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
}
|
||||
|
||||
// Output schema (matches Python appearance_processor.py)
|
||||
#[derive(Serialize)]
|
||||
struct Output {
|
||||
frame_count: u64,
|
||||
fps: f64,
|
||||
frames: Vec<OutputFrame>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OutputFrame {
|
||||
frame: i64,
|
||||
timestamp: f64,
|
||||
persons: Vec<OutputPerson>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OutputPerson {
|
||||
person_id: usize,
|
||||
// Python emits the pose.json bbox verbatim (raw numbers). Keep original JSON to match
|
||||
// integer/float representation exactly.
|
||||
bbox: Value,
|
||||
facing: String,
|
||||
body_parts: Vec<BodyPart>,
|
||||
dominant_colors: Vec<Vec<f64>>,
|
||||
hsv_histogram: Vec<Vec<f64>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct BodyPart {
|
||||
name: String,
|
||||
bbox: OBBox,
|
||||
hsv_histogram: Vec<Vec<f64>>,
|
||||
dominant_colors: Vec<Vec<f64>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OBBox {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
}
|
||||
|
||||
fn get_kp<'a>(keypoints: &'a [Keypoint], name: &str) -> Option<&'a Keypoint> {
|
||||
keypoints.iter().find(|kp| kp.name == name)
|
||||
}
|
||||
|
||||
fn determine_facing(keypoints: &[Keypoint]) -> String {
|
||||
let nose = get_kp(keypoints, "nose");
|
||||
let l_shoulder = get_kp(keypoints, "left_shoulder");
|
||||
let r_shoulder = get_kp(keypoints, "right_shoulder");
|
||||
|
||||
if nose.is_some_and(|n| n.confidence > 0.5) {
|
||||
return "front".to_string();
|
||||
}
|
||||
let sh_vis = [l_shoulder, r_shoulder]
|
||||
.iter()
|
||||
.filter(|s| s.is_some_and(|k| k.confidence > 0.5))
|
||||
.count();
|
||||
if sh_vis >= 2 && nose.is_none_or(|n| n.confidence < 0.2) {
|
||||
return "back".to_string();
|
||||
}
|
||||
if sh_vis >= 1 {
|
||||
return "profile".to_string();
|
||||
}
|
||||
"unknown".to_string()
|
||||
}
|
||||
|
||||
fn compute_body_regions(
|
||||
keypoints: &[Keypoint],
|
||||
face: &FaceBBox,
|
||||
) -> Vec<(String, BBox)> {
|
||||
let fx = face.x;
|
||||
let fy = face.y;
|
||||
let fw = face.width;
|
||||
let fh = face.height;
|
||||
let face_cx = fx + fw / 2.0;
|
||||
|
||||
let nose = get_kp(keypoints, "nose");
|
||||
let ls = get_kp(keypoints, "left_shoulder");
|
||||
let rs = get_kp(keypoints, "right_shoulder");
|
||||
let lw = get_kp(keypoints, "left_wrist");
|
||||
let rw = get_kp(keypoints, "right_wrist");
|
||||
let lh = get_kp(keypoints, "left_hip");
|
||||
let rh = get_kp(keypoints, "right_hip");
|
||||
let la = get_kp(keypoints, "left_ankle");
|
||||
let ra = get_kp(keypoints, "right_ankle");
|
||||
|
||||
let kp_nose = nose.map(|n| (n.x, n.y)).unwrap_or((face_cx, fy + fh * 0.5));
|
||||
let kp_sh_l = ls.map(|s| s.x).unwrap_or(face_cx - fw * 1.5);
|
||||
let kp_sh_r = rs.map(|s| s.x).unwrap_or(face_cx + fw * 1.5);
|
||||
let kp_sh_mid_x = (kp_sh_l + kp_sh_r) / 2.0;
|
||||
let kp_sh_mid_y = if ls.is_some() && rs.is_some() {
|
||||
(ls.unwrap().y + rs.unwrap().y) / 2.0
|
||||
} else {
|
||||
fy + fh + fh * 0.3
|
||||
};
|
||||
let kp_hip_y = if lh.is_some() && rh.is_some() {
|
||||
(lh.unwrap().y + rh.unwrap().y) / 2.0
|
||||
} else {
|
||||
kp_sh_mid_y + fw * 2.0
|
||||
};
|
||||
let kp_hip_l = lh.map(|x| x.x).unwrap_or(kp_sh_mid_x - fw * 1.2);
|
||||
let kp_hip_r = rh.map(|x| x.x).unwrap_or(kp_sh_mid_x + fw * 1.2);
|
||||
|
||||
// Ordered to match Python dict insertion order (head → neck → upper → lower → hand → foot)
|
||||
let mut ordered_names: Vec<&str> = vec![
|
||||
"head",
|
||||
"neck",
|
||||
"front_upper_body",
|
||||
"back_upper_body",
|
||||
"front_lower_body",
|
||||
"back_lower_body",
|
||||
"left_hand",
|
||||
"right_hand",
|
||||
"left_foot",
|
||||
"right_foot",
|
||||
];
|
||||
let mut regions: Vec<(String, BBox)> = Vec::new();
|
||||
|
||||
let head_w = fw * 1.6;
|
||||
let head_h = fh * 1.5;
|
||||
regions.push(("head".to_string(), BBox {
|
||||
x: kp_nose.0 - head_w / 2.0,
|
||||
y: kp_nose.1 - head_h * 0.5,
|
||||
width: head_w,
|
||||
height: head_h,
|
||||
}));
|
||||
|
||||
let neck_w = fw * 1.5;
|
||||
regions.push(("neck".to_string(), BBox {
|
||||
x: kp_sh_mid_x - neck_w / 2.0,
|
||||
y: kp_nose.1 + fh * 0.4,
|
||||
width: neck_w,
|
||||
height: (kp_sh_mid_y - kp_nose.1 - fh * 0.4).max(fh * 0.3),
|
||||
}));
|
||||
|
||||
let ub_w = ((kp_sh_r - kp_sh_l).abs() * 1.3).max(fw * 3.0);
|
||||
let ub_h = fh * 3.0;
|
||||
let upper = BBox {
|
||||
x: kp_sh_mid_x - ub_w / 2.0,
|
||||
y: kp_sh_mid_y,
|
||||
width: ub_w,
|
||||
height: ub_h,
|
||||
};
|
||||
regions.push(("front_upper_body".to_string(), upper.clone()));
|
||||
regions.push(("back_upper_body".to_string(), upper));
|
||||
|
||||
let lb_w = ((kp_hip_r - kp_hip_l).abs() * 1.3).max(fw * 3.5);
|
||||
let lb_h = fh * 3.0;
|
||||
let lower = BBox {
|
||||
x: kp_sh_mid_x - lb_w / 2.0,
|
||||
y: kp_hip_y,
|
||||
width: lb_w,
|
||||
height: lb_h,
|
||||
};
|
||||
regions.push(("front_lower_body".to_string(), lower.clone()));
|
||||
regions.push(("back_lower_body".to_string(), lower));
|
||||
|
||||
// hands: wrist-aligned
|
||||
let hs = fw * 1.0;
|
||||
let left_hand = if lw.is_some_and(|k| k.confidence > 0.3) {
|
||||
BBox {
|
||||
x: lw.unwrap().x - hs / 2.0,
|
||||
y: lw.unwrap().y - hs / 2.0,
|
||||
width: hs,
|
||||
height: hs,
|
||||
}
|
||||
} else {
|
||||
BBox {
|
||||
x: kp_sh_l - hs,
|
||||
y: kp_sh_mid_y + fh * 0.5,
|
||||
width: hs,
|
||||
height: hs,
|
||||
}
|
||||
};
|
||||
let right_hand = if rw.is_some_and(|k| k.confidence > 0.3) {
|
||||
BBox {
|
||||
x: rw.unwrap().x - hs / 2.0,
|
||||
y: rw.unwrap().y - hs / 2.0,
|
||||
width: hs,
|
||||
height: hs,
|
||||
}
|
||||
} else {
|
||||
BBox {
|
||||
x: kp_sh_r,
|
||||
y: kp_sh_mid_y + fh * 0.5,
|
||||
width: hs,
|
||||
height: hs,
|
||||
}
|
||||
};
|
||||
regions.push(("left_hand".to_string(), left_hand));
|
||||
regions.push(("right_hand".to_string(), right_hand));
|
||||
|
||||
// feet: ankle-aligned
|
||||
let fs = fw * 1.0;
|
||||
let left_foot = if la.is_some_and(|k| k.confidence > 0.3) {
|
||||
BBox {
|
||||
x: la.unwrap().x - fs / 2.0,
|
||||
y: la.unwrap().y,
|
||||
width: fs,
|
||||
height: fs * 0.75,
|
||||
}
|
||||
} else {
|
||||
BBox {
|
||||
x: kp_sh_mid_x - fw * 1.0,
|
||||
y: kp_hip_y + fh * 2.5,
|
||||
width: fs,
|
||||
height: fs * 0.75,
|
||||
}
|
||||
};
|
||||
let right_foot = if ra.is_some_and(|k| k.confidence > 0.3) {
|
||||
BBox {
|
||||
x: ra.unwrap().x - fs / 2.0,
|
||||
y: ra.unwrap().y,
|
||||
width: fs,
|
||||
height: fs * 0.75,
|
||||
}
|
||||
} else {
|
||||
BBox {
|
||||
x: kp_sh_mid_x + fw * 1.0 - fs,
|
||||
y: kp_hip_y + fh * 2.5,
|
||||
width: fs,
|
||||
height: fs * 0.75,
|
||||
}
|
||||
};
|
||||
regions.push(("left_foot".to_string(), left_foot));
|
||||
regions.push(("right_foot".to_string(), right_foot));
|
||||
|
||||
let _ = &mut ordered_names;
|
||||
|
||||
// Extrapolate each bbox outward
|
||||
let margins: [(&str, f64); 10] = [
|
||||
("head", 0.10),
|
||||
("neck", 0.15),
|
||||
("front_upper_body", 0.20),
|
||||
("back_upper_body", 0.20),
|
||||
("front_lower_body", 0.15),
|
||||
("back_lower_body", 0.15),
|
||||
("left_hand", 0.25),
|
||||
("right_hand", 0.25),
|
||||
("left_foot", 0.20),
|
||||
("right_foot", 0.20),
|
||||
];
|
||||
let margin: std::collections::HashMap<&str, f64> = margins.iter().copied().collect();
|
||||
|
||||
regions
|
||||
.into_iter()
|
||||
.map(|(name, rb)| {
|
||||
let m = margin.get(name.as_str()).copied().unwrap_or(0.15);
|
||||
let dx = (rb.width * m) as i64;
|
||||
let dy = (rb.height * m) as i64;
|
||||
(
|
||||
name.clone(),
|
||||
BBox {
|
||||
x: rb.x - dx as f64,
|
||||
y: rb.y - dy as f64,
|
||||
width: rb.width + dx as f64 * 2.0,
|
||||
height: rb.height + dy as f64 * 2.0,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn filter_by_facing(regions: Vec<(String, BBox)>, facing: &str) -> Vec<(String, BBox)> {
|
||||
let (keep_front, keep_back) = match facing {
|
||||
"front" => (true, false),
|
||||
"back" => (false, true),
|
||||
_ => (true, true),
|
||||
};
|
||||
regions
|
||||
.into_iter()
|
||||
.filter(|(name, _)| {
|
||||
if name == "front_upper_body" || name == "front_lower_body" {
|
||||
keep_front
|
||||
} else if name == "back_upper_body" || name == "back_lower_body" {
|
||||
keep_back
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn safe_roi(
|
||||
frame: &image::RgbImage,
|
||||
x: f64,
|
||||
y: f64,
|
||||
w: f64,
|
||||
h: f64,
|
||||
) -> Option<image::RgbImage> {
|
||||
if w <= 0.0 || h <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let x1 = (x.max(0.0)) as u32;
|
||||
let y1 = (y.max(0.0)) as u32;
|
||||
let x2 = ((x + w).min(frame.width() as f64)) as u32;
|
||||
let y2 = ((y + h).min(frame.height() as f64)) as u32;
|
||||
if x2 <= x1 || y2 <= y1 {
|
||||
return None;
|
||||
}
|
||||
frame.try_view(x1, y1, x2 - x1, y2 - y1).ok().map(|v| v.to_image())
|
||||
}
|
||||
|
||||
// Deterministic k-means (k=5, attempts=10, iter=10, eps=1.0) on HSV pixels — seed fixed
|
||||
// so output is reproducible (Python cv2.kmeans uses KMEANS_RANDOM_CENTERS: non-deterministic).
|
||||
// A/B gate relaxes dominant color comparison accordingly.
|
||||
fn kmeans_dominant(pixels: &[[f64; 3]], k: usize, attempts: usize) -> Vec<[f64; 3]> {
|
||||
if pixels.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
if pixels.len() < 5 {
|
||||
// Python: fewer than 5 pixels → mean as single dominant color
|
||||
let mut mean = [0.0; 3];
|
||||
for p in pixels {
|
||||
for i in 0..3 {
|
||||
mean[i] += p[i];
|
||||
}
|
||||
}
|
||||
for i in 0..3 {
|
||||
mean[i] /= pixels.len() as f64;
|
||||
}
|
||||
return vec![mean];
|
||||
}
|
||||
|
||||
let mut best: Option<(f64, Vec<[f64; 3]>)> = None;
|
||||
for seed in 0..attempts as u64 {
|
||||
let mut centers = init_centers(pixels, k, seed);
|
||||
for _ in 0..10 {
|
||||
let (labels, _counts) = assign(pixels, ¢ers);
|
||||
let new_centers = recompute(pixels, &labels, k);
|
||||
let max_shift = centers
|
||||
.iter()
|
||||
.zip(new_centers.iter())
|
||||
.map(|(a, b)| dist(a, b))
|
||||
.fold(0.0f64, f64::max);
|
||||
centers = new_centers;
|
||||
if max_shift <= 1.0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (labels, _counts) = assign(pixels, ¢ers);
|
||||
let sse: f64 = pixels
|
||||
.iter()
|
||||
.zip(labels.iter())
|
||||
.map(|(p, &l)| dist(p, ¢ers[l]))
|
||||
.sum();
|
||||
if best.as_ref().map(|(e, _)| sse < *e).unwrap_or(true) {
|
||||
best = Some((sse, centers));
|
||||
}
|
||||
}
|
||||
|
||||
let (_, centers) = best.unwrap();
|
||||
let (labels, _counts) = assign(pixels, ¢ers);
|
||||
let mut counts = vec![0usize; k];
|
||||
for &l in &labels {
|
||||
counts[l] += 1;
|
||||
}
|
||||
// Sort centers by cluster count descending (Python: centers[np.argsort(-counts)[:5]])
|
||||
let mut idx: Vec<usize> = (0..k).collect();
|
||||
idx.sort_by(|&a, &b| counts[b].cmp(&counts[a]));
|
||||
idx.iter().map(|&i| centers[i]).collect()
|
||||
}
|
||||
|
||||
fn dist(a: &[f64; 3], b: &[f64; 3]) -> f64 {
|
||||
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
fn init_centers(pixels: &[[f64; 3]], k: usize, seed: u64) -> Vec<[f64; 3]> {
|
||||
let mut rng = SplitMix64::new(seed);
|
||||
let n = pixels.len();
|
||||
let mut chosen = Vec::with_capacity(k);
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
while chosen.len() < k {
|
||||
let i = (rng.next_u64() % n as u64) as usize;
|
||||
if used.insert(i) {
|
||||
chosen.push(pixels[i]);
|
||||
}
|
||||
}
|
||||
chosen
|
||||
}
|
||||
|
||||
fn assign(pixels: &[[f64; 3]], centers: &[[f64; 3]]) -> (Vec<usize>, Vec<usize>) {
|
||||
let mut labels = Vec::with_capacity(pixels.len());
|
||||
let mut counts = vec![0usize; centers.len()];
|
||||
for p in pixels {
|
||||
let mut best_i = 0;
|
||||
let mut best_d = f64::INFINITY;
|
||||
for (i, c) in centers.iter().enumerate() {
|
||||
let d = dist(p, c);
|
||||
if d < best_d {
|
||||
best_d = d;
|
||||
best_i = i;
|
||||
}
|
||||
}
|
||||
labels.push(best_i);
|
||||
counts[best_i] += 1;
|
||||
}
|
||||
(labels, counts)
|
||||
}
|
||||
|
||||
fn recompute(pixels: &[[f64; 3]], labels: &[usize], k: usize) -> Vec<[f64; 3]> {
|
||||
let mut sums = vec![[0.0; 3]; k];
|
||||
let mut counts = vec![0usize; k];
|
||||
for (p, &l) in pixels.iter().zip(labels.iter()) {
|
||||
for i in 0..3 {
|
||||
sums[l][i] += p[i];
|
||||
}
|
||||
counts[l] += 1;
|
||||
}
|
||||
let mut centers = vec![[0.0; 3]; k];
|
||||
for i in 0..k {
|
||||
if counts[i] > 0 {
|
||||
for j in 0..3 {
|
||||
centers[i][j] = sums[i][j] / counts[i] as f64;
|
||||
}
|
||||
}
|
||||
}
|
||||
centers
|
||||
}
|
||||
|
||||
/// SplitMix64 PRNG (deterministic).
|
||||
struct SplitMix64 {
|
||||
state: u64,
|
||||
}
|
||||
|
||||
impl SplitMix64 {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self { state: seed }
|
||||
}
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
self.state = self.state.wrapping_add(0x9E3779B97F4A7C15);
|
||||
let mut z = self.state;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_color(roi: &image::RgbImage) -> Option<(Vec<Vec<f64>>, Vec<Vec<f64>>)> {
|
||||
if roi.width() < 2 || roi.height() < 2 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut h_hist = vec![0.0f64; 30];
|
||||
let mut s_hist = vec![0.0f64; 32];
|
||||
let mut v_hist = vec![0.0f64; 32];
|
||||
let mut pixels: Vec<[f64; 3]> = Vec::new();
|
||||
|
||||
for px in roi.pixels() {
|
||||
let r = px[0] as f64;
|
||||
let g = px[1] as f64;
|
||||
let b = px[2] as f64;
|
||||
// OpenCV BGR2HSV and RGB2HSV produce the same HSV for the same underlying color
|
||||
// triple; PNG stores (R,G,B), so identical to cv2 frame interpreted as BGR.
|
||||
let (h, s, v) = bgr2hsv(r, g, b);
|
||||
let hb = ((h / 6.0).floor() as usize).min(29);
|
||||
let sb = ((s / 8.0).floor() as usize).min(31);
|
||||
let vb = ((v / 8.0).floor() as usize).min(31);
|
||||
h_hist[hb] += 1.0;
|
||||
s_hist[sb] += 1.0;
|
||||
v_hist[vb] += 1.0;
|
||||
pixels.push([h, s, v]);
|
||||
}
|
||||
|
||||
let hs = h_hist.iter().sum::<f64>().max(1.0);
|
||||
let ss = s_hist.iter().sum::<f64>().max(1.0);
|
||||
let vs = v_hist.iter().sum::<f64>().max(1.0);
|
||||
|
||||
let h_norm: Vec<f64> = h_hist.iter().map(|x| x / hs).collect();
|
||||
let s_norm: Vec<f64> = s_hist.iter().map(|x| x / ss).collect();
|
||||
let v_norm: Vec<f64> = v_hist.iter().map(|x| x / vs).collect();
|
||||
|
||||
// Subsample for kmeans if too many pixels (cv2 uses all but is SIMD-optimized)
|
||||
let kmeans_pixels = if pixels.len() > 10000 {
|
||||
let step = pixels.len() / 10000;
|
||||
pixels.iter().step_by(step).copied().collect::<Vec<_>>()
|
||||
} else {
|
||||
pixels.clone()
|
||||
};
|
||||
let dominant = kmeans_dominant(&kmeans_pixels, 5, 10);
|
||||
let dominant: Vec<Vec<f64>> = dominant.iter().map(|d| d.to_vec()).collect();
|
||||
|
||||
Some((vec![h_norm, s_norm, v_norm], dominant))
|
||||
}
|
||||
|
||||
/// OpenCV 8-bit BGR→HSV. H in [0,180], S and V in [0,255].
|
||||
fn bgr2hsv(r: f64, g: f64, b: f64) -> (f64, f64, f64) {
|
||||
let v = r.max(g).max(b);
|
||||
let mn = r.min(g).min(b);
|
||||
let delta = v - mn;
|
||||
if delta == 0.0 {
|
||||
return (0.0, 0.0, v);
|
||||
}
|
||||
let s = delta * 255.0 / v;
|
||||
let mut h;
|
||||
if v == r {
|
||||
h = 60.0 * (g - b) / delta;
|
||||
} else if v == g {
|
||||
h = 60.0 * (2.0 + (b - r) / delta);
|
||||
} else {
|
||||
h = 60.0 * (4.0 + (r - g) / delta);
|
||||
}
|
||||
if h < 0.0 {
|
||||
h += 360.0;
|
||||
}
|
||||
(h / 2.0, s, v)
|
||||
}
|
||||
|
||||
/// Extract only the needed frames in one ffmpeg pass. Builds a `select` filter expression
|
||||
/// compressing contiguous frame ranges into `between(n,a,b)` terms.
|
||||
fn extract_frames(
|
||||
video_path: &std::path::Path,
|
||||
needed: &[i64],
|
||||
out_tmp: &std::path::Path,
|
||||
) -> Result<Vec<std::path::PathBuf>, String> {
|
||||
if needed.is_empty() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
std::fs::create_dir_all(out_tmp).map_err(|e| e.to_string())?;
|
||||
|
||||
// Compact runs
|
||||
let mut terms: Vec<String> = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < needed.len() {
|
||||
let start = needed[i];
|
||||
let mut end = start;
|
||||
let mut j = i;
|
||||
while j + 1 < needed.len() && needed[j + 1] == end + 1 {
|
||||
end += 1;
|
||||
j += 1;
|
||||
}
|
||||
if start == end {
|
||||
terms.push(format!("eq(n\\,{})", start));
|
||||
} else {
|
||||
terms.push(format!("between(n\\,{}\\,{})", start, end));
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
let select_expr = terms.join("+");
|
||||
|
||||
let filter = format!("select='{}'", select_expr);
|
||||
let out_pattern = out_tmp.join("frame_%05d.png");
|
||||
let status = Command::new("ffmpeg")
|
||||
.arg("-v")
|
||||
.arg("error")
|
||||
.arg("-i")
|
||||
.arg(video_path)
|
||||
.arg("-vf")
|
||||
.arg(&filter)
|
||||
.arg("-vsync")
|
||||
.arg("0")
|
||||
.arg("-f")
|
||||
.arg("image2")
|
||||
.arg(&out_pattern)
|
||||
.status()
|
||||
.map_err(|e| format!("ffmpeg launch failed: {e}"))?;
|
||||
if !status.success() {
|
||||
return Err(format!("ffmpeg failed with status {status}"));
|
||||
}
|
||||
|
||||
// Output files are named frame_00001.png ... in the same order as the needed list.
|
||||
let mut paths = Vec::with_capacity(needed.len());
|
||||
for (i, _) in needed.iter().enumerate() {
|
||||
let p = out_tmp.join(format!("frame_{:05}.png", i + 1));
|
||||
if !p.exists() {
|
||||
return Err(format!("ffmpeg expected output {p:?} missing"));
|
||||
}
|
||||
paths.push(p);
|
||||
}
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
let pose_str = std::fs::read_to_string(&args.pose_json).expect("Failed to read pose json");
|
||||
let pose: PoseData = serde_json::from_str(&pose_str).expect("Failed to parse pose json");
|
||||
|
||||
// Load face.json for anchor bbox (same directory as pose_json)
|
||||
let face_path =
|
||||
std::path::PathBuf::from(args.pose_json.to_string_lossy().replace(".pose.json", ".face.json"));
|
||||
let mut face_by_frame: std::collections::BTreeMap<i64, FaceBBox> = std::collections::BTreeMap::new();
|
||||
if face_path.exists() {
|
||||
let face_str = std::fs::read_to_string(&face_path).expect("Failed to read face json");
|
||||
if let Ok(face_data) = serde_json::from_str::<FaceData>(&face_str) {
|
||||
for fframe in face_data.frames {
|
||||
if let Some(first) = fframe.faces.first() {
|
||||
face_by_frame.insert(fframe.frame, first.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fps = if pose.fps > 0.0 { pose.fps } else { 30.0 };
|
||||
|
||||
// Collect needed frames (pose frames that have persons), sorted for ffmpeg select
|
||||
let mut needed: Vec<i64> = pose
|
||||
.frames
|
||||
.iter()
|
||||
.filter(|f| !f.persons.is_empty())
|
||||
.map(|f| f.frame)
|
||||
.collect();
|
||||
needed.sort_unstable();
|
||||
|
||||
// Extract frames
|
||||
let out_tmp = args.output_path.with_extension("frames_tmp");
|
||||
let frame_paths = match extract_frames(&args.video_path, &needed, &out_tmp) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
eprintln!("[APPEARANCE] frame extraction failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
// Map frame number → extracted file
|
||||
let frame_file: std::collections::BTreeMap<i64, std::path::PathBuf> = needed
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &f)| (f, frame_paths[i].clone()))
|
||||
.collect();
|
||||
|
||||
let mut frames_out: Vec<OutputFrame> = Vec::new();
|
||||
|
||||
for pose_frame in pose.frames.iter().filter(|f| !f.persons.is_empty()) {
|
||||
let frame_num = pose_frame.frame;
|
||||
let frame_img = match frame_file.get(&frame_num) {
|
||||
Some(p) => match image::open(p) {
|
||||
Ok(img) => img.to_rgb8(),
|
||||
Err(e) => {
|
||||
eprintln!("[APPEARANCE] failed to decode {p:?}: {e}");
|
||||
continue;
|
||||
}
|
||||
},
|
||||
None => continue,
|
||||
};
|
||||
|
||||
// Get face bbox for this frame (Python: face_by_frame.get(frame_num, persons[0].bbox))
|
||||
let fallback = pose_frame.persons[0].bbox.clone();
|
||||
let face_bbox = face_by_frame
|
||||
.get(&frame_num)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| FaceBBox {
|
||||
x: fallback.x,
|
||||
y: fallback.y,
|
||||
width: fallback.width,
|
||||
height: fallback.height,
|
||||
});
|
||||
|
||||
let mut frame_persons = Vec::new();
|
||||
for (pid, person) in pose_frame.persons.iter().enumerate() {
|
||||
let keypoints = &person.keypoints;
|
||||
if keypoints.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let bbox = &person.bbox;
|
||||
let facing = determine_facing(keypoints);
|
||||
let all_regions = compute_body_regions(keypoints, &face_bbox);
|
||||
let regions = filter_by_facing(all_regions, &facing);
|
||||
|
||||
let mut body_parts = Vec::new();
|
||||
for (name, rb) in regions {
|
||||
let roi = safe_roi(&frame_img, rb.x, rb.y, rb.width, rb.height);
|
||||
if let Some(roi_img) = roi {
|
||||
if let Some((hist, colors)) = extract_color(&roi_img) {
|
||||
body_parts.push(BodyPart {
|
||||
name,
|
||||
bbox: OBBox {
|
||||
x: rb.x,
|
||||
y: rb.y,
|
||||
width: rb.width,
|
||||
height: rb.height,
|
||||
},
|
||||
hsv_histogram: hist,
|
||||
dominant_colors: colors,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut full: Option<(Vec<Vec<f64>>, Vec<Vec<f64>>)> = None;
|
||||
if bbox.width > 0.0 && bbox.height > 0.0 {
|
||||
let full_roi = safe_roi(&frame_img, bbox.x, bbox.y, bbox.width, bbox.height);
|
||||
if let Some(f) = full_roi {
|
||||
full = extract_color(&f);
|
||||
}
|
||||
}
|
||||
|
||||
let empty_hist = vec![vec![], vec![], vec![]];
|
||||
let person_bbox_json = serde_json::json!({
|
||||
"x": bbox.x,
|
||||
"y": bbox.y,
|
||||
"width": bbox.width,
|
||||
"height": bbox.height,
|
||||
});
|
||||
frame_persons.push(OutputPerson {
|
||||
person_id: pid,
|
||||
bbox: person_bbox_json,
|
||||
facing,
|
||||
body_parts,
|
||||
dominant_colors: full.as_ref().map(|(_, c)| c.clone()).unwrap_or_default(),
|
||||
hsv_histogram: full.as_ref().map(|(h, _)| h.clone()).unwrap_or(empty_hist),
|
||||
});
|
||||
}
|
||||
|
||||
if !frame_persons.is_empty() {
|
||||
frames_out.push(OutputFrame {
|
||||
frame: frame_num,
|
||||
timestamp: pose_frame.timestamp.unwrap_or(frame_num as f64 / fps),
|
||||
persons: frame_persons,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let _ = std::fs::remove_dir_all(&out_tmp);
|
||||
|
||||
let output = Output {
|
||||
frame_count: frames_out.len() as u64,
|
||||
fps,
|
||||
frames: frames_out,
|
||||
};
|
||||
let json_str = serde_json::to_string_pretty(&output).expect("serialize failed");
|
||||
std::fs::write(&args.output_path, json_str).expect("Failed to write output");
|
||||
eprintln!("[APPEARANCE] Done: {} frames", output.frame_count);
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
use clap::Parser;
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Instant;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use rust_processors::asrx::cluster;
|
||||
use rust_processors::asrx::{l2_normalize, Ecapa, Frontend, SAMPLE_RATE};
|
||||
use rust_processors::vad::AudioReader;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_asr_asrx")]
|
||||
#[command(about = "ASR + Diarization (Rust + MLX Whisper)")]
|
||||
#[command(version)]
|
||||
struct Cli {
|
||||
/// Input audio/video file
|
||||
#[arg(short, long)]
|
||||
input: String,
|
||||
|
||||
/// Output JSON file
|
||||
#[arg(short, long)]
|
||||
output: String,
|
||||
|
||||
/// Whisper model path
|
||||
#[arg(long, default_value = "/Users/accusys/models/whisper-small-mlx")]
|
||||
model: String,
|
||||
|
||||
/// VAD model path
|
||||
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
|
||||
vad_model: String,
|
||||
|
||||
/// Language (auto-detect if not specified)
|
||||
#[arg(short, long)]
|
||||
language: Option<String>,
|
||||
|
||||
/// Enable diarization
|
||||
#[arg(long, default_value = "true")]
|
||||
diarize: bool,
|
||||
|
||||
/// ECAPA model path
|
||||
#[arg(long, default_value = "/Users/accusys/models/ecapa_tdnn.onnx")]
|
||||
ecapa_model: String,
|
||||
|
||||
/// ECAPA window file
|
||||
#[arg(long, default_value = "/Users/accusys/models/ecapa_window_400.f32")]
|
||||
window_file: String,
|
||||
|
||||
/// ECAPA mel file
|
||||
#[arg(long, default_value = "/Users/accusys/models/ecapa_mel_201x80.f32")]
|
||||
mel_file: String,
|
||||
|
||||
/// Max speakers
|
||||
#[arg(long, default_value = "10")]
|
||||
max_speakers: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct Segment {
|
||||
id: usize,
|
||||
start: f64,
|
||||
end: f64,
|
||||
text: String,
|
||||
speaker_id: Option<String>,
|
||||
is_multi_speaker: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct AsrResult {
|
||||
text: String,
|
||||
segments: Vec<AsrSegment>,
|
||||
language: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct AsrSegment {
|
||||
id: usize,
|
||||
start: f64,
|
||||
end: f64,
|
||||
text: String,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
println!("[ASR-ASRX] Starting...");
|
||||
let start_total = Instant::now();
|
||||
|
||||
let input_path = Path::new(&cli.input);
|
||||
if !input_path.exists() {
|
||||
anyhow::bail!("Input file not found: {}", cli.input);
|
||||
}
|
||||
|
||||
// Step 1: Extract audio (if video)
|
||||
println!("[1/4] Extracting audio...");
|
||||
let audio_path = if is_video_file(&cli.input) {
|
||||
extract_audio(&cli.input)?
|
||||
} else {
|
||||
cli.input.clone()
|
||||
};
|
||||
|
||||
// Step 2: VAD detection
|
||||
println!("[2/4] VAD detection...");
|
||||
let vad_segments = run_vad(&audio_path, &cli.vad_model)?;
|
||||
println!("[VAD] Found {} speech segments", vad_segments.len());
|
||||
|
||||
// Step 3: ASR transcription
|
||||
println!("[3/6] ASR transcription...");
|
||||
let asr_result = run_mlx_whisper(&audio_path, &cli.model, cli.language.as_deref())?;
|
||||
println!("[ASR] Language: {}", asr_result.language);
|
||||
println!("[ASR] Segments: {}", asr_result.segments.len());
|
||||
|
||||
// Step 4: Diarization (if enabled)
|
||||
let segments = if cli.diarize {
|
||||
println!("[4/6] Computing embeddings...");
|
||||
println!("[5/6] Clustering speakers...");
|
||||
println!("[6/6] Assigning speaker IDs...");
|
||||
perform_diarization(
|
||||
&audio_path,
|
||||
&asr_result.segments,
|
||||
&cli.ecapa_model,
|
||||
&cli.window_file,
|
||||
&cli.mel_file,
|
||||
cli.max_speakers,
|
||||
)?
|
||||
} else {
|
||||
println!("[4/6] Skipping diarization...");
|
||||
asr_result.segments.iter().enumerate().map(|(i, seg)| {
|
||||
Segment {
|
||||
id: i,
|
||||
start: seg.start,
|
||||
end: seg.end,
|
||||
text: seg.text.clone(),
|
||||
speaker_id: None,
|
||||
is_multi_speaker: false,
|
||||
}
|
||||
}).collect()
|
||||
};
|
||||
|
||||
// Count speakers
|
||||
let n_speakers = segments.iter()
|
||||
.filter_map(|s| s.speaker_id.as_ref())
|
||||
.map(|s| s.clone())
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
.len();
|
||||
|
||||
// Build speaker stats
|
||||
let mut speaker_stats: BTreeMap<String, (usize, f64)> = BTreeMap::new();
|
||||
for seg in &segments {
|
||||
if let Some(ref speaker) = seg.speaker_id {
|
||||
let entry = speaker_stats.entry(speaker.clone()).or_insert((0, 0.0));
|
||||
entry.0 += 1;
|
||||
entry.1 += seg.end - seg.start;
|
||||
}
|
||||
}
|
||||
|
||||
let stats_json: serde_json::Value = speaker_stats
|
||||
.into_iter()
|
||||
.map(|(k, (count, dur))| (k, json!({"count": count, "duration": (dur * 1000.0).round() / 1000.0})))
|
||||
.collect();
|
||||
|
||||
// Output
|
||||
let output = json!({
|
||||
"language": asr_result.language,
|
||||
"model": cli.model,
|
||||
"processor": "rust_asr_asrx",
|
||||
"segments": segments,
|
||||
"n_speakers": n_speakers,
|
||||
"speaker_stats": stats_json,
|
||||
"processing_time": {
|
||||
"total": start_total.elapsed().as_secs_f64()
|
||||
}
|
||||
});
|
||||
|
||||
std::fs::write(&cli.output, serde_json::to_string_pretty(&output)?)?;
|
||||
println!("[ASR-ASRX] Output: {}", cli.output);
|
||||
println!("[ASR-ASRX] Done in {:.2}s", start_total.elapsed().as_secs_f32());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_video_file(path: &str) -> bool {
|
||||
let ext = Path::new(path)
|
||||
.extension()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("");
|
||||
|
||||
matches!(ext.to_lowercase().as_str(), "mp4" | "mkv" | "avi" | "mov")
|
||||
}
|
||||
|
||||
fn extract_audio(input: &str) -> Result<String> {
|
||||
let output = input.replace(".mp4", ".wav").replace(".mkv", ".wav");
|
||||
|
||||
let status = Command::new("ffmpeg")
|
||||
.args(&[
|
||||
"-y", "-i", input,
|
||||
"-vn", "-acodec", "pcm_s16le",
|
||||
"-ar", "16000", "-ac", "1",
|
||||
&output
|
||||
])
|
||||
.status()
|
||||
.context("Failed to run ffmpeg")?;
|
||||
|
||||
if !status.success() {
|
||||
anyhow::bail!("ffmpeg failed");
|
||||
}
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn run_vad(audio_path: &str, vad_model: &str) -> Result<Vec<(f64, f64)>> {
|
||||
let binary = "/Users/accusys/momentry_core/tools/cli/rust/target/release/rust_vad";
|
||||
|
||||
let output = Command::new(binary)
|
||||
.args(&["--audio", audio_path, "--model", vad_model, "--format", "json"])
|
||||
.output()
|
||||
.context("Failed to run rust_vad")?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!("rust_vad failed: {}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let json_str = stdout.lines()
|
||||
.skip_while(|line| !line.starts_with('{'))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
let json: serde_json::Value = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse VAD JSON")?;
|
||||
let segments = json["segments"]
|
||||
.as_array()
|
||||
.context("Invalid VAD output")?;
|
||||
|
||||
Ok(segments.iter().map(|s| {
|
||||
let start = s["start"].as_f64().unwrap();
|
||||
let end = s["end"].as_f64().unwrap();
|
||||
(start, end)
|
||||
}).collect())
|
||||
}
|
||||
|
||||
fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Result<AsrResult> {
|
||||
let mut args = vec![
|
||||
audio_path.to_string(),
|
||||
"--model".to_string(), model.to_string(),
|
||||
"--output-format".to_string(), "json".to_string(),
|
||||
];
|
||||
|
||||
if let Some(lang) = language {
|
||||
args.push("--language".to_string());
|
||||
args.push(lang.to_string());
|
||||
}
|
||||
|
||||
let output = Command::new("/opt/homebrew/bin/mlx_whisper")
|
||||
.args(&args)
|
||||
.current_dir("/tmp")
|
||||
.output()
|
||||
.context("Failed to run mlx_whisper")?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!("mlx_whisper failed: {}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
|
||||
let output_file = Path::new(audio_path)
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap();
|
||||
|
||||
let json_path = format!("/tmp/{}.json", output_file);
|
||||
let json_content = std::fs::read_to_string(&json_path)
|
||||
.context("Failed to read MLX Whisper output")?;
|
||||
|
||||
let json: serde_json::Value = serde_json::from_str(&json_content)?;
|
||||
|
||||
let segments = json["segments"]
|
||||
.as_array()
|
||||
.context("Invalid MLX Whisper output")?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, s)| AsrSegment {
|
||||
id: i,
|
||||
start: s["start"].as_f64().unwrap(),
|
||||
end: s["end"].as_f64().unwrap(),
|
||||
text: s["text"].as_str().unwrap().to_string(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(AsrResult {
|
||||
text: json["text"].as_str().unwrap().to_string(),
|
||||
segments,
|
||||
language: json["language"].as_str().unwrap().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn perform_diarization(
|
||||
audio_path: &str,
|
||||
asr_segments: &[AsrSegment],
|
||||
ecapa_model: &str,
|
||||
window_file: &str,
|
||||
mel_file: &str,
|
||||
max_speakers: usize,
|
||||
) -> Result<Vec<Segment>> {
|
||||
// Load audio
|
||||
let audio = AudioReader::from_wav(audio_path)
|
||||
.context("Failed to read audio for diarization")?;
|
||||
let samples = audio.samples();
|
||||
|
||||
// Initialize ECAPA
|
||||
let mut frontend = Frontend::new(window_file, mel_file)
|
||||
.context("Failed to load ASRX frontend")?;
|
||||
let mut ecapa = Ecapa::new(ecapa_model)
|
||||
.context("Failed to load ECAPA model")?;
|
||||
|
||||
// Compute embeddings for each segment
|
||||
let mut embeddings: Vec<Vec<f32>> = Vec::with_capacity(asr_segments.len());
|
||||
|
||||
for seg in asr_segments {
|
||||
let a = (seg.start * SAMPLE_RATE as f64) as usize;
|
||||
let b = ((seg.end * SAMPLE_RATE as f64) as usize).min(samples.len());
|
||||
|
||||
let seg_audio = if b > a {
|
||||
&samples[a..b]
|
||||
} else {
|
||||
&samples[0..0]
|
||||
};
|
||||
|
||||
let (feats, n_frames) = frontend.compute_feats(seg_audio);
|
||||
let mut emb = if n_frames > 0 {
|
||||
ecapa.embed(&feats, n_frames)?
|
||||
} else {
|
||||
vec![0f32; 192]
|
||||
};
|
||||
|
||||
l2_normalize(&mut emb);
|
||||
embeddings.push(emb);
|
||||
}
|
||||
|
||||
// Clustering
|
||||
let distances = cluster::cosine_distances(&embeddings);
|
||||
let n_est = cluster::estimate_n_speakers(&distances, max_speakers);
|
||||
let k = n_est.min(asr_segments.len()).max(1);
|
||||
let labels = cluster::agglomerative(&distances, k);
|
||||
|
||||
// Build segments with speaker IDs
|
||||
let segments: Vec<Segment> = asr_segments
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, seg)| Segment {
|
||||
id: i,
|
||||
start: seg.start,
|
||||
end: seg.end,
|
||||
text: seg.text.clone(),
|
||||
speaker_id: Some(format!("SPEAKER_{}", labels[i])),
|
||||
is_multi_speaker: false,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(segments)
|
||||
}
|
||||
|
||||
fn combine_vad_asr(vad_segments: &[(f64, f64)], asr_result: &AsrResult) -> Vec<Segment> {
|
||||
asr_result.segments.iter().enumerate().map(|(i, asr_seg)| {
|
||||
Segment {
|
||||
id: i,
|
||||
start: asr_seg.start,
|
||||
end: asr_seg.end,
|
||||
text: asr_seg.text.clone(),
|
||||
speaker_id: None,
|
||||
is_multi_speaker: false,
|
||||
}
|
||||
}).collect()
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Instant;
|
||||
|
||||
use rust_processors::asrx::cluster;
|
||||
use rust_processors::asrx::{l2_normalize, Ecapa, Frontend, SAMPLE_RATE};
|
||||
use rust_processors::vad::segment::SegmentCollector;
|
||||
use rust_processors::vad::{AudioReader, SileroVad};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_asrx")]
|
||||
#[command(about = "Rust-native speaker diarization (ASRX)")]
|
||||
struct Cli {
|
||||
/// Input video file
|
||||
video_path: String,
|
||||
|
||||
/// Output JSON path ({file_uuid}.asrx.json)
|
||||
output_path: String,
|
||||
|
||||
/// File UUID (for Redis publishing compatibility)
|
||||
#[arg(long)]
|
||||
uuid: Option<String>,
|
||||
|
||||
/// File UUID (for Qdrant storage compatibility)
|
||||
#[arg(long = "file-uuid")]
|
||||
file_uuid: Option<String>,
|
||||
|
||||
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
|
||||
vad_model: String,
|
||||
|
||||
#[arg(long, default_value = "/Users/accusys/models/ecapa_tdnn.onnx")]
|
||||
ecapa_model: String,
|
||||
|
||||
#[arg(long, default_value = "/Users/accusys/models/ecapa_window_400.f32")]
|
||||
window_file: String,
|
||||
|
||||
#[arg(long, default_value = "/Users/accusys/models/ecapa_mel_201x80.f32")]
|
||||
mel_file: String,
|
||||
|
||||
#[arg(long, default_value = "10")]
|
||||
max_speakers: usize,
|
||||
|
||||
#[arg(long, default_value = "0.5")]
|
||||
vad_threshold: f32,
|
||||
|
||||
#[arg(long, default_value = "500")]
|
||||
min_speech: u32,
|
||||
|
||||
#[arg(long, default_value = "300")]
|
||||
min_silence: u32,
|
||||
}
|
||||
|
||||
const CHUNK_SIZE: usize = 512;
|
||||
|
||||
struct AsrSegment {
|
||||
start: f32,
|
||||
end: f32,
|
||||
text: String,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
let start_all = Instant::now();
|
||||
|
||||
let output_dir = Path::new(&cli.output_path)
|
||||
.parent()
|
||||
.map(|p| p.to_path_buf())
|
||||
.unwrap_or_else(|| Path::new(".").to_path_buf());
|
||||
let uuid_part = Path::new(&cli.output_path)
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("")
|
||||
.split('.')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let asr_path = cli.output_path.replace(".asrx.json", ".asr.json");
|
||||
|
||||
let write_result = |status: &str,
|
||||
language: Option<&str>,
|
||||
segments: Vec<serde_json::Value>,
|
||||
n_speakers: usize,
|
||||
speaker_stats: serde_json::Value|
|
||||
-> Result<()> {
|
||||
let out = json!({
|
||||
"status": status,
|
||||
"language": language,
|
||||
"segments": segments,
|
||||
"segment_count": segments.len(),
|
||||
"n_speakers": n_speakers,
|
||||
"speaker_stats": speaker_stats,
|
||||
});
|
||||
if let Some(parent) = Path::new(&cli.output_path).parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
std::fs::write(&cli.output_path, serde_json::to_string_pretty(&out)?)
|
||||
.context("Failed to write ASRX output")?;
|
||||
Ok(())
|
||||
};
|
||||
|
||||
// 1. Probe audio tracks; skip if none.
|
||||
println!("[rust_asrx] Probing audio tracks: {}", cli.video_path);
|
||||
let tracks = probe_audio_tracks(&cli.video_path);
|
||||
if tracks.is_empty() {
|
||||
println!("[rust_asrx] No audio stream detected");
|
||||
return write_result("no_audio_track", None, vec![], 0, json!({}));
|
||||
}
|
||||
|
||||
// 2. If ASR already reported silence/no-audio, mirror it.
|
||||
if Path::new(&asr_path).exists() {
|
||||
if let Ok(text) = std::fs::read_to_string(&asr_path) {
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
|
||||
let asr_status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
|
||||
let asr_lang = v.get("language").and_then(|s| s.as_str());
|
||||
if asr_status == "no_audio_track" || asr_status == "silent_audio" {
|
||||
println!("[rust_asrx] ASR status={}, skipping", asr_status);
|
||||
return write_result(asr_status, asr_lang, vec![], 0, json!({}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Load ASR segments for time alignment (text source).
|
||||
let (asr_segments, language) = load_asr_segments(&asr_path);
|
||||
|
||||
// 4. Extract audio to 16kHz mono WAV.
|
||||
let tmp_wav = format!("/tmp/rust_asrx_{}.wav", uuid_part);
|
||||
let track_index = select_best_track(&tracks);
|
||||
if let Err(e) = extract_audio(&cli.video_path, track_index, &tmp_wav) {
|
||||
println!("[rust_asrx] Audio extraction failed: {}", e);
|
||||
return write_result("silent_audio", language.as_deref(), vec![], 0, json!({}));
|
||||
}
|
||||
|
||||
let audio = AudioReader::from_wav(&tmp_wav).context("Failed to read extracted WAV")?;
|
||||
let samples = audio.samples();
|
||||
let duration = audio.duration();
|
||||
let _ = std::fs::remove_file(&tmp_wav);
|
||||
|
||||
// 5. VAD refinement per ASR segment (or whole file if no ASR).
|
||||
let mut vad = SileroVad::new(&cli.vad_model).context("Failed to load Silero VAD")?;
|
||||
let mut refined: Vec<(f32, f32, String)> = Vec::new();
|
||||
if asr_segments.is_empty() {
|
||||
let subs = scan_within_segment(
|
||||
&mut vad,
|
||||
samples,
|
||||
0.0,
|
||||
duration,
|
||||
cli.vad_threshold,
|
||||
cli.min_speech,
|
||||
cli.min_silence,
|
||||
);
|
||||
for (s, e) in subs {
|
||||
refined.push((s, e, String::new()));
|
||||
}
|
||||
} else {
|
||||
for seg in &asr_segments {
|
||||
let subs = scan_within_segment(
|
||||
&mut vad,
|
||||
samples,
|
||||
seg.start,
|
||||
seg.end,
|
||||
cli.vad_threshold,
|
||||
cli.min_speech,
|
||||
cli.min_silence,
|
||||
);
|
||||
if subs.is_empty() {
|
||||
refined.push((seg.start, seg.end, seg.text.clone()));
|
||||
} else {
|
||||
for (s, e) in subs {
|
||||
refined.push((s, e, seg.text.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if refined.is_empty() {
|
||||
println!("[rust_asrx] No speech segments");
|
||||
return write_result("silent_audio", language.as_deref(), vec![], 0, json!({}));
|
||||
}
|
||||
println!("[rust_asrx] Refined segments: {}", refined.len());
|
||||
|
||||
// 6. Speaker embeddings (ECAPA) per refined segment.
|
||||
let mut frontend = Frontend::new(&cli.window_file, &cli.mel_file)
|
||||
.context("Failed to load ASRX frontend constants")?;
|
||||
let mut ecapa = Ecapa::new(&cli.ecapa_model).context("Failed to load ECAPA model")?;
|
||||
let mut embeddings: Vec<Vec<f32>> = Vec::with_capacity(refined.len());
|
||||
for (s, e, _) in &refined {
|
||||
let a = (*s * SAMPLE_RATE as f32) as usize;
|
||||
let b = ((*e * SAMPLE_RATE as f32) as usize).min(samples.len());
|
||||
let seg_audio = if b > a {
|
||||
&samples[a..b]
|
||||
} else {
|
||||
&samples[0..0]
|
||||
};
|
||||
let (feats, n_frames) = frontend.compute_feats(seg_audio);
|
||||
let mut emb = if n_frames > 0 {
|
||||
ecapa.embed(&feats, n_frames)?
|
||||
} else {
|
||||
vec![0f32; 192]
|
||||
};
|
||||
l2_normalize(&mut emb);
|
||||
embeddings.push(emb);
|
||||
}
|
||||
|
||||
// 7. Clustering.
|
||||
let distances = cluster::cosine_distances(&embeddings);
|
||||
let n_est = cluster::estimate_n_speakers(&distances, cli.max_speakers);
|
||||
let k = n_est.min(refined.len()).max(1);
|
||||
let labels = cluster::agglomerative(&distances, k);
|
||||
let n_speakers = labels.iter().copied().max().map(|m| m + 1).unwrap_or(0);
|
||||
println!("[rust_asrx] Estimated speakers: {}", n_speakers);
|
||||
|
||||
// 8. Quality (cosine similarity to cluster centroid).
|
||||
let qualities = cluster_qualities(&embeddings, &labels);
|
||||
|
||||
// 9. Build segments.
|
||||
let fps = read_fps(&output_dir, &uuid_part);
|
||||
let mut segments: Vec<serde_json::Value> = Vec::with_capacity(refined.len());
|
||||
let mut speaker_stats: std::collections::BTreeMap<String, (usize, f64)> =
|
||||
std::collections::BTreeMap::new();
|
||||
for (i, (s, e, text)) in refined.iter().enumerate() {
|
||||
let speaker = format!("SPEAKER_{}", labels[i]);
|
||||
let start_frame = (s * fps) as u64;
|
||||
let end_frame = (e * fps) as u64;
|
||||
segments.push(json!({
|
||||
"start_time": round3(*s),
|
||||
"end_time": round3(*e),
|
||||
"start_frame": start_frame,
|
||||
"end_frame": end_frame,
|
||||
"text": text,
|
||||
"speaker_id": speaker,
|
||||
"language": language,
|
||||
"lang_prob": 0.0,
|
||||
"quality": (qualities[i] * 1000.0).round() / 1000.0,
|
||||
}));
|
||||
let entry = speaker_stats.entry(speaker).or_insert((0, 0.0));
|
||||
entry.0 += 1;
|
||||
entry.1 += (*e - *s) as f64;
|
||||
}
|
||||
let stats_json: serde_json::Value = speaker_stats
|
||||
.into_iter()
|
||||
.map(|(k, (count, dur))| (k, json!({"count": count, "duration": round3(dur as f32)})))
|
||||
.collect();
|
||||
|
||||
write_result(
|
||||
"has_transcript",
|
||||
language.as_deref(),
|
||||
segments,
|
||||
n_speakers,
|
||||
stats_json,
|
||||
)?;
|
||||
println!(
|
||||
"[rust_asrx] Done: {} segments, {} speakers in {:.2}s",
|
||||
refined.len(),
|
||||
n_speakers,
|
||||
start_all.elapsed().as_secs_f32()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn round3(v: f32) -> f64 {
|
||||
((v as f64) * 1000.0).round() / 1000.0
|
||||
}
|
||||
|
||||
/// VAD-scan a time window and return refined sub-segments on the global timeline.
|
||||
fn scan_within_segment(
|
||||
vad: &mut SileroVad,
|
||||
samples: &[f32],
|
||||
start_sec: f32,
|
||||
end_sec: f32,
|
||||
threshold: f32,
|
||||
min_speech_ms: u32,
|
||||
min_silence_ms: u32,
|
||||
) -> Vec<(f32, f32)> {
|
||||
let a = (start_sec * SAMPLE_RATE as f32) as usize;
|
||||
let b = ((end_sec * SAMPLE_RATE as f32) as usize).min(samples.len());
|
||||
if b <= a {
|
||||
return Vec::new();
|
||||
}
|
||||
let sub = &samples[a..b];
|
||||
let offset = a as f32 / SAMPLE_RATE as f32;
|
||||
|
||||
vad.reset_state();
|
||||
let mut collector = SegmentCollector::new(threshold, min_speech_ms, min_silence_ms);
|
||||
let mut i = 0;
|
||||
while i < sub.len() {
|
||||
let end = (i + CHUNK_SIZE).min(sub.len());
|
||||
let mut chunk = sub[i..end].to_vec();
|
||||
if chunk.len() < CHUNK_SIZE {
|
||||
chunk.resize(CHUNK_SIZE, 0.0);
|
||||
}
|
||||
let prob = match vad.detect(&chunk) {
|
||||
Ok(p) => p,
|
||||
Err(_) => 0.0,
|
||||
};
|
||||
collector.process(i as f32 / SAMPLE_RATE as f32, prob);
|
||||
i += CHUNK_SIZE;
|
||||
}
|
||||
collector.finalize(sub.len() as f32 / SAMPLE_RATE as f32);
|
||||
collector
|
||||
.segments()
|
||||
.iter()
|
||||
.map(|s| (s.start_sec + offset, s.end_sec + offset))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn cluster_qualities(embeddings: &[Vec<f32>], labels: &[usize]) -> Vec<f32> {
|
||||
let n = embeddings.len();
|
||||
let dim = if n > 0 { embeddings[0].len() } else { 0 };
|
||||
let k = labels.iter().copied().max().map(|m| m + 1).unwrap_or(0);
|
||||
let mut centroids = vec![vec![0f32; dim]; k];
|
||||
let mut counts = vec![0usize; k];
|
||||
for (i, emb) in embeddings.iter().enumerate() {
|
||||
let l = labels[i];
|
||||
for d in 0..dim {
|
||||
centroids[l][d] += emb[d];
|
||||
}
|
||||
counts[l] += 1;
|
||||
}
|
||||
for l in 0..k {
|
||||
if counts[l] > 0 {
|
||||
for d in 0..dim {
|
||||
centroids[l][d] /= counts[l] as f32;
|
||||
}
|
||||
l2_normalize(&mut centroids[l]);
|
||||
}
|
||||
}
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let l = labels[i];
|
||||
embeddings[i]
|
||||
.iter()
|
||||
.zip(centroids[l].iter())
|
||||
.map(|(a, b)| a * b)
|
||||
.sum::<f32>()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn load_asr_segments(asr_path: &str) -> (Vec<AsrSegment>, Option<String>) {
|
||||
let mut segments = Vec::new();
|
||||
let mut language = None;
|
||||
if let Ok(text) = std::fs::read_to_string(asr_path) {
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
|
||||
language = v
|
||||
.get("language")
|
||||
.and_then(|s| s.as_str())
|
||||
.map(|s| s.to_string());
|
||||
if let Some(arr) = v.get("segments").and_then(|s| s.as_array()) {
|
||||
for seg in arr {
|
||||
let start = seg
|
||||
.get("start_time")
|
||||
.or_else(|| seg.get("start"))
|
||||
.and_then(|n| n.as_f64())
|
||||
.unwrap_or(0.0) as f32;
|
||||
let end = seg
|
||||
.get("end_time")
|
||||
.or_else(|| seg.get("end"))
|
||||
.and_then(|n| n.as_f64())
|
||||
.unwrap_or(0.0) as f32;
|
||||
let text = seg
|
||||
.get("text")
|
||||
.and_then(|s| s.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
segments.push(AsrSegment { start, end, text });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(segments, language)
|
||||
}
|
||||
|
||||
struct AudioTrack {
|
||||
index: i64,
|
||||
language: String,
|
||||
channels: i64,
|
||||
}
|
||||
|
||||
fn probe_audio_tracks(video_path: &str) -> Vec<AudioTrack> {
|
||||
let out = Command::new("ffprobe")
|
||||
.args([
|
||||
"-v",
|
||||
"quiet",
|
||||
"-print_format",
|
||||
"json",
|
||||
"-show_streams",
|
||||
"-select_streams",
|
||||
"a",
|
||||
video_path,
|
||||
])
|
||||
.output();
|
||||
let out = match out {
|
||||
Ok(o) if o.status.success() => o,
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
let v: serde_json::Value = match serde_json::from_slice(&out.stdout) {
|
||||
Ok(v) => v,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
let mut tracks = Vec::new();
|
||||
if let Some(streams) = v.get("streams").and_then(|s| s.as_array()) {
|
||||
for s in streams {
|
||||
tracks.push(AudioTrack {
|
||||
index: s.get("index").and_then(|x| x.as_i64()).unwrap_or(0),
|
||||
language: s
|
||||
.get("tags")
|
||||
.and_then(|t| t.get("language"))
|
||||
.and_then(|l| l.as_str())
|
||||
.unwrap_or("und")
|
||||
.to_string(),
|
||||
channels: s.get("channels").and_then(|c| c.as_i64()).unwrap_or(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
tracks
|
||||
}
|
||||
|
||||
/// Prefer English, else the track with the most channels.
|
||||
fn select_best_track(tracks: &[AudioTrack]) -> i64 {
|
||||
for t in tracks {
|
||||
if t.language == "eng" || t.language == "en" {
|
||||
return t.index;
|
||||
}
|
||||
}
|
||||
let mut best = &tracks[0];
|
||||
for t in tracks {
|
||||
if t.channels > best.channels {
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
best.index
|
||||
}
|
||||
|
||||
fn extract_audio(video_path: &str, track_index: i64, output_wav: &str) -> Result<()> {
|
||||
let status = Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-v",
|
||||
"quiet",
|
||||
"-i",
|
||||
video_path,
|
||||
"-map",
|
||||
&format!("0:{}", track_index),
|
||||
"-ar",
|
||||
"16000",
|
||||
"-ac",
|
||||
"1",
|
||||
"-sample_fmt",
|
||||
"s16",
|
||||
output_wav,
|
||||
])
|
||||
.status()
|
||||
.context("Failed to run ffmpeg")?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("ffmpeg exited with {}", status);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_fps(output_dir: &Path, uuid_part: &str) -> f32 {
|
||||
let probe_path = output_dir.join(format!("{}.probe.json", uuid_part));
|
||||
if let Ok(text) = std::fs::read_to_string(&probe_path) {
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
|
||||
if let Some(streams) = v.get("streams").and_then(|s| s.as_array()) {
|
||||
for s in streams {
|
||||
if s.get("codec_type").and_then(|c| c.as_str()) == Some("video") {
|
||||
if let Some(rate) = s.get("r_frame_rate").and_then(|r| r.as_str()) {
|
||||
if let Some((num, den)) = rate.split_once('/') {
|
||||
let n: f32 = num.parse().unwrap_or(30.0);
|
||||
let d: f32 = den.parse().unwrap_or(1.0);
|
||||
if d > 0.0 {
|
||||
return n / d;
|
||||
}
|
||||
} else if let Ok(f) = rate.parse::<f32>() {
|
||||
return f;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
30.0
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_cut")]
|
||||
#[command(about = "Scene detection using ffmpeg")]
|
||||
struct Cli {
|
||||
/// Video file path
|
||||
#[arg(required = true)]
|
||||
video_path: String,
|
||||
|
||||
/// Output JSON path
|
||||
#[arg(long)]
|
||||
output: Option<String>,
|
||||
|
||||
/// Video UUID
|
||||
#[arg(long)]
|
||||
uuid: Option<String>,
|
||||
|
||||
/// Minimum scene duration (seconds)
|
||||
#[arg(long, default_value = "0.5")]
|
||||
min_scene_duration: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct CutResult {
|
||||
scene_count: usize,
|
||||
scenes: Vec<Scene>,
|
||||
video_info: VideoInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Scene {
|
||||
scene_id: usize,
|
||||
start_frame: u64,
|
||||
start_time: f64,
|
||||
end_frame: u64,
|
||||
end_time: f64,
|
||||
duration: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct VideoInfo {
|
||||
duration: f64,
|
||||
fps: f64,
|
||||
frame_count: u64,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Cli::parse();
|
||||
|
||||
println!("[CUT] Processing: {}", args.video_path);
|
||||
|
||||
let output_path = args.output.unwrap_or_else(|| {
|
||||
args.video_path.replace(".mp4", ".cut.json")
|
||||
});
|
||||
|
||||
let video_info = get_video_info(&args.video_path)?;
|
||||
println!("[CUT] Duration: {:.1}s, FPS: {:.1}, Frames: {}",
|
||||
video_info.duration, video_info.fps, video_info.frame_count);
|
||||
|
||||
let scenes = detect_scenes(&args.video_path, args.min_scene_duration, &video_info)?;
|
||||
println!("[CUT] Detected {} scenes", scenes.len());
|
||||
|
||||
let result = CutResult {
|
||||
scene_count: scenes.len(),
|
||||
scenes,
|
||||
video_info,
|
||||
};
|
||||
|
||||
let json = serde_json::to_string_pretty(&result)?;
|
||||
std::fs::write(&output_path, json)?;
|
||||
println!("[CUT] Output: {}", output_path);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_video_info(video_path: &str) -> Result<VideoInfo> {
|
||||
let output = Command::new("ffprobe")
|
||||
.args([
|
||||
"-v", "quiet",
|
||||
"-print_format", "json",
|
||||
"-show_format",
|
||||
"-show_streams",
|
||||
video_path,
|
||||
])
|
||||
.output()
|
||||
.context("Failed to run ffprobe")?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!("ffprobe failed");
|
||||
}
|
||||
|
||||
let json: serde_json::Value = serde_json::from_slice(&output.stdout)?;
|
||||
|
||||
let duration = json["format"]["duration"]
|
||||
.as_str()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0.0);
|
||||
|
||||
let fps_str = json["streams"][0]["r_frame_rate"]
|
||||
.as_str()
|
||||
.unwrap_or("30/1");
|
||||
|
||||
let fps = if fps_str.contains('/') {
|
||||
let parts: Vec<&str> = fps_str.split('/').collect();
|
||||
let num: f64 = parts[0].parse().unwrap_or(30.0);
|
||||
let den: f64 = parts[1].parse().unwrap_or(1.0);
|
||||
num / den
|
||||
} else {
|
||||
fps_str.parse().unwrap_or(30.0)
|
||||
};
|
||||
|
||||
let frame_count = (duration * fps) as u64;
|
||||
|
||||
Ok(VideoInfo {
|
||||
duration,
|
||||
fps,
|
||||
frame_count,
|
||||
})
|
||||
}
|
||||
|
||||
fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) -> Result<Vec<Scene>> {
|
||||
let output = Command::new("ffmpeg")
|
||||
.args([
|
||||
"-i", video_path,
|
||||
"-vf", "select='gt(scene,0.3)',showinfo",
|
||||
"-f", "null",
|
||||
"-",
|
||||
])
|
||||
.output()
|
||||
.context("Failed to run ffmpeg")?;
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let mut scenes = Vec::new();
|
||||
|
||||
let mut last_time = 0.0;
|
||||
let mut scene_id = 0;
|
||||
|
||||
for line in stderr.lines() {
|
||||
if line.contains("pts_time:") {
|
||||
if let Some(time_str) = line.split("pts_time:").nth(1) {
|
||||
if let Ok(time) = time_str.split_whitespace().next().unwrap_or("0").parse::<f64>() {
|
||||
if time - last_time >= min_duration {
|
||||
let start_frame = (last_time * video_info.fps) as u64;
|
||||
let end_frame = (time * video_info.fps) as u64;
|
||||
|
||||
scenes.push(Scene {
|
||||
scene_id,
|
||||
start_frame,
|
||||
start_time: last_time,
|
||||
end_frame,
|
||||
end_time: time,
|
||||
duration: time - last_time,
|
||||
});
|
||||
|
||||
scene_id += 1;
|
||||
last_time = time;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if scenes.is_empty() {
|
||||
scenes.push(Scene {
|
||||
scene_id: 0,
|
||||
start_frame: 0,
|
||||
start_time: 0.0,
|
||||
end_frame: video_info.frame_count,
|
||||
end_time: video_info.duration,
|
||||
duration: video_info.duration,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(scenes)
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// Face Clustering Processor (Rust port of fast_face_clustering_processor.py)
|
||||
///
|
||||
/// Loads face embeddings from Qdrant `_faces`, groups by trace_id, computes
|
||||
/// weighted-average embeddings per trace, then clusters traces with either the
|
||||
/// seed-leader method (default, deterministic) or average-linkage agglomerative.
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_face_cluster", about = "Face Clustering Processor (Rust port)")]
|
||||
struct Args {
|
||||
video_path: String,
|
||||
output_path: PathBuf,
|
||||
#[arg(short = 'u', long = "uuid", default_value = "")]
|
||||
uuid: String,
|
||||
#[arg(long = "frames", default_value = None)]
|
||||
frames: Option<String>,
|
||||
#[arg(long = "method", default_value = "leader")]
|
||||
method: String,
|
||||
#[arg(long = "threshold", default_value_t = 0.15)]
|
||||
threshold: f64,
|
||||
#[arg(long = "stage2")]
|
||||
stage2: bool,
|
||||
#[arg(long = "merge-threshold", default_value_t = 0.20)]
|
||||
merge_threshold: f64,
|
||||
#[arg(long = "force")]
|
||||
force: bool,
|
||||
}
|
||||
|
||||
const CONFIDENCE_THRESHOLD: f64 = 0.5;
|
||||
const DEFAULT_QDRANT_URL: &str = "http://localhost:6333";
|
||||
const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FacePoint {
|
||||
payload: Value,
|
||||
vector: Vec<f64>,
|
||||
}
|
||||
|
||||
fn env_var(name: &str, default: &str) -> String {
|
||||
std::env::var(name).unwrap_or_else(|_| default.to_string())
|
||||
}
|
||||
|
||||
/// Mimic Python's `round(x, n)` (banker's rounding / round-half-to-even).
|
||||
fn round_digits(x: f64, digits: i32) -> f64 {
|
||||
let factor = 10_f64.powi(digits);
|
||||
(x * factor).round_ties_even() / factor
|
||||
}
|
||||
|
||||
/// Recursively round all float values to 2 decimals (Python `round_json_numbers`).
|
||||
fn round_json(value: Value) -> Value {
|
||||
match value {
|
||||
Value::Number(n) => {
|
||||
if n.is_f64() {
|
||||
let f = n.as_f64().unwrap_or(0.0);
|
||||
let r = round_digits(f, 2);
|
||||
serde_json::Number::from_f64(r)
|
||||
.map(Value::Number)
|
||||
.unwrap_or(Value::Number(n))
|
||||
} else {
|
||||
Value::Number(n)
|
||||
}
|
||||
}
|
||||
Value::Array(items) => Value::Array(items.into_iter().map(round_json).collect()),
|
||||
Value::Object(map) => {
|
||||
Value::Object(map.into_iter().map(|(k, v)| (k, round_json(v))).collect())
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_empty_output(status: &str, file_uuid: &str, output_path: &std::path::Path) {
|
||||
let output_data = json!({
|
||||
"status": status,
|
||||
"file_uuid": file_uuid,
|
||||
"clusters": [],
|
||||
"frames": [],
|
||||
});
|
||||
let text = serde_json::to_string_pretty(&output_data).unwrap_or_default();
|
||||
let _ = std::fs::write(output_path, text);
|
||||
eprintln!("Wrote empty output ({}) to {}", status, output_path.display());
|
||||
}
|
||||
|
||||
/// Scroll all Qdrant `_faces` points (payload + vector) for a file via HTTP.
|
||||
fn load_qdrant_faces(uuid: &str) -> Vec<FacePoint> {
|
||||
let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL);
|
||||
let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY);
|
||||
let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url);
|
||||
|
||||
let mut all_points: Vec<FacePoint> = Vec::new();
|
||||
let mut offset: Option<Value> = None;
|
||||
loop {
|
||||
let mut body = json!({
|
||||
"limit": 10000,
|
||||
"with_payload": true,
|
||||
"with_vector": true,
|
||||
"filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]},
|
||||
});
|
||||
if let Some(ref off) = offset {
|
||||
body["offset"] = off.clone();
|
||||
}
|
||||
|
||||
let resp = ureq::post(&scroll_url)
|
||||
.set("api-key", &qdrant_api_key)
|
||||
.timeout(Duration::from_secs(60))
|
||||
.send_json(body);
|
||||
|
||||
match resp {
|
||||
Ok(r) => {
|
||||
let data: Value = r.into_json().unwrap_or(Value::Null);
|
||||
let points = data
|
||||
.pointer("/result/points")
|
||||
.and_then(|p| p.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
for p in points {
|
||||
let payload = p.get("payload").cloned().unwrap_or(Value::Null);
|
||||
let vector = p
|
||||
.get("vector")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|v| {
|
||||
v.iter()
|
||||
.filter_map(|x| x.as_f64())
|
||||
.collect::<Vec<f64>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
all_points.push(FacePoint { payload, vector });
|
||||
}
|
||||
let next = data.pointer("/result/next_page_offset").cloned();
|
||||
match next {
|
||||
Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)),
|
||||
Some(Value::Number(_)) => break,
|
||||
Some(Value::Null) | None => break,
|
||||
other => {
|
||||
offset = other;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Qdrant scroll error: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("Loaded {} points from Qdrant _faces", all_points.len());
|
||||
all_points
|
||||
}
|
||||
|
||||
fn dot(a: &[f64], b: &[f64]) -> f64 {
|
||||
a.iter().zip(b).map(|(x, y)| x * y).sum()
|
||||
}
|
||||
|
||||
fn norm(v: &[f64]) -> f64 {
|
||||
v.iter().map(|x| x * x).sum::<f64>().sqrt()
|
||||
}
|
||||
|
||||
fn cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
|
||||
let n1 = norm(a);
|
||||
let n2 = norm(b);
|
||||
if n1 > 0.0 && n2 > 0.0 {
|
||||
dot(a, b) / (n1 * n2)
|
||||
} else {
|
||||
-1.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Weighted-average embedding per trace + pairs (cluster_by_trace).
|
||||
/// Returns (trace_embeddings: BTreeMap<trace_id, Vec<f64>>).
|
||||
fn cluster_by_trace(
|
||||
points: &[FacePoint],
|
||||
min_faces_per_trace: usize,
|
||||
confidence_threshold: f64,
|
||||
) -> BTreeMap<i64, Vec<f64>> {
|
||||
let high_conf: Vec<&FacePoint> = points
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
p.payload
|
||||
.get("confidence")
|
||||
.and_then(|c| c.as_f64())
|
||||
.unwrap_or(0.0)
|
||||
>= confidence_threshold
|
||||
})
|
||||
.collect();
|
||||
eprintln!(
|
||||
"[FILTER] {}/{} faces pass confidence >= {}",
|
||||
high_conf.len(),
|
||||
points.len(),
|
||||
confidence_threshold
|
||||
);
|
||||
|
||||
let mut traces: BTreeMap<i64, Vec<&FacePoint>> = BTreeMap::new();
|
||||
for p in &high_conf {
|
||||
if let Some(trace_id) = p.payload.get("trace_id").and_then(|t| t.as_i64()) {
|
||||
if trace_id >= 0 {
|
||||
traces.entry(trace_id).or_default().push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("[TRACE] Found {} unique traces", traces.len());
|
||||
|
||||
let mut trace_embeddings: BTreeMap<i64, Vec<f64>> = BTreeMap::new();
|
||||
for (trace_id, trace_points) in traces.iter() {
|
||||
if trace_points.len() < min_faces_per_trace {
|
||||
continue;
|
||||
}
|
||||
let mut embeddings: Vec<&[f64]> = Vec::new();
|
||||
let mut weights: Vec<f64> = Vec::new();
|
||||
for p in trace_points {
|
||||
embeddings.push(&p.vector);
|
||||
weights.push(p.payload.get("confidence").and_then(|c| c.as_f64()).unwrap_or(1.0));
|
||||
}
|
||||
let weight_sum: f64 = weights.iter().sum();
|
||||
for w in weights.iter_mut() {
|
||||
*w /= weight_sum;
|
||||
}
|
||||
let dim = embeddings.first().map(|e| e.len()).unwrap_or(0);
|
||||
let mut avg = vec![0.0_f64; dim];
|
||||
for (e, w) in embeddings.iter().zip(weights.iter()) {
|
||||
for (i, x) in e.iter().enumerate() {
|
||||
avg[i] += x * w;
|
||||
}
|
||||
}
|
||||
let n = norm(&avg);
|
||||
if n > 0.0 {
|
||||
for x in avg.iter_mut() {
|
||||
*x /= n;
|
||||
}
|
||||
}
|
||||
trace_embeddings.insert(*trace_id, avg);
|
||||
}
|
||||
eprintln!(
|
||||
"[TRACE] {} traces with >= {} faces",
|
||||
trace_embeddings.len(),
|
||||
min_faces_per_trace
|
||||
);
|
||||
trace_embeddings
|
||||
}
|
||||
|
||||
/// Seed-leader clustering with incremental mean centroids (Python default method).
|
||||
/// Returns (trace_to_person, trace_similarities).
|
||||
fn seed_leader_cluster(
|
||||
trace_embeddings: &BTreeMap<i64, Vec<f64>>,
|
||||
threshold: f64,
|
||||
) -> (BTreeMap<i64, i64>, BTreeMap<i64, f64>) {
|
||||
let trace_ids: Vec<&i64> = trace_embeddings.keys().collect();
|
||||
let n_traces = trace_ids.len();
|
||||
if n_traces == 0 {
|
||||
return (BTreeMap::new(), BTreeMap::new());
|
||||
}
|
||||
if n_traces == 1 {
|
||||
let tid = *trace_ids[0];
|
||||
let mut tm = BTreeMap::new();
|
||||
tm.insert(tid, 0);
|
||||
let mut sm = BTreeMap::new();
|
||||
sm.insert(tid, 1.0);
|
||||
return (tm, sm);
|
||||
}
|
||||
|
||||
let sim_threshold = 1.0 - threshold;
|
||||
let mut persons: Vec<(Vec<f64>, Vec<i64>)> = Vec::new(); // (centroid, member_trace_ids)
|
||||
let mut trace_similarities: BTreeMap<i64, f64> = BTreeMap::new();
|
||||
|
||||
for tid in trace_ids {
|
||||
let centroid = trace_embeddings[tid].clone();
|
||||
if persons.is_empty() {
|
||||
persons.push((centroid, vec![*tid]));
|
||||
trace_similarities.insert(*tid, 1.0);
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut best_sim = -1.0;
|
||||
let mut best_person_idx: Option<usize> = None;
|
||||
for (idx, person) in persons.iter().enumerate() {
|
||||
let sim = cosine_similarity(¢roid, &person.0);
|
||||
if sim > best_sim {
|
||||
best_sim = sim;
|
||||
best_person_idx = Some(idx);
|
||||
}
|
||||
}
|
||||
|
||||
match best_person_idx {
|
||||
Some(idx) if best_sim >= sim_threshold => {
|
||||
persons[idx].1.push(*tid);
|
||||
trace_similarities.insert(*tid, best_sim);
|
||||
let members: Vec<Vec<f64>> = persons[idx]
|
||||
.1
|
||||
.iter()
|
||||
.map(|m| trace_embeddings[m].clone())
|
||||
.collect();
|
||||
let dim = members[0].len();
|
||||
let mut mean = vec![0.0_f64; dim];
|
||||
for m in &members {
|
||||
for (i, x) in m.iter().enumerate() {
|
||||
mean[i] += x;
|
||||
}
|
||||
}
|
||||
let cnt = members.len() as f64;
|
||||
for x in mean.iter_mut() {
|
||||
*x /= cnt;
|
||||
}
|
||||
persons[idx].0 = mean;
|
||||
}
|
||||
_ => {
|
||||
persons.push((centroid, vec![*tid]));
|
||||
trace_similarities.insert(*tid, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut trace_to_person: BTreeMap<i64, i64> = BTreeMap::new();
|
||||
for (person_label, person) in persons.iter().enumerate() {
|
||||
for m in &person.1 {
|
||||
trace_to_person.insert(*m, person_label as i64);
|
||||
}
|
||||
}
|
||||
eprintln!("[CLUSTER] Seed-leader detected {} unique persons", persons.len());
|
||||
(trace_to_person, trace_similarities)
|
||||
}
|
||||
|
||||
/// Average-linkage agglomerative clustering (sklearn AgglomerativeClustering
|
||||
/// with metric="cosine", linkage="average", distance_threshold=threshold).
|
||||
/// Trace similarity is a 1.0 placeholder, matching the Python script.
|
||||
fn agglomerative_cluster(
|
||||
trace_embeddings: &BTreeMap<i64, Vec<f64>>,
|
||||
threshold: f64,
|
||||
) -> (BTreeMap<i64, i64>, BTreeMap<i64, f64>) {
|
||||
let trace_ids: Vec<&i64> = trace_embeddings.keys().collect();
|
||||
let n = trace_ids.len();
|
||||
if n == 0 {
|
||||
return (BTreeMap::new(), BTreeMap::new());
|
||||
}
|
||||
if n == 1 {
|
||||
let mut tm = BTreeMap::new();
|
||||
tm.insert(*trace_ids[0], 0);
|
||||
let mut sm = BTreeMap::new();
|
||||
sm.insert(*trace_ids[0], 1.0);
|
||||
return (tm, sm);
|
||||
}
|
||||
|
||||
// distance matrix: 1 - cosine
|
||||
let mut dist = vec![vec![0.0_f64; n]; n];
|
||||
for i in 0..n {
|
||||
for j in (i + 1)..n {
|
||||
let d = 1.0 - cosine_similarity(&trace_embeddings[&trace_ids[i]], &trace_embeddings[&trace_ids[j]]);
|
||||
dist[i][j] = d;
|
||||
dist[j][i] = d;
|
||||
}
|
||||
}
|
||||
|
||||
// Each cluster: set of member indices. Merges happen in-place: targets stay
|
||||
// within 0..n, merged-away clusters are cleared + marked inactive.
|
||||
let mut clusters: Vec<Vec<usize>> = (0..n).map(|i| vec![i]).collect();
|
||||
let mut active = vec![true; n];
|
||||
|
||||
loop {
|
||||
// Find pair (a, b) with min distance among active clusters (average linkage).
|
||||
// Given the input is trace means, average linkage of members = average of
|
||||
// pairwise distances. We maintain dist as the average linkage between clusters.
|
||||
let mut best_d = f64::INFINITY;
|
||||
let mut best_pair: Option<(usize, usize)> = None;
|
||||
for a in 0..n {
|
||||
if !active[a] || clusters[a].is_empty() {
|
||||
continue;
|
||||
}
|
||||
for b in (a + 1)..n {
|
||||
if !active[b] || clusters[b].is_empty() {
|
||||
continue;
|
||||
}
|
||||
if dist[a][b] < best_d {
|
||||
best_d = dist[a][b];
|
||||
best_pair = Some((a, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some((a, b)) = best_pair else { break };
|
||||
if best_d > threshold {
|
||||
break;
|
||||
}
|
||||
|
||||
// Merge b into a.
|
||||
let mut merged = clusters[a].clone();
|
||||
merged.extend_from_slice(&clusters[b]);
|
||||
clusters[a] = merged;
|
||||
clusters[b].clear();
|
||||
active[b] = false;
|
||||
|
||||
// Update average-linkage distances from merged cluster (a) to all others.
|
||||
// Recompute via members is exact for average linkage (UPGMA).
|
||||
for k in 0..n {
|
||||
if !active[k] || k == a || clusters[k].is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut sum = 0.0;
|
||||
let mut cnt = 0;
|
||||
for &mi in &clusters[a] {
|
||||
for &mk in &clusters[k] {
|
||||
sum += 1.0 - cosine_similarity(
|
||||
&trace_embeddings[&trace_ids[mi]],
|
||||
&trace_embeddings[&trace_ids[mk]],
|
||||
);
|
||||
cnt += 1;
|
||||
}
|
||||
}
|
||||
dist[a][k] = if cnt > 0 { sum / cnt as f64 } else { f64::INFINITY };
|
||||
dist[k][a] = dist[a][k];
|
||||
}
|
||||
}
|
||||
|
||||
let mut trace_to_person: BTreeMap<i64, i64> = BTreeMap::new();
|
||||
let mut label = 0;
|
||||
for cid in 0..n {
|
||||
if active[cid] && !clusters[cid].is_empty() {
|
||||
for &mi in &clusters[cid] {
|
||||
trace_to_person.insert(*trace_ids[mi], label);
|
||||
}
|
||||
label += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let mut trace_similarities: BTreeMap<i64, f64> = BTreeMap::new();
|
||||
for tid in trace_ids.iter() {
|
||||
trace_similarities.insert(**tid, 1.0);
|
||||
}
|
||||
|
||||
eprintln!("[CLUSTER] Agglomerative detected {} unique persons", label);
|
||||
(trace_to_person, trace_similarities)
|
||||
}
|
||||
|
||||
/// Stage 2: Merge over-split clusters based on centroid similarity.
|
||||
/// 1. Compute centroid for each person (mean of trace embeddings)
|
||||
/// 2. Find person pairs with distance < merge_threshold
|
||||
/// 3. Merge iteratively
|
||||
/// 4. Remap labels to consecutive integers
|
||||
fn stage2_merge_clusters(
|
||||
trace_embeddings: &BTreeMap<i64, Vec<f64>>,
|
||||
initial_labels: &BTreeMap<i64, i64>,
|
||||
merge_threshold: f64,
|
||||
) -> BTreeMap<i64, i64> {
|
||||
// 1. Compute centroids for each person
|
||||
let mut person_centroids: BTreeMap<i64, Vec<f64>> = BTreeMap::new();
|
||||
let mut person_counts: BTreeMap<i64, usize> = BTreeMap::new();
|
||||
|
||||
for (trace_id, embedding) in trace_embeddings.iter() {
|
||||
let person_label = initial_labels[trace_id];
|
||||
let centroid = person_centroids.entry(person_label).or_insert(vec![0.0; embedding.len()]);
|
||||
for (i, &val) in embedding.iter().enumerate() {
|
||||
centroid[i] += val;
|
||||
}
|
||||
*person_counts.entry(person_label).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
// Normalize centroids
|
||||
for (person_label, centroid) in person_centroids.iter_mut() {
|
||||
let count = person_counts[person_label] as f64;
|
||||
for val in centroid.iter_mut() {
|
||||
*val /= count;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Find merge pairs (distance < merge_threshold)
|
||||
let person_labels: Vec<i64> = person_centroids.keys().cloned().collect();
|
||||
let mut merge_pairs: Vec<(i64, i64)> = Vec::new();
|
||||
|
||||
for i in 0..person_labels.len() {
|
||||
for j in (i + 1)..person_labels.len() {
|
||||
let label1 = person_labels[i];
|
||||
let label2 = person_labels[j];
|
||||
let dist = 1.0 - cosine_similarity(&person_centroids[&label1], &person_centroids[&label2]);
|
||||
if dist < merge_threshold {
|
||||
merge_pairs.push((label1, label2));
|
||||
eprintln!("[STAGE2] Merge candidate: Person_{} <-> Person_{} (distance={:.4})",
|
||||
label1, label2, dist);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if merge_pairs.is_empty() {
|
||||
eprintln!("[STAGE2] No clusters to merge");
|
||||
return initial_labels.clone();
|
||||
}
|
||||
|
||||
// 3. Merge iteratively (union-find style)
|
||||
let mut label_mapping: BTreeMap<i64, i64> = person_labels.iter().map(|&l| (l, l)).collect();
|
||||
|
||||
for (label1, label2) in merge_pairs {
|
||||
let target = label_mapping[&label1];
|
||||
let source = label_mapping[&label2];
|
||||
if target != source {
|
||||
// Merge source into target (use smaller label as target)
|
||||
let final_target = if target < source { target } else { source };
|
||||
let final_source = if target < source { source } else { target };
|
||||
|
||||
for (_, mapped) in label_mapping.iter_mut() {
|
||||
if *mapped == final_source {
|
||||
*mapped = final_target;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Remap to consecutive integers
|
||||
let final_labels: std::collections::HashSet<i64> = label_mapping.values().cloned().collect();
|
||||
let mut sorted_labels: Vec<i64> = final_labels.into_iter().collect();
|
||||
sorted_labels.sort();
|
||||
|
||||
let mut label_to_person: BTreeMap<i64, i64> = BTreeMap::new();
|
||||
for (i, &label) in sorted_labels.iter().enumerate() {
|
||||
label_to_person.insert(label, i as i64);
|
||||
}
|
||||
|
||||
// 5. Build final trace_to_person mapping
|
||||
let mut trace_to_person: BTreeMap<i64, i64> = BTreeMap::new();
|
||||
for (trace_id, &initial_label) in initial_labels.iter() {
|
||||
let merged_label = label_mapping[&initial_label];
|
||||
let final_label = label_to_person[&merged_label];
|
||||
trace_to_person.insert(*trace_id, final_label);
|
||||
}
|
||||
|
||||
let n_before = person_labels.len();
|
||||
let n_after = sorted_labels.len();
|
||||
eprintln!("[STAGE2] Merged {} -> {} persons", n_before, n_after);
|
||||
|
||||
trace_to_person
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
let uuid = if args.uuid.is_empty() {
|
||||
std::path::Path::new(&args.video_path)
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("quick_preview")
|
||||
.to_string()
|
||||
} else {
|
||||
args.uuid.clone()
|
||||
};
|
||||
|
||||
let output_dir = args.output_path.parent().unwrap_or(std::path::Path::new("."));
|
||||
let mut face_json_path = output_dir.join(format!("{}.face.json", uuid));
|
||||
|
||||
eprintln!("[FACE_CLUSTER] Starting face clustering: {}", args.video_path);
|
||||
eprintln!("[DEBUG] Output dir: {:?}", output_dir);
|
||||
eprintln!("[DEBUG] Initial face_json_path: {:?}", face_json_path);
|
||||
eprintln!("[DEBUG] File exists (attempt 1): {}", face_json_path.exists());
|
||||
|
||||
if !face_json_path.exists() {
|
||||
face_json_path = output_dir.join(&uuid).join(format!("{}.face.json", uuid));
|
||||
eprintln!("[DEBUG] Fallback face_json_path: {:?}", face_json_path);
|
||||
eprintln!("[DEBUG] File exists (attempt 2): {}", face_json_path.exists());
|
||||
}
|
||||
|
||||
if !face_json_path.exists() {
|
||||
eprintln!("Face JSON not found.");
|
||||
write_empty_output("no_face_json", &uuid, &args.output_path);
|
||||
return;
|
||||
}
|
||||
|
||||
let face_json_content = std::fs::read_to_string(&face_json_path).expect("Failed to read face.json");
|
||||
eprintln!("[DEBUG] Face JSON content length: {} bytes", face_json_content.len());
|
||||
|
||||
let face_data: Value = serde_json::from_str(&face_json_content).expect("Failed to parse face.json");
|
||||
eprintln!("[DEBUG] Face data top-level keys: {:?}", face_data.as_object().map(|o| o.keys().collect::<Vec<_>>()));
|
||||
|
||||
let frames_list = face_data.get("frames").and_then(|f| f.as_array()).cloned().unwrap_or_default();
|
||||
eprintln!("[DEBUG] Frames list length: {}", frames_list.len());
|
||||
|
||||
if frames_list.is_empty() {
|
||||
eprintln!("No frames in JSON (no faces).");
|
||||
write_empty_output("no_faces", &uuid, &args.output_path);
|
||||
return;
|
||||
}
|
||||
|
||||
let fps_value = face_data
|
||||
.get("fps")
|
||||
.and_then(|f| f.as_f64())
|
||||
.unwrap_or(23.98);
|
||||
|
||||
let points = load_qdrant_faces(&uuid);
|
||||
if points.is_empty() {
|
||||
eprintln!("No embeddings found in Qdrant.");
|
||||
write_empty_output("no_embeddings", &uuid, &args.output_path);
|
||||
return;
|
||||
}
|
||||
|
||||
let threshold = args.threshold;
|
||||
let trace_embeddings = cluster_by_trace(&points, 1, CONFIDENCE_THRESHOLD);
|
||||
if trace_embeddings.is_empty() {
|
||||
eprintln!("No valid traces found.");
|
||||
write_empty_output("no_embeddings", &uuid, &args.output_path);
|
||||
return;
|
||||
}
|
||||
|
||||
let (initial_trace_to_person, trace_similarities) = if args.method == "agglomerative" {
|
||||
agglomerative_cluster(&trace_embeddings, threshold)
|
||||
} else {
|
||||
seed_leader_cluster(&trace_embeddings, threshold)
|
||||
};
|
||||
|
||||
// Stage 2: Merge over-split clusters (optional)
|
||||
let trace_to_person = if args.stage2 {
|
||||
eprintln!("[STAGE2] Applying Stage 2 merge with threshold={}", args.merge_threshold);
|
||||
stage2_merge_clusters(&trace_embeddings, &initial_trace_to_person, args.merge_threshold)
|
||||
} else {
|
||||
initial_trace_to_person
|
||||
};
|
||||
|
||||
if trace_to_person.is_empty() {
|
||||
eprintln!("Clustering produced no results.");
|
||||
write_empty_output("no_embeddings", &uuid, &args.output_path);
|
||||
return;
|
||||
}
|
||||
|
||||
let n_persons: usize = trace_to_person.values().collect::<std::collections::HashSet<_>>().len();
|
||||
eprintln!("Clustering result: {} persons ({} traces)", n_persons, trace_to_person.len());
|
||||
|
||||
// Load face_traced.json to get trace_id for each face.
|
||||
let traced_path = output_dir.join(format!("{}.face_traced.json", uuid));
|
||||
let mut traced_frames: Value = Value::Object(Default::default());
|
||||
if traced_path.exists() {
|
||||
if let Ok(s) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(v) = serde_json::from_str::<Value>(&s) {
|
||||
let frames_raw = v.get("frames").cloned().unwrap_or_else(|| Value::Object(Default::default()));
|
||||
// Handle both array and object formats
|
||||
if let Some(frames_array) = frames_raw.as_array() {
|
||||
// Convert array to object for compatibility
|
||||
for frame_obj in frames_array {
|
||||
if let Some(frame_num) = frame_obj.get("frame").and_then(|f| f.as_u64()) {
|
||||
if let Some(obj) = traced_frames.as_object_mut() {
|
||||
obj.insert(frame_num.to_string(), frame_obj.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(" Loaded face_traced.json: {} frames (converted from array)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0));
|
||||
} else if frames_raw.is_object() {
|
||||
traced_frames = frames_raw;
|
||||
eprintln!(" Loaded face_traced.json: {} frames (dict)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0));
|
||||
} else {
|
||||
eprintln!(" Warning: Unexpected frames format: {:?}", frames_raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut matched_count = 0_i64;
|
||||
let mut frames_list = frames_list;
|
||||
for (frame_idx, frame_obj) in frames_list.iter_mut().enumerate() {
|
||||
let frame_num = frame_obj
|
||||
.get("frame")
|
||||
.and_then(|f| f.as_i64())
|
||||
.unwrap_or(frame_idx as i64);
|
||||
let traced_frame = traced_frames
|
||||
.get(frame_num.to_string().as_str())
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({}));
|
||||
let traced_faces = traced_frame
|
||||
.get("faces")
|
||||
.and_then(|f| f.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(faces) = frame_obj.get_mut("faces").and_then(|f| f.as_array_mut()) {
|
||||
for (face_idx, face) in faces.iter_mut().enumerate() {
|
||||
let trace_id = traced_faces
|
||||
.get(face_idx)
|
||||
.and_then(|f| f.get("trace_id"))
|
||||
.and_then(|t| t.as_i64());
|
||||
if let Some(trace_id) = trace_id {
|
||||
if let Some(person_label) = trace_to_person.get(&trace_id) {
|
||||
face["person_id"] = json!(format!("Person_{}", person_label));
|
||||
face["trace_id"] = json!(trace_id);
|
||||
matched_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(" Assigned person_id to {} faces", matched_count);
|
||||
|
||||
if matched_count == 0 {
|
||||
eprintln!("No faces matched to any trace - check Qdrant data integrity");
|
||||
write_empty_output("no_faces", &uuid, &args.output_path);
|
||||
return;
|
||||
}
|
||||
|
||||
// Person face counts + best face (representative).
|
||||
let mut person_face_count: BTreeMap<String, u64> = BTreeMap::new();
|
||||
let mut person_best_face: BTreeMap<String, Value> = BTreeMap::new();
|
||||
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
|
||||
let frame_num = frame_obj.get("frame")
|
||||
.and_then(|f| f.as_u64())
|
||||
.unwrap_or(frame_idx as u64);
|
||||
let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default();
|
||||
for (face_idx, face) in faces.iter().enumerate() {
|
||||
let person_id = face.get("person_id").and_then(|p| p.as_str());
|
||||
if let Some(person_id) = person_id {
|
||||
*person_face_count.entry(person_id.to_string()).or_insert(0) += 1;
|
||||
let confidence = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.9);
|
||||
let entry = person_best_face
|
||||
.entry(person_id.to_string())
|
||||
.or_insert_with(|| {
|
||||
json!({
|
||||
"confidence": f64::NEG_INFINITY,
|
||||
})
|
||||
});
|
||||
if confidence > entry.get("confidence").and_then(|c| c.as_f64()).unwrap_or(f64::NEG_INFINITY) {
|
||||
*entry = json!({
|
||||
"face_id": format!("face_{}_{}", frame_num, face_idx),
|
||||
"confidence": confidence,
|
||||
"frame": frame_num,
|
||||
"bbox": {
|
||||
"x": face.get("x").cloned().unwrap_or(Value::Null),
|
||||
"y": face.get("y").cloned().unwrap_or(Value::Null),
|
||||
"width": face.get("width").cloned().unwrap_or(Value::Null),
|
||||
"height": face.get("height").cloned().unwrap_or(Value::Null),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build per-person similarity stats from trace_similarities.
|
||||
let mut person_sims: BTreeMap<i64, Vec<f64>> = BTreeMap::new();
|
||||
let sim_threshold_value = 1.0 - threshold;
|
||||
for (tid, person_label) in trace_to_person.iter() {
|
||||
let sim = trace_similarities.get(tid).copied().unwrap_or(0.0);
|
||||
person_sims.entry(*person_label).or_default().push(sim);
|
||||
}
|
||||
|
||||
let mut sorted_persons: Vec<(&String, &u64)> = person_face_count.iter().collect();
|
||||
sorted_persons.sort_by(|a, b| b.1.cmp(a.1));
|
||||
|
||||
let mut clusters: Vec<Value> = Vec::new();
|
||||
for (person_id, count) in sorted_persons {
|
||||
let person_label: Option<i64> = person_id
|
||||
.split('_')
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse::<i64>().ok());
|
||||
|
||||
let mut similarity_info: Option<Value> = None;
|
||||
if let Some(label) = person_label {
|
||||
if let Some(sims) = person_sims.get(&label) {
|
||||
if !sims.is_empty() {
|
||||
let min_s = sims.iter().cloned().fold(f64::INFINITY, f64::min);
|
||||
let avg_s = sims.iter().sum::<f64>() / sims.len() as f64;
|
||||
similarity_info = Some(json!({
|
||||
"min": round_digits(min_s, 4),
|
||||
"avg": round_digits(avg_s, 4),
|
||||
"threshold": round_digits(sim_threshold_value, 4),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut cluster_entry = json!({
|
||||
"cluster_id": person_id,
|
||||
"face_count": count,
|
||||
});
|
||||
if let Some(rep) = person_best_face.get(person_id) {
|
||||
cluster_entry["representative_face"] = rep.clone();
|
||||
}
|
||||
if let Some(sim) = similarity_info {
|
||||
cluster_entry["similarity"] = sim;
|
||||
}
|
||||
clusters.push(cluster_entry);
|
||||
}
|
||||
|
||||
// Build output frames.
|
||||
let mut output_frames: Vec<Value> = Vec::new();
|
||||
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
|
||||
let frame_num = frame_obj.get("frame")
|
||||
.and_then(|f| f.as_u64())
|
||||
.unwrap_or(frame_idx as u64);
|
||||
let timestamp = frame_obj.get("timestamp").cloned().unwrap_or_else(|| {
|
||||
if fps_value > 0.0 {
|
||||
json!(frame_num as f64 / fps_value)
|
||||
} else {
|
||||
json!(0)
|
||||
}
|
||||
});
|
||||
let mut output_faces: Vec<Value> = Vec::new();
|
||||
let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default();
|
||||
for (face_idx, face) in faces.iter().enumerate() {
|
||||
let person_id = face.get("person_id").and_then(|p| p.as_str());
|
||||
if let Some(person_id) = person_id {
|
||||
output_faces.push(json!({
|
||||
"face_id": format!("face_{}_{}", frame_num, face_idx),
|
||||
"cluster_id": person_id,
|
||||
"trace_id": face.get("trace_id").cloned().unwrap_or(Value::Null),
|
||||
"confidence": face.get("confidence").cloned().unwrap_or(json!(0.9)),
|
||||
}));
|
||||
}
|
||||
}
|
||||
if !output_faces.is_empty() {
|
||||
output_frames.push(json!({
|
||||
"frame": frame_num,
|
||||
"timestamp": timestamp,
|
||||
"faces": output_faces,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// Filter low-quality clusters (hand detections, isolated faces)
|
||||
// Filter criteria:
|
||||
// - face_count < 5 (too few faces, likely isolated or hand)
|
||||
// - bbox_area > 200,000 (abnormally large bbox, likely hand/object)
|
||||
let min_face_count = 3;
|
||||
let max_bbox_area = 200_000.0;
|
||||
|
||||
let mut filtered_cluster_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
let mut filtered_clusters: Vec<Value> = Vec::new();
|
||||
|
||||
for cluster in &clusters {
|
||||
let cluster_id = cluster.get("cluster_id").and_then(|c| c.as_str()).unwrap_or("");
|
||||
let face_count = cluster.get("face_count").and_then(|c| c.as_i64()).unwrap_or(0);
|
||||
|
||||
// Calculate bbox area from representative_face
|
||||
let bbox_area: f64 = cluster.get("representative_face")
|
||||
.and_then(|rf| rf.get("bbox"))
|
||||
.map(|bbox| {
|
||||
let w = bbox.get("width").and_then(|w| w.as_f64()).unwrap_or(0.0);
|
||||
let h = bbox.get("height").and_then(|h| h.as_f64()).unwrap_or(0.0);
|
||||
w * h
|
||||
})
|
||||
.unwrap_or(0.0);
|
||||
|
||||
// Filter logic
|
||||
if face_count < min_face_count || bbox_area > max_bbox_area {
|
||||
eprintln!("[CLUSTER] Filtered out {}: face_count={}, bbox_area={}",
|
||||
cluster_id, face_count, bbox_area);
|
||||
filtered_cluster_ids.insert(cluster_id.to_string());
|
||||
} else {
|
||||
filtered_clusters.push(cluster.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// Remove filtered clusters from output_frames
|
||||
let filtered_frames: Vec<Value> = output_frames.iter().map(|frame| {
|
||||
let faces = frame.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default();
|
||||
let filtered_faces: Vec<Value> = faces.iter()
|
||||
.filter(|face| {
|
||||
let cluster_id = face.get("cluster_id").and_then(|c| c.as_str()).unwrap_or("");
|
||||
!filtered_cluster_ids.contains(cluster_id)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if filtered_faces.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
json!({
|
||||
"frame": frame.get("frame").cloned().unwrap_or(Value::Null),
|
||||
"timestamp": frame.get("timestamp").cloned().unwrap_or(Value::Null),
|
||||
"faces": filtered_faces,
|
||||
})
|
||||
}
|
||||
}).filter(|f| !f.is_null()).collect();
|
||||
|
||||
eprintln!("[CLUSTER] Filtered {} low-quality clusters ({} total)",
|
||||
filtered_cluster_ids.len(), clusters.len());
|
||||
eprintln!("[CLUSTER] Remaining: {} clusters", filtered_clusters.len());
|
||||
|
||||
let mut output_data = json!({
|
||||
"status": "has_faces",
|
||||
"file_uuid": uuid,
|
||||
"clusters": filtered_clusters,
|
||||
"frames": filtered_frames,
|
||||
});
|
||||
|
||||
// Auto-bind speakers from asrx.json.
|
||||
let asrx_path = output_dir.join(format!("{}.asrx.json", uuid));
|
||||
let speaker_mapping = auto_bind_speakers(&output_frames, &asrx_path);
|
||||
if !speaker_mapping.is_null() {
|
||||
output_data["speaker_person_mapping"] = speaker_mapping;
|
||||
}
|
||||
|
||||
let rounded = round_json(output_data);
|
||||
let text = serde_json::to_string_pretty(&rounded).map_err(|e| e.to_string());
|
||||
match text {
|
||||
Ok(t) => {
|
||||
std::fs::write(&args.output_path, t).expect("Failed to write output");
|
||||
eprintln!("Saved clustered data to {}", args.output_path.display());
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Failed to serialize output: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute speaker -> Person_N mapping by vote (Python auto_bind_speakers).
|
||||
fn auto_bind_speakers(output_frames: &[Value], asrx_path: &std::path::Path) -> Value {
|
||||
if !asrx_path.exists() {
|
||||
eprintln!("Missing data for speaker binding.");
|
||||
return Value::Null;
|
||||
}
|
||||
|
||||
let asrx_data: Value = match std::fs::read_to_string(asrx_path) {
|
||||
Ok(s) => match serde_json::from_str(&s) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!(" Failed to load ASRX: {}", e);
|
||||
return Value::Null;
|
||||
}
|
||||
},
|
||||
Err(_) => return Value::Null,
|
||||
};
|
||||
|
||||
eprintln!("Auto-binding Speakers to Persons...");
|
||||
|
||||
let mut face_spans: Vec<(f64, String)> = Vec::new();
|
||||
for frame_obj in output_frames {
|
||||
if let Some(ts) = frame_obj.get("timestamp").and_then(|t| t.as_f64()) {
|
||||
if let Some(faces) = frame_obj.get("faces").and_then(|f| f.as_array()) {
|
||||
for face in faces {
|
||||
if let Some(person_id) = face.get("cluster_id").and_then(|p| p.as_str()) {
|
||||
face_spans.push((ts, person_id.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut speaker_person_counts: BTreeMap<String, BTreeMap<String, i64>> = BTreeMap::new();
|
||||
let segments = asrx_data.get("segments").and_then(|s| s.as_array()).cloned().unwrap_or_default();
|
||||
for seg in &segments {
|
||||
let start = seg.get("start_time").or_else(|| seg.get("start")).and_then(|x| x.as_f64());
|
||||
let end = seg.get("end_time").or_else(|| seg.get("end")).and_then(|x| x.as_f64());
|
||||
let speaker = seg.get("speaker_id").and_then(|x| x.as_str());
|
||||
if speaker.is_none() || start.is_none() || end.is_none() {
|
||||
continue;
|
||||
}
|
||||
let speaker = speaker.unwrap();
|
||||
let start = start.unwrap();
|
||||
let end = end.unwrap();
|
||||
let candidates: Vec<&(f64, String)> = face_spans
|
||||
.iter()
|
||||
.filter(|(ts, _)| start <= *ts && *ts <= end)
|
||||
.collect();
|
||||
if !candidates.is_empty() {
|
||||
let mut person_counts: BTreeMap<String, i64> = BTreeMap::new();
|
||||
for (_, pid) in candidates.iter() {
|
||||
*person_counts.entry(pid.clone()).or_insert(0) += 1;
|
||||
}
|
||||
let best_person = person_counts
|
||||
.iter()
|
||||
.max_by(|a, b| a.1.cmp(b.1))
|
||||
.map(|(p, _)| p.clone());
|
||||
if let Some(best) = best_person {
|
||||
let entry = speaker_person_counts.entry(speaker.to_string()).or_default();
|
||||
*entry.entry(best).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut mapping: BTreeMap<String, String> = BTreeMap::new();
|
||||
for (speaker, persons) in speaker_person_counts.iter() {
|
||||
if persons.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let best_person = persons.iter().max_by(|a, b| a.1.cmp(b.1)).map(|(p, _)| p);
|
||||
if let Some(best) = best_person {
|
||||
mapping.insert(speaker.clone(), best.clone());
|
||||
eprintln!(" {} is likely {} ({} votes)", speaker, best, persons[best]);
|
||||
}
|
||||
}
|
||||
|
||||
if mapping.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
serde_json::to_value(mapping).unwrap_or(Value::Null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Instant;
|
||||
|
||||
mod face_processor;
|
||||
|
||||
use face_processor::{
|
||||
FaceOutput, FrameData, FaceInfo, Metadata, PoseAngle,
|
||||
VideoReader, FaceDetector, FaceCropper, EmbeddingExtractor,
|
||||
QdrantFaceStore, FaceEmbedPayload,
|
||||
};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "rust_face_processor")]
|
||||
#[command(about = "Face detection and embedding extraction using Rust")]
|
||||
struct Args {
|
||||
/// Path to video file
|
||||
#[arg(short, long)]
|
||||
video: PathBuf,
|
||||
|
||||
/// Path to output JSON file
|
||||
#[arg(short, long)]
|
||||
output: PathBuf,
|
||||
|
||||
/// Video file UUID
|
||||
#[arg(short, long)]
|
||||
uuid: String,
|
||||
|
||||
/// Sample interval (frames)
|
||||
#[arg(long, default_value = "3")]
|
||||
sample_interval: usize,
|
||||
|
||||
/// Path to ONNX model
|
||||
#[arg(long, default_value = "models/facenet_vggface2.onnx")]
|
||||
model: PathBuf,
|
||||
}
|
||||
|
||||
fn classify_pose(roll: f64, yaw: f64) -> String {
|
||||
let abs_yaw = yaw.abs();
|
||||
let abs_roll = roll.abs();
|
||||
|
||||
if abs_yaw < 15.0 && abs_roll < 15.0 {
|
||||
"frontal".to_string()
|
||||
} else if abs_yaw > 30.0 {
|
||||
if yaw > 0.0 {
|
||||
"profile_right".to_string()
|
||||
} else {
|
||||
"profile_left".to_string()
|
||||
}
|
||||
} else {
|
||||
"three_quarter".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
let start_time = Instant::now();
|
||||
|
||||
println!("[FACE_RUST] Starting face processor");
|
||||
println!("[FACE_RUST] Video: {:?}", args.video);
|
||||
println!("[FACE_RUST] Output: {:?}", args.output);
|
||||
println!("[FACE_RUST] UUID: {}", args.uuid);
|
||||
|
||||
// Initialize modules
|
||||
let mut video_reader = VideoReader::new(&args.video)
|
||||
.context("Failed to initialize video reader")?;
|
||||
|
||||
println!("[FACE_RUST] Video: {}x{}, {:.1} fps, {} frames",
|
||||
video_reader.width(),
|
||||
video_reader.height(),
|
||||
video_reader.fps(),
|
||||
video_reader.frame_count()
|
||||
);
|
||||
|
||||
let detector = FaceDetector::new()
|
||||
.context("Failed to initialize face detector")?;
|
||||
|
||||
let cropper = FaceCropper::new();
|
||||
|
||||
let mut embedder = EmbeddingExtractor::new(&args.model)
|
||||
.context("Failed to initialize embedding extractor")?;
|
||||
|
||||
// Initialize Qdrant
|
||||
let qdrant = QdrantFaceStore::new()
|
||||
.await
|
||||
.context("Failed to initialize Qdrant store")?;
|
||||
|
||||
// Run face detection
|
||||
let detection_output = args.output.with_extension("detect.json");
|
||||
let detections = detector.detect(&args.video, &detection_output, args.sample_interval)?;
|
||||
|
||||
// Process each detection
|
||||
let mut frames: Vec<FrameData> = Vec::new();
|
||||
let mut embeddings_data: Vec<FaceEmbedPayload> = Vec::new();
|
||||
let mut total_embeddings = 0;
|
||||
let mut total_faces = 0;
|
||||
|
||||
println!("[FACE_RUST] Processing {} faces...", detections.len());
|
||||
|
||||
for detection in detections {
|
||||
// Read frame
|
||||
let frame = match video_reader.read_frame(detection.frame)? {
|
||||
Some(f) => f,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
// Crop face
|
||||
let face_img = cropper.crop(&frame, &detection.bbox)?;
|
||||
|
||||
// Extract embedding
|
||||
let embedding = embedder.extract(&face_img)?;
|
||||
total_embeddings += 1;
|
||||
|
||||
// Store embedding data for Qdrant
|
||||
embeddings_data.push(FaceEmbedPayload {
|
||||
frame: detection.frame,
|
||||
trace_id: 0, // Will be updated by face tracker
|
||||
bbox: detection.bbox.clone(),
|
||||
confidence: detection.confidence,
|
||||
capture_quality: detection.capture_quality.map(|q| q as f64),
|
||||
embedding,
|
||||
});
|
||||
|
||||
// Classify pose
|
||||
let pose_angle = detection.pose.as_ref().map(|p| {
|
||||
PoseAngle {
|
||||
angle: classify_pose(p.roll, p.yaw),
|
||||
roll: p.roll,
|
||||
yaw: p.yaw,
|
||||
pitch: p.pitch,
|
||||
}
|
||||
});
|
||||
|
||||
// Create face info (without embedding)
|
||||
let face_info = FaceInfo {
|
||||
x: detection.bbox.x,
|
||||
y: detection.bbox.y,
|
||||
width: detection.bbox.width,
|
||||
height: detection.bbox.height,
|
||||
confidence: detection.confidence,
|
||||
pose_angle,
|
||||
capture_quality: detection.capture_quality,
|
||||
};
|
||||
|
||||
// Add to frame
|
||||
frames.push(FrameData {
|
||||
frame: detection.frame,
|
||||
timestamp: detection.timestamp,
|
||||
faces: vec![face_info],
|
||||
});
|
||||
|
||||
total_faces += 1;
|
||||
|
||||
if total_faces % 100 == 0 {
|
||||
println!("[FACE_RUST] Processed {} faces", total_faces);
|
||||
}
|
||||
}
|
||||
|
||||
// Push embeddings to Qdrant
|
||||
if !embeddings_data.is_empty() {
|
||||
println!("[QDRANT] Pushing {} embeddings...", embeddings_data.len());
|
||||
let pushed = qdrant.push_embeddings_batch(&args.uuid, embeddings_data)
|
||||
.await
|
||||
.context("Failed to push embeddings to Qdrant")?;
|
||||
println!("[QDRANT] Pushed {} embeddings to _faces collection", pushed);
|
||||
}
|
||||
|
||||
// Create output
|
||||
let output = FaceOutput {
|
||||
status: if total_faces > 0 { "has_faces" } else { "no_faces" }.to_string(),
|
||||
frame_count: frames.len(),
|
||||
fps: video_reader.fps(),
|
||||
frames,
|
||||
total_faces,
|
||||
metadata: Metadata {
|
||||
embedding_method: "rust_facenet".to_string(),
|
||||
embedding_model: "InceptionResnetV1_VGGFace2".to_string(),
|
||||
total_embeddings,
|
||||
},
|
||||
};
|
||||
|
||||
// Write output
|
||||
let json = serde_json::to_string_pretty(&output)?;
|
||||
std::fs::write(&args.output, json)?;
|
||||
|
||||
let elapsed = start_time.elapsed();
|
||||
|
||||
println!("[FACE_RUST] Done: {} frames, {} faces, {} embeddings, {:.1}s",
|
||||
output.frame_count,
|
||||
output.total_faces,
|
||||
output.metadata.total_embeddings,
|
||||
elapsed.as_secs_f64()
|
||||
);
|
||||
|
||||
println!("[FACE_RUST] Output written to {:?}", args.output);
|
||||
|
||||
// Clean up detection output
|
||||
if detection_output.exists() {
|
||||
std::fs::remove_file(&detection_output)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use image::DynamicImage;
|
||||
use ndarray::IxDyn;
|
||||
use ort::session::Session;
|
||||
use ort::value::Value;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "rust_facenet")]
|
||||
#[command(about = "Extract face embeddings using ONNX Runtime")]
|
||||
struct Args {
|
||||
/// Path to face image
|
||||
#[arg(short, long)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to ONNX model
|
||||
#[arg(short, long, default_value = "models/facenet_vggface2.onnx")]
|
||||
model: PathBuf,
|
||||
}
|
||||
|
||||
struct FaceNetModel {
|
||||
session: Session,
|
||||
}
|
||||
|
||||
impl FaceNetModel {
|
||||
fn new(model_path: &PathBuf) -> Result<Self> {
|
||||
println!("[FACENET] Loading model: {:?}", model_path);
|
||||
|
||||
let session = Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?;
|
||||
|
||||
println!("[FACENET] Model loaded successfully");
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
fn preprocess(&self, img: &DynamicImage) -> Result<ndarray::Array<f32, IxDyn>> {
|
||||
let resized = img.resize_exact(160, 160, image::imageops::FilterType::Lanczos3);
|
||||
|
||||
let mut input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, 3, 160, 160]),
|
||||
vec![0.0f32; 1 * 3 * 160 * 160]
|
||||
).context("Failed to create input array")?;
|
||||
|
||||
for (x, y, pixel) in resized.to_rgb8().enumerate_pixels() {
|
||||
let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32);
|
||||
input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0;
|
||||
input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0;
|
||||
input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0;
|
||||
}
|
||||
|
||||
Ok(input_array)
|
||||
}
|
||||
|
||||
fn extract_embedding(&mut self, img: &DynamicImage) -> Result<Vec<f32>> {
|
||||
let input_array = self.preprocess(img)?;
|
||||
let input_value = Value::from_array(input_array)
|
||||
.context("Failed to create input value")?;
|
||||
|
||||
let inputs = ort::inputs!["input" => input_value];
|
||||
|
||||
let outputs = self.session.run(inputs)
|
||||
.context("Failed to run inference")?;
|
||||
|
||||
let output = outputs["output"].try_extract_tensor::<f32>()
|
||||
.context("Failed to extract output tensor")?;
|
||||
|
||||
let output_data = output.1;
|
||||
let embedding = output_data.to_vec();
|
||||
|
||||
Ok(embedding)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
let mut model = FaceNetModel::new(&args.model)?;
|
||||
let img = image::open(&args.input)
|
||||
.context(format!("Failed to load image: {:?}", args.input))?;
|
||||
|
||||
println!("[FACENET] Processing image: {:?}", args.input);
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let embedding = model.extract_embedding(&img)?;
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
println!("[FACENET] Extraction time: {:?}", elapsed);
|
||||
println!("[FACENET] Embedding length: {}", embedding.len());
|
||||
|
||||
let output = json!({
|
||||
"embedding": embedding,
|
||||
"count": embedding.len(),
|
||||
"time_ms": elapsed.as_millis()
|
||||
});
|
||||
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use image::DynamicImage;
|
||||
use ndarray::IxDyn;
|
||||
use ort::session::Session;
|
||||
use ort::value::Value;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "rust_facenet_coreml")]
|
||||
#[command(about = "Extract face embeddings using ONNX Runtime with CoreML acceleration")]
|
||||
struct Args {
|
||||
/// Path to face image
|
||||
#[arg(short, long)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to ONNX model
|
||||
#[arg(short, long, default_value = "models/facenet_vggface2.onnx")]
|
||||
model: PathBuf,
|
||||
|
||||
/// Use CoreML acceleration (flag, no value needed)
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
coreml: bool,
|
||||
}
|
||||
|
||||
struct FaceNetModel {
|
||||
session: Session,
|
||||
}
|
||||
|
||||
impl FaceNetModel {
|
||||
fn new(model_path: &PathBuf, use_coreml: bool) -> Result<Self> {
|
||||
println!("[FACENET] Loading model: {:?}", model_path);
|
||||
println!("[FACENET] CoreML acceleration: {}", use_coreml);
|
||||
|
||||
let session = if use_coreml {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
println!("[FACENET] Using CoreML feature (but ort API is unclear)");
|
||||
|
||||
let mut builder = Session::builder()
|
||||
.context("Failed to create session builder")?;
|
||||
|
||||
builder.commit_from_file(model_path)
|
||||
.context("Failed to load model")?
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
println!("[FACENET] CoreML only available on macOS, using CPU");
|
||||
Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?
|
||||
}
|
||||
} else {
|
||||
println!("[FACENET] Using CPU");
|
||||
Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?
|
||||
};
|
||||
|
||||
println!("[FACENET] Model loaded successfully");
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
fn preprocess(&self, img: &DynamicImage) -> Result<ndarray::Array<f32, IxDyn>> {
|
||||
let resized = img.resize_exact(160, 160, image::imageops::FilterType::Lanczos3);
|
||||
|
||||
let mut input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, 3, 160, 160]),
|
||||
vec![0.0f32; 1 * 3 * 160 * 160]
|
||||
).context("Failed to create input array")?;
|
||||
|
||||
for (x, y, pixel) in resized.to_rgb8().enumerate_pixels() {
|
||||
let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32);
|
||||
input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0;
|
||||
input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0;
|
||||
input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0;
|
||||
}
|
||||
|
||||
Ok(input_array)
|
||||
}
|
||||
|
||||
fn extract_embedding(&mut self, img: &DynamicImage) -> Result<Vec<f32>> {
|
||||
let input_array = self.preprocess(img)?;
|
||||
let input_value = Value::from_array(input_array)
|
||||
.context("Failed to create input value")?;
|
||||
|
||||
let inputs = ort::inputs!["input" => input_value];
|
||||
|
||||
let outputs = self.session.run(inputs)
|
||||
.context("Failed to run inference")?;
|
||||
|
||||
let output = outputs["output"].try_extract_tensor::<f32>()
|
||||
.context("Failed to extract output tensor")?;
|
||||
|
||||
let output_data = output.1;
|
||||
let embedding = output_data.to_vec();
|
||||
|
||||
Ok(embedding)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
let mut model = FaceNetModel::new(&args.model, args.coreml)?;
|
||||
let img = image::open(&args.input)
|
||||
.context(format!("Failed to load image: {:?}", args.input))?;
|
||||
|
||||
println!("[FACENET] Processing image: {:?}", args.input);
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let embedding = model.extract_embedding(&img)?;
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
println!("[FACENET] Extraction time: {:?}", elapsed);
|
||||
println!("[FACENET] Embedding length: {}", embedding.len());
|
||||
|
||||
let output = json!({
|
||||
"embedding": embedding,
|
||||
"count": embedding.len(),
|
||||
"time_ms": elapsed.as_millis(),
|
||||
"coreml": args.coreml
|
||||
});
|
||||
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::process::Command;
|
||||
|
||||
use clap::Parser;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_pose", about = "Pose Processor (Rust port of pose_processor.py interpolation)")]
|
||||
struct Args {
|
||||
video_path: std::path::PathBuf,
|
||||
/// Existing pose.json produced by swift_face_pose (source of detected frames).
|
||||
source_pose: std::path::PathBuf,
|
||||
output_path: std::path::PathBuf,
|
||||
#[arg(short = 'u', long = "uuid", default_value = "")]
|
||||
uuid: String,
|
||||
/// Comma-separated 8Hz target frames. When provided, detection is skipped and
|
||||
/// the source is copied through unchanged (matches Python's 8Hz short-circuit).
|
||||
#[arg(long = "frames", default_value = None)]
|
||||
frames: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct PoseResult {
|
||||
frame_count: u64,
|
||||
fps: f64,
|
||||
#[serde(default)]
|
||||
frames: Vec<PoseFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct PoseFrame {
|
||||
frame: i64,
|
||||
#[serde(default)]
|
||||
timestamp: f64,
|
||||
#[serde(default)]
|
||||
persons: Vec<PersonPose>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct PersonPose {
|
||||
#[serde(default)]
|
||||
keypoints: Vec<Keypoint>,
|
||||
#[serde(default)]
|
||||
bbox: Option<BBoxInt>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct Keypoint {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
x: f64,
|
||||
#[serde(default)]
|
||||
y: f64,
|
||||
#[serde(default)]
|
||||
confidence: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
|
||||
struct BBoxInt {
|
||||
x: i64,
|
||||
y: i64,
|
||||
width: i64,
|
||||
height: i64,
|
||||
}
|
||||
|
||||
/// Mimic Python's `round(x, 2)` (banker's rounding / round-half-to-even).
|
||||
fn round2(x: f64) -> f64 {
|
||||
(x * 100.0).round_ties_even() / 100.0
|
||||
}
|
||||
|
||||
/// Recursively round all float values to 2 decimals (Python `round_json_numbers`).
|
||||
/// Integers pass through unchanged, matching Python's `round_json_numbers`.
|
||||
fn round_json(value: Value) -> Value {
|
||||
match value {
|
||||
Value::Number(n) => {
|
||||
if n.is_f64() {
|
||||
let f = n.as_f64().unwrap_or(0.0);
|
||||
let r = round2(f);
|
||||
serde_json::Number::from_f64(r).map(Value::Number).unwrap_or(Value::Number(n))
|
||||
} else {
|
||||
Value::Number(n)
|
||||
}
|
||||
}
|
||||
Value::Array(items) => Value::Array(items.into_iter().map(round_json).collect()),
|
||||
Value::Object(map) => {
|
||||
Value::Object(map.into_iter().map(|(k, v)| (k, round_json(v))).collect())
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get total video frame count via ffprobe (nb_frames, falling back to duration*fps).
|
||||
fn total_video_frames(video_path: &std::path::Path) -> u64 {
|
||||
let nb_str = Command::new("ffprobe")
|
||||
.args([
|
||||
"-v", "error", "-select_streams", "v:0",
|
||||
"-show_entries", "stream=nb_frames", "-of", "csv=p=0",
|
||||
])
|
||||
.arg(video_path)
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().trim_end_matches(',').to_string());
|
||||
|
||||
if let Some(s) = nb_str {
|
||||
if s != "N/A" {
|
||||
if let Ok(n) = s.parse::<u64>() {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
// Fallback: duration * fps
|
||||
let dur = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0"])
|
||||
.arg(video_path)
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().parse::<f64>().unwrap_or(0.0))
|
||||
.unwrap_or(0.0);
|
||||
let fps_str = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=r_frame_rate", "-of", "csv=p=0"])
|
||||
.arg(video_path)
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().trim_end_matches(',').to_string());
|
||||
let fps = fps_str
|
||||
.map(|s| {
|
||||
if let Some((n, d)) = s.split_once('/') {
|
||||
let n: f64 = n.trim().parse().unwrap_or(30.0);
|
||||
let d: f64 = d.trim().trim_end_matches(',').parse().unwrap_or(1.0);
|
||||
if d > 0.0 {
|
||||
n / d
|
||||
} else {
|
||||
30.0
|
||||
}
|
||||
} else {
|
||||
s.parse().unwrap_or(30.0)
|
||||
}
|
||||
})
|
||||
.unwrap_or(30.0);
|
||||
(dur * fps) as u64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn interpolate_pose(source: &PoseResult, video_path: &std::path::Path) -> PoseResult {
|
||||
let total = total_video_frames(video_path);
|
||||
let fps = source.fps;
|
||||
eprintln!(
|
||||
"[POSE] interpolating {} detected frames -> {} total video frames (fps={})",
|
||||
source.frames.len(),
|
||||
total,
|
||||
fps
|
||||
);
|
||||
|
||||
if source.frames.is_empty() {
|
||||
return source.clone();
|
||||
}
|
||||
|
||||
// Collect frames per person index across all detected frames.
|
||||
let mut all_persons: BTreeMap<usize, Vec<(i64, PersonPose)>> = BTreeMap::new();
|
||||
for f in &source.frames {
|
||||
for (i, p) in f.persons.iter().enumerate() {
|
||||
all_persons.entry(i).or_default().push((f.frame, p.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
let mut interpolated_frames: Vec<PoseFrame> = Vec::new();
|
||||
|
||||
for frame_num in 0..total {
|
||||
let ts = frame_num as f64 / fps;
|
||||
let mut persons_in_frame: Vec<PersonPose> = Vec::new();
|
||||
|
||||
for (_person_id, person_frames) in &all_persons {
|
||||
let mut before: Option<(i64, &PersonPose)> = None;
|
||||
let mut after: Option<(i64, &PersonPose)> = None;
|
||||
for (fn_, p) in person_frames {
|
||||
if *fn_ <= frame_num as i64 {
|
||||
before = Some((*fn_, p));
|
||||
}
|
||||
if *fn_ >= frame_num as i64 && after.is_none() {
|
||||
after = Some((*fn_, p));
|
||||
}
|
||||
}
|
||||
|
||||
if before.is_none() && after.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (interp_kps, interp_bbox): (Vec<Keypoint>, Option<BBoxInt>) = if let (Some((t0, b)), Some((t1, a))) = (before, after) {
|
||||
if t0 != t1 {
|
||||
let t = (frame_num as i64 - t0) as f64 / (t1 - t0) as f64;
|
||||
let kp_before = &b.keypoints;
|
||||
let kp_after = &a.keypoints;
|
||||
let mut kps: Vec<Keypoint> = Vec::new();
|
||||
for i in 0..kp_before.len().max(kp_after.len()) {
|
||||
let kp0 = if i < kp_before.len() { &kp_before[i] } else { &kp_after[i] };
|
||||
let kp1 = if i < kp_after.len() { &kp_after[i] } else { &kp_before[i] };
|
||||
kps.push(Keypoint {
|
||||
name: kp0.name.clone(),
|
||||
x: kp0.x + t * (kp1.x - kp0.x),
|
||||
y: kp0.y + t * (kp1.y - kp0.y),
|
||||
confidence: kp0.confidence + t * (kp1.confidence - kp0.confidence),
|
||||
});
|
||||
}
|
||||
let bbox = match (&b.bbox, &a.bbox) {
|
||||
(Some(b0), Some(b1)) => Some(BBoxInt {
|
||||
x: (b0.x as f64 + t * (b1.x as f64 - b0.x as f64)) as i64,
|
||||
y: (b0.y as f64 + t * (b1.y as f64 - b0.y as f64)) as i64,
|
||||
width: (b0.width as f64 + t * (b1.width as f64 - b0.width as f64)) as i64,
|
||||
height: (b0.height as f64 + t * (b1.height as f64 - b0.height as f64)) as i64,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
(kps, bbox)
|
||||
} else {
|
||||
(b.keypoints.clone(), b.bbox.clone())
|
||||
}
|
||||
} else if let Some((_, b)) = before {
|
||||
(b.keypoints.clone(), b.bbox.clone())
|
||||
} else if let Some((_, a)) = after {
|
||||
(a.keypoints.clone(), a.bbox.clone())
|
||||
} else {
|
||||
(Vec::new(), None)
|
||||
};
|
||||
|
||||
let valid_bbox = interp_bbox
|
||||
.as_ref()
|
||||
.map(|b| b.width > 0 && b.height > 0)
|
||||
.unwrap_or(false);
|
||||
if valid_bbox {
|
||||
persons_in_frame.push(PersonPose {
|
||||
keypoints: interp_kps,
|
||||
bbox: interp_bbox,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if !persons_in_frame.is_empty() {
|
||||
interpolated_frames.push(PoseFrame {
|
||||
frame: frame_num as i64,
|
||||
timestamp: ts,
|
||||
persons: persons_in_frame,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("[POSE] interpolated -> {} frames", interpolated_frames.len());
|
||||
PoseResult {
|
||||
frame_count: interpolated_frames.len() as u64,
|
||||
fps,
|
||||
frames: interpolated_frames,
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
let source_str = std::fs::read_to_string(&args.source_pose).expect("failed to read source_pose");
|
||||
let source: PoseResult = serde_json::from_str(&source_str).expect("failed to parse source_pose");
|
||||
|
||||
let result: PoseResult = if args.frames.is_some() {
|
||||
eprintln!("[POSE] 8Hz mode: returning {} frames without interpolation", source.frames.len());
|
||||
source
|
||||
} else {
|
||||
interpolate_pose(&source, &args.video_path)
|
||||
};
|
||||
|
||||
let json = round_json(serde_json::to_value(&result).expect("serialize result"));
|
||||
std::fs::write(&args.output_path, serde_json::to_string(&json).unwrap()).expect("write output");
|
||||
eprintln!("[POSE] Done: {} frames -> {}", result.frame_count, args.output_path.display());
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_scene_vlm")]
|
||||
#[command(about = "Scene VLM analysis using LLM API")]
|
||||
struct Cli {
|
||||
/// File UUID
|
||||
#[arg(long)]
|
||||
file_uuid: String,
|
||||
|
||||
/// Output directory
|
||||
#[arg(long)]
|
||||
output_dir: Option<String>,
|
||||
|
||||
/// LLM API URL
|
||||
#[arg(long, default_value = "http://localhost:8080/v1/chat/completions")]
|
||||
llm_url: String,
|
||||
|
||||
/// Max tokens
|
||||
#[arg(long, default_value = "300")]
|
||||
max_tokens: u32,
|
||||
|
||||
/// Scene number (optional, process specific scene)
|
||||
#[arg(long)]
|
||||
scene_number: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct SceneAnalysis {
|
||||
scene_number: usize,
|
||||
vlm_description: String,
|
||||
vlm_location: Option<String>,
|
||||
vlm_activity: Option<String>,
|
||||
vlm_mood: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct SceneProfile {
|
||||
file_uuid: String,
|
||||
scenes: Vec<SceneAnalysis>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Cli::parse();
|
||||
|
||||
println!("[SCENE_VLM] Processing file: {}", args.file_uuid);
|
||||
|
||||
let output_dir = args.output_dir.unwrap_or_else(|| {
|
||||
std::env::var("MOMENTRY_OUTPUT_DIR")
|
||||
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string())
|
||||
});
|
||||
|
||||
let scenes = analyze_scenes(&args.file_uuid, &output_dir, &args.llm_url, args.max_tokens)?;
|
||||
|
||||
println!("[SCENE_VLM] Analyzed {} scenes", scenes.len());
|
||||
|
||||
let profile = SceneProfile {
|
||||
file_uuid: args.file_uuid.clone(),
|
||||
scenes,
|
||||
};
|
||||
|
||||
let output_path = format!("{}/{}_scene_profile.json", output_dir, args.file_uuid);
|
||||
let json = serde_json::to_string_pretty(&profile)?;
|
||||
std::fs::write(&output_path, json)?;
|
||||
|
||||
println!("[SCENE_VLM] Output: {}", output_path);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn analyze_scenes(
|
||||
file_uuid: &str,
|
||||
output_dir: &str,
|
||||
llm_url: &str,
|
||||
max_tokens: u32,
|
||||
) -> Result<Vec<SceneAnalysis>> {
|
||||
let mut scenes = Vec::new();
|
||||
|
||||
for entry in std::fs::read_dir(output_dir)? {
|
||||
let entry = entry?;
|
||||
let filename = entry.file_name().to_string_lossy().to_string();
|
||||
|
||||
if filename.starts_with(file_uuid) && filename.contains("_scene_") && filename.ends_with(".jpg") {
|
||||
if let Some(scene_num) = extract_scene_number(&filename) {
|
||||
println!("[SCENE_VLM] Processing scene {}", scene_num);
|
||||
|
||||
let image_path = entry.path();
|
||||
match analyze_scene_image(&image_path, scene_num, llm_url, max_tokens) {
|
||||
Ok(analysis) => scenes.push(analysis),
|
||||
Err(e) => println!("[SCENE_VLM] Failed to analyze scene {}: {}", scene_num, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scenes.sort_by_key(|s| s.scene_number);
|
||||
Ok(scenes)
|
||||
}
|
||||
|
||||
fn extract_scene_number(filename: &str) -> Option<usize> {
|
||||
let parts: Vec<&str> = filename.split("_scene_").collect();
|
||||
if parts.len() == 2 {
|
||||
parts[1].trim_end_matches(".jpg").parse().ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn analyze_scene_image(
|
||||
image_path: &PathBuf,
|
||||
scene_number: usize,
|
||||
llm_url: &str,
|
||||
max_tokens: u32,
|
||||
) -> Result<SceneAnalysis> {
|
||||
let image_data = std::fs::read(image_path)?;
|
||||
let image_b64 = base64_encode(&image_data);
|
||||
|
||||
let prompt = "Describe this scene in detail. Include: location, activity, mood, and key visual elements.";
|
||||
|
||||
let description = call_llm(llm_url, &image_b64, prompt, max_tokens)?;
|
||||
|
||||
Ok(SceneAnalysis {
|
||||
scene_number,
|
||||
vlm_description: description,
|
||||
vlm_location: None,
|
||||
vlm_activity: None,
|
||||
vlm_mood: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn base64_encode(data: &[u8]) -> String {
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
general_purpose::STANDARD.encode(data)
|
||||
}
|
||||
|
||||
fn call_llm(url: &str, image_b64: &str, prompt: &str, max_tokens: u32) -> Result<String> {
|
||||
let client = reqwest::blocking::Client::new();
|
||||
|
||||
let body = serde_json::json!({
|
||||
"model": "gemma-4-12b-it",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": prompt},
|
||||
{"type": "image_url", "image_url": {"url": format!("data:image/jpeg;base64,{}", image_b64)}}
|
||||
]
|
||||
}],
|
||||
"max_tokens": max_tokens
|
||||
});
|
||||
|
||||
let resp = client
|
||||
.post(url)
|
||||
.json(&body)
|
||||
.timeout(std::time::Duration::from_secs(60))
|
||||
.send()
|
||||
.context("Failed to call LLM API")?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
anyhow::bail!("LLM API returned error: {}", resp.status());
|
||||
}
|
||||
|
||||
let json: serde_json::Value = resp.json().context("Failed to parse LLM response")?;
|
||||
|
||||
let content = json["choices"][0]["message"]["content"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
Ok(content)
|
||||
}
|
||||
@@ -0,0 +1,921 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const DEFAULT_QDRANT_URL: &str = "http://localhost:6333";
|
||||
const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200";
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_store_traced_faces", about = "Store Traced Faces (Rust)")]
|
||||
struct Args {
|
||||
/// File UUID
|
||||
file_uuid: String,
|
||||
/// Face JSON path (optional)
|
||||
#[arg(long)]
|
||||
face_json: Option<PathBuf>,
|
||||
/// Output directory
|
||||
#[arg(long, default_value = "/Users/accusys/momentry/output")]
|
||||
output_dir: PathBuf,
|
||||
/// Minimum trace length
|
||||
#[arg(long, default_value = "0")]
|
||||
min_trace_len: usize,
|
||||
/// Minimum average confidence
|
||||
#[arg(long, default_value = "0.0")]
|
||||
min_confidence: f32,
|
||||
/// Similarity threshold for face matching
|
||||
#[arg(long, default_value = "0.85")]
|
||||
similarity_threshold: f64,
|
||||
/// IoU threshold for bbox overlap
|
||||
#[arg(long, default_value = "0.3")]
|
||||
iou_threshold: f64,
|
||||
}
|
||||
|
||||
fn env_var(name: &str, default: &str) -> String {
|
||||
std::env::var(name).unwrap_or_else(|_| default.to_string())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FacePoint {
|
||||
payload: Value,
|
||||
vector: Vec<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct FaceDetection {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
trace_id: Option<i32>,
|
||||
// FIX: Add flat bbox fields for consistency with face.json
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
x: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
y: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
width: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
height: Option<i32>,
|
||||
confidence: f32,
|
||||
// FIX: Make bbox optional during deserialization, will be filled later if missing
|
||||
#[serde(default)]
|
||||
bbox: BBox,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
embedding: Option<Vec<f32>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pose: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
landmarks: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
lips: Option<serde_json::Value>,
|
||||
#[serde(rename = "captureQuality", skip_serializing_if = "Option::is_none")]
|
||||
capture_quality: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
|
||||
struct BBox {
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
#[serde(default)]
|
||||
x2: i32,
|
||||
#[serde(default)]
|
||||
y2: i32,
|
||||
#[serde(default)]
|
||||
center_x: i32,
|
||||
#[serde(default)]
|
||||
center_y: i32,
|
||||
}
|
||||
|
||||
impl BBox {
|
||||
fn compute_derived(&mut self) {
|
||||
self.x2 = self.x + self.width;
|
||||
self.y2 = self.y + self.height;
|
||||
self.center_x = self.x + self.width / 2;
|
||||
self.center_y = self.y + self.height / 2;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct FaceFrame {
|
||||
frame: i64,
|
||||
timestamp: f64,
|
||||
faces: Vec<FaceDetection>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct TraceInfo {
|
||||
trace_id: i32,
|
||||
#[serde(default)]
|
||||
frame_count: u64,
|
||||
start_frame: u64,
|
||||
end_frame: u64,
|
||||
#[serde(default)]
|
||||
start_time: f64,
|
||||
#[serde(default)]
|
||||
end_time: f64,
|
||||
#[serde(default)]
|
||||
avg_confidence: f64,
|
||||
#[serde(default)]
|
||||
avg_capture_quality: f64,
|
||||
#[serde(default)]
|
||||
best_frame: u64,
|
||||
#[serde(default)]
|
||||
best_confidence: f64,
|
||||
#[serde(default)]
|
||||
avg_bbox: BBox,
|
||||
#[serde(default)]
|
||||
face_instances: Vec<TracePoint>,
|
||||
// Legacy fields (keep for backward compatibility)
|
||||
#[serde(default)]
|
||||
total_appearances: usize,
|
||||
#[serde(default)]
|
||||
path: Vec<TracePoint>,
|
||||
#[serde(default)]
|
||||
frames: Vec<TracePoint>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct TracePoint {
|
||||
frame: i64,
|
||||
#[serde(default)]
|
||||
timestamp: f64,
|
||||
bbox: BBox,
|
||||
confidence: f32,
|
||||
#[serde(default)]
|
||||
capture_quality: f32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pose: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
landmarks: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
struct TraceStatsSummary {
|
||||
#[serde(default)]
|
||||
total_traces: usize,
|
||||
#[serde(default)]
|
||||
total_face_instances: usize,
|
||||
#[serde(default)]
|
||||
avg_trace_length: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct FaceTracedData {
|
||||
#[serde(default = "default_schema_version")]
|
||||
schema_version: String,
|
||||
fps: f64,
|
||||
#[serde(default)]
|
||||
file_uuid: Option<String>,
|
||||
status: String,
|
||||
stats: TraceStatsSummary,
|
||||
frames: Vec<FaceFrame>,
|
||||
traces: Vec<TraceInfo>,
|
||||
}
|
||||
|
||||
fn default_schema_version() -> String {
|
||||
"2.0".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct FaceData {
|
||||
fps: f64,
|
||||
frame_count: i64,
|
||||
frames: Vec<FaceFrame>,
|
||||
}
|
||||
|
||||
/// Load existing trace_ids from face_traced.json if it exists.
|
||||
/// Returns a map of (frame, face_idx) -> trace_id.
|
||||
fn load_existing_trace_ids(traced_path: &std::path::Path) -> HashMap<(i64, usize), i32> {
|
||||
let mut result = HashMap::new();
|
||||
|
||||
if !traced_path.exists() {
|
||||
return result;
|
||||
}
|
||||
|
||||
let content = match std::fs::read_to_string(traced_path) {
|
||||
Ok(c) => c,
|
||||
Err(_) => return result,
|
||||
};
|
||||
|
||||
let traced_data: serde_json::Value = match serde_json::from_str(&content) {
|
||||
Ok(d) => d,
|
||||
Err(_) => return result,
|
||||
};
|
||||
|
||||
// Read trace_ids directly from frames array
|
||||
if let Some(frames) = traced_data.get("frames").and_then(|f| f.as_array()) {
|
||||
for frame in frames {
|
||||
let frame_num = frame.get("frame").and_then(|f| f.as_i64()).unwrap_or(0);
|
||||
if let Some(faces) = frame.get("faces").and_then(|f| f.as_array()) {
|
||||
for (face_idx, face) in faces.iter().enumerate() {
|
||||
if let Some(trace_id) = face.get("trace_id").and_then(|t| t.as_i64()) {
|
||||
result.insert((frame_num, face_idx), trace_id as i32);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Check if two bboxes match within tolerance (±tolerance pixels)
|
||||
fn bboxes_match(b1: &BBox, b2: &BBox, tolerance: i32) -> bool {
|
||||
(b1.x - b2.x).abs() <= tolerance &&
|
||||
(b1.y - b2.y).abs() <= tolerance &&
|
||||
(b1.width - b2.width).abs() <= tolerance &&
|
||||
(b1.height - b2.height).abs() <= tolerance
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
println!("[TRACE_STORE] Processing file: {}", args.file_uuid);
|
||||
|
||||
// Determine input path
|
||||
let face_json_path = args.face_json.unwrap_or_else(|| {
|
||||
args.output_dir.join(format!("{}.face.json", args.file_uuid))
|
||||
});
|
||||
|
||||
println!("[TRACE_STORE] Reading face.json from: {:?}", face_json_path);
|
||||
|
||||
// Read face.json
|
||||
let face_json_str = std::fs::read_to_string(&face_json_path)
|
||||
.with_context(|| format!("Failed to read {:?}", face_json_path))?;
|
||||
|
||||
let mut face_data: FaceData = serde_json::from_str(&face_json_str)
|
||||
.with_context(|| "Failed to parse face.json")?;
|
||||
|
||||
// FIX: Ensure all faces have bbox by constructing from flat fields if missing
|
||||
for frame in &mut face_data.frames {
|
||||
for face in &mut frame.faces {
|
||||
if face.bbox.x == 0 && face.bbox.y == 0 && face.bbox.width == 0 && face.bbox.height == 0 {
|
||||
// bbox is empty, construct from flat fields
|
||||
face.bbox = BBox {
|
||||
x: face.x.unwrap_or(0),
|
||||
y: face.y.unwrap_or(0),
|
||||
width: face.width.unwrap_or(0),
|
||||
height: face.height.unwrap_or(0),
|
||||
x2: 0,
|
||||
y2: 0,
|
||||
center_x: 0,
|
||||
center_y: 0,
|
||||
};
|
||||
}
|
||||
// Compute derived bbox fields
|
||||
face.bbox.compute_derived();
|
||||
}
|
||||
}
|
||||
|
||||
println!("[TRACE_STORE] Frames: {}", face_data.frames.len());
|
||||
|
||||
// Load embeddings from Qdrant
|
||||
println!("[TRACE_STORE] Loading embeddings from Qdrant...");
|
||||
let qdrant_faces = load_qdrant_faces(&args.file_uuid);
|
||||
|
||||
// Load existing trace_ids from face_traced.json if available
|
||||
let traced_json_path = args.output_dir.join(format!("{}.face_traced.json", args.file_uuid));
|
||||
let existing_trace_ids = load_existing_trace_ids(&traced_json_path);
|
||||
if !existing_trace_ids.is_empty() {
|
||||
println!("[TRACE_STORE] Loaded {} existing trace_ids from face_traced.json", existing_trace_ids.len());
|
||||
}
|
||||
|
||||
// Run face tracking
|
||||
println!("[TRACE_STORE] Running face tracking with embedding similarity (threshold={})...", args.similarity_threshold);
|
||||
let traces = run_face_tracking(
|
||||
&mut face_data,
|
||||
&qdrant_faces,
|
||||
&existing_trace_ids,
|
||||
args.min_trace_len,
|
||||
args.min_confidence,
|
||||
args.similarity_threshold,
|
||||
args.iou_threshold,
|
||||
)?;
|
||||
|
||||
println!("[TRACE_STORE] Traces: {}", traces.len());
|
||||
|
||||
// Update trace_ids in Qdrant
|
||||
println!("[TRACE_STORE] Updating trace_ids in Qdrant...");
|
||||
let trace_mapping: HashMap<(i64, i32, i32, i32, i32), i32> = build_trace_mapping(&face_data);
|
||||
if !trace_mapping.is_empty() {
|
||||
update_qdrant_trace_ids(&args.file_uuid, &trace_mapping)?;
|
||||
println!("[TRACE_STORE] Updated {} trace_ids in Qdrant", trace_mapping.len());
|
||||
} else {
|
||||
println!("[TRACE_STORE] No trace_ids to update");
|
||||
}
|
||||
|
||||
// Convert traces to v2 format
|
||||
let traces_v2: Vec<TraceInfo> = traces
|
||||
.into_iter()
|
||||
.map(|(_, mut t)| {
|
||||
// Compute derived bbox fields
|
||||
for point in &mut t.path {
|
||||
let mut bbox = point.bbox.clone();
|
||||
bbox.compute_derived();
|
||||
point.bbox = bbox;
|
||||
}
|
||||
for point in &mut t.frames {
|
||||
let mut bbox = point.bbox.clone();
|
||||
bbox.compute_derived();
|
||||
point.bbox = bbox;
|
||||
}
|
||||
|
||||
// Calculate stats
|
||||
let frame_count = t.path.len() as u64;
|
||||
let start_frame = t.path.first().map(|p| p.frame as u64).unwrap_or(0);
|
||||
let end_frame = t.path.last().map(|p| p.frame as u64).unwrap_or(0);
|
||||
let start_time = start_frame as f64 / face_data.fps;
|
||||
let end_time = end_frame as f64 / face_data.fps;
|
||||
let avg_confidence = if !t.path.is_empty() {
|
||||
t.path.iter().map(|p| p.confidence as f64).sum::<f64>() / t.path.len() as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let avg_capture_quality = if !t.path.is_empty() {
|
||||
t.path.iter().map(|p| p.capture_quality as f64).sum::<f64>() / t.path.len() as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let best = t.path.iter().max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap());
|
||||
let best_frame = best.map(|p| p.frame as u64).unwrap_or(0);
|
||||
let best_confidence = best.map(|p| p.confidence as f64).unwrap_or(0.0);
|
||||
|
||||
// Calculate average bbox
|
||||
let avg_bbox = if !t.path.is_empty() {
|
||||
let mut bbox = BBox::default();
|
||||
for p in &t.path {
|
||||
bbox.x += p.bbox.x;
|
||||
bbox.y += p.bbox.y;
|
||||
bbox.width += p.bbox.width;
|
||||
bbox.height += p.bbox.height;
|
||||
}
|
||||
let n = t.path.len() as i32;
|
||||
bbox.x /= n;
|
||||
bbox.y /= n;
|
||||
bbox.width /= n;
|
||||
bbox.height /= n;
|
||||
bbox.compute_derived();
|
||||
bbox
|
||||
} else {
|
||||
BBox::default()
|
||||
};
|
||||
|
||||
TraceInfo {
|
||||
trace_id: t.trace_id,
|
||||
frame_count,
|
||||
start_frame,
|
||||
end_frame,
|
||||
start_time,
|
||||
end_time,
|
||||
avg_confidence,
|
||||
avg_capture_quality,
|
||||
best_frame,
|
||||
best_confidence,
|
||||
avg_bbox,
|
||||
face_instances: t.path.clone(),
|
||||
total_appearances: t.total_appearances,
|
||||
path: t.path,
|
||||
frames: t.frames,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let total_traces = traces_v2.len();
|
||||
let total_face_instances: usize = traces_v2.iter().map(|t| t.frame_count as usize).sum();
|
||||
let avg_trace_length = if total_traces > 0 {
|
||||
traces_v2.iter().map(|t| t.frame_count as f64).sum::<f64>() / total_traces as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Create output (v2 format)
|
||||
let traced_data = FaceTracedData {
|
||||
schema_version: "2.0".to_string(),
|
||||
fps: face_data.fps,
|
||||
file_uuid: Some(args.file_uuid.clone()),
|
||||
status: "completed".to_string(),
|
||||
stats: TraceStatsSummary {
|
||||
total_traces,
|
||||
total_face_instances,
|
||||
avg_trace_length,
|
||||
},
|
||||
frames: face_data.frames,
|
||||
traces: traces_v2,
|
||||
};
|
||||
|
||||
// Write face_traced.json
|
||||
let traced_json_path = args.output_dir.join(format!("{}.face_traced.json", args.file_uuid));
|
||||
println!("[TRACE_STORE] Writing face_traced.json to: {:?}", traced_json_path);
|
||||
|
||||
let traced_json_str = serde_json::to_string_pretty(&traced_data)
|
||||
.with_context(|| "Failed to serialize face_traced.json")?;
|
||||
|
||||
std::fs::write(&traced_json_path, traced_json_str)
|
||||
.with_context(|| format!("Failed to write {:?}", traced_json_path))?;
|
||||
|
||||
println!("[TRACE_STORE] Done");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_face_tracking(
|
||||
face_data: &mut FaceData,
|
||||
qdrant_faces: &[FacePoint],
|
||||
existing_trace_ids: &HashMap<(i64, usize), i32>,
|
||||
min_trace_len: usize,
|
||||
min_confidence: f32,
|
||||
similarity_threshold: f64,
|
||||
iou_threshold: f64,
|
||||
) -> Result<HashMap<String, TraceInfo>> {
|
||||
let mut traces: HashMap<String, TraceInfo> = HashMap::new();
|
||||
let mut next_trace_id = 1;
|
||||
|
||||
// If we have existing trace_ids, use the max existing ID as starting point
|
||||
if !existing_trace_ids.is_empty() {
|
||||
next_trace_id = existing_trace_ids.values().copied().max().unwrap_or(0) + 1;
|
||||
println!("[TRACE] Resuming from existing trace_ids, next_id={}", next_trace_id);
|
||||
}
|
||||
|
||||
// Build frame -> embedding map from Qdrant data
|
||||
let mut frame_embeddings: HashMap<i64, Vec<(Vec<f64>, f32, BBox)>> = HashMap::new();
|
||||
for point in qdrant_faces {
|
||||
let frame = point.payload.get("frame")
|
||||
.and_then(|f| f.as_i64())
|
||||
.unwrap_or(0);
|
||||
let confidence = point.payload.get("confidence")
|
||||
.and_then(|c| c.as_f64())
|
||||
.unwrap_or(0.9) as f32;
|
||||
|
||||
// Qdrant may store bbox in two formats:
|
||||
// 1. Nested bbox field (from face_processor.py)
|
||||
// 2. Direct x, y, width, height fields (from rust_store_traced_faces)
|
||||
let mut bbox_struct = if let Some(bbox_obj) = point.payload.get("bbox").and_then(|b| b.as_object()) {
|
||||
BBox {
|
||||
x: bbox_obj.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
|
||||
y: bbox_obj.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32,
|
||||
width: bbox_obj.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32,
|
||||
height: bbox_obj.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32,
|
||||
x2: bbox_obj.get("x2").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
|
||||
y2: bbox_obj.get("y2").and_then(|y| y.as_i64()).unwrap_or(0) as i32,
|
||||
center_x: bbox_obj.get("center_x").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
|
||||
center_y: bbox_obj.get("center_y").and_then(|y| y.as_i64()).unwrap_or(0) as i32,
|
||||
}
|
||||
} else {
|
||||
// Direct fields
|
||||
BBox {
|
||||
x: point.payload.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
|
||||
y: point.payload.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32,
|
||||
width: point.payload.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32,
|
||||
height: point.payload.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32,
|
||||
x2: 0,
|
||||
y2: 0,
|
||||
center_x: 0,
|
||||
center_y: 0,
|
||||
}
|
||||
};
|
||||
bbox_struct.compute_derived();
|
||||
|
||||
// Debug: log first few embeddings
|
||||
if frame_embeddings.len() < 5 {
|
||||
eprintln!("[TRACE] Qdrant point: frame={}, bbox={:?}, vector_len={}",
|
||||
frame, bbox_struct, point.vector.len());
|
||||
}
|
||||
|
||||
frame_embeddings
|
||||
.entry(frame)
|
||||
.or_insert_with(Vec::new)
|
||||
.push((point.vector.clone(), confidence, bbox_struct));
|
||||
}
|
||||
|
||||
eprintln!("[TRACE] Built embedding map for {} frames", frame_embeddings.len());
|
||||
|
||||
// Face matching with embedding similarity
|
||||
let mut face_trace_ids: HashMap<(i64, usize), i32> = HashMap::new();
|
||||
|
||||
let frames_len = face_data.frames.len();
|
||||
|
||||
for frame_idx in 0..frames_len {
|
||||
let frame = &face_data.frames[frame_idx];
|
||||
let current_frame_num = frame.frame;
|
||||
|
||||
// Get embeddings for current frame
|
||||
let current_embeddings = frame_embeddings.get(¤t_frame_num).cloned().unwrap_or_default();
|
||||
|
||||
for face_idx in 0..frame.faces.len() {
|
||||
let current_face = &frame.faces[face_idx];
|
||||
|
||||
// First check if we have an existing trace_id for this face
|
||||
if let Some(&existing_tid) = existing_trace_ids.get(&(current_frame_num, face_idx)) {
|
||||
face_trace_ids.insert((current_frame_num, face_idx), existing_tid);
|
||||
|
||||
let trace_key = existing_tid.to_string();
|
||||
let trace = traces.entry(trace_key).or_insert(TraceInfo {
|
||||
trace_id: existing_tid,
|
||||
frame_count: 0,
|
||||
start_frame: 0,
|
||||
end_frame: 0,
|
||||
start_time: 0.0,
|
||||
end_time: 0.0,
|
||||
avg_confidence: 0.0,
|
||||
avg_capture_quality: 0.0,
|
||||
best_frame: 0,
|
||||
best_confidence: 0.0,
|
||||
avg_bbox: BBox::default(),
|
||||
face_instances: Vec::new(),
|
||||
total_appearances: 0,
|
||||
path: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
});
|
||||
trace.total_appearances += 1;
|
||||
let mut bbox = current_face.bbox.clone();
|
||||
bbox.compute_derived();
|
||||
trace.path.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
timestamp: current_frame_num as f64 / face_data.fps,
|
||||
bbox: bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
capture_quality: current_face.capture_quality.unwrap_or(0.0),
|
||||
pose: current_face.pose.clone(),
|
||||
landmarks: current_face.landmarks.clone(),
|
||||
});
|
||||
trace.frames.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
timestamp: current_frame_num as f64 / face_data.fps,
|
||||
bbox,
|
||||
confidence: current_face.confidence,
|
||||
capture_quality: current_face.capture_quality.unwrap_or(0.0),
|
||||
pose: current_face.pose.clone(),
|
||||
landmarks: current_face.landmarks.clone(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find matching embedding with bbox tolerance (±5px)
|
||||
let current_embedding = current_embeddings.iter()
|
||||
.find(|(_, _, bbox)| {
|
||||
bboxes_match(bbox, ¤t_face.bbox, 5)
|
||||
})
|
||||
.map(|(emb, _, _)| emb.clone());
|
||||
|
||||
if frame_idx == 0 || frame_idx % 20 == 0 {
|
||||
eprintln!("[TRACE] Frame {} face {}: bbox={:?}, has_emb={}",
|
||||
current_frame_num, face_idx, current_face.bbox, current_embedding.is_some());
|
||||
}
|
||||
|
||||
let mut best_match: Option<(i32, f64, f64)> = None;
|
||||
let mut best_iou = 0.0;
|
||||
|
||||
if frame_idx > 0 {
|
||||
let prev_frame = &face_data.frames[frame_idx - 1];
|
||||
|
||||
// Check previous frame (regardless of frame number difference)
|
||||
for (prev_face_idx, prev_face) in prev_frame.faces.iter().enumerate() {
|
||||
if let Some(&prev_trace_id) = face_trace_ids.get(&(prev_frame.frame, prev_face_idx)) {
|
||||
let iou = calculate_iou(¤t_face.bbox, &prev_face.bbox);
|
||||
|
||||
// Get previous embedding with bbox tolerance
|
||||
let prev_embeddings = frame_embeddings.get(&prev_frame.frame).cloned().unwrap_or_default();
|
||||
let prev_embedding = prev_embeddings.iter()
|
||||
.find(|(_, _, bbox)| {
|
||||
bboxes_match(bbox, &prev_face.bbox, 5)
|
||||
})
|
||||
.map(|(emb, _, _)| emb);
|
||||
|
||||
// Calculate similarity if both embeddings exist
|
||||
let similarity = match (¤t_embedding, &prev_embedding) {
|
||||
(Some(curr), Some(prev)) => calculate_cosine_similarity(curr, prev),
|
||||
_ => 0.0,
|
||||
};
|
||||
|
||||
// Match if IoU AND similarity meet thresholds
|
||||
if iou > best_iou
|
||||
&& iou > iou_threshold
|
||||
&& similarity > similarity_threshold {
|
||||
best_iou = iou;
|
||||
best_match = Some((prev_trace_id, iou, similarity));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let trace_id = if let Some((matched_trace_id, iou, sim)) = best_match {
|
||||
eprintln!("[TRACE] Frame {} face {}: matched trace {} (iou={:.3}, sim={:.3})",
|
||||
current_frame_num, face_idx, matched_trace_id, iou, sim);
|
||||
matched_trace_id
|
||||
} else {
|
||||
let tid = next_trace_id;
|
||||
next_trace_id += 1;
|
||||
eprintln!("[TRACE] Frame {} face {}: new trace {}", current_frame_num, face_idx, tid);
|
||||
tid
|
||||
};
|
||||
|
||||
face_trace_ids.insert((current_frame_num, face_idx), trace_id);
|
||||
|
||||
let trace_key = trace_id.to_string();
|
||||
let trace = traces.entry(trace_key).or_insert(TraceInfo {
|
||||
trace_id,
|
||||
frame_count: 0,
|
||||
start_frame: 0,
|
||||
end_frame: 0,
|
||||
start_time: 0.0,
|
||||
end_time: 0.0,
|
||||
avg_confidence: 0.0,
|
||||
avg_capture_quality: 0.0,
|
||||
best_frame: 0,
|
||||
best_confidence: 0.0,
|
||||
avg_bbox: BBox::default(),
|
||||
face_instances: Vec::new(),
|
||||
total_appearances: 0,
|
||||
path: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
});
|
||||
|
||||
trace.total_appearances += 1;
|
||||
let mut bbox = current_face.bbox.clone();
|
||||
bbox.compute_derived();
|
||||
let timestamp = current_frame_num as f64 / face_data.fps;
|
||||
trace.path.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
timestamp,
|
||||
bbox: bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
capture_quality: current_face.capture_quality.unwrap_or(0.0),
|
||||
pose: current_face.pose.clone(),
|
||||
landmarks: current_face.landmarks.clone(),
|
||||
});
|
||||
trace.frames.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
timestamp,
|
||||
bbox,
|
||||
confidence: current_face.confidence,
|
||||
capture_quality: current_face.capture_quality.unwrap_or(0.0),
|
||||
pose: current_face.pose.clone(),
|
||||
landmarks: current_face.landmarks.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Assign trace_ids to faces
|
||||
for frame in &mut face_data.frames {
|
||||
for (face_idx, face) in frame.faces.iter_mut().enumerate() {
|
||||
if let Some(&trace_id) = face_trace_ids.get(&(frame.frame, face_idx)) {
|
||||
face.trace_id = Some(trace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate average confidence for each trace
|
||||
for trace in traces.values_mut() {
|
||||
if !trace.path.is_empty() {
|
||||
let sum: f64 = trace.path.iter().map(|p| p.confidence as f64).sum();
|
||||
trace.avg_confidence = sum / trace.path.len() as f64;
|
||||
}
|
||||
}
|
||||
|
||||
// Filter traces
|
||||
if min_trace_len > 0 || min_confidence > 0.0 {
|
||||
traces.retain(|_, trace| {
|
||||
trace.total_appearances >= min_trace_len
|
||||
&& (min_confidence == 0.0 || trace.avg_confidence >= min_confidence as f64)
|
||||
});
|
||||
}
|
||||
|
||||
Ok(traces)
|
||||
}
|
||||
|
||||
fn calculate_iou(bbox1: &BBox, bbox2: &BBox) -> f64 {
|
||||
let x1 = std::cmp::max(bbox1.x, bbox2.x);
|
||||
let y1 = std::cmp::max(bbox1.y, bbox2.y);
|
||||
let x2 = std::cmp::min(bbox1.x + bbox1.width, bbox2.x + bbox2.width);
|
||||
let y2 = std::cmp::min(bbox1.y + bbox1.height, bbox2.y + bbox2.height);
|
||||
|
||||
if x2 < x1 || y2 < y1 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let intersection = (x2 - x1) as i64 * (y2 - y1) as i64;
|
||||
let area1 = bbox1.width as i64 * bbox1.height as i64;
|
||||
let area2 = bbox2.width as i64 * bbox2.height as i64;
|
||||
let union = area1 + area2 - intersection;
|
||||
|
||||
if union == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
intersection as f64 / union as f64
|
||||
}
|
||||
|
||||
fn calculate_cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
|
||||
if a.len() != b.len() || a.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let dot: f64 = a.iter().zip(b).map(|(x, y)| x * y).sum();
|
||||
let na: f64 = a.iter().map(|x| x * x).sum::<f64>().sqrt();
|
||||
let nb: f64 = b.iter().map(|x| x * x).sum::<f64>().sqrt();
|
||||
if na == 0.0 || nb == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
dot / (na * nb)
|
||||
}
|
||||
}
|
||||
|
||||
fn load_qdrant_faces(uuid: &str) -> Vec<FacePoint> {
|
||||
let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL);
|
||||
let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY);
|
||||
let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url);
|
||||
|
||||
let mut all_points: Vec<FacePoint> = Vec::new();
|
||||
let mut offset: Option<Value> = None;
|
||||
|
||||
loop {
|
||||
let mut body = json!({
|
||||
"limit": 10000,
|
||||
"with_payload": true,
|
||||
"with_vector": true,
|
||||
"filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]},
|
||||
});
|
||||
if let Some(ref off) = offset {
|
||||
body["offset"] = off.clone();
|
||||
}
|
||||
|
||||
let resp = ureq::post(&scroll_url)
|
||||
.set("api-key", &qdrant_api_key)
|
||||
.timeout(Duration::from_secs(60))
|
||||
.send_json(body);
|
||||
|
||||
match resp {
|
||||
Ok(r) => {
|
||||
let data: Value = r.into_json().unwrap_or(Value::Null);
|
||||
let points = data
|
||||
.pointer("/result/points")
|
||||
.and_then(|p| p.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
for p in points {
|
||||
let payload = p.get("payload").cloned().unwrap_or(Value::Null);
|
||||
let vector = p
|
||||
.get("vector")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|v| {
|
||||
v.iter()
|
||||
.filter_map(|x| x.as_f64())
|
||||
.collect::<Vec<f64>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
all_points.push(FacePoint { payload, vector });
|
||||
}
|
||||
|
||||
let next = data.pointer("/result/next_page_offset").cloned();
|
||||
match next {
|
||||
Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)),
|
||||
Some(Value::Number(_)) => break,
|
||||
Some(Value::Null) | None => break,
|
||||
other => {
|
||||
offset = other;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[TRACE] Qdrant scroll error: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("[TRACE] Loaded {} points from Qdrant _faces", all_points.len());
|
||||
all_points
|
||||
}
|
||||
|
||||
fn build_trace_mapping(face_data: &FaceData) -> HashMap<(i64, i32, i32, i32, i32), i32> {
|
||||
let mut mapping = HashMap::new();
|
||||
for frame in &face_data.frames {
|
||||
for face in &frame.faces {
|
||||
if let Some(trace_id) = face.trace_id {
|
||||
let key = (frame.frame, face.bbox.x, face.bbox.y, face.bbox.width, face.bbox.height);
|
||||
mapping.insert(key, trace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
mapping
|
||||
}
|
||||
|
||||
fn update_qdrant_trace_ids(
|
||||
file_uuid: &str,
|
||||
trace_mapping: &HashMap<(i64, i32, i32, i32, i32), i32>,
|
||||
) -> Result<()> {
|
||||
let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL);
|
||||
let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY);
|
||||
|
||||
// Load all points for this file
|
||||
let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url);
|
||||
let mut offset: Option<Value> = None;
|
||||
let mut trace_updates: HashMap<i32, Vec<Value>> = HashMap::new();
|
||||
|
||||
loop {
|
||||
let mut body = json!({
|
||||
"limit": 10000,
|
||||
"with_payload": true,
|
||||
"with_vector": false,
|
||||
"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]},
|
||||
});
|
||||
if let Some(ref off) = offset {
|
||||
body["offset"] = off.clone();
|
||||
}
|
||||
|
||||
let resp = ureq::post(&scroll_url)
|
||||
.set("api-key", &qdrant_api_key)
|
||||
.timeout(Duration::from_secs(60))
|
||||
.send_json(body);
|
||||
|
||||
match resp {
|
||||
Ok(r) => {
|
||||
let data: Value = r.into_json().unwrap_or(Value::Null);
|
||||
let points = data
|
||||
.pointer("/result/points")
|
||||
.and_then(|p| p.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
for point in points {
|
||||
let point_id = point.get("id").cloned();
|
||||
let payload = point.get("payload").cloned().unwrap_or(Value::Null);
|
||||
|
||||
let frame = payload.get("frame").and_then(|f| f.as_i64()).unwrap_or(0);
|
||||
|
||||
// Support two bbox formats
|
||||
let (x, y, width, height) = if let Some(bbox_obj) = payload.get("bbox").and_then(|b| b.as_object()) {
|
||||
(
|
||||
bbox_obj.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
|
||||
bbox_obj.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32,
|
||||
bbox_obj.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32,
|
||||
bbox_obj.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
payload.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
|
||||
payload.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32,
|
||||
payload.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32,
|
||||
payload.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32,
|
||||
)
|
||||
};
|
||||
|
||||
let key = (frame, x, y, width, height);
|
||||
if let Some(&trace_id) = trace_mapping.get(&key) {
|
||||
if let Some(id) = point_id {
|
||||
trace_updates
|
||||
.entry(trace_id)
|
||||
.or_default()
|
||||
.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let next = data.pointer("/result/next_page_offset").cloned();
|
||||
match next {
|
||||
Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)),
|
||||
Some(Value::Number(_)) => break,
|
||||
Some(Value::Null) | None => break,
|
||||
other => {
|
||||
offset = other;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[TRACE] Qdrant scroll error: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if trace_updates.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let update_url = format!("{}/collections/_faces/points/payload", qdrant_url);
|
||||
|
||||
for (trace_id, point_ids) in trace_updates {
|
||||
let body = json!({
|
||||
"payload": {
|
||||
"trace_id": trace_id
|
||||
},
|
||||
"points": point_ids
|
||||
});
|
||||
|
||||
let resp = ureq::post(&update_url)
|
||||
.set("api-key", &qdrant_api_key)
|
||||
.timeout(Duration::from_secs(60))
|
||||
.send_json(body);
|
||||
|
||||
if let Err(e) = resp {
|
||||
eprintln!("[TRACE] Failed to update Qdrant trace_id {} for {} points: {}", trace_id, point_ids.len(), e);
|
||||
} else {
|
||||
println!("[TRACE] Updated trace_id {} for {} points", trace_id, point_ids.len());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const DEFAULT_QDRANT_URL: &str = "http://localhost:6333";
|
||||
const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200";
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_store_traced_faces", about = "Store Traced Faces (Rust)")]
|
||||
struct Args {
|
||||
/// File UUID
|
||||
file_uuid: String,
|
||||
/// Face JSON path (optional)
|
||||
#[arg(long)]
|
||||
face_json: Option<PathBuf>,
|
||||
/// Output directory
|
||||
#[arg(long, default_value = "/Users/accusys/momentry/output")]
|
||||
output_dir: PathBuf,
|
||||
/// Minimum trace length
|
||||
#[arg(long, default_value = "0")]
|
||||
min_trace_len: usize,
|
||||
/// Minimum average confidence
|
||||
#[arg(long, default_value = "0.0")]
|
||||
min_confidence: f32,
|
||||
/// Similarity threshold for face matching
|
||||
#[arg(long, default_value = "0.85")]
|
||||
similarity_threshold: f64,
|
||||
/// Distance threshold (pixels)
|
||||
#[arg(long, default_value = "100.0")]
|
||||
distance_threshold: f64,
|
||||
}
|
||||
|
||||
fn env_var(name: &str, default: &str) -> String {
|
||||
std::env::var(name).unwrap_or_else(|_| default.to_string())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FacePoint {
|
||||
payload: Value,
|
||||
vector: Vec<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct FaceDetection {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
trace_id: Option<i32>,
|
||||
confidence: f32,
|
||||
bbox: BBox,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
embedding: Option<Vec<f32>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pose: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
landmarks: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
lips: Option<serde_json::Value>,
|
||||
#[serde(rename = "captureQuality", skip_serializing_if = "Option::is_none")]
|
||||
capture_quality: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct BBox {
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct FaceFrame {
|
||||
frame: i64,
|
||||
timestamp: f64,
|
||||
faces: Vec<FaceDetection>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct TraceInfo {
|
||||
trace_id: i32,
|
||||
total_appearances: usize,
|
||||
avg_confidence: f32,
|
||||
path: Vec<TracePoint>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct TracePoint {
|
||||
frame: i64,
|
||||
bbox: BBox,
|
||||
confidence: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct FaceData {
|
||||
fps: f64,
|
||||
frame_count: i64,
|
||||
frames: Vec<FaceFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct FaceTracedData {
|
||||
fps: f64,
|
||||
frames: Vec<FaceFrame>,
|
||||
traces: HashMap<String, TraceInfo>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
println!("[TRACE_STORE] Processing file: {}", args.file_uuid);
|
||||
|
||||
// Determine input path
|
||||
let face_json_path = args.face_json.unwrap_or_else(|| {
|
||||
args.output_dir.join(format!("{}.face.json", args.file_uuid))
|
||||
});
|
||||
|
||||
println!("[TRACE_STORE] Reading face.json from: {:?}", face_json_path);
|
||||
|
||||
// Read face.json
|
||||
let face_json_str = std::fs::read_to_string(&face_json_path)
|
||||
.with_context(|| format!("Failed to read {:?}", face_json_path))?;
|
||||
|
||||
let mut face_data: FaceData = serde_json::from_str(&face_json_str)
|
||||
.with_context(|| "Failed to parse face.json")?;
|
||||
|
||||
println!("[TRACE_STORE] Frames: {}", face_data.frames.len());
|
||||
|
||||
// Run face tracking
|
||||
println!("[TRACE_STORE] Loading embeddings from Qdrant...");
|
||||
let qdrant_faces = load_qdrant_faces(&args.file_uuid);
|
||||
|
||||
println!("[TRACE_STORE] Running face tracking with embedding similarity (threshold={})...", args.similarity_threshold);
|
||||
let traces = run_face_tracking(
|
||||
&mut face_data,
|
||||
&qdrant_faces,
|
||||
args.min_trace_len,
|
||||
args.min_confidence,
|
||||
args.similarity_threshold,
|
||||
args.distance_threshold,
|
||||
)?;
|
||||
|
||||
println!("[TRACE_STORE] Traces: {}", traces.len());
|
||||
|
||||
// Create output
|
||||
let traced_data = FaceTracedData {
|
||||
fps: face_data.fps,
|
||||
frames: face_data.frames,
|
||||
traces,
|
||||
};
|
||||
|
||||
// Write face_traced.json
|
||||
let traced_json_path = args.output_dir.join(format!("{}.face_traced.json", args.file_uuid));
|
||||
println!("[TRACE_STORE] Writing face_traced.json to: {:?}", traced_json_path);
|
||||
|
||||
let traced_json_str = serde_json::to_string_pretty(&traced_data)
|
||||
.with_context(|| "Failed to serialize face_traced.json")?;
|
||||
|
||||
std::fs::write(&traced_json_path, traced_json_str)
|
||||
.with_context(|| format!("Failed to write {:?}", traced_json_path))?;
|
||||
|
||||
println!("[TRACE_STORE] Done");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_face_tracking(
|
||||
face_data: &mut FaceData,
|
||||
qdrant_faces: &[FacePoint],
|
||||
min_trace_len: usize,
|
||||
min_confidence: f32,
|
||||
similarity_threshold: f64,
|
||||
distance_threshold: f64,
|
||||
) -> Result<HashMap<String, TraceInfo>> {
|
||||
let mut traces: HashMap<String, TraceInfo> = HashMap::new();
|
||||
let mut next_trace_id = 1;
|
||||
|
||||
// Build frame -> embedding map from Qdrant data
|
||||
let mut frame_embeddings: HashMap<i64, Vec<(Vec<f64>, f32, BBox)>> = HashMap::new();
|
||||
for point in qdrant_faces {
|
||||
let frame = point.payload.get("frame")
|
||||
.and_then(|f| f.as_i64())
|
||||
.unwrap_or(0);
|
||||
let confidence = point.payload.get("confidence")
|
||||
.and_then(|c| c.as_f64())
|
||||
.unwrap_or(0.9) as f32;
|
||||
let bbox = point.payload.get("bbox");
|
||||
let bbox_struct = if let Some(bbox_obj) = bbox {
|
||||
BBox {
|
||||
x: bbox_obj.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
|
||||
y: bbox_obj.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32,
|
||||
width: bbox_obj.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32,
|
||||
height: bbox_obj.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32,
|
||||
}
|
||||
} else {
|
||||
BBox { x: 0, y: 0, width: 0, height: 0 }
|
||||
};
|
||||
|
||||
frame_embeddings
|
||||
.entry(frame)
|
||||
.or_insert_with(Vec::new)
|
||||
.push((point.vector.clone(), confidence, bbox_struct));
|
||||
}
|
||||
|
||||
eprintln!("[TRACE] Built embedding map for {} frames", frame_embeddings.len());
|
||||
|
||||
// Face matching with embedding similarity
|
||||
let mut face_trace_ids: HashMap<(i64, usize), i32> = HashMap::new(); // (frame, face_idx) -> trace_id
|
||||
|
||||
let frames_len = face_data.frames.len();
|
||||
|
||||
for frame_idx in 0..frames_len {
|
||||
let frame = &face_data.frames[frame_idx];
|
||||
let current_frame_num = frame.frame;
|
||||
|
||||
// Get embeddings for current frame
|
||||
let current_embeddings = frame_embeddings.get(¤t_frame_num).cloned().unwrap_or_default();
|
||||
|
||||
for face_idx in 0..frame.faces.len() {
|
||||
let current_face = &frame.faces[face_idx];
|
||||
|
||||
// Find matching embedding
|
||||
let current_embedding = current_embeddings.iter()
|
||||
.find(|(_, _, bbox)| {
|
||||
bbox.x == current_face.bbox.x &&
|
||||
bbox.y == current_face.bbox.y &&
|
||||
bbox.width == current_face.bbox.width &&
|
||||
bbox.height == current_face.bbox.height
|
||||
})
|
||||
.map(|(emb, _, _)| emb.clone());
|
||||
|
||||
let mut best_match: Option<(i32, f64, f64)> = None; // (trace_id, distance, similarity)
|
||||
let mut best_distance = f64::MAX;
|
||||
let mut best_similarity = 0.0;
|
||||
|
||||
if frame_idx > 0 {
|
||||
let prev_frame = &face_data.frames[frame_idx - 1];
|
||||
|
||||
// Check previous frame or frame - 3
|
||||
if prev_frame.frame == current_frame_num - 3 || prev_frame.frame == current_frame_num - 1 {
|
||||
for (prev_face_idx, prev_face) in prev_frame.faces.iter().enumerate() {
|
||||
if let Some(&prev_trace_id) = face_trace_ids.get(&(prev_frame.frame, prev_face_idx)) {
|
||||
let distance = calculate_bbox_distance(
|
||||
¤t_face.bbox,
|
||||
&prev_face.bbox,
|
||||
);
|
||||
|
||||
// Get previous embedding
|
||||
let prev_embeddings = frame_embeddings.get(&prev_frame.frame).cloned().unwrap_or_default();
|
||||
let prev_embedding = prev_embeddings.iter()
|
||||
.find(|(_, _, bbox)| {
|
||||
bbox.x == prev_face.bbox.x &&
|
||||
bbox.y == prev_face.bbox.y &&
|
||||
bbox.width == prev_face.bbox.width &&
|
||||
bbox.height == prev_face.bbox.height
|
||||
})
|
||||
.map(|(emb, _, _)| emb);
|
||||
|
||||
// Calculate similarity if both embeddings exist
|
||||
let similarity = match (¤t_embedding, &prev_embedding) {
|
||||
(Some(curr), Some(prev)) => calculate_cosine_similarity(curr, prev),
|
||||
_ => 0.0,
|
||||
};
|
||||
|
||||
// Match if distance AND similarity meet thresholds
|
||||
if distance < best_distance
|
||||
&& distance < distance_threshold
|
||||
&& similarity > similarity_threshold {
|
||||
best_distance = distance;
|
||||
best_similarity = similarity;
|
||||
best_match = Some((prev_trace_id, distance, similarity));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let trace_id = if let Some((matched_trace_id, _, _)) = best_match {
|
||||
matched_trace_id
|
||||
} else {
|
||||
let tid = next_trace_id;
|
||||
next_trace_id += 1;
|
||||
tid
|
||||
};
|
||||
|
||||
face_trace_ids.insert((current_frame_num, face_idx), trace_id);
|
||||
|
||||
let trace_key = trace_id.to_string();
|
||||
let trace = traces.entry(trace_key).or_insert(TraceInfo {
|
||||
trace_id,
|
||||
total_appearances: 0,
|
||||
avg_confidence: 0.0,
|
||||
path: Vec::new(),
|
||||
});
|
||||
|
||||
trace.total_appearances += 1;
|
||||
trace.path.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
bbox: current_face.bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Assign trace_ids to faces
|
||||
for frame in &mut face_data.frames {
|
||||
for (face_idx, face) in frame.faces.iter_mut().enumerate() {
|
||||
if let Some(&trace_id) = face_trace_ids.get(&(frame.frame, face_idx)) {
|
||||
face.trace_id = Some(trace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate average confidence for each trace
|
||||
for trace in traces.values_mut() {
|
||||
if !trace.path.is_empty() {
|
||||
let sum: f32 = trace.path.iter().map(|p| p.confidence).sum();
|
||||
trace.avg_confidence = sum / trace.path.len() as f32;
|
||||
}
|
||||
}
|
||||
|
||||
// Filter traces by min_trace_len and min_confidence
|
||||
if min_trace_len > 0 || min_confidence > 0.0 {
|
||||
traces.retain(|_, trace| {
|
||||
trace.total_appearances >= min_trace_len
|
||||
&& (min_confidence == 0.0 || trace.avg_confidence >= min_confidence)
|
||||
});
|
||||
}
|
||||
|
||||
Ok(traces)
|
||||
}
|
||||
|
||||
let frames_len = face_data.frames.len();
|
||||
|
||||
for frame_idx in 0..frames_len {
|
||||
let frame = &face_data.frames[frame_idx];
|
||||
let current_frame_num = frame.frame;
|
||||
let current_faces = frame.faces.clone();
|
||||
|
||||
let mut face_trace_ids = Vec::new();
|
||||
|
||||
for face_idx in 0..current_faces.len() {
|
||||
let current_face = ¤t_faces[face_idx];
|
||||
|
||||
let mut best_match: Option<(i32, f64)> = None;
|
||||
let mut best_distance = f64::MAX;
|
||||
|
||||
if frame_idx > 0 {
|
||||
let prev_frame = &face_data.frames[frame_idx - 1];
|
||||
|
||||
if prev_frame.frame == current_frame_num - 3 || prev_frame.frame == current_frame_num - 1 {
|
||||
for prev_face in &prev_frame.faces {
|
||||
if let Some(prev_trace_id) = prev_face.trace_id {
|
||||
let distance = calculate_bbox_distance(
|
||||
¤t_face.bbox,
|
||||
&prev_face.bbox,
|
||||
);
|
||||
|
||||
if distance < best_distance && distance < distance_threshold {
|
||||
best_distance = distance;
|
||||
best_match = Some((prev_trace_id, distance));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let trace_id = if let Some((matched_trace_id, _distance)) = best_match {
|
||||
matched_trace_id
|
||||
} else {
|
||||
let tid = next_trace_id;
|
||||
next_trace_id += 1;
|
||||
tid
|
||||
};
|
||||
|
||||
face_trace_ids.push(trace_id);
|
||||
|
||||
let trace_key = trace_id.to_string();
|
||||
let trace = traces.entry(trace_key).or_insert(TraceInfo {
|
||||
trace_id,
|
||||
total_appearances: 0,
|
||||
avg_confidence: 0.0,
|
||||
path: Vec::new(),
|
||||
});
|
||||
|
||||
trace.total_appearances += 1;
|
||||
trace.path.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
bbox: current_face.bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Assign trace_ids to faces
|
||||
for frame in &mut face_data.frames {
|
||||
for (face_idx, face) in frame.faces.iter_mut().enumerate() {
|
||||
if let Some(&trace_id) = face_trace_ids.get(&(frame.frame, face_idx)) {
|
||||
face.trace_id = Some(trace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for trace in traces.values_mut() {
|
||||
if !trace.path.is_empty() {
|
||||
let sum: f32 = trace.path.iter().map(|p| p.confidence).sum();
|
||||
trace.avg_confidence = sum / trace.path.len() as f32;
|
||||
}
|
||||
}
|
||||
|
||||
if min_trace_len > 0 || min_confidence > 0.0 {
|
||||
traces.retain(|_, trace| {
|
||||
trace.total_appearances >= min_trace_len
|
||||
&& (min_confidence == 0.0 || trace.avg_confidence >= min_confidence)
|
||||
});
|
||||
}
|
||||
|
||||
Ok(traces)
|
||||
}
|
||||
|
||||
fn calculate_bbox_distance(bbox1: &BBox, bbox2: &BBox) -> f64 {
|
||||
let cx1 = bbox1.x as f64 + bbox1.width as f64 / 2.0;
|
||||
let cy1 = bbox1.y as f64 + bbox1.height as f64 / 2.0;
|
||||
let cx2 = bbox2.x as f64 + bbox2.width as f64 / 2.0;
|
||||
let cy2 = bbox2.y as f64 + bbox2.height as f64 / 2.0;
|
||||
|
||||
((cx1 - cx2).powi(2) + (cy1 - cy2).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
fn calculate_cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
|
||||
if a.len() != b.len() || a.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let dot: f64 = a.iter().zip(b).map(|(x, y)| x * y).sum();
|
||||
let na: f64 = a.iter().map(|x| x * x).sum::<f64>().sqrt();
|
||||
let nb: f64 = b.iter().map(|x| x * x).sum::<f64>().sqrt();
|
||||
if na == 0.0 || nb == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
dot / (na * nb)
|
||||
}
|
||||
}
|
||||
|
||||
/// Scroll all Qdrant `_faces` points (payload + vector) for a file via HTTP.
|
||||
fn load_qdrant_faces(uuid: &str) -> Vec<FacePoint> {
|
||||
let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL);
|
||||
let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY);
|
||||
let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url);
|
||||
|
||||
let mut all_points: Vec<FacePoint> = Vec::new();
|
||||
let mut offset: Option<Value> = None;
|
||||
|
||||
loop {
|
||||
let mut body = json!({
|
||||
"limit": 10000,
|
||||
"with_payload": true,
|
||||
"with_vector": true,
|
||||
"filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]},
|
||||
});
|
||||
if let Some(ref off) = offset {
|
||||
body["offset"] = off.clone();
|
||||
}
|
||||
|
||||
let resp = ureq::post(&scroll_url)
|
||||
.set("api-key", &qdrant_api_key)
|
||||
.timeout(Duration::from_secs(60))
|
||||
.send_json(body);
|
||||
|
||||
match resp {
|
||||
Ok(r) => {
|
||||
let data: Value = r.into_json().unwrap_or(Value::Null);
|
||||
let points = data
|
||||
.pointer("/result/points")
|
||||
.and_then(|p| p.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
for p in points {
|
||||
let payload = p.get("payload").cloned().unwrap_or(Value::Null);
|
||||
let vector = p
|
||||
.get("vector")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|v| {
|
||||
v.iter()
|
||||
.filter_map(|x| x.as_f64())
|
||||
.collect::<Vec<f64>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
all_points.push(FacePoint { payload, vector });
|
||||
}
|
||||
|
||||
let next = data.pointer("/result/next_page_offset").cloned();
|
||||
match next {
|
||||
Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)),
|
||||
Some(Value::Number(_)) => break,
|
||||
Some(Value::Null) | None => break,
|
||||
other => {
|
||||
offset = other;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[TRACE] Qdrant scroll error: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("[TRACE] Loaded {} points from Qdrant _faces", all_points.len());
|
||||
all_points
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
use clap::Parser;
|
||||
use anyhow::Result;
|
||||
use serde_json::json;
|
||||
use std::time::Instant;
|
||||
|
||||
use rust_processors::vad::{SileroVad, AudioReader, SpeechSegment};
|
||||
use rust_processors::vad::segment::SegmentCollector;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_vad")]
|
||||
#[command(about = "Silero VAD ONNX (Rust implementation)")]
|
||||
struct Cli {
|
||||
/// Input audio file (WAV 16kHz mono)
|
||||
#[arg(short, long)]
|
||||
audio: String,
|
||||
|
||||
/// ONNX model path
|
||||
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
|
||||
model: String,
|
||||
|
||||
/// Speech probability threshold
|
||||
#[arg(long, default_value = "0.5")]
|
||||
threshold: f32,
|
||||
|
||||
/// Minimum speech duration (milliseconds)
|
||||
#[arg(long, default_value = "500")]
|
||||
min_speech: u32,
|
||||
|
||||
/// Minimum silence duration (milliseconds)
|
||||
#[arg(long, default_value = "300")]
|
||||
min_silence: u32,
|
||||
|
||||
/// Chunk size (samples)
|
||||
#[arg(long, default_value = "512")]
|
||||
chunk_size: usize,
|
||||
|
||||
/// Output format
|
||||
#[arg(long, default_value = "json")]
|
||||
format: String,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
println!("[VAD] Loading model: {}", cli.model);
|
||||
let start_load = Instant::now();
|
||||
let mut vad = SileroVad::new(&cli.model)?;
|
||||
println!("[VAD] Model loaded in {:.2}s", start_load.elapsed().as_secs_f32());
|
||||
|
||||
println!("[VAD] Loading audio: {}", cli.audio);
|
||||
let audio = AudioReader::from_wav(&cli.audio)?;
|
||||
let samples = audio.samples();
|
||||
let sample_rate = audio.sample_rate();
|
||||
let duration = audio.duration();
|
||||
|
||||
println!("[VAD] Audio: {} samples, {} Hz, {:.2}s",
|
||||
samples.len(), sample_rate, duration);
|
||||
|
||||
// 檢測語音
|
||||
println!("[VAD] Detecting speech...");
|
||||
let start_detect = Instant::now();
|
||||
|
||||
let mut collector = SegmentCollector::new(
|
||||
cli.threshold,
|
||||
cli.min_speech,
|
||||
cli.min_silence
|
||||
);
|
||||
|
||||
// 分塊處理
|
||||
for i in (0..samples.len()).step_by(cli.chunk_size) {
|
||||
let end = (i + cli.chunk_size).min(samples.len());
|
||||
let chunk = &samples[i..end];
|
||||
|
||||
// 如果塊太小,填充零
|
||||
let mut chunk_vec = chunk.to_vec();
|
||||
if chunk_vec.len() < cli.chunk_size {
|
||||
chunk_vec.resize(cli.chunk_size, 0.0);
|
||||
}
|
||||
|
||||
// 檢測
|
||||
let speech_prob = vad.detect(&chunk_vec)?;
|
||||
|
||||
// 時間戳
|
||||
let timestamp = i as f32 / sample_rate as f32;
|
||||
|
||||
// 收集片段
|
||||
collector.process(timestamp, speech_prob);
|
||||
}
|
||||
|
||||
// 結束處理
|
||||
let end_timestamp = samples.len() as f32 / sample_rate as f32;
|
||||
collector.finalize(end_timestamp);
|
||||
|
||||
let segments = collector.segments();
|
||||
let detect_time = start_detect.elapsed().as_secs_f32();
|
||||
|
||||
println!("[VAD] Detection completed in {:.2}s", detect_time);
|
||||
println!("[VAD] Found {} speech segments", segments.len());
|
||||
|
||||
// 計算統計
|
||||
let total_speech: f32 = segments.iter().map(|s| s.duration()).sum();
|
||||
let speech_ratio = total_speech / duration;
|
||||
|
||||
println!("[VAD] Total speech: {:.2}s ({:.1}%)", total_speech, speech_ratio * 100.0);
|
||||
println!("[VAD] Processing speed: {:.2}x real-time", duration / detect_time);
|
||||
|
||||
// 輸出結果
|
||||
match cli.format.as_str() {
|
||||
"json" => {
|
||||
let output = json!({
|
||||
"audio_file": cli.audio,
|
||||
"sample_rate": sample_rate,
|
||||
"duration": duration,
|
||||
"segments": segments.iter().map(|s| json!({
|
||||
"start": s.start_sec,
|
||||
"end": s.end_sec,
|
||||
"duration": s.duration()
|
||||
})).collect::<Vec<_>>(),
|
||||
"statistics": {
|
||||
"segment_count": segments.len(),
|
||||
"total_speech": total_speech,
|
||||
"speech_ratio": speech_ratio,
|
||||
"detect_time": detect_time
|
||||
}
|
||||
});
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
}
|
||||
"text" => {
|
||||
for seg in segments {
|
||||
println!("{:.2} - {:.2} ({:.2}s)",
|
||||
seg.start_sec, seg.end_sec, seg.duration());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
anyhow::bail!("Unknown output format: {}", cli.format);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use clap::Parser;
|
||||
use anyhow::{Context, Result};
|
||||
use serde_json::json;
|
||||
use std::time::Instant;
|
||||
|
||||
use whisper_rs::{WhisperContext, WhisperContextParameters, FullParams, SamplingStrategy};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_whisper_rs")]
|
||||
#[command(about = "Whisper ASR using whisper-rs (whisper.cpp bindings)")]
|
||||
struct Cli {
|
||||
/// Input audio file (WAV 16kHz mono)
|
||||
#[arg(short, long)]
|
||||
input: String,
|
||||
|
||||
/// Output JSON file
|
||||
#[arg(short, long)]
|
||||
output: Option<String>,
|
||||
|
||||
/// Whisper model path
|
||||
#[arg(long, default_value = "/Users/accusys/models/ggml-tiny.bin")]
|
||||
model: String,
|
||||
|
||||
/// Language (auto-detect if not specified)
|
||||
#[arg(short, long)]
|
||||
language: Option<String>,
|
||||
|
||||
/// Number of threads
|
||||
#[arg(long, default_value = "4")]
|
||||
threads: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Segment {
|
||||
start: f64,
|
||||
end: f64,
|
||||
text: String,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
println!("[Whisper-RS] Starting...");
|
||||
let start_total = Instant::now();
|
||||
|
||||
// Step 1: Load model
|
||||
println!("[1/3] Loading model: {}", cli.model);
|
||||
let load_start = Instant::now();
|
||||
|
||||
let mut params = WhisperContextParameters::default();
|
||||
params.use_gpu = true;
|
||||
|
||||
let ctx = WhisperContext::new_with_params(&cli.model, params)
|
||||
.context("Failed to load Whisper model")?;
|
||||
|
||||
println!("[Whisper-RS] Model loaded in {:.2}s", load_start.elapsed().as_secs_f32());
|
||||
|
||||
// Step 2: Load audio
|
||||
println!("[2/3] Loading audio: {}", cli.input);
|
||||
let audio_start = Instant::now();
|
||||
|
||||
let audio = hound::WavReader::open(&cli.input)
|
||||
.context("Failed to read WAV file")?;
|
||||
let samples: Vec<f32> = audio.into_samples::<i16>()
|
||||
.filter_map(|s| s.ok())
|
||||
.map(|s| s as f32 / 32768.0)
|
||||
.collect();
|
||||
|
||||
println!("[Whisper-RS] Audio loaded: {} samples", samples.len());
|
||||
println!("[Whisper-RS] Audio load time: {:.2}s", audio_start.elapsed().as_secs_f32());
|
||||
|
||||
// Step 3: Transcribe
|
||||
println!("[3/3] Transcribing...");
|
||||
let transcribe_start = Instant::now();
|
||||
|
||||
let mut state = ctx.create_state()
|
||||
.context("Failed to create Whisper state")?;
|
||||
|
||||
let mut full_params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 });
|
||||
full_params.set_n_threads(cli.threads);
|
||||
|
||||
if let Some(ref lang) = cli.language {
|
||||
full_params.set_language(Some(lang));
|
||||
}
|
||||
|
||||
state.full(full_params, &samples)
|
||||
.context("Failed to transcribe audio")?;
|
||||
|
||||
// Extract segments
|
||||
let num_segments = state.full_n_segments();
|
||||
let mut segments: Vec<Segment> = Vec::new();
|
||||
|
||||
for i in 0..num_segments {
|
||||
let seg = state.get_segment(i).expect("Failed to get segment");
|
||||
segments.push(Segment {
|
||||
start: seg.start_timestamp() as f64 / 100.0,
|
||||
end: seg.end_timestamp() as f64 / 100.0,
|
||||
text: seg.to_str().unwrap_or("").to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let transcribe_time = transcribe_start.elapsed().as_secs_f32();
|
||||
println!("[Whisper-RS] Transcribed {} segments in {:.2}s", segments.len(), transcribe_time);
|
||||
|
||||
// Output
|
||||
let output = json!({
|
||||
"processor": "whisper-rs",
|
||||
"model": cli.model,
|
||||
"segments": segments.iter().enumerate().map(|(i, seg)| json!({
|
||||
"id": i,
|
||||
"start": seg.start,
|
||||
"end": seg.end,
|
||||
"text": seg.text,
|
||||
})).collect::<Vec<_>>(),
|
||||
"processing_time": {
|
||||
"load": load_start.elapsed().as_secs_f64(),
|
||||
"transcribe": transcribe_time as f64,
|
||||
"total": start_total.elapsed().as_secs_f64()
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(ref output_path) = cli.output {
|
||||
std::fs::write(output_path, serde_json::to_string_pretty(&output)?)?;
|
||||
println!("[Whisper-RS] Output: {}", output_path);
|
||||
} else {
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
}
|
||||
|
||||
println!("[Whisper-RS] Done in {:.2}s", start_total.elapsed().as_secs_f32());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, ImageBuffer, imageops};
|
||||
use crate::face_processor::BBox;
|
||||
|
||||
pub struct FaceCropper;
|
||||
|
||||
impl FaceCropper {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
pub fn crop(&self, frame: &RgbImage, bbox: &BBox) -> Result<RgbImage> {
|
||||
let width = frame.width() as i32;
|
||||
let height = frame.height() as i32;
|
||||
|
||||
// Clamp bbox to frame boundaries
|
||||
let x = bbox.x.max(0).min(width - 1) as u32;
|
||||
let y = bbox.y.max(0).min(height - 1) as u32;
|
||||
let w = bbox.width.max(1).min(width - x as i32) as u32;
|
||||
let h = bbox.height.max(1).min(height - y as i32) as u32;
|
||||
|
||||
// Crop face
|
||||
let cropped = imageops::crop(frame, x, y, w, h).to_image();
|
||||
|
||||
Ok(cropped)
|
||||
}
|
||||
|
||||
pub fn resize_to_160(&self, face: &RgbImage) -> Result<RgbImage> {
|
||||
let resized = imageops::resize(
|
||||
face,
|
||||
160,
|
||||
160,
|
||||
imageops::FilterType::Lanczos3,
|
||||
);
|
||||
|
||||
Ok(resized)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use serde::Deserialize;
|
||||
use crate::face_processor::FaceDetection;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftDetection {
|
||||
frames: Vec<SwiftFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftFrame {
|
||||
frame: usize,
|
||||
timestamp: f64,
|
||||
faces: Vec<SwiftFace>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftFace {
|
||||
bbox: SwiftBBox,
|
||||
confidence: f64,
|
||||
#[serde(rename = "captureQuality")]
|
||||
capture_quality: Option<i32>,
|
||||
pose: Option<SwiftPose>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftBBox {
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftPose {
|
||||
roll: f64,
|
||||
yaw: f64,
|
||||
pitch: f64,
|
||||
}
|
||||
|
||||
pub struct FaceDetector {
|
||||
swift_binary: String,
|
||||
}
|
||||
|
||||
impl FaceDetector {
|
||||
pub fn new() -> Result<Self> {
|
||||
let swift_binary = Self::find_swift_binary()?;
|
||||
Ok(Self { swift_binary })
|
||||
}
|
||||
|
||||
fn find_swift_binary() -> Result<String> {
|
||||
// Try release build first
|
||||
let release = "scripts/swift_processors/.build/release/swift_face";
|
||||
if Path::new(release).exists() {
|
||||
return Ok(release.to_string());
|
||||
}
|
||||
|
||||
// Try debug build
|
||||
let debug = "scripts/swift_processors/.build/debug/swift_face";
|
||||
if Path::new(debug).exists() {
|
||||
return Ok(debug.to_string());
|
||||
}
|
||||
|
||||
anyhow::bail!("Swift face binary not found")
|
||||
}
|
||||
|
||||
pub fn detect(&self, video_path: &Path, output_path: &Path, sample_interval: usize) -> Result<Vec<FaceDetection>> {
|
||||
println!("[DETECTION] Running Swift face detection...");
|
||||
|
||||
let output = Command::new(&self.swift_binary)
|
||||
.arg(video_path)
|
||||
.arg(output_path)
|
||||
.arg("--sample-interval")
|
||||
.arg(sample_interval.to_string())
|
||||
.output()
|
||||
.context("Failed to run Swift face detection")?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!("Swift face detection failed: {:?}", output.stderr);
|
||||
}
|
||||
|
||||
// Parse output JSON
|
||||
let detection: SwiftDetection = serde_json::from_slice(&output.stdout)
|
||||
.context("Failed to parse Swift detection output")?;
|
||||
|
||||
// Convert to our format
|
||||
let faces: Vec<FaceDetection> = detection.frames.into_iter().flat_map(|frame| {
|
||||
frame.faces.into_iter().map(|face| {
|
||||
FaceDetection {
|
||||
frame: frame.frame,
|
||||
timestamp: frame.timestamp,
|
||||
bbox: crate::face_processor::BBox {
|
||||
x: face.bbox.x,
|
||||
y: face.bbox.y,
|
||||
width: face.bbox.width,
|
||||
height: face.bbox.height,
|
||||
},
|
||||
confidence: face.confidence,
|
||||
capture_quality: face.capture_quality,
|
||||
pose: face.pose.map(|p| crate::face_processor::PoseInfo {
|
||||
roll: p.roll,
|
||||
yaw: p.yaw,
|
||||
pitch: p.pitch,
|
||||
}),
|
||||
}
|
||||
}).collect::<Vec<_>>()
|
||||
}).collect();
|
||||
|
||||
println!("[DETECTION] Found {} faces", faces.len());
|
||||
|
||||
Ok(faces)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, imageops};
|
||||
use ndarray::IxDyn;
|
||||
use ort::{session::Session, value::Value};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct EmbeddingExtractor {
|
||||
session: Session,
|
||||
}
|
||||
|
||||
impl EmbeddingExtractor {
|
||||
pub fn new(model_path: &Path) -> Result<Self> {
|
||||
println!("[EMBEDDING] Loading model: {:?}", model_path);
|
||||
|
||||
let session = Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?;
|
||||
|
||||
println!("[EMBEDDING] Model loaded successfully");
|
||||
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
pub fn extract(&mut self, face: &RgbImage) -> Result<Vec<f32>> {
|
||||
// Preprocess: resize to 160x160 and normalize to [-1, 1]
|
||||
let resized = imageops::resize(
|
||||
face,
|
||||
160,
|
||||
160,
|
||||
imageops::FilterType::Lanczos3,
|
||||
);
|
||||
|
||||
// Convert to normalized tensor
|
||||
let mut input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, 3, 160, 160]),
|
||||
vec![0.0f32; 1 * 3 * 160 * 160]
|
||||
).context("Failed to create input array")?;
|
||||
|
||||
for (x, y, pixel) in resized.enumerate_pixels() {
|
||||
let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32);
|
||||
input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0;
|
||||
input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0;
|
||||
input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0;
|
||||
}
|
||||
|
||||
// Create input value
|
||||
let input_value = Value::from_array(input_array)
|
||||
.context("Failed to create input value")?;
|
||||
|
||||
let inputs = ort::inputs!["input" => input_value];
|
||||
|
||||
// Run inference
|
||||
let outputs = self.session.run(inputs)
|
||||
.context("Failed to run inference")?;
|
||||
|
||||
// Extract output
|
||||
let output = outputs["output"].try_extract_tensor::<f32>()
|
||||
.context("Failed to extract output tensor")?;
|
||||
|
||||
let output_data = output.1;
|
||||
let embedding = output_data.to_vec();
|
||||
|
||||
Ok(embedding)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
pub mod types;
|
||||
pub mod video;
|
||||
pub mod detection;
|
||||
pub mod crop;
|
||||
pub mod embedding;
|
||||
|
||||
pub use types::*;
|
||||
pub use video::VideoReader;
|
||||
pub use detection::FaceDetector;
|
||||
pub use crop::FaceCropper;
|
||||
pub use embedding::EmbeddingExtractor;
|
||||
@@ -0,0 +1,78 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BBox {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceDetection {
|
||||
pub frame: usize,
|
||||
pub timestamp: f64,
|
||||
pub bbox: BBox,
|
||||
pub confidence: f64,
|
||||
pub capture_quality: Option<i32>,
|
||||
pub pose: Option<PoseInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PoseInfo {
|
||||
pub roll: f64,
|
||||
pub yaw: f64,
|
||||
pub pitch: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceEmbedding {
|
||||
pub frame: usize,
|
||||
pub trace_id: usize,
|
||||
pub bbox: BBox,
|
||||
pub confidence: f64,
|
||||
pub embedding: Vec<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FaceOutput {
|
||||
pub status: String,
|
||||
pub frame_count: usize,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<FrameData>,
|
||||
pub total_faces: usize,
|
||||
pub metadata: Metadata,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FrameData {
|
||||
pub frame: usize,
|
||||
pub timestamp: f64,
|
||||
pub faces: Vec<FaceInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FaceInfo {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub confidence: f64,
|
||||
pub capture_quality: Option<f64>,
|
||||
pub pose_angle: Option<PoseAngle>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct PoseAngle {
|
||||
pub angle: String,
|
||||
pub roll: f64,
|
||||
pub yaw: f64,
|
||||
pub pitch: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Metadata {
|
||||
pub embedding_method: String,
|
||||
pub embedding_model: String,
|
||||
pub total_embeddings: usize,
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
use anyhow::{Context, Result};
|
||||
use ffmpeg_next as ffmpeg;
|
||||
use image::{RgbImage, ImageBuffer};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct VideoReader {
|
||||
decoder: ffmpeg::decoder::Video,
|
||||
scaler: ffmpeg::software::scaling::Context,
|
||||
frame_count: usize,
|
||||
fps: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
impl VideoReader {
|
||||
pub fn new(video_path: &Path) -> Result<Self> {
|
||||
ffmpeg::init().context("Failed to initialize FFmpeg")?;
|
||||
|
||||
let input = ffmpeg::format::input(video_path)
|
||||
.context("Failed to open video file")?;
|
||||
|
||||
let video_stream = input
|
||||
.streams()
|
||||
.best(ffmpeg::media::Type::Video)
|
||||
.context("No video stream found")?;
|
||||
|
||||
let stream_index = video_stream.index();
|
||||
let fps = video_stream.avg_frame_rate().numerator() as f64
|
||||
/ video_stream.avg_frame_rate().denominator() as f64;
|
||||
let frame_count = video_stream.frames() as usize;
|
||||
|
||||
let context_decoder = ffmpeg::codec::context::Context::from_parameters(
|
||||
video_stream.parameters()
|
||||
)?;
|
||||
|
||||
let decoder = context_decoder
|
||||
.decoder()
|
||||
.video()
|
||||
.context("Failed to get video decoder")?;
|
||||
|
||||
let width = decoder.width();
|
||||
let height = decoder.height();
|
||||
|
||||
let scaler = ffmpeg::software::scaling::Context::get(
|
||||
decoder.format(),
|
||||
width,
|
||||
height,
|
||||
ffmpeg::format::pixel::Pixel::RGB24,
|
||||
width,
|
||||
height,
|
||||
ffmpeg::software::scaling::Flags::BILINEAR,
|
||||
)?;
|
||||
|
||||
Ok(Self {
|
||||
decoder,
|
||||
scaler,
|
||||
frame_count,
|
||||
fps,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fps(&self) -> f64 {
|
||||
self.fps
|
||||
}
|
||||
|
||||
pub fn frame_count(&self) -> usize {
|
||||
self.frame_count
|
||||
}
|
||||
|
||||
pub fn width(&self) -> u32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
pub fn height(&self) -> u32 {
|
||||
self.height
|
||||
}
|
||||
|
||||
pub fn read_frame(&mut self, frame_num: usize) -> Result<Option<RgbImage>> {
|
||||
// Seek to frame
|
||||
let seek_time = frame_num as f64 / self.fps;
|
||||
self.decoder.set_position(seek_time as i64)?;
|
||||
|
||||
// Read and decode frame
|
||||
let mut frame = ffmpeg::util::frame::Video::empty();
|
||||
let mut rgb_frame = ffmpeg::util::frame::Video::empty();
|
||||
|
||||
self.decoder.receive_frame(&mut frame)?;
|
||||
self.scaler.run(&frame, &mut rgb_frame)?;
|
||||
|
||||
// Convert to image::RgbImage
|
||||
let data = rgb_frame.data(0);
|
||||
let linesize = rgb_frame.stride(0);
|
||||
|
||||
let mut img_data = Vec::with_capacity((self.width * self.height * 3) as usize);
|
||||
|
||||
for y in 0..self.height {
|
||||
let offset = (y * linesize) as usize;
|
||||
let row = &data[offset..offset + (self.width * 3) as usize];
|
||||
img_data.extend_from_slice(row);
|
||||
}
|
||||
|
||||
let img = ImageBuffer::from_raw(self.width, self.height, img_data)
|
||||
.context("Failed to create image buffer")?;
|
||||
|
||||
Ok(Some(img))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod asrx;
|
||||
pub mod vad;
|
||||
@@ -0,0 +1,39 @@
|
||||
use anyhow::{Context, Result};
|
||||
use hound::WavReader;
|
||||
|
||||
pub struct AudioReader {
|
||||
samples: Vec<f32>,
|
||||
sample_rate: u32,
|
||||
}
|
||||
|
||||
impl AudioReader {
|
||||
pub fn from_wav(path: &str) -> Result<Self> {
|
||||
let reader = WavReader::open(path).context("Failed to open WAV file")?;
|
||||
|
||||
let spec = reader.spec();
|
||||
let sample_rate = spec.sample_rate;
|
||||
|
||||
// 轉換為 f32,範圍 [-1.0, 1.0]
|
||||
let samples: Vec<f32> = reader
|
||||
.into_samples::<i16>()
|
||||
.map(|s| s.map(|v| v as f32 / 32768.0).unwrap_or(0.0))
|
||||
.collect();
|
||||
|
||||
Ok(Self {
|
||||
samples,
|
||||
sample_rate,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn samples(&self) -> &[f32] {
|
||||
&self.samples
|
||||
}
|
||||
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
pub fn duration(&self) -> f32 {
|
||||
self.samples.len() as f32 / self.sample_rate as f32
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod audio;
|
||||
pub mod onnx;
|
||||
pub mod segment;
|
||||
|
||||
pub use audio::AudioReader;
|
||||
pub use onnx::SileroVad;
|
||||
pub use segment::SpeechSegment;
|
||||
@@ -0,0 +1,101 @@
|
||||
use anyhow::{Context, Result};
|
||||
use ndarray::IxDyn;
|
||||
use ort::session::{builder::GraphOptimizationLevel, Session};
|
||||
use ort::value::Value;
|
||||
|
||||
pub struct SileroVad {
|
||||
session: Session,
|
||||
state: Vec<f32>, // [2, 1, 128] = 256 elements
|
||||
context: Vec<f32>, // [1, 64] for 16kHz
|
||||
sample_rate: i64,
|
||||
context_size: usize, // 64 for 16kHz, 32 for 8kHz
|
||||
}
|
||||
|
||||
impl SileroVad {
|
||||
pub fn new(model_path: &str) -> Result<Self> {
|
||||
let session = Session::builder()?
|
||||
.with_optimization_level(GraphOptimizationLevel::Level1)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))?
|
||||
.commit_from_file(model_path)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to load model: {}", e))?;
|
||||
|
||||
let sample_rate = 16000;
|
||||
let context_size = if sample_rate == 16000 { 64 } else { 32 };
|
||||
|
||||
Ok(Self {
|
||||
session,
|
||||
state: vec![0.0; 256], // [2, 1, 128] = 256
|
||||
context: vec![0.0; context_size], // [1, 64]
|
||||
sample_rate,
|
||||
context_size,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn detect(&mut self, audio_chunk: &[f32]) -> Result<f32> {
|
||||
// 拼接 context 和當前塊
|
||||
let mut input_with_context = Vec::with_capacity(self.context_size + audio_chunk.len());
|
||||
input_with_context.extend_from_slice(&self.context);
|
||||
input_with_context.extend_from_slice(audio_chunk);
|
||||
|
||||
// 準備輸入
|
||||
let input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, input_with_context.len()]),
|
||||
input_with_context.clone(),
|
||||
)
|
||||
.context("Failed to create input array")?;
|
||||
|
||||
let state_array = ndarray::Array::from_shape_vec(IxDyn(&[2, 1, 128]), self.state.clone())
|
||||
.context("Failed to create state array")?;
|
||||
|
||||
let sr_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[]), // 標量
|
||||
vec![self.sample_rate],
|
||||
)
|
||||
.context("Failed to create sr array")?;
|
||||
|
||||
// 創建 ONNX Value
|
||||
let input_value = Value::from_array(input_array).context("Failed to create input value")?;
|
||||
let state_value = Value::from_array(state_array).context("Failed to create state value")?;
|
||||
let sr_value = Value::from_array(sr_array).context("Failed to create sr value")?;
|
||||
|
||||
// 運行推理
|
||||
let inputs = ort::inputs![
|
||||
"input" => input_value,
|
||||
"state" => state_value,
|
||||
"sr" => sr_value,
|
||||
];
|
||||
|
||||
let outputs = self
|
||||
.session
|
||||
.run(inputs)
|
||||
.context("Failed to run inference")?;
|
||||
|
||||
// 提取輸出
|
||||
let output = outputs["output"]
|
||||
.try_extract_tensor::<f32>()
|
||||
.context("Failed to extract output")?;
|
||||
|
||||
// output 是 (&Shape, &[f32]) tuple
|
||||
let output_data = output.1;
|
||||
let speech_prob = output_data[0];
|
||||
|
||||
// 更新隱藏狀態
|
||||
let state_n = outputs["stateN"]
|
||||
.try_extract_tensor::<f32>()
|
||||
.context("Failed to extract stateN")?;
|
||||
|
||||
// state_n 是 (&Shape, &[f32]) tuple
|
||||
let state_data = state_n.1;
|
||||
self.state = state_data.to_vec();
|
||||
|
||||
// 更新 context(當前輸入的最後 context_size 個樣本)
|
||||
self.context = input_with_context[input_with_context.len() - self.context_size..].to_vec();
|
||||
|
||||
Ok(speech_prob)
|
||||
}
|
||||
|
||||
pub fn reset_state(&mut self) {
|
||||
self.state = vec![0.0; 256];
|
||||
self.context = vec![0.0; self.context_size];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SpeechSegment {
|
||||
pub start_sec: f32,
|
||||
pub end_sec: f32,
|
||||
}
|
||||
|
||||
impl SpeechSegment {
|
||||
pub fn new(start_sec: f32, end_sec: f32) -> Self {
|
||||
Self { start_sec, end_sec }
|
||||
}
|
||||
|
||||
pub fn duration(&self) -> f32 {
|
||||
self.end_sec - self.start_sec
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SegmentCollector {
|
||||
segments: Vec<SpeechSegment>,
|
||||
current_start: Option<f32>,
|
||||
threshold: f32,
|
||||
min_speech_duration: f32,
|
||||
min_silence_duration: f32,
|
||||
silence_start: Option<f32>,
|
||||
}
|
||||
|
||||
impl SegmentCollector {
|
||||
pub fn new(threshold: f32, min_speech_ms: u32, min_silence_ms: u32) -> Self {
|
||||
Self {
|
||||
segments: Vec::new(),
|
||||
current_start: None,
|
||||
threshold,
|
||||
min_speech_duration: min_speech_ms as f32 / 1000.0,
|
||||
min_silence_duration: min_silence_ms as f32 / 1000.0,
|
||||
silence_start: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn process(&mut self, timestamp: f32, speech_prob: f32) {
|
||||
if speech_prob >= self.threshold {
|
||||
// 語音
|
||||
if self.current_start.is_none() {
|
||||
self.current_start = Some(timestamp);
|
||||
}
|
||||
self.silence_start = None;
|
||||
} else {
|
||||
// 靜音
|
||||
if self.current_start.is_some() {
|
||||
if self.silence_start.is_none() {
|
||||
self.silence_start = Some(timestamp);
|
||||
}
|
||||
|
||||
// 檢查是否結束語音段
|
||||
if let Some(silence_start) = self.silence_start {
|
||||
let silence_duration = timestamp - silence_start;
|
||||
if silence_duration >= self.min_silence_duration {
|
||||
// 結束語音段
|
||||
if let Some(start) = self.current_start {
|
||||
let duration = silence_start - start;
|
||||
if duration >= self.min_speech_duration {
|
||||
self.segments.push(SpeechSegment::new(start, silence_start));
|
||||
}
|
||||
}
|
||||
self.current_start = None;
|
||||
self.silence_start = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finalize(&mut self, end_timestamp: f32) {
|
||||
// 處理最後一個段
|
||||
if let Some(start) = self.current_start {
|
||||
let duration = end_timestamp - start;
|
||||
if duration >= self.min_speech_duration {
|
||||
self.segments.push(SpeechSegment::new(start, end_timestamp));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn segments(&self) -> &[SpeechSegment] {
|
||||
&self.segments
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
可能的 features:
|
||||
- coreml
|
||||
- load-dynamic
|
||||
- download-binaries
|
||||
- tracing
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "swift-argument-parser",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-argument-parser.git",
|
||||
"state" : {
|
||||
"revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382",
|
||||
"version" : "1.8.2"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// swift-tools-version:5.9
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "swift_processors",
|
||||
platforms: [.macOS(.v12)],
|
||||
products: [
|
||||
.executable(name: "swift_scene_detector", targets: ["swift_scene_detector"]),
|
||||
.executable(name: "swift_face", targets: ["swift_face"]),
|
||||
.executable(name: "swift_ocr", targets: ["swift_ocr"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.0"),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "swift_scene_detector",
|
||||
path: "Sources/swift_scene_detector"
|
||||
),
|
||||
.executableTarget(
|
||||
name: "swift_face",
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
path: "Sources/swift_face"
|
||||
),
|
||||
.executableTarget(
|
||||
name: "swift_ocr",
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
path: "Sources/swift_ocr"
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,423 @@
|
||||
import Foundation
|
||||
import Vision
|
||||
import ArgumentParser
|
||||
import AVFoundation
|
||||
|
||||
/// Calculate capture quality based on face size and confidence
|
||||
/// Returns a score between 0.0 and 1.0
|
||||
func calculateFallbackCaptureQuality(
|
||||
faceWidth: Int,
|
||||
faceHeight: Int,
|
||||
imageWidth: Int,
|
||||
imageHeight: Int,
|
||||
confidence: Double
|
||||
) -> Double {
|
||||
// Face size relative to image (larger faces = better quality)
|
||||
let faceArea = Double(faceWidth * faceHeight)
|
||||
let imageArea = Double(imageWidth * imageHeight)
|
||||
let relativeSize = min(1.0, faceArea / (imageArea * 0.25)) // Normalize to max 25% of image
|
||||
|
||||
// Combine confidence and size (50% weight each)
|
||||
let quality = (confidence * 0.5) + (relativeSize * 0.5)
|
||||
|
||||
return min(1.0, max(0.0, quality))
|
||||
}
|
||||
|
||||
/// Swift Face Processor - Apple Vision Framework for face detection + pose
|
||||
/// Uses AVAssetImageGenerator for reliable frame access (no AVAssetReader corruption).
|
||||
@main
|
||||
struct SwiftFace: ParsableCommand {
|
||||
@Argument(help: "Video file path")
|
||||
var inputPath: String
|
||||
|
||||
@Argument(help: "Output JSON path")
|
||||
var outputPath: String
|
||||
|
||||
@Option(name: .long, help: "Sample interval (frames, default=3)")
|
||||
var sampleInterval: Int = 3
|
||||
|
||||
@Option(name: .long, help: "UUID for logging")
|
||||
var uuid: String = ""
|
||||
|
||||
mutating func run() throws {
|
||||
let startTime = Date()
|
||||
print("[SwiftFace] Vision-based face detection: \(inputPath)")
|
||||
|
||||
let url = URL(fileURLWithPath: inputPath)
|
||||
let asset = AVAsset(url: url)
|
||||
|
||||
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
|
||||
print("[SwiftFace] No video track found")
|
||||
return
|
||||
}
|
||||
|
||||
let fps = videoTrack.nominalFrameRate
|
||||
let duration = CMTimeGetSeconds(asset.duration)
|
||||
let totalFrames = Int(duration * Double(fps))
|
||||
let width = Int(videoTrack.naturalSize.width)
|
||||
let height = Int(videoTrack.naturalSize.height)
|
||||
print("[SwiftFace] Video: \(width)x\(height), \(String(format: "%.1f", fps))fps, \(totalFrames) frames")
|
||||
|
||||
// Read face detection settings from environment variables (with defaults)
|
||||
// Keep in sync with src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT
|
||||
let MIN_CONFIDENCE = Double(ProcessInfo.processInfo.environment["FACE_MIN_CONFIDENCE"] ?? "0.5") ?? 0.5
|
||||
let MIN_SIZE = Int(ProcessInfo.processInfo.environment["FACE_MIN_SIZE"] ?? "1") ?? 1
|
||||
print("[SwiftFace] Settings: MIN_CONFIDENCE=\(MIN_CONFIDENCE), MIN_SIZE=\(MIN_SIZE)")
|
||||
|
||||
let generator = AVAssetImageGenerator(asset: asset)
|
||||
generator.requestedTimeToleranceBefore = .zero
|
||||
generator.requestedTimeToleranceAfter = .zero
|
||||
generator.appliesPreferredTrackTransform = true
|
||||
|
||||
var allFrames: [[String: Any]] = []
|
||||
var processedCount = 0
|
||||
var checkedCount = 0
|
||||
|
||||
let frameInterval = TimeInterval(sampleInterval) / Double(fps)
|
||||
|
||||
// Process in batches of 1000 frames to avoid memory pressure
|
||||
let batchSize = 1000
|
||||
let totalSamples = totalFrames / sampleInterval
|
||||
|
||||
for batchStart in stride(from: 0, to: totalSamples, by: batchSize) {
|
||||
let batchEnd = min(batchStart + batchSize, totalSamples)
|
||||
var times: [NSValue] = []
|
||||
|
||||
for i in batchStart..<batchEnd {
|
||||
let seconds = Double(i) * frameInterval
|
||||
let cmTime = CMTime(seconds: seconds, preferredTimescale: 1000)
|
||||
times.append(NSValue(time: cmTime))
|
||||
}
|
||||
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var batchError: Error? = nil
|
||||
|
||||
generator.generateCGImagesAsynchronously(forTimes: times) { requestedTime, cgImage, actualTime, result, error in
|
||||
defer { semaphore.signal() }
|
||||
|
||||
checkedCount += 1
|
||||
|
||||
guard result == .succeeded, let cgImage = cgImage else {
|
||||
if let error = error {
|
||||
fputs("[SwiftFace] Frame error at \(CMTimeGetSeconds(requestedTime)): \(error.localizedDescription)\n", stderr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Convert CGImage to CVPixelBuffer for Vision
|
||||
var pixelBuffer: CVPixelBuffer?
|
||||
let attrs: [CFString: Any] = [
|
||||
kCVPixelBufferCGImageCompatibilityKey: true,
|
||||
kCVPixelBufferCGBitmapContextCompatibilityKey: true,
|
||||
kCVPixelBufferWidthKey: cgImage.width,
|
||||
kCVPixelBufferHeightKey: cgImage.height,
|
||||
]
|
||||
CVPixelBufferCreate(kCFAllocatorDefault, cgImage.width, cgImage.height,
|
||||
kCVPixelFormatType_32BGRA, attrs as CFDictionary, &pixelBuffer)
|
||||
|
||||
guard let pb = pixelBuffer else { return }
|
||||
|
||||
CVPixelBufferLockBaseAddress(pb, [])
|
||||
defer { CVPixelBufferUnlockBaseAddress(pb, []) }
|
||||
|
||||
let context = CGContext(data: CVPixelBufferGetBaseAddress(pb),
|
||||
width: cgImage.width, height: cgImage.height,
|
||||
bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pb),
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)!
|
||||
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height))
|
||||
|
||||
let handler = VNImageRequestHandler(cvPixelBuffer: pb, options: [:])
|
||||
let detectReq = VNDetectFaceRectanglesRequest()
|
||||
let lmReq = VNDetectFaceLandmarksRequest()
|
||||
let captureQReq = VNDetectFaceCaptureQualityRequest()
|
||||
|
||||
do {
|
||||
try handler.perform([detectReq, lmReq, captureQReq])
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
let faceObservations = detectReq.results ?? []
|
||||
let landmarkObservations = lmReq.results ?? []
|
||||
let captureQualityObs = captureQReq.results ?? []
|
||||
let hasQualityResults = !captureQualityObs.isEmpty
|
||||
guard !faceObservations.isEmpty || !landmarkObservations.isEmpty else {
|
||||
return
|
||||
}
|
||||
|
||||
let seconds = CMTimeGetSeconds(actualTime)
|
||||
let frameNumber = Int((seconds * Double(fps)).rounded())
|
||||
var frameFaces: [[String: Any]] = []
|
||||
|
||||
// Use actual CGImage size (may differ from naturalSize after transform)
|
||||
let imgW = CGFloat(cgImage.width)
|
||||
let imgH = CGFloat(cgImage.height)
|
||||
|
||||
// Process landmark observations FIRST (each has bbox + landmarks, self-consistent)
|
||||
// Quality filtering - uses MIN_CONFIDENCE and MIN_SIZE from outer scope
|
||||
|
||||
for lmObs in landmarkObservations {
|
||||
// Confidence filter
|
||||
let lmConf = Double(lmObs.confidence)
|
||||
if lmConf < MIN_CONFIDENCE { continue }
|
||||
|
||||
let bb = lmObs.boundingBox
|
||||
let faceW = Int(bb.size.width * imgW)
|
||||
let faceH = Int(bb.size.height * imgH)
|
||||
|
||||
// Size filter
|
||||
if faceW < MIN_SIZE || faceH < MIN_SIZE { continue }
|
||||
|
||||
let faceX = Int(bb.origin.x * imgW)
|
||||
let faceY = Int((1.0 - bb.origin.y - bb.size.height) * imgH)
|
||||
|
||||
// Match capture quality request by bbox overlap (landmarks request
|
||||
// results don't populate faceCaptureQuality on macOS)
|
||||
var captureQ = 0.0
|
||||
var bestOverlap: CGFloat = 0
|
||||
for cqObs in captureQualityObs {
|
||||
let cb = cqObs.boundingBox
|
||||
let ix = max(bb.minX, cb.minX)
|
||||
let iy = max(bb.minY, cb.minY)
|
||||
let iw = min(bb.maxX, cb.maxX) - ix
|
||||
let ih = min(bb.maxY, cb.maxY) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let overlap = (iw * ih) / (bb.width * bb.height)
|
||||
if overlap > bestOverlap {
|
||||
bestOverlap = overlap
|
||||
if let cq = cqObs.faceCaptureQuality {
|
||||
captureQ = Double(cq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Calculate quality from size, confidence, pose if API didn't provide it
|
||||
if captureQ == 0.0 {
|
||||
let faceArea = Double(faceW * faceH)
|
||||
let imgArea = Double(imgW * imgH)
|
||||
let sizeScore = min(1.0, (faceArea / imgArea) * 4.0) // Normalize, larger = better
|
||||
let confScore = lmConf // Already 0-1
|
||||
|
||||
// Pose score (frontal = 1.0, profile = 0.0)
|
||||
var poseScore = 1.0
|
||||
if let yaw = lmObs.yaw?.doubleValue {
|
||||
poseScore = max(0.0, 1.0 - abs(yaw) / 90.0)
|
||||
}
|
||||
|
||||
// Weighted combination
|
||||
captureQ = sizeScore * 0.3 + confScore * 0.4 + poseScore * 0.3
|
||||
}
|
||||
|
||||
// Match face observation by bbox to extract faceprint (embedding)
|
||||
var embedding: [Float]? = nil
|
||||
if #available(macOS 14, *) {
|
||||
var matchCount = 0
|
||||
for faceObs in faceObservations {
|
||||
let fBB = faceObs.boundingBox
|
||||
let ix = max(bb.minX, fBB.origin.x)
|
||||
let iy = max(bb.minY, fBB.origin.y)
|
||||
let iw = min(bb.maxX, fBB.origin.x + fBB.width) - ix
|
||||
let ih = min(bb.maxY, fBB.origin.y + fBB.height) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let intersection = iw * ih
|
||||
let union = bb.width * bb.height + fBB.width * fBB.height - intersection
|
||||
if intersection / union > 0.5 {
|
||||
matchCount += 1
|
||||
// Try to extract faceprint
|
||||
if let fp = faceObs.value(forKey: "faceprint") as? NSObject {
|
||||
if let desc = fp.value(forKey: "descriptor") as? NSObject {
|
||||
if let elems = desc.value(forKey: "elements") as? [NSNumber] {
|
||||
embedding = elems.map { Float($0.doubleValue) }
|
||||
} else {
|
||||
print("[DEBUG] No elements in descriptor")
|
||||
}
|
||||
} else {
|
||||
print("[DEBUG] No descriptor in faceprint")
|
||||
}
|
||||
} else {
|
||||
print("[DEBUG] No faceprint in faceObs (frame \(frameNumber), match \(matchCount))")
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var faceData: [String: Any] = [
|
||||
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
||||
"width": faceW, "height": faceH],
|
||||
"confidence": Double(lmObs.confidence),
|
||||
"captureQuality": captureQ,
|
||||
]
|
||||
|
||||
// Add embedding if available
|
||||
if let emb = embedding {
|
||||
faceData["embedding"] = emb
|
||||
}
|
||||
|
||||
// Pose from landmark observation
|
||||
if let yaw = lmObs.yaw?.doubleValue,
|
||||
let roll = lmObs.roll?.doubleValue {
|
||||
var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw]
|
||||
if let pitch = lmObs.pitch?.doubleValue {
|
||||
poseInfo["pitch"] = pitch
|
||||
}
|
||||
faceData["pose"] = poseInfo
|
||||
}
|
||||
|
||||
// Landmarks with Y-flip (macOS image coords: bottom-left -> top-left)
|
||||
if let lms = lmObs.landmarks {
|
||||
let imgSize = CGSize(width: imgW, height: imgH)
|
||||
let leftEye = lms.leftEye?.pointsInImage(imageSize: imgSize) ?? []
|
||||
let rightEye = lms.rightEye?.pointsInImage(imageSize: imgSize) ?? []
|
||||
let nose = lms.nose?.pointsInImage(imageSize: imgSize) ?? []
|
||||
|
||||
if !leftEye.isEmpty || !rightEye.isEmpty || !nose.isEmpty {
|
||||
var lm: [String: [[Double]]] = [:]
|
||||
if !leftEye.isEmpty {
|
||||
lm["left_eye"] = leftEye.map { [Double($0.x), Double(imgH - $0.y)] }
|
||||
}
|
||||
if !rightEye.isEmpty {
|
||||
lm["right_eye"] = rightEye.map { [Double($0.x), Double(imgH - $0.y)] }
|
||||
}
|
||||
if !nose.isEmpty {
|
||||
lm["nose"] = nose.map { [Double($0.x), Double(imgH - $0.y)] }
|
||||
}
|
||||
faceData["landmarks"] = lm
|
||||
}
|
||||
|
||||
let outer = lms.outerLips?.pointsInImage(imageSize: imgSize) ?? []
|
||||
let inner = lms.innerLips?.pointsInImage(imageSize: imgSize) ?? []
|
||||
if !outer.isEmpty || !inner.isEmpty {
|
||||
faceData["lips"] = [
|
||||
"outer_lips": outer.map { [Double($0.x), Double(imgH - $0.y)] },
|
||||
"inner_lips": inner.map { [Double($0.x), Double(imgH - $0.y)] }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
frameFaces.append(faceData)
|
||||
}
|
||||
|
||||
// Output face rect observations that the landmark detector missed.
|
||||
// Match against ALL landmark observations via IoU to avoid duplicates.
|
||||
for faceObs in faceObservations {
|
||||
let fBB = faceObs.boundingBox
|
||||
var matched = false
|
||||
for lmObs in landmarkObservations {
|
||||
let lBB = lmObs.boundingBox
|
||||
let ix = max(fBB.origin.x, lBB.origin.x)
|
||||
let iy = max(fBB.origin.y, lBB.origin.y)
|
||||
let iw = min(fBB.maxX, lBB.maxX) - ix
|
||||
let ih = min(fBB.maxY, lBB.maxY) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let intersection = iw * ih
|
||||
let union = fBB.width * fBB.height + lBB.width * lBB.height - intersection
|
||||
if intersection / union > 0.3 {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched { continue }
|
||||
|
||||
// Quality filtering for unmatched face rects
|
||||
|
||||
if Double(faceObs.confidence) < MIN_CONFIDENCE { continue }
|
||||
|
||||
let faceW = Int(fBB.size.width * imgW)
|
||||
let faceH = Int(fBB.size.height * imgH)
|
||||
if faceW < MIN_SIZE || faceH < MIN_SIZE { continue }
|
||||
|
||||
// Unmatched face rect: output without landmarks
|
||||
let faceX = Int(fBB.origin.x * imgW)
|
||||
let faceY = Int((1.0 - fBB.origin.y - fBB.size.height) * imgH)
|
||||
|
||||
// Match capture quality request by bbox overlap
|
||||
var captureQ = 0.0
|
||||
var bestOverlap: CGFloat = 0
|
||||
for cqObs in captureQualityObs {
|
||||
let cb = cqObs.boundingBox
|
||||
let ix = max(fBB.minX, cb.minX)
|
||||
let iy = max(fBB.minY, cb.minY)
|
||||
let iw = min(fBB.maxX, cb.maxX) - ix
|
||||
let ih = min(fBB.maxY, cb.maxY) - iy
|
||||
if iw <= 0 || ih <= 0 { continue }
|
||||
let overlap = (iw * ih) / (fBB.width * fBB.height)
|
||||
if overlap > bestOverlap {
|
||||
bestOverlap = overlap
|
||||
if let cq = cqObs.faceCaptureQuality {
|
||||
captureQ = Double(cq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Calculate quality from size and confidence if API didn't provide it
|
||||
if captureQ == 0.0 {
|
||||
let faceArea = Double(faceW * faceH)
|
||||
let imgArea = Double(imgW * imgH)
|
||||
let sizeScore = min(1.0, (faceArea / imgArea) * 4.0) // Normalize, larger = better
|
||||
let confScore = Double(faceObs.confidence) // Already 0-1
|
||||
|
||||
// Weighted combination (no pose available for unmatched faces)
|
||||
captureQ = sizeScore * 0.5 + confScore * 0.5
|
||||
}
|
||||
|
||||
var faceData: [String: Any] = [
|
||||
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
||||
"width": faceW, "height": faceH],
|
||||
"confidence": Double(faceObs.confidence),
|
||||
"captureQuality": captureQ,
|
||||
]
|
||||
if let yaw = faceObs.yaw?.doubleValue,
|
||||
let roll = faceObs.roll?.doubleValue {
|
||||
var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw]
|
||||
if let pitch = faceObs.pitch?.doubleValue {
|
||||
poseInfo["pitch"] = pitch
|
||||
}
|
||||
faceData["pose"] = poseInfo
|
||||
}
|
||||
frameFaces.append(faceData)
|
||||
}
|
||||
|
||||
if !frameFaces.isEmpty {
|
||||
allFrames.append([
|
||||
"frame": frameNumber,
|
||||
"timestamp": seconds,
|
||||
"faces": frameFaces,
|
||||
])
|
||||
processedCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for batch to complete
|
||||
for _ in batchStart..<batchEnd {
|
||||
semaphore.wait()
|
||||
}
|
||||
|
||||
let elapsed = Date().timeIntervalSince(startTime)
|
||||
let pct = Int(Double(min(batchEnd, totalSamples)) / Double(totalSamples) * 100)
|
||||
print("[SwiftFace] \(processedCount) frames with faces, \(pct)% complete, \(Int(elapsed))s elapsed")
|
||||
fflush(stdout)
|
||||
}
|
||||
|
||||
generator.cancelAllCGImageGeneration()
|
||||
|
||||
let output: [String: Any] = [
|
||||
"frame_count": allFrames.count,
|
||||
"fps": Double(fps),
|
||||
"frames": allFrames,
|
||||
]
|
||||
|
||||
guard let jsonData = try? JSONSerialization.data(withJSONObject: output, options: []),
|
||||
let jsonString = String(data: jsonData, encoding: .utf8) else {
|
||||
print("[SwiftFace] Failed to serialize JSON")
|
||||
return
|
||||
}
|
||||
|
||||
let outputURL = URL(fileURLWithPath: outputPath)
|
||||
try jsonString.write(to: outputURL, atomically: false, encoding: .utf8)
|
||||
|
||||
let elapsed = Date().timeIntervalSince(startTime)
|
||||
print("[SwiftFace] Done: \(allFrames.count) frames, \(String(format: "%.1f", elapsed))s → \(outputPath)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import Foundation
|
||||
import Vision
|
||||
import ArgumentParser
|
||||
import AVFoundation
|
||||
import AppKit
|
||||
|
||||
/// Swift OCR Processor - replaces Python PaddleOCR
|
||||
/// Uses Apple Vision Framework (VNRecognizeTextRequest) with ANE acceleration
|
||||
///
|
||||
/// Output format (compatible with OcrResult Rust struct):
|
||||
/// {
|
||||
/// "frame_count": N,
|
||||
/// "fps": 30.0,
|
||||
/// "frames": [
|
||||
/// { "frame": 0, "timestamp": 0.0, "texts": [{ "text": "...", "x": 0, "y": 0, "width": 0, "height": 0, "confidence": 0.0 }] }
|
||||
/// ]
|
||||
/// }
|
||||
@main
|
||||
struct SwiftOCR: ParsableCommand {
|
||||
@Argument(help: "Video file path")
|
||||
var inputPath: String
|
||||
|
||||
@Argument(help: "Output JSON path")
|
||||
var outputPath: String
|
||||
|
||||
@Option(name: .long, help: "Frames to skip between OCR (default=30)")
|
||||
var sampleInterval: Int = 30
|
||||
|
||||
@Option(name: .long, help: "Video FPS (auto-detect if 0)")
|
||||
var fps: Double = 0
|
||||
|
||||
@Option(name: .long, help: "UUID for logging")
|
||||
var uuid: String = ""
|
||||
|
||||
@Option(name: .long, help: "Recognition level: fast or accurate (default=accurate)")
|
||||
var recognitionLevel: String = "accurate"
|
||||
|
||||
mutating func run() throws {
|
||||
let startTime = Date()
|
||||
print("[SwiftOCR] Starting: \(inputPath)")
|
||||
print("[SwiftOCR] Sample interval: \(sampleInterval)")
|
||||
|
||||
let url = URL(fileURLWithPath: inputPath)
|
||||
let asset = AVAsset(url: url)
|
||||
|
||||
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
|
||||
print("[SwiftOCR] Error: No video track"); return
|
||||
}
|
||||
|
||||
let duration = asset.duration.seconds
|
||||
let detectedFps = fps > 0 ? fps : Double(videoTrack.nominalFrameRate)
|
||||
let totalFrames = Int(duration * detectedFps)
|
||||
print("[SwiftOCR] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", detectedFps)), Frames: \(totalFrames)")
|
||||
|
||||
let frameStep = sampleInterval
|
||||
|
||||
// Use shared frame cache if available (set by FrameManager)
|
||||
let tempDir: URL
|
||||
let framesDir: URL
|
||||
if let cacheDir = ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] {
|
||||
framesDir = URL(fileURLWithPath: cacheDir)
|
||||
tempDir = framesDir // No cleanup needed (managed by FrameManager)
|
||||
print("[SwiftOCR] Using shared frame cache: \(cacheDir)")
|
||||
} else {
|
||||
tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("swift_ocr_\(UUID().uuidString)")
|
||||
framesDir = tempDir.appendingPathComponent("frames")
|
||||
try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true)
|
||||
|
||||
let framePattern = framesDir.appendingPathComponent("frame_%05d.jpg").path
|
||||
print("[SwiftOCR] Extracting frames with ffmpeg (interval=\(frameStep))...")
|
||||
|
||||
// Get video dimensions for smart scaling
|
||||
let videoSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
|
||||
let videoWidth = Int(abs(videoSize.width))
|
||||
let maxOcrWidth = 1920
|
||||
let targetWidth = min(videoWidth, maxOcrWidth)
|
||||
|
||||
// Build scale filter: only downscale if video > 1920px wide
|
||||
let scaleFilter: String
|
||||
if videoWidth > maxOcrWidth {
|
||||
scaleFilter = "select=not(mod(n\\,\(frameStep))),scale=\(targetWidth):-2"
|
||||
print("[SwiftOCR] Video width \(videoWidth)px > \(maxOcrWidth)px, scaling to \(targetWidth)px")
|
||||
} else {
|
||||
scaleFilter = "select=not(mod(n\\,\(frameStep)))"
|
||||
print("[SwiftOCR] Video width \(videoWidth)px <= \(maxOcrWidth)px, using native resolution")
|
||||
}
|
||||
|
||||
let extractProc = Process()
|
||||
extractProc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
|
||||
extractProc.arguments = ["-y", "-v", "quiet", "-i", inputPath,
|
||||
"-vf", scaleFilter,
|
||||
"-vsync", "vfr", "-q:v", "15", framePattern]
|
||||
let startExtract = Date()
|
||||
try extractProc.run()
|
||||
extractProc.waitUntilExit()
|
||||
let extractTime = Date().timeIntervalSince(startExtract)
|
||||
print("[SwiftOCR] Frame extraction complete: \(String(format: "%.1f", extractTime))s")
|
||||
}
|
||||
|
||||
// Sort extracted frame files
|
||||
let fileManager = FileManager.default
|
||||
let allFiles = (try? fileManager.contentsOfDirectory(atPath: framesDir.path)) ?? []
|
||||
let frameFiles = allFiles
|
||||
.filter { $0.hasPrefix("frame_") && $0.hasSuffix(".jpg") }
|
||||
.sorted()
|
||||
|
||||
let level: VNRequestTextRecognitionLevel = (recognitionLevel == "fast") ? .fast : .accurate
|
||||
var ocrFrames: [[String: Any]] = []
|
||||
var lastProgress = 0
|
||||
let totalFrames_to_process = frameFiles.count
|
||||
|
||||
for (i, frameName) in frameFiles.enumerated() {
|
||||
let imgPath = framesDir.appendingPathComponent(frameName).path
|
||||
|
||||
guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)),
|
||||
let img = NSImage(data: imgData),
|
||||
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
|
||||
continue
|
||||
}
|
||||
|
||||
// Extract frame number from filename
|
||||
let frameNumber = Int(frameName.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? (i * frameStep)
|
||||
let timestamp = Double(frameNumber) / detectedFps
|
||||
|
||||
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
|
||||
let request = VNRecognizeTextRequest()
|
||||
request.recognitionLevel = level
|
||||
request.usesLanguageCorrection = true
|
||||
request.preferBackgroundProcessing = true
|
||||
|
||||
guard (try? handler.perform([request])) != nil,
|
||||
let results = request.results else { continue }
|
||||
|
||||
var texts: [[String: Any]] = []
|
||||
let cgW = cgImage.width
|
||||
let cgH = cgImage.height
|
||||
for obs in results {
|
||||
guard let candidate = obs.topCandidates(1).first else { continue }
|
||||
let conf = candidate.confidence
|
||||
guard conf > 0.3 else { continue }
|
||||
let bb = obs.boundingBox
|
||||
let item: [String: Any] = [
|
||||
"text": candidate.string,
|
||||
"x": Int(bb.origin.x * CGFloat(cgW)),
|
||||
"y": Int((1.0 - bb.origin.y - bb.size.height) * CGFloat(cgH)),
|
||||
"width": Int(bb.size.width * CGFloat(cgW)),
|
||||
"height": Int(bb.size.height * CGFloat(cgH)),
|
||||
"confidence": Double(round(conf * 100)) / 100
|
||||
]
|
||||
texts.append(item)
|
||||
}
|
||||
|
||||
if !texts.isEmpty {
|
||||
ocrFrames.append([
|
||||
"frame": frameNumber,
|
||||
"timestamp": Double(round(timestamp * 100)) / 100,
|
||||
"texts": texts
|
||||
])
|
||||
}
|
||||
|
||||
let pct = Int(Float(i) / Float(totalFrames_to_process) * 100)
|
||||
if pct >= lastProgress + 5 {
|
||||
print("[SwiftOCR] Progress: \(pct)% (\(i)/\(totalFrames_to_process) samples, \(ocrFrames.count) with text)")
|
||||
lastProgress = pct
|
||||
}
|
||||
}
|
||||
|
||||
// Write output
|
||||
let outputDict: [String: Any] = [
|
||||
"frame_count": ocrFrames.count,
|
||||
"fps": detectedFps,
|
||||
"frames": ocrFrames
|
||||
]
|
||||
|
||||
if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) {
|
||||
try jsonData.write(to: URL(fileURLWithPath: outputPath))
|
||||
}
|
||||
|
||||
let elapsed = Date().timeIntervalSince(startTime)
|
||||
print("[SwiftOCR] Complete: \(ocrFrames.count) frames with text, \(String(format: "%.1f", elapsed))s")
|
||||
if duration > 0 {
|
||||
print("[SwiftOCR] RTF: \(String(format: "%.3f", elapsed / duration))x")
|
||||
}
|
||||
|
||||
// Clean up temp dir if we created it (not shared cache)
|
||||
if ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] == nil {
|
||||
try? FileManager.default.removeItem(at: tempDir)
|
||||
}
|
||||
}
|
||||
|
||||
func recognizeText(pixelBuffer: CVPixelBuffer, level: VNRequestTextRecognitionLevel) -> [[String: Any]] {
|
||||
var texts: [[String: Any]] = []
|
||||
let request = VNRecognizeTextRequest()
|
||||
request.recognitionLevel = level
|
||||
request.usesLanguageCorrection = true
|
||||
request.preferBackgroundProcessing = true
|
||||
|
||||
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
|
||||
guard (try? handler.perform([request])) != nil,
|
||||
let results = request.results else { return texts }
|
||||
|
||||
let cgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer))
|
||||
let cgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer))
|
||||
|
||||
for obs in results {
|
||||
guard let candidate = obs.topCandidates(1).first,
|
||||
candidate.confidence > 0.2 else { continue }
|
||||
let bb = obs.boundingBox
|
||||
texts.append([
|
||||
"text": candidate.string,
|
||||
"x": Int(bb.origin.x * cgW),
|
||||
"y": Int((1.0 - bb.origin.y - bb.size.height) * cgH),
|
||||
"width": Int(bb.size.width * cgW),
|
||||
"height": Int(bb.size.height * cgH),
|
||||
"confidence": candidate.confidence
|
||||
])
|
||||
}
|
||||
return texts
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import CoreImage
|
||||
|
||||
struct Scene: Codable {
|
||||
let scene_id: Int
|
||||
let start_frame: Int
|
||||
let start_time: Double
|
||||
let end_frame: Int
|
||||
let end_time: Double
|
||||
let duration: Double
|
||||
let score: Float
|
||||
}
|
||||
|
||||
struct VideoInfo: Codable {
|
||||
let duration: Double
|
||||
let fps: Double
|
||||
let frame_count: Int
|
||||
let width: Int
|
||||
let height: Int
|
||||
}
|
||||
|
||||
struct CutResult: Codable {
|
||||
let scene_count: Int
|
||||
let scenes: [Scene]
|
||||
let video_info: VideoInfo
|
||||
}
|
||||
|
||||
func detectScenes(videoPath: String, threshold: Float = 0.3, minSceneDuration: Double = 0.5) throws -> CutResult {
|
||||
print("[SceneDetector] Processing: \(videoPath)")
|
||||
|
||||
let url = URL(fileURLWithPath: videoPath)
|
||||
let asset = AVAsset(url: url)
|
||||
|
||||
guard let track = asset.tracks(withMediaType: .video).first else {
|
||||
throw NSError(domain: "SceneDetector", code: 1, userInfo: [NSLocalizedDescriptionKey: "No video track"])
|
||||
}
|
||||
|
||||
let duration = asset.duration.seconds
|
||||
let fps = Double(track.nominalFrameRate)
|
||||
let frameCount = Int(duration * fps)
|
||||
|
||||
let dimensions = track.naturalSize
|
||||
let width = Int(dimensions.width)
|
||||
let height = Int(dimensions.height)
|
||||
|
||||
print("[SceneDetector] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", fps)), Frames: \(frameCount)")
|
||||
|
||||
let reader = try AVAssetReader(asset: asset)
|
||||
|
||||
let outputSettings: [String: Any] = [
|
||||
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
|
||||
kCVPixelBufferWidthKey as String: 160,
|
||||
kCVPixelBufferHeightKey as String: 90
|
||||
]
|
||||
|
||||
let output = AVAssetReaderTrackOutput(track: track, outputSettings: outputSettings)
|
||||
reader.add(output)
|
||||
|
||||
guard reader.startReading() else {
|
||||
throw NSError(domain: "SceneDetector", code: 3, userInfo: [NSLocalizedDescriptionKey: "Failed to start reading"])
|
||||
}
|
||||
|
||||
var scenes: [Scene] = []
|
||||
var previousBuffer: CVPixelBuffer?
|
||||
var frameNum = 0
|
||||
var lastSceneFrame = 0
|
||||
|
||||
let context = CIContext(options: [.useSoftwareRenderer: false])
|
||||
|
||||
print("[SceneDetector] Processing frames...")
|
||||
|
||||
while reader.status == .reading {
|
||||
guard let sampleBuffer = output.copyNextSampleBuffer(),
|
||||
let currentBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
|
||||
break
|
||||
}
|
||||
|
||||
if let prevBuffer = previousBuffer {
|
||||
if frameNum % 3 == 0 {
|
||||
let diff = calculateFrameDifference(frame1: prevBuffer, frame2: currentBuffer, context: context)
|
||||
|
||||
if diff > threshold {
|
||||
let startTime = Double(lastSceneFrame) / fps
|
||||
let endTime = Double(frameNum) / fps
|
||||
|
||||
if endTime - startTime >= minSceneDuration {
|
||||
let sceneId = scenes.count
|
||||
let scene = Scene(
|
||||
scene_id: sceneId,
|
||||
start_frame: lastSceneFrame,
|
||||
start_time: startTime,
|
||||
end_frame: frameNum,
|
||||
end_time: endTime,
|
||||
duration: endTime - startTime,
|
||||
score: diff
|
||||
)
|
||||
scenes.append(scene)
|
||||
lastSceneFrame = frameNum
|
||||
print("[SceneDetector] Scene \(sceneId) at frame \(frameNum)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
previousBuffer = currentBuffer
|
||||
frameNum += 1
|
||||
}
|
||||
|
||||
if frameNum > lastSceneFrame {
|
||||
let sceneId = scenes.count
|
||||
let startTime = Double(lastSceneFrame) / fps
|
||||
let endTime = Double(frameNum) / fps
|
||||
let duration = endTime - startTime
|
||||
|
||||
let lastScene = Scene(
|
||||
scene_id: sceneId,
|
||||
start_frame: lastSceneFrame,
|
||||
start_time: startTime,
|
||||
end_frame: frameNum,
|
||||
end_time: endTime,
|
||||
duration: duration,
|
||||
score: 0.0
|
||||
)
|
||||
scenes.append(lastScene)
|
||||
}
|
||||
|
||||
print("[SceneDetector] Detected \(scenes.count) scenes")
|
||||
|
||||
let info = VideoInfo(
|
||||
duration: duration,
|
||||
fps: fps,
|
||||
frame_count: frameCount,
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
|
||||
return CutResult(scene_count: scenes.count, scenes: scenes, video_info: info)
|
||||
}
|
||||
|
||||
func calculateFrameDifference(frame1: CVPixelBuffer, frame2: CVPixelBuffer, context: CIContext) -> Float {
|
||||
let ciImage1 = CIImage(cvPixelBuffer: frame1)
|
||||
let ciImage2 = CIImage(cvPixelBuffer: frame2)
|
||||
|
||||
guard let differenceFilter = CIFilter(name: "CIDifferenceBlendMode") else {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
differenceFilter.setValue(ciImage1, forKey: kCIInputImageKey)
|
||||
differenceFilter.setValue(ciImage2, forKey: kCIInputBackgroundImageKey)
|
||||
|
||||
guard let diffImage = differenceFilter.outputImage else {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
let extent = diffImage.extent
|
||||
let totalPixels = extent.width * extent.height
|
||||
|
||||
guard totalPixels > 0 else {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
var totalDiff: Float = 0
|
||||
let sampleCount = 100
|
||||
|
||||
for i in 0..<sampleCount {
|
||||
let x = extent.origin.x + extent.width * CGFloat(i) / CGFloat(sampleCount)
|
||||
let y = extent.origin.y + extent.height * CGFloat(i) / CGFloat(sampleCount)
|
||||
|
||||
if let cgImage = context.createCGImage(diffImage, from: CGRect(x: x, y: y, width: 1, height: 1)) {
|
||||
if let data = cgImage.dataProvider?.data {
|
||||
let buffer = CFDataGetBytePtr(data)
|
||||
if let buffer = buffer {
|
||||
let r = Float(buffer[0])
|
||||
let g = Float(buffer[1])
|
||||
let b = Float(buffer[2])
|
||||
totalDiff += (r + g + b) / (3.0 * 255.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return totalDiff / Float(sampleCount)
|
||||
}
|
||||
|
||||
// CLI
|
||||
let args = CommandLine.arguments
|
||||
if args.count < 3 {
|
||||
print("Usage: swift_scene_detector <video_path> <output_path> [--threshold 0.3]")
|
||||
exit(1)
|
||||
}
|
||||
|
||||
let videoPath = args[1]
|
||||
let outputPath = args[2]
|
||||
var threshold: Float = 0.3
|
||||
var minSceneDuration: Double = 0.5
|
||||
|
||||
var i = 3
|
||||
while i < args.count {
|
||||
if args[i] == "--threshold", i + 1 < args.count {
|
||||
threshold = Float(args[i + 1]) ?? 0.3
|
||||
i += 2
|
||||
} else if args[i] == "--min-duration", i + 1 < args.count {
|
||||
minSceneDuration = Double(args[i + 1]) ?? 0.5
|
||||
i += 2
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let result = try detectScenes(videoPath: videoPath, threshold: threshold, minSceneDuration: minSceneDuration)
|
||||
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = .prettyPrinted
|
||||
let jsonData = try encoder.encode(result)
|
||||
try jsonData.write(to: URL(fileURLWithPath: outputPath))
|
||||
|
||||
print("[SceneDetector] Output: \(outputPath)")
|
||||
} catch {
|
||||
print("[SceneDetector] Error: \(error)")
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import Foundation
|
||||
import Speech
|
||||
import ArgumentParser
|
||||
|
||||
/// Swift CLI 處理器:使用 Apple Speech Framework 進行語音辨識
|
||||
/// 作為 Python ASR (faster-whisper) 的替代方案
|
||||
///
|
||||
/// 比較項目:
|
||||
/// - Speech Framework 使用 Apple 內建模型(ANE 加速)
|
||||
/// - 無需下載模型,系統內建
|
||||
/// - 支援即時與批次辨識
|
||||
/// - 語言支援依作業系統版本
|
||||
|
||||
/// 合併逐字 segments 成句子
|
||||
/// 當相鄰 segment 間隔 < 0.5s 時合併,間隔 >= 0.5s 時視為句子邊界
|
||||
func mergeWordSegments(_ segments: [[String: Any]]) -> [[String: Any]] {
|
||||
let gapThreshold: TimeInterval = 0.5
|
||||
var merged: [[String: Any]] = []
|
||||
var current: [String: Any]? = nil
|
||||
|
||||
for seg in segments {
|
||||
guard let start = seg["start"] as? TimeInterval,
|
||||
let end = seg["end"] as? TimeInterval,
|
||||
let text = seg["text"] as? String,
|
||||
let conf = seg["confidence"] as? Float else {
|
||||
continue
|
||||
}
|
||||
|
||||
if var cur = current {
|
||||
let curEnd = cur["end"] as? TimeInterval ?? 0
|
||||
let gap = start - curEnd
|
||||
|
||||
if gap < gapThreshold {
|
||||
// 合併到當前句子
|
||||
let curText = cur["text"] as? String ?? ""
|
||||
let curConf = cur["confidence"] as? Float ?? 0
|
||||
let wordCount = cur["_wordCount"] as? Int ?? 0
|
||||
cur["text"] = curText + (curText.hasSuffix(" ") ? "" : " ") + text
|
||||
cur["end"] = end
|
||||
// 用 confidence 加權平均(依字數)
|
||||
let totalWords = wordCount + 1
|
||||
cur["confidence"] = (curConf * Float(wordCount) + conf) / Float(totalWords)
|
||||
cur["_wordCount"] = totalWords
|
||||
current = cur
|
||||
} else {
|
||||
// 句子邊界:儲存當前,開始新的
|
||||
cur.removeValue(forKey: "_wordCount")
|
||||
merged.append(cur)
|
||||
current = [
|
||||
"start": start,
|
||||
"end": end,
|
||||
"text": text,
|
||||
"confidence": conf,
|
||||
"_wordCount": 1
|
||||
]
|
||||
}
|
||||
} else {
|
||||
current = [
|
||||
"start": start,
|
||||
"end": end,
|
||||
"text": text,
|
||||
"confidence": conf,
|
||||
"_wordCount": 1
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
if let cur = current {
|
||||
var finalCur = cur
|
||||
finalCur.removeValue(forKey: "_wordCount")
|
||||
merged.append(finalCur)
|
||||
}
|
||||
|
||||
return merged
|
||||
}
|
||||
|
||||
@main
|
||||
struct ASRSwift: ParsableCommand {
|
||||
@Argument(help: "音訊/影片檔案路徑")
|
||||
var inputPath: String
|
||||
|
||||
@Argument(help: "輸出 JSON 路徑")
|
||||
var outputPath: String
|
||||
|
||||
@Option(name: .long, help: "UUID for Redis")
|
||||
var uuid: String = ""
|
||||
|
||||
@Option(name: .long, help: "語言 (留空則自動嘗試支援的語種)")
|
||||
var language: String = ""
|
||||
|
||||
/// 嘗試自動偵測語種
|
||||
func detectLanguage() -> String {
|
||||
if !language.isEmpty { return language }
|
||||
// 優先嘗試常用語種
|
||||
let candidates = ["zh-TW", "zh-Hans", "en-US", "ja-JP", "ko-KR"]
|
||||
for localeId in candidates {
|
||||
if let reco = SFSpeechRecognizer(locale: Locale(identifier: localeId)), reco.isAvailable {
|
||||
print("[ASR_Swift] Auto-detected language: \(localeId)")
|
||||
return localeId
|
||||
}
|
||||
}
|
||||
return "en-US"
|
||||
}
|
||||
|
||||
mutating func run() throws {
|
||||
let startTime = Date()
|
||||
|
||||
print("[ASR_Swift] Starting: \(inputPath)")
|
||||
print("[ASR_Swift] Language: \(language)")
|
||||
print("[ASR_Swift] Output: \(outputPath)")
|
||||
|
||||
// 1. 萃取音訊(若為影片檔)
|
||||
let audioURL: URL
|
||||
let ext = (inputPath as NSString).pathExtension.lowercased()
|
||||
let tempDir = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("asr_swift_\(UUID().uuidString)")
|
||||
|
||||
if ["mp4", "mov", "mkv", "avi"].contains(ext) {
|
||||
// 需要 ffmpeg 萃取音訊
|
||||
let wavPath = tempDir.appendingPathComponent("audio.wav").path
|
||||
print("[ASR_Swift] Extracting audio from video...")
|
||||
let proc = Process()
|
||||
proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
|
||||
proc.arguments = ["-y", "-v", "quiet", "-i", inputPath,
|
||||
"-ar", "16000", "-ac", "1", wavPath]
|
||||
try proc.run()
|
||||
proc.waitUntilExit()
|
||||
guard FileManager.default.fileExists(atPath: wavPath) else {
|
||||
print("[ASR_Swift] Error: ffmpeg failed to extract audio")
|
||||
throw NSError(domain: "ASRSwift", code: 1, userInfo: nil)
|
||||
}
|
||||
audioURL = URL(fileURLWithPath: wavPath)
|
||||
print("[ASR_Swift] Audio extracted: \(wavPath)")
|
||||
} else {
|
||||
audioURL = URL(fileURLWithPath: inputPath)
|
||||
}
|
||||
|
||||
// 2. 語音辨識
|
||||
print("[ASR_Swift] Starting recognition...")
|
||||
|
||||
// 請求授權
|
||||
let authGroup = DispatchGroup()
|
||||
authGroup.enter()
|
||||
var authStatus: SFSpeechRecognizerAuthorizationStatus = .notDetermined
|
||||
SFSpeechRecognizer.requestAuthorization { status in
|
||||
authStatus = status
|
||||
authGroup.leave()
|
||||
}
|
||||
authGroup.wait()
|
||||
guard authStatus == .authorized else {
|
||||
print("[ASR_Swift] Speech recognition not authorized: \(authStatus.rawValue)")
|
||||
return
|
||||
}
|
||||
print("[ASR_Swift] Speech recognition authorized")
|
||||
|
||||
let finalLang = detectLanguage()
|
||||
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: finalLang))
|
||||
guard let recognizer = recognizer, recognizer.isAvailable else {
|
||||
print("[ASR_Swift] Error: Speech recognizer not available for \(language)")
|
||||
// 回傳空結果
|
||||
let emptyResult: [String: Any] = [
|
||||
"language": language,
|
||||
"segments": [],
|
||||
"processing_time": Date().timeIntervalSince(startTime),
|
||||
"model": "Apple Speech Framework",
|
||||
"error": "Recognizer not available"
|
||||
]
|
||||
let jsonData = try JSONSerialization.data(withJSONObject: emptyResult, options: [.prettyPrinted])
|
||||
try jsonData.write(to: URL(fileURLWithPath: outputPath))
|
||||
return
|
||||
}
|
||||
|
||||
let request = SFSpeechURLRecognitionRequest(url: audioURL)
|
||||
request.shouldReportPartialResults = false
|
||||
request.taskHint = .dictation
|
||||
|
||||
var allSegments: [[String: Any]] = []
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
let task = recognizer.recognitionTask(with: request) { result, error in
|
||||
if let error = error {
|
||||
print("[ASR_Swift] Recognition error: \(error.localizedDescription)")
|
||||
semaphore.signal()
|
||||
return
|
||||
}
|
||||
|
||||
if let result = result, result.isFinal {
|
||||
let duration = Date().timeIntervalSince(startTime)
|
||||
print("[ASR_Swift] Recognition completed in \(String(format: "%.2f", duration))s")
|
||||
|
||||
// 將辨識結果轉為 segment 格式
|
||||
for segment in result.bestTranscription.segments {
|
||||
let seg: [String: Any] = [
|
||||
"start": segment.timestamp,
|
||||
"end": segment.timestamp + segment.duration,
|
||||
"text": segment.substring,
|
||||
"speaker_id": nil as String?,
|
||||
"confidence": segment.confidence
|
||||
]
|
||||
allSegments.append(seg)
|
||||
}
|
||||
|
||||
// 合併逐字 segments 成句子
|
||||
if !allSegments.isEmpty {
|
||||
let beforeCount = allSegments.count
|
||||
allSegments = mergeWordSegments(allSegments)
|
||||
print("[ASR_Swift] Merged segments: \(beforeCount) → \(allSegments.count)")
|
||||
}
|
||||
|
||||
// 若無 segment,用整個文字建立一個
|
||||
if allSegments.isEmpty {
|
||||
let fullText = result.bestTranscription.formattedString
|
||||
let seg: [String: Any] = [
|
||||
"start": 0.0,
|
||||
"end": Date().timeIntervalSince(startTime),
|
||||
"text": fullText,
|
||||
"speaker_id": nil as String?,
|
||||
"confidence": 1.0
|
||||
]
|
||||
allSegments.append(seg)
|
||||
}
|
||||
|
||||
semaphore.signal()
|
||||
}
|
||||
}
|
||||
|
||||
// RunLoop 是必要的 — Speech Framework 需要 main runloop 觸發 callback
|
||||
// 使用 semaphore 等待完成,避免固定 timeout
|
||||
while semaphore.wait(timeout: .now()) == .timedOut {
|
||||
RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))
|
||||
}
|
||||
task.cancel()
|
||||
|
||||
// 3. 輸出 JSON
|
||||
let outputDict: [String: Any] = [
|
||||
"language": language,
|
||||
"segments": allSegments,
|
||||
"processing_time": Date().timeIntervalSince(startTime),
|
||||
"model": "Apple Speech Framework (ANE accelerated)",
|
||||
"total_segments": allSegments.count
|
||||
]
|
||||
|
||||
let jsonData = try JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted])
|
||||
try jsonData.write(to: URL(fileURLWithPath: outputPath))
|
||||
|
||||
print("[ASR_Swift] Saved \(allSegments.count) segments to \(outputPath)")
|
||||
print("[ASR_Swift] Total time: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
|
||||
|
||||
// 清理暫存
|
||||
if tempDir != audioURL.deletingLastPathComponent() {
|
||||
try? FileManager.default.removeItem(at: tempDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import Foundation
|
||||
import Speech
|
||||
import ArgumentParser
|
||||
|
||||
/// Swift ASRX Processor
|
||||
/// Speaker Diarization via Apple Speech Framework
|
||||
///
|
||||
/// 使用 SFSpeechRecognizer 進行語音辨識並嘗試分離說話人
|
||||
/// 目前 Apple Speech Framework 不直接支援 speaker diarization,
|
||||
/// 此實作透過音訊分段 + 逐段辨識來近似 diarization 效果
|
||||
|
||||
@main
|
||||
struct ASRXSwift: ParsableCommand {
|
||||
@Argument(help: "音訊/影片檔案路徑")
|
||||
var inputPath: String
|
||||
|
||||
@Argument(help: "輸出 JSON 路徑")
|
||||
var outputPath: String
|
||||
|
||||
@Option(name: .long, help: "UUID for Redis")
|
||||
var uuid: String = ""
|
||||
|
||||
@Option(name: .long, help: "語言 (留空自動偵測)")
|
||||
var language: String = ""
|
||||
|
||||
@Option(name: .long, help: "分段長度(秒),預設 5 秒")
|
||||
var segmentDuration: Double = 5.0
|
||||
|
||||
mutating func run() throws {
|
||||
let startTime = Date()
|
||||
print("[ASRX_Swift] Starting: \(inputPath)")
|
||||
|
||||
// 1. 萃取音訊
|
||||
let audioURL = extractAudio(from: inputPath)
|
||||
defer { try? FileManager.default.removeItem(at: audioURL.deletingLastPathComponent()) }
|
||||
|
||||
// 2. 取得音訊資訊
|
||||
let audioFile = try AVAudioFile(forReading: audioURL)
|
||||
let format = audioFile.processingFormat
|
||||
let totalFrames = audioFile.length
|
||||
let duration = Double(totalFrames) / format.sampleRate
|
||||
print("[ASRX_Swift] Audio: \(totalFrames) frames, \(String(format: "%.1f", duration))s, \(format.sampleRate)Hz")
|
||||
|
||||
// 3. 載入完整音訊
|
||||
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(totalFrames)) else {
|
||||
throw NSError(domain: "ASRXSwift", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to create buffer"])
|
||||
}
|
||||
try audioFile.read(into: buffer)
|
||||
|
||||
guard let floatDataPtr = buffer.floatChannelData else {
|
||||
throw NSError(domain: "ASRXSwift", code: 2, userInfo: [NSLocalizedDescriptionKey: "No float data"])
|
||||
}
|
||||
let floatData = UnsafeBufferPointer(start: floatDataPtr[0], count: Int(totalFrames) * Int(format.channelCount))
|
||||
|
||||
// 4. 分段辨識
|
||||
let finalLang = resolveLanguage()
|
||||
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: finalLang))!
|
||||
let frameStep = Int(segmentDuration * format.sampleRate)
|
||||
let totalSegments = Int(ceil(duration / segmentDuration))
|
||||
|
||||
print("[ASRX_Swift] Splitting into \(totalSegments) segments of \(Int(segmentDuration))s")
|
||||
print("[ASRX_Swift] Language: \(finalLang)")
|
||||
print("[ASRX_Swift] Starting diarization...")
|
||||
|
||||
var segments: [[String: Any]] = []
|
||||
var processedCount = 0
|
||||
|
||||
for segIdx in 0..<totalSegments {
|
||||
let startFrame = segIdx * frameStep
|
||||
let endFrame = min(startFrame + frameStep, Int(totalFrames))
|
||||
|
||||
// 取出該段音訊
|
||||
let segLength = endFrame - startFrame
|
||||
guard Double(segLength) > format.sampleRate * 0.5 else { continue } // 跳過 < 0.5s 的片段
|
||||
|
||||
let segBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(segLength))!
|
||||
segBuffer.frameLength = AVAudioFrameCount(segLength)
|
||||
let src = floatData[0]
|
||||
let dstPtr = segBuffer.floatChannelData![0]
|
||||
let srcSlice = Array(floatData[startFrame..<endFrame])
|
||||
dstPtr.initialize(from: srcSlice, count: segLength)
|
||||
|
||||
// 寫入暫存 WAV(用標準 16-bit PCM 格式)
|
||||
let segURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("seg_\(segIdx).wav")
|
||||
let wavSettings: [String: Any] = [
|
||||
AVFormatIDKey: kAudioFormatLinearPCM,
|
||||
AVSampleRateKey: 16000,
|
||||
AVNumberOfChannelsKey: 1,
|
||||
AVLinearPCMBitDepthKey: 16,
|
||||
AVLinearPCMIsFloatKey: false,
|
||||
]
|
||||
let segFile = try AVAudioFile(forWriting: segURL, settings: wavSettings,
|
||||
commonFormat: .pcmFormatInt16, interleaved: false)
|
||||
try segFile.write(from: segBuffer)
|
||||
|
||||
// 辨識該段
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var segText = ""
|
||||
var segConfidence: Float = 0
|
||||
|
||||
let request = SFSpeechURLRecognitionRequest(url: segURL)
|
||||
request.shouldReportPartialResults = false
|
||||
request.requiresOnDeviceRecognition = true
|
||||
|
||||
let task = recognizer.recognitionTask(with: request) { result, error in
|
||||
if let error = error {
|
||||
print("[ASRX_Swift] Segment \(segIdx) error: \(error.localizedDescription)")
|
||||
} else if let result = result, result.isFinal {
|
||||
segText = result.bestTranscription.formattedString
|
||||
if let firstSeg = result.bestTranscription.segments.first {
|
||||
segConfidence = firstSeg.confidence
|
||||
}
|
||||
}
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
RunLoop.current.run(until: Date(timeIntervalSinceNow: 10))
|
||||
if !segText.isEmpty {
|
||||
segments.append([
|
||||
"start_time": Double(startFrame) / format.sampleRate,
|
||||
"end_time": Double(endFrame) / format.sampleRate,
|
||||
"start_frame": Int(Double(startFrame) / format.sampleRate * 30),
|
||||
"end_frame": Int(Double(endFrame) / format.sampleRate * 30),
|
||||
"text": segText,
|
||||
"speaker_id": "SPEAKER_\(segIdx % 2)", // 簡單輪替作為 speaker 標記
|
||||
"confidence": segConfidence,
|
||||
])
|
||||
processedCount += 1
|
||||
}
|
||||
task.cancel()
|
||||
try? FileManager.default.removeItem(at: segURL)
|
||||
}
|
||||
|
||||
// 5. 輸出 JSON
|
||||
let outputDict: [String: Any] = [
|
||||
"language": finalLang,
|
||||
"segments": segments,
|
||||
"total_segments": processedCount,
|
||||
"total_duration": duration,
|
||||
"processing_time": Date().timeIntervalSince(startTime),
|
||||
"speaker_count": 2,
|
||||
"model": "Apple Speech Framework (segmented diarization)",
|
||||
]
|
||||
|
||||
let jsonData = try JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted])
|
||||
try jsonData.write(to: URL(fileURLWithPath: outputPath))
|
||||
|
||||
print("[ASRX_Swift] Output: \(processedCount) segments to \(outputPath)")
|
||||
print("[ASRX_Swift] Total: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
|
||||
}
|
||||
|
||||
func extractAudio(from path: String) -> URL {
|
||||
let ext = (path as NSString).pathExtension.lowercased()
|
||||
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("asrx_\(UUID().uuidString)")
|
||||
try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
|
||||
let wavURL = tempDir.appendingPathComponent("audio.wav")
|
||||
|
||||
if ["mp4", "mov", "mkv", "avi"].contains(ext) {
|
||||
print("[ASRX_Swift] Extracting audio from video...")
|
||||
let proc = Process()
|
||||
proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
|
||||
proc.arguments = ["-y", "-v", "quiet", "-i", path, "-ar", "16000", "-ac", "1", wavURL.path]
|
||||
try! proc.run()
|
||||
proc.waitUntilExit()
|
||||
} else {
|
||||
try! FileManager.default.copyItem(at: URL(fileURLWithPath: path), to: wavURL)
|
||||
}
|
||||
return wavURL
|
||||
}
|
||||
|
||||
func resolveLanguage() -> String {
|
||||
// 1. If --language is specified, use it
|
||||
if !language.isEmpty {
|
||||
print("[ASRX_Swift] Using specified language: \(language)")
|
||||
return language
|
||||
}
|
||||
|
||||
// 2. Try to read language from ASR JSON
|
||||
let outputDir = URL(fileURLWithPath: outputPath).deletingLastPathComponent()
|
||||
let fileUUID = URL(fileURLWithPath: outputPath).deletingPathExtension().lastPathComponent
|
||||
let asrJsonPath = outputDir.appendingPathComponent("\(fileUUID).asr.json").path
|
||||
|
||||
if FileManager.default.fileExists(atPath: asrJsonPath) {
|
||||
do {
|
||||
let asrData = try Data(contentsOf: URL(fileURLWithPath: asrJsonPath))
|
||||
if let asrJson = try JSONSerialization.jsonObject(with: asrData) as? [String: Any],
|
||||
let asrLang = asrJson["language"] as? String {
|
||||
// Map ASR language codes to Apple locale identifiers
|
||||
let langMap: [String: String] = [
|
||||
"en": "en-US",
|
||||
"zh": "zh-TW",
|
||||
"ja": "ja-JP",
|
||||
"ko": "ko-KR",
|
||||
"es": "es-ES",
|
||||
"fr": "fr-FR",
|
||||
"de": "de-DE",
|
||||
]
|
||||
let appleLang = langMap[asrLang] ?? asrLang
|
||||
print("[ASRX_Swift] Using language from ASR JSON: \(asrLang) -> \(appleLang)")
|
||||
return appleLang
|
||||
}
|
||||
} catch {
|
||||
print("[ASRX_Swift] Warning: Failed to read ASR JSON: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Fallback to auto-detection (prioritize en-US)
|
||||
let candidates = ["en-US", "zh-TW", "zh-Hans", "ja-JP", "ko-KR"]
|
||||
for localeId in candidates {
|
||||
if let reco = SFSpeechRecognizer(locale: Locale(identifier: localeId)), reco.isAvailable {
|
||||
print("[ASRX_Swift] Auto-detected language: \(localeId)")
|
||||
return localeId
|
||||
}
|
||||
}
|
||||
return "en-US"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env swift
|
||||
import Foundation
|
||||
import Vision
|
||||
import AVFoundation
|
||||
import ArgumentParser
|
||||
|
||||
/// Full-movie body pose scanner: compute head-to-body ratio for every frame
|
||||
/// with face detections. Outputs JSONL (one object per frame).
|
||||
@main
|
||||
struct BodyPoseScanner: ParsableCommand {
|
||||
@Argument(help: "Video file path")
|
||||
var videoPath: String
|
||||
|
||||
@Argument(help: "Output JSONL path")
|
||||
var outputPath: String
|
||||
|
||||
@Option(help: "Frames to scan (comma-separated, e.g. '840,900,960') or 'all' to scan everything")
|
||||
var frames: String = "all"
|
||||
|
||||
@Option(help: "Sample interval (every N frames, for 'all' mode)")
|
||||
var interval: Int = 60
|
||||
|
||||
func run() throws {
|
||||
let url = URL(fileURLWithPath: videoPath)
|
||||
let asset = AVAsset(url: url)
|
||||
guard let reader = try? AVAssetReader(asset: asset) else {
|
||||
print("[BodyPose] Cannot open video"); return
|
||||
}
|
||||
|
||||
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
|
||||
print("[BodyPose] No video track"); return
|
||||
}
|
||||
|
||||
let fps = videoTrack.nominalFrameRate
|
||||
let totalFrames = Int(videoTrack.timeRange.duration.seconds * Double(fps))
|
||||
|
||||
let readerOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: [
|
||||
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
|
||||
])
|
||||
readerOutput.alwaysCopiesSampleData = false
|
||||
reader.add(readerOutput)
|
||||
reader.startReading()
|
||||
|
||||
// Parse target frames
|
||||
var targetFrames = Set<Int>()
|
||||
if frames == "all" {
|
||||
targetFrames = Set(stride(from: 0, to: totalFrames, by: interval))
|
||||
} else {
|
||||
targetFrames = Set(frames.split(separator: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) })
|
||||
}
|
||||
|
||||
var frameCount = 0
|
||||
var results: [[String: Any]] = []
|
||||
let bodyRequest = VNDetectHumanBodyPoseRequest()
|
||||
|
||||
guard let fh = FileHandle(forWritingAtPath: outputPath) else {
|
||||
print("[BodyPose] Cannot create output"); return
|
||||
}
|
||||
|
||||
while let sampleBuffer = readerOutput.copyNextSampleBuffer() {
|
||||
defer { frameCount += 1 }
|
||||
guard targetFrames.contains(frameCount) else { continue }
|
||||
targetFrames.remove(frameCount)
|
||||
|
||||
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { continue }
|
||||
|
||||
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
|
||||
try? handler.perform([bodyRequest])
|
||||
|
||||
guard let poses = bodyRequest.results, !poses.isEmpty else { continue }
|
||||
|
||||
let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer))
|
||||
let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer))
|
||||
|
||||
for obs in poses {
|
||||
guard let pts = try? obs.recognizedPoints(.all) else { continue }
|
||||
|
||||
var joints: [String: CGFloat] = [:]
|
||||
for (name, pt) in pts where pt.confidence > 0.3 {
|
||||
// Convert Vision (bottom-left origin) to pixel (top-left origin)
|
||||
joints[String(describing: name)] = pt.location.x * imgW
|
||||
joints[String(describing: name) + "_y"] = imgH - pt.location.y * imgH
|
||||
}
|
||||
|
||||
// Get head top
|
||||
let headY = joints["head_joint_y"] ?? joints["neck_1_joint_y"] ??
|
||||
joints["neck_2_joint_y"] ?? joints["right_eye_joint_y"] ?? 0
|
||||
|
||||
// Get lowest visible body point (foot > ankle > knee > hip)
|
||||
var bodyBottom = CGFloat.greatestFiniteMagnitude
|
||||
for jn in ["right_ankle_joint_y", "left_ankle_joint_y",
|
||||
"right_knee_joint_y", "left_knee_joint_y",
|
||||
"right_hip_joint_y", "left_hip_joint_y"] {
|
||||
if let v = joints[jn], v > 0 {
|
||||
bodyBottom = min(bodyBottom, v)
|
||||
}
|
||||
}
|
||||
|
||||
let bodyH = bodyBottom == .greatestFiniteMagnitude ? 0 : abs(headY - bodyBottom)
|
||||
let headH = abs(headY - (joints["neck_1_joint_y"] ?? headY))
|
||||
|
||||
let h2b = bodyH > 0 ? headH / bodyH : 0
|
||||
|
||||
let row: [String: Any] = [
|
||||
"frame": frameCount, "timestamp": Double(frameCount)/Double(fps),
|
||||
"head_top_y": headY, "body_bottom_y": bodyBottom,
|
||||
"body_h_px": bodyH, "head_h_px": headH,
|
||||
"h2b_ratio": Double(String(format: "%.3f", h2b)) ?? 0,
|
||||
"has_full_body": bodyH > 0 && headH > 0,
|
||||
"joints": joints.mapValues { Double($0) }
|
||||
]
|
||||
|
||||
var jsonData = try! JSONSerialization.data(withJSONObject: row)
|
||||
jsonData.append(10) // newline
|
||||
fh.write(jsonData)
|
||||
}
|
||||
|
||||
if targetFrames.isEmpty { break }
|
||||
}
|
||||
reader.cancelReading()
|
||||
fh.closeFile()
|
||||
print("[BodyPose] Done: \(results.count) frames → \(outputPath)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import Foundation
|
||||
import Speech
|
||||
|
||||
// Check what's available in Speech framework
|
||||
print("=== Speech Framework API Availability ===")
|
||||
|
||||
// SFSpeechRecognizer
|
||||
print("SFSpeechRecognizer available: true")
|
||||
|
||||
// Check for SFSpeechRecognitionMetadata (iOS 17+, macOS 14+)
|
||||
let mdClass = NSClassFromString("SFSpeechRecognitionMetadata")
|
||||
print("SFSpeechRecognitionMetadata: \(mdClass != nil ? "✅ Available" : "❌ Not available")")
|
||||
|
||||
// Check SFSpeechAnalyzer (iOS 17+, macOS 14+)
|
||||
let analyzerClass = NSClassFromString("SFSpeechAnalyzer")
|
||||
print("SFSpeechAnalyzer: \(analyzerClass != nil ? "✅ Available" : "❌ Not available")")
|
||||
|
||||
// Check for speaker identification types
|
||||
let seClass = NSClassFromString("SFSpeakerEmbedding")
|
||||
print("SFSpeakerEmbedding: \(seClass != nil ? "✅ Available" : "❌ Not available")")
|
||||
|
||||
let siClass = NSClassFromString("SFSpeakerIdentification")
|
||||
print("SFSpeakerIdentification: \(siClass != nil ? "✅ Available" : "❌ Not available")")
|
||||
|
||||
let sevClass = NSClassFromString("SFSpeakerEmbeddingVector")
|
||||
print("SFSpeakerEmbeddingVector: \(sevClass != nil ? "✅ Available" : "❌ Not available")")
|
||||
|
||||
let srClass = NSClassFromString("SFSpeakerRecognition")
|
||||
print("SFSpeakerRecognition: \(srClass != nil ? "✅ Available" : "❌ Not available")")
|
||||
|
||||
// Check for AFVoiceBank / AVAudioSession speaker recognition
|
||||
let avClass = NSClassFromString("AVVoiceBank")
|
||||
print("AVVoiceBank: \(avClass != nil ? "✅ Available" : "❌ Not available")")
|
||||
|
||||
// Check AVAudioSession
|
||||
if #available(macOS 14, *) {
|
||||
print("macOS 14+ APIs available: ✅")
|
||||
} else {
|
||||
print("macOS 14+ APIs: ❌")
|
||||
}
|
||||
|
||||
// Summarize
|
||||
print()
|
||||
print("=== Summary ===")
|
||||
print("SFSpeechAnalyzer: \(analyzerClass != nil ? "✅ High-level speech analysis API" : "❌ Not available on this macOS version")")
|
||||
print("Speaker recognition APIs: \(seClass != nil || siClass != nil || srClass != nil ? "✅ Speaker recognition APIs exist" : "❌ No speaker recognition APIs found")")
|
||||
@@ -0,0 +1,23 @@
|
||||
import Foundation
|
||||
import Vision
|
||||
|
||||
let classes = [
|
||||
"VNDetectFaceRectanglesRequest",
|
||||
"VNDetectHumanRectanglesRequest",
|
||||
"VNDetectHumanBodyPoseRequest",
|
||||
"VNDetectHumanHandPoseRequest",
|
||||
"VNClassifyImageRequest",
|
||||
"VNRecognizeTextRequest",
|
||||
"VNGenerateObjectnessBasedSaliencyImageRequest",
|
||||
"VNGenerateAttentionBasedSaliencyImageRequest",
|
||||
"VNRecognizeObjectsRequest",
|
||||
"VNDetectContoursRequest",
|
||||
"VNDetectTrajectoriesRequest",
|
||||
]
|
||||
for cname in classes {
|
||||
if NSClassFromString(cname) != nil {
|
||||
print("\(cname): ✅")
|
||||
} else {
|
||||
print("\(cname): ❌")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.camera</key>
|
||||
<true/>
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
<key>com.apple.security.files.user-selected.read-write</key>
|
||||
<true/>
|
||||
<key>com.apple.security.temporary-exception.audio-upload</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,206 @@
|
||||
import Foundation
|
||||
import Vision
|
||||
import ArgumentParser
|
||||
import AppKit
|
||||
import AVFoundation
|
||||
|
||||
/// Full comparison: Apple Vision Framework vs InsightFace for face processing
|
||||
@main
|
||||
struct FaceCompareTest: ParsableCommand {
|
||||
@Argument(help: "Video path or image path")
|
||||
var inputPath: String
|
||||
|
||||
@Option(name: .long, help: "Sample interval (frames)")
|
||||
var sampleInterval: Int = 30
|
||||
|
||||
@Option(name: .long, help: "Maximum frames to process")
|
||||
var maxFrames: Int = 20
|
||||
|
||||
mutating func run() throws {
|
||||
let startTime = Date()
|
||||
print("=== Apple Vision Framework Face Processing ===")
|
||||
#if arch(arm64)
|
||||
print("HW: Apple Silicon ✅")
|
||||
#endif
|
||||
|
||||
let url = URL(fileURLWithPath: inputPath)
|
||||
let ext = (inputPath as NSString).pathExtension.lowercased()
|
||||
|
||||
if ["mp4", "mov", "mkv", "avi"].contains(ext) {
|
||||
try processVideo(url: url)
|
||||
} else {
|
||||
try processImage(url: url)
|
||||
}
|
||||
|
||||
print("Time: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
|
||||
}
|
||||
|
||||
func processVideo(url: URL) throws {
|
||||
let asset = AVAsset(url: url)
|
||||
guard let track = asset.tracks(withMediaType: .video).first else {
|
||||
print("No video track"); return
|
||||
}
|
||||
let duration = asset.duration.seconds
|
||||
let fps = Double(track.nominalFrameRate)
|
||||
let totalFrames = Int(duration * fps)
|
||||
print("Video: \(duration)s @ \(fps)fps = \(totalFrames) frames")
|
||||
|
||||
// Extract frames with ffmpeg at sample interval
|
||||
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("face_compare_\(UUID().uuidString)")
|
||||
let framesDir = tempDir.appendingPathComponent("frames")
|
||||
try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: tempDir) }
|
||||
|
||||
let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path
|
||||
let proc = Process()
|
||||
proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
|
||||
proc.arguments = ["-y", "-v", "quiet", "-i", url.path,
|
||||
"-vf", "select=not(mod(n\\,\(sampleInterval)))",
|
||||
"-vsync", "vfr", "-q:v", "5", pattern]
|
||||
try proc.run()
|
||||
proc.waitUntilExit()
|
||||
|
||||
let allFiles = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? []
|
||||
let frameFiles = allFiles.filter { $0.hasSuffix(".jpg") }.sorted().prefix(maxFrames)
|
||||
|
||||
var totalFaces = 0
|
||||
var framesWithFaces = 0
|
||||
var frameCount = 0
|
||||
|
||||
for fname in frameFiles {
|
||||
let imgPath = framesDir.appendingPathComponent(fname).path
|
||||
guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)),
|
||||
let img = NSImage(data: imgData),
|
||||
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue }
|
||||
|
||||
let frameNum = Int(fname.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? 0
|
||||
let timestamp = Double(frameNum) / fps
|
||||
|
||||
// Run all face detection requests
|
||||
let faceResult = detectFaces(cgImage: cgImage)
|
||||
if faceResult.count > 0 {
|
||||
totalFaces += faceResult.count
|
||||
framesWithFaces += 1
|
||||
print(" Frame \(frameNum) (\(String(format: "%.1f", timestamp))s): \(faceResult.count) faces")
|
||||
for (i, f) in faceResult.enumerated() {
|
||||
print(" [\(i)] bbox=(\(String(format: "%.0f", f.x)),\(String(format: "%.0f", f.y))) size=\(String(format: "%.0f", f.w))x\(String(format: "%.0f", f.h)) conf=\(String(format: "%.3f", f.conf)) quality=\(String(format: "%.3f", f.quality)) landmarks=\(f.landmarks) embedding=\(f.hasEmbedding ? "✅" : "❌")")
|
||||
}
|
||||
}
|
||||
frameCount += 1
|
||||
}
|
||||
|
||||
print("\n=== Summary ===")
|
||||
print("Frames processed: \(frameCount)")
|
||||
print("Frames with faces: \(framesWithFaces)")
|
||||
print("Total faces detected: \(totalFaces)")
|
||||
|
||||
// Compare with existing InsightFace JSON if available
|
||||
let uuid = extractUUID(from: url.lastPathComponent)
|
||||
if uuid != "" {
|
||||
let faceJsonPath = "/Users/accusys/momentry/output_dev/\(uuid).face.json"
|
||||
if FileManager.default.fileExists(atPath: faceJsonPath) {
|
||||
print("\n=== Comparison with InsightFace (\(uuid).face.json) ===")
|
||||
if let data = try? Data(contentsOf: URL(fileURLWithPath: faceJsonPath)),
|
||||
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let frames = json["frames"] as? [[String: Any]] {
|
||||
let insightFaces = frames.filter { ($0["faces"] as? [Any])?.count ?? 0 > 0 }.count
|
||||
let totalInsightFaces = frames.reduce(0) { $0 + (($1["faces"] as? [Any])?.count ?? 0) }
|
||||
print(" InsightFace frames with faces: \(insightFaces)")
|
||||
print(" InsightFace total faces: \(totalInsightFaces)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func processImage(url: URL) throws {
|
||||
guard let imgData = try? Data(contentsOf: url),
|
||||
let img = NSImage(data: imgData),
|
||||
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
|
||||
print("Cannot load image"); return
|
||||
}
|
||||
print("Image: \(cgImage.width)x\(cgImage.height)")
|
||||
let result = detectFaces(cgImage: cgImage)
|
||||
print("Vision faces: \(result.count)")
|
||||
for (i, f) in result.enumerated() {
|
||||
print(" [\(i)] bbox=(\(String(format: "%.0f", f.x)),\(String(format: "%.0f", f.y))) size=\(String(format: "%.0f", f.w))x\(String(format: "%.0f", f.h)) conf=\(String(format: "%.3f", f.conf)) quality=\(String(format: "%.3f", f.quality)) landmarks=\(f.landmarks) embedding=\(f.hasEmbedding ? "✅" : "❌")")
|
||||
}
|
||||
}
|
||||
|
||||
struct FaceResult {
|
||||
let x, y, w, h: Float
|
||||
let conf: Float
|
||||
let quality: Float
|
||||
let landmarks: Int
|
||||
let hasEmbedding: Bool
|
||||
}
|
||||
|
||||
func detectFaces(cgImage: CGImage) -> [FaceResult] {
|
||||
var results: [FaceResult] = []
|
||||
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
|
||||
|
||||
// 1. Face Detection
|
||||
let detectReq = VNDetectFaceRectanglesRequest()
|
||||
try? handler.perform([detectReq])
|
||||
|
||||
// 2. Face Landmarks (run separately for each detected face)
|
||||
let landmarkReq = VNDetectFaceLandmarksRequest()
|
||||
|
||||
// 3. Face Capture Quality
|
||||
let qualityReq = VNDetectFaceCaptureQualityRequest()
|
||||
|
||||
// Run all requests
|
||||
try? handler.perform([landmarkReq, qualityReq])
|
||||
|
||||
guard let detections = detectReq.results else { return [] }
|
||||
|
||||
let qualityResults = qualityReq.results ?? []
|
||||
|
||||
for (i, face) in detections.enumerated() {
|
||||
let bb = face.boundingBox
|
||||
let w = Float(cgImage.width)
|
||||
let h = Float(cgImage.height)
|
||||
let x = Float(bb.origin.x) * w
|
||||
let y = Float(bb.origin.y) * h
|
||||
let fw = Float(bb.size.width) * w
|
||||
let fh = Float(bb.size.height) * h
|
||||
|
||||
// Get landmarks count
|
||||
var lmCount = 0
|
||||
if let lmResults = landmarkReq.results, i < lmResults.count {
|
||||
let lms = lmResults[i].landmarks
|
||||
if let left = lms?.leftEye { lmCount += left.pointCount }
|
||||
if let right = lms?.rightEye { lmCount += right.pointCount }
|
||||
if let nose = lms?.nose { lmCount += nose.pointCount }
|
||||
}
|
||||
|
||||
// Get quality score
|
||||
var quality: Float = 0
|
||||
if i < qualityResults.count {
|
||||
if #available(macOS 14, *) {
|
||||
quality = (qualityResults[i].value(forKey: "faceCaptureQuality") as? Double).map { Float($0) } ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
// Check for faceprint (embedding) via KVC
|
||||
var hasEmbedding = false
|
||||
if #available(macOS 14, *) {
|
||||
if let fp = face.value(forKey: "faceprint") as? NSObject {
|
||||
hasEmbedding = (fp.value(forKey: "data") as? Data) != nil
|
||||
}
|
||||
}
|
||||
|
||||
results.append(FaceResult(x: x, y: y, w: fw, h: fh, conf: face.confidence, quality: quality, landmarks: lmCount, hasEmbedding: hasEmbedding))
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func extractUUID(from filename: String) -> String {
|
||||
// Try to extract 32-char hex UUID from filename
|
||||
let pattern = try? NSRegularExpression(pattern: "[a-f0-9]{32}")
|
||||
if let match = pattern?.firstMatch(in: filename, range: NSRange(location: 0, length: filename.count)) {
|
||||
return (filename as NSString).substring(with: match.range)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import Foundation
|
||||
import Vision
|
||||
import ArgumentParser
|
||||
import AppKit
|
||||
|
||||
/// POC: Test Apple Vision Framework for face detection + faceprint extraction
|
||||
@main
|
||||
struct FaceVisionTest: ParsableCommand {
|
||||
@Argument(help: "Input image path")
|
||||
var inputPath: String
|
||||
|
||||
mutating func run() throws {
|
||||
let startTime = Date()
|
||||
print("=== Apple Vision Framework Face POC ===")
|
||||
#if arch(arm64)
|
||||
print("HW: Apple Silicon ✅")
|
||||
#else
|
||||
print("HW: Intel")
|
||||
#endif
|
||||
|
||||
guard let image = NSImage(contentsOfFile: inputPath) else {
|
||||
print("Error: cannot load image"); return
|
||||
}
|
||||
guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
|
||||
print("Error: cannot get CGImage"); return
|
||||
}
|
||||
print("Image: \(cgImage.width)x\(cgImage.height)")
|
||||
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
|
||||
|
||||
// 1. Detect faces (synchronous)
|
||||
print("\n--- Detection ---")
|
||||
let detectReq = VNDetectFaceRectanglesRequest()
|
||||
try handler.perform([detectReq])
|
||||
let faces = detectReq.results ?? []
|
||||
print("Faces: \(faces.count)")
|
||||
for (i, f) in faces.enumerated() {
|
||||
let bb = f.boundingBox
|
||||
print(" [\(i)] bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y))) size=(\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) conf=\(String(format: "%.2f", f.confidence))")
|
||||
}
|
||||
|
||||
guard !faces.isEmpty else { print("No faces"); return }
|
||||
|
||||
// 2. Landmarks
|
||||
print("\n--- Landmarks ---")
|
||||
let lmReq = VNDetectFaceLandmarksRequest()
|
||||
try handler.perform([lmReq])
|
||||
if let lmResults = lmReq.results {
|
||||
for (i, f) in lmResults.enumerated() {
|
||||
if let lms = f.landmarks {
|
||||
let count = (lms.leftEye?.pointCount ?? 0) + (lms.rightEye?.pointCount ?? 0)
|
||||
print(" [\(i)] landmarks: \(lms.leftEye?.pointCount ?? 0)+\(lms.rightEye?.pointCount ?? 0) eye pts, nose=\(lms.nose?.pointCount ?? 0)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Capture quality
|
||||
print("\n--- Capture Quality ---")
|
||||
let qualReq = VNDetectFaceCaptureQualityRequest()
|
||||
try handler.perform([qualReq])
|
||||
if let qResults = qualReq.results {
|
||||
for (i, f) in qResults.enumerated() {
|
||||
if #available(macOS 14, *) {
|
||||
let q = f.value(forKey: "faceCaptureQuality") as? Double ?? -1
|
||||
print(" [\(i)] quality=\(String(format: "%.4f", q))")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Faceprint (embedding)
|
||||
print("\n--- Faceprint ---")
|
||||
if #available(macOS 14, *) {
|
||||
let fpClass: AnyClass? = NSClassFromString("VNFaceprint")
|
||||
print("VNFaceprint class: \(fpClass != nil ? "✅ exists" : "❌ nil")")
|
||||
|
||||
if let first = faces.first {
|
||||
let fp = first.value(forKey: "faceprint") as? NSObject
|
||||
print("faceprint KVC: \(fp != nil ? "✅" : "❌")")
|
||||
if let fpData = fp {
|
||||
let data = fpData.value(forKey: "data") as? Data
|
||||
print(" data: \(data != nil ? "\(data!.count) bytes" : "nil")")
|
||||
let desc = fpData.value(forKey: "descriptor") as? NSObject
|
||||
print(" descriptor: \(desc != nil ? "✅ class=\(type(of: desc!))" : "nil")")
|
||||
if let d = desc, let elems = d.value(forKey: "elements") as? [NSNumber] {
|
||||
print(" elements: \(elems.count) dims")
|
||||
if elems.count > 0 {
|
||||
print(" first 5: \(elems.prefix(5).map { String(format: "%.4f", $0.doubleValue) }.joined(separator: ", "))")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
print("macOS 14+ required")
|
||||
}
|
||||
|
||||
print("\nTime: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
|
||||
print("=== Done ===")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import Foundation
|
||||
import Vision
|
||||
import CoreML
|
||||
import ArgumentParser
|
||||
import AVFoundation
|
||||
|
||||
/// FaceNet CoreML Embedding Generator
|
||||
/// Reads face.json, extracts face regions, generates 512-dim embeddings via FaceNet
|
||||
@main
|
||||
struct FaceNetEmbedding: ParsableCommand {
|
||||
@Argument(help: "Video file path")
|
||||
var videoPath: String
|
||||
|
||||
@Argument(help: "Input face.json path")
|
||||
var inputPath: String
|
||||
|
||||
@Argument(help: "Output face.json path")
|
||||
var outputPath: String
|
||||
|
||||
@Option(name: .long, help: "UUID for logging")
|
||||
var uuid: String = ""
|
||||
|
||||
mutating func run() throws {
|
||||
let startTime = Date()
|
||||
print("[FaceNet] Loading FaceNet CoreML model...")
|
||||
|
||||
// Load FaceNet CoreML model
|
||||
let modelURL = URL(fileURLWithPath: "/Users/accusys/momentry_core/models/facenet512.mlpackage/Data/com.apple.CoreML/model.mlmodel")
|
||||
let compiledURL = try MLModel.compileModel(at: modelURL)
|
||||
let model = try MLModel(contentsOf: compiledURL)
|
||||
print("[FaceNet] Model loaded (ANE+GPU+CPU)")
|
||||
|
||||
// Load face.json
|
||||
let faceData = try Data(contentsOf: URL(fileURLWithPath: inputPath))
|
||||
var faceJson = try JSONSerialization.jsonObject(with: faceData) as! [String: Any]
|
||||
var frames = faceJson["frames"] as! [[String: Any]]
|
||||
let fps = faceJson["fps"] as! Double
|
||||
print("[FaceNet] Loaded \(frames.count) frames from \(inputPath)")
|
||||
|
||||
// Load video
|
||||
let asset = AVURLAsset(url: URL(fileURLWithPath: videoPath))
|
||||
let generator = AVAssetImageGenerator(asset: asset)
|
||||
generator.requestedTimeToleranceBefore = .zero
|
||||
generator.requestedTimeToleranceAfter = .zero
|
||||
generator.appliesPreferredTrackTransform = true
|
||||
|
||||
var embeddingCount = 0
|
||||
var processedFrames = 0
|
||||
|
||||
// Process frames in batches
|
||||
for i in 0..<frames.count {
|
||||
var frame = frames[i]
|
||||
let frameNumber = frame["frame"] as! Int
|
||||
var faces = frame["faces"] as! [[String: Any]]
|
||||
|
||||
if faces.isEmpty { continue }
|
||||
|
||||
// Extract frame image
|
||||
let time = CMTime(seconds: Double(frameNumber) / fps, preferredTimescale: 1000)
|
||||
guard let imageRef = try? generator.copyCGImage(at: time, actualTime: nil) else {
|
||||
print("[FaceNet] Failed to extract frame \(frameNumber)")
|
||||
continue
|
||||
}
|
||||
|
||||
// Process each face in this frame
|
||||
for j in 0..<faces.count {
|
||||
var face = faces[j]
|
||||
|
||||
// Skip if already has embedding
|
||||
if face["embedding"] != nil {
|
||||
embeddingCount += 1
|
||||
continue
|
||||
}
|
||||
|
||||
// Get face bbox
|
||||
guard let bbox = face["bbox"] as? [String: Int] else { continue }
|
||||
let x = bbox["x"]!
|
||||
let y = bbox["y"]!
|
||||
let w = bbox["width"]!
|
||||
let h = bbox["height"]!
|
||||
|
||||
// Extract face region
|
||||
// Note: CGImage coordinates are bottom-up, so flip Y
|
||||
let flippedY = imageRef.height - y - h
|
||||
let faceRect = CGRect(x: max(0, x), y: max(0, flippedY), width: min(w, imageRef.width - x), height: min(h, imageRef.height - flippedY))
|
||||
|
||||
guard let faceImage = imageRef.cropping(to: faceRect) else {
|
||||
continue
|
||||
}
|
||||
|
||||
// Resize to 160x160 and convert to MLMultiArray
|
||||
guard let resizedImage = resizeImage(faceImage, to: CGSize(width: 160, height: 160)) else {
|
||||
continue
|
||||
}
|
||||
|
||||
guard let inputArray = cgImageToMLMultiArray(resizedImage) else {
|
||||
continue
|
||||
}
|
||||
|
||||
// Generate embedding via CoreML
|
||||
let inputFeatures = try MLDictionaryFeatureProvider(dictionary: ["input": inputArray])
|
||||
let outputFeatures = try model.prediction(from: inputFeatures)
|
||||
|
||||
if let output = outputFeatures.featureValue(for: "var_2167")?.multiArrayValue {
|
||||
// Convert MLMultiArray to [Float]
|
||||
let embeddingArray = (0..<output.count).map { Float(output[$0].doubleValue) }
|
||||
|
||||
// Add embedding to face
|
||||
face["embedding"] = embeddingArray
|
||||
faces[j] = face
|
||||
embeddingCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
frame["faces"] = faces
|
||||
frames[i] = frame
|
||||
processedFrames += 1
|
||||
|
||||
if processedFrames % 50 == 0 {
|
||||
print("[FaceNet] Processed \(processedFrames)/\(frames.count) frames, \(embeddingCount) embeddings")
|
||||
}
|
||||
}
|
||||
|
||||
// Save updated face.json
|
||||
faceJson["frames"] = frames
|
||||
let outputData = try JSONSerialization.data(withJSONObject: faceJson)
|
||||
try outputData.write(to: URL(fileURLWithPath: outputPath))
|
||||
|
||||
let elapsed = Date().timeIntervalSince(startTime)
|
||||
print("[FaceNet] Done: \(embeddingCount) embeddings in \(String(format: "%.1f", elapsed))s → \(outputPath)")
|
||||
}
|
||||
|
||||
private func resizeImage(_ image: CGImage, to size: CGSize) -> CGImage? {
|
||||
let width = Int(size.width)
|
||||
let height = Int(size.height)
|
||||
let bytesPerPixel = 4
|
||||
let bytesPerRow = width * bytesPerPixel
|
||||
|
||||
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }
|
||||
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
|
||||
|
||||
context.interpolationQuality = .high
|
||||
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
|
||||
|
||||
return context.makeImage()
|
||||
}
|
||||
|
||||
private func cgImageToMLMultiArray(_ image: CGImage) -> MLMultiArray? {
|
||||
let width = image.width
|
||||
let height = image.height
|
||||
|
||||
// Create MLMultiArray with shape [1, 3, 160, 160] (batch, channels, height, width)
|
||||
guard let array = try? MLMultiArray(shape: [1, 3, NSNumber(value: height), NSNumber(value: width)], dataType: .float32) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create CGContext to read pixel data
|
||||
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }
|
||||
var rawData = [UInt8](repeating: 0, count: width * height * 4)
|
||||
|
||||
guard let context = CGContext(data: &rawData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
|
||||
|
||||
// Convert RGB to MLMultiArray (normalized to [0, 1])
|
||||
// FaceNet expects [batch, channels, height, width]
|
||||
for y in 0..<height {
|
||||
for x in 0..<width {
|
||||
let pixelIndex = (y * width + x) * 4
|
||||
let r = Float(rawData[pixelIndex]) / 255.0
|
||||
let g = Float(rawData[pixelIndex + 1]) / 255.0
|
||||
let b = Float(rawData[pixelIndex + 2]) / 255.0
|
||||
|
||||
// [batch, channels, height, width]
|
||||
// R channel: [0, 0, y, x]
|
||||
// G channel: [0, 1, y, x]
|
||||
// B channel: [0, 2, y, x]
|
||||
let rIndex = 0 * 3 * height * width + 0 * height * width + y * width + x
|
||||
let gIndex = 0 * 3 * height * width + 1 * height * width + y * width + x
|
||||
let bIndex = 0 * 3 * height * width + 2 * height * width + y * width + x
|
||||
|
||||
array[rIndex] = NSNumber(value: r)
|
||||
array[gIndex] = NSNumber(value: g)
|
||||
array[bIndex] = NSNumber(value: b)
|
||||
}
|
||||
}
|
||||
|
||||
return array
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import Foundation
|
||||
import Vision
|
||||
import ArgumentParser
|
||||
import AppKit
|
||||
import AVFoundation
|
||||
|
||||
/// Benchmark: Apple Vision Framework body pose detection speed
|
||||
@main
|
||||
struct PoseBenchmark: ParsableCommand {
|
||||
@Argument(help: "Video path or image directory")
|
||||
var inputPath: String
|
||||
|
||||
@Option(name: .long, help: "Sample interval (frames)")
|
||||
var sampleInterval: Int = 30
|
||||
|
||||
mutating func run() throws {
|
||||
let start = Date()
|
||||
print("=== Vision Body Pose Benchmark ===")
|
||||
#if arch(arm64)
|
||||
print("HW: Apple Silicon ✅")
|
||||
#endif
|
||||
|
||||
let url = URL(fileURLWithPath: inputPath)
|
||||
let asset = AVAsset(url: url)
|
||||
guard let track = asset.tracks(withMediaType: .video).first else {
|
||||
print("No video track"); return
|
||||
}
|
||||
let duration = asset.duration.seconds
|
||||
let fps = Double(track.nominalFrameRate)
|
||||
let totalFrames = Int(duration * fps)
|
||||
|
||||
// Extract frames with ffmpeg
|
||||
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("pose_bench_\(UUID().uuidString)")
|
||||
let framesDir = tempDir.appendingPathComponent("frames")
|
||||
try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true)
|
||||
|
||||
let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path
|
||||
let extract = Process()
|
||||
extract.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
|
||||
extract.arguments = ["-y", "-v", "quiet", "-i", inputPath,
|
||||
"-vf", "select=not(mod(n\\,\(sampleInterval)))",
|
||||
"-vsync", "vfr", "-q:v", "5", pattern]
|
||||
try extract.run()
|
||||
extract.waitUntilExit()
|
||||
|
||||
let files = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? []
|
||||
let frameFiles = files.filter { $0.hasSuffix(".jpg") }.sorted()
|
||||
print("Frames: \(frameFiles.count)")
|
||||
|
||||
// Process all frames in one loop (no subprocess overhead)
|
||||
var totalPoses = 0
|
||||
var framesWithPose = 0
|
||||
let inferenceStart = Date()
|
||||
|
||||
for fname in frameFiles {
|
||||
let imgPath = framesDir.appendingPathComponent(fname).path
|
||||
guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)),
|
||||
let img = NSImage(data: imgData),
|
||||
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue }
|
||||
|
||||
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
|
||||
let req = VNDetectHumanBodyPoseRequest()
|
||||
try? handler.perform([req])
|
||||
|
||||
if let poses = req.results, !poses.isEmpty {
|
||||
framesWithPose += 1
|
||||
totalPoses += poses.count
|
||||
}
|
||||
}
|
||||
|
||||
let inferenceTime = Date().timeIntervalSince(inferenceStart)
|
||||
let totalTime = Date().timeIntervalSince(start)
|
||||
|
||||
print("\n=== Results ===")
|
||||
print("Frames: \(frameFiles.count), with poses: \(framesWithPose)")
|
||||
print("Total poses: \(totalPoses)")
|
||||
print("Inference: \(String(format: "%.2f", inferenceTime))s")
|
||||
print("Per frame: \(String(format: "%.0f", inferenceTime / Double(frameFiles.count) * 1000))ms")
|
||||
print("Total: \(String(format: "%.2f", totalTime))s")
|
||||
|
||||
try FileManager.default.removeItem(at: tempDir)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user