fix: Face processor now saves status and total_faces to face.json

This commit is contained in:
Accusys
2026-09-26 23:06:11 +08:00
parent 8a736a4103
commit 357e585399
99 changed files with 13881 additions and 1065 deletions
+440 -2
View File
@@ -169,6 +169,18 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bit_field"
version = "0.10.3"
@@ -208,12 +220,24 @@ version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cc"
version = "1.4.6"
@@ -284,6 +308,22 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -324,6 +364,16 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "der"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
dependencies = [
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "displaydoc"
version = "0.2.7"
@@ -361,6 +411,16 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "exr"
version = "1.74.2"
@@ -378,6 +438,12 @@ dependencies = [
"zune-inflate",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fax"
version = "0.2.7"
@@ -410,6 +476,21 @@ dependencies = [
"zlib-rs",
]
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
@@ -480,6 +561,34 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hmac-sha256"
version = "1.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec9d92d097f4749b64e8cc33d924d9f40a2d4eb91402b458014b781f5733d60f"
[[package]]
name = "hound"
version = "3.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f"
[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "icu_collections"
version = "2.3.0"
@@ -694,6 +803,12 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.3"
@@ -715,6 +830,22 @@ dependencies = [
"imgref",
]
[[package]]
name = "lzma-rust2"
version = "0.15.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619"
[[package]]
name = "matrixmultiply"
version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
dependencies = [
"autocfg",
"rawpointer",
]
[[package]]
name = "maybe-rayon"
version = "0.1.1"
@@ -761,6 +892,38 @@ dependencies = [
"pxfm",
]
[[package]]
name = "native-tls"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
dependencies = [
"libc",
"log",
"openssl",
"openssl-probe",
"openssl-sys",
"schannel",
"security-framework",
"security-framework-sys",
"tempfile",
]
[[package]]
name = "ndarray"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
dependencies = [
"matrixmultiply",
"num-complex",
"num-integer",
"num-traits",
"portable-atomic",
"portable-atomic-util",
"rawpointer",
]
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
@@ -863,6 +1026,73 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "openssl"
version = "0.10.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
dependencies = [
"bitflags",
"cfg-if",
"foreign-types",
"libc",
"openssl-macros",
"openssl-sys",
]
[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-sys"
version = "0.9.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
dependencies = [
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "ort"
version = "2.0.0-rc.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4336a1e2b38848325241c72889086886004e589b7c74f335e60a8e8db5138a0b"
dependencies = [
"ndarray",
"ort-sys",
"smallvec",
"tracing",
"ureq 3.4.2",
]
[[package]]
name = "ort-sys"
version = "2.0.0-rc.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf211e3776eea6aec988552fa118dd746d70e1b1e5e244058d1c98015f3e5872"
dependencies = [
"hmac-sha256",
"lzma-rust2",
"ureq 3.4.2",
]
[[package]]
name = "paste"
version = "1.0.15"
@@ -875,12 +1105,33 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
[[package]]
name = "pem-rfc7468"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9"
dependencies = [
"base64ct",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "png"
version = "0.18.1"
@@ -894,6 +1145,21 @@ dependencies = [
"miniz_oxide 0.8.9",
]
[[package]]
name = "portable-atomic"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
[[package]]
name = "portable-atomic-util"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
dependencies = [
"portable-atomic",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -1093,6 +1359,12 @@ dependencies = [
"bitflags",
]
[[package]]
name = "rawpointer"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
[[package]]
name = "rayon"
version = "1.12.0"
@@ -1143,11 +1415,29 @@ dependencies = [
name = "rust_processors"
version = "0.1.0"
dependencies = [
"anyhow",
"clap",
"hound",
"image",
"ndarray",
"ort",
"serde",
"serde_json",
"ureq",
"tempfile",
"ureq 2.12.1",
]
[[package]]
name = "rustix"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
]
[[package]]
@@ -1191,6 +1481,38 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "schannel"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags",
"core-foundation",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "serde"
version = "1.0.229"
@@ -1261,6 +1583,17 @@ version = "1.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
[[package]]
name = "socks"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0c3dbbd9ae980613c6dd8e28a9407b50509d3803b57624d5dfe8315218cd58b"
dependencies = [
"byteorder",
"libc",
"winapi",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -1312,6 +1645,19 @@ dependencies = [
"syn 3.0.5",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "thiserror"
version = "2.0.20"
@@ -1356,6 +1702,25 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-core",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -1374,7 +1739,7 @@ version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
dependencies = [
"base64",
"base64 0.22.1",
"flate2",
"log",
"once_cell",
@@ -1386,6 +1751,36 @@ dependencies = [
"webpki-roots 0.26.11",
]
[[package]]
name = "ureq"
version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
dependencies = [
"base64 0.23.1",
"der",
"log",
"native-tls",
"percent-encoding",
"rustls-pki-types",
"socks",
"ureq-proto",
"utf8-zero",
"webpki-root-certs",
]
[[package]]
name = "ureq-proto"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"
dependencies = [
"base64 0.23.1",
"http",
"httparse",
"log",
]
[[package]]
name = "url"
version = "2.5.8"
@@ -1398,6 +1793,12 @@ dependencies = [
"serde",
]
[[package]]
name = "utf8-zero"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
[[package]]
name = "utf8_iter"
version = "1.0.4"
@@ -1421,6 +1822,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -1487,6 +1894,15 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "webpki-root-certs"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
@@ -1511,6 +1927,28 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
+13
View File
@@ -16,6 +16,10 @@ path = "src/bin/rust_pose.rs"
name = "rust_face_cluster"
path = "src/bin/rust_face_cluster.rs"
[[bin]]
name = "rust_vad"
path = "src/bin/rust_vad.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
@@ -23,5 +27,14 @@ clap = { version = "4", features = ["derive"] }
image = "0.25"
ureq = { version = "2", features = ["json"] }
# VAD dependencies
ort = { version = "2.0.0-rc.13", features = ["download-binaries"] }
hound = "3.5"
ndarray = "0.17"
anyhow = "1"
[dev-dependencies]
tempfile = "3"
[profile.release]
opt-level = 2
+140
View File
@@ -0,0 +1,140 @@
use clap::Parser;
use anyhow::Result;
use serde_json::json;
use std::time::Instant;
use rust_processors::vad::{SileroVad, AudioReader, SpeechSegment};
use rust_processors::vad::segment::SegmentCollector;
#[derive(Parser)]
#[command(name = "rust_vad")]
#[command(about = "Silero VAD ONNX (Rust implementation)")]
struct Cli {
/// Input audio file (WAV 16kHz mono)
#[arg(short, long)]
audio: String,
/// ONNX model path
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
model: String,
/// Speech probability threshold
#[arg(long, default_value = "0.5")]
threshold: f32,
/// Minimum speech duration (milliseconds)
#[arg(long, default_value = "500")]
min_speech: u32,
/// Minimum silence duration (milliseconds)
#[arg(long, default_value = "300")]
min_silence: u32,
/// Chunk size (samples)
#[arg(long, default_value = "512")]
chunk_size: usize,
/// Output format
#[arg(long, default_value = "json")]
format: String,
}
fn main() -> Result<()> {
let cli = Cli::parse();
println!("[VAD] Loading model: {}", cli.model);
let start_load = Instant::now();
let mut vad = SileroVad::new(&cli.model)?;
println!("[VAD] Model loaded in {:.2}s", start_load.elapsed().as_secs_f32());
println!("[VAD] Loading audio: {}", cli.audio);
let audio = AudioReader::from_wav(&cli.audio)?;
let samples = audio.samples();
let sample_rate = audio.sample_rate();
let duration = audio.duration();
println!("[VAD] Audio: {} samples, {} Hz, {:.2}s",
samples.len(), sample_rate, duration);
// 檢測語音
println!("[VAD] Detecting speech...");
let start_detect = Instant::now();
let mut collector = SegmentCollector::new(
cli.threshold,
cli.min_speech,
cli.min_silence
);
// 分塊處理
for i in (0..samples.len()).step_by(cli.chunk_size) {
let end = (i + cli.chunk_size).min(samples.len());
let chunk = &samples[i..end];
// 如果塊太小,填充零
let mut chunk_vec = chunk.to_vec();
if chunk_vec.len() < cli.chunk_size {
chunk_vec.resize(cli.chunk_size, 0.0);
}
// 檢測
let speech_prob = vad.detect(&chunk_vec)?;
// 時間戳
let timestamp = i as f32 / sample_rate as f32;
// 收集片段
collector.process(timestamp, speech_prob);
}
// 結束處理
let end_timestamp = samples.len() as f32 / sample_rate as f32;
collector.finalize(end_timestamp);
let segments = collector.segments();
let detect_time = start_detect.elapsed().as_secs_f32();
println!("[VAD] Detection completed in {:.2}s", detect_time);
println!("[VAD] Found {} speech segments", segments.len());
// 計算統計
let total_speech: f32 = segments.iter().map(|s| s.duration()).sum();
let speech_ratio = total_speech / duration;
println!("[VAD] Total speech: {:.2}s ({:.1}%)", total_speech, speech_ratio * 100.0);
println!("[VAD] Processing speed: {:.2}x real-time", duration / detect_time);
// 輸出結果
match cli.format.as_str() {
"json" => {
let output = json!({
"audio_file": cli.audio,
"sample_rate": sample_rate,
"duration": duration,
"segments": segments.iter().map(|s| json!({
"start": s.start_sec,
"end": s.end_sec,
"duration": s.duration()
})).collect::<Vec<_>>(),
"statistics": {
"segment_count": segments.len(),
"total_speech": total_speech,
"speech_ratio": speech_ratio,
"detect_time": detect_time
}
});
println!("{}", serde_json::to_string_pretty(&output)?);
}
"text" => {
for seg in segments {
println!("{:.2} - {:.2} ({:.2}s)",
seg.start_sec, seg.end_sec, seg.duration());
}
}
_ => {
anyhow::bail!("Unknown output format: {}", cli.format);
}
}
Ok(())
}
+1
View File
@@ -0,0 +1 @@
pub mod vad;
+42
View File
@@ -0,0 +1,42 @@
use anyhow::{Context, Result};
use hound::WavReader;
pub struct AudioReader {
samples: Vec<f32>,
sample_rate: u32,
}
impl AudioReader {
pub fn from_wav(path: &str) -> Result<Self> {
let reader = WavReader::open(path)
.context("Failed to open WAV file")?;
let spec = reader.spec();
let sample_rate = spec.sample_rate;
// 轉換為 f32,範圍 [-1.0, 1.0]
let samples: Vec<f32> = reader.into_samples::<i16>()
.map(|s| {
s.map(|v| v as f32 / 32768.0)
.unwrap_or(0.0)
})
.collect();
Ok(Self {
samples,
sample_rate,
})
}
pub fn samples(&self) -> &[f32] {
&self.samples
}
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
pub fn duration(&self) -> f32 {
self.samples.len() as f32 / self.sample_rate as f32
}
}
+7
View File
@@ -0,0 +1,7 @@
pub mod onnx;
pub mod audio;
pub mod segment;
pub use onnx::SileroVad;
pub use audio::AudioReader;
pub use segment::SpeechSegment;
+100
View File
@@ -0,0 +1,100 @@
use anyhow::{Context, Result};
use ort::session::{Session, builder::GraphOptimizationLevel};
use ort::value::Value;
use ndarray::IxDyn;
pub struct SileroVad {
session: Session,
state: Vec<f32>, // [2, 1, 128] = 256 elements
context: Vec<f32>, // [1, 64] for 16kHz
sample_rate: i64,
context_size: usize, // 64 for 16kHz, 32 for 8kHz
}
impl SileroVad {
pub fn new(model_path: &str) -> Result<Self> {
let session = Session::builder()?
.with_optimization_level(GraphOptimizationLevel::Level1)
.map_err(|e| anyhow::anyhow!("Failed to set optimization level: {}", e))?
.commit_from_file(model_path)
.map_err(|e| anyhow::anyhow!("Failed to load model: {}", e))?;
let sample_rate = 16000;
let context_size = if sample_rate == 16000 { 64 } else { 32 };
Ok(Self {
session,
state: vec![0.0; 256], // [2, 1, 128] = 256
context: vec![0.0; context_size], // [1, 64]
sample_rate,
context_size,
})
}
pub fn detect(&mut self, audio_chunk: &[f32]) -> Result<f32> {
// 拼接 context 和當前塊
let mut input_with_context = Vec::with_capacity(self.context_size + audio_chunk.len());
input_with_context.extend_from_slice(&self.context);
input_with_context.extend_from_slice(audio_chunk);
// 準備輸入
let input_array = ndarray::Array::from_shape_vec(
IxDyn(&[1, input_with_context.len()]),
input_with_context.clone()
).context("Failed to create input array")?;
let state_array = ndarray::Array::from_shape_vec(
IxDyn(&[2, 1, 128]),
self.state.clone()
).context("Failed to create state array")?;
let sr_array = ndarray::Array::from_shape_vec(
IxDyn(&[]), // 標量
vec![self.sample_rate]
).context("Failed to create sr array")?;
// 創建 ONNX Value
let input_value = Value::from_array(input_array)
.context("Failed to create input value")?;
let state_value = Value::from_array(state_array)
.context("Failed to create state value")?;
let sr_value = Value::from_array(sr_array)
.context("Failed to create sr value")?;
// 運行推理
let inputs = ort::inputs![
"input" => input_value,
"state" => state_value,
"sr" => sr_value,
];
let outputs = self.session.run(inputs)
.context("Failed to run inference")?;
// 提取輸出
let output = outputs["output"].try_extract_tensor::<f32>()
.context("Failed to extract output")?;
// output 是 (&Shape, &[f32]) tuple
let output_data = output.1;
let speech_prob = output_data[0];
// 更新隱藏狀態
let state_n = outputs["stateN"].try_extract_tensor::<f32>()
.context("Failed to extract stateN")?;
// state_n 是 (&Shape, &[f32]) tuple
let state_data = state_n.1;
self.state = state_data.to_vec();
// 更新 context(當前輸入的最後 context_size 個樣本)
self.context = input_with_context[input_with_context.len() - self.context_size..].to_vec();
Ok(speech_prob)
}
pub fn reset_state(&mut self) {
self.state = vec![0.0; 256];
self.context = vec![0.0; self.context_size];
}
}
@@ -0,0 +1,86 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpeechSegment {
pub start_sec: f32,
pub end_sec: f32,
}
impl SpeechSegment {
pub fn new(start_sec: f32, end_sec: f32) -> Self {
Self { start_sec, end_sec }
}
pub fn duration(&self) -> f32 {
self.end_sec - self.start_sec
}
}
pub struct SegmentCollector {
segments: Vec<SpeechSegment>,
current_start: Option<f32>,
threshold: f32,
min_speech_duration: f32,
min_silence_duration: f32,
silence_start: Option<f32>,
}
impl SegmentCollector {
pub fn new(threshold: f32, min_speech_ms: u32, min_silence_ms: u32) -> Self {
Self {
segments: Vec::new(),
current_start: None,
threshold,
min_speech_duration: min_speech_ms as f32 / 1000.0,
min_silence_duration: min_silence_ms as f32 / 1000.0,
silence_start: None,
}
}
pub fn process(&mut self, timestamp: f32, speech_prob: f32) {
if speech_prob >= self.threshold {
// 語音
if self.current_start.is_none() {
self.current_start = Some(timestamp);
}
self.silence_start = None;
} else {
// 靜音
if self.current_start.is_some() {
if self.silence_start.is_none() {
self.silence_start = Some(timestamp);
}
// 檢查是否結束語音段
if let Some(silence_start) = self.silence_start {
let silence_duration = timestamp - silence_start;
if silence_duration >= self.min_silence_duration {
// 結束語音段
if let Some(start) = self.current_start {
let duration = silence_start - start;
if duration >= self.min_speech_duration {
self.segments.push(SpeechSegment::new(start, silence_start));
}
}
self.current_start = None;
self.silence_start = None;
}
}
}
}
}
pub fn finalize(&mut self, end_timestamp: f32) {
// 處理最後一個段
if let Some(start) = self.current_start {
let duration = end_timestamp - start;
if duration >= self.min_speech_duration {
self.segments.push(SpeechSegment::new(start, end_timestamp));
}
}
}
pub fn segments(&self) -> &[SpeechSegment] {
&self.segments
}
}