use anyhow::Result; use momentry_core::core::config; use momentry_core::core::db::{qdrant_db::QdrantDb, PostgresDb}; use serde_json::json; use std::path::PathBuf; use std::process::Command; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; #[tokio::main] async fn main() -> Result<()> { tracing_subscriber::fmt::init(); let db = PostgresDb::new(&config::DATABASE_URL).await?; let qdrant = QdrantDb::new(); // Find all files with traces let files: Vec = sqlx::query_scalar::<_, String>( "SELECT DISTINCT file_uuid FROM trace_profiles ORDER BY file_uuid", ) .fetch_all(db.pool()) .await?; println!("Found {} files to process", files.len()); let total_rebuilt = Arc::new(AtomicUsize::new(0)); let total_skipped = Arc::new(AtomicUsize::new(0)); let total_errors = Arc::new(AtomicUsize::new(0)); // Process files in parallel (4 at a time) let mut tasks = Vec::new(); for file_uuid in files { let qdrant = QdrantDb::new(); let rebuilt = total_rebuilt.clone(); let skipped = total_skipped.clone(); let errors = total_errors.clone(); let task = tokio::spawn(async move { match rebuild_file_thumbs(&qdrant, &file_uuid).await { Ok((r, s)) => { rebuilt.fetch_add(r, Ordering::Relaxed); skipped.fetch_add(s, Ordering::Relaxed); } Err(e) => { errors.fetch_add(1, Ordering::Relaxed); eprintln!(" ❌ {} : {}", file_uuid, e); } } }); tasks.push(task); // Limit concurrency to 4 if tasks.len() >= 4 { tasks.pop().unwrap().await?; } } // Wait for remaining tasks for task in tasks { task.await?; } println!( "\nDone! Rebuilt: {}, Skipped: {}, Errors: {}", total_rebuilt.load(Ordering::Relaxed), total_skipped.load(Ordering::Relaxed), total_errors.load(Ordering::Relaxed) ); Ok(()) } async fn rebuild_file_thumbs(qdrant: &QdrantDb, file_uuid: &str) -> Result<(usize, usize)> { // Get all face points for this file let filter = json!({ "must": [ {"key": "file_uuid", "match": {"value": file_uuid}} ] }); let points = qdrant.scroll_all_points("_faces", filter, 10000).await?; if points.is_empty() { return Ok((0, 0)); } // Get video path from DB let db = PostgresDb::new(&config::DATABASE_URL).await?; let video_path: Option = sqlx::query_scalar("SELECT file_path FROM videos WHERE file_uuid = $1") .bind(file_uuid) .fetch_optional(db.pool()) .await? .flatten(); let video_path = match video_path { Some(p) => p, None => return Ok((0, 0)), }; // Group by trace_id and find best face (highest confidence) let mut best_faces: std::collections::HashMap = std::collections::HashMap::new(); for p in &points { let payload = &p["payload"]; if let Some(tid) = payload["trace_id"].as_i64() { let conf = payload["confidence"].as_f64().unwrap_or(0.0); let frame = payload["frame"].as_i64().unwrap_or(0); let bbox = &payload["bbox"]; let x = bbox["x"].as_f64().unwrap_or(0.0); let y = bbox["y"].as_f64().unwrap_or(0.0); let w = bbox["width"].as_f64().unwrap_or(0.0); let h = bbox["height"].as_f64().unwrap_or(0.0); let entry = best_faces .entry(tid as i32) .or_insert((0.0, 0, 0.0, 0.0, 0.0, 0.0)); if conf > entry.0 { *entry = (conf, frame, x, y, w, h); } } } let output_dir = config::OUTPUT_DIR.as_str(); let mut rebuilt = 0; let mut skipped = 0; for (trace_id, (_conf, frame, x, y, w, h)) in &best_faces { let trace_dir = PathBuf::from(output_dir) .join(file_uuid) .join(format!("trace_{}", trace_id)); let key_face_path = trace_dir.join("key_face.jpg"); // Check if already exists and valid if key_face_path.exists() { let meta = std::fs::metadata(&key_face_path)?; if meta.len() > 100 { skipped += 1; continue; } } // Create directory std::fs::create_dir_all(&trace_dir)?; // Extract frame using select=eq(n,frame) for VFR compatibility let frame_num = *frame; let x_val = *x as i64; let y_val = *y as i64; let w_val = *w as i64; let h_val = *h as i64; let select_filter = format!("select=eq(n\\,{})", frame_num); // Use ffmpeg pipe to extract frame, then crop in one pipeline let size = (w_val.max(h_val) as f64 * 1.2) as i64; // 20% padding let half = size / 2; let crop_x = (x_val - half).max(0); let crop_y = (y_val - half).max(0); let output = Command::new("ffmpeg") .args([ "-y", "-v", "quiet", "-i", &video_path, "-vf", &format!( "select=eq(n\\,{}),crop={}:{}:{}:{}", frame_num, size, size, crop_x, crop_y ), "-frames:v", "1", "-q:v", "2", key_face_path.to_str().unwrap(), ]) .output(); match output { Ok(out) if out.status.success() && key_face_path.exists() => { rebuilt += 1; } _ => { // Fallback: extract frame first, then crop let tmp_frame = trace_dir.join("tmp_frame.jpg"); let _ = Command::new("ffmpeg") .args([ "-y", "-v", "quiet", "-i", &video_path, "-vf", &select_filter, "-frames:v", "1", "-q:v", "2", tmp_frame.to_str().unwrap(), ]) .output(); if tmp_frame.exists() { let _ = Command::new("ffmpeg") .args([ "-y", "-v", "quiet", "-i", tmp_frame.to_str().unwrap(), "-vf", &format!("crop={}:{}:{}:{}", size, size, crop_x, crop_y), "-q:v", "2", key_face_path.to_str().unwrap(), ]) .output(); let _ = std::fs::remove_file(&tmp_frame); if key_face_path.exists() { rebuilt += 1; } } } } } Ok((rebuilt, skipped)) }