feat: declarative pipeline config, non-blocking Scene VLM, rust_asrx

Consolidated snapshot (previously WIP in working tree).

- core/pipeline_config: new module loading config/pipeline_flows.json as the
  source of truth for stage execution mode (parallel/blocking) and dependencies
- worker/job_worker: dispatch Scene VLM to a background task when the stage is
  declared parallel, unblocking the worker poll loop; resolve processor
  dependencies from pipeline_flows.json (fallback to built-in)
- config/pipeline_flows.json: asrx depends on [cut, asr]
- scripts/fix_stuck_jobs: fix UTC timezone comparison, raise default threshold
  to 6h, skip jobs with recent processor activity
- rust_asrx: Rust speaker diarization CLI + processor wiring
- processor metadata helper; fast_face_clustering script; file_progress pipeline
  API; scan API; VAD updates
This commit is contained in:
Accusys
2026-10-15 13:01:12 +08:00
parent 667e279768
commit 882e31ab96
76 changed files with 10117 additions and 300 deletions
+40
View File
@@ -1540,6 +1540,15 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "primal-check"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"
dependencies = [
"num-integer",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -1866,12 +1875,27 @@ dependencies = [
"ort",
"regex",
"reqwest",
"rustfft",
"serde",
"serde_json",
"tokio",
"uuid",
]
[[package]]
name = "rustfft"
version = "6.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"
dependencies = [
"num-complex",
"num-integer",
"num-traits",
"primal-check",
"strength_reduce",
"transpose",
]
[[package]]
name = "rustix"
version = "1.1.5"
@@ -2099,6 +2123,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "strength_reduce"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
[[package]]
name = "strsim"
version = "0.11.1"
@@ -2357,6 +2387,16 @@ dependencies = [
"once_cell",
]
[[package]]
name = "transpose"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
dependencies = [
"num-integer",
"strength_reduce",
]
[[package]]
name = "try-lock"
version = "0.2.5"
+5
View File
@@ -43,10 +43,15 @@ path = "src/bin/rust_facenet_coreml.rs"
name = "rust_face_processor"
path = "src/bin/rust_face_processor.rs"
[[bin]]
name = "rust_asrx"
path = "src/bin/rust_asrx.rs"
[dependencies]
ort = { version = "2.0.0-rc.13", features = ["download-binaries"] }
hound = "3.5"
ndarray = "0.17"
rustfft = "6.4"
anyhow = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
+138
View File
@@ -0,0 +1,138 @@
//! Speaker clustering: faithful port of `speaker_cluster_fixed.py`
//! (agglomerative average-linkage with cosine distance).
/// Cosine distance matrix `[n][n]` for L2-normalized embeddings.
/// `dist[i][j] = 1 - dot(e_i, e_j)`.
pub fn cosine_distances(embeddings: &[Vec<f32>]) -> Vec<Vec<f32>> {
let n = embeddings.len();
let mut d = vec![vec![0f32; n]; n];
for i in 0..n {
for j in (i + 1)..n {
let dot: f32 = embeddings[i]
.iter()
.zip(embeddings[j].iter())
.map(|(a, b)| a * b)
.sum();
let v = 1.0 - dot;
d[i][j] = v;
d[j][i] = v;
}
}
d
}
/// Port of `estimate_n_speakers_from_embeddings`; result clamped to `[2, max]`.
pub fn estimate_n_speakers(distances: &[Vec<f32>], max_speakers: usize) -> usize {
let n = distances.len();
if n < 2 {
return 2;
}
let sample = n.min(200);
let mut min_distances = Vec::with_capacity(sample);
for i in 0..sample {
let mut row = distances[i].clone();
row.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
if row.len() > 1 {
min_distances.push(row[1]);
}
}
if min_distances.is_empty() {
return 2;
}
let avg = min_distances.iter().sum::<f32>() / min_distances.len() as f32;
let threshold = avg * 1.5;
let m = min_distances.len();
let mut assigned = vec![false; m];
let mut n_speakers = 1usize;
for i in 0..m {
if assigned[i] {
continue;
}
n_speakers += 1;
for j in (i + 1)..m {
if assigned[j] {
continue;
}
let idx_i = if n > 200 { i * (n / 200) } else { i };
let idx_j = if n > 200 { j * (n / 200) } else { j };
if idx_i < n && idx_j < n && distances[idx_i][idx_j] < threshold {
assigned[j] = true;
}
}
}
n_speakers.clamp(2, max_speakers.max(2))
}
/// Agglomerative clustering (average linkage) using a precomputed distance
/// matrix, stopping at `k` clusters. Returns a label per point.
pub fn agglomerative(distances: &[Vec<f32>], k: usize) -> Vec<usize> {
let n = distances.len();
if n == 0 {
return Vec::new();
}
if k >= n {
return (0..n).collect();
}
let mut d = distances.to_vec();
let mut root: Vec<usize> = (0..n).collect(); // union-find representative
let mut active = vec![true; n];
let mut size = vec![1usize; n];
let mut remaining = n;
while remaining > k {
let mut best_i = 0;
let mut best_j = 1;
let mut best = f32::INFINITY;
for i in 0..n {
if !active[i] {
continue;
}
for j in (i + 1)..n {
if active[j] && d[i][j] < best {
best = d[i][j];
best_i = i;
best_j = j;
}
}
}
// Merge best_j into best_i (UPGMA average linkage update).
let (i, j) = (best_i, best_j);
let si = size[i] as f32;
let sj = size[j] as f32;
for x in 0..n {
if x == i || x == j || !active[x] {
continue;
}
let v = (si * d[i][x] + sj * d[j][x]) / (si + sj);
d[i][x] = v;
d[x][i] = v;
}
size[i] += size[j];
active[j] = false;
root[j] = i;
remaining -= 1;
}
let find = |root: &Vec<usize>, mut x: usize| -> usize {
while root[x] != x {
x = root[x];
}
x
};
let mut label_of: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
let mut labels = vec![0usize; n];
let mut next = 0usize;
for p in 0..n {
let r = find(&root, p);
let label = *label_of.entry(r).or_insert_with(|| {
let l = next;
next += 1;
l
});
labels[p] = label;
}
labels
}
+192
View File
@@ -0,0 +1,192 @@
//! Rust-native speaker diarization (ASRX) building blocks.
//!
//! - `Frontend`: speechbrain-compatible fbank frontend (framing, STFT via
//! rustfft, mel filterbank, log-dB, sentence mean-normalization).
//! - `Ecapa`: ECAPA-TDNN speaker-embedding network (ONNX, `feats -> embedding`).
pub mod cluster;
use anyhow::{Context, Result};
use ndarray::IxDyn;
use ort::session::{builder::GraphOptimizationLevel, Session};
use ort::value::Value;
use rustfft::num_complex::Complex;
use rustfft::FftPlanner;
pub const SAMPLE_RATE: usize = 16000;
pub const N_FFT: usize = 400;
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;
const PAD: usize = N_FFT / 2;
const AMIN: f32 = 1e-10;
const TOP_DB: f32 = 80.0;
const MULTIPLIER: f32 = 10.0;
/// speechbrain-compatible log-mel frontend.
pub struct Frontend {
window: Vec<f32>,
mel: Vec<f32>, // [N_BINS * N_MELS], row-major (freq-major)
planner: FftPlanner<f32>,
}
impl Frontend {
/// Load the hamming window (400 f32) and the mel matrix (201x80 f32).
pub fn new(window_path: &str, mel_path: &str) -> Result<Self> {
let window = read_f32_file(window_path)?;
if window.len() != WIN_LENGTH {
anyhow::bail!(
"window file has {} values, expected {}",
window.len(),
WIN_LENGTH
);
}
let mel = read_f32_file(mel_path)?;
if mel.len() != N_BINS * N_MELS {
anyhow::bail!(
"mel file has {} values, expected {}",
mel.len(),
N_BINS * N_MELS
);
}
Ok(Self {
window,
mel,
planner: FftPlanner::new(),
})
}
/// Compute log-mel features [n_frames, N_MELS] (flattened) for a waveform.
///
/// Mirrors speechbrain `Fbank` with `mean_var_norm(norm_type="sentence",
/// std_norm=False)`: center-padded framing, power spectrum, mel matmul,
/// amplitude-to-dB with top_db clipping, then per-utterance mean removal.
pub fn compute_feats(&mut self, samples: &[f32]) -> (Vec<f32>, usize) {
let n = samples.len();
if n == 0 {
return (Vec::new(), 0);
}
let n_frames = 1 + n / HOP_LENGTH;
let mut fbank = vec![0f32; n_frames * N_MELS];
let fft = self.planner.plan_fft_forward(N_FFT);
let mut buffer = vec![Complex::new(0f32, 0f32); N_FFT];
for t in 0..n_frames {
let base = t * HOP_LENGTH;
for k in 0..N_FFT {
let idx = base + k;
let s = if idx >= PAD {
let si = idx - PAD;
if si < n {
samples[si]
} else {
0.0
}
} else {
0.0
};
buffer[k] = Complex::new(s * self.window[k], 0.0);
}
fft.process(&mut buffer);
let row = &mut fbank[t * N_MELS..(t + 1) * N_MELS];
for m in 0..N_MELS {
let mut acc = 0.0f32;
for b in 0..N_BINS {
let p = buffer[b].re * buffer[b].re + buffer[b].im * buffer[b].im;
acc += self.mel[b * N_MELS + m] * p;
}
row[m] = acc;
}
}
// amplitude_to_DB: 10*log10(clamp(x, amin)) with db_multiplier = 0.
let mut db_max = f32::NEG_INFINITY;
for v in fbank.iter_mut() {
*v = MULTIPLIER * v.max(AMIN).log10();
if *v > db_max {
db_max = *v;
}
}
let floor = db_max - TOP_DB;
for v in fbank.iter_mut() {
if *v < floor {
*v = floor;
}
}
// sentence mean normalization (std_norm=False -> subtract mean only)
let mut mean = vec![0f32; N_MELS];
for t in 0..n_frames {
for m in 0..N_MELS {
mean[m] += fbank[t * N_MELS + m];
}
}
let inv = 1.0 / n_frames as f32;
for m in 0..N_MELS {
mean[m] *= inv;
}
for t in 0..n_frames {
for m in 0..N_MELS {
fbank[t * N_MELS + m] -= mean[m];
}
}
(fbank, n_frames)
}
}
/// ECAPA-TDNN speaker embedding network (ONNX).
pub struct Ecapa {
session: Session,
}
impl Ecapa {
pub fn new(model_path: &str) -> Result<Self> {
let session = Session::builder()?
.with_optimization_level(GraphOptimizationLevel::Level1)
.map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))?
.commit_from_file(model_path)
.map_err(|e| anyhow::anyhow!("Failed to load ECAPA model: {}", e))?;
Ok(Self { session })
}
/// Run the embedding network on features [n_frames, N_MELS]; returns 192-d.
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())
.context("Failed to create ECAPA input array")?;
let input_value = Value::from_array(input).context("Failed to create input value")?;
let inputs = ort::inputs!["feats" => input_value];
let outputs = self.session.run(inputs).context("Failed to run ECAPA")?;
let out = outputs["embedding"]
.try_extract_tensor::<f32>()
.context("Failed to extract embedding")?;
Ok(out.1.to_vec())
}
}
fn read_f32_file(path: &str) -> Result<Vec<f32>> {
let bytes = std::fs::read(path).with_context(|| format!("Failed to read {}", path))?;
if bytes.len() % 4 != 0 {
anyhow::bail!("{} length not a multiple of 4", path);
}
let mut out = Vec::with_capacity(bytes.len() / 4);
for chunk in bytes.chunks_exact(4) {
out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
}
Ok(out)
}
/// L2-normalize a vector in place.
pub fn l2_normalize(v: &mut [f32]) {
let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
if norm > 0.0 {
for x in v.iter_mut() {
*x /= norm;
}
}
}
+488
View File
@@ -0,0 +1,488 @@
use anyhow::{Context, Result};
use clap::Parser;
use serde_json::json;
use std::path::Path;
use std::process::Command;
use std::time::Instant;
use rust_processors::asrx::cluster;
use rust_processors::asrx::{l2_normalize, Ecapa, Frontend, SAMPLE_RATE};
use rust_processors::vad::segment::SegmentCollector;
use rust_processors::vad::{AudioReader, SileroVad};
#[derive(Parser)]
#[command(name = "rust_asrx")]
#[command(about = "Rust-native speaker diarization (ASRX)")]
struct Cli {
/// Input video file
video_path: String,
/// Output JSON path ({file_uuid}.asrx.json)
output_path: String,
/// File UUID (for Redis publishing compatibility)
#[arg(long)]
uuid: Option<String>,
/// File UUID (for Qdrant storage compatibility)
#[arg(long = "file-uuid")]
file_uuid: Option<String>,
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
vad_model: String,
#[arg(long, default_value = "/Users/accusys/models/ecapa_tdnn.onnx")]
ecapa_model: String,
#[arg(long, default_value = "/Users/accusys/models/ecapa_window_400.f32")]
window_file: String,
#[arg(long, default_value = "/Users/accusys/models/ecapa_mel_201x80.f32")]
mel_file: String,
#[arg(long, default_value = "10")]
max_speakers: usize,
#[arg(long, default_value = "0.5")]
vad_threshold: f32,
#[arg(long, default_value = "500")]
min_speech: u32,
#[arg(long, default_value = "300")]
min_silence: u32,
}
const CHUNK_SIZE: usize = 512;
struct AsrSegment {
start: f32,
end: f32,
text: String,
}
fn main() -> Result<()> {
let cli = Cli::parse();
let start_all = Instant::now();
let output_dir = Path::new(&cli.output_path)
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| Path::new(".").to_path_buf());
let uuid_part = Path::new(&cli.output_path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("")
.split('.')
.next()
.unwrap_or("")
.to_string();
let asr_path = cli.output_path.replace(".asrx.json", ".asr.json");
let write_result = |status: &str,
language: Option<&str>,
segments: Vec<serde_json::Value>,
n_speakers: usize,
speaker_stats: serde_json::Value|
-> Result<()> {
let out = json!({
"status": status,
"language": language,
"segments": segments,
"segment_count": segments.len(),
"n_speakers": n_speakers,
"speaker_stats": speaker_stats,
});
if let Some(parent) = Path::new(&cli.output_path).parent() {
let _ = std::fs::create_dir_all(parent);
}
std::fs::write(&cli.output_path, serde_json::to_string_pretty(&out)?)
.context("Failed to write ASRX output")?;
Ok(())
};
// 1. Probe audio tracks; skip if none.
println!("[rust_asrx] Probing audio tracks: {}", cli.video_path);
let tracks = probe_audio_tracks(&cli.video_path);
if tracks.is_empty() {
println!("[rust_asrx] No audio stream detected");
return write_result("no_audio_track", None, vec![], 0, json!({}));
}
// 2. If ASR already reported silence/no-audio, mirror it.
if Path::new(&asr_path).exists() {
if let Ok(text) = std::fs::read_to_string(&asr_path) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
let asr_status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
let asr_lang = v.get("language").and_then(|s| s.as_str());
if asr_status == "no_audio_track" || asr_status == "silent_audio" {
println!("[rust_asrx] ASR status={}, skipping", asr_status);
return write_result(asr_status, asr_lang, vec![], 0, json!({}));
}
}
}
}
// 3. Load ASR segments for time alignment (text source).
let (asr_segments, language) = load_asr_segments(&asr_path);
// 4. Extract audio to 16kHz mono WAV.
let tmp_wav = format!("/tmp/rust_asrx_{}.wav", uuid_part);
let track_index = select_best_track(&tracks);
if let Err(e) = extract_audio(&cli.video_path, track_index, &tmp_wav) {
println!("[rust_asrx] Audio extraction failed: {}", e);
return write_result("silent_audio", language.as_deref(), vec![], 0, json!({}));
}
let audio = AudioReader::from_wav(&tmp_wav).context("Failed to read extracted WAV")?;
let samples = audio.samples();
let duration = audio.duration();
let _ = std::fs::remove_file(&tmp_wav);
// 5. VAD refinement per ASR segment (or whole file if no ASR).
let mut vad = SileroVad::new(&cli.vad_model).context("Failed to load Silero VAD")?;
let mut refined: Vec<(f32, f32, String)> = Vec::new();
if asr_segments.is_empty() {
let subs = scan_within_segment(
&mut vad,
samples,
0.0,
duration,
cli.vad_threshold,
cli.min_speech,
cli.min_silence,
);
for (s, e) in subs {
refined.push((s, e, String::new()));
}
} else {
for seg in &asr_segments {
let subs = scan_within_segment(
&mut vad,
samples,
seg.start,
seg.end,
cli.vad_threshold,
cli.min_speech,
cli.min_silence,
);
if subs.is_empty() {
refined.push((seg.start, seg.end, seg.text.clone()));
} else {
for (s, e) in subs {
refined.push((s, e, seg.text.clone()));
}
}
}
}
if refined.is_empty() {
println!("[rust_asrx] No speech segments");
return write_result("silent_audio", language.as_deref(), vec![], 0, json!({}));
}
println!("[rust_asrx] Refined segments: {}", refined.len());
// 6. Speaker embeddings (ECAPA) per refined segment.
let mut frontend = Frontend::new(&cli.window_file, &cli.mel_file)
.context("Failed to load ASRX frontend constants")?;
let mut ecapa = Ecapa::new(&cli.ecapa_model).context("Failed to load ECAPA model")?;
let mut embeddings: Vec<Vec<f32>> = Vec::with_capacity(refined.len());
for (s, e, _) in &refined {
let a = (*s * SAMPLE_RATE as f32) as usize;
let b = ((*e * SAMPLE_RATE as f32) as usize).min(samples.len());
let seg_audio = if b > a {
&samples[a..b]
} else {
&samples[0..0]
};
let (feats, n_frames) = frontend.compute_feats(seg_audio);
let mut emb = if n_frames > 0 {
ecapa.embed(&feats, n_frames)?
} else {
vec![0f32; 192]
};
l2_normalize(&mut emb);
embeddings.push(emb);
}
// 7. Clustering.
let distances = cluster::cosine_distances(&embeddings);
let n_est = cluster::estimate_n_speakers(&distances, cli.max_speakers);
let k = n_est.min(refined.len()).max(1);
let labels = cluster::agglomerative(&distances, k);
let n_speakers = labels.iter().copied().max().map(|m| m + 1).unwrap_or(0);
println!("[rust_asrx] Estimated speakers: {}", n_speakers);
// 8. Quality (cosine similarity to cluster centroid).
let qualities = cluster_qualities(&embeddings, &labels);
// 9. Build segments.
let fps = read_fps(&output_dir, &uuid_part);
let mut segments: Vec<serde_json::Value> = Vec::with_capacity(refined.len());
let mut speaker_stats: std::collections::BTreeMap<String, (usize, f64)> =
std::collections::BTreeMap::new();
for (i, (s, e, text)) in refined.iter().enumerate() {
let speaker = format!("SPEAKER_{}", labels[i]);
let start_frame = (s * fps) as u64;
let end_frame = (e * fps) as u64;
segments.push(json!({
"start_time": round3(*s),
"end_time": round3(*e),
"start_frame": start_frame,
"end_frame": end_frame,
"text": text,
"speaker_id": speaker,
"language": language,
"lang_prob": 0.0,
"quality": (qualities[i] * 1000.0).round() / 1000.0,
}));
let entry = speaker_stats.entry(speaker).or_insert((0, 0.0));
entry.0 += 1;
entry.1 += (*e - *s) as f64;
}
let stats_json: serde_json::Value = speaker_stats
.into_iter()
.map(|(k, (count, dur))| (k, json!({"count": count, "duration": round3(dur as f32)})))
.collect();
write_result(
"has_transcript",
language.as_deref(),
segments,
n_speakers,
stats_json,
)?;
println!(
"[rust_asrx] Done: {} segments, {} speakers in {:.2}s",
refined.len(),
n_speakers,
start_all.elapsed().as_secs_f32()
);
Ok(())
}
fn round3(v: f32) -> f64 {
((v as f64) * 1000.0).round() / 1000.0
}
/// VAD-scan a time window and return refined sub-segments on the global timeline.
fn scan_within_segment(
vad: &mut SileroVad,
samples: &[f32],
start_sec: f32,
end_sec: f32,
threshold: f32,
min_speech_ms: u32,
min_silence_ms: u32,
) -> Vec<(f32, f32)> {
let a = (start_sec * SAMPLE_RATE as f32) as usize;
let b = ((end_sec * SAMPLE_RATE as f32) as usize).min(samples.len());
if b <= a {
return Vec::new();
}
let sub = &samples[a..b];
let offset = a as f32 / SAMPLE_RATE as f32;
vad.reset_state();
let mut collector = SegmentCollector::new(threshold, min_speech_ms, min_silence_ms);
let mut i = 0;
while i < sub.len() {
let end = (i + CHUNK_SIZE).min(sub.len());
let mut chunk = sub[i..end].to_vec();
if chunk.len() < CHUNK_SIZE {
chunk.resize(CHUNK_SIZE, 0.0);
}
let prob = match vad.detect(&chunk) {
Ok(p) => p,
Err(_) => 0.0,
};
collector.process(i as f32 / SAMPLE_RATE as f32, prob);
i += CHUNK_SIZE;
}
collector.finalize(sub.len() as f32 / SAMPLE_RATE as f32);
collector
.segments()
.iter()
.map(|s| (s.start_sec + offset, s.end_sec + offset))
.collect()
}
fn cluster_qualities(embeddings: &[Vec<f32>], labels: &[usize]) -> Vec<f32> {
let n = embeddings.len();
let dim = if n > 0 { embeddings[0].len() } else { 0 };
let k = labels.iter().copied().max().map(|m| m + 1).unwrap_or(0);
let mut centroids = vec![vec![0f32; dim]; k];
let mut counts = vec![0usize; k];
for (i, emb) in embeddings.iter().enumerate() {
let l = labels[i];
for d in 0..dim {
centroids[l][d] += emb[d];
}
counts[l] += 1;
}
for l in 0..k {
if counts[l] > 0 {
for d in 0..dim {
centroids[l][d] /= counts[l] as f32;
}
l2_normalize(&mut centroids[l]);
}
}
(0..n)
.map(|i| {
let l = labels[i];
embeddings[i]
.iter()
.zip(centroids[l].iter())
.map(|(a, b)| a * b)
.sum::<f32>()
})
.collect()
}
fn load_asr_segments(asr_path: &str) -> (Vec<AsrSegment>, Option<String>) {
let mut segments = Vec::new();
let mut language = None;
if let Ok(text) = std::fs::read_to_string(asr_path) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
language = v
.get("language")
.and_then(|s| s.as_str())
.map(|s| s.to_string());
if let Some(arr) = v.get("segments").and_then(|s| s.as_array()) {
for seg in arr {
let start = seg
.get("start_time")
.or_else(|| seg.get("start"))
.and_then(|n| n.as_f64())
.unwrap_or(0.0) as f32;
let end = seg
.get("end_time")
.or_else(|| seg.get("end"))
.and_then(|n| n.as_f64())
.unwrap_or(0.0) as f32;
let text = seg
.get("text")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string();
segments.push(AsrSegment { start, end, text });
}
}
}
}
(segments, language)
}
struct AudioTrack {
index: i64,
language: String,
channels: i64,
}
fn probe_audio_tracks(video_path: &str) -> Vec<AudioTrack> {
let out = Command::new("ffprobe")
.args([
"-v",
"quiet",
"-print_format",
"json",
"-show_streams",
"-select_streams",
"a",
video_path,
])
.output();
let out = match out {
Ok(o) if o.status.success() => o,
_ => return Vec::new(),
};
let v: serde_json::Value = match serde_json::from_slice(&out.stdout) {
Ok(v) => v,
Err(_) => return Vec::new(),
};
let mut tracks = Vec::new();
if let Some(streams) = v.get("streams").and_then(|s| s.as_array()) {
for s in streams {
tracks.push(AudioTrack {
index: s.get("index").and_then(|x| x.as_i64()).unwrap_or(0),
language: s
.get("tags")
.and_then(|t| t.get("language"))
.and_then(|l| l.as_str())
.unwrap_or("und")
.to_string(),
channels: s.get("channels").and_then(|c| c.as_i64()).unwrap_or(0),
});
}
}
tracks
}
/// Prefer English, else the track with the most channels.
fn select_best_track(tracks: &[AudioTrack]) -> i64 {
for t in tracks {
if t.language == "eng" || t.language == "en" {
return t.index;
}
}
let mut best = &tracks[0];
for t in tracks {
if t.channels > best.channels {
best = t;
}
}
best.index
}
fn extract_audio(video_path: &str, track_index: i64, output_wav: &str) -> Result<()> {
let status = Command::new("ffmpeg")
.args([
"-y",
"-v",
"quiet",
"-i",
video_path,
"-map",
&format!("0:{}", track_index),
"-ar",
"16000",
"-ac",
"1",
"-sample_fmt",
"s16",
output_wav,
])
.status()
.context("Failed to run ffmpeg")?;
if !status.success() {
anyhow::bail!("ffmpeg exited with {}", status);
}
Ok(())
}
fn read_fps(output_dir: &Path, uuid_part: &str) -> f32 {
let probe_path = output_dir.join(format!("{}.probe.json", uuid_part));
if let Ok(text) = std::fs::read_to_string(&probe_path) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
if let Some(streams) = v.get("streams").and_then(|s| s.as_array()) {
for s in streams {
if s.get("codec_type").and_then(|c| c.as_str()) == Some("video") {
if let Some(rate) = s.get("r_frame_rate").and_then(|r| r.as_str()) {
if let Some((num, den)) = rate.split_once('/') {
let n: f32 = num.parse().unwrap_or(30.0);
let d: f32 = den.parse().unwrap_or(1.0);
if d > 0.0 {
return n / d;
}
} else if let Ok(f) = rate.parse::<f32>() {
return f;
}
}
}
}
}
}
}
30.0
}
+1
View File
@@ -1 +1,2 @@
pub mod asrx;
pub mod vad;
+10 -13
View File
@@ -8,34 +8,31 @@ pub struct AudioReader {
impl AudioReader {
pub fn from_wav(path: &str) -> Result<Self> {
let reader = WavReader::open(path)
.context("Failed to open WAV file")?;
let reader = WavReader::open(path).context("Failed to open WAV file")?;
let spec = reader.spec();
let sample_rate = spec.sample_rate;
// 轉換為 f32,範圍 [-1.0, 1.0]
let samples: Vec<f32> = reader.into_samples::<i16>()
.map(|s| {
s.map(|v| v as f32 / 32768.0)
.unwrap_or(0.0)
})
let samples: Vec<f32> = reader
.into_samples::<i16>()
.map(|s| s.map(|v| v as f32 / 32768.0).unwrap_or(0.0))
.collect();
Ok(Self {
samples,
sample_rate,
})
}
pub fn samples(&self) -> &[f32] {
&self.samples
}
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
pub fn duration(&self) -> f32 {
self.samples.len() as f32 / self.sample_rate as f32
}
+2 -2
View File
@@ -1,7 +1,7 @@
pub mod onnx;
pub mod audio;
pub mod onnx;
pub mod segment;
pub use onnx::SileroVad;
pub use audio::AudioReader;
pub use onnx::SileroVad;
pub use segment::SpeechSegment;
+42 -41
View File
@@ -1,14 +1,14 @@
use anyhow::{Context, Result};
use ort::session::{Session, builder::GraphOptimizationLevel};
use ort::value::Value;
use ndarray::IxDyn;
use ort::session::{builder::GraphOptimizationLevel, Session};
use ort::value::Value;
pub struct SileroVad {
session: Session,
state: Vec<f32>, // [2, 1, 128] = 256 elements
context: Vec<f32>, // [1, 64] for 16kHz
state: Vec<f32>, // [2, 1, 128] = 256 elements
context: Vec<f32>, // [1, 64] for 16kHz
sample_rate: i64,
context_size: usize, // 64 for 16kHz, 32 for 8kHz
context_size: usize, // 64 for 16kHz, 32 for 8kHz
}
impl SileroVad {
@@ -18,81 +18,82 @@ impl SileroVad {
.map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))?
.commit_from_file(model_path)
.map_err(|e| anyhow::anyhow!("Failed to load model: {}", e))?;
let sample_rate = 16000;
let context_size = if sample_rate == 16000 { 64 } else { 32 };
Ok(Self {
session,
state: vec![0.0; 256], // [2, 1, 128] = 256
context: vec![0.0; context_size], // [1, 64]
state: vec![0.0; 256], // [2, 1, 128] = 256
context: vec![0.0; context_size], // [1, 64]
sample_rate,
context_size,
})
}
pub fn detect(&mut self, audio_chunk: &[f32]) -> Result<f32> {
// 拼接 context 和當前塊
let mut input_with_context = Vec::with_capacity(self.context_size + audio_chunk.len());
input_with_context.extend_from_slice(&self.context);
input_with_context.extend_from_slice(audio_chunk);
// 準備輸入
let input_array = ndarray::Array::from_shape_vec(
IxDyn(&[1, input_with_context.len()]),
input_with_context.clone()
).context("Failed to create input array")?;
let state_array = ndarray::Array::from_shape_vec(
IxDyn(&[2, 1, 128]),
self.state.clone()
).context("Failed to create state array")?;
input_with_context.clone(),
)
.context("Failed to create input array")?;
let state_array = ndarray::Array::from_shape_vec(IxDyn(&[2, 1, 128]), self.state.clone())
.context("Failed to create state array")?;
let sr_array = ndarray::Array::from_shape_vec(
IxDyn(&[]), // 標量
vec![self.sample_rate]
).context("Failed to create sr array")?;
IxDyn(&[]), // 標量
vec![self.sample_rate],
)
.context("Failed to create sr array")?;
// 創建 ONNX Value
let input_value = Value::from_array(input_array)
.context("Failed to create input value")?;
let state_value = Value::from_array(state_array)
.context("Failed to create state value")?;
let sr_value = Value::from_array(sr_array)
.context("Failed to create sr value")?;
let input_value = Value::from_array(input_array).context("Failed to create input value")?;
let state_value = Value::from_array(state_array).context("Failed to create state value")?;
let sr_value = Value::from_array(sr_array).context("Failed to create sr value")?;
// 運行推理
let inputs = ort::inputs![
"input" => input_value,
"state" => state_value,
"sr" => sr_value,
];
let outputs = self.session.run(inputs)
let outputs = self
.session
.run(inputs)
.context("Failed to run inference")?;
// 提取輸出
let output = outputs["output"].try_extract_tensor::<f32>()
let output = outputs["output"]
.try_extract_tensor::<f32>()
.context("Failed to extract output")?;
// output 是 (&Shape, &[f32]) tuple
let output_data = output.1;
let speech_prob = output_data[0];
// 更新隱藏狀態
let state_n = outputs["stateN"].try_extract_tensor::<f32>()
let state_n = outputs["stateN"]
.try_extract_tensor::<f32>()
.context("Failed to extract stateN")?;
// state_n 是 (&Shape, &[f32]) tuple
let state_data = state_n.1;
self.state = state_data.to_vec();
// 更新 context(當前輸入的最後 context_size 個樣本)
self.context = input_with_context[input_with_context.len() - self.context_size..].to_vec();
Ok(speech_prob)
}
pub fn reset_state(&mut self) {
self.state = vec![0.0; 256];
self.context = vec![0.0; self.context_size];
+5 -5
View File
@@ -10,7 +10,7 @@ impl SpeechSegment {
pub fn new(start_sec: f32, end_sec: f32) -> Self {
Self { start_sec, end_sec }
}
pub fn duration(&self) -> f32 {
self.end_sec - self.start_sec
}
@@ -36,7 +36,7 @@ impl SegmentCollector {
silence_start: None,
}
}
pub fn process(&mut self, timestamp: f32, speech_prob: f32) {
if speech_prob >= self.threshold {
// 語音
@@ -50,7 +50,7 @@ impl SegmentCollector {
if self.silence_start.is_none() {
self.silence_start = Some(timestamp);
}
// 檢查是否結束語音段
if let Some(silence_start) = self.silence_start {
let silence_duration = timestamp - silence_start;
@@ -69,7 +69,7 @@ impl SegmentCollector {
}
}
}
pub fn finalize(&mut self, end_timestamp: f32) {
// 處理最後一個段
if let Some(start) = self.current_start {
@@ -79,7 +79,7 @@ impl SegmentCollector {
}
}
}
pub fn segments(&self) -> &[SpeechSegment] {
&self.segments
}
+1
View File
@@ -0,0 +1 @@
/Users/accusys/momentry_core/scripts/asr_processor_simplified.py
+1
View File
@@ -0,0 +1 @@
/Users/accusys/momentry_core/scripts/asrx_processor.py
@@ -0,0 +1,655 @@
#!/opt/homebrew/bin/python3.11
"""
Face Clustering Processor V3 - Single-stage trace clustering (Stage 2 merge removed)
Strategy:
1. Load face embeddings from Qdrant _faces collection
2. Group by trace_id, compute weighted average embedding per trace
3. Single-stage AgglomerativeClustering (no Stage 2 merge)
4. Assign person_id to all faces in each trace
5. Output face_cluster.json with auto speaker binding
Output format:
{"status", "file_uuid", "clusters": [{cluster_id, face_count, representative_face}], "frames": [{frame, timestamp, faces: [{face_id, cluster_id, confidence}]}]}
Changes from V2:
- Added argparse for CLI arguments
- Added Redis progress reporting
- Added status + file_uuid to output
- Added auto_bind_speakers() integration
Changes from previous (broken) version:
- REMOVED Stage 2 merge logic (was incorrectly merging different people)
"""
import argparse
import json
import numpy as np
import os
import sys
from collections import defaultdict
from sklearn.cluster import AgglomerativeClustering
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
UUID = os.getenv("UUID", "quick_preview")
OUTPUT_DIR = os.getenv("MOMENTRY_OUTPUT_DIR", "./output")
OUTPUT_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.face_clustered.json")
ASRX_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.asrx.json")
CLUSTER_THRESHOLD = 0.20 # Updated for facenet-pytorch (was 0.15 for CoreML)
CLUSTER_METHOD = "leader"
def write_empty_output(status: str, file_uuid: str, output_path: str):
output_data = {
"status": status,
"file_uuid": file_uuid,
"clusters": [],
"frames": [],
}
with open(output_path, "w", encoding="utf-8") as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
print(f"Wrote empty output ({status}) to {output_path}")
def load_qdrant_faces(uuid: str, publisher: RedisPublisher) -> list:
"""Load all face points (payload + vector) from Qdrant _faces for a file."""
publisher.progress("face_cluster", 0, 100, "Loading embeddings from Qdrant")
try:
import requests
qdrant_url = os.environ.get("QDRANT_URL", "http://localhost:6333")
qdrant_api_key = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
headers = {}
if qdrant_api_key:
headers["api-key"] = qdrant_api_key
all_points = []
offset = None
while True:
body = {
"limit": 10000,
"with_payload": True,
"with_vector": True,
"filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]},
}
if offset:
body["offset"] = offset
resp = requests.post(
f"{qdrant_url}/collections/_faces/points/scroll",
json=body,
headers=headers,
timeout=60,
)
if resp.status_code != 200:
print(f"Qdrant scroll error: {resp.status_code}")
break
data = resp.json()
batch = data.get("result", {}).get("points", [])
all_points.extend(batch)
next_offset = data.get("result", {}).get("next_page_offset")
if not next_offset:
break
offset = next_offset
print(f"Loaded {len(all_points)} points from Qdrant _faces")
return all_points
except Exception as e:
print(f"Failed to load embeddings from Qdrant: {e}")
return []
def cluster_by_trace(
points: list, min_faces_per_trace: int = 1, confidence_threshold: float = 0.5
) -> tuple:
"""
Cluster faces by trace_id:
1. Filter low-confidence faces
2. Group by trace_id
3. Compute weighted average embedding per trace
"""
high_conf_points = [
p
for p in points
if p.get("payload", {}).get("confidence", 0) >= confidence_threshold
]
print(
f"[FILTER] {len(high_conf_points)}/{len(points)} faces pass confidence >= {confidence_threshold}"
)
traces = defaultdict(list)
for point in high_conf_points:
payload = point.get("payload", {})
trace_id = payload.get("trace_id")
if trace_id is not None and trace_id >= 0:
traces[trace_id].append(point)
print(f"[TRACE] Found {len(traces)} unique traces")
trace_embeddings = {}
for trace_id, trace_points in traces.items():
if len(trace_points) < min_faces_per_trace:
continue
embeddings = []
weights = []
for p in trace_points:
embeddings.append(p["vector"])
weights.append(p.get("payload", {}).get("confidence", 1.0))
embeddings = np.array(embeddings)
weights = np.array(weights)
weights = weights / weights.sum()
avg_embedding = np.average(embeddings, axis=0, weights=weights)
avg_embedding = avg_embedding / np.linalg.norm(avg_embedding)
trace_embeddings[trace_id] = {
"embedding": avg_embedding,
"face_count": len(trace_points),
"avg_confidence": float(np.mean(weights)),
"frames": [p.get("payload", {}).get("frame") for p in trace_points],
"points": trace_points,
}
print(f"[TRACE] {len(trace_embeddings)} traces with >= {min_faces_per_trace} faces")
return trace_embeddings, traces
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
"""
Single-stage AgglomerativeClustering on trace means.
No Stage 2 merge (the problematic logic has been removed).
Returns: (trace_to_person, trace_similarities)
"""
if not trace_embeddings:
return {}, {}
trace_ids = list(trace_embeddings.keys())
n_traces = len(trace_ids)
if n_traces == 0:
return {}, {}
if n_traces == 1:
return {trace_ids[0]: 0}, {trace_ids[0]: 1.0}
embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids])
print(
f"[CLUSTER] Agglomerative: {n_traces} traces, distance_threshold={threshold}..."
)
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=threshold,
metric="cosine",
linkage="average",
)
labels = clustering.fit_predict(embeddings)
unique_labels = set(labels)
print(f"[CLUSTER] Detected {len(unique_labels)} unique persons")
trace_to_person = {}
trace_similarities = {}
for i, trace_id in enumerate(trace_ids):
trace_to_person[trace_id] = labels[i]
# For agglomerative, similarity = 1 - distance to cluster (approximate)
trace_similarities[trace_id] = 1.0 # placeholder; exact requires pairwise
return trace_to_person, trace_similarities
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
"""
Seed-leader clustering with incremental mean centroids.
Algorithm:
1. Iterate traces in stable order (by trace_id).
2. For each trace, compare its centroid to each existing person's mean centroid.
3. If max cosine similarity >= (1 - threshold) → assign to that person, update mean.
4. Else → create new person seeded by this trace.
threshold: cosine distance threshold (default 0.35 = similarity >= 0.65)
Returns: (trace_to_person: dict, trace_similarities: dict)
trace_to_person: {trace_id: person_label}
trace_similarities: {trace_id: similarity_to_centroid}
"""
if not trace_embeddings:
return {}, {}
# Sort by trace_id for deterministic order
trace_ids = sorted(trace_embeddings.keys())
n_traces = len(trace_ids)
if n_traces == 0:
return {}, {}
if n_traces == 1:
return {trace_ids[0]: 0}, {trace_ids[0]: 1.0}
sim_threshold = 1.0 - threshold # cosine similarity threshold
persons = [] # list of {centroid: np.array, member_trace_ids: []}
trace_similarities = {}
print(
f"[CLUSTER] Seed-leader: {n_traces} traces, similarity_threshold={sim_threshold:.3f} (distance={threshold})..."
)
for trace_id in trace_ids:
centroid = trace_embeddings[trace_id]["embedding"]
if not persons:
# First trace → seed first person
persons.append(
{"centroid": centroid.copy(), "member_trace_ids": [trace_id]}
)
trace_similarities[trace_id] = 1.0 # first trace is the centroid
continue
# Find best matching person by cosine similarity to current mean centroid
best_sim = -1.0
best_person_idx = -1
for idx, person in enumerate(persons):
p_centroid = person["centroid"]
norm1 = np.linalg.norm(centroid)
norm2 = np.linalg.norm(p_centroid)
if norm1 > 0 and norm2 > 0:
sim = np.dot(centroid, p_centroid) / (norm1 * norm2)
if sim > best_sim:
best_sim = sim
best_person_idx = idx
if best_sim >= sim_threshold:
# Assign to this person, update mean centroid (incremental)
persons[best_person_idx]["member_trace_ids"].append(trace_id)
trace_similarities[trace_id] = best_sim
# Recompute mean from all member trace centroids
member_embeddings = np.array(
[
trace_embeddings[tid]["embedding"]
for tid in persons[best_person_idx]["member_trace_ids"]
]
)
persons[best_person_idx]["centroid"] = np.mean(member_embeddings, axis=0)
else:
# New person
persons.append(
{"centroid": centroid.copy(), "member_trace_ids": [trace_id]}
)
trace_similarities[trace_id] = 1.0 # seed trace is its own centroid
# Build trace_to_person mapping
trace_to_person = {}
for person_label, person in enumerate(persons):
for tid in person["member_trace_ids"]:
trace_to_person[tid] = person_label
print(f"[CLUSTER] Seed-leader detected {len(persons)} unique persons")
return trace_to_person, trace_similarities
def auto_bind_speakers(output_frames: list, asrx_path: str = ASRX_JSON_PATH) -> dict:
"""
Compute speaker -> Person_N mapping by vote.
Each ASRX segment is matched against face timestamps; the most frequent
person within the segment's time span gets one vote for that speaker.
Returns {"SPEAKER_0": "Person_37", ...}. Pure computation, no DB writes.
"""
if not os.path.exists(asrx_path):
print("Missing data for speaker binding.")
return {}
try:
with open(asrx_path) as f:
asrx_data = json.load(f)
except Exception as e:
print(f" Failed to load ASRX: {e}")
return {}
print("Auto-binding Speakers to Persons...")
face_spans = []
for frame_obj in output_frames:
ts = frame_obj.get("timestamp")
for face in frame_obj.get("faces", []):
person_id = face.get("cluster_id")
if person_id and ts is not None:
face_spans.append({"ts": ts, "person_id": person_id})
speaker_person_counts = {}
for seg in asrx_data.get("segments", []):
start = seg.get("start_time", seg.get("start"))
end = seg.get("end_time", seg.get("end"))
speaker = seg.get("speaker_id")
if not speaker or start is None or end is None:
continue
candidates = [
f for f in face_spans if f.get("ts") is not None and start <= f["ts"] <= end
]
if candidates:
person_counts = {}
for c in candidates:
pid = c["person_id"]
person_counts[pid] = person_counts.get(pid, 0) + 1
if speaker not in speaker_person_counts:
speaker_person_counts[speaker] = {}
best_person = max(person_counts, key=person_counts.get)
speaker_person_counts[speaker][best_person] = (
speaker_person_counts[speaker].get(best_person, 0) + 1
)
mapping = {}
for speaker, persons in speaker_person_counts.items():
if not persons:
continue
best_person = max(persons, key=persons.get)
mapping[speaker] = best_person
print(f" {speaker} is likely {best_person} ({persons[best_person]} votes)")
return mapping
def main():
global OUTPUT_JSON_PATH, UUID
parser = argparse.ArgumentParser(description="Face Clustering Processor V3")
parser.add_argument("video_path", help="Path to video file")
parser.add_argument("output_path", help="Path to output JSON file")
parser.add_argument("--uuid", help="Video UUID (optional, overrides env var)")
parser.add_argument(
"--force", action="store_true", help="Overwrite existing output"
)
parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS)
parser.add_argument(
"--method",
choices=["agglomerative", "leader"],
default="leader",
help="Clustering method: agglomerative (sklearn) or seed-leader (default: leader)",
)
parser.add_argument(
"--threshold",
type=float,
default=CLUSTER_THRESHOLD,
help=f"Cosine distance threshold for clustering (default: {CLUSTER_THRESHOLD})",
)
args = parser.parse_args()
OUTPUT_JSON_PATH = args.output_path
output_dir = os.path.dirname(args.output_path)
if args.uuid:
uuid = args.uuid
else:
uuid = os.path.basename(args.video_path).rsplit(".", 1)[0]
UUID = uuid
face_json_path = os.path.join(output_dir, f"{uuid}.face.json")
if not os.path.exists(face_json_path):
face_json_path = os.path.join(output_dir, uuid, f"{uuid}.face.json")
publisher = RedisPublisher(uuid)
publisher.info("face_cluster", "Face clustering started")
if not os.path.exists(face_json_path):
print("Face JSON not found.")
write_empty_output("no_face_json", uuid, OUTPUT_JSON_PATH)
publisher.complete("face_cluster", "No face.json found")
return
with open(face_json_path) as f:
face_data = json.load(f)
frames_list = face_data.get("frames", [])
if not frames_list:
print("No frames in JSON (no faces).")
write_empty_output("no_faces", uuid, OUTPUT_JSON_PATH)
publisher.complete("face_cluster", "No faces to cluster")
return
fps_value = face_data.get("fps", 23.98)
points = load_qdrant_faces(uuid, publisher)
if not points:
print("No embeddings found in Qdrant.")
write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH)
publisher.complete("face_cluster", "No embeddings in Qdrant")
return
publisher.progress("face_cluster", 10, 100, f"Loaded {len(points)} Qdrant points")
# Count unique traces before filtering
unique_trace_ids = set()
for p in points:
tid = p.get("payload", {}).get("trace_id")
if tid is not None and tid >= 0:
unique_trace_ids.add(tid)
# Keep all traces for maximum recall. Noise is handled by the
# confidence_threshold filter in cluster_by_trace (0.5), not by
# dropping short traces — short appearances (walk-ons, passers-by)
# are real people and must stay in the dedup pool, even for
# large files with many faces.
min_faces = 1
print(
f"[CONFIG] unique_traces={len(unique_trace_ids)}, min_faces_per_trace={min_faces}"
)
trace_embeddings, traces = cluster_by_trace(
points, min_faces_per_trace=min_faces, confidence_threshold=0.5
)
if not trace_embeddings:
print("No valid traces found.")
write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH)
publisher.complete("face_cluster", "No valid traces")
return
publisher.progress("face_cluster", 30, 100, f"Found {len(trace_embeddings)} traces")
# Select clustering method
threshold = args.threshold
method = args.method
if method == "leader":
trace_to_person, trace_similarities = seed_leader_cluster(
trace_embeddings, threshold=threshold
)
else:
trace_to_person, trace_similarities = single_stage_clustering(
trace_embeddings, threshold=threshold
)
if not trace_to_person:
print("Clustering produced no results.")
write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH)
publisher.complete("face_cluster", "Clustering empty")
return
n_persons = len(set(trace_to_person.values()))
print(f"Clustering result: {n_persons} persons ({len(trace_to_person)} traces)")
publisher.progress("face_cluster", 50, 100, f"Found {n_persons} persons")
# Load face_traced.json to get trace_id for each face
traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json")
traced_frames = {}
if os.path.exists(traced_path):
try:
with open(traced_path) as f:
traced_data = json.load(f)
frames_raw = traced_data.get("frames", {})
# Handle both dict and list formats
if isinstance(frames_raw, list):
# Convert list to dict for backward compatibility
for frame_obj in frames_raw:
frame_num = frame_obj.get("frame")
if frame_num is not None:
traced_frames[str(frame_num)] = frame_obj
print(f" Loaded face_traced.json: {len(traced_frames)} frames (converted from list)")
elif isinstance(frames_raw, dict):
traced_frames = frames_raw
print(f" Loaded face_traced.json: {len(traced_frames)} frames (dict)")
else:
print(f" Warning: Unexpected frames format: {type(frames_raw)}")
except Exception as e:
print(f" Warning: Failed to load face_traced.json: {e}")
matched_count = 0
for frame_idx, frame_obj in enumerate(frames_list):
frame_num = frame_obj.get("frame", frame_idx)
# Get traced faces for this frame
traced_frame = traced_frames.get(str(frame_num), {})
traced_faces = traced_frame.get("faces", [])
for face_idx, face in enumerate(frame_obj.get("faces", [])):
# Get trace_id from face_traced.json
trace_id = None
if face_idx < len(traced_faces):
trace_id = traced_faces[face_idx].get("trace_id")
if trace_id is not None and trace_id in trace_to_person:
person_label = trace_to_person[trace_id]
face["person_id"] = f"Person_{person_label}"
face["trace_id"] = trace_id
matched_count += 1
print(f" Assigned person_id to {matched_count} faces")
if matched_count == 0:
print("No faces matched to any trace - check Qdrant data integrity")
publisher.progress("face_cluster", 100, 100, "No trace matches")
write_empty_output("no_faces", uuid, OUTPUT_JSON_PATH)
return
publisher.progress("face_cluster", 70, 100, f"Matched {matched_count} faces")
person_face_count = defaultdict(int)
person_best_face = {}
for frame_idx, frame_obj in enumerate(frames_list):
for face_idx, face in enumerate(frame_obj.get("faces", [])):
person_id = face.get("person_id")
if not person_id:
continue
person_face_count[person_id] += 1
confidence = face.get("confidence", 0.9)
if (
person_id not in person_best_face
or confidence > person_best_face[person_id]["confidence"]
):
person_best_face[person_id] = {
"face_id": f"face_{frame_idx}_{face_idx}",
"confidence": confidence,
"frame": frame_obj.get("frame", frame_idx),
"bbox": {
"x": face.get("x"),
"y": face.get("y"),
"width": face.get("width"),
"height": face.get("height"),
},
}
# Build per-person similarity stats from trace_similarities
person_sims = defaultdict(list)
sim_threshold_value = 1.0 - threshold # similarity threshold
for tid, person_label in trace_to_person.items():
sim = trace_similarities.get(tid, 0.0)
person_sims[person_label].append(sim)
person_labels_sorted = sorted(
person_face_count.keys(), key=lambda p: -person_face_count[p]
)
clusters = []
for person_id in person_labels_sorted:
# Extract person number from "Person_N" to get the integer label
person_label = None
try:
person_label = int(person_id.split("_")[1])
except (IndexError, ValueError):
pass
sims = person_sims.get(person_label, []) if person_label is not None else []
similarity_info = None
if sims:
similarity_info = {
"min": round(float(min(sims)), 4),
"avg": round(float(sum(sims) / len(sims)), 4),
"threshold": round(sim_threshold_value, 4),
}
cluster_entry = {
"cluster_id": person_id,
"face_count": person_face_count[person_id],
"representative_face": person_best_face.get(person_id),
}
if similarity_info:
cluster_entry["similarity"] = similarity_info
clusters.append(cluster_entry)
output_frames = []
for frame_idx, frame_obj in enumerate(frames_list):
timestamp = frame_obj.get(
"timestamp", frame_obj.get("frame", 0) / fps_value if fps_value > 0 else 0
)
output_faces = []
for face_idx, face in enumerate(frame_obj.get("faces", [])):
person_id = face.get("person_id")
if person_id:
output_faces.append(
{
"face_id": f"face_{frame_idx}_{face_idx}",
"cluster_id": person_id,
"trace_id": face.get("trace_id"),
"confidence": face.get("confidence", 0.9),
}
)
if output_faces:
output_frames.append(
{
"frame": frame_obj.get("frame", frame_idx),
"timestamp": timestamp,
"faces": output_faces,
}
)
output_data = {
"status": "has_faces",
"file_uuid": UUID,
"clusters": clusters,
"frames": output_frames,
}
speaker_mapping = auto_bind_speakers(
output_frames, os.path.join(output_dir, f"{uuid}.asrx.json")
)
if speaker_mapping:
output_data["speaker_person_mapping"] = speaker_mapping
with open(OUTPUT_JSON_PATH, "w", encoding="utf-8") as f:
json.dump(round_json_numbers(output_data), f, indent=2, ensure_ascii=False)
print(f"Saved clustered data to {OUTPUT_JSON_PATH}")
publisher.progress("face_cluster", 90, 100, f"{len(clusters)} clusters")
publisher.complete("face_cluster", f"{len(clusters)} clusters")
if speaker_mapping:
publisher.info(
"face_cluster",
f"Speaker mapping: {len(speaker_mapping)} speakers",
)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
/Users/accusys/momentry_core/tools/script/ocr/ocr_processor.py
+1
View File
@@ -0,0 +1 @@
/Users/accusys/momentry_core/tools/script/face/store_traced_faces.py
+1
View File
@@ -0,0 +1 @@
/Users/accusys/momentry_core/scripts/swift_processors
+590
View File
@@ -0,0 +1,590 @@
#!/opt/homebrew/bin/python3.11
"""
Face Tracker - Track faces across frames using embedding similarity and bbox proximity
Purpose:
1. Assign unique trace_id to each face across frames
2. Track face movement across adjacent frames
3. Output trace statistics (duration, path, confidence)
Algorithm:
1. For first frame: assign new trace_id to each face
2. For subsequent frames:
- Calculate bbox overlap with previous frame faces
- Calculate embedding cosine similarity
- Match faces if both conditions met
- Assign same trace_id if matched, new trace_id if not
Matching Conditions:
- bbox overlap > 0.3 (IoU)
- embedding similarity > 0.7
- OR single condition > threshold (fallback)
Output:
- face.json with trace_id added to each face
- trace statistics report
"""
import json
import argparse
import numpy as np
def strip_embeddings_and_round(obj):
"""Remove face embeddings from face_traced.json and round floats to 2 dp.
Embeddings live in Qdrant _faces (512D); storing them in the JSON bloats the
file (~2MB+ per 1000 faces). face_tracker consumes embeddings in-memory (loaded
from Qdrant before tracking), so stripping at write time is safe: all downstream
consumers (TKG, clustering, cluster_agent) read Qdrant or trace IDs instead.
"""
if isinstance(obj, dict):
return {
k: strip_embeddings_and_round(v)
for k, v in obj.items()
if not (k == "embedding")
}
if isinstance(obj, list):
return [strip_embeddings_and_round(v) for v in obj]
if isinstance(obj, float):
return round(obj, 2)
return obj
from typing import Dict, List, Set
from collections import defaultdict
def calculate_bbox_iou(bbox1: Dict, bbox2: Dict) -> float:
"""
Calculate Intersection over Union (IoU) between two bboxes
Args:
bbox1: {"x": int, "y": int, "width": int, "height": int}
bbox2: same structure
Returns:
IoU score (0.0 - 1.0)
"""
x1, y1, w1, h1 = bbox1["x"], bbox1["y"], bbox1["width"], bbox1["height"]
x2, y2, w2, h2 = bbox2["x"], bbox2["y"], bbox2["width"], bbox2["height"]
x1_min, x1_max = x1, x1 + w1
y1_min, y1_max = y1, y1 + h1
x2_min, x2_max = x2, x2 + w2
y2_min, y2_max = y2, y2 + h2
inter_x_min = max(x1_min, x2_min)
inter_x_max = min(x1_max, x2_max)
inter_y_min = max(y1_min, y2_min)
inter_y_max = min(y1_max, y2_max)
if inter_x_max <= inter_x_min or inter_y_max <= inter_y_min:
return 0.0
inter_area = (inter_x_max - inter_x_min) * (inter_y_max - inter_y_min)
area1 = w1 * h1
area2 = w2 * h2
union_area = area1 + area2 - inter_area
return inter_area / union_area if union_area > 0 else 0.0
def calculate_bbox_distance(bbox1: Dict, bbox2: Dict) -> float:
"""
Calculate center distance between two bboxes
Returns:
Euclidean distance between centers
"""
cx1 = bbox1["x"] + bbox1["width"] / 2
cy1 = bbox1["y"] + bbox1["height"] / 2
cx2 = bbox2["x"] + bbox2["width"] / 2
cy2 = bbox2["y"] + bbox2["height"] / 2
return np.sqrt((cx1 - cx2) ** 2 + (cy1 - cy2) ** 2)
def calculate_embedding_similarity(emb1: List[float], emb2: List[float]) -> float:
"""
Calculate cosine similarity between two embeddings
Returns:
Cosine similarity (-1.0 - 1.0)
"""
if emb1 is None or emb2 is None:
return 0.0
v1 = np.array(emb1)
v2 = np.array(emb2)
norm1 = np.linalg.norm(v1)
norm2 = np.linalg.norm(v2)
if norm1 == 0 or norm2 == 0:
return 0.0
return np.dot(v1, v2) / (norm1 * norm2)
def match_faces(
current_faces: List[Dict],
previous_faces: List[Dict],
iou_threshold: float = 0.3,
similarity_threshold: float = 0.7,
distance_threshold: float = 100.0,
use_embedding: bool = True,
frame_gap: int = 1,
cut_boundaries: Set[int] = None,
prev_frame: int = None,
curr_frame: int = None,
) -> Dict[int, int]:
"""
Match current frame faces to previous frame faces
Args:
current_faces: Faces in current frame
previous_faces: Faces in previous frame
iou_threshold: Minimum IoU for matching
similarity_threshold: Minimum embedding similarity for matching
distance_threshold: Maximum bbox center distance for matching
use_embedding: Whether to use embedding similarity
frame_gap: Number of frames between current and previous (1=adjacent)
cut_boundaries: Set of frame numbers where scene cuts occur
prev_frame: Previous frame number (for cut detection)
curr_frame: Current frame number (for cut detection)
Returns:
Dict mapping current_face_index -> previous_face_index (or -1 if new)
"""
if not previous_faces:
return {i: -1 for i in range(len(current_faces))}
# If frame gap is too large, force new traces (likely crossed multiple scenes)
if frame_gap is not None and frame_gap > 30:
return {i: -1 for i in range(len(current_faces))}
# If a scene cut exists between prev and current frame, only continue
# traces for faces matching the previous frame with high IoU (same person
# in the same position across the cut); unmatched faces get new traces.
if cut_boundaries and prev_frame is not None and curr_frame is not None:
for cf in cut_boundaries:
if prev_frame < cf <= curr_frame:
matches = {}
used_prev = set()
for curr_idx, curr_face in enumerate(current_faces):
best_prev_idx = -1
best_iou = 0.0
curr_bbox = {
"x": curr_face["x"],
"y": curr_face["y"],
"width": curr_face["width"],
"height": curr_face["height"],
}
for prev_idx, prev_face in enumerate(previous_faces):
if prev_idx in used_prev:
continue
prev_bbox = {
"x": prev_face["x"],
"y": prev_face["y"],
"width": prev_face["width"],
"height": prev_face["height"],
}
iou = calculate_bbox_iou(curr_bbox, prev_bbox)
if iou > best_iou:
best_iou = iou
best_prev_idx = prev_idx
if best_prev_idx >= 0 and best_iou > 0.5:
matches[curr_idx] = best_prev_idx
used_prev.add(best_prev_idx)
else:
matches[curr_idx] = -1
return matches
matches = {}
used_prev = set()
for curr_idx, curr_face in enumerate(current_faces):
best_prev_idx = -1
best_score = 0.0
curr_bbox = {
"x": curr_face["x"],
"y": curr_face["y"],
"width": curr_face["width"],
"height": curr_face["height"],
}
curr_emb = curr_face.get("embedding")
for prev_idx, prev_face in enumerate(previous_faces):
if prev_idx in used_prev:
continue
prev_bbox = {
"x": prev_face["x"],
"y": prev_face["y"],
"width": prev_face["width"],
"height": prev_face["height"],
}
prev_emb = prev_face.get("embedding")
iou = calculate_bbox_iou(curr_bbox, prev_bbox)
distance = calculate_bbox_distance(curr_bbox, prev_bbox)
similarity = 0.0
if use_embedding and curr_emb and prev_emb:
similarity = calculate_embedding_similarity(curr_emb, prev_emb)
# Bbox size consistency check: sudden size change = different person
prev_area = prev_bbox["width"] * prev_bbox["height"]
curr_area = curr_bbox["width"] * curr_bbox["height"]
area_ratio = max(curr_area, prev_area) / max(1, min(curr_area, prev_area))
score = 0.0
# Reject only if BOTH embedding AND IoU disagree (different person + different position)
if use_embedding and curr_emb and prev_emb and similarity < 0.5 and iou < 0.3:
continue
# Reject if bbox size changes by more than 5x (e.g., far shot → close-up)
if area_ratio > 5.0 and similarity < 0.8:
continue
# Edge exit: if previous face was near frame edge and current face is not,
# the old face likely exited and a new face appeared
prev_at_edge = (prev_bbox["x"] < 50 or
prev_bbox["x"] + prev_bbox["width"] > 1870 or
prev_bbox["y"] < 50 or
prev_bbox["y"] + prev_bbox["height"] > 1030)
curr_at_edge = (curr_bbox["x"] < 50 or
curr_bbox["x"] + curr_bbox["width"] > 1870 or
curr_bbox["y"] < 50 or
curr_bbox["y"] + curr_bbox["height"] > 1030)
if prev_at_edge and not curr_at_edge and similarity < 0.8:
continue
if iou > iou_threshold and similarity > similarity_threshold:
score = iou + similarity
elif iou > 0.5 and similarity > 0.65:
score = iou * 1.5 + similarity * 0.5
elif iou > 0.35 and distance < distance_threshold:
score = iou * 2 - distance / 500
elif similarity > 0.85:
score = similarity * 2
elif similarity > 0.75 and distance < distance_threshold:
score = similarity - distance / 1000
# For frame gaps (tracking lost and recovered), require higher confidence
elif frame_gap > 1 and similarity > 0.8 and iou > 0.2:
score = similarity + iou
if score > best_score:
best_score = score
best_prev_idx = prev_idx
if best_prev_idx >= 0 and best_score > 0:
matches[curr_idx] = best_prev_idx
used_prev.add(best_prev_idx)
else:
matches[curr_idx] = -1
return matches
def track_faces(
face_data: Dict,
iou_threshold: float = 0.3,
similarity_threshold: float = 0.7,
distance_threshold: float = 100.0,
use_embedding: bool = True,
cut_boundaries: Set[int] = None,
) -> Dict:
"""
Track faces across all frames
Args:
face_data: face.json data
iou_threshold: IoU threshold for matching
similarity_threshold: Embedding similarity threshold
distance_threshold: Distance threshold for matching
use_embedding: Whether to use embedding
Returns:
Updated face_data with trace_id added to each face
"""
frames = face_data.get("frames", {})
if not frames:
print("No frames found in face.json")
return face_data
# Support both list and dict formats
if isinstance(frames, list):
# List format: [{frame: 0, faces: [...]}, ...]
sorted_frames = sorted(frames, key=lambda x: x.get("frame", 0))
# Convert to dict format for consistency
frames_dict = {}
for frame_data in sorted_frames:
frame_num = frame_data.get("frame")
if frame_num is not None:
frames_dict[str(frame_num)] = {"faces": frame_data.get("faces", [])}
frames = frames_dict
face_data["frames"] = frames
sorted_frames = sorted(frames.items(), key=lambda x: int(x[0]))
next_trace_id = 0
traces = defaultdict(list)
prev_faces = []
prev_trace_ids = []
prev_frame_num = None
prev_face_frame = None # last frame number that had actual faces
print(f"\nTracking faces across {len(sorted_frames)} frames...")
print(f"Parameters: iou={iou_threshold}, similarity={similarity_threshold}, distance={distance_threshold}")
print()
for frame_num_str, frame_data in sorted_frames:
frame_num = int(frame_num_str)
frame_gap = frame_num - prev_frame_num if prev_frame_num is not None else 1
prev_frame_num = frame_num
faces = frame_data.get("faces", [])
if not faces:
prev_faces = []
prev_trace_ids = []
continue
matches = match_faces(
faces,
prev_faces,
iou_threshold,
similarity_threshold,
distance_threshold,
use_embedding,
frame_gap,
cut_boundaries,
prev_face_frame,
frame_num,
)
trace_ids = []
for curr_idx, prev_idx in matches.items():
if prev_idx >= 0:
trace_id = prev_trace_ids[prev_idx]
else:
trace_id = next_trace_id
next_trace_id += 1
faces[curr_idx]["trace_id"] = trace_id
trace_ids.append(trace_id)
traces[trace_id].append({
"frame": frame_num,
"face_index": curr_idx,
"bbox": {
"x": faces[curr_idx]["x"],
"y": faces[curr_idx]["y"],
"width": faces[curr_idx]["width"],
"height": faces[curr_idx]["height"],
},
"confidence": faces[curr_idx].get("confidence", 0.0),
"pose_angle": faces[curr_idx].get("pose_angle", {}).get("angle", "unknown"),
"pose_full": faces[curr_idx].get("pose_angle", {}), # 完整 pose 信息
})
prev_faces = faces
prev_trace_ids = trace_ids
prev_face_frame = frame_num
if frame_num % 100 == 0:
print(f" Frame {frame_num}: {len(faces)} faces, {len(set(trace_ids))} active traces")
face_data["traces"] = {}
for trace_id, path in traces.items():
if len(path) >= 1:
duration_frames = path[-1]["frame"] - path[0]["frame"] + 1
avg_confidence = sum(p["confidence"] for p in path) / len(path)
pose_angles = [p["pose_angle"] for p in path]
# Pose Trace: 完整 pose 信息
pose_trace = []
for p in path:
pose_info = p.get("pose_full", {})
pose_trace.append({
"frame": p["frame"],
"angle": pose_info.get("angle", "unknown"),
"confidence": pose_info.get("confidence", 0.0),
"pitch": pose_info.get("pitch", "neutral"),
"features": pose_info.get("features", {}),
})
# Pose Statistics
pose_counts = defaultdict(int)
pose_confidence_by_angle = defaultdict(list)
for pose in pose_trace:
pose_counts[pose["angle"]] += 1
pose_confidence_by_angle[pose["angle"]].append(pose["confidence"])
pose_statistics = {
"distribution": dict(pose_counts),
"avg_confidence_by_angle": {
angle: round(sum(conf_list) / len(conf_list), 3)
for angle, conf_list in pose_confidence_by_angle.items()
},
"dominant_angle": max(pose_counts.items(), key=lambda x: x[1])[0] if pose_counts else "unknown",
"pose_count": len(pose_counts),
}
# Pose Transitions: pose 变化事件
pose_transitions = []
prev_pose = None
for i, pose in enumerate(pose_trace):
if prev_pose is not None and pose["angle"] != prev_pose["angle"]:
pose_transitions.append({
"frame": pose["frame"],
"from_angle": prev_pose["angle"],
"to_angle": pose["angle"],
"transition_index": len(pose_transitions) + 1,
})
prev_pose = pose
face_data["traces"][str(trace_id)] = {
"trace_id": trace_id,
"start_frame": path[0]["frame"],
"end_frame": path[-1]["frame"],
"duration_frames": duration_frames,
"duration_seconds": duration_frames / (face_data.get("metadata") or {}).get("fps", face_data.get("fps", 30.0)),
"total_appearances": len(path),
"avg_confidence": avg_confidence,
"pose_angles": pose_angles,
"pose_trace": pose_trace,
"pose_statistics": pose_statistics,
"pose_transitions": pose_transitions,
"path": path,
}
# Ensure metadata exists
if not face_data.get("metadata"):
face_data["metadata"] = {}
face_data["metadata"]["trace_stats"] = {
"total_traces": next_trace_id,
"active_traces": len(traces),
"long_traces": len([t for t in traces.values() if len(t) >= 2]),
}
return face_data
def analyze_traces(face_data: Dict) -> None:
"""
Analyze and print trace statistics
"""
traces = face_data.get("traces", {})
metadata = face_data.get("metadata", {})
print("\n" + "=" * 60)
print("Face Trace Analysis")
print("=" * 60)
print(f"\nTotal traces: {metadata.get('trace_stats', {}).get('total_traces', 0)}")
print(f"Long traces (>= 2 frames): {len(traces)}")
if not traces:
return
sorted_traces = sorted(traces.values(), key=lambda x: x["duration_frames"], reverse=True)
print("\n=== Top 10 Longest Traces ===")
for i, trace in enumerate(sorted_traces[:10]):
print(f"\nTrace {trace['trace_id']}:")
print(f" Frames: {trace['start_frame']} - {trace['end_frame']} ({trace['duration_frames']} frames)")
print(f" Duration: {trace['duration_seconds']:.2f} seconds")
print(f" Appearances: {trace['total_appearances']}")
print(f" Avg Confidence: {trace['avg_confidence']:.3f}")
# Pose Statistics
pose_stats = trace.get("pose_statistics", {})
print(f" Pose Distribution: {pose_stats.get('distribution', {})}")
print(f" Dominant Angle: {pose_stats.get('dominant_angle', 'unknown')}")
# Pose Transitions
transitions = trace.get("pose_transitions", [])
if transitions:
print(f" Pose Transitions: {len(transitions)} events")
for t in transitions[:3]: # 只显示前 3 个
print(f" - Frame {t['frame']}: {t['from_angle']} → {t['to_angle']}")
pose_stats = defaultdict(int)
for trace in traces.values():
for pose in trace["pose_angles"]:
pose_stats[pose] += 1
print("\n=== Pose Distribution in Traces ===")
for pose, count in sorted(pose_stats.items(), key=lambda x: x[1], reverse=True):
print(f" {pose}: {count}")
duration_distribution = defaultdict(int)
for trace in traces.values():
d = trace["duration_frames"]
if d <= 30:
duration_distribution["short (<= 30 frames)"] += 1
elif d <= 90:
duration_distribution["medium (31-90 frames)"] += 1
else:
duration_distribution["long (> 90 frames)"] += 1
print("\n=== Trace Duration Distribution ===")
for duration, count in sorted(duration_distribution.items()):
print(f" {duration}: {count}")
def main():
parser = argparse.ArgumentParser(description="Track faces across frames")
parser.add_argument("--face-json", required=True, help="Path to face.json")
parser.add_argument("--output", help="Output path (default: face_traced.json)")
parser.add_argument("--iou-threshold", type=float, default=0.3, help="IoU threshold")
parser.add_argument("--similarity-threshold", type=float, default=0.7, help="Embedding similarity threshold")
parser.add_argument("--distance-threshold", type=float, default=100.0, help="Distance threshold")
parser.add_argument("--no-embedding", action="store_true", help="Disable embedding matching")
parser.add_argument("--cuts-json", help="Path to cut.json for scene-cut-aware tracking")
parser.add_argument("--analyze-only", action="store_true", help="Only analyze, don't output")
args = parser.parse_args()
# Load cut boundaries if provided
cut_boundaries = None
if args.cuts_json:
with open(args.cuts_json) as f:
cuts = json.load(f)
cut_boundaries = {s["start_frame"] for s in cuts.get("scenes", []) if s["start_frame"] > 0}
print(f" Cut boundaries loaded: {len(cut_boundaries)} cuts")
print("=" * 60)
print("Face Tracker")
print("=" * 60)
with open(args.face_json) as f:
face_data = json.load(f)
print(f"\nInput: {args.face_json}")
print(f"Frames: {len(face_data.get('frames', {}))}")
face_data = track_faces(
face_data,
iou_threshold=args.iou_threshold,
similarity_threshold=args.similarity_threshold,
distance_threshold=args.distance_threshold,
use_embedding=not args.no_embedding,
cut_boundaries=cut_boundaries,
)
analyze_traces(face_data)
if not args.analyze_only:
output_path = args.output or args.face_json.replace(".json", "_traced.json")
with open(output_path, "w") as f:
json.dump(strip_embeddings_and_round(face_data), f, indent=2)
print(f"\n✅ Output saved to: {output_path}")
if __name__ == "__main__":
main()
+722
View File
@@ -0,0 +1,722 @@
#!/opt/homebrew/bin/python3.11
"""
Qdrant _faces and _seeds Collection Operations
Functions for _faces:
- ensure_faces_collection(): Create _faces collection if not exists
- generate_point_id(): Generate consistent point ID
- push_face_embeddings_batch(): Batch push embeddings to Qdrant
- update_trace_ids(): Update trace_id after face tracking
- get_file_faces(): Get all face points for a file
- get_trace_representatives(): Get representative embeddings per trace
Functions for _seeds:
- ensure_seeds_collection(): Create _seeds collection if not exists
- push_seed_embedding(): Push identity seed embedding
- get_seeds(): Get all seed points
- search_seeds(): Cosine search against seeds
- delete_seed(): Delete a seed point
Collection Schema:
- _faces: 512D, Cosine, payload: {file_uuid, frame, trace_id, bbox, confidence, identity_id, identity_uuid, stranger_id}
- _seeds: 512D, Cosine, payload: {identity_id, identity_uuid, name, source, file_uuid, trace_id, tmdb_id, created_at}
"""
import os
import json
import hashlib
import urllib.request
import urllib.error
from typing import Optional
from datetime import datetime
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
FACES_COLLECTION = "_faces"
SEEDS_COLLECTION = "_seeds"
VECTOR_DIM = 512
# Default 1000 (was 100): larger pages cut the number of scroll/set_payload HTTP
# round-trips ~10x on large files (B2). Still overridable via QDRANT_BATCH_SIZE.
BATCH_SIZE = int(os.environ.get("QDRANT_BATCH_SIZE", "1000"))
def qdrant_request(method: str, path: str, body: dict = None) -> dict:
"""Make HTTP request to Qdrant"""
url = f"{QDRANT_URL}{path}"
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read())
except urllib.error.HTTPError as e:
error_body = e.read().decode()
raise RuntimeError(f"Qdrant HTTP {e.code}: {error_body}")
def ensure_faces_collection() -> bool:
"""Create _faces collection if not exists"""
url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}"
req = urllib.request.Request(url, method="GET")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
return True # Collection exists
except urllib.error.HTTPError as e:
if e.code != 404:
raise RuntimeError(f"Qdrant check failed: {e.read().decode()}")
# Create collection
body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}}
create_url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}"
data = json.dumps(body).encode()
req = urllib.request.Request(create_url, data=data, method="PUT")
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
print(f"[QDRANT] Created collection: {FACES_COLLECTION}")
return True
except urllib.error.HTTPError as e:
raise RuntimeError(f"Qdrant create collection failed: {e.read().decode()}")
def generate_point_id(file_uuid: str, frame: int, trace_id: int = 0) -> int:
"""Generate consistent point ID from file_uuid + frame + trace_id"""
key = f"{file_uuid}_{frame}_{trace_id}"
return int(hashlib.md5(key.encode()).hexdigest()[:16], 16)
def push_face_embeddings_batch(file_uuid: str, faces: list, publisher=None) -> int:
"""Batch push face embeddings to _faces collection
Args:
file_uuid: Video file UUID
faces: List of {frame, trace_id, bbox, confidence, embedding}
publisher: RedisPublisher for progress reporting (optional)
Returns:
Number of successfully pushed embeddings
Raises:
RuntimeError: If Qdrant push fails
"""
if not faces:
return 0
ensure_faces_collection()
total = len(faces)
pushed = 0
for i in range(0, total, BATCH_SIZE):
batch = faces[i : i + BATCH_SIZE]
points = []
for face in batch:
point_id = generate_point_id(
file_uuid, face["frame"], face.get("trace_id", 0)
)
points.append(
{
"id": point_id,
"vector": face["embedding"],
"payload": {
"file_uuid": file_uuid,
"frame": face["frame"],
"trace_id": face.get("trace_id", 0),
"bbox": face["bbox"],
"confidence": face.get("confidence", 0.5),
"capture_quality": face.get("capture_quality", 0.0),
"identity_id": 0,
"identity_uuid": "",
"stranger_id": 0,
},
}
)
body = {"points": points}
url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points?wait=true"
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, method="PUT")
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
pushed += len(batch)
except urllib.error.HTTPError as e:
error_body = e.read().decode()
raise RuntimeError(
f"Qdrant push failed (batch {i // BATCH_SIZE}): HTTP {e.code} - {error_body}"
)
if publisher:
pct = int((i + len(batch)) * 100 / total)
publisher.progress("face", i + len(batch), total, f"Qdrant push {pct}%")
print(f"[QDRANT] Pushed {pushed} embeddings to {FACES_COLLECTION}")
return pushed
def update_trace_ids(
file_uuid: str, trace_mapping: dict, return_trace_ids: bool = False
):
"""Update trace_id for all face points in a file
Called by store_traced_faces.py after face tracking.
Uses Qdrant set_payload to avoid reading/writing vectors.
Args:
file_uuid: Video file UUID
trace_mapping: {frame: {bbox_key: trace_id}}
bbox_key = f"{x}_{y}_{width}_{height}"
return_trace_ids: If True, also return the set of trace_ids seen during the
scroll. This lets the caller avoid a redundant full collection scan just
to count unique traces (B1 optimization for large files).
Returns:
Number of updated points, or (updated_count, trace_id_set) if return_trace_ids.
"""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"with_vector": False,
"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]},
}
if offset:
body["offset"] = offset
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
all_points.extend(batch)
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
# Group point IDs by trace_id
trace_groups = {}
for point in all_points:
point_id = point["id"]
payload = point.get("payload", {})
frame = payload.get("frame")
# Support two bbox formats:
# 1. Nested bbox field
# 2. Direct x, y, width, height fields
bbox = payload.get("bbox", {})
if bbox:
# Format 1: has bbox field
x = bbox.get('x')
y = bbox.get('y')
width = bbox.get('width')
height = bbox.get('height')
else:
# Format 2: direct fields
x = payload.get('x')
y = payload.get('y')
width = payload.get('width')
height = payload.get('height')
if x is None or y is None or width is None or height is None:
continue
bbox_key = f"{x}_{y}_{width}_{height}"
trace_id = trace_mapping.get(frame, {}).get(bbox_key)
if trace_id is None:
continue
if trace_id not in trace_groups:
trace_groups[trace_id] = []
trace_groups[trace_id].append(point_id)
if not trace_groups:
return (0, set()) if return_trace_ids else 0
# Use set_payload per trace_id group (no vector write)
total = 0
for trace_id, point_ids in trace_groups.items():
for i in range(0, len(point_ids), BATCH_SIZE):
batch_ids = point_ids[i : i + BATCH_SIZE]
set_points_payload({"trace_id": trace_id}, batch_ids)
total += len(batch_ids)
print(f"[QDRANT] Updated {total} trace_ids in {FACES_COLLECTION}")
if return_trace_ids:
return total, set(trace_groups.keys())
return total
def set_points_payload(payload: dict, point_ids: list, wait: bool = True) -> dict:
"""Set payload fields on specific Qdrant points (without touching vectors)
Args:
payload: Dict of payload fields to set (e.g. {"trace_id": 5})
point_ids: List of Qdrant point IDs
wait: Wait for operation to complete
Returns:
Qdrant API response
"""
body = {
"payload": payload,
"points": point_ids,
"wait": wait,
}
return qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/payload", body
)
def delete_file_faces(file_uuid: str) -> int:
"""Delete all face points for a file
Args:
file_uuid: Video file UUID
Returns:
Number of deleted points
"""
body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}}
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/delete", body
)
deleted = result.get("result", {}).get("operation_id", 0)
print(f"[QDRANT] Deleted faces for file_uuid={file_uuid}")
return deleted
def get_file_faces(file_uuid: str, with_vector: bool = False) -> list:
"""Get all face points for a file
Args:
file_uuid: Video file UUID
with_vector: Whether to include vector data (default False for payload-only)
Returns:
List of points with payload (and vector if requested)
"""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"with_vector": with_vector,
"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]},
}
if offset:
body["offset"] = offset
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
all_points.extend(batch)
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
return all_points
def count_file_faces(file_uuid: str) -> int:
"""Count face points for a file
Args:
file_uuid: Video file UUID
Returns:
Number of face points
"""
body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}}
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/count", body
)
return result.get("result", {}).get("count", 0)
def get_trace_representatives(file_uuid: str) -> dict:
"""Get representative embeddings per trace for multi-angle matching
Args:
file_uuid: Video file UUID
Returns:
{trace_id: [{'frame', 'embedding', 'bbox'}, ...]}
Each trace has 3 representatives: start, middle, end
"""
all_points = get_file_faces(file_uuid, with_vector=True)
traces = {}
for point in all_points:
payload = point.get("payload", {})
vector = point.get("vector", [])
trace_id = payload.get("trace_id", 0)
if trace_id == 0:
continue
if trace_id not in traces:
traces[trace_id] = []
traces[trace_id].append(
{
"frame": payload.get("frame"),
"embedding": vector,
"bbox": payload.get("bbox", {}),
"confidence": payload.get("confidence", 0.5),
}
)
for trace_id in traces:
points = traces[trace_id]
points.sort(key=lambda x: x["frame"])
if len(points) <= 3:
traces[trace_id] = points
else:
start = points[0]
end = points[-1]
middle_idx = len(points) // 2
middle = points[middle_idx]
traces[trace_id] = [start, middle, end]
return traces
def get_trace_centroid(file_uuid: str, trace_id: int) -> list:
"""Get centroid embedding for a trace
Args:
file_uuid: Video file UUID
trace_id: Trace ID
Returns:
Centroid embedding (512D)
"""
reps = get_trace_representatives(file_uuid).get(trace_id, [])
if not reps:
return [0.0] * VECTOR_DIM
centroid = [0.0] * VECTOR_DIM
for rep in reps:
for i, v in enumerate(rep["embedding"]):
centroid[i] += v
count = len(reps)
for i in range(VECTOR_DIM):
centroid[i] /= count
return centroid
# ==================== _seeds Collection ====================
def ensure_seeds_collection() -> bool:
"""Create _seeds collection if not exists"""
url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}"
req = urllib.request.Request(url, method="GET")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
return True # Collection exists
except urllib.error.HTTPError as e:
if e.code != 404:
raise RuntimeError(f"Qdrant check failed: {e.read().decode()}")
body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}}
create_url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}"
data = json.dumps(body).encode()
req = urllib.request.Request(create_url, data=data, method="PUT")
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
print(f"[QDRANT] Created collection: {SEEDS_COLLECTION}")
return True
except urllib.error.HTTPError as e:
raise RuntimeError(f"Qdrant create collection failed: {e.read().decode()}")
def push_seed_embedding(
identity_id: int,
identity_uuid: str,
name: str,
embedding: list,
source: str = "tmdb",
file_uuid: str = None,
trace_id: int = None,
tmdb_id: int = None,
) -> bool:
"""Push identity seed embedding to _seeds collection
Args:
identity_id: PG identity.id
identity_uuid: Identity UUID
name: Identity name
embedding: 512D embedding
source: 'tmdb' | 'manual' | 'propagation'
file_uuid: File UUID (for manual/propagation seeds)
trace_id: Trace ID (for propagation seeds)
tmdb_id: TMDb ID (for TMDb seeds)
Returns:
True if successful
Raises:
RuntimeError: If Qdrant push fails
"""
ensure_seeds_collection()
payload = {
"identity_id": identity_id,
"identity_uuid": identity_uuid,
"name": name,
"source": source,
"created_at": datetime.now().isoformat(),
}
if file_uuid:
payload["file_uuid"] = file_uuid
if trace_id:
payload["trace_id"] = trace_id
if tmdb_id:
payload["tmdb_id"] = tmdb_id
body = {
"points": [
{
"id": identity_id, # Use identity_id as point_id
"vector": embedding,
"payload": payload,
}
]
}
url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}/points?wait=true"
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, method="PUT")
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
print(f"[QDRANT] Pushed seed: {name} (id={identity_id}, source={source})")
return True
except urllib.error.HTTPError as e:
error_body = e.read().decode()
raise RuntimeError(f"Qdrant seed push failed: HTTP {e.code} - {error_body}")
def get_seeds(source: str = None, file_uuid: str = None) -> list:
"""Get all seed points
Args:
source: Filter by source ('tmdb', 'manual', 'propagation'), or None for all
file_uuid: Filter by file_uuid, or None for all
Returns:
List of seed points with payload and vector
"""
ensure_seeds_collection()
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"with_vector": True,
}
filters = []
if source:
filters.append({"key": "source", "match": {"value": source}})
if file_uuid:
filters.append({"key": "file_uuid", "match": {"value": file_uuid}})
if filters:
body["filter"] = {"must": filters}
if offset:
body["offset"] = offset
result = qdrant_request(
"POST", f"/collections/{SEEDS_COLLECTION}/points/scroll", body
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
all_points.extend(batch)
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
return all_points
def search_seeds(
query_embedding: list, limit: int = 10, threshold: float = 0.0
) -> list:
"""Cosine search against seeds
Args:
query_embedding: 512D query vector
limit: Max results
threshold: Minimum score threshold
Returns:
List of {identity_id, identity_uuid, name, source, score}
"""
ensure_seeds_collection()
body = {
"vector": query_embedding,
"limit": limit,
"with_payload": True,
}
result = qdrant_request(
"POST", f"/collections/{SEEDS_COLLECTION}/points/search", body
)
points = result.get("result", [])
results = []
for point in points:
score = point.get("score", 0)
if score < threshold:
continue
payload = point.get("payload", {})
results.append(
{
"identity_id": payload.get("identity_id"),
"identity_uuid": payload.get("identity_uuid"),
"name": payload.get("name"),
"source": payload.get("source"),
"score": score,
}
)
return results
def delete_seed(identity_id: int) -> bool:
"""Delete a seed point
Args:
identity_id: Identity ID (used as point_id)
Returns:
True if successful
"""
body = {"points": [identity_id]}
result = qdrant_request(
"POST", f"/collections/{SEEDS_COLLECTION}/points/delete?wait=true", body
)
print(f"[QDRANT] Deleted seed: identity_id={identity_id}")
return result.get("result", {}).get("status") == "completed"
def count_seeds(source: str = None) -> int:
"""Count seed points
Args:
source: Filter by source, or None for all
Returns:
Number of seed points
"""
ensure_seeds_collection()
body = {}
if source:
body["filter"] = {"must": [{"key": "source", "match": {"value": source}}]}
result = qdrant_request(
"POST", f"/collections/{SEEDS_COLLECTION}/points/count", body
)
return result.get("result", {}).get("count", 0)
def update_identity_in_faces(
file_uuid: str, trace_id: int, identity_id: int, identity_uuid: str
) -> int:
"""Update identity_id/identity_uuid for all face points with trace_id
Called after identity binding confirmation.
Uses Qdrant set_payload to avoid reading/writing vectors.
Args:
file_uuid: Video file UUID
trace_id: Trace ID
identity_id: Identity ID
identity_uuid: Identity UUID
Returns:
Number of updated points
"""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"with_vector": False,
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": trace_id}},
]
},
}
if offset:
body["offset"] = offset
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
all_points.extend(batch)
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
if not all_points:
return 0
point_ids = [point["id"] for point in all_points]
# Use set_payload (no vector write)
for i in range(0, len(point_ids), BATCH_SIZE):
batch_ids = point_ids[i : i + BATCH_SIZE]
set_points_payload(
{"identity_id": identity_id, "identity_uuid": identity_uuid}, batch_ids
)
print(
f"[QDRANT] Updated {len(point_ids)} face points with identity_id={identity_id}"
)
return len(point_ids)