use axum::{ body::Body, extract::{Extension, Path, Query, State}, http::{header, StatusCode}, response::{IntoResponse, Json, Response}, routing::{delete, get, post}, Router, }; use serde::{Deserialize, Serialize}; use std::sync::Arc; use crate::core::db::schema::t; use crate::core::db::PostgresDb; use crate::core::file_profile::{count_face_artifacts, FaceArtifactsCounts}; pub fn trace_agent_routes() -> Router { Router::new() .route("/api/v1/file/:file_uuid/traces", post(list_traces_sorted)) .route( "/api/v1/file/:file_uuid/trace/:trace_id/faces", get(list_trace_faces), ) .route( "/api/v1/file/:file_uuid/trace/:trace_id/representative-face", get(get_representative_face), ) .route( "/api/v1/file/:file_uuid/trace/:trace_id/thumbnail", get(get_trace_thumbnail), ) .route( "/api/v1/file/:file_uuid/stranger/:stranger_id/representative-face", get(get_stranger_representative_face), ) .route( "/api/v1/file/:file_uuid/stranger/:stranger_id/thumbnail", get(get_stranger_thumbnail), ) .route( "/api/v1/file/:file_uuid/identities/:identity_uuid_a/co-occur-with/:identity_uuid_b", get(get_cooccurrence), ) .route("/api/v1/file/:file_uuid/tkg/rebuild", post(rebuild_tkg)) .route("/api/v1/file/:file_uuid/tkg", get(get_tkg_operations)) .route("/api/v1/file/:file_uuid/tkg", delete(delete_tkg)) .route("/api/v1/file/:file_uuid/rule2", post(ingest_rule2)) .route( "/api/v1/file/:file_uuid/representative-frame", get(get_representative_frame), ) .route("/api/v1/file/:file_uuid/tkg/nodes", post(query_tkg_nodes)) .route("/api/v1/file/:file_uuid/tkg/edges", post(query_tkg_edges)) .route( "/api/v1/file/:file_uuid/tkg/node/:node_id", get(get_tkg_node_detail), ) .route( "/api/v1/file/:file_uuid/trace/:trace_id", delete(delete_trace), ) .route( "/api/v1/file/:file_uuid/trace/:trace_id/restore", post(restore_trace), ) .route( "/api/v1/file/:file_uuid/trace/:trace_id/merge/:target_trace_id", post(merge_trace), ) .route( "/api/v1/file/:file_uuid/trace/:trace_id/regenerate-thumbnail", post(regenerate_trace_thumbnail), ) } #[derive(Debug, Deserialize)] struct TracesRequest { min_faces: Option, sort_by: Option, page: Option, page_size: Option, limit: Option, min_confidence: Option, max_confidence: Option, } #[derive(Debug, Serialize)] struct TraceInfo { trace_id: i32, face_count: i64, start_frame: i64, end_frame: i64, start_time: f64, end_time: f64, duration_sec: f64, avg_confidence: f64, best_face_id: i32, best_face_frame: i64, best_face_confidence: f64, best_face_bbox: Option, avg_capture_quality: f64, best_face_capture_quality: f64, sample_face_id: Option, thumbnail_url: String, } #[derive(Debug, Serialize)] struct TracesResponse { success: bool, file_uuid: String, fps: f64, total_traces: i64, total_faces: i64, page: i64, page_size: i64, traces: Vec, // On-disk face artifact counts (vs expected) for completion transparency face_artifacts: FaceArtifactsCounts, } async fn list_traces_sorted( State(state): State, Path(file_uuid): Path, Json(req): Json, ) -> Result, (StatusCode, String)> { let min_faces = req.min_faces.unwrap_or(1); let sort = req.sort_by.as_deref().unwrap_or("first_appearance"); let page = req.page.unwrap_or(1).max(1); let page_size = req.page_size.unwrap_or(50).max(1).min(3000); let hard_limit = req.limit.unwrap_or(500).min(3000); let effective_limit = hard_limit.min(page_size); let db_offset = (page - 1) * page_size; let min_confidence = req.min_confidence.unwrap_or(0.0); let max_confidence = req.max_confidence.unwrap_or(1.0); let order_clause = match sort { "face_count" => "face_count DESC", "duration" => "duration_sec DESC", _ => "start_frame ASC", }; let fps: f64 = sqlx::query_scalar(&format!( "SELECT COALESCE(fps, 24.0) FROM {} WHERE file_uuid = $1", crate::core::db::schema::table_name("videos") )) .bind(&file_uuid) .fetch_optional(state.db.pool()) .await .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))? .unwrap_or(24.0); // Get face points from Qdrant _faces use crate::core::db::qdrant_db::QdrantDb; use serde_json::json; use std::collections::HashMap; let qdrant = QdrantDb::new(); let face_filter = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}} ], "must_not": [ {"key": "status", "match": {"value": "deleted"}} ] }); let points = qdrant .scroll_all_points("_faces", face_filter, 2000) .await .unwrap_or_default(); // Aggregate by trace_id struct TraceAgg { face_count: i64, start_frame: i64, end_frame: i64, avg_confidence: f64, sum_confidence: f64, best_confidence: f64, best_point_id: i64, best_frame: i64, best_bbox: Option, sum_capture_quality: f64, best_capture_quality: f64, best_capture_point_id: i64, best_capture_frame: i64, best_capture_bbox: Option, } let mut trace_data: HashMap = HashMap::new(); for point in &points { let payload = &point["payload"]; let trace_id = payload["trace_id"].as_i64().unwrap_or(0) as i32; let frame = payload["frame"].as_i64().unwrap_or(0); let confidence = payload["confidence"].as_f64().unwrap_or(0.5); let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0); let point_id = point["id"].as_i64().unwrap_or(0); if confidence < min_confidence || confidence > max_confidence { continue; } let entry = trace_data.entry(trace_id).or_insert(TraceAgg { face_count: 0, start_frame: i64::MAX, end_frame: i64::MIN, avg_confidence: 0.0, sum_confidence: 0.0, best_confidence: 0.0, best_point_id: 0, best_frame: 0, best_bbox: None, sum_capture_quality: 0.0, best_capture_quality: 0.0, best_capture_point_id: 0, best_capture_frame: 0, best_capture_bbox: None, }); entry.face_count += 1; entry.start_frame = entry.start_frame.min(frame); entry.end_frame = entry.end_frame.max(frame); entry.sum_confidence += confidence; entry.sum_capture_quality += capture_quality; if confidence > entry.best_confidence { entry.best_confidence = confidence; entry.best_point_id = point_id; entry.best_frame = frame; entry.best_bbox = payload.get("bbox").cloned(); } if capture_quality > entry.best_capture_quality { entry.best_capture_quality = capture_quality; entry.best_capture_point_id = point_id; entry.best_capture_frame = frame; entry.best_capture_bbox = payload.get("bbox").cloned(); } } // Filter by min_faces and sort let mut traces_vec: Vec<( i32, i64, i64, i64, f64, f64, i32, i64, f64, Option, f64, f64, )> = trace_data .into_iter() .filter(|(_, agg)| agg.face_count >= min_faces) .map(|(tid, agg)| { let duration = (agg.end_frame - agg.start_frame) as f64; let avg_conf = if agg.face_count > 0 { agg.sum_confidence / agg.face_count as f64 } else { 0.0 }; let avg_cq = if agg.face_count > 0 { agg.sum_capture_quality / agg.face_count as f64 } else { 0.0 }; ( tid, agg.face_count, agg.start_frame, agg.end_frame, duration, avg_conf, agg.best_point_id as i32, agg.best_frame, agg.best_confidence, agg.best_bbox, avg_cq, agg.best_capture_quality, ) }) .collect(); match order_clause { "face_count DESC" => traces_vec.sort_by(|a, b| b.1.cmp(&a.1)), "duration_sec DESC" => { traces_vec.sort_by(|a, b| b.4.partial_cmp(&a.4).unwrap_or(std::cmp::Ordering::Equal)) } _ => traces_vec.sort_by(|a, b| a.2.cmp(&b.2)), } // Apply pagination let total_traces = traces_vec.len() as i64; let total_faces: i64 = points.len() as i64; let traces_vec: Vec<_> = traces_vec .into_iter() .skip(db_offset as usize) .take(effective_limit as usize) .collect(); let traces: Vec = traces_vec .into_iter() .map( |(tid, fc, sf, ef, dur, conf, bfid, bff, bfc, bfb, acq, bcq)| TraceInfo { trace_id: tid, face_count: fc, start_frame: sf, end_frame: ef, start_time: sf as f64 / fps, end_time: ef as f64 / fps, duration_sec: dur / fps, avg_confidence: conf, best_face_id: bfid, best_face_frame: bff, best_face_confidence: bfc, best_face_bbox: bfb, avg_capture_quality: acq, best_face_capture_quality: bcq, sample_face_id: None, thumbnail_url: format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, tid), }, ) .collect(); // On-disk face artifact counts (vs expected) for completion transparency let trace_profiles_table = crate::core::db::schema::table_name("trace_profiles"); let expected_traces: i64 = sqlx::query_scalar(&format!( "SELECT COUNT(*) FROM {} WHERE file_uuid = $1", trace_profiles_table )) .bind(&file_uuid) .fetch_one(state.db.pool()) .await .unwrap_or(0); let mut face_artifacts = count_face_artifacts(crate::core::config::OUTPUT_DIR.as_str(), &file_uuid); face_artifacts.expected_traces = expected_traces; Ok(Json(TracesResponse { success: true, file_uuid, fps, total_traces, total_faces, page, page_size, traces, face_artifacts, })) } // ── Individual face detections for a trace ── #[derive(Debug, Deserialize)] struct TraceFacesQuery { page: Option, page_size: Option, limit: Option, offset: Option, interpolate: Option, } #[derive(Debug, Serialize)] struct TraceFaceItem { id: i32, start_frame: i64, end_frame: i64, start_time: f64, end_time: f64, x: Option, y: Option, width: Option, height: Option, confidence: f64, capture_quality: f64, interpolated: bool, } #[derive(Debug, Serialize)] struct TraceFacesResponse { success: bool, file_uuid: String, trace_id: i32, fps: f64, total: i64, faces: Vec, } fn lerp_i32(a: Option, b: Option, t: f64) -> Option { match (a, b) { (Some(av), Some(bv)) => Some((av as f64 + (bv - av) as f64 * t).round() as i32), _ => None, } } async fn list_trace_faces( State(state): State, Path((file_uuid, trace_id)): Path<(String, i32)>, Query(q): Query, ) -> Result, (StatusCode, String)> { let limit = q.limit.unwrap_or(200).min(1000); // Support both page/page_size and offset; page/page_size takes precedence let offset = if q.page.is_some() || q.page_size.is_some() { let p = q.page.unwrap_or(1).max(1); let ps = q.page_size.unwrap_or(200).max(1).min(1000); (p - 1) * ps } else { q.offset.unwrap_or(0) }; let interpolate = q.interpolate.unwrap_or(false); let fps: f64 = sqlx::query_scalar(&format!( "SELECT COALESCE(fps, 24.0) FROM {} WHERE file_uuid = $1", crate::core::db::schema::table_name("videos") )) .bind(&file_uuid) .fetch_optional(state.db.pool()) .await .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))? .unwrap_or(24.0); // Get face points from Qdrant _faces for this trace use crate::core::db::qdrant_db::QdrantDb; use serde_json::json; let qdrant = QdrantDb::new(); let trace_filter = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}} ] }); let points = qdrant .scroll_all_points("_faces", trace_filter, 1000) .await .unwrap_or_default(); let total_detected: i64 = points.len() as i64; // Apply pagination let paged: Vec<_> = points .into_iter() .skip(offset as usize) .take(limit as usize) .collect(); let mut faces: Vec = Vec::new(); for (i, point) in paged.iter().enumerate() { let payload = &point["payload"]; let frame = payload["frame"].as_i64().unwrap_or(0); let bbox = &payload["bbox"]; let x = bbox["x"].as_f64().unwrap_or(0.0) as i32; let y = bbox["y"].as_f64().unwrap_or(0.0) as i32; let w = bbox["width"].as_f64().unwrap_or(0.0) as i32; let h = bbox["height"].as_f64().unwrap_or(0.0) as i32; let conf = payload["confidence"].as_f64().unwrap_or(0.5) as f32; let id = i as i32; let cur = (x, y, w, h); // Add interpolated frames between previous and current detection if interpolate && i > 0 { let prev_point = &paged[i - 1]; let prev_payload = &prev_point["payload"]; let prev_bbox = &prev_payload["bbox"]; let prev_frame = prev_payload["frame"].as_i64().unwrap_or(0); let prev_x = prev_bbox["x"].as_f64().unwrap_or(0.0) as i32; let prev_y = prev_bbox["y"].as_f64().unwrap_or(0.0) as i32; let prev_w = prev_bbox["width"].as_f64().unwrap_or(0.0) as i32; let prev_h = prev_bbox["height"].as_f64().unwrap_or(0.0) as i32; let gap = frame - prev_frame; if gap > 1 { for mid in 1..gap { let t = mid as f64 / gap as f64; let mid_x = lerp_i32(Some(prev_x), Some(x), t).unwrap_or(0); let mid_y = lerp_i32(Some(prev_y), Some(y), t).unwrap_or(0); let mid_w = lerp_i32(Some(prev_w), Some(w), t).unwrap_or(0); let mid_h = lerp_i32(Some(prev_h), Some(h), t).unwrap_or(0); let mid_frame = prev_frame + mid; let mt = (mid_frame as f64 / fps * 10.0).round() / 10.0; faces.push(TraceFaceItem { id: 0, start_frame: mid_frame, end_frame: mid_frame, start_time: mt, end_time: mt, x: Some(mid_x), y: Some(mid_y), width: Some(mid_w), height: Some(mid_h), confidence: 0.0, capture_quality: 0.0, interpolated: true, }); } } } // Add the real detection let frame_val = frame; let ft = (frame_val as f64 / fps * 10.0).round() / 10.0; let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0); faces.push(TraceFaceItem { id, start_frame: frame_val, end_frame: frame_val, start_time: ft, end_time: ft, x: Some(x), y: Some(y), width: Some(w), height: Some(h), confidence: conf as f64, capture_quality, interpolated: false, }); } let total = if interpolate && faces.len() as i64 > total_detected { faces.len() as i64 } else { total_detected }; Ok(Json(TraceFacesResponse { success: true, file_uuid, trace_id, fps, total, faces, })) } #[derive(Debug, Serialize)] struct RepFaceBbox { x: i32, y: i32, width: i32, height: i32, } #[derive(Debug, Serialize)] struct RepFaceResult { frame_number: i64, timestamp_secs: f64, bbox: RepFaceBbox, confidence: f64, quality_score: f64, blur_score: f64, } #[derive(Debug, Serialize)] struct RepFaceResponse { success: bool, file_uuid: String, trace_id: i32, face_count: i64, representative: RepFaceResult, } struct RepFaceSelection { frame: i64, x: i32, y: i32, w: i32, h: i32, conf: f64, blur: f64, score: f64, video_path: String, fps: f64, face_count: i64, } async fn select_rep_face( pool: &sqlx::PgPool, file_uuid: &str, trace_id: i32, err_fn: F, ) -> Result where F: Fn(anyhow::Error) -> T, { use crate::core::db::qdrant_db::QdrantDb; use crate::core::db::schema; use serde_json::json; let video_table = schema::table_name("videos"); let fps: f64 = sqlx::query_scalar(&format!( "SELECT COALESCE(fps, 25.0) FROM {} WHERE file_uuid = $1", video_table )) .bind(file_uuid) .fetch_optional(pool) .await .map_err(|e| err_fn(anyhow::anyhow!("{}", e)))? .unwrap_or(25.0); // Get face count from Qdrant let qdrant = QdrantDb::new(); let trace_filter = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}} ] }); let points = qdrant .scroll_all_points("_faces", trace_filter, 1000) .await .unwrap_or_default(); let face_count: (i64,) = (points.len() as i64,); struct Candidate { frame: i64, x: i32, y: i32, w: i32, h: i32, conf: f64, score: f64, } // Get top faces by quality from Qdrant let mut candidates: Vec = points .iter() .filter_map(|p| { let payload = &p["payload"]; let bbox = &payload["bbox"]; let w = bbox["width"].as_f64()? as i32; let h = bbox["height"].as_f64()? as i32; let conf = payload["confidence"].as_f64()?; if conf <= 0.7 { return None; } let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0); let score = (w as f64 * h as f64) * conf * (0.2 + capture_quality); Some(Candidate { frame: payload["frame"].as_i64().unwrap_or(0), x: bbox["x"].as_f64()? as i32, y: bbox["y"].as_f64()? as i32, w, h, conf, score, }) }) .collect(); candidates.sort_by(|a, b| { b.score .partial_cmp(&a.score) .unwrap_or(std::cmp::Ordering::Equal) }); let rows: Vec<_> = candidates.into_iter().take(10).collect(); if rows.is_empty() { return Err(err_fn(anyhow::anyhow!("No suitable face found"))); } let candidates: Vec = rows; let video_path: String = sqlx::query_scalar(&format!( "SELECT file_path FROM {} WHERE file_uuid = $1", video_table )) .bind(file_uuid) .fetch_optional(pool) .await .map_err(|e| err_fn(anyhow::anyhow!("{}", e)))? .ok_or_else(|| err_fn(anyhow::anyhow!("Video not found")))?; let mut best = candidates[0].frame; let mut best_blur = f64::MAX; let mut best_idx = 0usize; for (i, c) in candidates.iter().enumerate() { let seek = c.frame as f64 / fps; if let Ok(output) = tokio::process::Command::new("ffmpeg") .args([ "-ss", &format!("{:.2}", seek), "-i", &video_path, "-vframes", "1", "-vf", &format!("crop={}:{}:{}:{},blurdetect", c.w, c.h, c.x, c.y), "-f", "null", "-", ]) .output() .await { let stderr = String::from_utf8_lossy(&output.stderr); for line in stderr.lines() { if let Some(blur_str) = line.split("blur mean: ").nth(1) { if let Ok(blur) = blur_str.trim().parse::() { if blur < best_blur { best_blur = blur; best = c.frame; best_idx = i; } } } } } } let chosen = &candidates[best_idx]; Ok(RepFaceSelection { frame: chosen.frame, x: chosen.x, y: chosen.y, w: chosen.w, h: chosen.h, conf: chosen.conf, blur: best_blur, score: chosen.score, video_path, fps, face_count: face_count.0, }) } async fn get_representative_face( State(state): State, Path((file_uuid, trace_id)): Path<(String, i32)>, ) -> Result, (StatusCode, Json)> { get_representative_face_inner(&state, &file_uuid, trace_id).await } async fn get_representative_face_inner( state: &crate::api::types::AppState, file_uuid: &str, trace_id: i32, ) -> Result, (StatusCode, Json)> { let sel = select_rep_face(state.db.pool(), file_uuid, trace_id, |e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) }) .await?; Ok(Json(RepFaceResponse { success: true, file_uuid: file_uuid.to_string(), trace_id, face_count: sel.face_count, representative: RepFaceResult { frame_number: sel.frame, timestamp_secs: sel.frame as f64 / sel.fps, bbox: RepFaceBbox { x: sel.x, y: sel.y, width: sel.w, height: sel.h, }, confidence: sel.conf, quality_score: sel.score, blur_score: sel.blur, }, })) } async fn get_trace_thumbnail( State(state): State, Path((file_uuid, trace_id)): Path<(String, i32)>, ) -> Result)> { get_trace_thumbnail_inner(&state, &file_uuid, trace_id).await } async fn get_trace_thumbnail_inner( state: &crate::api::types::AppState, file_uuid: &str, trace_id: i32, ) -> Result)> { // Step 1: Check for pre-stored face crops in .faces/{file_uuid}/{trace_id}/ // For trace_id=0 (untracked/stranger), check unbound directory instead let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let trace_id_str = trace_id.to_string(); let trace_dir_name = if trace_id == 0 { "unbound" } else { &trace_id_str }; let trace_dir = std::path::PathBuf::from(output_dir) .join(".faces") .join(&file_uuid) .join(trace_dir_name); if trace_dir.exists() { // Find any cached face crop in this trace directory if let Ok(mut entries) = std::fs::read_dir(&trace_dir) { while let Some(Ok(entry)) = entries.next() { let path = entry.path(); if path.extension().map_or(false, |e| e == "jpg") { tracing::info!( "[trace_thumbnail] Using cached face crop: {}", path.display() ); let bytes = tokio::fs::read(&path).await.map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })?; // Validate cached JPEG crate::core::thumbnail::validator::validate_jpeg(&bytes).map_err(|e| { tracing::warn!("[trace_thumbnail] Cached JPEG validation failed: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Invalid cached JPEG"})), ) })?; return Ok(Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "image/jpeg") .header(header::CACHE_CONTROL, "public, max-age=86400") .body(Body::from(bytes)) .unwrap()); } } } } // Step 1.5: Check trace_profile's key_face.jpg for consistency with Face Detail modal let profile_trace_dir = std::path::PathBuf::from(output_dir) .join(&file_uuid) .join(format!("trace_{}", trace_id)); let key_face_path = profile_trace_dir.join("key_face.jpg"); if key_face_path.exists() { if let Ok(bytes) = tokio::fs::read(&key_face_path).await { if crate::core::thumbnail::validator::validate_jpeg(&bytes).is_ok() { tracing::info!( "[trace_thumbnail] Using trace_profile key_face.jpg: {}", key_face_path.display() ); return Ok(Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "image/jpeg") .header(header::CACHE_CONTROL, "public, max-age=86400") .body(Body::from(bytes)) .unwrap()); } } } // Step 2: Fallback to ffmpeg on-demand extraction let sel = select_rep_face(state.db.pool(), &file_uuid, trace_id, |e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) }) .await?; let seek = sel.frame as f64 / sel.fps; let tmp = std::env::temp_dir().join(format!("trace_{}_{}.jpg", file_uuid, trace_id)); tracing::debug!( "[trace_thumbnail] Fallback to ffmpeg for trace {} frame {}", trace_id, sel.frame ); let status = tokio::process::Command::new("ffmpeg") .args([ "-ss", &format!("{:.2}", seek), "-i", &sel.video_path, "-vframes", "1", "-vf", &format!("crop={}:{}:{}:{},scale=320:320", sel.w, sel.h, sel.x, sel.y), "-q:v", "2", "-y", &tmp.to_string_lossy().to_string(), ]) .output() .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })?; if !status.status.success() { return Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "FFmpeg failed"})), )); } let bytes = tokio::fs::read(&tmp).await.map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })?; crate::core::thumbnail::validator::validate_jpeg(&bytes).map_err(|e| { tracing::warn!("[trace_thumbnail] JPEG validation failed: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Invalid JPEG output"})), ) })?; let _ = tokio::fs::remove_file(&tmp).await; Ok(Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "image/jpeg") .header(header::CACHE_CONTROL, "public, max-age=86400") .body(Body::from(bytes)) .unwrap()) } // Regenerate a trace's key_face.jpg by re-cropping the best-confidence face // from the video with the bbox clamped to the frame dimensions. Fixes the // "key frame OK, bbox OK, but key_face broken" case where an out-of-bounds // bbox made ffmpeg silently shift the crop. async fn regenerate_trace_thumbnail( State(state): State, Path((file_uuid, trace_id)): Path<(String, i32)>, ) -> Result, (StatusCode, Json)> { use serde_json::json; let videos_table = crate::core::db::schema::table_name("videos"); // Query video info: path, dimensions, fps let row: Option<(String, Option, Option, Option)> = sqlx::query_as(&format!( "SELECT file_path, width, height, fps FROM {} WHERE file_uuid = $1", videos_table )) .bind(&file_uuid) .fetch_optional(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})), ) })?; let (video_path, video_width, video_height, fps) = row.ok_or_else(|| { ( StatusCode::NOT_FOUND, Json(json!({"error": "Video not found"})), ) })?; let video_width = video_width.ok_or_else(|| { ( StatusCode::BAD_REQUEST, Json(json!({"error": "Video width unavailable, cannot clamp crop"})), ) })?; let video_height = video_height.ok_or_else(|| { ( StatusCode::BAD_REQUEST, Json(json!({"error": "Video height unavailable, cannot clamp crop"})), ) })?; let fps = fps.unwrap_or(25.0); // Scroll Qdrant _faces for this trace and pick the highest-confidence face. // Unlike select_rep_face, no blur-optimization happens: we reuse the // existing best-confidence frame + bbox to restore the same region. use crate::core::db::qdrant_db::QdrantDb; let qdrant = QdrantDb::new(); let trace_filter = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}} ] }); let points = qdrant .scroll_all_points("_faces", trace_filter, 1000) .await .unwrap_or_default(); let best = points .iter() .filter_map(|p| { let payload = &p["payload"]; let bbox = &payload["bbox"]; let w = bbox["width"].as_f64()? as i32; let h = bbox["height"].as_f64()? as i32; let conf = payload["confidence"].as_f64()?; Some(( payload["frame"].as_i64().unwrap_or(0), bbox["x"].as_f64()? as i32, bbox["y"].as_f64()? as i32, w, h, conf, )) }) .reduce(|acc, cur| { // Match list_traces_sorted tie-break: strict > keeps the first-seen // point on equal confidence so the label and thumbnail agree. if cur.5 > acc.5 { cur } else { acc } }); let (best_frame, bx, by, bw, bh, _conf) = best.ok_or_else(|| { ( StatusCode::NOT_FOUND, Json(json!({"error": "No face found for this trace"})), ) })?; // Clamp bbox to frame dimensions let (cx, cy, cw, ch) = crate::core::thumbnail::validator::clamp_crop(bx, by, bw, bh, video_width, video_height); tracing::info!( "[regenerate-thumbnail] trace {} frame {} bbox {}x{} at ({},{})", trace_id, best_frame, cw, ch, cx, cy ); // Crop the face region from the video using decoded frame index (VFR-safe) let tmp = std::env::temp_dir().join(format!("regen_trace_{}_{}.jpg", file_uuid, trace_id)); let select = format!("select=eq(n\\,{})", best_frame); let status = tokio::process::Command::new("ffmpeg") .args([ "-y", "-i", &video_path, "-vf", &format!("{},crop={}:{}:{}:{}", select, cw, ch, cx, cy), "-frames:v", "1", "-q:v", "2", &tmp.to_string_lossy().to_string(), ]) .output() .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})), ) })?; if !status.status.success() { return Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "FFmpeg failed during regeneration"})), )); } let bytes = tokio::fs::read(&tmp).await.map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})), ) })?; crate::core::thumbnail::validator::validate_jpeg(&bytes).map_err(|e| { tracing::warn!("[regenerate-thumbnail] JPEG validation failed: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "Invalid JPEG output"})), ) })?; let _ = tokio::fs::remove_file(&tmp).await; // Overwrite key_face.jpg in the trace profile directory let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let profile_dir = std::path::PathBuf::from(output_dir) .join(&file_uuid) .join(format!("trace_{}", trace_id)); if let Err(e) = tokio::fs::create_dir_all(&profile_dir).await { tracing::warn!("[regenerate-thumbnail] Failed to create trace dir: {}", e); } let _ = tokio::fs::write(profile_dir.join("key_face.jpg"), &bytes).await; // Sync .faces cache if the cached crop file exists for the best frame let trace_dir_name = if trace_id == 0 { "unbound".to_string() } else { trace_id.to_string() }; let faces_cached = std::path::PathBuf::from(output_dir) .join(".faces") .join(&file_uuid) .join(trace_dir_name) .join(format!("{}.jpg", best_frame)); if faces_cached.exists() { let _ = tokio::fs::write(&faces_cached, &bytes).await; } Ok(Json(json!({ "success": true, "file_uuid": file_uuid, "trace_id": trace_id, "frame": best_frame, "bbox": {"x": cx, "y": cy, "width": cw, "height": ch}, }))) } #[derive(Debug, Serialize)] struct CoOccurIdentity { identity_uuid: String, name: String, trace_id: i32, } #[derive(Debug, Serialize)] struct CoOccurRepFace { frame_number: i64, bbox: RepFaceBbox, confidence: f64, thumbnail_url: String, } #[derive(Debug, Serialize)] struct CoOccurrence { frame_number: i64, timestamp_secs: f64, total_cooccurrence_frames: i64, representative_face_a: Option, representative_face_b: Option, } #[derive(Debug, Serialize)] struct CoOccurResponse { success: bool, file_uuid: String, identity_a: CoOccurIdentity, identity_b: CoOccurIdentity, first_cooccurrence: CoOccurrence, } async fn get_cooccurrence( State(state): State, Path((file_uuid, identity_uuid_a, identity_uuid_b)): Path<(String, String, String)>, ) -> Result, (StatusCode, Json)> { use crate::core::db::qdrant_db::QdrantDb; use crate::core::db::schema; use serde_json::json; let id_table = schema::table_name("identities"); // Stage 1: Get identity names and IDs let id_a = sqlx::query_as::<_, (i32, String)>(&format!( "SELECT id, name FROM {} WHERE uuid::text = $1 OR REPLACE(uuid::text, '-', '') = $1", id_table )) .bind(&identity_uuid_a) .fetch_optional(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? .ok_or_else(|| { ( StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Identity A not found"})), ) })?; let id_b = sqlx::query_as::<_, (i32, String)>(&format!( "SELECT id, name FROM {} WHERE uuid::text = $1 OR REPLACE(uuid::text, '-', '') = $1", id_table )) .bind(&identity_uuid_b) .fetch_optional(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? .ok_or_else(|| { ( StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Identity B not found"})), ) })?; // Stage 2: Find first frame where both identity_ids appear (from Qdrant _faces) let qdrant = QdrantDb::new(); // Get frames for identity A let filter_a = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "identity_id", "match": {"value": id_a.0}} ] }); let points_a = qdrant .scroll_all_points("_faces", filter_a, 1000) .await .unwrap_or_default(); let frames_a: std::collections::HashSet = points_a .iter() .filter_map(|p| p["payload"]["frame"].as_i64()) .collect(); // Get frames for identity B and find first co-occurrence let filter_b = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "identity_id", "match": {"value": id_b.0}} ] }); let points_b = qdrant .scroll_all_points("_faces", filter_b, 1000) .await .unwrap_or_default(); let cooccur: Option<(i64,)> = points_b .iter() .filter_map(|p| p["payload"]["frame"].as_i64()) .find(|f| frames_a.contains(f)) .map(|f| (f,)); let (first_frame,) = cooccur.ok_or_else(|| { (StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "These two identities never appear together in this file"}))) })?; // Get fps for timestamp let video_table = schema::table_name("videos"); let fps: f64 = sqlx::query_scalar(&format!( "SELECT COALESCE(fps, 25.0) FROM {} WHERE file_uuid = $1", video_table )) .bind(&file_uuid) .fetch_optional(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? .unwrap_or(25.0); // Stage 3: Get trace_ids for both at this frame (from Qdrant _faces) let trace_a: Option<(i32,)> = points_a .iter() .find(|p| p["payload"]["frame"].as_i64() == Some(first_frame)) .and_then(|p| p["payload"]["trace_id"].as_i64()) .map(|t| (t as i32,)); let trace_b: Option<(i32,)> = points_b .iter() .find(|p| p["payload"]["frame"].as_i64() == Some(first_frame)) .and_then(|p| p["payload"]["trace_id"].as_i64()) .map(|t| (t as i32,)); // Stage 4: Get representative faces for both traces (reusing select_rep_face) let rep_a = if let Some((tid,)) = trace_a { select_rep_face(state.db.pool(), &file_uuid, tid, |e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) }) .await .ok() .map(|sel| CoOccurRepFace { frame_number: sel.frame, bbox: RepFaceBbox { x: sel.x, y: sel.y, width: sel.w, height: sel.h, }, confidence: sel.conf, thumbnail_url: format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, tid), }) } else { None }; let rep_b = if let Some((tid,)) = trace_b { select_rep_face(state.db.pool(), &file_uuid, tid, |e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) }) .await .ok() .map(|sel| CoOccurRepFace { frame_number: sel.frame, bbox: RepFaceBbox { x: sel.x, y: sel.y, width: sel.w, height: sel.h, }, confidence: sel.conf, thumbnail_url: format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, tid), }) } else { None }; // Total co-occurrence frames (from Qdrant _faces) let frames_b: std::collections::HashSet = points_b .iter() .filter_map(|p| p["payload"]["frame"].as_i64()) .collect(); let total_cooccurrence_frames: i64 = points_a .iter() .filter_map(|p| p["payload"]["frame"].as_i64()) .filter(|f| frames_b.contains(f)) .count() as i64; Ok(Json(CoOccurResponse { success: true, file_uuid, identity_a: CoOccurIdentity { identity_uuid: identity_uuid_a, name: id_a.1, trace_id: trace_a.map(|t| t.0).unwrap_or(0), }, identity_b: CoOccurIdentity { identity_uuid: identity_uuid_b, name: id_b.1, trace_id: trace_b.map(|t| t.0).unwrap_or(0), }, first_cooccurrence: CoOccurrence { frame_number: first_frame, timestamp_secs: first_frame as f64 / fps, total_cooccurrence_frames, representative_face_a: rep_a, representative_face_b: rep_b, }, })) } use crate::core::config::OUTPUT_DIR; #[derive(Serialize)] struct TkgRebuildResponse { success: bool, file_uuid: String, result: Option, error: Option, } #[derive(Deserialize)] struct RebuildParams { force: Option, } async fn rebuild_tkg( State(state): State, Path(file_uuid): Path, Query(params): Query, ) -> Json { use crate::core::chunk::rule2_ingest::ingest_rule2; use crate::core::tkg::TkgService; use tracing::info; let db = state.db.clone(); let tkg_service = TkgService::new(state.db); let force = params.force.unwrap_or(false); let result = tkg_service.rebuild(&file_uuid, &OUTPUT_DIR, force).await; match result { Ok(r) => { // Always trigger Rule 2 (even with 0 edges) info!( "[TKG] Rebuild completed for {}: {} nodes, {} edges", file_uuid, r.total_nodes(), r.total_edges() ); match ingest_rule2(db.pool(), &file_uuid, None, None).await { Ok(count) => info!("[TKG] Rule 2 created {} relationship chunks", count), Err(e) => info!("[TKG] Rule 2 ingestion failed: {}", e), } Json(TkgRebuildResponse { success: true, file_uuid, result: Some(r.to_json()), error: None, }) } Err(e) => Json(TkgRebuildResponse { success: false, file_uuid, result: None, error: Some(e.to_string()), }), } } async fn get_tkg_operations( State(state): State, Path(file_uuid): Path, ) -> Json> { use crate::core::tkg::TkgService; let tkg_service = TkgService::new(state.db); let operations = tkg_service .get_operations(&file_uuid) .await .unwrap_or_default(); Json(operations) } async fn delete_tkg( State(state): State, Path(file_uuid): Path, ) -> Json { use crate::core::tkg::TkgService; let tkg_service = TkgService::new(state.db); match tkg_service.delete_tkg_and_logs(&file_uuid).await { Ok(_) => Json(serde_json::json!({"success": true, "message": "TKG deleted successfully"})), Err(e) => Json(serde_json::json!({"success": false, "error": e.to_string()})), } } // ── Representative Frame (JSON) ─────────────────────────────────── use crate::core::processor::tkg; #[derive(Serialize)] struct RepFrameResponse { success: bool, file_uuid: String, frame_number: i64, timestamp_secs: f64, face_quality: f64, main_identities: Vec, traces: Vec, } async fn get_representative_frame( State(state): State, Path(file_uuid): Path, ) -> Result, (StatusCode, Json)> { let result = tkg::query_auto_representative_frame(state.db.pool(), &file_uuid) .await .map_err(|e| { ( StatusCode::NOT_FOUND, Json(serde_json::json!({"error": e.to_string()})), ) })?; let fps = query_fps(state.db.pool(), &file_uuid).await; Ok(Json(RepFrameResponse { success: true, file_uuid, frame_number: result.frame_number, timestamp_secs: result.frame_number as f64 / fps, face_quality: result.face_quality, main_identities: result.main_identities, traces: result.traces, })) } async fn query_fps(pool: &sqlx::PgPool, file_uuid: &str) -> f64 { use crate::core::db::schema; let video_table = schema::table_name("videos"); sqlx::query_scalar(&format!( "SELECT COALESCE(fps, 25.0) FROM {} WHERE file_uuid = $1", video_table )) .bind(file_uuid) .fetch_optional(pool) .await .ok() .flatten() .unwrap_or(25.0) } async fn get_stranger_representative_face( State(state): State, Path((file_uuid, stranger_id)): Path<(String, i32)>, ) -> Result, (StatusCode, Json)> { // Get trace_id from Qdrant _faces by stranger_id use crate::core::db::qdrant_db::QdrantDb; use serde_json::json; let qdrant = QdrantDb::new(); let filter = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "stranger_id", "match": {"value": stranger_id}} ] }); let points = qdrant .scroll_all_points("_faces", filter, 1) .await .unwrap_or_default(); let trace_id: i32 = points .first() .and_then(|p| p["payload"]["trace_id"].as_i64()) .map(|t| t as i32) .ok_or(( StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Stranger not found"})), ))?; get_representative_face_inner(&state, &file_uuid, trace_id).await } async fn get_stranger_thumbnail( State(state): State, Path((file_uuid, stranger_id)): Path<(String, i32)>, ) -> Result)> { use crate::core::db::qdrant_db::QdrantDb; use serde_json::json; let qdrant = QdrantDb::new(); let filter = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "stranger_id", "match": {"value": stranger_id}} ] }); let points = qdrant .scroll_all_points("_faces", filter, 1) .await .unwrap_or_default(); let trace_id: i32 = points .first() .and_then(|p| p["payload"]["trace_id"].as_i64()) .map(|t| t as i32) .ok_or(( StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Stranger not found"})), ))?; get_trace_thumbnail_inner(&state, &file_uuid, trace_id).await } // ── TKG Node/Edge Query APIs ───────────────────────────────────── #[derive(Debug, Deserialize)] struct TkgNodesRequest { node_type: Option, page: Option, page_size: Option, } #[derive(Debug, Serialize)] struct TkgNodeInfo { id: i64, node_type: String, external_id: String, label: String, properties: serde_json::Value, } #[derive(Debug, Serialize)] struct TkgNodesResponse { success: bool, file_uuid: String, total: i64, page: i64, page_size: i64, nodes: Vec, } async fn query_tkg_nodes( State(state): State, Path(file_uuid): Path, Json(req): Json, ) -> Result, (StatusCode, Json)> { let nodes_table = t("tkg_nodes"); let page = req.page.unwrap_or(1).max(1); let page_size = req.page_size.unwrap_or(100).max(1).min(500); let offset = (page - 1) * page_size; let (where_clause, count_args, query_args) = if let Some(ref node_type) = req.node_type { ( "WHERE file_uuid = $1 AND node_type = $2".to_string(), vec![serde_json::json!([&file_uuid, node_type])], vec![serde_json::json!([ &file_uuid, node_type, page_size, offset ])], ) } else { ( "WHERE file_uuid = $1".to_string(), vec![serde_json::json!([&file_uuid])], vec![serde_json::json!([&file_uuid, page_size, offset])], ) }; let total: i64 = if let Some(ref node_type) = req.node_type { sqlx::query_scalar(&format!( "SELECT COUNT(*) FROM {} {}", nodes_table, where_clause )) .bind(&file_uuid) .bind(node_type) .fetch_one(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? } else { sqlx::query_scalar(&format!( "SELECT COUNT(*) FROM {} {}", nodes_table, where_clause )) .bind(&file_uuid) .fetch_one(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? }; let query = format!( "SELECT id, node_type, external_id, label, properties FROM {} {} ORDER BY id LIMIT ${} OFFSET ${}", nodes_table, where_clause, if req.node_type.is_some() { 3 } else { 2 }, if req.node_type.is_some() { 4 } else { 3 } ); let rows: Vec<(i64, String, String, String, serde_json::Value)> = if let Some(ref node_type) = req.node_type { sqlx::query_as(&query) .bind(&file_uuid) .bind(node_type) .bind(page_size) .bind(offset) .fetch_all(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? } else { sqlx::query_as(&query) .bind(&file_uuid) .bind(page_size) .bind(offset) .fetch_all(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? }; let nodes = rows .into_iter() .map( |(id, node_type, external_id, label, properties)| TkgNodeInfo { id, node_type, external_id, label, properties, }, ) .collect(); Ok(Json(TkgNodesResponse { success: true, file_uuid, total, page, page_size, nodes, })) } #[derive(Debug, Deserialize)] struct TkgEdgesRequest { edge_type: Option, source_type: Option, target_type: Option, page: Option, page_size: Option, } #[derive(Debug, Serialize)] struct TkgEdgeInfo { id: i64, edge_type: String, source_node_id: i64, target_node_id: i64, properties: serde_json::Value, } #[derive(Debug, Serialize)] struct TkgEdgesResponse { success: bool, file_uuid: String, total: i64, page: i64, page_size: i64, edges: Vec, } async fn query_tkg_edges( State(state): State, Path(file_uuid): Path, Json(req): Json, ) -> Result, (StatusCode, Json)> { let edges_table = t("tkg_edges"); let nodes_table = t("tkg_nodes"); let page = req.page.unwrap_or(1).max(1); let page_size = req.page_size.unwrap_or(100).max(1).min(500); let offset = (page - 1) * page_size; let mut conditions = vec!["e.file_uuid = $1".to_string()]; let mut param_idx = 2i32; let mut joins = String::new(); if let Some(ref edge_type) = req.edge_type { conditions.push(format!("e.edge_type = ${}", param_idx)); param_idx += 1; } if req.source_type.is_some() || req.target_type.is_some() { joins = format!( " JOIN {} sn ON e.source_node_id = sn.id JOIN {} tn ON e.target_node_id = tn.id", nodes_table, nodes_table ); } if let Some(ref source_type) = req.source_type { conditions.push(format!("sn.node_type = ${}", param_idx)); param_idx += 1; } if let Some(ref target_type) = req.target_type { conditions.push(format!("tn.node_type = ${}", param_idx)); param_idx += 1; } let where_clause = conditions.join(" AND "); let count_query = format!( "SELECT COUNT(*) FROM {} e {} WHERE {}", edges_table, joins, where_clause ); let total: i64 = { let mut q = sqlx::query_scalar::<_, i64>(&count_query).bind(&file_uuid); if let Some(ref edge_type) = req.edge_type { q = q.bind(edge_type); } if let Some(ref source_type) = req.source_type { q = q.bind(source_type); } if let Some(ref target_type) = req.target_type { q = q.bind(target_type); } q.fetch_one(state.db.pool()).await.map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? }; let query = format!( "SELECT e.id, e.edge_type, e.source_node_id, e.target_node_id, e.properties FROM {} e {} WHERE {} ORDER BY e.id LIMIT ${} OFFSET ${}", edges_table, joins, where_clause, param_idx, param_idx + 1 ); let rows: Vec<(i64, String, i64, i64, serde_json::Value)> = { let mut q = sqlx::query_as(&query).bind(&file_uuid); if let Some(ref edge_type) = req.edge_type { q = q.bind(edge_type); } if let Some(ref source_type) = req.source_type { q = q.bind(source_type); } if let Some(ref target_type) = req.target_type { q = q.bind(target_type); } q.bind(page_size) .bind(offset) .fetch_all(state.db.pool()) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })? }; let edges = rows .into_iter() .map( |(id, edge_type, source_node_id, target_node_id, properties)| TkgEdgeInfo { id, edge_type, source_node_id, target_node_id, properties, }, ) .collect(); Ok(Json(TkgEdgesResponse { success: true, file_uuid, total, page, page_size, edges, })) } #[derive(Debug, Serialize)] struct TkgNodeWithEdges { node: TkgNodeInfo, incoming_edges: Vec, outgoing_edges: Vec, } #[derive(Debug, Serialize)] struct TkgNodeDetailResponse { success: bool, file_uuid: String, node: Option, error: Option, } async fn get_tkg_node_detail( State(state): State, Path((file_uuid, node_id)): Path<(String, i64)>, ) -> Json { let nodes_table = t("tkg_nodes"); let edges_table = t("tkg_edges"); let node: Option<(i64, String, String, String, serde_json::Value)> = sqlx::query_as( &format!("SELECT id, node_type, external_id, label, properties FROM {} WHERE file_uuid = $1 AND id = $2", nodes_table) ) .bind(&file_uuid).bind(node_id) .fetch_optional(state.db.pool()).await.ok().flatten(); match node { Some((id, node_type, external_id, label, properties)) => { let incoming: Vec = sqlx::query_as( &format!("SELECT id, edge_type, source_node_id, target_node_id, properties FROM {} WHERE file_uuid = $1 AND target_node_id = $2", edges_table) ) .bind(&file_uuid).bind(node_id) .fetch_all(state.db.pool()).await.unwrap_or_default() .into_iter().map(|(id, edge_type, source_node_id, target_node_id, properties)| { TkgEdgeInfo { id, edge_type, source_node_id, target_node_id, properties } }).collect(); let outgoing: Vec = sqlx::query_as( &format!("SELECT id, edge_type, source_node_id, target_node_id, properties FROM {} WHERE file_uuid = $1 AND source_node_id = $2", edges_table) ) .bind(&file_uuid).bind(node_id) .fetch_all(state.db.pool()).await.unwrap_or_default() .into_iter().map(|(id, edge_type, source_node_id, target_node_id, properties)| { TkgEdgeInfo { id, edge_type, source_node_id, target_node_id, properties } }).collect(); Json(TkgNodeDetailResponse { success: true, file_uuid, node: Some(TkgNodeWithEdges { node: TkgNodeInfo { id, node_type, external_id, label, properties, }, incoming_edges: incoming, outgoing_edges: outgoing, }), error: None, }) } None => Json(TkgNodeDetailResponse { success: false, file_uuid, node: None, error: Some("Node not found".to_string()), }), } } // ── Rule 2 Ingest ─────────────────────────────────────────────────── #[derive(Serialize)] struct IngestRule2Response { success: bool, file_uuid: String, rule2_chunks: i64, vectorized_chunks: Option, error: Option, } async fn ingest_rule2( State(state): State, Path(file_uuid): Path, ) -> Result, (StatusCode, Json)> { use crate::core::chunk::rule2_ingest::ingest_rule2; use crate::core::db::qdrant_db::{QdrantDb, VectorPayload}; use crate::core::db::schema; use crate::core::embedding::Embedder; use tracing::info; let result = ingest_rule2(state.db.pool(), &file_uuid, None, None).await; match result { Ok(rule2_chunks) => { info!( "[Rule2API] {} relationship chunks created for {}", rule2_chunks, file_uuid ); // Auto-vectorize relationship chunks let embedder = Embedder::new("embeddinggemma-300m".to_string()); let qdrant = QdrantDb::new(); let pool = state.db.pool(); let chunk_table = schema::table_name("chunk"); let rows: Vec<(String, String, i64, i64, f64, f64)> = sqlx::query_as(&format!( "SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time \ FROM {} WHERE file_uuid = $1 AND chunk_type = 'relationship' \ AND embedding IS NULL AND (text_content IS NOT NULL AND text_content != '')", chunk_table )) .bind(&file_uuid) .fetch_all(pool) .await .map_err(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})), ) })?; let mut vectorized = 0i64; for (chunk_id, text, start_frame, end_frame, start_time, end_time) in &rows { if text.is_empty() { continue; } if let Ok(vector) = embedder.embed_document(&text).await { if state .db .store_vector(&chunk_id, &vector, &file_uuid) .await .is_ok() { let payload = VectorPayload { file_uuid: file_uuid.clone(), chunk_id: chunk_id.clone(), chunk_type: "relationship".to_string(), start_frame: *start_frame, end_frame: *end_frame, start_time: *start_time, end_time: *end_time, text: Some(text.clone()), }; if qdrant .upsert_vector(&chunk_id, &vector, payload) .await .is_ok() { vectorized += 1; } } } } Ok(Json(IngestRule2Response { success: true, file_uuid, rule2_chunks: rule2_chunks as i64, vectorized_chunks: Some(vectorized), error: None, })) } Err(e) => Ok(Json(IngestRule2Response { success: false, file_uuid, rule2_chunks: 0, vectorized_chunks: None, error: Some(e.to_string()), })), } } async fn delete_trace( State(state): State, Path((file_uuid, trace_id)): Path<(String, i32)>, Json(req): Json, ) -> Json { let hard_delete = req .get("hard_delete") .and_then(|v| v.as_bool()) .unwrap_or(false); let mode = req.get("mode").and_then(|v| v.as_str()).unwrap_or(""); if mode == "delete" { return delete_trace_permanent(state, &file_uuid, trace_id).await; } let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); if hard_delete { // "Hard delete" now means: restore trace to unassigned. // Keep _faces points, tkg_nodes rows and trace_profiles rows; // only reset the name/label back to the default so the trace // shows up in the unassigned/pending list again. Data is never // destroyed, so groups can be re-created later. let nodes_table = crate::core::db::schema::table_name("tkg_nodes"); let tp_table = crate::core::db::schema::table_name("trace_profiles"); let ext_id_face = format!("face_track_{}", trace_id); let ext_id_trace = format!("trace_{}", trace_id); let default_name = format!("Face Trace {}", trace_id); // 1. Save TKG nodes before reset (for undo) 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(); // 1b. Save trace profile before reset (for undo) let profile_snapshot: Vec<(i32, Option, serde_json::Value)> = sqlx::query_as(&format!( "SELECT trace_id, name, properties FROM {} WHERE file_uuid = $1 AND trace_id = $2", tp_table )) .bind(&file_uuid) .bind(trace_id) .fetch_all(state.db.pool()) .await .unwrap_or_default(); // 2. Reset tkg_nodes label to the unassigned default (rows preserved) let _ = sqlx::query(&format!( "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND (external_id = $3 OR external_id = $4)", nodes_table )) .bind(&default_name) .bind(&file_uuid) .bind(&ext_id_face) .bind(&ext_id_trace) .execute(state.db.pool()) .await; // 3. Reset trace_profiles name to the unassigned default (UPSERT so the // row is also created when it was missing) let _ = crate::core::db::schema::upsert_trace_profile( state.db.pool(), &file_uuid, trace_id, &default_name, None, ) .await; // 4. Keep _faces points intact (do NOT delete) // 5. Save operation snapshot for undo 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::>(), "trace_profiles": profile_snapshot.iter().map(|(tid, name, props)| { serde_json::json!({ "trace_id": tid, "name": name, "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, "unassigned": true, "message": format!("Trace {} restored to unassigned (data preserved)", trace_id), })) } else { // Soft delete: mark as deleted in Qdrant and TKG let filter = serde_json::json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}} ] }); let payload = serde_json::json!({ "status": "deleted" }); let qdrant_updated = match qdrant .update_payload_by_filter("_faces", filter.clone(), payload) .await { Ok(_) => { tracing::info!( "[delete_trace] Soft deleted (marked) trace {} in {}", trace_id, file_uuid ); true } Err(e) => { tracing::error!( "[delete_trace] Failed to mark Qdrant points as deleted: {}", e ); return Json(serde_json::json!({ "success": false, "error": format!("Failed to mark Qdrant points: {}", e) })); } }; // Update TKG node status 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!( "UPDATE {} SET properties = properties || $1::jsonb \ WHERE file_uuid = $2 AND node_type = 'face_track' AND (external_id = $3 OR external_id = $4)", nodes_table )) .bind(serde_json::json!({"status": "deleted"})) .bind(&file_uuid) .bind(&ext_id_face) .bind(&ext_id_trace) .execute(state.db.pool()) .await; let tkg_updated = match tkg_result { Ok(r) => r.rows_affected(), Err(e) => { tracing::error!("[delete_trace] Failed to mark TKG nodes as deleted: {}", e); 0 } }; Json(serde_json::json!({ "success": true, "file_uuid": file_uuid, "trace_id": trace_id, "hard_delete": false, "qdrant_marked": qdrant_updated, "tkg_nodes_marked": tkg_updated })) } } /// Permanently remove a trace (unrecoverable): Qdrant points + trace_profiles /// + tkg_nodes + on-disk files. Does NOT write to trace_operation_history (no undo). async fn delete_trace_permanent( state: crate::api::types::AppState, file_uuid: &str, trace_id: i32, ) -> Json { let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); let filter = serde_json::json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}} ] }); // 1. Count + delete Qdrant _faces points let points_count = qdrant .scroll_all_points("_faces", filter.clone(), 1000) .await .map(|pts| pts.len() as u64) .unwrap_or(0); let qdrant_ok = match qdrant.delete_points_by_filter("_faces", filter).await { Ok(_) => true, Err(e) => { tracing::error!( "[delete_trace] Failed to delete Qdrant points for trace {} in {}: {}", trace_id, file_uuid, e ); return Json(serde_json::json!({ "success": false, "error": format!("Failed to delete Qdrant points: {}", e) })); } }; // 2. Delete trace_profiles row let tp_table = crate::core::db::schema::table_name("trace_profiles"); let tp_deleted = sqlx::query(&format!( "DELETE FROM {} WHERE file_uuid = $1 AND trace_id = $2", tp_table )) .bind(file_uuid) .bind(trace_id) .execute(state.db.pool()) .await .map(|r| r.rows_affected()) .unwrap_or(0); // 3. Delete tkg_nodes face_track rows (face_track_N or trace_N) 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_deleted = sqlx::query(&format!( "DELETE 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) .execute(state.db.pool()) .await .map(|r| r.rows_affected()) .unwrap_or(0); // 4. Best-effort disk removal (output/{file_uuid}/trace_{trace_id}/ and // output/.faces/{file_uuid}/{trace_id}/) let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let mut files_removed = true; let mut disk_error: Option = None; let trace_dir = crate::core::file_profile::FaceTraceProfile::trace_dir( output_dir, file_uuid, trace_id as i64, ); if trace_dir.exists() { if let Err(e) = std::fs::remove_dir_all(&trace_dir) { files_removed = false; disk_error = Some(format!("trace dir: {}", e)); tracing::error!( "[delete_trace] Failed to remove {}: {}", trace_dir.display(), e ); } } let faces_dir = std::path::PathBuf::from(output_dir) .join(".faces") .join(file_uuid) .join(trace_id.to_string()); if faces_dir.exists() { if let Err(e) = std::fs::remove_dir_all(&faces_dir) { files_removed = false; disk_error = Some(format!("faces dir: {}", e)); tracing::error!( "[delete_trace] Failed to remove {}: {}", faces_dir.display(), e ); } } tracing::info!( "[delete_trace] Permanently deleted trace {} in {} (qdrant: {}, profiles: {}, tkg: {}, files: {})", trace_id, file_uuid, points_count, tp_deleted, tkg_deleted, files_removed ); Json(serde_json::json!({ "success": true, "file_uuid": file_uuid, "trace_id": trace_id, "mode": "delete", "qdrant_points_deleted": points_count, "trace_profiles_deleted": tp_deleted, "tkg_nodes_deleted": tkg_deleted, "files_removed": files_removed, "files_removed_error": disk_error, "qdrant_ok": qdrant_ok, })) } async fn merge_trace( State(state): State, Path((file_uuid, trace_id, target_trace_id)): Path<(String, i32, i32)>, ) -> Json { if trace_id == target_trace_id { return Json(serde_json::json!({ "success": false, "error": "Cannot merge trace into itself" })); } 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(); // Snapshot source trace profile before merge let tp_table = crate::core::db::schema::table_name("trace_profiles"); let profile_snapshot: Vec<(i32, Option, serde_json::Value)> = sqlx::query_as(&format!( "SELECT trace_id, name, properties FROM {} WHERE file_uuid = $1 AND trace_id = $2", tp_table )) .bind(&file_uuid) .bind(trace_id) .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::>(), "trace_profiles": profile_snapshot.iter().map(|(tid, name, props)| { serde_json::json!({ "trace_id": tid, "name": name, "properties": props, }) }).collect::>(), }); // Step 1: Update all face points from source trace to target trace let src_filter = serde_json::json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}} ] }); // Get count before update let points_count = qdrant .scroll_all_points("_faces", src_filter.clone(), 1) .await .map(|pts| pts.len()) .unwrap_or(0); // Update all source points to target trace_id let new_payload = serde_json::json!({ "trace_id": target_trace_id, "merged_from": trace_id }); let moved_count = match qdrant .update_payload_by_filter("_faces", src_filter, new_payload) .await { Ok(_) => points_count as u64, Err(e) => { return Json(serde_json::json!({ "success": false, "error": format!("Failed to update trace_id in Qdrant: {}", e) })); } }; // Step 2: Delete source TKG nodes 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 )) .bind(&file_uuid) .bind(&ext_id_face) .bind(&ext_id_trace) .execute(state.db.pool()) .await; let tkg_deleted = match tkg_result { Ok(r) => r.rows_affected(), Err(e) => { tracing::error!("[merge_trace] Failed to delete source TKG nodes: {}", e); 0 } }; // Step 2b: Delete source trace profile let _ = sqlx::query(&format!( "DELETE FROM {} WHERE file_uuid = $1 AND trace_id = $2", tp_table )) .bind(&file_uuid) .bind(trace_id) .execute(state.db.pool()) .await; // 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, "file_uuid": file_uuid, "source_trace_id": trace_id, "target_trace_id": target_trace_id, "points_moved": moved_count, "tkg_nodes_deleted": tkg_deleted })) } async fn restore_trace( State(state): State, Path((file_uuid, trace_id)): Path<(String, i32)>, ) -> Json { let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); // Restore semantics depend on the recorded operation: // - "hard_delete" now preserves data and only resets names, so undo // restores the original name/label from the operation snapshot. // - Legacy soft delete (status=deleted markers) is still cleared. let op_table = crate::core::db::schema::table_name("trace_operation_history"); let snapshot: Option<(i64, serde_json::Value)> = sqlx::query_as(&format!( "SELECT id, before_snapshot FROM {} \ WHERE file_uuid = $1 AND operation = 'hard_delete' AND is_undone = false \ AND before_snapshot->>'trace_id' = $2::text \ ORDER BY created_at DESC LIMIT 1", op_table )) .bind(&file_uuid) .bind(trace_id) .fetch_optional(state.db.pool()) .await .unwrap_or(None); if let Some((history_id, before_snapshot)) = snapshot { 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); // Restore tkg_nodes label 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(""); let props = node .get("properties") .cloned() .unwrap_or(serde_json::json!({"trace_id": trace_id})); if !label.is_empty() { let _ = sqlx::query(&format!( "UPDATE {} SET label = $1, properties = $2 \ WHERE file_uuid = $3 AND node_type = 'face_track' AND external_id = $4", nodes_table )) .bind(label) .bind(&props) .bind(&file_uuid) .bind(ext_id) .execute(state.db.pool()) .await; } } } // Restore trace_profiles name let profile_name = before_snapshot["trace_profiles"] .as_array() .and_then(|arr| { arr.iter() .find(|p| p["trace_id"].as_i64() == Some(trace_id as i64)) }) .and_then(|p| p["name"].as_str().map(String::from)) .unwrap_or_else(|| format!("Face Trace {}", trace_id)); let _ = crate::core::db::schema::upsert_trace_profile( state.db.pool(), &file_uuid, trace_id, &profile_name, None, ) .await; // Clear any legacy deleted status markers let legacy_filter = serde_json::json!({ "must": [ {"key": "file_uuid", "match": {"value": &file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}}, {"key": "status", "match": {"value": "deleted"}} ] }); let _ = qdrant .update_payload_by_filter( "_faces", legacy_filter, serde_json::json!({"status": serde_json::Value::Null}), ) .await; let _ = sqlx::query(&format!( "UPDATE {} SET properties = properties - 'status' \ 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) .execute(state.db.pool()) .await; // Mark snapshot as undone let _ = sqlx::query(&format!( "UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1", op_table )) .bind(history_id) .execute(state.db.pool()) .await; return Json(serde_json::json!({ "success": true, "file_uuid": file_uuid, "trace_id": trace_id, "name_restored": true, "restored_name": profile_name, "tkg_nodes_restored": tkg_snapshot_count(&before_snapshot), })); } // Legacy path: soft-deleted trace (status=deleted markers), clear them let filter = serde_json::json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}}, {"key": "status", "match": {"value": "deleted"}} ] }); let points_to_restore = qdrant .scroll_all_points("_faces", filter.clone(), 1) .await .map(|pts| pts.len()) .unwrap_or(0); if points_to_restore == 0 { return Json(serde_json::json!({ "success": false, "error": "Trace not found or not deleted" })); } let clear_payload = serde_json::json!({ "status": serde_json::Value::Null }); let qdrant_restored = match qdrant .update_payload_by_filter("_faces", filter, clear_payload) .await { Ok(_) => { tracing::info!( "[restore_trace] Restored {} Qdrant points for trace {} in {}", points_to_restore, trace_id, file_uuid ); true } Err(e) => { tracing::error!("[restore_trace] Failed to restore Qdrant points: {}", e); return Json(serde_json::json!({ "success": false, "error": format!("Failed to restore Qdrant points: {}", e) })); } }; // Restore TKG node: clear deleted status let nodes_table = crate::core::db::schema::table_name("tkg_nodes"); let ext_id_trace = format!("trace_{}", trace_id); let tkg_result = sqlx::query(&format!( "UPDATE {} SET properties = properties - 'status' \ WHERE file_uuid = $1 AND node_type = 'face_track' AND external_id = $2", nodes_table )) .bind(&file_uuid) .bind(&ext_id_trace) .execute(state.db.pool()) .await; let tkg_restored = match tkg_result { Ok(r) => r.rows_affected(), Err(e) => { tracing::error!("[restore_trace] Failed to restore TKG node: {}", e); 0 } }; Json(serde_json::json!({ "success": true, "file_uuid": file_uuid, "trace_id": trace_id, "name_restored": false, "qdrant_restored": qdrant_restored, "tkg_nodes_restored": tkg_restored })) } fn tkg_snapshot_count(before_snapshot: &serde_json::Value) -> usize { before_snapshot["tkg_nodes"] .as_array() .map(|a| a.len()) .unwrap_or(0) }