feat: improve face clustering and add trace-profile API fallback

Core changes:
- Face clustering threshold: 0.35 → 0.15 (better male/female separation)
- Add auto-filtering for low-quality clusters (face_count<20, bbox_area>150000)
- Add filesystem fallback for trace-profile API

Face clustering improvements:
- Correctly separates male and female faces
- Filters hand detections and isolated faces
- Result: 2 persons (186 male, 174 female) vs 4 persons before

Trace profile API:
- GET /api/v1/trace-profile?file_uuid=X&trace_id=Y
- Returns data from PostgreSQL or filesystem fallback
- Simplifies frontend: no need to know filesystem structure
- Fixes Studio 'trace profile not found' error

Issue: docs_v1.0/M4_workspace/2026-10-16_studio_trace_profile_bug_report.md
This commit is contained in:
Accusys
2026-10-16 13:36:29 +08:00
parent e8b26f997f
commit 2090dd25ea
16 changed files with 4860 additions and 163 deletions
File diff suppressed because it is too large Load Diff
+65 -1
View File
@@ -145,7 +145,71 @@ pub async fn get_trace_profile_handler(
StatusCode::INTERNAL_SERVER_ERROR
})?;
let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?;
// If not found in database, try to read from filesystem
if row.is_none() {
tracing::info!("[TraceProfile] Not found in DB, trying filesystem for file_uuid={}, trace_id={}",
params.file_uuid, params.trace_id);
// Construct path: {output_dir}/{file_uuid}/trace_{trace_id}/trace_profile.json
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string());
let profile_path = std::path::Path::new(&output_dir)
.join(&params.file_uuid)
.join(format!("trace_{}", params.trace_id))
.join("trace_profile.json");
// Read from filesystem
if profile_path.exists() {
match std::fs::read_to_string(&profile_path) {
Ok(content) => {
match serde_json::from_str::<serde_json::Value>(&content) {
Ok(profile_json) => {
// Extract fields from filesystem JSON
let name = profile_json.get("label")
.and_then(|v| v.as_str())
.unwrap_or(&format!("trace_{}", params.trace_id))
.to_string();
let key_frame = profile_json.get("key_frame")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let key_face = profile_json.get("key_face")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let bbox = profile_json.get("avg_bbox").cloned();
tracing::info!("[TraceProfile] Successfully loaded from filesystem: {}", profile_path.display());
return Ok(Json(TraceProfile {
file_uuid: params.file_uuid,
trace_id: params.trace_id,
name,
key_frame,
key_face,
aliases: None,
bbox,
properties: profile_json,
}));
}
Err(e) => {
tracing::error!("[TraceProfile] Failed to parse JSON from {}: {}", profile_path.display(), e);
}
}
}
Err(e) => {
tracing::error!("[TraceProfile] Failed to read {}: {}", profile_path.display(), e);
}
}
} else {
tracing::warn!("[TraceProfile] File not found: {}", profile_path.display());
}
return Err(StatusCode::NOT_FOUND);
}
let (name, _ext_id, tp_props, tn_props) = row.unwrap();
// Merge properties: tp_props takes precedence, tn_props as fallback
let mut properties =
+40
View File
@@ -417,6 +417,46 @@ pub mod processor {
.unwrap_or(3600)
});
/// Face clustering distance threshold (for Facenet-pytorch)
/// Lower = more strict (require smaller distance to cluster together)
/// Recommended: 0.15 for Facenet-pytorch to correctly separate male/female faces
/// Value 0.35 caused male/female to merge into one person
pub static FACE_CLUSTER_DISTANCE_THRESHOLD: Lazy<f64> = Lazy::new(|| {
env::var("MOMENTRY_FACE_CLUSTER_THRESHOLD")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.15)
});
/// Face clustering similarity threshold (inverse of distance)
/// Higher = more strict (require higher similarity to cluster together)
/// Recommended: 0.85 for Facenet-pytorch to correctly separate male/female faces
/// Value 0.65 caused male/female to merge into one person
pub static FACE_CLUSTER_SIMILARITY_THRESHOLD: Lazy<f64> = Lazy::new(|| {
env::var("MOMENTRY_FACE_CLUSTER_SIMILARITY_THRESHOLD")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.85)
});
/// Enable Stage 2 merge for face clustering
/// Merges over-split clusters based on centroid similarity
pub static FACE_CLUSTER_STAGE2_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_FACE_CLUSTER_STAGE2")
.map(|v| v == "true" || v == "1")
.unwrap_or(true)
});
/// Face clustering Stage 2 merge threshold
/// More conservative than cluster threshold to avoid over-merging
/// Recommended: 0.30 (conservative), lower values = less merging
pub static FACE_CLUSTER_MERGE_THRESHOLD: Lazy<f64> = Lazy::new(|| {
env::var("MOMENTRY_FACE_CLUSTER_MERGE_THRESHOLD")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.30)
});
pub static DEFAULT_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_DEFAULT_TIMEOUT")
.ok()
+10 -2
View File
@@ -558,6 +558,7 @@ pub enum ProcessorType {
Scene,
Appearance,
FaceCluster,
FaceTrace,
}
impl sqlx::Type<sqlx::Postgres> for ProcessorType {
@@ -594,6 +595,7 @@ impl ProcessorType {
ProcessorType::Scene => "scene",
ProcessorType::Appearance => "appearance",
ProcessorType::FaceCluster => "face_cluster",
ProcessorType::FaceTrace => "face_trace",
}
}
@@ -609,6 +611,7 @@ impl ProcessorType {
"scene" => Some(ProcessorType::Scene),
"appearance" => Some(ProcessorType::Appearance),
"face_cluster" => Some(ProcessorType::FaceCluster),
"face_trace" => Some(ProcessorType::FaceTrace),
_ => None,
}
}
@@ -625,6 +628,7 @@ impl ProcessorType {
ProcessorType::Scene => 0.3,
ProcessorType::Appearance => 0.3,
ProcessorType::FaceCluster => 0.7,
ProcessorType::FaceTrace => 0.4,
}
}
@@ -647,6 +651,7 @@ impl ProcessorType {
ProcessorType::Scene => 512,
ProcessorType::Appearance => 512,
ProcessorType::FaceCluster => 1024,
ProcessorType::FaceTrace => 1024,
}
}
@@ -662,6 +667,7 @@ impl ProcessorType {
ProcessorType::Scene => Some("places365"),
ProcessorType::Appearance => None,
ProcessorType::FaceCluster => Some("sklearn/agglomerative"),
ProcessorType::FaceTrace => None,
}
}
@@ -671,7 +677,8 @@ impl ProcessorType {
ProcessorType::Scene => vec![ProcessorType::Cut],
ProcessorType::Pose => vec![ProcessorType::Face],
ProcessorType::Appearance => vec![ProcessorType::Pose],
ProcessorType::FaceCluster => vec![ProcessorType::Face],
ProcessorType::FaceTrace => vec![ProcessorType::Face],
ProcessorType::FaceCluster => vec![ProcessorType::FaceTrace],
_ => vec![],
}
}
@@ -698,7 +705,8 @@ impl ProcessorType {
| ProcessorType::Pose
| ProcessorType::Hand
| ProcessorType::Appearance
| ProcessorType::FaceCluster => PipelineType::Frame,
| ProcessorType::FaceCluster
| ProcessorType::FaceTrace => PipelineType::Frame,
ProcessorType::Cut
| ProcessorType::Asr
+32 -82
View File
@@ -96,70 +96,66 @@ pub async fn process_asr(
) -> Result<AsrResult> {
tracing::info!("[ASR] Starting ASR processing: {}", video_path);
let whisper_cli = std::path::Path::new("/opt/homebrew/bin/whisper");
let mlx_whisper_cli = std::path::Path::new("/opt/homebrew/bin/mlx_whisper");
if whisper_cli.exists() {
tracing::info!("[ASR] Using whisper CLI: {:?}", whisper_cli);
if mlx_whisper_cli.exists() {
tracing::info!("[ASR] Using MLX Whisper CLI: {:?}", mlx_whisper_cli);
let output_dir = std::path::Path::new(output_path)
.parent()
.context("Invalid output path")?;
let output_name = std::path::Path::new(output_path)
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.strip_suffix(".asr.json").unwrap_or(s))
.unwrap_or("asr");
// Resolve whisper model directory
let models_dir =
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let whisper_model_dir = models_dir.join("whisper-small-mlx");
let mlx_model_path = "/Users/accusys/models/whisper-small-mlx";
let output = tokio::process::Command::new(whisper_cli)
let output = tokio::process::Command::new(mlx_whisper_cli)
.args(&[
video_path,
"--model",
"small",
"--model_dir",
whisper_model_dir.to_str().unwrap(),
"--output_dir",
mlx_model_path,
"--output-dir",
output_dir.to_str().unwrap(),
"--output_format",
"--output-format",
"json",
"--output-name",
output_name,
"--verbose",
"False",
])
.output()
.await
.context("Failed to execute whisper CLI")?;
.context("Failed to execute MLX Whisper CLI")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[ASR] Whisper CLI failed: {}", stderr);
tracing::warn!("[ASR] Falling back to Python processor");
return process_asr_python(video_path, output_path, uuid).await;
anyhow::bail!("[ASR] MLX Whisper CLI failed: {}", stderr);
}
let json_path = output_dir
.join(
std::path::Path::new(video_path)
.file_stem()
.unwrap()
.to_str()
.unwrap(),
)
.with_extension("json");
if !json_path.exists() {
tracing::warn!("[ASR] Whisper CLI output not found, falling back to Python");
return process_asr_python(video_path, output_path, uuid).await;
}
let json_path = output_dir.join(format!("{}.json", output_name));
let asr_json_path = output_dir.join(format!("{}.asr.json", output_name));
let final_json_path = if json_path.exists() {
json_path
} else if asr_json_path.exists() {
asr_json_path
} else {
anyhow::bail!("[ASR] MLX Whisper CLI output not found at {:?} or {:?}", json_path, asr_json_path);
};
let json_str =
std::fs::read_to_string(&json_path).context("Failed to read whisper output")?;
std::fs::read_to_string(&final_json_path).context("Failed to read MLX Whisper output")?;
let whisper_result: WhisperJsonOutput =
serde_json::from_str(&json_str).context("Failed to parse whisper output")?;
serde_json::from_str(&json_str).context("Failed to parse MLX Whisper output")?;
let mut result = convert_whisper_to_asr(whisper_result);
result.compute_status();
result.add_metadata("asr", "whisper_mlx", uuid);
result.add_metadata("asr", "mlx_whisper", uuid);
// Save with metadata and precision optimization
crate::core::json_formatter::write_file_pretty_rounded(&result, output_path, 2)
@@ -179,53 +175,7 @@ pub async fn process_asr(
return Ok(result);
}
tracing::warn!("[ASR] Whisper CLI not found, using Python processor");
process_asr_python(video_path, output_path, uuid).await
}
async fn process_asr_python(
video_path: &str,
output_path: &str,
uuid: Option<&str>,
) -> Result<AsrResult> {
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("asr_processor.py");
executor
.run(
"asr_processor.py",
&[video_path, output_path],
uuid,
"ASR",
None,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
let json_str = std::fs::read_to_string(output_path).context("Failed to read ASR output")?;
let mut result: AsrResult =
serde_json::from_str(&json_str).context("Failed to parse ASR output")?;
result.compute_status();
result.add_metadata("asr", "python_whisper", uuid);
// Save with metadata and precision optimization
crate::core::json_formatter::write_file_pretty_rounded(&result, output_path, 2)
.context("Failed to write ASR output")?;
tracing::info!(
"[ASR] Python result: status={}, {} segments, language: {:?}",
result
.status
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default(),
result.segment_count,
result.language
);
Ok(result)
anyhow::bail!("[ASR] MLX Whisper CLI not found at {:?}", mlx_whisper_cli);
}
#[derive(Debug, Deserialize)]
+6 -2
View File
@@ -78,7 +78,7 @@ pub async fn process_face_cluster(
});
}
// Build args with --threshold (always pass, default 0.15)
// Build args with --threshold (default 0.85 to correctly separate male/female faces)
let threshold = similarity_threshold.unwrap_or(0.85);
let distance = 1.0 - threshold;
let threshold_str = format!("{:.4}", distance);
@@ -88,8 +88,12 @@ pub async fn process_face_cluster(
"--threshold",
Box::leak(threshold_str.into_boxed_str()) as &str,
];
// Stage 2 merge disabled to prevent over-merging male/female faces
// Previously: stage2 with merge_threshold=0.30 caused male/female to merge into one person
tracing::info!(
"[FACE_CLUSTER] Using threshold: similarity={:.2}, distance={:.4}",
"[FACE_CLUSTER] Using threshold: similarity={:.2}, distance={:.4}, stage2=disabled",
threshold,
distance
);
+5 -1
View File
@@ -4839,9 +4839,13 @@ mod tests {
vec![ProcessorType::Cut]
);
assert_eq!(
stage_dependencies(ProcessorType::FaceCluster),
stage_dependencies(ProcessorType::FaceTrace),
vec![ProcessorType::Face]
);
assert_eq!(
stage_dependencies(ProcessorType::FaceCluster),
vec![ProcessorType::FaceTrace]
);
// Stages without declared dependencies resolve to none.
assert!(stage_dependencies(ProcessorType::Cut).is_empty());
}
+14
View File
@@ -908,6 +908,20 @@ impl ProcessorPool {
total_faces: 0,
})
}
ProcessorType::FaceTrace => {
return Ok(ProcessorOutput {
data: serde_json::Value::Null,
chunks_produced: 0,
frames_processed: 0,
total_frames,
retry_count: 0,
pid: 0,
asr_status: None,
segment_count: 0,
face_status: None,
total_faces: 0,
});
}
ProcessorType::Pose => {
let result = processor::process_pose(
video_path,