feat: restructure tools directory

新結構:
- tools/script/ (Python 處理器腳本)
- tools/cli/ (Swift/Rust CLI 工具)

遷移內容:
- Python 腳本: ASR, Face, Pose, Cut, OCR, VLM, Embedding, Identity
- Swift CLI: 24 個 Swift 處理器和測試文件
- Rust CLI: Face Cluster, Appearance, Pose

保留向後兼容:
- 舊路徑 scripts/ 仍然存在
- 環境變數可配置新路徑

文檔:
- tools/README.md
- docs_v1.0/DESIGN/Tools_Directory_Restructure.md
This commit is contained in:
Accusys
2026-09-27 12:04:23 +08:00
parent db74b11e21
commit af028ab8f4
54 changed files with 15459 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
/target
Cargo.lock.orig
+2195
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
[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"
[[bin]]
name = "rust_vad"
path = "src/bin/rust_vad.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
clap = { version = "4", features = ["derive"] }
image = "0.25"
ureq = { version = "2", features = ["json"] }
# VAD dependencies
ort = { version = "2.0.0-rc.13", features = ["download-binaries"] }
hound = "3.5"
ndarray = "0.17"
anyhow = "1"
[dev-dependencies]
tempfile = "3"
[profile.release]
opt-level = 2
+817
View File
@@ -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);
}
+780
View File
@@ -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)
}
}
+275
View File
@@ -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());
}
+140
View File
@@ -0,0 +1,140 @@
use clap::Parser;
use anyhow::Result;
use serde_json::json;
use std::time::Instant;
use rust_processors::vad::{SileroVad, AudioReader, SpeechSegment};
use rust_processors::vad::segment::SegmentCollector;
#[derive(Parser)]
#[command(name = "rust_vad")]
#[command(about = "Silero VAD ONNX (Rust implementation)")]
struct Cli {
/// Input audio file (WAV 16kHz mono)
#[arg(short, long)]
audio: String,
/// ONNX model path
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
model: String,
/// Speech probability threshold
#[arg(long, default_value = "0.5")]
threshold: f32,
/// Minimum speech duration (milliseconds)
#[arg(long, default_value = "500")]
min_speech: u32,
/// Minimum silence duration (milliseconds)
#[arg(long, default_value = "300")]
min_silence: u32,
/// Chunk size (samples)
#[arg(long, default_value = "512")]
chunk_size: usize,
/// Output format
#[arg(long, default_value = "json")]
format: String,
}
fn main() -> Result<()> {
let cli = Cli::parse();
println!("[VAD] Loading model: {}", cli.model);
let start_load = Instant::now();
let mut vad = SileroVad::new(&cli.model)?;
println!("[VAD] Model loaded in {:.2}s", start_load.elapsed().as_secs_f32());
println!("[VAD] Loading audio: {}", cli.audio);
let audio = AudioReader::from_wav(&cli.audio)?;
let samples = audio.samples();
let sample_rate = audio.sample_rate();
let duration = audio.duration();
println!("[VAD] Audio: {} samples, {} Hz, {:.2}s",
samples.len(), sample_rate, duration);
// 檢測語音
println!("[VAD] Detecting speech...");
let start_detect = Instant::now();
let mut collector = SegmentCollector::new(
cli.threshold,
cli.min_speech,
cli.min_silence
);
// 分塊處理
for i in (0..samples.len()).step_by(cli.chunk_size) {
let end = (i + cli.chunk_size).min(samples.len());
let chunk = &samples[i..end];
// 如果塊太小,填充零
let mut chunk_vec = chunk.to_vec();
if chunk_vec.len() < cli.chunk_size {
chunk_vec.resize(cli.chunk_size, 0.0);
}
// 檢測
let speech_prob = vad.detect(&chunk_vec)?;
// 時間戳
let timestamp = i as f32 / sample_rate as f32;
// 收集片段
collector.process(timestamp, speech_prob);
}
// 結束處理
let end_timestamp = samples.len() as f32 / sample_rate as f32;
collector.finalize(end_timestamp);
let segments = collector.segments();
let detect_time = start_detect.elapsed().as_secs_f32();
println!("[VAD] Detection completed in {:.2}s", detect_time);
println!("[VAD] Found {} speech segments", segments.len());
// 計算統計
let total_speech: f32 = segments.iter().map(|s| s.duration()).sum();
let speech_ratio = total_speech / duration;
println!("[VAD] Total speech: {:.2}s ({:.1}%)", total_speech, speech_ratio * 100.0);
println!("[VAD] Processing speed: {:.2}x real-time", duration / detect_time);
// 輸出結果
match cli.format.as_str() {
"json" => {
let output = json!({
"audio_file": cli.audio,
"sample_rate": sample_rate,
"duration": duration,
"segments": segments.iter().map(|s| json!({
"start": s.start_sec,
"end": s.end_sec,
"duration": s.duration()
})).collect::<Vec<_>>(),
"statistics": {
"segment_count": segments.len(),
"total_speech": total_speech,
"speech_ratio": speech_ratio,
"detect_time": detect_time
}
});
println!("{}", serde_json::to_string_pretty(&output)?);
}
"text" => {
for seg in segments {
println!("{:.2} - {:.2} ({:.2}s)",
seg.start_sec, seg.end_sec, seg.duration());
}
}
_ => {
anyhow::bail!("Unknown output format: {}", cli.format);
}
}
Ok(())
}
+1
View File
@@ -0,0 +1 @@
pub mod vad;
+42
View File
@@ -0,0 +1,42 @@
use anyhow::{Context, Result};
use hound::WavReader;
pub struct AudioReader {
samples: Vec<f32>,
sample_rate: u32,
}
impl AudioReader {
pub fn from_wav(path: &str) -> Result<Self> {
let reader = WavReader::open(path)
.context("Failed to open WAV file")?;
let spec = reader.spec();
let sample_rate = spec.sample_rate;
// 轉換為 f32,範圍 [-1.0, 1.0]
let samples: Vec<f32> = reader.into_samples::<i16>()
.map(|s| {
s.map(|v| v as f32 / 32768.0)
.unwrap_or(0.0)
})
.collect();
Ok(Self {
samples,
sample_rate,
})
}
pub fn samples(&self) -> &[f32] {
&self.samples
}
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
pub fn duration(&self) -> f32 {
self.samples.len() as f32 / self.sample_rate as f32
}
}
+7
View File
@@ -0,0 +1,7 @@
pub mod onnx;
pub mod audio;
pub mod segment;
pub use onnx::SileroVad;
pub use audio::AudioReader;
pub use segment::SpeechSegment;
+100
View File
@@ -0,0 +1,100 @@
use anyhow::{Context, Result};
use ort::session::{Session, builder::GraphOptimizationLevel};
use ort::value::Value;
use ndarray::IxDyn;
pub struct SileroVad {
session: Session,
state: Vec<f32>, // [2, 1, 128] = 256 elements
context: Vec<f32>, // [1, 64] for 16kHz
sample_rate: i64,
context_size: usize, // 64 for 16kHz, 32 for 8kHz
}
impl SileroVad {
pub fn new(model_path: &str) -> Result<Self> {
let session = Session::builder()?
.with_optimization_level(GraphOptimizationLevel::Level1)
.map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))?
.commit_from_file(model_path)
.map_err(|e| anyhow::anyhow!("Failed to load model: {}", e))?;
let sample_rate = 16000;
let context_size = if sample_rate == 16000 { 64 } else { 32 };
Ok(Self {
session,
state: vec![0.0; 256], // [2, 1, 128] = 256
context: vec![0.0; context_size], // [1, 64]
sample_rate,
context_size,
})
}
pub fn detect(&mut self, audio_chunk: &[f32]) -> Result<f32> {
// 拼接 context 和當前塊
let mut input_with_context = Vec::with_capacity(self.context_size + audio_chunk.len());
input_with_context.extend_from_slice(&self.context);
input_with_context.extend_from_slice(audio_chunk);
// 準備輸入
let input_array = ndarray::Array::from_shape_vec(
IxDyn(&[1, input_with_context.len()]),
input_with_context.clone()
).context("Failed to create input array")?;
let state_array = ndarray::Array::from_shape_vec(
IxDyn(&[2, 1, 128]),
self.state.clone()
).context("Failed to create state array")?;
let sr_array = ndarray::Array::from_shape_vec(
IxDyn(&[]), // 標量
vec![self.sample_rate]
).context("Failed to create sr array")?;
// 創建 ONNX Value
let input_value = Value::from_array(input_array)
.context("Failed to create input value")?;
let state_value = Value::from_array(state_array)
.context("Failed to create state value")?;
let sr_value = Value::from_array(sr_array)
.context("Failed to create sr value")?;
// 運行推理
let inputs = ort::inputs![
"input" => input_value,
"state" => state_value,
"sr" => sr_value,
];
let outputs = self.session.run(inputs)
.context("Failed to run inference")?;
// 提取輸出
let output = outputs["output"].try_extract_tensor::<f32>()
.context("Failed to extract output")?;
// output 是 (&Shape, &[f32]) tuple
let output_data = output.1;
let speech_prob = output_data[0];
// 更新隱藏狀態
let state_n = outputs["stateN"].try_extract_tensor::<f32>()
.context("Failed to extract stateN")?;
// state_n 是 (&Shape, &[f32]) tuple
let state_data = state_n.1;
self.state = state_data.to_vec();
// 更新 context(當前輸入的最後 context_size 個樣本)
self.context = input_with_context[input_with_context.len() - self.context_size..].to_vec();
Ok(speech_prob)
}
pub fn reset_state(&mut self) {
self.state = vec![0.0; 256];
self.context = vec![0.0; self.context_size];
}
}
+86
View File
@@ -0,0 +1,86 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpeechSegment {
pub start_sec: f32,
pub end_sec: f32,
}
impl SpeechSegment {
pub fn new(start_sec: f32, end_sec: f32) -> Self {
Self { start_sec, end_sec }
}
pub fn duration(&self) -> f32 {
self.end_sec - self.start_sec
}
}
pub struct SegmentCollector {
segments: Vec<SpeechSegment>,
current_start: Option<f32>,
threshold: f32,
min_speech_duration: f32,
min_silence_duration: f32,
silence_start: Option<f32>,
}
impl SegmentCollector {
pub fn new(threshold: f32, min_speech_ms: u32, min_silence_ms: u32) -> Self {
Self {
segments: Vec::new(),
current_start: None,
threshold,
min_speech_duration: min_speech_ms as f32 / 1000.0,
min_silence_duration: min_silence_ms as f32 / 1000.0,
silence_start: None,
}
}
pub fn process(&mut self, timestamp: f32, speech_prob: f32) {
if speech_prob >= self.threshold {
// 語音
if self.current_start.is_none() {
self.current_start = Some(timestamp);
}
self.silence_start = None;
} else {
// 靜音
if self.current_start.is_some() {
if self.silence_start.is_none() {
self.silence_start = Some(timestamp);
}
// 檢查是否結束語音段
if let Some(silence_start) = self.silence_start {
let silence_duration = timestamp - silence_start;
if silence_duration >= self.min_silence_duration {
// 結束語音段
if let Some(start) = self.current_start {
let duration = silence_start - start;
if duration >= self.min_speech_duration {
self.segments.push(SpeechSegment::new(start, silence_start));
}
}
self.current_start = None;
self.silence_start = None;
}
}
}
}
}
pub fn finalize(&mut self, end_timestamp: f32) {
// 處理最後一個段
if let Some(start) = self.current_start {
let duration = end_timestamp - start;
if duration >= self.min_speech_duration {
self.segments.push(SpeechSegment::new(start, end_timestamp));
}
}
}
pub fn segments(&self) -> &[SpeechSegment] {
&self.segments
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"pins" : [
{
"identity" : "swift-argument-parser",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-argument-parser",
"state" : {
"revision" : "626b5b7b2f45e1b0b1c6f4a309296d1d21d7311b",
"version" : "1.7.1"
}
}
],
"version" : 2
}
+154
View File
@@ -0,0 +1,154 @@
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "SwiftProcessors",
platforms: [
.macOS(.v14)
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),
],
targets: [
.executableTarget(
name: "asr_swift",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["asr_swift.swift"]
),
.executableTarget(
name: "asrx_swift",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["asrx_swift.swift"]
),
.executableTarget(
name: "speaker_test",
dependencies: [],
path: ".",
sources: ["speaker_test.swift"]
),
.executableTarget(
name: "speaker_meta_test",
dependencies: [],
path: ".",
sources: ["speaker_meta_test.swift"]
),
.executableTarget(
name: "face_vision_test",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["face_vision_test.swift"]
),
.executableTarget(
name: "vision_object_test",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["vision_object_test.swift"]
),
.executableTarget(
name: "swift_cut_test",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["swift_cut_test.swift"]
),
.executableTarget(
name: "vision_ocr_test",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["vision_ocr_test.swift"]
),
.executableTarget(
name: "swift_ocr",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["swift_ocr.swift"]
),
.executableTarget(
name: "face_compare_test",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["face_compare_test.swift"]
),
.executableTarget(
name: "pose_benchmark",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["pose_benchmark.swift"]
),
.executableTarget(
name: "swift_pose",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["swift_pose.swift"]
),
.executableTarget(
name: "swift_face",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["swift_face.swift"]
),
.executableTarget(
name: "swift_hand",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["swift_hand.swift"]
),
.executableTarget(
name: "swift_face_pose",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["swift_face_pose.swift"]
),
.executableTarget(
name: "swift_pose_expansion",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["swift_pose_expansion.swift"]
),
.executableTarget(
name: "swift_appearance_expansion",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["swift_appearance_expansion.swift"]
),
.executableTarget(
name: "facenet_embedding",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
path: ".",
sources: ["facenet_embedding.swift"]
),
]
)
+254
View File
@@ -0,0 +1,254 @@
import Foundation
import Speech
import ArgumentParser
/// Swift CLI 處理器:使用 Apple Speech Framework 進行語音辨識
/// 作為 Python ASR (faster-whisper) 的替代方案
///
/// 比較項目:
/// - Speech Framework 使用 Apple 內建模型(ANE 加速)
/// - 無需下載模型,系統內建
/// - 支援即時與批次辨識
/// - 語言支援依作業系統版本
/// 合併逐字 segments 成句子
/// 當相鄰 segment 間隔 < 0.5s 時合併,間隔 >= 0.5s 時視為句子邊界
func mergeWordSegments(_ segments: [[String: Any]]) -> [[String: Any]] {
let gapThreshold: TimeInterval = 0.5
var merged: [[String: Any]] = []
var current: [String: Any]? = nil
for seg in segments {
guard let start = seg["start"] as? TimeInterval,
let end = seg["end"] as? TimeInterval,
let text = seg["text"] as? String,
let conf = seg["confidence"] as? Float else {
continue
}
if var cur = current {
let curEnd = cur["end"] as? TimeInterval ?? 0
let gap = start - curEnd
if gap < gapThreshold {
// 合併到當前句子
let curText = cur["text"] as? String ?? ""
let curConf = cur["confidence"] as? Float ?? 0
let wordCount = cur["_wordCount"] as? Int ?? 0
cur["text"] = curText + (curText.hasSuffix(" ") ? "" : " ") + text
cur["end"] = end
// 用 confidence 加權平均(依字數)
let totalWords = wordCount + 1
cur["confidence"] = (curConf * Float(wordCount) + conf) / Float(totalWords)
cur["_wordCount"] = totalWords
current = cur
} else {
// 句子邊界:儲存當前,開始新的
cur.removeValue(forKey: "_wordCount")
merged.append(cur)
current = [
"start": start,
"end": end,
"text": text,
"confidence": conf,
"_wordCount": 1
]
}
} else {
current = [
"start": start,
"end": end,
"text": text,
"confidence": conf,
"_wordCount": 1
]
}
}
if let cur = current {
var finalCur = cur
finalCur.removeValue(forKey: "_wordCount")
merged.append(finalCur)
}
return merged
}
@main
struct ASRSwift: ParsableCommand {
@Argument(help: "音訊/影片檔案路徑")
var inputPath: String
@Argument(help: "輸出 JSON 路徑")
var outputPath: String
@Option(name: .long, help: "UUID for Redis")
var uuid: String = ""
@Option(name: .long, help: "語言 (留空則自動嘗試支援的語種)")
var language: String = ""
/// 嘗試自動偵測語種
func detectLanguage() -> String {
if !language.isEmpty { return language }
// 優先嘗試常用語種
let candidates = ["zh-TW", "zh-Hans", "en-US", "ja-JP", "ko-KR"]
for localeId in candidates {
if let reco = SFSpeechRecognizer(locale: Locale(identifier: localeId)), reco.isAvailable {
print("[ASR_Swift] Auto-detected language: \(localeId)")
return localeId
}
}
return "en-US"
}
mutating func run() throws {
let startTime = Date()
print("[ASR_Swift] Starting: \(inputPath)")
print("[ASR_Swift] Language: \(language)")
print("[ASR_Swift] Output: \(outputPath)")
// 1. 萃取音訊(若為影片檔)
let audioURL: URL
let ext = (inputPath as NSString).pathExtension.lowercased()
let tempDir = FileManager.default.temporaryDirectory
.appendingPathComponent("asr_swift_\(UUID().uuidString)")
if ["mp4", "mov", "mkv", "avi"].contains(ext) {
// 需要 ffmpeg 萃取音訊
let wavPath = tempDir.appendingPathComponent("audio.wav").path
print("[ASR_Swift] Extracting audio from video...")
let proc = Process()
proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
proc.arguments = ["-y", "-v", "quiet", "-i", inputPath,
"-ar", "16000", "-ac", "1", wavPath]
try proc.run()
proc.waitUntilExit()
guard FileManager.default.fileExists(atPath: wavPath) else {
print("[ASR_Swift] Error: ffmpeg failed to extract audio")
throw NSError(domain: "ASRSwift", code: 1, userInfo: nil)
}
audioURL = URL(fileURLWithPath: wavPath)
print("[ASR_Swift] Audio extracted: \(wavPath)")
} else {
audioURL = URL(fileURLWithPath: inputPath)
}
// 2. 語音辨識
print("[ASR_Swift] Starting recognition...")
// 請求授權
let authGroup = DispatchGroup()
authGroup.enter()
var authStatus: SFSpeechRecognizerAuthorizationStatus = .notDetermined
SFSpeechRecognizer.requestAuthorization { status in
authStatus = status
authGroup.leave()
}
authGroup.wait()
guard authStatus == .authorized else {
print("[ASR_Swift] Speech recognition not authorized: \(authStatus.rawValue)")
return
}
print("[ASR_Swift] Speech recognition authorized")
let finalLang = detectLanguage()
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: finalLang))
guard let recognizer = recognizer, recognizer.isAvailable else {
print("[ASR_Swift] Error: Speech recognizer not available for \(language)")
// 回傳空結果
let emptyResult: [String: Any] = [
"language": language,
"segments": [],
"processing_time": Date().timeIntervalSince(startTime),
"model": "Apple Speech Framework",
"error": "Recognizer not available"
]
let jsonData = try JSONSerialization.data(withJSONObject: emptyResult, options: [.prettyPrinted])
try jsonData.write(to: URL(fileURLWithPath: outputPath))
return
}
let request = SFSpeechURLRecognitionRequest(url: audioURL)
request.shouldReportPartialResults = false
request.taskHint = .dictation
var allSegments: [[String: Any]] = []
let semaphore = DispatchSemaphore(value: 0)
let task = recognizer.recognitionTask(with: request) { result, error in
if let error = error {
print("[ASR_Swift] Recognition error: \(error.localizedDescription)")
semaphore.signal()
return
}
if let result = result, result.isFinal {
let duration = Date().timeIntervalSince(startTime)
print("[ASR_Swift] Recognition completed in \(String(format: "%.2f", duration))s")
// 將辨識結果轉為 segment 格式
for segment in result.bestTranscription.segments {
let seg: [String: Any] = [
"start": segment.timestamp,
"end": segment.timestamp + segment.duration,
"text": segment.substring,
"speaker_id": nil as String?,
"confidence": segment.confidence
]
allSegments.append(seg)
}
// 合併逐字 segments 成句子
if !allSegments.isEmpty {
let beforeCount = allSegments.count
allSegments = mergeWordSegments(allSegments)
print("[ASR_Swift] Merged segments: \(beforeCount) → \(allSegments.count)")
}
// 若無 segment,用整個文字建立一個
if allSegments.isEmpty {
let fullText = result.bestTranscription.formattedString
let seg: [String: Any] = [
"start": 0.0,
"end": Date().timeIntervalSince(startTime),
"text": fullText,
"speaker_id": nil as String?,
"confidence": 1.0
]
allSegments.append(seg)
}
semaphore.signal()
}
}
// RunLoop 是必要的 — Speech Framework 需要 main runloop 觸發 callback
// 使用 semaphore 等待完成,避免固定 timeout
while semaphore.wait(timeout: .now()) == .timedOut {
RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))
}
task.cancel()
// 3. 輸出 JSON
let outputDict: [String: Any] = [
"language": language,
"segments": allSegments,
"processing_time": Date().timeIntervalSince(startTime),
"model": "Apple Speech Framework (ANE accelerated)",
"total_segments": allSegments.count
]
let jsonData = try JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted])
try jsonData.write(to: URL(fileURLWithPath: outputPath))
print("[ASR_Swift] Saved \(allSegments.count) segments to \(outputPath)")
print("[ASR_Swift] Total time: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
// 清理暫存
if tempDir != audioURL.deletingLastPathComponent() {
try? FileManager.default.removeItem(at: tempDir)
}
}
}
+183
View File
@@ -0,0 +1,183 @@
import Foundation
import Speech
import ArgumentParser
/// Swift ASRX Processor
/// Speaker Diarization via Apple Speech Framework
///
/// 使用 SFSpeechRecognizer 進行語音辨識並嘗試分離說話人
/// 目前 Apple Speech Framework 不直接支援 speaker diarization,
/// 此實作透過音訊分段 + 逐段辨識來近似 diarization 效果
@main
struct ASRXSwift: ParsableCommand {
@Argument(help: "音訊/影片檔案路徑")
var inputPath: String
@Argument(help: "輸出 JSON 路徑")
var outputPath: String
@Option(name: .long, help: "UUID for Redis")
var uuid: String = ""
@Option(name: .long, help: "語言 (留空自動偵測)")
var language: String = ""
@Option(name: .long, help: "分段長度(秒),預設 5 秒")
var segmentDuration: Double = 5.0
mutating func run() throws {
let startTime = Date()
print("[ASRX_Swift] Starting: \(inputPath)")
// 1. 萃取音訊
let audioURL = extractAudio(from: inputPath)
defer { try? FileManager.default.removeItem(at: audioURL.deletingLastPathComponent()) }
// 2. 取得音訊資訊
let audioFile = try AVAudioFile(forReading: audioURL)
let format = audioFile.processingFormat
let totalFrames = audioFile.length
let duration = Double(totalFrames) / format.sampleRate
print("[ASRX_Swift] Audio: \(totalFrames) frames, \(String(format: "%.1f", duration))s, \(format.sampleRate)Hz")
// 3. 載入完整音訊
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(totalFrames)) else {
throw NSError(domain: "ASRXSwift", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to create buffer"])
}
try audioFile.read(into: buffer)
guard let floatDataPtr = buffer.floatChannelData else {
throw NSError(domain: "ASRXSwift", code: 2, userInfo: [NSLocalizedDescriptionKey: "No float data"])
}
let floatData = UnsafeBufferPointer(start: floatDataPtr[0], count: Int(totalFrames) * Int(format.channelCount))
// 4. 分段辨識
let finalLang = resolveLanguage()
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: finalLang))!
let frameStep = Int(segmentDuration * format.sampleRate)
let totalSegments = Int(ceil(duration / segmentDuration))
print("[ASRX_Swift] Splitting into \(totalSegments) segments of \(Int(segmentDuration))s")
print("[ASRX_Swift] Language: \(finalLang)")
print("[ASRX_Swift] Starting diarization...")
var segments: [[String: Any]] = []
var processedCount = 0
for segIdx in 0..<totalSegments {
let startFrame = segIdx * frameStep
let endFrame = min(startFrame + frameStep, Int(totalFrames))
// 取出該段音訊
let segLength = endFrame - startFrame
guard Double(segLength) > format.sampleRate * 0.5 else { continue } // 跳過 < 0.5s 的片段
let segBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(segLength))!
segBuffer.frameLength = AVAudioFrameCount(segLength)
let src = floatData[0]
let dstPtr = segBuffer.floatChannelData![0]
let srcSlice = Array(floatData[startFrame..<endFrame])
dstPtr.initialize(from: srcSlice, count: segLength)
// 寫入暫存 WAV(用標準 16-bit PCM 格式)
let segURL = FileManager.default.temporaryDirectory
.appendingPathComponent("seg_\(segIdx).wav")
let wavSettings: [String: Any] = [
AVFormatIDKey: kAudioFormatLinearPCM,
AVSampleRateKey: 16000,
AVNumberOfChannelsKey: 1,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsFloatKey: false,
]
let segFile = try AVAudioFile(forWriting: segURL, settings: wavSettings,
commonFormat: .pcmFormatInt16, interleaved: false)
try segFile.write(from: segBuffer)
// 辨識該段
let semaphore = DispatchSemaphore(value: 0)
var segText = ""
var segConfidence: Float = 0
let request = SFSpeechURLRecognitionRequest(url: segURL)
request.shouldReportPartialResults = false
request.requiresOnDeviceRecognition = true
let task = recognizer.recognitionTask(with: request) { result, error in
if let error = error {
print("[ASRX_Swift] Segment \(segIdx) error: \(error.localizedDescription)")
} else if let result = result, result.isFinal {
segText = result.bestTranscription.formattedString
if let firstSeg = result.bestTranscription.segments.first {
segConfidence = firstSeg.confidence
}
}
semaphore.signal()
}
RunLoop.current.run(until: Date(timeIntervalSinceNow: 10))
if !segText.isEmpty {
segments.append([
"start_time": Double(startFrame) / format.sampleRate,
"end_time": Double(endFrame) / format.sampleRate,
"start_frame": Int(Double(startFrame) / format.sampleRate * 30),
"end_frame": Int(Double(endFrame) / format.sampleRate * 30),
"text": segText,
"speaker_id": "SPEAKER_\(segIdx % 2)", // 簡單輪替作為 speaker 標記
"confidence": segConfidence,
])
processedCount += 1
}
task.cancel()
try? FileManager.default.removeItem(at: segURL)
}
// 5. 輸出 JSON
let outputDict: [String: Any] = [
"language": finalLang,
"segments": segments,
"total_segments": processedCount,
"total_duration": duration,
"processing_time": Date().timeIntervalSince(startTime),
"speaker_count": 2,
"model": "Apple Speech Framework (segmented diarization)",
]
let jsonData = try JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted])
try jsonData.write(to: URL(fileURLWithPath: outputPath))
print("[ASRX_Swift] Output: \(processedCount) segments to \(outputPath)")
print("[ASRX_Swift] Total: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
}
func extractAudio(from path: String) -> URL {
let ext = (path as NSString).pathExtension.lowercased()
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("asrx_\(UUID().uuidString)")
try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
let wavURL = tempDir.appendingPathComponent("audio.wav")
if ["mp4", "mov", "mkv", "avi"].contains(ext) {
print("[ASRX_Swift] Extracting audio from video...")
let proc = Process()
proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
proc.arguments = ["-y", "-v", "quiet", "-i", path, "-ar", "16000", "-ac", "1", wavURL.path]
try! proc.run()
proc.waitUntilExit()
} else {
try! FileManager.default.copyItem(at: URL(fileURLWithPath: path), to: wavURL)
}
return wavURL
}
func resolveLanguage() -> String {
if !language.isEmpty { return language }
let candidates = ["zh-TW", "zh-Hans", "en-US", "ja-JP", "ko-KR"]
for localeId in candidates {
if let reco = SFSpeechRecognizer(locale: Locale(identifier: localeId)), reco.isAvailable {
print("[ASRX_Swift] Auto-detected language: \(localeId)")
return localeId
}
}
return "en-US"
}
}
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env swift
import Foundation
import Vision
import AVFoundation
import ArgumentParser
/// Full-movie body pose scanner: compute head-to-body ratio for every frame
/// with face detections. Outputs JSONL (one object per frame).
@main
struct BodyPoseScanner: ParsableCommand {
@Argument(help: "Video file path")
var videoPath: String
@Argument(help: "Output JSONL path")
var outputPath: String
@Option(help: "Frames to scan (comma-separated, e.g. '840,900,960') or 'all' to scan everything")
var frames: String = "all"
@Option(help: "Sample interval (every N frames, for 'all' mode)")
var interval: Int = 60
func run() throws {
let url = URL(fileURLWithPath: videoPath)
let asset = AVAsset(url: url)
guard let reader = try? AVAssetReader(asset: asset) else {
print("[BodyPose] Cannot open video"); return
}
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
print("[BodyPose] No video track"); return
}
let fps = videoTrack.nominalFrameRate
let totalFrames = Int(videoTrack.timeRange.duration.seconds * Double(fps))
let readerOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
])
readerOutput.alwaysCopiesSampleData = false
reader.add(readerOutput)
reader.startReading()
// Parse target frames
var targetFrames = Set<Int>()
if frames == "all" {
targetFrames = Set(stride(from: 0, to: totalFrames, by: interval))
} else {
targetFrames = Set(frames.split(separator: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) })
}
var frameCount = 0
var results: [[String: Any]] = []
let bodyRequest = VNDetectHumanBodyPoseRequest()
guard let fh = FileHandle(forWritingAtPath: outputPath) else {
print("[BodyPose] Cannot create output"); return
}
while let sampleBuffer = readerOutput.copyNextSampleBuffer() {
defer { frameCount += 1 }
guard targetFrames.contains(frameCount) else { continue }
targetFrames.remove(frameCount)
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { continue }
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
try? handler.perform([bodyRequest])
guard let poses = bodyRequest.results, !poses.isEmpty else { continue }
let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer))
let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer))
for obs in poses {
guard let pts = try? obs.recognizedPoints(.all) else { continue }
var joints: [String: CGFloat] = [:]
for (name, pt) in pts where pt.confidence > 0.3 {
// Convert Vision (bottom-left origin) to pixel (top-left origin)
joints[String(describing: name)] = pt.location.x * imgW
joints[String(describing: name) + "_y"] = imgH - pt.location.y * imgH
}
// Get head top
let headY = joints["head_joint_y"] ?? joints["neck_1_joint_y"] ??
joints["neck_2_joint_y"] ?? joints["right_eye_joint_y"] ?? 0
// Get lowest visible body point (foot > ankle > knee > hip)
var bodyBottom = CGFloat.greatestFiniteMagnitude
for jn in ["right_ankle_joint_y", "left_ankle_joint_y",
"right_knee_joint_y", "left_knee_joint_y",
"right_hip_joint_y", "left_hip_joint_y"] {
if let v = joints[jn], v > 0 {
bodyBottom = min(bodyBottom, v)
}
}
let bodyH = bodyBottom == .greatestFiniteMagnitude ? 0 : abs(headY - bodyBottom)
let headH = abs(headY - (joints["neck_1_joint_y"] ?? headY))
let h2b = bodyH > 0 ? headH / bodyH : 0
let row: [String: Any] = [
"frame": frameCount, "timestamp": Double(frameCount)/Double(fps),
"head_top_y": headY, "body_bottom_y": bodyBottom,
"body_h_px": bodyH, "head_h_px": headH,
"h2b_ratio": Double(String(format: "%.3f", h2b)) ?? 0,
"has_full_body": bodyH > 0 && headH > 0,
"joints": joints.mapValues { Double($0) }
]
var jsonData = try! JSONSerialization.data(withJSONObject: row)
jsonData.append(10) // newline
fh.write(jsonData)
}
if targetFrames.isEmpty { break }
}
reader.cancelReading()
fh.closeFile()
print("[BodyPose] Done: \(results.count) frames → \(outputPath)")
}
}
+46
View File
@@ -0,0 +1,46 @@
import Foundation
import Speech
// Check what's available in Speech framework
print("=== Speech Framework API Availability ===")
// SFSpeechRecognizer
print("SFSpeechRecognizer available: true")
// Check for SFSpeechRecognitionMetadata (iOS 17+, macOS 14+)
let mdClass = NSClassFromString("SFSpeechRecognitionMetadata")
print("SFSpeechRecognitionMetadata: \(mdClass != nil ? "✅ Available" : "❌ Not available")")
// Check SFSpeechAnalyzer (iOS 17+, macOS 14+)
let analyzerClass = NSClassFromString("SFSpeechAnalyzer")
print("SFSpeechAnalyzer: \(analyzerClass != nil ? "✅ Available" : "❌ Not available")")
// Check for speaker identification types
let seClass = NSClassFromString("SFSpeakerEmbedding")
print("SFSpeakerEmbedding: \(seClass != nil ? "✅ Available" : "❌ Not available")")
let siClass = NSClassFromString("SFSpeakerIdentification")
print("SFSpeakerIdentification: \(siClass != nil ? "✅ Available" : "❌ Not available")")
let sevClass = NSClassFromString("SFSpeakerEmbeddingVector")
print("SFSpeakerEmbeddingVector: \(sevClass != nil ? "✅ Available" : "❌ Not available")")
let srClass = NSClassFromString("SFSpeakerRecognition")
print("SFSpeakerRecognition: \(srClass != nil ? "✅ Available" : "❌ Not available")")
// Check for AFVoiceBank / AVAudioSession speaker recognition
let avClass = NSClassFromString("AVVoiceBank")
print("AVVoiceBank: \(avClass != nil ? "✅ Available" : "❌ Not available")")
// Check AVAudioSession
if #available(macOS 14, *) {
print("macOS 14+ APIs available: ✅")
} else {
print("macOS 14+ APIs: ❌")
}
// Summarize
print()
print("=== Summary ===")
print("SFSpeechAnalyzer: \(analyzerClass != nil ? "✅ High-level speech analysis API" : "❌ Not available on this macOS version")")
print("Speaker recognition APIs: \(seClass != nil || siClass != nil || srClass != nil ? "✅ Speaker recognition APIs exist" : "❌ No speaker recognition APIs found")")
+23
View File
@@ -0,0 +1,23 @@
import Foundation
import Vision
let classes = [
"VNDetectFaceRectanglesRequest",
"VNDetectHumanRectanglesRequest",
"VNDetectHumanBodyPoseRequest",
"VNDetectHumanHandPoseRequest",
"VNClassifyImageRequest",
"VNRecognizeTextRequest",
"VNGenerateObjectnessBasedSaliencyImageRequest",
"VNGenerateAttentionBasedSaliencyImageRequest",
"VNRecognizeObjectsRequest",
"VNDetectContoursRequest",
"VNDetectTrajectoriesRequest",
]
for cname in classes {
if NSClassFromString(cname) != nil {
print("\(cname): ✅")
} else {
print("\(cname): ❌")
}
}
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.device.audio-input</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.temporary-exception.audio-upload</key>
<true/>
</dict>
</plist>
+206
View File
@@ -0,0 +1,206 @@
import Foundation
import Vision
import ArgumentParser
import AppKit
import AVFoundation
/// Full comparison: Apple Vision Framework vs InsightFace for face processing
@main
struct FaceCompareTest: ParsableCommand {
@Argument(help: "Video path or image path")
var inputPath: String
@Option(name: .long, help: "Sample interval (frames)")
var sampleInterval: Int = 30
@Option(name: .long, help: "Maximum frames to process")
var maxFrames: Int = 20
mutating func run() throws {
let startTime = Date()
print("=== Apple Vision Framework Face Processing ===")
#if arch(arm64)
print("HW: Apple Silicon ✅")
#endif
let url = URL(fileURLWithPath: inputPath)
let ext = (inputPath as NSString).pathExtension.lowercased()
if ["mp4", "mov", "mkv", "avi"].contains(ext) {
try processVideo(url: url)
} else {
try processImage(url: url)
}
print("Time: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
}
func processVideo(url: URL) throws {
let asset = AVAsset(url: url)
guard let track = asset.tracks(withMediaType: .video).first else {
print("No video track"); return
}
let duration = asset.duration.seconds
let fps = Double(track.nominalFrameRate)
let totalFrames = Int(duration * fps)
print("Video: \(duration)s @ \(fps)fps = \(totalFrames) frames")
// Extract frames with ffmpeg at sample interval
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("face_compare_\(UUID().uuidString)")
let framesDir = tempDir.appendingPathComponent("frames")
try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: tempDir) }
let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path
let proc = Process()
proc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
proc.arguments = ["-y", "-v", "quiet", "-i", url.path,
"-vf", "select=not(mod(n\\,\(sampleInterval)))",
"-vsync", "vfr", "-q:v", "5", pattern]
try proc.run()
proc.waitUntilExit()
let allFiles = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? []
let frameFiles = allFiles.filter { $0.hasSuffix(".jpg") }.sorted().prefix(maxFrames)
var totalFaces = 0
var framesWithFaces = 0
var frameCount = 0
for fname in frameFiles {
let imgPath = framesDir.appendingPathComponent(fname).path
guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)),
let img = NSImage(data: imgData),
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue }
let frameNum = Int(fname.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? 0
let timestamp = Double(frameNum) / fps
// Run all face detection requests
let faceResult = detectFaces(cgImage: cgImage)
if faceResult.count > 0 {
totalFaces += faceResult.count
framesWithFaces += 1
print(" Frame \(frameNum) (\(String(format: "%.1f", timestamp))s): \(faceResult.count) faces")
for (i, f) in faceResult.enumerated() {
print(" [\(i)] bbox=(\(String(format: "%.0f", f.x)),\(String(format: "%.0f", f.y))) size=\(String(format: "%.0f", f.w))x\(String(format: "%.0f", f.h)) conf=\(String(format: "%.3f", f.conf)) quality=\(String(format: "%.3f", f.quality)) landmarks=\(f.landmarks) embedding=\(f.hasEmbedding ? "✅" : "❌")")
}
}
frameCount += 1
}
print("\n=== Summary ===")
print("Frames processed: \(frameCount)")
print("Frames with faces: \(framesWithFaces)")
print("Total faces detected: \(totalFaces)")
// Compare with existing InsightFace JSON if available
let uuid = extractUUID(from: url.lastPathComponent)
if uuid != "" {
let faceJsonPath = "/Users/accusys/momentry/output_dev/\(uuid).face.json"
if FileManager.default.fileExists(atPath: faceJsonPath) {
print("\n=== Comparison with InsightFace (\(uuid).face.json) ===")
if let data = try? Data(contentsOf: URL(fileURLWithPath: faceJsonPath)),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let frames = json["frames"] as? [[String: Any]] {
let insightFaces = frames.filter { ($0["faces"] as? [Any])?.count ?? 0 > 0 }.count
let totalInsightFaces = frames.reduce(0) { $0 + (($1["faces"] as? [Any])?.count ?? 0) }
print(" InsightFace frames with faces: \(insightFaces)")
print(" InsightFace total faces: \(totalInsightFaces)")
}
}
}
}
func processImage(url: URL) throws {
guard let imgData = try? Data(contentsOf: url),
let img = NSImage(data: imgData),
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
print("Cannot load image"); return
}
print("Image: \(cgImage.width)x\(cgImage.height)")
let result = detectFaces(cgImage: cgImage)
print("Vision faces: \(result.count)")
for (i, f) in result.enumerated() {
print(" [\(i)] bbox=(\(String(format: "%.0f", f.x)),\(String(format: "%.0f", f.y))) size=\(String(format: "%.0f", f.w))x\(String(format: "%.0f", f.h)) conf=\(String(format: "%.3f", f.conf)) quality=\(String(format: "%.3f", f.quality)) landmarks=\(f.landmarks) embedding=\(f.hasEmbedding ? "✅" : "❌")")
}
}
struct FaceResult {
let x, y, w, h: Float
let conf: Float
let quality: Float
let landmarks: Int
let hasEmbedding: Bool
}
func detectFaces(cgImage: CGImage) -> [FaceResult] {
var results: [FaceResult] = []
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
// 1. Face Detection
let detectReq = VNDetectFaceRectanglesRequest()
try? handler.perform([detectReq])
// 2. Face Landmarks (run separately for each detected face)
let landmarkReq = VNDetectFaceLandmarksRequest()
// 3. Face Capture Quality
let qualityReq = VNDetectFaceCaptureQualityRequest()
// Run all requests
try? handler.perform([landmarkReq, qualityReq])
guard let detections = detectReq.results else { return [] }
let qualityResults = qualityReq.results ?? []
for (i, face) in detections.enumerated() {
let bb = face.boundingBox
let w = Float(cgImage.width)
let h = Float(cgImage.height)
let x = Float(bb.origin.x) * w
let y = Float(bb.origin.y) * h
let fw = Float(bb.size.width) * w
let fh = Float(bb.size.height) * h
// Get landmarks count
var lmCount = 0
if let lmResults = landmarkReq.results, i < lmResults.count {
let lms = lmResults[i].landmarks
if let left = lms?.leftEye { lmCount += left.pointCount }
if let right = lms?.rightEye { lmCount += right.pointCount }
if let nose = lms?.nose { lmCount += nose.pointCount }
}
// Get quality score
var quality: Float = 0
if i < qualityResults.count {
if #available(macOS 14, *) {
quality = (qualityResults[i].value(forKey: "faceCaptureQuality") as? Double).map { Float($0) } ?? 0
}
}
// Check for faceprint (embedding) via KVC
var hasEmbedding = false
if #available(macOS 14, *) {
if let fp = face.value(forKey: "faceprint") as? NSObject {
hasEmbedding = (fp.value(forKey: "data") as? Data) != nil
}
}
results.append(FaceResult(x: x, y: y, w: fw, h: fh, conf: face.confidence, quality: quality, landmarks: lmCount, hasEmbedding: hasEmbedding))
}
return results
}
func extractUUID(from filename: String) -> String {
// Try to extract 32-char hex UUID from filename
let pattern = try? NSRegularExpression(pattern: "[a-f0-9]{32}")
if let match = pattern?.firstMatch(in: filename, range: NSRange(location: 0, length: filename.count)) {
return (filename as NSString).substring(with: match.range)
}
return ""
}
}
+98
View File
@@ -0,0 +1,98 @@
import Foundation
import Vision
import ArgumentParser
import AppKit
/// POC: Test Apple Vision Framework for face detection + faceprint extraction
@main
struct FaceVisionTest: ParsableCommand {
@Argument(help: "Input image path")
var inputPath: String
mutating func run() throws {
let startTime = Date()
print("=== Apple Vision Framework Face POC ===")
#if arch(arm64)
print("HW: Apple Silicon ✅")
#else
print("HW: Intel")
#endif
guard let image = NSImage(contentsOfFile: inputPath) else {
print("Error: cannot load image"); return
}
guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
print("Error: cannot get CGImage"); return
}
print("Image: \(cgImage.width)x\(cgImage.height)")
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
// 1. Detect faces (synchronous)
print("\n--- Detection ---")
let detectReq = VNDetectFaceRectanglesRequest()
try handler.perform([detectReq])
let faces = detectReq.results ?? []
print("Faces: \(faces.count)")
for (i, f) in faces.enumerated() {
let bb = f.boundingBox
print(" [\(i)] bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y))) size=(\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) conf=\(String(format: "%.2f", f.confidence))")
}
guard !faces.isEmpty else { print("No faces"); return }
// 2. Landmarks
print("\n--- Landmarks ---")
let lmReq = VNDetectFaceLandmarksRequest()
try handler.perform([lmReq])
if let lmResults = lmReq.results {
for (i, f) in lmResults.enumerated() {
if let lms = f.landmarks {
let count = (lms.leftEye?.pointCount ?? 0) + (lms.rightEye?.pointCount ?? 0)
print(" [\(i)] landmarks: \(lms.leftEye?.pointCount ?? 0)+\(lms.rightEye?.pointCount ?? 0) eye pts, nose=\(lms.nose?.pointCount ?? 0)")
}
}
}
// 3. Capture quality
print("\n--- Capture Quality ---")
let qualReq = VNDetectFaceCaptureQualityRequest()
try handler.perform([qualReq])
if let qResults = qualReq.results {
for (i, f) in qResults.enumerated() {
if #available(macOS 14, *) {
let q = f.value(forKey: "faceCaptureQuality") as? Double ?? -1
print(" [\(i)] quality=\(String(format: "%.4f", q))")
}
}
}
// 4. Faceprint (embedding)
print("\n--- Faceprint ---")
if #available(macOS 14, *) {
let fpClass: AnyClass? = NSClassFromString("VNFaceprint")
print("VNFaceprint class: \(fpClass != nil ? "✅ exists" : "❌ nil")")
if let first = faces.first {
let fp = first.value(forKey: "faceprint") as? NSObject
print("faceprint KVC: \(fp != nil ? "✅" : "❌")")
if let fpData = fp {
let data = fpData.value(forKey: "data") as? Data
print(" data: \(data != nil ? "\(data!.count) bytes" : "nil")")
let desc = fpData.value(forKey: "descriptor") as? NSObject
print(" descriptor: \(desc != nil ? "✅ class=\(type(of: desc!))" : "nil")")
if let d = desc, let elems = d.value(forKey: "elements") as? [NSNumber] {
print(" elements: \(elems.count) dims")
if elems.count > 0 {
print(" first 5: \(elems.prefix(5).map { String(format: "%.4f", $0.doubleValue) }.joined(separator: ", "))")
}
}
}
}
} else {
print("macOS 14+ required")
}
print("\nTime: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
print("=== Done ===")
}
}
+192
View File
@@ -0,0 +1,192 @@
import Foundation
import Vision
import CoreML
import ArgumentParser
import AVFoundation
/// FaceNet CoreML Embedding Generator
/// Reads face.json, extracts face regions, generates 512-dim embeddings via FaceNet
@main
struct FaceNetEmbedding: ParsableCommand {
@Argument(help: "Video file path")
var videoPath: String
@Argument(help: "Input face.json path")
var inputPath: String
@Argument(help: "Output face.json path")
var outputPath: String
@Option(name: .long, help: "UUID for logging")
var uuid: String = ""
mutating func run() throws {
let startTime = Date()
print("[FaceNet] Loading FaceNet CoreML model...")
// Load FaceNet CoreML model
let modelURL = URL(fileURLWithPath: "/Users/accusys/momentry_core/models/facenet512.mlpackage/Data/com.apple.CoreML/model.mlmodel")
let compiledURL = try MLModel.compileModel(at: modelURL)
let model = try MLModel(contentsOf: compiledURL)
print("[FaceNet] Model loaded (ANE+GPU+CPU)")
// Load face.json
let faceData = try Data(contentsOf: URL(fileURLWithPath: inputPath))
var faceJson = try JSONSerialization.jsonObject(with: faceData) as! [String: Any]
var frames = faceJson["frames"] as! [[String: Any]]
let fps = faceJson["fps"] as! Double
print("[FaceNet] Loaded \(frames.count) frames from \(inputPath)")
// Load video
let asset = AVURLAsset(url: URL(fileURLWithPath: videoPath))
let generator = AVAssetImageGenerator(asset: asset)
generator.requestedTimeToleranceBefore = .zero
generator.requestedTimeToleranceAfter = .zero
generator.appliesPreferredTrackTransform = true
var embeddingCount = 0
var processedFrames = 0
// Process frames in batches
for i in 0..<frames.count {
var frame = frames[i]
let frameNumber = frame["frame"] as! Int
var faces = frame["faces"] as! [[String: Any]]
if faces.isEmpty { continue }
// Extract frame image
let time = CMTime(seconds: Double(frameNumber) / fps, preferredTimescale: 1000)
guard let imageRef = try? generator.copyCGImage(at: time, actualTime: nil) else {
print("[FaceNet] Failed to extract frame \(frameNumber)")
continue
}
// Process each face in this frame
for j in 0..<faces.count {
var face = faces[j]
// Skip if already has embedding
if face["embedding"] != nil {
embeddingCount += 1
continue
}
// Get face bbox
guard let bbox = face["bbox"] as? [String: Int] else { continue }
let x = bbox["x"]!
let y = bbox["y"]!
let w = bbox["width"]!
let h = bbox["height"]!
// Extract face region
// Note: CGImage coordinates are bottom-up, so flip Y
let flippedY = imageRef.height - y - h
let faceRect = CGRect(x: max(0, x), y: max(0, flippedY), width: min(w, imageRef.width - x), height: min(h, imageRef.height - flippedY))
guard let faceImage = imageRef.cropping(to: faceRect) else {
continue
}
// Resize to 160x160 and convert to MLMultiArray
guard let resizedImage = resizeImage(faceImage, to: CGSize(width: 160, height: 160)) else {
continue
}
guard let inputArray = cgImageToMLMultiArray(resizedImage) else {
continue
}
// Generate embedding via CoreML
let inputFeatures = try MLDictionaryFeatureProvider(dictionary: ["input": inputArray])
let outputFeatures = try model.prediction(from: inputFeatures)
if let output = outputFeatures.featureValue(for: "var_2167")?.multiArrayValue {
// Convert MLMultiArray to [Float]
let embeddingArray = (0..<output.count).map { Float(output[$0].doubleValue) }
// Add embedding to face
face["embedding"] = embeddingArray
faces[j] = face
embeddingCount += 1
}
}
frame["faces"] = faces
frames[i] = frame
processedFrames += 1
if processedFrames % 50 == 0 {
print("[FaceNet] Processed \(processedFrames)/\(frames.count) frames, \(embeddingCount) embeddings")
}
}
// Save updated face.json
faceJson["frames"] = frames
let outputData = try JSONSerialization.data(withJSONObject: faceJson)
try outputData.write(to: URL(fileURLWithPath: outputPath))
let elapsed = Date().timeIntervalSince(startTime)
print("[FaceNet] Done: \(embeddingCount) embeddings in \(String(format: "%.1f", elapsed))s → \(outputPath)")
}
private func resizeImage(_ image: CGImage, to size: CGSize) -> CGImage? {
let width = Int(size.width)
let height = Int(size.height)
let bytesPerPixel = 4
let bytesPerRow = width * bytesPerPixel
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
context.interpolationQuality = .high
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
return context.makeImage()
}
private func cgImageToMLMultiArray(_ image: CGImage) -> MLMultiArray? {
let width = image.width
let height = image.height
// Create MLMultiArray with shape [1, 3, 160, 160] (batch, channels, height, width)
guard let array = try? MLMultiArray(shape: [1, 3, NSNumber(value: height), NSNumber(value: width)], dataType: .float32) else {
return nil
}
// Create CGContext to read pixel data
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }
var rawData = [UInt8](repeating: 0, count: width * height * 4)
guard let context = CGContext(data: &rawData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
return nil
}
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
// Convert RGB to MLMultiArray (normalized to [0, 1])
// FaceNet expects [batch, channels, height, width]
for y in 0..<height {
for x in 0..<width {
let pixelIndex = (y * width + x) * 4
let r = Float(rawData[pixelIndex]) / 255.0
let g = Float(rawData[pixelIndex + 1]) / 255.0
let b = Float(rawData[pixelIndex + 2]) / 255.0
// [batch, channels, height, width]
// R channel: [0, 0, y, x]
// G channel: [0, 1, y, x]
// B channel: [0, 2, y, x]
let rIndex = 0 * 3 * height * width + 0 * height * width + y * width + x
let gIndex = 0 * 3 * height * width + 1 * height * width + y * width + x
let bIndex = 0 * 3 * height * width + 2 * height * width + y * width + x
array[rIndex] = NSNumber(value: r)
array[gIndex] = NSNumber(value: g)
array[bIndex] = NSNumber(value: b)
}
}
return array
}
}
+83
View File
@@ -0,0 +1,83 @@
import Foundation
import Vision
import ArgumentParser
import AppKit
import AVFoundation
/// Benchmark: Apple Vision Framework body pose detection speed
@main
struct PoseBenchmark: ParsableCommand {
@Argument(help: "Video path or image directory")
var inputPath: String
@Option(name: .long, help: "Sample interval (frames)")
var sampleInterval: Int = 30
mutating func run() throws {
let start = Date()
print("=== Vision Body Pose Benchmark ===")
#if arch(arm64)
print("HW: Apple Silicon ✅")
#endif
let url = URL(fileURLWithPath: inputPath)
let asset = AVAsset(url: url)
guard let track = asset.tracks(withMediaType: .video).first else {
print("No video track"); return
}
let duration = asset.duration.seconds
let fps = Double(track.nominalFrameRate)
let totalFrames = Int(duration * fps)
// Extract frames with ffmpeg
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("pose_bench_\(UUID().uuidString)")
let framesDir = tempDir.appendingPathComponent("frames")
try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true)
let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path
let extract = Process()
extract.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
extract.arguments = ["-y", "-v", "quiet", "-i", inputPath,
"-vf", "select=not(mod(n\\,\(sampleInterval)))",
"-vsync", "vfr", "-q:v", "5", pattern]
try extract.run()
extract.waitUntilExit()
let files = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? []
let frameFiles = files.filter { $0.hasSuffix(".jpg") }.sorted()
print("Frames: \(frameFiles.count)")
// Process all frames in one loop (no subprocess overhead)
var totalPoses = 0
var framesWithPose = 0
let inferenceStart = Date()
for fname in frameFiles {
let imgPath = framesDir.appendingPathComponent(fname).path
guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)),
let img = NSImage(data: imgData),
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue }
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
let req = VNDetectHumanBodyPoseRequest()
try? handler.perform([req])
if let poses = req.results, !poses.isEmpty {
framesWithPose += 1
totalPoses += poses.count
}
}
let inferenceTime = Date().timeIntervalSince(inferenceStart)
let totalTime = Date().timeIntervalSince(start)
print("\n=== Results ===")
print("Frames: \(frameFiles.count), with poses: \(framesWithPose)")
print("Total poses: \(totalPoses)")
print("Inference: \(String(format: "%.2f", inferenceTime))s")
print("Per frame: \(String(format: "%.0f", inferenceTime / Double(frameFiles.count) * 1000))ms")
print("Total: \(String(format: "%.2f", totalTime))s")
try FileManager.default.removeItem(at: tempDir)
}
}
+106
View File
@@ -0,0 +1,106 @@
import Foundation
import Speech
/// Test: Use KVC to check for speaker metadata on SFSpeechRecognitionResult
@main
struct SpeakerMetaTest {
static func main() {
print("=== Speaker Metadata Test ===")
let testFile = "/tmp/test_60s_b.wav"
guard FileManager.default.fileExists(atPath: testFile) else {
print("Test file not found")
return
}
let semaphore = DispatchSemaphore(value: 0)
var done = false
SFSpeechRecognizer.requestAuthorization { status in
guard status == .authorized else {
print("Authorization: \(status.rawValue)")
semaphore.signal()
return
}
print("Authorization: ✅")
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
recognizer.supportsOnDeviceRecognition ? print("On-device: ✅") : print("On-device: ❌ (will use server)")
let request = SFSpeechURLRecognitionRequest(url: URL(fileURLWithPath: testFile))
request.shouldReportPartialResults = false
request.requiresOnDeviceRecognition = false
request.taskHint = .dictation
print("Starting recognition...")
let task = recognizer.recognitionTask(with: request) { result, error in
if let error = error {
print("Error: \(error.localizedDescription)")
} else if let result = result, result.isFinal {
print("Recognition complete: \(result.bestTranscription.segments.count) raw segments")
// Check for metadata on the result object
let resultMetadata = result.value(forKey: "metadata") as? NSObject
print("Result metadata: \(resultMetadata != nil ? "✅" : "❌")")
if let rm = resultMetadata {
print(" Result metadata class: \(type(of: rm))")
// Dump all KVC values
for key in ["speakerID", "speakerName", "speakerConfidence", "voiceProfileID", "speaker"] {
if let val = rm.value(forKey: key) {
print(" result.\(key) = \(val)")
}
}
}
// Check each segment for metadata
var speakerCount = 0
for (i, seg) in result.bestTranscription.segments.enumerated() {
let segMetadata = seg.value(forKey: "metadata") as? NSObject
if let sm = segMetadata {
if i < 3 {
print("Seg[\(i)] metadata class: \(type(of: sm))")
// Try common keys
for key in ["speakerID", "speaker", "voice", "speakerConfidence", "speakerName"] {
if let val = sm.value(forKey: key) {
print(" seg.\(key) = \(val)")
speakerCount += 1
}
}
}
}
}
if speakerCount == 0 {
print("No speaker metadata found on any segment")
} else {
print("Found speaker metadata on segments: ✅")
}
// Also check all KVC keys on first segment
if let firstSeg = result.bestTranscription.segments.first {
print("\nAll KVC keys on first segment:")
let keys = ["metadata", "speaker", "voice", "recognition", "analysis", "audio"]
for key in keys {
if let val = firstSeg.value(forKey: key) {
print(" \(key): \(type(of: val)) = \(val)")
}
}
}
}
done = true
semaphore.signal()
}
// Run loop until done
while !done {
RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))
}
task.cancel()
semaphore.signal()
}
semaphore.wait()
print("Done")
}
}
+113
View File
@@ -0,0 +1,113 @@
import Foundation
import Speech
/// POC: Test SFSpeechAnalyzer + SFSpeechRecognitionMetadata for speaker detection
/// Goal: Determine if ANE-accelerated speaker diarization is feasible
@main
struct SpeakerTest {
static func main() {
print("=== SFSpeechAnalyzer Speaker Detection POC ===")
// 1. Check if running on ANE-capable hardware
#if arch(arm64)
print("Hardware: Apple Silicon ✅ (ANE available)")
#else
print("Hardware: Intel ❌ (No ANE)")
#endif
// 2. Check SFSpeechRecognizer on-device capability
let locale = Locale(identifier: "en-US")
let recognizerCheck = SFSpeechRecognizer(locale: locale)
print("On-device recognition: \(recognizerCheck?.supportsOnDeviceRecognition == true ? "✅" : "❌")")
// 3. Check SFSpeechAnalyzer capabilities via availability API
if #available(macOS 14, *) {
print("\n=== SFSpeechAnalyzer Analysis ===")
let analyzerClass: AnyClass? = NSClassFromString("SFSpeechAnalyzer")
print("SFSpeechAnalyzer: \(analyzerClass != nil ? "✅ Available" : "❌ Not available")")
let mdClass: AnyClass? = NSClassFromString("SFSpeechRecognitionMetadata")
print("SFSpeechRecognitionMetadata: \(mdClass != nil ? "✅ Available" : "❌ Not available")")
}
// 4. Test: Run ASR with SFSpeechRecognitionMetadata
print("\n=== Real-world Test ===")
let testFile = "/tmp/test_60s_b.wav"
guard FileManager.default.fileExists(atPath: testFile) else {
print("Test file not found: \(testFile)")
return
}
let semaphore = DispatchSemaphore(value: 0)
var detectedSpeakers: Set<String> = []
print("Running ASR with speaker detection on 60s clip...")
SFSpeechRecognizer.requestAuthorization { status in
guard status == .authorized else {
print("Authorization denied")
semaphore.signal()
return
}
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
guard recognizer.isAvailable else {
print("Recognizer not available")
semaphore.signal()
return
}
let request = SFSpeechURLRecognitionRequest(url: URL(fileURLWithPath: testFile))
request.shouldReportPartialResults = false
request.requiresOnDeviceRecognition = true
request.taskHint = .dictation
let task = recognizer.recognitionTask(with: request) { result, error in
if let error = error {
print("Recognition error: \(error.localizedDescription)")
} else if let result = result, result.isFinal {
let text = result.bestTranscription.formattedString
print("Text: \(text.prefix(200))")
print("Segments: \(result.bestTranscription.segments.count)")
// Check each segment for speaker metadata
if #available(macOS 14, *) {
for (i, seg) in result.bestTranscription.segments.enumerated() {
// Access metadata via KVC since it might be a private API
let md = seg.value(forKey: "metadata") as? NSObject
if let md = md {
let speakerId = md.value(forKey: "speakerID") as? String
let speakerName = md.value(forKey: "speakerName") as? String
let confidence = md.value(forKey: "speakerConfidence") as? Double
if let sid = speakerId {
detectedSpeakers.insert(sid)
if i < 5 || i % 20 == 0 {
print(" Seg[\(i)] speaker=\(sid) name=\(speakerName ?? "?") conf=\(confidence ?? 0) text=\"\(seg.substring.prefix(40))\"")
}
}
}
}
print("\nUnique speakers detected: \(detectedSpeakers)")
if detectedSpeakers.isEmpty {
print("⚠️ No speaker metadata found in recognition results")
}
} else {
print("macOS 14+ required for speaker metadata")
}
}
semaphore.signal()
}
// Wait
while semaphore.wait(timeout: .now()) == .timedOut {
RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))
}
task.cancel()
}
semaphore.wait()
}
}
@@ -0,0 +1,332 @@
import Foundation
import Vision
import ArgumentParser
import AVFoundation
/// Swift Appearance Expansion Processor V2
///
/// Reads pose.json and extracts colors at keypoint positions.
///
/// Algorithm:
/// 1. Load pose.json, get frames with trace_id
/// 2. For each pose frame, extract colors at keypoint positions
/// 3. Record overall brightness for lighting adjustment
/// 4. Expand outward, stop when 3 consecutive frames have low similarity
/// 5. Output at 8Hz sampling
///
/// Key Concepts:
/// - Appearance = colors at body part positions (head, torso, legs, feet)
/// - Used for tracking and agent search ("person wearing red shirt")
/// - Approximate colors are sufficient for top-K search
@main
struct SwiftAppearanceExpansion: ParsableCommand {
@Argument(help: "Video file path")
var videoPath: String
@Argument(help: "Input pose.json path")
var posePath: String
@Argument(help: "Output appearance.json path")
var outputPath: String
@Option(name: .long, help: "UUID for logging")
var uuid: String = ""
@Option(name: .long, help: "Consecutive miss threshold (default: 3)")
var missThreshold: Int = 3
@Option(name: .long, help: "Color sampling radius (default: 15)")
var colorRadius: Int = 15
mutating func run() throws {
let startTime = Date()
print("[AppearanceExpansion] Starting appearance extraction from pose: \(videoPath)")
// Load pose.json
guard let poseData = try? Data(contentsOf: URL(fileURLWithPath: posePath)) else {
print("[AppearanceExpansion] ERROR: Cannot read \(posePath)")
return
}
guard let poseJson = try? JSONSerialization.jsonObject(with: poseData) as? [String: Any] else {
print("[AppearanceExpansion] ERROR: Invalid JSON in \(posePath)")
return
}
// Extract frames with trace_id from pose
var poseFrameDict: [Int: [String: Any]] = [:] // frame -> pose data with trace_id
if let frames = poseJson["frames"] as? [[String: Any]] {
for frameData in frames {
guard let frameNum = frameData["frame"] as? Int else { continue }
poseFrameDict[frameNum] = frameData
}
}
print("[AppearanceExpansion] Found \(poseFrameDict.count) pose frames in \(posePath)")
if poseFrameDict.isEmpty {
print("[AppearanceExpansion] No pose frames found, skipping")
let emptyOutput: [String: Any] = ["frame_count": 0, "fps": 0.0, "frames": []]
let jsonData = try JSONSerialization.data(withJSONObject: emptyOutput, options: [])
try jsonData.write(to: URL(fileURLWithPath: outputPath))
return
}
// Get video info
let url = URL(fileURLWithPath: videoPath)
let asset = AVAsset(url: url)
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
print("[AppearanceExpansion] ERROR: No video track")
return
}
let fps = videoTrack.nominalFrameRate
let duration = CMTimeGetSeconds(asset.duration)
let totalFrames = Int(duration * Double(fps))
let sampleInterval = max(1, Int(floor(Double(fps) / 8.0)))
print("[AppearanceExpansion] Video: \(fps)fps, \(totalFrames) frames, 8Hz interval=\(sampleInterval)")
// Track appearance frames
var appearanceFrameDict: [Int: [String: Any]] = [:]
// Setup asset reader
let outputSettings: [String: Any] = [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA
]
let reader = try AVAssetReader(asset: asset)
let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings)
trackOutput.alwaysCopiesSampleData = false
reader.add(trackOutput)
guard reader.startReading() else {
print("[AppearanceExpansion] ERROR: Cannot start reader")
return
}
// Process frames
var frameIndex = 0
while let sampleBuffer = trackOutput.copyNextSampleBuffer() {
defer { frameIndex += 1 }
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
continue
}
// Check if this is a pose frame
if let poseData = poseFrameDict[frameIndex] {
let seconds = Double(frameIndex) / Double(fps)
// Extract colors at keypoint positions
let colors = extractColorsAtKeypoints(pixelBuffer: pixelBuffer, poseData: poseData, radius: colorRadius)
// Calculate overall brightness
let brightness = calculateBrightness(pixelBuffer: pixelBuffer)
// Get trace_id from pose (inherit)
let traceId = poseData["trace_id"] as? Int ?? 0
appearanceFrameDict[frameIndex] = [
"frame": frameIndex,
"timestamp": seconds,
"trace_id": traceId,
"brightness": brightness,
"colors": colors
]
}
// Progress logging
if frameIndex % 5000 == 0 {
let elapsed = Date().timeIntervalSince(startTime)
print("[AppearanceExpansion] Frame \(frameIndex)/\(totalFrames), \(appearanceFrameDict.count) appearances, \(Int(elapsed))s")
fflush(stdout)
}
}
reader.cancelReading()
print("[AppearanceExpansion] Extraction done: \(appearanceFrameDict.count) frames with appearance")
// 8Hz sampling output
var outputFrames: [[String: Any]] = []
let sortedAppearanceFrames = appearanceFrameDict.keys.sorted()
var targetFrame = 0
while targetFrame < totalFrames {
// Find closest appearance frame to target
var closestFrame: Int? = nil
var closestDist = Int.max
for appFrame in sortedAppearanceFrames {
let dist = abs(appFrame - targetFrame)
if dist < closestDist && dist <= sampleInterval {
closestDist = dist
closestFrame = appFrame
}
}
if let cf = closestFrame, let data = appearanceFrameDict[cf] {
outputFrames.append(data)
}
targetFrame += sampleInterval
}
// Write output
let output: [String: Any] = [
"frame_count": outputFrames.count,
"fps": Double(fps),
"frames": outputFrames
]
let jsonData = try JSONSerialization.data(withJSONObject: output, options: [])
try jsonData.write(to: URL(fileURLWithPath: outputPath))
let elapsed = Date().timeIntervalSince(startTime)
print("[AppearanceExpansion] Done: \(outputFrames.count) frames at 8Hz, \(String(format: "%.1f", elapsed))s → \(outputPath)")
}
/// Extract colors at keypoint positions
func extractColorsAtKeypoints(pixelBuffer: CVPixelBuffer, poseData: [String: Any], radius: Int) -> [String: [Int]] {
let imgW = CVPixelBufferGetWidth(pixelBuffer)
let imgH = CVPixelBufferGetHeight(pixelBuffer)
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }
guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else {
return [:]
}
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
let buffer = baseAddress.bindMemory(to: UInt8.self, capacity: bytesPerRow * imgH)
var colors: [String: [Int]] = [:]
// Define keypoint groups for body parts
let bodyParts: [String: [String]] = [
"head": ["nose", "left_eye", "right_eye", "left_ear", "right_ear"],
"torso": ["left_shoulder", "right_shoulder"],
"legs": ["left_hip", "right_hip", "left_knee", "right_knee"],
"feet": ["left_ankle", "right_ankle"]
]
// Extract color for each body part
for (partName, keypointNames) in bodyParts {
var totalR = 0, totalG = 0, totalB = 0
var count = 0
// Get persons array from pose data
if let persons = poseData["persons"] as? [[String: Any]] {
for person in persons {
if let keypoints = person["keypoints"] as? [[String: Any]] {
for kp in keypoints {
guard let name = kp["name"] as? String,
keypointNames.contains(name),
let x = kp["x"] as? Double,
let y = kp["y"] as? Double,
let confidence = kp["confidence"] as? Double,
confidence > 0.3 else { continue }
// Get average color around keypoint
let color = getAverageColor(
buffer: buffer,
bytesPerRow: bytesPerRow,
imgW: imgW,
imgH: imgH,
centerX: Int(x),
centerY: Int(y),
radius: radius
)
totalR += color.0
totalG += color.1
totalB += color.2
count += 1
}
}
}
}
if count > 0 {
colors[partName] = [totalR / count, totalG / count, totalB / count]
}
}
return colors
}
/// Get average color around a position
func getAverageColor(
buffer: UnsafeMutablePointer<UInt8>,
bytesPerRow: Int,
imgW: Int,
imgH: Int,
centerX: Int,
centerY: Int,
radius: Int
) -> (Int, Int, Int) {
let x1 = max(0, centerX - radius)
let x2 = min(imgW - 1, centerX + radius)
let y1 = max(0, centerY - radius)
let y2 = min(imgH - 1, centerY + radius)
var totalR = 0, totalG = 0, totalB = 0, count = 0
for y in y1...y2 {
let rowStart = y * bytesPerRow
for x in x1...x2 {
let offset = rowStart + x * 4
totalB += Int(buffer[offset])
totalG += Int(buffer[offset + 1])
totalR += Int(buffer[offset + 2])
count += 1
}
}
if count > 0 {
return (totalR / count, totalG / count, totalB / count)
}
return (0, 0, 0)
}
/// Calculate overall brightness of frame
func calculateBrightness(pixelBuffer: CVPixelBuffer) -> Double {
let imgW = CVPixelBufferGetWidth(pixelBuffer)
let imgH = CVPixelBufferGetHeight(pixelBuffer)
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }
guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else {
return 0.0
}
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
let buffer = baseAddress.bindMemory(to: UInt8.self, capacity: bytesPerRow * imgH)
var totalBrightness = 0.0
var count = 0
// Sample every 10 pixels for speed
for y in stride(from: 0, to: imgH, by: 10) {
let rowStart = y * bytesPerRow
for x in stride(from: 0, to: imgW, by: 10) {
let offset = rowStart + x * 4
let b = Double(buffer[offset])
let g = Double(buffer[offset + 1])
let r = Double(buffer[offset + 2])
// Calculate luminance
let luminance = 0.299 * r + 0.587 * g + 0.114 * b
totalBrightness += luminance / 255.0
count += 1
}
}
return count > 0 ? totalBrightness / Double(count) : 0.0
}
}
+191
View File
@@ -0,0 +1,191 @@
import Foundation
import AVFoundation
import ArgumentParser
import Accelerate
/// POC: Swift-based scene cut detection using AVFoundation histogram analysis
/// Compared against Python PySceneDetect ContentDetector (threshold=27)
@main
struct SwiftCutTest: ParsableCommand {
@Argument(help: "Video file path")
var inputPath: String
@Argument(help: "Output JSON path (optional)")
var outputPath: String?
@Option(name: .long, help: "Detection threshold (higher= fewer cuts, default 0.3)")
var threshold: Double = 0.3
@Option(name: .long, help: "Sample interval in frames (default=1)")
var sampleInterval: Int = 1
mutating func run() throws {
let startTime = Date()
print("=== Swift Scene Cut Detection POC ===")
#if arch(arm64)
print("HW: Apple Silicon ✅ (ANE available)")
#endif
let url = URL(fileURLWithPath: inputPath)
let asset = AVAsset(url: url)
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
print("Error: No video track found"); return
}
let duration = asset.duration.seconds
let fps = videoTrack.nominalFrameRate
let totalFrames = Int(duration * Double(fps))
print("Video: \(inputPath)")
print("Duration: \(String(format: "%.1f", duration))s")
print("FPS: \(String(format: "%.1f", fps))")
print("Total frames: \(totalFrames)")
print("Threshold: \(String(format: "%.2f", threshold))")
print("Sample interval: \(sampleInterval)")
// Read frame histogram data using AVAssetReader
guard let reader = try? AVAssetReader(asset: asset) else {
print("Error: Cannot create asset reader"); return
}
let settings: [String: Any] = [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
kCVPixelBufferWidthKey as String: 320, // downscale for speed
kCVPixelBufferHeightKey as String: 180,
]
let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: settings)
reader.add(trackOutput)
reader.startReading()
var frameIndex = 0
var prevHistogram: [Float]?
var scenes: [(start: Double, end: Double)] = []
var sceneStart: Double = 0
var diffs: [(frame: Int, diff: Float)] = []
let frameStep = sampleInterval
var lastPrint = 0
while reader.status == .reading {
guard let sampleBuffer = trackOutput.copyNextSampleBuffer() else { break }
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
CMSampleBufferInvalidate(sampleBuffer); continue
}
if frameIndex % frameStep == 0 {
let timestamp = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer))
// Compute histogram
let histogram = computeLuminanceHistogram(pixelBuffer: pixelBuffer)
if let prev = prevHistogram {
let diff = histogramDifference(prev, histogram)
if diff > Float(threshold) {
// Scene cut detected
let sceneEnd = timestamp
scenes.append((start: sceneStart, end: sceneEnd))
sceneStart = timestamp
diffs.append((frame: frameIndex, diff: diff))
if scenes.count % 50 == 0 {
print(" Scenes so far: \(scenes.count) at frame \(frameIndex)/\(totalFrames)")
}
}
}
prevHistogram = histogram
}
frameIndex += 1
CMSampleBufferInvalidate(sampleBuffer)
// Progress every 5%
let pct = Int(Float(frameIndex) / Float(totalFrames) * 100)
if pct >= lastPrint + 5 {
print(" Progress: \(pct)% (\(frameIndex)/\(totalFrames) frames)")
lastPrint = pct
}
}
// Add last scene
if sceneStart < duration {
scenes.append((start: sceneStart, end: duration))
}
let elapsed = Date().timeIntervalSince(startTime)
print("\n=== Results ===")
print("Scenes detected: \(scenes.count)")
print("Time: \(String(format: "%.2f", elapsed))s")
if totalFrames > 0 {
let rtf = elapsed / duration
print("RTF: \(String(format: "%.3f", rtf))x")
}
print("Last 5 cuts:")
for s in scenes.suffix(5) {
print(" \(String(format: "%.1f", s.start))s - \(String(format: "%.1f", s.end))s")
}
// Output JSON if requested
if let outPath = outputPath {
let outputDict: [String: Any] = [
"scenes": scenes.map { ["start_time": $0.start, "end_time": $0.end] },
"metadata": [
"video_path": inputPath,
"duration": duration,
"fps": fps,
"total_frames": totalFrames,
"threshold": threshold,
"sample_interval": sampleInterval,
"processing_time": elapsed,
"rtf": elapsed / duration,
],
"diffs": diffs.map { ["frame": $0.frame, "diff": String(format: "%.4f", $0.diff)] }
]
if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) {
try jsonData.write(to: URL(fileURLWithPath: outPath))
print("Output written to: \(outPath)")
}
}
}
func computeLuminanceHistogram(pixelBuffer: CVPixelBuffer) -> [Float] {
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer)!
var histogram = [Float](repeating: 0, count: 64) // 64 bins for speed
for y in 0..<height {
let row = baseAddress.advanced(by: y * bytesPerRow)
let pixels = row.assumingMemoryBound(to: UInt8.self)
for x in 0..<width {
let b = pixels[x * 4]
let g = pixels[x * 4 + 1]
let r = pixels[x * 4 + 2]
let luminance = (0.299 * Float(r) + 0.587 * Float(g) + 0.114 * Float(b))
let bin = min(Int(luminance / 256.0 * 64.0), 63)
histogram[bin] += 1
}
}
// Normalize
let total = Float(width * height)
for i in 0..<histogram.count {
histogram[i] /= total
}
return histogram
}
func histogramDifference(_ a: [Float], _ b: [Float]) -> Float {
var diff: Float = 0
for i in 0..<min(a.count, b.count) {
diff += abs(a[i] - b[i])
}
return diff
}
}
+374
View File
@@ -0,0 +1,374 @@
import Foundation
import Vision
import ArgumentParser
import AVFoundation
/// Swift Face Processor - Apple Vision Framework for face detection + pose
/// Uses AVAssetImageGenerator for reliable frame access (no AVAssetReader corruption).
@main
struct SwiftFace: ParsableCommand {
@Argument(help: "Video file path")
var inputPath: String
@Argument(help: "Output JSON path")
var outputPath: String
@Option(name: .long, help: "Sample interval (frames, default=3)")
var sampleInterval: Int = 3
@Option(name: .long, help: "UUID for logging")
var uuid: String = ""
mutating func run() throws {
let startTime = Date()
print("[SwiftFace] Vision-based face detection: \(inputPath)")
let url = URL(fileURLWithPath: inputPath)
let asset = AVAsset(url: url)
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
print("[SwiftFace] No video track found")
return
}
let fps = videoTrack.nominalFrameRate
let duration = CMTimeGetSeconds(asset.duration)
let totalFrames = Int(duration * Double(fps))
let width = Int(videoTrack.naturalSize.width)
let height = Int(videoTrack.naturalSize.height)
print("[SwiftFace] Video: \(width)x\(height), \(String(format: "%.1f", fps))fps, \(totalFrames) frames")
// Read face detection settings from environment variables (with defaults)
// Keep in sync with src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT
let MIN_CONFIDENCE = Double(ProcessInfo.processInfo.environment["FACE_MIN_CONFIDENCE"] ?? "0.5") ?? 0.5
let MIN_SIZE = Int(ProcessInfo.processInfo.environment["FACE_MIN_SIZE"] ?? "1") ?? 1
print("[SwiftFace] Settings: MIN_CONFIDENCE=\(MIN_CONFIDENCE), MIN_SIZE=\(MIN_SIZE)")
let generator = AVAssetImageGenerator(asset: asset)
generator.requestedTimeToleranceBefore = .zero
generator.requestedTimeToleranceAfter = .zero
generator.appliesPreferredTrackTransform = true
var allFrames: [[String: Any]] = []
var processedCount = 0
var checkedCount = 0
let frameInterval = TimeInterval(sampleInterval) / Double(fps)
// Process in batches of 1000 frames to avoid memory pressure
let batchSize = 1000
let totalSamples = totalFrames / sampleInterval
for batchStart in stride(from: 0, to: totalSamples, by: batchSize) {
let batchEnd = min(batchStart + batchSize, totalSamples)
var times: [NSValue] = []
for i in batchStart..<batchEnd {
let seconds = Double(i) * frameInterval
let cmTime = CMTime(seconds: seconds, preferredTimescale: 1000)
times.append(NSValue(time: cmTime))
}
let semaphore = DispatchSemaphore(value: 0)
var batchError: Error? = nil
generator.generateCGImagesAsynchronously(forTimes: times) { requestedTime, cgImage, actualTime, result, error in
defer { semaphore.signal() }
checkedCount += 1
guard result == .succeeded, let cgImage = cgImage else {
if let error = error {
fputs("[SwiftFace] Frame error at \(CMTimeGetSeconds(requestedTime)): \(error.localizedDescription)\n", stderr)
}
return
}
// Convert CGImage to CVPixelBuffer for Vision
var pixelBuffer: CVPixelBuffer?
let attrs: [CFString: Any] = [
kCVPixelBufferCGImageCompatibilityKey: true,
kCVPixelBufferCGBitmapContextCompatibilityKey: true,
kCVPixelBufferWidthKey: cgImage.width,
kCVPixelBufferHeightKey: cgImage.height,
]
CVPixelBufferCreate(kCFAllocatorDefault, cgImage.width, cgImage.height,
kCVPixelFormatType_32BGRA, attrs as CFDictionary, &pixelBuffer)
guard let pb = pixelBuffer else { return }
CVPixelBufferLockBaseAddress(pb, [])
defer { CVPixelBufferUnlockBaseAddress(pb, []) }
let context = CGContext(data: CVPixelBufferGetBaseAddress(pb),
width: cgImage.width, height: cgImage.height,
bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pb),
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)!
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height))
let handler = VNImageRequestHandler(cvPixelBuffer: pb, options: [:])
let detectReq = VNDetectFaceRectanglesRequest()
let lmReq = VNDetectFaceLandmarksRequest()
let captureQReq = VNDetectFaceCaptureQualityRequest()
do {
try handler.perform([detectReq, lmReq, captureQReq])
} catch {
return
}
let faceObservations = detectReq.results ?? []
let landmarkObservations = lmReq.results ?? []
let captureQualityObs = captureQReq.results ?? []
guard !faceObservations.isEmpty || !landmarkObservations.isEmpty else {
return
}
let seconds = CMTimeGetSeconds(actualTime)
let frameNumber = Int((seconds * Double(fps)).rounded())
var frameFaces: [[String: Any]] = []
// Use actual CGImage size (may differ from naturalSize after transform)
let imgW = CGFloat(cgImage.width)
let imgH = CGFloat(cgImage.height)
// Process landmark observations FIRST (each has bbox + landmarks, self-consistent)
// Quality filtering - uses MIN_CONFIDENCE and MIN_SIZE from outer scope
for lmObs in landmarkObservations {
// Confidence filter
let lmConf = Double(lmObs.confidence)
if lmConf < MIN_CONFIDENCE { continue }
let bb = lmObs.boundingBox
let faceW = Int(bb.size.width * imgW)
let faceH = Int(bb.size.height * imgH)
// Size filter
if faceW < MIN_SIZE || faceH < MIN_SIZE { continue }
let faceX = Int(bb.origin.x * imgW)
let faceY = Int((1.0 - bb.origin.y - bb.size.height) * imgH)
// Match capture quality request by bbox overlap (landmarks request
// results don't populate faceCaptureQuality on macOS)
var captureQ = 0.0
var bestOverlap: CGFloat = 0
for cqObs in captureQualityObs {
let cb = cqObs.boundingBox
let ix = max(bb.minX, cb.minX)
let iy = max(bb.minY, cb.minY)
let iw = min(bb.maxX, cb.maxX) - ix
let ih = min(bb.maxY, cb.maxY) - iy
if iw <= 0 || ih <= 0 { continue }
let overlap = (iw * ih) / (bb.width * bb.height)
if overlap > bestOverlap {
bestOverlap = overlap
if let cq = cqObs.faceCaptureQuality {
captureQ = Double(cq)
}
}
}
// Match face observation by bbox to extract faceprint (embedding)
var embedding: [Float]? = nil
if #available(macOS 14, *) {
var matchCount = 0
for faceObs in faceObservations {
let fBB = faceObs.boundingBox
let ix = max(bb.minX, fBB.origin.x)
let iy = max(bb.minY, fBB.origin.y)
let iw = min(bb.maxX, fBB.origin.x + fBB.width) - ix
let ih = min(bb.maxY, fBB.origin.y + fBB.height) - iy
if iw <= 0 || ih <= 0 { continue }
let intersection = iw * ih
let union = bb.width * bb.height + fBB.width * fBB.height - intersection
if intersection / union > 0.5 {
matchCount += 1
// Try to extract faceprint
if let fp = faceObs.value(forKey: "faceprint") as? NSObject {
if let desc = fp.value(forKey: "descriptor") as? NSObject {
if let elems = desc.value(forKey: "elements") as? [NSNumber] {
embedding = elems.map { Float($0.doubleValue) }
} else {
print("[DEBUG] No elements in descriptor")
}
} else {
print("[DEBUG] No descriptor in faceprint")
}
} else {
print("[DEBUG] No faceprint in faceObs (frame \(frameNumber), match \(matchCount))")
}
break
}
}
}
var faceData: [String: Any] = [
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
"width": faceW, "height": faceH],
"confidence": Double(lmObs.confidence),
"captureQuality": captureQ,
]
// Add embedding if available
if let emb = embedding {
faceData["embedding"] = emb
}
// Pose from landmark observation
if let yaw = lmObs.yaw?.doubleValue,
let roll = lmObs.roll?.doubleValue {
var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw]
if let pitch = lmObs.pitch?.doubleValue {
poseInfo["pitch"] = pitch
}
faceData["pose"] = poseInfo
}
// Landmarks with Y-flip (macOS image coords: bottom-left -> top-left)
if let lms = lmObs.landmarks {
let imgSize = CGSize(width: imgW, height: imgH)
let leftEye = lms.leftEye?.pointsInImage(imageSize: imgSize) ?? []
let rightEye = lms.rightEye?.pointsInImage(imageSize: imgSize) ?? []
let nose = lms.nose?.pointsInImage(imageSize: imgSize) ?? []
if !leftEye.isEmpty || !rightEye.isEmpty || !nose.isEmpty {
var lm: [String: [[Double]]] = [:]
if !leftEye.isEmpty {
lm["left_eye"] = leftEye.map { [Double($0.x), Double(imgH - $0.y)] }
}
if !rightEye.isEmpty {
lm["right_eye"] = rightEye.map { [Double($0.x), Double(imgH - $0.y)] }
}
if !nose.isEmpty {
lm["nose"] = nose.map { [Double($0.x), Double(imgH - $0.y)] }
}
faceData["landmarks"] = lm
}
let outer = lms.outerLips?.pointsInImage(imageSize: imgSize) ?? []
let inner = lms.innerLips?.pointsInImage(imageSize: imgSize) ?? []
if !outer.isEmpty || !inner.isEmpty {
faceData["lips"] = [
"outer_lips": outer.map { [Double($0.x), Double(imgH - $0.y)] },
"inner_lips": inner.map { [Double($0.x), Double(imgH - $0.y)] }
]
}
}
frameFaces.append(faceData)
}
// Output face rect observations that the landmark detector missed.
// Match against ALL landmark observations via IoU to avoid duplicates.
for faceObs in faceObservations {
let fBB = faceObs.boundingBox
var matched = false
for lmObs in landmarkObservations {
let lBB = lmObs.boundingBox
let ix = max(fBB.origin.x, lBB.origin.x)
let iy = max(fBB.origin.y, lBB.origin.y)
let iw = min(fBB.maxX, lBB.maxX) - ix
let ih = min(fBB.maxY, lBB.maxY) - iy
if iw <= 0 || ih <= 0 { continue }
let intersection = iw * ih
let union = fBB.width * fBB.height + lBB.width * lBB.height - intersection
if intersection / union > 0.3 {
matched = true
break
}
}
if matched { continue }
// Quality filtering for unmatched face rects
if Double(faceObs.confidence) < MIN_CONFIDENCE { continue }
let faceW = Int(fBB.size.width * imgW)
let faceH = Int(fBB.size.height * imgH)
if faceW < MIN_SIZE || faceH < MIN_SIZE { continue }
// Unmatched face rect: output without landmarks
let faceX = Int(fBB.origin.x * imgW)
let faceY = Int((1.0 - fBB.origin.y - fBB.size.height) * imgH)
// Match capture quality request by bbox overlap
var captureQ = 0.0
var bestOverlap: CGFloat = 0
for cqObs in captureQualityObs {
let cb = cqObs.boundingBox
let ix = max(fBB.minX, cb.minX)
let iy = max(fBB.minY, cb.minY)
let iw = min(fBB.maxX, cb.maxX) - ix
let ih = min(fBB.maxY, cb.maxY) - iy
if iw <= 0 || ih <= 0 { continue }
let overlap = (iw * ih) / (fBB.width * fBB.height)
if overlap > bestOverlap {
bestOverlap = overlap
if let cq = cqObs.faceCaptureQuality {
captureQ = Double(cq)
}
}
}
var faceData: [String: Any] = [
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
"width": faceW, "height": faceH],
"confidence": Double(faceObs.confidence),
"captureQuality": captureQ,
]
if let yaw = faceObs.yaw?.doubleValue,
let roll = faceObs.roll?.doubleValue {
var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw]
if let pitch = faceObs.pitch?.doubleValue {
poseInfo["pitch"] = pitch
}
faceData["pose"] = poseInfo
}
frameFaces.append(faceData)
}
if !frameFaces.isEmpty {
allFrames.append([
"frame": frameNumber,
"timestamp": seconds,
"faces": frameFaces,
])
processedCount += 1
}
}
// Wait for batch to complete
for _ in batchStart..<batchEnd {
semaphore.wait()
}
let elapsed = Date().timeIntervalSince(startTime)
let pct = Int(Double(min(batchEnd, totalSamples)) / Double(totalSamples) * 100)
print("[SwiftFace] \(processedCount) frames with faces, \(pct)% complete, \(Int(elapsed))s elapsed")
fflush(stdout)
}
generator.cancelAllCGImageGeneration()
let output: [String: Any] = [
"frame_count": allFrames.count,
"fps": Double(fps),
"frames": allFrames,
]
guard let jsonData = try? JSONSerialization.data(withJSONObject: output, options: []),
let jsonString = String(data: jsonData, encoding: .utf8) else {
print("[SwiftFace] Failed to serialize JSON")
return
}
let outputURL = URL(fileURLWithPath: outputPath)
try jsonString.write(to: outputURL, atomically: false, encoding: .utf8)
let elapsed = Date().timeIntervalSince(startTime)
print("[SwiftFace] Done: \(allFrames.count) frames, \(String(format: "%.1f", elapsed))s → \(outputPath)")
}
}
+855
View File
@@ -0,0 +1,855 @@
import Foundation
import Vision
import ArgumentParser
import AVFoundation
import CoreImage
// MARK: - HSV Histogram Utilities
/// Convert BGRA pixel buffer to HSV histogram
/// Returns normalized [H, S, V] histograms (30 bins for H, 32 for S, 32 for V)
func computeHSVHistogram(pixelBuffer: CVPixelBuffer, bbox: [String: Int]? = nil) -> ([Double], [Double], [Double]) {
let imgW = CVPixelBufferGetWidth(pixelBuffer)
let imgH = CVPixelBufferGetHeight(pixelBuffer)
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }
guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else {
return ([], [], [])
}
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
let buffer = baseAddress.bindMemory(to: UInt8.self, capacity: bytesPerRow * imgH)
// Determine ROI
let x1 = bbox.map { max(0, $0["x"] ?? 0) } ?? 0
let y1 = bbox.map { max(0, $0["y"] ?? 0) } ?? 0
let x2 = bbox.map { min(imgW, ($0["x"] ?? 0) + ($0["width"] ?? imgW)) } ?? imgW
let y2 = bbox.map { min(imgH, ($0["y"] ?? 0) + ($0["height"] ?? imgH)) } ?? imgH
// Histogram bins: H=30 (0-180), S=32 (0-256), V=32 (0-256)
var hHist = Array(repeating: 0.0, count: 30)
var sHist = Array(repeating: 0.0, count: 32)
var vHist = Array(repeating: 0.0, count: 32)
var totalPixels = 0
for y in y1..<y2 {
let rowStart = y * bytesPerRow
for x in x1..<x2 {
let offset = rowStart + x * 4
let b = Double(buffer[offset])
let g = Double(buffer[offset + 1])
let r = Double(buffer[offset + 2])
// RGB to HSV
let maxVal = max(r, g, b) / 255.0
let minVal = min(r, g, b) / 255.0
let delta = maxVal - minVal
var h: Double = 0
let s: Double
let v = maxVal
if delta > 0.001 {
s = delta / maxVal
if maxVal == r {
h = 60.0 * ((g - b) / 255.0 / delta)
} else if maxVal == g {
h = 60.0 * (2.0 + (b - r) / 255.0 / delta)
} else {
h = 60.0 * (4.0 + (r - g) / 255.0 / delta)
}
if h < 0 { h += 360.0 }
} else {
s = 0
}
// Bin: H 0-180 -> 30 bins, S 0-256 -> 32 bins, V 0-256 -> 32 bins
let hBin = min(29, Int(h / 6.0))
let sBin = min(31, Int(s * 32.0))
let vBin = min(31, Int(v * 32.0))
hHist[hBin] += 1
sHist[sBin] += 1
vHist[vBin] += 1
totalPixels += 1
}
}
// Normalize
let hSum = hHist.reduce(0, +)
let sSum = sHist.reduce(0, +)
let vSum = vHist.reduce(0, +)
if hSum > 0 { hHist = hHist.map { $0 / hSum } }
if sSum > 0 { sHist = sHist.map { $0 / sSum } }
if vSum > 0 { vHist = vHist.map { $0 / vSum } }
return (hHist, sHist, vHist)
}
/// Compute Bhattacharyya coefficient between two normalized histograms
/// Returns similarity score in [0, 1]
func histogramSimilarity(hist1: [Double], hist2: [Double]) -> Double {
guard hist1.count == hist2.count, !hist1.isEmpty else { return 0.0 }
var sum = 0.0
for i in 0..<hist1.count {
let a = hist1[i]
let b = hist2[i]
if a > 0 && b > 0 {
sum += sqrt(a * b)
}
}
return sum // Bhattacharyya coefficient [0, 1]
}
/// Combined HSV similarity (average of H, S, V similarities)
func combinedHSVSimilarity(hist1: ([Double], [Double], [Double]), hist2: ([Double], [Double], [Double])) -> Double {
let hSim = histogramSimilarity(hist1: hist1.0, hist2: hist2.0)
let sSim = histogramSimilarity(hist1: hist1.1, hist2: hist2.1)
let vSim = histogramSimilarity(hist1: hist1.2, hist2: hist2.2)
return (hSim + sSim + vSim) / 3.0
}
// MARK: - Frame processing helpers
/// Result from processing a single frame for face detection
struct FrameFaceResult {
let hasFace: Bool
let faces: [[String: Any]]
let landmarkObservations: [VNFaceObservation]
}
/// Result from processing a single frame for pose detection
struct FramePoseResult {
let hasPose: Bool
let persons: [[String: Any]]
}
/// Process a single frame for face detection
func processFrameForFace(pixelBuffer: CVPixelBuffer, fps: Float) -> FrameFaceResult {
let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer))
let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer))
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
let faceReq = VNDetectFaceRectanglesRequest()
let lmReq = VNDetectFaceLandmarksRequest()
do {
try handler.perform([faceReq, lmReq])
} catch {
return FrameFaceResult(hasFace: false, faces: [], landmarkObservations: [])
}
let faceObservations = faceReq.results ?? []
let landmarkObservations = lmReq.results ?? []
var faces: [[String: Any]] = []
var hasFace = false
let MIN_CONFIDENCE = 0.6
let MIN_SIZE = 20
if !faceObservations.isEmpty || !landmarkObservations.isEmpty {
hasFace = true
for lmObs in landmarkObservations {
let lmConf = Double(lmObs.confidence)
if lmConf < MIN_CONFIDENCE { continue }
let bb = lmObs.boundingBox
let faceW = Int(bb.size.width * imgW)
let faceH = Int(bb.size.height * imgH)
if faceW < MIN_SIZE || faceH < MIN_SIZE { continue }
let faceX = Int(bb.origin.x * imgW)
let faceY = Int((1.0 - bb.origin.y - bb.size.height) * imgH)
var faceData: [String: Any] = [
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
"width": faceW, "height": faceH],
"confidence": Double(lmObs.confidence),
"captureQuality": Double(lmObs.value(forKey: "faceCaptureQuality") as? Double ?? 0),
]
if let yaw = lmObs.yaw?.doubleValue,
let roll = lmObs.roll?.doubleValue {
var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw]
if let pitch = lmObs.pitch?.doubleValue {
poseInfo["pitch"] = pitch
}
faceData["pose"] = poseInfo
}
if let lms = lmObs.landmarks {
let imgSize = CGSize(width: imgW, height: imgH)
let leftEye = lms.leftEye?.pointsInImage(imageSize: imgSize) ?? []
let rightEye = lms.rightEye?.pointsInImage(imageSize: imgSize) ?? []
let nose = lms.nose?.pointsInImage(imageSize: imgSize) ?? []
if !leftEye.isEmpty || !rightEye.isEmpty || !nose.isEmpty {
var lm: [String: [[Double]]] = [:]
if !leftEye.isEmpty {
lm["left_eye"] = leftEye.map { [Double($0.x), Double(imgH - $0.y)] }
}
if !rightEye.isEmpty {
lm["right_eye"] = rightEye.map { [Double($0.x), Double(imgH - $0.y)] }
}
if !nose.isEmpty {
lm["nose"] = nose.map { [Double($0.x), Double(imgH - $0.y)] }
}
faceData["landmarks"] = lm
}
let outer = lms.outerLips?.pointsInImage(imageSize: imgSize) ?? []
let inner = lms.innerLips?.pointsInImage(imageSize: imgSize) ?? []
if !outer.isEmpty || !inner.isEmpty {
faceData["lips"] = [
"outer_lips": outer.map { [Double($0.x), Double(imgH - $0.y)] },
"inner_lips": inner.map { [Double($0.x), Double(imgH - $0.y)] }
]
}
}
faces.append(faceData)
}
for faceObs in faceObservations {
let fBB = faceObs.boundingBox
var matched = false
for lmObs in landmarkObservations {
let lBB = lmObs.boundingBox
let ix = max(fBB.origin.x, lBB.origin.x)
let iy = max(fBB.origin.y, lBB.origin.y)
let iw = min(fBB.maxX, lBB.maxX) - ix
let ih = min(fBB.maxY, lBB.maxY) - iy
if iw <= 0 || ih <= 0 { continue }
let intersection = iw * ih
let union = fBB.width * fBB.height + lBB.width * lBB.height - intersection
if intersection / union > 0.3 {
matched = true
break
}
}
if matched { continue }
if faceObs.confidence < MIN_CONFIDENCE { continue }
let faceW = Int(fBB.size.width * imgW)
let faceH = Int(fBB.size.height * imgH)
if faceW < MIN_SIZE || faceH < MIN_SIZE { continue }
let faceX = Int(fBB.origin.x * imgW)
let faceY = Int((1.0 - fBB.origin.y - fBB.size.height) * imgH)
var faceData: [String: Any] = [
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
"width": faceW, "height": faceH],
"confidence": Double(faceObs.confidence),
"captureQuality": Double(faceObs.faceCaptureQuality ?? 0),
]
if let yaw = faceObs.yaw?.doubleValue,
let roll = faceObs.roll?.doubleValue {
var poseInfo: [String: Any] = ["roll": roll, "yaw": yaw]
if let pitch = faceObs.pitch?.doubleValue {
poseInfo["pitch"] = pitch
}
faceData["pose"] = poseInfo
}
faces.append(faceData)
}
}
return FrameFaceResult(hasFace: hasFace, faces: faces, landmarkObservations: landmarkObservations)
}
/// Process a single frame for pose detection
func processFrameForPose(pixelBuffer: CVPixelBuffer, landmarkObservations: [VNFaceObservation]? = nil) -> FramePoseResult {
let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer))
let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer))
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
let bodyReq = VNDetectHumanBodyPoseRequest()
do {
try handler.perform([bodyReq])
} catch {
return FramePoseResult(hasPose: false, persons: [])
}
let jointNames: [VNHumanBodyPoseObservation.JointName] = [
.nose, .leftEye, .rightEye, .leftEar, .rightEar,
.neck, .root,
.leftShoulder, .rightShoulder,
.leftElbow, .rightElbow,
.leftWrist, .rightWrist,
.leftHip, .rightHip,
.leftKnee, .rightKnee,
.leftAnkle, .rightAnkle,
]
var persons: [[String: Any]] = []
// If we have face landmarks, extract pose keypoints from them
let lmObs = landmarkObservations?.first
if let lmObs = lmObs, let lms = lmObs.landmarks {
let lmConf = Double(lmObs.confidence)
if lmConf >= 0.6 {
let imgSize = CGSize(width: imgW, height: imgH)
var keypoints: [[String: Any]] = []
if let nosePoints = lms.nose?.pointsInImage(imageSize: imgSize) {
for pt in nosePoints {
keypoints.append([
"name": "nose",
"x": Double(pt.x),
"y": Double(imgH - pt.y),
"confidence": lmConf
])
}
}
if let leftEyePoints = lms.leftEye?.pointsInImage(imageSize: imgSize) {
for pt in leftEyePoints {
keypoints.append([
"name": "left_eye",
"x": Double(pt.x),
"y": Double(imgH - pt.y),
"confidence": lmConf
])
}
}
if let rightEyePoints = lms.rightEye?.pointsInImage(imageSize: imgSize) {
for pt in rightEyePoints {
keypoints.append([
"name": "right_eye",
"x": Double(pt.x),
"y": Double(imgH - pt.y),
"confidence": lmConf
])
}
}
if !keypoints.isEmpty {
persons.append([
"keypoints": keypoints,
"bbox": ["x": 0, "y": 0, "width": 0, "height": 0]
])
}
}
}
// Also process body pose detections
let poses = bodyReq.results ?? []
for pose in poses {
var keypoints: [[String: Any]] = []
var minX = CGFloat.greatestFiniteMagnitude
var minY = CGFloat.greatestFiniteMagnitude
var maxX: CGFloat = 0
var maxY: CGFloat = 0
for joint in jointNames {
if let point = try? pose.recognizedPoint(joint) {
let desc = String(describing: joint.rawValue)
var rawName = desc
.replacingOccurrences(of: "VNRecognizedPointKey(_rawValue: ", with: "")
.replacingOccurrences(of: ")", with: "")
.trimmingCharacters(in: .whitespaces)
let nameMap: [String: String] = [
"head_joint": "nose",
"left_eye_joint": "left_eye",
"right_eye_joint": "right_eye",
"left_ear_joint": "left_ear",
"right_ear_joint": "right_ear",
"neck_1_joint": "neck",
"left_shoulder_1_joint": "left_shoulder",
"right_shoulder_1_joint": "right_shoulder",
"left_elbow_1_joint": "left_elbow",
"right_elbow_1_joint": "right_elbow",
"left_hand_joint": "left_wrist",
"right_hand_joint": "right_wrist",
"left_hip_1_joint": "left_hip",
"right_hip_1_joint": "right_hip",
"left_knee_1_joint": "left_knee",
"right_knee_1_joint": "right_knee",
"left_ankle_1_joint": "left_ankle",
"right_ankle_1_joint": "right_ankle",
"center_hip_joint": "root",
]
if let mapped = nameMap[rawName] {
rawName = mapped
}
let px = point.location.x * CGFloat(imgW)
let py = CGFloat(imgH) - point.location.y * CGFloat(imgH)
keypoints.append([
"name": rawName.isEmpty ? "\(joint)" : rawName,
"x": px,
"y": py,
"confidence": point.confidence,
])
if point.confidence > 0.1 {
minX = min(minX, px)
minY = min(minY, py)
maxX = max(maxX, px)
maxY = max(maxY, py)
}
}
}
var bbox: [String: Any] = ["x": 0, "y": 0, "width": 0, "height": 0]
if maxX > minX {
bbox = [
"x": Int(minX),
"y": Int(minY),
"width": Int(maxX - minX),
"height": Int(maxY - minY),
]
}
persons.append(["keypoints": keypoints, "bbox": bbox])
}
let hasPose = !persons.isEmpty
return FramePoseResult(hasPose: hasPose, persons: persons)
}
// MARK: - Main processor
/// Swift Face+Pose+Appearance Processor - three-stage pipeline
/// Stage 1: 8Hz sampled Face detection
/// Stage 2: Pose expansion (forward/backward until 3 consecutive misses)
/// Stage 3: Appearance expansion (HSV histogram similarity, 3 consecutive < 0.5)
/// Output: face.json, pose.json, appearance.json (all 8Hz sampled)
@main
struct SwiftFacePose: ParsableCommand {
@Argument(help: "Video file path")
var inputPath: String
@Argument(help: "Output JSON path for face detection")
var faceOutput: String
@Argument(help: "Output JSON path for pose detection")
var poseOutput: String
@Argument(help: "Output JSON path for appearance detection")
var appearanceOutput: String
@Option(name: .long, help: "Sample interval (frames, default=30)")
var sampleInterval: Int = 30
@Option(name: .long, help: "UUID for logging")
var uuid: String = ""
// Expansion parameters
let expansionMissThreshold = 3 // consecutive misses to stop expansion
let appearanceSimilarityThreshold = 0.5 // HSV histogram similarity threshold
mutating func run() throws {
let startTime = Date()
print("[SwiftFacePose] Vision face+pose+appearance detection: \(inputPath)")
let url = URL(fileURLWithPath: inputPath)
let asset = AVAsset(url: url)
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
print("[SwiftFacePose] No video track found")
return
}
let fps = videoTrack.nominalFrameRate
let duration = CMTimeGetSeconds(asset.duration)
let totalFrames = Int(duration * Double(fps))
print("[SwiftFacePose] Video: \(Int(videoTrack.naturalSize.width))x\(Int(videoTrack.naturalSize.height)), \(String(format: "%.1f", fps))fps, \(totalFrames) frames, interval=\(sampleInterval)")
let outputSettings: [String: Any] = [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA
]
// ============================================================
// Stage 1: 8Hz sampled Face detection + Pose = Face
// ============================================================
print("[SwiftFacePose] Stage 1: 8Hz face sampling + pose=face...")
var faceFrames: [[String: Any]] = []
var faceFrameSet = Set<Int>()
var poseFrameDict: [Int: [String: Any]] = [:]
var poseFrameSet = Set<Int>()
do {
let reader = try AVAssetReader(asset: asset)
let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings)
trackOutput.alwaysCopiesSampleData = false
reader.add(trackOutput)
guard reader.startReading() else {
print("[SwiftFacePose] Failed to start reader for stage 1")
return
}
var frameIndex = 0
var processedCount = 0
while let sampleBuffer = trackOutput.copyNextSampleBuffer() {
defer { frameIndex += 1 }
if frameIndex % sampleInterval != 0 {
continue
}
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
continue
}
let result = processFrameForFace(pixelBuffer: pixelBuffer, fps: fps)
if result.hasFace && !result.faces.isEmpty {
let seconds = Double(frameIndex) / Double(fps)
faceFrames.append([
"frame": frameIndex,
"timestamp": seconds,
"faces": result.faces,
])
faceFrameSet.insert(frameIndex)
// Stage 1: Pose = Face (use face landmarks as pose keypoints)
let poseResult = processFrameForPose(pixelBuffer: pixelBuffer, landmarkObservations: result.landmarkObservations)
if poseResult.hasPose {
poseFrameDict[frameIndex] = [
"frame": frameIndex,
"timestamp": seconds,
"persons": poseResult.persons,
]
poseFrameSet.insert(frameIndex)
}
}
processedCount += 1
if processedCount % 100 == 0 {
let elapsed = Date().timeIntervalSince(startTime)
let totalSamples = totalFrames / sampleInterval
let pct = Int(Double(processedCount) / Double(totalSamples) * 100)
print("[SwiftFacePose] Stage 1: \(faceFrames.count) face frames, \(pct)% complete, \(Int(elapsed))s")
fflush(stdout)
}
}
reader.cancelReading()
}
print("[SwiftFacePose] Stage 1 done: \(faceFrames.count) face frames, \(poseFrameDict.count) pose frames")
// ============================================================
// Stage 2: Pose expansion (from face frames, forward/backward)
// ============================================================
print("[SwiftFacePose] Stage 2: Pose expansion...")
// Full pass to detect pose on all frames
do {
let reader = try AVAssetReader(asset: asset)
let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings)
trackOutput.alwaysCopiesSampleData = false
reader.add(trackOutput)
guard reader.startReading() else {
print("[SwiftFacePose] Failed to start reader for stage 2")
return
}
var frameIndex = 0
var processedCount = 0
var consecutiveMisses = 0
let maxConsecutiveMisses = 300 // stop after 300 consecutive misses (10s at 30fps)
while let sampleBuffer = trackOutput.copyNextSampleBuffer() {
defer { frameIndex += 1 }
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
continue
}
// Check if we should process this frame:
// 1. It's near a face frame (within 300 frames)
// 2. Or we're in an expansion streak
let nearFaceFrame = faceFrameSet.contains { faceFrame in
abs(faceFrame - frameIndex) <= 300
}
if nearFaceFrame || consecutiveMisses < maxConsecutiveMisses {
let result = processFrameForPose(pixelBuffer: pixelBuffer)
let seconds = Double(frameIndex) / Double(fps)
if result.hasPose {
poseFrameDict[frameIndex] = [
"frame": frameIndex,
"timestamp": seconds,
"persons": result.persons,
]
poseFrameSet.insert(frameIndex)
consecutiveMisses = 0
} else {
// Try with face landmarks if this is a face frame
if faceFrameSet.contains(frameIndex) {
let faceResult = processFrameForFace(pixelBuffer: pixelBuffer, fps: fps)
if faceResult.hasFace {
let poseResult = processFrameForPose(pixelBuffer: pixelBuffer, landmarkObservations: faceResult.landmarkObservations)
if poseResult.hasPose {
poseFrameDict[frameIndex] = [
"frame": frameIndex,
"timestamp": seconds,
"persons": poseResult.persons,
]
poseFrameSet.insert(frameIndex)
consecutiveMisses = 0
continue
}
}
}
consecutiveMisses += 1
}
}
processedCount += 1
if processedCount % 5000 == 0 {
let elapsed = Date().timeIntervalSince(startTime)
print("[SwiftFacePose] Stage 2: \(poseFrameDict.count) pose frames, frame \(frameIndex), \(Int(elapsed))s")
fflush(stdout)
}
}
reader.cancelReading()
}
print("[SwiftFacePose] Stage 2 done: \(poseFrameDict.count) pose frames")
// ============================================================
// Stage 3: Appearance expansion (from pose frames, HSV similarity)
// ============================================================
print("[SwiftFacePose] Stage 3: Appearance expansion...")
var appearanceFrameDict: [Int: [String: Any]] = [:]
// Full pass to detect appearance on all pose frames
var referenceHistograms: [Int: ([Double], [Double], [Double])] = [:]
var consecutiveMisses = 0
let maxConsecutiveMisses = 300 // stop after 300 consecutive misses
do {
let reader = try AVAssetReader(asset: asset)
let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings)
trackOutput.alwaysCopiesSampleData = false
reader.add(trackOutput)
guard reader.startReading() else {
print("[SwiftFacePose] Failed to start reader for stage 3")
return
}
var frameIndex = 0
var processedCount = 0
while let sampleBuffer = trackOutput.copyNextSampleBuffer() {
defer { frameIndex += 1 }
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
continue
}
// Check if we should process this frame
let nearPoseFrame = poseFrameSet.contains { poseFrame in
abs(poseFrame - frameIndex) <= 300
}
if nearPoseFrame || consecutiveMisses < maxConsecutiveMisses {
// If this is a pose frame, compute reference histogram
if poseFrameSet.contains(frameIndex) {
let hist = computeHSVHistogram(pixelBuffer: pixelBuffer)
referenceHistograms[frameIndex] = hist
consecutiveMisses = 0
let poseData = poseFrameDict[frameIndex]
let seconds = Double(frameIndex) / Double(fps)
appearanceFrameDict[frameIndex] = [
"frame": frameIndex,
"timestamp": seconds,
"persons": poseData?["persons"] ?? [],
"hsv_histogram": [hist.0, hist.1, hist.2],
]
} else if !referenceHistograms.isEmpty {
// Check similarity with nearest reference
let nearestRef = referenceHistograms
.sorted { abs($0.key - frameIndex) < abs($1.key - frameIndex) }
.first
if let (refFrame, refHist) = nearestRef {
let currentHist = computeHSVHistogram(pixelBuffer: pixelBuffer)
let similarity = combinedHSVSimilarity(hist1: currentHist, hist2: refHist)
if similarity >= appearanceSimilarityThreshold {
let seconds = Double(frameIndex) / Double(fps)
// Find nearest pose data
let nearestPoseData = poseFrameDict[refFrame]
appearanceFrameDict[frameIndex] = [
"frame": frameIndex,
"timestamp": seconds,
"persons": nearestPoseData?["persons"] ?? [],
"hsv_histogram": [currentHist.0, currentHist.1, currentHist.2],
]
consecutiveMisses = 0
} else {
consecutiveMisses += 1
}
}
}
}
processedCount += 1
if processedCount % 5000 == 0 {
let elapsed = Date().timeIntervalSince(startTime)
print("[SwiftFacePose] Stage 3: \(appearanceFrameDict.count) appearance frames, frame \(frameIndex), \(Int(elapsed))s")
fflush(stdout)
}
}
reader.cancelReading()
}
print("[SwiftFacePose] Stage 3 done: \(appearanceFrameDict.count) appearance frames")
// ============================================================
// Stage 4: 8Hz sampling output
// ============================================================
print("[SwiftFacePose] Stage 4: 8Hz sampling output...")
// Sample face frames (already at 8Hz)
let outputFaceFrames = faceFrames
// Convert poseFrameDict to sorted array for efficient search
let sortedPoseFrames = poseFrameDict.sorted { $0.key < $1.key }.map { $0.value }
let sortedPoseFrameNumbers = poseFrameDict.keys.sorted()
// Sample pose frames (take closest to 8Hz grid)
var outputPoseFrames: [[String: Any]] = []
var frameIdx = 0
while frameIdx < totalFrames {
// Binary search for closest pose frame
let searchRadius = sampleInterval // ±30 frames
let searchStart = max(0, frameIdx - searchRadius)
let searchEnd = min(totalFrames - 1, frameIdx + searchRadius)
// Find closest pose frame in range
var closestPoseFrame: [String: Any]?
var closestDist = Int.max
for f in searchStart...searchEnd {
if let data = poseFrameDict[f] {
let dist = abs(f - frameIdx)
if dist < closestDist {
closestDist = dist
closestPoseFrame = data
}
}
}
// If no frame found in range, find the nearest one regardless of distance
if closestPoseFrame == nil {
for f in sortedPoseFrameNumbers {
let dist = abs(f - frameIdx)
if dist < closestDist {
closestDist = dist
closestPoseFrame = poseFrameDict[f]
}
}
}
if let data = closestPoseFrame {
outputPoseFrames.append(data)
}
frameIdx += sampleInterval
}
// Sample appearance frames (take closest to 8Hz grid)
var outputAppearanceFrames: [[String: Any]] = []
let sortedAppearanceFrameNumbers = appearanceFrameDict.keys.sorted()
frameIdx = 0
while frameIdx < totalFrames {
let searchRadius = sampleInterval // ±30 frames
let searchStart = max(0, frameIdx - searchRadius)
let searchEnd = min(totalFrames - 1, frameIdx + searchRadius)
var closestAppearanceFrame: [String: Any]?
var closestDist = Int.max
for f in searchStart...searchEnd {
if let data = appearanceFrameDict[f] {
let dist = abs(f - frameIdx)
if dist < closestDist {
closestDist = dist
closestAppearanceFrame = data
}
}
}
// If no frame found in range, find the nearest one
if closestAppearanceFrame == nil {
for f in sortedAppearanceFrameNumbers {
let dist = abs(f - frameIdx)
if dist < closestDist {
closestDist = dist
closestAppearanceFrame = appearanceFrameDict[f]
}
}
}
if let data = closestAppearanceFrame {
outputAppearanceFrames.append(data)
}
frameIdx += sampleInterval
}
// ============================================================
// Write output files
// ============================================================
// face.json
let faceOutputDict: [String: Any] = [
"frame_count": outputFaceFrames.count,
"fps": Double(fps),
"frames": outputFaceFrames,
]
do {
let faceJson = try JSONSerialization.data(withJSONObject: faceOutputDict, options: [])
try faceJson.write(to: URL(fileURLWithPath: faceOutput))
print("[SwiftFacePose] Face output written: \(faceOutput)")
} catch {
print("[SwiftFacePose] ERROR writing face output: \(error)")
}
// pose.json
let poseOutputDict: [String: Any] = [
"frame_count": outputPoseFrames.count,
"fps": Double(fps),
"frames": outputPoseFrames,
]
do {
let poseJson = try JSONSerialization.data(withJSONObject: poseOutputDict, options: [.prettyPrinted])
try poseJson.write(to: URL(fileURLWithPath: poseOutput))
print("[SwiftFacePose] Pose output written: \(poseOutput)")
} catch {
print("[SwiftFacePose] ERROR writing pose output: \(error)")
}
// appearance.json
let appearanceOutputDict: [String: Any] = [
"frame_count": outputAppearanceFrames.count,
"fps": Double(fps),
"frames": outputAppearanceFrames,
]
do {
let appearanceJson = try JSONSerialization.data(withJSONObject: appearanceOutputDict, options: [.prettyPrinted])
try appearanceJson.write(to: URL(fileURLWithPath: appearanceOutput))
print("[SwiftFacePose] Appearance output written: \(appearanceOutput)")
} catch {
print("[SwiftFacePose] ERROR writing appearance output: \(error)")
}
let elapsed = Date().timeIntervalSince(startTime)
print("[SwiftFacePose] Done: \(outputFaceFrames.count) face, \(outputPoseFrames.count) pose, \(outputAppearanceFrames.count) appearance frames, \(String(format: "%.1f", elapsed))s")
}
}
+299
View File
@@ -0,0 +1,299 @@
import Foundation
import Vision
import ArgumentParser
import AppKit
import AVFoundation
/// Swift Hand Pose Processor
/// Uses Apple Vision Framework VNDetectHumanHandPoseRequest for 21 hand landmarks
@main
struct SwiftHandProcessor: ParsableCommand {
@Argument(help: "Input video path")
var inputPath: String
@Argument(help: "Output JSON path")
var outputPath: String
@Option(name: [.short, .long], help: "UUID for the file")
var uuid: String = ""
@Option(name: [.short, .long], help: "Sample interval (frames)")
var sampleInterval: Int = 3
@Option(name: [.long], help: "Minimum confidence threshold")
var minConfidence: Double = 0.3
func run() throws {
print("[SwiftHand] Starting: \(inputPath)")
let url = URL(fileURLWithPath: inputPath)
let asset = AVURLAsset(url: url)
guard let track = asset.tracks(withMediaType: AVMediaType.video).first else {
print("[SwiftHand] Error: No video track"); return
}
let duration = asset.duration.seconds
let fps = Double(track.nominalFrameRate)
print("[SwiftHand] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", fps))")
// Extract frames using ffmpeg (same approach as swift_pose)
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("swift_hand_\(UUID().uuidString)")
let framesDir = tempDir.appendingPathComponent("frames")
try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true)
let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path
print("[SwiftHand] Extracting frames...")
let extract = Process()
extract.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
extract.arguments = ["-y", "-v", "quiet", "-i", inputPath,
"-vf", "select=not(mod(n\\,\(sampleInterval)))",
"-vsync", "vfr", "-q:v", "15", pattern]
try extract.run()
extract.waitUntilExit()
let files = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? []
let frameFiles = files.filter { $0.hasSuffix(".jpg") }.sorted()
print("[SwiftHand] Extracted \(frameFiles.count) frames")
// Hand joint names (21 landmarks)
let jointNames: [VNHumanHandPoseObservation.JointName] = [
.wrist,
.thumbTip, .thumbIP, .thumbMP, .thumbCMC,
.indexTip, .indexDIP, .indexPIP, .indexMCP,
.middleTip, .middleDIP, .middlePIP, .middleMCP,
.ringTip, .ringDIP, .ringPIP, .ringMCP,
.littleTip, .littleDIP, .littlePIP, .littleMCP,
]
var handFrames: [[String: Any]] = []
var lastProgress = 0
for (i, fname) in frameFiles.enumerated() {
let imgPath = framesDir.appendingPathComponent(fname).path
guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)),
let img = NSImage(data: imgData),
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue }
let frameNum = Int(fname.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? (i * sampleInterval)
let timestamp = Double(frameNum) / fps
let w = cgImage.width
let h = cgImage.height
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
let req = VNDetectHumanHandPoseRequest()
try? handler.perform([req])
guard let hands = req.results, !hands.isEmpty else { continue }
var persons: [[String: Any]] = []
for (handIdx, hand) in hands.enumerated() {
if Float(hand.confidence) < Float(minConfidence) {
continue
}
var landmarks: [[String: Any]] = []
for joint in jointNames {
if let point = try? hand.recognizedPoint(joint) {
let desc = String(describing: joint.rawValue.rawValue)
let rawName = desc
.replacingOccurrences(of: "VNRecognizedPointKey(_rawValue: ", with: "")
.replacingOccurrences(of: ")", with: "")
.trimmingCharacters(in: .whitespaces)
let name = mapJointName(rawName)
let px = Float(point.location.x) * Float(w)
let py = Float(h) - Float(point.location.y) * Float(h) // Y-flip to Top-Left
let conf = Float(point.confidence)
if conf > 0.1 {
landmarks.append([
"name": name,
"x": px,
"y": py,
"confidence": conf
])
}
}
}
// Gesture detection
let gesture = detectGesture(hand)
let handType = handIdx == 0 ? "left" : "right"
persons.append([
"person_id": handIdx,
"hand_type": handType,
"confidence": Float(hand.confidence),
"landmarks": landmarks,
"num_landmarks": landmarks.count,
"gesture": gesture["gesture"] as? String ?? "unknown",
"hand_state": gesture["hand_state"] as? String ?? "empty",
"finger_extensions": gesture["finger_extensions"] as? [String: Bool] ?? [:],
"num_fingers_extended": gesture["num_fingers_extended"] as? Int ?? 0,
"num_fingers_curled": gesture["num_fingers_curled"] as? Int ?? 0
])
}
if !persons.isEmpty {
handFrames.append([
"frame": frameNum,
"timestamp": timestamp,
"persons": persons
])
}
// Progress reporting
let progress = (i + 1) * 100 / frameFiles.count
if progress > lastProgress && progress % 10 == 0 {
print("[SwiftHand] Progress: \(progress)% (\(handFrames.count) hand frames)")
lastProgress = progress
}
}
// Cleanup temp directory
try? FileManager.default.removeItem(at: tempDir)
// Build output JSON
let outputData: [String: Any] = [
"frame_count": handFrames.count,
"fps": fps,
"frames": handFrames,
"metadata": [
"source": "swift_hand",
"uuid": uuid,
"landmarks_per_hand": 21,
"min_confidence": minConfidence,
"sample_interval": sampleInterval
]
]
let jsonData = try JSONSerialization.data(withJSONObject: outputData, options: [.prettyPrinted])
try jsonData.write(to: URL(fileURLWithPath: outputPath))
print("[SwiftHand] Complete: \(handFrames.count) frames with hands")
print("[SwiftHand] Output: \(outputPath)")
}
/// Map Vision joint codes to readable names
func mapJointName(_ rawName: String) -> String {
let mapping: [String: String] = [
"VNHLKWRI": "wrist",
"VNHLKTIP": "thumb_tip",
"VNHLKTTIP": "thumb_tip",
"VNHLKTMP": "thumb_mp",
"VNHLKTCMC": "thumb_cmc",
"VNHLKITIP": "index_tip",
"VNHLKIDIP": "index_dip",
"VNHLKIPIP": "index_pip",
"VNHLKIMCP": "index_mcp",
"VNHLKMTIP": "middle_tip",
"VNHLKMDIP": "middle_dip",
"VNHLKMPIP": "middle_pip",
"VNHLKMMCP": "middle_mcp",
"VNHLKRTIP": "ring_tip",
"VNHLKRDIP": "ring_dip",
"VNHLKRPIP": "ring_pip",
"VNHLKRMCP": "ring_mcp",
"VNHLKPTIP": "little_tip",
"VNHLKPDIP": "little_dip",
"VNHLKPPIP": "little_pip",
"VNHLKPMCP": "little_mcp",
]
return mapping[rawName] ?? rawName.lowercased()
}
/// Detect gesture from finger extensions
/// Returns: gesture, hand_state ("empty" or "holding"), finger info
func detectGesture(_ hand: VNHumanHandPoseObservation) -> [String: Any] {
// Finger extension check (tip lower than pip after flip = extended)
func isFingerExtended(tipName: VNHumanHandPoseObservation.JointName, pipName: VNHumanHandPoseObservation.JointName) -> Bool {
guard let tip = try? hand.recognizedPoint(tipName),
let pip = try? hand.recognizedPoint(pipName) else { return false }
return tip.confidence > 0.3 && pip.confidence > 0.3 && tip.location.y > pip.location.y
}
// Finger curled check (tip higher than pip after flip = curled around object)
func isFingerCurled(tipName: VNHumanHandPoseObservation.JointName, pipName: VNHumanHandPoseObservation.JointName) -> Bool {
guard let tip = try? hand.recognizedPoint(tipName),
let pip = try? hand.recognizedPoint(pipName) else { return false }
return tip.confidence > 0.3 && pip.confidence > 0.3 && tip.location.y < pip.location.y
}
// Thumb: tip vs cmc (horizontal distance)
func isThumbExtended() -> Bool {
guard let tip = try? hand.recognizedPoint(.thumbTip),
let cmc = try? hand.recognizedPoint(.thumbCMC) else { return false }
return tip.confidence > 0.3 && cmc.confidence > 0.3 &&
abs(tip.location.x - cmc.location.x) > 0.05
}
let thumb = isThumbExtended()
let index = isFingerExtended(tipName: .indexTip, pipName: .indexPIP)
let middle = isFingerExtended(tipName: .middleTip, pipName: .middlePIP)
let ring = isFingerExtended(tipName: .ringTip, pipName: .ringPIP)
let little = isFingerExtended(tipName: .littleTip, pipName: .littlePIP)
// Curled fingers (holding object indicator)
let indexCurled = isFingerCurled(tipName: .indexTip, pipName: .indexPIP)
let middleCurled = isFingerCurled(tipName: .middleTip, pipName: .middlePIP)
let ringCurled = isFingerCurled(tipName: .ringTip, pipName: .ringPIP)
let littleCurled = isFingerCurled(tipName: .littleTip, pipName: .littlePIP)
let extensions: [String: Bool] = [
"thumb": thumb,
"index": index,
"middle": middle,
"ring": ring,
"little": little
]
let numExtended = extensions.values.filter { $0 }.count
let numCurled = [indexCurled, middleCurled, ringCurled, littleCurled].filter { $0 }.count
var gesture = "unknown"
var handState = "empty" // "empty" or "holding"
// === HOLDING DETECTION ===
// Holding object: 2+ fingers curled, thumb may be wrapped or supporting
if numCurled >= 2 && !thumb {
// Fist-like grip without thumb extended
handState = "holding"
gesture = "holding_object"
} else if numCurled >= 3 {
// Multiple fingers wrapped around object
handState = "holding"
gesture = "holding_object"
}
// === EMPTY HAND GESTURES ===
else if numExtended == 5 {
gesture = "open_hand"
} else if numExtended == 0 {
gesture = "fist"
} else if thumb && numExtended == 1 {
gesture = "thumbs_up"
} else if index && numExtended == 1 {
gesture = "pointing"
} else if index && middle && numExtended == 2 {
gesture = "peace_sign"
} else if thumb && index && !middle && !ring && !little {
gesture = "ok_sign"
} else if thumb && index && middle && !ring && !little {
gesture = "three_fingers"
} else if numExtended >= 3 {
gesture = "partial_open"
}
return [
"gesture": gesture,
"hand_state": handState,
"finger_extensions": extensions,
"num_fingers_extended": numExtended,
"num_fingers_curled": numCurled
]
}
}
+220
View File
@@ -0,0 +1,220 @@
import Foundation
import Vision
import ArgumentParser
import AVFoundation
import AppKit
/// Swift OCR Processor - replaces Python PaddleOCR
/// Uses Apple Vision Framework (VNRecognizeTextRequest) with ANE acceleration
///
/// Output format (compatible with OcrResult Rust struct):
/// {
/// "frame_count": N,
/// "fps": 30.0,
/// "frames": [
/// { "frame": 0, "timestamp": 0.0, "texts": [{ "text": "...", "x": 0, "y": 0, "width": 0, "height": 0, "confidence": 0.0 }] }
/// ]
/// }
@main
struct SwiftOCR: ParsableCommand {
@Argument(help: "Video file path")
var inputPath: String
@Argument(help: "Output JSON path")
var outputPath: String
@Option(name: .long, help: "Frames to skip between OCR (default=30)")
var sampleInterval: Int = 30
@Option(name: .long, help: "Video FPS (auto-detect if 0)")
var fps: Double = 0
@Option(name: .long, help: "UUID for logging")
var uuid: String = ""
@Option(name: .long, help: "Recognition level: fast or accurate (default=accurate)")
var recognitionLevel: String = "accurate"
mutating func run() throws {
let startTime = Date()
print("[SwiftOCR] Starting: \(inputPath)")
print("[SwiftOCR] Sample interval: \(sampleInterval)")
let url = URL(fileURLWithPath: inputPath)
let asset = AVAsset(url: url)
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
print("[SwiftOCR] Error: No video track"); return
}
let duration = asset.duration.seconds
let detectedFps = fps > 0 ? fps : Double(videoTrack.nominalFrameRate)
let totalFrames = Int(duration * detectedFps)
print("[SwiftOCR] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", detectedFps)), Frames: \(totalFrames)")
let frameStep = sampleInterval
// Use shared frame cache if available (set by FrameManager)
let tempDir: URL
let framesDir: URL
if let cacheDir = ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] {
framesDir = URL(fileURLWithPath: cacheDir)
tempDir = framesDir // No cleanup needed (managed by FrameManager)
print("[SwiftOCR] Using shared frame cache: \(cacheDir)")
} else {
tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("swift_ocr_\(UUID().uuidString)")
framesDir = tempDir.appendingPathComponent("frames")
try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true)
let framePattern = framesDir.appendingPathComponent("frame_%05d.jpg").path
print("[SwiftOCR] Extracting frames with ffmpeg (interval=\(frameStep))...")
// Get video dimensions for smart scaling
let videoSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let videoWidth = Int(abs(videoSize.width))
let maxOcrWidth = 1920
let targetWidth = min(videoWidth, maxOcrWidth)
// Build scale filter: only downscale if video > 1920px wide
let scaleFilter: String
if videoWidth > maxOcrWidth {
scaleFilter = "select=not(mod(n\\,\(frameStep))),scale=\(targetWidth):-2"
print("[SwiftOCR] Video width \(videoWidth)px > \(maxOcrWidth)px, scaling to \(targetWidth)px")
} else {
scaleFilter = "select=not(mod(n\\,\(frameStep)))"
print("[SwiftOCR] Video width \(videoWidth)px <= \(maxOcrWidth)px, using native resolution")
}
let extractProc = Process()
extractProc.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
extractProc.arguments = ["-y", "-v", "quiet", "-i", inputPath,
"-vf", scaleFilter,
"-vsync", "vfr", "-q:v", "15", framePattern]
let startExtract = Date()
try extractProc.run()
extractProc.waitUntilExit()
let extractTime = Date().timeIntervalSince(startExtract)
print("[SwiftOCR] Frame extraction complete: \(String(format: "%.1f", extractTime))s")
}
// Sort extracted frame files
let fileManager = FileManager.default
let allFiles = (try? fileManager.contentsOfDirectory(atPath: framesDir.path)) ?? []
let frameFiles = allFiles
.filter { $0.hasPrefix("frame_") && $0.hasSuffix(".jpg") }
.sorted()
let level: VNRequestTextRecognitionLevel = (recognitionLevel == "fast") ? .fast : .accurate
var ocrFrames: [[String: Any]] = []
var lastProgress = 0
let totalFrames_to_process = frameFiles.count
for (i, frameName) in frameFiles.enumerated() {
let imgPath = framesDir.appendingPathComponent(frameName).path
guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)),
let img = NSImage(data: imgData),
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
continue
}
// Extract frame number from filename
let frameNumber = Int(frameName.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? (i * frameStep)
let timestamp = Double(frameNumber) / detectedFps
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
let request = VNRecognizeTextRequest()
request.recognitionLevel = level
request.usesLanguageCorrection = true
request.preferBackgroundProcessing = true
guard (try? handler.perform([request])) != nil,
let results = request.results else { continue }
var texts: [[String: Any]] = []
let cgW = cgImage.width
let cgH = cgImage.height
for obs in results {
guard let candidate = obs.topCandidates(1).first else { continue }
let conf = candidate.confidence
guard conf > 0.3 else { continue }
let bb = obs.boundingBox
let item: [String: Any] = [
"text": candidate.string,
"x": Int(bb.origin.x * CGFloat(cgW)),
"y": Int((1.0 - bb.origin.y - bb.size.height) * CGFloat(cgH)),
"width": Int(bb.size.width * CGFloat(cgW)),
"height": Int(bb.size.height * CGFloat(cgH)),
"confidence": Double(round(conf * 100)) / 100
]
texts.append(item)
}
if !texts.isEmpty {
ocrFrames.append([
"frame": frameNumber,
"timestamp": Double(round(timestamp * 100)) / 100,
"texts": texts
])
}
let pct = Int(Float(i) / Float(totalFrames_to_process) * 100)
if pct >= lastProgress + 5 {
print("[SwiftOCR] Progress: \(pct)% (\(i)/\(totalFrames_to_process) samples, \(ocrFrames.count) with text)")
lastProgress = pct
}
}
// Write output
let outputDict: [String: Any] = [
"frame_count": ocrFrames.count,
"fps": detectedFps,
"frames": ocrFrames
]
if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) {
try jsonData.write(to: URL(fileURLWithPath: outputPath))
}
let elapsed = Date().timeIntervalSince(startTime)
print("[SwiftOCR] Complete: \(ocrFrames.count) frames with text, \(String(format: "%.1f", elapsed))s")
if duration > 0 {
print("[SwiftOCR] RTF: \(String(format: "%.3f", elapsed / duration))x")
}
// Clean up temp dir if we created it (not shared cache)
if ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] == nil {
try? FileManager.default.removeItem(at: tempDir)
}
}
func recognizeText(pixelBuffer: CVPixelBuffer, level: VNRequestTextRecognitionLevel) -> [[String: Any]] {
var texts: [[String: Any]] = []
let request = VNRecognizeTextRequest()
request.recognitionLevel = level
request.usesLanguageCorrection = true
request.preferBackgroundProcessing = true
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
guard (try? handler.perform([request])) != nil,
let results = request.results else { return texts }
let cgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer))
let cgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer))
for obs in results {
guard let candidate = obs.topCandidates(1).first,
candidate.confidence > 0.2 else { continue }
let bb = obs.boundingBox
texts.append([
"text": candidate.string,
"x": Int(bb.origin.x * cgW),
"y": Int((1.0 - bb.origin.y - bb.size.height) * cgH),
"width": Int(bb.size.width * cgW),
"height": Int(bb.size.height * cgH),
"confidence": candidate.confidence
])
}
return texts
}
}
+222
View File
@@ -0,0 +1,222 @@
import Foundation
import Vision
import ArgumentParser
import AppKit
import AVFoundation
/// Swift Pose Processor - replaces YOLOv8 Pose / MediaPipe Pose
/// Uses VNDetectHumanBodyPoseRequest with ANE acceleration
///
/// Output format (compatible with PoseResult Rust struct):
/// {
/// "frame_count": N, "fps": 30.0,
/// "frames": [
/// { "frame": 0, "timestamp": 0.0, "persons": [
/// { "keypoints": [{"name":"nose","x":100,"y":200,"confidence":0.95}],
/// "bbox": {"x":0,"y":0,"width":100,"height":200}
/// }
/// ]}
/// ]
/// }
@main
struct SwiftPose: ParsableCommand {
@Argument(help: "Video file path")
var inputPath: String
@Argument(help: "Output JSON path")
var outputPath: String
@Option(name: .long, help: "Sample interval (frames, default=3)")
var sampleInterval: Int = 3
@Option(name: .long, help: "UUID for logging")
var uuid: String = ""
mutating func run() throws {
let startTime = Date()
print("[SwiftPose] Starting: \(inputPath)")
let url = URL(fileURLWithPath: inputPath)
let asset = AVAsset(url: url)
guard let track = asset.tracks(withMediaType: .video).first else {
print("[SwiftPose] Error: No video track"); return
}
let duration = asset.duration.seconds
let fps = Double(track.nominalFrameRate)
print("[SwiftPose] Duration: \(String(format: "%.1f", duration))s, FPS: \(String(format: "%.1f", fps))")
// Extract frames (use shared cache or ffmpeg)
let tempDir: URL
let framesDir: URL
if let cacheDir = ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] {
framesDir = URL(fileURLWithPath: cacheDir)
tempDir = framesDir
print("[SwiftPose] Using shared frame cache: \(cacheDir)")
} else {
tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("swift_pose_\(UUID().uuidString)")
framesDir = tempDir.appendingPathComponent("frames")
try FileManager.default.createDirectory(at: framesDir, withIntermediateDirectories: true)
let pattern = framesDir.appendingPathComponent("frame_%05d.jpg").path
print("[SwiftPose] Extracting frames...")
let extract = Process()
extract.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/ffmpeg")
extract.arguments = ["-y", "-v", "quiet", "-i", inputPath,
"-vf", "select=not(mod(n\\,\(sampleInterval)))",
"-vsync", "vfr", "-q:v", "15", pattern]
try extract.run()
extract.waitUntilExit()
}
let files = (try? FileManager.default.contentsOfDirectory(atPath: framesDir.path)) ?? []
let frameFiles = files.filter { $0.hasSuffix(".jpg") }.sorted()
print("[SwiftPose] Extracted \(frameFiles.count) frames")
let jointNames: [VNHumanBodyPoseObservation.JointName] = [
.nose, .leftEye, .rightEye, .leftEar, .rightEar,
.neck, .root,
.leftShoulder, .rightShoulder,
.leftElbow, .rightElbow,
.leftWrist, .rightWrist,
.leftHip, .rightHip,
.leftKnee, .rightKnee,
.leftAnkle, .rightAnkle,
]
var poseFrames: [[String: Any]] = []
var lastProgress = 0
for (i, fname) in frameFiles.enumerated() {
let imgPath = framesDir.appendingPathComponent(fname).path
guard let imgData = try? Data(contentsOf: URL(fileURLWithPath: imgPath)),
let img = NSImage(data: imgData),
let cgImage = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { continue }
let frameNum = Int(fname.replacingOccurrences(of: "frame_", with: "").replacingOccurrences(of: ".jpg", with: "")) ?? (i * sampleInterval)
let timestamp = Double(frameNum) / fps
let w = cgImage.width
let h = cgImage.height
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
let req = VNDetectHumanBodyPoseRequest()
try? handler.perform([req])
guard let poses = req.results, !poses.isEmpty else { continue }
var persons: [[String: Any]] = []
for pose in poses {
var keypoints: [[String: Any]] = []
var minX = CGFloat.greatestFiniteMagnitude
var minY = CGFloat.greatestFiniteMagnitude
var maxX: CGFloat = 0
var maxY: CGFloat = 0
for joint in jointNames {
if let point = try? pose.recognizedPoint(joint) {
let desc = String(describing: joint.rawValue)
var rawName = desc
.replacingOccurrences(of: "VNRecognizedPointKey(_rawValue: ", with: "")
.replacingOccurrences(of: ")", with: "")
.trimmingCharacters(in: .whitespaces)
// Map Vision Framework joint names to standard names
let nameMap: [String: String] = [
"head_joint": "nose",
"left_eye_joint": "left_eye",
"right_eye_joint": "right_eye",
"left_ear_joint": "left_ear",
"right_ear_joint": "right_ear",
"neck_1_joint": "neck",
"left_shoulder_1_joint": "left_shoulder",
"right_shoulder_1_joint": "right_shoulder",
"left_elbow_1_joint": "left_elbow",
"right_elbow_1_joint": "right_elbow",
"left_hand_joint": "left_wrist",
"right_hand_joint": "right_wrist",
"left_hip_1_joint": "left_hip",
"right_hip_1_joint": "right_hip",
"left_knee_1_joint": "left_knee",
"right_knee_1_joint": "right_knee",
"left_ankle_1_joint": "left_ankle",
"right_ankle_1_joint": "right_ankle",
"center_hip_joint": "root",
"left_forearm_joint": "left_elbow",
"right_forearm_joint": "right_elbow",
"left_upLeg_joint": "left_hip",
"right_upLeg_joint": "right_hip",
"left_leg_joint": "left_knee",
"right_leg_joint": "right_knee",
"left_foot_joint": "left_ankle",
"right_foot_joint": "right_ankle",
]
if let mapped = nameMap[rawName] {
rawName = mapped
}
let px = point.location.x * CGFloat(w)
let py = CGFloat(h) - point.location.y * CGFloat(h)
keypoints.append([
"name": rawName.isEmpty ? "\(joint)" : rawName,
"x": Double(round(px * 100)) / 100,
"y": Double(round(py * 100)) / 100,
"confidence": Double(round(point.confidence * 100)) / 100,
])
if point.confidence > 0.1 {
minX = min(minX, px)
minY = min(minY, py)
maxX = max(maxX, px)
maxY = max(maxY, py)
}
}
}
var bbox: [String: Any] = [
"x": 0, "y": 0, "width": 0, "height": 0
]
if maxX > minX {
bbox = [
"x": Int(minX),
"y": Int(minY),
"width": Int(maxX - minX),
"height": Int(maxY - minY),
]
}
persons.append(["keypoints": keypoints, "bbox": bbox])
}
if !persons.isEmpty {
poseFrames.append([
"frame": frameNum,
"timestamp": Double(round(timestamp * 100)) / 100,
"persons": persons,
])
}
let pct = Int(Float(i) / Float(frameFiles.count) * 100)
if pct >= lastProgress + 10 {
print("[SwiftPose] Progress: \(pct)% (\(i)/\(frameFiles.count), \(persons.count) poses)")
lastProgress = pct
}
}
// Write output
let outputDict: [String: Any] = [
"frame_count": poseFrames.count,
"fps": Double(round(fps * 100)) / 100,
"frames": poseFrames,
]
if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) {
try jsonData.write(to: URL(fileURLWithPath: outputPath))
}
let elapsed = Date().timeIntervalSince(startTime)
print("[SwiftPose] Complete: \(poseFrames.count) frames, \(String(format: "%.1f", elapsed))s")
if duration > 0 {
print("[SwiftPose] RTF: \(String(format: "%.3f", elapsed / duration))x")
}
// Clean up temp dir if we created it
if ProcessInfo.processInfo.environment["MOMENTRY_FRAME_DIR"] == nil {
try? FileManager.default.removeItem(at: tempDir)
}
}
}
+376
View File
@@ -0,0 +1,376 @@
import Foundation
import Vision
import ArgumentParser
import AVFoundation
/// Swift Pose Expansion Processor V2
///
/// Reads face_traced.json (from face tracking) and expands pose detection from trace frames.
/// Inherits trace_id from face traces for proper tracking continuity.
///
/// Algorithm:
/// 1. Load face_traced.json, extract frames grouped by trace_id
/// 2. For each trace_id, start from face frames and expand forward/backward
/// 3. Stop expansion when 3 consecutive frames have no pose detection
/// 4. Associate each pose with the nearest face's trace_id
/// 5. Output pose.json at 8Hz sampling (floor(fps/8) interval)
@main
struct SwiftPoseExpansion: ParsableCommand {
@Argument(help: "Video file path")
var videoPath: String
@Argument(help: "Input face_traced.json path")
var faceTracedPath: String
@Argument(help: "Output pose.json path")
var outputPath: String
@Option(name: .long, help: "UUID for logging")
var uuid: String = ""
@Option(name: .long, help: "Consecutive miss threshold to stop expansion (default: 3)")
var missThreshold: Int = 3
mutating func run() throws {
let startTime = Date()
print("[PoseExpansion] Starting pose expansion from face traces: \(videoPath)")
// Load face_traced.json
guard let faceData = try? Data(contentsOf: URL(fileURLWithPath: faceTracedPath)) else {
print("[PoseExpansion] ERROR: Cannot read \(faceTracedPath)")
return
}
guard let faceJson = try? JSONSerialization.jsonObject(with: faceData) as? [String: Any] else {
print("[PoseExpansion] ERROR: Invalid JSON in \(faceTracedPath)")
return
}
// Extract frames with trace_id mapping
// frameToTraces: frame -> [(trace_id, x, y, w, h)]
var frameToTraces: [Int: [(traceId: Int, x: Double, y: Double, w: Double, h: Double)]] = [:]
var allTraceIds: Set<Int> = []
// Handle both dict and list format
if let framesDict = faceJson["frames"] as? [String: Any] {
for (frameStr, frameData) in framesDict {
guard let frameNum = Int(frameStr) else { continue }
if let faces = (frameData as? [String: Any])?["faces"] as? [[String: Any]] {
for face in faces {
if let traceId = face["trace_id"] as? Int, traceId > 0 {
allTraceIds.insert(traceId)
let bbox = face["bbox"] as? [String: Any]
let x = bbox?["x"] as? Double ?? face["x"] as? Double ?? 0
let y = bbox?["y"] as? Double ?? face["y"] as? Double ?? 0
let w = bbox?["width"] as? Double ?? face["width"] as? Double ?? 0
let h = bbox?["height"] as? Double ?? face["height"] as? Double ?? 0
frameToTraces[frameNum, default: []].append((traceId, x, y, w, h))
}
}
}
}
} else if let framesList = faceJson["frames"] as? [[String: Any]] {
for frameData in framesList {
guard let frameNum = frameData["frame"] as? Int else { continue }
if let faces = frameData["faces"] as? [[String: Any]] {
for face in faces {
if let traceId = face["trace_id"] as? Int, traceId > 0 {
allTraceIds.insert(traceId)
let bbox = face["bbox"] as? [String: Any]
let x = bbox?["x"] as? Double ?? face["x"] as? Double ?? 0
let y = bbox?["y"] as? Double ?? face["y"] as? Double ?? 0
let w = bbox?["width"] as? Double ?? face["width"] as? Double ?? 0
let h = bbox?["height"] as? Double ?? face["height"] as? Double ?? 0
frameToTraces[frameNum, default: []].append((traceId, x, y, w, h))
}
}
}
}
}
print("[PoseExpansion] Found \(allTraceIds.count) traces, \(frameToTraces.count) frames in \(faceTracedPath)")
if frameToTraces.isEmpty {
print("[PoseExpansion] No traces found, skipping pose expansion")
let emptyOutput: [String: Any] = ["frame_count": 0, "fps": 0.0, "frames": []]
let jsonData = try JSONSerialization.data(withJSONObject: emptyOutput, options: [])
try jsonData.write(to: URL(fileURLWithPath: outputPath))
return
}
// Get video info
let url = URL(fileURLWithPath: videoPath)
let asset = AVAsset(url: url)
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
print("[PoseExpansion] ERROR: No video track")
return
}
let fps = videoTrack.nominalFrameRate
let duration = CMTimeGetSeconds(asset.duration)
let totalFrames = Int(duration * Double(fps))
let sampleInterval = max(1, Int(floor(Double(fps) / 8.0)))
print("[PoseExpansion] Video: \(fps)fps, \(totalFrames) frames, 8Hz interval=\(sampleInterval)")
// Build set of all face frames
let allFaceFrameSet = Set(frameToTraces.keys)
// Track which frames have pose with trace_id
var poseFrameDict: [Int: [String: Any]] = [:]
// Setup asset reader
let outputSettings: [String: Any] = [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA
]
let reader = try AVAssetReader(asset: asset)
let trackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings)
trackOutput.alwaysCopiesSampleData = false
reader.add(trackOutput)
guard reader.startReading() else {
print("[PoseExpansion] ERROR: Cannot start reader")
return
}
// Process frames
var frameIndex = 0
var consecutiveMisses = 0
var activeTraceIds: Set<Int> = [] // Currently active traces being expanded
while let sampleBuffer = trackOutput.copyNextSampleBuffer() {
defer { frameIndex += 1 }
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
continue
}
// Check if this frame has face traces
let faceTraces = frameToTraces[frameIndex]
let isFaceFrame = faceTraces != nil && !faceTraces!.isEmpty
if isFaceFrame, let traces = faceTraces {
// Update active traces
for ft in traces {
activeTraceIds.insert(ft.traceId)
}
consecutiveMisses = 0
}
// Check if we should process this frame
let shouldProcess = isFaceFrame ||
(consecutiveMisses < missThreshold * sampleInterval && !activeTraceIds.isEmpty)
if shouldProcess {
let poseResult = detectPose(pixelBuffer: pixelBuffer)
if poseResult.hasPose {
let seconds = Double(frameIndex) / Double(fps)
// Determine trace_id for this pose
var traceId = 0
if isFaceFrame, let traces = faceTraces {
// Use the trace_id from face (may need bbox matching for multi-person)
// For now, use the first trace_id found
traceId = traces.first?.traceId ?? 0
} else {
// Inherit from nearest face frame with active trace
let nearestFaceFrame = findNearestFaceFrame(
frameIndex: frameIndex,
frameToTraces: frameToTraces,
activeTraceIds: activeTraceIds
)
if let nearest = nearestFaceFrame, let traces = frameToTraces[nearest] {
traceId = traces.first?.traceId ?? 0
}
}
poseFrameDict[frameIndex] = [
"frame": frameIndex,
"timestamp": seconds,
"trace_id": traceId,
"persons": poseResult.persons
]
consecutiveMisses = 0
} else {
consecutiveMisses += 1
}
}
// Progress logging
if frameIndex % 5000 == 0 {
let elapsed = Date().timeIntervalSince(startTime)
print("[PoseExpansion] Frame \(frameIndex)/\(totalFrames), \(poseFrameDict.count) poses, \(Int(elapsed))s")
fflush(stdout)
}
}
reader.cancelReading()
print("[PoseExpansion] Detection done: \(poseFrameDict.count) frames with pose")
// 8Hz sampling output
var outputFrames: [[String: Any]] = []
let sortedPoseFrames = poseFrameDict.keys.sorted()
var targetFrame = 0
while targetFrame < totalFrames {
// Find closest pose frame to target
var closestFrame: Int? = nil
var closestDist = Int.max
for poseFrame in sortedPoseFrames {
let dist = abs(poseFrame - targetFrame)
if dist < closestDist && dist <= sampleInterval {
closestDist = dist
closestFrame = poseFrame
}
}
if let cf = closestFrame, let data = poseFrameDict[cf] {
outputFrames.append(data)
}
targetFrame += sampleInterval
}
// Write output
let output: [String: Any] = [
"frame_count": outputFrames.count,
"fps": Double(fps),
"frames": outputFrames
]
let jsonData = try JSONSerialization.data(withJSONObject: output, options: [])
try jsonData.write(to: URL(fileURLWithPath: outputPath))
let elapsed = Date().timeIntervalSince(startTime)
print("[PoseExpansion] Done: \(outputFrames.count) frames at 8Hz, \(String(format: "%.1f", elapsed))s → \(outputPath)")
}
/// Find nearest face frame with active trace
func findNearestFaceFrame(
frameIndex: Int,
frameToTraces: [Int: [(traceId: Int, x: Double, y: Double, w: Double, h: Double)]],
activeTraceIds: Set<Int>
) -> Int? {
var nearestFrame: Int? = nil
var nearestDist = Int.max
for (frameNum, traces) in frameToTraces {
// Check if this frame has an active trace
let hasActiveTrace = traces.contains { activeTraceIds.contains($0.traceId) }
if hasActiveTrace {
let dist = abs(frameNum - frameIndex)
if dist < nearestDist {
nearestDist = dist
nearestFrame = frameNum
}
}
}
return nearestFrame
}
func detectPose(pixelBuffer: CVPixelBuffer) -> (hasPose: Bool, persons: [[String: Any]]) {
let imgW = CGFloat(CVPixelBufferGetWidth(pixelBuffer))
let imgH = CGFloat(CVPixelBufferGetHeight(pixelBuffer))
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
let bodyReq = VNDetectHumanBodyPoseRequest()
do {
try handler.perform([bodyReq])
} catch {
return (false, [])
}
let jointNames: [VNHumanBodyPoseObservation.JointName] = [
.nose, .leftEye, .rightEye, .leftEar, .rightEar,
.neck, .root,
.leftShoulder, .rightShoulder,
.leftElbow, .rightElbow,
.leftWrist, .rightWrist,
.leftHip, .rightHip,
.leftKnee, .rightKnee,
.leftAnkle, .rightAnkle,
]
var persons: [[String: Any]] = []
let poses = bodyReq.results ?? []
for pose in poses {
var keypoints: [[String: Any]] = []
var minX = CGFloat.greatestFiniteMagnitude
var minY = CGFloat.greatestFiniteMagnitude
var maxX: CGFloat = 0
var maxY: CGFloat = 0
for joint in jointNames {
if let point = try? pose.recognizedPoint(joint) {
let desc = String(describing: joint.rawValue)
var rawName = desc
.replacingOccurrences(of: "VNRecognizedPointKey(_rawValue: ", with: "")
.replacingOccurrences(of: ")", with: "")
.trimmingCharacters(in: .whitespaces)
let nameMap: [String: String] = [
"head_joint": "nose",
"left_eye_joint": "left_eye",
"right_eye_joint": "right_eye",
"left_ear_joint": "left_ear",
"right_ear_joint": "right_ear",
"neck_1_joint": "neck",
"left_shoulder_1_joint": "left_shoulder",
"right_shoulder_1_joint": "right_shoulder",
"left_elbow_1_joint": "left_elbow",
"right_elbow_1_joint": "right_elbow",
"left_hand_joint": "left_wrist",
"right_hand_joint": "right_wrist",
"left_hip_1_joint": "left_hip",
"right_hip_1_joint": "right_hip",
"left_knee_1_joint": "left_knee",
"right_knee_1_joint": "right_knee",
"left_ankle_1_joint": "left_ankle",
"right_ankle_1_joint": "right_ankle",
"center_hip_joint": "root",
]
if let mapped = nameMap[rawName] {
rawName = mapped
}
let px = point.location.x * CGFloat(imgW)
let py = CGFloat(imgH) - point.location.y * CGFloat(imgH)
keypoints.append([
"name": rawName.isEmpty ? "\(joint)" : rawName,
"x": px,
"y": py,
"confidence": point.confidence,
])
if point.confidence > 0.1 {
minX = min(minX, px)
minY = min(minY, py)
maxX = max(maxX, px)
maxY = max(maxY, py)
}
}
}
var bbox: [String: Any] = ["x": 0, "y": 0, "width": 0, "height": 0]
if maxX > minX {
bbox = [
"x": Int(minX),
"y": Int(minY),
"width": Int(maxX - minX),
"height": Int(maxY - minY),
]
}
persons.append(["keypoints": keypoints, "bbox": bbox])
}
return (!persons.isEmpty, persons)
}
}
+102
View File
@@ -0,0 +1,102 @@
import Foundation
import Vision
import ArgumentParser
import AppKit
/// POC: Test Apple Vision Framework for object detection (YOLO replacement)
@main
struct VisionObjectTest: ParsableCommand {
@Argument(help: "Input image path")
var inputPath: String
func run() throws {
let startTime = Date()
print("=== Apple Vision Framework Object Detection POC ===")
#if arch(arm64)
print("HW: Apple Silicon ✅ (ANE available)")
#endif
guard let image = NSImage(contentsOfFile: inputPath) else {
print("Error: cannot load image"); return
}
guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
print("Error: cannot get CGImage"); return
}
print("Image: \(cgImage.width)x\(cgImage.height)")
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
// 1. VNClassifyImageRequest (scene classification - replaces scene_classifier)
print("\n--- VNClassifyImageRequest ---")
let clsReq = VNClassifyImageRequest()
try handler.perform([clsReq])
if let classifications = clsReq.results {
print("Top classifications:")
for c in classifications.prefix(10) {
print(" \(c.identifier): conf=\(String(format: "%.3f", c.confidence))")
}
}
// 2. VNDetectHumanRectanglesRequest (person detection - YOLO replacement for 'person')
print("\n--- VNDetectHumanRectanglesRequest ---")
let humanReq = VNDetectHumanRectanglesRequest()
try handler.perform([humanReq])
if let humans = humanReq.results {
print("Humans: \(humans.count)")
for (i, h) in humans.enumerated() {
let bb = h.boundingBox
print(" [\(i)] bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y))) size=(\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) conf=\(String(format: "%.2f", h.confidence))")
}
}
// 3. VNDetectHumanBodyPoseRequest (pose estimation - MediaPipe replacement)
print("\n--- VNDetectHumanBodyPoseRequest ---")
let poseReq = VNDetectHumanBodyPoseRequest()
try handler.perform([poseReq])
if let poses = poseReq.results {
print("Body poses: \(poses.count)")
for (i, p) in poses.enumerated() {
let joints = p.availableJointNames
print(" [\(i)] \(joints.count) joints detected")
// Show key joints
for joint in [VNHumanBodyPoseObservation.JointName.neck,
VNHumanBodyPoseObservation.JointName.leftShoulder,
VNHumanBodyPoseObservation.JointName.rightShoulder,
VNHumanBodyPoseObservation.JointName.leftWrist,
VNHumanBodyPoseObservation.JointName.rightWrist,
VNHumanBodyPoseObservation.JointName.root] {
if let pt = try? p.recognizedPoint(joint) {
print(" \(joint.rawValue): (\(String(format: "%.3f", pt.location.x)), \(String(format: "%.3f", pt.location.y))) conf=\(String(format: "%.2f", pt.confidence))")
}
}
}
}
// 4. VNDetectHumanHandPoseRequest (hand pose)
print("\n--- VNDetectHumanHandPoseRequest ---")
let handReq = VNDetectHumanHandPoseRequest()
try handler.perform([handReq])
if let hands = handReq.results {
print("Hands: \(hands.count)")
for (i, h) in hands.enumerated() {
print(" [\(i)] confidence=\(String(format: "%.2f", h.confidence))")
}
}
// 5. VNGenerateObjectnessBasedSaliencyImageRequest (object detection without labels)
print("\n--- VNGenerateObjectnessBasedSaliencyImageRequest ---")
let salReq = VNGenerateObjectnessBasedSaliencyImageRequest()
try handler.perform([salReq])
if let sal = salReq.results?.first {
if let objects = sal.salientObjects {
print("Salient objects: \(objects.count)")
for (i, ob) in objects.enumerated().prefix(10) {
let bb = ob.boundingBox
print(" [\(i)] bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y)),\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) conf=\(String(format: "%.2f", ob.confidence))")
}
}
}
print("\nTime: \(String(format: "%.2f", Date().timeIntervalSince(startTime)))s")
print("=== Done ===")
}
}
+71
View File
@@ -0,0 +1,71 @@
import Foundation
import Vision
import ArgumentParser
import AppKit
/// POC: Test Apple Vision Framework OCR (VNRecognizeTextRequest) vs PaddleOCR
@main
struct VisionOCRTest: ParsableCommand {
@Argument(help: "Input image path")
var inputPath: String
@Option(name: .long, help: "Recognition level (.fast or .accurate, default .accurate)")
var level: String = "accurate"
mutating func run() throws {
let startTime = Date()
print("=== Apple Vision Framework OCR POC ===")
#if arch(arm64)
print("HW: Apple Silicon ✅")
#endif
guard let image = NSImage(contentsOfFile: inputPath) else {
print("Error: cannot load image"); return
}
guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
print("Error: cannot get CGImage"); return
}
print("Image: \(cgImage.width)x\(cgImage.height)")
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
// VNRecognizeTextRequest
print("\n--- VNRecognizeTextRequest ---")
let req = VNRecognizeTextRequest()
if level == "fast" {
req.recognitionLevel = .fast
} else {
req.recognitionLevel = .accurate
}
req.usesLanguageCorrection = true
req.preferBackgroundProcessing = true
try handler.perform([req])
guard let results = req.results else {
print("No OCR results"); return
}
print("Text blocks: \(results.count)")
var totalChars = 0
for (i, obs) in results.enumerated() {
guard let candidate = obs.topCandidates(1).first else { continue }
let text = candidate.string
let conf = candidate.confidence
let bb = obs.boundingBox
totalChars += text.count
if i < 20 {
print(" [\(i)] conf=\(String(format: "%.3f", conf)) bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y)),\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) \"\(text.prefix(80))\"")
}
}
print(" ... \(results.count) total, \(totalChars) chars")
// Check language support
print("\n--- Language Support ---")
let supported = (try? VNRecognizeTextRequest.supportedRecognitionLanguages(for: .accurate, revision: VNRecognizeTextRequest.currentRevision)) ?? []
print("Supported languages (\(supported.count)): \(supported.prefix(10).joined(separator: ", "))...")
let elapsed = Date().timeIntervalSince(startTime)
print("\nTime: \(String(format: "%.2f", elapsed))s")
print("=== Done ===")
}
}