use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; use crate::core::config::{FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_SIZE_DEFAULT}; /// Version of the file profile schema. const PROFILE_VERSION: &str = "1.0"; // ─── Data Types ─── /// Per-file face detection thresholds. `min_confidence` is 0–100 (%), /// `min_size` is px, `min_capture_quality` is 0–1. Mirrors `videos.face_filter` DB column. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FaceFilterSettings { pub min_confidence: f64, pub min_size: i32, #[serde(default)] pub min_capture_quality: f64, } impl FaceFilterSettings { /// Mirrors Apple Vision default detection thresholds (0.5 / 1px). /// Filter later for display; detect everything first. pub fn defaults() -> Self { Self { min_confidence: FACE_FILTER_CONFIDENCE_PCT_DEFAULT, min_size: FACE_MIN_SIZE_DEFAULT, min_capture_quality: 0.0, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FileProfile { pub version: String, pub file_uuid: String, pub file_name: String, pub file_type: String, pub birth: BirthInfo, pub current: CurrentInfo, pub history: Vec, pub metadata: Option, pub key_frame: Option, // filename: {uuid}.key_frame.jpg, video only pub proxy_path: Option, // 720p proxy path for 1080p+ videos pub audio_track: Option, // audio track classification: no_audio/silent_audio/music_only/speech_only/speech_with_music pub face_filter: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BirthInfo { pub mac_address: String, pub birthday: String, // RFC3339 pub original_path: String, pub original_filename: String, pub canonical_path: String, pub content_hash: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CurrentInfo { pub path: String, pub file_name: String, pub file_type: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HistoryEntry { pub action: String, pub timestamp: String, // RFC3339 pub path: String, pub file_name: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MediaMetadata { pub duration: f64, pub width: u32, pub height: u32, pub fps: f64, pub total_frames: u64, } // ─── Construction ─── impl FileProfile { /// Build a new profile from registration parameters. #[allow(clippy::too_many_arguments)] pub fn from_registration( file_uuid: &str, file_name: &str, file_type: &str, mac_address: &str, birthday: &str, canonical_path: &str, content_hash: &str, duration: f64, width: u32, height: u32, fps: f64, total_frames: u64, ) -> Self { let now = chrono::Utc::now().to_rfc3339(); let parent = Path::new(canonical_path) .parent() .map(|p| p.to_string_lossy().to_string()) .unwrap_or_default(); Self { version: PROFILE_VERSION.to_string(), file_uuid: file_uuid.to_string(), file_name: file_name.to_string(), file_type: file_type.to_string(), birth: BirthInfo { mac_address: mac_address.to_string(), birthday: birthday.to_string(), original_path: parent, original_filename: file_name.to_string(), canonical_path: canonical_path.to_string(), content_hash: if content_hash.is_empty() { None } else { Some(content_hash.to_string()) }, }, current: CurrentInfo { path: canonical_path.to_string(), file_name: file_name.to_string(), file_type: file_type.to_string(), }, history: vec![HistoryEntry { action: "registered".to_string(), timestamp: now, path: canonical_path.to_string(), file_name: file_name.to_string(), }], metadata: if duration > 0.0 || width > 0 || height > 0 { Some(MediaMetadata { duration, width, height, fps, total_frames, }) } else { None }, key_frame: None, proxy_path: None, audio_track: None, face_filter: None, } } /// Build a minimal profile for zombie files (missing path/name in DB). pub fn from_zombie(file_uuid: &str, file_type: &str, content_hash: &str) -> Self { let now = chrono::Utc::now().to_rfc3339(); Self { version: PROFILE_VERSION.to_string(), file_uuid: file_uuid.to_string(), file_name: String::new(), file_type: file_type.to_string(), birth: BirthInfo { mac_address: String::new(), birthday: String::new(), original_path: String::new(), original_filename: String::new(), canonical_path: String::new(), content_hash: if content_hash.is_empty() { None } else { Some(content_hash.to_string()) }, }, current: CurrentInfo { path: String::new(), file_name: String::new(), file_type: file_type.to_string(), }, history: vec![HistoryEntry { action: "recovered_zombie".to_string(), timestamp: now, path: String::new(), file_name: String::new(), }], metadata: None, key_frame: None, proxy_path: None, audio_track: None, face_filter: None, } } // ─── Persistence ─── /// Return the profile file path: `{output_dir}/{file_uuid}.profile.json` pub fn profile_path(output_dir: &str, file_uuid: &str) -> PathBuf { Path::new(output_dir).join(format!("{}.profile.json", file_uuid)) } /// Save profile to disk. pub fn save_to_disk(&self, output_dir: &str) -> Result<()> { let path = Self::profile_path(output_dir, &self.file_uuid); let json = serde_json::to_string_pretty(self).context("Failed to serialize file profile")?; std::fs::write(&path, json) .with_context(|| format!("Failed to write profile to {}", path.display()))?; tracing::debug!("[FileProfile] Saved profile for {}", self.file_uuid); Ok(()) } /// Load profile from disk. Returns `None` if file doesn't exist. pub fn load_from_disk(output_dir: &str, file_uuid: &str) -> Option { let path = Self::profile_path(output_dir, file_uuid); let content = std::fs::read_to_string(&path).ok()?; serde_json::from_str(&content).ok() } /// Load profile from disk, returning error if not found. pub fn load_or_error(output_dir: &str, file_uuid: &str) -> Result { let path = Self::profile_path(output_dir, file_uuid); let content = std::fs::read_to_string(&path) .with_context(|| format!("Profile not found: {}", path.display()))?; serde_json::from_str(&content).context("Failed to parse file profile") } // ─── Updates ─── /// Record a path/name change. Updates `current` and appends to `history`. pub fn update_current_path(&mut self, new_path: &str, new_name: &str) { let now = chrono::Utc::now().to_rfc3339(); // Only record if something actually changed if self.current.path == new_path && self.current.file_name == new_name { return; } self.history.push(HistoryEntry { action: "moved".to_string(), timestamp: now, path: new_path.to_string(), file_name: new_name.to_string(), }); self.current.path = new_path.to_string(); self.current.file_name = new_name.to_string(); } /// Set the key_frame (base64-encoded JPEG). pub fn set_key_frame(&mut self, key_frame: String) { self.key_frame = Some(key_frame); } /// Build a profile from existing DB data (for backfilling). #[allow(clippy::too_many_arguments)] pub fn from_db_record( file_uuid: &str, file_name: &str, file_path: &str, file_type: &str, content_hash: &str, duration: f64, width: u32, height: u32, fps: f64, total_frames: u64, ) -> Self { let now = chrono::Utc::now().to_rfc3339(); let parent = Path::new(file_path) .parent() .map(|p| p.to_string_lossy().to_string()) .unwrap_or_default(); // Try to extract birthday from probe.json if available let birthday = now.clone(); Self { version: PROFILE_VERSION.to_string(), file_uuid: file_uuid.to_string(), file_name: file_name.to_string(), file_type: file_type.to_string(), birth: BirthInfo { mac_address: String::new(), // Unknown for backfilled records birthday, original_path: parent, original_filename: file_name.to_string(), canonical_path: file_path.to_string(), content_hash: if content_hash.is_empty() { None } else { Some(content_hash.to_string()) }, }, current: CurrentInfo { path: file_path.to_string(), file_name: file_name.to_string(), file_type: file_type.to_string(), }, history: vec![HistoryEntry { action: "backfilled".to_string(), timestamp: now, path: file_path.to_string(), file_name: file_name.to_string(), }], metadata: if duration > 0.0 || width > 0 || height > 0 { Some(MediaMetadata { duration, width, height, fps, total_frames, }) } else { None }, key_frame: None, proxy_path: None, audio_track: None, face_filter: None, } } // ─── Key Frame Extraction ─── /// Key frame filename: `{file_uuid}.key_frame.jpg` pub fn key_frame_filename(file_uuid: &str) -> String { format!("{}.key_frame.jpg", file_uuid) } /// Extract a representative frame from a video file using ffmpeg. /// Saves as `{output_dir}/{file_uuid}.key_frame.jpg`. Returns filename on success. pub fn extract_key_frame( video_path: &str, duration: f64, output_dir: &str, file_uuid: &str, ) -> Option { // Seek to 10% of duration (or 1s if duration is 0) let seek_time = if duration > 0.0 { duration * 0.1 } else { 1.0 }; let out_path = std::path::Path::new(output_dir).join(Self::key_frame_filename(file_uuid)); let status = std::process::Command::new("ffmpeg") .args([ "-y", "-ss", &format!("{:.2}", seek_time), "-i", video_path, "-vframes", "1", "-vf", "scale=640:-1", "-q:v", "5", &out_path.to_string_lossy(), ]) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .ok()?; if status.success() && out_path.exists() { Some(Self::key_frame_filename(file_uuid)) } else { None } } } // ─── Face Trace Profile ─── /// Per-trace profile stored in `output/{file_uuid}/{trace_id}/trace_profile.json`. /// /// Bbox is NOT stored here — it's already in Qdrant `_faces` per-point. /// Original pixel values from Apple Vision are never modified. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FaceTraceProfile { pub version: String, pub file_uuid: String, pub trace_id: i64, pub label: String, pub frame_count: i64, pub start_frame: i64, pub end_frame: i64, #[serde(default)] pub best_frame: Option, pub avg_confidence: Option, #[serde(default)] pub best_confidence: Option, #[serde(default)] pub avg_capture_quality: Option, #[serde(default)] pub best_capture_quality: Option, #[serde(default)] pub avg_bbox: Option, #[serde(default)] pub best_bbox: Option, pub key_frame: Option, // filename: key_frame.jpg pub key_face: Option, // filename: key_face.jpg pub status: String, // pending / bound / merged } /// Recursively round all float numbers in a JSON value to 2 decimal places. /// Used for trace_profile.json output only; in-memory values are preserved. pub(crate) fn round_json_value(v: &serde_json::Value) -> serde_json::Value { match v { serde_json::Value::Number(n) => { if let Some(f) = n.as_f64() { let rounded = (f * 100.0).round() / 100.0; serde_json::Value::from(rounded) } else { v.clone() } } serde_json::Value::Array(items) => { serde_json::Value::Array(items.iter().map(round_json_value).collect()) } serde_json::Value::Object(map) => serde_json::Value::Object( map.iter() .map(|(k, val)| (k.clone(), round_json_value(val))) .collect(), ), _ => v.clone(), } } impl FaceTraceProfile { /// Directory: `output/{file_uuid}/{trace_id}/` pub fn trace_dir(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf { Path::new(output_dir) .join(file_uuid) .join(format!("trace_{}", trace_id)) } /// Profile file path: `output/{file_uuid}/{trace_id}/trace_profile.json` pub fn profile_path(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf { Self::trace_dir(output_dir, file_uuid, trace_id).join("trace_profile.json") } /// Build a new trace profile. #[allow(clippy::too_many_arguments)] pub fn new( file_uuid: &str, trace_id: i64, label: &str, frame_count: i64, start_frame: i64, end_frame: i64, best_frame: i64, avg_confidence: Option, avg_capture_quality: Option, best_confidence: f64, best_capture_quality: f64, avg_bbox: serde_json::Value, best_bbox: Option, ) -> Self { Self { version: PROFILE_VERSION.to_string(), file_uuid: file_uuid.to_string(), trace_id, label: label.to_string(), frame_count, start_frame, end_frame, best_frame: Some(best_frame), avg_confidence, best_confidence: Some(best_confidence), avg_capture_quality, best_capture_quality: Some(best_capture_quality), avg_bbox: Some(avg_bbox), best_bbox, key_frame: None, key_face: None, status: "pending".to_string(), } } /// Save profile + key_frame.jpg + key_face.jpg to `output/{file_uuid}/{trace_id}/`. /// `key_frame_jpeg` and `key_face_jpeg` are raw JPEG bytes (optional). pub fn save( &mut self, output_dir: &str, key_frame_jpeg: Option<&[u8]>, key_face_jpeg: Option<&[u8]>, ) -> Result<()> { let dir = Self::trace_dir(output_dir, &self.file_uuid, self.trace_id); std::fs::create_dir_all(&dir) .with_context(|| format!("Failed to create {}", dir.display()))?; // Write key_frame.jpg if let Some(jpeg) = key_frame_jpeg { let kf_path = dir.join("key_frame.jpg"); std::fs::write(&kf_path, jpeg) .with_context(|| format!("Failed to write {}", kf_path.display()))?; self.key_frame = Some("key_frame.jpg".to_string()); } else if dir.join("key_frame.jpg").exists() { // Extraction failed but file already exists on disk: preserve reference self.key_frame = Some("key_frame.jpg".to_string()); } // Write key_face.jpg if let Some(jpeg) = key_face_jpeg { let face_path = dir.join("key_face.jpg"); std::fs::write(&face_path, jpeg) .with_context(|| format!("Failed to write {}", face_path.display()))?; self.key_face = Some("key_face.jpg".to_string()); } else if dir.join("key_face.jpg").exists() { // Crop failed but file already exists on disk: preserve reference self.key_face = Some("key_face.jpg".to_string()); } // Write trace_profile.json let json = serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*self)?)) .context("Failed to serialize FaceTraceProfile")?; let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id); std::fs::write(&profile_path, json) .with_context(|| format!("Failed to write {}", profile_path.display()))?; Ok(()) } /// Load profile from disk. pub fn load(output_dir: &str, file_uuid: &str, trace_id: i64) -> Option { let path = Self::profile_path(output_dir, file_uuid, trace_id); let content = std::fs::read_to_string(path).ok()?; serde_json::from_str(&content).ok() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_profile_path() { let path = FileProfile::profile_path("/output", "abc123"); assert_eq!(path, PathBuf::from("/output/abc123.profile.json")); } #[test] fn test_from_registration() { let profile = FileProfile::from_registration( "abc123", "test.mp4", "video", "aa:bb:cc:dd:ee:ff", "2026-01-01T00:00:00Z", "/Users/test/video.mp4", "hash123", 120.0, 1920, 1080, 30.0, 3600, ); assert_eq!(profile.version, "1.0"); assert_eq!(profile.file_uuid, "abc123"); assert_eq!(profile.file_name, "test.mp4"); assert_eq!(profile.current.path, "/Users/test/video.mp4"); assert_eq!(profile.history.len(), 1); assert_eq!(profile.history[0].action, "registered"); assert!(profile.metadata.is_some()); assert!(profile.key_frame.is_none()); } #[test] fn test_update_current_path() { let mut profile = FileProfile::from_registration( "abc123", "test.mp4", "video", "aa:bb:cc:dd:ee:ff", "2026-01-01T00:00:00Z", "/Users/test/video.mp4", "hash123", 120.0, 1920, 1080, 30.0, 3600, ); profile.update_current_path("/Users/test/moved.mp4", "moved.mp4"); assert_eq!(profile.current.path, "/Users/test/moved.mp4"); assert_eq!(profile.current.file_name, "moved.mp4"); assert_eq!(profile.history.len(), 2); assert_eq!(profile.history[1].action, "moved"); } #[test] fn test_no_move_if_same_path() { let mut profile = FileProfile::from_registration( "abc123", "test.mp4", "video", "aa:bb:cc:dd:ee:ff", "2026-01-01T00:00:00Z", "/Users/test/video.mp4", "hash123", 120.0, 1920, 1080, 30.0, 3600, ); profile.update_current_path("/Users/test/video.mp4", "test.mp4"); assert_eq!(profile.history.len(), 1); // No new entry } #[test] fn test_zombie_profile() { let profile = FileProfile::from_zombie("zombie123", "video", "hash"); assert_eq!(profile.file_uuid, "zombie123"); assert!(profile.file_name.is_empty()); assert!(profile.birth.canonical_path.is_empty()); assert_eq!(profile.history[0].action, "recovered_zombie"); } #[test] fn test_serialization_roundtrip() { let profile = FileProfile::from_registration( "abc123", "test.mp4", "video", "aa:bb:cc:dd:ee:ff", "2026-01-01T00:00:00Z", "/Users/test/video.mp4", "hash123", 120.0, 1920, 1080, 30.0, 3600, ); let json = serde_json::to_string(&profile).unwrap(); let restored: FileProfile = serde_json::from_str(&json).unwrap(); assert_eq!(restored.file_uuid, profile.file_uuid); assert_eq!(restored.file_name, profile.file_name); assert_eq!(restored.history.len(), 1); } #[test] fn test_face_filter_roundtrip() { let mut profile = FileProfile::from_registration( "abc123", "test.mp4", "video", "aa:bb:cc:dd:ee:ff", "2026-01-01T00:00:00Z", "/Users/test/video.mp4", "hash123", 120.0, 1920, 1080, 30.0, 3600, ); assert!(profile.face_filter.is_none()); profile.face_filter = Some(FaceFilterSettings { min_confidence: 85.0, min_size: 96, min_capture_quality: 0.0, }); let json = serde_json::to_string(&profile).unwrap(); let restored: FileProfile = serde_json::from_str(&json).unwrap(); let ff = restored.face_filter.unwrap(); assert_eq!(ff.min_confidence, 85.0); assert_eq!(ff.min_size, 96); } #[test] fn test_old_profile_without_face_filter_deserializes() { let json = r#"{ "version": "1.0", "file_uuid": "abc123", "file_name": "test.mp4", "file_type": "video", "birth": { "mac_address": "aa:bb:cc:dd:ee:ff", "birthday": "2026-01-01T00:00:00Z", "original_path": "/Users/test", "original_filename": "test.mp4", "canonical_path": "/Users/test/video.mp4", "content_hash": "hash123" }, "current": { "path": "/Users/test/video.mp4", "file_name": "test.mp4", "file_type": "video" }, "history": [], "metadata": null, "key_frame": null, "proxy_path": null, "audio_track": null }"#; let profile: FileProfile = serde_json::from_str(json).unwrap(); assert_eq!(profile.file_uuid, "abc123"); assert!(profile.face_filter.is_none()); } #[test] fn test_face_filter_defaults_match_detection_defaults() { let d = FaceFilterSettings::defaults(); assert_eq!(d.min_confidence, 50.0); assert_eq!(d.min_size, 1); } }