fix: face pipeline 三項修復
1. face_clustering: 先試 Rust binary,Python script 缺失不再提前返回空結果 2. face.rs: facenet model 查找加 fallback ( -> momentry_core/models),config 路徑補 --model 參數 3. rust_store_traced_faces: embedding 缺失時退回純 IoU 追蹤(不再強制要求 similarity);trace_profile.json 補上真實 avg_bbox/best_bbox/capture_quality
This commit is contained in:
@@ -8,6 +8,24 @@ use super::FaceStatus;
|
|||||||
|
|
||||||
const FACE_TIMEOUT: Duration = Duration::from_secs(7200);
|
const FACE_TIMEOUT: Duration = Duration::from_secs(7200);
|
||||||
|
|
||||||
|
/// Resolve the FaceNet512 CoreML model path.
|
||||||
|
/// Priority: $MOMENTRY_MODELS_DIR/facenet512.mlpackage -> momentry_core/models/facenet512.mlpackage
|
||||||
|
pub fn facenet_model_path() -> Option<std::path::PathBuf> {
|
||||||
|
use std::path::PathBuf;
|
||||||
|
let env_dir = std::env::var("MOMENTRY_MODELS_DIR")
|
||||||
|
.ok()
|
||||||
|
.map(PathBuf::from);
|
||||||
|
let candidates = [
|
||||||
|
env_dir.map(|d| d.join("facenet512.mlpackage")),
|
||||||
|
Some(
|
||||||
|
crate::core::path_utils::momentry_core_dir()
|
||||||
|
.join("models")
|
||||||
|
.join("facenet512.mlpackage"),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
candidates.into_iter().flatten().find(|p| p.exists())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
|
pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
let rel = format!(".build/release/{}", bin);
|
let rel = format!(".build/release/{}", bin);
|
||||||
@@ -323,16 +341,14 @@ pub async fn process_face(
|
|||||||
if facenet_path.exists() {
|
if facenet_path.exists() {
|
||||||
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
|
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
|
||||||
|
|
||||||
// Resolve model path
|
// Resolve model path (env dir -> momentry_core/models fallback)
|
||||||
let models_dir =
|
let model_path = match facenet_model_path() {
|
||||||
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
|
Some(p) => p,
|
||||||
let model_path = models_dir.join("facenet512.mlpackage");
|
None => {
|
||||||
|
tracing::error!("[FACE] FaceNet model not found (checked $MOMENTRY_MODELS_DIR and momentry_core/models)");
|
||||||
if !model_path.exists() {
|
|
||||||
tracing::error!("[FACE] FaceNet model not found at {:?}", model_path);
|
|
||||||
tracing::error!("[FACE] Set MOMENTRY_MODELS_DIR environment variable or ensure models/facenet512.mlpackage exists");
|
|
||||||
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
|
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let facenet_output = format!("{}.with_embedding", output_path);
|
let facenet_output = format!("{}.with_embedding", output_path);
|
||||||
let facenet_args = vec![
|
let facenet_args = vec![
|
||||||
@@ -549,11 +565,17 @@ async fn run_face_with_config(
|
|||||||
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
|
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
|
||||||
|
|
||||||
let facenet_output = format!("{}.with_embedding", output_path);
|
let facenet_output = format!("{}.with_embedding", output_path);
|
||||||
let facenet_args = vec![
|
let mut facenet_args = vec![
|
||||||
video_path.to_string(),
|
video_path.to_string(),
|
||||||
output_path.to_string(),
|
output_path.to_string(),
|
||||||
facenet_output.clone(),
|
facenet_output.clone(),
|
||||||
];
|
];
|
||||||
|
// Explicit --model (the binary otherwise derives the path from
|
||||||
|
// MOMENTRY_MODELS_DIR, which may not contain facenet512)
|
||||||
|
if let Some(model_path) = facenet_model_path() {
|
||||||
|
facenet_args.push("--model".to_string());
|
||||||
|
facenet_args.push(model_path.to_string_lossy().to_string());
|
||||||
|
}
|
||||||
|
|
||||||
let facenet_result = tokio::process::Command::new(facenet_path)
|
let facenet_result = tokio::process::Command::new(facenet_path)
|
||||||
.args(&facenet_args)
|
.args(&facenet_args)
|
||||||
|
|||||||
@@ -159,11 +159,14 @@ pub async fn process_face_cluster(
|
|||||||
similarity_threshold: Option<f64>,
|
similarity_threshold: Option<f64>,
|
||||||
) -> Result<FaceClusterResult> {
|
) -> Result<FaceClusterResult> {
|
||||||
let executor = PythonExecutor::new()?;
|
let executor = PythonExecutor::new()?;
|
||||||
let script_path = executor.script_path("fast_face_clustering_processor.py");
|
|
||||||
|
|
||||||
tracing::info!("[FACE_CLUSTER] Starting face clustering: {}", video_path);
|
tracing::info!("[FACE_CLUSTER] Starting face clustering: {}", video_path);
|
||||||
|
|
||||||
if !script_path.exists() {
|
// Try Rust binary first (preferred); legacy Python script is only a fallback.
|
||||||
|
// Do NOT bail early just because the Python script is missing — that would
|
||||||
|
// skip the Rust binary even when it exists.
|
||||||
|
let script_path = executor.script_path("fast_face_clustering_processor.py");
|
||||||
|
if executor.rust_binary_path("rust_face_cluster").is_none() && !script_path.exists() {
|
||||||
tracing::warn!("[FACE_CLUSTER] Script not found, returning empty result");
|
tracing::warn!("[FACE_CLUSTER] Script not found, returning empty result");
|
||||||
return Ok(FaceClusterResult {
|
return Ok(FaceClusterResult {
|
||||||
schema_version: "2.0".to_string(),
|
schema_version: "2.0".to_string(),
|
||||||
|
|||||||
@@ -349,9 +349,64 @@ fn extract_full_frame(video_path: &str, frame_num: usize, output: &std::path::Pa
|
|||||||
fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::Path) {
|
fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::Path) {
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
let best_confidence = trace.best_confidence;
|
// Compute real stats from face instances (fallback to path when instances empty)
|
||||||
let avg_confidence = trace.avg_confidence;
|
let instances: &Vec<TracePoint> = if !trace.face_instances.is_empty() {
|
||||||
let best_frame = trace.best_frame;
|
&trace.face_instances
|
||||||
|
} else {
|
||||||
|
&trace.path
|
||||||
|
};
|
||||||
|
|
||||||
|
let avg_confidence = if !instances.is_empty() {
|
||||||
|
instances.iter().map(|p| p.confidence as f64).sum::<f64>() / instances.len() as f64
|
||||||
|
} else {
|
||||||
|
trace.avg_confidence
|
||||||
|
};
|
||||||
|
|
||||||
|
let best = instances.iter().max_by(|a, b| {
|
||||||
|
a.confidence
|
||||||
|
.partial_cmp(&b.confidence)
|
||||||
|
.unwrap_or(std::cmp::Ordering::Equal)
|
||||||
|
});
|
||||||
|
|
||||||
|
let best_frame = best.map(|p| p.frame as u64).unwrap_or(trace.best_frame as u64);
|
||||||
|
let best_confidence = best.map(|p| p.confidence as f64).unwrap_or(trace.best_confidence);
|
||||||
|
|
||||||
|
let best_capture_quality = instances
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.capture_quality as f64)
|
||||||
|
.fold(0.0f64, |acc, q| if q > acc { q } else { acc });
|
||||||
|
let avg_capture_quality = if !instances.is_empty() {
|
||||||
|
instances.iter().map(|p| p.capture_quality as f64).sum::<f64>() / instances.len() as f64
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
|
||||||
|
let best_bbox = best.map(|p| {
|
||||||
|
serde_json::json!({
|
||||||
|
"x": p.bbox.x, "y": p.bbox.y,
|
||||||
|
"width": p.bbox.width, "height": p.bbox.height,
|
||||||
|
"x2": p.bbox.x2, "y2": p.bbox.y2,
|
||||||
|
"center_x": p.bbox.center_x, "center_y": p.bbox.center_y,
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
let avg_bbox = if !instances.is_empty() {
|
||||||
|
let mut b = trace.avg_bbox.clone();
|
||||||
|
let n = instances.len() as i32;
|
||||||
|
b.x = instances.iter().map(|p| p.bbox.x).sum::<i32>() / n;
|
||||||
|
b.y = instances.iter().map(|p| p.bbox.y).sum::<i32>() / n;
|
||||||
|
b.width = instances.iter().map(|p| p.bbox.width).sum::<i32>() / n;
|
||||||
|
b.height = instances.iter().map(|p| p.bbox.height).sum::<i32>() / n;
|
||||||
|
b.compute_derived();
|
||||||
|
serde_json::json!({
|
||||||
|
"x": b.x, "y": b.y,
|
||||||
|
"width": b.width, "height": b.height,
|
||||||
|
"x2": b.x2, "y2": b.y2,
|
||||||
|
"center_x": b.center_x, "center_y": b.center_y,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
serde_json::Value::Null
|
||||||
|
};
|
||||||
|
|
||||||
let profile = serde_json::json!({
|
let profile = serde_json::json!({
|
||||||
"version": "1.0",
|
"version": "1.0",
|
||||||
@@ -364,10 +419,10 @@ fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::P
|
|||||||
"best_frame": best_frame,
|
"best_frame": best_frame,
|
||||||
"avg_confidence": avg_confidence,
|
"avg_confidence": avg_confidence,
|
||||||
"best_confidence": best_confidence,
|
"best_confidence": best_confidence,
|
||||||
"avg_capture_quality": null,
|
"avg_capture_quality": avg_capture_quality,
|
||||||
"best_capture_quality": null,
|
"best_capture_quality": best_capture_quality,
|
||||||
"avg_bbox": null,
|
"avg_bbox": avg_bbox,
|
||||||
"best_bbox": null,
|
"best_bbox": best_bbox,
|
||||||
"key_frame": "key_frame.jpg",
|
"key_frame": "key_frame.jpg",
|
||||||
"key_face": "key_face.jpg",
|
"key_face": "key_face.jpg",
|
||||||
"status": "pending",
|
"status": "pending",
|
||||||
@@ -790,10 +845,18 @@ fn run_face_tracking(
|
|||||||
_ => 0.0,
|
_ => 0.0,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Match if IoU AND similarity meet thresholds
|
// Match if IoU AND similarity meet thresholds.
|
||||||
if iou > best_iou
|
// When embeddings are unavailable (either face missing its
|
||||||
|
// vector), fall back to IoU-only geometric continuation:
|
||||||
|
// consecutive frames of the same face have overlapping bboxes.
|
||||||
|
let matched = if current_embedding.is_none() || prev_embedding.is_none() {
|
||||||
|
iou > best_iou && iou > iou_threshold
|
||||||
|
} else {
|
||||||
|
iou > best_iou
|
||||||
&& iou > iou_threshold
|
&& iou > iou_threshold
|
||||||
&& similarity > similarity_threshold {
|
&& similarity > similarity_threshold
|
||||||
|
};
|
||||||
|
if matched {
|
||||||
best_iou = iou;
|
best_iou = iou;
|
||||||
best_match = Some((prev_trace_id, iou, similarity));
|
best_match = Some((prev_trace_id, iou, similarity));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user