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:
Accusys
2026-08-24 19:13:11 +08:00
parent d29b4804af
commit 9f12e835b8
43 changed files with 3993 additions and 491 deletions
+39 -37
View File
@@ -148,9 +148,7 @@ pub async fn trigger_cluster_agent(
// Check for existing running job for this file
let registry = CLUSTER_JOB_REGISTRY.read().await;
for (job_id, handle) in registry.iter() {
if handle.file_uuid == file_uuid
&& matches!(handle.status, ClusterJobStatus::Running)
{
if handle.file_uuid == file_uuid && matches!(handle.status, ClusterJobStatus::Running) {
return Ok(Json(ClusterAgentResponse {
success: false,
job_id: job_id.clone(),
@@ -215,7 +213,14 @@ pub async fn trigger_cluster_agent(
let total_traces = count_total_traces(&state, &file_uuid).await.unwrap_or(0);
let job_id = format!("cluster_{}_{}", file_uuid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs());
let job_id = format!(
"cluster_{}_{}",
file_uuid,
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
);
let output_path =
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid));
let cancel_token = tokio_util::sync::CancellationToken::new();
@@ -307,9 +312,10 @@ pub async fn trigger_cluster_agent(
// Build frames list
let frames = if total_frames > 0 {
let fps_val = if fps > 0.0 { fps } else { 30.0 };
Some(
crate::core::processor::PythonExecutor::compute_8hz_frames(total_frames, fps_val),
)
Some(crate::core::processor::PythonExecutor::compute_8hz_frames(
total_frames,
fps_val,
))
} else {
None
};
@@ -340,12 +346,9 @@ pub async fn trigger_cluster_agent(
}
// Update trace labels
let _ = update_trace_labels_from_cluster(
&db_clone,
&file_uuid_clone,
&cluster_result,
)
.await;
let _ =
update_trace_labels_from_cluster(&db_clone, &file_uuid_clone, &cluster_result)
.await;
handle.status = ClusterJobStatus::Completed;
handle.progress = 1.0;
@@ -371,7 +374,10 @@ pub async fn trigger_cluster_agent(
let job_id_for_cleanup = job_id_clone.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(300)).await;
CLUSTER_JOB_REGISTRY.write().await.remove(&job_id_for_cleanup);
CLUSTER_JOB_REGISTRY
.write()
.await
.remove(&job_id_for_cleanup);
});
});
@@ -401,10 +407,16 @@ pub async fn get_cluster_job_status(
})?;
let (status_str, message) = match &handle.status {
ClusterJobStatus::Running => ("running".to_string(), Some("Clustering in progress".to_string())),
ClusterJobStatus::Running => (
"running".to_string(),
Some("Clustering in progress".to_string()),
),
ClusterJobStatus::Completed => ("completed".to_string(), None),
ClusterJobStatus::Failed(msg) => ("failed".to_string(), Some(msg.clone())),
ClusterJobStatus::Cancelled => ("cancelled".to_string(), Some("Job was cancelled".to_string())),
ClusterJobStatus::Cancelled => (
"cancelled".to_string(),
Some("Job was cancelled".to_string()),
),
};
Ok(Json(ClusterJobStatusResponse {
@@ -414,7 +426,11 @@ pub async fn get_cluster_job_status(
progress: if matches!(handle.status, ClusterJobStatus::Running) {
Some(handle.progress)
} else {
Some(if matches!(handle.status, ClusterJobStatus::Completed) { 1.0 } else { handle.progress })
Some(if matches!(handle.status, ClusterJobStatus::Completed) {
1.0
} else {
handle.progress
})
},
message,
clusters: handle.clusters,
@@ -524,14 +540,8 @@ async fn update_trace_labels_from_cluster(
.await?;
}
let _ = schema::upsert_trace_profile(
db.pool(),
file_uuid,
*trace_id as i32,
&label,
None,
)
.await;
let _ = schema::upsert_trace_profile(db.pool(), file_uuid, *trace_id as i32, &label, None)
.await;
}
if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) {
@@ -539,14 +549,9 @@ async fn update_trace_labels_from_cluster(
for tid in &all_trace_ids {
if !trace_to_cluster.contains_key(tid) {
let name = format!("Person_{}", tid);
let _ = schema::upsert_trace_profile(
db.pool(),
file_uuid,
*tid as i32,
&name,
None,
)
.await;
let _ =
schema::upsert_trace_profile(db.pool(), file_uuid, *tid as i32, &name, None)
.await;
updated_count += 1;
}
}
@@ -587,10 +592,7 @@ fn get_all_trace_ids(file_uuid: &str) -> Option<Vec<i64>> {
}
}
async fn count_total_traces(
state: &AppState,
file_uuid: &str,
) -> anyhow::Result<usize> {
async fn count_total_traces(state: &AppState, file_uuid: &str) -> anyhow::Result<usize> {
let tkg_table = schema::table_name("tkg_nodes");
let count: (i64,) = sqlx::query_as(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND node_type = 'face_track'",
+73 -54
View File
@@ -12,8 +12,8 @@ use std::collections::HashMap;
use super::types::AppState;
use crate::core::db::schema;
use crate::core::face_filter_engine::{
default_filter_config, FaceFilterFeatures, FaceFilterResult, FilterEngine, FilterRecommendation,
FilterRuleConfig, RuleResult,
default_filter_config, FaceFilterFeatures, FaceFilterResult, FilterEngine,
FilterRecommendation, FilterRuleConfig, RuleResult,
};
/// Request to filter faces
@@ -43,7 +43,7 @@ pub struct FilteredFaceInfo {
/// Request to get faces with filtering
#[derive(Debug, Deserialize)]
pub struct GetFacesRequest {
pub source: Option<String>, // "all" | "apple_vision" | "mediapipe"
pub source: Option<String>, // "all" | "apple_vision" | "mediapipe"
pub page: Option<usize>,
pub page_size: Option<usize>,
}
@@ -134,24 +134,21 @@ pub async fn get_faces(
page: Some(1),
page_size: Some(50),
});
let page = req.page.unwrap_or(1);
let page_size = req.page_size.unwrap_or(50);
let offset = (page - 1) * page_size;
// Get total count
let filter_table = schema::table_name("face_filter_features");
let count_query = format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1",
filter_table
);
let count_query = format!("SELECT COUNT(*) FROM {} WHERE file_uuid = $1", filter_table);
let total: i64 = sqlx::query_scalar(&count_query)
.bind(&file_uuid)
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Get faces with filter features
let faces_query = format!(
"SELECT face_id, frame, primary_source, apple_vision_confidence, mediapipe_confidence,
@@ -163,7 +160,7 @@ pub async fn get_faces(
LIMIT $2 OFFSET $3",
filter_table
);
let rows = sqlx::query(&faces_query)
.bind(&file_uuid)
.bind(page_size as i64)
@@ -171,7 +168,7 @@ pub async fn get_faces(
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Build response
let faces: Vec<FaceInfo> = rows
.into_iter()
@@ -182,7 +179,7 @@ pub async fn get_faces(
let av_conf: Option<f64> = row.get(3);
let mp_conf: Option<f64> = row.get(4);
let bbox_size: Option<i32> = row.get(5);
FaceInfo {
face_id: face_id.clone(),
frame,
@@ -218,7 +215,7 @@ pub async fn get_faces(
}
})
.collect();
// Get source summary
let summary_query = format!(
"SELECT
@@ -229,19 +226,19 @@ pub async fn get_faces(
WHERE file_uuid = $1",
filter_table
);
let summary_row = sqlx::query(&summary_query)
.bind(&file_uuid)
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let apple_vision: i64 = summary_row.get(0);
let mediapipe: i64 = summary_row.get(1);
let merged_unique: i64 = summary_row.get(2);
let total_pages = ((total as f64) / (page_size as f64)).ceil() as usize;
Ok(Json(GetFacesResponse {
faces,
pagination: PaginationInfo {
@@ -264,7 +261,7 @@ pub async fn get_face_filter_report(
Path((file_uuid, face_id)): Path<(String, String)>,
) -> Result<Json<FaceFilterResult>, StatusCode> {
let filter_table = schema::table_name("face_filter_features");
let row = sqlx::query(&format!(
"SELECT face_id, frame, bbox_size, eye_ratio, nose_ratio, pose_score,
mediapipe_detected, mediapipe_iou, embedding_similarity,
@@ -279,7 +276,7 @@ pub async fn get_face_filter_report(
.fetch_optional(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
match row {
Some(row) => {
let features = FaceFilterFeatures {
@@ -299,13 +296,15 @@ pub async fn get_face_filter_report(
mediapipe_confidence: row.get(12),
primary_source: row.get(13),
};
// Apply default filter rules
let config = default_filter_config();
let engine = FilterEngine::new(config);
let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let result = engine
.filter_face(&features)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(result))
}
None => Err(StatusCode::NOT_FOUND),
@@ -319,7 +318,7 @@ pub async fn filter_faces(
req: Json<FilterFacesRequest>,
) -> Result<Json<FilterFacesResponse>, StatusCode> {
let filter_table = schema::table_name("face_filter_features");
// Get all faces for this file
let rows = sqlx::query(&format!(
"SELECT face_id, frame, bbox_size, eye_ratio, nose_ratio, pose_score,
@@ -334,19 +333,19 @@ pub async fn filter_faces(
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let total_faces = rows.len() as i32;
// Use provided rules or default
let config = req.0.rules.clone().unwrap_or_else(default_filter_config);
let engine = FilterEngine::new(config);
// Apply filters
let mut passed = 0;
let mut filtered = 0;
let mut filtered_faces = Vec::new();
let mut filter_stats: HashMap<String, i64> = HashMap::new();
for row in rows {
let features = FaceFilterFeatures {
face_id: row.get(0),
@@ -365,17 +364,22 @@ pub async fn filter_faces(
mediapipe_confidence: row.get(12),
primary_source: row.get(13),
};
let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let result = engine
.filter_face(&features)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if result.recommendation == FilterRecommendation::Accept {
passed += 1;
} else {
filtered += 1;
// Count reasons before moving
for reason in &result.reasons {
let key = if reason.contains("eye_ratio") || reason.contains("nose_ratio") || reason.contains("pose_score") {
let key = if reason.contains("eye_ratio")
|| reason.contains("nose_ratio")
|| reason.contains("pose_score")
{
"landmark".to_string()
} else if reason.contains("MediaPipe") {
"mediapipe".to_string()
@@ -386,10 +390,10 @@ pub async fn filter_faces(
} else {
"other".to_string()
};
*filter_stats.entry(key).or_insert(0) += 1;
}
filtered_faces.push(FilteredFaceInfo {
face_id: result.face_id,
frame: result.frame,
@@ -397,9 +401,9 @@ pub async fn filter_faces(
});
}
}
let filter_stats_json = serde_json::to_value(&filter_stats).unwrap_or_default();
Ok(Json(FilterFacesResponse {
total_faces,
passed,
@@ -415,7 +419,7 @@ pub async fn get_filter_stats(
Path(file_uuid): Path<String>,
) -> Result<Json<FilterStatsResponse>, StatusCode> {
let filter_table = schema::table_name("face_filter_features");
let row = sqlx::query(&format!(
"SELECT
COUNT(*) as total,
@@ -435,7 +439,7 @@ pub async fn get_filter_stats(
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let stats = serde_json::json!({
"total_faces": row.get::<i64, _>(0),
"by_source": {
@@ -451,7 +455,7 @@ pub async fn get_filter_stats(
"avg_consecutive_frames": row.get::<Option<f64>, _>(8),
}
});
Ok(Json(FilterStatsResponse {
total_faces: row.get(0),
by_category: stats,
@@ -465,9 +469,9 @@ pub async fn save_filter_rules(
req: Json<SaveFilterRulesRequest>,
) -> Result<Json<FilterRuleInfo>, StatusCode> {
let rules_table = schema::table_name("filter_rules");
let is_active = req.is_active.unwrap_or(true);
let row = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, rule_name, rules, is_active)
VALUES ($1, $2, $3, $4)
@@ -483,9 +487,9 @@ pub async fn save_filter_rules(
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let rules: FilterRuleConfig = serde_json::from_value(row.get(2)).unwrap();
Ok(Json(FilterRuleInfo {
id: row.get(0),
rule_name: row.get(1),
@@ -502,7 +506,7 @@ pub async fn get_filter_rules(
Path(file_uuid): Path<String>,
) -> Result<Json<FilterRulesResponse>, StatusCode> {
let rules_table = schema::table_name("filter_rules");
let rows = sqlx::query(&format!(
"SELECT id, rule_name, rules, is_active, created_at::TEXT, updated_at::TEXT
FROM {}
@@ -514,7 +518,7 @@ pub async fn get_filter_rules(
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let rules: Vec<FilterRuleInfo> = rows
.into_iter()
.map(|row| {
@@ -529,7 +533,7 @@ pub async fn get_filter_rules(
}
})
.collect();
Ok(Json(FilterRulesResponse { rules }))
}
@@ -537,9 +541,24 @@ pub async fn get_filter_rules(
pub fn face_filter_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/file/:file_uuid/face-filter/faces", get(get_faces))
.route("/api/v1/file/:file_uuid/face-filter/:face_id/report", get(get_face_filter_report))
.route("/api/v1/file/:file_uuid/face-filter/apply", post(filter_faces))
.route("/api/v1/file/:file_uuid/face-filter/stats", get(get_filter_stats))
.route("/api/v1/file/:file_uuid/face-filter/rules", get(get_filter_rules))
.route("/api/v1/file/:file_uuid/face-filter/rules", post(save_filter_rules))
.route(
"/api/v1/file/:file_uuid/face-filter/:face_id/report",
get(get_face_filter_report),
)
.route(
"/api/v1/file/:file_uuid/face-filter/apply",
post(filter_faces),
)
.route(
"/api/v1/file/:file_uuid/face-filter/stats",
get(get_filter_stats),
)
.route(
"/api/v1/file/:file_uuid/face-filter/rules",
get(get_filter_rules),
)
.route(
"/api/v1/file/:file_uuid/face-filter/rules",
post(save_filter_rules),
)
}
+6 -5
View File
@@ -1062,10 +1062,7 @@ async fn search_file_faces(
let where_sql = where_clauses.join(" AND ");
// Count total
let count_sql = format!(
"SELECT COUNT(*) FROM {} tp WHERE {}",
tp_table, where_sql
);
let count_sql = format!("SELECT COUNT(*) FROM {} tp WHERE {}", tp_table, where_sql);
let mut count_query = sqlx::query_scalar::<_, i64>(&count_sql).bind(&file_uuid);
if let Some(ref q) = params.q {
@@ -1110,7 +1107,11 @@ async fn search_file_faces(
WHERE {} \
ORDER BY tp.start_frame ASC \
LIMIT ${} OFFSET ${}",
tp_table, video_table, where_sql, param_idx, param_idx + 1
tp_table,
video_table,
where_sql,
param_idx,
param_idx + 1
);
let mut data_query = sqlx::query(&data_sql).bind(&file_uuid);
+16 -4
View File
@@ -1773,7 +1773,10 @@ async fn get_face_landmarks_handler(
let face_path = std::path::Path::new(output_dir).join(format!("{}.face.json", file_uuid));
if !face_path.exists() {
tracing::error!("[get_face_landmarks] File not found: {}", face_path.display());
tracing::error!(
"[get_face_landmarks] File not found: {}",
face_path.display()
);
return Err(StatusCode::NOT_FOUND);
}
@@ -1840,7 +1843,10 @@ async fn get_face_landmarks_handler(
y: face.get("y").and_then(|v| v.as_i64()).unwrap_or(0),
width: face.get("width").and_then(|v| v.as_i64()).unwrap_or(0),
height: face.get("height").and_then(|v| v.as_i64()).unwrap_or(0),
confidence: face.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0),
confidence: face
.get("confidence")
.and_then(|v| v.as_f64())
.unwrap_or(0.0),
})
.collect();
@@ -1850,8 +1856,14 @@ async fn get_face_landmarks_handler(
y: selected.get("y").and_then(|v| v.as_i64()).unwrap_or(0),
width: selected.get("width").and_then(|v| v.as_i64()).unwrap_or(0),
height: selected.get("height").and_then(|v| v.as_i64()).unwrap_or(0),
confidence: selected.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0),
pose_angle: selected.get("pose_angle").cloned().or_else(|| selected.get("pose").cloned()),
confidence: selected
.get("confidence")
.and_then(|v| v.as_f64())
.unwrap_or(0.0),
pose_angle: selected
.get("pose_angle")
.cloned()
.or_else(|| selected.get("pose").cloned()),
landmarks: selected
.get("landmarks")
.cloned()
+23 -8
View File
@@ -267,15 +267,21 @@ pub async fn request_logger(request: Request, next: Next) -> Response {
let query = request.uri().query().unwrap_or("").to_string();
// Skip health checks and static files to reduce noise
if path == "/api/v1/health"
|| path.starts_with("/static")
|| path.starts_with("/favicon")
{
if path == "/api/v1/health" || path.starts_with("/static") || path.starts_with("/favicon") {
return next.run(request).await;
}
let start = std::time::Instant::now();
tracing::info!("[API Request] {} {}{}", method, path, if query.is_empty() { String::new() } else { format!("?{}", query) });
tracing::info!(
"[API Request] {} {}{}",
method,
path,
if query.is_empty() {
String::new()
} else {
format!("?{}", query)
}
);
let response = next.run(request).await;
let duration = start.elapsed();
@@ -286,17 +292,26 @@ pub async fn request_logger(request: Request, next: Next) -> Response {
if status.is_server_error() {
tracing::error!(
"[API Response] {} {} -> {} ({}ms)",
method, path, status, duration_ms
method,
path,
status,
duration_ms
);
} else if status.is_client_error() {
tracing::warn!(
"[API Response] {} {} -> {} ({}ms)",
method, path, status, duration_ms
method,
path,
status,
duration_ms
);
} else {
tracing::info!(
"[API Response] {} {} -> {} ({}ms)",
method, path, status, duration_ms
method,
path,
status,
duration_ms
);
}
+22 -24
View File
@@ -120,31 +120,36 @@ pub async fn get_trace_profile_handler(
let external_id_face = format!("face_track_{}", params.trace_id);
let external_id_trace = format!("trace_{}", params.trace_id);
let row: Option<(String, String, Option<serde_json::Value>, Option<serde_json::Value>)> =
sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
let row: Option<(
String,
String,
Option<serde_json::Value>,
Option<serde_json::Value>,
)> = sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
tp.properties, tn.properties \
FROM {} tn \
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
AND tp.trace_id = (tn.properties->>'trace_id')::int \
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
AND (tn.external_id = $2 OR tn.external_id = $3)",
tkg_table, tp_table
))
.bind(&params.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[TraceProfile] DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tkg_table, tp_table
))
.bind(&params.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[TraceProfile] DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?;
// Merge properties: tp_props takes precedence, tn_props as fallback
let mut properties = tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
let mut properties =
tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
if let Some(tp_obj) = tp_props.as_ref().and_then(|v| v.as_object()) {
if let Some(props_obj) = properties.as_object_mut() {
for (k, v) in tp_obj {
@@ -1243,17 +1248,10 @@ pub async fn get_face_groups_handler(
}
}
// Filter out single-trace "groups" — only auto-generated Person_N names.
// User-named groups (even with 1 trace) are kept.
// All Person_N groups are shown as face groups regardless of trace count.
let mut filtered_groups: HashMap<String, Vec<i32>> = HashMap::new();
for (name, trace_ids) in groups {
let is_auto_name = name.starts_with("Person_");
if trace_ids.len() > 1 || !is_auto_name {
filtered_groups.insert(name, trace_ids);
} else {
// Single-trace auto-generated group → treat as unassigned
unassigned.extend(trace_ids);
}
filtered_groups.insert(name, trace_ids);
}
let include_trace_ids = q.include_trace_ids.unwrap_or(true);
+4 -1
View File
@@ -41,7 +41,10 @@ async fn main() -> Result<()> {
}
}
println!("\nDone! Total updated: {}, Errors: {}", total_updated, total_errors);
println!(
"\nDone! Total updated: {}, Errors: {}",
total_updated, total_errors
);
Ok(())
}
+44 -26
View File
@@ -69,10 +69,7 @@ async fn main() -> Result<()> {
Ok(())
}
async fn rebuild_file_thumbs(
qdrant: &QdrantDb,
file_uuid: &str,
) -> Result<(usize, usize)> {
async fn rebuild_file_thumbs(qdrant: &QdrantDb, file_uuid: &str) -> Result<(usize, usize)> {
// Get all face points for this file
let filter = json!({
"must": [
@@ -88,13 +85,12 @@ async fn rebuild_file_thumbs(
// Get video path from DB
let db = PostgresDb::new(&config::DATABASE_URL).await?;
let video_path: Option<String> = sqlx::query_scalar(
"SELECT file_path FROM videos WHERE file_uuid = $1",
)
.bind(file_uuid)
.fetch_optional(db.pool())
.await?
.flatten();
let video_path: Option<String> =
sqlx::query_scalar("SELECT file_path FROM videos WHERE file_uuid = $1")
.bind(file_uuid)
.fetch_optional(db.pool())
.await?
.flatten();
let video_path = match video_path {
Some(p) => p,
@@ -116,7 +112,9 @@ async fn rebuild_file_thumbs(
let w = bbox["width"].as_f64().unwrap_or(0.0);
let h = bbox["height"].as_f64().unwrap_or(0.0);
let entry = best_faces.entry(tid as i32).or_insert((0.0, 0, 0.0, 0.0, 0.0, 0.0));
let entry = best_faces
.entry(tid as i32)
.or_insert((0.0, 0, 0.0, 0.0, 0.0, 0.0));
if conf > entry.0 {
*entry = (conf, frame, x, y, w, h);
}
@@ -161,11 +159,20 @@ async fn rebuild_file_thumbs(
let output = Command::new("ffmpeg")
.args([
"-y", "-v", "quiet",
"-i", &video_path,
"-vf", &format!("select=eq(n\\,{}),crop={}:{}:{}:{}", frame_num, size, size, crop_x, crop_y),
"-frames:v", "1",
"-q:v", "2",
"-y",
"-v",
"quiet",
"-i",
&video_path,
"-vf",
&format!(
"select=eq(n\\,{}),crop={}:{}:{}:{}",
frame_num, size, size, crop_x, crop_y
),
"-frames:v",
"1",
"-q:v",
"2",
key_face_path.to_str().unwrap(),
])
.output();
@@ -179,11 +186,17 @@ async fn rebuild_file_thumbs(
let tmp_frame = trace_dir.join("tmp_frame.jpg");
let _ = Command::new("ffmpeg")
.args([
"-y", "-v", "quiet",
"-i", &video_path,
"-vf", &select_filter,
"-frames:v", "1",
"-q:v", "2",
"-y",
"-v",
"quiet",
"-i",
&video_path,
"-vf",
&select_filter,
"-frames:v",
"1",
"-q:v",
"2",
tmp_frame.to_str().unwrap(),
])
.output();
@@ -191,10 +204,15 @@ async fn rebuild_file_thumbs(
if tmp_frame.exists() {
let _ = Command::new("ffmpeg")
.args([
"-y", "-v", "quiet",
"-i", tmp_frame.to_str().unwrap(),
"-vf", &format!("crop={}:{}:{}:{}", size, size, crop_x, crop_y),
"-q:v", "2",
"-y",
"-v",
"quiet",
"-i",
tmp_frame.to_str().unwrap(),
"-vf",
&format!("crop={}:{}:{}:{}", size, size, crop_x, crop_y),
"-q:v",
"2",
key_face_path.to_str().unwrap(),
])
.output();
+5
View File
@@ -45,6 +45,11 @@ pub enum Commands {
/// File UUID
uuid: String,
},
/// Backfill missing TKG trace artifact dirs (skips existing dirs)
TkgBackfill {
/// File UUID
file_uuid: String,
},
/// Detect objects in an image using CLIP or Qwen3-VL
Detect {
/// Image path
+1 -4
View File
@@ -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,
+6 -26
View File
@@ -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);
+7 -2
View File
@@ -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);
+33 -7
View File
@@ -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
View File
@@ -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,
}
}
-88
View File
@@ -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)
}
+3
View File
@@ -50,6 +50,9 @@ async fn main() -> Result<()> {
Commands::StoreAsrx { uuid } => {
handle_store_asrx(&uuid).await?;
}
Commands::TkgBackfill { file_uuid } => {
handle_tkg_backfill(&file_uuid).await?;
}
Commands::Vectorize { uuid } => {
handle_vectorize(&uuid).await?;
}
+17
View File
@@ -404,6 +404,23 @@ pub async fn handle_phase1(uuid: &str) -> Result<()> {
momentry_core::core::pipeline::run_phase1(uuid).await
}
/// Handle tkg-backfill command
pub async fn handle_tkg_backfill(file_uuid: &str) -> Result<()> {
let db = momentry_core::core::db::postgres_db::PostgresDb::new(
&momentry_core::core::config::DATABASE_URL,
)
.await?;
let output_dir = momentry_core::core::config::OUTPUT_DIR.as_str();
let n = momentry_core::core::processor::tkg::backfill_trace_dirs(&db, file_uuid, output_dir)
.await?;
tracing::info!(
"[tkg-backfill] built {} trace artifact dirs for {}",
n,
file_uuid
);
Ok(())
}
/// Handle complete command
pub async fn handle_complete(uuid: &str) -> Result<()> {
let db = momentry_core::core::db::postgres_db::PostgresDb::new(
+54 -26
View File
@@ -2665,32 +2665,6 @@ impl JobWorker {
uuid_clone, e
),
}
// P5: VLM Summary — after face dedup writes trace_profiles
let face_count = Self::verify_traces_ready(&db_clone.pool(), &uuid_clone).await;
if face_count > 0 {
info!("[VLM] Starting for {}: {} traces verified", uuid_clone, face_count);
let db_p5 = db_clone.clone();
let redis_p5 = redis_clone.clone();
let uuid_p5 = uuid_clone.clone();
let output_dir_p5 = output_dir.clone();
tokio::spawn(async move {
let result = tokio::time::timeout(
std::time::Duration::from_secs(300),
crate::core::processor::vlm_summary::generate_vlm_summaries(
&db_p5, &uuid_p5, &output_dir_p5, Some(redis_p5),
),
)
.await;
match result {
Ok(stats) => info!(
"[VLM] Completed for {}: {}/{} summarized, {} embedded",
uuid_p5, stats.summarized, stats.total, stats.embedded
),
Err(_) => error!("[VLM] Timed out after 5 min for {}", uuid_p5),
}
});
}
});
} else {
warn!("Failed to parse face_cluster.json for {}", uuid);
@@ -2938,6 +2912,60 @@ impl JobWorker {
)
.await;
// P5: VLM Summary — wait for ALL key_frame.jpg files to be ready
let face_count = r.face_track_nodes;
if face_count > 0 {
let output_dir_wait = output_dir_clone.clone();
let uuid_wait = uuid_clone.clone();
let db_wait = db_clone.clone();
let redis_wait = redis_clone.clone();
tokio::spawn(async move {
// Poll until ALL key_frame.jpg files exist (max 10 min)
let max_attempts = 600; // 10 min / 1s
let mut ready_count = 0i64;
for attempt in 0..max_attempts {
// Count traces with key_frame.jpg on disk
let output_dir = output_dir_wait.as_str();
let trace_dir = std::path::PathBuf::from(output_dir)
.join(&uuid_wait);
ready_count = if trace_dir.exists() {
std::fs::read_dir(&trace_dir)
.ok()
.map(|entries| {
entries.filter_map(|e| e.ok()).filter(|e| {
e.path().join("key_frame.jpg").exists()
}).count() as i64
})
.unwrap_or(0)
} else {
0
};
if ready_count >= face_count as i64 && ready_count > 0 {
info!("[VLM-wait] All {}/{} key_frame.jpg ready for {}", ready_count, face_count, uuid_wait);
break;
}
if attempt % 30 == 0 {
info!("[VLM-wait] {}/{} key_frame.jpg ready for {} (waiting...)", ready_count, face_count, uuid_wait);
}
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
if ready_count >= face_count as i64 {
info!("[VLM] Starting for {}: {} traces verified", uuid_wait, ready_count);
let db_p5 = db_wait.clone();
let redis_p5 = redis_wait.clone();
let uuid_p5 = uuid_wait.clone();
let output_dir_p5 = output_dir_wait.clone();
crate::core::processor::vlm_summary::generate_vlm_summaries(
&db_p5, &uuid_p5, &output_dir_p5, Some(redis_p5),
).await;
} else {
warn!("[VLM] Skipping for {} (only {}/{} key_frame.jpg ready)", uuid_wait, ready_count, face_count);
}
});
}
// Trigger Rule 2 ingestion after TKG complete
if total_edges > 0 {
// Mark rule2_ingestion as running