feat: add regenerate trace thumbnail endpoint with bbox clamping

- validator::clamp_crop: clamp crop rect to frame dims (fixes OOB shift)
- tkg.rs: use clamp_crop in key_face crop paths (root-cause fix)
- trace_agent_api: POST /api/v1/file/:file_uuid/trace/:trace_id/regenerate-thumbnail
- docs: 26_trace_thumbnail_regenerate.md for Studio team
This commit is contained in:
Accusys
2026-08-12 03:04:19 +08:00
parent aa28bf93fb
commit 59ca6cdf83
5 changed files with 553 additions and 25 deletions
+190
View File
@@ -65,6 +65,10 @@ pub fn trace_agent_routes() -> Router<crate::api::types::AppState> {
"/api/v1/file/:file_uuid/trace/:trace_id/merge/:target_trace_id",
post(merge_trace),
)
.route(
"/api/v1/file/:file_uuid/trace/:trace_id/regenerate-thumbnail",
post(regenerate_trace_thumbnail),
)
}
#[derive(Debug, Deserialize)]
@@ -864,6 +868,192 @@ async fn get_trace_thumbnail_inner(
.unwrap())
}
// Regenerate a trace's key_face.jpg by re-cropping the best-confidence face
// from the video with the bbox clamped to the frame dimensions. Fixes the
// "key frame OK, bbox OK, but key_face broken" case where an out-of-bounds
// bbox made ffmpeg silently shift the crop.
async fn regenerate_trace_thumbnail(
State(state): State<crate::api::types::AppState>,
Path((file_uuid, trace_id)): Path<(String, i32)>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
use serde_json::json;
let videos_table = crate::core::db::schema::table_name("videos");
// Query video info: path, dimensions, fps
let row: Option<(String, Option<i32>, Option<i32>, Option<f64>)> = sqlx::query_as(&format!(
"SELECT file_path, width, height, fps FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
let (video_path, video_width, video_height, fps) = row.ok_or_else(|| {
(
StatusCode::NOT_FOUND,
Json(json!({"error": "Video not found"})),
)
})?;
let video_width = video_width.ok_or_else(|| {
(
StatusCode::BAD_REQUEST,
Json(json!({"error": "Video width unavailable, cannot clamp crop"})),
)
})?;
let video_height = video_height.ok_or_else(|| {
(
StatusCode::BAD_REQUEST,
Json(json!({"error": "Video height unavailable, cannot clamp crop"})),
)
})?;
let fps = fps.unwrap_or(25.0);
// Scroll Qdrant _faces for this trace and pick the highest-confidence face.
// Unlike select_rep_face, no blur-optimization happens: we reuse the
// existing best-confidence frame + bbox to restore the same region.
use crate::core::db::qdrant_db::QdrantDb;
let qdrant = QdrantDb::new();
let trace_filter = json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": trace_id}}
]
});
let points = qdrant
.scroll_all_points("_faces", trace_filter, 1000)
.await
.unwrap_or_default();
let best = points
.iter()
.filter_map(|p| {
let payload = &p["payload"];
let bbox = &payload["bbox"];
let w = bbox["width"].as_f64()? as i32;
let h = bbox["height"].as_f64()? as i32;
let conf = payload["confidence"].as_f64()?;
Some((
payload["frame"].as_i64().unwrap_or(0),
bbox["x"].as_f64()? as i32,
bbox["y"].as_f64()? as i32,
w,
h,
conf,
))
})
.max_by(|a, b| a.5.partial_cmp(&b.5).unwrap_or(std::cmp::Ordering::Equal));
let (best_frame, bx, by, bw, bh, _conf) = best.ok_or_else(|| {
(
StatusCode::NOT_FOUND,
Json(json!({"error": "No face found for this trace"})),
)
})?;
// Clamp bbox to frame dimensions
let (cx, cy, cw, ch) =
crate::core::thumbnail::validator::clamp_crop(bx, by, bw, bh, video_width, video_height);
tracing::info!(
"[regenerate-thumbnail] trace {} frame {} bbox {}x{} at ({},{})",
trace_id,
best_frame,
cw,
ch,
cx,
cy
);
// Crop the face region from the video using decoded frame index (VFR-safe)
let tmp = std::env::temp_dir().join(format!("regen_trace_{}_{}.jpg", file_uuid, trace_id));
let select = format!("select=eq(n\\,{})", best_frame);
let status = tokio::process::Command::new("ffmpeg")
.args([
"-y",
"-i",
&video_path,
"-vf",
&format!("{},crop={}:{}:{}:{}", select, cw, ch, cx, cy),
"-frames:v",
"1",
"-q:v",
"2",
&tmp.to_string_lossy().to_string(),
])
.output()
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
if !status.status.success() {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "FFmpeg failed during regeneration"})),
));
}
let bytes = tokio::fs::read(&tmp).await.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
crate::core::thumbnail::validator::validate_jpeg(&bytes).map_err(|e| {
tracing::warn!("[regenerate-thumbnail] JPEG validation failed: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "Invalid JPEG output"})),
)
})?;
let _ = tokio::fs::remove_file(&tmp).await;
// Overwrite key_face.jpg in the trace profile directory
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let profile_dir = std::path::PathBuf::from(output_dir)
.join(&file_uuid)
.join(format!("trace_{}", trace_id));
if let Err(e) = tokio::fs::create_dir_all(&profile_dir).await {
tracing::warn!("[regenerate-thumbnail] Failed to create trace dir: {}", e);
}
let _ = tokio::fs::write(profile_dir.join("key_face.jpg"), &bytes).await;
// Sync .faces cache if the cached crop file exists for the best frame
let trace_dir_name = if trace_id == 0 {
"unbound".to_string()
} else {
trace_id.to_string()
};
let faces_cached = std::path::PathBuf::from(output_dir)
.join(".faces")
.join(&file_uuid)
.join(trace_dir_name)
.join(format!("{}.jpg", best_frame));
if faces_cached.exists() {
let _ = tokio::fs::write(&faces_cached, &bytes).await;
}
Ok(Json(json!({
"success": true,
"file_uuid": file_uuid,
"trace_id": trace_id,
"frame": best_frame,
"bbox": {"x": cx, "y": cy, "width": cw, "height": ch},
})))
}
#[derive(Debug, Serialize)]
struct CoOccurIdentity {
identity_uuid: String,