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)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user