feat: port face clustering to Rust (rust_face_cluster) with A/B gating

- rust_face_cluster: seed-leader + agglomerative clustering port of
  fast_face_clustering_processor.py (Qdrant _faces scroll, trace aggregation,
  auto speaker bind, strict 2dp rounding parity)
- A/B verified vs Python on same Qdrant snapshot: both methods match on
  cluster membership/trace_id/confidence (leader + agglomerative)
- face_clustering.rs: USE_RUST_PROCESSORS switch with Python fallback
- executor.rs: run_rust_with_output_idx_and_frames (+ QDRANT env passthrough)
- appearance/pose: re-use rust runner path (previous migration)
- verify_face_cluster.py / verify_pose.py / verify_appearance.py: A/B harness
This commit is contained in:
Accusys
2026-09-16 21:50:07 +08:00
parent 362a735a91
commit e25c279eeb
14 changed files with 4473 additions and 27 deletions
+2
View File
@@ -0,0 +1,2 @@
/target
Cargo.lock.orig
+1757
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "rust_processors"
version = "0.1.0"
edition = "2021"
description = "Rust replacement for Python processor scripts (standalone binaries)"
[[bin]]
name = "rust_appearance"
path = "src/bin/rust_appearance.rs"
[[bin]]
name = "rust_pose"
path = "src/bin/rust_pose.rs"
[[bin]]
name = "rust_face_cluster"
path = "src/bin/rust_face_cluster.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
clap = { version = "4", features = ["derive"] }
image = "0.25"
ureq = { version = "2", features = ["json"] }
[profile.release]
opt-level = 2
@@ -0,0 +1,817 @@
use std::process::Command;
use image::GenericImageView;
use clap::Parser;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Parser)]
#[command(name = "rust_appearance", about = "Appearance Processor (Rust port of appearance_processor.py)")]
struct Args {
video_path: std::path::PathBuf,
pose_json: std::path::PathBuf,
output_path: std::path::PathBuf,
#[arg(short = 'u', long = "uuid", default_value = "")]
uuid: String,
#[arg(long = "frames", default_value = None)]
frames: Option<String>,
}
#[derive(Deserialize)]
struct Keypoint {
name: String,
x: f64,
y: f64,
#[serde(default = "default_conf")]
confidence: f64,
}
fn default_conf() -> f64 {
1.0
}
#[derive(Deserialize, Clone)]
#[serde(default)]
struct BBox {
x: f64,
y: f64,
width: f64,
height: f64,
}
impl Default for BBox {
fn default() -> Self {
Self { x: 0.0, y: 0.0, width: 0.0, height: 0.0 }
}
}
#[derive(Deserialize)]
struct Person {
bbox: BBox,
#[serde(default)]
keypoints: Vec<Keypoint>,
}
#[derive(Deserialize)]
struct PoseFrame {
frame: i64,
#[serde(default)]
timestamp: Option<f64>,
#[serde(default)]
persons: Vec<Person>,
}
#[derive(Deserialize)]
struct PoseData {
#[serde(default)]
fps: f64,
#[serde(default)]
frames: Vec<PoseFrame>,
}
#[derive(Deserialize)]
struct FaceData {
#[serde(default)]
frames: Vec<FaceFrame>,
}
#[derive(Deserialize)]
struct FaceFrame {
frame: i64,
#[serde(default)]
faces: Vec<FaceBBox>,
}
#[derive(Deserialize, Clone)]
struct FaceBBox {
x: f64,
y: f64,
width: f64,
height: f64,
}
// Output schema (matches Python appearance_processor.py)
#[derive(Serialize)]
struct Output {
frame_count: u64,
fps: f64,
frames: Vec<OutputFrame>,
}
#[derive(Serialize)]
struct OutputFrame {
frame: i64,
timestamp: f64,
persons: Vec<OutputPerson>,
}
#[derive(Serialize)]
struct OutputPerson {
person_id: usize,
// Python emits the pose.json bbox verbatim (raw numbers). Keep original JSON to match
// integer/float representation exactly.
bbox: Value,
facing: String,
body_parts: Vec<BodyPart>,
dominant_colors: Vec<Vec<f64>>,
hsv_histogram: Vec<Vec<f64>>,
}
#[derive(Serialize)]
struct BodyPart {
name: String,
bbox: OBBox,
hsv_histogram: Vec<Vec<f64>>,
dominant_colors: Vec<Vec<f64>>,
}
#[derive(Serialize)]
struct OBBox {
x: f64,
y: f64,
width: f64,
height: f64,
}
fn get_kp<'a>(keypoints: &'a [Keypoint], name: &str) -> Option<&'a Keypoint> {
keypoints.iter().find(|kp| kp.name == name)
}
fn determine_facing(keypoints: &[Keypoint]) -> String {
let nose = get_kp(keypoints, "nose");
let l_shoulder = get_kp(keypoints, "left_shoulder");
let r_shoulder = get_kp(keypoints, "right_shoulder");
if nose.is_some_and(|n| n.confidence > 0.5) {
return "front".to_string();
}
let sh_vis = [l_shoulder, r_shoulder]
.iter()
.filter(|s| s.is_some_and(|k| k.confidence > 0.5))
.count();
if sh_vis >= 2 && nose.is_none_or(|n| n.confidence < 0.2) {
return "back".to_string();
}
if sh_vis >= 1 {
return "profile".to_string();
}
"unknown".to_string()
}
fn compute_body_regions(
keypoints: &[Keypoint],
face: &FaceBBox,
) -> Vec<(String, BBox)> {
let fx = face.x;
let fy = face.y;
let fw = face.width;
let fh = face.height;
let face_cx = fx + fw / 2.0;
let nose = get_kp(keypoints, "nose");
let ls = get_kp(keypoints, "left_shoulder");
let rs = get_kp(keypoints, "right_shoulder");
let lw = get_kp(keypoints, "left_wrist");
let rw = get_kp(keypoints, "right_wrist");
let lh = get_kp(keypoints, "left_hip");
let rh = get_kp(keypoints, "right_hip");
let la = get_kp(keypoints, "left_ankle");
let ra = get_kp(keypoints, "right_ankle");
let kp_nose = nose.map(|n| (n.x, n.y)).unwrap_or((face_cx, fy + fh * 0.5));
let kp_sh_l = ls.map(|s| s.x).unwrap_or(face_cx - fw * 1.5);
let kp_sh_r = rs.map(|s| s.x).unwrap_or(face_cx + fw * 1.5);
let kp_sh_mid_x = (kp_sh_l + kp_sh_r) / 2.0;
let kp_sh_mid_y = if ls.is_some() && rs.is_some() {
(ls.unwrap().y + rs.unwrap().y) / 2.0
} else {
fy + fh + fh * 0.3
};
let kp_hip_y = if lh.is_some() && rh.is_some() {
(lh.unwrap().y + rh.unwrap().y) / 2.0
} else {
kp_sh_mid_y + fw * 2.0
};
let kp_hip_l = lh.map(|x| x.x).unwrap_or(kp_sh_mid_x - fw * 1.2);
let kp_hip_r = rh.map(|x| x.x).unwrap_or(kp_sh_mid_x + fw * 1.2);
// Ordered to match Python dict insertion order (head → neck → upper → lower → hand → foot)
let mut ordered_names: Vec<&str> = vec![
"head",
"neck",
"front_upper_body",
"back_upper_body",
"front_lower_body",
"back_lower_body",
"left_hand",
"right_hand",
"left_foot",
"right_foot",
];
let mut regions: Vec<(String, BBox)> = Vec::new();
let head_w = fw * 1.6;
let head_h = fh * 1.5;
regions.push(("head".to_string(), BBox {
x: kp_nose.0 - head_w / 2.0,
y: kp_nose.1 - head_h * 0.5,
width: head_w,
height: head_h,
}));
let neck_w = fw * 1.5;
regions.push(("neck".to_string(), BBox {
x: kp_sh_mid_x - neck_w / 2.0,
y: kp_nose.1 + fh * 0.4,
width: neck_w,
height: (kp_sh_mid_y - kp_nose.1 - fh * 0.4).max(fh * 0.3),
}));
let ub_w = ((kp_sh_r - kp_sh_l).abs() * 1.3).max(fw * 3.0);
let ub_h = fh * 3.0;
let upper = BBox {
x: kp_sh_mid_x - ub_w / 2.0,
y: kp_sh_mid_y,
width: ub_w,
height: ub_h,
};
regions.push(("front_upper_body".to_string(), upper.clone()));
regions.push(("back_upper_body".to_string(), upper));
let lb_w = ((kp_hip_r - kp_hip_l).abs() * 1.3).max(fw * 3.5);
let lb_h = fh * 3.0;
let lower = BBox {
x: kp_sh_mid_x - lb_w / 2.0,
y: kp_hip_y,
width: lb_w,
height: lb_h,
};
regions.push(("front_lower_body".to_string(), lower.clone()));
regions.push(("back_lower_body".to_string(), lower));
// hands: wrist-aligned
let hs = fw * 1.0;
let left_hand = if lw.is_some_and(|k| k.confidence > 0.3) {
BBox {
x: lw.unwrap().x - hs / 2.0,
y: lw.unwrap().y - hs / 2.0,
width: hs,
height: hs,
}
} else {
BBox {
x: kp_sh_l - hs,
y: kp_sh_mid_y + fh * 0.5,
width: hs,
height: hs,
}
};
let right_hand = if rw.is_some_and(|k| k.confidence > 0.3) {
BBox {
x: rw.unwrap().x - hs / 2.0,
y: rw.unwrap().y - hs / 2.0,
width: hs,
height: hs,
}
} else {
BBox {
x: kp_sh_r,
y: kp_sh_mid_y + fh * 0.5,
width: hs,
height: hs,
}
};
regions.push(("left_hand".to_string(), left_hand));
regions.push(("right_hand".to_string(), right_hand));
// feet: ankle-aligned
let fs = fw * 1.0;
let left_foot = if la.is_some_and(|k| k.confidence > 0.3) {
BBox {
x: la.unwrap().x - fs / 2.0,
y: la.unwrap().y,
width: fs,
height: fs * 0.75,
}
} else {
BBox {
x: kp_sh_mid_x - fw * 1.0,
y: kp_hip_y + fh * 2.5,
width: fs,
height: fs * 0.75,
}
};
let right_foot = if ra.is_some_and(|k| k.confidence > 0.3) {
BBox {
x: ra.unwrap().x - fs / 2.0,
y: ra.unwrap().y,
width: fs,
height: fs * 0.75,
}
} else {
BBox {
x: kp_sh_mid_x + fw * 1.0 - fs,
y: kp_hip_y + fh * 2.5,
width: fs,
height: fs * 0.75,
}
};
regions.push(("left_foot".to_string(), left_foot));
regions.push(("right_foot".to_string(), right_foot));
let _ = &mut ordered_names;
// Extrapolate each bbox outward
let margins: [(&str, f64); 10] = [
("head", 0.10),
("neck", 0.15),
("front_upper_body", 0.20),
("back_upper_body", 0.20),
("front_lower_body", 0.15),
("back_lower_body", 0.15),
("left_hand", 0.25),
("right_hand", 0.25),
("left_foot", 0.20),
("right_foot", 0.20),
];
let margin: std::collections::HashMap<&str, f64> = margins.iter().copied().collect();
regions
.into_iter()
.map(|(name, rb)| {
let m = margin.get(name.as_str()).copied().unwrap_or(0.15);
let dx = (rb.width * m) as i64;
let dy = (rb.height * m) as i64;
(
name.clone(),
BBox {
x: rb.x - dx as f64,
y: rb.y - dy as f64,
width: rb.width + dx as f64 * 2.0,
height: rb.height + dy as f64 * 2.0,
},
)
})
.collect()
}
fn filter_by_facing(regions: Vec<(String, BBox)>, facing: &str) -> Vec<(String, BBox)> {
let (keep_front, keep_back) = match facing {
"front" => (true, false),
"back" => (false, true),
_ => (true, true),
};
regions
.into_iter()
.filter(|(name, _)| {
if name == "front_upper_body" || name == "front_lower_body" {
keep_front
} else if name == "back_upper_body" || name == "back_lower_body" {
keep_back
} else {
true
}
})
.collect()
}
fn safe_roi(
frame: &image::RgbImage,
x: f64,
y: f64,
w: f64,
h: f64,
) -> Option<image::RgbImage> {
if w <= 0.0 || h <= 0.0 {
return None;
}
let x1 = (x.max(0.0)) as u32;
let y1 = (y.max(0.0)) as u32;
let x2 = ((x + w).min(frame.width() as f64)) as u32;
let y2 = ((y + h).min(frame.height() as f64)) as u32;
if x2 <= x1 || y2 <= y1 {
return None;
}
frame.try_view(x1, y1, x2 - x1, y2 - y1).ok().map(|v| v.to_image())
}
// Deterministic k-means (k=5, attempts=10, iter=10, eps=1.0) on HSV pixels — seed fixed
// so output is reproducible (Python cv2.kmeans uses KMEANS_RANDOM_CENTERS: non-deterministic).
// A/B gate relaxes dominant color comparison accordingly.
fn kmeans_dominant(pixels: &[[f64; 3]], k: usize, attempts: usize) -> Vec<[f64; 3]> {
if pixels.is_empty() {
return vec![];
}
if pixels.len() < 5 {
// Python: fewer than 5 pixels → mean as single dominant color
let mut mean = [0.0; 3];
for p in pixels {
for i in 0..3 {
mean[i] += p[i];
}
}
for i in 0..3 {
mean[i] /= pixels.len() as f64;
}
return vec![mean];
}
let mut best: Option<(f64, Vec<[f64; 3]>)> = None;
for seed in 0..attempts as u64 {
let mut centers = init_centers(pixels, k, seed);
for _ in 0..10 {
let (labels, _counts) = assign(pixels, &centers);
let new_centers = recompute(pixels, &labels, k);
let max_shift = centers
.iter()
.zip(new_centers.iter())
.map(|(a, b)| dist(a, b))
.fold(0.0f64, f64::max);
centers = new_centers;
if max_shift <= 1.0 {
break;
}
}
let (labels, _counts) = assign(pixels, &centers);
let sse: f64 = pixels
.iter()
.zip(labels.iter())
.map(|(p, &l)| dist(p, &centers[l]))
.sum();
if best.as_ref().map(|(e, _)| sse < *e).unwrap_or(true) {
best = Some((sse, centers));
}
}
let (_, centers) = best.unwrap();
let (labels, _counts) = assign(pixels, &centers);
let mut counts = vec![0usize; k];
for &l in &labels {
counts[l] += 1;
}
// Sort centers by cluster count descending (Python: centers[np.argsort(-counts)[:5]])
let mut idx: Vec<usize> = (0..k).collect();
idx.sort_by(|&a, &b| counts[b].cmp(&counts[a]));
idx.iter().map(|&i| centers[i]).collect()
}
fn dist(a: &[f64; 3], b: &[f64; 3]) -> f64 {
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
}
fn init_centers(pixels: &[[f64; 3]], k: usize, seed: u64) -> Vec<[f64; 3]> {
let mut rng = SplitMix64::new(seed);
let n = pixels.len();
let mut chosen = Vec::with_capacity(k);
let mut used = std::collections::BTreeSet::new();
while chosen.len() < k {
let i = (rng.next_u64() % n as u64) as usize;
if used.insert(i) {
chosen.push(pixels[i]);
}
}
chosen
}
fn assign(pixels: &[[f64; 3]], centers: &[[f64; 3]]) -> (Vec<usize>, Vec<usize>) {
let mut labels = Vec::with_capacity(pixels.len());
let mut counts = vec![0usize; centers.len()];
for p in pixels {
let mut best_i = 0;
let mut best_d = f64::INFINITY;
for (i, c) in centers.iter().enumerate() {
let d = dist(p, c);
if d < best_d {
best_d = d;
best_i = i;
}
}
labels.push(best_i);
counts[best_i] += 1;
}
(labels, counts)
}
fn recompute(pixels: &[[f64; 3]], labels: &[usize], k: usize) -> Vec<[f64; 3]> {
let mut sums = vec![[0.0; 3]; k];
let mut counts = vec![0usize; k];
for (p, &l) in pixels.iter().zip(labels.iter()) {
for i in 0..3 {
sums[l][i] += p[i];
}
counts[l] += 1;
}
let mut centers = vec![[0.0; 3]; k];
for i in 0..k {
if counts[i] > 0 {
for j in 0..3 {
centers[i][j] = sums[i][j] / counts[i] as f64;
}
}
}
centers
}
/// SplitMix64 PRNG (deterministic).
struct SplitMix64 {
state: u64,
}
impl SplitMix64 {
fn new(seed: u64) -> Self {
Self { state: seed }
}
fn next_u64(&mut self) -> u64 {
self.state = self.state.wrapping_add(0x9E3779B97F4A7C15);
let mut z = self.state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
z ^ (z >> 31)
}
}
fn extract_color(roi: &image::RgbImage) -> Option<(Vec<Vec<f64>>, Vec<Vec<f64>>)> {
if roi.width() < 2 || roi.height() < 2 {
return None;
}
let mut h_hist = vec![0.0f64; 30];
let mut s_hist = vec![0.0f64; 32];
let mut v_hist = vec![0.0f64; 32];
let mut pixels: Vec<[f64; 3]> = Vec::new();
for px in roi.pixels() {
let r = px[0] as f64;
let g = px[1] as f64;
let b = px[2] as f64;
// OpenCV BGR2HSV and RGB2HSV produce the same HSV for the same underlying color
// triple; PNG stores (R,G,B), so identical to cv2 frame interpreted as BGR.
let (h, s, v) = bgr2hsv(r, g, b);
let hb = ((h / 6.0).floor() as usize).min(29);
let sb = ((s / 8.0).floor() as usize).min(31);
let vb = ((v / 8.0).floor() as usize).min(31);
h_hist[hb] += 1.0;
s_hist[sb] += 1.0;
v_hist[vb] += 1.0;
pixels.push([h, s, v]);
}
let hs = h_hist.iter().sum::<f64>().max(1.0);
let ss = s_hist.iter().sum::<f64>().max(1.0);
let vs = v_hist.iter().sum::<f64>().max(1.0);
let h_norm: Vec<f64> = h_hist.iter().map(|x| x / hs).collect();
let s_norm: Vec<f64> = s_hist.iter().map(|x| x / ss).collect();
let v_norm: Vec<f64> = v_hist.iter().map(|x| x / vs).collect();
// Subsample for kmeans if too many pixels (cv2 uses all but is SIMD-optimized)
let kmeans_pixels = if pixels.len() > 10000 {
let step = pixels.len() / 10000;
pixels.iter().step_by(step).copied().collect::<Vec<_>>()
} else {
pixels.clone()
};
let dominant = kmeans_dominant(&kmeans_pixels, 5, 10);
let dominant: Vec<Vec<f64>> = dominant.iter().map(|d| d.to_vec()).collect();
Some((vec![h_norm, s_norm, v_norm], dominant))
}
/// OpenCV 8-bit BGR→HSV. H in [0,180], S and V in [0,255].
fn bgr2hsv(r: f64, g: f64, b: f64) -> (f64, f64, f64) {
let v = r.max(g).max(b);
let mn = r.min(g).min(b);
let delta = v - mn;
if delta == 0.0 {
return (0.0, 0.0, v);
}
let s = delta * 255.0 / v;
let mut h;
if v == r {
h = 60.0 * (g - b) / delta;
} else if v == g {
h = 60.0 * (2.0 + (b - r) / delta);
} else {
h = 60.0 * (4.0 + (r - g) / delta);
}
if h < 0.0 {
h += 360.0;
}
(h / 2.0, s, v)
}
/// Extract only the needed frames in one ffmpeg pass. Builds a `select` filter expression
/// compressing contiguous frame ranges into `between(n,a,b)` terms.
fn extract_frames(
video_path: &std::path::Path,
needed: &[i64],
out_tmp: &std::path::Path,
) -> Result<Vec<std::path::PathBuf>, String> {
if needed.is_empty() {
return Ok(vec![]);
}
std::fs::create_dir_all(out_tmp).map_err(|e| e.to_string())?;
// Compact runs
let mut terms: Vec<String> = Vec::new();
let mut i = 0usize;
while i < needed.len() {
let start = needed[i];
let mut end = start;
let mut j = i;
while j + 1 < needed.len() && needed[j + 1] == end + 1 {
end += 1;
j += 1;
}
if start == end {
terms.push(format!("eq(n\\,{})", start));
} else {
terms.push(format!("between(n\\,{}\\,{})", start, end));
}
i = j + 1;
}
let select_expr = terms.join("+");
let filter = format!("select='{}'", select_expr);
let out_pattern = out_tmp.join("frame_%05d.png");
let status = Command::new("ffmpeg")
.arg("-v")
.arg("error")
.arg("-i")
.arg(video_path)
.arg("-vf")
.arg(&filter)
.arg("-vsync")
.arg("0")
.arg("-f")
.arg("image2")
.arg(&out_pattern)
.status()
.map_err(|e| format!("ffmpeg launch failed: {e}"))?;
if !status.success() {
return Err(format!("ffmpeg failed with status {status}"));
}
// Output files are named frame_00001.png ... in the same order as the needed list.
let mut paths = Vec::with_capacity(needed.len());
for (i, _) in needed.iter().enumerate() {
let p = out_tmp.join(format!("frame_{:05}.png", i + 1));
if !p.exists() {
return Err(format!("ffmpeg expected output {p:?} missing"));
}
paths.push(p);
}
Ok(paths)
}
fn main() {
let args = Args::parse();
let pose_str = std::fs::read_to_string(&args.pose_json).expect("Failed to read pose json");
let pose: PoseData = serde_json::from_str(&pose_str).expect("Failed to parse pose json");
// Load face.json for anchor bbox (same directory as pose_json)
let face_path =
std::path::PathBuf::from(args.pose_json.to_string_lossy().replace(".pose.json", ".face.json"));
let mut face_by_frame: std::collections::BTreeMap<i64, FaceBBox> = std::collections::BTreeMap::new();
if face_path.exists() {
let face_str = std::fs::read_to_string(&face_path).expect("Failed to read face json");
if let Ok(face_data) = serde_json::from_str::<FaceData>(&face_str) {
for fframe in face_data.frames {
if let Some(first) = fframe.faces.first() {
face_by_frame.insert(fframe.frame, first.clone());
}
}
}
}
let fps = if pose.fps > 0.0 { pose.fps } else { 30.0 };
// Collect needed frames (pose frames that have persons), sorted for ffmpeg select
let mut needed: Vec<i64> = pose
.frames
.iter()
.filter(|f| !f.persons.is_empty())
.map(|f| f.frame)
.collect();
needed.sort_unstable();
// Extract frames
let out_tmp = args.output_path.with_extension("frames_tmp");
let frame_paths = match extract_frames(&args.video_path, &needed, &out_tmp) {
Ok(p) => p,
Err(e) => {
eprintln!("[APPEARANCE] frame extraction failed: {e}");
std::process::exit(1);
}
};
// Map frame number → extracted file
let frame_file: std::collections::BTreeMap<i64, std::path::PathBuf> = needed
.iter()
.enumerate()
.map(|(i, &f)| (f, frame_paths[i].clone()))
.collect();
let mut frames_out: Vec<OutputFrame> = Vec::new();
for pose_frame in pose.frames.iter().filter(|f| !f.persons.is_empty()) {
let frame_num = pose_frame.frame;
let frame_img = match frame_file.get(&frame_num) {
Some(p) => match image::open(p) {
Ok(img) => img.to_rgb8(),
Err(e) => {
eprintln!("[APPEARANCE] failed to decode {p:?}: {e}");
continue;
}
},
None => continue,
};
// Get face bbox for this frame (Python: face_by_frame.get(frame_num, persons[0].bbox))
let fallback = pose_frame.persons[0].bbox.clone();
let face_bbox = face_by_frame
.get(&frame_num)
.cloned()
.unwrap_or_else(|| FaceBBox {
x: fallback.x,
y: fallback.y,
width: fallback.width,
height: fallback.height,
});
let mut frame_persons = Vec::new();
for (pid, person) in pose_frame.persons.iter().enumerate() {
let keypoints = &person.keypoints;
if keypoints.is_empty() {
continue;
}
let bbox = &person.bbox;
let facing = determine_facing(keypoints);
let all_regions = compute_body_regions(keypoints, &face_bbox);
let regions = filter_by_facing(all_regions, &facing);
let mut body_parts = Vec::new();
for (name, rb) in regions {
let roi = safe_roi(&frame_img, rb.x, rb.y, rb.width, rb.height);
if let Some(roi_img) = roi {
if let Some((hist, colors)) = extract_color(&roi_img) {
body_parts.push(BodyPart {
name,
bbox: OBBox {
x: rb.x,
y: rb.y,
width: rb.width,
height: rb.height,
},
hsv_histogram: hist,
dominant_colors: colors,
});
}
}
}
let mut full: Option<(Vec<Vec<f64>>, Vec<Vec<f64>>)> = None;
if bbox.width > 0.0 && bbox.height > 0.0 {
let full_roi = safe_roi(&frame_img, bbox.x, bbox.y, bbox.width, bbox.height);
if let Some(f) = full_roi {
full = extract_color(&f);
}
}
let empty_hist = vec![vec![], vec![], vec![]];
let person_bbox_json = serde_json::json!({
"x": bbox.x,
"y": bbox.y,
"width": bbox.width,
"height": bbox.height,
});
frame_persons.push(OutputPerson {
person_id: pid,
bbox: person_bbox_json,
facing,
body_parts,
dominant_colors: full.as_ref().map(|(_, c)| c.clone()).unwrap_or_default(),
hsv_histogram: full.as_ref().map(|(h, _)| h.clone()).unwrap_or(empty_hist),
});
}
if !frame_persons.is_empty() {
frames_out.push(OutputFrame {
frame: frame_num,
timestamp: pose_frame.timestamp.unwrap_or(frame_num as f64 / fps),
persons: frame_persons,
});
}
}
let _ = std::fs::remove_dir_all(&out_tmp);
let output = Output {
frame_count: frames_out.len() as u64,
fps,
frames: frames_out,
};
let json_str = serde_json::to_string_pretty(&output).expect("serialize failed");
std::fs::write(&args.output_path, json_str).expect("Failed to write output");
eprintln!("[APPEARANCE] Done: {} frames", output.frame_count);
}
@@ -0,0 +1,780 @@
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::Duration;
use clap::Parser;
use serde_json::{json, Value};
/// Face Clustering Processor (Rust port of fast_face_clustering_processor.py)
///
/// Loads face embeddings from Qdrant `_faces`, groups by trace_id, computes
/// weighted-average embeddings per trace, then clusters traces with either the
/// seed-leader method (default, deterministic) or average-linkage agglomerative.
#[derive(Parser)]
#[command(name = "rust_face_cluster", about = "Face Clustering Processor (Rust port)")]
struct Args {
video_path: String,
output_path: PathBuf,
#[arg(short = 'u', long = "uuid", default_value = "")]
uuid: String,
#[arg(long = "frames", default_value = None)]
frames: Option<String>,
#[arg(long = "method", default_value = "leader")]
method: String,
#[arg(long = "threshold", default_value_t = 0.35)]
threshold: f64,
#[arg(long = "force")]
force: bool,
}
const CONFIDENCE_THRESHOLD: f64 = 0.5;
const DEFAULT_QDRANT_URL: &str = "http://localhost:6333";
const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200";
#[derive(Clone)]
struct FacePoint {
payload: Value,
vector: Vec<f64>,
}
fn env_var(name: &str, default: &str) -> String {
std::env::var(name).unwrap_or_else(|_| default.to_string())
}
/// Mimic Python's `round(x, n)` (banker's rounding / round-half-to-even).
fn round_digits(x: f64, digits: i32) -> f64 {
let factor = 10_f64.powi(digits);
(x * factor).round_ties_even() / factor
}
/// Recursively round all float values to 2 decimals (Python `round_json_numbers`).
fn round_json(value: Value) -> Value {
match value {
Value::Number(n) => {
if n.is_f64() {
let f = n.as_f64().unwrap_or(0.0);
let r = round_digits(f, 2);
serde_json::Number::from_f64(r)
.map(Value::Number)
.unwrap_or(Value::Number(n))
} else {
Value::Number(n)
}
}
Value::Array(items) => Value::Array(items.into_iter().map(round_json).collect()),
Value::Object(map) => {
Value::Object(map.into_iter().map(|(k, v)| (k, round_json(v))).collect())
}
other => other,
}
}
fn write_empty_output(status: &str, file_uuid: &str, output_path: &std::path::Path) {
let output_data = json!({
"status": status,
"file_uuid": file_uuid,
"clusters": [],
"frames": [],
});
let text = serde_json::to_string_pretty(&output_data).unwrap_or_default();
let _ = std::fs::write(output_path, text);
eprintln!("Wrote empty output ({}) to {}", status, output_path.display());
}
/// Scroll all Qdrant `_faces` points (payload + vector) for a file via HTTP.
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);
let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url);
let mut all_points: Vec<FacePoint> = Vec::new();
let mut offset: Option<Value> = None;
loop {
let mut body = json!({
"limit": 10000,
"with_payload": true,
"with_vector": true,
"filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]},
});
if let Some(ref off) = offset {
body["offset"] = off.clone();
}
let resp = ureq::post(&scroll_url)
.set("api-key", &qdrant_api_key)
.timeout(Duration::from_secs(60))
.send_json(body);
match resp {
Ok(r) => {
let data: Value = r.into_json().unwrap_or(Value::Null);
let points = data
.pointer("/result/points")
.and_then(|p| p.as_array())
.cloned()
.unwrap_or_default();
for p in points {
let payload = p.get("payload").cloned().unwrap_or(Value::Null);
let vector = p
.get("vector")
.and_then(|v| v.as_array())
.map(|v| {
v.iter()
.filter_map(|x| x.as_f64())
.collect::<Vec<f64>>()
})
.unwrap_or_default();
all_points.push(FacePoint { payload, vector });
}
let next = data.pointer("/result/next_page_offset").cloned();
match next {
Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)),
Some(Value::Number(_)) => break,
Some(Value::Null) | None => break,
other => {
offset = other;
}
}
}
Err(e) => {
eprintln!("Qdrant scroll error: {}", e);
break;
}
}
}
eprintln!("Loaded {} points from Qdrant _faces", all_points.len());
all_points
}
fn dot(a: &[f64], b: &[f64]) -> f64 {
a.iter().zip(b).map(|(x, y)| x * y).sum()
}
fn norm(v: &[f64]) -> f64 {
v.iter().map(|x| x * x).sum::<f64>().sqrt()
}
fn cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
let n1 = norm(a);
let n2 = norm(b);
if n1 > 0.0 && n2 > 0.0 {
dot(a, b) / (n1 * n2)
} else {
-1.0
}
}
/// Weighted-average embedding per trace + pairs (cluster_by_trace).
/// Returns (trace_embeddings: BTreeMap<trace_id, Vec<f64>>).
fn cluster_by_trace(
points: &[FacePoint],
min_faces_per_trace: usize,
confidence_threshold: f64,
) -> BTreeMap<i64, Vec<f64>> {
let high_conf: Vec<&FacePoint> = points
.iter()
.filter(|p| {
p.payload
.get("confidence")
.and_then(|c| c.as_f64())
.unwrap_or(0.0)
>= confidence_threshold
})
.collect();
eprintln!(
"[FILTER] {}/{} faces pass confidence >= {}",
high_conf.len(),
points.len(),
confidence_threshold
);
let mut traces: BTreeMap<i64, Vec<&FacePoint>> = BTreeMap::new();
for p in &high_conf {
if let Some(trace_id) = p.payload.get("trace_id").and_then(|t| t.as_i64()) {
if trace_id >= 0 {
traces.entry(trace_id).or_default().push(p);
}
}
}
eprintln!("[TRACE] Found {} unique traces", traces.len());
let mut trace_embeddings: BTreeMap<i64, Vec<f64>> = BTreeMap::new();
for (trace_id, trace_points) in traces.iter() {
if trace_points.len() < min_faces_per_trace {
continue;
}
let mut embeddings: Vec<&[f64]> = Vec::new();
let mut weights: Vec<f64> = Vec::new();
for p in trace_points {
embeddings.push(&p.vector);
weights.push(p.payload.get("confidence").and_then(|c| c.as_f64()).unwrap_or(1.0));
}
let weight_sum: f64 = weights.iter().sum();
for w in weights.iter_mut() {
*w /= weight_sum;
}
let dim = embeddings.first().map(|e| e.len()).unwrap_or(0);
let mut avg = vec![0.0_f64; dim];
for (e, w) in embeddings.iter().zip(weights.iter()) {
for (i, x) in e.iter().enumerate() {
avg[i] += x * w;
}
}
let n = norm(&avg);
if n > 0.0 {
for x in avg.iter_mut() {
*x /= n;
}
}
trace_embeddings.insert(*trace_id, avg);
}
eprintln!(
"[TRACE] {} traces with >= {} faces",
trace_embeddings.len(),
min_faces_per_trace
);
trace_embeddings
}
/// Seed-leader clustering with incremental mean centroids (Python default method).
/// Returns (trace_to_person, trace_similarities).
fn seed_leader_cluster(
trace_embeddings: &BTreeMap<i64, Vec<f64>>,
threshold: f64,
) -> (BTreeMap<i64, i64>, BTreeMap<i64, f64>) {
let trace_ids: Vec<&i64> = trace_embeddings.keys().collect();
let n_traces = trace_ids.len();
if n_traces == 0 {
return (BTreeMap::new(), BTreeMap::new());
}
if n_traces == 1 {
let tid = *trace_ids[0];
let mut tm = BTreeMap::new();
tm.insert(tid, 0);
let mut sm = BTreeMap::new();
sm.insert(tid, 1.0);
return (tm, sm);
}
let sim_threshold = 1.0 - threshold;
let mut persons: Vec<(Vec<f64>, Vec<i64>)> = Vec::new(); // (centroid, member_trace_ids)
let mut trace_similarities: BTreeMap<i64, f64> = BTreeMap::new();
for tid in trace_ids {
let centroid = trace_embeddings[tid].clone();
if persons.is_empty() {
persons.push((centroid, vec![*tid]));
trace_similarities.insert(*tid, 1.0);
continue;
}
let mut best_sim = -1.0;
let mut best_person_idx: Option<usize> = None;
for (idx, person) in persons.iter().enumerate() {
let sim = cosine_similarity(&centroid, &person.0);
if sim > best_sim {
best_sim = sim;
best_person_idx = Some(idx);
}
}
match best_person_idx {
Some(idx) if best_sim >= sim_threshold => {
persons[idx].1.push(*tid);
trace_similarities.insert(*tid, best_sim);
let members: Vec<Vec<f64>> = persons[idx]
.1
.iter()
.map(|m| trace_embeddings[m].clone())
.collect();
let dim = members[0].len();
let mut mean = vec![0.0_f64; dim];
for m in &members {
for (i, x) in m.iter().enumerate() {
mean[i] += x;
}
}
let cnt = members.len() as f64;
for x in mean.iter_mut() {
*x /= cnt;
}
persons[idx].0 = mean;
}
_ => {
persons.push((centroid, vec![*tid]));
trace_similarities.insert(*tid, 1.0);
}
}
}
let mut trace_to_person: BTreeMap<i64, i64> = BTreeMap::new();
for (person_label, person) in persons.iter().enumerate() {
for m in &person.1 {
trace_to_person.insert(*m, person_label as i64);
}
}
eprintln!("[CLUSTER] Seed-leader detected {} unique persons", persons.len());
(trace_to_person, trace_similarities)
}
/// Average-linkage agglomerative clustering (sklearn AgglomerativeClustering
/// with metric="cosine", linkage="average", distance_threshold=threshold).
/// Trace similarity is a 1.0 placeholder, matching the Python script.
fn agglomerative_cluster(
trace_embeddings: &BTreeMap<i64, Vec<f64>>,
threshold: f64,
) -> (BTreeMap<i64, i64>, BTreeMap<i64, f64>) {
let trace_ids: Vec<&i64> = trace_embeddings.keys().collect();
let n = trace_ids.len();
if n == 0 {
return (BTreeMap::new(), BTreeMap::new());
}
if n == 1 {
let mut tm = BTreeMap::new();
tm.insert(*trace_ids[0], 0);
let mut sm = BTreeMap::new();
sm.insert(*trace_ids[0], 1.0);
return (tm, sm);
}
// distance matrix: 1 - cosine
let mut dist = vec![vec![0.0_f64; n]; n];
for i in 0..n {
for j in (i + 1)..n {
let d = 1.0 - cosine_similarity(&trace_embeddings[&trace_ids[i]], &trace_embeddings[&trace_ids[j]]);
dist[i][j] = d;
dist[j][i] = d;
}
}
// Each cluster: set of member indices. Merges happen in-place: targets stay
// within 0..n, merged-away clusters are cleared + marked inactive.
let mut clusters: Vec<Vec<usize>> = (0..n).map(|i| vec![i]).collect();
let mut active = vec![true; n];
loop {
// Find pair (a, b) with min distance among active clusters (average linkage).
// Given the input is trace means, average linkage of members = average of
// pairwise distances. We maintain dist as the average linkage between clusters.
let mut best_d = f64::INFINITY;
let mut best_pair: Option<(usize, usize)> = None;
for a in 0..n {
if !active[a] || clusters[a].is_empty() {
continue;
}
for b in (a + 1)..n {
if !active[b] || clusters[b].is_empty() {
continue;
}
if dist[a][b] < best_d {
best_d = dist[a][b];
best_pair = Some((a, b));
}
}
}
let Some((a, b)) = best_pair else { break };
if best_d > threshold {
break;
}
// Merge b into a.
let mut merged = clusters[a].clone();
merged.extend_from_slice(&clusters[b]);
clusters[a] = merged;
clusters[b].clear();
active[b] = false;
// Update average-linkage distances from merged cluster (a) to all others.
// Recompute via members is exact for average linkage (UPGMA).
for k in 0..n {
if !active[k] || k == a || clusters[k].is_empty() {
continue;
}
let mut sum = 0.0;
let mut cnt = 0;
for &mi in &clusters[a] {
for &mk in &clusters[k] {
sum += 1.0 - cosine_similarity(
&trace_embeddings[&trace_ids[mi]],
&trace_embeddings[&trace_ids[mk]],
);
cnt += 1;
}
}
dist[a][k] = if cnt > 0 { sum / cnt as f64 } else { f64::INFINITY };
dist[k][a] = dist[a][k];
}
}
let mut trace_to_person: BTreeMap<i64, i64> = BTreeMap::new();
let mut label = 0;
for cid in 0..n {
if active[cid] && !clusters[cid].is_empty() {
for &mi in &clusters[cid] {
trace_to_person.insert(*trace_ids[mi], label);
}
label += 1;
}
}
let mut trace_similarities: BTreeMap<i64, f64> = BTreeMap::new();
for tid in trace_ids.iter() {
trace_similarities.insert(**tid, 1.0);
}
eprintln!("[CLUSTER] Agglomerative detected {} unique persons", label);
(trace_to_person, trace_similarities)
}
fn main() {
let args = Args::parse();
let uuid = if args.uuid.is_empty() {
std::path::Path::new(&args.video_path)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("quick_preview")
.to_string()
} else {
args.uuid.clone()
};
let output_dir = args.output_path.parent().unwrap_or(std::path::Path::new("."));
let mut face_json_path = output_dir.join(format!("{}.face.json", uuid));
if !face_json_path.exists() {
face_json_path = output_dir.join(&uuid).join(format!("{}.face.json", uuid));
}
eprintln!("[FACE_CLUSTER] Starting face clustering: {}", args.video_path);
if !face_json_path.exists() {
eprintln!("Face JSON not found.");
write_empty_output("no_face_json", &uuid, &args.output_path);
return;
}
let face_data: Value = serde_json::from_str(
&std::fs::read_to_string(&face_json_path).expect("Failed to read face.json"),
)
.expect("Failed to parse face.json");
let frames_list = face_data.get("frames").and_then(|f| f.as_array()).cloned().unwrap_or_default();
if frames_list.is_empty() {
eprintln!("No frames in JSON (no faces).");
write_empty_output("no_faces", &uuid, &args.output_path);
return;
}
let fps_value = face_data
.get("fps")
.and_then(|f| f.as_f64())
.unwrap_or(23.98);
let points = load_qdrant_faces(&uuid);
if points.is_empty() {
eprintln!("No embeddings found in Qdrant.");
write_empty_output("no_embeddings", &uuid, &args.output_path);
return;
}
let threshold = args.threshold;
let trace_embeddings = cluster_by_trace(&points, 1, CONFIDENCE_THRESHOLD);
if trace_embeddings.is_empty() {
eprintln!("No valid traces found.");
write_empty_output("no_embeddings", &uuid, &args.output_path);
return;
}
let (trace_to_person, trace_similarities) = if args.method == "agglomerative" {
agglomerative_cluster(&trace_embeddings, threshold)
} else {
seed_leader_cluster(&trace_embeddings, threshold)
};
if trace_to_person.is_empty() {
eprintln!("Clustering produced no results.");
write_empty_output("no_embeddings", &uuid, &args.output_path);
return;
}
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.
let traced_path = output_dir.join(format!("{}.face_traced.json", uuid));
let mut traced_frames: Value = Value::Object(Default::default());
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) {
traced_frames = v.get("frames").cloned().unwrap_or_else(|| Value::Object(Default::default()));
let _ = traced_frames.as_object().map(|o| o.len());
eprintln!(" Loaded face_traced.json: {} frames", traced_frames.as_object().map(|o| o.len()).unwrap_or(0));
}
}
}
let mut matched_count = 0_i64;
let mut frames_list = frames_list;
for (frame_idx, frame_obj) in frames_list.iter_mut().enumerate() {
let frame_num = frame_obj
.get("frame")
.and_then(|f| f.as_i64())
.unwrap_or(frame_idx as i64);
let traced_frame = traced_frames
.get(frame_num.to_string().as_str())
.cloned()
.unwrap_or_else(|| json!({}));
let traced_faces = traced_frame
.get("faces")
.and_then(|f| f.as_array())
.cloned()
.unwrap_or_default();
if let Some(faces) = frame_obj.get_mut("faces").and_then(|f| f.as_array_mut()) {
for (face_idx, face) in faces.iter_mut().enumerate() {
let trace_id = traced_faces
.get(face_idx)
.and_then(|f| f.get("trace_id"))
.and_then(|t| t.as_i64());
if let Some(trace_id) = trace_id {
if let Some(person_label) = trace_to_person.get(&trace_id) {
face["person_id"] = json!(format!("Person_{}", person_label));
face["trace_id"] = json!(trace_id);
matched_count += 1;
}
}
}
}
}
eprintln!(" Assigned person_id to {} faces", matched_count);
if matched_count == 0 {
eprintln!("No faces matched to any trace - check Qdrant data integrity");
write_empty_output("no_faces", &uuid, &args.output_path);
return;
}
// Person face counts + best face (representative).
let mut person_face_count: BTreeMap<String, u64> = BTreeMap::new();
let mut person_best_face: BTreeMap<String, Value> = BTreeMap::new();
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default();
for (face_idx, face) in faces.iter().enumerate() {
let person_id = face.get("person_id").and_then(|p| p.as_str());
if let Some(person_id) = person_id {
*person_face_count.entry(person_id.to_string()).or_insert(0) += 1;
let confidence = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.9);
let entry = person_best_face
.entry(person_id.to_string())
.or_insert_with(|| {
json!({
"confidence": f64::NEG_INFINITY,
})
});
if confidence > entry.get("confidence").and_then(|c| c.as_f64()).unwrap_or(f64::NEG_INFINITY) {
*entry = json!({
"face_id": format!("face_{}_{}", frame_idx, face_idx),
"confidence": confidence,
"frame": frame_obj.get("frame").cloned().unwrap_or(json!(frame_idx)),
"bbox": {
"x": face.get("x").cloned().unwrap_or(Value::Null),
"y": face.get("y").cloned().unwrap_or(Value::Null),
"width": face.get("width").cloned().unwrap_or(Value::Null),
"height": face.get("height").cloned().unwrap_or(Value::Null),
}
});
}
}
}
}
// Build per-person similarity stats from trace_similarities.
let mut person_sims: BTreeMap<i64, Vec<f64>> = BTreeMap::new();
let sim_threshold_value = 1.0 - threshold;
for (tid, person_label) in trace_to_person.iter() {
let sim = trace_similarities.get(tid).copied().unwrap_or(0.0);
person_sims.entry(*person_label).or_default().push(sim);
}
let mut sorted_persons: Vec<(&String, &u64)> = person_face_count.iter().collect();
sorted_persons.sort_by(|a, b| b.1.cmp(a.1));
let mut clusters: Vec<Value> = Vec::new();
for (person_id, count) in sorted_persons {
let person_label: Option<i64> = person_id
.split('_')
.nth(1)
.and_then(|s| s.parse::<i64>().ok());
let mut similarity_info: Option<Value> = None;
if let Some(label) = person_label {
if let Some(sims) = person_sims.get(&label) {
if !sims.is_empty() {
let min_s = sims.iter().cloned().fold(f64::INFINITY, f64::min);
let avg_s = sims.iter().sum::<f64>() / sims.len() as f64;
similarity_info = Some(json!({
"min": round_digits(min_s, 4),
"avg": round_digits(avg_s, 4),
"threshold": round_digits(sim_threshold_value, 4),
}));
}
}
}
let mut cluster_entry = json!({
"cluster_id": person_id,
"face_count": count,
});
if let Some(rep) = person_best_face.get(person_id) {
cluster_entry["representative_face"] = rep.clone();
}
if let Some(sim) = similarity_info {
cluster_entry["similarity"] = sim;
}
clusters.push(cluster_entry);
}
// Build output frames.
let mut output_frames: Vec<Value> = Vec::new();
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
let timestamp = frame_obj.get("timestamp").cloned().unwrap_or_else(|| {
if fps_value > 0.0 {
json!(frame_obj.get("frame").and_then(|f| f.as_i64()).unwrap_or(frame_idx as i64) as f64 / fps_value)
} else {
json!(0)
}
});
let mut output_faces: Vec<Value> = Vec::new();
let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default();
for (face_idx, face) in faces.iter().enumerate() {
let person_id = face.get("person_id").and_then(|p| p.as_str());
if let Some(person_id) = person_id {
output_faces.push(json!({
"face_id": format!("face_{}_{}", frame_idx, face_idx),
"cluster_id": person_id,
"trace_id": face.get("trace_id").cloned().unwrap_or(Value::Null),
"confidence": face.get("confidence").cloned().unwrap_or(json!(0.9)),
}));
}
}
if !output_faces.is_empty() {
output_frames.push(json!({
"frame": frame_obj.get("frame").cloned().unwrap_or(json!(frame_idx)),
"timestamp": timestamp,
"faces": output_faces,
}));
}
}
let mut output_data = json!({
"status": "has_faces",
"file_uuid": uuid,
"clusters": clusters,
"frames": output_frames,
});
// Auto-bind speakers from asrx.json.
let asrx_path = output_dir.join(format!("{}.asrx.json", uuid));
let speaker_mapping = auto_bind_speakers(&output_frames, &asrx_path);
if !speaker_mapping.is_null() {
output_data["speaker_person_mapping"] = speaker_mapping;
}
let rounded = round_json(output_data);
let text = serde_json::to_string_pretty(&rounded).map_err(|e| e.to_string());
match text {
Ok(t) => {
std::fs::write(&args.output_path, t).expect("Failed to write output");
eprintln!("Saved clustered data to {}", args.output_path.display());
}
Err(e) => {
eprintln!("Failed to serialize output: {}", e);
std::process::exit(1);
}
}
}
/// Compute speaker -> Person_N mapping by vote (Python auto_bind_speakers).
fn auto_bind_speakers(output_frames: &[Value], asrx_path: &std::path::Path) -> Value {
if !asrx_path.exists() {
eprintln!("Missing data for speaker binding.");
return Value::Null;
}
let asrx_data: Value = match std::fs::read_to_string(asrx_path) {
Ok(s) => match serde_json::from_str(&s) {
Ok(v) => v,
Err(e) => {
eprintln!(" Failed to load ASRX: {}", e);
return Value::Null;
}
},
Err(_) => return Value::Null,
};
eprintln!("Auto-binding Speakers to Persons...");
let mut face_spans: Vec<(f64, String)> = Vec::new();
for frame_obj in output_frames {
if let Some(ts) = frame_obj.get("timestamp").and_then(|t| t.as_f64()) {
if let Some(faces) = frame_obj.get("faces").and_then(|f| f.as_array()) {
for face in faces {
if let Some(person_id) = face.get("cluster_id").and_then(|p| p.as_str()) {
face_spans.push((ts, person_id.to_string()));
}
}
}
}
}
let mut speaker_person_counts: BTreeMap<String, BTreeMap<String, i64>> = BTreeMap::new();
let segments = asrx_data.get("segments").and_then(|s| s.as_array()).cloned().unwrap_or_default();
for seg in &segments {
let start = seg.get("start_time").or_else(|| seg.get("start")).and_then(|x| x.as_f64());
let end = seg.get("end_time").or_else(|| seg.get("end")).and_then(|x| x.as_f64());
let speaker = seg.get("speaker_id").and_then(|x| x.as_str());
if speaker.is_none() || start.is_none() || end.is_none() {
continue;
}
let speaker = speaker.unwrap();
let start = start.unwrap();
let end = end.unwrap();
let candidates: Vec<&(f64, String)> = face_spans
.iter()
.filter(|(ts, _)| start <= *ts && *ts <= end)
.collect();
if !candidates.is_empty() {
let mut person_counts: BTreeMap<String, i64> = BTreeMap::new();
for (_, pid) in candidates.iter() {
*person_counts.entry(pid.clone()).or_insert(0) += 1;
}
let best_person = person_counts
.iter()
.max_by(|a, b| a.1.cmp(b.1))
.map(|(p, _)| p.clone());
if let Some(best) = best_person {
let entry = speaker_person_counts.entry(speaker.to_string()).or_default();
*entry.entry(best).or_insert(0) += 1;
}
}
}
let mut mapping: BTreeMap<String, String> = BTreeMap::new();
for (speaker, persons) in speaker_person_counts.iter() {
if persons.is_empty() {
continue;
}
let best_person = persons.iter().max_by(|a, b| a.1.cmp(b.1)).map(|(p, _)| p);
if let Some(best) = best_person {
mapping.insert(speaker.clone(), best.clone());
eprintln!(" {} is likely {} ({} votes)", speaker, best, persons[best]);
}
}
if mapping.is_empty() {
Value::Null
} else {
serde_json::to_value(mapping).unwrap_or(Value::Null)
}
}
@@ -0,0 +1,275 @@
use std::collections::BTreeMap;
use std::process::Command;
use clap::Parser;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Parser)]
#[command(name = "rust_pose", about = "Pose Processor (Rust port of pose_processor.py interpolation)")]
struct Args {
video_path: std::path::PathBuf,
/// Existing pose.json produced by swift_face_pose (source of detected frames).
source_pose: std::path::PathBuf,
output_path: std::path::PathBuf,
#[arg(short = 'u', long = "uuid", default_value = "")]
uuid: String,
/// Comma-separated 8Hz target frames. When provided, detection is skipped and
/// the source is copied through unchanged (matches Python's 8Hz short-circuit).
#[arg(long = "frames", default_value = None)]
frames: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
struct PoseResult {
frame_count: u64,
fps: f64,
#[serde(default)]
frames: Vec<PoseFrame>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
struct PoseFrame {
frame: i64,
#[serde(default)]
timestamp: f64,
#[serde(default)]
persons: Vec<PersonPose>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
struct PersonPose {
#[serde(default)]
keypoints: Vec<Keypoint>,
#[serde(default)]
bbox: Option<BBoxInt>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
struct Keypoint {
name: String,
#[serde(default)]
x: f64,
#[serde(default)]
y: f64,
#[serde(default)]
confidence: f64,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
struct BBoxInt {
x: i64,
y: i64,
width: i64,
height: i64,
}
/// Mimic Python's `round(x, 2)` (banker's rounding / round-half-to-even).
fn round2(x: f64) -> f64 {
(x * 100.0).round_ties_even() / 100.0
}
/// Recursively round all float values to 2 decimals (Python `round_json_numbers`).
/// Integers pass through unchanged, matching Python's `round_json_numbers`.
fn round_json(value: Value) -> Value {
match value {
Value::Number(n) => {
if n.is_f64() {
let f = n.as_f64().unwrap_or(0.0);
let r = round2(f);
serde_json::Number::from_f64(r).map(Value::Number).unwrap_or(Value::Number(n))
} else {
Value::Number(n)
}
}
Value::Array(items) => Value::Array(items.into_iter().map(round_json).collect()),
Value::Object(map) => {
Value::Object(map.into_iter().map(|(k, v)| (k, round_json(v))).collect())
}
other => other,
}
}
/// Get total video frame count via ffprobe (nb_frames, falling back to duration*fps).
fn total_video_frames(video_path: &std::path::Path) -> u64 {
let nb_str = Command::new("ffprobe")
.args([
"-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=nb_frames", "-of", "csv=p=0",
])
.arg(video_path)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().trim_end_matches(',').to_string());
if let Some(s) = nb_str {
if s != "N/A" {
if let Ok(n) = s.parse::<u64>() {
return n;
}
}
// Fallback: duration * fps
let dur = Command::new("ffprobe")
.args(["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0"])
.arg(video_path)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().parse::<f64>().unwrap_or(0.0))
.unwrap_or(0.0);
let fps_str = Command::new("ffprobe")
.args(["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=r_frame_rate", "-of", "csv=p=0"])
.arg(video_path)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().trim_end_matches(',').to_string());
let fps = fps_str
.map(|s| {
if let Some((n, d)) = s.split_once('/') {
let n: f64 = n.trim().parse().unwrap_or(30.0);
let d: f64 = d.trim().trim_end_matches(',').parse().unwrap_or(1.0);
if d > 0.0 {
n / d
} else {
30.0
}
} else {
s.parse().unwrap_or(30.0)
}
})
.unwrap_or(30.0);
(dur * fps) as u64
} else {
0
}
}
fn interpolate_pose(source: &PoseResult, video_path: &std::path::Path) -> PoseResult {
let total = total_video_frames(video_path);
let fps = source.fps;
eprintln!(
"[POSE] interpolating {} detected frames -> {} total video frames (fps={})",
source.frames.len(),
total,
fps
);
if source.frames.is_empty() {
return source.clone();
}
// Collect frames per person index across all detected frames.
let mut all_persons: BTreeMap<usize, Vec<(i64, PersonPose)>> = BTreeMap::new();
for f in &source.frames {
for (i, p) in f.persons.iter().enumerate() {
all_persons.entry(i).or_default().push((f.frame, p.clone()));
}
}
let mut interpolated_frames: Vec<PoseFrame> = Vec::new();
for frame_num in 0..total {
let ts = frame_num as f64 / fps;
let mut persons_in_frame: Vec<PersonPose> = Vec::new();
for (_person_id, person_frames) in &all_persons {
let mut before: Option<(i64, &PersonPose)> = None;
let mut after: Option<(i64, &PersonPose)> = None;
for (fn_, p) in person_frames {
if *fn_ <= frame_num as i64 {
before = Some((*fn_, p));
}
if *fn_ >= frame_num as i64 && after.is_none() {
after = Some((*fn_, p));
}
}
if before.is_none() && after.is_none() {
continue;
}
let (interp_kps, interp_bbox): (Vec<Keypoint>, Option<BBoxInt>) = if let (Some((t0, b)), Some((t1, a))) = (before, after) {
if t0 != t1 {
let t = (frame_num as i64 - t0) as f64 / (t1 - t0) as f64;
let kp_before = &b.keypoints;
let kp_after = &a.keypoints;
let mut kps: Vec<Keypoint> = Vec::new();
for i in 0..kp_before.len().max(kp_after.len()) {
let kp0 = if i < kp_before.len() { &kp_before[i] } else { &kp_after[i] };
let kp1 = if i < kp_after.len() { &kp_after[i] } else { &kp_before[i] };
kps.push(Keypoint {
name: kp0.name.clone(),
x: kp0.x + t * (kp1.x - kp0.x),
y: kp0.y + t * (kp1.y - kp0.y),
confidence: kp0.confidence + t * (kp1.confidence - kp0.confidence),
});
}
let bbox = match (&b.bbox, &a.bbox) {
(Some(b0), Some(b1)) => Some(BBoxInt {
x: (b0.x as f64 + t * (b1.x as f64 - b0.x as f64)) as i64,
y: (b0.y as f64 + t * (b1.y as f64 - b0.y as f64)) as i64,
width: (b0.width as f64 + t * (b1.width as f64 - b0.width as f64)) as i64,
height: (b0.height as f64 + t * (b1.height as f64 - b0.height as f64)) as i64,
}),
_ => None,
};
(kps, bbox)
} else {
(b.keypoints.clone(), b.bbox.clone())
}
} else if let Some((_, b)) = before {
(b.keypoints.clone(), b.bbox.clone())
} else if let Some((_, a)) = after {
(a.keypoints.clone(), a.bbox.clone())
} else {
(Vec::new(), None)
};
let valid_bbox = interp_bbox
.as_ref()
.map(|b| b.width > 0 && b.height > 0)
.unwrap_or(false);
if valid_bbox {
persons_in_frame.push(PersonPose {
keypoints: interp_kps,
bbox: interp_bbox,
});
}
}
if !persons_in_frame.is_empty() {
interpolated_frames.push(PoseFrame {
frame: frame_num as i64,
timestamp: ts,
persons: persons_in_frame,
});
}
}
eprintln!("[POSE] interpolated -> {} frames", interpolated_frames.len());
PoseResult {
frame_count: interpolated_frames.len() as u64,
fps,
frames: interpolated_frames,
}
}
fn main() {
let args = Args::parse();
let source_str = std::fs::read_to_string(&args.source_pose).expect("failed to read source_pose");
let source: PoseResult = serde_json::from_str(&source_str).expect("failed to parse source_pose");
let result: PoseResult = if args.frames.is_some() {
eprintln!("[POSE] 8Hz mode: returning {} frames without interpolation", source.frames.len());
source
} else {
interpolate_pose(&source, &args.video_path)
};
let json = round_json(serde_json::to_value(&result).expect("serialize result"));
std::fs::write(&args.output_path, serde_json::to_string(&json).unwrap()).expect("write output");
eprintln!("[POSE] Done: {} frames -> {}", result.frame_count, args.output_path.display());
}
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""A/B verification: Python appearance_processor vs rust_appearance.
Compares two appearance.json outputs structurally:
- frame_count, fps
- per frame: persons, facing, bbox, body parts (name/bbox), histograms, dominant colors
Done for the P0 validation gate of the Rust processor migration.
"""
import json
import sys
def load(p):
with open(p) as f:
return json.load(f)
def compare_bbox(a, b, tol=1.0):
if abs(a["x"] - b["x"]) > tol or abs(a["y"] - b["y"]) > tol:
return False
if abs(a["width"] - b["width"]) > tol or abs(a["height"] - b["height"]) > tol:
return False
return True
def hist_diff(h1, h2):
"""Mean absolute difference of normalized histograms."""
if len(h1) != len(h2):
return 1.0
if len(h1) == 0:
return 0.0
total = 0.0
for a, b in zip(h1, h2):
total += abs(a - b)
return total / len(h1)
def colors_close(c1, c2, tol=30.0):
"""Dominant colors are k-means outputs (random init in Python) — compare loosely."""
if len(c1) != len(c2):
return len(c1) == 0 and len(c2) == 0
if len(c1) == 0:
return True
matched = 0
used = [False] * len(c2)
for a in c1:
best = None
bi = -1
for i, b in enumerate(c2):
if used[i]:
continue
d = sum((x - y) ** 2 for x, y in zip(a, b)) ** 0.5
if best is None or d < best:
best = d
bi = i
if best is not None and best <= tol:
matched += 1
used[bi] = True
return matched >= max(1, len(c1) // 2)
def main():
py = load(sys.argv[1])
rs = load(sys.argv[2])
issues = []
if py["frame_count"] != rs["frame_count"]:
issues.append(f"frame_count mismatch: {py['frame_count']} vs {rs['frame_count']}")
if abs(py["fps"] - rs["fps"]) > 0.01:
issues.append(f"fps mismatch: {py['fps']} vs {rs['fps']}")
py_frames = {f["frame"]: f for f in py["frames"]}
rs_frames = {f["frame"]: f for f in rs["frames"]}
if set(py_frames) != set(rs_frames):
issues.append(f"frame sets differ: py={len(py_frames)} rs={len(rs_frames)}")
n_frames = 0
n_persons = 0
n_parts = 0
facing_mismatch = 0
hist_fail = 0
color_fail = 0
bbox_fail = 0
missing_parts = 0
for fnum, pf in sorted(py_frames.items()):
rf = rs_frames.get(fnum)
if rf is None:
continue
n_frames += 1
if len(pf["persons"]) != len(rf["persons"]):
issues.append(f"frame {fnum}: person count {len(pf['persons'])} vs {len(rf['persons'])}")
continue
for pp, rp in zip(pf["persons"], rf["persons"]):
n_persons += 1
if pp["facing"] != rp["facing"]:
facing_mismatch += 1
if not compare_bbox(pp["bbox"], rp["bbox"], tol=1.0):
bbox_fail += 1
# histograms (full bbox)
if len(pp["hsv_histogram"]) == 3 and len(rp["hsv_histogram"]) == 3:
for ch in range(3):
if hist_diff(pp["hsv_histogram"][ch], rp["hsv_histogram"][ch]) > 0.02:
hist_fail += 1
break
elif pp["hsv_histogram"] != rp["hsv_histogram"]:
hist_fail += 1
if not colors_close(pp["dominant_colors"], rp["dominant_colors"]):
color_fail += 1
py_parts = {bp["name"]: bp for bp in pp["body_parts"]}
rs_parts = {bp["name"]: bp for bp in rp["body_parts"]}
if set(py_parts) != set(rs_parts):
missing_parts += 1
continue
for name, pb in py_parts.items():
rb = rs_parts[name]
n_parts += 1
if not compare_bbox(pb["bbox"], rb["bbox"], tol=1.0):
bbox_fail += 1
for ch in range(3):
if hist_diff(pb["hsv_histogram"][ch], rb["hsv_histogram"][ch]) > 0.02:
hist_fail += 1
break
if not colors_close(pb["dominant_colors"], rb["dominant_colors"]):
color_fail += 1
print(f"frames : {n_frames}")
print(f"persons : {n_persons}")
print(f"body parts : {n_parts}")
print(f"facing : {facing_mismatch} mismatch")
print(f"bbox : {bbox_fail} mismatch (>1px)")
print(f"histogram : {hist_fail} fail (>2% diff)")
print(f"colors : {color_fail} fail (loose match)")
print(f"missing parts: {missing_parts}")
if issues:
print("ISSUES:")
for i in issues[:20]:
print(" -", i)
else:
print("OK: no structural issues")
if __name__ == "__main__":
main()
+225
View File
@@ -0,0 +1,225 @@
#!/opt/homebrew/bin/python3.11
"""
A/B verify: Python fast_face_clustering_processor.py vs rust_face_cluster.
Runs both against the SAME Qdrant _faces data and SAME face.json/face_traced.json
inputs. Compares:
- cluster membership correspondence (trace_id -> person mapping)
- cluster_id set equivalence (members may be renumbered, but must match)
- representative_face face_id / frame / bbox equality
- output frame face_id / cluster / trace / confidence equality
Usage:
verify_face_cluster.py <video> <uuid> <outdir> [--method leader|agglomerative]
"""
import argparse
import json
import os
import subprocess
import sys
import tempfile
from collections import defaultdict
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PY_SCRIPT = os.path.join(SCRIPT_DIR, "fast_face_clustering_processor.py")
RUST_BIN = os.path.join(
SCRIPT_DIR, "rust_processors", "target", "release", "rust_face_cluster"
)
def norm_mapping(trace_to_person: dict) -> dict:
"""Renumber person labels per trace set so order doesn't matter."""
return trace_to_person
def load_cluster_json(path: str) -> dict:
with open(path) as f:
return json.load(f)
def mapping_from_output(output: dict) -> dict:
"""Rebuild {trace_id: cluster_id_renormalized} from frames section."""
trace_to_person = {}
for frame in output.get("frames", []):
for face in frame.get("faces", []):
tid = face.get("trace_id")
if tid is not None:
trace_to_person[tid] = face.get("cluster_id")
# Renormalize: sort trace_ids by cluster id assignment → integer labels.
# Group traces by raw cluster_id, then sort clusters by first-seen trace.
clusters = defaultdict(list)
for tid, cid in trace_to_person.items():
clusters[cid].append(tid)
# order by min trace_id within cluster (deterministic)
ordered = sorted(clusters.items(), key=lambda kv: min(kv[1]))
renum = {old: new for new, (old, _) in enumerate(ordered)}
return {tid: renum[cid] for tid, cid in trace_to_person.items()}
def compare(output_py, output_rust, method):
errors = []
status_py = output_py.get("status")
status_rust = output_rust.get("status")
if status_py != status_rust:
errors.append(f"status mismatch: {status_py} vs {status_rust}")
frames_py = output_py.get("frames", [])
frames_rust = output_rust.get("frames", [])
if len(frames_py) != len(frames_rust):
errors.append(f"frame count mismatch: {len(frames_py)} vs {len(frames_rust)}")
# Compare per-frame face assignments (face_id is the key).
map_py = {}
map_rust = {}
for frame in frames_py:
for face in frame.get("faces", []):
map_py[face["face_id"]] = face
for frame in frames_rust:
for face in frame.get("faces", []):
map_rust[face["face_id"]] = face
if set(map_py.keys()) != set(map_rust.keys()):
errors.append(
f"face_id set mismatch: {len(map_py)} vs {len(map_rust)}"
)
return errors
# Renumber both cluster_id sets so labels are comparable.
cluster_renum = {}
for fid, face in sorted(map_py.items(), key=lambda kv: kv[1].get("trace_id") or 0):
cid = face["cluster_id"]
if cid not in cluster_renum:
cluster_renum[cid] = len(cluster_renum)
map_py_renum = {fid: cluster_renum.get(f["cluster_id"]) for fid, f in map_py.items()}
cluster_renum_r = {}
for fid, face in sorted(map_rust.items(), key=lambda kv: kv[1].get("trace_id") or 0):
cid = face["cluster_id"]
if cid not in cluster_renum_r:
cluster_renum_r[cid] = len(cluster_renum_r)
map_rust_renum = {fid: cluster_renum_r.get(f["cluster_id"]) for fid, f in map_rust.items()}
metric = method
cluster_mismatch = 0
trace_mismatch = 0
conf_mismatch = 0
for fid in map_py.keys():
f_py = map_py[fid]
f_rust = map_rust[fid]
if map_py_renum[fid] != map_rust_renum[fid]:
cluster_mismatch += 1
if f_py.get("trace_id") != f_rust.get("trace_id"):
trace_mismatch += 1
if abs((f_py.get("confidence") or 0) - (f_rust.get("confidence") or 0)) > 1e-9:
conf_mismatch += 1
if cluster_mismatch == 0:
print(f" [{metric}] cluster_id assignments: MATCH ({len(map_py)} faces)")
else:
errors.append(
f" [{metric}] {cluster_mismatch}/{len(map_py)} faces have different cluster after renumber"
)
if trace_mismatch == 0:
print(f" [{metric}] trace_id: MATCH")
else:
errors.append(f" [{metric}] {trace_mismatch} trace_id mismatches")
if conf_mismatch == 0:
print(f" [{metric}] confidence: MATCH")
else:
errors.append(f" [{metric}] {conf_mismatch} confidence mismatches")
# Compare cluster-level stats (counts, representative face).
clusters_py = {c["cluster_id"]: c for c in output_py.get("clusters", [])}
clusters_rust = {c["cluster_id"]: c for c in output_rust.get("clusters", [])}
if set(clusters_py.keys()) != set(clusters_rust.keys()):
errors.append(
f"cluster_id key set mismatch: {sorted(clusters_py.keys())} vs {sorted(clusters_rust.keys())}"
)
# Map Python cluster -> Rust cluster by member traces (frame-level).
py_cluster_members = defaultdict(set)
rust_cluster_members = defaultdict(set)
for fid, label in map_py_renum.items():
py_cluster_members[label].add(fid)
for fid, label in map_rust_renum.items():
rust_cluster_members[label].add(fid)
for label_py, members_py in py_cluster_members.items():
match = None
for label_r, members_r in rust_cluster_members.items():
if members_py == members_r:
match = label_r
break
if match is None:
errors.append(
f"cluster {label_py} (py, {len(members_py)} members) has no equivalent in rust"
)
print(f" [{metric}] cluster correspondence: {'MATCH' if not errors else 'MISMATCH'}")
return errors
def main():
parser = argparse.ArgumentParser()
parser.add_argument("video")
parser.add_argument("uuid")
parser.add_argument("outdir", help="dir containing face.json/face_traced.json/asrx.json")
parser.add_argument("--method", default="leader", choices=["leader", "agglomerative"])
args = parser.parse_args()
py_out = os.path.join(args.outdir, "ab_python.json")
rust_out = os.path.join(args.outdir, "ab_rust.json")
env = dict(os.environ)
env["MOMENTRY_OUTPUT_DIR"] = args.outdir
print(f"Running Python ({args.method}) ...")
subprocess.run(
[
sys.executable,
PY_SCRIPT,
args.video,
py_out,
"--uuid",
args.uuid,
"--method",
args.method,
],
check=True,
env=env,
capture_output=True,
text=True,
)
print(f"Running Rust ({args.method}) ...")
subprocess.run(
[
RUST_BIN,
args.video,
rust_out,
"--uuid",
args.uuid,
"--method",
args.method,
],
check=True,
env=env,
capture_output=True,
text=True,
)
output_py = load_cluster_json(py_out)
output_rust = load_cluster_json(rust_out)
errors = compare(output_py, output_rust, args.method)
if errors:
print("\nFAIL")
for e in errors:
print(" -", e)
sys.exit(1)
print("\nPASS")
if __name__ == "__main__":
main()
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""A/B verify rust_pose interpolation vs Python pose_processor.py interpolate_pose."""
import json
import subprocess
import sys
import pose_processor as pp
VIDEO = "/Users/accusys/momentry/var/sftpgo/data/demo/IMG_9449 (1).MOV"
SOURCE = "/Users/accusys/momentry/output/4655a0ab3c077e30c12b2298c2750650.pose.json"
PY_OUT = "/tmp/pose_python.json"
RS_OUT = "/tmp/pose_rust.json"
KP_TOL = 0.6
BBOX_TOL = 1.0
def main():
# --- Python baseline ---
with open(SOURCE) as f:
detected = json.load(f)
py_result = pp.interpolate_pose(detected, VIDEO)
# round like the real script does
py_result = pp.round_json_numbers(py_result)
with open(PY_OUT, "w") as f:
json.dump(py_result, f)
# --- Rust ---
rs = subprocess.run(
[
"/Users/accusys/momentry_core/scripts/rust_processors/target/release/rust_pose",
VIDEO,
SOURCE,
RS_OUT,
],
capture_output=True,
text=True,
)
if rs.returncode != 0:
print("RUST FAILED:\n", rs.stderr)
sys.exit(1)
print(rs.stderr.strip())
with open(PY_OUT) as f:
py_data = json.load(f)
with open(RS_OUT) as f:
rs_data = json.load(f)
py_frames = py_data.get("frames", [])
rs_frames = rs_data.get("frames", [])
print(f"Python: frame_count={py_data.get('frame_count')} fps={py_data.get('fps')} frames={len(py_frames)}")
print(f"Rust: frame_count={rs_data.get('frame_count')} fps={rs_data.get('fps')} frames={len(rs_frames)}")
failures = []
total_kps = 0
max_kp_diff = 0.0
bbox_mismatch = 0
if len(py_frames) != len(rs_frames):
failures.append(f"frame count mismatch: {len(py_frames)} vs {len(rs_frames)}")
rs_by_frame = {f["frame"]: f for f in rs_frames}
for pf in py_frames:
fnum = pf["frame"]
rf = rs_by_frame.get(fnum)
if rf is None:
failures.append(f"frame {fnum}: missing in Rust")
continue
if len(pf["persons"]) != len(rf["persons"]):
failures.append(f"frame {fnum}: person count {len(pf['persons'])} vs {len(rf['persons'])}")
for pi, (ppr, rpr) in enumerate(zip(pf["persons"], rf["persons"])):
pbb = ppr.get("bbox", {})
rbb = rpr.get("bbox", {})
for key in ("x", "y", "width", "height"):
if abs(pbb.get(key, 0) - rbb.get(key, 0)) > BBOX_TOL:
bbox_mismatch += 1
failures.append(f"frame {fnum} person{pi} bbox.{key}: {pbb.get(key)} vs {rbb.get(key)}")
pk = ppr.get("keypoints", [])
rk = rpr.get("keypoints", [])
if len(pk) != len(rk):
failures.append(f"frame {fnum} person{pi}: keypoint count {len(pk)} vs {len(rk)}")
continue
for i, (a, b) in enumerate(zip(pk, rk)):
total_kps += 1
for field in ("x", "y"):
d = abs(a.get(field, 0) - b.get(field, 0))
max_kp_diff = max(max_kp_diff, d)
if d > KP_TOL:
failures.append(f"frame {fnum} p{pi} kp{i}.{field}: {a.get(field)} vs {b.get(field)} (diff {d:.4f})")
print(f"\nTotal keypoints compared: {total_kps}, max kp diff: {max_kp_diff:.4f}, bbox mismatches: {bbox_mismatch}")
if failures:
print(f"\nFAIL ({len(failures)} issues)")
for msg in failures[:80]:
print(" ", msg)
sys.exit(1)
print("\nPASS")
if __name__ == "__main__":
main()
+10
View File
@@ -43,6 +43,16 @@ pub fn set_auto_pipeline_enabled(enabled: bool) {
tracing::info!("Auto-pipeline enabled set to: {}", enabled);
}
// ─────────────────────────────────────────────────────────────
// Sensitive configs (always from ENV, never in JSON)
// ─────────────────────────────────────────────────────────────
pub static USE_RUST_PROCESSORS: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_USE_RUST_PROCESSORS")
.map(|v| v == "true" || v == "1")
.unwrap_or(false)
});
pub static DATABASE_URL: Lazy<String> = Lazy::new(|| {
env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://accusys@localhost:5432/momentry".to_string())
+71 -26
View File
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::time::Duration;
use super::executor::PythonExecutor;
use crate::core::config::USE_RUST_PROCESSORS;
const APPEARANCE_TIMEOUT: Duration = Duration::from_secs(7200);
@@ -66,36 +67,80 @@ pub async fn process_appearance(
}
let executor = PythonExecutor::new()?;
let script_name = "appearance_processor.py";
let script_path = executor.script_path(script_name);
tracing::info!(
"[APPEARANCE] Starting appearance extraction: {}",
video_path
);
if *USE_RUST_PROCESSORS {
if let Some(rust_bin) = executor.rust_binary_path("rust_appearance") {
tracing::info!("[APPEARANCE] Using Rust binary: {:?}", rust_bin);
executor
.run_rust_with_output_idx_and_frames(
&rust_bin,
&[video_path, pose_path, output_path],
Some(2),
uuid,
frames,
"APPEARANCE",
Some(APPEARANCE_TIMEOUT),
)
.await
.with_context(|| format!("Failed to run Rust binary {:?}", rust_bin))?;
} else {
tracing::warn!(
"[APPEARANCE] MOMENTRY_USE_RUST_PROCESSORS=1 but rust_appearance binary not found, falling back to Python"
);
let script_name = "appearance_processor.py";
let script_path = executor.script_path(script_name);
if !script_path.exists() {
tracing::warn!("[APPEARANCE] Script not found, returning empty result");
return Ok(AppearanceResult {
frame_count: 0,
fps: 0.0,
frames: vec![],
});
}
executor
.run_with_output_idx_and_frames(
script_name,
&[video_path, pose_path, output_path],
uuid,
"APPEARANCE",
Some(APPEARANCE_TIMEOUT),
Some(2),
frames,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
}
} else {
let script_name = "appearance_processor.py";
let script_path = executor.script_path(script_name);
if !script_path.exists() {
tracing::warn!("[APPEARANCE] Script not found, returning empty result");
return Ok(AppearanceResult {
frame_count: 0,
fps: 0.0,
frames: vec![],
});
if !script_path.exists() {
tracing::warn!("[APPEARANCE] Script not found, returning empty result");
return Ok(AppearanceResult {
frame_count: 0,
fps: 0.0,
frames: vec![],
});
}
tracing::info!(
"[APPEARANCE] Starting appearance extraction (Python): {}",
video_path
);
executor
.run_with_output_idx_and_frames(
script_name,
&[video_path, pose_path, output_path],
uuid,
"APPEARANCE",
Some(APPEARANCE_TIMEOUT),
Some(2),
frames,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
}
executor
.run_with_output_idx_and_frames(
script_name,
&[video_path, pose_path, output_path],
uuid,
"APPEARANCE",
Some(APPEARANCE_TIMEOUT),
Some(2),
frames,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
let json_str =
std::fs::read_to_string(output_path).context("Failed to read APPEARANCE output")?;
+191
View File
@@ -1159,6 +1159,197 @@ impl PythonExecutor {
}
}
/// Resolve the path to a compiled Rust processor binary.
/// Looks under `<scripts_dir>/rust_processors/target/release/` first, falling
/// back to `target/debug/` (mirrors the swift_processors layout convention).
pub fn rust_binary_path(&self, bin_name: &str) -> Option<PathBuf> {
let base = self.scripts_dir.join("rust_processors").join("target");
for profile in ["release", "debug"] {
let p = base.join(profile).join(bin_name);
if p.exists() {
return Some(p);
}
}
None
}
/// Run a Rust processor binary with the same output-tmp / timeout / process-group
/// semantics as the Python scripts. `output_idx` is the arg index for the output
/// JSON path; `uuid`/`frames` are appended as `--uuid=X` and `--frames=a,b,c`
/// when provided.
pub async fn run_rust_with_output_idx_and_frames(
&self,
bin_path: &std::path::Path,
args: &[&str],
output_idx: Option<usize>,
uuid: Option<&str>,
frames: Option<&[i64]>,
log_prefix: &str,
timeout_duration: Option<Duration>,
) -> Result<()> {
if !bin_path.exists() {
anyhow::bail!("Rust processor not found: {:?}", bin_path);
}
let output_path =
output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p)));
let tmp_path = output_path.as_ref().map(|p| {
let mut tmp = p.to_path_buf();
tmp.set_extension("json.tmp");
tmp
});
let mut cmd = Command::new(bin_path);
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
if let Ok(qdrant_url) = std::env::var("QDRANT_URL") {
cmd.env("QDRANT_URL", qdrant_url);
}
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
for (i, arg) in args.iter().enumerate() {
if Some(i) == output_idx {
if let Some(ref tmp) = tmp_path {
cmd.arg(tmp);
continue;
}
}
cmd.arg(arg);
}
if let Some(frames) = frames {
if !frames.is_empty() {
let frames_str = Self::format_frames_arg(frames);
cmd.arg("--frames").arg(&frames_str);
}
}
if let Some(u) = uuid {
cmd.arg("--uuid").arg(u);
}
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
cmd.kill_on_drop(true);
cmd.process_group(0);
tracing::info!("[{}] Starting rust: {:?}", log_prefix, cmd);
let mut child = cmd.spawn().with_context(|| {
format!("Failed to run Rust processor {:?}", bin_path)
})?;
let child_pid = child.id();
let stdout = child.stdout.take().context("Failed to capture stdout")?;
let stderr = child.stderr.take().context("Failed to capture stderr")?;
let mut stdout_reader = BufReader::new(stdout).lines();
let mut stderr_reader = BufReader::new(stderr).lines();
let run_future = async {
let mut stdout_done = false;
let mut stderr_done = false;
loop {
tokio::select! {
line = stdout_reader.next_line(), if !stdout_done => {
match line {
Ok(Some(line)) => {
if line.starts_with(&format!("{}_", log_prefix)) {
tracing::info!("[{}] {}", log_prefix, line);
}
}
Ok(None) => stdout_done = true,
Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e),
}
}
line = stderr_reader.next_line(), if !stderr_done => {
match line {
Ok(Some(line)) => {
if line.starts_with(&format!("{}_", log_prefix)) {
tracing::info!("[{}] {}", log_prefix, line);
} else if !line.trim().is_empty() {
tracing::warn!("[{} stderr] {}", log_prefix, line);
}
}
Ok(None) => stderr_done = true,
Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e),
}
}
status = child.wait() => {
match status {
Ok(status) => {
if !status.success() {
tracing::error!("[{}] Process failed: {}", log_prefix, status);
return Err(anyhow::anyhow!("{} exited with: {}", bin_path.display(), status));
}
tracing::info!("[{}] Completed successfully", log_prefix);
}
Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e),
}
break;
}
}
}
Ok(())
};
let mark_failed = || {
if let Some(tmp) = &tmp_path {
if tmp.exists() {
if let Some(out) = &output_path {
let is_valid = std::fs::read_to_string(tmp)
.ok()
.and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
.is_some();
if is_valid {
let mut partial_path = out.to_path_buf();
partial_path.set_extension("json.partial");
let _ = std::fs::rename(tmp, &partial_path);
} else {
let mut err_path = out.to_path_buf();
err_path.set_extension("json.err");
let _ = std::fs::rename(tmp, &err_path);
}
}
}
}
};
if let Some(duration) = timeout_duration {
match timeout(duration, run_future).await {
Ok(Ok(())) => {}
Ok(Err(e)) => {
mark_failed();
return Err(e);
}
Err(_) => {
mark_failed();
if let Some(pid) = child_pid {
unsafe {
libc::killpg(pid as i32, libc::SIGKILL);
}
}
child.kill().await.context("Failed to kill process")?;
anyhow::bail!("{} timed out after {:?}", log_prefix, duration);
}
}
} else if let Err(e) = run_future.await {
mark_failed();
return Err(e);
}
if let Some(tmp) = &tmp_path {
if tmp.exists() {
if let Some(out) = &output_path {
let _ = std::fs::rename(tmp, out);
}
}
}
Ok(())
}
pub fn script_path(&self, script_name: &str) -> PathBuf {
self.scripts_dir.join(script_name)
}
+34
View File
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::time::Duration;
use super::executor::PythonExecutor;
use crate::core::config::USE_RUST_PROCESSORS;
const FACE_CLUSTER_TIMEOUT: Duration = Duration::from_secs(3600);
@@ -92,6 +93,39 @@ pub async fn process_face_cluster(
);
}
// Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1)
if *USE_RUST_PROCESSORS {
if let Some(rust_bin) = executor.rust_binary_path("rust_face_cluster") {
tracing::info!("[FACE_CLUSTER] Using Rust binary: {:?}", rust_bin);
executor
.run_rust_with_output_idx_and_frames(
&rust_bin,
&args,
Some(1),
uuid,
frames,
"FACE_CLUSTER",
Some(FACE_CLUSTER_TIMEOUT),
)
.await
.with_context(|| format!("Failed to run Rust binary {:?}", rust_bin))?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read FACE_CLUSTER output")?;
let result: FaceClusterResult =
serde_json::from_str(&json_str).context("Failed to parse FACE_CLUSTER output")?;
tracing::info!(
"[FACE_CLUSTER] Rust Result: {} clusters, {} frames",
result.clusters.len(),
result.frames.len()
);
return Ok(result);
}
tracing::warn!(
"[FACE_CLUSTER] MOMENTRY_USE_RUST_PROCESSORS=1 but rust_face_cluster binary not found, falling back to Python"
);
}
executor
.run_with_output_idx_and_frames(
"fast_face_clustering_processor.py",
+37 -1
View File
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::time::Duration;
use super::executor::PythonExecutor;
use crate::core::config::USE_RUST_PROCESSORS;
const POSE_TIMEOUT: Duration = Duration::from_secs(7200);
@@ -156,8 +157,43 @@ pub async fn process_pose(
total_video_frames
);
// Call Python pose_processor.py for interpolation
let executor = PythonExecutor::new()?;
// Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1)
if *USE_RUST_PROCESSORS {
if let Some(rust_bin) = executor.rust_binary_path("rust_pose") {
tracing::info!("[POSE] Using Rust binary: {:?}", rust_bin);
executor
.run_rust_with_output_idx_and_frames(
&rust_bin,
// rust_pose reads `video source_pose output`;
// output is routed to .tmp and promoted on success.
&[video_path, output_path, output_path],
Some(2),
uuid,
None,
"POSE",
Some(POSE_TIMEOUT),
)
.await
.with_context(|| format!("Failed to run Rust binary {:?}", rust_bin))?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read interpolated POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse interpolated POSE output")?;
tracing::info!(
"[POSE] Rust interpolation completed: {} frames",
result.frames.len()
);
return Ok(result);
}
tracing::warn!(
"[POSE] MOMENTRY_USE_RUST_PROCESSORS=1 but rust_pose binary not found, falling back to Python"
);
}
// Call Python pose_processor.py for interpolation
let script_path = executor.script_path("pose_processor.py");
if script_path.exists() {