31d1b4050f
- Changed min_confidence from 50.0 to 0.5 (Vision uses 0.0-1.0 range) - Changed min_size from 32 to 1 (was filtering out all small faces) - Changed min_capture_quality from 25.0 to 0.25 - Fixes issue where all videos showed 0 faces detected Root cause: admin_config.rs used wrong defaults (50.0/32) instead of config.rs constants (0.5/1), causing Vision framework to filter out ALL faces because confidence threshold exceeded valid range. Verified: IMG_9449 now correctly detects 191 faces (was 0).
857 lines
29 KiB
Rust
857 lines
29 KiB
Rust
use anyhow::{Context, Result};
|
||
use serde::{Deserialize, Serialize};
|
||
use std::path::{Path, PathBuf};
|
||
|
||
/// 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,
|
||
|
||
// Single Frame Trace 配置
|
||
#[serde(default = "default_true")]
|
||
pub single_frame_trace_vlm_enabled: bool,
|
||
#[serde(default = "default_true")]
|
||
pub single_frame_trace_group_enabled: bool,
|
||
#[serde(default = "default_true")]
|
||
pub single_frame_trace_unassigned_enabled: bool,
|
||
|
||
// Single Trace Group 配置
|
||
#[serde(default = "default_true")]
|
||
pub single_trace_group_filter_enabled: bool,
|
||
}
|
||
|
||
fn default_true() -> bool { true }
|
||
|
||
impl FaceFilterSettings {
|
||
/// Load defaults from admin config (processor_config.face).
|
||
/// Falls back to hardcoded values if admin config unavailable.
|
||
pub fn defaults() -> Self {
|
||
let (min_confidence, min_size, min_capture_quality) =
|
||
crate::core::admin_config::get_face_filter_defaults();
|
||
|
||
Self {
|
||
min_confidence,
|
||
min_size,
|
||
min_capture_quality,
|
||
single_frame_trace_vlm_enabled: true,
|
||
single_frame_trace_group_enabled: true,
|
||
single_frame_trace_unassigned_enabled: true,
|
||
single_trace_group_filter_enabled: true,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[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<HistoryEntry>,
|
||
pub metadata: Option<MediaMetadata>,
|
||
pub key_frame: Option<String>, // filename: {uuid}.key_frame.jpg, video only
|
||
pub proxy_path: Option<String>, // 720p proxy path for 1080p+ videos
|
||
pub audio_track: Option<String>, // audio track classification: no_audio/silent_audio/music_only/speech_only/speech_with_music
|
||
pub face_filter: Option<FaceFilterSettings>,
|
||
#[serde(default)]
|
||
pub moment_interval: Option<f64>, // 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<String>,
|
||
}
|
||
|
||
#[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")?;
|
||
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<Self> {
|
||
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<Self> {
|
||
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<String> {
|
||
// 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<i64>,
|
||
pub avg_confidence: Option<f64>,
|
||
#[serde(default)]
|
||
pub best_confidence: Option<f64>,
|
||
#[serde(default)]
|
||
pub avg_capture_quality: Option<f64>,
|
||
#[serde(default)]
|
||
pub best_capture_quality: Option<f64>,
|
||
#[serde(default)]
|
||
pub avg_bbox: Option<serde_json::Value>,
|
||
#[serde(default)]
|
||
pub best_bbox: Option<serde_json::Value>,
|
||
pub key_frame: Option<String>, // filename: key_frame.jpg
|
||
pub key_face: Option<String>, // filename: key_face.jpg
|
||
pub status: String, // pending / bound / merged
|
||
#[serde(default)]
|
||
pub vlm_summary: Option<String>, // 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<f64>,
|
||
avg_capture_quality: Option<f64>,
|
||
best_confidence: f64,
|
||
best_capture_quality: f64,
|
||
avg_bbox: serde_json::Value,
|
||
best_bbox: Option<serde_json::Value>,
|
||
) -> 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(),
|
||
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);
|
||
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<Self> {
|
||
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_<number>`
|
||
if !dir_name.starts_with("trace_") || !path.is_dir() {
|
||
continue;
|
||
}
|
||
if dir_name[6..].parse::<i64>().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
|
||
}
|
||
|
||
#[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 {
|
||
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);
|
||
}
|
||
}
|