Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea voice: speech to speech on this computer, for raea.app's Ideate. A session of JSON lines (say, end, stop, mute in; ready, speech began/ended, heard, saying, word, said out): Silero VAD finds the person's turns, Parakeet TDT 0.6b v3 writes their words, Pocket TTS speaks the agent's as they stream, all on ONNX Runtime with cpal for the microphone and speakers, so it runs on any OS with no cloud voice. While it speaks it doesn't listen unless --duplex (a laptop hears its own speakers); words begun before it started are still heard. raea voice hear FILE.wav and raea voice say "WORDS" -o OUT.wav do one of each; --from/--to put a recording and a file in place of the microphone and speakers for checks. Measured on an M5 Pro: 8.9 s heard in 266 ms, first sound 44 to 81 ms after the words (crate raea-app-voice, bin raea-voice; the raea CLI's voice arm is not yet compiled into a release binary)

shinyobjectz04cd051788b1
diff --git a/Cargo.lock b/Cargo.lock
index 70e4287e..d3e8689a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14035,6 +14035,18 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-app-voice"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "cpal 0.15.3",
+ "ort",
+ "raea-sys-ml",
+ "raea-sys-speech",
+ "serde_json",
+]
+
[[package]]
name = "raea-app-workspace"
version = "0.1.0"
@@ -14282,6 +14294,7 @@ dependencies = [
"raea-app-sound",
"raea-app-targets",
"raea-app-tools",
+ "raea-app-voice",
"raea-app-workspace",
"raea-bevy-plugins",
"raea-core-alloc",
diff --git a/Cargo.toml b/Cargo.toml
index e786664e..f21ecb8d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -226,6 +226,7 @@ members = [
"apps/make",
"apps/solid",
"apps/scene",
+ "apps/voice",
"apps/media",
"apps/targets",
"apps/game",
diff --git a/apps/voice/Cargo.toml b/apps/voice/Cargo.toml
new file mode 100644
index 00000000..ff995452
--- /dev/null
+++ b/apps/voice/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "raea-app-voice"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "raea voice: speech to speech on this computer (Silero's turns, Parakeet's words, Pocket TTS's voice) as lines of JSON, for an agent that talks"
+
+[[bin]]
+name = "raea-voice"
+path = "src/main.rs"
+
+[dependencies]
+# Pocket TTS and its word clock
+raea-sys-speech = { path = "../../systems/speech" }
+# ort sessions the way raea builds them, and the model cache
+raea-sys-ml = { path = "../../systems/ml" }
+ort = { version = "=2.0.0-rc.13", features = ["half"] }
+# the microphone and the speakers: the cpal the mixer uses
+cpal = "0.15"
+anyhow = "1"
+serde_json = "1"
+
+[target.'cfg(all(windows, target_arch = "x86_64"))'.dependencies]
+ort = { version = "=2.0.0-rc.13", features = ["load-dynamic"] }
diff --git a/apps/voice/src/asr.rs b/apps/voice/src/asr.rs
new file mode 100644
index 00000000..8193daf4
--- /dev/null
+++ b/apps/voice/src/asr.rs
@@ -0,0 +1,118 @@
+//! Parakeet TDT 0.6b v3 (NVIDIA, CC-BY-4.0) on ONNX: what was said. The export is istupakov/parakeet-tdt-0.6b-v3-onnx
+//! (int8 encoder and decoder, NeMo's 128-bin front end as a model of its own), decoded as onnx-asr's
+//! NemoConformerTdt decodes it: greedy, each step's token and how many encoder frames to skip.
+
+use std::path::Path;
+
+use anyhow::{anyhow, Context};
+use ort::session::Session;
+use ort::value::Tensor;
+use raea_sys_ml::models::Spec;
+
+const REPO: &str = "istupakov/parakeet-tdt-0.6b-v3-onnx";
+pub const SPEC: Spec = Spec {
+ name: "parakeet-tdt-0.6b-v3",
+ files: &[
+ (REPO, "nemo128.onnx", "nemo128.onnx"),
+ (REPO, "encoder-model.int8.onnx", "encoder-model.int8.onnx"),
+ (REPO, "decoder_joint-model.int8.onnx", "decoder_joint-model.int8.onnx"),
+ (REPO, "vocab.txt", "vocab.txt"),
+ ],
+};
+
+/// The prediction network's state: two layers of 640.
+const STATE: usize = 2 * 640;
+/// Tokens one encoder frame may give before the decoder moves on (onnx-asr's max_tokens_per_step).
+const PER_STEP: usize = 10;
+
+pub struct Asr {
+ front: Session,
+ encoder: Session,
+ decoder: Session,
+ vocab: Vec<String>,
+}
+
+fn err(e: ort::Error) -> anyhow::Error {
+ anyhow!("parakeet: {e}")
+}
+
+impl Asr {
+ pub fn load(dir: &Path) -> anyhow::Result<Asr> {
+ let vocab = std::fs::read_to_string(dir.join("vocab.txt")).context("parakeet's vocab.txt")?;
+ // "token id" a line; the token itself can hold a space's mark but never a plain space
+ let vocab: Vec<String> = vocab.lines().filter_map(|l| l.rsplit_once(' ').map(|(t, _)| t.to_string())).collect();
+ anyhow::ensure!(vocab.last().map(String::as_str) == Some("<blk>"), "parakeet's vocab.txt doesn't end in its blank");
+ Ok(Asr {
+ front: raea_sys_ml::session(&dir.join("nemo128.onnx"))?,
+ encoder: raea_sys_ml::session(&dir.join("encoder-model.int8.onnx"))?,
+ decoder: raea_sys_ml::session(&dir.join("decoder_joint-model.int8.onnx"))?,
+ vocab,
+ })
+ }
+
+ /// The words in `x` (16 kHz mono), as one line.
+ pub fn hear(&mut self, x: &[f32]) -> anyhow::Result<String> {
+ if x.len() < 1600 {
+ return Ok(String::new());
+ }
+ let wave = Tensor::from_array(([1usize, x.len()], x.to_vec())).map_err(err)?;
+ let len = Tensor::from_array(([1usize], vec![x.len() as i64])).map_err(err)?;
+ let (shape, feats, flen) = {
+ let o = self.front.run(ort::inputs!["waveforms" => wave, "waveforms_lens" => len]).map_err(err)?;
+ let (shape, f) = o["features"].try_extract_tensor::<f32>().map_err(err)?;
+ let (_, l) = o["features_lens"].try_extract_tensor::<i64>().map_err(err)?;
+ (shape.iter().map(|d| *d as usize).collect::<Vec<_>>(), f.to_vec(), l[0])
+ };
+ let feats = Tensor::from_array((shape, feats)).map_err(err)?;
+ let flen = Tensor::from_array(([1usize], vec![flen])).map_err(err)?;
+ let (dim, frames, enc) = {
+ let o = self.encoder.run(ort::inputs!["audio_signal" => feats, "length" => flen]).map_err(err)?;
+ let (shape, e) = o["outputs"].try_extract_tensor::<f32>().map_err(err)?;
+ let (_, l) = o["encoded_lengths"].try_extract_tensor::<i64>().map_err(err)?;
+ (shape[1] as usize, (shape[2] as usize, l[0] as usize), e.to_vec())
+ };
+ let (width, frames) = frames;
+ let blank = self.vocab.len() - 1;
+ let (mut s1, mut s2) = (vec![0f32; STATE], vec![0f32; STATE]);
+ let mut tokens: Vec<usize> = Vec::new();
+ let (mut t, mut emitted) = (0usize, 0usize);
+ while t < frames.min(width) {
+ let frame: Vec<f32> = (0..dim).map(|d| enc[d * width + t]).collect();
+ let last = tokens.last().copied().unwrap_or(blank) as i32;
+ let o = self
+ .decoder
+ .run(ort::inputs![
+ "encoder_outputs" => Tensor::from_array(([1usize, dim, 1], frame)).map_err(err)?,
+ "targets" => Tensor::from_array(([1usize, 1], vec![last])).map_err(err)?,
+ "target_length" => Tensor::from_array(([1usize], vec![1i32])).map_err(err)?,
+ "input_states_1" => Tensor::from_array(([2usize, 1, 640], s1.clone())).map_err(err)?,
+ "input_states_2" => Tensor::from_array(([2usize, 1, 640], s2.clone())).map_err(err)?,
+ ])
+ .map_err(err)?;
+ let (_, logits) = o["outputs"].try_extract_tensor::<f32>().map_err(err)?;
+ let best = |v: &[f32]| v.iter().enumerate().fold((0usize, f32::NEG_INFINITY), |b, (i, x)| if *x > b.1 { (i, *x) } else { b }).0;
+ let token = best(&logits[..self.vocab.len()]);
+ let skip = best(&logits[self.vocab.len()..]);
+ if token != blank {
+ s1.copy_from_slice(&o["output_states_1"].try_extract_tensor::<f32>().map_err(err)?.1[..STATE]);
+ s2.copy_from_slice(&o["output_states_2"].try_extract_tensor::<f32>().map_err(err)?.1[..STATE]);
+ tokens.push(token);
+ emitted += 1;
+ }
+ if skip > 0 {
+ t += skip;
+ emitted = 0;
+ } else if token == blank || emitted == PER_STEP {
+ t += 1;
+ emitted = 0;
+ }
+ }
+ Ok(self.text(&tokens))
+ }
+
+ /// Tokens as a line: a token's leading mark is the space before a word.
+ fn text(&self, tokens: &[usize]) -> String {
+ let joined: String = tokens.iter().map(|t| self.vocab[*t].as_str()).filter(|t| !t.starts_with("<|")).collect();
+ joined.replace('\u{2581}', " ").split_whitespace().collect::<Vec<_>>().join(" ")
+ }
+}
diff --git a/apps/voice/src/audio.rs b/apps/voice/src/audio.rs
new file mode 100644
index 00000000..f62ed775
--- /dev/null
+++ b/apps/voice/src/audio.rs
@@ -0,0 +1,274 @@
+//! The microphone and the speakers (cpal), or files in their place (`--from`, `--to`: a session with no devices, for
+//! checks and for measuring).
+
+use std::collections::VecDeque;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::mpsc::Sender;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use anyhow::{anyhow, bail, Context};
+use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
+
+/// A stream's rate changed as it comes, by linear interpolation: speech in, and Pocket's 24 kHz out.
+pub struct Resample {
+ /// input samples per output sample
+ step: f64,
+ /// where the next output sample falls, in input samples from the start of the next piece (-1 is `last`)
+ pos: f64,
+ last: f32,
+}
+
+impl Resample {
+ pub fn new(from: u32, to: u32) -> Resample {
+ Resample { step: from as f64 / to as f64, pos: 0.0, last: 0.0 }
+ }
+
+ pub fn push(&mut self, x: &[f32], out: &mut Vec<f32>) {
+ let Some(&end) = x.last() else { return };
+ while self.pos + 1.0 < x.len() as f64 {
+ let i = self.pos.floor();
+ let a = if i < 0.0 { self.last } else { x[i as usize] };
+ let b = x[(i + 1.0) as usize];
+ out.push(a + (b - a) * (self.pos - i) as f32);
+ self.pos += self.step;
+ }
+ self.pos -= x.len() as f64;
+ self.last = end;
+ }
+}
+
+/// Interleaved channels as one: each frame's mean.
+fn mono(x: &[f32], ch: usize) -> Vec<f32> {
+ let mut out = Vec::with_capacity(x.len() / ch + 1);
+ for frame in x.chunks(ch) {
+ let mut sum = 0.0;
+ for s in frame {
+ sum += s;
+ }
+ out.push(sum / frame.len() as f32);
+ }
+ out
+}
+
+/// A WAV's sound as mono samples and its rate: 16-bit PCM or 32-bit float, any channels.
+pub fn read_wav(path: &Path) -> anyhow::Result<(Vec<f32>, u32)> {
+ let b = std::fs::read(path).with_context(|| format!("{}", path.display()))?;
+ anyhow::ensure!(b.len() > 12 && &b[..4] == b"RIFF" && &b[8..12] == b"WAVE", "{}: not a WAV file", path.display());
+ let u16_at = |i: usize| u16::from_le_bytes([b[i], b[i + 1]]);
+ let u32_at = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
+ let (mut at, mut fmt) = (12usize, None);
+ while at + 8 <= b.len() {
+ let (id, len) = (&b[at..at + 4], u32_at(at + 4) as usize);
+ let body = at + 8;
+ if id == b"fmt " && body + 16 <= b.len() {
+ fmt = Some((u16_at(body), u16_at(body + 2) as usize, u32_at(body + 4), u16_at(body + 14)));
+ } else if id == b"data" {
+ let (kind, ch, rate, bits) = fmt.ok_or_else(|| anyhow!("{}: its sound comes before its format", path.display()))?;
+ let data = &b[body..(body + len).min(b.len())];
+ let one: Vec<f32> = match (kind, bits) {
+ (1, 16) => data.chunks_exact(2).map(|s| i16::from_le_bytes([s[0], s[1]]) as f32 / 32768.0).collect(),
+ (3, 32) => data.chunks_exact(4).map(|s| f32::from_le_bytes([s[0], s[1], s[2], s[3]])).collect(),
+ _ => bail!("{}: a {bits}-bit WAV of kind {kind}; 16-bit PCM and 32-bit float are read", path.display()),
+ };
+ return Ok((mono(&one, ch.max(1)), rate));
+ }
+ at = body + len + (len & 1);
+ }
+ bail!("{}: a WAV with no sound in it", path.display())
+}
+
+/// Mono samples as a 16-bit WAV.
+pub fn write_wav(path: &Path, x: &[f32], rate: u32) -> anyhow::Result<()> {
+ let mut b = Vec::with_capacity(44 + x.len() * 2);
+ let len = (x.len() * 2) as u32;
+ b.extend_from_slice(b"RIFF");
+ b.extend_from_slice(&(36 + len).to_le_bytes());
+ b.extend_from_slice(b"WAVEfmt ");
+ for v in [16u32, 1 | (1 << 16), rate, rate * 2, 2 | (16 << 16)] {
+ b.extend_from_slice(&v.to_le_bytes());
+ }
+ b.extend_from_slice(b"data");
+ b.extend_from_slice(&len.to_le_bytes());
+ for s in x {
+ b.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0) as i16).to_le_bytes());
+ }
+ std::fs::write(path, b).with_context(|| format!("{}", path.display()))
+}
+
+/// The microphone: 16 kHz mono in pieces down `tx` for as long as the stream it returns is kept.
+pub fn microphone(tx: Sender<Vec<f32>>) -> anyhow::Result<cpal::Stream> {
+ let dev = cpal::default_host().default_input_device().ok_or_else(|| anyhow!("this computer has no microphone to listen on"))?;
+ let cfg = dev.default_input_config().map_err(|e| anyhow!("the microphone: {e}"))?;
+ let ch = cfg.channels().max(1) as usize;
+ let mut rs = Resample::new(cfg.sample_rate().0, crate::turns::RATE as u32);
+ let mut take = move |mono: Vec<f32>| {
+ let mut out = Vec::with_capacity(mono.len());
+ rs.push(&mono, &mut out);
+ let _ = tx.send(out);
+ };
+ let bad = |e| eprintln!("raea voice: the microphone: {e}");
+ let stream = match cfg.sample_format() {
+ cpal::SampleFormat::F32 => {
+ dev.build_input_stream(&cfg.config(), move |d: &[f32], _: &cpal::InputCallbackInfo| take(mono(d, ch)), bad, None)
+ }
+ cpal::SampleFormat::I16 => dev.build_input_stream(
+ &cfg.config(),
+ move |d: &[i16], _: &cpal::InputCallbackInfo| {
+ let x: Vec<f32> = d.iter().map(|s| *s as f32 / 32768.0).collect();
+ take(mono(&x, ch))
+ },
+ bad,
+ None,
+ ),
+ f => bail!("the microphone gives {f:?} samples, which raea voice doesn't read"),
+ }
+ .map_err(|e| anyhow!("the microphone didn't open (is raea allowed to use it? System Settings > Privacy & Security > Microphone): {e}"))?;
+ stream.play().map_err(|e| anyhow!("the microphone didn't start: {e}"))?;
+ Ok(stream)
+}
+
+/// A WAV in the microphone's place: its sound at the pace it was recorded (at once with `fast`), a second and a half
+/// of quiet after it so its last turn ends, and then the channel closes.
+pub fn microphone_file(path: &Path, fast: bool, tx: Sender<Vec<f32>>) -> anyhow::Result<()> {
+ let (x, rate) = read_wav(path)?;
+ let mut heard = Vec::with_capacity(x.len());
+ Resample::new(rate, crate::turns::RATE as u32).push(&x, &mut heard);
+ heard.extend(std::iter::repeat_n(0.0, crate::turns::RATE * 3 / 2));
+ std::thread::spawn(move || {
+ for piece in heard.chunks(crate::turns::WIN) {
+ if tx.send(piece.to_vec()).is_err() {
+ return;
+ }
+ if !fast {
+ std::thread::sleep(Duration::from_micros(1_000_000 * piece.len() as u64 / crate::turns::RATE as u64));
+ }
+ }
+ });
+ Ok(())
+}
+
+/// What is waiting to be played, shared with whoever makes the sound.
+pub struct Line {
+ pub queue: Mutex<VecDeque<f32>>,
+ /// samples played so far, at the voice's rate
+ pub played: AtomicU64,
+ /// everything played, when it goes to a file
+ kept: Mutex<Vec<f32>>,
+ keep: AtomicBool,
+}
+
+impl Line {
+ /// Drops what hasn't been played yet (the person spoke over it, or it was stopped).
+ pub fn clear(&self) {
+ self.queue.lock().unwrap().clear();
+ }
+
+ /// (samples played so far, samples still waiting to be)
+ pub fn at(&self) -> (u64, usize) {
+ (self.played.load(Ordering::Relaxed), self.queue.lock().unwrap().len())
+ }
+
+ /// The next `n` samples (fewer when the queue runs out), counted as played.
+ fn take(&self, n: usize) -> Vec<f32> {
+ let mut q = self.queue.lock().unwrap();
+ let n = n.min(q.len());
+ let got: Vec<f32> = q.drain(..n).collect();
+ self.played.fetch_add(n as u64, Ordering::Relaxed);
+ if self.keep.load(Ordering::Relaxed) {
+ self.kept.lock().unwrap().extend(&got);
+ }
+ got
+ }
+}
+
+/// A file in the speakers' place: what is waiting is taken at the pace it would play (all of it at once with `fast`).
+fn drain(line: Arc<Line>, each: usize) {
+ std::thread::spawn(move || {
+ while Arc::strong_count(&line) > 1 {
+ std::thread::sleep(Duration::from_millis(20));
+ line.take(each);
+ }
+ });
+}
+
+/// The speakers, or a file in their place.
+pub struct Speaker {
+ pub line: Arc<Line>,
+ rate: u32,
+ to: Option<PathBuf>,
+ _stream: Option<cpal::Stream>,
+}
+
+impl Speaker {
+ /// `rate`: the voice's. With `to`, nothing sounds: what would have played is written there when the session ends.
+ pub fn open(rate: u32, to: Option<PathBuf>, fast: bool) -> anyhow::Result<Speaker> {
+ let line = Arc::new(Line { queue: Mutex::new(VecDeque::new()), played: AtomicU64::new(0), kept: Mutex::new(Vec::new()), keep: AtomicBool::new(to.is_some()) });
+ if to.is_some() {
+ drain(line.clone(), if fast { usize::MAX } else { rate as usize / 50 });
+ return Ok(Speaker { line, rate, to, _stream: None });
+ }
+ let dev = cpal::default_host().default_output_device().ok_or_else(|| anyhow!("this computer has nothing to play sound on"))?;
+ let cfg = dev.default_output_config().map_err(|e| anyhow!("the speakers: {e}"))?;
+ anyhow::ensure!(cfg.sample_format() == cpal::SampleFormat::F32, "the speakers take {:?} samples, which raea voice doesn't write", cfg.sample_format());
+ let ch = cfg.channels().max(1) as usize;
+ let mut rs = Resample::new(rate, cfg.sample_rate().0);
+ let need = rate as f64 / cfg.sample_rate().0 as f64;
+ let l = line.clone();
+ let mut ready: VecDeque<f32> = VecDeque::new();
+ let play = move |out: &mut [f32], _: &cpal::OutputCallbackInfo| {
+ let frames = out.len() / ch;
+ if ready.len() < frames {
+ let mut made = Vec::new();
+ rs.push(&l.take(((frames - ready.len()) as f64 * need).ceil() as usize + 2), &mut made);
+ ready.extend(made);
+ }
+ for f in out.chunks_mut(ch) {
+ f.fill(ready.pop_front().unwrap_or(0.0));
+ }
+ };
+ let stream = dev.build_output_stream(&cfg.config(), play, |e| eprintln!("raea voice: the speakers: {e}"), None).map_err(|e| anyhow!("the speakers didn't open: {e}"))?;
+ stream.play().map_err(|e| anyhow!("the speakers didn't start: {e}"))?;
+ Ok(Speaker { line, rate, to, _stream: Some(stream) })
+ }
+
+ /// Writes the file, when the session's sound went to one.
+ pub fn close(&self) -> anyhow::Result<()> {
+ match &self.to {
+ Some(p) => write_wav(p, &self.line.kept.lock().unwrap(), self.rate),
+ None => Ok(()),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_rate_changes_piece_by_piece_as_it_would_whole() {
+ let x: Vec<f32> = (0..4800).map(|i| (i as f32 * 0.01).sin()).collect();
+ let mut whole = Vec::new();
+ Resample::new(48_000, 16_000).push(&x, &mut whole);
+ let mut pieces = Vec::new();
+ let mut rs = Resample::new(48_000, 16_000);
+ for p in x.chunks(477) {
+ rs.push(p, &mut pieces);
+ }
+ assert!((whole.len() as i64 - 1600).abs() <= 1, "a third as many samples: {}", whole.len());
+ assert_eq!(whole.len(), pieces.len());
+ assert!(whole.iter().zip(&pieces).all(|(a, b)| (a - b).abs() < 1e-5));
+ }
+
+ #[test]
+ fn a_wav_written_reads_back() {
+ let f = std::env::temp_dir().join(format!("raea-voice-{}.wav", std::process::id()));
+ let x: Vec<f32> = (0..2400).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
+ write_wav(&f, &x, 24_000).unwrap();
+ let (y, rate) = read_wav(&f).unwrap();
+ std::fs::remove_file(&f).unwrap();
+ assert_eq!((rate, y.len()), (24_000, x.len()));
+ assert!(x.iter().zip(&y).all(|(a, b)| (a - b).abs() < 1e-3));
+ }
+}
diff --git a/apps/voice/src/lib.rs b/apps/voice/src/lib.rs
new file mode 100644
index 00000000..7fa7f566
--- /dev/null
+++ b/apps/voice/src/lib.rs
@@ -0,0 +1,101 @@
+//! `raea voice`: speech to speech on this computer, for an agent that talks (the app's ideation session). Silero VAD
+//! says when the person starts and stops speaking, Parakeet says what they said, and Pocket TTS says the agent's
+//! words as they arrive, sentence by sentence. Nothing leaves the computer and nothing is paid for; the models are
+//! fetched the first time (about 800 MB) into raea's model folder.
+//!
+//! `raea voice` is a session over lines of JSON (session.rs has them). `raea voice hear FILE.wav` and
+//! `raea voice say "WORDS" -o OUT.wav` are one hearing and one saying, with how long each took.
+
+use std::path::PathBuf;
+use std::time::Instant;
+
+use serde_json::json;
+
+pub mod asr;
+pub mod audio;
+pub mod session;
+pub mod speak;
+pub mod turns;
+
+pub const USAGE: &str = "raea voice [--voice NAME] [--duplex] [--pause MS] [--from IN.wav] [--to OUT.wav] [--fast] | raea voice hear FILE.wav | raea voice say \"WORDS\" -o OUT.wav [--voice NAME]";
+
+/// A model's download told as it goes, once every 20 MB of each file.
+pub fn fetching(emit: fn(serde_json::Value)) -> impl FnMut(&str, u64) {
+ let mut last = (String::new(), 0u64);
+ move |file: &str, bytes: u64| {
+ let mb = bytes / 20_000_000 * 20;
+ if last.0 != file || last.1 != mb {
+ last = (file.to_string(), mb);
+ emit(json!({ "fetch": { "file": file, "mb": mb } }));
+ }
+ }
+}
+
+/// The word after `name` on the command line.
+fn flag(args: &[String], name: &str) -> Option<String> {
+ args.windows(2).find(|w| w[0] == name).map(|w| w[1].clone())
+}
+
+fn quiet(_: serde_json::Value) {}
+
+/// `raea voice hear FILE.wav`: what the file says, with how long loading and hearing took.
+fn hear(file: &str) -> anyhow::Result<String> {
+ let (x, rate) = audio::read_wav(std::path::Path::new(file))?;
+ let mut heard = Vec::with_capacity(x.len());
+ audio::Resample::new(rate, turns::RATE as u32).push(&x, &mut heard);
+ let t = Instant::now();
+ let mut asr = asr::Asr::load(&raea_sys_ml::models::ensure(&asr::SPEC, &mut fetching(quiet))?)?;
+ let load_ms = t.elapsed().as_millis() as u64;
+ let t = Instant::now();
+ let text = asr.hear(&heard)?;
+ Ok(json!({ "text": text, "seconds": heard.len() as f64 / turns::RATE as f64, "load_ms": load_ms, "ms": t.elapsed().as_millis() as u64 }).to_string())
+}
+
+/// `raea voice say "WORDS" -o OUT.wav`: the words said into a file, with how long the first sound and the whole took.
+fn say(text: &str, out: &str, voice: Option<String>) -> anyhow::Result<String> {
+ use raea_sys_speech::pocket::{Out, Pocket};
+ let t = Instant::now();
+ let mut pocket = Pocket::load(&raea_sys_ml::models::ensure(&Pocket::SPEC, &mut fetching(quiet))?)?;
+ let voice = voice.unwrap_or_else(Pocket::default_voice);
+ pocket.begin("", &voice, 1, 0.7)?;
+ let load_ms = t.elapsed().as_millis() as u64;
+ let t = Instant::now();
+ let (mut sound, mut first_ms) = (Vec::new(), None);
+ let mut g = pocket.begin(text, &voice, 7, 0.7)?;
+ while let Some(o) = pocket.step(&mut g)? {
+ if let Out::Audio(a) = o {
+ first_ms.get_or_insert(t.elapsed().as_millis() as u64);
+ sound.extend(a);
+ }
+ }
+ let ms = t.elapsed().as_millis() as u64;
+ audio::write_wav(std::path::Path::new(out), &sound, speak::RATE)?;
+ Ok(json!({ "voice": voice, "seconds": sound.len() as f64 / speak::RATE as f64, "load_ms": load_ms, "first_ms": first_ms, "ms": ms }).to_string())
+}
+
+pub fn cli(args: &[String]) -> Result<String, String> {
+ let said = |e: anyhow::Error| format!("raea voice: {e:#}");
+ match args.get(1).map(String::as_str) {
+ Some("hear") => hear(args.get(2).ok_or(USAGE)?).map_err(said),
+ Some("say") => say(args.get(2).ok_or(USAGE)?, &flag(args, "-o").ok_or(USAGE)?, flag(args, "--voice")).map_err(said),
+ Some(a) if !a.starts_with("--") => Err(USAGE.into()),
+ _ => {
+ let pause_ms = match flag(args, "--pause") {
+ Some(p) => p.parse().map_err(|_| "--pause takes milliseconds".to_string())?,
+ None => 700,
+ };
+ let o = session::Opts {
+ from: flag(args, "--from").map(PathBuf::from),
+ to: flag(args, "--to").map(PathBuf::from),
+ voice: flag(args, "--voice"),
+ duplex: args.iter().any(|a| a == "--duplex"),
+ fast: args.iter().any(|a| a == "--fast"),
+ pause_ms,
+ };
+ session::run(o).map(|_| String::new()).map_err(|e| {
+ session::emit(json!({ "error": format!("{e:#}") }));
+ said(e)
+ })
+ }
+ }
+}
diff --git a/apps/voice/src/main.rs b/apps/voice/src/main.rs
new file mode 100644
index 00000000..12dac417
--- /dev/null
+++ b/apps/voice/src/main.rs
@@ -0,0 +1,12 @@
+//! `raea-voice`: raea voice on its own (what `raea voice` runs), for a build that needs none of the engine.
+fn main() {
+ let args: Vec<String> = std::iter::once("voice".to_string()).chain(std::env::args().skip(1)).collect();
+ match raea_app_voice::cli(&args) {
+ Ok(s) if s.is_empty() => {}
+ Ok(s) => println!("{s}"),
+ Err(e) => {
+ eprintln!("{e}");
+ std::process::exit(1);
+ }
+ }
+}
diff --git a/apps/voice/src/session.rs b/apps/voice/src/session.rs
new file mode 100644
index 00000000..f02e78f0
--- /dev/null
+++ b/apps/voice/src/session.rs
@@ -0,0 +1,237 @@
+//! A voice session: lines of JSON in (what to say), lines of JSON out (what was heard, and how the saying goes).
+//!
+//! in {"say":{"id":"u1","text":"Got it. "}} more of utterance u1's words (send as a model streams them)
+//! {"end":"u1"} u1 has all its words
+//! {"stop":true} stop talking now
+//! {"mute":true|false} stop or start listening
+//! {"quit":true} (or the input closing) say what's left, then end
+//! out {"fetch":{"file","mb"}} a model downloading, the first time
+//! {"ready":{"voice","hears","rate"}} it can hear and speak
+//! {"level":-37.5} the microphone's loudness (dBFS), a few times a second
+//! {"speech":"began"|"ended"} the person started or stopped speaking
+//! {"heard":{"text","seconds","ms"}} what they said, how long they spoke and how long hearing it took
+//! {"saying":{"id","first_ms"}} u1's first sound, and how long after its first words came
+//! {"word":{"id","i","text"}} a word of u1 starting to sound
+//! {"said":{"id"}} u1 was said to its end
+//! {"stopped":{"id"}} u1 was cut off (a stop, or the person spoke over it)
+//! {"error":"..."}
+//!
+//! While raea speaks it doesn't listen, unless `duplex` (headphones): a laptop's microphone hears its own speakers,
+//! and raea would take its own voice for the person interrupting.
+
+use std::io::{BufRead, Write};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::mpsc::{channel, RecvTimeoutError};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use serde_json::{json, Value};
+
+use crate::audio::{microphone, microphone_file, Speaker};
+use crate::speak::{Say, Words, RATE};
+use crate::turns::{Turn, Turns, Vad, WIN};
+
+pub struct Opts {
+ pub from: Option<PathBuf>,
+ pub to: Option<PathBuf>,
+ pub voice: Option<String>,
+ pub duplex: bool,
+ pub fast: bool,
+ pub pause_ms: usize,
+}
+
+pub fn emit(v: Value) {
+ let mut o = std::io::stdout().lock();
+ let _ = writeln!(o, "{v}");
+ let _ = o.flush();
+}
+
+/// What a line of input asks for; None for a line that asks nothing known.
+pub enum Ask {
+ Say(Say),
+ Mute(bool),
+ Quit,
+}
+
+pub fn ask(line: &str) -> Option<Ask> {
+ let v: Value = serde_json::from_str(line).ok()?;
+ if let Some(s) = v.get("say") {
+ return Some(Ask::Say(Say::Text { id: s.get("id")?.as_str()?.to_string(), text: s.get("text")?.as_str()?.to_string() }));
+ }
+ if let Some(id) = v.get("end").and_then(Value::as_str) {
+ return Some(Ask::Say(Say::End(id.to_string())));
+ }
+ if v.get("stop").is_some() {
+ return Some(Ask::Say(Say::Stop));
+ }
+ if let Some(m) = v.get("mute").and_then(Value::as_bool) {
+ return Some(Ask::Mute(m));
+ }
+ v.get("quit").map(|_| Ask::Quit)
+}
+
+/// dBFS of a window, one decimal.
+fn level(win: &[f32]) -> f64 {
+ let rms = (win.iter().map(|s| s * s).sum::<f32>() / win.len().max(1) as f32).sqrt();
+ ((20.0 * rms.max(1e-6).log10()) as f64 * 10.0).round() / 10.0
+}
+
+pub fn run(o: Opts) -> anyhow::Result<()> {
+ let speaker = Speaker::open(RATE, o.to.clone(), o.fast)?;
+ let words = Arc::new(Mutex::new(Words::default()));
+ let talking = Arc::new(AtomicBool::new(false));
+ let muted = Arc::new(AtomicBool::new(false));
+ let closing = Arc::new(AtomicBool::new(false));
+ let hearing = Arc::new(AtomicUsize::new(0));
+
+ // the voice
+ let (say_tx, say_rx) = channel::<Say>();
+ let (voice_ready, voice_is) = channel();
+ let (line, w, t, name) = (speaker.line.clone(), words.clone(), talking.clone(), o.voice.clone());
+ let voice = std::thread::spawn(move || crate::speak::worker(say_rx, line, w, name, t, voice_ready, emit));
+
+ // the ears: each turn's sound heard on its own thread, so the microphone is never kept waiting
+ let (heard_tx, heard_rx) = channel::<Vec<f32>>();
+ let (ears_ready, ears_are) = channel();
+ let pending = hearing.clone();
+ std::thread::spawn(move || {
+ let loaded = raea_sys_ml::models::ensure(&crate::asr::SPEC, &mut crate::fetching(emit)).and_then(|d| crate::asr::Asr::load(&d));
+ let mut asr = match loaded {
+ Ok(a) => {
+ let _ = ears_ready.send(Ok(()));
+ a
+ }
+ Err(e) => {
+ let _ = ears_ready.send(Err(e));
+ return;
+ }
+ };
+ for said in heard_rx {
+ let t = Instant::now();
+ match asr.hear(&said) {
+ Ok(text) => emit(json!({ "heard": { "text": text, "seconds": (said.len() as f64 / crate::turns::RATE as f64 * 100.0).round() / 100.0, "ms": t.elapsed().as_millis() as u64 } })),
+ Err(e) => emit(json!({ "error": format!("{e:#}") })),
+ }
+ pending.fetch_sub(1, Ordering::Relaxed);
+ }
+ });
+ let mut vad = Vad::load(&crate::turns::model(&mut crate::fetching(emit))?)?;
+ let name = voice_is.recv().map_err(|_| anyhow::anyhow!("the voice stopped before it could speak"))??;
+ ears_are.recv().map_err(|_| anyhow::anyhow!("the ears stopped before they could hear"))??;
+
+ // what's asked, line by line
+ let (tx, m, c) = (say_tx.clone(), muted.clone(), closing.clone());
+ std::thread::spawn(move || {
+ for line in std::io::stdin().lock().lines() {
+ let Ok(line) = line else { break };
+ match ask(&line) {
+ Some(Ask::Say(s)) => drop(tx.send(s)),
+ Some(Ask::Mute(on)) => m.store(on, Ordering::Relaxed),
+ Some(Ask::Quit) => break,
+ None if line.trim().is_empty() => {}
+ None => emit(json!({ "error": format!("not a line raea voice knows: {}", line.chars().take(120).collect::<String>()) })),
+ }
+ }
+ let _ = tx.send(Say::Close);
+ c.store(true, Ordering::Relaxed);
+ });
+
+ let (mic_tx, mic_rx) = channel::<Vec<f32>>();
+ let _mic = match &o.from {
+ Some(f) => {
+ microphone_file(f, o.fast, mic_tx)?;
+ None
+ }
+ None => Some(microphone(mic_tx)?),
+ };
+ emit(json!({ "ready": { "voice": name, "hears": "parakeet-tdt-0.6b-v3", "rate": RATE } }));
+
+ let mut turns = Turns::new(o.pause_ms);
+ let (mut buf, mut windows, mut mic_done) = (Vec::<f32>::new(), 0usize, false);
+ let mut quiet_since = Instant::now();
+ loop {
+ match mic_rx.recv_timeout(Duration::from_millis(30)) {
+ Ok(piece) => buf.extend(piece),
+ Err(RecvTimeoutError::Timeout) => {}
+ Err(RecvTimeoutError::Disconnected) => mic_done = true,
+ }
+ while buf.len() >= WIN {
+ let win: Vec<f32> = buf.drain(..WIN).collect();
+ windows += 1;
+ let speaking = talking.load(Ordering::Relaxed);
+ if speaking {
+ quiet_since = Instant::now();
+ }
+ // its own voice dies away in the room for a moment after the last sample
+ let own = speaking || quiet_since.elapsed() < Duration::from_millis(250);
+ if muted.load(Ordering::Relaxed) || (own && !o.duplex) {
+ if turns.speaking() {
+ emit(json!({ "speech": "ended" }));
+ }
+ // muted, their words are dropped; talked over by raea, what they had said so far is still heard
+ if muted.load(Ordering::Relaxed) {
+ turns.clear();
+ } else if let Some(said) = turns.cut() {
+ hearing.fetch_add(1, Ordering::Relaxed);
+ let _ = heard_tx.send(said);
+ }
+ vad.reset();
+ continue;
+ }
+ if windows % 4 == 0 {
+ emit(json!({ "level": level(&win) }));
+ }
+ match turns.push(&win, vad.speech(&win)?) {
+ Some(Turn::Began) => {
+ emit(json!({ "speech": "began" }));
+ if speaking {
+ let _ = say_tx.send(Say::Stop);
+ }
+ }
+ Some(Turn::Ended(said)) => {
+ emit(json!({ "speech": "ended" }));
+ hearing.fetch_add(1, Ordering::Relaxed);
+ let _ = heard_tx.send(said);
+ }
+ None => {}
+ }
+ }
+ // the words whose sound has started
+ {
+ let mut w = words.lock().unwrap();
+ let played = speaker.line.at().0;
+ while w.told < w.starts.len() && w.told < w.words.len() && played >= w.start_at + (w.starts[w.told] * RATE as f64) as u64 {
+ emit(json!({ "word": { "id": w.id, "i": w.told, "text": w.words[w.told] } }));
+ w.told += 1;
+ }
+ }
+ let idle = voice.is_finished() && hearing.load(Ordering::Relaxed) == 0;
+ if closing.load(Ordering::Relaxed) && idle && (o.from.is_none() || mic_done) {
+ break;
+ }
+ }
+ speaker.close()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_lines_a_session_takes() {
+ assert!(matches!(ask(r#"{"say":{"id":"u1","text":"Hello. "}}"#), Some(Ask::Say(Say::Text { id, text })) if id == "u1" && text == "Hello. "));
+ assert!(matches!(ask(r#"{"end":"u1"}"#), Some(Ask::Say(Say::End(id))) if id == "u1"));
+ assert!(matches!(ask(r#"{"stop":true}"#), Some(Ask::Say(Say::Stop))));
+ assert!(matches!(ask(r#"{"mute":true}"#), Some(Ask::Mute(true))));
+ assert!(matches!(ask(r#"{"quit":true}"#), Some(Ask::Quit)));
+ assert!(ask(r#"{"sing":"la"}"#).is_none() && ask("not json").is_none());
+ }
+
+ #[test]
+ fn quiet_and_loud_in_dbfs() {
+ assert_eq!(level(&[0.0; 512]), -120.0);
+ assert_eq!(level(&[1.0; 512]), 0.0);
+ assert_eq!(level(&[0.1; 512]), -20.0);
+ }
+}
diff --git a/apps/voice/src/speak.rs b/apps/voice/src/speak.rs
new file mode 100644
index 00000000..19932054
--- /dev/null
+++ b/apps/voice/src/speak.rs
@@ -0,0 +1,248 @@
+//! The voice: what the agent says, said by Pocket TTS as its words arrive. Text comes in pieces (a model's stream);
+//! each whole sentence is said as soon as it's there, so the first sound doesn't wait for the last word. The word
+//! clock says when each word starts, for a caption that follows the voice.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::mpsc::{Receiver, TryRecvError};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use raea_sys_speech::pocket::{Out, Pocket};
+use raea_sys_speech::words::Clock;
+use serde_json::json;
+
+use crate::audio::Line;
+
+/// Pocket's rate.
+pub const RATE: u32 = 24_000;
+const TEMPERATURE: f32 = 0.7;
+
+pub enum Say {
+ /// more of what `id` says
+ Text { id: String, text: String },
+ /// `id` has all its words
+ End(String),
+ /// stop talking now
+ Stop,
+ /// say what's left, then finish
+ Close,
+}
+
+/// The words being said and when each starts, for whoever follows the playback.
+#[derive(Default)]
+pub struct Words {
+ pub id: String,
+ pub words: Vec<String>,
+ /// seconds into the utterance, for the words whose start is decided
+ pub starts: Vec<f64>,
+ /// how many have been told
+ pub told: usize,
+ /// the playback position (samples played) its first sample has
+ pub start_at: u64,
+}
+
+/// The sentences `buf` holds whole, taken out of it: up to its last full stop, question or exclamation mark that a
+/// space or a line end follows. With `all`, everything.
+pub fn whole(buf: &mut String, all: bool) -> Option<String> {
+ let cut = if all {
+ buf.len()
+ } else {
+ let b = buf.as_bytes();
+ let ends = |i: usize| matches!(b[i], b'.' | b'!' | b'?') && b.get(i + 1).is_some_and(|c| c.is_ascii_whitespace());
+ (0..b.len()).rev().find(|i| ends(*i) || b[*i] == b'\n').map(|i| i + 1)?
+ };
+ let said: String = buf.drain(..cut).collect();
+ (!said.trim().is_empty()).then(|| said.trim().to_string())
+}
+
+struct Utter {
+ id: String,
+ buf: String,
+ ended: bool,
+ line: Vec<f32>,
+ clock: Clock,
+ asked: Instant,
+ sounded: bool,
+}
+
+struct Voice {
+ pocket: Pocket,
+ name: String,
+ out: Arc<Line>,
+ words: Arc<Mutex<Words>>,
+ emit: fn(serde_json::Value),
+ now: Option<Utter>,
+ closing: bool,
+ seed: u64,
+}
+
+impl Voice {
+ fn take(&mut self, m: Say) {
+ match m {
+ Say::Text { id, text } => {
+ if self.now.as_ref().is_none_or(|u| u.id != id) {
+ *self.words.lock().unwrap() = Words { id: id.clone(), ..Words::default() };
+ self.now = Some(Utter { id, buf: String::new(), ended: false, line: Vec::new(), clock: Clock::new(RATE), asked: Instant::now(), sounded: false });
+ }
+ self.now.as_mut().unwrap().buf.push_str(&text);
+ }
+ Say::End(id) => {
+ if let Some(u) = self.now.as_mut().filter(|u| u.id == id) {
+ u.ended = true;
+ }
+ }
+ Say::Stop => {
+ self.out.clear();
+ if let Some(u) = self.now.take() {
+ self.words.lock().unwrap().id.clear();
+ (self.emit)(json!({ "stopped": { "id": u.id } }));
+ }
+ }
+ Say::Close => {
+ self.closing = true;
+ if let Some(u) = self.now.as_mut() {
+ u.ended = true;
+ }
+ }
+ }
+ }
+
+ /// Everything waiting on the channel; false once the other end is gone.
+ fn drain(&mut self, rx: &Receiver<Say>) -> bool {
+ loop {
+ match rx.try_recv() {
+ Ok(m) => self.take(m),
+ Err(TryRecvError::Empty) => return true,
+ Err(TryRecvError::Disconnected) => {
+ self.take(Say::Close);
+ return false;
+ }
+ }
+ }
+ }
+
+ /// Says `text` for the utterance `id`; stops early when that utterance is stopped or replaced.
+ fn say(&mut self, id: &str, text: &str, rx: &Receiver<Say>) -> anyhow::Result<()> {
+ self.seed = self.seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ let mut g = self.pocket.begin(text, &self.name, self.seed, TEMPERATURE)?;
+ while let Some(out) = self.pocket.step(&mut g)? {
+ let Some(u) = self.now.as_mut().filter(|u| u.id == id) else { return Ok(()) };
+ match out {
+ Out::Begin(sentence) => u.clock.begin_sentence(&sentence, u.line.len()),
+ Out::End => u.clock.end_sentence(u.line.len()),
+ Out::Audio(a) => {
+ if !u.sounded {
+ u.sounded = true;
+ let (played, waiting) = self.out.at();
+ self.words.lock().unwrap().start_at = played + waiting as u64;
+ (self.emit)(json!({ "saying": { "id": id, "first_ms": u.asked.elapsed().as_millis() as u64 } }));
+ }
+ self.out.queue.lock().unwrap().extend(&a);
+ u.line.extend_from_slice(&a);
+ u.clock.advance(&u.line, false);
+ self.publish();
+ }
+ }
+ self.drain(rx);
+ }
+ Ok(())
+ }
+
+ fn publish(&mut self) {
+ let Some(u) = &self.now else { return };
+ let mut w = self.words.lock().unwrap();
+ if w.id == u.id && (w.words.len() != u.clock.words.len() || w.starts.len() != u.clock.starts.len()) {
+ w.words.clone_from(&u.clock.words);
+ w.starts.clone_from(&u.clock.starts);
+ }
+ }
+}
+
+/// The voice's thread: loads Pocket, says `ready` once it can speak, then says what comes down `rx` until it closes.
+/// `busy` is up while an utterance is being made or played.
+pub fn worker(rx: Receiver<Say>, out: Arc<Line>, words: Arc<Mutex<Words>>, name: Option<String>, busy: Arc<AtomicBool>, ready: std::sync::mpsc::Sender<anyhow::Result<String>>, emit: fn(serde_json::Value)) {
+ let loaded = (|| {
+ let dir = raea_sys_ml::models::ensure(&Pocket::SPEC, &mut crate::fetching(emit))?;
+ let mut pocket = Pocket::load(&dir)?;
+ anyhow::ensure!(pocket.sample_rate() == RATE, "Pocket TTS speaks at {} Hz, not {RATE}", pocket.sample_rate());
+ let name = name.unwrap_or_else(Pocket::default_voice);
+ // the voice's state loaded now, not under the first words
+ pocket.begin("", &name, 1, TEMPERATURE)?;
+ Ok((pocket, name))
+ })();
+ let (pocket, name) = match loaded {
+ Ok(p) => p,
+ Err(e) => {
+ let _ = ready.send(Err(e));
+ return;
+ }
+ };
+ let _ = ready.send(Ok(name.clone()));
+ let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(7) | 1;
+ let mut v = Voice { pocket, name, out, words, emit, now: None, closing: false, seed };
+ loop {
+ busy.store(v.now.is_some() || v.out.at().1 > 0, Ordering::Relaxed);
+ let Some(u) = v.now.as_mut() else {
+ if v.closing {
+ return;
+ }
+ match rx.recv() {
+ Ok(m) => v.take(m),
+ Err(_) => return,
+ }
+ continue;
+ };
+ let ended = u.ended;
+ if let Some(text) = whole(&mut u.buf, ended) {
+ let id = u.id.clone();
+ if let Err(e) = v.say(&id, &text, &rx) {
+ emit(json!({ "error": format!("Pocket TTS: {e:#}") }));
+ v.take(Say::Stop);
+ }
+ continue;
+ }
+ if ended {
+ // every word made: the clock decides the last starts, and the utterance is said once it has all played
+ u.clock.advance(&u.line, true);
+ let id = u.id.clone();
+ v.publish();
+ while v.out.at().1 > 0 && v.now.as_ref().is_some_and(|u| u.id == id) {
+ std::thread::sleep(Duration::from_millis(15));
+ v.drain(&rx);
+ }
+ if v.now.as_ref().is_some_and(|u| u.id == id) {
+ v.now = None;
+ emit(json!({ "said": { "id": id } }));
+ }
+ continue;
+ }
+ // waiting for the rest of a sentence
+ match rx.recv_timeout(Duration::from_millis(50)) {
+ Ok(m) => v.take(m),
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
+ Err(_) => v.take(Say::Close),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn whole_sentences_are_said_as_they_arrive() {
+ let mut buf = String::from("Got it. A launch film for the Ridge 2");
+ assert_eq!(whole(&mut buf, false).as_deref(), Some("Got it."));
+ assert_eq!(whole(&mut buf, false), None, "half a sentence waits for its end");
+ buf.push_str(", gritty. Who is it for");
+ assert_eq!(whole(&mut buf, false).as_deref(), Some("A launch film for the Ridge 2, gritty."));
+ assert_eq!(whole(&mut buf, true).as_deref(), Some("Who is it for"), "with everything in, what's left is said");
+ assert_eq!(whole(&mut buf, true), None);
+ }
+
+ #[test]
+ fn a_number_with_a_point_is_not_a_sentence_end() {
+ let mut buf = String::from("It costs 2.5 times more");
+ assert_eq!(whole(&mut buf, false), None);
+ }
+}
diff --git a/apps/voice/src/turns.rs b/apps/voice/src/turns.rs
new file mode 100644
index 00000000..9cdf3b59
--- /dev/null
+++ b/apps/voice/src/turns.rs
@@ -0,0 +1,189 @@
+//! Whose turn it is: Silero VAD v5 (MIT) window by window as the microphone comes in, and from it when the person
+//! starts speaking and when they've stopped (a pause long enough to be the end of what they were saying).
+
+use std::path::PathBuf;
+
+use anyhow::anyhow;
+use ort::session::Session;
+use ort::value::Tensor;
+
+pub const RATE: usize = 16_000;
+/// Silero's window: 32 ms.
+pub const WIN: usize = 512;
+const CTX: usize = 64;
+/// The silero-vad 5.1.2 package's model.
+const URL: &str = "https://github.com/snakers4/silero-vad/raw/v5.1.2/src/silero_vad/data/silero_vad.onnx";
+
+pub fn model(progress: &mut dyn FnMut(&str, u64)) -> anyhow::Result<PathBuf> {
+ raea_sys_ml::models::ensure_url("silero-vad", "silero_vad.onnx", URL, progress)
+}
+
+pub struct Vad {
+ session: Session,
+ state: Vec<f32>,
+ ctx: Vec<f32>,
+}
+
+impl Vad {
+ pub fn load(file: &std::path::Path) -> anyhow::Result<Vad> {
+ Ok(Vad { session: raea_sys_ml::session(file)?, state: vec![0.0; 2 * 128], ctx: vec![0.0; CTX] })
+ }
+
+ /// How likely this window (WIN samples at 16 kHz) is speech; the state carries on from the last one.
+ pub fn speech(&mut self, win: &[f32]) -> anyhow::Result<f32> {
+ let e = |e: ort::Error| anyhow!("silero vad: {e}");
+ let mut input = self.ctx.clone();
+ input.extend_from_slice(win);
+ self.ctx.copy_from_slice(&input[input.len() - CTX..]);
+ let o = self
+ .session
+ .run(ort::inputs![
+ "input" => Tensor::from_array(([1usize, CTX + WIN], input)).map_err(e)?,
+ "state" => Tensor::from_array(([2usize, 1, 128], self.state.clone())).map_err(e)?,
+ "sr" => Tensor::from_array(((), vec![RATE as i64])).map_err(e)?,
+ ])
+ .map_err(e)?;
+ let p = o["output"].try_extract_tensor::<f32>().map_err(e)?.1[0];
+ self.state.copy_from_slice(&o["stateN"].try_extract_tensor::<f32>().map_err(e)?.1[..256]);
+ Ok(p)
+ }
+
+ pub fn reset(&mut self) {
+ self.state.fill(0.0);
+ self.ctx.fill(0.0);
+ }
+}
+
+/// What a window of sound changed.
+#[derive(Debug, PartialEq)]
+pub enum Turn {
+ /// the person started speaking
+ Began,
+ /// they stopped: everything they said, with a little quiet on either side
+ Ended(Vec<f32>),
+}
+
+/// The turn-taking over window probabilities: speech begins after `ON` windows in a row at 0.5 or more, and ends
+/// after `quiet` windows in a row under 0.35 (Silero's own two thresholds).
+pub struct Turns {
+ /// windows of quiet that end a turn
+ pub quiet: usize,
+ speaking: bool,
+ run: usize,
+ silent: usize,
+ /// the sound kept: the last PRE windows while nobody speaks, the whole turn while someone does
+ kept: Vec<f32>,
+}
+
+/// Windows of speech in a row that begin a turn (96 ms: a click or a cough is shorter).
+const ON: usize = 3;
+/// Windows kept from before a turn began (its first sound comes before Silero is sure).
+const PRE: usize = 10;
+/// A turn is cut off here (a minute), so one never grows without end under steady noise.
+const LONGEST: usize = RATE * 60;
+
+impl Turns {
+ /// `pause_ms`: how long a pause ends the turn.
+ pub fn new(pause_ms: usize) -> Turns {
+ Turns { quiet: (pause_ms * RATE / 1000 / WIN).max(1), speaking: false, run: 0, silent: 0, kept: Vec::new() }
+ }
+
+ pub fn speaking(&self) -> bool {
+ self.speaking
+ }
+
+ /// Forgets a turn under way (the microphone was muted, or raea itself was talking).
+ pub fn clear(&mut self) {
+ (self.speaking, self.run, self.silent) = (false, 0, 0);
+ self.kept.clear();
+ }
+
+ /// The turn under way, as far as it got, when raea itself starts talking over it: half a second or more of it is
+ /// still the person's words (they began before the agent's greeting reached them), anything shorter is forgotten.
+ pub fn cut(&mut self) -> Option<Vec<f32>> {
+ let said = (self.speaking && self.kept.len() >= RATE / 2).then(|| std::mem::take(&mut self.kept));
+ self.clear();
+ said
+ }
+
+ /// One more window and how likely it is speech.
+ pub fn push(&mut self, win: &[f32], p: f32) -> Option<Turn> {
+ self.kept.extend_from_slice(win);
+ if !self.speaking {
+ self.run = if p >= 0.5 { self.run + 1 } else { 0 };
+ if self.run >= ON {
+ (self.speaking, self.silent) = (true, 0);
+ return Some(Turn::Began);
+ }
+ let keep = (PRE + self.run) * WIN;
+ if self.kept.len() > keep {
+ self.kept.drain(..self.kept.len() - keep);
+ }
+ return None;
+ }
+ self.silent = if p < 0.35 { self.silent + 1 } else { 0 };
+ if self.silent < self.quiet && self.kept.len() < LONGEST {
+ return None;
+ }
+ // the closing quiet but for a few windows goes: it's the pause, not the turn
+ let cut = self.silent.saturating_sub(4) * WIN;
+ let mut said = std::mem::take(&mut self.kept);
+ said.truncate(said.len() - cut.min(said.len()));
+ self.clear();
+ Some(Turn::Ended(said))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_turn_cut_short_keeps_what_was_said() {
+ let mut t = Turns::new(700);
+ assert!(t.cut().is_none());
+ for _ in 0..40 {
+ t.push(&[0.1; WIN], 0.9);
+ }
+ assert!(t.speaking());
+ assert!(t.cut().is_some_and(|said| said.len() >= RATE / 2));
+ assert!(!t.speaking() && t.cut().is_none());
+ // a moment of it isn't a turn
+ for _ in 0..ON + 1 {
+ t.push(&[0.1; WIN], 0.9);
+ }
+ assert!(t.speaking() && t.cut().is_none());
+ }
+
+ fn feed(t: &mut Turns, probs: &[(f32, usize)]) -> Vec<Turn> {
+ let mut out = Vec::new();
+ for (p, n) in probs {
+ for _ in 0..*n {
+ out.extend(t.push(&[0.1; WIN], *p));
+ }
+ }
+ out
+ }
+
+ #[test]
+ fn a_turn_begins_on_steady_speech_and_ends_on_a_long_pause() {
+ let mut t = Turns::new(640);
+ // a click (one window), then half a second of speech, a short pause mid-sentence, more speech, then quiet
+ let got = feed(&mut t, &[(0.1, 20), (0.9, 1), (0.1, 5), (0.9, 16), (0.1, 8), (0.9, 16), (0.1, 30)]);
+ assert_eq!(got.len(), 2, "one turn: the click begins nothing, the short pause ends nothing: {got:?}");
+ assert_eq!(got[0], Turn::Began);
+ let Turn::Ended(said) = &got[1] else { panic!("{got:?}") };
+ // what was said: the quiet kept from before, both runs of speech and the pause between, a little closing quiet
+ let windows = said.len() / WIN;
+ assert!((16 + 8 + 16 + 4..=16 + 8 + 16 + 4 + PRE + ON).contains(&windows), "{windows} windows");
+ assert!(!t.speaking());
+ }
+
+ #[test]
+ fn clearing_forgets_a_turn_under_way() {
+ let mut t = Turns::new(640);
+ assert_eq!(feed(&mut t, &[(0.9, 10)]), vec![Turn::Began]);
+ t.clear();
+ assert!(feed(&mut t, &[(0.1, 40)]).is_empty(), "nothing ends: nothing was under way");
+ }
+}
diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.toml
index 6025afd3..34183ae4 100644
--- a/engine/cli/Cargo.toml
+++ b/engine/cli/Cargo.toml
@@ -76,6 +76,7 @@ raea-app-solid = { path = "../../apps/solid" }
raea-app-judge = { path = "../../apps/judge" }
# raea scene lint|explain|light|stage (docs/stage-guards.feature)
raea-app-scene = { path = "../../apps/scene" }
+raea-app-voice = { path = "../../apps/voice" }
raea-app-ask = { path = "../../apps/ask" }
# raea bake light (docs/bake.feature)
raea-app-lightbake = { path = "../../apps/lightbake" }
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index afa929ed..843f977a 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -266,8 +266,8 @@ pub fn run(args: &[String]) -> R<String> {
Some("bake") => return raea_app_lightbake::cli(args), // `bake light`: bounce light baked on raea's ray tracer, held to Cycles (apps/lightbake)
// `wear bake REQUEST.json [-o OUT.json]`: raea/wear's cause maps of a .glb (raea-runtime-wear, registered in thread.rs)
Some("wear") => return raea_runtime_wear::cli(args, motion::media_path),
- // `scene lint|explain EDIT.tsx`: what each 3D part rests on; floating, sunk and clipping parts (raea-sys-contact, through motion/contact.rs)
- Some("scene") => return raea_app_scene::cli(args),
+ Some("scene") => return raea_app_scene::cli(args), // `scene lint|explain EDIT.tsx`: what each 3D part rests on; floating, sunk and clipping parts (raea-sys-contact, through motion/contact.rs)
+ Some("voice") => return raea_app_voice::cli(args), // `voice [hear FILE.wav | say "WORDS" -o OUT.wav]`: speech in and out on this computer, as JSON lines for raea.app's Ideate (apps/voice)
// `song FILE [-o OUT.song.json] [--plot OUT.png]`: the song's energy map for pacing (apps/tools/src/song.rs)
Some("song") => return tools::song::song(args),
// `track CLIP.mp4 [--subject X,Y,W,H] [--from S]`: the clip's camera solved for <Matchmove> (motion/track.rs)
diff --git a/tools/layers.toml b/tools/layers.toml
index 22f61f95..c3bd8e77 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -214,6 +214,7 @@ raea-app-interchange = "apps"
raea-app-judge = "apps"
raea-app-make = "apps"
raea-app-scene = "apps" # raea scene lint|explain|light|stage
+raea-app-voice = "apps" # raea voice: speech to speech on this computer, as lines of JSON
raea-app-ask = "apps"
raea-app-lightbake = "apps" # raea bake light (docs/bake.feature)
raea-sys-lightbake = "systems" # light baked over raea/wear's atlas on raea's ray tracer (docs/bake.feature)