fix: face group name read consistency, sync_file_status fix, cleanup ghost records, identity_agent replaced with face_dedup

- get_face_groups_handler: COALESCE(tp.name, tn.label) for name consistency
- sync_file_status: compare JSON vs pre_chunks (not chunk table)
- face consistency: compare frames.len() not total_faces
- cleanup 2 ghost records with NULL file_name/file_path
- replace identity_agent with face_dedup in pipeline stages
- remove identity_agent_api.rs and all references
- update required_processors to match actual processors
- update AGENTS.md with team responsibilities
- add Studio pipeline changes documentation
This commit is contained in:
Accusys
2026-07-27 02:15:51 +08:00
parent fcdeab82e6
commit 39a2cbc65b
118 changed files with 19386 additions and 2964 deletions
+559
View File
@@ -0,0 +1,559 @@
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 ───
#[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
}
#[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,
}
}
/// 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,
}
}
// ─── 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,
}
}
// ─── 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,
pub avg_confidence: Option<f64>,
pub key_frame: Option<String>, // filename: key_frame.jpg
pub key_face: Option<String>, // filename: key_face.jpg
pub status: String, // pending / bound / merged
}
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,
avg_confidence: Option<f64>,
) -> 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,
avg_confidence,
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());
}
// 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());
}
// Write trace_profile.json
let json =
serde_json::to_string_pretty(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()
}
}
#[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);
}
}