feat: real service test endpoints (proxy 7-route round-trip, core/chat/vlm/markbase/embedding), unified log paths + errorLog, pipeline tools/import/export/folder APIs, face pipeline check, dynamic concurrency tuning
This commit is contained in:
@@ -19,6 +19,11 @@ pub const HOP_LENGTH: usize = 160;
|
||||
pub const WIN_LENGTH: usize = 400;
|
||||
pub const N_BINS: usize = N_FFT / 2 + 1; // 201
|
||||
pub const N_MELS: usize = 80;
|
||||
|
||||
/// ECAPA 嵌入的最低幀數(10ms/幀 → 16 幀 = 160ms)。
|
||||
/// 不足者以循環 tile 補足 — 反映 padding 需要時間軸長度 >= 2,
|
||||
/// 且太短的情緒特徵毫無意義,補足只是為了讓模型能跑完。
|
||||
pub const MIN_EMBED_FRAMES: usize = 16;
|
||||
const PAD: usize = N_FFT / 2;
|
||||
const AMIN: f32 = 1e-10;
|
||||
const TOP_DB: f32 = 80.0;
|
||||
@@ -154,8 +159,30 @@ impl Ecapa {
|
||||
}
|
||||
|
||||
/// Run the embedding network on features [n_frames, N_MELS]; returns 192-d.
|
||||
///
|
||||
/// ECAPA TDNN 的 conv 使用 reflect padding,時間軸過短(< 若干幀)會在
|
||||
/// ONNX Pad node 崩潰:"Pad reflect requires axis length >= 2 after
|
||||
/// slicing. Input shape:{1,80,1}"。長度不足的片段以循環 tile 補足到
|
||||
/// MIN_EMBED_FRAMES,避免崩潰並保留粗略的說話者相似度。
|
||||
pub fn embed(&mut self, feats: &[f32], n_frames: usize) -> Result<Vec<f32>> {
|
||||
let input = ndarray::Array::from_shape_vec(IxDyn(&[1, n_frames, N_MELS]), feats.to_vec())
|
||||
// 極短(或空)片段:無法形成有效特徵 → 回傳零向量(不參與聚類相似度)
|
||||
if n_frames == 0 || feats.is_empty() {
|
||||
return Ok(vec![0f32; 192]);
|
||||
}
|
||||
|
||||
let min_frames = MIN_EMBED_FRAMES;
|
||||
let (feats_vec, n_eff) = if n_frames < min_frames {
|
||||
let mut padded = Vec::with_capacity(min_frames * N_MELS);
|
||||
for t in 0..min_frames {
|
||||
let src = t % n_frames;
|
||||
padded.extend_from_slice(&feats[src * N_MELS..(src + 1) * N_MELS]);
|
||||
}
|
||||
(padded, min_frames)
|
||||
} else {
|
||||
(feats.to_vec(), n_frames)
|
||||
};
|
||||
|
||||
let input = ndarray::Array::from_shape_vec(IxDyn(&[1, n_eff, N_MELS]), feats_vec)
|
||||
.context("Failed to create ECAPA input array")?;
|
||||
|
||||
let input_value = Value::from_array(input).context("Failed to create input value")?;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use anyhow::{Context, Result};
|
||||
use chrono::Utc;
|
||||
use clap::Parser;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::process::Command;
|
||||
@@ -24,15 +25,87 @@ struct Cli {
|
||||
min_scene_duration: f64,
|
||||
}
|
||||
|
||||
// ─── 標準化輸出格式 ─────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct CutResult {
|
||||
scene_count: usize,
|
||||
struct StandardOutput {
|
||||
_meta: Meta,
|
||||
_debug: DebugInfo,
|
||||
status: String,
|
||||
data: CutData,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Meta {
|
||||
schema_version: String,
|
||||
processor: ProcessorInfo,
|
||||
source: SourceInfo,
|
||||
timestamps: Timestamps,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pipeline: Option<PipelineInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct ProcessorInfo {
|
||||
name: String,
|
||||
tool: String,
|
||||
version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct SourceInfo {
|
||||
file_uuid: String,
|
||||
file_path: String,
|
||||
file_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Timestamps {
|
||||
created_at: String,
|
||||
completed_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct PipelineInfo {
|
||||
scan_id: String,
|
||||
worker_id: String,
|
||||
stage: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct DebugInfo {
|
||||
absolute_path: String,
|
||||
written_at_unix: u64,
|
||||
output_dir: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct CutData {
|
||||
frame_count: u64,
|
||||
fps: f64,
|
||||
scenes: Vec<Scene>,
|
||||
video_info: VideoInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Scene {
|
||||
scene_number: usize,
|
||||
start_frame: u64,
|
||||
end_frame: u64,
|
||||
start_time: f64,
|
||||
end_time: f64,
|
||||
}
|
||||
|
||||
// ─── 舊格式(向後相容)─────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct CutResult {
|
||||
scene_count: usize,
|
||||
scenes: Vec<InternalScene>,
|
||||
video_info: VideoInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct InternalScene {
|
||||
scene_id: usize,
|
||||
start_frame: u64,
|
||||
start_time: f64,
|
||||
@@ -54,7 +127,11 @@ fn main() -> Result<()> {
|
||||
println!("[CUT] Processing: {}", args.video_path);
|
||||
|
||||
let output_path = args.output.unwrap_or_else(|| {
|
||||
args.video_path.replace(".mp4", ".cut.json")
|
||||
if let Some(uuid) = &args.uuid {
|
||||
format!("output/demo/{}.cut.json", uuid)
|
||||
} else {
|
||||
args.video_path.replace(".mp4", ".cut.json")
|
||||
}
|
||||
});
|
||||
|
||||
let video_info = get_video_info(&args.video_path)?;
|
||||
@@ -64,13 +141,62 @@ fn main() -> Result<()> {
|
||||
let scenes = detect_scenes(&args.video_path, args.min_scene_duration, &video_info)?;
|
||||
println!("[CUT] Detected {} scenes", scenes.len());
|
||||
|
||||
let result = CutResult {
|
||||
scene_count: scenes.len(),
|
||||
scenes,
|
||||
video_info,
|
||||
// 建立標準化輸出
|
||||
let file_uuid = args.uuid.clone().unwrap_or_default();
|
||||
let file_name = std::path::Path::new(&args.video_path)
|
||||
.file_name()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
|
||||
let now = Utc::now();
|
||||
let standard_output = StandardOutput {
|
||||
_meta: Meta {
|
||||
schema_version: "1.0".to_string(),
|
||||
processor: ProcessorInfo {
|
||||
name: "cut".to_string(),
|
||||
tool: "ffmpeg_native".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
},
|
||||
source: SourceInfo {
|
||||
file_uuid: file_uuid.clone(),
|
||||
file_path: args.video_path.clone(),
|
||||
file_name: file_name.clone(),
|
||||
},
|
||||
timestamps: Timestamps {
|
||||
created_at: now.to_rfc3339(),
|
||||
completed_at: now.to_rfc3339(),
|
||||
},
|
||||
pipeline: Some(PipelineInfo {
|
||||
scan_id: std::env::var("MOMENTRY_SCAN_ID").unwrap_or_default(),
|
||||
worker_id: std::env::var("MOMENTRY_WORKER_ID").unwrap_or_default(),
|
||||
stage: "deep_scan".to_string(),
|
||||
}),
|
||||
},
|
||||
_debug: DebugInfo {
|
||||
absolute_path: std::fs::canonicalize(&output_path)
|
||||
.unwrap_or_else(|_| std::path::PathBuf::from(&output_path))
|
||||
.to_string_lossy()
|
||||
.to_string(),
|
||||
written_at_unix: now.timestamp() as u64,
|
||||
output_dir: std::env::var("MOMENTRY_OUTPUT_DIR")
|
||||
.unwrap_or_else(|_| "output/demo".to_string()),
|
||||
},
|
||||
status: "completed".to_string(),
|
||||
data: CutData {
|
||||
frame_count: video_info.frame_count,
|
||||
fps: video_info.fps,
|
||||
scenes: scenes.into_iter().map(|s: InternalScene| Scene {
|
||||
scene_number: s.scene_id,
|
||||
start_frame: s.start_frame,
|
||||
end_frame: s.end_frame,
|
||||
start_time: s.start_time,
|
||||
end_time: s.end_time,
|
||||
}).collect(),
|
||||
},
|
||||
};
|
||||
|
||||
let json = serde_json::to_string_pretty(&result)?;
|
||||
let json = serde_json::to_string_pretty(&standard_output)?;
|
||||
std::fs::write(&output_path, json)?;
|
||||
println!("[CUT] Output: {}", output_path);
|
||||
|
||||
@@ -122,7 +248,7 @@ fn get_video_info(video_path: &str) -> Result<VideoInfo> {
|
||||
})
|
||||
}
|
||||
|
||||
fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) -> Result<Vec<Scene>> {
|
||||
fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) -> Result<Vec<InternalScene>> {
|
||||
let output = Command::new("ffmpeg")
|
||||
.args([
|
||||
"-i", video_path,
|
||||
@@ -147,7 +273,7 @@ fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) ->
|
||||
let start_frame = (last_time * video_info.fps) as u64;
|
||||
let end_frame = (time * video_info.fps) as u64;
|
||||
|
||||
scenes.push(Scene {
|
||||
scenes.push(InternalScene {
|
||||
scene_id,
|
||||
start_frame,
|
||||
start_time: last_time,
|
||||
@@ -165,7 +291,7 @@ fn detect_scenes(video_path: &str, min_duration: f64, video_info: &VideoInfo) ->
|
||||
}
|
||||
|
||||
if scenes.is_empty() {
|
||||
scenes.push(Scene {
|
||||
scenes.push(InternalScene {
|
||||
scene_id: 0,
|
||||
start_frame: 0,
|
||||
start_time: 0.0,
|
||||
|
||||
@@ -528,6 +528,138 @@ fn stage2_merge_clusters(
|
||||
trace_to_person
|
||||
}
|
||||
|
||||
/// Apply co-occurrence constraints: split traces that appear in same frame but are assigned to same person
|
||||
fn apply_cooccurrence_constraints(
|
||||
trace_to_person: std::collections::BTreeMap<i64, i64>,
|
||||
trace_embeddings: &std::collections::BTreeMap<i64, Vec<f64>>,
|
||||
constraints: &std::collections::HashSet<(i64, i64)>,
|
||||
) -> std::collections::BTreeMap<i64, i64> {
|
||||
let mut trace_to_person: std::collections::HashMap<i64, i64> = trace_to_person.into_iter().collect();
|
||||
let mut next_person_id = trace_to_person.values().max().copied().unwrap_or(0) + 1;
|
||||
let mut split_count = 0;
|
||||
|
||||
for (tid_a, tid_b) in constraints.iter() {
|
||||
let person_a = trace_to_person.get(tid_a).copied();
|
||||
let person_b = trace_to_person.get(tid_b).copied();
|
||||
|
||||
if let (Some(pa), Some(pb)) = (person_a, person_b) {
|
||||
if pa == pb {
|
||||
// Same person but shouldn't be - split trace_b to new person
|
||||
trace_to_person.insert(*tid_b, next_person_id);
|
||||
next_person_id += 1;
|
||||
split_count += 1;
|
||||
eprintln!(" [SPLIT] Trace {} from Person_{} (co-occurs with trace {})", tid_b, pa, tid_a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if split_count > 0 {
|
||||
eprintln!("[CONSTRAINT] Split {} traces due to co-occurrence", split_count);
|
||||
}
|
||||
|
||||
// Re-index person IDs to be contiguous
|
||||
let unique_pids: std::collections::BTreeSet<i64> = trace_to_person.values().copied().collect();
|
||||
let pid_map: std::collections::HashMap<i64, i64> = unique_pids.into_iter().enumerate().map(|(new, old)| (old, new as i64)).collect();
|
||||
let trace_to_person: std::collections::BTreeMap<i64, i64> = trace_to_person.into_iter().map(|(tid, pid)| (tid, *pid_map.get(&pid).unwrap())).collect();
|
||||
|
||||
trace_to_person
|
||||
}
|
||||
|
||||
/// Merge small clusters into the most similar large cluster
|
||||
fn merge_small_clusters(
|
||||
trace_to_person: std::collections::BTreeMap<i64, i64>,
|
||||
trace_embeddings: &std::collections::BTreeMap<i64, Vec<f64>>,
|
||||
trace_similarities: &std::collections::BTreeMap<i64, f64>,
|
||||
min_large_cluster_size: usize,
|
||||
merge_similarity_threshold: f64,
|
||||
) -> std::collections::BTreeMap<i64, i64> {
|
||||
let mut trace_to_person = trace_to_person;
|
||||
|
||||
// Count traces per person
|
||||
let mut person_trace_count: std::collections::HashMap<i64, usize> = std::collections::HashMap::new();
|
||||
for (_, pid) in &trace_to_person {
|
||||
*person_trace_count.entry(*pid).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
// Identify large clusters (seeds) and small clusters
|
||||
let mut large_clusters: std::collections::HashSet<i64> = std::collections::HashSet::new();
|
||||
let mut small_clusters: std::collections::HashSet<i64> = std::collections::HashSet::new();
|
||||
|
||||
for (pid, count) in &person_trace_count {
|
||||
if *count >= min_large_cluster_size {
|
||||
large_clusters.insert(*pid);
|
||||
} else {
|
||||
small_clusters.insert(*pid);
|
||||
}
|
||||
}
|
||||
|
||||
if small_clusters.is_empty() || large_clusters.is_empty() {
|
||||
return trace_to_person;
|
||||
}
|
||||
|
||||
eprintln!("[MERGE] Large clusters: {:?}, Small clusters: {:?}", large_clusters, small_clusters);
|
||||
|
||||
// Compute mean embedding for each person
|
||||
let mut person_embeddings: std::collections::HashMap<i64, Vec<f64>> = std::collections::HashMap::new();
|
||||
for (tid, pid) in &trace_to_person {
|
||||
if let Some(emb) = trace_embeddings.get(tid) {
|
||||
person_embeddings.entry(*pid).or_insert_with(|| vec![0.0; emb.len()]);
|
||||
let pe = person_embeddings.get_mut(pid).unwrap();
|
||||
for (i, &v) in emb.iter().enumerate() {
|
||||
pe[i] += v;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Normalize
|
||||
for (pid, traces) in &person_trace_count {
|
||||
if let Some(pe) = person_embeddings.get_mut(pid) {
|
||||
let count = *traces as f64;
|
||||
for v in pe.iter_mut() {
|
||||
*v /= count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge each small cluster into most similar large cluster
|
||||
for small_pid in small_clusters {
|
||||
let mut best_sim = -1.0;
|
||||
let mut best_large_pid: Option<i64> = None;
|
||||
|
||||
for large_pid in &large_clusters {
|
||||
if let (Some(emb_small), Some(emb_large)) = (person_embeddings.get(&small_pid), person_embeddings.get(large_pid)) {
|
||||
let sim = cosine_similarity(emb_small, emb_large);
|
||||
if sim > best_sim {
|
||||
best_sim = sim;
|
||||
best_large_pid = Some(*large_pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(target_pid) = best_large_pid {
|
||||
if best_sim >= merge_similarity_threshold {
|
||||
eprintln!(" [MERGE] Person_{} ({} traces) -> Person_{} (sim={:.3})",
|
||||
small_pid, person_trace_count.get(&small_pid).unwrap_or(&0), target_pid, best_sim);
|
||||
|
||||
// Reassign all traces from small to large
|
||||
for (tid, pid) in trace_to_person.iter_mut() {
|
||||
if *pid == small_pid {
|
||||
*pid = target_pid;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eprintln!(" [SKIP] Person_{} not similar enough to any large cluster (best sim={:.3})", small_pid, best_sim);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Re-index person IDs
|
||||
let unique_pids: std::collections::BTreeSet<i64> = trace_to_person.values().copied().collect();
|
||||
let pid_map: std::collections::HashMap<i64, i64> = unique_pids.into_iter().enumerate().map(|(new, old)| (old, new as i64)).collect();
|
||||
trace_to_person = trace_to_person.into_iter().map(|(tid, pid)| (tid, *pid_map.get(&pid).unwrap())).collect();
|
||||
|
||||
trace_to_person
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
@@ -619,9 +751,11 @@ fn main() {
|
||||
let n_persons: usize = trace_to_person.values().collect::<std::collections::HashSet<_>>().len();
|
||||
eprintln!("Clustering result: {} persons ({} traces)", n_persons, trace_to_person.len());
|
||||
|
||||
// Load face_traced.json to get trace_id for each face.
|
||||
// Load face_traced.json to get trace_id for each face AND build co-occurrence constraints
|
||||
let traced_path = output_dir.join(format!("{}.face_traced.json", uuid));
|
||||
let mut traced_frames: Value = Value::Object(Default::default());
|
||||
let mut cooccurrence_constraints: std::collections::HashSet<(i64, i64)> = std::collections::HashSet::new();
|
||||
|
||||
if traced_path.exists() {
|
||||
if let Ok(s) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(v) = serde_json::from_str::<Value>(&s) {
|
||||
@@ -634,18 +768,78 @@ fn main() {
|
||||
if let Some(obj) = traced_frames.as_object_mut() {
|
||||
obj.insert(frame_num.to_string(), frame_obj.clone());
|
||||
}
|
||||
|
||||
// Build co-occurrence constraints: traces in same frame must be different persons
|
||||
if let Some(faces) = frame_obj.get("faces").and_then(|f| f.as_array()) {
|
||||
let mut frame_trace_ids: Vec<i64> = Vec::new();
|
||||
for face in faces {
|
||||
if let Some(tid) = face.get("trace_id").and_then(|t| t.as_i64()) {
|
||||
frame_trace_ids.push(tid);
|
||||
}
|
||||
}
|
||||
// Add all pairs
|
||||
for i in 0..frame_trace_ids.len() {
|
||||
for j in (i+1)..frame_trace_ids.len() {
|
||||
let a = frame_trace_ids[i];
|
||||
let b = frame_trace_ids[j];
|
||||
cooccurrence_constraints.insert((a.min(b), a.max(b)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(" Loaded face_traced.json: {} frames (converted from array)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0));
|
||||
} else if frames_raw.is_object() {
|
||||
traced_frames = frames_raw;
|
||||
eprintln!(" Loaded face_traced.json: {} frames (dict)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0));
|
||||
|
||||
// Build co-occurrence constraints from object format
|
||||
for (_frame_key, frame_obj) in traced_frames.as_object().unwrap() {
|
||||
if let Some(faces) = frame_obj.get("faces").and_then(|f| f.as_array()) {
|
||||
let mut frame_trace_ids: Vec<i64> = Vec::new();
|
||||
for face in faces {
|
||||
if let Some(tid) = face.get("trace_id").and_then(|t| t.as_i64()) {
|
||||
frame_trace_ids.push(tid);
|
||||
}
|
||||
}
|
||||
for i in 0..frame_trace_ids.len() {
|
||||
for j in (i+1)..frame_trace_ids.len() {
|
||||
let a = frame_trace_ids[i];
|
||||
let b = frame_trace_ids[j];
|
||||
cooccurrence_constraints.insert((a.min(b), a.max(b)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eprintln!(" Warning: Unexpected frames format: {:?}", frames_raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("[CONSTRAINT] Built {} co-occurrence constraints", cooccurrence_constraints.len());
|
||||
|
||||
// Apply co-occurrence constraints: split traces that are in same frame but same person
|
||||
let mut trace_to_person = apply_cooccurrence_constraints(
|
||||
trace_to_person,
|
||||
&trace_embeddings,
|
||||
&cooccurrence_constraints
|
||||
);
|
||||
|
||||
eprintln!("[CONSTRAINT] After constraints: {} persons", n_persons);
|
||||
|
||||
// Post-process: merge small clusters into most similar large cluster
|
||||
let trace_to_person = merge_small_clusters(
|
||||
trace_to_person,
|
||||
&trace_embeddings,
|
||||
&trace_similarities,
|
||||
5, // min traces to be considered a "large" cluster
|
||||
0.7 // similarity threshold for merging
|
||||
);
|
||||
|
||||
let n_persons: usize = trace_to_person.values().collect::<std::collections::HashSet<_>>().len();
|
||||
eprintln!("[MERGE] After merging small clusters: {} persons", n_persons);
|
||||
|
||||
let mut matched_count = 0_i64;
|
||||
let mut frames_list = frames_list;
|
||||
|
||||
@@ -236,8 +236,8 @@ fn bboxes_match(b1: &BBox, b2: &BBox, tolerance: i32) -> bool {
|
||||
(b1.height - b2.height).abs() <= tolerance
|
||||
}
|
||||
|
||||
/// Extract key_face.jpg for each trace using ffmpeg crop.
|
||||
/// Uses the highest-confidence frame's bbox from the trace.
|
||||
/// Extract complete trace artifacts: key_face.jpg, key_frame.jpg, trace_profile.json
|
||||
/// Uses face_data directly (faces with trace_id set by tracking) to avoid trace_id mismatch after merge.
|
||||
fn extract_face_jpegs(
|
||||
file_uuid: &str,
|
||||
output_dir: &std::path::Path,
|
||||
@@ -247,44 +247,138 @@ fn extract_face_jpegs(
|
||||
) -> Result<()> {
|
||||
let base_dir = output_dir.join(file_uuid);
|
||||
|
||||
for trace in traces {
|
||||
let trace_dir = base_dir.join(format!("trace_{}", trace.trace_id));
|
||||
std::fs::create_dir_all(&trace_dir).ok();
|
||||
// Build a map: trace_id → best face (highest confidence)
|
||||
use std::collections::HashMap;
|
||||
let mut best_faces: HashMap<i32, (usize, &FaceDetection)> = HashMap::new();
|
||||
|
||||
// Find the best face (highest confidence) for this trace
|
||||
let mut best_face: Option<(usize, &FaceDetection)> = None;
|
||||
|
||||
for frame in &face_data.frames {
|
||||
for face in &frame.faces {
|
||||
if let Some(tid) = face.trace_id {
|
||||
if tid == trace.trace_id as i32 {
|
||||
let frame_num = frame.frame as usize;
|
||||
if let Some((_, bf)) = &best_face {
|
||||
if face.confidence > bf.confidence {
|
||||
best_face = Some((frame_num, face));
|
||||
}
|
||||
} else {
|
||||
best_face = Some((frame_num, face));
|
||||
for frame in &face_data.frames {
|
||||
for face in &frame.faces {
|
||||
if let Some(tid) = face.trace_id {
|
||||
let frame_num = frame.frame as usize;
|
||||
let entry = best_faces.entry(tid);
|
||||
match entry {
|
||||
std::collections::hash_map::Entry::Occupied(mut occ) => {
|
||||
if face.confidence > occ.get().1.confidence {
|
||||
*occ.get_mut() = (frame_num, face);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract key_face.jpg from the best frame
|
||||
if let Some((frame_num, face)) = best_face {
|
||||
if face.bbox.width > 0 && face.bbox.height > 0 {
|
||||
let out_path = trace_dir.join("key_face.jpg");
|
||||
if let Err(e) = extract_face_crop(video_path, frame_num, face, &out_path) {
|
||||
println!("[TRACE_STORE] WARN key_face.jpg for trace {}: {}", trace.trace_id, e);
|
||||
std::collections::hash_map::Entry::Vacant(vac) => {
|
||||
vac.insert((frame_num, face));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For each trace, extract artifacts using the best face
|
||||
for trace in traces {
|
||||
let trace_dir = base_dir.join(format!("trace_{}", trace.trace_id));
|
||||
std::fs::create_dir_all(&trace_dir).ok();
|
||||
|
||||
// Find the best face for this trace from the map
|
||||
if let Some((frame_num, face)) = best_faces.get(&trace.trace_id) {
|
||||
let frame_num = *frame_num;
|
||||
|
||||
// Extract key_face.jpg from the best frame
|
||||
if face.bbox.width > 0 && face.bbox.height > 0 {
|
||||
let out_path = trace_dir.join("key_face.jpg");
|
||||
if !out_path.exists() {
|
||||
if let Err(e) = extract_face_crop(video_path, frame_num, face, &out_path) {
|
||||
println!("[TRACE_STORE] WARN key_face.jpg for trace {}: {}", trace.trace_id, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract key_frame.jpg (full frame at best_face frame)
|
||||
let key_frame_path = trace_dir.join("key_frame.jpg");
|
||||
if !key_frame_path.exists() {
|
||||
if let Err(e) = extract_full_frame(video_path, frame_num, &key_frame_path) {
|
||||
println!("[TRACE_STORE] WARN key_frame.jpg for trace {}: {}", trace.trace_id, e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Fallback: use trace's best_frame if available
|
||||
if trace.best_frame > 0 {
|
||||
let key_frame_path = trace_dir.join("key_frame.jpg");
|
||||
if !key_frame_path.exists() {
|
||||
if let Err(e) = extract_full_frame(video_path, trace.best_frame as usize, &key_frame_path) {
|
||||
println!("[TRACE_STORE] WARN key_frame.jpg for trace {}: {}", trace.trace_id, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write trace_profile.json
|
||||
let profile_path = trace_dir.join("trace_profile.json");
|
||||
if !profile_path.exists() {
|
||||
write_trace_profile(trace, file_uuid, &profile_path);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Use ffmpeg to extract a full frame (no crop).
|
||||
fn extract_full_frame(video_path: &str, frame_num: usize, output: &std::path::Path) -> Result<()> {
|
||||
let status = std::process::Command::new("ffmpeg")
|
||||
.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin")
|
||||
.args([
|
||||
"-y", "-v", "quiet",
|
||||
"-i", video_path,
|
||||
"-vf", &format!("select=eq(n\\,{})", frame_num),
|
||||
"-frames:v", "1",
|
||||
"-q:v", "3",
|
||||
"-f", "image2",
|
||||
output.to_str().unwrap(),
|
||||
])
|
||||
.status()
|
||||
.context("Failed to run ffmpeg for key_frame")?;
|
||||
|
||||
if !status.success() {
|
||||
anyhow::bail!("ffmpeg exit code: {:?}", status.code());
|
||||
}
|
||||
|
||||
if !output.exists() {
|
||||
anyhow::bail!("ffmpeg did not produce key_frame output");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write trace_profile.json with trace metadata.
|
||||
fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::Path) {
|
||||
use std::io::Write;
|
||||
|
||||
let best_confidence = trace.best_confidence;
|
||||
let avg_confidence = trace.avg_confidence;
|
||||
let best_frame = trace.best_frame;
|
||||
|
||||
let profile = serde_json::json!({
|
||||
"version": "1.0",
|
||||
"file_uuid": file_uuid,
|
||||
"trace_id": trace.trace_id,
|
||||
"label": null,
|
||||
"frame_count": trace.frame_count,
|
||||
"start_frame": trace.start_frame,
|
||||
"end_frame": trace.end_frame,
|
||||
"best_frame": best_frame,
|
||||
"avg_confidence": avg_confidence,
|
||||
"best_confidence": best_confidence,
|
||||
"avg_capture_quality": null,
|
||||
"best_capture_quality": null,
|
||||
"avg_bbox": null,
|
||||
"best_bbox": null,
|
||||
"key_frame": "key_frame.jpg",
|
||||
"key_face": "key_face.jpg",
|
||||
"status": "pending",
|
||||
"vlm_summary": null,
|
||||
});
|
||||
|
||||
if let Ok(mut f) = std::fs::File::create(output) {
|
||||
let _ = writeln!(f, "{}", serde_json::to_string_pretty(&profile).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
|
||||
/// Use ffmpeg to extract a single cropped face frame.
|
||||
fn extract_face_crop(video_path: &str, frame_num: usize, face: &FaceDetection, output: &std::path::Path) -> Result<()> {
|
||||
let x = face.bbox.x;
|
||||
@@ -383,6 +477,19 @@ fn main() -> Result<()> {
|
||||
|
||||
println!("[TRACE_STORE] Traces: {}", traces.len());
|
||||
|
||||
// Post-process: merge short traces with similar longer traces
|
||||
let min_merge_len = 5; // Merge traces with < 5 frames
|
||||
let merge_similarity = 0.75; // Cosine similarity threshold for merging
|
||||
println!("[TRACE_STORE] Merging short traces (<{} frames, sim>{})...", min_merge_len, merge_similarity);
|
||||
println!("[DEBUG] Before merge: {} traces", traces.len());
|
||||
for (tid, t) in &traces {
|
||||
if t.frame_count < 10 {
|
||||
println!("[DEBUG] Trace '{}': frame_count={}", tid, t.frame_count);
|
||||
}
|
||||
}
|
||||
let traces = merge_short_traces(traces, min_merge_len, merge_similarity);
|
||||
println!("[TRACE_STORE] After merge: {} traces", traces.len());
|
||||
|
||||
// Update trace_ids in Qdrant
|
||||
println!("[TRACE_STORE] Updating trace_ids in Qdrant...");
|
||||
let trace_mapping: HashMap<(i64, i32, i32, i32, i32), i32> = build_trace_mapping(&face_data);
|
||||
@@ -815,6 +922,91 @@ fn calculate_cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge short traces with temporally close longer traces
|
||||
fn merge_short_traces(
|
||||
traces: HashMap<String, TraceInfo>,
|
||||
min_len: usize,
|
||||
_similarity_threshold: f64,
|
||||
) -> HashMap<String, TraceInfo> {
|
||||
let mut traces = traces;
|
||||
|
||||
// Find short traces (use face_instances since frame_count is 0 at this point)
|
||||
let short_traces: Vec<String> = traces.iter()
|
||||
.filter(|(_, t)| t.face_instances.len() < min_len)
|
||||
.map(|(tid, _)| tid.clone())
|
||||
.collect();
|
||||
|
||||
if short_traces.is_empty() {
|
||||
return traces;
|
||||
}
|
||||
|
||||
// Merge each short trace to the temporally closest long trace
|
||||
for short_tid in short_traces {
|
||||
let short_trace = match traces.get(&short_tid) {
|
||||
Some(t) => t.clone(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
// Find the closest long trace by time overlap or proximity
|
||||
let mut best_score = -1.0;
|
||||
let mut best_tid: Option<String> = None;
|
||||
|
||||
for (tid, trace) in &traces {
|
||||
if *tid == short_tid { continue; }
|
||||
if trace.frame_count < min_len as u64 { continue; }
|
||||
|
||||
// Calculate temporal overlap/proximity score
|
||||
let overlap_start = short_trace.start_frame.max(trace.start_frame);
|
||||
let overlap_end = short_trace.end_frame.min(trace.end_frame);
|
||||
let overlap = if overlap_end > overlap_start {
|
||||
(overlap_end - overlap_start) as f64
|
||||
} else {
|
||||
// Calculate gap
|
||||
let gap = if short_trace.end_frame < trace.start_frame {
|
||||
trace.start_frame - short_trace.end_frame
|
||||
} else if trace.end_frame < short_trace.start_frame {
|
||||
short_trace.start_frame - trace.end_frame
|
||||
} else {
|
||||
0
|
||||
} as f64;
|
||||
-gap.max(1.0) // Negative score for gap
|
||||
};
|
||||
|
||||
// Normalize by short trace length
|
||||
let score = overlap / short_trace.frame_count.max(1) as f64;
|
||||
if score > best_score {
|
||||
best_score = score;
|
||||
best_tid = Some(tid.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// Merge if there's overlap or small gap (< 10 frames)
|
||||
if let Some(target_tid) = best_tid {
|
||||
if best_score > -10.0 {
|
||||
println!(" Merging trace {} ({} faces) into trace {} (score={:.1})",
|
||||
short_tid, short_trace.frame_count as usize, target_tid, best_score);
|
||||
|
||||
// Move face instances from short to target
|
||||
if let Some(mut short_trace) = traces.remove(&short_tid) {
|
||||
if let Some(target_trace) = traces.get_mut(&target_tid) {
|
||||
for point in short_trace.face_instances.drain(..) {
|
||||
target_trace.face_instances.push(point);
|
||||
}
|
||||
// Update stats
|
||||
target_trace.frame_count += short_trace.frame_count;
|
||||
target_trace.start_frame = target_trace.start_frame.min(short_trace.start_frame);
|
||||
target_trace.end_frame = target_trace.end_frame.max(short_trace.end_frame);
|
||||
target_trace.start_time = target_trace.start_time.min(short_trace.start_time);
|
||||
target_trace.end_time = target_trace.end_time.max(short_trace.end_time);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traces
|
||||
}
|
||||
|
||||
fn load_qdrant_faces(uuid: &str) -> Vec<FacePoint> {
|
||||
let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL);
|
||||
let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY);
|
||||
|
||||
Reference in New Issue
Block a user