fix: TKG key frame/face selection uses best-confidence — match frontend label
- tkg.rs: key_frame/key_face/best_bbox now use best-confidence frame (was cq_best capture-quality) so thumbnails agree with trace_agent_api best_face_frame / [F..] labels - keep cq_best_quality as trace-level stat only - add backfill_trace_dirs + skip_existing resume mode - trace_agent_api.rs regenerate-thumbnail: use strict > tie-break (reduce) matching list_traces_sorted so equal-confidence frames pick the same one
This commit is contained in:
@@ -1002,7 +1002,15 @@ async fn regenerate_trace_thumbnail(
|
|||||||
conf,
|
conf,
|
||||||
))
|
))
|
||||||
})
|
})
|
||||||
.max_by(|a, b| a.5.partial_cmp(&b.5).unwrap_or(std::cmp::Ordering::Equal));
|
.reduce(|acc, cur| {
|
||||||
|
// Match list_traces_sorted tie-break: strict > keeps the first-seen
|
||||||
|
// point on equal confidence so the label and thumbnail agree.
|
||||||
|
if cur.5 > acc.5 {
|
||||||
|
cur
|
||||||
|
} else {
|
||||||
|
acc
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let (best_frame, bx, by, bw, bh, _conf) = best.ok_or_else(|| {
|
let (best_frame, bx, by, bw, bh, _conf) = best.ok_or_else(|| {
|
||||||
(
|
(
|
||||||
|
|||||||
+73
-30
@@ -766,7 +766,7 @@ pub async fn build_tkg(
|
|||||||
if let Some(r) = redis.as_ref() {
|
if let Some(r) = redis.as_ref() {
|
||||||
publish_tkg_progress(r, file_uuid, &progress).await;
|
publish_tkg_progress(r, file_uuid, &progress).await;
|
||||||
}
|
}
|
||||||
let n_face = build_face_track_nodes(pool, file_uuid, &pose_data, &face_points).await?;
|
let n_face = build_face_track_nodes(pool, file_uuid, &pose_data, &face_points, false).await?;
|
||||||
progress.stats.face_track_nodes = n_face as i64;
|
progress.stats.face_track_nodes = n_face as i64;
|
||||||
progress.update_phase(
|
progress.update_phase(
|
||||||
TkgPhase::FaceTrackNodes,
|
TkgPhase::FaceTrackNodes,
|
||||||
@@ -1101,13 +1101,52 @@ pub async fn build_tkg(
|
|||||||
|
|
||||||
// ── Node builders ─────────────────────────────────────────────────
|
// ── Node builders ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Backfill missing trace artifact dirs (key_frame.jpg / key_face.jpg / trace_profile.json)
|
||||||
|
/// by skipping traces whose artifacts already exist on disk. Only rebuilds the
|
||||||
|
/// face_track nodes; other node types and edges are left untouched.
|
||||||
|
pub async fn backfill_trace_dirs(
|
||||||
|
db: &PostgresDb,
|
||||||
|
file_uuid: &str,
|
||||||
|
output_dir: &str,
|
||||||
|
) -> Result<usize> {
|
||||||
|
let pool = db.pool();
|
||||||
|
let pose_data = load_face_pose_data(output_dir, file_uuid)
|
||||||
|
.map_err(|e| {
|
||||||
|
tracing::error!("[TKG-BACKFILL] Failed to load face pose data: {}", e);
|
||||||
|
e
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
tracing::info!(
|
||||||
|
"[TKG-BACKFILL] Loaded {} pose entries from face.json (output_dir={})",
|
||||||
|
pose_data.len(),
|
||||||
|
output_dir
|
||||||
|
);
|
||||||
|
|
||||||
|
let face_points = scroll_face_points(file_uuid).await;
|
||||||
|
tracing::info!(
|
||||||
|
"[TKG-BACKFILL] Fetched {} face points from Qdrant for {}",
|
||||||
|
face_points.len(),
|
||||||
|
file_uuid
|
||||||
|
);
|
||||||
|
|
||||||
|
let n =
|
||||||
|
build_face_track_nodes_from_qdrant(pool, file_uuid, &pose_data, &face_points, true).await?;
|
||||||
|
tracing::info!(
|
||||||
|
"[TKG-BACKFILL] backfilled {} face_track artifact dirs for {}",
|
||||||
|
n,
|
||||||
|
file_uuid
|
||||||
|
);
|
||||||
|
Ok(n)
|
||||||
|
}
|
||||||
|
|
||||||
async fn build_face_track_nodes(
|
async fn build_face_track_nodes(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
file_uuid: &str,
|
file_uuid: &str,
|
||||||
pose_data: &[FacePose],
|
pose_data: &[FacePose],
|
||||||
face_points: &[FacePoint],
|
face_points: &[FacePoint],
|
||||||
|
skip_existing: bool,
|
||||||
) -> Result<usize> {
|
) -> Result<usize> {
|
||||||
build_face_track_nodes_from_qdrant(pool, file_uuid, pose_data, face_points).await
|
build_face_track_nodes_from_qdrant(pool, file_uuid, pose_data, face_points, skip_existing).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn build_face_track_nodes_from_qdrant(
|
async fn build_face_track_nodes_from_qdrant(
|
||||||
@@ -1115,6 +1154,7 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
file_uuid: &str,
|
file_uuid: &str,
|
||||||
pose_data: &[FacePose],
|
pose_data: &[FacePose],
|
||||||
face_points: &[FacePoint],
|
face_points: &[FacePoint],
|
||||||
|
skip_existing: bool,
|
||||||
) -> Result<usize> {
|
) -> Result<usize> {
|
||||||
let nodes_table = t("tkg_nodes");
|
let nodes_table = t("tkg_nodes");
|
||||||
|
|
||||||
@@ -1141,10 +1181,7 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
best_frame: i64,
|
best_frame: i64,
|
||||||
best_confidence: f64,
|
best_confidence: f64,
|
||||||
best_point_id: Option<String>,
|
best_point_id: Option<String>,
|
||||||
cq_best_frame: i64,
|
|
||||||
cq_best_quality: f64,
|
cq_best_quality: f64,
|
||||||
cq_best_point_id: Option<String>,
|
|
||||||
cq_best_bbox: Option<serde_json::Value>,
|
|
||||||
best_bbox: Option<serde_json::Value>,
|
best_bbox: Option<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1164,10 +1201,7 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
best_frame: 0,
|
best_frame: 0,
|
||||||
best_confidence: 0.0,
|
best_confidence: 0.0,
|
||||||
best_point_id: None,
|
best_point_id: None,
|
||||||
cq_best_frame: 0,
|
|
||||||
cq_best_quality: 0.0,
|
cq_best_quality: 0.0,
|
||||||
cq_best_point_id: None,
|
|
||||||
cq_best_bbox: None,
|
|
||||||
best_bbox: None,
|
best_bbox: None,
|
||||||
});
|
});
|
||||||
entry.frame_count += 1;
|
entry.frame_count += 1;
|
||||||
@@ -1192,22 +1226,31 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
"height": p.h.round() as i64,
|
"height": p.h.round() as i64,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
// Track best capture quality face (used for key frame / key face set)
|
// Track best capture quality (trace-level stat only; key frame/face selection
|
||||||
|
// uses the best-confidence face below for consistency with the frontend)
|
||||||
if p.capture_quality > entry.cq_best_quality {
|
if p.capture_quality > entry.cq_best_quality {
|
||||||
entry.cq_best_quality = p.capture_quality;
|
entry.cq_best_quality = p.capture_quality;
|
||||||
entry.cq_best_frame = p.frame;
|
|
||||||
entry.cq_best_point_id = p.point_id.clone();
|
|
||||||
entry.cq_best_bbox = Some(serde_json::json!({
|
|
||||||
"x": p.x.round() as i64,
|
|
||||||
"y": p.y.round() as i64,
|
|
||||||
"width": p.w.round() as i64,
|
|
||||||
"height": p.h.round() as i64,
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
for (tid, agg) in &traces {
|
for (tid, agg) in &traces {
|
||||||
|
// Skip traces whose artifacts already exist on disk (backfill/resume mode)
|
||||||
|
if skip_existing {
|
||||||
|
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||||
|
let trace_dir =
|
||||||
|
crate::core::file_profile::FaceTraceProfile::trace_dir(output_dir, file_uuid, *tid);
|
||||||
|
let kf_path = trace_dir.join("key_frame.jpg");
|
||||||
|
let kface_path = trace_dir.join("key_face.jpg");
|
||||||
|
let tp_path = crate::core::file_profile::FaceTraceProfile::profile_path(
|
||||||
|
output_dir, file_uuid, *tid,
|
||||||
|
);
|
||||||
|
if kf_path.exists() && kface_path.exists() && tp_path.exists() {
|
||||||
|
tracing::info!("[TKG-BACKFILL] trace {}: already complete, skipping", tid);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Use trace_N as primary external_id (consistent with cluster_agent)
|
// Use trace_N as primary external_id (consistent with cluster_agent)
|
||||||
let external_id = format!("trace_{}", tid);
|
let external_id = format!("trace_{}", tid);
|
||||||
let label = format!("Face Trace {}", tid);
|
let label = format!("Face Trace {}", tid);
|
||||||
@@ -1254,15 +1297,15 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
"frame_count": agg.frame_count,
|
"frame_count": agg.frame_count,
|
||||||
"start_frame": agg.start_f,
|
"start_frame": agg.start_f,
|
||||||
"end_frame": agg.end_f,
|
"end_frame": agg.end_f,
|
||||||
"key_frame": agg.cq_best_frame,
|
"key_frame": agg.best_frame,
|
||||||
"key_face": agg.cq_best_point_id.as_deref().unwrap_or(""),
|
"key_face": agg.best_point_id.as_deref().unwrap_or(""),
|
||||||
"avg_bbox": {
|
"avg_bbox": {
|
||||||
"x": (agg.sum_x / agg.frame_count as f64).round() as i64,
|
"x": (agg.sum_x / agg.frame_count as f64).round() as i64,
|
||||||
"y": (agg.sum_y / agg.frame_count as f64).round() as i64,
|
"y": (agg.sum_y / agg.frame_count as f64).round() as i64,
|
||||||
"width": (agg.sum_w / agg.frame_count as f64).round() as i64,
|
"width": (agg.sum_w / agg.frame_count as f64).round() as i64,
|
||||||
"height": (agg.sum_h / agg.frame_count as f64).round() as i64,
|
"height": (agg.sum_h / agg.frame_count as f64).round() as i64,
|
||||||
},
|
},
|
||||||
"best_bbox": agg.cq_best_bbox,
|
"best_bbox": agg.best_bbox,
|
||||||
"avg_yaw": (avg_yaw * 1000.0).round() / 1000.0,
|
"avg_yaw": (avg_yaw * 1000.0).round() / 1000.0,
|
||||||
"avg_pitch": (avg_pitch * 1000.0).round() / 1000.0,
|
"avg_pitch": (avg_pitch * 1000.0).round() / 1000.0,
|
||||||
"avg_roll": (avg_roll * 1000.0).round() / 1000.0,
|
"avg_roll": (avg_roll * 1000.0).round() / 1000.0,
|
||||||
@@ -1320,19 +1363,19 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
agg.frame_count,
|
agg.frame_count,
|
||||||
agg.start_f,
|
agg.start_f,
|
||||||
agg.end_f,
|
agg.end_f,
|
||||||
agg.cq_best_frame,
|
agg.best_frame,
|
||||||
Some(avg_confidence),
|
Some(avg_confidence),
|
||||||
Some(avg_capture_quality),
|
Some(avg_capture_quality),
|
||||||
agg.best_confidence,
|
agg.best_confidence,
|
||||||
agg.cq_best_quality,
|
agg.cq_best_quality,
|
||||||
props["avg_bbox"].clone(),
|
props["avg_bbox"].clone(),
|
||||||
agg.cq_best_bbox.clone(),
|
agg.best_bbox.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Extract key_frame JPEG bytes via ffmpeg pipe
|
// Extract key_frame JPEG bytes via ffmpeg pipe
|
||||||
// Use select=eq(n\,frame) for VFR compatibility (decoded index, not time-based)
|
// Use select=eq(n\,frame) for VFR compatibility (decoded index, not time-based)
|
||||||
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
|
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
|
||||||
let select = format!("select=eq(n\\,{})", agg.cq_best_frame);
|
let select = format!("select=eq(n\\,{})", agg.best_frame);
|
||||||
let output = std::process::Command::new("ffmpeg")
|
let output = std::process::Command::new("ffmpeg")
|
||||||
.args(["-y", "-v", "quiet", "-i"])
|
.args(["-y", "-v", "quiet", "-i"])
|
||||||
.arg(vp)
|
.arg(vp)
|
||||||
@@ -1360,13 +1403,13 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Crop key_face JPEG bytes from key_frame using representative bbox (best capture quality frame)
|
// 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| {
|
let key_face_jpeg: Option<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
|
||||||
// Find bbox for cq_best_frame from trace frames
|
// Find bbox for best_frame from trace frames
|
||||||
let (bf, bx, by, bw, bh) = agg
|
let (bf, bx, by, bw, bh) = agg
|
||||||
.frames
|
.frames
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(f, _, _, _, _)| *f == agg.cq_best_frame)?;
|
.find(|(f, _, _, _, _)| *f == agg.best_frame)?;
|
||||||
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
|
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
|
||||||
|
|
||||||
// Validate bbox: must have positive dimensions
|
// Validate bbox: must have positive dimensions
|
||||||
@@ -1413,8 +1456,8 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Save all three files to output/{file_uuid}/{trace_id}/
|
// Save all three files to output/{file_uuid}/{trace_id}/
|
||||||
let mut key_frame_file = agg.cq_best_frame.to_string();
|
let mut key_frame_file = agg.best_frame.to_string();
|
||||||
let mut key_face_file = agg.cq_best_point_id.as_deref().unwrap_or("").to_string();
|
let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string();
|
||||||
|
|
||||||
match trace_profile.save(
|
match trace_profile.save(
|
||||||
output_dir,
|
output_dir,
|
||||||
@@ -1465,7 +1508,7 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
|
|
||||||
if need_retry {
|
if need_retry {
|
||||||
if let Some(ref vp) = video_path {
|
if let Some(ref vp) = video_path {
|
||||||
let select = format!("select=eq(n\\,{})", agg.cq_best_frame);
|
let select = format!("select=eq(n\\,{})", agg.best_frame);
|
||||||
// Retry key_frame extraction
|
// Retry key_frame extraction
|
||||||
if !kf_path.exists() {
|
if !kf_path.exists() {
|
||||||
if let Ok(output) = std::process::Command::new("ffmpeg")
|
if let Ok(output) = std::process::Command::new("ffmpeg")
|
||||||
@@ -1504,7 +1547,7 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
let (_, bx, by, bw, bh) = agg
|
let (_, bx, by, bw, bh) = agg
|
||||||
.frames
|
.frames
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(f, _, _, _, _)| *f == agg.cq_best_frame)
|
.find(|(f, _, _, _, _)| *f == agg.best_frame)
|
||||||
.cloned()
|
.cloned()
|
||||||
.unwrap_or((0, 0.0, 0.0, 100.0, 100.0));
|
.unwrap_or((0, 0.0, 0.0, 100.0, 100.0));
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user