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,
});
}
+22 -10
View File
@@ -1421,6 +1421,7 @@ pub async fn exec_trace_search(
let sql = format!(
"SELECT tp.file_uuid, tp.trace_id, tp.name, tp.start_frame, tp.end_frame, \
tp.frame_count, tp.key_frame, tp.status, tp.avg_confidence, \
tp.avg_capture_quality, tp.best_capture_quality, tp.best_confidence, \
tp.vlm_description, tp.vlm_clothing, tp.vlm_tags, tp.vlm_location, \
tp.vlm_setting, tp.vlm_lighting, COALESCE(v.file_name, ''), COALESCE(v.fps, 25.0) \
FROM {} tp \
@@ -1459,14 +1460,17 @@ pub async fn exec_trace_search(
let key_frame: Option<String> = row.get(6);
let status: Option<String> = row.get(7);
let avg_confidence: Option<f64> = row.get(8);
let vlm_description: Option<String> = row.get(9);
let vlm_clothing: Option<String> = row.get(10);
let vlm_tags: Option<Vec<String>> = row.get(11);
let vlm_location: Option<String> = row.get(12);
let vlm_setting: Option<String> = row.get(13);
let vlm_lighting: Option<String> = row.get(14);
let file_name: String = row.get(15);
let fps: f64 = row.get(16);
let avg_capture_quality: Option<f64> = row.get(9);
let best_capture_quality: Option<f64> = row.get(10);
let best_confidence: Option<f64> = row.get(11);
let vlm_description: Option<String> = row.get(12);
let vlm_clothing: Option<String> = row.get(13);
let vlm_tags: Option<Vec<String>> = row.get(14);
let vlm_location: Option<String> = row.get(15);
let vlm_setting: Option<String> = row.get(16);
let vlm_lighting: Option<String> = row.get(17);
let file_name: String = row.get(18);
let fps: f64 = row.get(19);
let start_time = start_frame.map(|f| (f as f64 / fps).round() / 100.0);
let end_time = end_frame.map(|f| (f as f64 / fps).round() / 100.0);
@@ -1485,6 +1489,9 @@ pub async fn exec_trace_search(
"key_frame": key_frame,
"status": status,
"avg_confidence": avg_confidence,
"best_confidence": best_confidence,
"avg_capture_quality": avg_capture_quality,
"best_capture_quality": best_capture_quality,
"vlm_description": vlm_description,
"vlm_clothing": vlm_clothing,
"vlm_tags": vlm_tags,
@@ -1652,6 +1659,7 @@ pub async fn exec_face_profile_search(
"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 \
@@ -1691,7 +1699,9 @@ pub async fn exec_face_profile_search(
let key_frame: Option<String> = row.get(6);
let key_face: Option<String> = row.get(7);
let avg_confidence: Option<f64> = row.get(8);
let external_id: Option<String> = row.get(9);
let avg_capture_quality: Option<f64> = row.get(9);
let best_capture_quality: Option<f64> = row.get(10);
let external_id: Option<String> = row.get(11);
serde_json::json!({
"card_type": "face_profile",
@@ -1704,7 +1714,9 @@ pub async fn exec_face_profile_search(
"frame_count": frame_count,
"key_frame": key_frame,
"key_face": key_face,
"avg_confidence": avg_confidence
"avg_confidence": avg_confidence,
"avg_capture_quality": avg_capture_quality,
"best_capture_quality": best_capture_quality
})
})
.collect();
+7
View File
@@ -145,6 +145,13 @@ pub static MONGODB_DATABASE: Lazy<String> =
pub static QDRANT_COLLECTION: Lazy<String> =
Lazy::new(|| env::var("QDRANT_COLLECTION").unwrap_or_else(|_| "momentry_rule1".to_string()));
// ─── Face detection thresholds (single source of truth) ───
// Defaults mirror Apple Vision native detection (0.5 confidence / 1px min size).
// Keep scripts/swift_processors/swift_face.swift and scripts/face_processor.py in sync.
pub const FACE_MIN_CONFIDENCE_DEFAULT: f64 = 0.5; // detection threshold (0-1)
pub const FACE_MIN_SIZE_DEFAULT: i32 = 1; // detection min face size (px)
pub const FACE_FILTER_CONFIDENCE_PCT_DEFAULT: f64 = 50.0; // videos.face_filter (0-100%)
pub mod processor {
use super::*;
+32 -2
View File
@@ -10,6 +10,7 @@ use uuid::Uuid;
use super::{schema, Database, QdrantDb};
use crate::core::chunk::types::{Chunk, ChunkRule, ChunkType};
use crate::core::config::{FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT};
use crate::core::text::synonym::normalize_chinese_query;
use crate::core::text::{
global_synonym_expander,
@@ -1028,6 +1029,7 @@ impl PostgresDb {
"content_hash TEXT",
"proxy_path TEXT",
"audio_track TEXT",
"face_filter JSONB",
];
for col in &video_cols {
let (col_name, col_def) = col.split_once(' ').unwrap_or((col, ""));
@@ -1268,7 +1270,29 @@ impl PostgresDb {
sqlx::query("CREATE TABLE IF NOT EXISTS strangers (id SERIAL PRIMARY KEY, file_uuid TEXT, trace_id INTEGER, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
// ── Trace Profiles (VLM metadata for face traces) ──
sqlx::query("CREATE TABLE IF NOT EXISTS trace_profiles (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, trace_id INTEGER NOT NULL, name VARCHAR(255), start_frame BIGINT, end_frame BIGINT, frame_count INTEGER, key_frame VARCHAR(255), key_face VARCHAR(255), status VARCHAR(50) DEFAULT 'pending', avg_confidence DOUBLE PRECISION, vlm_description TEXT, vlm_clothing TEXT, vlm_tags TEXT[], vlm_location VARCHAR(255), vlm_setting VARCHAR(255), vlm_lighting VARCHAR(100), vlm_weather VARCHAR(100), vlm_hand_objects TEXT, vlm_has_plants BOOLEAN, vlm_has_animals BOOLEAN, vlm_background TEXT, vlm_bg_tags TEXT[], vlm_model VARCHAR(64), metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
sqlx::query("CREATE TABLE IF NOT EXISTS trace_profiles (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, trace_id INTEGER NOT NULL, name VARCHAR(255), start_frame BIGINT, end_frame BIGINT, frame_count INTEGER, key_frame VARCHAR(255), key_face VARCHAR(255), status VARCHAR(50) DEFAULT 'pending', avg_confidence DOUBLE PRECISION, best_confidence DOUBLE PRECISION, avg_capture_quality DOUBLE PRECISION, best_capture_quality DOUBLE PRECISION, avg_bbox JSONB, best_bbox JSONB, vlm_description TEXT, vlm_clothing TEXT, vlm_tags TEXT[], vlm_location VARCHAR(255), vlm_setting VARCHAR(255), vlm_lighting VARCHAR(100), vlm_weather VARCHAR(100), vlm_hand_objects TEXT, vlm_has_plants BOOLEAN, vlm_has_animals BOOLEAN, vlm_background TEXT, vlm_bg_tags TEXT[], vlm_model VARCHAR(64), metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
// Migration: add new fields to existing trace_profiles tables (safe no-op if columns exist)
sqlx::query(
"ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_confidence DOUBLE PRECISION",
)
.execute(pool)
.await?;
sqlx::query(
"ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS avg_capture_quality DOUBLE PRECISION",
)
.execute(pool)
.await?;
sqlx::query(
"ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_capture_quality DOUBLE PRECISION",
)
.execute(pool)
.await?;
sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS avg_bbox JSONB")
.execute(pool)
.await?;
sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_bbox JSONB")
.execute(pool)
.await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)",
)
@@ -1971,7 +1995,13 @@ impl PostgresDb {
.fetch_optional(&self.pool)
.await?;
let face_settings_json = face_settings.map(|v| v.to_string()).unwrap_or_else(|| "{\"min_confidence\": 0.75, \"min_size\": 64}".to_string());
let face_settings_json = face_settings.map(|v| v.to_string()).unwrap_or_else(|| {
serde_json::json!({
"min_confidence": FACE_MIN_CONFIDENCE_DEFAULT,
"min_size": FACE_MIN_SIZE_DEFAULT
})
.to_string()
});
let row = if let Some(job_id) = existing_id {
// Update existing job
+12 -1
View File
@@ -42,7 +42,8 @@ pub async fn upsert_trace_profile(
// Use LEFT JOIN to get tkg_nodes data for backfilling
let sql = format!(
"INSERT INTO {tp_table} (file_uuid, trace_id, name, start_frame, end_frame, \
frame_count, key_frame, key_face, status, avg_confidence, properties) \
frame_count, key_frame, key_face, status, avg_confidence, \
best_confidence, avg_capture_quality, best_capture_quality, avg_bbox, best_bbox, properties) \
SELECT $1, $2, $3, \
COALESCE((tn.properties->>'start_frame')::bigint, tp.start_frame), \
COALESCE((tn.properties->>'end_frame')::bigint, tp.end_frame), \
@@ -51,6 +52,11 @@ pub async fn upsert_trace_profile(
COALESCE(tn.properties->>'key_face', tp.key_face), \
'pending', \
COALESCE((tn.properties->>'avg_confidence')::double precision, tp.avg_confidence), \
COALESCE((tn.properties->>'best_confidence')::double precision, tp.best_confidence), \
COALESCE((tn.properties->>'avg_capture_quality')::double precision, tp.avg_capture_quality), \
COALESCE((tn.properties->>'best_capture_quality')::double precision, tp.best_capture_quality), \
COALESCE((tn.properties->>'avg_bbox')::jsonb, tp.avg_bbox), \
COALESCE((tn.properties->>'best_bbox')::jsonb, tp.best_bbox), \
COALESCE($4::jsonb, tn.properties, '{{}}'::jsonb) \
FROM (VALUES (1)) AS dummy \
LEFT JOIN {tkg_table} tn ON tn.file_uuid = $1 \
@@ -64,6 +70,11 @@ pub async fn upsert_trace_profile(
key_frame = COALESCE(EXCLUDED.key_frame, {tp_table}.key_frame), \
key_face = COALESCE(EXCLUDED.key_face, {tp_table}.key_face), \
avg_confidence = COALESCE(EXCLUDED.avg_confidence, {tp_table}.avg_confidence), \
best_confidence = COALESCE(EXCLUDED.best_confidence, {tp_table}.best_confidence), \
avg_capture_quality = COALESCE(EXCLUDED.avg_capture_quality, {tp_table}.avg_capture_quality), \
best_capture_quality = COALESCE(EXCLUDED.best_capture_quality, {tp_table}.best_capture_quality), \
avg_bbox = COALESCE(EXCLUDED.avg_bbox, {tp_table}.avg_bbox), \
best_bbox = COALESCE(EXCLUDED.best_bbox, {tp_table}.best_bbox), \
updated_at = NOW()",
);
+95 -63
View File
@@ -8,26 +8,26 @@ pub struct FaceFilterFeatures {
pub face_id: String,
pub file_uuid: String,
pub frame: i32,
// Bbox size (pre-computed as min(width, height))
pub bbox_size: Option<i32>,
// Landmark geometric features
pub eye_ratio: Option<f64>,
pub nose_ratio: Option<f64>,
pub pose_score: Option<f64>,
// MediaPipe verification features
pub mediapipe_detected: Option<bool>,
pub mediapipe_iou: Option<f64>,
// Embedding similarity features
pub embedding_similarity: Option<f64>,
// Temporal consistency features
pub consecutive_frames: Option<i32>,
pub total_frames_detected: Option<i32>,
// Source information
pub apple_vision_confidence: Option<f64>,
pub mediapipe_confidence: Option<f64>,
@@ -173,7 +173,11 @@ impl FilterEngine {
}
/// Apply landmark analysis rule
fn apply_landmark_analysis(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
fn apply_landmark_analysis(
&self,
features: &FaceFilterFeatures,
config: &RuleConfig,
) -> RuleResult {
if !config.enabled {
return RuleResult {
enabled: false,
@@ -190,7 +194,7 @@ impl FilterEngine {
if let Some(eye_ratio) = features.eye_ratio {
let min = config.thresholds["eye_ratio_min"].as_f64().unwrap_or(0.25);
let max = config.thresholds["eye_ratio_max"].as_f64().unwrap_or(0.55);
if eye_ratio < min || eye_ratio > max {
score -= 0.25;
reasons.push(format!("eye_ratio abnormal ({:.3})", eye_ratio));
@@ -200,7 +204,7 @@ impl FilterEngine {
// Check nose ratio
if let Some(nose_ratio) = features.nose_ratio {
let min = config.thresholds["nose_ratio_min"].as_f64().unwrap_or(0.08);
if nose_ratio < min {
score -= 0.25;
reasons.push(format!("nose_ratio too low ({:.3})", nose_ratio));
@@ -210,7 +214,7 @@ impl FilterEngine {
// Check pose score
if let Some(pose_score) = features.pose_score {
let max = config.thresholds["pose_score_max"].as_f64().unwrap_or(0.8);
if pose_score > max {
score -= 0.25;
reasons.push(format!("pose_score too high ({:.3})", pose_score));
@@ -233,7 +237,11 @@ impl FilterEngine {
}
/// Apply MediaPipe verification rule
fn apply_mediapipe_verification(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
fn apply_mediapipe_verification(
&self,
features: &FaceFilterFeatures,
config: &RuleConfig,
) -> RuleResult {
if !config.enabled {
return RuleResult {
enabled: false,
@@ -256,7 +264,7 @@ impl FilterEngine {
// Check IoU if available
if let Some(iou) = features.mediapipe_iou {
let min_iou = config.thresholds["min_iou"].as_f64().unwrap_or(0.3);
if iou < min_iou {
return RuleResult {
enabled: true,
@@ -276,7 +284,11 @@ impl FilterEngine {
}
/// Apply embedding similarity rule
fn apply_embedding_similarity(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
fn apply_embedding_similarity(
&self,
features: &FaceFilterFeatures,
config: &RuleConfig,
) -> RuleResult {
if !config.enabled {
return RuleResult {
enabled: false,
@@ -288,7 +300,7 @@ impl FilterEngine {
if let Some(similarity) = features.embedding_similarity {
let min_similarity = config.thresholds["min_similarity"].as_f64().unwrap_or(0.70);
if similarity < min_similarity {
return RuleResult {
enabled: true,
@@ -308,7 +320,11 @@ impl FilterEngine {
}
/// Apply temporal consistency rule
fn apply_temporal_consistency(&self, features: &FaceFilterFeatures, config: &RuleConfig) -> RuleResult {
fn apply_temporal_consistency(
&self,
features: &FaceFilterFeatures,
config: &RuleConfig,
) -> RuleResult {
if !config.enabled {
return RuleResult {
enabled: false,
@@ -319,8 +335,10 @@ impl FilterEngine {
}
if let Some(consecutive) = features.consecutive_frames {
let min_consecutive = config.thresholds["min_consecutive_frames"].as_i64().unwrap_or(3) as i32;
let min_consecutive = config.thresholds["min_consecutive_frames"]
.as_i64()
.unwrap_or(3) as i32;
if consecutive < min_consecutive {
return RuleResult {
enabled: true,
@@ -343,42 +361,54 @@ impl FilterEngine {
/// Default filter configuration
pub fn default_filter_config() -> FilterRuleConfig {
let mut rules = HashMap::new();
rules.insert("landmark_analysis".to_string(), RuleConfig {
enabled: true,
weight: 0.3,
thresholds: serde_json::json!({
"eye_ratio_min": 0.25,
"eye_ratio_max": 0.55,
"nose_ratio_min": 0.08,
"pose_score_max": 0.8
}),
});
rules.insert("mediapipe_verification".to_string(), RuleConfig {
enabled: true,
weight: 0.2,
thresholds: serde_json::json!({
"min_iou": 0.3
}),
});
rules.insert("embedding_similarity".to_string(), RuleConfig {
enabled: true,
weight: 0.3,
thresholds: serde_json::json!({
"min_similarity": 0.70
}),
});
rules.insert("temporal_consistency".to_string(), RuleConfig {
enabled: true,
weight: 0.2,
thresholds: serde_json::json!({
"min_consecutive_frames": 3
}),
});
rules.insert(
"landmark_analysis".to_string(),
RuleConfig {
enabled: true,
weight: 0.3,
thresholds: serde_json::json!({
"eye_ratio_min": 0.25,
"eye_ratio_max": 0.55,
"nose_ratio_min": 0.08,
"pose_score_max": 0.8
}),
},
);
rules.insert(
"mediapipe_verification".to_string(),
RuleConfig {
enabled: true,
weight: 0.2,
thresholds: serde_json::json!({
"min_iou": 0.3
}),
},
);
rules.insert(
"embedding_similarity".to_string(),
RuleConfig {
enabled: true,
weight: 0.3,
thresholds: serde_json::json!({
"min_similarity": 0.70
}),
},
);
rules.insert(
"temporal_consistency".to_string(),
RuleConfig {
enabled: true,
weight: 0.2,
thresholds: serde_json::json!({
"min_consecutive_frames": 3
}),
},
);
FilterRuleConfig {
version: "1.0".to_string(),
rules,
@@ -398,11 +428,12 @@ mod tests {
fn test_filter_engine_accept() {
let config = default_filter_config();
let engine = FilterEngine::new(config);
let features = FaceFilterFeatures {
face_id: "test_001".to_string(),
file_uuid: "test".to_string(),
frame: 0,
bbox_size: Some(80),
eye_ratio: Some(0.37),
nose_ratio: Some(0.15),
pose_score: Some(0.1),
@@ -415,7 +446,7 @@ mod tests {
mediapipe_confidence: Some(0.9),
primary_source: Some("apple_vision".to_string()),
};
let result = engine.filter_face(&features).unwrap();
assert_eq!(result.recommendation, FilterRecommendation::Accept);
}
@@ -424,24 +455,25 @@ mod tests {
fn test_filter_engine_reject() {
let config = default_filter_config();
let engine = FilterEngine::new(config);
let features = FaceFilterFeatures {
face_id: "test_002".to_string(),
file_uuid: "test".to_string(),
frame: 671,
eye_ratio: Some(0.33),
nose_ratio: Some(0.02), // Abnormal
pose_score: Some(0.08),
mediapipe_detected: Some(false), // Not detected
bbox_size: Some(40),
eye_ratio: Some(0.60), // Abnormal (above max 0.55)
nose_ratio: Some(0.02), // Abnormal
pose_score: Some(0.9), // Abnormal (above max 0.8)
mediapipe_detected: Some(false), // Not detected
mediapipe_iou: Some(0.0),
embedding_similarity: Some(0.15), // Low similarity
consecutive_frames: Some(1), // Single frame
embedding_similarity: Some(0.05), // Very low similarity
consecutive_frames: Some(1), // Single frame
total_frames_detected: Some(1),
apple_vision_confidence: Some(0.84),
mediapipe_confidence: None,
primary_source: Some("apple_vision".to_string()),
};
let result = engine.filter_face(&features).unwrap();
assert_eq!(result.recommendation, FilterRecommendation::Reject);
}
+32 -3
View File
@@ -2,17 +2,21 @@ use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use crate::core::config::{FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_SIZE_DEFAULT};
/// Version of the file profile schema.
const PROFILE_VERSION: &str = "1.0";
// ─── Data Types ───
/// Per-file face detection thresholds. `min_confidence` is 0–100 (%),
/// `min_size` is px. Mirrors `videos.face_filter` DB column (same units).
/// `min_size` is px, `min_capture_quality` is 0–1. Mirrors `videos.face_filter` DB column.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaceFilterSettings {
pub min_confidence: f64,
pub min_size: i32,
#[serde(default)]
pub min_capture_quality: f64,
}
impl FaceFilterSettings {
@@ -20,8 +24,9 @@ impl FaceFilterSettings {
/// Filter later for display; detect everything first.
pub fn defaults() -> Self {
Self {
min_confidence: 50.0,
min_size: 1,
min_confidence: FACE_FILTER_CONFIDENCE_PCT_DEFAULT,
min_size: FACE_MIN_SIZE_DEFAULT,
min_capture_quality: 0.0,
}
}
}
@@ -378,7 +383,19 @@ pub struct FaceTraceProfile {
pub frame_count: i64,
pub start_frame: i64,
pub end_frame: i64,
#[serde(default)]
pub best_frame: Option<i64>,
pub avg_confidence: Option<f64>,
#[serde(default)]
pub best_confidence: Option<f64>,
#[serde(default)]
pub avg_capture_quality: Option<f64>,
#[serde(default)]
pub best_capture_quality: Option<f64>,
#[serde(default)]
pub avg_bbox: Option<serde_json::Value>,
#[serde(default)]
pub best_bbox: Option<serde_json::Value>,
pub key_frame: Option<String>, // filename: key_frame.jpg
pub key_face: Option<String>, // filename: key_face.jpg
pub status: String, // pending / bound / merged
@@ -406,7 +423,13 @@ impl FaceTraceProfile {
frame_count: i64,
start_frame: i64,
end_frame: i64,
best_frame: i64,
avg_confidence: Option<f64>,
avg_capture_quality: Option<f64>,
best_confidence: f64,
best_capture_quality: f64,
avg_bbox: serde_json::Value,
best_bbox: Option<serde_json::Value>,
) -> Self {
Self {
version: PROFILE_VERSION.to_string(),
@@ -416,7 +439,13 @@ impl FaceTraceProfile {
frame_count,
start_frame,
end_frame,
best_frame: Some(best_frame),
avg_confidence,
best_confidence: Some(best_confidence),
avg_capture_quality,
best_capture_quality: Some(best_capture_quality),
avg_bbox: Some(avg_bbox),
best_bbox,
key_frame: None,
key_face: None,
status: "pending".to_string(),
+7
View File
@@ -107,8 +107,10 @@ mod tests {
#[test]
fn test_asr_result_serialization() {
let result = AsrResult {
status: None,
language: Some("en".to_string()),
language_probability: Some(0.95),
segment_count: 2,
segments: vec![
AsrSegment {
start_time: 0.0,
@@ -116,6 +118,7 @@ mod tests {
start_frame: Some(0),
end_frame: Some(60),
text: "Hello world".to_string(),
confidence: 0.95,
},
AsrSegment {
start_time: 2.5,
@@ -123,6 +126,7 @@ mod tests {
start_frame: Some(60),
end_frame: Some(120),
text: "Test speech".to_string(),
confidence: 0.9,
},
],
};
@@ -157,6 +161,7 @@ mod tests {
start_frame: Some(0),
end_frame: Some(24),
text: String::new(),
confidence: 0.0,
};
assert_eq!(segment.start_time, 0.0);
assert_eq!(segment.end_time, 1.0);
@@ -166,9 +171,11 @@ mod tests {
#[test]
fn test_asr_result_empty_segments() {
let result = AsrResult {
status: None,
language: None,
language_probability: None,
segments: vec![],
segment_count: 0,
};
assert!(result.language.is_none());
assert!(result.segments.is_empty());
+4
View File
@@ -214,6 +214,7 @@ mod tests {
#[test]
fn test_asrx_result_serialization() {
let result = AsrxResult {
status: None,
language: Some("en".to_string()),
segments: vec![AsrxSegment {
start_time: 0.0,
@@ -227,6 +228,7 @@ mod tests {
quality: None,
}],
embeddings: None,
segment_count: 1,
};
let json = serde_json::to_string(&result).unwrap();
@@ -255,9 +257,11 @@ mod tests {
#[test]
fn test_asrx_result_empty_segments() {
let result = AsrxResult {
status: None,
language: None,
segments: vec![],
embeddings: None,
segment_count: 0,
};
assert!(result.segments.is_empty());
assert!(result.language.is_none());
+9
View File
@@ -53,6 +53,8 @@ pub struct Face {
pub width: i32,
pub height: i32,
pub confidence: f32,
#[serde(default)]
pub capture_quality: Option<f32>,
pub embedding: Option<Vec<f32>>,
pub landmarks: Option<serde_json::Value>,
pub pose_angle: Option<serde_json::Value>,
@@ -148,8 +150,10 @@ mod tests {
#[test]
fn test_face_result_serialization() {
let result = FaceResult {
status: None,
frame_count: 100,
fps: 30.0,
total_faces: 1,
frames: vec![FaceFrame {
frame: 0,
timestamp: 0.0,
@@ -160,6 +164,7 @@ mod tests {
width: 50,
height: 60,
confidence: 0.95,
capture_quality: Some(0.9),
embedding: Some(vec![0.1, 0.2, 0.3]),
landmarks: Some(serde_json::json!([[10.0, 20.0], [30.0, 40.0]])),
pose_angle: None,
@@ -216,9 +221,11 @@ mod tests {
#[test]
fn test_face_result_empty_frames() {
let result = FaceResult {
status: None,
frame_count: 0,
fps: 0.0,
frames: vec![],
total_faces: 0,
};
assert!(result.frames.is_empty());
}
@@ -232,6 +239,7 @@ mod tests {
width: 10,
height: 10,
confidence: 0.5,
capture_quality: None,
embedding: None,
landmarks: None,
pose_angle: None,
@@ -249,6 +257,7 @@ mod tests {
width: 50,
height: 60,
confidence: 0.95,
capture_quality: Some(0.8),
embedding: Some(vec![0.1; 512]),
landmarks: None,
pose_angle: None,
+73 -10
View File
@@ -20,6 +20,7 @@ struct FacePoint {
w: f64,
h: f64,
confidence: f64,
capture_quality: f64,
point_id: Option<String>,
}
@@ -121,6 +122,7 @@ fn parse_face_points(points: Vec<serde_json::Value>) -> Vec<FacePoint> {
w,
h,
confidence: payload["confidence"].as_f64().unwrap_or(0.5),
capture_quality: payload["capture_quality"].as_f64().unwrap_or(0.0),
point_id: p["id"].as_u64().map(|id| id.to_string()),
})
})
@@ -1134,10 +1136,16 @@ async fn build_face_track_nodes_from_qdrant(
sum_w: f64,
sum_h: f64,
sum_confidence: f64,
sum_capture_quality: f64,
frames: Vec<(i64, f64, f64, f64, f64)>, // (frame, x, y, w, h)
best_frame: i64,
best_confidence: f64,
best_point_id: Option<String>,
cq_best_frame: i64,
cq_best_quality: f64,
cq_best_point_id: Option<String>,
cq_best_bbox: Option<serde_json::Value>,
best_bbox: Option<serde_json::Value>,
}
let mut traces: HashMap<i64, TraceAgg> = HashMap::new();
@@ -1151,10 +1159,16 @@ async fn build_face_track_nodes_from_qdrant(
sum_w: 0.0,
sum_h: 0.0,
sum_confidence: 0.0,
sum_capture_quality: 0.0,
frames: vec![],
best_frame: 0,
best_confidence: 0.0,
best_point_id: None,
cq_best_frame: 0,
cq_best_quality: 0.0,
cq_best_point_id: None,
cq_best_bbox: None,
best_bbox: None,
});
entry.frame_count += 1;
entry.start_f = entry.start_f.min(p.frame);
@@ -1164,12 +1178,31 @@ async fn build_face_track_nodes_from_qdrant(
entry.sum_w += p.w;
entry.sum_h += p.h;
entry.sum_confidence += p.confidence;
entry.sum_capture_quality += p.capture_quality;
entry.frames.push((p.frame, p.x, p.y, p.w, p.h));
// Track best face (highest confidence)
if p.confidence > entry.best_confidence {
entry.best_confidence = p.confidence;
entry.best_frame = p.frame;
entry.best_point_id = p.point_id.clone();
entry.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,
}));
}
// Track best capture quality face (used for key frame / key face set)
if p.capture_quality > entry.cq_best_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,
}));
}
}
@@ -1210,24 +1243,34 @@ async fn build_face_track_nodes_from_qdrant(
0.0
};
let avg_capture_quality = if agg.frame_count > 0 {
agg.sum_capture_quality / agg.frame_count as f64
} else {
0.0
};
let props = serde_json::json!({
"trace_id": tid,
"frame_count": agg.frame_count,
"start_frame": agg.start_f,
"end_frame": agg.end_f,
"key_frame": agg.best_frame,
"key_face": agg.best_point_id.as_deref().unwrap_or(""),
"key_frame": agg.cq_best_frame,
"key_face": agg.cq_best_point_id.as_deref().unwrap_or(""),
"avg_bbox": {
"x": (agg.sum_x / 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,
"height": (agg.sum_h / agg.frame_count as f64).round() as i64,
},
"best_bbox": agg.cq_best_bbox,
"avg_yaw": (avg_yaw * 1000.0).round() / 1000.0,
"avg_pitch": (avg_pitch * 1000.0).round() / 1000.0,
"avg_roll": (avg_roll * 1000.0).round() / 1000.0,
"pose_count": pose_count,
"avg_confidence": (avg_confidence * 1000.0).round() / 1000.0,
"best_confidence": (agg.best_confidence * 1000.0).round() / 1000.0,
"avg_capture_quality": (avg_capture_quality * 1000.0).round() / 1000.0,
"best_capture_quality": (agg.cq_best_quality * 1000.0).round() / 1000.0,
"status": "pending",
});
@@ -1277,13 +1320,19 @@ async fn build_face_track_nodes_from_qdrant(
agg.frame_count,
agg.start_f,
agg.end_f,
agg.cq_best_frame,
Some(avg_confidence),
Some(avg_capture_quality),
agg.best_confidence,
agg.cq_best_quality,
props["avg_bbox"].clone(),
agg.cq_best_bbox.clone(),
);
// Extract key_frame JPEG bytes via ffmpeg pipe
// 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 select = format!("select=eq(n\\,{})", agg.best_frame);
let select = format!("select=eq(n\\,{})", agg.cq_best_frame);
let output = std::process::Command::new("ffmpeg")
.args(["-y", "-v", "quiet", "-i"])
.arg(vp)
@@ -1311,13 +1360,13 @@ async fn build_face_track_nodes_from_qdrant(
}
});
// Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame)
// Crop key_face JPEG bytes from key_frame using representative bbox (best capture quality frame)
let key_face_jpeg: Option<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
// Find bbox for best_frame from trace frames
// Find bbox for cq_best_frame from trace frames
let (bf, bx, by, bw, bh) = agg
.frames
.iter()
.find(|(f, _, _, _, _)| *f == agg.best_frame)?;
.find(|(f, _, _, _, _)| *f == agg.cq_best_frame)?;
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
// Validate bbox: must have positive dimensions
@@ -1364,8 +1413,8 @@ async fn build_face_track_nodes_from_qdrant(
});
// Save all three files to output/{file_uuid}/{trace_id}/
let mut key_frame_file = agg.best_frame.to_string();
let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string();
let mut key_frame_file = agg.cq_best_frame.to_string();
let mut key_face_file = agg.cq_best_point_id.as_deref().unwrap_or("").to_string();
match trace_profile.save(
output_dir,
@@ -1416,7 +1465,7 @@ async fn build_face_track_nodes_from_qdrant(
if need_retry {
if let Some(ref vp) = video_path {
let select = format!("select=eq(n\\,{})", agg.best_frame);
let select = format!("select=eq(n\\,{})", agg.cq_best_frame);
// Retry key_frame extraction
if !kf_path.exists() {
if let Ok(output) = std::process::Command::new("ffmpeg")
@@ -1455,7 +1504,7 @@ async fn build_face_track_nodes_from_qdrant(
let (_, bx, by, bw, bh) = agg
.frames
.iter()
.find(|(f, _, _, _, _)| *f == agg.best_frame)
.find(|(f, _, _, _, _)| *f == agg.cq_best_frame)
.cloned()
.unwrap_or((0, 0.0, 0.0, 100.0, 100.0));
@@ -1533,10 +1582,15 @@ async fn build_face_track_nodes_from_qdrant(
"key_frame": key_frame_file,
"key_face": key_face_file,
"avg_bbox": props["avg_bbox"].clone(),
"best_bbox": props["best_bbox"].clone(),
"avg_yaw": props["avg_yaw"].clone(),
"avg_pitch": props["avg_pitch"].clone(),
"avg_roll": props["avg_roll"].clone(),
"pose_count": pose_count,
"avg_confidence": props["avg_confidence"].clone(),
"best_confidence": props["best_confidence"].clone(),
"avg_capture_quality": props["avg_capture_quality"].clone(),
"best_capture_quality": props["best_capture_quality"].clone(),
"status": "pending",
});
@@ -3601,6 +3655,7 @@ mod tests {
w: 50.0,
h: 50.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
},
FacePoint {
@@ -3611,6 +3666,7 @@ mod tests {
w: 50.0,
h: 50.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
},
FacePoint {
@@ -3621,6 +3677,7 @@ mod tests {
w: 50.0,
h: 50.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
},
FacePoint {
@@ -3631,6 +3688,7 @@ mod tests {
w: 50.0,
h: 50.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
},
];
@@ -3661,6 +3719,7 @@ mod tests {
w: 100.0,
h: 100.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
},
FacePoint {
@@ -3671,6 +3730,7 @@ mod tests {
w: 100.0,
h: 100.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
},
];
@@ -3692,6 +3752,7 @@ mod tests {
w: 100.0,
h: 100.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
},
FacePoint {
@@ -3702,6 +3763,7 @@ mod tests {
w: 100.0,
h: 100.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
},
];
@@ -3722,6 +3784,7 @@ mod tests {
w: 100.0,
h: 100.0,
confidence: 0.9,
capture_quality: 0.0,
point_id: None,
}];
let index = build_frame_index(&points);
+11 -3
View File
@@ -21,7 +21,9 @@ static FACE_TRACE_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSe
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
use crate::core::chunk::rule1_ingest;
use crate::core::config::OUTPUT_DIR;
use crate::core::config::{
FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR,
};
use crate::core::db::qdrant_db::QdrantDb;
use crate::core::db::{
schema, MonitorJobStatus, PostgresDb, ProcessorJobStatus, RedisClient, VectorPayload,
@@ -464,8 +466,14 @@ impl JobWorker {
// Read face_settings from job and set environment variables for face processor
let mut face_settings_backup: Option<(String, String)> = None;
if let Some(ref fs) = job.face_settings {
let min_confidence = fs.get("min_confidence").and_then(|v| v.as_f64()).unwrap_or(0.5);
let min_size = fs.get("min_size").and_then(|v| v.as_i64()).unwrap_or(1) as i32;
let min_confidence = fs
.get("min_confidence")
.and_then(|v| v.as_f64())
.unwrap_or(FACE_MIN_CONFIDENCE_DEFAULT);
let min_size = fs
.get("min_size")
.and_then(|v| v.as_i64())
.unwrap_or(FACE_MIN_SIZE_DEFAULT as i64) as i32;
tracing::info!(
"[WORKER] Job {} face_settings: CONFIDENCE={}, SIZE={}",
job.uuid,