use axum::{ extract::{Path, Query, State}, http::StatusCode, Extension, Json, }; use serde::{Deserialize, Serialize}; use sqlx::PgPool; use std::collections::HashMap; use crate::api::middleware::UserAuth; use crate::api::types::AppState; use crate::core::db::schema; use crate::core::file_profile::FaceFilterSettings; 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: i32, } #[derive(Debug, Serialize, Deserialize)] pub struct TraceProfile { pub file_uuid: String, pub trace_id: i32, pub name: String, pub key_frame: Option, pub key_face: Option, pub aliases: Option, pub bbox: Option, pub properties: serde_json::Value, } #[derive(Deserialize)] pub struct UpdateTraceProfileRequest { pub file_uuid: String, pub trace_id: i32, pub name: Option, pub key_frame: Option, pub key_face: Option, pub aliases: Option, pub properties: Option, } #[derive(Deserialize)] pub struct UpdateTraceProfileGroupRequest { pub file_uuid: String, pub trace_ids: Vec, pub name: String, } #[derive(Debug, Deserialize)] pub struct MergeGroupsRequest { pub file_uuid: String, pub source_groups: Vec, pub target_group_name: String, } #[derive(Debug, Serialize)] pub struct MergeGroupsResponse { pub success: bool, pub file_uuid: String, pub source_groups: Vec, pub target_group_name: String, pub traces_merged: u64, 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, Option, Option, )> = 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) .bind(&external_id_trace) .fetch_optional(state.db.pool()) .await .map_err(|e| { tracing::error!("[TraceProfile] DB error: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?; // Merge properties: tp_props takes precedence, tn_props as fallback let mut properties = tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new())); if let Some(tp_obj) = tp_props.as_ref().and_then(|v| v.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()) .map(|s| s.to_string()); let aliases = properties.get("aliases").cloned(); let bbox = properties.get("avg_bbox").cloned(); Ok(Json(TraceProfile { file_uuid: params.file_uuid, trace_id: params.trace_id, name, key_frame, key_face, aliases, bbox, properties, })) } pub async fn update_trace_profile_handler( State(state): State, Extension(_auth): Extension, Json(req): Json, ) -> Result, StatusCode> { let tp_table = schema::table_name("trace_profiles"); // Get current profile let current: Option<(Option, serde_json::Value)> = sqlx::query_as(&format!( "SELECT name, properties FROM {} WHERE file_uuid = $1 AND trace_id = $2", tp_table )) .bind(&req.file_uuid) .bind(req.trace_id) .fetch_optional(state.db.pool()) .await .map_err(|e| { tracing::error!("[TraceProfile] DB error: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; let (current_name, mut current_props) = match current { Some((name, props)) => (name, props), None => (None, serde_json::json!({})), }; // Build updates for trace_profiles let mut tp_updates: Vec = Vec::new(); let mut param_idx = 3; if let Some(ref new_name) = req.name { if Some(new_name) != current_name.as_ref() { param_idx += 1; tp_updates.push(format!("name = ${}", param_idx)); } } // Merge properties if let Some(ref new_props) = req.properties { if let Some(obj) = new_props.as_object() { for (k, v) in obj { current_props[k] = v.clone(); } } } if let Some(ref key_frame) = req.key_frame { current_props["key_frame"] = serde_json::json!(key_frame); } if let Some(ref key_face) = req.key_face { current_props["key_face"] = serde_json::json!(key_face); } if let Some(ref aliases) = req.aliases { current_props["aliases"] = aliases.clone(); } if tp_updates.is_empty() && req.properties.is_none() && req.key_frame.is_none() && req.key_face.is_none() && req.aliases.is_none() { return Ok(Json(serde_json::json!({ "success": true, "message": "No changes" }))); } let new_name_val = req.name.as_deref(); let before_name = current_name.clone().unwrap_or_default(); let final_name = new_name_val.unwrap_or(before_name.as_str()); // Self-healing: ensure a tkg_nodes face_track row exists so the trace // can appear in face-groups / cluster-results even if it was previously // lost (e.g. by an old hard-delete). let _ = schema::ensure_face_track_node(state.db.pool(), &req.file_uuid, req.trace_id, final_name) .await; match schema::upsert_trace_profile( state.db.pool(), &req.file_uuid, req.trace_id, final_name, Some(¤t_props), ) .await { Ok(affected) if 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); Err(StatusCode::INTERNAL_SERVER_ERROR) } } } pub async fn update_trace_profile_group_handler( State(state): State, Extension(_auth): Extension, Json(req): Json, ) -> 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; let nodes_table = schema::table_name("tkg_nodes"); for trace_id in &req.trace_ids { // Self-healing: make sure the face_track node exists. let _ = schema::ensure_face_track_node(state.db.pool(), &req.file_uuid, *trace_id, &req.name) .await; match schema::upsert_trace_profile( state.db.pool(), &req.file_uuid, *trace_id, &req.name, None, ) .await { Ok(affected) => updated += affected, Err(e) => { tracing::error!("[TraceProfileGroup] UPSERT error: {}", e); return Err(StatusCode::INTERNAL_SERVER_ERROR); } } // Keep tkg_nodes.label in sync with the profile name. if let Err(e) = sqlx::query(&format!( "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND (external_id = $3 OR (properties->>'trace_id')::int = $4)", nodes_table )) .bind(&req.name) .bind(&req.file_uuid) .bind(format!("trace_{}", trace_id)) .bind(*trace_id) .execute(state.db.pool()) .await { tracing::error!("[TraceProfileGroup] tkg label sync error: {}", e); } } 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), "file_uuid": req.file_uuid, "updated_count": updated }))) } pub async fn merge_groups_handler( State(state): State, Extension(_auth): Extension, Json(req): Json, ) -> Result, (StatusCode, Json)> { let tkg_table = schema::table_name("tkg_nodes"); // Defensively drop the target name from the source list so a merge does // not fail just because the client echoed the target among sources. let source_groups: Vec = req .source_groups .iter() .filter(|g| *g != &req.target_group_name) .cloned() .collect(); if source_groups.is_empty() { return Err(( StatusCode::BAD_REQUEST, Json(serde_json::json!({ "success": false, "error": "source_groups cannot be empty" })), )); } // 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(&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()})), ) })?; // Resolve source trace_ids from trace_profiles.name (the grouping source // of truth). We match by name rather than by tkg_nodes.label to stay // correct even when tkg_nodes.label has drifted out of sync. let matching_trace_ids: Vec = sqlx::query_scalar(&format!( "SELECT trace_id FROM {} WHERE file_uuid = $1 AND name = ANY($2) ORDER BY trace_id", tp_table )) .bind(&req.file_uuid) .bind(&source_groups) .fetch_all(state.db.pool()) .await .map_err(|e| { tracing::error!("[MergeGroups] Failed to collect trace_ids: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })?; // Update tkg_nodes.label for the resolved trace_ids (by external_id, not // by the possibly-stale label) so both tables stay consistent. let nodes_table = schema::table_name("tkg_nodes"); // Build an IN list of external_id values ('trace_{tid}'). When there are // no matches we use IN (NULL) which safely affects zero rows. let in_list = if matching_trace_ids.is_empty() { "NULL".to_string() } else { matching_trace_ids .iter() .map(|tid| format!("'trace_{}'", tid)) .collect::>() .join(", ") }; let nodes_result = sqlx::query(&format!( "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' \ AND external_id IN ({})", nodes_table, in_list )) .bind(&req.target_group_name) .bind(&req.file_uuid) .execute(state.db.pool()) .await; // UPSERT each matching trace profile to the target name let mut updated: u64 = 0; for trace_id in &matching_trace_ids { // Self-healing: ensure the face_track node exists for this trace. let _ = schema::ensure_face_track_node( state.db.pool(), &req.file_uuid, *trace_id, &req.target_group_name, ) .await; match schema::upsert_trace_profile( state.db.pool(), &req.file_uuid, *trace_id, &req.target_group_name, None, ) .await { Ok(affected) => updated += affected, Err(e) => { tracing::error!("[MergeGroups] UPSERT error: {}", e); return Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), )); } } } match nodes_result { Ok(nodes_res) => { let nodes_updated = nodes_res.rows_affected(); let group_count = 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": &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, target_group_name: target_name.clone(), traces_merged: updated, message: format!("Merged {} group(s) into '{}'", group_count, target_name), })) } Err(e) => { tracing::error!("[MergeGroups] DB error: {}", e); Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({ "success": false, "error": e.to_string() })), )) } } } #[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 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 (UPSERT to handle missing rows) let _ = schema::upsert_trace_profile(state.db.pool(), &file_uuid, trace_id, name, None).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; } } // 3b. Restore source trace profile (UPSERT to handle missing row) let source_name = before_snapshot["trace_profiles"] .as_array() .and_then(|arr| { arr.iter() .find(|p| p["trace_id"].as_i64() == Some(source_trace_id)) }) .and_then(|p| p["name"].as_str().map(String::from)) .unwrap_or_else(|| "Person_0".to_string()); let _ = schema::upsert_trace_profile( state.db.pool(), &file_uuid, source_trace_id as i32, &source_name, None, ) .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() { // No trash collection means the original hard-delete (new semantics) // only reset the name to "unassigned" and kept the data. Rebuild the // named group directly from the operation snapshot instead of looking // for trashed Qdrant points. tracing::warn!( "[UndoHardDelete] No _faces_trash points for trace {}; rebuilding from snapshot", trace_id ); // Re-insert TKG nodes from snapshot (ON CONFLICT updates label/props). 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 (file_uuid, node_type, external_id) DO UPDATE SET label = EXCLUDED.label, properties = EXCLUDED.properties", tkg_table )) .bind(&file_uuid) .bind(ext_id) .bind(label) .bind(&props) .execute(state.db.pool()) .await; } } // Restore trace profile name from snapshot. let profile_name = before_snapshot["trace_profiles"] .as_array() .and_then(|arr| { arr.iter() .find(|p| p["trace_id"].as_i64() == Some(trace_id)) }) .and_then(|p| p["name"].as_str().map(String::from)) .unwrap_or_else(|| "Person_0".to_string()); let _ = schema::upsert_trace_profile( state.db.pool(), &file_uuid, trace_id as i32, &profile_name, None, ) .await; } else { // Legacy path: restore actual Qdrant points from _faces_trash. // 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; } } // 4b. Restore trace profile (UPSERT to handle missing row) let profile_name = before_snapshot["trace_profiles"] .as_array() .and_then(|arr| { arr.iter() .find(|p| p["trace_id"].as_i64() == Some(trace_id)) }) .and_then(|p| p["name"].as_str().map(String::from)) .unwrap_or_else(|| "Person_0".to_string()); let _ = schema::upsert_trace_profile( state.db.pool(), &file_uuid, trace_id as i32, &profile_name, None, ) .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)] pub struct FileProfileQuery { pub file_uuid: String, } #[derive(Debug, Serialize, Deserialize)] pub struct FileProfile { pub file_uuid: String, pub file_name: String, pub file_path: String, pub status: String, pub duration: f64, pub width: i32, pub height: i32, pub fps: f64, pub total_frames: i64, pub face_filter: FaceFilterSettings, #[serde(skip_serializing_if = "Option::is_none")] pub birth: Option, #[serde(skip_serializing_if = "Option::is_none")] pub history: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub key_frame: Option, #[serde(skip_serializing_if = "Option::is_none")] pub proxy_path: Option, #[serde(skip_serializing_if = "Option::is_none")] pub audio_track: Option, } #[derive(Deserialize)] pub struct UpdateFileProfileRequest { pub file_uuid: String, pub file_path: Option, pub file_name: Option, pub face_filter: Option, } pub async fn get_file_profile_handler( State(state): State, Extension(_auth): Extension, Query(params): Query, ) -> Result, StatusCode> { let videos_table = schema::table_name("videos"); // Load basic file info from database let row: Option<( String, String, String, String, f64, i32, i32, f64, i64, Option, // face_filter (for backward compatibility) )> = sqlx::query_as(&format!( "SELECT file_uuid, file_name, file_path, status, duration, width, height, fps, \ COALESCE(total_frames, 0), face_filter FROM {} WHERE file_uuid = $1", videos_table )) .bind(¶ms.file_uuid) .fetch_optional(state.db.pool()) .await .map_err(|e| { tracing::error!("[FileProfile] DB error: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; let ( file_uuid, file_name, file_path, status, duration, width, height, fps, total_frames, db_face_filter, ) = row.ok_or(StatusCode::NOT_FOUND)?; // Try to load face_filter from .profile.json (primary source) let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let disk_profile = crate::core::file_profile::FileProfile::load_from_disk(output_dir, &file_uuid); // Priority: File > Database > Default let face_filter = disk_profile .as_ref() .and_then(|p| p.face_filter.clone()) .or_else(|| { // Fallback to database (backward compatibility) db_face_filter .and_then(|v| serde_json::from_value::(v).ok()) }) .unwrap_or_else(FaceFilterSettings::defaults); // Auto-migration: If face_filter exists in DB but not in file, write to file if disk_profile.is_none() && db_face_filter.is_some() { tracing::info!("[FileProfile] Auto-migrating face_filter to file for {}", file_uuid); let mut new_profile = crate::core::file_profile::FileProfile::from_db_record( &file_uuid, &file_name, &file_path, "video", "", duration, width, height, fps, total_frames, ); new_profile.face_filter = Some(face_filter.clone()); if let Err(e) = new_profile.save_to_disk(output_dir) { tracing::warn!("[FileProfile] Auto-migration failed: {}", e); } } // Fallback for zombie files: if DB fields are empty, try to recover from profile let effective_name = if file_name.is_empty() { disk_profile .as_ref() .map(|p| p.file_name.clone()) .unwrap_or_default() } else { file_name }; let effective_path = if file_path.is_empty() { disk_profile .as_ref() .map(|p| p.current.path.clone()) .unwrap_or_default() } else { file_path }; Ok(Json(FileProfile { file_uuid, file_name: effective_name, file_path: effective_path, status, duration, width, height, fps, total_frames, face_filter, birth: disk_profile .as_ref() .and_then(|p| serde_json::to_value(&p.birth).ok()), history: disk_profile.as_ref().map(|p| { p.history .iter() .map(|h| serde_json::to_value(h).unwrap_or_default()) .collect() }), key_frame: disk_profile.as_ref().and_then(|p| p.key_frame.clone()), proxy_path: disk_profile.as_ref().and_then(|p| p.proxy_path.clone()), audio_track: disk_profile.as_ref().and_then(|p| p.audio_track.clone()), })) } pub async fn update_file_profile_handler( State(state): State, Extension(_auth): Extension, Json(req): Json, ) -> Result, StatusCode> { let videos_table = schema::table_name("videos"); // Update database fields (path, name) if provided let mut updates: Vec = Vec::new(); let mut binds: Vec = Vec::new(); if let Some(s) = req.file_path.as_ref().filter(|s| !s.is_empty()) { updates.push(format!("file_path = ${}", updates.len() + 1)); binds.push(s.clone()); } if let Some(s) = req.file_name.as_ref().filter(|s| !s.is_empty()) { updates.push(format!("file_name = ${}", updates.len() + 1)); binds.push(s.clone()); } // Update database if path or name changed if !updates.is_empty() { let file_uuid_idx = updates.len() + 1; updates.push("updated_at = CURRENT_TIMESTAMP".to_string()); let sql = format!( "UPDATE {} SET {} WHERE file_uuid = ${}", videos_table, updates.join(", "), file_uuid_idx ); let mut query = sqlx::query(&sql); for b in &binds { query = query.bind(b); } query = query.bind(&req.file_uuid); let result = query.execute(state.db.pool()).await; if let Err(e) = result { tracing::error!("[FileProfile] Update failed: {}", e); return Err(StatusCode::INTERNAL_SERVER_ERROR); } } // Update .profile.json (primary source for face_filter) let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let mut profile = crate::core::file_profile::FileProfile::load_from_disk(output_dir, &req.file_uuid) .unwrap_or_else(|| { // Create new profile if doesn't exist crate::core::file_profile::FileProfile::from_db_record( &req.file_uuid, req.file_name.as_deref().unwrap_or(""), req.file_path.as_deref().unwrap_or(""), "video", "", 0.0, 0, 0, 0.0, 0, ) }); // Update path/name if provided if let Some(ref new_path) = req.file_path { if let Some(ref new_name) = req.file_name { profile.update_current_path(new_path, new_name); } } // Update face_filter (primary source) if let Some(ref ff) = req.face_filter { profile.face_filter = Some(ff.clone()); } // Save to disk if let Err(e) = profile.save_to_disk(output_dir) { tracing::error!("[FileProfile] Failed to save to disk: {}", e); return Err(StatusCode::INTERNAL_SERVER_ERROR); } Ok(Json(serde_json::json!({ "success": true, "message": "File profile updated", "file_uuid": req.file_uuid }))) } // ─── Face Groups ─── #[derive(Debug, Serialize, Deserialize)] pub struct FaceGroup { pub group_id: i32, pub name: String, #[serde(skip_serializing_if = "Option::is_none")] pub trace_ids: Option>, pub trace_count: i32, pub representative_trace: i32, pub editable: bool, } #[derive(Deserialize)] pub struct FaceGroupsQuery { #[serde(default)] pub include_trace_ids: Option, } #[derive(Debug, Serialize, Deserialize)] pub struct FaceGroupsResponse { pub success: bool, pub file_uuid: String, pub face_groups: Vec, pub total_groups: i32, pub unassigned_traces: Vec, } pub async fn get_face_groups_handler( State(state): State, Extension(_auth): Extension, Path(file_uuid): Path, Query(q): Query, ) -> Result, StatusCode> { let tkg_table = schema::table_name("tkg_nodes"); let tp_table = schema::table_name("trace_profiles"); let v_table = schema::table_name("videos"); // Read face_filter settings let settings: crate::core::file_profile::FaceFilterSettings = sqlx::query_scalar(&format!( "SELECT face_filter FROM {v_table} WHERE file_uuid = $1" )) .bind(&file_uuid) .fetch_optional(state.db.pool()) .await .ok() .flatten() .and_then(|v| serde_json::from_value(v).ok()) .unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults); let rows: Vec<(String, i32, Option)> = sqlx::query_as(&format!( "SELECT COALESCE(tp.name, tn.label) as name, \ COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id, \ tp.frame_count \ 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 trace_id", tkg_table, tp_table )) .bind(&file_uuid) .fetch_all(state.db.pool()) .await .map_err(|e| { tracing::error!("[FaceGroups] DB error: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; let mut groups: HashMap> = HashMap::new(); let mut unassigned: Vec = Vec::new(); for (name, trace_id, frame_count) in rows { // Filter single frame traces if disabled if frame_count == Some(1) { if !settings.trace_settings.single_frame_trace_group_enabled && !name.starts_with("Face Trace ") && !name.starts_with("Trace ") { continue; } if !settings.trace_settings.single_frame_trace_unassigned_enabled && (name.starts_with("Face Trace ") || name.starts_with("Trace ")) { continue; } } if name.starts_with("Face Trace ") || name.starts_with("Trace ") { unassigned.push(trace_id); } else { groups.entry(name).or_default().push(trace_id); } } // Filter single-trace groups if enabled let mut filtered_groups: HashMap> = HashMap::new(); for (name, trace_ids) in groups { let is_auto_name = name.starts_with("Person_"); let should_filter = settings.trace_settings.single_trace_group_filter_enabled && trace_ids.len() == 1 && is_auto_name; if !should_filter { filtered_groups.insert(name, trace_ids); } } let include_trace_ids = q.include_trace_ids.unwrap_or(true); let face_groups: Vec = filtered_groups .into_iter() .enumerate() .map(|(idx, (name, trace_ids))| FaceGroup { group_id: (idx + 1) as i32, name, trace_count: trace_ids.len() as i32, representative_trace: trace_ids.first().copied().unwrap_or(0), trace_ids: if include_trace_ids { Some(trace_ids) } else { None }, editable: true, }) .collect(); Ok(Json(FaceGroupsResponse { success: true, file_uuid, total_groups: face_groups.len() as i32, unassigned_traces: unassigned, face_groups, })) } // ─── Cluster Results (Studio-compatible) ─── #[derive(Deserialize)] pub struct ClusterResultsQuery { pub file_hash: String, } #[derive(Debug, Serialize)] pub struct ClusterResultsFace { pub face_id: String, pub confidence: f64, pub cluster_id: Option, } #[derive(Debug, Serialize)] pub struct ClusterResultsFrame { pub frame: i64, pub timestamp: f64, pub faces: Vec, } #[derive(Debug, Serialize, Clone)] pub struct ClusterSimilarityInfo { pub min: f64, pub avg: f64, pub threshold: f64, } #[derive(Debug, Serialize)] pub struct ClusterResultsGroup { pub group_id: i32, pub cluster_id: i32, pub name: String, pub trace_ids: Vec, pub trace_count: i32, pub representative_trace: i32, pub similarity: Option, } #[derive(Debug, Serialize)] pub struct ClusterResultsResponse { pub success: bool, pub file_uuid: String, pub face_groups: Vec, pub frames: Vec, } pub async fn get_cluster_results_handler( State(state): State, Extension(_auth): Extension, Query(params): Query, ) -> Result, StatusCode> { let file_uuid = params.file_hash; let tkg_table = schema::table_name("tkg_nodes"); let tp_table = schema::table_name("trace_profiles"); let v_table = schema::table_name("videos"); // Read face_filter settings let settings: crate::core::file_profile::FaceFilterSettings = sqlx::query_scalar(&format!( "SELECT face_filter FROM {v_table} WHERE file_uuid = $1" )) .bind(&file_uuid) .fetch_optional(state.db.pool()) .await .ok() .flatten() .and_then(|v| serde_json::from_value(v).ok()) .unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults); // 1. Build face groups (same grouping logic as face-groups handler) let rows: Vec<(String, i32, Option)> = sqlx::query_as(&format!( "SELECT COALESCE(tp.name, tn.label) as name, \ COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id, \ tp.frame_count \ 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 trace_id", tkg_table, tp_table )) .bind(&file_uuid) .fetch_all(state.db.pool()) .await .map_err(|e| { tracing::error!("[ClusterResults] DB error: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; let mut groups: HashMap> = HashMap::new(); for (name, trace_id, frame_count) in rows { // Filter out single frame traces if disabled if frame_count == Some(1) && !settings.trace_settings.single_frame_trace_group_enabled { continue; } if !(name.starts_with("Face Trace ") || name.starts_with("Trace ")) { groups.entry(name).or_default().push(trace_id); } } // Filter out single-trace "groups" — only auto-generated Person_N names. // User-named groups (even with 1 trace) are kept. let mut filtered_groups: HashMap> = HashMap::new(); for (name, trace_ids) in groups { let is_auto_name = name.starts_with("Person_"); let should_filter = settings.trace_settings.single_trace_group_filter_enabled && trace_ids.len() == 1 && is_auto_name; if !should_filter { filtered_groups.insert(name, trace_ids); } } // trace_id -> cluster_id mapping for frame faces let mut trace_to_cluster: HashMap = HashMap::new(); // Load face_cluster.json for similarity data let cluster_similarity: HashMap = { let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid); let mut map = HashMap::new(); if let Ok(content) = std::fs::read_to_string(&fc_path) { if let Ok(data) = serde_json::from_str::(&content) { if let Some(clusters) = data.get("clusters").and_then(|c| c.as_array()) { for c in clusters { if let (Some(cid), Some(sim)) = ( c.get("cluster_id").and_then(|v| v.as_str()), c.get("similarity"), ) { if let (Some(min), Some(avg), Some(threshold)) = ( sim.get("min").and_then(|v| v.as_f64()), sim.get("avg").and_then(|v| v.as_f64()), sim.get("threshold").and_then(|v| v.as_f64()), ) { map.insert( cid.to_string(), ClusterSimilarityInfo { min, avg, threshold, }, ); } } } } } } map }; let face_groups: Vec = filtered_groups .into_iter() .enumerate() .map(|(idx, (name, trace_ids))| { let group_id = (idx + 1) as i32; for tid in &trace_ids { trace_to_cluster.insert(*tid, group_id); } // Try to find similarity data for this cluster let similarity = cluster_similarity.get(&name).cloned(); ClusterResultsGroup { group_id, cluster_id: group_id, name, trace_count: trace_ids.len() as i32, representative_trace: trace_ids.first().copied().unwrap_or(0), trace_ids, similarity, } }) .collect(); // 2. Get fps for frame -> timestamp conversion let videos_table = schema::table_name("videos"); let fps: f64 = sqlx::query_scalar(&format!( "SELECT fps FROM {} WHERE file_uuid = $1", videos_table )) .bind(&file_uuid) .fetch_optional(state.db.pool()) .await .map_err(|e| { tracing::error!("[ClusterResults] fps query failed: {}", e); StatusCode::INTERNAL_SERVER_ERROR })? .unwrap_or(0.0); // 3. Scroll _faces for this file and group by frame let face_filter = serde_json::json!({ "must": [ {"key": "file_uuid", "match": {"value": &file_uuid}} ] }); let points = state .qdrant .scroll_all_points("_faces", face_filter, 1000) .await .map_err(|e| { tracing::error!("[ClusterResults] Qdrant scroll failed: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?; let mut frames_map: HashMap> = HashMap::new(); for p in &points { let payload = &p["payload"]; let frame = payload["frame"].as_i64().unwrap_or(0); let trace_id = payload["trace_id"].as_i64().map(|t| t as i32).unwrap_or(0); let point_id = p["id"].as_u64().unwrap_or(0); let confidence = payload["confidence"].as_f64().unwrap_or(0.0); // Only include faces that belong to a group (Studio skips unassigned) let cluster_id = trace_to_cluster.get(&trace_id).copied(); if cluster_id.is_none() { continue; } frames_map .entry(frame) .or_default() .push(ClusterResultsFace { face_id: format!("{:x}", point_id), confidence, cluster_id, }); } let mut frames: Vec = frames_map .into_iter() .map(|(frame, faces)| ClusterResultsFrame { frame, timestamp: if fps > 0.0 { frame as f64 / fps } else { 0.0 }, faces, }) .collect(); frames.sort_by_key(|f| f.frame); Ok(Json(ClusterResultsResponse { success: true, file_uuid, face_groups, frames, })) } // ─── 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 { use axum::routing::{get, post, put}; axum::Router::new() .route("/api/v1/trace-profile", get(get_trace_profile_handler)) .route("/api/v1/trace-profile", put(update_trace_profile_handler)) .route( "/api/v1/trace-profile/group", put(update_trace_profile_group_handler), ) .route("/api/v1/file-profile", get(get_file_profile_handler)) .route("/api/v1/file-profile", put(update_file_profile_handler)) .route( "/api/v1/file/:file_uuid/face-groups", get(get_face_groups_handler), ) .route( "/api/v1/file/:file_uuid/face-groups/similar", get(get_similar_group_handler), ) .route("/api/v1/cluster-results", get(get_cluster_results_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), ) }