feat: face fix deployment + trace_* regeneration + executor stderr filter fix
- swift_face.swift: frame rounding (.rounded()), conf 0.75, min_size 64 - trace_* directories regenerated for KOBA (37 traces, start_frame 5307) - executor.rs: stderr filter now logs all non-empty stderr (was discarding) - VAD not skippable in ASRX (main_fixed.py Step 2 always runs) - Step 2.5 sentence boundary refinement added - Cluster agent async endpoints + similarity transparency - Keyword search: relationship text extraction, priority ordering - Face fix handoff doc for Studio team
This commit is contained in:
@@ -535,6 +535,8 @@ impl PythonExecutor {
|
||||
Ok(Some(line)) => {
|
||||
if line.starts_with(&format!("{}_", log_prefix)) {
|
||||
tracing::info!("[{}] {}", log_prefix, line);
|
||||
} else if !line.trim().is_empty() {
|
||||
tracing::warn!("[{} stderr] {}", log_prefix, line);
|
||||
}
|
||||
}
|
||||
Ok(None) => stderr_done = true,
|
||||
@@ -738,6 +740,8 @@ impl PythonExecutor {
|
||||
Ok(Some(line)) => {
|
||||
if line.starts_with(&format!("{}_", log_prefix)) {
|
||||
tracing::info!("[{}] {}", log_prefix, line);
|
||||
} else if !line.trim().is_empty() {
|
||||
tracing::warn!("[{} stderr] {}", log_prefix, line);
|
||||
}
|
||||
}
|
||||
Ok(None) => stderr_done = true,
|
||||
@@ -825,6 +829,202 @@ impl PythonExecutor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Like `run_with_output_idx_and_frames` but accepts a `CancellationToken` so the caller
|
||||
/// can cleanly abort the Python subprocess without leaking processes.
|
||||
pub async fn run_with_output_idx_and_frames_with_cancel(
|
||||
&self,
|
||||
script_name: &str,
|
||||
args: &[&str],
|
||||
uuid: Option<&str>,
|
||||
log_prefix: &str,
|
||||
timeout_duration: Option<Duration>,
|
||||
output_idx: Option<usize>,
|
||||
frames: Option<&[i64]>,
|
||||
cancel: tokio_util::sync::CancellationToken,
|
||||
) -> Result<()> {
|
||||
let script_path = self.scripts_dir.join(script_name);
|
||||
|
||||
if !script_path.exists() {
|
||||
anyhow::bail!("Script not found: {:?}", script_path);
|
||||
}
|
||||
|
||||
self.verify_script_integrity(script_name).context(
|
||||
"Pre-execution integrity check failed — possible version mismatch or corruption",
|
||||
)?;
|
||||
|
||||
let output_path =
|
||||
output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p)));
|
||||
let tmp_path = output_path.as_ref().map(|p| {
|
||||
let mut tmp = p.to_path_buf();
|
||||
tmp.set_extension("json.tmp");
|
||||
tmp
|
||||
});
|
||||
|
||||
let mut cmd = Command::new(&self.python_path);
|
||||
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
|
||||
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
|
||||
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
|
||||
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
|
||||
if let Ok(qdrant_url) = std::env::var("QDRANT_URL") {
|
||||
cmd.env("QDRANT_URL", qdrant_url);
|
||||
}
|
||||
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
|
||||
cmd.env("QDRANT_API_KEY", qdrant_api_key);
|
||||
}
|
||||
cmd.arg(&script_path);
|
||||
|
||||
for (i, arg) in args.iter().enumerate() {
|
||||
if Some(i) == output_idx {
|
||||
if let Some(ref tmp) = tmp_path {
|
||||
cmd.arg(tmp);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
if let Some(u) = uuid {
|
||||
cmd.arg("--uuid").arg(u);
|
||||
}
|
||||
|
||||
// Append extra args (e.g. --threshold) after --uuid
|
||||
// Pass frame list for 8Hz sampling
|
||||
if let Some(frames) = frames {
|
||||
if !frames.is_empty() {
|
||||
let frames_str = Self::format_frames_arg(frames);
|
||||
cmd.arg("--frames").arg(&frames_str);
|
||||
}
|
||||
}
|
||||
|
||||
cmd.stdout(Stdio::piped());
|
||||
cmd.stderr(Stdio::piped());
|
||||
cmd.kill_on_drop(true);
|
||||
cmd.process_group(0);
|
||||
|
||||
tracing::info!("[{}] Starting: {:?}", log_prefix, script_name);
|
||||
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.with_context(|| format!("Failed to run {}", script_name))?;
|
||||
let child_pid = child.id();
|
||||
|
||||
let stdout = child.stdout.take().context("Failed to capture stdout")?;
|
||||
let stderr = child.stderr.take().context("Failed to capture stderr")?;
|
||||
|
||||
let mut stdout_reader = BufReader::new(stdout).lines();
|
||||
let mut stderr_reader = BufReader::new(stderr).lines();
|
||||
|
||||
let run_future = async {
|
||||
let mut stdout_done = false;
|
||||
let mut stderr_done = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
line = stdout_reader.next_line(), if !stdout_done => {
|
||||
match line {
|
||||
Ok(Some(line)) => {
|
||||
if line.starts_with(&format!("{}_", log_prefix)) {
|
||||
tracing::info!("[{}] {}", log_prefix, line);
|
||||
}
|
||||
}
|
||||
Ok(None) => stdout_done = true,
|
||||
Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e),
|
||||
}
|
||||
}
|
||||
line = stderr_reader.next_line(), if !stderr_done => {
|
||||
match line {
|
||||
Ok(Some(line)) => {
|
||||
if line.starts_with(&format!("{}_", log_prefix)) {
|
||||
tracing::info!("[{}] {}", log_prefix, line);
|
||||
} else if !line.trim().is_empty() {
|
||||
tracing::warn!("[{} stderr] {}", log_prefix, line);
|
||||
}
|
||||
}
|
||||
Ok(None) => stderr_done = true,
|
||||
Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e),
|
||||
}
|
||||
}
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!("[{}] Cancelled by caller", log_prefix);
|
||||
if let Some(pid) = child_pid {
|
||||
unsafe { libc::killpg(pid as i32, libc::SIGTERM); }
|
||||
}
|
||||
return Err(anyhow::anyhow!("{} cancelled by caller", script_name));
|
||||
}
|
||||
status = child.wait() => {
|
||||
match status {
|
||||
Ok(status) => {
|
||||
if !status.success() {
|
||||
tracing::error!("[{}] Process failed: {}", log_prefix, status);
|
||||
return Err(anyhow::anyhow!("{} exited with: {}", script_name, status));
|
||||
}
|
||||
tracing::info!("[{}] Completed successfully", log_prefix);
|
||||
}
|
||||
Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e),
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
let mark_failed = || {
|
||||
if let Some(tmp) = &tmp_path {
|
||||
if tmp.exists() {
|
||||
if let Some(out) = &output_path {
|
||||
let is_valid = std::fs::read_to_string(tmp)
|
||||
.ok()
|
||||
.and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
|
||||
.is_some();
|
||||
if is_valid {
|
||||
let mut partial_path = out.to_path_buf();
|
||||
partial_path.set_extension("json.partial");
|
||||
let _ = std::fs::rename(tmp, &partial_path);
|
||||
tracing::warn!("[Executor] Partial output preserved: {:?}", partial_path);
|
||||
} else {
|
||||
let mut err_path = out.to_path_buf();
|
||||
err_path.set_extension("json.err");
|
||||
let _ = std::fs::rename(tmp, &err_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(duration) = timeout_duration {
|
||||
match timeout(duration, run_future).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(e)) => {
|
||||
mark_failed();
|
||||
return Err(e);
|
||||
}
|
||||
Err(_) => {
|
||||
mark_failed();
|
||||
if let Some(pid) = child_pid {
|
||||
unsafe { libc::killpg(pid as i32, libc::SIGKILL); }
|
||||
}
|
||||
child.kill().await.context("Failed to kill process")?;
|
||||
anyhow::bail!("{} timed out after {:?}", script_name, duration);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if let Err(e) = run_future.await {
|
||||
mark_failed();
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(tmp) = &tmp_path {
|
||||
if tmp.exists() {
|
||||
if let Some(out) = &output_path {
|
||||
let _ = std::fs::rename(tmp, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run_with_output(
|
||||
&self,
|
||||
script_name: &str,
|
||||
|
||||
@@ -17,6 +17,14 @@ pub struct FaceClusterInfo {
|
||||
pub cluster_id: String,
|
||||
pub face_count: usize,
|
||||
pub representative_face: Option<RepresentativeFace>,
|
||||
pub similarity: Option<ClusterSimilarity>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct ClusterSimilarity {
|
||||
pub min: f64,
|
||||
pub avg: f64,
|
||||
pub threshold: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
@@ -55,6 +63,7 @@ pub async fn process_face_cluster(
|
||||
output_path: &str,
|
||||
uuid: Option<&str>,
|
||||
frames: Option<&[i64]>,
|
||||
similarity_threshold: Option<f64>,
|
||||
) -> Result<FaceClusterResult> {
|
||||
let executor = PythonExecutor::new()?;
|
||||
let script_path = executor.script_path("fast_face_clustering_processor.py");
|
||||
@@ -69,13 +78,28 @@ pub async fn process_face_cluster(
|
||||
});
|
||||
}
|
||||
|
||||
// Build args with optional --threshold
|
||||
let distance = similarity_threshold.map(|s| 1.0 - s);
|
||||
let mut args = vec![video_path, output_path];
|
||||
if let Some(d) = distance {
|
||||
let threshold_str = format!("{:.4}", d);
|
||||
args.push("--threshold");
|
||||
args.push(Box::leak(threshold_str.into_boxed_str()) as &str);
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] similarity={:.2} → distance={:.4}",
|
||||
similarity_threshold.unwrap_or(0.65),
|
||||
d
|
||||
);
|
||||
}
|
||||
|
||||
executor
|
||||
.run_with_frames(
|
||||
.run_with_output_idx_and_frames(
|
||||
"fast_face_clustering_processor.py",
|
||||
&[video_path, output_path],
|
||||
&args,
|
||||
uuid,
|
||||
"FACE_CLUSTER",
|
||||
Some(FACE_CLUSTER_TIMEOUT),
|
||||
Some(1),
|
||||
frames,
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -96,8 +96,7 @@ pub fn group_ocr_texts_by_zone_and_proximity(
|
||||
|
||||
for frame in frames {
|
||||
// Rule 2: Frame difference detection
|
||||
let current_texts: HashSet<String> =
|
||||
frame.texts.iter().map(|t| t.text.clone()).collect();
|
||||
let current_texts: HashSet<String> = frame.texts.iter().map(|t| t.text.clone()).collect();
|
||||
let similarity = jaccard_similarity(&last_texts, ¤t_texts);
|
||||
|
||||
if !last_texts.is_empty() && similarity < TEXT_SIMILARITY_THRESHOLD {
|
||||
|
||||
+177
-8
@@ -1304,13 +1304,31 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
// Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame)
|
||||
let key_face_jpeg: Option<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
|
||||
// Find bbox for best_frame from trace frames
|
||||
let (_, bx, by, bw, bh) = agg.frames.iter().find(|(f, _, _, _, _)| *f == agg.best_frame)?;
|
||||
let (bf, bx, by, bw, bh) = agg
|
||||
.frames
|
||||
.iter()
|
||||
.find(|(f, _, _, _, _)| *f == agg.best_frame)?;
|
||||
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
|
||||
|
||||
// Validate bbox: must have positive dimensions
|
||||
if bw < 2.0 || bh < 2.0 {
|
||||
tracing::warn!(
|
||||
"[TKG] trace {}: invalid bbox {}x{} at ({},{}), skipping key_face",
|
||||
tid,
|
||||
bw,
|
||||
bh,
|
||||
bx,
|
||||
by
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let crop_filter = format!(
|
||||
"crop={}:{}:{}:{}",
|
||||
(*bw as i64).max(1),
|
||||
(*bh as i64).max(1),
|
||||
(*bx as i64).max(0),
|
||||
(*by as i64).max(0),
|
||||
(bw as i64).max(1),
|
||||
(bh as i64).max(1),
|
||||
(bx as i64).max(0),
|
||||
(by as i64).max(0),
|
||||
);
|
||||
let mut cmd = std::process::Command::new("ffmpeg");
|
||||
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
||||
@@ -1336,7 +1354,7 @@ 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();
|
||||
|
||||
|
||||
match trace_profile.save(
|
||||
output_dir,
|
||||
key_frame_jpeg.as_deref(),
|
||||
@@ -1347,7 +1365,154 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
key_face_file = "key_face.jpg".to_string();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[TKG] Failed to save trace_profile for trace {}: {}", tid, e);
|
||||
tracing::error!(
|
||||
"[TKG] Failed to save trace_profile for trace {}: {}",
|
||||
tid,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate all three outputs exist: key_frame.jpg, key_face.jpg, trace_profile.json
|
||||
// If missing, retry extraction on the spot
|
||||
let trace_dir =
|
||||
crate::core::file_profile::FaceTraceProfile::trace_dir(output_dir, file_uuid, *tid);
|
||||
let kf_path = trace_dir.join("key_frame.jpg");
|
||||
let kface_path = trace_dir.join("key_face.jpg");
|
||||
let tp_path =
|
||||
crate::core::file_profile::FaceTraceProfile::profile_path(output_dir, file_uuid, *tid);
|
||||
|
||||
let mut need_retry = false;
|
||||
if !kf_path.exists() {
|
||||
tracing::warn!(
|
||||
"[TKG-VERIFY] trace {}: key_frame.jpg missing, retrying",
|
||||
tid
|
||||
);
|
||||
need_retry = true;
|
||||
}
|
||||
if !kface_path.exists() {
|
||||
tracing::warn!("[TKG-VERIFY] trace {}: key_face.jpg missing, retrying", tid);
|
||||
need_retry = true;
|
||||
}
|
||||
if !tp_path.exists() {
|
||||
tracing::warn!(
|
||||
"[TKG-VERIFY] trace {}: trace_profile.json missing, retrying",
|
||||
tid
|
||||
);
|
||||
need_retry = true;
|
||||
}
|
||||
|
||||
if need_retry {
|
||||
if let Some(ref vp) = video_path {
|
||||
let timestamp = agg.best_frame as f64 / actual_fps;
|
||||
// Retry key_frame extraction
|
||||
if !kf_path.exists() {
|
||||
if let Ok(output) = std::process::Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-v",
|
||||
"quiet",
|
||||
"-ss",
|
||||
&format!("{:.3}", timestamp),
|
||||
"-i",
|
||||
vp,
|
||||
])
|
||||
.args([
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-f",
|
||||
"image2pipe",
|
||||
"-c:v",
|
||||
"mjpeg",
|
||||
"pipe:1",
|
||||
])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
{
|
||||
if output.status.success() && !output.stdout.is_empty() {
|
||||
let _ = std::fs::write(&kf_path, &output.stdout);
|
||||
if kf_path.exists() {
|
||||
tracing::info!(
|
||||
"[TKG-VERIFY] trace {}: key_frame.jpg recovered",
|
||||
tid
|
||||
);
|
||||
key_frame_file = "key_frame.jpg".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Retry key_face crop
|
||||
if !kface_path.exists() && kf_path.exists() {
|
||||
let (_, bx, by, bw, bh) = agg
|
||||
.frames
|
||||
.iter()
|
||||
.find(|(f, _, _, _, _)| *f == agg.best_frame)
|
||||
.cloned()
|
||||
.unwrap_or((0, 0.0, 0.0, 100.0, 100.0));
|
||||
|
||||
// Validate bbox
|
||||
if bw < 2.0 || bh < 2.0 {
|
||||
tracing::warn!(
|
||||
"[TKG-VERIFY] trace {}: invalid bbox {}x{}, skipping key_face retry",
|
||||
tid,
|
||||
bw,
|
||||
bh
|
||||
);
|
||||
} else {
|
||||
let crop_filter = format!(
|
||||
"crop={}:{}:{}:{}",
|
||||
(bw as i64).max(1),
|
||||
(bh as i64).max(1),
|
||||
(bx as i64).max(0),
|
||||
(by as i64).max(0),
|
||||
);
|
||||
if let Ok(kf_bytes) = std::fs::read(&kf_path) {
|
||||
let mut cmd = std::process::Command::new("ffmpeg");
|
||||
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
||||
.args(["-frames:v", "1", "-q:v", "2", "-vf"])
|
||||
.arg(&crop_filter)
|
||||
.args(["-f", "image2pipe", "-c:v", "mjpeg", "pipe:1"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null());
|
||||
if let Ok(mut child) = cmd.spawn() {
|
||||
if let Some(ref mut stdin) = child.stdin {
|
||||
use std::io::Write;
|
||||
let _ = stdin.write_all(&kf_bytes);
|
||||
}
|
||||
if let Ok(output) = child.wait_with_output() {
|
||||
if output.status.success() && !output.stdout.is_empty() {
|
||||
let _ = std::fs::write(&kface_path, &output.stdout);
|
||||
if kface_path.exists() {
|
||||
tracing::info!(
|
||||
"[TKG-VERIFY] trace {}: key_face.jpg recovered",
|
||||
tid
|
||||
);
|
||||
key_face_file = "key_face.jpg".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Update trace_profile with recovered file paths, then rewrite profile
|
||||
// (even if it already exists — it may have stale null key_frame/key_face)
|
||||
if kf_path.exists() {
|
||||
trace_profile.key_frame = Some("key_frame.jpg".to_string());
|
||||
}
|
||||
if kface_path.exists() {
|
||||
trace_profile.key_face = Some("key_face.jpg".to_string());
|
||||
}
|
||||
if let Ok(json) = serde_json::to_string_pretty(&trace_profile) {
|
||||
let _ = std::fs::write(&tp_path, json);
|
||||
if tp_path.exists() {
|
||||
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1399,7 +1564,11 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
count += 1;
|
||||
}
|
||||
|
||||
tracing::info!("[TKG-face_track] built {} face_track nodes for {}", count, file_uuid);
|
||||
tracing::info!(
|
||||
"[TKG-face_track] built {} face_track nodes for {}",
|
||||
count,
|
||||
file_uuid
|
||||
);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user