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
+2
View File
@@ -54,6 +54,8 @@ pub struct AsrSegment {
pub start_frame: Option<i64>,
pub end_frame: Option<i64>,
pub text: String,
#[serde(default)]
pub confidence: f64,
}
pub async fn process_asr(
+17 -1
View File
@@ -16,7 +16,23 @@ pub struct FaceClusterResult {
pub struct FaceClusterInfo {
pub cluster_id: String,
pub face_count: usize,
pub representative_face: Option<String>,
pub representative_face: Option<RepresentativeFace>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RepresentativeFace {
pub face_id: String,
pub confidence: f64,
pub frame: u64,
pub bbox: BoundingBox,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BoundingBox {
pub x: u64,
pub y: u64,
pub width: u64,
pub height: u64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
+111 -36
View File
@@ -97,7 +97,7 @@ fn parse_face_points(points: Vec<serde_json::Value>) -> Vec<FacePoint> {
.iter()
.filter_map(|p| {
let payload = &p["payload"];
let trace_id = payload["trace_id"].as_i64().filter(|&t| t > 0);
let trace_id = payload["trace_id"].as_i64().filter(|&t| t >= 0);
if trace_id.is_none() {
no_trace_id += 1;
return None;
@@ -519,6 +519,7 @@ fn load_face_pose_data(output_dir: &str, file_uuid: &str) -> Result<Vec<FacePose
/// Match a face from face_detections (frame, x, y, w, h) to its pose in face.json
/// Uses bbox center distance to find the best match when multiple faces per frame.
/// Returns None if no pose within threshold (unreliable match).
fn get_pose_for_face(
frame: i64,
x: f64,
@@ -527,6 +528,8 @@ fn get_pose_for_face(
h: f64,
poses: &[FacePose],
) -> Option<(f64, f64, f64)> {
const MAX_CENTER_DIST: f64 = 100.0; // Max center distance for valid match (pixels)
let cx = x + w / 2.0;
let cy = y + h / 2.0;
let mut best_dist = f64::MAX;
@@ -535,7 +538,7 @@ fn get_pose_for_face(
let pcx = p.x + p.w / 2.0;
let pcy = p.y + p.h / 2.0;
let dist = (cx - pcx).abs() + (cy - pcy).abs();
if dist < best_dist {
if dist < best_dist && dist < MAX_CENTER_DIST {
best_dist = dist;
result = Some((p.yaw, p.pitch, p.roll));
}
@@ -1130,6 +1133,7 @@ async fn build_face_track_nodes_from_qdrant(
sum_y: f64,
sum_w: f64,
sum_h: f64,
sum_confidence: f64,
frames: Vec<(i64, f64, f64, f64, f64)>, // (frame, x, y, w, h)
best_frame: i64,
best_confidence: f64,
@@ -1146,6 +1150,7 @@ async fn build_face_track_nodes_from_qdrant(
sum_y: 0.0,
sum_w: 0.0,
sum_h: 0.0,
sum_confidence: 0.0,
frames: vec![],
best_frame: 0,
best_confidence: 0.0,
@@ -1158,6 +1163,7 @@ async fn build_face_track_nodes_from_qdrant(
entry.sum_y += p.y;
entry.sum_w += p.w;
entry.sum_h += p.h;
entry.sum_confidence += p.confidence;
entry.frames.push((p.frame, p.x, p.y, p.w, p.h));
// Track best face (highest confidence)
if p.confidence > entry.best_confidence {
@@ -1218,14 +1224,8 @@ async fn build_face_track_nodes_from_qdrant(
"status": "pending",
});
// Save key frame and key face JPGs
// Save key_frame.jpg + key_face.jpg + trace_profile.json
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let face_dir = std::path::PathBuf::from(output_dir)
.join(".faces").join(file_uuid).join(&external_id);
let _ = std::fs::create_dir_all(&face_dir);
let key_frame_path = face_dir.join("key_frame.jpg");
let key_face_path = face_dir.join("key_face.jpg");
// Get video path from database
let video_path: Option<String> = sqlx::query_scalar(&format!(
@@ -1238,41 +1238,116 @@ async fn build_face_track_nodes_from_qdrant(
.ok()
.flatten();
// Extract key frame using ffmpeg
if !key_frame_path.exists() {
if let Some(ref vp) = video_path {
let timestamp = agg.best_frame as f64 / 30.0;
let _ = std::process::Command::new("ffmpeg")
.args(["-y", "-v", "quiet", "-ss", &timestamp.to_string(), "-i", vp])
.args(["-frames:v", "1", "-q:v", "2"])
.arg(key_frame_path.to_str().unwrap_or(""))
.output();
// Get actual fps for timestamp calculation
let actual_fps: f64 = sqlx::query_scalar(&format!(
"SELECT fps FROM {} WHERE file_uuid = $1",
crate::core::db::schema::table_name("videos")
))
.bind(file_uuid)
.fetch_optional(pool)
.await
.ok()
.flatten()
.unwrap_or(30.0);
let avg_confidence = if agg.frame_count > 0 {
agg.sum_confidence / agg.frame_count as f64
} else {
0.0
};
let mut trace_profile = crate::core::file_profile::FaceTraceProfile::new(
file_uuid,
*tid,
&label,
agg.frame_count,
agg.start_f,
agg.end_f,
Some(avg_confidence),
);
// Extract key_frame JPEG bytes via ffmpeg pipe
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
let timestamp = agg.best_frame as f64 / actual_fps;
let output = std::process::Command::new("ffmpeg")
.args([
"-y",
"-v",
"quiet",
"-ss",
&format!("{:.3}", timestamp),
"-i",
])
.arg(vp)
.args([
"-frames:v",
"1",
"-q:v",
"2",
"-f",
"image2pipe",
"-c:v",
"mjpeg",
"pipe:1",
])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if output.status.success() && !output.stdout.is_empty() {
Some(output.stdout)
} else {
None
}
}
});
// Crop key face from key frame using bbox
if !key_face_path.exists() && key_frame_path.exists() {
let bbox = &props["avg_bbox"];
let x = bbox["x"].as_i64().unwrap_or(0) as u32;
let y = bbox["y"].as_i64().unwrap_or(0) as u32;
let w = bbox["width"].as_i64().unwrap_or(100) as u32;
let h = bbox["height"].as_i64().unwrap_or(100) as u32;
let _ = std::process::Command::new("ffmpeg")
.args(["-y", "-v", "quiet", "-i", key_frame_path.to_str().unwrap_or("")])
.args(["-vf", &format!("crop={}:{}:{}:{}", w, h, x, y)])
.args(["-q:v", "2"])
.arg(key_face_path.to_str().unwrap_or(""))
.output();
}
// Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame)
let key_face_jpeg: Option<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
// Find bbox for best_frame from trace frames
let (_, bx, by, bw, bh) = agg.frames.iter().find(|(f, _, _, _, _)| *f == agg.best_frame)?;
let crop_filter = format!(
"crop={}:{}:{}:{}",
(*bw as i64).max(1),
(*bh as i64).max(1),
(*bx as i64).max(0),
(*by as i64).max(0),
);
let mut cmd = std::process::Command::new("ffmpeg");
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
.args(["-frames:v", "1", "-q:v", "2", "-vf"])
.arg(&crop_filter)
.args(["-f", "image2pipe", "-c:v", "mjpeg", "pipe:1"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null());
let mut child = cmd.spawn().ok()?;
if let Some(ref mut stdin) = child.stdin {
use std::io::Write;
let _ = stdin.write_all(kf);
}
let output = child.wait_with_output().ok()?;
if output.status.success() && !output.stdout.is_empty() {
Some(output.stdout)
} else {
None
}
});
// Update props with actual file paths
// Save all three files to output/{file_uuid}/{trace_id}/
let _ = trace_profile.save(
output_dir,
key_frame_jpeg.as_deref(),
key_face_jpeg.as_deref(),
);
// Update props with actual file paths (for DB properties JSONB)
let final_props = serde_json::json!({
"trace_id": tid,
"frame_count": agg.frame_count,
"start_frame": agg.start_f,
"end_frame": agg.end_f,
"key_frame": if key_frame_path.exists() { key_frame_path.to_string_lossy().to_string() } else { serde_json::Value::Null.to_string() },
"key_face": if key_face_path.exists() { key_face_path.to_string_lossy().to_string() } else { serde_json::Value::Null.to_string() },
"key_frame": agg.best_frame,
"key_face": agg.best_point_id.as_deref().unwrap_or(""),
"avg_bbox": props["avg_bbox"].clone(),
"avg_yaw": props["avg_yaw"].clone(),
"avg_pitch": props["avg_pitch"].clone(),