fix: schema.rs COALESCE加固 + rebuild_trace_thumbs tool
- schema.rs: ON CONFLICT 加入 COALESCE 避免 edge case 把回填值打回 NULL - rebuild_trace_thumbs: 從 Qdrant _faces 找 best face 重建 key_face.jpg - 已完成 61/10184 traces(工具運作中,大檔案需較長時間)
This commit is contained in:
@@ -155,3 +155,7 @@ tempfile = "3"
|
||||
[[bin]]
|
||||
name = "backfill_trace_profiles"
|
||||
path = "src/bin/backfill_trace_profiles.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rebuild_trace_thumbs"
|
||||
path = "src/bin/rebuild_trace_thumbs.rs"
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
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;
|
||||
|
||||
#[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 mut total_rebuilt = 0;
|
||||
let mut total_skipped = 0;
|
||||
let mut total_errors = 0;
|
||||
|
||||
for file_uuid in &files {
|
||||
match rebuild_file_thumbs(&db, &qdrant, file_uuid).await {
|
||||
Ok((rebuilt, skipped)) => {
|
||||
total_rebuilt += rebuilt;
|
||||
total_skipped += skipped;
|
||||
println!(" ✅ {} : {} rebuilt, {} skipped", file_uuid, rebuilt, skipped);
|
||||
}
|
||||
Err(e) => {
|
||||
total_errors += 1;
|
||||
eprintln!(" ❌ {} : {}", file_uuid, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("\nDone! Rebuilt: {}, Skipped: {}, Errors: {}", total_rebuilt, total_skipped, total_errors);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn rebuild_file_thumbs(
|
||||
db: &PostgresDb,
|
||||
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
|
||||
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, (i64, i64, i64, i64, i64)> = 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) as i64;
|
||||
let y = bbox["y"].as_f64().unwrap_or(0.0) as i64;
|
||||
let w = bbox["width"].as_f64().unwrap_or(0.0) as i64;
|
||||
let h = bbox["height"].as_f64().unwrap_or(0.0) as i64;
|
||||
|
||||
let entry = best_faces.entry(tid as i32).or_insert((0, 0, 0, 0, 0));
|
||||
if conf > entry.0 as f64 || entry.0 == 0 {
|
||||
*entry = (conf as i64, frame, x, y, w.max(h)); // Use max(w,h) for square crop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let output_dir = config::OUTPUT_DIR.as_str();
|
||||
let mut rebuilt = 0;
|
||||
let mut skipped = 0;
|
||||
|
||||
for (trace_id, (_conf, frame, x, y, size)) 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)
|
||||
let select_filter = format!("select=eq(n\\,{})", frame);
|
||||
let key_frame_tmp = trace_dir.join("key_frame_tmp.jpg");
|
||||
|
||||
let output = Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y", "-v", "quiet",
|
||||
"-i", &video_path,
|
||||
"-vf", &select_filter,
|
||||
"-frames:v", "1",
|
||||
"-q:v", "2",
|
||||
"-f", "image2pipe",
|
||||
"-c:v", "mjpeg",
|
||||
"pipe:1",
|
||||
])
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() || output.stdout.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
std::fs::write(&key_frame_tmp, &output.stdout)?;
|
||||
|
||||
// Crop square around face
|
||||
let half = size / 2;
|
||||
let crop_x = (x - half).max(0);
|
||||
let crop_y = (y - half).max(0);
|
||||
let crop_filter = format!("crop={}:{}:{}:{}", size, size, crop_x, crop_y);
|
||||
|
||||
let output = Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y", "-v", "quiet",
|
||||
"-i", key_frame_tmp.to_str().unwrap(),
|
||||
"-vf", &crop_filter,
|
||||
"-q:v", "2",
|
||||
key_face_path.to_str().unwrap(),
|
||||
])
|
||||
.output()?;
|
||||
|
||||
let _ = std::fs::remove_file(&key_frame_tmp);
|
||||
|
||||
if output.status.success() && key_face_path.exists() {
|
||||
rebuilt += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok((rebuilt, skipped))
|
||||
}
|
||||
+12
-12
@@ -53,19 +53,19 @@ pub async fn upsert_trace_profile(
|
||||
COALESCE($4::jsonb, {props_sub}, '{{}}'::jsonb)) \
|
||||
ON CONFLICT (file_uuid, trace_id) \
|
||||
DO UPDATE SET name = EXCLUDED.name{update_props}, \
|
||||
start_frame = EXCLUDED.start_frame, \
|
||||
end_frame = EXCLUDED.end_frame, \
|
||||
frame_count = EXCLUDED.frame_count, \
|
||||
key_frame = EXCLUDED.key_frame, \
|
||||
key_face = EXCLUDED.key_face, \
|
||||
avg_confidence = EXCLUDED.avg_confidence, \
|
||||
start_frame = COALESCE(EXCLUDED.start_frame, trace_profiles.start_frame), \
|
||||
end_frame = COALESCE(EXCLUDED.end_frame, trace_profiles.end_frame), \
|
||||
frame_count = COALESCE(EXCLUDED.frame_count, trace_profiles.frame_count), \
|
||||
key_frame = COALESCE(EXCLUDED.key_frame, trace_profiles.key_frame), \
|
||||
key_face = COALESCE(EXCLUDED.key_face, trace_profiles.key_face), \
|
||||
avg_confidence = COALESCE(EXCLUDED.avg_confidence, trace_profiles.avg_confidence), \
|
||||
updated_at = NOW()",
|
||||
sf = tkg_sub("(tn.properties->>'start_frame')::bigint"),
|
||||
ef = tkg_sub("(tn.properties->>'end_frame')::bigint"),
|
||||
fc = tkg_sub("(tn.properties->>'frame_count')::int"),
|
||||
kf = tkg_sub("tn.properties->>'key_frame'"),
|
||||
kface = tkg_sub("tn.properties->>'key_face'"),
|
||||
avgc = tkg_sub("(tn.properties->>'avg_confidence')::double precision"),
|
||||
sf = tkg_sub("COALESCE((tn.properties->>'start_frame')::bigint, trace_profiles.start_frame)"),
|
||||
ef = tkg_sub("COALESCE((tn.properties->>'end_frame')::bigint, trace_profiles.end_frame)"),
|
||||
fc = tkg_sub("COALESCE((tn.properties->>'frame_count')::int, trace_profiles.frame_count)"),
|
||||
kf = tkg_sub("COALESCE(tn.properties->>'key_frame', trace_profiles.key_frame)"),
|
||||
kface = tkg_sub("COALESCE(tn.properties->>'key_face', trace_profiles.key_face)"),
|
||||
avgc = tkg_sub("COALESCE((tn.properties->>'avg_confidence')::double precision, trace_profiles.avg_confidence)"),
|
||||
props_sub = tkg_sub("tn.properties"),
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user