fix: add min_capture_quality to FaceFilterSettings + trace profile fixes

- Add min_capture_quality to FaceFilterSettings (file_profile.rs)
- Fix store_traced_faces.py: load embeddings from Qdrant with_vector=True
- Fix face_tracker.py: force new traces when frame_gap > 30
- Fix backfill_trace_profiles.py: key_frame select=eq(n,N), bbox scaling, best_frame
- Add best_frame to FaceTraceProfile (Rust + Python)
- Fix min_capture_quality persistence in file-profile API
This commit is contained in:
Accusys
2026-08-13 10:12:21 +08:00
parent 71172fa354
commit 39e9ce4c3b
25 changed files with 723 additions and 131 deletions
+4 -3
View File
@@ -501,11 +501,12 @@ async fn register_single_file(
let status = "registered";
let _ = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, status, content_hash, registration_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW()) ON CONFLICT (file_uuid) DO UPDATE SET file_path = EXCLUDED.file_path, file_name = EXCLUDED.file_name, status = EXCLUDED.status, content_hash = EXCLUDED.content_hash, duration = EXCLUDED.duration, width = EXCLUDED.width, height = EXCLUDED.height, fps = EXCLUDED.fps, probe_json = EXCLUDED.probe_json",
"INSERT INTO {} (file_uuid, file_path, file_name, file_type, duration, width, height, fps, total_frames, probe_json, status, content_hash, registration_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NOW()) ON CONFLICT (file_uuid) DO UPDATE SET file_path = EXCLUDED.file_path, file_name = EXCLUDED.file_name, status = EXCLUDED.status, content_hash = EXCLUDED.content_hash, duration = EXCLUDED.duration, width = EXCLUDED.width, height = EXCLUDED.height, fps = EXCLUDED.fps, total_frames = EXCLUDED.total_frames, probe_json = EXCLUDED.probe_json",
videos_table
))
.bind(&file_uuid).bind(&canonical_path).bind(&final_name).bind(&final_file_type)
.bind(duration).bind(width as i32).bind(height as i32).bind(fps)
.bind(total_frames as i64)
.bind(&probe_json).bind(status).bind(&content_hash_val)
.execute(db.pool()).await;
@@ -808,8 +809,8 @@ async fn register_file(
// Convert face_settings to serde_json::Value for create_monitor_job
let face_settings_json = req.face_settings.as_ref().map(|fs| {
serde_json::json!({
"min_confidence": fs.min_confidence.unwrap_or(0.75),
"min_size": fs.min_size.unwrap_or(64)
"min_confidence": fs.min_confidence.unwrap_or(config::FACE_MIN_CONFIDENCE_DEFAULT),
"min_size": fs.min_size.unwrap_or(config::FACE_MIN_SIZE_DEFAULT)
})
});
tokio::spawn(async move {
+15
View File
@@ -429,6 +429,8 @@ pub struct UnassignedTrace {
pub best_face_frame: i64,
pub best_face_confidence: f64,
pub best_face_bbox: Option<serde_json::Value>,
pub avg_capture_quality: f64,
pub best_capture_quality: f64,
}
#[derive(Debug, Serialize)]
@@ -484,6 +486,8 @@ async fn list_unassigned_traces(
best_point_id: i64,
best_frame: i64,
best_bbox: Option<serde_json::Value>,
sum_capture_quality: f64,
best_capture_quality: f64,
}
let mut trace_map: BTreeMap<(String, i32), TraceAgg> = BTreeMap::new();
@@ -499,6 +503,7 @@ async fn list_unassigned_traces(
}
let frame = payload["frame"].as_i64().unwrap_or(0);
let confidence = payload["confidence"].as_f64().unwrap_or(0.0);
let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0);
let point_id = point["id"].as_i64().unwrap_or(0);
let entry = trace_map.entry((file_uuid, trace_id)).or_default();
@@ -509,6 +514,10 @@ async fn list_unassigned_traces(
if frame > entry.end_frame {
entry.end_frame = frame;
}
entry.sum_capture_quality += capture_quality;
if capture_quality > entry.best_capture_quality {
entry.best_capture_quality = capture_quality;
}
if confidence > entry.best_confidence {
entry.best_confidence = confidence;
entry.best_point_id = point_id;
@@ -540,6 +549,12 @@ async fn list_unassigned_traces(
best_face_frame: agg.best_frame,
best_face_confidence: agg.best_confidence,
best_face_bbox: agg.best_bbox,
avg_capture_quality: if agg.frame_count > 0 {
agg.sum_capture_quality / agg.frame_count as f64
} else {
0.0
},
best_capture_quality: agg.best_capture_quality,
})
.collect();
+7
View File
@@ -968,6 +968,8 @@ pub struct FaceSearchItem {
pub end_frame: i64,
pub frame_count: i32,
pub avg_confidence: f64,
pub avg_capture_quality: f64,
pub best_capture_quality: f64,
pub thumbnail_url: String,
}
@@ -1101,6 +1103,7 @@ async fn search_file_faces(
let data_sql = format!(
"SELECT tp.trace_id, tp.file_uuid, COALESCE(tp.name, 'Unassigned') as name, \
tp.start_frame, tp.end_frame, tp.frame_count, tp.avg_confidence, \
tp.avg_capture_quality, tp.best_capture_quality, \
v.file_name \
FROM {} tp \
LEFT JOIN {} v ON tp.file_uuid = v.file_uuid \
@@ -1149,6 +1152,8 @@ async fn search_file_faces(
let end_frame: i64 = r.get("end_frame");
let frame_count: i32 = r.get("frame_count");
let avg_confidence: f64 = r.try_get("avg_confidence").ok().unwrap_or(0.0);
let avg_capture_quality: f64 = r.try_get("avg_capture_quality").ok().unwrap_or(0.0);
let best_capture_quality: f64 = r.try_get("best_capture_quality").ok().unwrap_or(0.0);
FaceSearchItem {
trace_id,
@@ -1159,6 +1164,8 @@ async fn search_file_faces(
end_frame,
frame_count,
avg_confidence: (avg_confidence * 1000.0).round() / 1000.0,
avg_capture_quality: (avg_capture_quality * 1000.0).round() / 1000.0,
best_capture_quality: (best_capture_quality * 1000.0).round() / 1000.0,
thumbnail_url: format!("/api/v1/trace-thumb/{}/{}", file_uuid, trace_id),
}
})
+13
View File
@@ -819,6 +819,8 @@ pub struct IdentityTraceInfo {
pub first_sec: f64,
pub last_sec: f64,
pub avg_confidence: f64,
pub avg_capture_quality: f64,
pub best_capture_quality: f64,
}
#[derive(Debug, Serialize)]
@@ -1088,6 +1090,15 @@ pub async fn get_identity_traces(
.filter_map(|p| p["payload"]["confidence"].as_f64())
.sum::<f64>()
/ frame_count as f64;
let avg_capture_quality = points
.iter()
.filter_map(|p| p["payload"]["capture_quality"].as_f64())
.sum::<f64>()
/ frame_count as f64;
let best_capture_quality = points
.iter()
.filter_map(|p| p["payload"]["capture_quality"].as_f64())
.fold(0.0_f64, f64::max);
let fps = fps_cache.get(file_uuid).copied().unwrap_or(30.0);
traces.push(IdentityTraceInfo {
@@ -1107,6 +1118,8 @@ pub async fn get_identity_traces(
0.0
},
avg_confidence: (avg_confidence * 10000.0).round() / 10000.0,
avg_capture_quality: (avg_capture_quality * 10000.0).round() / 10000.0,
best_capture_quality: (best_capture_quality * 10000.0).round() / 10000.0,
});
}
traces.sort_by(|a, b| a.trace_id.cmp(&b.trace_id));
+140
View File
@@ -1728,6 +1728,142 @@ async fn get_appearance_handler(
}))
}
// ── Face Landmarks Endpoint ──
#[derive(Debug, serde::Deserialize)]
struct FaceLandmarksQuery {
frame: i64,
bbox_x: Option<f64>,
bbox_y: Option<f64>,
bbox_w: Option<f64>,
bbox_h: Option<f64>,
}
#[derive(Debug, serde::Serialize)]
struct FaceBBox {
x: i64,
y: i64,
width: i64,
height: i64,
confidence: f64,
}
#[derive(Debug, serde::Serialize)]
struct FaceLandmarksResponse {
frame: i64,
x: i64,
y: i64,
width: i64,
height: i64,
confidence: f64,
pose_angle: Option<serde_json::Value>,
landmarks: serde_json::Value,
lips: serde_json::Value,
faces: Vec<FaceBBox>,
}
async fn get_face_landmarks_handler(
State(_state): State<crate::api::types::AppState>,
Path(file_uuid): Path<String>,
Query(params): Query<FaceLandmarksQuery>,
) -> Result<axum::Json<FaceLandmarksResponse>, StatusCode> {
use crate::core::config::OUTPUT_DIR;
let output_dir = OUTPUT_DIR.as_str();
let face_path = std::path::Path::new(output_dir).join(format!("{}.face.json", file_uuid));
if !face_path.exists() {
tracing::error!("[get_face_landmarks] File not found: {}", face_path.display());
return Err(StatusCode::NOT_FOUND);
}
let content = std::fs::read_to_string(&face_path).map_err(|e| {
tracing::error!("[get_face_landmarks] Failed to read face.json: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let data: serde_json::Value = serde_json::from_str(&content).map_err(|e| {
tracing::error!("[get_face_landmarks] Failed to parse face.json: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let frames = data
.get("frames")
.and_then(|v| v.as_array())
.ok_or(StatusCode::NOT_FOUND)?;
let frame_data = frames
.iter()
.find(|f| f.get("frame").and_then(|v| v.as_i64()) == Some(params.frame))
.ok_or(StatusCode::NOT_FOUND)?;
let faces = frame_data
.get("faces")
.and_then(|v| v.as_array())
.ok_or(StatusCode::NOT_FOUND)?;
if faces.is_empty() {
return Err(StatusCode::NOT_FOUND);
}
// Select the face closest to the provided bbox center (if given), otherwise the first face.
let selected = match (params.bbox_x, params.bbox_y, params.bbox_w, params.bbox_h) {
(Some(bx), Some(by), Some(bw), Some(bh)) => {
const MAX_CENTER_DIST: f64 = 100.0;
let tcx = bx + bw / 2.0;
let tcy = by + bh / 2.0;
let mut best_dist = f64::MAX;
let mut best = None;
for face in faces {
let x = face.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0);
let y = face.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);
let w = face.get("width").and_then(|v| v.as_f64()).unwrap_or(0.0);
let h = face.get("height").and_then(|v| v.as_f64()).unwrap_or(0.0);
let cx = x + w / 2.0;
let cy = y + h / 2.0;
let dist = (cx - tcx).abs() + (cy - tcy).abs();
if dist < best_dist && dist < MAX_CENTER_DIST {
best_dist = dist;
best = Some(face);
}
}
best.ok_or(StatusCode::NOT_FOUND)?
}
_ => &faces[0],
};
// All faces in this frame (bbox + confidence only) for other-face overlays.
let faces_out: Vec<FaceBBox> = faces
.iter()
.map(|face| FaceBBox {
x: face.get("x").and_then(|v| v.as_i64()).unwrap_or(0),
y: face.get("y").and_then(|v| v.as_i64()).unwrap_or(0),
width: face.get("width").and_then(|v| v.as_i64()).unwrap_or(0),
height: face.get("height").and_then(|v| v.as_i64()).unwrap_or(0),
confidence: face.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0),
})
.collect();
Ok(axum::Json(FaceLandmarksResponse {
frame: params.frame,
x: selected.get("x").and_then(|v| v.as_i64()).unwrap_or(0),
y: selected.get("y").and_then(|v| v.as_i64()).unwrap_or(0),
width: selected.get("width").and_then(|v| v.as_i64()).unwrap_or(0),
height: selected.get("height").and_then(|v| v.as_i64()).unwrap_or(0),
confidence: selected.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0),
pose_angle: selected.get("pose_angle").cloned().or_else(|| selected.get("pose").cloned()),
landmarks: selected
.get("landmarks")
.cloned()
.unwrap_or(serde_json::Value::Null),
lips: selected
.get("lips")
.cloned()
.unwrap_or(serde_json::Value::Null),
faces: faces_out,
}))
}
pub fn pose_appearance_routes() -> Router<crate::api::types::AppState> {
Router::new()
.route("/api/v1/file/:file_uuid/pose", get(get_pose_handler))
@@ -1735,4 +1871,8 @@ pub fn pose_appearance_routes() -> Router<crate::api::types::AppState> {
"/api/v1/file/:file_uuid/appearance",
get(get_appearance_handler),
)
.route(
"/api/v1/file/:file_uuid/face-landmarks",
get(get_face_landmarks_handler),
)
}
+11 -5
View File
@@ -11,7 +11,10 @@ use std::time::Instant;
use super::types::AppState;
use crate::core::cache::{keys, RedisCache};
use crate::core::config::REDIS_KEY_PREFIX;
use crate::core::config::{
FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT,
REDIS_KEY_PREFIX,
};
use crate::core::db::schema;
use crate::core::db::{
Database, MonitorJobStatus, PostgresDb, ProgressMessage, RedisClient, VideoRecord, VideoStatus,
@@ -279,15 +282,18 @@ async fn trigger_processing(
// (videos.face_filter, min_confidence 0-100) → None (caller uses Apple Vision defaults 0.5/1).
let face_settings_json = if let Some(fs) = req.face_settings.as_ref() {
Some(serde_json::json!({
"min_confidence": fs.min_confidence.unwrap_or(0.5),
"min_size": fs.min_size.unwrap_or(1)
"min_confidence": fs.min_confidence.unwrap_or(FACE_MIN_CONFIDENCE_DEFAULT),
"min_size": fs.min_size.unwrap_or(FACE_MIN_SIZE_DEFAULT)
}))
} else if let Some(v) = face_filter.as_ref() {
let min_conf_pct = v
.get("min_confidence")
.and_then(|x| x.as_f64())
.unwrap_or(50.0);
let min_size = v.get("min_size").and_then(|x| x.as_i64()).unwrap_or(1) as i32;
.unwrap_or(FACE_FILTER_CONFIDENCE_PCT_DEFAULT);
let min_size = v
.get("min_size")
.and_then(|x| x.as_i64())
.unwrap_or(FACE_MIN_SIZE_DEFAULT as i64) as i32;
Some(serde_json::json!({
"min_confidence": min_conf_pct / 100.0,
"min_size": min_size
+38 -2
View File
@@ -96,6 +96,8 @@ struct TraceInfo {
best_face_frame: i64,
best_face_confidence: f64,
best_face_bbox: Option<serde_json::Value>,
avg_capture_quality: f64,
best_face_capture_quality: f64,
sample_face_id: Option<String>,
thumbnail_url: String,
}
@@ -173,6 +175,11 @@ async fn list_traces_sorted(
best_point_id: i64,
best_frame: i64,
best_bbox: Option<serde_json::Value>,
sum_capture_quality: f64,
best_capture_quality: f64,
best_capture_point_id: i64,
best_capture_frame: i64,
best_capture_bbox: Option<serde_json::Value>,
}
let mut trace_data: HashMap<i32, TraceAgg> = HashMap::new();
@@ -181,6 +188,7 @@ async fn list_traces_sorted(
let trace_id = payload["trace_id"].as_i64().unwrap_or(0) as i32;
let frame = payload["frame"].as_i64().unwrap_or(0);
let confidence = payload["confidence"].as_f64().unwrap_or(0.5);
let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0);
let point_id = point["id"].as_i64().unwrap_or(0);
if confidence < min_confidence || confidence > max_confidence {
@@ -197,17 +205,29 @@ async fn list_traces_sorted(
best_point_id: 0,
best_frame: 0,
best_bbox: None,
sum_capture_quality: 0.0,
best_capture_quality: 0.0,
best_capture_point_id: 0,
best_capture_frame: 0,
best_capture_bbox: None,
});
entry.face_count += 1;
entry.start_frame = entry.start_frame.min(frame);
entry.end_frame = entry.end_frame.max(frame);
entry.sum_confidence += confidence;
entry.sum_capture_quality += capture_quality;
if confidence > entry.best_confidence {
entry.best_confidence = confidence;
entry.best_point_id = point_id;
entry.best_frame = frame;
entry.best_bbox = payload.get("bbox").cloned();
}
if capture_quality > entry.best_capture_quality {
entry.best_capture_quality = capture_quality;
entry.best_capture_point_id = point_id;
entry.best_capture_frame = frame;
entry.best_capture_bbox = payload.get("bbox").cloned();
}
}
// Filter by min_faces and sort
@@ -222,6 +242,8 @@ async fn list_traces_sorted(
i64,
f64,
Option<serde_json::Value>,
f64,
f64,
)> = trace_data
.into_iter()
.filter(|(_, agg)| agg.face_count >= min_faces)
@@ -232,6 +254,11 @@ async fn list_traces_sorted(
} else {
0.0
};
let avg_cq = if agg.face_count > 0 {
agg.sum_capture_quality / agg.face_count as f64
} else {
0.0
};
(
tid,
agg.face_count,
@@ -243,6 +270,8 @@ async fn list_traces_sorted(
agg.best_frame,
agg.best_confidence,
agg.best_bbox,
avg_cq,
agg.best_capture_quality,
)
})
.collect();
@@ -267,7 +296,7 @@ async fn list_traces_sorted(
let traces: Vec<TraceInfo> = traces_vec
.into_iter()
.map(
|(tid, fc, sf, ef, dur, conf, bfid, bff, bfc, bfb)| TraceInfo {
|(tid, fc, sf, ef, dur, conf, bfid, bff, bfc, bfb, acq, bcq)| TraceInfo {
trace_id: tid,
face_count: fc,
start_frame: sf,
@@ -280,6 +309,8 @@ async fn list_traces_sorted(
best_face_frame: bff,
best_face_confidence: bfc,
best_face_bbox: bfb,
avg_capture_quality: acq,
best_face_capture_quality: bcq,
sample_face_id: None,
thumbnail_url: format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, tid),
},
@@ -321,6 +352,7 @@ struct TraceFaceItem {
width: Option<i32>,
height: Option<i32>,
confidence: f64,
capture_quality: f64,
interpolated: bool,
}
@@ -438,6 +470,7 @@ async fn list_trace_faces(
width: Some(mid_w),
height: Some(mid_h),
confidence: 0.0,
capture_quality: 0.0,
interpolated: true,
});
}
@@ -447,6 +480,7 @@ async fn list_trace_faces(
// Add the real detection
let frame_val = frame;
let ft = (frame_val as f64 / fps * 10.0).round() / 10.0;
let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0);
faces.push(TraceFaceItem {
id,
start_frame: frame_val,
@@ -458,6 +492,7 @@ async fn list_trace_faces(
width: Some(w),
height: Some(h),
confidence: conf as f64,
capture_quality,
interpolated: false,
});
}
@@ -579,7 +614,8 @@ where
if conf <= 0.7 {
return None;
}
let score = (w as f64 * h as f64) * conf;
let capture_quality = payload["capture_quality"].as_f64().unwrap_or(0.0);
let score = (w as f64 * h as f64) * conf * (0.2 + capture_quality);
Some(Candidate {
frame: payload["frame"].as_i64().unwrap_or(0),
x: bbox["x"].as_f64()? as i32,
+18
View File
@@ -97,6 +97,8 @@ pub enum SearchResult {
end_time: Option<f64>,
key_frame: Option<String>,
key_face: Option<String>,
avg_capture_quality: Option<f64>,
best_capture_quality: Option<f64>,
},
}
@@ -329,6 +331,8 @@ pub struct PeopleResult {
pub key_frame: Option<String>,
pub key_face: Option<String>,
pub avg_confidence: Option<f64>,
pub avg_capture_quality: Option<f64>,
pub best_capture_quality: Option<f64>,
}
async fn search_chunks(
@@ -604,6 +608,7 @@ async fn search_persons_internal(
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
tp.start_frame, tp.end_frame, tp.frame_count, \
tp.key_frame, tp.key_face, tp.avg_confidence, \
tp.avg_capture_quality, tp.best_capture_quality, \
n.external_id \
FROM {} tp \
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
@@ -643,6 +648,8 @@ async fn search_persons_internal(
Option<String>,
Option<String>,
Option<f64>,
Option<f64>,
Option<f64>,
Option<String>,
)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?;
@@ -658,6 +665,8 @@ async fn search_persons_internal(
key_frame,
key_face,
avg_confidence,
avg_capture_quality,
best_capture_quality,
external_id,
) in rows
{
@@ -679,6 +688,8 @@ async fn search_persons_internal(
end_time: None,
key_frame,
key_face,
avg_capture_quality,
best_capture_quality,
});
}
@@ -780,6 +791,7 @@ async fn search_people_by_query(
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
tp.start_frame, tp.end_frame, tp.frame_count, \
tp.key_frame, tp.key_face, tp.avg_confidence, \
tp.avg_capture_quality, tp.best_capture_quality, \
n.external_id \
FROM {} tp \
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
@@ -819,6 +831,8 @@ async fn search_people_by_query(
Option<String>,
Option<String>,
Option<f64>,
Option<f64>,
Option<f64>,
Option<String>,
)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?;
@@ -833,6 +847,8 @@ async fn search_people_by_query(
key_frame,
key_face,
avg_confidence,
avg_capture_quality,
best_capture_quality,
external_id,
) in rows
{
@@ -850,6 +866,8 @@ async fn search_people_by_query(
key_frame,
key_face,
avg_confidence,
avg_capture_quality,
best_capture_quality,
});
}