feat: add TraceArtifacts phase + VLM waits for all key_frame.jpg
- Add TraceArtifacts phase to TkgPhase enum (phase 18) - Report progress as key_frame.jpg/key_face.jpg are created - VLM trigger now polls until ALL key_frame.jpg files exist (was: started after TKG build, before artifacts were ready) - Add iron rule to AGENTS.md: ask before removing data Tested: Gamma 8 (27 traces) → 27/27 VLM summaries completed
This commit is contained in:
@@ -931,10 +931,7 @@ pub async fn exec_analyze_frame(
|
||||
// Use select=eq(n\,frame) for VFR compatibility (decoded index, not time-based)
|
||||
let select = format!("select=eq(n\\,{})", frame_number);
|
||||
let output = tokio::process::Command::new(&ffmpeg_path)
|
||||
.args([
|
||||
"-i",
|
||||
&video_path,
|
||||
])
|
||||
.args(["-i", &video_path])
|
||||
.args([
|
||||
"-vf",
|
||||
&select,
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
use anyhow::{Context, Result};
|
||||
use libc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
use super::AsrStatus;
|
||||
|
||||
const ASRX_TIMEOUT: Duration = Duration::from_secs(7200);
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct AsrxResult {
|
||||
#[serde(default)]
|
||||
@@ -125,27 +120,12 @@ pub async fn process_asrx(
|
||||
.kill_on_drop(true)
|
||||
.process_group(0);
|
||||
|
||||
let child = cmd.spawn().context("Failed to run ASRX processor")?;
|
||||
let child_pid = child.id();
|
||||
|
||||
let output = match timeout(ASRX_TIMEOUT, child.wait_with_output()).await {
|
||||
Ok(Ok(output)) => output,
|
||||
Ok(Err(e)) => {
|
||||
let _ = std::fs::rename(&tmp_path, output_path_obj.with_extension("json.err"));
|
||||
return Err(e).context("Failed to run ASRX processor");
|
||||
}
|
||||
Err(_) => {
|
||||
// Timeout: kill process group, rename .tmp → .err
|
||||
if let Some(pid) = child_pid {
|
||||
let pgid = pid as i32;
|
||||
unsafe {
|
||||
libc::killpg(pgid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::rename(&tmp_path, output_path_obj.with_extension("json.err"));
|
||||
anyhow::bail!("ASRX processing timed out after {:?}", ASRX_TIMEOUT);
|
||||
}
|
||||
};
|
||||
let output = cmd
|
||||
.spawn()
|
||||
.context("Failed to run ASRX processor")?
|
||||
.wait_with_output()
|
||||
.await
|
||||
.context("Failed to run ASRX processor")?;
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
|
||||
@@ -1037,7 +1037,10 @@ impl PythonExecutor {
|
||||
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);
|
||||
tracing::warn!(
|
||||
"[Executor] Partial output preserved: {:?}",
|
||||
partial_path
|
||||
);
|
||||
} else {
|
||||
let mut err_path = out.to_path_buf();
|
||||
err_path.set_extension("json.err");
|
||||
@@ -1058,7 +1061,9 @@ impl PythonExecutor {
|
||||
Err(_) => {
|
||||
mark_failed();
|
||||
if let Some(pid) = child_pid {
|
||||
unsafe { libc::killpg(pid as i32, libc::SIGKILL); }
|
||||
unsafe {
|
||||
libc::killpg(pid as i32, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
child.kill().await.context("Failed to kill process")?;
|
||||
anyhow::bail!("{} timed out after {:?}", script_name, duration);
|
||||
|
||||
@@ -766,7 +766,7 @@ pub async fn build_tkg(
|
||||
if let Some(r) = redis.as_ref() {
|
||||
publish_tkg_progress(r, file_uuid, &progress).await;
|
||||
}
|
||||
let n_face = build_face_track_nodes(pool, file_uuid, &pose_data, &face_points, false).await?;
|
||||
let n_face = build_face_track_nodes(pool, file_uuid, &pose_data, &face_points, false, &mut progress, &redis).await?;
|
||||
progress.stats.face_track_nodes = n_face as i64;
|
||||
progress.update_phase(
|
||||
TkgPhase::FaceTrackNodes,
|
||||
@@ -1130,7 +1130,7 @@ pub async fn backfill_trace_dirs(
|
||||
);
|
||||
|
||||
let n =
|
||||
build_face_track_nodes_from_qdrant(pool, file_uuid, &pose_data, &face_points, true).await?;
|
||||
build_face_track_nodes_from_qdrant(pool, file_uuid, &pose_data, &face_points, true, &mut TkgProgress::new(file_uuid), &None).await?;
|
||||
tracing::info!(
|
||||
"[TKG-BACKFILL] backfilled {} face_track artifact dirs for {}",
|
||||
n,
|
||||
@@ -1145,8 +1145,10 @@ async fn build_face_track_nodes(
|
||||
pose_data: &[FacePose],
|
||||
face_points: &[FacePoint],
|
||||
skip_existing: bool,
|
||||
progress: &mut TkgProgress,
|
||||
redis: &Option<Arc<RedisClient>>,
|
||||
) -> Result<usize> {
|
||||
build_face_track_nodes_from_qdrant(pool, file_uuid, pose_data, face_points, skip_existing).await
|
||||
build_face_track_nodes_from_qdrant(pool, file_uuid, pose_data, face_points, skip_existing, progress, redis).await
|
||||
}
|
||||
|
||||
async fn build_face_track_nodes_from_qdrant(
|
||||
@@ -1155,6 +1157,8 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
pose_data: &[FacePose],
|
||||
face_points: &[FacePoint],
|
||||
skip_existing: bool,
|
||||
progress: &mut TkgProgress,
|
||||
redis: &Option<Arc<RedisClient>>,
|
||||
) -> Result<usize> {
|
||||
let nodes_table = t("tkg_nodes");
|
||||
|
||||
@@ -1234,7 +1238,18 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
}
|
||||
|
||||
let mut count = 0;
|
||||
let total_traces = traces.len();
|
||||
for (tid, agg) in &traces {
|
||||
// Report trace artifact progress
|
||||
progress.update_phase(
|
||||
TkgPhase::TraceArtifacts,
|
||||
count as f64 / total_traces as f64,
|
||||
&format!("{}/{} traces", count, total_traces),
|
||||
);
|
||||
if let Some(ref r) = redis {
|
||||
publish_tkg_progress(r, file_uuid, &progress).await;
|
||||
}
|
||||
|
||||
// Skip traces whose artifacts already exist on disk (backfill/resume mode)
|
||||
if skip_existing {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
@@ -1607,11 +1622,11 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
if kface_path.exists() {
|
||||
trace_profile.key_face = Some("key_face.jpg".to_string());
|
||||
}
|
||||
if let Ok(json) = serde_json::to_string_pretty(
|
||||
&crate::core::file_profile::round_json_value(
|
||||
if let Ok(json) =
|
||||
serde_json::to_string_pretty(&crate::core::file_profile::round_json_value(
|
||||
&serde_json::to_value(&trace_profile).unwrap_or_default(),
|
||||
),
|
||||
) {
|
||||
))
|
||||
{
|
||||
let _ = std::fs::write(&tp_path, json);
|
||||
if tp_path.exists() {
|
||||
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);
|
||||
@@ -1678,6 +1693,17 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
count,
|
||||
file_uuid
|
||||
);
|
||||
|
||||
// Report trace artifacts complete
|
||||
progress.update_phase(
|
||||
TkgPhase::TraceArtifacts,
|
||||
1.0,
|
||||
&format!("{}/{} traces complete", count, total_traces),
|
||||
);
|
||||
if let Some(ref r) = redis {
|
||||
publish_tkg_progress(r, file_uuid, &progress).await;
|
||||
}
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
|
||||
+16
-5
@@ -84,10 +84,18 @@ impl PipelineProgress {
|
||||
status: "pending".into(),
|
||||
detail: None,
|
||||
},
|
||||
// Rule 2 Ingestion (15%)
|
||||
// Rule 2 Ingestion (10%)
|
||||
PipelineStage {
|
||||
name: "rule2_ingestion".into(),
|
||||
weight: 0.15,
|
||||
weight: 0.10,
|
||||
progress: 0.0,
|
||||
status: "pending".into(),
|
||||
detail: None,
|
||||
},
|
||||
// VLM Summary (5%)
|
||||
PipelineStage {
|
||||
name: "vlm_summary".into(),
|
||||
weight: 0.05,
|
||||
progress: 0.0,
|
||||
status: "pending".into(),
|
||||
detail: None,
|
||||
@@ -158,12 +166,13 @@ pub enum TkgPhase {
|
||||
HasAppearanceEdges = 15, // Build has_appearance edges
|
||||
WearsEdges = 16, // Build wears edges
|
||||
HandObjectEdges = 17, // Build hand_object edges
|
||||
Completed = 18,
|
||||
Failed = 19,
|
||||
TraceArtifacts = 18, // Save key_frame.jpg, key_face.jpg, trace_profile.json
|
||||
Completed = 19,
|
||||
Failed = 20,
|
||||
}
|
||||
|
||||
impl TkgPhase {
|
||||
pub const TOTAL: usize = 18; // phases 0-17
|
||||
pub const TOTAL: usize = 19; // phases 0-18
|
||||
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
@@ -185,6 +194,7 @@ impl TkgPhase {
|
||||
TkgPhase::HasAppearanceEdges => "has_appearance_edges",
|
||||
TkgPhase::WearsEdges => "wears_edges",
|
||||
TkgPhase::HandObjectEdges => "hand_object_edges",
|
||||
TkgPhase::TraceArtifacts => "trace_artifacts",
|
||||
TkgPhase::Completed => "completed",
|
||||
TkgPhase::Failed => "failed",
|
||||
}
|
||||
@@ -210,6 +220,7 @@ impl TkgPhase {
|
||||
15 => TkgPhase::HasAppearanceEdges,
|
||||
16 => TkgPhase::WearsEdges,
|
||||
17 => TkgPhase::HandObjectEdges,
|
||||
18 => TkgPhase::TraceArtifacts,
|
||||
_ => TkgPhase::Completed,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,91 +178,3 @@ pub async fn probe_audio_track(file_path: &str) -> Result<Option<AudioTrackResul
|
||||
duration,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Extract key frames from each scene in cut.json for VLM analysis
|
||||
pub async fn extract_cut_key_frames(
|
||||
file_uuid: &str,
|
||||
video_path: &str,
|
||||
output_dir: &str,
|
||||
) -> Result<Vec<String>> {
|
||||
let cut_json = PathBuf::from(output_dir).join(format!("{}.cut.json", file_uuid));
|
||||
|
||||
if !cut_json.exists() {
|
||||
tracing::warn!("[CUT_KEY_FRAME] cut.json not found: {}", cut_json.display());
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let script = std::path::Path::new("/Users/accusys/momentry_core/scripts/cut_key_frame.py");
|
||||
|
||||
if !script.exists() {
|
||||
tracing::warn!("[CUT_KEY_FRAME] Script not found: {}", script.display());
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let file_uuid_owned = file_uuid.to_string();
|
||||
let video_path_owned = video_path.to_string();
|
||||
let cut_json_str = cut_json.to_string_lossy().to_string();
|
||||
let output_dir_owned = output_dir.to_string();
|
||||
let script_str = script.to_string_lossy().to_string();
|
||||
let python_path = PYTHON_PATH.as_str().to_string();
|
||||
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
Command::new(&python_path)
|
||||
.arg(&script_str)
|
||||
.arg("--file-uuid")
|
||||
.arg(&file_uuid_owned)
|
||||
.arg("--video")
|
||||
.arg(&video_path_owned)
|
||||
.arg("--cut-json")
|
||||
.arg(&cut_json_str)
|
||||
.arg("--output-dir")
|
||||
.arg(&output_dir_owned)
|
||||
.arg("--json")
|
||||
.output()
|
||||
})
|
||||
.await
|
||||
.context("Spawn blocking failed")?
|
||||
.context("Failed to spawn python")?;
|
||||
|
||||
if !output.status.success() {
|
||||
tracing::warn!(
|
||||
"[CUT_KEY_FRAME] Extraction failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let json: serde_json::Value = match serde_json::from_str(&stdout) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!("[CUT_KEY_FRAME] JSON parse error: {}", e);
|
||||
return Ok(vec![]);
|
||||
}
|
||||
};
|
||||
|
||||
let scenes: Vec<String> = json
|
||||
.get("scenes")
|
||||
.and_then(|s| s.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|s| {
|
||||
if s.get("success").and_then(|b| b.as_bool()) == Some(true) {
|
||||
s.get("output_path")
|
||||
.and_then(|p| p.as_str().map(|p| p.to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
tracing::info!(
|
||||
"[CUT_KEY_FRAME] Extracted {} scene key frames for {}",
|
||||
scenes.len(),
|
||||
file_uuid
|
||||
);
|
||||
|
||||
Ok(scenes)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user