Files
momentry_core/src/bin/rebuild_trace_thumbs.rs
T
Accusys 9f12e835b8 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
2026-08-24 19:13:11 +08:00

230 lines
7.2 KiB
Rust

use anyhow::Result;
use momentry_core::core::config;
use momentry_core::core::db::{qdrant_db::QdrantDb, PostgresDb};
use serde_json::json;
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let db = PostgresDb::new(&config::DATABASE_URL).await?;
let qdrant = QdrantDb::new();
// Find all files with traces
let files: Vec<String> = sqlx::query_scalar::<_, String>(
"SELECT DISTINCT file_uuid FROM trace_profiles ORDER BY file_uuid",
)
.fetch_all(db.pool())
.await?;
println!("Found {} files to process", files.len());
let total_rebuilt = Arc::new(AtomicUsize::new(0));
let total_skipped = Arc::new(AtomicUsize::new(0));
let total_errors = Arc::new(AtomicUsize::new(0));
// Process files in parallel (4 at a time)
let mut tasks = Vec::new();
for file_uuid in files {
let qdrant = QdrantDb::new();
let rebuilt = total_rebuilt.clone();
let skipped = total_skipped.clone();
let errors = total_errors.clone();
let task = tokio::spawn(async move {
match rebuild_file_thumbs(&qdrant, &file_uuid).await {
Ok((r, s)) => {
rebuilt.fetch_add(r, Ordering::Relaxed);
skipped.fetch_add(s, Ordering::Relaxed);
}
Err(e) => {
errors.fetch_add(1, Ordering::Relaxed);
eprintln!(" ❌ {} : {}", file_uuid, e);
}
}
});
tasks.push(task);
// Limit concurrency to 4
if tasks.len() >= 4 {
tasks.pop().unwrap().await?;
}
}
// Wait for remaining tasks
for task in tasks {
task.await?;
}
println!(
"\nDone! Rebuilt: {}, Skipped: {}, Errors: {}",
total_rebuilt.load(Ordering::Relaxed),
total_skipped.load(Ordering::Relaxed),
total_errors.load(Ordering::Relaxed)
);
Ok(())
}
async fn rebuild_file_thumbs(qdrant: &QdrantDb, file_uuid: &str) -> Result<(usize, usize)> {
// Get all face points for this file
let filter = json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}}
]
});
let points = qdrant.scroll_all_points("_faces", filter, 10000).await?;
if points.is_empty() {
return Ok((0, 0));
}
// 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 = match video_path {
Some(p) => p,
None => return Ok((0, 0)),
};
// Group by trace_id and find best face (highest confidence)
let mut best_faces: std::collections::HashMap<i32, (f64, i64, f64, f64, f64, f64)> =
std::collections::HashMap::new();
for p in &points {
let payload = &p["payload"];
if let Some(tid) = payload["trace_id"].as_i64() {
let conf = payload["confidence"].as_f64().unwrap_or(0.0);
let frame = payload["frame"].as_i64().unwrap_or(0);
let bbox = &payload["bbox"];
let x = bbox["x"].as_f64().unwrap_or(0.0);
let y = bbox["y"].as_f64().unwrap_or(0.0);
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));
if conf > entry.0 {
*entry = (conf, frame, x, y, w, h);
}
}
}
let output_dir = config::OUTPUT_DIR.as_str();
let mut rebuilt = 0;
let mut skipped = 0;
for (trace_id, (_conf, frame, x, y, w, h)) in &best_faces {
let trace_dir = PathBuf::from(output_dir)
.join(file_uuid)
.join(format!("trace_{}", trace_id));
let key_face_path = trace_dir.join("key_face.jpg");
// Check if already exists and valid
if key_face_path.exists() {
let meta = std::fs::metadata(&key_face_path)?;
if meta.len() > 100 {
skipped += 1;
continue;
}
}
// Create directory
std::fs::create_dir_all(&trace_dir)?;
// Extract frame using select=eq(n,frame) for VFR compatibility
let frame_num = *frame;
let x_val = *x as i64;
let y_val = *y as i64;
let w_val = *w as i64;
let h_val = *h as i64;
let select_filter = format!("select=eq(n\\,{})", frame_num);
// Use ffmpeg pipe to extract frame, then crop in one pipeline
let size = (w_val.max(h_val) as f64 * 1.2) as i64; // 20% padding
let half = size / 2;
let crop_x = (x_val - half).max(0);
let crop_y = (y_val - half).max(0);
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",
key_face_path.to_str().unwrap(),
])
.output();
match output {
Ok(out) if out.status.success() && key_face_path.exists() => {
rebuilt += 1;
}
_ => {
// Fallback: extract frame first, then crop
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",
tmp_frame.to_str().unwrap(),
])
.output();
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",
key_face_path.to_str().unwrap(),
])
.output();
let _ = std::fs::remove_file(&tmp_frame);
if key_face_path.exists() {
rebuilt += 1;
}
}
}
}
}
Ok((rebuilt, skipped))
}