fix: face group name read consistency, sync_file_status fix, cleanup ghost records, identity_agent replaced with face_dedup
- get_face_groups_handler: COALESCE(tp.name, tn.label) for name consistency - sync_file_status: compare JSON vs pre_chunks (not chunk table) - face consistency: compare frames.len() not total_faces - cleanup 2 ghost records with NULL file_name/file_path - replace identity_agent with face_dedup in pipeline stages - remove identity_agent_api.rs and all references - update required_processors to match actual processors - update AGENTS.md with team responsibilities - add Studio pipeline changes documentation
This commit is contained in:
+91
-37
@@ -80,50 +80,71 @@ pub struct AgentSearchResponse {
|
||||
|
||||
const SYSTEM_PROMPT: &str = r#"你是 Momentry 影片分析助手。回答用戶關於影片內容的問題。
|
||||
|
||||
## Greeting and Conversation Handling (CRITICAL - Check First)
|
||||
- If user input is ONLY a greeting ("hi", "hello", "hey", "你好", "您好", "hallo"):
|
||||
- **DO NOT call any search tools**
|
||||
- Respond in English: "Hello! I'm Momentry video analysis assistant. I can help you search video content, find people, and analyze scenes. What would you like to know?"
|
||||
- If user asks "how are you" or "thanks", respond briefly in English without tools
|
||||
- **Only use search tools when user asks about VIDEO CONTENT**
|
||||
|
||||
## Response Language (MANDATORY)
|
||||
- **DEFAULT: English** - You MUST respond in English unless user explicitly requests another language
|
||||
- This applies to ALL responses: greetings, search results, explanations
|
||||
- Example: If user asks "gun", respond in English about gun-related content
|
||||
- Only respond in Chinese if user writes in Chinese AND explicitly requests Chinese response
|
||||
|
||||
## 核心原則:預設搜尋所有影片,不主動反問
|
||||
- **所有查詢都預設搜尋全部影片**,不要問用戶「哪部影片」
|
||||
- 如果搜尋到多部影片,直接列出所有結果,不要反問用戶選擇
|
||||
- 只有當多個搜尋工具都返回空、且問題明顯指向特定影片時,才問用戶
|
||||
- 搜尋工具(find_file, list_files, smart_search, universal_search)的 file_uuid 參數可省略以搜尋全部
|
||||
- 搜尋工具(smart_search, semantic_search, trace_search)的 file_uuid 參數可省略以搜尋全部
|
||||
|
||||
## 工具使用規則(重要:優先使用 smart_search)
|
||||
1. **內容/關鍵字問題優先使用 smart_search** — 可以找到影片內的具體文字內容(OCR、ASR)
|
||||
2. **如果 smart_search 找到結果,附帶顯示 chunk 文字內容**(包含 [OCR]、[ASRX] 標記)
|
||||
3. find_file 僅用於搜尋片名,不適合搜尋內容關鍵字
|
||||
4. 人物問題使用 tkg_query
|
||||
5. 人物台詞/發言問題使用 identities_search(輸入人名→回傳台詞片段)
|
||||
6. 人物對話互動(誰跟誰說話)使用 tkg_query 的 speaker_interaction
|
||||
7. 人物台詞內容使用 tkg_query 的 speaker_dialogue
|
||||
8. 用文字反查人物使用 identity_text(輸入關鍵字→找出誰說/提到這段話)
|
||||
9. 畫面分析使用 analyze_frame — 可以分析影片中的任何畫面內容(場景、人物表情、動作、物件等)
|
||||
10. **人物外貌/衣著/顏色問題使用 vlm_describe** — 用 trace_id 查人臉裁切圖,經 VLM 分析描述衣著顏色、款式、配件等
|
||||
11. **vlm_describe 使用流程**:先用 tkg_query top_identities/identity_traces 找到該人的 trace_id,再呼叫 vlm_describe(file_uuid + trace_id)
|
||||
12. **可以同時呼叫多個工具,但需符合以下條件:**
|
||||
- ✅ 查詢多部影片的相同資訊(如:3部影片的人物列表)
|
||||
- ✅ 需要組合多個來源的資訊才能回答(如:file_info + tkg_query)
|
||||
- ❌ 不要為了「嘗試所有可能」而盲目並行呼叫
|
||||
- ❌ 如果單一工具已返回足夠答案,不需要額外呼叫
|
||||
- ❌ 如果 smart_search 已找到相關 chunk,不需要再呼叫 find_file
|
||||
- ❌ 如果單一工具已返回足夠答案,不需要額外呼叫
|
||||
## 搜尋工具選擇策略(重要:根據問題類型選擇正確工具)
|
||||
|
||||
## 回答規則
|
||||
### 優先順序(按此順序選擇工具)
|
||||
1. **semantic_search** - 語意搜尋 → **優先使用(適合大多數查詢)**
|
||||
2. **smart_search** - 精確關鍵字匹配(僅在需要精確匹配時使用)
|
||||
3. **trace_search** - 人物外貌、衣著、地點
|
||||
4. **find_file** - 僅搜尋片名(不搜尋內容)
|
||||
|
||||
### semantic_search(語意搜尋)- 優先使用
|
||||
- **使用時機**:大多數查詢(理解意圖、概念性問題、一般話題)
|
||||
- **範例**:「gun」、「car」、「他在做什麼」、「發生了什麼事」
|
||||
- **回傳**:語意相關的 Top 10 chunk 卡片(text_preview, score, frame_range)
|
||||
|
||||
### smart_search(精確關鍵字匹配)
|
||||
- **使用時機**:需要精確匹配專有名詞、特定詞彙(如人名、地名、專業術語)
|
||||
- **範例**:「Cary Grant」、「Paris」、「確切的台詞引用」
|
||||
- **回傳**:包含關鍵字的 Top 10 chunk 卡片(text_content, frame_range)
|
||||
|
||||
### trace_search(人物軌跡 VLM 搜尋)
|
||||
- **使用時機**:搜尋人物外貌、衣著、地點、場景
|
||||
- **範例**:「穿藍色衣服的人」、「在展場出現的人」、「戴眼鏡的人」
|
||||
- **回傳**:符合的 face trace 卡片(name, vlm_description, vlm_clothing, vlm_tags, frame_range)
|
||||
|
||||
### face_profile_search(用名字或 VLM 註記搜尋人臉)
|
||||
- **使用時機**:用「人名」或「VLM 註記」搜尋已命名的人臉畫面
|
||||
- **範例**:「找出 Susan 的畫面」、「穿藍色衣服的人」、「在展場的人」
|
||||
- **搜尋欄位**:name, vlm_description, vlm_clothing, vlm_tags, vlm_location, vlm_setting
|
||||
- **回傳**:符合的 face profile 卡片(name, key_frame, key_face, frame_range, time_range)
|
||||
|
||||
### find_file(僅搜尋片名)
|
||||
- **使用時機**:僅搜尋影片檔名
|
||||
- **範例**:「find a video named action」
|
||||
- **注意**:不適合搜尋內容,內容搜尋請用 semantic_search
|
||||
|
||||
## 回答格式
|
||||
- 回答長度依問題類型調整:
|
||||
- 簡單查詢(如「列出影片」)→ 簡潔列表回答(1-2句)
|
||||
- 分析問題(如「描述情節」)→ 詳細回答(3-5句)
|
||||
- 計數問題(如「有幾個場景」)→ 直接回答數字 + 簡短說明
|
||||
- 回答格式:
|
||||
- ✅ 如果找到影片,附上 file_uuid
|
||||
- ✅ 對於人物問題,說出角色名和演員名(如果有)
|
||||
- ✅ 引用資料時附上具體數字(frame 編號、時間秒數)
|
||||
- ❌ 不要輸出 JSON 格式,用自然語言回答
|
||||
- ❌ 不要編造資料,如果找不到就明確說「找不到」
|
||||
- 簡單查詢 → 簡潔列表回答(1-2句)
|
||||
- 分析問題 → 詳細回答(3-5句)
|
||||
- **回傳 Top 10 卡片**:每個搜尋工具會回傳最多 10 張卡片
|
||||
- 卡片包含:file_uuid, chunk_id/trace_id, start_time, end_time, score, text_preview/vlm_description
|
||||
- 用自然語言回答,附上 file_name 和時間範圍
|
||||
|
||||
## 停止規則(重要)
|
||||
## 停止規則
|
||||
- **如果已經找到足夠資訊回答用戶問題,立即停止呼叫工具,直接回答**
|
||||
- **如果連續 2 次呼叫工具都返回空結果或相同資訊,停止並告知用戶「找不到更多相關資訊」**
|
||||
- **如果用戶問題不明確或範圍過大,停止並提供簡潔摘要**
|
||||
- **如果單一工具呼叫返回完整答案,不需要額外呼叫其他工具補充**
|
||||
- **優化效率:避免重複呼叫相同工具或查詢相同內容**"#;
|
||||
- **如果連續 2 次呼叫工具都返回空結果,停止並告知「找不到更多相關資訊」**
|
||||
- **優化效率:避免重複呼叫相同工具**"#;
|
||||
|
||||
fn make_tools(pool: &sqlx::PgPool) -> Vec<ToolDef> {
|
||||
vec![
|
||||
@@ -161,11 +182,31 @@ fn make_tools(pool: &sqlx::PgPool) -> Vec<ToolDef> {
|
||||
),
|
||||
function_calling::make_tool(
|
||||
"smart_search",
|
||||
"語意搜尋 chunk 文字內容。適合需要理解意圖的查詢。",
|
||||
"關鍵字搜尋 chunk 文字內容(ILIKE)。適合精確匹配專有名詞、特定詞彙。",
|
||||
serde_json::json!({
|
||||
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
|
||||
"query": {"type": "string", "description": "搜尋關鍵字"},
|
||||
"limit": {"type": "integer", "default": 5}
|
||||
"limit": {"type": "integer", "default": 10}
|
||||
}),
|
||||
vec!["query"],
|
||||
),
|
||||
function_calling::make_tool(
|
||||
"semantic_search",
|
||||
"語意搜尋(embedding + Qdrant)。適合理解意圖的查詢,如「他在做什麼」、「發生了什麼事」。",
|
||||
serde_json::json!({
|
||||
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
|
||||
"query": {"type": "string", "description": "搜尋關鍵字(會轉為 embedding)"},
|
||||
"limit": {"type": "integer", "default": 10}
|
||||
}),
|
||||
vec!["query"],
|
||||
),
|
||||
function_calling::make_tool(
|
||||
"trace_search",
|
||||
"搜尋人物軌跡的 VLM 註記(外貌描述、衣著、標籤、地點、場景)。輸入關鍵字,回傳符合的 face trace 卡片。適合回答「穿藍色衣服的人」、「在展場出現的人」。",
|
||||
serde_json::json!({
|
||||
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
|
||||
"query": {"type": "string", "description": "搜尋關鍵字(會搜尋 name, vlm_description, vlm_clothing, vlm_tags, vlm_location, vlm_setting)"},
|
||||
"limit": {"type": "integer", "default": 10}
|
||||
}),
|
||||
vec!["query"],
|
||||
),
|
||||
@@ -273,6 +314,16 @@ fn make_tools(pool: &sqlx::PgPool) -> Vec<ToolDef> {
|
||||
}),
|
||||
vec!["file_uuid", "trace_id"],
|
||||
),
|
||||
function_calling::make_tool(
|
||||
"face_profile_search",
|
||||
"用名字或 VLM 註記搜尋已命名的人臉。輸入關鍵字(名字、衣著描述、地點、標籤),回傳符合的 face profile 卡片(含 key_frame、key_face、時間範圍、frame 範圍)。適合回答「找出穿藍色衣服的人」、「Susan 出現在哪」、「在展場的人」。",
|
||||
serde_json::json!({
|
||||
"name": {"type": "string", "description": "搜尋關鍵字(會搜尋 name, vlm_description, vlm_clothing, vlm_tags, vlm_location, vlm_setting)"},
|
||||
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
|
||||
"limit": {"type": "integer", "default": 10}
|
||||
}),
|
||||
vec!["name"],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -301,6 +352,8 @@ async fn execute_tool(pool: &sqlx::PgPool, tool_call: &ToolCall) -> (String, Str
|
||||
"tkg_edges_query" => tools::exec_tkg_edges_query(pool, &args).await,
|
||||
"tkg_node_detail" => tools::exec_tkg_node_detail(pool, &args).await,
|
||||
"smart_search" => tools::exec_smart_search(pool, &args).await,
|
||||
"semantic_search" => tools::exec_semantic_search(pool, &args).await,
|
||||
"trace_search" => tools::exec_trace_search(pool, &args).await,
|
||||
"identity_text" => tools::exec_identity_text(pool, &args).await,
|
||||
"identities_search" => tools::exec_identities_search(pool, &args).await,
|
||||
"get_identity_detail" => tools::exec_get_identity_detail(pool, &args).await,
|
||||
@@ -309,6 +362,7 @@ async fn execute_tool(pool: &sqlx::PgPool, tool_call: &ToolCall) -> (String, Str
|
||||
"analyze_frame" => tools::exec_analyze_frame(pool, &args).await,
|
||||
"search_by_appearance" => tools::exec_search_by_appearance(pool, &args).await,
|
||||
"vlm_describe" => tools::exec_vlm_describe(pool, &args).await,
|
||||
"face_profile_search" => tools::exec_face_profile_search(pool, &args).await,
|
||||
_ => Err(format!("Unknown tool: {}", name)),
|
||||
};
|
||||
let content = match result {
|
||||
|
||||
+19
-10
@@ -1,9 +1,8 @@
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
routing::post,
|
||||
Router,
|
||||
Extension, Json, Router,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
@@ -120,14 +119,12 @@ pub async fn trigger_cluster_agent(
|
||||
)
|
||||
})?;
|
||||
|
||||
let total_traces = count_total_traces(&state, &file_uuid)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
let total_traces = count_total_traces(&state, &file_uuid).await.map_err(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
|
||||
tracing::info!(
|
||||
"[ClusterAgent] Completed for {}: {} clusters, {} traces",
|
||||
@@ -186,6 +183,7 @@ async fn update_trace_labels_from_cluster(
|
||||
}
|
||||
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
for (trace_id, cluster_id) in &trace_to_cluster {
|
||||
let external_id = format!("trace_{}", trace_id);
|
||||
let label = cluster_id.clone();
|
||||
@@ -213,6 +211,17 @@ async fn update_trace_labels_from_cluster(
|
||||
.execute(state.db.pool())
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Sync name to trace_profiles
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
|
||||
tp_table
|
||||
))
|
||||
.bind(&label)
|
||||
.bind(file_uuid)
|
||||
.bind(trace_id)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
|
||||
+234
-27
@@ -140,6 +140,8 @@ struct RegisterFileResponse {
|
||||
registration_time: Option<String>,
|
||||
already_exists: bool,
|
||||
message: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
warning: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -214,6 +216,7 @@ async fn register_single_file(
|
||||
registration_time: None,
|
||||
already_exists: false,
|
||||
message: format!("File not found: {}", file_path),
|
||||
warning: None,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -245,6 +248,7 @@ async fn register_single_file(
|
||||
registration_time: None,
|
||||
already_exists: false,
|
||||
message: format!("DB init failed: {}", e),
|
||||
warning: None,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -369,6 +373,7 @@ async fn register_single_file(
|
||||
registration_time: rt,
|
||||
already_exists: true,
|
||||
message: format!("Content already registered: {}", epath),
|
||||
warning: None,
|
||||
};
|
||||
}
|
||||
return RegisterFileResponse {
|
||||
@@ -385,6 +390,7 @@ async fn register_single_file(
|
||||
registration_time: None,
|
||||
already_exists: true,
|
||||
message: "Content already registered (identical file)".to_string(),
|
||||
warning: None,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -620,6 +626,7 @@ async fn register_single_file(
|
||||
registration_time: None,
|
||||
already_exists: false,
|
||||
message: "File registered successfully".to_string(),
|
||||
warning: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -627,6 +634,13 @@ async fn register_file(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<RegisterFileRequest>,
|
||||
) -> Result<Json<RegisterFileResponse>, StatusCode> {
|
||||
let worker_running = super::health::check_worker_alive(&state).await;
|
||||
let worker_warning = if !worker_running {
|
||||
Some("Worker is not running - file will be registered but not processed automatically".to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let file_path = req.file_path.clone();
|
||||
let pattern = req.pattern;
|
||||
|
||||
@@ -650,6 +664,7 @@ async fn register_file(
|
||||
"Pattern requires a directory, but path is not a dir: {}",
|
||||
file_path
|
||||
),
|
||||
warning: None,
|
||||
}));
|
||||
}
|
||||
let re = regex::Regex::new(pat).map_err(|e| {
|
||||
@@ -713,6 +728,7 @@ async fn register_file(
|
||||
"Batch register: {} registered, {} skipped, {} failed",
|
||||
registered, skipped, failed
|
||||
),
|
||||
warning: worker_warning.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -765,8 +781,12 @@ async fn register_file(
|
||||
}
|
||||
}
|
||||
|
||||
let resp =
|
||||
let mut resp =
|
||||
register_single_file(&state, &file_path, req.user_id, req.content_hash, req.force).await;
|
||||
|
||||
if worker_warning.is_some() {
|
||||
resp.warning = worker_warning;
|
||||
}
|
||||
|
||||
if resp.success
|
||||
&& !resp.already_exists
|
||||
@@ -805,7 +825,7 @@ async fn register_file(
|
||||
.init_processing_status(&auto_uuid, all_procs, total as u64)
|
||||
.await;
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET status = 'processing' WHERE file_uuid = $1",
|
||||
"UPDATE {} SET status = 'scanning' WHERE file_uuid = $1",
|
||||
schema::table_name("videos")
|
||||
))
|
||||
.bind(&auto_uuid)
|
||||
@@ -1617,42 +1637,229 @@ async fn sync_file_status(
|
||||
use crate::core::config::OUTPUT_DIR;
|
||||
|
||||
let output_dir = OUTPUT_DIR.as_str();
|
||||
let required_processors = ["face.json", "asrx.json", "ocr.json", "pose.json", "appearance.json"];
|
||||
let chunk_table = schema::table_name("chunk");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let tkg_nodes_table = schema::table_name("tkg_nodes");
|
||||
let tkg_edges_table = schema::table_name("tkg_edges");
|
||||
|
||||
let mut completed_count = 0;
|
||||
for processor in &required_processors {
|
||||
let path = std::path::Path::new(output_dir)
|
||||
.join(format!("{}.{}", file_uuid, processor));
|
||||
if path.exists() {
|
||||
completed_count += 1;
|
||||
// 檢查 processor JSON 是否存在
|
||||
let processors = [
|
||||
("asr", "asr.json"),
|
||||
("asrx", "asrx.json"),
|
||||
("ocr", "ocr.json"),
|
||||
("pose", "pose.json"),
|
||||
("cut", "cut.json"),
|
||||
("face", "face.json"),
|
||||
("face_cluster", "face_cluster.json"),
|
||||
];
|
||||
|
||||
let mut processor_status = serde_json::Map::new();
|
||||
let mut errors = Vec::new();
|
||||
let mut all_consistent = true;
|
||||
let mut any_json_exists = false;
|
||||
|
||||
for (name, filename) in &processors {
|
||||
let path = std::path::Path::new(output_dir).join(format!("{}.{}", file_uuid, filename));
|
||||
let json_exists = path.exists();
|
||||
let mut consistent = false;
|
||||
|
||||
if json_exists {
|
||||
any_json_exists = true;
|
||||
|
||||
// 讀取 JSON 內容
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(content) => {
|
||||
if let Ok(json_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
// 檢查 DB 與 JSON 是否一致
|
||||
let pre_table = schema::table_name("pre_chunks");
|
||||
consistent = match *name {
|
||||
"asr" => {
|
||||
let json_count = json_data.get("segments").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
let is_no_audio = json_data.get("status").and_then(|s| s.as_str()) == Some("no_audio_track")
|
||||
|| json_data.get("status").and_then(|s| s.as_str()) == Some("silent_audio");
|
||||
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asr'", pre_table
|
||||
))
|
||||
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
|
||||
is_no_audio || (json_count as i64) == db_count
|
||||
}
|
||||
"asrx" => {
|
||||
let json_count = json_data.get("segments").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asrx'", pre_table
|
||||
))
|
||||
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
|
||||
(json_count as i64) == db_count
|
||||
}
|
||||
"ocr" => {
|
||||
let json_count = json_data.get("frames").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'ocr'", pre_table
|
||||
))
|
||||
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
|
||||
(json_count as i64) == db_count
|
||||
}
|
||||
"cut" => {
|
||||
let json_count = json_data.get("scenes").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'cut'", pre_table
|
||||
))
|
||||
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
|
||||
(json_count as i64) == db_count
|
||||
}
|
||||
"face" => {
|
||||
let json_frame_count = json_data.get("frames").and_then(|f| f.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
let is_no_faces = json_data.get("status").and_then(|s| s.as_str()) == Some("no_faces");
|
||||
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'face'", pre_table
|
||||
))
|
||||
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
|
||||
is_no_faces || json_frame_count == (db_count as usize)
|
||||
}
|
||||
"face_cluster" => {
|
||||
// cluster 數量可能不等於 trace 數量,只要 JSON 存在就視為一致
|
||||
true
|
||||
}
|
||||
"pose" => {
|
||||
// pose 通常不需要入庫 chunks,只要 JSON 存在就視為一致
|
||||
true
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
} else {
|
||||
errors.push(serde_json::json!({
|
||||
"processor": name,
|
||||
"error": "JSON parse failed"
|
||||
}));
|
||||
consistent = false;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
errors.push(serde_json::json!({
|
||||
"processor": name,
|
||||
"error": format!("Read failed: {}", e)
|
||||
}));
|
||||
consistent = false;
|
||||
}
|
||||
}
|
||||
|
||||
if !consistent {
|
||||
all_consistent = false;
|
||||
}
|
||||
}
|
||||
|
||||
processor_status.insert(name.to_string(), serde_json::json!({
|
||||
"json_exists": json_exists,
|
||||
"consistent": consistent
|
||||
}));
|
||||
}
|
||||
|
||||
let all_complete = completed_count == required_processors.len();
|
||||
let new_status = if all_complete { "completed" } else { "processing" };
|
||||
// 如果有錯誤,回傳錯誤
|
||||
if !errors.is_empty() {
|
||||
return Ok(Json(serde_json::json!({
|
||||
"success": false,
|
||||
"file_uuid": file_uuid,
|
||||
"status": "error",
|
||||
"errors": errors
|
||||
})));
|
||||
}
|
||||
|
||||
// 檢查 DB 進階狀態
|
||||
let has_sentence: bool = sqlx::query_scalar(&format!(
|
||||
"SELECT 1 FROM {} WHERE file_uuid = $1 AND chunk_type = 'sentence' LIMIT 1", chunk_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.unwrap_or(None)
|
||||
.unwrap_or(0) > 0;
|
||||
|
||||
let has_tkg_nodes: bool = sqlx::query_scalar(&format!(
|
||||
"SELECT 1 FROM {} WHERE file_uuid = $1 LIMIT 1", tkg_nodes_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.unwrap_or(None)
|
||||
.unwrap_or(0) > 0;
|
||||
|
||||
let has_tkg_edges: bool = sqlx::query_scalar(&format!(
|
||||
"SELECT 1 FROM {} WHERE file_uuid = $1 LIMIT 1", tkg_edges_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.unwrap_or(None)
|
||||
.unwrap_or(0) > 0;
|
||||
|
||||
// 狀態判斷
|
||||
let new_status = if all_consistent && any_json_exists {
|
||||
// 所有 JSON 都存在且與 DB 一致
|
||||
if has_tkg_edges {
|
||||
"agent_ready"
|
||||
} else {
|
||||
"completed" // 即使 0 筆也算完成
|
||||
}
|
||||
} else if any_json_exists {
|
||||
// 部分 JSON 存在但不一致 → 入庫中
|
||||
"scanning"
|
||||
} else {
|
||||
// 無 JSON → 未開始
|
||||
"registered"
|
||||
};
|
||||
|
||||
// 更新 DB status
|
||||
let videos_table = schema::table_name("videos");
|
||||
let result = sqlx::query(&format!(
|
||||
sqlx::query(&format!(
|
||||
"UPDATE {} SET status = $1, updated_at = NOW() WHERE file_uuid = $2",
|
||||
videos_table
|
||||
))
|
||||
.bind(new_status)
|
||||
.bind(&file_uuid)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[SYNC_STATUS] Update failed: {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
match result {
|
||||
Ok(res) if res.rows_affected() > 0 => Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"file_uuid": file_uuid,
|
||||
"status": new_status,
|
||||
"processors_complete": completed_count,
|
||||
"processors_total": required_processors.len()
|
||||
}))),
|
||||
Ok(_) => Err(StatusCode::NOT_FOUND),
|
||||
Err(e) => {
|
||||
tracing::error!("[SYNC_STATUS] Update failed: {}", e);
|
||||
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
}
|
||||
// 查詢 monitor_jobs 取得 worker 狀態
|
||||
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
||||
let job: Option<(String, Option<String>, i32, i32, Vec<String>, Vec<String>, Option<chrono::NaiveDateTime>)> =
|
||||
sqlx::query_as(&format!(
|
||||
"SELECT status, current_processor, progress_total, progress_current, \
|
||||
completed_processors, failed_processors, updated_at \
|
||||
FROM {} WHERE uuid = $1 ORDER BY created_at DESC LIMIT 1",
|
||||
monitor_jobs_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
|
||||
let worker_info = if let Some((status, current_proc, total, current, completed, failed, updated)) = job {
|
||||
serde_json::json!({
|
||||
"has_job": true,
|
||||
"job_status": status,
|
||||
"current_processor": current_proc,
|
||||
"progress_total": total,
|
||||
"progress_current": current,
|
||||
"completed_processors": completed,
|
||||
"failed_processors": failed,
|
||||
"updated_at": updated.map(|t| t.format("%Y-%m-%dT%H:%M:%S").to_string())
|
||||
})
|
||||
} else {
|
||||
serde_json::json!({
|
||||
"has_job": false
|
||||
})
|
||||
};
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"file_uuid": file_uuid,
|
||||
"status": new_status,
|
||||
"processors": processor_status,
|
||||
"worker": worker_info
|
||||
})))
|
||||
}
|
||||
|
||||
+21
-2
@@ -215,7 +215,7 @@ pub async fn health(State(state): State<AppState>) -> Json<HealthResponse> {
|
||||
build_timestamp: env!("BUILD_TIMESTAMP").to_string(),
|
||||
uptime_ms: get_uptime_ms(),
|
||||
watcher_running: check_process_running("watcher"),
|
||||
worker_running: check_process_running("worker"),
|
||||
worker_running: check_worker_alive(&state).await,
|
||||
auto_pipeline_enabled: config::get_auto_pipeline_enabled(),
|
||||
watcher_auto_register_enabled: config::get_watcher_auto_register(),
|
||||
system_timezone: config::SYSTEM_TIMEZONE.clone(),
|
||||
@@ -380,7 +380,7 @@ pub async fn health_detailed(State(state): State<AppState>) -> Json<DetailedHeal
|
||||
llm: check_http(config::LLM_HEALTH_URL.as_str()).await,
|
||||
rsync: check_rsync().await,
|
||||
watcher_running: check_process_running("watcher"),
|
||||
worker_running: check_process_running("worker"),
|
||||
worker_running: check_worker_alive(&state).await,
|
||||
},
|
||||
schema: check_schema_migrations(state.db.pool()).await,
|
||||
identities: {
|
||||
@@ -628,6 +628,25 @@ async fn check_rsync() -> ServiceStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check worker liveness via Redis health key TTL.
|
||||
/// Returns true if the Worker's Redis health key exists and has remaining TTL > 0.
|
||||
pub async fn check_worker_alive(state: &AppState) -> bool {
|
||||
let health_key = format!("{}health", crate::core::config::REDIS_KEY_PREFIX.as_str());
|
||||
let client = state.redis_cache.get_client().await;
|
||||
let guard = client.write().await;
|
||||
if let Ok(mut conn) = guard.get_conn().await {
|
||||
let ttl: Result<i64, _> = redis::cmd("TTL")
|
||||
.arg(&[health_key.as_str()])
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
match ttl {
|
||||
Ok(ttl) if ttl > 0 => return true,
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn check_process_running(name: &str) -> bool {
|
||||
let patterns: &[&str] = match name {
|
||||
"watcher" => &[
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -326,7 +326,11 @@ pub async fn unbind_identity(
|
||||
.await;
|
||||
|
||||
match &result {
|
||||
Ok(r) => tracing::info!("[unbind_identity] TKG update: {} rows affected for trace {}", r.rows_affected(), tid),
|
||||
Ok(r) => tracing::info!(
|
||||
"[unbind_identity] TKG update: {} rows affected for trace {}",
|
||||
r.rows_affected(),
|
||||
tid
|
||||
),
|
||||
Err(e) => tracing::error!("[unbind_identity] TKG update failed: {}", e),
|
||||
}
|
||||
}
|
||||
@@ -923,7 +927,11 @@ pub async fn bind_identity_trace(
|
||||
.await;
|
||||
|
||||
match &result {
|
||||
Ok(r) => tracing::info!("[bind_identity_trace] TKG update: {} rows affected for trace {}", r.rows_affected(), req.trace_id),
|
||||
Ok(r) => tracing::info!(
|
||||
"[bind_identity_trace] TKG update: {} rows affected for trace {}",
|
||||
r.rows_affected(),
|
||||
req.trace_id
|
||||
),
|
||||
Err(e) => tracing::error!("[bind_identity_trace] TKG update failed: {}", e),
|
||||
}
|
||||
|
||||
|
||||
+130
-43
@@ -666,19 +666,31 @@ async fn stream_video(
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt};
|
||||
|
||||
let (_mode, audio) = parse_video_params(¶ms);
|
||||
let use_original = params.get("original").map(|v| v == "true").unwrap_or(false);
|
||||
|
||||
let videos_table = schema::table_name("videos");
|
||||
let row: Option<(String,)> = sqlx::query_as(&format!(
|
||||
"SELECT file_path FROM {} WHERE file_uuid = $1",
|
||||
let row: Option<(String, Option<String>)> = sqlx::query_as(&format!(
|
||||
"SELECT file_path, proxy_path FROM {} WHERE file_uuid = $1",
|
||||
videos_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let (file_path,) = row.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let (file_path, proxy_path) = row.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let src = std::path::PathBuf::from(&file_path);
|
||||
// Use proxy if available and not explicitly requesting original
|
||||
let effective_path = if !use_original {
|
||||
proxy_path
|
||||
.as_ref()
|
||||
.filter(|p| std::path::Path::new(p).exists())
|
||||
.unwrap_or(&file_path)
|
||||
.clone()
|
||||
} else {
|
||||
file_path.clone()
|
||||
};
|
||||
|
||||
let src = std::path::PathBuf::from(&effective_path);
|
||||
if !src.exists() {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
@@ -723,7 +735,7 @@ async fn stream_video(
|
||||
let tmp_str = tmp.to_str().unwrap_or("").to_string();
|
||||
let ss = start_sec.to_string();
|
||||
let d = dur.to_string();
|
||||
let mut chunk_args = vec!["-ss", &ss, "-i", &file_path, "-t", &d, "-c", "copy"];
|
||||
let mut chunk_args = vec!["-ss", &ss, "-i", &effective_path, "-t", &d, "-c", "copy"];
|
||||
if audio == "off" {
|
||||
chunk_args.push("-an");
|
||||
}
|
||||
@@ -736,15 +748,57 @@ async fn stream_video(
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
let data = tokio::fs::read(&tmp)
|
||||
let clip_size = tokio::fs::metadata(&tmp)
|
||||
.await
|
||||
.map(|m| m.len())
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Ok(Response::builder()
|
||||
.header(header::CONTENT_TYPE, "video/mp4")
|
||||
.header(header::CONTENT_LENGTH, data.len())
|
||||
.body(Body::from(data))
|
||||
.unwrap());
|
||||
|
||||
let range_hdr = request
|
||||
.headers()
|
||||
.get(header::RANGE)
|
||||
.and_then(|v| v.to_str().ok());
|
||||
|
||||
if let Some(range_str) = range_hdr {
|
||||
let (start, end) = parse_range(range_str, clip_size);
|
||||
let length = end - start + 1;
|
||||
let mut file = tokio::fs::File::open(&tmp)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
file.seek(std::io::SeekFrom::Start(start))
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let take = file.take(length);
|
||||
let stream = tokio_util::io::ReaderStream::new(take);
|
||||
let body = Body::from_stream(stream);
|
||||
let resp = Response::builder()
|
||||
.status(StatusCode::PARTIAL_CONTENT)
|
||||
.header(header::CONTENT_TYPE, "video/mp4")
|
||||
.header(
|
||||
header::CONTENT_RANGE,
|
||||
format!("bytes {}-{}/{}", start, end, clip_size),
|
||||
)
|
||||
.header(header::CONTENT_LENGTH, length)
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.body(body)
|
||||
.unwrap();
|
||||
let tmp_path = tmp.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
|
||||
let _ = tokio::fs::remove_file(&tmp_path).await;
|
||||
});
|
||||
return Ok(resp);
|
||||
} else {
|
||||
let data = tokio::fs::read(&tmp)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let _ = tokio::fs::remove_file(&tmp).await;
|
||||
return Ok(Response::builder()
|
||||
.header(header::CONTENT_TYPE, "video/mp4")
|
||||
.header(header::CONTENT_LENGTH, data.len())
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.body(Body::from(data))
|
||||
.unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
// Full file streaming with range request support
|
||||
@@ -1391,8 +1445,7 @@ async fn get_pose_handler(
|
||||
use std::collections::HashMap as StdHashMap;
|
||||
|
||||
let output_dir = OUTPUT_DIR.as_str();
|
||||
let pose_path = std::path::Path::new(output_dir)
|
||||
.join(format!("{}.pose.json", file_uuid));
|
||||
let pose_path = std::path::Path::new(output_dir).join(format!("{}.pose.json", file_uuid));
|
||||
|
||||
if !pose_path.exists() {
|
||||
tracing::error!("[get_pose] File not found: {}", pose_path.display());
|
||||
@@ -1409,7 +1462,10 @@ async fn get_pose_handler(
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let frames = data.get("frames").and_then(|v| v.as_array()).ok_or(StatusCode::NOT_FOUND)?;
|
||||
let frames = data
|
||||
.get("frames")
|
||||
.and_then(|v| v.as_array())
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let frame_data = frames
|
||||
.iter()
|
||||
@@ -1440,39 +1496,61 @@ async fn get_pose_handler(
|
||||
|
||||
if let Some(existing) = unique_kps.get(name) {
|
||||
if conf > existing.confidence {
|
||||
unique_kps.insert(name.to_string(), PoseKeypoint {
|
||||
unique_kps.insert(
|
||||
name.to_string(),
|
||||
PoseKeypoint {
|
||||
name: name.to_string(),
|
||||
x,
|
||||
y,
|
||||
confidence: conf,
|
||||
},
|
||||
);
|
||||
}
|
||||
} else {
|
||||
unique_kps.insert(
|
||||
name.to_string(),
|
||||
PoseKeypoint {
|
||||
name: name.to_string(),
|
||||
x,
|
||||
y,
|
||||
confidence: conf,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
unique_kps.insert(name.to_string(), PoseKeypoint {
|
||||
name: name.to_string(),
|
||||
x,
|
||||
y,
|
||||
confidence: conf,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let coco_names = [
|
||||
"nose", "left_eye", "right_eye", "left_ear", "right_ear",
|
||||
"left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
|
||||
"left_wrist", "right_wrist", "left_hip", "right_hip",
|
||||
"left_knee", "right_knee", "left_ankle", "right_ankle",
|
||||
"nose",
|
||||
"left_eye",
|
||||
"right_eye",
|
||||
"left_ear",
|
||||
"right_ear",
|
||||
"left_shoulder",
|
||||
"right_shoulder",
|
||||
"left_elbow",
|
||||
"right_elbow",
|
||||
"left_wrist",
|
||||
"right_wrist",
|
||||
"left_hip",
|
||||
"right_hip",
|
||||
"left_knee",
|
||||
"right_knee",
|
||||
"left_ankle",
|
||||
"right_ankle",
|
||||
];
|
||||
|
||||
let keypoints: Vec<PoseKeypoint> = coco_names
|
||||
.iter()
|
||||
.map(|name| {
|
||||
unique_kps.get(*name).cloned().unwrap_or_else(|| PoseKeypoint {
|
||||
name: name.to_string(),
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
confidence: 0.0,
|
||||
})
|
||||
unique_kps
|
||||
.get(*name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| PoseKeypoint {
|
||||
name: name.to_string(),
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
confidence: 0.0,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -1492,11 +1570,14 @@ async fn get_appearance_handler(
|
||||
use crate::core::config::OUTPUT_DIR;
|
||||
|
||||
let output_dir = OUTPUT_DIR.as_str();
|
||||
let appearance_path = std::path::Path::new(output_dir)
|
||||
.join(format!("{}.appearance.json", file_uuid));
|
||||
let appearance_path =
|
||||
std::path::Path::new(output_dir).join(format!("{}.appearance.json", file_uuid));
|
||||
|
||||
if !appearance_path.exists() {
|
||||
tracing::error!("[get_appearance] File not found: {}", appearance_path.display());
|
||||
tracing::error!(
|
||||
"[get_appearance] File not found: {}",
|
||||
appearance_path.display()
|
||||
);
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
@@ -1510,7 +1591,10 @@ async fn get_appearance_handler(
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let frames = data.get("frames").and_then(|v| v.as_array()).ok_or(StatusCode::NOT_FOUND)?;
|
||||
let frames = data
|
||||
.get("frames")
|
||||
.and_then(|v| v.as_array())
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let frame_data = frames
|
||||
.iter()
|
||||
@@ -1523,9 +1607,9 @@ async fn get_appearance_handler(
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|channel| {
|
||||
channel.as_array().map(|bins| {
|
||||
bins.iter().filter_map(|v| v.as_f64()).collect()
|
||||
})
|
||||
channel
|
||||
.as_array()
|
||||
.map(|bins| bins.iter().filter_map(|v| v.as_f64()).collect())
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
@@ -1541,5 +1625,8 @@ async fn get_appearance_handler(
|
||||
pub fn pose_appearance_routes() -> Router<crate::api::types::AppState> {
|
||||
Router::new()
|
||||
.route("/api/v1/file/:file_uuid/pose", get(get_pose_handler))
|
||||
.route("/api/v1/file/:file_uuid/appearance", get(get_appearance_handler))
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/appearance",
|
||||
get(get_appearance_handler),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ pub mod docs;
|
||||
pub mod files;
|
||||
pub mod health;
|
||||
pub mod identities;
|
||||
pub mod identity_agent_api;
|
||||
pub mod identity_api;
|
||||
pub mod identity_binding;
|
||||
pub mod llm_search;
|
||||
|
||||
+228
-74
@@ -1,15 +1,15 @@
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, Query, State},
|
||||
http::StatusCode,
|
||||
Extension, Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::core::db::schema;
|
||||
use crate::api::middleware::UserAuth;
|
||||
use crate::api::types::AppState;
|
||||
use crate::core::db::schema;
|
||||
|
||||
// ─── Trace Profile ───
|
||||
|
||||
@@ -49,6 +49,23 @@ pub struct UpdateTraceProfileGroupRequest {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct MergeGroupsRequest {
|
||||
pub file_uuid: String,
|
||||
pub source_groups: Vec<String>,
|
||||
pub target_group_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct MergeGroupsResponse {
|
||||
pub success: bool,
|
||||
pub file_uuid: String,
|
||||
pub source_groups: Vec<String>,
|
||||
pub target_group_name: String,
|
||||
pub traces_merged: u64,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
pub async fn get_trace_profile_handler(
|
||||
State(state): State<AppState>,
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
@@ -100,19 +117,16 @@ pub async fn update_trace_profile_handler(
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
Json(req): Json<UpdateTraceProfileRequest>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let external_id_face = format!("face_track_{}", req.trace_id);
|
||||
let external_id_trace = format!("trace_{}", req.trace_id);
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let nodes_table = schema::table_name("tkg_nodes");
|
||||
|
||||
// Get current node (match both external_id formats)
|
||||
let current: Option<(String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT label, properties FROM {} \
|
||||
WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
|
||||
tkg_table
|
||||
// Get current profile
|
||||
let current: Option<(Option<String>, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT name, properties FROM {} WHERE file_uuid = $1 AND trace_id = $2",
|
||||
tp_table
|
||||
))
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&external_id_face)
|
||||
.bind(&external_id_trace)
|
||||
.bind(req.trace_id)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
@@ -120,14 +134,16 @@ pub async fn update_trace_profile_handler(
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let (current_label, mut current_props) = current.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let (current_name, mut current_props) = current.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
// Build updates
|
||||
let mut updates: Vec<String> = Vec::new();
|
||||
// Build updates for trace_profiles
|
||||
let mut tp_updates: Vec<String> = Vec::new();
|
||||
let mut param_idx = 3;
|
||||
|
||||
if let Some(ref new_name) = req.name {
|
||||
if new_name != ¤t_label {
|
||||
updates.push(format!("label = $5"));
|
||||
if Some(new_name) != current_name.as_ref() {
|
||||
param_idx += 1;
|
||||
tp_updates.push(format!("name = ${}", param_idx));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,8 +168,11 @@ pub async fn update_trace_profile_handler(
|
||||
current_props["aliases"] = aliases.clone();
|
||||
}
|
||||
|
||||
if updates.is_empty() && req.properties.is_none() && req.key_frame.is_none()
|
||||
&& req.key_face.is_none() && req.aliases.is_none()
|
||||
if tp_updates.is_empty()
|
||||
&& req.properties.is_none()
|
||||
&& req.key_frame.is_none()
|
||||
&& req.key_face.is_none()
|
||||
&& req.aliases.is_none()
|
||||
{
|
||||
return Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
@@ -161,40 +180,28 @@ pub async fn update_trace_profile_handler(
|
||||
})));
|
||||
}
|
||||
|
||||
let mut query = format!(
|
||||
"UPDATE {} SET properties = properties || $4::jsonb",
|
||||
tkg_table
|
||||
);
|
||||
if !updates.is_empty() {
|
||||
query.push_str(", ");
|
||||
query.push_str(&updates.join(", "));
|
||||
}
|
||||
query.push_str(" WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)");
|
||||
|
||||
query.push_str(" RETURNING id");
|
||||
|
||||
let props_json = serde_json::to_string(¤t_props).unwrap();
|
||||
|
||||
let result = if !updates.is_empty() {
|
||||
sqlx::query(&query)
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&external_id_face)
|
||||
.bind(&external_id_trace)
|
||||
.bind(&props_json)
|
||||
.bind(req.name.as_ref().unwrap_or(¤t_label))
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
} else {
|
||||
sqlx::query(&query)
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&external_id_face)
|
||||
.bind(&external_id_trace)
|
||||
.bind(&props_json)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
};
|
||||
let mut query = format!(
|
||||
"UPDATE {} SET properties = $2::jsonb",
|
||||
tp_table
|
||||
);
|
||||
if !tp_updates.is_empty() {
|
||||
query.push_str(", ");
|
||||
query.push_str(&tp_updates.join(", "));
|
||||
}
|
||||
query.push_str(" WHERE file_uuid = $1 AND trace_id = $3");
|
||||
|
||||
match result {
|
||||
let mut sql_query = sqlx::query(&query)
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&props_json)
|
||||
.bind(req.trace_id);
|
||||
|
||||
if let Some(ref new_name) = req.name {
|
||||
sql_query = sql_query.bind(new_name);
|
||||
}
|
||||
|
||||
match sql_query.execute(state.db.pool()).await {
|
||||
Ok(res) if res.rows_affected() > 0 => Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": "Trace profile updated",
|
||||
@@ -214,21 +221,17 @@ pub async fn update_trace_profile_group_handler(
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
Json(req): Json<UpdateTraceProfileGroupRequest>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
|
||||
let mut updated = 0;
|
||||
for trace_id in &req.trace_ids {
|
||||
let external_id_face = format!("face_track_{}", trace_id);
|
||||
let external_id_trace = format!("trace_{}", trace_id);
|
||||
let result = sqlx::query(&format!(
|
||||
"UPDATE {} SET label = $1 \
|
||||
WHERE file_uuid = $2 AND node_type = 'face_track' AND (external_id = $3 OR external_id = $4)",
|
||||
tkg_table
|
||||
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
|
||||
tp_table
|
||||
))
|
||||
.bind(&req.name)
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&external_id_face)
|
||||
.bind(&external_id_trace)
|
||||
.bind(trace_id)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
@@ -245,6 +248,78 @@ pub async fn update_trace_profile_group_handler(
|
||||
})))
|
||||
}
|
||||
|
||||
pub async fn merge_groups_handler(
|
||||
State(state): State<AppState>,
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
Json(req): Json<MergeGroupsRequest>,
|
||||
) -> Result<Json<MergeGroupsResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
|
||||
if req.source_groups.contains(&req.target_group_name) {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"success": false,
|
||||
"error": "Target group cannot be in source_groups list"
|
||||
})),
|
||||
));
|
||||
}
|
||||
|
||||
if req.source_groups.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"success": false,
|
||||
"error": "source_groups cannot be empty"
|
||||
})),
|
||||
));
|
||||
}
|
||||
|
||||
// Update trace_profiles.name for all matching traces
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let nodes_table = schema::table_name("tkg_nodes");
|
||||
|
||||
let result = sqlx::query(&format!(
|
||||
"UPDATE {} tp SET name = $1 \
|
||||
WHERE tp.file_uuid = $2 AND tp.trace_id IN (\
|
||||
SELECT REPLACE(n.external_id, 'trace_', '')::int \
|
||||
FROM {} n WHERE n.file_uuid = $2 AND n.node_type = 'face_track' AND n.label = ANY($3)\
|
||||
)",
|
||||
tp_table, nodes_table
|
||||
))
|
||||
.bind(&req.target_group_name)
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&req.source_groups)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(res) => {
|
||||
let updated = res.rows_affected();
|
||||
let group_count = req.source_groups.len();
|
||||
let target_name = req.target_group_name.clone();
|
||||
Ok(Json(MergeGroupsResponse {
|
||||
success: true,
|
||||
file_uuid: req.file_uuid,
|
||||
source_groups: req.source_groups,
|
||||
target_group_name: req.target_group_name,
|
||||
traces_merged: updated,
|
||||
message: format!("Merged {} group(s) into '{}'", group_count, target_name),
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[MergeGroups] DB error: {}", e);
|
||||
Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"success": false,
|
||||
"error": e.to_string()
|
||||
})),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── File Profile ───
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -263,6 +338,16 @@ pub struct FileProfile {
|
||||
pub height: i32,
|
||||
pub fps: f64,
|
||||
pub total_frames: i64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub birth: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub history: Option<Vec<serde_json::Value>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub key_frame: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_path: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub audio_track: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -296,16 +381,51 @@ pub async fn get_file_profile_handler(
|
||||
let (file_uuid, file_name, file_path, status, duration, width, height, fps, total_frames) =
|
||||
row.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
// Enrich with on-disk profile data (birth, history, key_frame)
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let disk_profile =
|
||||
crate::core::file_profile::FileProfile::load_from_disk(output_dir, &file_uuid);
|
||||
|
||||
// Fallback for zombie files: if DB fields are empty, try to recover from profile
|
||||
let effective_name = if file_name.is_empty() {
|
||||
disk_profile
|
||||
.as_ref()
|
||||
.map(|p| p.file_name.clone())
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
file_name
|
||||
};
|
||||
let effective_path = if file_path.is_empty() {
|
||||
disk_profile
|
||||
.as_ref()
|
||||
.map(|p| p.current.path.clone())
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
file_path
|
||||
};
|
||||
|
||||
Ok(Json(FileProfile {
|
||||
file_uuid,
|
||||
file_name,
|
||||
file_path,
|
||||
file_name: effective_name,
|
||||
file_path: effective_path,
|
||||
status,
|
||||
duration,
|
||||
width,
|
||||
height,
|
||||
fps,
|
||||
total_frames,
|
||||
birth: disk_profile
|
||||
.as_ref()
|
||||
.and_then(|p| serde_json::to_value(&p.birth).ok()),
|
||||
history: disk_profile.as_ref().map(|p| {
|
||||
p.history
|
||||
.iter()
|
||||
.map(|h| serde_json::to_value(h).unwrap_or_default())
|
||||
.collect()
|
||||
}),
|
||||
key_frame: disk_profile.as_ref().and_then(|p| p.key_frame.clone()),
|
||||
proxy_path: disk_profile.as_ref().and_then(|p| p.proxy_path.clone()),
|
||||
audio_track: disk_profile.as_ref().and_then(|p| p.audio_track.clone()),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -372,11 +492,34 @@ pub async fn update_file_profile_handler(
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(res) if res.rows_affected() > 0 => Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": "File profile updated",
|
||||
"file_uuid": req.file_uuid
|
||||
}))),
|
||||
Ok(res) if res.rows_affected() > 0 => {
|
||||
// Update on-disk profile if path or name changed
|
||||
if req.file_path.is_some() || req.file_name.is_some() {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
if let Some(mut profile) = crate::core::file_profile::FileProfile::load_from_disk(
|
||||
output_dir,
|
||||
&req.file_uuid,
|
||||
) {
|
||||
let new_path = req
|
||||
.file_path
|
||||
.clone()
|
||||
.unwrap_or_else(|| profile.current.path.clone());
|
||||
let new_name = req
|
||||
.file_name
|
||||
.clone()
|
||||
.unwrap_or_else(|| profile.current.file_name.clone());
|
||||
profile.update_current_path(&new_path, &new_name);
|
||||
if let Err(e) = profile.save_to_disk(output_dir) {
|
||||
tracing::warn!("[FileProfile] Failed to update on-disk profile: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": "File profile updated",
|
||||
"file_uuid": req.file_uuid
|
||||
})))
|
||||
}
|
||||
Ok(_) => Err(StatusCode::NOT_FOUND),
|
||||
Err(e) => {
|
||||
tracing::error!("[FileProfile] Update failed: {}", e);
|
||||
@@ -412,12 +555,16 @@ pub async fn get_face_groups_handler(
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Result<Json<FaceGroupsResponse>, StatusCode> {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
|
||||
let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT label, properties FROM {} \
|
||||
WHERE file_uuid = $1 AND node_type = 'face_track' \
|
||||
ORDER BY (properties->>'trace_id')::int",
|
||||
tkg_table
|
||||
"SELECT COALESCE(tp.name, tn.label) as name, tn.properties \
|
||||
FROM {} tn \
|
||||
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
|
||||
AND tp.trace_id = (tn.properties->>'trace_id')::int \
|
||||
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
|
||||
ORDER BY (tn.properties->>'trace_id')::int",
|
||||
tkg_table, tp_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_all(state.db.pool())
|
||||
@@ -430,16 +577,16 @@ pub async fn get_face_groups_handler(
|
||||
let mut groups: HashMap<String, Vec<i64>> = HashMap::new();
|
||||
let mut unassigned: Vec<i64> = Vec::new();
|
||||
|
||||
for (label, properties) in rows {
|
||||
for (name, properties) in rows {
|
||||
let trace_id = properties
|
||||
.get("trace_id")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0);
|
||||
|
||||
if label.starts_with("Face Trace ") || label.starts_with("Trace ") {
|
||||
if name.starts_with("Face Trace ") || name.starts_with("Trace ") {
|
||||
unassigned.push(trace_id);
|
||||
} else {
|
||||
groups.entry(label).or_default().push(trace_id);
|
||||
groups.entry(name).or_default().push(trace_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,7 +615,7 @@ pub async fn get_face_groups_handler(
|
||||
// ─── Routes ───
|
||||
|
||||
pub fn profile_routes() -> axum::Router<AppState> {
|
||||
use axum::routing::{get, put};
|
||||
use axum::routing::{get, post, put};
|
||||
axum::Router::new()
|
||||
.route("/api/v1/trace-profile", get(get_trace_profile_handler))
|
||||
.route("/api/v1/trace-profile", put(update_trace_profile_handler))
|
||||
@@ -478,5 +625,12 @@ pub fn profile_routes() -> axum::Router<AppState> {
|
||||
)
|
||||
.route("/api/v1/file-profile", get(get_file_profile_handler))
|
||||
.route("/api/v1/file-profile", put(update_file_profile_handler))
|
||||
.route("/api/v1/file/:file_uuid/face-groups", get(get_face_groups_handler))
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/face-groups",
|
||||
get(get_face_groups_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/groups/merge",
|
||||
post(merge_groups_handler),
|
||||
)
|
||||
}
|
||||
|
||||
+88
-45
@@ -25,8 +25,8 @@ struct FileStatsResponse {
|
||||
qdrant: QdrantStats,
|
||||
// TKG stats
|
||||
tkg: TkgFileStats,
|
||||
// Identity Agent stats
|
||||
identity_agent: IdentityAgentStats,
|
||||
// Face Dedup stats
|
||||
face_dedup: FaceDedupStats,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -78,12 +78,10 @@ struct TkgFileStats {
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Default)]
|
||||
struct IdentityAgentStats {
|
||||
struct FaceDedupStats {
|
||||
clusters: i64,
|
||||
identities_created: i64,
|
||||
tmdb_matches: i64,
|
||||
speaker_bindings: i64,
|
||||
confirmations: i64,
|
||||
face_tracks: i64,
|
||||
consistent: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -1030,26 +1028,31 @@ async fn get_file_stats(
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// 6. Get Identity Agent stats from Qdrant _seeds
|
||||
let seeds_filter = json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": file_uuid}}
|
||||
]
|
||||
});
|
||||
let seed_points = qdrant_db
|
||||
.scroll_all_points("_seeds", seeds_filter, 500)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
// 6. Get Face Dedup stats
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let face_cluster_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
|
||||
let face_clusters = if std::path::Path::new(&face_cluster_path).exists() {
|
||||
if let Ok(content) = std::fs::read_to_string(&face_cluster_path) {
|
||||
if let Ok(cluster_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
cluster_data.get("clusters")
|
||||
.and_then(|c| c.as_array())
|
||||
.map(|a| a.len())
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
} else {
|
||||
0
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let face_track_count = tkg.face_track_nodes;
|
||||
|
||||
let identity_agent = IdentityAgentStats {
|
||||
clusters: 0, // From face_clustered.json if available
|
||||
identities_created: face_identities.len() as i64,
|
||||
tmdb_matches: seed_points
|
||||
.iter()
|
||||
.filter(|p| p["payload"]["source"].as_str() == Some("tmdb"))
|
||||
.count() as i64,
|
||||
speaker_bindings: speaker_points.len() as i64,
|
||||
confirmations: 0, // From identity_bindings table
|
||||
let face_dedup = FaceDedupStats {
|
||||
clusters: face_clusters as i64,
|
||||
face_tracks: face_track_count,
|
||||
consistent: (face_clusters as i64) == face_track_count,
|
||||
};
|
||||
|
||||
Ok(Json(FileStatsResponse {
|
||||
@@ -1060,7 +1063,7 @@ async fn get_file_stats(
|
||||
postgres,
|
||||
qdrant: qdrant_stats,
|
||||
tkg,
|
||||
identity_agent,
|
||||
face_dedup,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1108,6 +1111,38 @@ async fn get_pipeline_progress_handler(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Result<Json<crate::core::progress::PipelineProgress>, StatusCode> {
|
||||
// 1. Try to read existing progress from Redis first
|
||||
let redis_progress: Option<crate::core::progress::PipelineProgress> = {
|
||||
use crate::core::db::RedisClient;
|
||||
if let Ok(redis) = RedisClient::new() {
|
||||
if let Ok(mut conn) = redis.get_conn().await {
|
||||
let key = format!(
|
||||
"{}progress:{}:pipeline",
|
||||
crate::core::config::REDIS_KEY_PREFIX.as_str(),
|
||||
file_uuid
|
||||
);
|
||||
redis::cmd("GET")
|
||||
.arg(&key)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|s: String| serde_json::from_str(&s).ok())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// 2. If Redis has complete progress (100%), return it directly
|
||||
if let Some(ref rp) = redis_progress {
|
||||
if rp.overall_progress >= 1.0 {
|
||||
return Ok(Json(rp.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Otherwise, compute actual progress from DB state
|
||||
let pool = state.db.pool();
|
||||
let chunk_table = schema::table_name("chunk");
|
||||
let tkg_nodes_table = schema::table_name("tkg_nodes");
|
||||
@@ -1207,29 +1242,37 @@ async fn get_pipeline_progress_handler(
|
||||
);
|
||||
}
|
||||
|
||||
// Check identity agent from _seeds
|
||||
use crate::core::db::qdrant_db::QdrantDb;
|
||||
use serde_json::json;
|
||||
let qdrant = QdrantDb::new();
|
||||
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "dev".to_string());
|
||||
let seeds_collection = if schema == "public" {
|
||||
"momentry_public_speaker"
|
||||
} else {
|
||||
&format!("momentry_{}_speaker", schema)
|
||||
};
|
||||
let seeds_filter = json!({"must": [{"key": "file_uuid", "match": {"value": &file_uuid}}]});
|
||||
let seed_points = qdrant
|
||||
.scroll_all_points("_seeds", seeds_filter, 100)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
if !seed_points.is_empty() {
|
||||
// Handle music-only files: if processors and rule1 completed, tkg_nodes has nodes but no edges/relationships
|
||||
// Mark face_dedup, tkg_edges and rule2_ingestion as "completed (no faces)" to reach 100%
|
||||
if processors_done && tkg_node_count > 0 && tkg_edge_count == 0 {
|
||||
pp.update_stage("face_dedup", 1.0, "completed", Some("no faces".to_string()));
|
||||
pp.update_stage("tkg_edges", 1.0, "completed", Some("no faces".to_string()));
|
||||
pp.update_stage("rule2_ingestion", 1.0, "completed", Some("no faces".to_string()));
|
||||
}
|
||||
|
||||
// Check face dedup from face_cluster.json
|
||||
if processors_done && tkg_node_count > 0 {
|
||||
pp.update_stage(
|
||||
"identity_agent",
|
||||
"face_dedup",
|
||||
1.0,
|
||||
"completed",
|
||||
Some(format!("{} seeds", seed_points.len())),
|
||||
Some(format!("{} tracks", tkg_node_count)),
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Merge with Redis progress: Redis-completed stages override DB state
|
||||
if let Some(ref rp) = redis_progress {
|
||||
for redis_stage in &rp.stages {
|
||||
if redis_stage.status == "completed" {
|
||||
pp.update_stage(
|
||||
&redis_stage.name,
|
||||
redis_stage.progress,
|
||||
&redis_stage.status,
|
||||
redis_stage.detail.clone(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(pp))
|
||||
}
|
||||
|
||||
+146
-20
@@ -40,6 +40,7 @@ pub struct SearchResult {
|
||||
pub file_name: Option<String>,
|
||||
pub serve_url: Option<String>,
|
||||
pub thumbnail_url: Option<String>,
|
||||
pub source_type: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -63,6 +64,14 @@ struct MergedResult {
|
||||
source: String,
|
||||
}
|
||||
|
||||
fn map_chunk_type_to_source(chunk_type: &str) -> String {
|
||||
match chunk_type.to_lowercase().as_str() {
|
||||
"ocr" => "ocr".to_string(),
|
||||
"sentence" => "asrx".to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Enrich a Qdrant search result with full data from PostgreSQL
|
||||
async fn enrich_from_pg(
|
||||
db: &crate::core::db::PostgresDb,
|
||||
@@ -89,6 +98,7 @@ async fn enrich_from_pg(
|
||||
file_name: None,
|
||||
serve_url: None,
|
||||
thumbnail_url: None,
|
||||
source_type: Some(map_chunk_type_to_source(&p.chunk_type)),
|
||||
}),
|
||||
Ok(None) => None,
|
||||
Err(e) => {
|
||||
@@ -117,6 +127,7 @@ fn pg_result_to_search(p: &SemanticSearchResult) -> SearchResult {
|
||||
file_name: None,
|
||||
serve_url: None,
|
||||
thumbnail_url: None,
|
||||
source_type: Some(map_chunk_type_to_source(&p.chunk_type)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,7 +428,7 @@ pub async fn smart_search(
|
||||
let is_keyword_only = mr.keyword_score.is_some() && mr.semantic_score.is_none();
|
||||
let is_semantic_only = mr.semantic_score.is_some() && mr.keyword_score.is_none();
|
||||
let skip_text_match = is_keyword_only || is_semantic_only;
|
||||
|
||||
|
||||
if !skip_text_match {
|
||||
// 關鍵字過濾: CJK 用子字串匹配,英文用單詞邊界匹配
|
||||
// 使用 text_content 或 summary 進行匹配
|
||||
@@ -464,23 +475,11 @@ pub async fn smart_search(
|
||||
pg.summary.clone()
|
||||
};
|
||||
|
||||
// Determine source prefix based on content field
|
||||
let source_prefix = if let Some(ref content) = pg.content {
|
||||
let text = content.get("text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
let ocr_text = content.get("ocr_text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
|
||||
let has_asrx = !text.trim().is_empty();
|
||||
let has_ocr = !ocr_text.trim().is_empty();
|
||||
|
||||
if has_asrx && has_ocr {
|
||||
"[ASRX+OCR] "
|
||||
} else if has_asrx {
|
||||
"[ASRX] "
|
||||
} else if has_ocr {
|
||||
"[OCR] "
|
||||
} else {
|
||||
""
|
||||
}
|
||||
let source_type_value = map_chunk_type_to_source(&pg.chunk_type);
|
||||
let source_prefix = if pg.chunk_type == "ocr" {
|
||||
"[OCR] "
|
||||
} else if pg.chunk_type == "sentence" {
|
||||
"[ASRX] "
|
||||
} else {
|
||||
""
|
||||
};
|
||||
@@ -497,7 +496,11 @@ pub async fn smart_search(
|
||||
end_time: pg.end_time,
|
||||
raw_text: None,
|
||||
summary: Some(format!("{}{}", source_prefix, display_text)),
|
||||
text_content: Some(format!("{}{}", source_prefix, pg.text_content.clone().unwrap_or_default())),
|
||||
text_content: Some(format!(
|
||||
"{}{}",
|
||||
source_prefix,
|
||||
pg.text_content.clone().unwrap_or_default()
|
||||
)),
|
||||
metadata: pg.metadata.clone(),
|
||||
similarity: Some(mr.score),
|
||||
file_name: None,
|
||||
@@ -508,6 +511,7 @@ pub async fn smart_search(
|
||||
fu, mr.chunk_id
|
||||
)
|
||||
}),
|
||||
source_type: Some(source_type_value),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -569,8 +573,130 @@ pub async fn smart_search(
|
||||
}))
|
||||
}
|
||||
|
||||
/// Keyword-only search (BM25, no vector)
|
||||
pub async fn keyword_search(
|
||||
State(state): State<crate::api::types::AppState>,
|
||||
Json(req): Json<SmartSearchRequest>,
|
||||
) -> Result<Json<SmartSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let db = &state.db;
|
||||
let page = req.page.unwrap_or(1).max(1);
|
||||
let page_size = req.page_size.unwrap_or(5).max(1);
|
||||
let limit = page_size;
|
||||
|
||||
// Keyword search via PG BM25
|
||||
let keyword_results = db
|
||||
.search_bm25(&req.query, req.file_uuid.as_deref(), limit as i64)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("Keyword search failed: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({ "error": e.to_string() })),
|
||||
)
|
||||
})?;
|
||||
|
||||
tracing::info!(
|
||||
"Keyword search: {} hits for '{}'",
|
||||
keyword_results.len(),
|
||||
req.query
|
||||
);
|
||||
|
||||
let mut results = Vec::new();
|
||||
for row in keyword_results.iter() {
|
||||
if let Ok(Some(p)) = db
|
||||
.get_chunk_by_id_no_embedding(&row.file_uuid, &row.chunk_id)
|
||||
.await
|
||||
{
|
||||
results.push(SearchResult {
|
||||
id: 0,
|
||||
file_uuid: p.file_uuid.clone(),
|
||||
parent_id: p.scene_order,
|
||||
scene_order: Some(p.scene_order),
|
||||
start_frame: p.start_frame,
|
||||
end_frame: p.end_frame,
|
||||
fps: p.fps,
|
||||
start_time: p.start_time,
|
||||
end_time: p.end_time,
|
||||
raw_text: None,
|
||||
summary: Some(p.summary.clone()),
|
||||
text_content: p.text_content.clone(),
|
||||
metadata: p.metadata.clone(),
|
||||
similarity: Some(row.bm25_score as f64),
|
||||
file_name: None,
|
||||
serve_url: None,
|
||||
thumbnail_url: None,
|
||||
source_type: Some(map_chunk_type_to_source(&p.chunk_type)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(SmartSearchResponse {
|
||||
query: req.query,
|
||||
results,
|
||||
page,
|
||||
page_size,
|
||||
strategy: "keyword".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Semantic-only search (vector, no keyword)
|
||||
pub async fn semantic_search(
|
||||
State(state): State<crate::api::types::AppState>,
|
||||
Json(req): Json<SmartSearchRequest>,
|
||||
) -> Result<Json<SmartSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let db = &state.db;
|
||||
let qdrant = &state.qdrant;
|
||||
let page = req.page.unwrap_or(1).max(1);
|
||||
let page_size = req.page_size.unwrap_or(5).max(1);
|
||||
let limit = page_size;
|
||||
|
||||
// Generate embedding
|
||||
let embedder = Embedder::new("embeddinggemma-300m".to_string());
|
||||
let embedding = embedder.embed_query(&req.query).await.map_err(|e| {
|
||||
tracing::error!("Embedding failed: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({ "error": e.to_string() })),
|
||||
)
|
||||
})?;
|
||||
|
||||
// Semantic search via Qdrant
|
||||
let semantic_results = if let Some(file_uuid) = &req.file_uuid {
|
||||
qdrant
|
||||
.search_in_uuid(&embedding, file_uuid, limit)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
qdrant.search(&embedding, limit).await.unwrap_or_default()
|
||||
};
|
||||
|
||||
tracing::info!(
|
||||
"Semantic search: {} hits for '{}'",
|
||||
semantic_results.len(),
|
||||
req.query
|
||||
);
|
||||
|
||||
let mut results = Vec::new();
|
||||
for hit in semantic_results.iter() {
|
||||
if let Some(p) = enrich_from_pg(db, &hit.uuid, &hit.chunk_id, hit.score).await {
|
||||
results.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(SmartSearchResponse {
|
||||
query: req.query,
|
||||
results,
|
||||
page,
|
||||
page_size,
|
||||
strategy: "semantic".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
// --- Router Setup ---
|
||||
|
||||
pub fn search_routes() -> Router<crate::api::types::AppState> {
|
||||
Router::new().route("/api/v1/search/smart", post(smart_search))
|
||||
Router::new()
|
||||
.route("/api/v1/search/smart", post(smart_search))
|
||||
.route("/api/v1/search/keyword", post(keyword_search))
|
||||
.route("/api/v1/search/semantic", post(semantic_search))
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ use super::files;
|
||||
use super::health;
|
||||
use super::health::{health, health_consistency, health_detailed};
|
||||
use super::identities;
|
||||
use super::identity_agent_api;
|
||||
use super::identity_api;
|
||||
use super::identity_binding;
|
||||
use super::llm_search;
|
||||
@@ -118,7 +117,6 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
.merge(agent_api::agent_routes())
|
||||
.merge(agent_search::agent_search_routes())
|
||||
.merge(processing::processing_routes())
|
||||
.merge(identity_agent_api::identity_agent_routes())
|
||||
.merge(media_api::bbox_routes())
|
||||
.merge(media_api::media_proxy_routes())
|
||||
.merge(media_api::pose_appearance_routes())
|
||||
|
||||
+51
-13
@@ -1706,7 +1706,10 @@ async fn delete_trace(
|
||||
Path((file_uuid, trace_id)): Path<(String, i32)>,
|
||||
Json(req): Json<serde_json::Value>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let hard_delete = req.get("hard_delete").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let hard_delete = req
|
||||
.get("hard_delete")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
|
||||
@@ -1719,9 +1722,17 @@ async fn delete_trace(
|
||||
]
|
||||
});
|
||||
|
||||
let deleted_count = match qdrant.delete_points_by_filter("_faces", filter.clone()).await {
|
||||
let deleted_count = match qdrant
|
||||
.delete_points_by_filter("_faces", filter.clone())
|
||||
.await
|
||||
{
|
||||
Ok(count) => {
|
||||
tracing::info!("[delete_trace] Hard deleted {} face points from Qdrant for trace {} in {}", count, trace_id, file_uuid);
|
||||
tracing::info!(
|
||||
"[delete_trace] Hard deleted {} face points from Qdrant for trace {} in {}",
|
||||
count,
|
||||
trace_id,
|
||||
file_uuid
|
||||
);
|
||||
count
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -1776,13 +1787,23 @@ async fn delete_trace(
|
||||
"status": "deleted"
|
||||
});
|
||||
|
||||
let qdrant_updated = match qdrant.update_payload_by_filter("_faces", filter.clone(), payload).await {
|
||||
let qdrant_updated = match qdrant
|
||||
.update_payload_by_filter("_faces", filter.clone(), payload)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
tracing::info!("[delete_trace] Soft deleted (marked) trace {} in {}", trace_id, file_uuid);
|
||||
tracing::info!(
|
||||
"[delete_trace] Soft deleted (marked) trace {} in {}",
|
||||
trace_id,
|
||||
file_uuid
|
||||
);
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[delete_trace] Failed to mark Qdrant points as deleted: {}", e);
|
||||
tracing::error!(
|
||||
"[delete_trace] Failed to mark Qdrant points as deleted: {}",
|
||||
e
|
||||
);
|
||||
return Json(serde_json::json!({
|
||||
"success": false,
|
||||
"error": format!("Failed to mark Qdrant points: {}", e)
|
||||
@@ -1848,8 +1869,11 @@ async fn merge_trace(
|
||||
});
|
||||
|
||||
// Get count before update
|
||||
let points_count = qdrant.scroll_all_points("_faces", src_filter.clone(), 1).await
|
||||
.map(|pts| pts.len()).unwrap_or(0);
|
||||
let points_count = qdrant
|
||||
.scroll_all_points("_faces", src_filter.clone(), 1)
|
||||
.await
|
||||
.map(|pts| pts.len())
|
||||
.unwrap_or(0);
|
||||
|
||||
// Update all source points to target trace_id
|
||||
let new_payload = serde_json::json!({
|
||||
@@ -1857,7 +1881,10 @@ async fn merge_trace(
|
||||
"merged_from": trace_id
|
||||
});
|
||||
|
||||
let moved_count = match qdrant.update_payload_by_filter("_faces", src_filter, new_payload).await {
|
||||
let moved_count = match qdrant
|
||||
.update_payload_by_filter("_faces", src_filter, new_payload)
|
||||
.await
|
||||
{
|
||||
Ok(_) => points_count as u64,
|
||||
Err(e) => {
|
||||
return Json(serde_json::json!({
|
||||
@@ -1919,8 +1946,11 @@ async fn restore_trace(
|
||||
});
|
||||
|
||||
// Get count of points to restore
|
||||
let points_to_restore = qdrant.scroll_all_points("_faces", filter.clone(), 1).await
|
||||
.map(|pts| pts.len()).unwrap_or(0);
|
||||
let points_to_restore = qdrant
|
||||
.scroll_all_points("_faces", filter.clone(), 1)
|
||||
.await
|
||||
.map(|pts| pts.len())
|
||||
.unwrap_or(0);
|
||||
|
||||
if points_to_restore == 0 {
|
||||
return Json(serde_json::json!({
|
||||
@@ -1934,9 +1964,17 @@ async fn restore_trace(
|
||||
"status": serde_json::Value::Null
|
||||
});
|
||||
|
||||
let qdrant_restored = match qdrant.update_payload_by_filter("_faces", filter, clear_payload).await {
|
||||
let qdrant_restored = match qdrant
|
||||
.update_payload_by_filter("_faces", filter, clear_payload)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
tracing::info!("[restore_trace] Restored {} Qdrant points for trace {} in {}", points_to_restore, trace_id, file_uuid);
|
||||
tracing::info!(
|
||||
"[restore_trace] Restored {} Qdrant points for trace {} in {}",
|
||||
points_to_restore,
|
||||
trace_id,
|
||||
file_uuid
|
||||
);
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
+139
-269
@@ -88,13 +88,15 @@ pub enum SearchResult {
|
||||
#[serde(rename = "person")]
|
||||
Person {
|
||||
file_uuid: Option<String>,
|
||||
identity_id: i32,
|
||||
identity_uuid: String,
|
||||
trace_id: i32,
|
||||
external_id: String,
|
||||
name: Option<String>,
|
||||
appearance_count: i32,
|
||||
frame_count: Option<i32>,
|
||||
score: f64,
|
||||
first_appearance_time: Option<f64>,
|
||||
last_appearance_time: Option<f64>,
|
||||
start_time: Option<f64>,
|
||||
end_time: Option<f64>,
|
||||
key_frame: Option<String>,
|
||||
key_face: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -102,6 +104,7 @@ pub fn universal_search_routes() -> Router<crate::api::types::AppState> {
|
||||
Router::new()
|
||||
.route("/api/v1/search/universal", post(universal_search))
|
||||
.route("/api/v1/search/frames", post(search_frames))
|
||||
.route("/api/v1/search/people", get(search_people))
|
||||
}
|
||||
|
||||
/// Unified search across all data types
|
||||
@@ -154,10 +157,10 @@ pub async fn universal_search(
|
||||
results.extend(frame_results);
|
||||
}
|
||||
|
||||
// Search persons
|
||||
if types.contains(&"person".to_string()) {
|
||||
let person_results = search_persons_internal(&db, &req).await.unwrap_or_default();
|
||||
results.extend(person_results);
|
||||
// Search people
|
||||
if types.contains(&"people".to_string()) || types.is_empty() {
|
||||
let people_results = search_persons_internal(&db, &req).await.unwrap_or_default();
|
||||
results.extend(people_results);
|
||||
}
|
||||
|
||||
// Deduplicate by chunk_id / frame_number / person_id
|
||||
@@ -168,7 +171,7 @@ pub async fn universal_search(
|
||||
results.retain(|r| match r {
|
||||
SearchResult::Chunk { chunk_id, .. } => seen_chunks.insert(chunk_id.clone()),
|
||||
SearchResult::Frame { frame_number, .. } => seen_frames.insert(*frame_number),
|
||||
SearchResult::Person { identity_id, .. } => seen_persons.insert(*identity_id),
|
||||
SearchResult::Person { trace_id, .. } => seen_persons.insert(*trace_id),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -236,11 +239,11 @@ pub async fn search_frames(
|
||||
}))
|
||||
}
|
||||
|
||||
/// Search persons by name or speaker_id
|
||||
pub async fn search_persons(
|
||||
/// Search people by name from trace_profiles (named face tracks)
|
||||
pub async fn search_people(
|
||||
State(_state): State<crate::api::types::AppState>,
|
||||
Query(query): Query<PersonSearchQuery>,
|
||||
) -> Result<Json<PersonSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
Query(query): Query<PeopleSearchQuery>,
|
||||
) -> Result<Json<PeopleSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let db = PostgresDb::init().await.map_err(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
@@ -249,7 +252,7 @@ pub async fn search_persons(
|
||||
})?;
|
||||
|
||||
let limit = query.limit.unwrap_or(20);
|
||||
let persons = search_persons_by_query(
|
||||
let people = search_people_by_query(
|
||||
&db,
|
||||
&query.file_uuid,
|
||||
&query.query,
|
||||
@@ -264,10 +267,10 @@ pub async fn search_persons(
|
||||
)
|
||||
})?;
|
||||
|
||||
let persons_count = persons.len();
|
||||
Ok(Json(PersonSearchResponse {
|
||||
persons,
|
||||
total: persons_count,
|
||||
let total = people.len();
|
||||
Ok(Json(PeopleSearchResponse {
|
||||
people,
|
||||
total,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -301,27 +304,34 @@ pub struct FrameResult {
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct PersonSearchQuery {
|
||||
pub file_uuid: String,
|
||||
pub struct PeopleSearchQuery {
|
||||
pub file_uuid: Option<String>,
|
||||
pub query: Option<String>,
|
||||
pub min_appearances: Option<i32>,
|
||||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PersonSearchResponse {
|
||||
pub persons: Vec<PersonResult>,
|
||||
pub struct PeopleSearchResponse {
|
||||
pub people: Vec<PeopleResult>,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PersonResult {
|
||||
pub identity_id: i32,
|
||||
pub identity_uuid: String,
|
||||
pub struct PeopleResult {
|
||||
pub file_uuid: String,
|
||||
pub file_name: String,
|
||||
pub trace_id: i32,
|
||||
pub external_id: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub appearance_count: i32,
|
||||
pub first_appearance_time: Option<f64>,
|
||||
pub last_appearance_time: Option<f64>,
|
||||
pub start_frame: Option<i64>,
|
||||
pub end_frame: Option<i64>,
|
||||
pub frame_count: Option<i32>,
|
||||
pub start_time: Option<f64>,
|
||||
pub end_time: Option<f64>,
|
||||
pub key_frame: Option<String>,
|
||||
pub key_face: Option<String>,
|
||||
pub avg_confidence: Option<f64>,
|
||||
}
|
||||
|
||||
async fn search_chunks(
|
||||
@@ -590,162 +600,65 @@ async fn search_persons_internal(
|
||||
db: &PostgresDb,
|
||||
req: &UniversalSearchRequest,
|
||||
) -> Result<Vec<SearchResult>, anyhow::Error> {
|
||||
let id_table = schema::table_name("identities");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let nodes_table = schema::table_name("tkg_nodes");
|
||||
|
||||
// Query matching identities from PostgreSQL
|
||||
let mut id_sql = format!(
|
||||
"SELECT id, uuid::text, name FROM {} WHERE name IS NOT NULL",
|
||||
id_table
|
||||
let mut sql = format!(
|
||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
||||
tp.start_frame, tp.end_frame, tp.frame_count, \
|
||||
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
||||
n.external_id \
|
||||
FROM {} tp \
|
||||
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
||||
AND n.node_type = 'face_track' \
|
||||
AND REPLACE(n.external_id, 'trace_', '')::int = tp.trace_id \
|
||||
WHERE tp.name IS NOT NULL AND tp.name != ''",
|
||||
tp_table, nodes_table
|
||||
);
|
||||
if !req.query.is_empty() {
|
||||
let q = req.query.replace('\'', "''");
|
||||
id_sql.push_str(&format!(" AND name ILIKE '%{}%'", q));
|
||||
sql.push_str(&format!(
|
||||
" AND (tp.name ILIKE '%{0}%' \
|
||||
OR tp.vlm_description ILIKE '%{0}%' \
|
||||
OR tp.vlm_clothing ILIKE '%{0}%' \
|
||||
OR EXISTS (SELECT 1 FROM unnest(tp.vlm_tags) tag WHERE tag ILIKE '%{0}%') \
|
||||
OR tp.vlm_location ILIKE '%{0}%' \
|
||||
OR tp.vlm_setting ILIKE '%{0}%')",
|
||||
q
|
||||
));
|
||||
}
|
||||
id_sql.push_str(" ORDER BY name ASC");
|
||||
|
||||
let identities: Vec<(i32, String, Option<String>)> =
|
||||
sqlx::query_as(&id_sql).fetch_all(db.pool()).await?;
|
||||
|
||||
if identities.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
if let Some(ref fuuid) = req.file_uuid {
|
||||
let safe = fuuid.replace('\'', "''");
|
||||
sql.push_str(&format!(" AND tp.file_uuid = '{}'", safe));
|
||||
}
|
||||
sql.push_str(&format!(" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", req.page_size.unwrap_or(20)));
|
||||
|
||||
// For each identity, scroll _faces points from Qdrant and aggregate per file
|
||||
let qdrant = QdrantDb::new();
|
||||
let limit = req.page_size.unwrap_or(20);
|
||||
let rows: Vec<(String, i32, Option<String>, Option<i64>, Option<i64>, Option<i32>,
|
||||
Option<String>, Option<String>, Option<f64>, Option<String>)> =
|
||||
sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
||||
|
||||
// Aggregate frame ranges per (identity_id, file_uuid)
|
||||
use std::collections::HashMap;
|
||||
let mut agg: HashMap<(i32, String), (i64, i64, i64)> = HashMap::new(); // (id, fu) -> (count, min_frame, max_frame)
|
||||
|
||||
for (id, _uuid, _name) in &identities {
|
||||
let scroll_filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "identity_id", "match": {"value": id}}
|
||||
]
|
||||
});
|
||||
|
||||
let points = match qdrant
|
||||
.scroll_all_points("_faces", scroll_filter, 1000)
|
||||
.await
|
||||
{
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::warn!("Qdrant scroll failed for identity {}: {}", id, e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
for point in &points {
|
||||
let payload = &point["payload"];
|
||||
let file_uuid = match payload["file_uuid"].as_str() {
|
||||
Some(f) => f.to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
// Apply file_uuid filter if specified
|
||||
if let Some(ref filter_fu) = req.file_uuid {
|
||||
if &file_uuid != filter_fu {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let frame = payload["frame"].as_i64().unwrap_or(0);
|
||||
let entry = agg
|
||||
.entry((*id, file_uuid))
|
||||
.or_insert((0, i64::MAX, i64::MIN));
|
||||
entry.0 += 1;
|
||||
if frame < entry.1 {
|
||||
entry.1 = frame;
|
||||
}
|
||||
if frame > entry.2 {
|
||||
entry.2 = frame;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cache FPS per file_uuid for frame→second conversion
|
||||
use std::collections::HashSet;
|
||||
let file_uuids: HashSet<&str> = agg.keys().map(|(_, fu)| fu.as_str()).collect();
|
||||
let video_table = crate::core::db::schema::table_name("videos");
|
||||
let mut fps_cache: HashMap<String, f64> = HashMap::new();
|
||||
for fu in file_uuids {
|
||||
let fps: f64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COALESCE(fps, 30.0) FROM {} WHERE file_uuid = $1",
|
||||
video_table
|
||||
))
|
||||
.bind(fu)
|
||||
.fetch_optional(db.pool())
|
||||
.await?
|
||||
.unwrap_or(30.0);
|
||||
fps_cache.insert(fu.to_string(), fps);
|
||||
}
|
||||
|
||||
// Build results
|
||||
let q_lower = req.query.to_lowercase();
|
||||
let mut results: Vec<SearchResult> = identities
|
||||
.iter()
|
||||
.flat_map(|(id, uuid, name)| {
|
||||
let name_str = name.as_deref().unwrap_or("");
|
||||
let name_match = !req.query.is_empty() && name_str.to_lowercase().contains(&q_lower);
|
||||
let score = if name_match { 0.95 } else { 0.5 };
|
||||
// Yield entries for this identity's files
|
||||
let files: Vec<String> = agg
|
||||
.keys()
|
||||
.filter(|(iid, _)| iid == id)
|
||||
.map(|(_, fu)| fu.clone())
|
||||
.collect();
|
||||
if files.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
files
|
||||
.into_iter()
|
||||
.map(|fu| {
|
||||
let (count, min_fr, max_fr) = agg[&(*id, fu.clone())];
|
||||
let fps = fps_cache.get(&fu).copied().unwrap_or(30.0);
|
||||
let first = if min_fr == i64::MAX {
|
||||
None
|
||||
} else {
|
||||
Some(min_fr as f64 / fps)
|
||||
};
|
||||
let last = if max_fr == i64::MIN {
|
||||
None
|
||||
} else {
|
||||
Some(max_fr as f64 / fps)
|
||||
};
|
||||
SearchResult::Person {
|
||||
file_uuid: Some(fu),
|
||||
identity_id: *id,
|
||||
identity_uuid: uuid.clone(),
|
||||
name: name.clone(),
|
||||
appearance_count: count as i32,
|
||||
score,
|
||||
first_appearance_time: first,
|
||||
last_appearance_time: last,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mut results: Vec<SearchResult> = Vec::new();
|
||||
for (fuuid, trace_id, name, start_frame, end_frame, frame_count,
|
||||
key_frame, key_face, avg_confidence, external_id) in rows
|
||||
{
|
||||
let name_match = !req.query.is_empty()
|
||||
&& name.as_deref().map(|n| n.to_lowercase().contains(&q_lower)).unwrap_or(false);
|
||||
let score = if name_match { 0.95 } else { 0.5 };
|
||||
|
||||
// Sort by appearance_count descending, then limit
|
||||
results.sort_by(|a, b| {
|
||||
let a_count = match a {
|
||||
SearchResult::Person {
|
||||
appearance_count, ..
|
||||
} => *appearance_count,
|
||||
_ => 0,
|
||||
};
|
||||
let b_count = match b {
|
||||
SearchResult::Person {
|
||||
appearance_count, ..
|
||||
} => *appearance_count,
|
||||
_ => 0,
|
||||
};
|
||||
b_count.cmp(&a_count)
|
||||
});
|
||||
results.truncate(limit);
|
||||
results.push(SearchResult::Person {
|
||||
file_uuid: Some(fuuid),
|
||||
trace_id,
|
||||
external_id: external_id.unwrap_or_else(|| format!("trace_{}", trace_id)),
|
||||
name,
|
||||
frame_count,
|
||||
score,
|
||||
start_time: None,
|
||||
end_time: None,
|
||||
key_frame,
|
||||
key_face,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
@@ -831,114 +744,71 @@ async fn search_frames_internal_v2(
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
async fn search_persons_by_query(
|
||||
async fn search_people_by_query(
|
||||
db: &PostgresDb,
|
||||
file_uuid: &str,
|
||||
file_uuid: &Option<String>,
|
||||
query: &Option<String>,
|
||||
min_appearances: Option<i32>,
|
||||
_min_appearances: Option<i32>,
|
||||
limit: usize,
|
||||
) -> Result<Vec<PersonResult>, anyhow::Error> {
|
||||
let id_table = schema::table_name("identities");
|
||||
) -> Result<Vec<PeopleResult>, anyhow::Error> {
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let nodes_table = schema::table_name("tkg_nodes");
|
||||
|
||||
// Query matching identities from PostgreSQL
|
||||
let mut id_sql = format!(
|
||||
"SELECT id, uuid::text, name FROM {} WHERE name IS NOT NULL",
|
||||
id_table
|
||||
let mut sql = format!(
|
||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
||||
tp.start_frame, tp.end_frame, tp.frame_count, \
|
||||
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
||||
n.external_id \
|
||||
FROM {} tp \
|
||||
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
||||
AND n.node_type = 'face_track' \
|
||||
AND REPLACE(n.external_id, 'trace_', '')::int = tp.trace_id \
|
||||
WHERE tp.name IS NOT NULL AND tp.name != ''",
|
||||
tp_table, nodes_table
|
||||
);
|
||||
if let Some(q) = query {
|
||||
let safe = q.replace('\'', "''");
|
||||
id_sql.push_str(&format!(" AND name ILIKE '%{}%'", safe));
|
||||
sql.push_str(&format!(
|
||||
" AND (tp.name ILIKE '%{0}%' \
|
||||
OR tp.vlm_description ILIKE '%{0}%' \
|
||||
OR tp.vlm_clothing ILIKE '%{0}%' \
|
||||
OR EXISTS (SELECT 1 FROM unnest(tp.vlm_tags) tag WHERE tag ILIKE '%{0}%') \
|
||||
OR tp.vlm_location ILIKE '%{0}%' \
|
||||
OR tp.vlm_setting ILIKE '%{0}%')",
|
||||
safe
|
||||
));
|
||||
}
|
||||
id_sql.push_str(" ORDER BY name ASC");
|
||||
|
||||
let identities: Vec<(i32, String, Option<String>)> =
|
||||
sqlx::query_as(&id_sql).fetch_all(db.pool()).await?;
|
||||
|
||||
if identities.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
if let Some(fuuid) = file_uuid {
|
||||
let safe = fuuid.replace('\'', "''");
|
||||
sql.push_str(&format!(" AND tp.file_uuid = '{}'", safe));
|
||||
}
|
||||
sql.push_str(&format!(" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", limit));
|
||||
|
||||
// For each identity, scroll _faces points from Qdrant and aggregate
|
||||
let qdrant = QdrantDb::new();
|
||||
let mut results: Vec<PersonResult> = Vec::new();
|
||||
let rows: Vec<(String, i32, Option<String>, Option<i64>, Option<i64>, Option<i32>,
|
||||
Option<String>, Option<String>, Option<f64>, Option<String>)> =
|
||||
sqlx::query_as(&sql).fetch_all(db.pool()).await?;
|
||||
|
||||
for (id, uuid, name) in &identities {
|
||||
let scroll_filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "identity_id", "match": {"value": id}},
|
||||
{"key": "file_uuid", "match": {"value": file_uuid}}
|
||||
]
|
||||
});
|
||||
|
||||
let points = match qdrant
|
||||
.scroll_all_points("_faces", scroll_filter, 1000)
|
||||
.await
|
||||
{
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::warn!("Qdrant scroll failed for identity {}: {}", id, e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if points.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let count = points.len() as i64;
|
||||
if let Some(min) = min_appearances {
|
||||
if (count as i32) < min {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let min_frame = points
|
||||
.iter()
|
||||
.filter_map(|p| p["payload"]["frame"].as_i64())
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let max_frame = points
|
||||
.iter()
|
||||
.filter_map(|p| p["payload"]["frame"].as_i64())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
// Look up FPS for this file
|
||||
let video_table = crate::core::db::schema::table_name("videos");
|
||||
let fps: f64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COALESCE(fps, 30.0) FROM {} WHERE file_uuid = $1",
|
||||
video_table
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.fetch_optional(db.pool())
|
||||
.await?
|
||||
.unwrap_or(30.0);
|
||||
|
||||
let first_time = if fps > 0.0 {
|
||||
Some(min_frame as f64 / fps)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let last_time = if fps > 0.0 {
|
||||
Some(max_frame as f64 / fps)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
results.push(PersonResult {
|
||||
identity_id: *id,
|
||||
identity_uuid: uuid.clone(),
|
||||
name: name.clone(),
|
||||
appearance_count: count as i32,
|
||||
first_appearance_time: first_time,
|
||||
last_appearance_time: last_time,
|
||||
let mut results: Vec<PeopleResult> = Vec::new();
|
||||
for (fuuid, trace_id, name, start_frame, end_frame, frame_count,
|
||||
key_frame, key_face, avg_confidence, external_id) in rows
|
||||
{
|
||||
results.push(PeopleResult {
|
||||
file_uuid: fuuid,
|
||||
file_name: String::new(),
|
||||
trace_id,
|
||||
external_id,
|
||||
name,
|
||||
start_frame,
|
||||
end_frame,
|
||||
frame_count,
|
||||
start_time: None,
|
||||
end_time: None,
|
||||
key_frame,
|
||||
key_face,
|
||||
avg_confidence,
|
||||
});
|
||||
}
|
||||
|
||||
// Sort by appearance_count descending, then limit
|
||||
results.sort_by(|a, b| b.appearance_count.cmp(&a.appearance_count));
|
||||
results.truncate(limit);
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -25,11 +25,12 @@ pub async fn handle_agent(tool: &str, args_str: &str) -> Result<()> {
|
||||
"get_file_info" => tools::exec_get_file_info(pool, &args).await,
|
||||
"get_representative_frame" => tools::exec_get_representative_frame(pool, &args).await,
|
||||
"analyze_frame" => tools::exec_analyze_frame(pool, &args).await,
|
||||
"vlm_describe" => tools::exec_vlm_describe(pool, &args).await,
|
||||
_ => anyhow::bail!(
|
||||
"Unknown tool: {}. Available tools: find_file, list_files, tkg_query, \
|
||||
tkg_nodes_query, tkg_edges_query, tkg_node_detail, smart_search, \
|
||||
identity_text, identities_search, get_identity_detail, get_file_info, \
|
||||
get_representative_frame, analyze_frame",
|
||||
get_representative_frame, analyze_frame, vlm_describe",
|
||||
tool
|
||||
),
|
||||
};
|
||||
|
||||
+437
-88
@@ -4,6 +4,7 @@ use std::time::Duration;
|
||||
|
||||
use crate::core::db::qdrant_db::QdrantDb;
|
||||
use crate::core::db::schema;
|
||||
use crate::core::embedding::Embedder;
|
||||
use crate::core::llm::function_calling::call_llm_vision;
|
||||
use crate::core::processor::tkg::query_auto_representative_frame;
|
||||
|
||||
@@ -54,7 +55,12 @@ pub async fn exec_find_file(
|
||||
let mut files = Vec::new();
|
||||
for (u, n) in rows {
|
||||
let has_data = has_faces_in_qdrant(&u).await;
|
||||
files.push(serde_json::json!({"file_uuid": u, "file_name": n, "has_data": has_data}));
|
||||
files.push(serde_json::json!({
|
||||
"card_type": "file",
|
||||
"file_uuid": u,
|
||||
"file_name": n,
|
||||
"has_data": has_data
|
||||
}));
|
||||
}
|
||||
Ok(serde_json::json!({"found": true, "files": files}).to_string())
|
||||
}
|
||||
@@ -551,104 +557,117 @@ pub async fn exec_smart_search(
|
||||
args: &serde_json::Value,
|
||||
) -> Result<String, String> {
|
||||
let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let file_uuid = args.get("file_uuid").and_then(|v| v.as_str());
|
||||
let limit = args.get("limit").and_then(|v| v.as_i64()).unwrap_or(5);
|
||||
let file_uuid = args
|
||||
.get("file_uuid")
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty() && *s != "<nil>" && *s != "null");
|
||||
let limit = args.get("limit").and_then(|v| v.as_i64()).unwrap_or(5) as i64;
|
||||
|
||||
tracing::info!("[smart_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit);
|
||||
|
||||
let chunk_table = schema::table_name("chunk");
|
||||
let videos = schema::table_name("videos");
|
||||
let mut sql = format!(
|
||||
"SELECT chunk_id, text_content, start_frame, end_frame, chunk_type, content \
|
||||
FROM {} WHERE text_content ILIKE $1",
|
||||
chunk_table
|
||||
"SELECT c.chunk_id, c.text_content, c.start_frame, c.end_frame, c.chunk_type, c.content, \
|
||||
c.file_uuid, v.file_name, COALESCE(v.fps, 25.0) as fps \
|
||||
FROM {} c \
|
||||
LEFT JOIN {} v ON v.file_uuid = c.file_uuid \
|
||||
WHERE c.text_content ILIKE $1",
|
||||
chunk_table, videos
|
||||
);
|
||||
if file_uuid.is_some() {
|
||||
sql.push_str(" AND file_uuid = $2");
|
||||
sql.push_str(" AND c.file_uuid = $2");
|
||||
}
|
||||
sql.push_str(&format!(" ORDER BY start_frame LIMIT {}", limit));
|
||||
sql.push_str(&format!(" ORDER BY c.start_frame LIMIT {}", limit));
|
||||
|
||||
if let Some(fuid) = file_uuid {
|
||||
let like = format!("%{}%", query);
|
||||
let rows: Vec<(String, Option<String>, i64, i64, String, Option<serde_json::Value>)> = sqlx::query_as(&sql)
|
||||
let like = format!("%{}%", query);
|
||||
tracing::info!("[smart_search] SQL: {}, like: {}", sql, like);
|
||||
|
||||
let rows: Vec<(
|
||||
String,
|
||||
Option<String>,
|
||||
i64,
|
||||
i64,
|
||||
String,
|
||||
Option<serde_json::Value>,
|
||||
String,
|
||||
String,
|
||||
f64,
|
||||
)> = if let Some(fuid) = file_uuid {
|
||||
sqlx::query_as(&sql)
|
||||
.bind(&like)
|
||||
.bind(fuid)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let results: Vec<Vec<serde_json::Value>> = rows.into_iter().map(|(chunk_id, text_content, start_frame, end_frame, chunk_type, content)| {
|
||||
let source_prefix = if let Some(ref content) = content {
|
||||
let text = content.get("text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
let ocr_text = content.get("ocr_text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
|
||||
let has_asrx = !text.trim().is_empty();
|
||||
let has_ocr = !ocr_text.trim().is_empty();
|
||||
|
||||
if has_asrx && has_ocr {
|
||||
"[ASRX+OCR] "
|
||||
} else if has_asrx {
|
||||
"[ASRX] "
|
||||
} else if has_ocr {
|
||||
"[OCR] "
|
||||
} else {
|
||||
""
|
||||
}
|
||||
} else {
|
||||
""
|
||||
};
|
||||
|
||||
let prefixed_text = text_content.map(|t| format!("{}{}", source_prefix, t));
|
||||
|
||||
vec![
|
||||
serde_json::json!(chunk_id),
|
||||
serde_json::json!(prefixed_text),
|
||||
serde_json::json!(start_frame),
|
||||
serde_json::json!(end_frame),
|
||||
serde_json::json!(chunk_type),
|
||||
]
|
||||
}).collect();
|
||||
|
||||
Ok(serde_json::json!({"results": results}).to_string())
|
||||
.map_err(|e| {
|
||||
tracing::error!("[smart_search] Query failed: {}", e);
|
||||
e.to_string()
|
||||
})?
|
||||
} else {
|
||||
let like = format!("%{}%", query);
|
||||
let rows: Vec<(String, Option<String>, i64, i64, String, Option<serde_json::Value>)> = sqlx::query_as(&sql)
|
||||
sqlx::query_as(&sql)
|
||||
.bind(&like)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let results: Vec<Vec<serde_json::Value>> = rows.into_iter().map(|(chunk_id, text_content, start_frame, end_frame, chunk_type, content)| {
|
||||
let source_prefix = if let Some(ref content) = content {
|
||||
let text = content.get("text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
let ocr_text = content.get("ocr_text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
|
||||
let has_asrx = !text.trim().is_empty();
|
||||
let has_ocr = !ocr_text.trim().is_empty();
|
||||
|
||||
if has_asrx && has_ocr {
|
||||
"[ASRX+OCR] "
|
||||
} else if has_asrx {
|
||||
"[ASRX] "
|
||||
} else if has_ocr {
|
||||
"[OCR] "
|
||||
.map_err(|e| {
|
||||
tracing::error!("[smart_search] Query failed: {}", e);
|
||||
e.to_string()
|
||||
})?
|
||||
};
|
||||
|
||||
tracing::info!("[smart_search] Found {} rows", rows.len());
|
||||
|
||||
let cards: Vec<serde_json::Value> = rows
|
||||
.into_iter()
|
||||
.map(
|
||||
|(chunk_id, text_content, start_frame, end_frame, chunk_type, content, fuuid, file_name, fps)| {
|
||||
let source = if let Some(ref c) = content {
|
||||
let text = c.get("text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
let ocr_text = c.get("ocr_text").and_then(|t| t.as_str()).unwrap_or("");
|
||||
if !text.trim().is_empty() && !ocr_text.trim().is_empty() {
|
||||
"asrx+ocr"
|
||||
} else if !text.trim().is_empty() {
|
||||
"asrx"
|
||||
} else if !ocr_text.trim().is_empty() {
|
||||
"ocr"
|
||||
} else {
|
||||
"unknown"
|
||||
}
|
||||
} else {
|
||||
""
|
||||
}
|
||||
} else {
|
||||
""
|
||||
};
|
||||
|
||||
let prefixed_text = text_content.map(|t| format!("{}{}", source_prefix, t));
|
||||
|
||||
vec![
|
||||
serde_json::json!(chunk_id),
|
||||
serde_json::json!(prefixed_text),
|
||||
serde_json::json!(start_frame),
|
||||
serde_json::json!(end_frame),
|
||||
serde_json::json!(chunk_type),
|
||||
]
|
||||
}).collect();
|
||||
|
||||
Ok(serde_json::json!({"results": results}).to_string())
|
||||
}
|
||||
"unknown"
|
||||
};
|
||||
|
||||
let text_preview = text_content
|
||||
.as_ref()
|
||||
.map(|t| t.chars().take(150).collect::<String>())
|
||||
.unwrap_or_default();
|
||||
|
||||
let start_time = if fps > 0.0 { start_frame as f64 / fps } else { 0.0 };
|
||||
let end_time = if fps > 0.0 { end_frame as f64 / fps } else { 0.0 };
|
||||
|
||||
serde_json::json!({
|
||||
"card_type": "chunk",
|
||||
"file_uuid": fuuid,
|
||||
"chunk_id": chunk_id,
|
||||
"chunk_type": chunk_type,
|
||||
"file_name": file_name,
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start_frame": start_frame,
|
||||
"end_frame": end_frame,
|
||||
"score": 1.0,
|
||||
"text_preview": text_preview,
|
||||
"source": source
|
||||
})
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"tool": "smart_search",
|
||||
"query": query,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
}).to_string())
|
||||
}
|
||||
|
||||
pub async fn exec_identity_text(
|
||||
@@ -1268,14 +1287,16 @@ pub async fn exec_vlm_describe(
|
||||
return Ok(serde_json::json!({"error": "file_uuid is required"}).to_string());
|
||||
}
|
||||
if trace_id <= 0 {
|
||||
return Ok(serde_json::json!({"error": "trace_id is required and must be > 0"}).to_string());
|
||||
return Ok(
|
||||
serde_json::json!({"error": "trace_id is required and must be > 0"}).to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let crop_path = face_crop_path(file_uuid, trace_id)
|
||||
.ok_or_else(|| format!("No face crop found for {} trace {}", file_uuid, trace_id))?;
|
||||
|
||||
let jpeg_bytes = std::fs::read(&crop_path)
|
||||
.map_err(|e| format!("Failed to read face crop: {}", e))?;
|
||||
let jpeg_bytes =
|
||||
std::fs::read(&crop_path).map_err(|e| format!("Failed to read face crop: {}", e))?;
|
||||
|
||||
let videos = schema::table_name("videos");
|
||||
let fps: f64 = sqlx::query_scalar(&format!(
|
||||
@@ -1297,8 +1318,8 @@ pub async fn exec_vlm_describe(
|
||||
|
||||
let base64_img = BASE64.encode(&jpeg_bytes);
|
||||
|
||||
let ollama_url = std::env::var("OLLAMA_URL")
|
||||
.unwrap_or_else(|_| "http://localhost:11434".to_string());
|
||||
let ollama_url =
|
||||
std::env::var("OLLAMA_URL").unwrap_or_else(|_| "http://localhost:11434".to_string());
|
||||
let model = std::env::var("VLM_MODEL").unwrap_or_else(|_| "llava".to_string());
|
||||
|
||||
let body = serde_json::json!({
|
||||
@@ -1346,3 +1367,331 @@ pub async fn exec_vlm_describe(
|
||||
})
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// Search trace profiles by VLM fields (description, clothing, tags, location, setting, name)
|
||||
/// Returns top N matching traces as cards with file_uuid, trace_id, name, frame_range, VLM data
|
||||
pub async fn exec_trace_search(
|
||||
pool: &sqlx::PgPool,
|
||||
args: &serde_json::Value,
|
||||
) -> Result<String, String> {
|
||||
let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let file_uuid = args.get("file_uuid").and_then(|v| v.as_str());
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(10)
|
||||
.min(50) as i32;
|
||||
|
||||
if query.is_empty() {
|
||||
return Err("query is required".to_string());
|
||||
}
|
||||
|
||||
let table = schema::table_name("trace_profiles");
|
||||
let videos = schema::table_name("videos");
|
||||
let like_q = format!("%{}%", query.to_lowercase().replace('%', "%%"));
|
||||
|
||||
let sql = format!(
|
||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, tp.start_frame, tp.end_frame, \
|
||||
tp.frame_count, tp.key_frame, tp.status, tp.avg_confidence, \
|
||||
tp.vlm_description, tp.vlm_clothing, tp.vlm_tags, tp.vlm_location, \
|
||||
tp.vlm_setting, tp.vlm_lighting, COALESCE(v.file_name, ''), COALESCE(v.fps, 25.0) \
|
||||
FROM {} tp \
|
||||
LEFT JOIN {} v ON v.file_uuid = tp.file_uuid \
|
||||
WHERE ($1::text IS NULL OR tp.file_uuid = $1) \
|
||||
AND (LOWER(tp.name) LIKE $2 \
|
||||
OR LOWER(tp.vlm_description) LIKE $2 \
|
||||
OR LOWER(tp.vlm_clothing) LIKE $2 \
|
||||
OR EXISTS (SELECT 1 FROM unnest(tp.vlm_tags) tag WHERE LOWER(tag) LIKE $2) \
|
||||
OR LOWER(tp.vlm_location) LIKE $2 \
|
||||
OR LOWER(tp.vlm_setting) LIKE $2 \
|
||||
OR LOWER(tp.vlm_background) LIKE $2) \
|
||||
ORDER BY tp.frame_count DESC \
|
||||
LIMIT $3",
|
||||
table, videos
|
||||
);
|
||||
|
||||
let rows = sqlx::query(&sql)
|
||||
.bind(file_uuid)
|
||||
.bind(&like_q)
|
||||
.bind(limit)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|e| format!("DB query failed: {}", e))?;
|
||||
|
||||
let cards: Vec<serde_json::Value> = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
use sqlx::Row;
|
||||
let file_uuid: String = row.get(0);
|
||||
let trace_id: i32 = row.get(1);
|
||||
let name: Option<String> = row.get(2);
|
||||
let start_frame: Option<i64> = row.get(3);
|
||||
let end_frame: Option<i64> = row.get(4);
|
||||
let frame_count: Option<i32> = row.get(5);
|
||||
let key_frame: Option<String> = row.get(6);
|
||||
let status: Option<String> = row.get(7);
|
||||
let avg_confidence: Option<f64> = row.get(8);
|
||||
let vlm_description: Option<String> = row.get(9);
|
||||
let vlm_clothing: Option<String> = row.get(10);
|
||||
let vlm_tags: Option<Vec<String>> = row.get(11);
|
||||
let vlm_location: Option<String> = row.get(12);
|
||||
let vlm_setting: Option<String> = row.get(13);
|
||||
let vlm_lighting: Option<String> = row.get(14);
|
||||
let file_name: String = row.get(15);
|
||||
let fps: f64 = row.get(16);
|
||||
|
||||
let start_time = start_frame.map(|f| (f as f64 / fps).round() / 100.0);
|
||||
let end_time = end_frame.map(|f| (f as f64 / fps).round() / 100.0);
|
||||
|
||||
serde_json::json!({
|
||||
"card_type": "face",
|
||||
"file_uuid": file_uuid,
|
||||
"trace_id": trace_id,
|
||||
"name": name,
|
||||
"file_name": file_name,
|
||||
"start_frame": start_frame,
|
||||
"end_frame": end_frame,
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"frame_count": frame_count,
|
||||
"key_frame": key_frame,
|
||||
"status": status,
|
||||
"avg_confidence": avg_confidence,
|
||||
"vlm_description": vlm_description,
|
||||
"vlm_clothing": vlm_clothing,
|
||||
"vlm_tags": vlm_tags,
|
||||
"vlm_location": vlm_location,
|
||||
"vlm_setting": vlm_setting,
|
||||
"vlm_lighting": vlm_lighting
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(
|
||||
serde_json::json!({
|
||||
"tool": "trace_search",
|
||||
"query": query,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Semantic search using embedding + Qdrant
|
||||
/// Returns top N chunk results with video segment info
|
||||
pub async fn exec_semantic_search(
|
||||
pool: &sqlx::PgPool,
|
||||
args: &serde_json::Value,
|
||||
) -> Result<String, String> {
|
||||
let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let file_uuid = args
|
||||
.get("file_uuid")
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty() && *s != "<nil>" && *s != "null");
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(10)
|
||||
.min(50) as usize;
|
||||
|
||||
tracing::info!("[exec_semantic_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit);
|
||||
|
||||
if query.is_empty() {
|
||||
return Err("query is required".to_string());
|
||||
}
|
||||
|
||||
// Generate embedding
|
||||
let embedder = Embedder::new("embeddinggemma-300m".to_string());
|
||||
let embedding = embedder
|
||||
.embed_query(query)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[exec_semantic_search] Embedding failed: {}", e);
|
||||
format!("Embedding failed: {}", e)
|
||||
})?;
|
||||
|
||||
tracing::info!("[exec_semantic_search] Embedding generated, dim={}", embedding.len());
|
||||
|
||||
// Search Qdrant
|
||||
let qdrant = QdrantDb::new();
|
||||
let search_results = if let Some(fuuid) = file_uuid {
|
||||
tracing::info!("[exec_semantic_search] Searching in uuid: {}", fuuid);
|
||||
qdrant
|
||||
.search_in_uuid(&embedding, fuuid, limit)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[exec_semantic_search] Qdrant search_in_uuid failed: {}", e);
|
||||
format!("Qdrant search failed: {}", e)
|
||||
})?
|
||||
} else {
|
||||
tracing::info!("[exec_semantic_search] Searching all collections");
|
||||
qdrant
|
||||
.search(&embedding, limit)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[exec_semantic_search] Qdrant search failed: {}", e);
|
||||
format!("Qdrant search failed: {}", e)
|
||||
})?
|
||||
};
|
||||
|
||||
tracing::info!("[exec_semantic_search] Qdrant returned {} hits", search_results.len());
|
||||
|
||||
// Enrich from PostgreSQL
|
||||
let chunk_table = schema::table_name("chunk");
|
||||
let videos = schema::table_name("videos");
|
||||
|
||||
let mut cards = Vec::new();
|
||||
for hit in search_results.iter() {
|
||||
let row: Option<(
|
||||
String,
|
||||
String,
|
||||
f64,
|
||||
f64,
|
||||
f64,
|
||||
Option<String>,
|
||||
String,
|
||||
)> = sqlx::query_as(&format!(
|
||||
"SELECT c.chunk_id, c.chunk_type, c.start_time, c.end_time, c.fps, \
|
||||
c.text_content, v.file_name \
|
||||
FROM {} c \
|
||||
JOIN {} v ON v.file_uuid = c.file_uuid \
|
||||
WHERE c.file_uuid = $1 AND c.chunk_id = $2",
|
||||
chunk_table, videos
|
||||
))
|
||||
.bind(&hit.uuid)
|
||||
.bind(&hit.chunk_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| format!("PG query failed: {}", e))?;
|
||||
|
||||
if let Some((chunk_id, chunk_type, start_time, end_time, fps, text_content, file_name)) = row {
|
||||
let start_frame = (start_time * fps) as i64;
|
||||
let end_frame = (end_time * fps) as i64;
|
||||
let text_preview = text_content
|
||||
.as_ref()
|
||||
.map(|t| t.chars().take(150).collect::<String>())
|
||||
.unwrap_or_default();
|
||||
|
||||
cards.push(serde_json::json!({
|
||||
"card_type": "chunk",
|
||||
"file_uuid": hit.uuid,
|
||||
"chunk_id": chunk_id,
|
||||
"chunk_type": chunk_type,
|
||||
"file_name": file_name,
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start_frame": start_frame,
|
||||
"end_frame": end_frame,
|
||||
"score": hit.score,
|
||||
"text_preview": text_preview,
|
||||
"source": chunk_type
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(
|
||||
serde_json::json!({
|
||||
"tool": "semantic_search",
|
||||
"query": query,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Search named face profiles by name — finds face_track TKG nodes whose label
|
||||
/// matches the given name, joined with trace_profiles for frame/key-image info.
|
||||
/// Returns cards with key_frame, key_face, frame_range, and time_range.
|
||||
pub async fn exec_face_profile_search(
|
||||
pool: &sqlx::PgPool,
|
||||
args: &serde_json::Value,
|
||||
) -> Result<String, String> {
|
||||
let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let file_uuid = args.get("file_uuid").and_then(|v| v.as_str());
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(10)
|
||||
.min(50) as i32;
|
||||
|
||||
if name.is_empty() {
|
||||
return Err("name is required".to_string());
|
||||
}
|
||||
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let nodes_table = schema::table_name("tkg_nodes");
|
||||
let like_q = format!("%{}%", name.replace('%', "%%"));
|
||||
|
||||
let sql = format!(
|
||||
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
|
||||
tp.start_frame, tp.end_frame, tp.frame_count, \
|
||||
tp.key_frame, tp.key_face, tp.avg_confidence, \
|
||||
n.external_id \
|
||||
FROM {} tp \
|
||||
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
|
||||
AND n.node_type = 'face_track' \
|
||||
AND REPLACE(n.external_id, 'trace_', '')::int = tp.trace_id \
|
||||
WHERE tp.name IS NOT NULL AND tp.name != '' \
|
||||
AND (tp.name ILIKE $1 \
|
||||
OR tp.vlm_description ILIKE $1 \
|
||||
OR tp.vlm_clothing ILIKE $1 \
|
||||
OR EXISTS (SELECT 1 FROM unnest(tp.vlm_tags) tag WHERE tag ILIKE $1) \
|
||||
OR tp.vlm_location ILIKE $1 \
|
||||
OR tp.vlm_setting ILIKE $1) \
|
||||
AND ($2::text IS NULL OR tp.file_uuid = $2) \
|
||||
ORDER BY tp.frame_count DESC NULLS LAST \
|
||||
LIMIT $3",
|
||||
tp_table, nodes_table
|
||||
);
|
||||
|
||||
let rows = sqlx::query(&sql)
|
||||
.bind(&like_q)
|
||||
.bind(file_uuid)
|
||||
.bind(limit)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|e| format!("DB query failed: {}", e))?;
|
||||
|
||||
let cards: Vec<serde_json::Value> = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
use sqlx::Row;
|
||||
let file_uuid: String = row.get(0);
|
||||
let trace_id: i32 = row.get(1);
|
||||
let name: Option<String> = row.get(2);
|
||||
let start_frame: Option<i64> = row.get(3);
|
||||
let end_frame: Option<i64> = row.get(4);
|
||||
let frame_count: Option<i32> = row.get(5);
|
||||
let key_frame: Option<String> = row.get(6);
|
||||
let key_face: Option<String> = row.get(7);
|
||||
let avg_confidence: Option<f64> = row.get(8);
|
||||
let external_id: Option<String> = row.get(9);
|
||||
|
||||
serde_json::json!({
|
||||
"card_type": "face_profile",
|
||||
"file_uuid": file_uuid,
|
||||
"trace_id": trace_id,
|
||||
"external_id": external_id.unwrap_or_else(|| format!("trace_{}", trace_id)),
|
||||
"name": name,
|
||||
"start_frame": start_frame,
|
||||
"end_frame": end_frame,
|
||||
"frame_count": frame_count,
|
||||
"key_frame": key_frame,
|
||||
"key_face": key_face,
|
||||
"avg_confidence": avg_confidence
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(
|
||||
serde_json::json!({
|
||||
"tool": "face_profile_search",
|
||||
"query": name,
|
||||
"count": cards.len(),
|
||||
"cards": cards
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ pub enum ChunkType {
|
||||
Trace,
|
||||
Story,
|
||||
Relationship,
|
||||
Ocr,
|
||||
}
|
||||
|
||||
impl ChunkType {
|
||||
@@ -21,6 +22,7 @@ impl ChunkType {
|
||||
ChunkType::Trace => "trace",
|
||||
ChunkType::Story => "story",
|
||||
ChunkType::Relationship => "relationship",
|
||||
ChunkType::Ocr => "ocr",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,10 +195,16 @@ pub enum VideoStatus {
|
||||
Registered,
|
||||
Pending,
|
||||
Queued,
|
||||
Scanning,
|
||||
Processing,
|
||||
Processed,
|
||||
Indexed,
|
||||
CheckedOut,
|
||||
KeywordReady,
|
||||
SemanticReady,
|
||||
PeopleReady,
|
||||
FaceMgmtReady,
|
||||
AgentReady,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
@@ -210,10 +216,21 @@ impl VideoStatus {
|
||||
VideoStatus::Registered => "registered",
|
||||
VideoStatus::Pending => "pending",
|
||||
VideoStatus::Queued => "queued",
|
||||
VideoStatus::Scanning => "scanning",
|
||||
VideoStatus::Processing => "processing",
|
||||
VideoStatus::Processed => "processed",
|
||||
VideoStatus::Indexed => "indexed",
|
||||
VideoStatus::CheckedOut => "checked_out",
|
||||
VideoStatus::KeywordReady => "keyword_ready",
|
||||
VideoStatus::SemanticReady => "semantic_ready",
|
||||
VideoStatus::PeopleReady => "people_ready",
|
||||
VideoStatus::FaceMgmtReady => "face_mgmt_ready",
|
||||
VideoStatus::AgentReady => "agent_ready",
|
||||
VideoStatus::Completed => "completed",
|
||||
VideoStatus::Failed => "failed",
|
||||
VideoStatus::Processed => "processed",
|
||||
VideoStatus::Indexed => "indexed",
|
||||
VideoStatus::CheckedOut => "checked_out",
|
||||
VideoStatus::Completed => "completed",
|
||||
VideoStatus::Failed => "failed",
|
||||
}
|
||||
@@ -225,10 +242,21 @@ impl VideoStatus {
|
||||
"registered" => Some(VideoStatus::Registered),
|
||||
"pending" => Some(VideoStatus::Pending),
|
||||
"queued" => Some(VideoStatus::Queued),
|
||||
"scanning" => Some(VideoStatus::Scanning),
|
||||
"processing" => Some(VideoStatus::Processing),
|
||||
"processed" => Some(VideoStatus::Processed),
|
||||
"indexed" => Some(VideoStatus::Indexed),
|
||||
"checked_out" => Some(VideoStatus::CheckedOut),
|
||||
"keyword_ready" => Some(VideoStatus::KeywordReady),
|
||||
"semantic_ready" => Some(VideoStatus::SemanticReady),
|
||||
"people_ready" => Some(VideoStatus::FaceMgmtReady),
|
||||
"face_mgmt_ready" => Some(VideoStatus::FaceMgmtReady),
|
||||
"agent_ready" => Some(VideoStatus::AgentReady),
|
||||
"completed" => Some(VideoStatus::Completed),
|
||||
"failed" => Some(VideoStatus::Failed),
|
||||
"processed" => Some(VideoStatus::Processed),
|
||||
"indexed" => Some(VideoStatus::Indexed),
|
||||
"checked_out" => Some(VideoStatus::CheckedOut),
|
||||
"completed" => Some(VideoStatus::Completed),
|
||||
"failed" => Some(VideoStatus::Failed),
|
||||
_ => None,
|
||||
@@ -264,6 +292,8 @@ pub struct VideoRow {
|
||||
pub registration_time: Option<String>,
|
||||
pub total_frames: Option<i64>,
|
||||
pub parent_uuid: Option<String>,
|
||||
pub proxy_path: Option<String>,
|
||||
pub audio_track: Option<String>,
|
||||
}
|
||||
|
||||
impl From<VideoRow> for VideoRecord {
|
||||
@@ -302,6 +332,8 @@ impl From<VideoRow> for VideoRecord {
|
||||
cut_max_duration: 0.0,
|
||||
scene_done: false,
|
||||
audio_tracks: None,
|
||||
proxy_path: row.proxy_path,
|
||||
audio_track: row.audio_track,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -333,6 +365,8 @@ pub struct VideoRecord {
|
||||
pub cut_max_duration: f64,
|
||||
pub scene_done: bool,
|
||||
pub audio_tracks: Option<serde_json::Value>,
|
||||
pub proxy_path: Option<String>,
|
||||
pub audio_track: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -963,6 +997,8 @@ impl PostgresDb {
|
||||
"cut_count INTEGER DEFAULT 0",
|
||||
"cut_max_duration DOUBLE PRECISION DEFAULT 0",
|
||||
"content_hash TEXT",
|
||||
"proxy_path TEXT",
|
||||
"audio_track TEXT",
|
||||
];
|
||||
for col in &video_cols {
|
||||
let (col_name, col_def) = col.split_once(' ').unwrap_or((col, ""));
|
||||
@@ -1196,6 +1232,12 @@ impl PostgresDb {
|
||||
// ── Strangers ──
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS strangers (id SERIAL PRIMARY KEY, file_uuid TEXT, trace_id INTEGER, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
|
||||
|
||||
// ── Trace Profiles (VLM metadata for face traces) ──
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS trace_profiles (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, trace_id INTEGER NOT NULL, name VARCHAR(255), start_frame BIGINT, end_frame BIGINT, frame_count INTEGER, key_frame VARCHAR(255), key_face VARCHAR(255), status VARCHAR(50) DEFAULT 'pending', avg_confidence DOUBLE PRECISION, vlm_description TEXT, vlm_clothing TEXT, vlm_tags TEXT[], vlm_location VARCHAR(255), vlm_setting VARCHAR(255), vlm_lighting VARCHAR(100), vlm_weather VARCHAR(100), vlm_hand_objects TEXT, vlm_has_plants BOOLEAN, vlm_has_animals BOOLEAN, vlm_background TEXT, vlm_bg_tags TEXT[], vlm_model VARCHAR(64), metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)").execute(pool).await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_name ON trace_profiles(name)").execute(pool).await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_tags ON trace_profiles USING GIN(vlm_tags)").execute(pool).await?;
|
||||
|
||||
// ── Cuts ──
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS cuts (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, cut_number INTEGER NOT NULL, start_frame BIGINT NOT NULL, end_frame BIGINT NOT NULL, start_time DOUBLE PRECISION, end_time DOUBLE PRECISION, fps DOUBLE PRECISION, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, cut_number))").execute(pool).await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_cuts_file_uuid ON cuts(file_uuid)")
|
||||
@@ -1477,7 +1519,7 @@ impl PostgresDb {
|
||||
let table = schema::table_name("videos");
|
||||
let result = sqlx::query_as::<_, VideoRow>(
|
||||
&format!(
|
||||
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid FROM {} WHERE file_uuid = $1",
|
||||
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid, proxy_path, audio_track FROM {} WHERE file_uuid = $1",
|
||||
table
|
||||
)
|
||||
)
|
||||
@@ -1503,7 +1545,7 @@ impl PostgresDb {
|
||||
let table = schema::table_name("videos");
|
||||
let result = sqlx::query_as::<_, VideoRow>(
|
||||
&format!(
|
||||
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid FROM {} WHERE file_name = $1 AND registration_time IS NOT NULL ORDER BY registration_time ASC LIMIT 1",
|
||||
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid, proxy_path, audio_track FROM {} WHERE file_name = $1 AND registration_time IS NOT NULL ORDER BY registration_time ASC LIMIT 1",
|
||||
table
|
||||
)
|
||||
)
|
||||
@@ -1587,7 +1629,7 @@ impl PostgresDb {
|
||||
.collect();
|
||||
let table = schema::table_name("videos");
|
||||
let sql = format!(
|
||||
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, parent_uuid FROM {} WHERE file_uuid = ANY($1)",
|
||||
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, parent_uuid, proxy_path, audio_track FROM {} WHERE file_uuid = ANY($1)",
|
||||
table
|
||||
);
|
||||
|
||||
@@ -1669,7 +1711,7 @@ impl PostgresDb {
|
||||
|
||||
// 2. Select Query
|
||||
// Cast created_at and registration_time to text
|
||||
let columns = "id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid";
|
||||
let columns = "id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid, proxy_path, audio_track";
|
||||
|
||||
// Determine parameter order for LIMIT/OFFSET
|
||||
// If search is present, pattern is $1. Limit is $2. Offset is $3.
|
||||
@@ -1910,7 +1952,7 @@ impl PostgresDb {
|
||||
&format!(
|
||||
r#"
|
||||
INSERT INTO {} (uuid, video_path, status, video_id, processors)
|
||||
VALUES ($1, $2, 'pending', $3, ARRAY['cut','asr','face','ocr','asrx','pose','appearance'])
|
||||
VALUES ($1, $2, 'pending', $3, ARRAY['cut','asr','face','ocr','asrx','pose'])
|
||||
RETURNING id, uuid, video_path, status, current_processor, progress_total, progress_current, error_count, last_error, started_at::TEXT, updated_at::TEXT, created_at::TEXT, processors, completed_processors, failed_processors, video_id
|
||||
"#,
|
||||
jobs_table
|
||||
@@ -2721,6 +2763,32 @@ impl PostgresDb {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_proxy_path(&self, uuid: &str, proxy_path: &str) -> Result<()> {
|
||||
let table = schema::table_name("videos");
|
||||
sqlx::query(&format!(
|
||||
"UPDATE {} SET proxy_path = $1, updated_at = CURRENT_TIMESTAMP WHERE file_uuid = $2",
|
||||
table
|
||||
))
|
||||
.bind(proxy_path)
|
||||
.bind(uuid)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_audio_track(&self, uuid: &str, audio_track: &str) -> Result<()> {
|
||||
let table = schema::table_name("videos");
|
||||
sqlx::query(&format!(
|
||||
"UPDATE {} SET audio_track = $1, updated_at = CURRENT_TIMESTAMP WHERE file_uuid = $2",
|
||||
table
|
||||
))
|
||||
.bind(audio_track)
|
||||
.bind(uuid)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_processing_status_completed(
|
||||
&self,
|
||||
uuid: &str,
|
||||
@@ -4648,6 +4716,8 @@ mod tests {
|
||||
cut_max_duration: 0.0,
|
||||
scene_done: false,
|
||||
audio_tracks: None,
|
||||
proxy_path: None,
|
||||
audio_track: None,
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&record).unwrap();
|
||||
|
||||
@@ -913,15 +913,8 @@ impl QdrantDb {
|
||||
Ok(all_points)
|
||||
}
|
||||
|
||||
pub async fn count_points(
|
||||
&self,
|
||||
collection: &str,
|
||||
filter: serde_json::Value,
|
||||
) -> Result<i64> {
|
||||
let url = format!(
|
||||
"{}/collections/{}/points/count",
|
||||
self.base_url, collection
|
||||
);
|
||||
pub async fn count_points(&self, collection: &str, filter: serde_json::Value) -> Result<i64> {
|
||||
let url = format!("{}/collections/{}/points/count", self.base_url, collection);
|
||||
|
||||
let body = serde_json::json!({
|
||||
"filter": filter,
|
||||
@@ -942,9 +935,7 @@ impl QdrantDb {
|
||||
}
|
||||
|
||||
let result: serde_json::Value = resp.json().await?;
|
||||
let count = result["result"]["count"]
|
||||
.as_i64()
|
||||
.unwrap_or(0);
|
||||
let count = result["result"]["count"].as_i64().unwrap_or(0);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,703 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Version of the lifecycle schema.
|
||||
const LIFECYCLE_VERSION: &str = "1.0";
|
||||
|
||||
// ─── Data Types ───
|
||||
|
||||
/// Complete lifecycle state for a file
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FileLifecycle {
|
||||
pub version: String,
|
||||
pub file_uuid: String,
|
||||
pub updated_at: String, // RFC3339
|
||||
pub stages: LifecycleStages,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LifecycleStages {
|
||||
/// Stage 0: Registration (profile.json, probe.json, cut.json)
|
||||
pub registration: StageState,
|
||||
/// Stage 1: First-level processors (asr, ocr, face)
|
||||
pub stage_1_processors: ProcessorGroupState,
|
||||
/// Stage 2: Second-level processors (asrx, face_vector, speaker_vector)
|
||||
pub stage_2_processors: ProcessorGroupState,
|
||||
/// Stage 3: Third-level processors (pose, appearance)
|
||||
pub stage_3_processors: ProcessorGroupState,
|
||||
/// Rule 1: Text ingestion (sentence chunks → PG + Qdrant)
|
||||
pub rule_1_ingestion: IngestionState,
|
||||
/// Rule 2: Node ingestion (face/speaker TKG nodes)
|
||||
pub rule_2_ingestion: IngestionState,
|
||||
/// Rule 3: Edge ingestion (TKG edges)
|
||||
pub rule_3_ingestion: IngestionState,
|
||||
/// Final completion
|
||||
pub completed: StageState,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StageState {
|
||||
pub status: String, // pending / in_progress / completed / failed / skipped
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub started_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub completed_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ProcessorGroupState {
|
||||
pub status: String, // pending / in_progress / completed / partial / failed
|
||||
pub processors: HashMap<String, ProcessorState>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ProcessorState {
|
||||
pub status: String, // pending / running / completed / failed / skipped
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub started_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub completed_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub progress: Option<ProgressInfo>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub output_count: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub retry_count: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ProgressInfo {
|
||||
pub current: i64,
|
||||
pub total: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IngestionState {
|
||||
pub status: String, // pending / in_progress / completed / failed / skipped
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub started_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub completed_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub items_ingested: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
// ─── Processor Definitions ───
|
||||
|
||||
/// Stage 1 processors (no dependencies, run in parallel)
|
||||
pub const STAGE_1_PROCESSORS: &[&str] = &["asr", "ocr", "face"];
|
||||
|
||||
/// Stage 2 processors (depend on stage 1)
|
||||
pub const STAGE_2_PROCESSORS: &[&str] = &["asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster"];
|
||||
|
||||
/// Stage 3 processors (depend on stage 2 or face)
|
||||
pub const STAGE_3_PROCESSORS: &[&str] = &["pose", "appearance"];
|
||||
|
||||
/// All processors in order
|
||||
pub const ALL_PROCESSORS: &[&str] = &[
|
||||
"cut", // Registration
|
||||
"asr", "ocr", "face", // Stage 1
|
||||
"asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster", // Stage 2
|
||||
"pose", "appearance", // Stage 3
|
||||
];
|
||||
|
||||
/// Get processor dependencies
|
||||
pub fn get_dependencies(processor: &str) -> Vec<&'static str> {
|
||||
match processor {
|
||||
"asrx" => vec!["cut", "asr"],
|
||||
"face_vector" => vec!["face"],
|
||||
"face_trace" => vec!["face_vector"], // trace after vectorization
|
||||
"speaker_vector" => vec!["asrx"],
|
||||
"face_cluster" => vec!["face_trace"], // deduplication after trace
|
||||
"pose" => vec!["face"],
|
||||
"appearance" => vec!["pose"],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Get processor stage
|
||||
pub fn get_stage(processor: &str) -> &'static str {
|
||||
match processor {
|
||||
"cut" => "registration",
|
||||
"asr" | "ocr" | "face" => "stage_1",
|
||||
"asrx" | "face_vector" | "face_trace" | "speaker_vector" | "face_cluster" => "stage_2",
|
||||
"pose" | "appearance" => "stage_3",
|
||||
_ => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Construction ───
|
||||
|
||||
impl FileLifecycle {
|
||||
/// Create a new lifecycle for a file
|
||||
pub fn new(file_uuid: &str) -> Self {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
let mut stage_1_processors = HashMap::new();
|
||||
for proc in STAGE_1_PROCESSORS {
|
||||
stage_1_processors.insert(proc.to_string(), ProcessorState::new("pending"));
|
||||
}
|
||||
|
||||
let mut stage_2_processors = HashMap::new();
|
||||
for proc in STAGE_2_PROCESSORS {
|
||||
stage_2_processors.insert(proc.to_string(), ProcessorState::new("pending"));
|
||||
}
|
||||
|
||||
let mut stage_3_processors = HashMap::new();
|
||||
for proc in STAGE_3_PROCESSORS {
|
||||
stage_3_processors.insert(proc.to_string(), ProcessorState::new("pending"));
|
||||
}
|
||||
|
||||
Self {
|
||||
version: LIFECYCLE_VERSION.to_string(),
|
||||
file_uuid: file_uuid.to_string(),
|
||||
updated_at: now,
|
||||
stages: LifecycleStages {
|
||||
registration: StageState::new("pending"),
|
||||
stage_1_processors: ProcessorGroupState {
|
||||
status: "pending".to_string(),
|
||||
processors: stage_1_processors,
|
||||
},
|
||||
stage_2_processors: ProcessorGroupState {
|
||||
status: "pending".to_string(),
|
||||
processors: stage_2_processors,
|
||||
},
|
||||
stage_3_processors: ProcessorGroupState {
|
||||
status: "pending".to_string(),
|
||||
processors: stage_3_processors,
|
||||
},
|
||||
rule_1_ingestion: IngestionState::new("pending"),
|
||||
rule_2_ingestion: IngestionState::new("pending"),
|
||||
rule_3_ingestion: IngestionState::new("pending"),
|
||||
completed: StageState::new("pending"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Create lifecycle from existing outputs (for recovery)
|
||||
pub fn from_existing_outputs(output_dir: &str, file_uuid: &str) -> Self {
|
||||
let mut lifecycle = Self::new(file_uuid);
|
||||
|
||||
// Check registration outputs
|
||||
let has_profile = Path::new(output_dir).join(format!("{}.profile.json", file_uuid)).exists();
|
||||
let has_probe = Path::new(output_dir).join(format!("{}.probe.json", file_uuid)).exists();
|
||||
let has_cut = Path::new(output_dir).join(format!("{}.cut.json", file_uuid)).exists();
|
||||
|
||||
if has_profile && has_probe && has_cut {
|
||||
lifecycle.mark_stage_completed("registration");
|
||||
}
|
||||
|
||||
// Check stage 1 processors
|
||||
for proc in STAGE_1_PROCESSORS {
|
||||
let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc));
|
||||
if path.exists() {
|
||||
lifecycle.mark_processor_completed(proc, None);
|
||||
}
|
||||
}
|
||||
|
||||
// Check stage 2 processors
|
||||
let has_asrx = Path::new(output_dir).join(format!("{}.asrx.json", file_uuid)).exists();
|
||||
if has_asrx {
|
||||
lifecycle.mark_processor_completed("asrx", None);
|
||||
// speaker_vector comes from asrx
|
||||
lifecycle.mark_processor_completed("speaker_vector", None);
|
||||
}
|
||||
|
||||
// face_vector: check if face.json exists (vectors stored in Qdrant)
|
||||
let has_face = Path::new(output_dir).join(format!("{}.face.json", file_uuid)).exists();
|
||||
if has_face {
|
||||
lifecycle.mark_processor_completed("face_vector", None);
|
||||
}
|
||||
|
||||
// face_trace: check face_traced.json (continuous face tracking)
|
||||
let has_face_traced = Path::new(output_dir).join(format!("{}.face_traced.json", file_uuid)).exists();
|
||||
if has_face_traced {
|
||||
lifecycle.mark_processor_completed("face_trace", None);
|
||||
}
|
||||
|
||||
// face_cluster: check face_cluster.json (deduplication of traces)
|
||||
let has_face_cluster = Path::new(output_dir).join(format!("{}.face_cluster.json", file_uuid)).exists();
|
||||
if has_face_cluster {
|
||||
lifecycle.mark_processor_completed("face_cluster", None);
|
||||
}
|
||||
|
||||
// Check stage 3 processors
|
||||
for proc in STAGE_3_PROCESSORS {
|
||||
let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc));
|
||||
if path.exists() {
|
||||
lifecycle.mark_processor_completed(proc, None);
|
||||
}
|
||||
}
|
||||
|
||||
lifecycle.update_group_status();
|
||||
lifecycle
|
||||
}
|
||||
|
||||
// ─── Persistence ───
|
||||
|
||||
/// Return the lifecycle file path: `{output_dir}/{file_uuid}.lifecycle.json`
|
||||
pub fn lifecycle_path(output_dir: &str, file_uuid: &str) -> PathBuf {
|
||||
Path::new(output_dir).join(format!("{}.lifecycle.json", file_uuid))
|
||||
}
|
||||
|
||||
/// Save lifecycle to disk
|
||||
pub fn save_to_disk(&self, output_dir: &str) -> Result<()> {
|
||||
let path = Self::lifecycle_path(output_dir, &self.file_uuid);
|
||||
let json = serde_json::to_string_pretty(self)
|
||||
.context("Failed to serialize lifecycle")?;
|
||||
std::fs::write(&path, json)
|
||||
.with_context(|| format!("Failed to write lifecycle to {}", path.display()))?;
|
||||
tracing::debug!("[Lifecycle] Saved for {}", self.file_uuid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load lifecycle from disk
|
||||
pub fn load_from_disk(output_dir: &str, file_uuid: &str) -> Option<Self> {
|
||||
let path = Self::lifecycle_path(output_dir, file_uuid);
|
||||
let content = std::fs::read_to_string(&path).ok()?;
|
||||
serde_json::from_str(&content).ok()
|
||||
}
|
||||
|
||||
/// Load or create new lifecycle
|
||||
pub fn load_or_create(output_dir: &str, file_uuid: &str) -> Self {
|
||||
Self::load_from_disk(output_dir, file_uuid)
|
||||
.unwrap_or_else(|| Self::from_existing_outputs(output_dir, file_uuid))
|
||||
}
|
||||
|
||||
// ─── State Updates ───
|
||||
|
||||
/// Mark a stage as started
|
||||
pub fn mark_stage_started(&mut self, stage: &str) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
match stage {
|
||||
"registration" => {
|
||||
self.stages.registration.status = "in_progress".to_string();
|
||||
self.stages.registration.started_at = Some(now);
|
||||
}
|
||||
"stage_1" => {
|
||||
self.stages.stage_1_processors.status = "in_progress".to_string();
|
||||
}
|
||||
"stage_2" => {
|
||||
self.stages.stage_2_processors.status = "in_progress".to_string();
|
||||
}
|
||||
"stage_3" => {
|
||||
self.stages.stage_3_processors.status = "in_progress".to_string();
|
||||
}
|
||||
"rule_1" => {
|
||||
self.stages.rule_1_ingestion.status = "in_progress".to_string();
|
||||
self.stages.rule_1_ingestion.started_at = Some(now);
|
||||
}
|
||||
"rule_2" => {
|
||||
self.stages.rule_2_ingestion.status = "in_progress".to_string();
|
||||
self.stages.rule_2_ingestion.started_at = Some(now);
|
||||
}
|
||||
"rule_3" => {
|
||||
self.stages.rule_3_ingestion.status = "in_progress".to_string();
|
||||
self.stages.rule_3_ingestion.started_at = Some(now);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark a stage as completed
|
||||
pub fn mark_stage_completed(&mut self, stage: &str) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
match stage {
|
||||
"registration" => {
|
||||
self.stages.registration.status = "completed".to_string();
|
||||
self.stages.registration.completed_at = Some(now);
|
||||
}
|
||||
"rule_1" => {
|
||||
self.stages.rule_1_ingestion.status = "completed".to_string();
|
||||
self.stages.rule_1_ingestion.completed_at = Some(now);
|
||||
}
|
||||
"rule_2" => {
|
||||
self.stages.rule_2_ingestion.status = "completed".to_string();
|
||||
self.stages.rule_2_ingestion.completed_at = Some(now);
|
||||
}
|
||||
"rule_3" => {
|
||||
self.stages.rule_3_ingestion.status = "completed".to_string();
|
||||
self.stages.rule_3_ingestion.completed_at = Some(now);
|
||||
}
|
||||
"completed" => {
|
||||
self.stages.completed.status = "completed".to_string();
|
||||
self.stages.completed.completed_at = Some(now);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark a processor as started
|
||||
pub fn mark_processor_started(&mut self, processor: &str) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &mut self.stages.stage_1_processors,
|
||||
"stage_2" => &mut self.stages.stage_2_processors,
|
||||
"stage_3" => &mut self.stages.stage_3_processors,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
if let Some(proc_state) = group.processors.get_mut(processor) {
|
||||
proc_state.status = "running".to_string();
|
||||
proc_state.started_at = Some(now);
|
||||
}
|
||||
|
||||
// Update group status
|
||||
group.status = "in_progress".to_string();
|
||||
}
|
||||
|
||||
/// Mark a processor as completed
|
||||
pub fn mark_processor_completed(&mut self, processor: &str, output_count: Option<i64>) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &mut self.stages.stage_1_processors,
|
||||
"stage_2" => &mut self.stages.stage_2_processors,
|
||||
"stage_3" => &mut self.stages.stage_3_processors,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
if let Some(proc_state) = group.processors.get_mut(processor) {
|
||||
proc_state.status = "completed".to_string();
|
||||
proc_state.completed_at = Some(now);
|
||||
proc_state.output_count = output_count;
|
||||
}
|
||||
|
||||
self.update_group_status();
|
||||
}
|
||||
|
||||
/// Mark a processor as failed
|
||||
pub fn mark_processor_failed(&mut self, processor: &str, error: &str, retry_count: i32) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
self.updated_at = now.clone();
|
||||
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &mut self.stages.stage_1_processors,
|
||||
"stage_2" => &mut self.stages.stage_2_processors,
|
||||
"stage_3" => &mut self.stages.stage_3_processors,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
if let Some(proc_state) = group.processors.get_mut(processor) {
|
||||
proc_state.status = "failed".to_string();
|
||||
proc_state.error = Some(error.to_string());
|
||||
proc_state.retry_count = Some(retry_count);
|
||||
}
|
||||
|
||||
self.update_group_status();
|
||||
}
|
||||
|
||||
/// Update processor progress
|
||||
pub fn update_processor_progress(&mut self, processor: &str, current: i64, total: i64) {
|
||||
self.updated_at = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &mut self.stages.stage_1_processors,
|
||||
"stage_2" => &mut self.stages.stage_2_processors,
|
||||
"stage_3" => &mut self.stages.stage_3_processors,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
if let Some(proc_state) = group.processors.get_mut(processor) {
|
||||
proc_state.progress = Some(ProgressInfo { current, total });
|
||||
}
|
||||
}
|
||||
|
||||
/// Update group status based on processor states
|
||||
fn update_group_status(&mut self) {
|
||||
// Update stage 1
|
||||
let stage_1 = &mut self.stages.stage_1_processors;
|
||||
stage_1.status = compute_group_status(&stage_1.processors);
|
||||
|
||||
// Update stage 2
|
||||
let stage_2 = &mut self.stages.stage_2_processors;
|
||||
stage_2.status = compute_group_status(&stage_2.processors);
|
||||
|
||||
// Update stage 3
|
||||
let stage_3 = &mut self.stages.stage_3_processors;
|
||||
stage_3.status = compute_group_status(&stage_3.processors);
|
||||
}
|
||||
|
||||
// ─── Queries ───
|
||||
|
||||
/// Check if a processor can run (dependencies met)
|
||||
pub fn can_run_processor(&self, processor: &str) -> bool {
|
||||
let deps = get_dependencies(processor);
|
||||
if deps.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
for dep in deps {
|
||||
if !self.is_processor_completed(dep) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Check if a processor is completed
|
||||
pub fn is_processor_completed(&self, processor: &str) -> bool {
|
||||
let stage = get_stage(processor);
|
||||
let group = match stage {
|
||||
"stage_1" => &self.stages.stage_1_processors,
|
||||
"stage_2" => &self.stages.stage_2_processors,
|
||||
"stage_3" => &self.stages.stage_3_processors,
|
||||
_ => return processor == "cut" && self.stages.registration.status == "completed",
|
||||
};
|
||||
|
||||
group.processors.get(processor)
|
||||
.map(|p| p.status == "completed")
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Get next processors to run
|
||||
pub fn get_next_processors(&self) -> Vec<String> {
|
||||
let mut next = Vec::new();
|
||||
|
||||
// Check stage 1
|
||||
if self.stages.registration.status != "completed" {
|
||||
return next; // Registration must complete first
|
||||
}
|
||||
|
||||
for proc in STAGE_1_PROCESSORS {
|
||||
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
|
||||
next.push(proc.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
if !next.is_empty() {
|
||||
return next;
|
||||
}
|
||||
|
||||
// Check stage 2
|
||||
for proc in STAGE_2_PROCESSORS {
|
||||
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
|
||||
next.push(proc.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
if !next.is_empty() {
|
||||
return next;
|
||||
}
|
||||
|
||||
// Check stage 3
|
||||
for proc in STAGE_3_PROCESSORS {
|
||||
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
|
||||
next.push(proc.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
next
|
||||
}
|
||||
|
||||
/// Check if all processors are complete
|
||||
pub fn all_processors_complete(&self) -> bool {
|
||||
for proc in ALL_PROCESSORS {
|
||||
if !self.is_processor_completed(proc) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Check if Rule 1 can run (text ingestion)
|
||||
pub fn can_run_rule_1(&self) -> bool {
|
||||
self.is_processor_completed("asrx")
|
||||
}
|
||||
|
||||
/// Check if Rule 2 can run (TKG nodes)
|
||||
pub fn can_run_rule_2(&self) -> bool {
|
||||
self.is_processor_completed("face_trace") && self.is_processor_completed("speaker_vector")
|
||||
}
|
||||
|
||||
/// Check if Rule 3 can run (TKG edges)
|
||||
pub fn can_run_rule_3(&self) -> bool {
|
||||
self.stages.rule_2_ingestion.status == "completed"
|
||||
}
|
||||
|
||||
/// Check if file is fully complete
|
||||
pub fn is_complete(&self) -> bool {
|
||||
self.all_processors_complete()
|
||||
&& self.stages.rule_1_ingestion.status == "completed"
|
||||
&& self.stages.rule_2_ingestion.status == "completed"
|
||||
&& self.stages.rule_3_ingestion.status == "completed"
|
||||
}
|
||||
|
||||
/// Get overall progress percentage
|
||||
pub fn overall_progress(&self) -> f64 {
|
||||
let mut completed = 0;
|
||||
let mut total = 0;
|
||||
|
||||
// Registration
|
||||
total += 1;
|
||||
if self.stages.registration.status == "completed" {
|
||||
completed += 1;
|
||||
}
|
||||
|
||||
// Stage 1
|
||||
for proc in STAGE_1_PROCESSORS {
|
||||
total += 1;
|
||||
if self.is_processor_completed(proc) {
|
||||
completed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 2
|
||||
for proc in STAGE_2_PROCESSORS {
|
||||
total += 1;
|
||||
if self.is_processor_completed(proc) {
|
||||
completed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 3
|
||||
for proc in STAGE_3_PROCESSORS {
|
||||
total += 1;
|
||||
if self.is_processor_completed(proc) {
|
||||
completed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Rules
|
||||
total += 3;
|
||||
if self.stages.rule_1_ingestion.status == "completed" { completed += 1; }
|
||||
if self.stages.rule_2_ingestion.status == "completed" { completed += 1; }
|
||||
if self.stages.rule_3_ingestion.status == "completed" { completed += 1; }
|
||||
|
||||
if total == 0 { 0.0 } else { (completed as f64 / total as f64) * 100.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl StageState {
|
||||
fn new(status: &str) -> Self {
|
||||
Self {
|
||||
status: status.to_string(),
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ProcessorState {
|
||||
fn new(status: &str) -> Self {
|
||||
Self {
|
||||
status: status.to_string(),
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
progress: None,
|
||||
output_count: None,
|
||||
error: None,
|
||||
retry_count: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IngestionState {
|
||||
fn new(status: &str) -> Self {
|
||||
Self {
|
||||
status: status.to_string(),
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
items_ingested: None,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute group status from processor states
|
||||
fn compute_group_status(processors: &HashMap<String, ProcessorState>) -> String {
|
||||
let mut has_running = false;
|
||||
let mut has_failed = false;
|
||||
let mut has_pending = false;
|
||||
let mut completed_count = 0;
|
||||
|
||||
for proc in processors.values() {
|
||||
match proc.status.as_str() {
|
||||
"running" => has_running = true,
|
||||
"failed" => has_failed = true,
|
||||
"pending" => has_pending = true,
|
||||
"completed" => completed_count += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if has_running {
|
||||
"in_progress".to_string()
|
||||
} else if has_failed {
|
||||
"failed".to_string()
|
||||
} else if has_pending {
|
||||
if completed_count > 0 {
|
||||
"partial".to_string()
|
||||
} else {
|
||||
"pending".to_string()
|
||||
}
|
||||
} else {
|
||||
"completed".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_lifecycle_new() {
|
||||
let lifecycle = FileLifecycle::new("test_uuid");
|
||||
assert_eq!(lifecycle.file_uuid, "test_uuid");
|
||||
assert_eq!(lifecycle.stages.registration.status, "pending");
|
||||
assert_eq!(lifecycle.stages.stage_1_processors.status, "pending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_processor_dependencies() {
|
||||
assert!(get_dependencies("asr").is_empty());
|
||||
assert_eq!(get_dependencies("asrx"), vec!["cut", "asr"]);
|
||||
assert_eq!(get_dependencies("pose"), vec!["face"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_can_run_processor() {
|
||||
let mut lifecycle = FileLifecycle::new("test");
|
||||
|
||||
// Initially, asrx cannot run (needs cut + asr)
|
||||
assert!(!lifecycle.can_run_processor("asrx"));
|
||||
|
||||
// After registration, still cannot run (needs asr)
|
||||
lifecycle.mark_stage_completed("registration");
|
||||
assert!(!lifecycle.can_run_processor("asrx"));
|
||||
|
||||
// After asr completes, can run
|
||||
lifecycle.mark_processor_completed("asr", Some(10));
|
||||
assert!(lifecycle.can_run_processor("asrx"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_overall_progress() {
|
||||
let mut lifecycle = FileLifecycle::new("test");
|
||||
assert_eq!(lifecycle.overall_progress(), 0.0);
|
||||
|
||||
lifecycle.mark_stage_completed("registration");
|
||||
let progress = lifecycle.overall_progress();
|
||||
assert!(progress > 0.0 && progress < 100.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Version of the file profile schema.
|
||||
const PROFILE_VERSION: &str = "1.0";
|
||||
|
||||
// ─── Data Types ───
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FileProfile {
|
||||
pub version: String,
|
||||
pub file_uuid: String,
|
||||
pub file_name: String,
|
||||
pub file_type: String,
|
||||
pub birth: BirthInfo,
|
||||
pub current: CurrentInfo,
|
||||
pub history: Vec<HistoryEntry>,
|
||||
pub metadata: Option<MediaMetadata>,
|
||||
pub key_frame: Option<String>, // filename: {uuid}.key_frame.jpg, video only
|
||||
pub proxy_path: Option<String>, // 720p proxy path for 1080p+ videos
|
||||
pub audio_track: Option<String>, // audio track classification: no_audio/silent_audio/music_only/speech_only/speech_with_music
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BirthInfo {
|
||||
pub mac_address: String,
|
||||
pub birthday: String, // RFC3339
|
||||
pub original_path: String,
|
||||
pub original_filename: String,
|
||||
pub canonical_path: String,
|
||||
pub content_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CurrentInfo {
|
||||
pub path: String,
|
||||
pub file_name: String,
|
||||
pub file_type: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HistoryEntry {
|
||||
pub action: String,
|
||||
pub timestamp: String, // RFC3339
|
||||
pub path: String,
|
||||
pub file_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MediaMetadata {
|
||||
pub duration: f64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: f64,
|
||||
pub total_frames: u64,
|
||||
}
|
||||
|
||||
// ─── Construction ───
|
||||
|
||||
impl FileProfile {
|
||||
/// Build a new profile from registration parameters.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn from_registration(
|
||||
file_uuid: &str,
|
||||
file_name: &str,
|
||||
file_type: &str,
|
||||
mac_address: &str,
|
||||
birthday: &str,
|
||||
canonical_path: &str,
|
||||
content_hash: &str,
|
||||
duration: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
fps: f64,
|
||||
total_frames: u64,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let parent = Path::new(canonical_path)
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
|
||||
Self {
|
||||
version: PROFILE_VERSION.to_string(),
|
||||
file_uuid: file_uuid.to_string(),
|
||||
file_name: file_name.to_string(),
|
||||
file_type: file_type.to_string(),
|
||||
birth: BirthInfo {
|
||||
mac_address: mac_address.to_string(),
|
||||
birthday: birthday.to_string(),
|
||||
original_path: parent,
|
||||
original_filename: file_name.to_string(),
|
||||
canonical_path: canonical_path.to_string(),
|
||||
content_hash: if content_hash.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(content_hash.to_string())
|
||||
},
|
||||
},
|
||||
current: CurrentInfo {
|
||||
path: canonical_path.to_string(),
|
||||
file_name: file_name.to_string(),
|
||||
file_type: file_type.to_string(),
|
||||
},
|
||||
history: vec![HistoryEntry {
|
||||
action: "registered".to_string(),
|
||||
timestamp: now,
|
||||
path: canonical_path.to_string(),
|
||||
file_name: file_name.to_string(),
|
||||
}],
|
||||
metadata: if duration > 0.0 || width > 0 || height > 0 {
|
||||
Some(MediaMetadata {
|
||||
duration,
|
||||
width,
|
||||
height,
|
||||
fps,
|
||||
total_frames,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
},
|
||||
key_frame: None,
|
||||
proxy_path: None,
|
||||
audio_track: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a minimal profile for zombie files (missing path/name in DB).
|
||||
pub fn from_zombie(file_uuid: &str, file_type: &str, content_hash: &str) -> Self {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
Self {
|
||||
version: PROFILE_VERSION.to_string(),
|
||||
file_uuid: file_uuid.to_string(),
|
||||
file_name: String::new(),
|
||||
file_type: file_type.to_string(),
|
||||
birth: BirthInfo {
|
||||
mac_address: String::new(),
|
||||
birthday: String::new(),
|
||||
original_path: String::new(),
|
||||
original_filename: String::new(),
|
||||
canonical_path: String::new(),
|
||||
content_hash: if content_hash.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(content_hash.to_string())
|
||||
},
|
||||
},
|
||||
current: CurrentInfo {
|
||||
path: String::new(),
|
||||
file_name: String::new(),
|
||||
file_type: file_type.to_string(),
|
||||
},
|
||||
history: vec![HistoryEntry {
|
||||
action: "recovered_zombie".to_string(),
|
||||
timestamp: now,
|
||||
path: String::new(),
|
||||
file_name: String::new(),
|
||||
}],
|
||||
metadata: None,
|
||||
key_frame: None,
|
||||
proxy_path: None,
|
||||
audio_track: None,
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Persistence ───
|
||||
|
||||
/// Return the profile file path: `{output_dir}/{file_uuid}.profile.json`
|
||||
pub fn profile_path(output_dir: &str, file_uuid: &str) -> PathBuf {
|
||||
Path::new(output_dir).join(format!("{}.profile.json", file_uuid))
|
||||
}
|
||||
|
||||
/// Save profile to disk.
|
||||
pub fn save_to_disk(&self, output_dir: &str) -> Result<()> {
|
||||
let path = Self::profile_path(output_dir, &self.file_uuid);
|
||||
let json =
|
||||
serde_json::to_string_pretty(self).context("Failed to serialize file profile")?;
|
||||
std::fs::write(&path, json)
|
||||
.with_context(|| format!("Failed to write profile to {}", path.display()))?;
|
||||
tracing::debug!("[FileProfile] Saved profile for {}", self.file_uuid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load profile from disk. Returns `None` if file doesn't exist.
|
||||
pub fn load_from_disk(output_dir: &str, file_uuid: &str) -> Option<Self> {
|
||||
let path = Self::profile_path(output_dir, file_uuid);
|
||||
let content = std::fs::read_to_string(&path).ok()?;
|
||||
serde_json::from_str(&content).ok()
|
||||
}
|
||||
|
||||
/// Load profile from disk, returning error if not found.
|
||||
pub fn load_or_error(output_dir: &str, file_uuid: &str) -> Result<Self> {
|
||||
let path = Self::profile_path(output_dir, file_uuid);
|
||||
let content = std::fs::read_to_string(&path)
|
||||
.with_context(|| format!("Profile not found: {}", path.display()))?;
|
||||
serde_json::from_str(&content).context("Failed to parse file profile")
|
||||
}
|
||||
|
||||
// ─── Updates ───
|
||||
|
||||
/// Record a path/name change. Updates `current` and appends to `history`.
|
||||
pub fn update_current_path(&mut self, new_path: &str, new_name: &str) {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
// Only record if something actually changed
|
||||
if self.current.path == new_path && self.current.file_name == new_name {
|
||||
return;
|
||||
}
|
||||
|
||||
self.history.push(HistoryEntry {
|
||||
action: "moved".to_string(),
|
||||
timestamp: now,
|
||||
path: new_path.to_string(),
|
||||
file_name: new_name.to_string(),
|
||||
});
|
||||
|
||||
self.current.path = new_path.to_string();
|
||||
self.current.file_name = new_name.to_string();
|
||||
}
|
||||
|
||||
/// Set the key_frame (base64-encoded JPEG).
|
||||
pub fn set_key_frame(&mut self, key_frame: String) {
|
||||
self.key_frame = Some(key_frame);
|
||||
}
|
||||
|
||||
/// Build a profile from existing DB data (for backfilling).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn from_db_record(
|
||||
file_uuid: &str,
|
||||
file_name: &str,
|
||||
file_path: &str,
|
||||
file_type: &str,
|
||||
content_hash: &str,
|
||||
duration: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
fps: f64,
|
||||
total_frames: u64,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let parent = Path::new(file_path)
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
|
||||
// Try to extract birthday from probe.json if available
|
||||
let birthday = now.clone();
|
||||
|
||||
Self {
|
||||
version: PROFILE_VERSION.to_string(),
|
||||
file_uuid: file_uuid.to_string(),
|
||||
file_name: file_name.to_string(),
|
||||
file_type: file_type.to_string(),
|
||||
birth: BirthInfo {
|
||||
mac_address: String::new(), // Unknown for backfilled records
|
||||
birthday,
|
||||
original_path: parent,
|
||||
original_filename: file_name.to_string(),
|
||||
canonical_path: file_path.to_string(),
|
||||
content_hash: if content_hash.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(content_hash.to_string())
|
||||
},
|
||||
},
|
||||
current: CurrentInfo {
|
||||
path: file_path.to_string(),
|
||||
file_name: file_name.to_string(),
|
||||
file_type: file_type.to_string(),
|
||||
},
|
||||
history: vec![HistoryEntry {
|
||||
action: "backfilled".to_string(),
|
||||
timestamp: now,
|
||||
path: file_path.to_string(),
|
||||
file_name: file_name.to_string(),
|
||||
}],
|
||||
metadata: if duration > 0.0 || width > 0 || height > 0 {
|
||||
Some(MediaMetadata {
|
||||
duration,
|
||||
width,
|
||||
height,
|
||||
fps,
|
||||
total_frames,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
},
|
||||
key_frame: None,
|
||||
proxy_path: None,
|
||||
audio_track: None,
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Key Frame Extraction ───
|
||||
|
||||
/// Key frame filename: `{file_uuid}.key_frame.jpg`
|
||||
pub fn key_frame_filename(file_uuid: &str) -> String {
|
||||
format!("{}.key_frame.jpg", file_uuid)
|
||||
}
|
||||
|
||||
/// Extract a representative frame from a video file using ffmpeg.
|
||||
/// Saves as `{output_dir}/{file_uuid}.key_frame.jpg`. Returns filename on success.
|
||||
pub fn extract_key_frame(
|
||||
video_path: &str,
|
||||
duration: f64,
|
||||
output_dir: &str,
|
||||
file_uuid: &str,
|
||||
) -> Option<String> {
|
||||
// Seek to 10% of duration (or 1s if duration is 0)
|
||||
let seek_time = if duration > 0.0 { duration * 0.1 } else { 1.0 };
|
||||
|
||||
let out_path = std::path::Path::new(output_dir).join(Self::key_frame_filename(file_uuid));
|
||||
|
||||
let status = std::process::Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-ss",
|
||||
&format!("{:.2}", seek_time),
|
||||
"-i",
|
||||
video_path,
|
||||
"-vframes",
|
||||
"1",
|
||||
"-vf",
|
||||
"scale=640:-1",
|
||||
"-q:v",
|
||||
"5",
|
||||
&out_path.to_string_lossy(),
|
||||
])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()
|
||||
.ok()?;
|
||||
|
||||
if status.success() && out_path.exists() {
|
||||
Some(Self::key_frame_filename(file_uuid))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Face Trace Profile ───
|
||||
|
||||
/// Per-trace profile stored in `output/{file_uuid}/{trace_id}/trace_profile.json`.
|
||||
///
|
||||
/// Bbox is NOT stored here — it's already in Qdrant `_faces` per-point.
|
||||
/// Original pixel values from Apple Vision are never modified.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceTraceProfile {
|
||||
pub version: String,
|
||||
pub file_uuid: String,
|
||||
pub trace_id: i64,
|
||||
pub label: String,
|
||||
pub frame_count: i64,
|
||||
pub start_frame: i64,
|
||||
pub end_frame: i64,
|
||||
pub avg_confidence: Option<f64>,
|
||||
pub key_frame: Option<String>, // filename: key_frame.jpg
|
||||
pub key_face: Option<String>, // filename: key_face.jpg
|
||||
pub status: String, // pending / bound / merged
|
||||
}
|
||||
|
||||
impl FaceTraceProfile {
|
||||
/// Directory: `output/{file_uuid}/{trace_id}/`
|
||||
pub fn trace_dir(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf {
|
||||
Path::new(output_dir)
|
||||
.join(file_uuid)
|
||||
.join(format!("trace_{}", trace_id))
|
||||
}
|
||||
|
||||
/// Profile file path: `output/{file_uuid}/{trace_id}/trace_profile.json`
|
||||
pub fn profile_path(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf {
|
||||
Self::trace_dir(output_dir, file_uuid, trace_id).join("trace_profile.json")
|
||||
}
|
||||
|
||||
/// Build a new trace profile.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
file_uuid: &str,
|
||||
trace_id: i64,
|
||||
label: &str,
|
||||
frame_count: i64,
|
||||
start_frame: i64,
|
||||
end_frame: i64,
|
||||
avg_confidence: Option<f64>,
|
||||
) -> Self {
|
||||
Self {
|
||||
version: PROFILE_VERSION.to_string(),
|
||||
file_uuid: file_uuid.to_string(),
|
||||
trace_id,
|
||||
label: label.to_string(),
|
||||
frame_count,
|
||||
start_frame,
|
||||
end_frame,
|
||||
avg_confidence,
|
||||
key_frame: None,
|
||||
key_face: None,
|
||||
status: "pending".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Save profile + key_frame.jpg + key_face.jpg to `output/{file_uuid}/{trace_id}/`.
|
||||
/// `key_frame_jpeg` and `key_face_jpeg` are raw JPEG bytes (optional).
|
||||
pub fn save(
|
||||
&mut self,
|
||||
output_dir: &str,
|
||||
key_frame_jpeg: Option<&[u8]>,
|
||||
key_face_jpeg: Option<&[u8]>,
|
||||
) -> Result<()> {
|
||||
let dir = Self::trace_dir(output_dir, &self.file_uuid, self.trace_id);
|
||||
std::fs::create_dir_all(&dir)
|
||||
.with_context(|| format!("Failed to create {}", dir.display()))?;
|
||||
|
||||
// Write key_frame.jpg
|
||||
if let Some(jpeg) = key_frame_jpeg {
|
||||
let kf_path = dir.join("key_frame.jpg");
|
||||
std::fs::write(&kf_path, jpeg)
|
||||
.with_context(|| format!("Failed to write {}", kf_path.display()))?;
|
||||
self.key_frame = Some("key_frame.jpg".to_string());
|
||||
}
|
||||
|
||||
// Write key_face.jpg
|
||||
if let Some(jpeg) = key_face_jpeg {
|
||||
let face_path = dir.join("key_face.jpg");
|
||||
std::fs::write(&face_path, jpeg)
|
||||
.with_context(|| format!("Failed to write {}", face_path.display()))?;
|
||||
self.key_face = Some("key_face.jpg".to_string());
|
||||
}
|
||||
|
||||
// Write trace_profile.json
|
||||
let json =
|
||||
serde_json::to_string_pretty(self).context("Failed to serialize FaceTraceProfile")?;
|
||||
let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id);
|
||||
std::fs::write(&profile_path, json)
|
||||
.with_context(|| format!("Failed to write {}", profile_path.display()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load profile from disk.
|
||||
pub fn load(output_dir: &str, file_uuid: &str, trace_id: i64) -> Option<Self> {
|
||||
let path = Self::profile_path(output_dir, file_uuid, trace_id);
|
||||
let content = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&content).ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_profile_path() {
|
||||
let path = FileProfile::profile_path("/output", "abc123");
|
||||
assert_eq!(path, PathBuf::from("/output/abc123.profile.json"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_registration() {
|
||||
let profile = FileProfile::from_registration(
|
||||
"abc123",
|
||||
"test.mp4",
|
||||
"video",
|
||||
"aa:bb:cc:dd:ee:ff",
|
||||
"2026-01-01T00:00:00Z",
|
||||
"/Users/test/video.mp4",
|
||||
"hash123",
|
||||
120.0,
|
||||
1920,
|
||||
1080,
|
||||
30.0,
|
||||
3600,
|
||||
);
|
||||
assert_eq!(profile.version, "1.0");
|
||||
assert_eq!(profile.file_uuid, "abc123");
|
||||
assert_eq!(profile.file_name, "test.mp4");
|
||||
assert_eq!(profile.current.path, "/Users/test/video.mp4");
|
||||
assert_eq!(profile.history.len(), 1);
|
||||
assert_eq!(profile.history[0].action, "registered");
|
||||
assert!(profile.metadata.is_some());
|
||||
assert!(profile.key_frame.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_update_current_path() {
|
||||
let mut profile = FileProfile::from_registration(
|
||||
"abc123",
|
||||
"test.mp4",
|
||||
"video",
|
||||
"aa:bb:cc:dd:ee:ff",
|
||||
"2026-01-01T00:00:00Z",
|
||||
"/Users/test/video.mp4",
|
||||
"hash123",
|
||||
120.0,
|
||||
1920,
|
||||
1080,
|
||||
30.0,
|
||||
3600,
|
||||
);
|
||||
profile.update_current_path("/Users/test/moved.mp4", "moved.mp4");
|
||||
assert_eq!(profile.current.path, "/Users/test/moved.mp4");
|
||||
assert_eq!(profile.current.file_name, "moved.mp4");
|
||||
assert_eq!(profile.history.len(), 2);
|
||||
assert_eq!(profile.history[1].action, "moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_move_if_same_path() {
|
||||
let mut profile = FileProfile::from_registration(
|
||||
"abc123",
|
||||
"test.mp4",
|
||||
"video",
|
||||
"aa:bb:cc:dd:ee:ff",
|
||||
"2026-01-01T00:00:00Z",
|
||||
"/Users/test/video.mp4",
|
||||
"hash123",
|
||||
120.0,
|
||||
1920,
|
||||
1080,
|
||||
30.0,
|
||||
3600,
|
||||
);
|
||||
profile.update_current_path("/Users/test/video.mp4", "test.mp4");
|
||||
assert_eq!(profile.history.len(), 1); // No new entry
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zombie_profile() {
|
||||
let profile = FileProfile::from_zombie("zombie123", "video", "hash");
|
||||
assert_eq!(profile.file_uuid, "zombie123");
|
||||
assert!(profile.file_name.is_empty());
|
||||
assert!(profile.birth.canonical_path.is_empty());
|
||||
assert_eq!(profile.history[0].action, "recovered_zombie");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialization_roundtrip() {
|
||||
let profile = FileProfile::from_registration(
|
||||
"abc123",
|
||||
"test.mp4",
|
||||
"video",
|
||||
"aa:bb:cc:dd:ee:ff",
|
||||
"2026-01-01T00:00:00Z",
|
||||
"/Users/test/video.mp4",
|
||||
"hash123",
|
||||
120.0,
|
||||
1920,
|
||||
1080,
|
||||
30.0,
|
||||
3600,
|
||||
);
|
||||
let json = serde_json::to_string(&profile).unwrap();
|
||||
let restored: FileProfile = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(restored.file_uuid, profile.file_uuid);
|
||||
assert_eq!(restored.file_name, profile.file_name);
|
||||
assert_eq!(restored.history.len(), 1);
|
||||
}
|
||||
}
|
||||
+52
-1
@@ -224,8 +224,9 @@ impl IngestionService {
|
||||
cut_max_duration: 0.0,
|
||||
scene_done: false,
|
||||
audio_tracks: None,
|
||||
proxy_path: None,
|
||||
audio_track: None,
|
||||
};
|
||||
|
||||
self.db
|
||||
.register_video(&record)
|
||||
.await
|
||||
@@ -254,6 +255,56 @@ impl IngestionService {
|
||||
.await
|
||||
.with_context(|| "Failed to set birth_registration")?;
|
||||
|
||||
// ── File Profile: write first artifact to disk ──
|
||||
{
|
||||
use crate::core::file_profile::FileProfile;
|
||||
let has_video = probe_result.as_ref().map_or(false, |pr| {
|
||||
pr.streams
|
||||
.iter()
|
||||
.any(|s| s.codec_type.as_deref() == Some("video"))
|
||||
});
|
||||
let has_audio = probe_result.as_ref().map_or(false, |pr| {
|
||||
pr.streams
|
||||
.iter()
|
||||
.any(|s| s.codec_type.as_deref() == Some("audio"))
|
||||
});
|
||||
let file_type_str = if has_video {
|
||||
"video"
|
||||
} else if has_audio {
|
||||
"audio"
|
||||
} else {
|
||||
"unknown"
|
||||
};
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let mut profile = FileProfile::from_registration(
|
||||
&uuid,
|
||||
&final_name,
|
||||
file_type_str,
|
||||
&uuid_utils::get_mac_address(),
|
||||
&birthday,
|
||||
&canonical_path.to_string_lossy(),
|
||||
&content_hash,
|
||||
duration,
|
||||
width,
|
||||
height,
|
||||
fps,
|
||||
total_frames.unwrap_or(0),
|
||||
);
|
||||
if has_video {
|
||||
if let Some(kf) = FileProfile::extract_key_frame(
|
||||
&canonical_path.to_string_lossy(),
|
||||
duration,
|
||||
output_dir,
|
||||
&uuid,
|
||||
) {
|
||||
profile.set_key_frame(kf);
|
||||
}
|
||||
}
|
||||
if let Err(e) = profile.save_to_disk(output_dir) {
|
||||
warn!("Failed to save file profile: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(uuid))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ pub mod chunk;
|
||||
pub mod config;
|
||||
pub mod db;
|
||||
pub mod embedding;
|
||||
pub mod file_lifecycle;
|
||||
pub mod file_profile;
|
||||
pub mod frame_cache;
|
||||
pub mod health_agent;
|
||||
pub mod identity;
|
||||
@@ -18,6 +20,7 @@ pub mod pipeline;
|
||||
pub mod probe;
|
||||
pub mod processor;
|
||||
pub mod progress;
|
||||
pub mod proxy;
|
||||
pub mod storage;
|
||||
pub mod text;
|
||||
pub mod thumbnail;
|
||||
|
||||
@@ -146,6 +146,84 @@ pub async fn vectorize_chunks(uuid: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reindex_embeddings(uuid: &str) -> Result<()> {
|
||||
let db = PostgresDb::new(&config::DATABASE_URL).await?;
|
||||
let qdrant = QdrantDb::new();
|
||||
let chunk_table = schema::table_name("chunk");
|
||||
|
||||
let rows = sqlx::query_as::<_, (String, String, String, i64, i64, f64, f64, String, String)>(
|
||||
&format!(
|
||||
"SELECT chunk_id, chunk_type, text_content, start_frame, end_frame, \
|
||||
start_time, end_time, content::text, embedding::text \
|
||||
FROM {} WHERE file_uuid = $1 AND embedding IS NOT NULL \
|
||||
ORDER BY id",
|
||||
chunk_table
|
||||
),
|
||||
)
|
||||
.bind(uuid)
|
||||
.fetch_all(db.pool())
|
||||
.await?;
|
||||
|
||||
if rows.is_empty() {
|
||||
println!("No chunks with embeddings to reindex for {}", uuid);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let total = rows.len();
|
||||
let mut stored = 0usize;
|
||||
|
||||
for (
|
||||
chunk_id,
|
||||
chunk_type,
|
||||
text,
|
||||
start_frame,
|
||||
end_frame,
|
||||
start_time,
|
||||
end_time,
|
||||
_content_str,
|
||||
embedding_text,
|
||||
) in &rows
|
||||
{
|
||||
let vector: Vec<f32> = match serde_json::from_str(embedding_text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to parse embedding for {}: {}", chunk_id, e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let payload = VectorPayload {
|
||||
file_uuid: uuid.to_string(),
|
||||
chunk_id: chunk_id.clone(),
|
||||
chunk_type: chunk_type.clone(),
|
||||
start_frame: *start_frame,
|
||||
end_frame: *end_frame,
|
||||
start_time: *start_time,
|
||||
end_time: *end_time,
|
||||
text: if text.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(text.clone())
|
||||
},
|
||||
};
|
||||
|
||||
if let Err(e) = qdrant.upsert_vector(chunk_id, &vector, payload).await {
|
||||
eprintln!("Qdrant upsert failed for {}: {}", chunk_id, e);
|
||||
continue;
|
||||
}
|
||||
stored += 1;
|
||||
if stored % 50 == 0 {
|
||||
println!("Reindexed {}/{} chunks for {}", stored, total, uuid);
|
||||
}
|
||||
}
|
||||
|
||||
println!(
|
||||
"Reindex complete: {}/{} embeddings pushed to Qdrant for {}",
|
||||
stored, total, uuid
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run_phase1(uuid: &str) -> Result<()> {
|
||||
let executor = PythonExecutor::new().context("Failed to create PythonExecutor")?;
|
||||
|
||||
|
||||
@@ -54,6 +54,8 @@ pub struct AsrSegment {
|
||||
pub start_frame: Option<i64>,
|
||||
pub end_frame: Option<i64>,
|
||||
pub text: String,
|
||||
#[serde(default)]
|
||||
pub confidence: f64,
|
||||
}
|
||||
|
||||
pub async fn process_asr(
|
||||
|
||||
@@ -16,7 +16,23 @@ pub struct FaceClusterResult {
|
||||
pub struct FaceClusterInfo {
|
||||
pub cluster_id: String,
|
||||
pub face_count: usize,
|
||||
pub representative_face: Option<String>,
|
||||
pub representative_face: Option<RepresentativeFace>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct RepresentativeFace {
|
||||
pub face_id: String,
|
||||
pub confidence: f64,
|
||||
pub frame: u64,
|
||||
pub bbox: BoundingBox,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct BoundingBox {
|
||||
pub x: u64,
|
||||
pub y: u64,
|
||||
pub width: u64,
|
||||
pub height: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
|
||||
+111
-36
@@ -97,7 +97,7 @@ fn parse_face_points(points: Vec<serde_json::Value>) -> Vec<FacePoint> {
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let payload = &p["payload"];
|
||||
let trace_id = payload["trace_id"].as_i64().filter(|&t| t > 0);
|
||||
let trace_id = payload["trace_id"].as_i64().filter(|&t| t >= 0);
|
||||
if trace_id.is_none() {
|
||||
no_trace_id += 1;
|
||||
return None;
|
||||
@@ -519,6 +519,7 @@ fn load_face_pose_data(output_dir: &str, file_uuid: &str) -> Result<Vec<FacePose
|
||||
|
||||
/// Match a face from face_detections (frame, x, y, w, h) to its pose in face.json
|
||||
/// Uses bbox center distance to find the best match when multiple faces per frame.
|
||||
/// Returns None if no pose within threshold (unreliable match).
|
||||
fn get_pose_for_face(
|
||||
frame: i64,
|
||||
x: f64,
|
||||
@@ -527,6 +528,8 @@ fn get_pose_for_face(
|
||||
h: f64,
|
||||
poses: &[FacePose],
|
||||
) -> Option<(f64, f64, f64)> {
|
||||
const MAX_CENTER_DIST: f64 = 100.0; // Max center distance for valid match (pixels)
|
||||
|
||||
let cx = x + w / 2.0;
|
||||
let cy = y + h / 2.0;
|
||||
let mut best_dist = f64::MAX;
|
||||
@@ -535,7 +538,7 @@ fn get_pose_for_face(
|
||||
let pcx = p.x + p.w / 2.0;
|
||||
let pcy = p.y + p.h / 2.0;
|
||||
let dist = (cx - pcx).abs() + (cy - pcy).abs();
|
||||
if dist < best_dist {
|
||||
if dist < best_dist && dist < MAX_CENTER_DIST {
|
||||
best_dist = dist;
|
||||
result = Some((p.yaw, p.pitch, p.roll));
|
||||
}
|
||||
@@ -1130,6 +1133,7 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
sum_y: f64,
|
||||
sum_w: f64,
|
||||
sum_h: f64,
|
||||
sum_confidence: f64,
|
||||
frames: Vec<(i64, f64, f64, f64, f64)>, // (frame, x, y, w, h)
|
||||
best_frame: i64,
|
||||
best_confidence: f64,
|
||||
@@ -1146,6 +1150,7 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
sum_y: 0.0,
|
||||
sum_w: 0.0,
|
||||
sum_h: 0.0,
|
||||
sum_confidence: 0.0,
|
||||
frames: vec![],
|
||||
best_frame: 0,
|
||||
best_confidence: 0.0,
|
||||
@@ -1158,6 +1163,7 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
entry.sum_y += p.y;
|
||||
entry.sum_w += p.w;
|
||||
entry.sum_h += p.h;
|
||||
entry.sum_confidence += p.confidence;
|
||||
entry.frames.push((p.frame, p.x, p.y, p.w, p.h));
|
||||
// Track best face (highest confidence)
|
||||
if p.confidence > entry.best_confidence {
|
||||
@@ -1218,14 +1224,8 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
"status": "pending",
|
||||
});
|
||||
|
||||
// Save key frame and key face JPGs
|
||||
// Save key_frame.jpg + key_face.jpg + trace_profile.json
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let face_dir = std::path::PathBuf::from(output_dir)
|
||||
.join(".faces").join(file_uuid).join(&external_id);
|
||||
let _ = std::fs::create_dir_all(&face_dir);
|
||||
|
||||
let key_frame_path = face_dir.join("key_frame.jpg");
|
||||
let key_face_path = face_dir.join("key_face.jpg");
|
||||
|
||||
// Get video path from database
|
||||
let video_path: Option<String> = sqlx::query_scalar(&format!(
|
||||
@@ -1238,41 +1238,116 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
.ok()
|
||||
.flatten();
|
||||
|
||||
// Extract key frame using ffmpeg
|
||||
if !key_frame_path.exists() {
|
||||
if let Some(ref vp) = video_path {
|
||||
let timestamp = agg.best_frame as f64 / 30.0;
|
||||
let _ = std::process::Command::new("ffmpeg")
|
||||
.args(["-y", "-v", "quiet", "-ss", ×tamp.to_string(), "-i", vp])
|
||||
.args(["-frames:v", "1", "-q:v", "2"])
|
||||
.arg(key_frame_path.to_str().unwrap_or(""))
|
||||
.output();
|
||||
// Get actual fps for timestamp calculation
|
||||
let actual_fps: f64 = sqlx::query_scalar(&format!(
|
||||
"SELECT fps FROM {} WHERE file_uuid = $1",
|
||||
crate::core::db::schema::table_name("videos")
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or(30.0);
|
||||
|
||||
let avg_confidence = if agg.frame_count > 0 {
|
||||
agg.sum_confidence / agg.frame_count as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let mut trace_profile = crate::core::file_profile::FaceTraceProfile::new(
|
||||
file_uuid,
|
||||
*tid,
|
||||
&label,
|
||||
agg.frame_count,
|
||||
agg.start_f,
|
||||
agg.end_f,
|
||||
Some(avg_confidence),
|
||||
);
|
||||
|
||||
// Extract key_frame JPEG bytes via ffmpeg pipe
|
||||
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
|
||||
let timestamp = agg.best_frame as f64 / actual_fps;
|
||||
let output = std::process::Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-v",
|
||||
"quiet",
|
||||
"-ss",
|
||||
&format!("{:.3}", timestamp),
|
||||
"-i",
|
||||
])
|
||||
.arg(vp)
|
||||
.args([
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-f",
|
||||
"image2pipe",
|
||||
"-c:v",
|
||||
"mjpeg",
|
||||
"pipe:1",
|
||||
])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
if output.status.success() && !output.stdout.is_empty() {
|
||||
Some(output.stdout)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Crop key face from key frame using bbox
|
||||
if !key_face_path.exists() && key_frame_path.exists() {
|
||||
let bbox = &props["avg_bbox"];
|
||||
let x = bbox["x"].as_i64().unwrap_or(0) as u32;
|
||||
let y = bbox["y"].as_i64().unwrap_or(0) as u32;
|
||||
let w = bbox["width"].as_i64().unwrap_or(100) as u32;
|
||||
let h = bbox["height"].as_i64().unwrap_or(100) as u32;
|
||||
let _ = std::process::Command::new("ffmpeg")
|
||||
.args(["-y", "-v", "quiet", "-i", key_frame_path.to_str().unwrap_or("")])
|
||||
.args(["-vf", &format!("crop={}:{}:{}:{}", w, h, x, y)])
|
||||
.args(["-q:v", "2"])
|
||||
.arg(key_face_path.to_str().unwrap_or(""))
|
||||
.output();
|
||||
}
|
||||
// Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame)
|
||||
let key_face_jpeg: Option<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
|
||||
// Find bbox for best_frame from trace frames
|
||||
let (_, bx, by, bw, bh) = agg.frames.iter().find(|(f, _, _, _, _)| *f == agg.best_frame)?;
|
||||
let crop_filter = format!(
|
||||
"crop={}:{}:{}:{}",
|
||||
(*bw as i64).max(1),
|
||||
(*bh as i64).max(1),
|
||||
(*bx as i64).max(0),
|
||||
(*by as i64).max(0),
|
||||
);
|
||||
let mut cmd = std::process::Command::new("ffmpeg");
|
||||
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
||||
.args(["-frames:v", "1", "-q:v", "2", "-vf"])
|
||||
.arg(&crop_filter)
|
||||
.args(["-f", "image2pipe", "-c:v", "mjpeg", "pipe:1"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null());
|
||||
let mut child = cmd.spawn().ok()?;
|
||||
if let Some(ref mut stdin) = child.stdin {
|
||||
use std::io::Write;
|
||||
let _ = stdin.write_all(kf);
|
||||
}
|
||||
let output = child.wait_with_output().ok()?;
|
||||
if output.status.success() && !output.stdout.is_empty() {
|
||||
Some(output.stdout)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
// Update props with actual file paths
|
||||
// Save all three files to output/{file_uuid}/{trace_id}/
|
||||
let _ = trace_profile.save(
|
||||
output_dir,
|
||||
key_frame_jpeg.as_deref(),
|
||||
key_face_jpeg.as_deref(),
|
||||
);
|
||||
|
||||
// Update props with actual file paths (for DB properties JSONB)
|
||||
let final_props = serde_json::json!({
|
||||
"trace_id": tid,
|
||||
"frame_count": agg.frame_count,
|
||||
"start_frame": agg.start_f,
|
||||
"end_frame": agg.end_f,
|
||||
"key_frame": if key_frame_path.exists() { key_frame_path.to_string_lossy().to_string() } else { serde_json::Value::Null.to_string() },
|
||||
"key_face": if key_face_path.exists() { key_face_path.to_string_lossy().to_string() } else { serde_json::Value::Null.to_string() },
|
||||
"key_frame": agg.best_frame,
|
||||
"key_face": agg.best_point_id.as_deref().unwrap_or(""),
|
||||
"avg_bbox": props["avg_bbox"].clone(),
|
||||
"avg_yaw": props["avg_yaw"].clone(),
|
||||
"avg_pitch": props["avg_pitch"].clone(),
|
||||
|
||||
@@ -63,7 +63,7 @@ impl PipelineProgress {
|
||||
detail: None,
|
||||
},
|
||||
PipelineStage {
|
||||
name: "identity_agent".into(),
|
||||
name: "face_dedup".into(),
|
||||
weight: 0.10,
|
||||
progress: 0.0,
|
||||
status: "pending".into(),
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
use crate::core::config::{OUTPUT_DIR, PYTHON_PATH};
|
||||
|
||||
const PROXY_HEIGHT: u32 = 720;
|
||||
const PROXY_CRF: u32 = 23;
|
||||
const MIN_HEIGHT_FOR_PROXY: u32 = 1080;
|
||||
|
||||
pub fn needs_proxy(width: u32, height: u32) -> bool {
|
||||
height >= MIN_HEIGHT_FOR_PROXY || width >= MIN_HEIGHT_FOR_PROXY
|
||||
}
|
||||
|
||||
pub fn proxy_output_path(file_path: &str) -> Result<PathBuf> {
|
||||
let src = std::path::Path::new(file_path);
|
||||
let stem = src
|
||||
.file_stem()
|
||||
.context("Cannot get file stem")?
|
||||
.to_string_lossy();
|
||||
let parent = src.parent().context("Cannot get parent dir")?;
|
||||
Ok(parent.join(format!("{}_720p.mp4", stem)))
|
||||
}
|
||||
|
||||
fn ffmpeg_cmd() -> Command {
|
||||
let ffmpeg_path = std::env::var("MOMENTRY_FFMPEG")
|
||||
.unwrap_or_else(|_| "ffmpeg".to_string());
|
||||
let mut cmd = Command::new(&ffmpeg_path);
|
||||
let full_lib = "/opt/homebrew/opt/ffmpeg-full/lib";
|
||||
if std::path::Path::new(full_lib).exists() {
|
||||
cmd.env("DYLD_LIBRARY_PATH", full_lib);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
pub async fn generate_proxy(file_path: &str, file_uuid: &str) -> Result<Option<String>> {
|
||||
let src = std::path::Path::new(file_path);
|
||||
if !src.exists() {
|
||||
tracing::warn!("[PROXY] Source file not found: {}", file_path);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let out = proxy_output_path(file_path)?;
|
||||
if out.exists() {
|
||||
tracing::info!("[PROXY] Proxy already exists: {}", out.display());
|
||||
return Ok(Some(out.to_string_lossy().to_string()));
|
||||
}
|
||||
|
||||
let out_str = out.to_string_lossy().to_string();
|
||||
let file_path_owned = file_path.to_string();
|
||||
|
||||
let status = tokio::task::spawn_blocking(move || {
|
||||
ffmpeg_cmd()
|
||||
.args([
|
||||
"-i", &file_path_owned,
|
||||
"-vf", &format!("scale=-2:{}", PROXY_HEIGHT),
|
||||
"-c:v", "libx264",
|
||||
"-preset", "fast",
|
||||
"-crf", &PROXY_CRF.to_string(),
|
||||
"-c:a", "aac",
|
||||
"-b:a", "128k",
|
||||
"-movflags", "+faststart",
|
||||
"-y", &out_str,
|
||||
])
|
||||
.status()
|
||||
})
|
||||
.await
|
||||
.context("Spawn blocking failed")?
|
||||
.context("Failed to spawn ffmpeg")?;
|
||||
|
||||
if !status.success() {
|
||||
let _ = tokio::fs::remove_file(&out).await;
|
||||
tracing::error!(
|
||||
"[PROXY] ffmpeg failed for {} (exit: {:?})",
|
||||
file_uuid,
|
||||
status.code()
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
"[PROXY] Generated 720p proxy: {} -> {}",
|
||||
file_uuid,
|
||||
out.display()
|
||||
);
|
||||
Ok(Some(out.to_string_lossy().to_string()))
|
||||
}
|
||||
|
||||
/// Audio track classification result
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioTrackResult {
|
||||
pub classification: String,
|
||||
pub speech_ratio: f64,
|
||||
pub speech_segments: i32,
|
||||
pub duration: f64,
|
||||
}
|
||||
|
||||
/// Probe audio track and classify using VAD
|
||||
pub async fn probe_audio_track(file_path: &str) -> Result<Option<AudioTrackResult>> {
|
||||
let script = std::path::Path::new("/Users/accusys/momentry_core/scripts/audio_track_probe.py");
|
||||
|
||||
if !script.exists() {
|
||||
tracing::warn!("[AUDIO_TRACK] Script not found: {}", script.display());
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let file_path_owned = file_path.to_string();
|
||||
let script_str = script.to_string_lossy().to_string();
|
||||
let python_path = PYTHON_PATH.as_str().to_string();
|
||||
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
Command::new(&python_path)
|
||||
.arg(&script_str)
|
||||
.arg("--file")
|
||||
.arg(&file_path_owned)
|
||||
.arg("--json")
|
||||
.output()
|
||||
})
|
||||
.await
|
||||
.context("Spawn blocking failed")?
|
||||
.context("Failed to spawn python")?;
|
||||
|
||||
if !output.status.success() {
|
||||
tracing::warn!(
|
||||
"[AUDIO_TRACK] Probe failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let json: serde_json::Value = match serde_json::from_str(&stdout) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!("[AUDIO_TRACK] JSON parse error: {}", e);
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
|
||||
let classification = json
|
||||
.get("classification")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("speech_only")
|
||||
.to_string();
|
||||
|
||||
let speech_ratio = json
|
||||
.get("speech_ratio")
|
||||
.and_then(|v| v.as_f64())
|
||||
.unwrap_or(0.5);
|
||||
|
||||
let speech_segments = json
|
||||
.get("speech_segments")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0) as i32;
|
||||
|
||||
let duration = json
|
||||
.get("duration")
|
||||
.and_then(|v| v.as_f64())
|
||||
.unwrap_or(0.0);
|
||||
|
||||
tracing::info!(
|
||||
"[AUDIO_TRACK] {} -> {} (ratio: {:.2}, segments: {})",
|
||||
file_path,
|
||||
classification,
|
||||
speech_ratio,
|
||||
speech_segments
|
||||
);
|
||||
|
||||
Ok(Some(AudioTrackResult {
|
||||
classification,
|
||||
speech_ratio,
|
||||
speech_segments,
|
||||
duration,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Extract key frames from each scene in cut.json for VLM analysis
|
||||
pub async fn extract_cut_key_frames(
|
||||
file_uuid: &str,
|
||||
video_path: &str,
|
||||
output_dir: &str,
|
||||
) -> Result<Vec<String>> {
|
||||
let cut_json = PathBuf::from(output_dir)
|
||||
.join(format!("{}.cut.json", file_uuid));
|
||||
|
||||
if !cut_json.exists() {
|
||||
tracing::warn!("[CUT_KEY_FRAME] cut.json not found: {}", cut_json.display());
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let script = std::path::Path::new("/Users/accusys/momentry_core/scripts/cut_key_frame.py");
|
||||
|
||||
if !script.exists() {
|
||||
tracing::warn!("[CUT_KEY_FRAME] Script not found: {}", script.display());
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let file_uuid_owned = file_uuid.to_string();
|
||||
let video_path_owned = video_path.to_string();
|
||||
let cut_json_str = cut_json.to_string_lossy().to_string();
|
||||
let output_dir_owned = output_dir.to_string();
|
||||
let script_str = script.to_string_lossy().to_string();
|
||||
let python_path = PYTHON_PATH.as_str().to_string();
|
||||
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
Command::new(&python_path)
|
||||
.arg(&script_str)
|
||||
.arg("--file-uuid")
|
||||
.arg(&file_uuid_owned)
|
||||
.arg("--video")
|
||||
.arg(&video_path_owned)
|
||||
.arg("--cut-json")
|
||||
.arg(&cut_json_str)
|
||||
.arg("--output-dir")
|
||||
.arg(&output_dir_owned)
|
||||
.arg("--json")
|
||||
.output()
|
||||
})
|
||||
.await
|
||||
.context("Spawn blocking failed")?
|
||||
.context("Failed to spawn python")?;
|
||||
|
||||
if !output.status.success() {
|
||||
tracing::warn!(
|
||||
"[CUT_KEY_FRAME] Extraction failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let json: serde_json::Value = match serde_json::from_str(&stdout) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!("[CUT_KEY_FRAME] JSON parse error: {}", e);
|
||||
return Ok(vec![]);
|
||||
}
|
||||
};
|
||||
|
||||
let scenes: Vec<String> = json
|
||||
.get("scenes")
|
||||
.and_then(|s| s.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|s| {
|
||||
if s.get("success").and_then(|b| b.as_bool()) == Some(true) {
|
||||
s.get("output_path").and_then(|p| p.as_str().map(|p| p.to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
tracing::info!(
|
||||
"[CUT_KEY_FRAME] Extracted {} scene key frames for {}",
|
||||
scenes.len(),
|
||||
file_uuid
|
||||
);
|
||||
|
||||
Ok(scenes)
|
||||
}
|
||||
@@ -1033,6 +1033,8 @@ async fn main() -> Result<()> {
|
||||
cut_max_duration: 0.0,
|
||||
scene_done: false,
|
||||
audio_tracks: None,
|
||||
proxy_path: None,
|
||||
audio_track: None,
|
||||
};
|
||||
|
||||
let video_id = db.register_video(&record).await?;
|
||||
|
||||
@@ -119,7 +119,7 @@ pub const PROCESSOR_SCHEMAS: &[ProcessorJsonSchema] = &[
|
||||
required_fields: &[
|
||||
RequiredField {
|
||||
path: "frame_count",
|
||||
field_type: FieldType::PositiveNumber,
|
||||
field_type: FieldType::Number,
|
||||
allow_empty: false,
|
||||
},
|
||||
RequiredField {
|
||||
@@ -140,7 +140,7 @@ pub const PROCESSOR_SCHEMAS: &[ProcessorJsonSchema] = &[
|
||||
required_fields: &[
|
||||
RequiredField {
|
||||
path: "frame_count",
|
||||
field_type: FieldType::PositiveNumber,
|
||||
field_type: FieldType::Number,
|
||||
allow_empty: false,
|
||||
},
|
||||
RequiredField {
|
||||
|
||||
@@ -174,6 +174,8 @@ async fn auto_register_file(file_path: &str) {
|
||||
cut_max_duration: 0.0,
|
||||
scene_done: false,
|
||||
audio_tracks: None,
|
||||
proxy_path: None,
|
||||
audio_track: None,
|
||||
};
|
||||
|
||||
let database_url = crate::core::config::DATABASE_URL.as_str();
|
||||
|
||||
+492
-273
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user