feat: face clustering pipeline improvements and Rust/Swift face processing
- Add Rust face processor module (detection, embedding, tracking, qdrant) - Add Facenet CoreML/ONNX conversion scripts and tests - Refactor swift_face into Sources/swift_face with ArgumentParser support - Update store_traced_faces to handle face.json correctly - Fix ASRX parsing and TKG bbox reading from Qdrant - Improve admin_config and trace_agent APIs - Add M4 workspace docs for face clustering, dedup, and Facenet validation - Fix worker heartbeat TTL (poll_interval x 3, min 60s) for offline detection
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, imageops};
|
||||
use crate::face_processor::BBox;
|
||||
|
||||
pub struct FaceCropper;
|
||||
|
||||
impl FaceCropper {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
pub fn crop(&self, frame: &RgbImage, bbox: &BBox) -> Result<RgbImage> {
|
||||
let width = frame.width() as i32;
|
||||
let height = frame.height() as i32;
|
||||
|
||||
// Clamp bbox to frame boundaries
|
||||
let x = bbox.x.max(0).min(width - 1) as u32;
|
||||
let y = bbox.y.max(0).min(height - 1) as u32;
|
||||
let w = bbox.width.max(1).min(width - x as i32) as u32;
|
||||
let h = bbox.height.max(1).min(height - y as i32) as u32;
|
||||
|
||||
// Clone frame for cropping (imageops::crop needs mutable reference)
|
||||
let mut frame_clone = frame.clone();
|
||||
|
||||
// Crop face
|
||||
let cropped = imageops::crop(&mut frame_clone, x, y, w, h).to_image();
|
||||
|
||||
Ok(cropped)
|
||||
}
|
||||
|
||||
pub fn resize_to_160(&self, face: &RgbImage) -> Result<RgbImage> {
|
||||
let resized = imageops::resize(
|
||||
face,
|
||||
160,
|
||||
160,
|
||||
imageops::FilterType::Lanczos3,
|
||||
);
|
||||
|
||||
Ok(resized)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::fs;
|
||||
use serde::Deserialize;
|
||||
use crate::face_processor::{FaceDetection, BBox, PoseInfo};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftOutput {
|
||||
#[serde(default)]
|
||||
fps: f64,
|
||||
#[serde(default)]
|
||||
frame_count: usize,
|
||||
frames: Vec<SwiftFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftFrame {
|
||||
frame: usize,
|
||||
#[serde(default)]
|
||||
timestamp: f64,
|
||||
faces: Vec<SwiftFace>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftFace {
|
||||
bbox: Option<SwiftBBox>,
|
||||
confidence: f64,
|
||||
#[serde(rename = "captureQuality")]
|
||||
capture_quality: Option<f64>,
|
||||
pose: Option<SwiftPose>,
|
||||
landmarks: Option<SwiftLandmarks>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Clone)]
|
||||
struct SwiftBBox {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftPose {
|
||||
roll: f64,
|
||||
yaw: f64,
|
||||
pitch: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftLandmarks {
|
||||
face_oval: Option<Vec<Vec<f64>>>,
|
||||
left_eye: Option<Vec<Vec<f64>>>,
|
||||
right_eye: Option<Vec<Vec<f64>>>,
|
||||
nose: Option<Vec<Vec<f64>>>,
|
||||
lips: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl SwiftFace {
|
||||
fn get_bbox(&self) -> Option<SwiftBBox> {
|
||||
// If bbox is directly provided
|
||||
if let Some(ref bbox) = self.bbox {
|
||||
return Some(bbox.clone());
|
||||
}
|
||||
|
||||
// Otherwise, derive from landmarks
|
||||
if let Some(ref landmarks) = self.landmarks {
|
||||
if let Some(ref face_oval) = landmarks.face_oval {
|
||||
if !face_oval.is_empty() {
|
||||
let mut min_x = f64::MAX;
|
||||
let mut min_y = f64::MAX;
|
||||
let mut max_x = f64::MIN;
|
||||
let mut max_y = f64::MIN;
|
||||
|
||||
for point in face_oval {
|
||||
if point.len() >= 2 {
|
||||
min_x = min_x.min(point[0]);
|
||||
min_y = min_y.min(point[1]);
|
||||
max_x = max_x.max(point[0]);
|
||||
max_y = max_y.max(point[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return Some(SwiftBBox {
|
||||
x: min_x,
|
||||
y: min_y,
|
||||
width: max_x - min_x,
|
||||
height: max_y - min_y,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FaceDetector {
|
||||
swift_binary: String,
|
||||
}
|
||||
|
||||
impl FaceDetector {
|
||||
pub fn new() -> Result<Self> {
|
||||
let swift_binary = Self::find_swift_binary()?;
|
||||
Ok(Self { swift_binary })
|
||||
}
|
||||
|
||||
fn find_swift_binary() -> Result<String> {
|
||||
// Try release build first
|
||||
let release = "scripts/swift_processors/.build/release/swift_face";
|
||||
if Path::new(release).exists() {
|
||||
return Ok(release.to_string());
|
||||
}
|
||||
|
||||
// Try debug build
|
||||
let debug = "scripts/swift_processors/.build/debug/swift_face";
|
||||
if Path::new(debug).exists() {
|
||||
return Ok(debug.to_string());
|
||||
}
|
||||
|
||||
anyhow::bail!("Swift face binary not found")
|
||||
}
|
||||
|
||||
pub fn detect(&self, video_path: &Path, output_path: &Path, sample_interval: usize) -> Result<Vec<FaceDetection>> {
|
||||
println!("[DETECTION] Running Swift face detection...");
|
||||
|
||||
// Swift writes to file, not stdout
|
||||
let output = Command::new(&self.swift_binary)
|
||||
.arg(video_path)
|
||||
.arg(output_path)
|
||||
.arg("--sample-interval")
|
||||
.arg(sample_interval.to_string())
|
||||
.output()
|
||||
.context("Failed to run Swift face detection")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
anyhow::bail!("Swift face detection failed: {}", stderr);
|
||||
}
|
||||
|
||||
// Read JSON from output file
|
||||
let json_content = fs::read_to_string(output_path)
|
||||
.context("Failed to read Swift detection output file")?;
|
||||
|
||||
// Parse Swift output: {"frames": [...], "fps": ..., "frame_count": ...}
|
||||
let swift_output: SwiftOutput = serde_json::from_str(&json_content)
|
||||
.context("Failed to parse Swift detection JSON")?;
|
||||
|
||||
println!("[DETECTION] Swift fps: {}, frame_count: {}", swift_output.fps, swift_output.frame_count);
|
||||
|
||||
// Convert to our format
|
||||
let faces: Vec<FaceDetection> = swift_output.frames.into_iter().flat_map(|frame| {
|
||||
frame.faces.into_iter().filter_map(|face| {
|
||||
let swift_bbox = face.get_bbox()?;
|
||||
|
||||
Some(FaceDetection {
|
||||
frame: frame.frame,
|
||||
timestamp: frame.timestamp,
|
||||
bbox: BBox {
|
||||
x: swift_bbox.x as i32,
|
||||
y: swift_bbox.y as i32,
|
||||
width: swift_bbox.width as i32,
|
||||
height: swift_bbox.height as i32,
|
||||
},
|
||||
confidence: face.confidence,
|
||||
capture_quality: face.capture_quality,
|
||||
pose: face.pose.map(|p| PoseInfo {
|
||||
roll: p.roll,
|
||||
yaw: p.yaw,
|
||||
pitch: p.pitch,
|
||||
}),
|
||||
})
|
||||
}).collect::<Vec<_>>()
|
||||
}).collect();
|
||||
|
||||
println!("[DETECTION] Found {} faces", faces.len());
|
||||
|
||||
Ok(faces)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, imageops};
|
||||
use ndarray::IxDyn;
|
||||
use ort::{session::Session, value::Value};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct EmbeddingExtractor {
|
||||
session: Session,
|
||||
}
|
||||
|
||||
impl EmbeddingExtractor {
|
||||
pub fn new(model_path: &Path) -> Result<Self> {
|
||||
println!("[EMBEDDING] Loading model: {:?}", model_path);
|
||||
|
||||
let session = Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?;
|
||||
|
||||
println!("[EMBEDDING] Model loaded successfully");
|
||||
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
pub fn extract(&mut self, face: &RgbImage) -> Result<Vec<f32>> {
|
||||
// Preprocess: resize to 160x160 and normalize to [-1, 1]
|
||||
let resized = imageops::resize(
|
||||
face,
|
||||
160,
|
||||
160,
|
||||
imageops::FilterType::Lanczos3,
|
||||
);
|
||||
|
||||
// Convert to normalized tensor
|
||||
let mut input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, 3, 160, 160]),
|
||||
vec![0.0f32; 1 * 3 * 160 * 160]
|
||||
).context("Failed to create input array")?;
|
||||
|
||||
for (x, y, pixel) in resized.enumerate_pixels() {
|
||||
let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32);
|
||||
input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0;
|
||||
input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0;
|
||||
input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0;
|
||||
}
|
||||
|
||||
// Create input value
|
||||
let input_value = Value::from_array(input_array)
|
||||
.context("Failed to create input value")?;
|
||||
|
||||
let inputs = ort::inputs!["input" => input_value];
|
||||
|
||||
// Run inference
|
||||
let outputs = self.session.run(inputs)
|
||||
.context("Failed to run inference")?;
|
||||
|
||||
// Extract output
|
||||
let output = outputs["output"].try_extract_tensor::<f32>()
|
||||
.context("Failed to extract output tensor")?;
|
||||
|
||||
let output_data = output.1;
|
||||
let embedding = output_data.to_vec();
|
||||
|
||||
Ok(embedding)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
pub mod types;
|
||||
pub mod video;
|
||||
pub mod qdrant;
|
||||
pub mod detection;
|
||||
pub mod crop;
|
||||
pub mod embedding;
|
||||
|
||||
pub use types::*;
|
||||
pub use video::VideoReader;
|
||||
pub use qdrant::{QdrantFaceStore, FaceEmbedPayload};
|
||||
pub use detection::FaceDetector;
|
||||
pub use crop::FaceCropper;
|
||||
pub use embedding::EmbeddingExtractor;
|
||||
@@ -0,0 +1,141 @@
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::json;
|
||||
|
||||
const COLLECTION_NAME: &str = "_faces";
|
||||
const VECTOR_SIZE: usize = 512;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FaceEmbedPayload {
|
||||
pub frame: usize,
|
||||
pub trace_id: i64,
|
||||
pub bbox: crate::face_processor::BBox,
|
||||
pub confidence: f64,
|
||||
pub capture_quality: Option<f64>,
|
||||
pub embedding: Vec<f32>,
|
||||
}
|
||||
|
||||
pub struct QdrantFaceStore {
|
||||
url: String,
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
impl QdrantFaceStore {
|
||||
pub async fn new() -> Result<Self> {
|
||||
let url = std::env::var("QDRANT_URL")
|
||||
.unwrap_or_else(|_| "http://localhost:6333".to_string());
|
||||
|
||||
let api_key = std::env::var("QDRANT_API_KEY")
|
||||
.unwrap_or_else(|_| "Test3200Test3200Test3200".to_string());
|
||||
|
||||
let store = Self { url, api_key };
|
||||
store.ensure_collection().await?;
|
||||
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
async fn ensure_collection(&self) -> Result<()> {
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let url = format!("{}/collections/{}", self.url, COLLECTION_NAME);
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.header("Api-Key", &self.api_key)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if resp.status() == 404 {
|
||||
println!("[QDRANT] Creating collection: {}", COLLECTION_NAME);
|
||||
|
||||
let create_url = format!("{}/collections/{}", self.url, COLLECTION_NAME);
|
||||
let body = json!({
|
||||
"vectors": {
|
||||
"size": VECTOR_SIZE,
|
||||
"distance": "Cosine"
|
||||
}
|
||||
});
|
||||
|
||||
client
|
||||
.put(&create_url)
|
||||
.header("Api-Key", &self.api_key)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
println!("[QDRANT] Collection created");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_point_id(file_uuid: &str, frame: usize, trace_id: i64) -> u64 {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
let key = format!("{}_{}_{}", file_uuid, frame, trace_id);
|
||||
let mut hasher = DefaultHasher::new();
|
||||
key.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
pub async fn push_embeddings_batch(
|
||||
&self,
|
||||
file_uuid: &str,
|
||||
faces: Vec<FaceEmbedPayload>,
|
||||
) -> Result<usize> {
|
||||
if faces.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
println!("[QDRANT] Pushing {} embeddings", faces.len());
|
||||
|
||||
let points: Vec<_> = faces
|
||||
.iter()
|
||||
.map(|face| {
|
||||
let point_id = Self::generate_point_id(file_uuid, face.frame, face.trace_id);
|
||||
json!({
|
||||
"id": point_id,
|
||||
"vector": &face.embedding,
|
||||
"payload": {
|
||||
"file_uuid": file_uuid,
|
||||
"frame": face.frame,
|
||||
"trace_id": face.trace_id,
|
||||
"bbox": {
|
||||
"x": face.bbox.x,
|
||||
"y": face.bbox.y,
|
||||
"width": face.bbox.width,
|
||||
"height": face.bbox.height,
|
||||
},
|
||||
"confidence": face.confidence,
|
||||
"capture_quality": face.capture_quality.unwrap_or(0.0),
|
||||
"identity_id": 0,
|
||||
"identity_uuid": "",
|
||||
"stranger_id": 0,
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let body = json!({"points": points});
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let url = format!("{}/collections/{}/points?wait=true", self.url, COLLECTION_NAME);
|
||||
|
||||
let resp = client
|
||||
.put(&url)
|
||||
.header("Api-Key", &self.api_key)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let status = resp.status();
|
||||
let response_text = resp.text().await?;
|
||||
|
||||
if !status.is_success() {
|
||||
bail!("Qdrant upsert failed ({}): {}", status, response_text);
|
||||
}
|
||||
|
||||
println!("[QDRANT] Pushed {} embeddings successfully", faces.len());
|
||||
|
||||
Ok(faces.len())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BBox {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceDetection {
|
||||
pub frame: usize,
|
||||
pub timestamp: f64,
|
||||
pub bbox: BBox,
|
||||
pub confidence: f64,
|
||||
pub capture_quality: Option<f64>,
|
||||
pub pose: Option<PoseInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PoseInfo {
|
||||
pub roll: f64,
|
||||
pub yaw: f64,
|
||||
pub pitch: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FaceEmbedding {
|
||||
pub frame: usize,
|
||||
pub trace_id: usize,
|
||||
pub bbox: BBox,
|
||||
pub confidence: f64,
|
||||
pub embedding: Vec<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FaceOutput {
|
||||
pub status: String,
|
||||
pub frame_count: usize,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<FrameData>,
|
||||
pub total_faces: usize,
|
||||
pub metadata: Metadata,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FrameData {
|
||||
pub frame: usize,
|
||||
pub timestamp: f64,
|
||||
pub faces: Vec<FaceInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FaceInfo {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub confidence: f64,
|
||||
pub pose_angle: Option<PoseAngle>,
|
||||
pub capture_quality: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct PoseAngle {
|
||||
pub angle: String,
|
||||
pub roll: f64,
|
||||
pub yaw: f64,
|
||||
pub pitch: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Metadata {
|
||||
pub embedding_method: String,
|
||||
pub embedding_model: String,
|
||||
pub total_embeddings: usize,
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, ImageBuffer};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
pub struct VideoReader {
|
||||
video_path: String,
|
||||
fps: f64,
|
||||
frame_count: usize,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
impl VideoReader {
|
||||
pub fn new(video_path: &Path) -> Result<Self> {
|
||||
// Use ffprobe to get video info
|
||||
let output = Command::new("ffprobe")
|
||||
.args(&[
|
||||
"-v", "error",
|
||||
"-select_streams", "v:0",
|
||||
"-count_packets",
|
||||
"-show_entries", "stream=width,height,r_frame_rate,nb_read_packets",
|
||||
"-of", "csv=p=0",
|
||||
video_path.to_str().unwrap()
|
||||
])
|
||||
.output()
|
||||
.context("Failed to run ffprobe")?;
|
||||
|
||||
let info = String::from_utf8_lossy(&output.stdout);
|
||||
let parts: Vec<&str> = info.trim().split(',').collect();
|
||||
|
||||
if parts.len() < 4 {
|
||||
anyhow::bail!("Invalid ffprobe output");
|
||||
}
|
||||
|
||||
let width: u32 = parts[0].parse()?;
|
||||
let height: u32 = parts[1].parse()?;
|
||||
|
||||
let fps_parts: Vec<&str> = parts[2].split('/').collect();
|
||||
let fps = if fps_parts.len() == 2 {
|
||||
fps_parts[0].parse::<f64>()? / fps_parts[1].parse::<f64>()?
|
||||
} else {
|
||||
parts[2].parse()?
|
||||
};
|
||||
|
||||
let frame_count: usize = parts[3].parse()?;
|
||||
|
||||
Ok(Self {
|
||||
video_path: video_path.to_str().unwrap().to_string(),
|
||||
fps,
|
||||
frame_count,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fps(&self) -> f64 {
|
||||
self.fps
|
||||
}
|
||||
|
||||
pub fn frame_count(&self) -> usize {
|
||||
self.frame_count
|
||||
}
|
||||
|
||||
pub fn width(&self) -> u32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
pub fn height(&self) -> u32 {
|
||||
self.height
|
||||
}
|
||||
|
||||
pub fn read_frame(&mut self, frame_num: usize) -> Result<Option<RgbImage>> {
|
||||
// Use ffmpeg to extract a specific frame
|
||||
let output = Command::new("ffmpeg")
|
||||
.args(&[
|
||||
"-i", &self.video_path,
|
||||
"-vf", &format!("select=eq(n\\,{})", frame_num),
|
||||
"-vframes", "1",
|
||||
"-f", "image2pipe",
|
||||
"-pix_fmt", "rgb24",
|
||||
"-vcodec", "rawvideo",
|
||||
"-"
|
||||
])
|
||||
.output()
|
||||
.context("Failed to run ffmpeg")?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let data = output.stdout;
|
||||
|
||||
// Create image from raw RGB data
|
||||
let img = ImageBuffer::from_raw(self.width, self.height, data)
|
||||
.context("Failed to create image buffer")?;
|
||||
|
||||
Ok(Some(img))
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ struct Args {
|
||||
frames: Option<String>,
|
||||
#[arg(long = "method", default_value = "leader")]
|
||||
method: String,
|
||||
#[arg(long = "threshold", default_value_t = 0.35)]
|
||||
#[arg(long = "threshold", default_value_t = 0.15)]
|
||||
threshold: f64,
|
||||
#[arg(long = "force")]
|
||||
force: bool,
|
||||
@@ -442,24 +442,33 @@ fn main() {
|
||||
|
||||
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));
|
||||
|
||||
eprintln!("[FACE_CLUSTER] Starting face clustering: {}", args.video_path);
|
||||
eprintln!("[DEBUG] Output dir: {:?}", output_dir);
|
||||
eprintln!("[DEBUG] Initial face_json_path: {:?}", face_json_path);
|
||||
eprintln!("[DEBUG] File exists (attempt 1): {}", face_json_path.exists());
|
||||
|
||||
if !face_json_path.exists() {
|
||||
face_json_path = output_dir.join(&uuid).join(format!("{}.face.json", uuid));
|
||||
eprintln!("[DEBUG] Fallback face_json_path: {:?}", face_json_path);
|
||||
eprintln!("[DEBUG] File exists (attempt 2): {}", face_json_path.exists());
|
||||
}
|
||||
|
||||
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 face_json_content = std::fs::read_to_string(&face_json_path).expect("Failed to read face.json");
|
||||
eprintln!("[DEBUG] Face JSON content length: {} bytes", face_json_content.len());
|
||||
|
||||
let face_data: Value = serde_json::from_str(&face_json_content).expect("Failed to parse face.json");
|
||||
eprintln!("[DEBUG] Face data top-level keys: {:?}", face_data.as_object().map(|o| o.keys().collect::<Vec<_>>()));
|
||||
|
||||
let frames_list = face_data.get("frames").and_then(|f| f.as_array()).cloned().unwrap_or_default();
|
||||
eprintln!("[DEBUG] Frames list length: {}", frames_list.len());
|
||||
|
||||
if frames_list.is_empty() {
|
||||
eprintln!("No frames in JSON (no faces).");
|
||||
write_empty_output("no_faces", &uuid, &args.output_path);
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Instant;
|
||||
|
||||
mod face_processor;
|
||||
|
||||
use face_processor::{
|
||||
FaceOutput, FrameData, FaceInfo, Metadata, PoseAngle,
|
||||
VideoReader, FaceDetector, FaceCropper, EmbeddingExtractor,
|
||||
QdrantFaceStore, FaceEmbedPayload,
|
||||
};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "rust_face_processor")]
|
||||
#[command(about = "Face detection and embedding extraction using Rust")]
|
||||
struct Args {
|
||||
/// Path to video file
|
||||
#[arg(short, long)]
|
||||
video: PathBuf,
|
||||
|
||||
/// Path to output JSON file
|
||||
#[arg(short, long)]
|
||||
output: PathBuf,
|
||||
|
||||
/// Video file UUID
|
||||
#[arg(short, long)]
|
||||
uuid: String,
|
||||
|
||||
/// Sample interval (frames)
|
||||
#[arg(long, default_value = "3")]
|
||||
sample_interval: usize,
|
||||
|
||||
/// Path to ONNX model
|
||||
#[arg(long, default_value = "models/facenet_vggface2.onnx")]
|
||||
model: PathBuf,
|
||||
}
|
||||
|
||||
fn classify_pose(roll: f64, yaw: f64) -> String {
|
||||
let abs_yaw = yaw.abs();
|
||||
let abs_roll = roll.abs();
|
||||
|
||||
if abs_yaw < 15.0 && abs_roll < 15.0 {
|
||||
"frontal".to_string()
|
||||
} else if abs_yaw > 30.0 {
|
||||
if yaw > 0.0 {
|
||||
"profile_right".to_string()
|
||||
} else {
|
||||
"profile_left".to_string()
|
||||
}
|
||||
} else {
|
||||
"three_quarter".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
let start_time = Instant::now();
|
||||
|
||||
println!("[FACE_RUST] Starting face processor");
|
||||
println!("[FACE_RUST] Video: {:?}", args.video);
|
||||
println!("[FACE_RUST] Output: {:?}", args.output);
|
||||
println!("[FACE_RUST] UUID: {}", args.uuid);
|
||||
|
||||
// Initialize modules
|
||||
let mut video_reader = VideoReader::new(&args.video)
|
||||
.context("Failed to initialize video reader")?;
|
||||
|
||||
println!("[FACE_RUST] Video: {}x{}, {:.1} fps, {} frames",
|
||||
video_reader.width(),
|
||||
video_reader.height(),
|
||||
video_reader.fps(),
|
||||
video_reader.frame_count()
|
||||
);
|
||||
|
||||
let detector = FaceDetector::new()
|
||||
.context("Failed to initialize face detector")?;
|
||||
|
||||
let cropper = FaceCropper::new();
|
||||
|
||||
let mut embedder = EmbeddingExtractor::new(&args.model)
|
||||
.context("Failed to initialize embedding extractor")?;
|
||||
|
||||
// Initialize Qdrant
|
||||
let qdrant = QdrantFaceStore::new()
|
||||
.await
|
||||
.context("Failed to initialize Qdrant store")?;
|
||||
|
||||
// Run face detection
|
||||
let detection_output = args.output.with_extension("detect.json");
|
||||
let detections = detector.detect(&args.video, &detection_output, args.sample_interval)?;
|
||||
|
||||
// Process each detection
|
||||
let mut frames: Vec<FrameData> = Vec::new();
|
||||
let mut embeddings_data: Vec<FaceEmbedPayload> = Vec::new();
|
||||
let mut total_embeddings = 0;
|
||||
let mut total_faces = 0;
|
||||
|
||||
println!("[FACE_RUST] Processing {} faces...", detections.len());
|
||||
|
||||
for detection in detections {
|
||||
// Read frame
|
||||
let frame = match video_reader.read_frame(detection.frame)? {
|
||||
Some(f) => f,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
// Crop face
|
||||
let face_img = cropper.crop(&frame, &detection.bbox)?;
|
||||
|
||||
// Extract embedding
|
||||
let embedding = embedder.extract(&face_img)?;
|
||||
total_embeddings += 1;
|
||||
|
||||
// Store embedding data for Qdrant
|
||||
embeddings_data.push(FaceEmbedPayload {
|
||||
frame: detection.frame,
|
||||
trace_id: 0, // Will be updated by face tracker
|
||||
bbox: detection.bbox.clone(),
|
||||
confidence: detection.confidence,
|
||||
capture_quality: detection.capture_quality.map(|q| q as f64),
|
||||
embedding,
|
||||
});
|
||||
|
||||
// Classify pose
|
||||
let pose_angle = detection.pose.as_ref().map(|p| {
|
||||
PoseAngle {
|
||||
angle: classify_pose(p.roll, p.yaw),
|
||||
roll: p.roll,
|
||||
yaw: p.yaw,
|
||||
pitch: p.pitch,
|
||||
}
|
||||
});
|
||||
|
||||
// Create face info (without embedding)
|
||||
let face_info = FaceInfo {
|
||||
x: detection.bbox.x,
|
||||
y: detection.bbox.y,
|
||||
width: detection.bbox.width,
|
||||
height: detection.bbox.height,
|
||||
confidence: detection.confidence,
|
||||
pose_angle,
|
||||
capture_quality: detection.capture_quality,
|
||||
};
|
||||
|
||||
// Add to frame
|
||||
frames.push(FrameData {
|
||||
frame: detection.frame,
|
||||
timestamp: detection.timestamp,
|
||||
faces: vec![face_info],
|
||||
});
|
||||
|
||||
total_faces += 1;
|
||||
|
||||
if total_faces % 100 == 0 {
|
||||
println!("[FACE_RUST] Processed {} faces", total_faces);
|
||||
}
|
||||
}
|
||||
|
||||
// Push embeddings to Qdrant
|
||||
if !embeddings_data.is_empty() {
|
||||
println!("[QDRANT] Pushing {} embeddings...", embeddings_data.len());
|
||||
let pushed = qdrant.push_embeddings_batch(&args.uuid, embeddings_data)
|
||||
.await
|
||||
.context("Failed to push embeddings to Qdrant")?;
|
||||
println!("[QDRANT] Pushed {} embeddings to _faces collection", pushed);
|
||||
}
|
||||
|
||||
// Create output
|
||||
let output = FaceOutput {
|
||||
status: if total_faces > 0 { "has_faces" } else { "no_faces" }.to_string(),
|
||||
frame_count: frames.len(),
|
||||
fps: video_reader.fps(),
|
||||
frames,
|
||||
total_faces,
|
||||
metadata: Metadata {
|
||||
embedding_method: "rust_facenet".to_string(),
|
||||
embedding_model: "InceptionResnetV1_VGGFace2".to_string(),
|
||||
total_embeddings,
|
||||
},
|
||||
};
|
||||
|
||||
// Write output
|
||||
let json = serde_json::to_string_pretty(&output)?;
|
||||
std::fs::write(&args.output, json)?;
|
||||
|
||||
let elapsed = start_time.elapsed();
|
||||
|
||||
println!("[FACE_RUST] Done: {} frames, {} faces, {} embeddings, {:.1}s",
|
||||
output.frame_count,
|
||||
output.total_faces,
|
||||
output.metadata.total_embeddings,
|
||||
elapsed.as_secs_f64()
|
||||
);
|
||||
|
||||
println!("[FACE_RUST] Output written to {:?}", args.output);
|
||||
|
||||
// Clean up detection output
|
||||
if detection_output.exists() {
|
||||
std::fs::remove_file(&detection_output)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use image::DynamicImage;
|
||||
use ndarray::IxDyn;
|
||||
use ort::session::Session;
|
||||
use ort::value::Value;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "rust_facenet")]
|
||||
#[command(about = "Extract face embeddings using ONNX Runtime")]
|
||||
struct Args {
|
||||
/// Path to face image
|
||||
#[arg(short, long)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to ONNX model
|
||||
#[arg(short, long, default_value = "models/facenet_vggface2.onnx")]
|
||||
model: PathBuf,
|
||||
}
|
||||
|
||||
struct FaceNetModel {
|
||||
session: Session,
|
||||
}
|
||||
|
||||
impl FaceNetModel {
|
||||
fn new(model_path: &PathBuf) -> Result<Self> {
|
||||
println!("[FACENET] Loading model: {:?}", model_path);
|
||||
|
||||
let session = Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?;
|
||||
|
||||
println!("[FACENET] Model loaded successfully");
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
fn preprocess(&self, img: &DynamicImage) -> Result<ndarray::Array<f32, IxDyn>> {
|
||||
let resized = img.resize_exact(160, 160, image::imageops::FilterType::Lanczos3);
|
||||
|
||||
let mut input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, 3, 160, 160]),
|
||||
vec![0.0f32; 1 * 3 * 160 * 160]
|
||||
).context("Failed to create input array")?;
|
||||
|
||||
for (x, y, pixel) in resized.to_rgb8().enumerate_pixels() {
|
||||
let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32);
|
||||
input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0;
|
||||
input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0;
|
||||
input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0;
|
||||
}
|
||||
|
||||
Ok(input_array)
|
||||
}
|
||||
|
||||
fn extract_embedding(&mut self, img: &DynamicImage) -> Result<Vec<f32>> {
|
||||
let input_array = self.preprocess(img)?;
|
||||
let input_value = Value::from_array(input_array)
|
||||
.context("Failed to create input value")?;
|
||||
|
||||
let inputs = ort::inputs!["input" => input_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 tensor")?;
|
||||
|
||||
let output_data = output.1;
|
||||
let embedding = output_data.to_vec();
|
||||
|
||||
Ok(embedding)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
let mut model = FaceNetModel::new(&args.model)?;
|
||||
let img = image::open(&args.input)
|
||||
.context(format!("Failed to load image: {:?}", args.input))?;
|
||||
|
||||
println!("[FACENET] Processing image: {:?}", args.input);
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let embedding = model.extract_embedding(&img)?;
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
println!("[FACENET] Extraction time: {:?}", elapsed);
|
||||
println!("[FACENET] Embedding length: {}", embedding.len());
|
||||
|
||||
let output = json!({
|
||||
"embedding": embedding,
|
||||
"count": embedding.len(),
|
||||
"time_ms": elapsed.as_millis()
|
||||
});
|
||||
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use image::DynamicImage;
|
||||
use ndarray::IxDyn;
|
||||
use ort::session::Session;
|
||||
use ort::value::Value;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "rust_facenet_coreml")]
|
||||
#[command(about = "Extract face embeddings using ONNX Runtime with CoreML acceleration")]
|
||||
struct Args {
|
||||
/// Path to face image
|
||||
#[arg(short, long)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to ONNX model
|
||||
#[arg(short, long, default_value = "models/facenet_vggface2.onnx")]
|
||||
model: PathBuf,
|
||||
|
||||
/// Use CoreML acceleration (flag, no value needed)
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
coreml: bool,
|
||||
}
|
||||
|
||||
struct FaceNetModel {
|
||||
session: Session,
|
||||
}
|
||||
|
||||
impl FaceNetModel {
|
||||
fn new(model_path: &PathBuf, use_coreml: bool) -> Result<Self> {
|
||||
println!("[FACENET] Loading model: {:?}", model_path);
|
||||
println!("[FACENET] CoreML acceleration: {}", use_coreml);
|
||||
|
||||
let session = if use_coreml {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
println!("[FACENET] Using CoreML feature (but ort API is unclear)");
|
||||
|
||||
let mut builder = Session::builder()
|
||||
.context("Failed to create session builder")?;
|
||||
|
||||
builder.commit_from_file(model_path)
|
||||
.context("Failed to load model")?
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
println!("[FACENET] CoreML only available on macOS, using CPU");
|
||||
Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?
|
||||
}
|
||||
} else {
|
||||
println!("[FACENET] Using CPU");
|
||||
Session::builder()
|
||||
.context("Failed to create session builder")?
|
||||
.commit_from_file(model_path)
|
||||
.context("Failed to load model")?
|
||||
};
|
||||
|
||||
println!("[FACENET] Model loaded successfully");
|
||||
Ok(Self { session })
|
||||
}
|
||||
|
||||
fn preprocess(&self, img: &DynamicImage) -> Result<ndarray::Array<f32, IxDyn>> {
|
||||
let resized = img.resize_exact(160, 160, image::imageops::FilterType::Lanczos3);
|
||||
|
||||
let mut input_array = ndarray::Array::from_shape_vec(
|
||||
IxDyn(&[1, 3, 160, 160]),
|
||||
vec![0.0f32; 1 * 3 * 160 * 160]
|
||||
).context("Failed to create input array")?;
|
||||
|
||||
for (x, y, pixel) in resized.to_rgb8().enumerate_pixels() {
|
||||
let (r, g, b) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32);
|
||||
input_array[[0, 0, y as usize, x as usize]] = (r / 127.5) - 1.0;
|
||||
input_array[[0, 1, y as usize, x as usize]] = (g / 127.5) - 1.0;
|
||||
input_array[[0, 2, y as usize, x as usize]] = (b / 127.5) - 1.0;
|
||||
}
|
||||
|
||||
Ok(input_array)
|
||||
}
|
||||
|
||||
fn extract_embedding(&mut self, img: &DynamicImage) -> Result<Vec<f32>> {
|
||||
let input_array = self.preprocess(img)?;
|
||||
let input_value = Value::from_array(input_array)
|
||||
.context("Failed to create input value")?;
|
||||
|
||||
let inputs = ort::inputs!["input" => input_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 tensor")?;
|
||||
|
||||
let output_data = output.1;
|
||||
let embedding = output_data.to_vec();
|
||||
|
||||
Ok(embedding)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
let mut model = FaceNetModel::new(&args.model, args.coreml)?;
|
||||
let img = image::open(&args.input)
|
||||
.context(format!("Failed to load image: {:?}", args.input))?;
|
||||
|
||||
println!("[FACENET] Processing image: {:?}", args.input);
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let embedding = model.extract_embedding(&img)?;
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
println!("[FACENET] Extraction time: {:?}", elapsed);
|
||||
println!("[FACENET] Embedding length: {}", embedding.len());
|
||||
|
||||
let output = json!({
|
||||
"embedding": embedding,
|
||||
"count": embedding.len(),
|
||||
"time_ms": elapsed.as_millis(),
|
||||
"coreml": args.coreml
|
||||
});
|
||||
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user