feat: Face JSON v2 schema - add schema_version, bbox x2/y2/center, keep embeddings, update clustering

This commit is contained in:
Accusys
2026-11-02 14:34:02 +08:00
parent 2fca49b120
commit 5d18183d82
566 changed files with 321788 additions and 1662 deletions
+135 -53
View File
@@ -593,6 +593,29 @@ pub async fn merge_groups_handler(
}
}
// Sync Qdrant person_id for all merged traces
if !matching_trace_ids.is_empty() {
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
let trace_filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": req.file_uuid}},
{"key": "trace_id", "match": {"any": matching_trace_ids.iter().map(|id| serde_json::json!(*id)).collect::<Vec<_>>()}}
]
});
let update_payload = serde_json::json!({
"person_id": req.target_group_name
});
if let Err(e) = qdrant
.update_payload_by_filter("_faces", trace_filter, update_payload)
.await
{
tracing::error!("[MergeGroups] Qdrant update error: {}", e);
// Don't fail the whole operation if Qdrant update fails
} else {
tracing::info!("[MergeGroups] Qdrant person_id updated for {} traces", matching_trace_ids.len());
}
}
match nodes_result {
Ok(nodes_res) => {
let nodes_updated = nodes_res.rows_affected();
@@ -1436,6 +1459,7 @@ pub struct ClusterResultsFace {
pub face_id: String,
pub confidence: f64,
pub cluster_id: Option<i32>,
pub trace_id: Option<i32>,
}
#[derive(Debug, Serialize)]
@@ -1493,9 +1517,10 @@ pub async fn get_cluster_results_handler(
.and_then(|v| serde_json::from_value(v).ok())
.unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults);
// 1. Build face groups (same grouping logic as face-groups handler)
// 1. Build face groups from TKG nodes (primary source)
// Use tkg_nodes.label as primary name, fallback to trace_profiles.name
let rows: Vec<(String, i32, Option<i32>)> = sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, \
"SELECT COALESCE(tn.label, tp.name) as name, \
COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id, \
tp.frame_count \
FROM {} tn \
@@ -1529,6 +1554,11 @@ pub async fn get_cluster_results_handler(
// User-named groups (even with 1 trace) are kept.
let mut filtered_groups: HashMap<String, Vec<i32>> = HashMap::new();
for (name, trace_ids) in groups {
// Filter out empty names and auto-generated trace names
if name.is_empty() || name.starts_with("Face Trace ") || name.starts_with("Trace ") {
continue;
}
let is_auto_name = name.starts_with("Person_");
let should_filter =
settings.trace_settings.single_trace_group_filter_enabled && trace_ids.len() == 1 && is_auto_name;
@@ -1538,10 +1568,55 @@ pub async fn get_cluster_results_handler(
}
}
// trace_id -> cluster_id mapping for frame faces
let mut trace_to_cluster: HashMap<i32, i32> = HashMap::new();
// Fallback: if no groups from DB, load from face_cluster.json
let mut fallback_from_json = filtered_groups.is_empty();
if fallback_from_json {
tracing::info!("[ClusterResults] No groups from DB, loading from face_cluster.json");
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
if let Ok(content) = std::fs::read_to_string(&fc_path) {
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
// Extract clusters
if let Some(clusters) = data.get("clusters").and_then(|c| c.as_array()) {
for c in clusters {
if let Some(cid) = c.get("cluster_id").and_then(|v| v.as_str()) {
// Use cluster_id as name
let name = cid.to_string();
let trace_ids: Vec<i32> = Vec::new();
filtered_groups.insert(name, trace_ids);
}
}
tracing::info!("[ClusterResults] Loaded {} clusters from face_cluster.json", clusters.len());
}
// Extract trace_ids from frames
if let Some(frames) = data.get("frames").and_then(|f| f.as_array()) {
for frame in frames {
if let Some(faces) = frame.get("faces").and_then(|f| f.as_array()) {
for face in faces {
// Use cluster_id from face_cluster.json (not person_id)
if let (Some(trace_id), Some(cluster_id)) = (
face.get("trace_id").and_then(|v| v.as_i64()),
face.get("cluster_id").and_then(|v| v.as_str()),
) {
let trace_id = trace_id as i32;
if let Some(trace_ids) = filtered_groups.get_mut(cluster_id) {
if !trace_ids.contains(&trace_id) {
trace_ids.push(trace_id);
}
}
}
}
}
}
tracing::info!("[ClusterResults] Extracted trace_ids from frames");
}
}
}
}
// Load face_cluster.json for similarity data
// Load face_cluster.json for similarity data only (not for adding clusters)
let cluster_similarity: HashMap<String, ClusterSimilarityInfo> = {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
@@ -1576,14 +1651,17 @@ pub async fn get_cluster_results_handler(
map
};
// Build trace_id -> name mapping before consuming filtered_groups
let trace_to_name: HashMap<i32, String> = filtered_groups
.iter()
.flat_map(|(name, trace_ids)| trace_ids.iter().map(|tid| (*tid, name.clone())))
.collect();
let face_groups: Vec<ClusterResultsGroup> = filtered_groups
.into_iter()
.enumerate()
.map(|(idx, (name, trace_ids))| {
let group_id = (idx + 1) as i32;
for tid in &trace_ids {
trace_to_cluster.insert(*tid, group_id);
}
// Try to find similarity data for this cluster
let similarity = cluster_similarity.get(&name).cloned();
ClusterResultsGroup {
@@ -1613,53 +1691,57 @@ pub async fn get_cluster_results_handler(
})?
.unwrap_or(0.0);
// 3. Scroll _faces for this file and group by frame
let face_filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": &file_uuid}}
]
});
let points = state
.qdrant
.scroll_all_points("_faces", face_filter, 1000)
.await
.map_err(|e| {
tracing::error!("[ClusterResults] Qdrant scroll failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let mut frames_map: HashMap<i64, Vec<ClusterResultsFace>> = HashMap::new();
for p in &points {
let payload = &p["payload"];
let frame = payload["frame"].as_i64().unwrap_or(0);
let trace_id = payload["trace_id"].as_i64().map(|t| t as i32).unwrap_or(0);
let point_id = p["id"].as_u64().unwrap_or(0);
let confidence = payload["confidence"].as_f64().unwrap_or(0.0);
// Only include faces that belong to a group (Studio skips unassigned)
let cluster_id = trace_to_cluster.get(&trace_id).copied();
if cluster_id.is_none() {
continue;
// 4. Build frames from face_cluster.json directly
let mut frames: Vec<ClusterResultsFrame> = Vec::new();
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
if let Ok(content) = std::fs::read_to_string(&fc_path) {
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(fc_frames) = data.get("frames").and_then(|f| f.as_array()) {
for fc_frame in fc_frames {
if let (Some(frame_num), Some(faces)) = (
fc_frame.get("frame").and_then(|f| f.as_i64()),
fc_frame.get("faces").and_then(|f| f.as_array()),
) {
let mut cluster_faces: Vec<ClusterResultsFace> = Vec::new();
for face in faces {
if let (Some(face_id), Some(trace_id), Some(confidence)) = (
face.get("face_id").and_then(|f| f.as_str()),
face.get("trace_id").and_then(|f| f.as_i64()),
face.get("confidence").and_then(|f| f.as_f64()),
) {
let trace_id = trace_id as i32;
// Use trace_to_name mapping instead of face.cluster_id
if let Some(cluster_name) = trace_to_name.get(&trace_id) {
// Find group_id for this cluster name
if let Some(group_id) = face_groups.iter().find(|g| g.name == *cluster_name).map(|g| g.group_id) {
cluster_faces.push(ClusterResultsFace {
face_id: face_id.to_string(),
confidence,
cluster_id: Some(group_id),
trace_id: Some(trace_id),
});
}
}
}
}
if !cluster_faces.is_empty() {
let timestamp = if fps > 0.0 { frame_num as f64 / fps } else { 0.0 };
frames.push(ClusterResultsFrame {
frame: frame_num,
timestamp,
faces: cluster_faces,
});
}
}
}
tracing::info!("[ClusterResults] Built {} frames from face_cluster.json", frames.len());
}
}
frames_map
.entry(frame)
.or_default()
.push(ClusterResultsFace {
face_id: format!("{:x}", point_id),
confidence,
cluster_id,
});
}
let mut frames: Vec<ClusterResultsFrame> = frames_map
.into_iter()
.map(|(frame, faces)| ClusterResultsFrame {
frame,
timestamp: if fps > 0.0 { frame as f64 / fps } else { 0.0 },
faces,
})
.collect();
frames.sort_by_key(|f| f.frame);
Ok(Json(ClusterResultsResponse {