fix: face pipeline 三項修復
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled

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:
Accusys
2026-11-17 17:26:00 +08:00
parent 5056c20667
commit 5b5c1d9563
3 changed files with 113 additions and 25 deletions
+33 -11
View File
@@ -8,6 +8,24 @@ use super::FaceStatus;
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 {
use std::path::PathBuf;
let rel = format!(".build/release/{}", bin);
@@ -323,16 +341,14 @@ pub async fn process_face(
if facenet_path.exists() {
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
// Resolve model path
let models_dir =
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let model_path = models_dir.join("facenet512.mlpackage");
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");
}
// Resolve model path (env dir -> momentry_core/models fallback)
let model_path = match facenet_model_path() {
Some(p) => p,
None => {
tracing::error!("[FACE] FaceNet model not found (checked $MOMENTRY_MODELS_DIR and momentry_core/models)");
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
}
};
let facenet_output = format!("{}.with_embedding", output_path);
let facenet_args = vec![
@@ -549,11 +565,17 @@ async fn run_face_with_config(
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
let facenet_output = format!("{}.with_embedding", output_path);
let facenet_args = vec![
let mut facenet_args = vec![
video_path.to_string(),
output_path.to_string(),
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)
.args(&facenet_args)
+5 -2
View File
@@ -159,11 +159,14 @@ pub async fn process_face_cluster(
similarity_threshold: Option<f64>,
) -> Result<FaceClusterResult> {
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("fast_face_clustering_processor.py");
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");
return Ok(FaceClusterResult {
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) {
use std::io::Write;
let best_confidence = trace.best_confidence;
let avg_confidence = trace.avg_confidence;
let best_frame = trace.best_frame;
// Compute real stats from face instances (fallback to path when instances empty)
let instances: &Vec<TracePoint> = if !trace.face_instances.is_empty() {
&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!({
"version": "1.0",
@@ -364,10 +419,10 @@ fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::P
"best_frame": best_frame,
"avg_confidence": avg_confidence,
"best_confidence": best_confidence,
"avg_capture_quality": null,
"best_capture_quality": null,
"avg_bbox": null,
"best_bbox": null,
"avg_capture_quality": avg_capture_quality,
"best_capture_quality": best_capture_quality,
"avg_bbox": avg_bbox,
"best_bbox": best_bbox,
"key_frame": "key_frame.jpg",
"key_face": "key_face.jpg",
"status": "pending",
@@ -789,11 +844,19 @@ fn run_face_tracking(
(Some(curr), Some(prev)) => calculate_cosine_similarity(curr, prev),
_ => 0.0,
};
// Match if IoU AND similarity meet thresholds
if iou > best_iou
&& iou > iou_threshold
&& similarity > similarity_threshold {
// Match if IoU AND similarity meet thresholds.
// 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
&& similarity > similarity_threshold
};
if matched {
best_iou = iou;
best_match = Some((prev_trace_id, iou, similarity));
}