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:
Generated
+214
-54
@@ -8,6 +8,15 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aligned"
|
||||
version = "0.4.3"
|
||||
@@ -26,6 +35,15 @@ dependencies = [
|
||||
"equator",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
@@ -114,6 +132,17 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.92"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atomic-waker"
|
||||
version = "1.1.2"
|
||||
@@ -262,6 +291,20 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||
dependencies = [
|
||||
"iana-time-zone",
|
||||
"js-sys",
|
||||
"num-traits",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
@@ -555,7 +598,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -564,12 +606,6 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-io"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
|
||||
|
||||
[[package]]
|
||||
name = "futures-sink"
|
||||
version = "0.3.34"
|
||||
@@ -589,10 +625,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"memchr",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
@@ -812,6 +845,30 @@ dependencies = [
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"core-foundation-sys",
|
||||
"iana-time-zone-haiku",
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone-haiku"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.3.0"
|
||||
@@ -1065,6 +1122,15 @@ version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
@@ -1352,7 +1418,7 @@ dependencies = [
|
||||
"ort-sys",
|
||||
"smallvec",
|
||||
"tracing",
|
||||
"ureq 3.4.2",
|
||||
"ureq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1363,7 +1429,30 @@ checksum = "cf211e3776eea6aec988552fa118dd746d70e1b1e5e244058d1c98015f3e5872"
|
||||
dependencies = [
|
||||
"hmac-sha256",
|
||||
"lzma-rust2",
|
||||
"ureq 3.4.2",
|
||||
"ureq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.9.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1664,6 +1753,44 @@ version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.12.28"
|
||||
@@ -1673,9 +1800,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"encoding_rs",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
@@ -1731,17 +1856,20 @@ name = "rust_processors"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"clap",
|
||||
"hound",
|
||||
"image",
|
||||
"ndarray",
|
||||
"ort",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"ureq 2.12.1",
|
||||
"tokio",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1763,9 +1891,7 @@ version = "0.23.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
@@ -1903,6 +2029,16 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||
dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
@@ -2104,11 +2240,25 @@ dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-macros"
|
||||
version = "2.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-native-tls"
|
||||
version = "0.3.1"
|
||||
@@ -2225,24 +2375,6 @@ version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "2.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"flate2",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"url",
|
||||
"webpki-roots 0.26.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "3.4.2"
|
||||
@@ -2303,6 +2435,17 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.26.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "v_frame"
|
||||
version = "0.3.9"
|
||||
@@ -2425,24 +2568,6 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "0.26.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||
dependencies = [
|
||||
"webpki-roots 1.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weezl"
|
||||
version = "0.1.12"
|
||||
@@ -2471,6 +2596,41 @@ version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
|
||||
+33
-24
@@ -2,7 +2,10 @@
|
||||
name = "rust_processors"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Rust replacement for Python processor scripts (standalone binaries)"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_vad"
|
||||
path = "src/bin/rust_vad.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_appearance"
|
||||
@@ -13,42 +16,48 @@ name = "rust_pose"
|
||||
path = "src/bin/rust_pose.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_face_cluster"
|
||||
path = "src/bin/rust_face_cluster.rs"
|
||||
name = "rust_cut"
|
||||
path = "src/bin/rust_cut.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_vad"
|
||||
path = "src/bin/rust_vad.rs"
|
||||
name = "rust_face_cluster"
|
||||
path = "src/bin/rust_face_cluster.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_store_traced_faces"
|
||||
path = "src/bin/rust_store_traced_faces.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_cut"
|
||||
path = "src/bin/rust_cut.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_scene_vlm"
|
||||
path = "src/bin/rust_scene_vlm.rs"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
image = "0.25"
|
||||
ureq = { version = "2", features = ["json"] }
|
||||
base64 = "0.22"
|
||||
reqwest = { version = "0.12", features = ["blocking", "json"] }
|
||||
[[bin]]
|
||||
name = "rust_facenet"
|
||||
path = "src/bin/rust_facenet.rs"
|
||||
|
||||
# VAD dependencies
|
||||
[[bin]]
|
||||
name = "rust_facenet_coreml"
|
||||
path = "src/bin/rust_facenet_coreml.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rust_face_processor"
|
||||
path = "src/bin/rust_face_processor.rs"
|
||||
|
||||
[dependencies]
|
||||
ort = { version = "2.0.0-rc.13", features = ["download-binaries"] }
|
||||
hound = "3.5"
|
||||
ndarray = "0.17"
|
||||
anyhow = "1"
|
||||
anyhow = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
clap = { version = "4.0", features = ["derive"] }
|
||||
image = "0.25"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
async-trait = "0.1"
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
base64 = "0.22"
|
||||
regex = "1.0"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.0", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 2
|
||||
[workspace]
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use anyhow::{Context, Result};
|
||||
use image::{RgbImage, ImageBuffer, 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;
|
||||
|
||||
// Crop face
|
||||
let cropped = imageops::crop(frame, 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,115 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use serde::Deserialize;
|
||||
use crate::face_processor::FaceDetection;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftDetection {
|
||||
frames: Vec<SwiftFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftFrame {
|
||||
frame: usize,
|
||||
timestamp: f64,
|
||||
faces: Vec<SwiftFace>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftFace {
|
||||
bbox: SwiftBBox,
|
||||
confidence: f64,
|
||||
#[serde(rename = "captureQuality")]
|
||||
capture_quality: Option<i32>,
|
||||
pose: Option<SwiftPose>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftBBox {
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SwiftPose {
|
||||
roll: f64,
|
||||
yaw: f64,
|
||||
pitch: f64,
|
||||
}
|
||||
|
||||
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...");
|
||||
|
||||
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() {
|
||||
anyhow::bail!("Swift face detection failed: {:?}", output.stderr);
|
||||
}
|
||||
|
||||
// Parse output JSON
|
||||
let detection: SwiftDetection = serde_json::from_slice(&output.stdout)
|
||||
.context("Failed to parse Swift detection output")?;
|
||||
|
||||
// Convert to our format
|
||||
let faces: Vec<FaceDetection> = detection.frames.into_iter().flat_map(|frame| {
|
||||
frame.faces.into_iter().map(|face| {
|
||||
FaceDetection {
|
||||
frame: frame.frame,
|
||||
timestamp: frame.timestamp,
|
||||
bbox: crate::face_processor::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,
|
||||
pose: face.pose.map(|p| crate::face_processor::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,11 @@
|
||||
pub mod types;
|
||||
pub mod video;
|
||||
pub mod detection;
|
||||
pub mod crop;
|
||||
pub mod embedding;
|
||||
|
||||
pub use types::*;
|
||||
pub use video::VideoReader;
|
||||
pub use detection::FaceDetector;
|
||||
pub use crop::FaceCropper;
|
||||
pub use embedding::EmbeddingExtractor;
|
||||
@@ -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<i32>,
|
||||
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 capture_quality: Option<f64>,
|
||||
pub pose_angle: Option<PoseAngle>,
|
||||
}
|
||||
|
||||
#[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,109 @@
|
||||
use anyhow::{Context, Result};
|
||||
use ffmpeg_next as ffmpeg;
|
||||
use image::{RgbImage, ImageBuffer};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct VideoReader {
|
||||
decoder: ffmpeg::decoder::Video,
|
||||
scaler: ffmpeg::software::scaling::Context,
|
||||
frame_count: usize,
|
||||
fps: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
impl VideoReader {
|
||||
pub fn new(video_path: &Path) -> Result<Self> {
|
||||
ffmpeg::init().context("Failed to initialize FFmpeg")?;
|
||||
|
||||
let input = ffmpeg::format::input(video_path)
|
||||
.context("Failed to open video file")?;
|
||||
|
||||
let video_stream = input
|
||||
.streams()
|
||||
.best(ffmpeg::media::Type::Video)
|
||||
.context("No video stream found")?;
|
||||
|
||||
let stream_index = video_stream.index();
|
||||
let fps = video_stream.avg_frame_rate().numerator() as f64
|
||||
/ video_stream.avg_frame_rate().denominator() as f64;
|
||||
let frame_count = video_stream.frames() as usize;
|
||||
|
||||
let context_decoder = ffmpeg::codec::context::Context::from_parameters(
|
||||
video_stream.parameters()
|
||||
)?;
|
||||
|
||||
let decoder = context_decoder
|
||||
.decoder()
|
||||
.video()
|
||||
.context("Failed to get video decoder")?;
|
||||
|
||||
let width = decoder.width();
|
||||
let height = decoder.height();
|
||||
|
||||
let scaler = ffmpeg::software::scaling::Context::get(
|
||||
decoder.format(),
|
||||
width,
|
||||
height,
|
||||
ffmpeg::format::pixel::Pixel::RGB24,
|
||||
width,
|
||||
height,
|
||||
ffmpeg::software::scaling::Flags::BILINEAR,
|
||||
)?;
|
||||
|
||||
Ok(Self {
|
||||
decoder,
|
||||
scaler,
|
||||
frame_count,
|
||||
fps,
|
||||
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>> {
|
||||
// Seek to frame
|
||||
let seek_time = frame_num as f64 / self.fps;
|
||||
self.decoder.set_position(seek_time as i64)?;
|
||||
|
||||
// Read and decode frame
|
||||
let mut frame = ffmpeg::util::frame::Video::empty();
|
||||
let mut rgb_frame = ffmpeg::util::frame::Video::empty();
|
||||
|
||||
self.decoder.receive_frame(&mut frame)?;
|
||||
self.scaler.run(&frame, &mut rgb_frame)?;
|
||||
|
||||
// Convert to image::RgbImage
|
||||
let data = rgb_frame.data(0);
|
||||
let linesize = rgb_frame.stride(0);
|
||||
|
||||
let mut img_data = Vec::with_capacity((self.width * self.height * 3) as usize);
|
||||
|
||||
for y in 0..self.height {
|
||||
let offset = (y * linesize) as usize;
|
||||
let row = &data[offset..offset + (self.width * 3) as usize];
|
||||
img_data.extend_from_slice(row);
|
||||
}
|
||||
|
||||
let img = ImageBuffer::from_raw(self.width, self.height, img_data)
|
||||
.context("Failed to create image buffer")?;
|
||||
|
||||
Ok(Some(img))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "swift-argument-parser",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-argument-parser.git",
|
||||
"state" : {
|
||||
"revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382",
|
||||
"version" : "1.8.2"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
@@ -6,11 +6,22 @@ let package = Package(
|
||||
platforms: [.macOS(.v12)],
|
||||
products: [
|
||||
.executable(name: "swift_scene_detector", targets: ["swift_scene_detector"]),
|
||||
.executable(name: "swift_face", targets: ["swift_face"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.0"),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "swift_scene_detector",
|
||||
path: "Sources/swift_scene_detector"
|
||||
),
|
||||
.executableTarget(
|
||||
name: "swift_face",
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
path: "Sources/swift_face"
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -170,6 +170,23 @@ struct SwiftFace: ParsableCommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Calculate quality from size, confidence, pose if API didn't provide it
|
||||
if captureQ == 0.0 {
|
||||
let faceArea = Double(faceW * faceH)
|
||||
let imgArea = Double(imgW * imgH)
|
||||
let sizeScore = min(1.0, (faceArea / imgArea) * 4.0) // Normalize, larger = better
|
||||
let confScore = lmConf // Already 0-1
|
||||
|
||||
// Pose score (frontal = 1.0, profile = 0.0)
|
||||
var poseScore = 1.0
|
||||
if let yaw = lmObs.yaw?.doubleValue {
|
||||
poseScore = max(0.0, 1.0 - abs(yaw) / 90.0)
|
||||
}
|
||||
|
||||
// Weighted combination
|
||||
captureQ = sizeScore * 0.3 + confScore * 0.4 + poseScore * 0.3
|
||||
}
|
||||
|
||||
// Match face observation by bbox to extract faceprint (embedding)
|
||||
var embedding: [Float]? = nil
|
||||
@@ -312,6 +329,17 @@ struct SwiftFace: ParsableCommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Calculate quality from size and confidence if API didn't provide it
|
||||
if captureQ == 0.0 {
|
||||
let faceArea = Double(faceW * faceH)
|
||||
let imgArea = Double(imgW * imgH)
|
||||
let sizeScore = min(1.0, (faceArea / imgArea) * 4.0) // Normalize, larger = better
|
||||
let confScore = Double(faceObs.confidence) // Already 0-1
|
||||
|
||||
// Weighted combination (no pose available for unmatched faces)
|
||||
captureQ = sizeScore * 0.5 + confScore * 0.5
|
||||
}
|
||||
|
||||
var faceData: [String: Any] = [
|
||||
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
|
||||
Reference in New Issue
Block a user