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:
@@ -0,0 +1,2 @@
|
||||
/target
|
||||
Cargo.lock.orig
|
||||
Generated
+1757
File diff suppressed because it is too large
Load Diff
@@ -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, ¢ers);
|
||||
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, ¢ers);
|
||||
let sse: f64 = pixels
|
||||
.iter()
|
||||
.zip(labels.iter())
|
||||
.map(|(p, &l)| dist(p, ¢ers[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, ¢ers);
|
||||
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(¢roid, &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());
|
||||
}
|
||||
Reference in New Issue
Block a user