Skip to content

Commit

Permalink
Fixes #4 (#5)
Browse files Browse the repository at this point in the history
* some users won't want static file

It adds to binary bloat, some people may prefer to use the file system
or have their own silero models to use.

* Tweak name and test
  • Loading branch information
xd009642 authored Aug 16, 2024
1 parent 6d97fbd commit 2293843
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,7 @@ edition = "2021"
anyhow = "1.0.86"
ndarray = "0.15.6"
ort = "2.0.0-rc.4"

[features]
default = ["static-model"]
static-model = []
34 changes: 24 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#![doc = include_str!("../README.md")]
use anyhow::{bail, Result};
use anyhow::{bail, Context, Result};
use ndarray::{Array1, Array2, Array3, ArrayBase, Ix1, Ix3, OwnedRepr};
use ort::{GraphOptimizationLevel, Session};
use std::path::Path;

/// Parameters used to configure a vad session. These will determine the sensitivity and switching
/// speed of detection.
Expand Down Expand Up @@ -68,14 +69,13 @@ pub enum VadTransition {
}

impl VadSession {
pub fn new(config: VadConfig) -> Result<Self> {
if ![8000_usize, 16000].contains(&config.sample_rate) {
bail!("Unsupported sample rate, use 8000 or 16000!");
}
let model_bytes: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/models/silero_vad.onnx"
));
pub fn new_from_path(file: impl AsRef<Path>, config: VadConfig) -> Result<Self> {
let bytes = std::fs::read(file.as_ref())
.with_context(|| format!("Couldn't read onnx file: {}", file.as_ref().display()))?;
Self::new_from_bytes(&bytes, config)
}

pub fn new_from_bytes(model_bytes: &[u8], config: VadConfig) -> Result<Self> {
let model = Session::builder()?
.with_optimization_level(GraphOptimizationLevel::Level3)?
.with_intra_threads(4)?
Expand All @@ -98,6 +98,18 @@ impl VadSession {
})
}

#[cfg(feature = "static-model")]
pub fn new(config: VadConfig) -> Result<Self> {
if ![8000_usize, 16000].contains(&config.sample_rate) {
bail!("Unsupported sample rate, use 8000 or 16000!");
}
let model_bytes: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/models/silero_vad.onnx"
));
Self::new_from_bytes(model_bytes, config)
}

/// Advance the VAD state machine with an audio frame. Keep between 30-96ms in length.
/// Return indicates if a transition from speech to silence (or silence to speech) occurred.
///
Expand Down Expand Up @@ -258,6 +270,8 @@ mod tests {

#[test]
fn model_loads() {
let mut sesion = VadSession::new(VadConfig::default()).unwrap();
let _sesion = VadSession::new(VadConfig::default()).unwrap();
let _sesion =
VadSession::new_from_path("models/silero_vad.onnx", VadConfig::default()).unwrap();
}
}

0 comments on commit 2293843

Please sign in to comment.