use anyhow::{Context, Result}; use serde::{Deserialize, Serialize, Serializer}; use std::path::{Path, PathBuf}; /// Version of the file profile schema. const PROFILE_VERSION: &str = "1.0"; /// Helper function to serialize f64 with 2 decimal places fn serialize_f64_2dec(value: &f64, serializer: S) -> Result { serializer.serialize_f64((*value * 100.0).round() / 100.0) } // ─── Data Types ─── /// UI filter rules for face display #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UiFilterRules { /// Minimum confidence threshold (0.0–1.0) pub min_confidence: f64, /// Maximum confidence threshold (0.0–1.0) pub max_confidence: f64, /// Minimum bounding box size in pixels pub min_bbox_size: i32, /// Maximum bounding box size in pixels pub max_bbox_size: i32, /// Face detection source filter: "apple_vision", "mediapipe", or "all" pub source: String, /// Backend status filter: "accept", "review", "reject", or "all" pub backend_status: String, } impl Default for UiFilterRules { fn default() -> Self { Self { min_confidence: 0.5, max_confidence: 1.0, min_bbox_size: 80, max_bbox_size: 10000, source: "all".to_string(), backend_status: "all".to_string(), } } } /// Processing thresholds for face detection #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProcessingThresholds { /// Minimum capture quality for face processing (0.0–1.0) pub min_capture_quality: f64, } impl Default for ProcessingThresholds { fn default() -> Self { Self { min_capture_quality: 0.0, } } } /// Trace processing settings #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TraceSettings { /// Enable VLM for single-frame traces #[serde(default = "default_true")] pub single_frame_trace_vlm_enabled: bool, /// Enable group display for single-frame traces #[serde(default = "default_true")] pub single_frame_trace_group_enabled: bool, /// Enable unassigned face display for single-frame traces #[serde(default = "default_true")] pub single_frame_trace_unassigned_enabled: bool, /// Enable filtering for single-trace groups #[serde(default = "default_true")] pub single_trace_group_filter_enabled: bool, } impl Default for TraceSettings { fn default() -> Self { Self { single_frame_trace_vlm_enabled: true, single_frame_trace_group_enabled: true, single_frame_trace_unassigned_enabled: true, single_trace_group_filter_enabled: true, } } } fn default_true() -> bool { true } /// Per-file face detection thresholds (V2 unified structure). /// Stores three categories: UI filter rules, processing thresholds, and trace settings. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FaceFilterSettings { pub version: String, pub ui_filter_rules: UiFilterRules, pub processing_thresholds: ProcessingThresholds, pub trace_settings: TraceSettings, } impl FaceFilterSettings { /// Create new settings with defaults pub fn new() -> Self { Self { version: "1.0".to_string(), ui_filter_rules: UiFilterRules::default(), processing_thresholds: ProcessingThresholds::default(), trace_settings: TraceSettings::default(), } } /// Load defaults from admin config (processor_config.face). /// Falls back to hardcoded values if admin config unavailable. pub fn defaults() -> Self { let (min_confidence_legacy, min_size, min_capture_quality) = crate::core::admin_config::get_face_filter_defaults(); // Convert legacy 0-100 confidence to 0.0-1.0 let min_confidence = min_confidence_legacy / 100.0; Self { version: "1.0".to_string(), ui_filter_rules: UiFilterRules { min_confidence, max_confidence: 1.0, min_bbox_size: min_size, max_bbox_size: 10000, source: "all".to_string(), backend_status: "all".to_string(), }, processing_thresholds: ProcessingThresholds { min_capture_quality, }, trace_settings: TraceSettings::default(), } } /// Convert from legacy format (0-100 confidence) to new format (0.0-1.0) pub fn from_legacy( min_confidence: f64, min_size: i32, min_capture_quality: f64, single_frame_trace_vlm_enabled: bool, single_frame_trace_group_enabled: bool, single_frame_trace_unassigned_enabled: bool, single_trace_group_filter_enabled: bool, ) -> Self { Self { version: "1.0".to_string(), ui_filter_rules: UiFilterRules { min_confidence: min_confidence / 100.0, // Convert 0-100 to 0.0-1.0 max_confidence: 1.0, min_bbox_size: min_size, max_bbox_size: 10000, source: "all".to_string(), backend_status: "all".to_string(), }, processing_thresholds: ProcessingThresholds { min_capture_quality, }, trace_settings: TraceSettings { single_frame_trace_vlm_enabled, single_frame_trace_group_enabled, single_frame_trace_unassigned_enabled, single_trace_group_filter_enabled, }, } } } impl Default for FaceFilterSettings { fn default() -> Self { Self::new() } } #[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, #[serde(default)] pub moment_interval: Option, // seconds per moment window, default 10.0 } #[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, moment_interval: 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, moment_interval: 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")?; let json = crate::core::json_debug::append_debug_footer(json, &path); 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, moment_interval: 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, #[serde(default)] pub label: Option, 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 #[serde(default)] pub vlm_summary: Option, // VLM free-text summary of key_frame } /// Recursively round float numbers in a JSON value to 2 decimal places. /// Integer numbers are preserved as-is (no `.0` suffix). /// 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 n.is_i64() || n.is_u64() { // Whole numbers keep their integer representation (no `.0`). v.clone() } else 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: Some(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(), vlm_summary: None, } } /// 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); let json = crate::core::json_debug::append_debug_footer(json, &profile_path); 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() } } /// On-disk face artifact counts for a file, used for completion transparency. /// `expected_traces` is the authoritative count from DB/Qdrant; the *_files /// fields reflect what actually exists on disk (TKG build may still be running). #[derive(Debug, Clone, Default, Serialize)] pub struct FaceArtifactsCounts { /// Authoritative number of traces for this file (DB trace_profiles count). pub expected_traces: i64, /// Number of `trace_N` directories present on disk. pub trace_dirs: i64, /// Number of `trace_profile.json` files present on disk. pub trace_profiles: i64, /// Number of `key_frame.jpg` files present on disk. pub key_frames: i64, /// Number of `key_face.jpg` files present on disk. pub key_faces: i64, } /// Scan `output/{file_uuid}/` once and count trace dirs + required artifacts. /// Returns all-zero counts when the directory does not exist (not yet processed). pub fn count_face_artifacts(output_dir: &str, file_uuid: &str) -> FaceArtifactsCounts { let mut counts = FaceArtifactsCounts::default(); let base = Path::new(output_dir).join(file_uuid); let entries = match std::fs::read_dir(&base) { Ok(e) => e, Err(_) => return counts, }; for entry in entries.flatten() { let path = entry.path(); let dir_name = match path.file_name().and_then(|n| n.to_str()) { Some(n) => n, None => continue, }; // Only count directories named `trace_` if !dir_name.starts_with("trace_") || !path.is_dir() { continue; } if dir_name[6..].parse::().is_err() { continue; } counts.trace_dirs += 1; if path.join("trace_profile.json").is_file() { counts.trace_profiles += 1; } if path.join("key_frame.jpg").is_file() { counts.key_frames += 1; } if path.join("key_face.jpg").is_file() { counts.key_faces += 1; } } counts } // ─── Scene VLM Profile ─── /// Scene VLM profile stored in `output/{file_uuid}.scenes.json`. /// Contains selected scene key frames and their VLM analysis results. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SceneProfile { pub version: String, pub file_uuid: String, #[serde(skip_serializing_if = "Option::is_none")] pub processor: Option, pub status: SceneStatus, pub video_info: VideoInfo, pub config: SceneConfig, pub total_scenes: usize, pub created_at: chrono::DateTime, pub updated_at: chrono::DateTime, pub scenes: Vec, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum SceneStatus { Pending, Ready, Processing, Completed, Failed, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct VideoInfo { pub duration_sec: f64, pub fps: f64, pub width: u32, pub height: u32, pub total_frames: u32, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SceneConfig { pub interval_sec: u32, pub use_cuts: bool, pub use_faces: bool, pub quality_metric: String, pub samples_per_interval: usize, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct VlmTag { pub en: String, pub local: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum VlmTagValue { Structured(VlmTag), String(String), } impl VlmTagValue { pub fn en(&self) -> &str { match self { Self::Structured(t) => &t.en, Self::String(s) => s, } } pub fn local(&self) -> &str { match self { Self::Structured(t) => &t.local, Self::String(_) => "", } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SceneFrame { pub index: usize, pub filename: String, #[serde(serialize_with = "serialize_f64_2dec")] pub timestamp_sec: f64, pub frame_number: u32, pub selection_reason: SelectionReason, #[serde(skip_serializing_if = "Option::is_none")] pub quality_score: Option, #[serde(skip_serializing_if = "Option::is_none")] pub quality_source: Option, #[serde(skip_serializing_if = "Option::is_none")] pub scene_info: Option, pub face_count: u32, #[serde(default)] pub person_traces: Vec, pub has_cut: bool, pub cut_count: u32, pub vlm_status: VlmStatus, #[serde(skip_serializing_if = "Option::is_none")] pub vlm_description: Option, #[serde(skip_serializing_if = "Option::is_none")] pub vlm_description_localized: Option, #[serde(skip_serializing_if = "Option::is_none")] pub vlm_scene_type: Option, #[serde(skip_serializing_if = "Option::is_none")] pub vlm_location: Option, #[serde(default)] pub vlm_objects: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub vlm_attributes: Option, #[serde(default)] pub vlm_tags: Vec, pub embedding_status: EmbeddingStatus, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SceneInfo { pub scene_id: u32, pub scene_start_sec: f64, pub scene_end_sec: f64, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum SelectionReason { BestBlur, PreCutBestBlur, PostCutBestBlur, SceneStart, Default, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum VlmStatus { Pending, Processing, Completed, Failed, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum EmbeddingStatus { Pending, Completed, Failed, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SceneAttributes { #[serde(skip_serializing_if = "Option::is_none")] pub lighting: Option, #[serde(skip_serializing_if = "Option::is_none")] pub weather: Option, #[serde(skip_serializing_if = "Option::is_none")] pub time_of_day: Option, } impl SceneProfile { pub fn new(file_uuid: &str, video_info: VideoInfo, config: SceneConfig) -> Self { use crate::core::processor::{ProcessorInfo, PROCESSOR_VERSION}; Self { version: "1.0".to_string(), file_uuid: file_uuid.to_string(), processor: Some(ProcessorInfo { name: "scene_vlm".to_string(), tool: "ffmpeg_scene_detect".to_string(), version: PROCESSOR_VERSION.to_string(), config: Some(serde_json::to_value(&config).unwrap_or(serde_json::json!({}))), }), status: SceneStatus::Pending, video_info, config, total_scenes: 0, created_at: chrono::Utc::now(), updated_at: chrono::Utc::now(), scenes: Vec::new(), } } pub fn scenes_path(output_dir: &str, file_uuid: &str) -> PathBuf { Path::new(output_dir).join(format!("{}.scenes.json", file_uuid)) } pub fn scenes_dir(output_dir: &str, file_uuid: &str) -> PathBuf { Path::new(output_dir).join(file_uuid).join("scenes") } pub fn scene_frame_path(output_dir: &str, file_uuid: &str, filename: &str) -> PathBuf { Self::scenes_dir(output_dir, file_uuid).join(filename) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_count_face_artifacts() { let tmp = std::env::temp_dir().join("momentry_count_face_artifacts_test"); let base = tmp.join("fileabc"); let t0 = base.join("trace_0"); let t1 = base.join("trace_1"); let t2 = base.join("trace_2"); std::fs::create_dir_all(&t0).unwrap(); std::fs::create_dir_all(&t1).unwrap(); std::fs::create_dir_all(&t2).unwrap(); // trace_0: full set std::fs::write(t0.join("trace_profile.json"), "{}").unwrap(); std::fs::write(t0.join("key_frame.jpg"), b"x").unwrap(); std::fs::write(t0.join("key_face.jpg"), b"x").unwrap(); // trace_1: profile only (key_frame/key_face missing) std::fs::write(t1.join("trace_profile.json"), "{}").unwrap(); // trace_2: empty dir // non-trace dir should be ignored std::fs::create_dir_all(base.join("not_a_trace")).unwrap(); let c = count_face_artifacts(tmp.to_str().unwrap(), "fileabc"); assert_eq!(c.trace_dirs, 3); assert_eq!(c.trace_profiles, 2); assert_eq!(c.key_frames, 1); assert_eq!(c.key_faces, 1); assert_eq!(c.expected_traces, 0); // Missing file dir -> all zeros let c0 = count_face_artifacts(tmp.to_str().unwrap(), "does_not_exist"); assert_eq!(c0.trace_dirs, 0); assert_eq!(c0.key_frames, 0); let _ = std::fs::remove_dir_all(&tmp); } #[test] fn test_profile_path() { let path = FileProfile::profile_path("/output", "abc123"); assert_eq!(path, PathBuf::from("/output/abc123.profile.json")); } #[test] fn test_round_json_value_preserves_integers() { let v = serde_json::json!({ "trace_id": 4560, "frame_count": 21, "start_frame": 150221, "avg_confidence": 0.781234, "best_confidence": 0.81, "bbox": {"x": 336, "y": 71, "width": 113, "height": 113} }); let rounded = round_json_value(&v); // Integers stay integers (no `.0` suffix) assert_eq!(rounded["trace_id"], serde_json::json!(4560)); assert!(rounded["trace_id"].is_i64()); assert_eq!(rounded["frame_count"], serde_json::json!(21)); assert!(rounded["frame_count"].is_i64()); assert_eq!(rounded["start_frame"], serde_json::json!(150221)); assert!(rounded["start_frame"].is_i64()); assert_eq!(rounded["bbox"]["x"], serde_json::json!(336)); assert!(rounded["bbox"]["x"].is_i64()); // Floats rounded to 2 decimals assert_eq!(rounded["avg_confidence"], serde_json::json!(0.78)); assert!(rounded["avg_confidence"].is_f64()); assert_eq!(rounded["best_confidence"], serde_json::json!(0.81)); assert!(rounded["best_confidence"].is_f64()); } #[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 { version: "1.0".to_string(), ui_filter_rules: UiFilterRules { min_confidence: 0.85, max_confidence: 1.0, min_bbox_size: 96, max_bbox_size: 10000, source: "all".to_string(), backend_status: "all".to_string(), }, processing_thresholds: ProcessingThresholds { min_capture_quality: 0.0, }, trace_settings: TraceSettings { single_frame_trace_vlm_enabled: true, single_frame_trace_group_enabled: true, single_frame_trace_unassigned_enabled: true, single_trace_group_filter_enabled: true, }, }); 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.version, "1.0"); assert_eq!(ff.ui_filter_rules.min_confidence, 0.85); assert_eq!(ff.ui_filter_rules.min_bbox_size, 96); assert_eq!(ff.trace_settings.single_frame_trace_vlm_enabled, true); } #[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.version, "1.0"); assert_eq!(d.ui_filter_rules.min_confidence, 0.5); // Converted from 50.0 (0-100 scale) assert_eq!(d.ui_filter_rules.max_confidence, 1.0); assert_eq!(d.ui_filter_rules.min_bbox_size, 1); assert_eq!(d.ui_filter_rules.source, "all"); assert_eq!(d.trace_settings.single_frame_trace_vlm_enabled, true); } #[test] fn test_face_filter_new_method() { let d = FaceFilterSettings::new(); assert_eq!(d.version, "1.0"); assert_eq!(d.ui_filter_rules.min_confidence, 0.5); assert_eq!(d.ui_filter_rules.max_confidence, 1.0); assert_eq!(d.ui_filter_rules.min_bbox_size, 80); assert_eq!(d.ui_filter_rules.max_bbox_size, 10000); assert_eq!(d.ui_filter_rules.source, "all"); assert_eq!(d.ui_filter_rules.backend_status, "all"); assert_eq!(d.processing_thresholds.min_capture_quality, 0.0); } #[test] fn test_face_filter_from_legacy() { let ff = FaceFilterSettings::from_legacy( 75.0, // 0-100 scale 100, 0.5, true, true, true, true, ); assert_eq!(ff.version, "1.0"); assert_eq!(ff.ui_filter_rules.min_confidence, 0.75); // Converted to 0-1 scale assert_eq!(ff.ui_filter_rules.min_bbox_size, 100); assert_eq!(ff.processing_thresholds.min_capture_quality, 0.5); } }