diff --git a/src/api/cluster_agent.rs b/src/api/cluster_agent.rs index d29ff713..96a43306 100644 --- a/src/api/cluster_agent.rs +++ b/src/api/cluster_agent.rs @@ -4,7 +4,7 @@ use axum::{ routing::post, Extension, Json, Router, }; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; @@ -14,6 +14,11 @@ use crate::core::config::OUTPUT_DIR; use crate::core::db::schema; use crate::core::processor::{process_face_cluster, FaceClusterResult}; +#[derive(Debug, Deserialize)] +pub struct ClusterAgentRequest { + pub confirm: Option, +} + #[derive(Debug, Serialize)] pub struct ClusterAgentResponse { success: bool, @@ -34,7 +39,19 @@ pub async fn trigger_cluster_agent( State(state): State, Extension(_auth): Extension, Path(file_uuid): Path, + Json(req): Json, ) -> Result, (StatusCode, Json)> { + // Require explicit confirmation to prevent accidental reclustering + if !req.confirm.unwrap_or(false) { + return Err(( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ + "success": false, + "error": "Confirmation required. Set 'confirm': true to proceed with reclustering. This will reset all trace names and re-cluster faces.", + "requires_confirmation": true + })), + )); + } let videos_table = schema::table_name("videos"); let row = sqlx::query(&format!( "SELECT file_path, COALESCE(total_frames, 0) as total_frames, COALESCE(fps, 25.0) as fps, probe_json FROM {} WHERE file_uuid = $1", @@ -88,6 +105,42 @@ pub async fn trigger_cluster_agent( let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid)); + // Reset all trace_profiles names to default (Person_N) before re-clustering + let tp_table = schema::table_name("trace_profiles"); + let traced_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid)); + if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced_data) = serde_json::from_str::(&content) { + if let Some(traces) = traced_data.get("traces") { + let trace_list = if traces.is_object() { + traces.as_object().map(|o| o.keys().filter_map(|k| k.parse::().ok()).collect::>()) + } else if traces.is_array() { + traces.as_array().map(|a| a.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect()) + } else { + None + }; + + if let Some(all_trace_ids) = trace_list { + for tid in &all_trace_ids { + let name = format!("Person_{}", tid); + let _ = sqlx::query(&format!( + "UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3", + tp_table + )) + .bind(&name) + .bind(&file_uuid) + .bind(tid) + .execute(state.db.pool()) + .await; + } + tracing::info!( + "[ClusterAgent] Reset {} trace names to default for {}", + all_trace_ids.len(), file_uuid + ); + } + } + } + } + tracing::info!("[ClusterAgent] Starting face clustering for {}", file_uuid); let result = process_face_cluster( &file_path, @@ -147,43 +200,43 @@ async fn update_trace_labels_from_cluster( file_uuid: &str, result: &FaceClusterResult, ) -> anyhow::Result<()> { - let scroll_filter = serde_json::json!({ - "must": [ - {"key": "file_uuid", "match": {"value": file_uuid}} - ] - }); - - let all_faces = state - .qdrant - .scroll_all_points("_faces", scroll_filter, 1000) - .await?; - - let mut frame_to_traces: HashMap> = HashMap::new(); - for point in &all_faces { - let payload = &point["payload"]; - if let (Some(frame), Some(trace_id)) = - (payload["frame"].as_u64(), payload["trace_id"].as_i64()) - { - if trace_id > 0 { - frame_to_traces.entry(frame).or_default().push(trace_id); + // Build index: (frame, face_index) → real trace_id from face_traced.json + // face_cluster.json's trace_id is cluster-internal (always 0), so we match + // by frame number + array index to get the actual traced trace_id. + let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str()) + .join(format!("{}.face_traced.json", file_uuid)); + let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new(); + if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced_data) = serde_json::from_str::(&content) { + if let Some(frames) = traced_data.get("frames").and_then(|v| v.as_object()) { + for (fnum_str, frame_data) in frames { + if let (Ok(fnum), Some(faces)) = ( + fnum_str.parse::(), + frame_data.get("faces").and_then(|v| v.as_array()), + ) { + for (idx, face) in faces.iter().enumerate() { + if let Some(tid) = face.get("trace_id").and_then(|v| v.as_i64()) { + frame_face_to_trace.insert((fnum, idx), tid); + } + } + } + } } } } let mut trace_to_cluster: HashMap = HashMap::new(); for frame_data in &result.frames { - let frame = frame_data.frame; - if let Some(trace_ids) = frame_to_traces.get(&frame) { - for (idx, face) in frame_data.faces.iter().enumerate() { - if idx < trace_ids.len() { - trace_to_cluster.insert(trace_ids[idx], face.cluster_id.clone()); - } + for (idx, face) in frame_data.faces.iter().enumerate() { + if let Some(&tid) = frame_face_to_trace.get(&(frame_data.frame, idx)) { + trace_to_cluster.insert(tid, face.cluster_id.clone()); } } } 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(); @@ -212,7 +265,6 @@ async fn update_trace_labels_from_cluster( .await?; } - // Sync name to trace_profiles let _ = sqlx::query(&format!( "UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3", tp_table @@ -224,8 +276,34 @@ async fn update_trace_labels_from_cluster( .await; } + // Reset unclustered traces (not found in any cluster) to default Person_N + if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) { + let mut updated_count = 0u64; + for tid in &all_trace_ids { + if !trace_to_cluster.contains_key(tid) { + let name = format!("Person_{}", tid); + let _ = sqlx::query(&format!( + "UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3", + tp_table + )) + .bind(&name) + .bind(file_uuid) + .bind(tid) + .execute(state.db.pool()) + .await; + updated_count += 1; + } + } + if updated_count > 0 { + tracing::info!( + "[ClusterAgent] Updated {} unclustered trace names for {}", + updated_count, file_uuid + ); + } + } + tracing::info!( - "[ClusterAgent] Updated {} trace labels for {}", + "[ClusterAgent] Updated {} trace labels from clustering for {}", trace_to_cluster.len(), file_uuid ); @@ -233,6 +311,21 @@ async fn update_trace_labels_from_cluster( Ok(()) } +fn get_all_trace_ids(file_uuid: &str) -> Option> { + let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str()) + .join(format!("{}.face_traced.json", file_uuid)); + let content = std::fs::read_to_string(&traced_path).ok()?; + let traced_data: serde_json::Value = serde_json::from_str(&content).ok()?; + let traces = traced_data.get("traces")?; + if let Some(obj) = traces.as_object() { + Some(obj.keys().filter_map(|k| k.parse::().ok()).collect()) + } else if let Some(arr) = traces.as_array() { + Some(arr.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect()) + } else { + None + } +} + async fn count_total_traces(state: &AppState, file_uuid: &str) -> anyhow::Result { let tkg_table = schema::table_name("tkg_nodes"); let count: (i64,) = sqlx::query_as(&format!( diff --git a/src/api/files.rs b/src/api/files.rs index 61ebe420..70808578 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -1088,6 +1088,17 @@ fn delete_output_files(uuid: &str) -> u64 { tracing::info!("[UNREGISTER] Deleted workspace SQLite: {}", path.display()); } } + tracing::info!( + "[UNREGISTER] Deleted {} output files for {}", + deleted_count, + uuid + ); + if deleted_count == 0 { + tracing::warn!( + "[UNREGISTER] No output files found to delete for {}", + uuid + ); + } deleted_count } @@ -1637,6 +1648,7 @@ async fn sync_file_status( use crate::core::config::OUTPUT_DIR; let output_dir = OUTPUT_DIR.as_str(); + let videos_table = schema::table_name("videos"); let chunk_table = schema::table_name("chunk"); let tp_table = schema::table_name("trace_profiles"); let tkg_nodes_table = schema::table_name("tkg_nodes"); @@ -1692,12 +1704,9 @@ async fn sync_file_status( (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 + // pre_chunks 存的是 grouped chunks (zone + proximity grouping), + // 不等於 frame count,只要 JSON 存在就視為一致 + true } "cut" => { let json_count = json_data.get("scenes").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0); @@ -1708,13 +1717,8 @@ async fn sync_file_status( (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 已遷移至 Qdrant,不再比對 pre_chunks + true } "face_cluster" => { // cluster 數量可能不等於 trace 數量,只要 JSON 存在就視為一致 @@ -1742,10 +1746,11 @@ async fn sync_file_status( consistent = false; } } - - if !consistent { - all_consistent = false; - } + } + + // JSON not existing also counts as inconsistent + if !consistent { + all_consistent = false; } processor_status.insert(name.to_string(), serde_json::json!({ @@ -1792,24 +1797,32 @@ async fn sync_file_status( .unwrap_or(None) .unwrap_or(0) > 0; +// 查詢 processing_status phase + let phase: String = sqlx::query_scalar(&format!( + "SELECT COALESCE(processing_status->>'phase', '') FROM {} WHERE file_uuid = $1", + videos_table + )) + .bind(&file_uuid) + .fetch_optional(state.db.pool()) + .await + .ok() + .flatten() + .unwrap_or_default(); + + let phase_completed = phase == "COMPLETED"; + // 狀態判斷 let new_status = if all_consistent && any_json_exists { - // 所有 JSON 都存在且與 DB 一致 - if has_tkg_edges { - "agent_ready" - } else { - "completed" // 即使 0 筆也算完成 - } + "completed" } else if any_json_exists { - // 部分 JSON 存在但不一致 → 入庫中 + // 部分 JSON 存在或不一致 → 入庫中 "scanning" } else { // 無 JSON → 未開始 "registered" }; - + // 更新 DB status - let videos_table = schema::table_name("videos"); sqlx::query(&format!( "UPDATE {} SET status = $1, updated_at = NOW() WHERE file_uuid = $2", videos_table diff --git a/src/api/identities.rs b/src/api/identities.rs index 1bc4d1b2..7f39e3aa 100644 --- a/src/api/identities.rs +++ b/src/api/identities.rs @@ -447,11 +447,11 @@ async fn list_unassigned_traces( let page_size = std::cmp::min(query.page_size.unwrap_or(20), 100); let offset = (page - 1) * page_size; - // Query Qdrant _faces for unbound traces (identity_id IS NULL, trace_id > 0) + // Query Qdrant _faces for unbound traces (identity_id IS NULL, trace_id >= 0) let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); let mut filter_must: Vec = vec![ serde_json::json!({"is_null": {"key": "identity_id"}}), - serde_json::json!({"key": "trace_id", "range": {"gt": 0}}), + serde_json::json!({"key": "trace_id", "range": {"gte": 0}}), ]; if let Some(ref file_uuid) = query.file_uuid { filter_must.push(serde_json::json!({"key": "file_uuid", "match": {"value": file_uuid}})); @@ -489,7 +489,7 @@ async fn list_unassigned_traces( None => continue, }; let trace_id = payload["trace_id"].as_i64().unwrap_or(0) as i32; - if trace_id <= 0 { + if trace_id < 0 { continue; } let frame = payload["frame"].as_i64().unwrap_or(0); diff --git a/src/api/media_api.rs b/src/api/media_api.rs index 9ab98e54..e2d52aa4 100644 --- a/src/api/media_api.rs +++ b/src/api/media_api.rs @@ -719,7 +719,7 @@ async fn stream_video( .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .unwrap_or(24.0); - (sf / _fps, (ef - sf) / _fps) + (sf / _fps, ((ef - sf).max(0.0) + 1.0) / _fps) } else if let (Some(st), Some(et)) = (start_time_param, end_time_param) { (st, et - st) } else if let (Some(s), Some(e)) = (start_legacy, end_legacy) { diff --git a/src/api/profile.rs b/src/api/profile.rs index 3572240b..5926f197 100644 --- a/src/api/profile.rs +++ b/src/api/profile.rs @@ -11,20 +11,34 @@ use crate::api::middleware::UserAuth; use crate::api::types::AppState; use crate::core::db::schema; +fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 { + if a.len() != b.len() || a.is_empty() { + return 0.0; + } + let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum(); + let na: f32 = a.iter().map(|x| x * x).sum::().sqrt(); + let nb: f32 = b.iter().map(|x| x * x).sum::().sqrt(); + if na == 0.0 || nb == 0.0 { + 0.0 + } else { + dot / (na * nb) + } +} + // ─── Trace Profile ─── #[derive(Deserialize)] pub struct TraceProfileQuery { pub file_uuid: String, - pub trace_id: i64, + pub trace_id: i32, } #[derive(Debug, Serialize, Deserialize)] pub struct TraceProfile { pub file_uuid: String, - pub trace_id: i64, + pub trace_id: i32, pub name: String, - pub key_frame: Option, + pub key_frame: Option, pub key_face: Option, pub aliases: Option, pub bbox: Option, @@ -34,9 +48,9 @@ pub struct TraceProfile { #[derive(Deserialize)] pub struct UpdateTraceProfileRequest { pub file_uuid: String, - pub trace_id: i64, + pub trace_id: i32, pub name: Option, - pub key_frame: Option, + pub key_frame: Option, pub key_face: Option, pub aliases: Option, pub properties: Option, @@ -45,7 +59,7 @@ pub struct UpdateTraceProfileRequest { #[derive(Deserialize)] pub struct UpdateTraceProfileGroupRequest { pub file_uuid: String, - pub trace_ids: Vec, + pub trace_ids: Vec, pub name: String, } @@ -66,19 +80,54 @@ pub struct MergeGroupsResponse { pub message: String, } +pub async fn save_trace_operation_snapshot( + pool: &PgPool, + file_uuid: &str, + operation: &str, + before_snapshot: serde_json::Value, + after_snapshot: Option, + user_id: Option<&str>, +) -> Result<(), ()> { + let table = schema::table_name("trace_operation_history"); + let result = sqlx::query(&format!( + "INSERT INTO {} (file_uuid, operation, before_snapshot, after_snapshot, user_id) VALUES ($1, $2, $3, $4, $5)", + table + )) + .bind(file_uuid) + .bind(operation) + .bind(&before_snapshot) + .bind(&after_snapshot) + .bind(user_id) + .execute(pool) + .await; + match result { + Ok(_) => Ok(()), + Err(e) => { + tracing::error!("[TraceOpHistory] Failed to save snapshot: {}", e); + Err(()) + } + } +} + pub async fn get_trace_profile_handler( State(state): State, Extension(_auth): Extension, Query(params): Query, ) -> Result, StatusCode> { let tkg_table = schema::table_name("tkg_nodes"); + let tp_table = schema::table_name("trace_profiles"); let external_id_face = format!("face_track_{}", params.trace_id); let external_id_trace = format!("trace_{}", params.trace_id); - let row: Option<(String, String, serde_json::Value)> = sqlx::query_as(&format!( - "SELECT label, external_id, properties FROM {} \ - WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)", - tkg_table + let row: Option<(String, String, serde_json::Value, serde_json::Value)> = sqlx::query_as(&format!( + "SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \ + tp.properties, 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' \ + AND (tn.external_id = $2 OR tn.external_id = $3)", + tkg_table, tp_table )) .bind(¶ms.file_uuid) .bind(&external_id_face) @@ -90,9 +139,21 @@ pub async fn get_trace_profile_handler( StatusCode::INTERNAL_SERVER_ERROR })?; - let (label, _ext_id, properties) = row.ok_or(StatusCode::NOT_FOUND)?; + let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?; - let key_frame = properties.get("key_frame").and_then(|v| v.as_i64()); + // Merge properties: tp_props takes precedence, tn_props as fallback + let mut properties = tn_props.clone(); + if let Some(tp_obj) = tp_props.as_object() { + if let Some(props_obj) = properties.as_object_mut() { + for (k, v) in tp_obj { + if !v.is_null() { + props_obj.insert(k.clone(), v.clone()); + } + } + } + } + + let key_frame = properties.get("key_frame").and_then(|v| v.as_str()).map(|s| s.to_string()); let key_face = properties .get("key_face") .and_then(|v| v.as_str()) @@ -103,7 +164,7 @@ pub async fn get_trace_profile_handler( Ok(Json(TraceProfile { file_uuid: params.file_uuid, trace_id: params.trace_id, - name: label, + name, key_frame, key_face, aliases, @@ -180,6 +241,9 @@ pub async fn update_trace_profile_handler( }))); } + let new_name_val = req.name.as_deref(); + let before_name = current_name.clone().unwrap_or_default(); + let props_json = serde_json::to_string(¤t_props).unwrap(); let mut query = format!( @@ -195,19 +259,34 @@ pub async fn update_trace_profile_handler( let mut sql_query = sqlx::query(&query) .bind(&req.file_uuid) .bind(&props_json) - .bind(req.trace_id); + .bind(req.trace_id as i32); 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", - "file_uuid": req.file_uuid, - "trace_id": req.trace_id - }))), + Ok(res) if res.rows_affected() > 0 => { + let after_name = new_name_val.unwrap_or(&before_name); + let _ = save_trace_operation_snapshot( + state.db.pool(), + &req.file_uuid, + "rename_single", + serde_json::json!({ + "traces": { req.trace_id.to_string(): before_name } + }), + Some(serde_json::json!({ + "traces": { req.trace_id.to_string(): after_name } + })), + None, + ).await; + Ok(Json(serde_json::json!({ + "success": true, + "message": "Trace profile updated", + "file_uuid": req.file_uuid, + "trace_id": req.trace_id + }))) + } Ok(_) => Err(StatusCode::NOT_FOUND), Err(e) => { tracing::error!("[TraceProfile] Update failed: {}", e); @@ -223,6 +302,26 @@ pub async fn update_trace_profile_group_handler( ) -> Result, StatusCode> { let tp_table = schema::table_name("trace_profiles"); + // Snapshot current names before update + let mut before_names: serde_json::Map = serde_json::Map::new(); + for trace_id in &req.trace_ids { + let current: Option<(String,)> = sqlx::query_as(&format!( + "SELECT name FROM {} WHERE file_uuid = $1 AND trace_id = $2", + tp_table + )) + .bind(&req.file_uuid) + .bind(trace_id) + .fetch_optional(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[TraceProfileGroup] DB error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + if let Some((name,)) = current { + before_names.insert(trace_id.to_string(), serde_json::json!(name)); + } + } + let mut updated = 0; for trace_id in &req.trace_ids { let result = sqlx::query(&format!( @@ -240,6 +339,17 @@ pub async fn update_trace_profile_group_handler( } } + let _ = save_trace_operation_snapshot( + state.db.pool(), + &req.file_uuid, + "rename_batch", + serde_json::json!({ "traces": before_names }), + Some(serde_json::json!({ + "traces": req.trace_ids.iter().map(|tid| (tid.to_string(), serde_json::json!(req.name))).collect::>() + })), + None, + ).await; + Ok(Json(serde_json::json!({ "success": true, "message": format!("Updated {} traces in group", updated), @@ -275,17 +385,31 @@ pub async fn merge_groups_handler( )); } - // Update trace_profiles.name for all matching traces + // Snapshot current names before merge let tp_table = schema::table_name("trace_profiles"); + let before_names: Vec<(i32, String)> = sqlx::query_as(&format!( + "SELECT trace_id, name FROM {} WHERE file_uuid = $1 AND name = ANY($2)", + tp_table + )) + .bind(&req.file_uuid) + .bind(&req.source_groups) + .fetch_all(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[MergeGroups] Snapshot error: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": e.to_string()})), + ) + })?; + + // Update trace_profiles.name AND tkg_nodes.label for all matching traces 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 + // First update tkg_nodes.label + let nodes_result = sqlx::query(&format!( + "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND label = ANY($3)", + nodes_table )) .bind(&req.target_group_name) .bind(&req.file_uuid) @@ -293,21 +417,50 @@ pub async fn merge_groups_handler( .execute(state.db.pool()) .await; - match result { - Ok(res) => { - let updated = res.rows_affected(); + // Then update trace_profiles.name + let tp_result = sqlx::query(&format!( + "UPDATE {} SET name = $1 WHERE file_uuid = $2 AND name = ANY($3)", + tp_table + )) + .bind(&req.target_group_name) + .bind(&req.file_uuid) + .bind(&req.source_groups) + .execute(state.db.pool()) + .await; + + match (nodes_result, tp_result) { + (Ok(nodes_res), Ok(tp_res)) => { + let updated = tp_res.rows_affected(); + let nodes_updated = nodes_res.rows_affected(); let group_count = req.source_groups.len(); let target_name = req.target_group_name.clone(); + + let before_map: serde_json::Map = before_names + .iter() + .map(|(tid, name)| (tid.to_string(), serde_json::json!(name))) + .collect(); + let _ = save_trace_operation_snapshot( + state.db.pool(), + &req.file_uuid, + "merge_groups", + serde_json::json!({ "traces": before_map, "target": &target_name, "sources": &req.source_groups }), + Some(serde_json::json!({ + "traces": before_names.iter().map(|(tid, _)| (tid.to_string(), serde_json::json!(&target_name))).collect::>(), + "target": &target_name, + })), + None, + ).await; + Ok(Json(MergeGroupsResponse { success: true, file_uuid: req.file_uuid, source_groups: req.source_groups, - target_group_name: req.target_group_name, + target_group_name: target_name.clone(), traces_merged: updated, message: format!("Merged {} group(s) into '{}'", group_count, target_name), })) } - Err(e) => { + (Err(e), _) | (_, Err(e)) => { tracing::error!("[MergeGroups] DB error: {}", e); Err(( StatusCode::INTERNAL_SERVER_ERROR, @@ -320,6 +473,299 @@ pub async fn merge_groups_handler( } } +#[derive(Serialize)] +pub struct UndoFaceOperationResponse { + pub success: bool, + pub file_uuid: String, + pub operation: String, + pub message: String, +} + +pub async fn undo_face_operation_handler( + State(state): State, + Extension(_auth): Extension, + Path(file_uuid): Path, +) -> Result, (StatusCode, Json)> { + let table = schema::table_name("trace_operation_history"); + let tp_table = schema::table_name("trace_profiles"); + let tkg_table = schema::table_name("tkg_nodes"); + + // Find latest undoable operation for this file + let record: Option<(i64, String, serde_json::Value)> = sqlx::query_as(&format!( + "SELECT id, operation, before_snapshot FROM {} WHERE file_uuid = $1 AND is_undone = false ORDER BY created_at DESC LIMIT 1", + table + )) + .bind(&file_uuid) + .fetch_optional(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[UndoFaceOp] DB error: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": e.to_string()})), + ) + })?; + + let (history_id, operation, before_snapshot) = record.ok_or_else(|| { + ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "No undoable operations found for this file"})), + ) + })?; + + // Handle merge_trace specially (Qdrant point restore) + if operation == "merge_trace" { + return undo_merge_trace(state, file_uuid, history_id, before_snapshot).await; + } + + // Handle hard_delete (restore from _faces_trash) + if operation == "hard_delete" { + return undo_hard_delete_trace(state, file_uuid, history_id, before_snapshot).await; + } + + // Handle operations with traces name mapping + let traces = before_snapshot.get("traces").and_then(|v| v.as_object()).ok_or_else(|| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": "Invalid snapshot: missing traces"})), + ) + })?; + + for (trace_id_str, name_val) in traces { + let name = name_val.as_str().unwrap_or("Person_0"); + let trace_id: i32 = trace_id_str.parse().unwrap_or(0); + + // Restore trace_profiles.name + let _ = sqlx::query(&format!( + "UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3", + tp_table + )) + .bind(name) + .bind(&file_uuid) + .bind(trace_id) + .execute(state.db.pool()) + .await; + + // For merge_groups, also restore tkg_nodes.label + if operation == "merge_groups" { + let _ = sqlx::query(&format!( + "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND external_id = $3", + tkg_table + )) + .bind(name) + .bind(&file_uuid) + .bind(format!("trace_{}", trace_id)) + .execute(state.db.pool()) + .await; + } + } + + // Mark as undone + let _ = sqlx::query(&format!( + "UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1", + table + )) + .bind(history_id) + .execute(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[UndoFaceOp] Failed to mark as undone: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": e.to_string()})), + ) + })?; + + Ok(Json(UndoFaceOperationResponse { + success: true, + file_uuid, + operation, + message: "Operation undone successfully".to_string(), + })) +} + +async fn undo_merge_trace( + state: AppState, + file_uuid: String, + history_id: i64, + before_snapshot: serde_json::Value, +) -> Result, (StatusCode, Json)> { + let table = schema::table_name("trace_operation_history"); + let tkg_table = schema::table_name("tkg_nodes"); + + let source_trace_id = before_snapshot["source_trace_id"].as_i64().unwrap_or(0); + let target_trace_id = before_snapshot["target_trace_id"].as_i64().unwrap_or(0); + + // 1. Delete merged points from target trace (those with merged_from marker) + let delete_filter = serde_json::json!({ + "must": [ + {"key": "file_uuid", "match": {"value": &file_uuid}}, + {"key": "trace_id", "match": {"value": target_trace_id}}, + {"key": "merged_from", "match": {"value": source_trace_id}} + ] + }); + let _ = state.qdrant.delete_points_by_filter("_faces", delete_filter).await; + + // 2. Re-insert original points + if let Some(qdrant_points) = before_snapshot["qdrant_points"].as_array() { + let owned_batch: Vec<(u64, Vec, Option)> = qdrant_points + .iter() + .filter_map(|p| { + let id = p["id"].as_u64()?; + let vec_arr = p["vector"].as_array()?; + let vector: Vec = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect(); + let payload = p["payload"].clone(); + Some((id, vector, Some(payload))) + }) + .collect(); + + let ref_batch: Vec<(u64, &[f32], Option)> = owned_batch + .iter() + .map(|(id, vec, pl)| (*id, vec.as_slice(), pl.clone())) + .collect(); + + if !ref_batch.is_empty() { + if let Err(e) = state.qdrant.upsert_vectors_batch("_faces", &ref_batch).await { + tracing::error!("[UndoMergeTrace] Failed to restore Qdrant points: {}", e); + } + } + } + + // 3. Re-insert TKG nodes + if let Some(tkg_nodes) = before_snapshot["tkg_nodes"].as_array() { + for node in tkg_nodes { + let ext_id = node["external_id"].as_str().unwrap_or(""); + let label = node["label"].as_str().unwrap_or("Person_0"); + let props = node.get("properties").cloned().unwrap_or(serde_json::json!({"trace_id": source_trace_id})); + + let _ = sqlx::query(&format!( + "INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4) ON CONFLICT DO NOTHING", + tkg_table + )) + .bind(&file_uuid) + .bind(ext_id) + .bind(label) + .bind(&props) + .execute(state.db.pool()) + .await; + } + } + + // Mark as undone + let _ = sqlx::query(&format!( + "UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1", + table + )) + .bind(history_id) + .execute(state.db.pool()) + .await; + + Ok(Json(UndoFaceOperationResponse { + success: true, + file_uuid, + operation: "merge_trace".to_string(), + message: "Trace merge undone successfully".to_string(), + })) +} + +async fn undo_hard_delete_trace( + state: AppState, + file_uuid: String, + history_id: i64, + before_snapshot: serde_json::Value, +) -> Result, (StatusCode, Json)> { + let table = schema::table_name("trace_operation_history"); + let tkg_table = schema::table_name("tkg_nodes"); + + let trace_id = before_snapshot["trace_id"].as_i64().unwrap_or(0); + + // 1. Scroll points from _faces_trash + let trash_filter = serde_json::json!({ + "must": [ + {"key": "file_uuid", "match": {"value": &file_uuid}}, + {"key": "trace_id", "match": {"value": trace_id}} + ] + }); + let trash_points = state.qdrant + .scroll_all_points_with_vectors("_faces_trash", trash_filter.clone(), 1000) + .await + .map_err(|e| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("Failed to read trash: {}", e)})), + ) + })?; + + if trash_points.is_empty() { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "No trashed points found for this trace"})), + )); + } + + // 2. Copy back to _faces + let restore_batch: Vec<(u64, Vec, serde_json::Value)> = trash_points + .iter() + .filter_map(|p| { + let id = p["id"].as_u64()?; + let vec_arr = p["vector"].as_array()?; + let vector: Vec = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect(); + let mut payload = p["payload"].clone(); + if let Some(obj) = payload.as_object_mut() { + obj.remove("trashed_at"); + } + Some((id, vector, payload)) + }) + .collect(); + + let ref_batch: Vec<(u64, &[f32], Option)> = restore_batch + .iter() + .map(|(id, vec, pl)| (*id, vec.as_slice(), Some(pl.clone()))) + .collect(); + + if let Err(e) = state.qdrant.upsert_vectors_batch("_faces", &ref_batch).await { + tracing::error!("[UndoHardDelete] Failed to restore points: {}", e); + } + + // 3. Delete from _faces_trash + let _ = state.qdrant.delete_points_by_filter("_faces_trash", trash_filter).await; + + // 4. Re-insert TKG nodes + if let Some(tkg_nodes) = before_snapshot["tkg_nodes"].as_array() { + for node in tkg_nodes { + let ext_id = node["external_id"].as_str().unwrap_or(""); + let label = node["label"].as_str().unwrap_or("Person_0"); + let props = node.get("properties").cloned().unwrap_or(serde_json::json!({"trace_id": trace_id})); + let _ = sqlx::query(&format!( + "INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4) ON CONFLICT DO NOTHING", + tkg_table + )) + .bind(&file_uuid) + .bind(ext_id) + .bind(label) + .bind(&props) + .execute(state.db.pool()) + .await; + } + } + + // 5. Mark as undone + let _ = sqlx::query(&format!( + "UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1", + table + )) + .bind(history_id) + .execute(state.db.pool()) + .await; + + Ok(Json(UndoFaceOperationResponse { + success: true, + file_uuid, + operation: "hard_delete".to_string(), + message: "Trace restored from trash successfully".to_string(), + })) +} + // ─── File Profile ─── #[derive(Deserialize)] @@ -439,11 +885,11 @@ pub async fn update_file_profile_handler( let mut updates: Vec = Vec::new(); let mut param_idx: i32 = 1; - if req.file_path.is_some() { + if req.file_path.as_ref().is_some_and(|s| !s.is_empty()) { updates.push(format!("file_path = ${}", param_idx)); param_idx += 1; } - if req.file_name.is_some() { + if req.file_name.as_ref().is_some_and(|s| !s.is_empty()) { updates.push(format!("file_name = ${}", param_idx)); param_idx += 1; } @@ -465,30 +911,35 @@ pub async fn update_file_profile_handler( ); // Build the SQL and execute with correct bind order - let result = match (&req.file_path, &req.file_name) { - (Some(fp), Some(fn_)) => { + let has_path = req.file_path.as_ref().is_some_and(|s| !s.is_empty()); + let has_name = req.file_name.as_ref().is_some_and(|s| !s.is_empty()); + let clean_path = req.file_path.as_ref().filter(|s| !s.is_empty()); + let clean_name = req.file_name.as_ref().filter(|s| !s.is_empty()); + + let result = match (has_path, has_name) { + (true, true) => { sqlx::query(&sql) - .bind(fp) - .bind(fn_) + .bind(clean_path.unwrap()) + .bind(clean_name.unwrap()) .bind(&req.file_uuid) .execute(state.db.pool()) .await } - (Some(fp), None) => { + (true, false) => { sqlx::query(&sql) - .bind(fp) + .bind(clean_path.unwrap()) .bind(&req.file_uuid) .execute(state.db.pool()) .await } - (None, Some(fn_)) => { + (false, true) => { sqlx::query(&sql) - .bind(fn_) + .bind(clean_name.unwrap()) .bind(&req.file_uuid) .execute(state.db.pool()) .await } - (None, None) => unreachable!(), + (false, false) => unreachable!(), }; match result { @@ -534,9 +985,9 @@ pub async fn update_file_profile_handler( pub struct FaceGroup { pub group_id: i32, pub name: String, - pub trace_ids: Vec, + pub trace_ids: Vec, pub trace_count: i32, - pub representative_trace: i64, + pub representative_trace: i32, pub editable: bool, } @@ -546,7 +997,7 @@ pub struct FaceGroupsResponse { pub file_uuid: String, pub face_groups: Vec, pub total_groups: i32, - pub unassigned_traces: Vec, + pub unassigned_traces: Vec, } pub async fn get_face_groups_handler( @@ -558,12 +1009,13 @@ pub async fn get_face_groups_handler( let tp_table = schema::table_name("trace_profiles"); let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&format!( - "SELECT COALESCE(tp.name, tn.label) as name, tn.properties \ + "SELECT COALESCE(tp.name, tn.label) as name, \ + COALESCE(tp.properties, tn.properties) as 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", + ORDER BY (COALESCE(tp.properties, tn.properties)->>'trace_id')::int", tkg_table, tp_table )) .bind(&file_uuid) @@ -574,13 +1026,14 @@ pub async fn get_face_groups_handler( StatusCode::INTERNAL_SERVER_ERROR })?; - let mut groups: HashMap> = HashMap::new(); - let mut unassigned: Vec = Vec::new(); + let mut groups: HashMap> = HashMap::new(); + let mut unassigned: Vec = Vec::new(); for (name, properties) in rows { let trace_id = properties .get("trace_id") .and_then(|v| v.as_i64()) + .map(|v| v as i32) .unwrap_or(0); if name.starts_with("Face Trace ") || name.starts_with("Trace ") { @@ -612,6 +1065,199 @@ pub async fn get_face_groups_handler( })) } +// ─── Similar Group Suggestion ─── + +#[derive(Deserialize)] +pub struct SimilarGroupQuery { + pub trace_ids: String, + pub top_k: Option, + pub min_score: Option, +} + +#[derive(Debug, Serialize)] +pub struct SimilarGroupSuggestion { + pub group_name: String, + pub score: f64, + pub matched_trace_id: i32, +} + +#[derive(Debug, Serialize)] +pub struct SimilarGroupResponse { + pub success: bool, + pub file_uuid: String, + pub suggestions: Vec, +} + +pub async fn get_similar_group_handler( + State(state): State, + Extension(_auth): Extension, + Path(file_uuid): Path, + Query(params): Query, +) -> Result, StatusCode> { + let source_trace_ids: Vec = params + .trace_ids + .split(',') + .filter_map(|s| s.trim().parse().ok()) + .collect(); + + if source_trace_ids.is_empty() { + return Ok(Json(SimilarGroupResponse { + success: false, + file_uuid, + suggestions: vec![], + })); + } + + let top_k = params.top_k.unwrap_or(1); + let min_score = params.min_score.unwrap_or(0.6); + + // 1. Scroll all face points for the file with vectors + let face_filter = serde_json::json!({ + "must": [{"key": "file_uuid", "match": {"value": &file_uuid}}] + }); + let all_points = match state + .qdrant + .scroll_all_points_with_vectors("_faces", face_filter, 1000) + .await + { + Ok(pts) => pts, + Err(e) => { + tracing::error!("[SimilarGroup] Qdrant scroll error: {}", e); + return Err(StatusCode::INTERNAL_SERVER_ERROR); + } + }; + + // 2. Group face vectors by trace_id + let mut trace_vectors: HashMap>> = HashMap::new(); + for point in &all_points { + let tid = point["payload"]["trace_id"].as_i64().unwrap_or(0); + if tid <= 0 { + continue; + } + let vector: Vec = point["vector"] + .as_array() + .map(|arr| { + arr.iter() + .filter_map(|v| v.as_f64().map(|f| f as f32)) + .collect() + }) + .unwrap_or_default(); + if vector.len() == 512 { + trace_vectors.entry(tid).or_default().push(vector); + } + } + + // 3. Compute source centroid + let mut source_vectors: Vec> = Vec::new(); + for tid in &source_trace_ids { + if let Some(vectors) = trace_vectors.get(tid) { + source_vectors.extend(vectors.clone()); + } + } + if source_vectors.is_empty() { + return Ok(Json(SimilarGroupResponse { + success: true, + file_uuid, + suggestions: vec![], + })); + } + + let dim = source_vectors[0].len(); + let mut centroid = vec![0.0f32; dim]; + for vec in &source_vectors { + for (i, &v) in vec.iter().enumerate() { + centroid[i] += v; + } + } + let count = source_vectors.len() as f32; + for v in &mut centroid { + *v /= count; + } + + // 4. Build trace_id → group_name mapping from DB + let tkg_table = schema::table_name("tkg_nodes"); + let tp_table = schema::table_name("trace_profiles"); + let db_rows: Vec<(String, i64)> = sqlx::query_as(&format!( + "SELECT COALESCE(tp.name, tn.label) as name, (tn.properties->>'trace_id')::bigint as trace_id \ + FROM {} tn \ + LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \ + AND tp.trace_id = (tn.properties->>'trace_id')::bigint \ + WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track'", + tkg_table, tp_table + )) + .bind(&file_uuid) + .fetch_all(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[SimilarGroup] DB error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + let mut trace_group: HashMap = HashMap::new(); + let mut group_traces: HashMap> = HashMap::new(); + for (name, trace_id) in &db_rows { + if name.starts_with("Face Trace ") || name.starts_with("Trace ") { + continue; + } + trace_group.insert(*trace_id, name.clone()); + group_traces.entry(name.clone()).or_default().push(*trace_id); + } + + let source_group_names: Vec = db_rows + .iter() + .filter(|(_, tid)| source_trace_ids.contains(tid)) + .map(|(name, _)| name.clone()) + .collect(); + + // 5. For each non-source trace, compute cosine similarity with centroid + // Use the best face per trace for the similarity score + let mut trace_scores: Vec<(i64, f64)> = Vec::new(); + for (&tid, vectors) in &trace_vectors { + if source_trace_ids.contains(&tid) { + continue; + } + let best_score: f64 = vectors + .iter() + .map(|v| cosine_similarity(¢roid, v) as f64) + .fold(0.0f64, f64::max); + if best_score >= min_score { + trace_scores.push((tid, best_score)); + } + } + + // 6. Aggregate by group name, keep best score + let mut group_scores: HashMap = HashMap::new(); + for (tid, score) in &trace_scores { + if let Some(gname) = trace_group.get(tid) { + if source_group_names.contains(gname) { + continue; + } + let entry = group_scores.entry(gname.clone()).or_insert((0.0, *tid)); + if *score > entry.0 { + *entry = (*score, *tid); + } + } + } + + // 7. Sort by score descending, take top_k + let mut suggestions: Vec = group_scores + .into_iter() + .map(|(group_name, (score, matched_trace_id))| SimilarGroupSuggestion { + group_name, + score, + matched_trace_id: matched_trace_id as i32, + }) + .collect(); + suggestions.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal)); + suggestions.truncate(top_k); + + Ok(Json(SimilarGroupResponse { + success: true, + file_uuid, + suggestions, + })) +} + // ─── Routes ─── pub fn profile_routes() -> axum::Router { @@ -629,8 +1275,16 @@ pub fn profile_routes() -> axum::Router { "/api/v1/file/:file_uuid/face-groups", get(get_face_groups_handler), ) + .route( + "/api/v1/file/:file_uuid/face-groups/similar", + get(get_similar_group_handler), + ) .route( "/api/v1/file/:file_uuid/groups/merge", post(merge_groups_handler), ) + .route( + "/api/v1/file/:file_uuid/face-operations/undo", + post(undo_face_operation_handler), + ) } diff --git a/src/api/search.rs b/src/api/search.rs index 02bb8be7..be572942 100644 --- a/src/api/search.rs +++ b/src/api/search.rs @@ -64,6 +64,37 @@ struct MergedResult { source: String, } +/// Parse /ocr, /asr, /asrx suffix from the end of a query string. +/// Returns (clean_query, optional_source_filter). +/// The filter value is in source_type terms ("ocr" / "asrx") for result filtering, +/// not chunk_type terms ("ocr" / "sentence"). +fn parse_source_filter(query: &str) -> (String, Option) { + let trimmed = query.trim(); + if let Some(rest) = trimmed + .strip_suffix("/ocr") + .or_else(|| trimmed.strip_suffix("/OCR")) + { + (rest.trim().to_string(), Some("ocr".to_string())) + } else if let Some(rest) = trimmed + .strip_suffix("/asr") + .or_else(|| trimmed.strip_suffix("/ASR")) + .or_else(|| trimmed.strip_suffix("/asrx")) + .or_else(|| trimmed.strip_suffix("/ASRX")) + { + (rest.trim().to_string(), Some("asrx".to_string())) + } else { + (query.to_string(), None) + } +} + +/// Map a source_type filter ("ocr" / "asrx") to chunk_type for DB queries. +fn source_filter_to_chunk_type(filter: &str) -> &str { + match filter { + "ocr" => "ocr", + _ => "sentence", // "asrx" → "sentence" + } +} + fn map_chunk_type_to_source(chunk_type: &str) -> String { match chunk_type.to_lowercase().as_str() { "ocr" => "ocr".to_string(), @@ -151,9 +182,14 @@ pub async fn smart_search( let hard_limit = req.limit.unwrap_or(usize::MAX); let limit = hard_limit.min(page_size); - // 1. Generate embedding + let (clean_query, source_filter) = parse_source_filter(&req.query); + let chunk_type_filter = source_filter + .as_deref() + .map(source_filter_to_chunk_type); + + // 1. Generate embedding from clean query let embedder = Embedder::new("embeddinggemma-300m".to_string()); - let embedding = embedder.embed_query(&req.query).await.map_err( + let embedding = embedder.embed_query(&clean_query).await.map_err( |e| -> (StatusCode, Json) { tracing::error!("Embedding failed: {}", e); ( @@ -199,7 +235,7 @@ pub async fn smart_search( // 3. Keyword search via PG ILIKE let keyword_results: Vec<(String, String, f64)> = match db - .search_bm25(&req.query, req.file_uuid.as_deref(), fetch_limit as i64) + .search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, fetch_limit as i64) .await { Ok(rows) => { @@ -221,14 +257,14 @@ pub async fn smart_search( // 3b. Video title search: if query matches a video title, get its chunks const TITLE_MATCH_SCORE: f64 = 0.75; // Lower than semantic max (0.85-0.9), but higher than keyword let title_results: Vec<(String, String, f64)> = { - let clean_query = req.query.replace('\'', "''"); + let clean_query_escaped = clean_query.replace('\'', "''"); let v_table = crate::core::db::schema::table_name("videos"); let c_table = crate::core::db::schema::table_name("chunk"); let video_rows: Vec<(String,)> = sqlx::query_as(&format!( "SELECT file_uuid::text FROM {} WHERE file_name ILIKE $1 LIMIT 5", v_table )) - .bind(format!("%{}%", clean_query)) + .bind(format!("%{}%", clean_query_escaped)) .fetch_all(db.pool()) .await .unwrap_or_default(); @@ -261,12 +297,12 @@ pub async fn smart_search( // 4. Identity search: if query matches a person name, get their chunks let identity_results: Vec<(String, String, f64)> = { let id_table = crate::core::db::schema::table_name("identities"); - let clean_query = req.query.replace('\'', "''"); + let clean_query_escaped = clean_query.replace('\'', "''"); let id_rows: Vec<(i32, String, String)> = sqlx::query_as(&format!( "SELECT id, name, uuid::text FROM {} WHERE name ILIKE $1 LIMIT 5", id_table )) - .bind(format!("%{}%", clean_query)) + .bind(format!("%{}%", clean_query_escaped)) .fetch_all(db.pool()) .await .unwrap_or_default(); @@ -407,7 +443,7 @@ pub async fn smart_search( ); // 6. Enrich top results from PG and build final response - let query_lower = req.query.to_lowercase(); + let query_lower = clean_query.to_lowercase(); let mut final_results = Vec::new(); // Take all merged results to ensure keyword results are processed // (keyword results often have low scores and rank last) @@ -423,6 +459,14 @@ pub async fn smart_search( .await }; if let Some(pg) = pg_opt.ok().flatten() { + // Apply source filter (/ocr /asr /asrx) + if let Some(ref filter) = source_filter { + let st = map_chunk_type_to_source(&pg.chunk_type); + if st != *filter { + continue; + } + } + // 關鍵字結果跳過 text_match 過濾(search_bm25 已經匹配過) // Semantic-only results 也跳過 text_match(語意匹配不需要詞彙匹配) let is_keyword_only = mr.keyword_score.is_some() && mr.semantic_score.is_none(); @@ -583,9 +627,14 @@ pub async fn keyword_search( let page_size = req.page_size.unwrap_or(5).max(1); let limit = page_size; + let (clean_query, source_filter) = parse_source_filter(&req.query); + let chunk_type_filter = source_filter + .as_deref() + .map(source_filter_to_chunk_type); + // Keyword search via PG BM25 let keyword_results = db - .search_bm25(&req.query, req.file_uuid.as_deref(), limit as i64) + .search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, limit as i64) .await .map_err(|e| { tracing::error!("Keyword search failed: {}", e); @@ -650,9 +699,11 @@ pub async fn semantic_search( let page_size = req.page_size.unwrap_or(5).max(1); let limit = page_size; - // Generate embedding + let (clean_query, source_filter) = parse_source_filter(&req.query); + + // Generate embedding from clean query let embedder = Embedder::new("embeddinggemma-300m".to_string()); - let embedding = embedder.embed_query(&req.query).await.map_err(|e| { + let embedding = embedder.embed_query(&clean_query).await.map_err(|e| { tracing::error!("Embedding failed: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, @@ -660,7 +711,7 @@ pub async fn semantic_search( ) })?; - // Semantic search via Qdrant + // Semantic search via Qdrant (only has sentence vectors, so /ocr returns empty) let semantic_results = if let Some(file_uuid) = &req.file_uuid { qdrant .search_in_uuid(&embedding, file_uuid, limit) @@ -673,12 +724,17 @@ pub async fn semantic_search( tracing::info!( "Semantic search: {} hits for '{}'", semantic_results.len(), - req.query + clean_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 { + if let Some(ref filter) = source_filter { + if p.source_type.as_deref() != Some(filter.as_str()) { + continue; + } + } results.push(p); } } diff --git a/src/api/server.rs b/src/api/server.rs index 4543d4a5..bbe9a472 100644 --- a/src/api/server.rs +++ b/src/api/server.rs @@ -97,6 +97,12 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> { let api_state = super::middleware::ApiState { db: db.clone() }; let qdrant = std::sync::Arc::new(QdrantDb::new()); + + // Ensure trash collection exists for trace hard-delete undo + if let Err(e) = qdrant.ensure_collection("_faces_trash", 512).await { + tracing::warn!("[Server] Failed to ensure _faces_trash collection: {}", e); + } + let state = AppState { db, qdrant, diff --git a/src/api/trace_agent_api.rs b/src/api/trace_agent_api.rs index 4c7252da..b065c11d 100644 --- a/src/api/trace_agent_api.rs +++ b/src/api/trace_agent_api.rs @@ -1714,41 +1714,67 @@ async fn delete_trace( let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); if hard_delete { - // Hard delete: actually remove from Qdrant and TKG + // Hard delete: move to _faces_trash, then remove from _faces and TKG let filter = serde_json::json!({ "must": [ - {"key": "file_uuid", "match": {"value": file_uuid}}, + {"key": "file_uuid", "match": {"value": &file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}} ] }); - let deleted_count = match qdrant - .delete_points_by_filter("_faces", filter.clone()) + // 0. Scroll points with vectors for trash backup + let trashed_points = qdrant + .scroll_all_points_with_vectors("_faces", filter.clone(), 1000) .await - { - Ok(count) => { - tracing::info!( - "[delete_trace] Hard deleted {} face points from Qdrant for trace {} in {}", - count, - trace_id, - file_uuid - ); - count - } - Err(e) => { - tracing::error!("[delete_trace] Failed to delete Qdrant points: {}", e); - return Json(serde_json::json!({ - "success": false, - "error": format!("Failed to delete Qdrant points: {}", e) - })); - } - }; + .unwrap_or_default(); + // 1. Copy to _faces_trash + if !trashed_points.is_empty() { + let trash_batch: Vec<(u64, Vec, serde_json::Value)> = trashed_points + .iter() + .filter_map(|p| { + let id = p["id"].as_u64()?; + let vec_arr = p["vector"].as_array()?; + let vector: Vec = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect(); + let mut payload = p["payload"].clone(); + if let Some(obj) = payload.as_object_mut() { + obj.insert("trashed_at".to_string(), serde_json::json!(chrono::Utc::now().to_rfc3339())); + } + Some((id, vector, payload)) + }) + .collect(); + + let ref_batch: Vec<(u64, &[f32], Option)> = trash_batch + .iter() + .map(|(id, vec, pl)| (*id, vec.as_slice(), Some(pl.clone()))) + .collect(); + + if let Err(e) = qdrant.upsert_vectors_batch("_faces_trash", &ref_batch).await { + tracing::error!("[delete_trace] Failed to copy to trash: {}", e); + } + } + + // 2. Save TKG nodes before deleting let nodes_table = crate::core::db::schema::table_name("tkg_nodes"); let ext_id_face = format!("face_track_{}", trace_id); let ext_id_trace = format!("trace_{}", trace_id); - let tkg_result = sqlx::query(&format!( + let tkg_snapshot: Vec<(String, String, serde_json::Value)> = sqlx::query_as(&format!( + "SELECT external_id, label, properties FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)", + nodes_table + )) + .bind(&file_uuid) + .bind(&ext_id_face) + .bind(&ext_id_trace) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default(); + + // 3. Delete from _faces + let _ = qdrant.delete_points_by_filter("_faces", filter.clone()).await; + + // 4. Delete TKG nodes + let _ = sqlx::query(&format!( "DELETE FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)", nodes_table )) @@ -1758,21 +1784,33 @@ async fn delete_trace( .execute(state.db.pool()) .await; - let tkg_deleted = match tkg_result { - Ok(r) => r.rows_affected(), - Err(e) => { - tracing::error!("[delete_trace] Failed to delete TKG nodes: {}", e); - 0 - } - }; + // 5. Save operation snapshot + let op_table = crate::core::db::schema::table_name("trace_operation_history"); + let before_snapshot = serde_json::json!({ + "trace_id": trace_id, + "tkg_nodes": tkg_snapshot.iter().map(|(ext_id, label, props)| { + serde_json::json!({ + "external_id": ext_id, + "label": label, + "properties": props, + }) + }).collect::>(), + }); + let _ = sqlx::query(&format!( + "INSERT INTO {} (file_uuid, operation, before_snapshot) VALUES ($1, 'hard_delete', $2)", + op_table + )) + .bind(&file_uuid) + .bind(&before_snapshot) + .execute(state.db.pool()) + .await; Json(serde_json::json!({ "success": true, "file_uuid": file_uuid, "trace_id": trace_id, "hard_delete": true, - "deleted_face_points": deleted_count, - "deleted_tkg_nodes": tkg_deleted + "trashed_points": trashed_points.len(), })) } else { // Soft delete: mark as deleted in Qdrant and TKG @@ -1860,6 +1898,45 @@ async fn merge_trace( let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); + // Step 0: Snapshot source trace state before merge + let src_filter_all = serde_json::json!({ + "must": [ + {"key": "file_uuid", "match": {"value": &file_uuid}}, + {"key": "trace_id", "match": {"value": trace_id}} + ] + }); + let qdrant_points = qdrant + .scroll_all_points_with_vectors("_faces", src_filter_all.clone(), 1000) + .await + .unwrap_or_default(); + + let nodes_table = crate::core::db::schema::table_name("tkg_nodes"); + let ext_id_face = format!("face_track_{}", trace_id); + let ext_id_trace = format!("trace_{}", trace_id); + let tkg_nodes: Vec<(String, String, serde_json::Value)> = sqlx::query_as(&format!( + "SELECT external_id, label, properties FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)", + nodes_table + )) + .bind(&file_uuid) + .bind(&ext_id_face) + .bind(&ext_id_trace) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default(); + + let before_snapshot = serde_json::json!({ + "source_trace_id": trace_id, + "target_trace_id": target_trace_id, + "qdrant_points": qdrant_points, + "tkg_nodes": tkg_nodes.iter().map(|(ext_id, label, props)| { + serde_json::json!({ + "external_id": ext_id, + "label": label, + "properties": props, + }) + }).collect::>(), + }); + // Step 1: Update all face points from source trace to target trace let src_filter = serde_json::json!({ "must": [ @@ -1895,10 +1972,6 @@ async fn merge_trace( }; // Step 2: Delete source TKG nodes - let nodes_table = crate::core::db::schema::table_name("tkg_nodes"); - let ext_id_face = format!("face_track_{}", trace_id); - let ext_id_trace = format!("trace_{}", trace_id); - let tkg_result = sqlx::query(&format!( "DELETE FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)", nodes_table @@ -1917,8 +1990,16 @@ async fn merge_trace( } }; - // Step 3: Rebuild TKG for the target trace - // (The TKG rebuild will pick up the merged points automatically) + // Step 3: Save operation snapshot for undo + let op_table = crate::core::db::schema::table_name("trace_operation_history"); + let _ = sqlx::query(&format!( + "INSERT INTO {} (file_uuid, operation, before_snapshot) VALUES ($1, 'merge_trace', $2)", + op_table + )) + .bind(&file_uuid) + .bind(&before_snapshot) + .execute(state.db.pool()) + .await; Json(serde_json::json!({ "success": true, diff --git a/src/bin/fix_chunks.rs b/src/bin/fix_chunks.rs index ba1a852a..b0a3c2f7 100644 --- a/src/bin/fix_chunks.rs +++ b/src/bin/fix_chunks.rs @@ -1,82 +1,42 @@ use anyhow::Result; +use momentry_core::core::chunk::rule1_ingest; use momentry_core::core::config; use momentry_core::core::db::PostgresDb; -use momentry_core::core::processor::asrx::AsrxResult; -use momentry_core::core::processor::face::FaceResult; -use momentry_core::core::processor::ocr::OcrResult; -use momentry_core::core::processor::pose::PoseResult; -use momentry_core::core::processor::yolo::{YoloPythonResult, YoloResult}; -use momentry_core::worker::processor::ProcessorPool; -use serde_json; -use std::fs; #[tokio::main] async fn main() -> Result<()> { - // Initialize tracing tracing_subscriber::fmt::init(); - // Database connection - let db_url = config::DATABASE_URL.clone(); - let db = PostgresDb::new(&db_url).await?; + let db = PostgresDb::new(&config::DATABASE_URL).await?; - let uuid = "9760d0820f0cf9a7"; + // Find files with OCR pre_chunks but missing OCR chunks + let files: Vec<(String, f64)> = sqlx::query_as::<_, (String, f64)>( + r#" + SELECT pc.file_uuid, v.fps + FROM pre_chunks pc + JOIN videos v ON v.file_uuid = pc.file_uuid + WHERE pc.processor_type = 'ocr' + AND NOT EXISTS ( + SELECT 1 FROM chunk c + WHERE c.file_uuid = pc.file_uuid AND c.chunk_type = 'ocr' + ) + GROUP BY pc.file_uuid, v.fps + ORDER BY COUNT(*) DESC + "# + ) + .fetch_all(db.pool()) + .await?; - // Load OCR result - let ocr_json = - fs::read_to_string("/Users/accusys/momentry/output/job_2_ocr_1774475908877.json")?; - let ocr_result: OcrResult = serde_json::from_str(&ocr_json)?; - println!("Loaded OCR result with {} frames", ocr_result.frames.len()); + println!("Found {} files with OCR stuck in pre_chunks", files.len()); - // Load FACE result - let face_json = - fs::read_to_string("/Users/accusys/momentry/output/job_2_face_1774475908878.json")?; - let face_result: FaceResult = serde_json::from_str(&face_json)?; - println!( - "Loaded FACE result with {} frames", - face_result.frames.len() - ); - - // Load POSE result - let pose_json = - fs::read_to_string("/Users/accusys/momentry/output/job_2_pose_1774475908880.json")?; - let pose_result: PoseResult = serde_json::from_str(&pose_json)?; - println!( - "Loaded POSE result with {} frames", - pose_result.frames.len() - ); - - // Load ASRX result - let asrx_json = - fs::read_to_string("/Users/accusys/momentry/output/job_2_asrx_1774475908887.json")?; - let asrx_result: AsrxResult = serde_json::from_str(&asrx_json)?; - println!( - "Loaded ASRX result with {} segments", - asrx_result.segments.len() - ); - - // Load YOLO result - let yolo_json = - fs::read_to_string("/Users/accusys/momentry/output/job_2_yolo_1774475908875.json")?; - let python_result: YoloPythonResult = serde_json::from_str(&yolo_json)?; - let yolo_result = python_result.to_yolo_result(); - println!( - "Loaded YOLO result with {} frames", - yolo_result.frames.len() - ); - - // Store chunks using ProcessorPool's static methods - println!("Storing OCR chunks..."); - ProcessorPool::store_ocr_chunks(&db, uuid, &ocr_result).await?; - println!("Storing FACE chunks..."); - ProcessorPool::store_face_chunks(&db, uuid, &face_result).await?; - println!("Storing POSE chunks..."); - ProcessorPool::store_pose_chunks(&db, uuid, &pose_result).await?; - println!("Storing ASRX chunks..."); - ProcessorPool::store_asrx_chunks(&db, uuid, &asrx_result).await?; - println!("Storing YOLO chunks..."); - ProcessorPool::store_yolo_chunks(&db, uuid, &yolo_result).await?; - - println!("All trace chunks stored successfully!"); + for (file_uuid, fps) in &files { + println!("Processing {} (fps={})...", file_uuid, fps); + match rule1_ingest::execute_rule1(&db, file_uuid, *fps).await { + Ok(count) => println!(" ✅ Created {} chunks", count), + Err(e) => eprintln!(" ❌ Failed: {}", e), + } + } + println!("Done!"); Ok(()) } diff --git a/src/bin/test_bm25_simple.rs b/src/bin/test_bm25_simple.rs index e65a11bc..90fdd04a 100644 --- a/src/bin/test_bm25_simple.rs +++ b/src/bin/test_bm25_simple.rs @@ -36,7 +36,7 @@ async fn main() -> Result<()> { Err(e) => println!(" TSQUERY 錯誤: {}", e), } - let results = pg.search_bm25(query_str, uuid_opt, 5).await?; + let results = pg.search_bm25(query_str, uuid_opt, None, 5).await?; println!("找到 {} 筆結果:", results.len()); for (i, r) in results.iter().enumerate() { diff --git a/src/bin/test_simplified_chinese.rs b/src/bin/test_simplified_chinese.rs index 09831029..4b999b9c 100644 --- a/src/bin/test_simplified_chinese.rs +++ b/src/bin/test_simplified_chinese.rs @@ -26,7 +26,7 @@ async fn main() -> Result<()> { } // 執行搜索 - let results = pg.search_bm25(query_str, None, 5).await?; + let results = pg.search_bm25(query_str, None, None, 5).await?; println!(" 找到 {} 筆結果", results.len()); for (i, r) in results.iter().enumerate() { println!(" {}. [{}] {}", i + 1, r.uuid, r.text); diff --git a/src/bin/test_synonym_expansion.rs b/src/bin/test_synonym_expansion.rs index 54bc033e..2bbeceb1 100644 --- a/src/bin/test_synonym_expansion.rs +++ b/src/bin/test_synonym_expansion.rs @@ -45,7 +45,7 @@ async fn main() -> Result<()> { } // 執行搜索(即使沒有結果) - let results = pg.search_bm25(query_str, None, 2).await?; + let results = pg.search_bm25(query_str, None, None, 2).await?; println!(" 找到 {} 筆結果", results.len()); for (i, r) in results.iter().enumerate() { println!(" {}. [{}] {}", i + 1, r.uuid, r.text); diff --git a/src/core/chunk/rule1_ingest.rs b/src/core/chunk/rule1_ingest.rs index 0cb1d723..5a38ec8e 100644 --- a/src/core/chunk/rule1_ingest.rs +++ b/src/core/chunk/rule1_ingest.rs @@ -242,16 +242,19 @@ async fn fetch_ocr_texts( .map(|arr| { arr.iter() .filter_map(|item| { - let text = item.get("text").and_then(|t| t.as_str())?; - let confidence = item - .get("confidence") - .and_then(|c| c.as_f64()) - .unwrap_or(0.0); - if confidence > OCR_CONFIDENCE_THRESHOLD { - Some(text.to_string()) - } else { - None + // Format A: array of objects with text/confidence fields + if let Some(obj_text) = item.get("text").and_then(|t| t.as_str()) { + let confidence = item + .get("confidence") + .and_then(|c| c.as_f64()) + .unwrap_or(0.0); + if confidence > OCR_CONFIDENCE_THRESHOLD { + return Some(obj_text.to_string()); + } + return None; } + // Format B: array of plain strings + item.as_str().map(|s| s.to_string()) }) .collect() }) diff --git a/src/core/db/postgres_db.rs b/src/core/db/postgres_db.rs index e56c62ed..5aa9c391 100644 --- a/src/core/db/postgres_db.rs +++ b/src/core/db/postgres_db.rs @@ -1174,6 +1174,12 @@ impl PostgresDb { sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_identity_history_identity_time ON {}(identity_id, created_at DESC)", history_table)).execute(pool).await?; sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_identity_history_not_undone ON {}(identity_id, created_at DESC) WHERE NOT is_undone", history_table)).execute(pool).await?; + // ── Trace Operation History (face group/trace undo) ── + let op_table = schema::table_name("trace_operation_history"); + sqlx::query(&format!("CREATE TABLE IF NOT EXISTS {} (id BIGSERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, operation VARCHAR(30) NOT NULL, before_snapshot JSONB NOT NULL, after_snapshot JSONB, is_undone BOOLEAN DEFAULT FALSE, undone_at TIMESTAMPTZ, user_id VARCHAR(100), created_at TIMESTAMPTZ DEFAULT NOW())", op_table)).execute(pool).await?; + sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_trace_op_history_file_time ON {}(file_uuid, created_at DESC)", op_table)).execute(pool).await?; + sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_trace_op_history_not_undone ON {}(file_uuid, created_at DESC) WHERE NOT is_undone", op_table)).execute(pool).await?; + // ── File Identities (N:N file ↔ identity) ── sqlx::query("CREATE TABLE IF NOT EXISTS file_identities (id SERIAL PRIMARY KEY, file_uuid VARCHAR(255) NOT NULL, identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, confidence DOUBLE PRECISION DEFAULT 1.0, metadata JSONB, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, UNIQUE(file_uuid, identity_id))").execute(pool).await?; sqlx::query( @@ -3099,8 +3105,8 @@ impl PostgresDb { let table = schema::table_name("processor_results"); let ptype = processor_type.as_str(); let id: i32 = sqlx::query_scalar(&format!( - "INSERT INTO {} (job_id, processor_type, processor, uuid, status) \ - VALUES ($1, $2, $2, $3, $4) \ +"INSERT INTO {} (job_id, processor_type, processor, file_uuid, uuid, status) \ + VALUES ($1, $2, $2, $3, $3, $4) \ ON CONFLICT (job_id, processor_type) DO UPDATE SET status = EXCLUDED.status, updated_at = CURRENT_TIMESTAMP \ RETURNING id", table )) @@ -3433,8 +3439,16 @@ impl PostgresDb { ) -> Result { let table = schema::table_name("processor_results"); let s = format!("{:?}", status).to_lowercase(); + // Only reset results that have been stuck in 'running' for a while. + // Freshly-started / actively-running results (updated_at within the window) + // are NOT flipped back to 'pending' — this prevents the worker from + // re-queuing work that is actually in flight (e.g. an untracked + // store_traced_faces.py subprocess), which previously caused an + // unbounded re-spawn / OOM spiral. let r = sqlx::query(&format!( - "UPDATE {} SET status = 'pending', error_message = $1 WHERE status = $2", + "UPDATE {} SET status = 'pending', error_message = $1 \ + WHERE status = $2 \ + AND updated_at < NOW() - INTERVAL '10 minutes'", table )) .bind(reason) @@ -3486,41 +3500,45 @@ impl PostgresDb { &self, query: &str, file_uuid: Option<&str>, + chunk_type: Option<&str>, limit: i64, ) -> Result> { let table = schema::table_name("chunk"); let like = format!("%{}%", query.replace('%', "%%")); use sqlx::Row; - // Simple LIKE-based matching (no FTS stemming) + // Build WHERE clauses dynamically to handle optional params + let mut clauses = vec!["text_content ILIKE $2".to_string(), "text_content != ''".to_string()]; + let mut next_idx = 3; + if file_uuid.is_some() { + next_idx += 1; + clauses.push(format!("file_uuid = ${}", next_idx)); + } + if chunk_type.is_some() { + next_idx += 1; + clauses.push(format!("chunk_type = ${}", next_idx)); + } + + let where_sql = clauses.join(" AND "); + let sql = format!( "SELECT chunk_id, file_uuid, chunk_type, text_content, start_time, end_time, \ (1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8))::float8 as score \ FROM {} \ - WHERE text_content ILIKE $2 AND text_content != '' \ - {}\ + WHERE {} \ ORDER BY score DESC \ LIMIT $3", - table, - if file_uuid.is_some() { "AND file_uuid = $4 " } else { "" } + table, where_sql ); - let rows = if let Some(u) = file_uuid { - sqlx::query(&sql) - .bind(query) - .bind(&like) - .bind(limit) - .bind(u) - .fetch_all(&self.pool) - .await? - } else { - sqlx::query(&sql) - .bind(query) - .bind(&like) - .bind(limit) - .fetch_all(&self.pool) - .await? - }; + let mut q = sqlx::query(&sql).bind(query).bind(&like).bind(limit); + if let Some(u) = file_uuid { + q = q.bind(u); + } + if let Some(ct) = chunk_type { + q = q.bind(ct); + } + let rows = q.fetch_all(&self.pool).await?; Ok(rows .into_iter() @@ -3548,7 +3566,7 @@ impl PostgresDb { _vector_weight: f32, _bm25_weight: f32, ) -> Result> { - self.search_bm25(query, uuid, limit as i64).await + self.search_bm25(query, uuid, None, limit as i64).await } pub async fn list_identities( diff --git a/src/core/db/qdrant_db.rs b/src/core/db/qdrant_db.rs index ae20b9e3..5cc83284 100644 --- a/src/core/db/qdrant_db.rs +++ b/src/core/db/qdrant_db.rs @@ -913,6 +913,56 @@ impl QdrantDb { Ok(all_points) } + /// Scroll ALL points with vectors, for reading face embeddings + pub async fn scroll_all_points_with_vectors( + &self, + collection: &str, + filter: serde_json::Value, + page_size: usize, + ) -> Result> { + let mut all_points = Vec::new(); + let mut offset: Option = None; + loop { + let url = format!("{}/collections/{}/points/scroll", self.base_url, collection); + let mut body = serde_json::json!({ + "filter": filter, + "limit": page_size, + "with_payload": true, + "with_vector": true, + }); + if let Some(ref off) = offset { + body["offset"] = off.clone(); + } + let resp = self + .client + .post(&url) + .header("api-key", &self.api_key) + .header("Content-Type", "application/json") + .json(&body) + .send() + .await?; + if !resp.status().is_success() { + anyhow::bail!("Qdrant scroll failed: {}", resp.status()); + } + let result: serde_json::Value = resp.json().await?; + let points = result["result"]["points"] + .as_array() + .cloned() + .unwrap_or_default(); + let batch_len = points.len(); + all_points.extend(points); + if batch_len < page_size { + break; + } + let next_offset = result["result"]["next_page_offset"].clone(); + if next_offset.is_null() { + break; + } + offset = Some(next_offset); + } + Ok(all_points) + } + pub async fn count_points(&self, collection: &str, filter: serde_json::Value) -> Result { let url = format!("{}/collections/{}/points/count", self.base_url, collection); diff --git a/src/core/processor/face_clustering.rs b/src/core/processor/face_clustering.rs index 7bddb892..154ad92b 100644 --- a/src/core/processor/face_clustering.rs +++ b/src/core/processor/face_clustering.rs @@ -46,6 +46,7 @@ pub struct FaceClusterFrame { pub struct ClusteredFace { pub face_id: String, pub cluster_id: String, + pub trace_id: Option, pub confidence: f32, } diff --git a/src/core/processor/ocr.rs b/src/core/processor/ocr.rs index 7bad79aa..25bb0ccf 100644 --- a/src/core/processor/ocr.rs +++ b/src/core/processor/ocr.rs @@ -1,11 +1,20 @@ use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; +use std::collections::HashSet; use std::time::Duration; use super::executor::PythonExecutor; const OCR_TIMEOUT: Duration = Duration::from_secs(7200); +/// Y-axis zone thresholds (relative to frame height) +const UI_Y_THRESHOLD: f64 = 0.15; +const SUBTITLE_Y_THRESHOLD: f64 = 0.70; +/// Maximum distance (pixels) for bbox-based grouping within Scene zone +const BBOX_MAX_DISTANCE: f64 = 300.0; +/// Jaccard similarity threshold for frame-to-frame text change detection +const TEXT_SIMILARITY_THRESHOLD: f64 = 0.5; + #[derive(Debug, Serialize, Deserialize, Clone)] pub struct OcrResult { pub frame_count: u64, @@ -30,6 +39,198 @@ pub struct OcrText { pub confidence: f32, } +/// Text zone classification based on Y-axis position +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TextZone { + UI, // Top 15% (titles, UI elements) + Scene, // Middle 55% (scene text, signs, labels) + Subtitle, // Bottom 30% (subtitles, captions) +} + +impl TextZone { + pub fn from_y(y_center: f64, frame_height: f64) -> Self { + let ratio = y_center / frame_height; + if ratio < UI_Y_THRESHOLD { + TextZone::UI + } else if ratio >= SUBTITLE_Y_THRESHOLD { + TextZone::Subtitle + } else { + TextZone::Scene + } + } + + pub fn as_str(&self) -> &'static str { + match self { + TextZone::UI => "ui", + TextZone::Scene => "scene", + TextZone::Subtitle => "subtitle", + } + } +} + +/// Grouped OCR texts with metadata +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct OcrGroup { + pub texts: Vec, + pub zone: TextZone, + pub start_frame: i64, + pub end_frame: i64, + pub start_timestamp: f64, + pub end_timestamp: f64, +} + +/// Group OCR texts by zone and proximity +pub fn group_ocr_texts_by_zone_and_proximity( + frames: &[OcrFrame], + frame_height: f64, +) -> Vec { + if frames.is_empty() { + return vec![]; + } + + let mut groups: Vec = Vec::new(); + let mut current_zone_texts: Vec<(TextZone, Vec)> = Vec::new(); + let mut last_texts: HashSet = HashSet::new(); + let mut start_frame = frames[0].frame as i64; + let mut start_timestamp = frames[0].timestamp; + + for frame in frames { + // Rule 2: Frame difference detection + let current_texts: HashSet = + frame.texts.iter().map(|t| t.text.clone()).collect(); + let similarity = jaccard_similarity(&last_texts, ¤t_texts); + + if !last_texts.is_empty() && similarity < TEXT_SIMILARITY_THRESHOLD { + // Text changed significantly, finalize current groups + for (zone, texts) in std::mem::take(&mut current_zone_texts) { + if !texts.is_empty() { + groups.push(OcrGroup { + texts, + zone, + start_frame, + end_frame: (frame.frame as i64).saturating_sub(1), + start_timestamp, + end_timestamp: frame.timestamp, + }); + } + } + start_frame = frame.frame as i64; + start_timestamp = frame.timestamp; + } + + // Rule 1: Y-axis zone classification + let mut zone_map: std::collections::HashMap> = + std::collections::HashMap::new(); + + for text in &frame.texts { + let y_center = text.y as f64 + text.height as f64 / 2.0; + let zone = TextZone::from_y(y_center, frame_height); + zone_map.entry(zone).or_default().push(text.text.clone()); + } + + // Rule 3: Bbox distance grouping for Scene zone + let scene_texts = zone_map.remove(&TextZone::Scene).unwrap_or_default(); + let scene_groups = group_by_bbox_distance(&frame.texts, &scene_texts, BBOX_MAX_DISTANCE); + + // Add UI and Subtitle texts (already grouped by zone) + for (zone, texts) in zone_map { + current_zone_texts.push((zone, texts)); + } + + // Add scene groups + for texts in scene_groups { + current_zone_texts.push((TextZone::Scene, texts)); + } + + last_texts = current_texts; + } + + // Finalize remaining groups + for (zone, texts) in current_zone_texts { + if !texts.is_empty() { + let last_frame = frames.last().unwrap(); + groups.push(OcrGroup { + texts, + zone, + start_frame, + end_frame: last_frame.frame as i64, + start_timestamp, + end_timestamp: last_frame.timestamp, + }); + } + } + + groups +} + +/// Calculate Jaccard similarity between two text sets +fn jaccard_similarity(set1: &HashSet, set2: &HashSet) -> f64 { + if set1.is_empty() && set2.is_empty() { + return 1.0; + } + let intersection = set1.intersection(set2).count(); + let union = set1.union(set2).count(); + if union == 0 { + 1.0 + } else { + intersection as f64 / union as f64 + } +} + +/// Group scene texts by bbox proximity +fn group_by_bbox_distance( + all_texts: &[OcrText], + scene_texts: &[String], + max_distance: f64, +) -> Vec> { + if scene_texts.is_empty() { + return vec![]; + } + + // Find bbox centers for scene texts + let scene_bboxes: Vec<(f64, f64, &str)> = all_texts + .iter() + .filter(|t| scene_texts.contains(&t.text)) + .map(|t| { + let x_center = t.x as f64 + t.width as f64 / 2.0; + let y_center = t.y as f64 + t.height as f64 / 2.0; + (x_center, y_center, t.text.as_str()) + }) + .collect(); + + // Simple clustering by distance + let mut groups: Vec> = Vec::new(); + let mut assigned = vec![false; scene_bboxes.len()]; + + for i in 0..scene_bboxes.len() { + if assigned[i] { + continue; + } + + let mut group = vec![scene_bboxes[i].2.to_string()]; + assigned[i] = true; + + for j in (i + 1)..scene_bboxes.len() { + if assigned[j] { + continue; + } + + let dist = ((scene_bboxes[i].0 - scene_bboxes[j].0).powi(2) + + (scene_bboxes[i].1 - scene_bboxes[j].1).powi(2)) + .sqrt(); + + if dist < max_distance { + group.push(scene_bboxes[j].2.to_string()); + assigned[j] = true; + } + } + + groups.push(group); + } + + groups +} + pub async fn process_ocr( video_path: &str, output_path: &str, diff --git a/src/core/processor/tkg.rs b/src/core/processor/tkg.rs index c3f9995c..19a66f74 100644 --- a/src/core/processor/tkg.rs +++ b/src/core/processor/tkg.rs @@ -32,7 +32,7 @@ async fn scroll_face_points(file_uuid: &str) -> Vec { let filter = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, - {"key": "trace_id", "range": {"gte": 1}} + {"key": "trace_id", "range": {"gte": 0}} ] }); @@ -1334,11 +1334,22 @@ async fn build_face_track_nodes_from_qdrant( }); // Save all three files to output/{file_uuid}/{trace_id}/ - let _ = trace_profile.save( + let mut key_frame_file = agg.best_frame.to_string(); + let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string(); + + match trace_profile.save( output_dir, key_frame_jpeg.as_deref(), key_face_jpeg.as_deref(), - ); + ) { + Ok(_) => { + key_frame_file = "key_frame.jpg".to_string(); + key_face_file = "key_face.jpg".to_string(); + } + Err(e) => { + tracing::error!("[TKG] Failed to save trace_profile for trace {}: {}", tid, e); + } + } // Update props with actual file paths (for DB properties JSONB) let final_props = serde_json::json!({ @@ -1346,8 +1357,8 @@ async fn build_face_track_nodes_from_qdrant( "frame_count": agg.frame_count, "start_frame": agg.start_f, "end_frame": agg.end_f, - "key_frame": agg.best_frame, - "key_face": agg.best_point_id.as_deref().unwrap_or(""), + "key_frame": key_frame_file, + "key_face": key_face_file, "avg_bbox": props["avg_bbox"].clone(), "avg_yaw": props["avg_yaw"].clone(), "avg_pitch": props["avg_pitch"].clone(), @@ -1388,6 +1399,7 @@ async fn build_face_track_nodes_from_qdrant( count += 1; } + tracing::info!("[TKG-face_track] built {} face_track nodes for {}", count, file_uuid); Ok(count) } diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index 6ff74f18..943f7954 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -2,10 +2,24 @@ use anyhow::{Context, Result}; use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; +use std::sync::LazyLock; use std::time::Duration; +use tokio::sync::Semaphore; use tokio::time::sleep; use tracing::{debug, error, info, warn}; +/// Bounds the number of concurrent heavy face-I/O Python tasks (store_traced_faces.py / +/// TKG build). These spawns bypass ProcessorPool (raw tokio::spawn) and each loads the +/// full face.json into numpy + scrolls all Qdrant face points, which previously caused +/// unbounded pile-up and OOM. Capacity mirrors FRAME_SLOT_MAX in processor.rs. +static FACE_IO_SEM: LazyLock = LazyLock::new(|| Semaphore::new(2)); + +/// Tracks uuids with an in-flight untracked face-trace/TKG Python spawn, to prevent the +/// same file from being spawned multiple times in a row (race between poll cycles) when +/// face_traced.json is not yet written. Guards against the duplicate-spawn loop. +static FACE_TRACE_INFLIGHT: LazyLock>> = + LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new())); + use crate::core::chunk::rule1_ingest; use crate::core::config::OUTPUT_DIR; use crate::core::db::qdrant_db::QdrantDb; @@ -101,6 +115,17 @@ impl JobWorker { } async fn poll_and_process(&self) -> Result<()> { + // Memory usage monitoring (every 100 polls) + static POLL_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let count = POLL_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if count % 100 == 0 { + if let Ok(mem_mb) = get_rss_mb() { + if mem_mb > 1024 { + warn!("⚠️ High memory usage: {} MB", mem_mb); + } + } + } + // 檢查系統資源並寫入 Redis let resources = SystemResources::check(); let dynamic_max = resources.safe_max_concurrent(self.config.max_concurrent); @@ -1137,7 +1162,7 @@ impl JobWorker { "language_probability": 0.0 }); let asr_path = format!( - "{}{}.asr.json", + "{}/{}.asr.json", crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), job.uuid ); @@ -1183,10 +1208,8 @@ impl JobWorker { // Special handling for ASRX: if ASR output exists with no_audio_track/silent_audio, skip processing if *processor_type == crate::core::db::ProcessorType::Asrx { let asr_output_path = format!( - "{}{}.asr.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), + "{}/{}.asr.json", + crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), job.uuid ); if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) { @@ -1195,6 +1218,23 @@ impl JobWorker { if let Some(status) = asr_status { if status == "no_audio_track" || status == "silent_audio" { info!("ASRX: ASR status={}, skipping ASRX processing", status); + + // Write asrx.json output file (so sync-status sees it) + let asrx_output_path = format!( + "{}/{}.asrx.json", + crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + job.uuid + ); + let asrx_result = serde_json::json!({ + "status": status, + "language": asr_data.get("language").and_then(|l| l.as_str()), + "segments": [], + "segment_count": 0 + }); + if let Err(e) = std::fs::write(&asrx_output_path, serde_json::to_string_pretty(&asrx_result).unwrap_or_default()) { + warn!("Failed to write ASRX output file: {}", e); + } + // Create completed result with same status if let Err(e) = self .db @@ -1439,6 +1479,21 @@ impl JobWorker { Ok(()) } + /// 統一 TKG 完成檢查 — P4 trigger 和 ingestion gate 共用。 + /// Face TKG:必須有 face_track_nodes > 0(代表 face tracking 已寫入 TKG)。 + /// No-face TKG 由 caller 自行短路(has_face=false 或 status=no_faces 時不需檢查)。 + async fn is_tkg_done(pool: &PgPool, uuid: &str) -> bool { + let nodes_table = crate::core::db::schema::table_name("tkg_nodes"); + let count: i64 = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {nodes_table} WHERE file_uuid = $1 AND node_type = 'face_track'" + )) + .bind(uuid) + .fetch_one(pool) + .await + .unwrap_or(0); + count > 0 + } + /// 檢查所有入庫步驟是否已完成(與 ingestion-status endpoint 同步邏輯) async fn ingestion_complete(pool: &PgPool, uuid: &str, job_processors: &[String]) -> bool { let chunk_t = schema::table_name("chunk"); @@ -1467,7 +1522,7 @@ impl JobWorker { .await .unwrap_or(None); - match asr_status.as_deref() { + let status_from_db = match asr_status.as_deref() { Some("no_audio_track") | Some("silent_audio") => true, Some("has_transcript") => { sqlx::query_scalar::<_, i32>(&format!( @@ -1480,6 +1535,32 @@ impl JobWorker { .unwrap_or(0) > 0 } _ => false, + }; + if status_from_db { + true + } else { + // Fallback: check asr.json file directly + let asr_path = format!( + "{}/{}.asr.json", + crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + uuid + ); + if let Ok(content) = std::fs::read_to_string(&asr_path) { + if let Ok(data) = serde_json::from_str::(&content) { + match data.get("status").and_then(|s| s.as_str()) { + Some("no_audio_track") | Some("silent_audio") => true, + Some("has_transcript") => { + data.get("segments").and_then(|s| s.as_array()) + .map(|a| !a.is_empty()).unwrap_or(false) + } + _ => false, + } + } else { + false + } + } else { + false + } } } else { true @@ -1535,31 +1616,27 @@ impl JobWorker { true }; - // 3. TKG: tkg_nodes 有資料(有 face 時才需要 TKG) - let tkg_done: bool = if has_face { - if trace_status == "no_faces" { - // 無臉不需要 TKG - true - } else { - let node_count: i32 = sqlx::query_scalar(&format!( - "SELECT COUNT(*) FROM {tkg_nodes_t} WHERE file_uuid = $1" - )) - .bind(uuid) - .fetch_one(pool) - .await - .unwrap_or(0); - - // TKG 完成 = nodes > 0(必須真正有 TKG 資料) - node_count > 0 - } + // 3. TKG: face_track_nodes 有資料(Face TKG 必須有 face tracking 寫入) + let tkg_done: bool = if has_face && trace_status != "no_faces" { + Self::is_tkg_done(pool, uuid).await } else { - // 無 face 不需要 TKG true }; // 4. Face Cluster: face_cluster.json 存在(有 face 時才需要) let face_cluster_done: bool = if has_face { if trace_status == "no_faces" { + // 直接寫入空的 face_cluster.json 讓 sync-status 能正確判斷 + let cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid); + if !std::path::Path::new(&cluster_path).exists() { + let empty_output = serde_json::json!({ + "status": "no_faces", + "file_uuid": uuid, + "clusters": [], + "frames": [] + }); + let _ = std::fs::write(&cluster_path, serde_json::to_string_pretty(&empty_output).unwrap_or_default()); + } true } else { let cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid); @@ -1607,7 +1684,7 @@ impl JobWorker { true }; - let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && rule3_done && scene_meta_done && qdrant_face_done; + let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && qdrant_face_done; tracing::info!( "[Ingestion] all_ok={} (asr={}, trace={}, tkg={}, face_cluster={}, rule3={}, scene_meta={}, qdrant_face={}) for uuid={}", @@ -1761,10 +1838,8 @@ impl JobWorker { // Special handling for ASRX: check ASR output file if processor_type == crate::core::db::ProcessorType::Asrx { let asr_output_path = format!( - "{}{}.asr.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), + "{}/{}.asr.json", + crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), uuid ); if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) { @@ -1776,6 +1851,23 @@ impl JobWorker { "ASRX: ASR status={}, creating completed result directly", status ); + + // Write asrx.json output file (so sync-status sees it) + let asrx_output_path = format!( + "{}/{}.asrx.json", + crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + uuid + ); + let asrx_result = serde_json::json!({ + "status": status, + "language": asr_data.get("language").and_then(|l| l.as_str()), + "segments": [], + "segment_count": 0 + }); + if let Err(e) = std::fs::write(&asrx_output_path, serde_json::to_string_pretty(&asrx_result).unwrap_or_default()) { + warn!("Failed to write ASRX output file: {}", e); + } + if let Err(e) = self .db .upsert_processor_result( @@ -1872,15 +1964,17 @@ impl JobWorker { let has_cut = completed_processors.iter().any(|p| p == "cut"); let has_face = completed_processors.iter().any(|p| p == "face"); let has_yolo = completed_processors.iter().any(|p| p == "yolo"); + let has_ocr = completed_processors.iter().any(|p| p == "ocr"); self.db .update_job_processors_arrays(job_id, completed_processors, failed_processors.clone()) .await?; - if has_asrx { + if has_asrx || has_ocr { // Guard: only spawn Rule 1 if sentence chunks don't exist yet + // or if OCR completed but OCR chunks are missing (OCR came after ASRX) let chunk_t = schema::table_name("chunk"); - let already_spawned: bool = sqlx::query_scalar::<_, i32>(&format!( + let has_sentence: bool = sqlx::query_scalar::<_, i32>(&format!( "SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'sentence' LIMIT 1" )) .bind(uuid) @@ -1889,7 +1983,23 @@ impl JobWorker { .unwrap_or(0) > 0; - if already_spawned { + let has_ocr_chunks: bool = if has_ocr { + sqlx::query_scalar::<_, i32>(&format!( + "SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'ocr' LIMIT 1" + )) + .bind(uuid) + .fetch_optional(self.db.pool()) + .await? + .unwrap_or(0) + > 0 + } else { + true // skip OCR check if OCR hasn't completed yet + }; + + // Run Rule1 if no sentence chunks yet, or if OCR finished but OCR chunks missing + let needs_rule1 = !has_sentence || (has_ocr && !has_ocr_chunks); + + if !needs_rule1 { info!("✅ Rule 1 already completed for {}, skipping spawn", uuid); } else { info!("📝 Prerequisites met for Rule 1 Chunking. Starting ingestion..."); @@ -1968,7 +2078,7 @@ impl JobWorker { // Note: Job status will be updated after Rule 2 (TKG) completion // Do not mark as completed here } - Err(e) => error!("❌ Phase 1 release pack failed: {}", e), + Err(e) => warn!("⚠️ Phase 1 release pack failed (non-fatal): {}", e), } } Err(e) => error!("❌ Rule 1 Ingestion failed: {}", e), @@ -1990,22 +2100,38 @@ impl JobWorker { // Runs face_tracker.py (IoU+embedding tracking), stores trace_id + position in DB if has_face { let traced_path = format!( - "{}{}.face_traced.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), + "{}/{}.face_traced.json", + crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), uuid ); if std::path::Path::new(&traced_path).exists() { info!("✅ Face trace already done for {}, skipping spawn", uuid); } else { - info!("📝 Face completed, triggering face trace + DB store..."); - let db_clone = self.db.clone(); - let redis_clone = self.redis.clone(); - let uuid_clone = uuid.to_string(); - tokio::spawn(async move { - // Mark face_tracing as running - { + // Guard against the same uuid being spawned twice across poll + // cycles (race before face_traced.json is written). + let mut inflight = FACE_TRACE_INFLIGHT.lock().await; + if inflight.contains(uuid) { + info!("⏳ Face trace already in-flight for {}, skipping duplicate spawn", uuid); + } else { + inflight.insert(uuid.to_string()); + drop(inflight); + info!("📝 Face completed, triggering face trace + DB store..."); + let db_clone = self.db.clone(); + let redis_clone = self.redis.clone(); + let uuid_clone = uuid.to_string(); + tokio::spawn(async move { + // Bound concurrent heavy face-I/O Python tasks to avoid OOM + // (these spawns bypass ProcessorPool). Held until block ends. + let _face_io_permit = match FACE_IO_SEM.acquire().await { + Ok(p) => p, + Err(_) => { + error!("❌ Face trace semaphore closed for {}", uuid_clone); + FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone); + return; + } + }; + // Mark face_tracing as running + { let mut pp = PipelineProgress::new(&uuid_clone); pp.update_stage("face_tracing", 0.0, "running", None); publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp).await; @@ -2014,6 +2140,7 @@ impl JobWorker { Ok(ex) => ex, Err(e) => { error!("Failed to create PythonExecutor for face trace: {}", e); + FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone); return; } }; @@ -2100,9 +2227,13 @@ impl JobWorker { error!("❌ Face trace + DB store failed for {}: {}", uuid_clone, e) } } + // Clear in-flight marker so this uuid can be retried later + // if it failed or the worker restarts before completion. + FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone); }); } } + } // 🚀 P2.5 Trigger: TMDb Face Matching (after Face, if TMDb data exists) if has_face && *crate::core::config::tmdb::PROBE_ENABLED { @@ -2240,81 +2371,73 @@ impl JobWorker { // 🚀 P4 Trigger: TKG Build (Face + ASRX) → then Rule2 ingestion if has_face && has_asrx { - let tkg_table = crate::core::db::schema::table_name("tkg_edges"); - let tkg_done: bool = sqlx::query_scalar::<_, i32>(&format!( - "SELECT 1 FROM {tkg_table} WHERE file_uuid = $1 LIMIT 1" - )) - .bind(uuid) - .fetch_optional(self.db.pool()) - .await - .unwrap_or(None) - .unwrap_or(0) - > 0; + // Check face.json status first to determine TKG type + let face_json_path = format!( + "{}/{}.face.json", + crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + uuid + ); - if tkg_done { - info!("✅ TKG already built for {}, skipping spawn", uuid); - } else { - // Check face.json status first - let face_json_path = format!( - "{}{}.face.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), - uuid - ); - - let has_faces = if std::path::Path::new(&face_json_path).exists() { - if let Ok(content) = std::fs::read_to_string(&face_json_path) { - if let Ok(face_data) = - serde_json::from_str::(&content) - { - face_data - .get("status") - .and_then(|s| s.as_str()) - .map(|s| s == "has_faces") - .unwrap_or(false) - } else { - false - } + let has_faces = if std::path::Path::new(&face_json_path).exists() { + if let Ok(content) = std::fs::read_to_string(&face_json_path) { + if let Ok(face_data) = + serde_json::from_str::(&content) + { + face_data + .get("status") + .and_then(|s| s.as_str()) + .map(|s| s == "has_faces") + .unwrap_or(false) } else { false } } else { false - }; + } + } else { + false + }; - if has_faces { - // Has faces - wait for face_traced.json - let traced_path = format!( - "{}{}.face_traced.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), - uuid + // Face TKG: must have face_track_nodes > 0 + // No-face TKG: not needed + let tkg_done: bool = if has_faces { + Self::is_tkg_done(self.db.pool(), uuid).await + } else { + true + }; + + if tkg_done { + info!("✅ TKG already built for {}, skipping spawn", uuid); + } else if has_faces { + // Has faces - wait for face_traced.json + let traced_path = format!( + "{}/{}.face_traced.json", + crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + uuid + ); + + if !std::path::Path::new(&traced_path).exists() { + info!( + "⏳ TKG build waiting for face_traced.json: {} (file_uuid={})", + traced_path, uuid ); - - if !std::path::Path::new(&traced_path).exists() { - info!( - "⏳ TKG build waiting for face_traced.json: {} (file_uuid={})", - traced_path, uuid - ); - } else { - // Verify Qdrant has face points before TKG build - let expected_faces = - if let Ok(content) = std::fs::read_to_string(&face_json_path) { - if let Ok(face_data) = - serde_json::from_str::(&content) - { - face_data - .get("total_faces") - .and_then(|t| t.as_i64()) - .unwrap_or(0) - } else { - 0 - } + } else { + // Verify Qdrant has face points before TKG build + let expected_faces = + if let Ok(content) = std::fs::read_to_string(&face_json_path) { + if let Ok(face_data) = + serde_json::from_str::(&content) + { + face_data + .get("total_faces") + .and_then(|t| t.as_i64()) + .unwrap_or(0) } else { 0 - }; + } + } else { + 0 + }; // Wait for Qdrant to have all face points (up to 30 seconds) let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); @@ -2360,6 +2483,15 @@ impl JobWorker { let uuid_clone = uuid.to_string(); let output_dir_clone = crate::core::config::OUTPUT_DIR.clone(); tokio::spawn(async move { + // Bound concurrent heavy face-I/O Python tasks to avoid OOM + // (build_tkg may internally spawn store_traced_faces.py). + let _face_io_permit = match FACE_IO_SEM.acquire().await { + Ok(p) => p, + Err(_) => { + error!("❌ TKG build semaphore closed for {}", uuid_clone); + return; + } + }; // Mark tkg_nodes + tkg_edges as running { let mut pp = PipelineProgress::new(&uuid_clone); @@ -2474,6 +2606,15 @@ impl JobWorker { let uuid_clone = uuid.to_string(); let output_dir_clone = crate::core::config::OUTPUT_DIR.clone(); tokio::spawn(async move { + // Bound concurrent heavy face-I/O Python tasks to avoid OOM + // (build_tkg may internally spawn store_traced_faces.py). + let _face_io_permit = match FACE_IO_SEM.acquire().await { + Ok(p) => p, + Err(_) => { + error!("❌ TKG build (no-faces) semaphore closed for {}", uuid_clone); + return; + } + }; // Mark tkg_nodes + tkg_edges as running (no-faces path) { let mut pp = PipelineProgress::new(&uuid_clone); @@ -2537,7 +2678,6 @@ impl JobWorker { } }); } - } } if !Self::ingestion_complete(self.db.pool(), uuid, job_processors).await { @@ -2812,44 +2952,43 @@ impl JobWorker { ) -> Result<()> { use std::collections::HashMap; - let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); - let scroll_filter = serde_json::json!({ - "must": [ - {"key": "file_uuid", "match": {"value": uuid}} - ] - }); - - let all_faces = qdrant - .scroll_all_points("_faces", scroll_filter, 1000) - .await - .context("Failed to scroll _faces from Qdrant")?; - - let mut frame_to_traces: HashMap> = HashMap::new(); - for point in &all_faces { - let payload = &point["payload"]; - if let (Some(frame), Some(trace_id)) = - (payload["frame"].as_u64(), payload["trace_id"].as_i64()) - { - if trace_id > 0 { - frame_to_traces.entry(frame).or_default().push(trace_id); + // Build index: (frame, face_index) → real trace_id from face_traced.json + // face_cluster.json's trace_id is cluster-internal (always 0), so we match + // by frame number + array index to get the actual traced trace_id. + let traced_path = format!("{}/{}.face_traced.json", crate::core::config::OUTPUT_DIR.as_str(), uuid); + let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new(); + if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced_data) = serde_json::from_str::(&content) { + if let Some(frames) = traced_data.get("frames").and_then(|v| v.as_object()) { + for (fnum_str, frame_data) in frames { + if let (Ok(fnum), Some(faces)) = ( + fnum_str.parse::(), + frame_data.get("faces").and_then(|v| v.as_array()), + ) { + for (idx, face) in faces.iter().enumerate() { + if let Some(tid) = face.get("trace_id").and_then(|v| v.as_i64()) { + frame_face_to_trace.insert((fnum, idx), tid); + } + } + } + } } } } let mut trace_to_cluster: HashMap = HashMap::new(); for frame_data in &result.frames { - let frame = frame_data.frame; - if let Some(trace_ids) = frame_to_traces.get(&frame) { - for (idx, face) in frame_data.faces.iter().enumerate() { - if idx < trace_ids.len() { - trace_to_cluster.insert(trace_ids[idx], face.cluster_id.clone()); - } + for (idx, face) in frame_data.faces.iter().enumerate() { + if let Some(&tid) = frame_face_to_trace.get(&(frame_data.frame, idx)) { + trace_to_cluster.insert(tid, face.cluster_id.clone()); } } } let tkg_table = crate::core::db::schema::table_name("tkg_nodes"); let tp_table = crate::core::db::schema::table_name("trace_profiles"); + + // Update traces that ARE in clusters for (trace_id, cluster_id) in &trace_to_cluster { let external_id = format!("trace_{}", trace_id); let label = cluster_id.clone(); @@ -2892,6 +3031,46 @@ impl JobWorker { .await; } + // Also update traces that are NOT in any cluster (keep default Person_N name) + if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced_data) = serde_json::from_str::(&content) { + if let Some(traces) = traced_data.get("traces") { + let trace_list = if traces.is_object() { + traces.as_object().map(|o| o.keys().filter_map(|k| k.parse::().ok()).collect::>()) + } else if traces.is_array() { + traces.as_array().map(|a| a.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect()) + } else { + None + }; + + if let Some(all_trace_ids) = trace_list { + let mut updated_count = 0u64; + for tid in &all_trace_ids { + if !trace_to_cluster.contains_key(tid) { + let name = format!("Person_{}", tid); + let _ = sqlx::query(&format!( + "UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3", + tp_table + )) + .bind(&name) + .bind(uuid) + .bind(tid) + .execute(db.pool()) + .await; + updated_count += 1; + } + } + if updated_count > 0 { + info!( + "[FaceCluster] Updated {} unclustered trace names for {}", + updated_count, uuid + ); + } + } + } + } + } + info!( "[FaceCluster] Updated {} trace labels for {}", trace_to_cluster.len(), @@ -2902,6 +3081,19 @@ impl JobWorker { } } +/// Get current process RSS in MB +fn get_rss_mb() -> std::io::Result { + let output = std::process::Command::new("ps") + .args(["-o", "rss=", "-p", &std::process::id().to_string()]) + .output()?; + let rss_kb = String::from_utf8(output.stdout) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))? + .trim() + .parse::() + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; + Ok(rss_kb / 1024) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/worker/processor.rs b/src/worker/processor.rs index 302d9059..65f17b99 100644 --- a/src/worker/processor.rs +++ b/src/worker/processor.rs @@ -1312,18 +1312,49 @@ impl ProcessorPool { uuid: &str, ocr_result: &OcrResult, ) -> Result<()> { - let frames_count = ocr_result.frames.len(); - tracing::info!("Storing {} OCR pre-chunks for video {}", frames_count, uuid); + use crate::core::processor::ocr::{group_ocr_texts_by_zone_and_proximity, OcrGroup}; + + // Get frame height from videos table for Y-axis zone classification + let videos_table = crate::core::db::schema::table_name("videos"); + let frame_height: Option = sqlx::query_scalar(&format!( + "SELECT height FROM {} WHERE file_uuid = $1", + videos_table + )) + .bind(uuid) + .fetch_optional(db.pool()) + .await? + .flatten(); + + let height = frame_height.unwrap_or(720) as f64; // Default fallback + + // Group OCR texts by zone and proximity + let groups: Vec = group_ocr_texts_by_zone_and_proximity(&ocr_result.frames, height); + + tracing::info!( + "Storing {} OCR groups (from {} frames) for video {}", + groups.len(), + ocr_result.frames.len(), + uuid + ); let mut pre_chunks_to_store = Vec::new(); - for frame in ocr_result.frames.iter() { + for group in &groups { let data = serde_json::json!({ - "texts": frame.texts, - "timestamp": frame.timestamp, + "texts": group.texts, + "zone": group.zone.as_str(), + "start_frame": group.start_frame, + "end_frame": group.end_frame, + "timestamp": group.start_timestamp, }); - pre_chunks_to_store.push((frame.frame as i64, Some(frame.timestamp), data, None, None)); + pre_chunks_to_store.push(( + group.start_frame, + Some(group.start_timestamp), + data, + None, + None, + )); } db.store_raw_pre_chunks_batch(uuid, "ocr", &pre_chunks_to_store)