567 lines
22 KiB
Rust
567 lines
22 KiB
Rust
//! Voice activity detection and utterance segmentation (Capri `asr_runtime/recognition.py`, Silero VAD v5).
|
|
use std::collections::VecDeque;
|
|
use std::path::Path;
|
|
|
|
use anyhow::{Result, ensure};
|
|
|
|
use crate::wake::WordBoundary;
|
|
|
|
pub const RATE: u64 = 16_000;
|
|
const WINDOW: usize = 512;
|
|
const PRE_ROLL: u64 = 6400;
|
|
const TAIL: u64 = 2400;
|
|
|
|
/// Silero VAD v5 through ONNX Runtime (Capri's pinned `silero_vad.onnx`).
|
|
pub struct Silero {
|
|
session: ort::session::Session,
|
|
state: Vec<f32>,
|
|
context: Vec<f32>,
|
|
}
|
|
|
|
impl Silero {
|
|
pub fn load(model: &Path) -> Result<Self> {
|
|
let session = ort::session::Session::builder(crate::ort_env()?)?.with_intra_threads(1).map_err(|e| anyhow::anyhow!("{e}"))?.commit_from_file(model)?;
|
|
Ok(Self { session, state: vec![0.0; 256], context: vec![0.0; 64] })
|
|
}
|
|
|
|
fn probability(&mut self, window: &[f32]) -> Result<f32> {
|
|
let mut input = self.context.clone();
|
|
input.extend_from_slice(window);
|
|
self.context.copy_from_slice(&input[input.len() - 64..]);
|
|
let outputs = self.session.run(ort::inputs![
|
|
"input" => ort::value::Tensor::from_array(([1usize, input.len()], input))?,
|
|
"state" => ort::value::Tensor::from_array(([2usize, 1, 128], self.state.clone()))?,
|
|
"sr" => ort::value::Tensor::from_array(ndarray::arr0(RATE as i64))?,
|
|
])?;
|
|
self.state = outputs["stateN"].try_extract_tensor::<f32>()?.1.to_vec();
|
|
Ok(outputs["output"].try_extract_tensor::<f32>()?.1[0])
|
|
}
|
|
|
|
fn reset(&mut self) {
|
|
self.state.fill(0.0);
|
|
self.context.fill(0.0);
|
|
}
|
|
}
|
|
|
|
pub enum Detector {
|
|
Silero(Box<Silero>),
|
|
/// Fallback until Silero is downloaded: RMS level instead of a speech model (probability 0.5 at -40 dBFS).
|
|
Energy,
|
|
}
|
|
|
|
impl Detector {
|
|
fn probability(&mut self, window: &[f32]) -> f32 {
|
|
match self {
|
|
Self::Silero(s) => s.probability(window).unwrap_or_else(|e| {
|
|
tracing::warn!(error = %e, "VAD inference failed");
|
|
0.0
|
|
}),
|
|
Self::Energy => ((window.iter().map(|x| x * x).sum::<f32>() / window.len() as f32).sqrt() * 50.0).min(1.0),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct Segment {
|
|
pub start: u64,
|
|
pub len: u64,
|
|
}
|
|
|
|
/// Streaming segmenter with sherpa-onnx `VoiceActivityDetector` semantics, on its own sample clock.
|
|
pub struct Vad {
|
|
detector: Detector,
|
|
threshold: f32,
|
|
min_speech: u64,
|
|
min_silence: u64,
|
|
max_speech: u64,
|
|
pending: Vec<f32>,
|
|
clock: u64,
|
|
triggered: bool,
|
|
temp_start: Option<u64>,
|
|
temp_end: Option<u64>,
|
|
seg_start: u64,
|
|
segments: VecDeque<Segment>,
|
|
}
|
|
|
|
impl Vad {
|
|
/// `max_speech_duration = maxUtterance + max(4, pause + 2) + 1` s: beyond the session limit, so it never crops a command.
|
|
pub fn new(detector: Detector, threshold: f32, min_speech_seconds: f32, pause_seconds: f32, max_utterance_seconds: u32) -> Self {
|
|
let max_speech = max_utterance_seconds as f32 + (pause_seconds + 2.0).max(4.0) + 1.0;
|
|
Self {
|
|
detector,
|
|
threshold,
|
|
min_speech: (min_speech_seconds * RATE as f32) as u64,
|
|
min_silence: (pause_seconds * RATE as f32) as u64,
|
|
max_speech: (max_speech * RATE as f32) as u64,
|
|
pending: Vec::new(),
|
|
clock: 0,
|
|
triggered: false,
|
|
temp_start: None,
|
|
temp_end: None,
|
|
seg_start: 0,
|
|
segments: VecDeque::new(),
|
|
}
|
|
}
|
|
|
|
fn close(&mut self, end: u64) {
|
|
self.segments.push_back(Segment { start: self.seg_start, len: end.saturating_sub(self.seg_start) });
|
|
self.triggered = false;
|
|
self.temp_start = None;
|
|
self.temp_end = None;
|
|
}
|
|
|
|
pub fn accept(&mut self, pcm: &[f32]) {
|
|
self.pending.extend_from_slice(pcm);
|
|
let mut offset = 0;
|
|
while self.pending.len() - offset >= WINDOW {
|
|
let window: Vec<f32> = self.pending[offset..offset + WINDOW].to_vec();
|
|
offset += WINDOW;
|
|
let speech = self.detector.probability(&window) >= self.threshold;
|
|
let end = self.clock + WINDOW as u64;
|
|
if speech {
|
|
self.temp_end = None;
|
|
if !self.triggered {
|
|
let start = *self.temp_start.get_or_insert(self.clock);
|
|
if end - start >= self.min_speech {
|
|
self.triggered = true;
|
|
self.seg_start = end.saturating_sub(2 * WINDOW as u64 + self.min_speech);
|
|
}
|
|
}
|
|
} else if !self.triggered {
|
|
self.temp_start = None;
|
|
} else {
|
|
let silence = *self.temp_end.get_or_insert(self.clock);
|
|
if end - silence >= self.min_silence {
|
|
self.close(silence);
|
|
}
|
|
}
|
|
if self.triggered && end - self.seg_start > self.max_speech {
|
|
self.close(end);
|
|
}
|
|
self.clock = end;
|
|
}
|
|
self.pending.drain(..offset);
|
|
}
|
|
|
|
pub fn flush(&mut self) {
|
|
if self.triggered {
|
|
let end = self.temp_end.unwrap_or(self.clock);
|
|
self.close(end);
|
|
}
|
|
}
|
|
|
|
pub fn reset(&mut self) {
|
|
if let Detector::Silero(s) = &mut self.detector {
|
|
s.reset();
|
|
}
|
|
self.pending.clear();
|
|
self.clock = 0;
|
|
self.triggered = false;
|
|
self.temp_start = None;
|
|
self.temp_end = None;
|
|
self.segments.clear();
|
|
}
|
|
|
|
fn current(&self) -> Segment {
|
|
Segment { start: self.seg_start, len: self.clock.saturating_sub(self.seg_start) }
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Phase {
|
|
Idle,
|
|
Speech,
|
|
Processing,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum RecEvent {
|
|
State { utterance: i64, phase: Phase },
|
|
WakeCandidate { utterance: i64, text: String, boundaries: Vec<WordBoundary> },
|
|
Transcript { utterance: i64, revision: u64, text: String, audio_seconds: f64, prefix_removed: bool, recognition_ms: f64 },
|
|
/// An overlong turn was dropped; capture and model keep running.
|
|
Reset { utterance: i64, next_utterance: i64 },
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct Job {
|
|
pub wake: bool,
|
|
pub utterance: i64,
|
|
pub revision: u64,
|
|
pub pcm: Vec<f32>,
|
|
pub audio_start: u64,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, PartialEq)]
|
|
pub struct Recognized {
|
|
pub text: String,
|
|
/// Word offsets in `text` and sample positions relative to the decoded audio.
|
|
pub boundaries: Vec<WordBoundary>,
|
|
pub prefix_removed: bool,
|
|
}
|
|
|
|
/// Removes leading words inside the confirmed wake interval (one encoder frame of margin).
|
|
pub fn remove_wake_prefix(result: Recognized, until_sample: u64) -> Recognized {
|
|
if result.boundaries.is_empty() {
|
|
return result;
|
|
}
|
|
let cutoff = until_sample.saturating_sub(1280);
|
|
let text = result.boundaries.iter().find(|w| w.start_sample >= cutoff).map_or(String::new(), |w| result.text[w.start..].trim().to_string());
|
|
Recognized { text, prefix_removed: true, ..result }
|
|
}
|
|
|
|
/// One microphone capture: utterance numbering, history, endpoints and wake probes.
|
|
pub struct Recognition {
|
|
vad: Vad,
|
|
alive: bool,
|
|
active: bool,
|
|
wake_enabled: bool,
|
|
pub attention: bool,
|
|
max_seconds: u32,
|
|
max_samples: u64,
|
|
probe_step: u64,
|
|
pub utterance: i64,
|
|
pub revision: u64,
|
|
probes: u32,
|
|
last_probe: u64,
|
|
pcm: Option<Vec<f32>>,
|
|
start: u64,
|
|
turn_start: Option<u64>,
|
|
received: u64,
|
|
next_activity: u64,
|
|
history: VecDeque<(u64, Vec<f32>)>,
|
|
vad_offset: u64,
|
|
pending_pause: Option<(Vad, f32)>,
|
|
wake_end: Option<u64>,
|
|
}
|
|
|
|
fn session_limit(max_seconds: u32, pause: f32) -> u64 {
|
|
((max_seconds as f32 + (pause + 2.0).max(4.0)) * RATE as f32) as u64
|
|
}
|
|
|
|
impl Recognition {
|
|
pub fn new(vad: Vad, wake_enabled: bool, max_utterance_seconds: u32, pause_seconds: f32, wake_probe_seconds: f32) -> Self {
|
|
Self {
|
|
vad,
|
|
alive: true,
|
|
active: false,
|
|
wake_enabled,
|
|
attention: !wake_enabled,
|
|
max_seconds: max_utterance_seconds,
|
|
max_samples: session_limit(max_utterance_seconds, pause_seconds),
|
|
probe_step: (wake_probe_seconds * RATE as f32) as u64,
|
|
utterance: 0,
|
|
revision: 0,
|
|
probes: 0,
|
|
last_probe: 0,
|
|
pcm: None,
|
|
start: 0,
|
|
turn_start: None,
|
|
received: 0,
|
|
next_activity: 0,
|
|
history: VecDeque::new(),
|
|
vad_offset: 0,
|
|
pending_pause: None,
|
|
wake_end: None,
|
|
}
|
|
}
|
|
|
|
/// A new pause applies only when idle; an utterance in progress keeps its detector.
|
|
pub fn configure_pause(&mut self, vad: Vad, seconds: f32) {
|
|
self.pending_pause = Some((vad, seconds));
|
|
self.apply_pending_pause();
|
|
}
|
|
|
|
fn apply_pending_pause(&mut self) {
|
|
if !self.active && self.pcm.is_none()
|
|
&& let Some((vad, seconds)) = self.pending_pause.take()
|
|
{
|
|
self.vad = vad;
|
|
self.vad_offset = self.received;
|
|
self.max_samples = session_limit(self.max_seconds, seconds);
|
|
}
|
|
}
|
|
|
|
fn audio(&self, start: u64, end: u64) -> Result<(u64, Vec<f32>)> {
|
|
let start = self.vad_offset.max(start.saturating_sub(PRE_ROLL));
|
|
let end = self.received.min(end + TAIL);
|
|
let mut out = Vec::new();
|
|
for (offset, chunk) in &self.history {
|
|
let stop = offset + chunk.len() as u64;
|
|
if *offset < end && stop > start {
|
|
out.extend_from_slice(&chunk[start.saturating_sub(*offset) as usize..(end.min(stop) - offset) as usize]);
|
|
}
|
|
}
|
|
ensure!(!out.is_empty(), "Speech audio is outside the bounded history");
|
|
Ok((start, out))
|
|
}
|
|
|
|
fn discard_turn(&mut self, events: &mut Vec<RecEvent>) {
|
|
let discarded = self.utterance;
|
|
self.utterance += 1;
|
|
self.revision += 1;
|
|
self.active = false;
|
|
self.attention = !self.wake_enabled;
|
|
self.pcm = None;
|
|
self.turn_start = None;
|
|
self.start = self.received;
|
|
(self.probes, self.last_probe, self.next_activity) = (0, 0, 0);
|
|
self.wake_end = None;
|
|
self.history.clear();
|
|
self.vad.reset();
|
|
self.vad_offset = self.received;
|
|
self.apply_pending_pause();
|
|
events.push(RecEvent::Reset { utterance: discarded, next_utterance: self.utterance });
|
|
}
|
|
|
|
/// Accepts at most 200 ms of mono 16 kHz audio. `decoder_idle` gates wake probes (refused while decoding).
|
|
pub fn accept(&mut self, samples: &[f32], finish: bool, decoder_idle: bool) -> Result<(Vec<RecEvent>, Vec<Job>)> {
|
|
ensure!(samples.len() <= 3200 && samples.iter().all(|x| x.is_finite()), "Expected at most 200ms of finite mono PCM");
|
|
ensure!(self.alive, "Inactive recognition session");
|
|
let (mut events, mut jobs) = (Vec::new(), Vec::new());
|
|
self.apply_pending_pause();
|
|
let pcm: Vec<f32> = samples.iter().map(|x| x.clamp(-1.0, 1.0)).collect();
|
|
let len = pcm.len() as u64;
|
|
if !pcm.is_empty() {
|
|
self.history.push_back((self.received, pcm.clone()));
|
|
}
|
|
self.received += len;
|
|
while self.history.front().is_some_and(|(o, c)| o + c.len() as u64 + self.max_samples <= self.received) {
|
|
self.history.pop_front();
|
|
}
|
|
self.vad.accept(&pcm);
|
|
if finish {
|
|
self.vad.flush();
|
|
}
|
|
let active = self.vad.triggered && !finish;
|
|
if active && self.turn_start.is_none() {
|
|
self.turn_start = Some(self.vad_offset.max(self.received.saturating_sub(len + PRE_ROLL)));
|
|
}
|
|
if let Some(turn) = self.turn_start
|
|
&& (active || !self.vad.segments.is_empty())
|
|
&& self.received - turn > self.max_samples
|
|
{
|
|
self.discard_turn(&mut events);
|
|
return Ok((events, jobs));
|
|
}
|
|
if active && !self.active {
|
|
// Speech resumed: an endpoint being decoded is invalidated and decoded again with the continuation.
|
|
self.revision += 1;
|
|
}
|
|
if active && (!self.active || self.received >= self.next_activity) {
|
|
events.push(RecEvent::State { utterance: self.utterance, phase: Phase::Speech });
|
|
self.next_activity = self.received + RATE;
|
|
}
|
|
self.active = active;
|
|
let mut completed = false;
|
|
while let Some(segment) = self.vad.segments.front().copied() {
|
|
let start = segment.start + self.vad_offset;
|
|
let oldest = self.history.front().map(|(o, _)| *o);
|
|
if segment.len > self.max_samples || oldest.is_some_and(|o| self.vad_offset.max(start.saturating_sub(PRE_ROLL)) < o) {
|
|
self.discard_turn(&mut events);
|
|
return Ok((events, jobs));
|
|
}
|
|
let (start, audio) = self.audio(start, start + segment.len)?;
|
|
self.vad.segments.pop_front();
|
|
match &mut self.pcm {
|
|
None => {
|
|
self.start = start;
|
|
self.turn_start = Some(start);
|
|
self.pcm = Some(audio);
|
|
}
|
|
Some(pcm) => {
|
|
let gap = start as i64 - (self.start + pcm.len() as u64) as i64;
|
|
let size = pcm.len() as i64 + gap.max(0) + (audio.len() as i64 + gap.min(0)).max(0);
|
|
if size > self.max_samples as i64 {
|
|
self.discard_turn(&mut events);
|
|
return Ok((events, jobs));
|
|
}
|
|
pcm.extend(std::iter::repeat_n(0.0, gap.max(0) as usize));
|
|
pcm.extend_from_slice(&audio[((-gap).max(0) as usize).min(audio.len())..]);
|
|
}
|
|
}
|
|
if self.pcm.as_ref().is_some_and(|p| p.len() as u64 > self.max_samples) {
|
|
self.discard_turn(&mut events);
|
|
return Ok((events, jobs));
|
|
}
|
|
completed = true;
|
|
}
|
|
if completed && !active {
|
|
self.revision += 1;
|
|
events.push(RecEvent::State { utterance: self.utterance, phase: Phase::Processing });
|
|
let mut pcm = self.pcm.clone().unwrap_or_default();
|
|
pcm.extend(std::iter::repeat_n(0.0, 3200)); // protects the final phoneme
|
|
jobs.push(Job { wake: false, utterance: self.utterance, revision: self.revision, pcm, audio_start: self.start });
|
|
} else if active && !self.attention && self.pcm.is_none() && self.probes < 3 {
|
|
let segment = self.vad.current();
|
|
if segment.len >= self.probe_step && segment.len - self.last_probe >= self.probe_step && segment.len <= 4 * RATE && decoder_idle {
|
|
let start = segment.start + self.vad_offset;
|
|
let (audio_start, pcm) = self.audio(start, start + segment.len)?;
|
|
jobs.push(Job { wake: true, utterance: self.utterance, revision: self.revision, pcm, audio_start });
|
|
self.probes += 1;
|
|
self.last_probe = segment.len;
|
|
}
|
|
}
|
|
Ok((events, jobs))
|
|
}
|
|
|
|
/// Whether a queued job is still worth decoding.
|
|
pub fn is_current(&self, job: &Job) -> bool {
|
|
self.alive && job.utterance == self.utterance && job.revision == self.revision
|
|
}
|
|
|
|
pub fn deliver(&mut self, job: &Job, result: Recognized, elapsed_ms: f64) -> Option<RecEvent> {
|
|
if !self.is_current(job) {
|
|
return None;
|
|
}
|
|
if job.wake {
|
|
// Internal wake matching only; never previewed or submitted.
|
|
return (self.active && !self.attention && !result.text.is_empty()).then(|| RecEvent::WakeCandidate {
|
|
utterance: job.utterance,
|
|
text: result.text,
|
|
boundaries: result
|
|
.boundaries
|
|
.into_iter()
|
|
.take(64)
|
|
.map(|w| WordBoundary { start_sample: w.start_sample + job.audio_start, end_sample: w.end_sample + job.audio_start, ..w })
|
|
.collect(),
|
|
});
|
|
}
|
|
if self.active {
|
|
return None;
|
|
}
|
|
let result = match self.wake_end.take() {
|
|
Some(end) => remove_wake_prefix(result, end.saturating_sub(job.audio_start)),
|
|
None => result,
|
|
};
|
|
self.pcm = None;
|
|
self.turn_start = None;
|
|
self.utterance += 1;
|
|
self.revision += 1;
|
|
(self.probes, self.last_probe) = (0, 0);
|
|
Some(RecEvent::Transcript {
|
|
utterance: job.utterance,
|
|
revision: job.revision,
|
|
text: result.text,
|
|
audio_seconds: (job.pcm.len() as f64 / RATE as f64 * 1000.0).round() / 1000.0,
|
|
prefix_removed: result.prefix_removed,
|
|
recognition_ms: (elapsed_ms * 100.0).round() / 100.0,
|
|
})
|
|
}
|
|
|
|
pub fn set_attention(&mut self, active: bool, utterance: Option<i64>, wake_end_sample: Option<u64>) -> Result<()> {
|
|
self.attention = active;
|
|
if !active {
|
|
self.wake_end = None;
|
|
} else if utterance == Some(self.utterance)
|
|
&& let Some(end) = wake_end_sample
|
|
{
|
|
ensure!(end > 0 && end <= self.received, "Invalid wake audio boundary");
|
|
self.wake_end = Some(end);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn stop(&mut self) {
|
|
self.alive = false;
|
|
self.pcm = None;
|
|
self.history.clear();
|
|
self.pending_pause = None;
|
|
self.vad.reset();
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn tone(seconds: f32, amplitude: f32) -> Vec<f32> {
|
|
(0..(seconds * 16000.0) as usize).map(|i| amplitude * (i as f32 * 0.07).sin()).collect()
|
|
}
|
|
|
|
fn feed(session: &mut Recognition, audio: &[f32]) -> (Vec<RecEvent>, Vec<Job>) {
|
|
let (mut events, mut jobs) = (Vec::new(), Vec::new());
|
|
for chunk in audio.chunks(1600) {
|
|
let (e, j) = session.accept(chunk, false, true).unwrap();
|
|
events.extend(e);
|
|
jobs.extend(j);
|
|
}
|
|
(events, jobs)
|
|
}
|
|
|
|
fn session(wake: bool, max: u32) -> Recognition {
|
|
Recognition::new(Vad::new(Detector::Energy, 0.5, 0.12, 1.0, max), wake, max, 1.0, 0.8)
|
|
}
|
|
|
|
#[test]
|
|
fn endpoint_produces_one_final_job_with_pre_roll() {
|
|
let mut s = session(false, 30);
|
|
let mut audio = tone(1.0, 0.0);
|
|
audio.extend(tone(1.5, 0.3));
|
|
audio.extend(tone(1.5, 0.0));
|
|
let (events, jobs) = feed(&mut s, &audio);
|
|
assert_eq!(events.first(), Some(&RecEvent::State { utterance: 0, phase: Phase::Speech }));
|
|
assert!(events.contains(&RecEvent::State { utterance: 0, phase: Phase::Processing }));
|
|
assert_eq!(jobs.len(), 1);
|
|
let job = &jobs[0];
|
|
assert!(!job.wake);
|
|
assert!((8000..16000).contains(&job.audio_start), "starts before the speech onset: {}", job.audio_start);
|
|
let seconds = job.pcm.len() as f32 / 16000.0;
|
|
assert!((1.5..2.4).contains(&seconds), "{seconds}");
|
|
let delivered = s.deliver(job, Recognized { text: "hello".into(), ..Default::default() }, 12.345).unwrap();
|
|
assert!(matches!(delivered, RecEvent::Transcript { utterance: 0, ref text, recognition_ms, .. } if text == "hello" && recognition_ms == 12.35));
|
|
assert_eq!(s.utterance, 1);
|
|
assert!(s.deliver(job, Recognized::default(), 1.0).is_none(), "a delivered job is stale");
|
|
}
|
|
|
|
#[test]
|
|
fn resumed_speech_invalidates_endpoint_and_merges() {
|
|
let mut s = session(false, 30);
|
|
let mut audio = tone(0.5, 0.0);
|
|
audio.extend(tone(1.0, 0.3));
|
|
audio.extend(tone(1.2, 0.0));
|
|
let (_, first) = feed(&mut s, &audio);
|
|
let (_, second) = feed(&mut s, &[tone(1.0, 0.3), tone(1.5, 0.0)].concat());
|
|
assert!(!s.is_current(&first[0]), "speech resumed after the endpoint");
|
|
assert!(second[0].pcm.len() > first[0].pcm.len() + 16000, "merged utterance holds both parts");
|
|
}
|
|
|
|
#[test]
|
|
fn overlong_turn_is_discarded_and_wake_probe_runs() {
|
|
let mut s = session(true, 10);
|
|
let (events, jobs) = feed(&mut s, &tone(15.0, 0.3));
|
|
assert!(jobs.iter().any(|j| j.wake), "wake probe while waiting for the name");
|
|
assert_eq!(jobs.iter().filter(|j| j.wake && j.utterance == 0).count(), 3, "at most three probes per utterance");
|
|
assert!(events.iter().any(|e| matches!(e, RecEvent::Reset { utterance: 0, next_utterance: 1 })));
|
|
assert!(jobs.iter().all(|j| j.wake), "no cropped command is decoded");
|
|
}
|
|
|
|
/// Capri's pinned Silero model: `CAPRI_VOICE_SPEECH_DIR=<data>/speech cargo test -- --ignored`.
|
|
#[test]
|
|
#[ignore]
|
|
fn silero_detects_a_tone_burst() {
|
|
let speech = std::path::PathBuf::from(std::env::var("CAPRI_VOICE_SPEECH_DIR").unwrap());
|
|
let mut silero = Silero::load(&crate::asr::silero_path(&speech)).unwrap();
|
|
let silence = vec![0.0f32; 512];
|
|
assert!(silero.probability(&silence).unwrap() < 0.5);
|
|
let mut vad = Vad::new(Detector::Silero(Box::new(silero)), 0.5, 0.12, 1.0, 30);
|
|
vad.accept(&tone(2.0, 0.0));
|
|
assert!(!vad.triggered);
|
|
}
|
|
|
|
#[test]
|
|
fn wake_prefix_removed_by_time() {
|
|
let result = Recognized {
|
|
text: "Hey Capri open it".into(),
|
|
boundaries: vec![
|
|
WordBoundary { start: 0, end: 3, start_sample: 0, end_sample: 4000 },
|
|
WordBoundary { start: 4, end: 9, start_sample: 4000, end_sample: 9000 },
|
|
WordBoundary { start: 10, end: 14, start_sample: 9000, end_sample: 12000 },
|
|
],
|
|
prefix_removed: false,
|
|
};
|
|
let stripped = remove_wake_prefix(result, 9500);
|
|
assert_eq!((stripped.text.as_str(), stripped.prefix_removed), ("open it", true));
|
|
}
|
|
}
|