fix(voice_worker): a hinted wake word may replace a near miss the plain decode wrote

Live 2026-11-19 "비서야" was decoded as "기사야" (two of six letters off, more than call
detection allows) while the hinted decode of the same audio gave "비서야"; the hint was
dropped because it changed the wake word count. The hint may now add one wake word where
the plain text is within a third of that word's letters (NFKD letters, Hangul by jamo).
On the user's 100 recordings: 5 fixed, 0 wrong; 0 of 216 noise decodes gained a wake word.

The live round trip test gets a going-on case: the person's own recordings of one thing
said in pieces, played into Discord with their real pauses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-19 21:55:10 +09:00
parent 41f539dd48
commit e716065538
5 changed files with 197 additions and 33 deletions

View File

@@ -17,6 +17,7 @@
//! cargo test --release --test live_round_trip -- --nocapture
//!
//! On Linux, put the pip CUDA libraries on LD_LIBRARY_PATH (nvidia/cublas/lib, nvidia/cudnn/lib).
//! JARVIS_LIVE_WORKER_ARGS adds worker arguments (e.g. "--stt-device cpu --stt-compute int8").
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -165,16 +166,23 @@ fn background_voices(url: String, token: String, samples: Vec<Vec<i16>>, stop: A
})
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn conversation_round_trip_on_real_discord() {
if std::env::var("JARVIS_LIVE_ROUND_TRIP").as_deref() != Ok("1") {
eprintln!("skipped: set JARVIS_LIVE_ROUND_TRIP=1");
return;
}
/// Both bots in the voice channel: the speaker bot (the "person") and Jarvis running the app's services
/// from a fresh data folder, with `call` as the settings' call section.
struct Live {
speaker_id: u64,
speaker_songbird: Arc<Songbird>,
s_shards: Arc<serenity::gateway::ShardManager>,
services: jarvis_app::services::Services,
core: jarvis_app::discord::DiscordCore,
events: Arc<Mutex<Vec<(Instant, CoreEvent)>>>,
call: Arc<tokio::sync::Mutex<songbird::Call>>,
ears: Ears,
guild: u64,
}
async fn start_live(call_settings: impl FnOnce(u64) -> Value) -> Live {
let guild: u64 = env("JARVIS_LIVE_GUILD").parse().unwrap();
let voice: u64 = env("JARVIS_LIVE_VOICE_CHANNEL").parse().unwrap();
let rounds: usize = std::env::var("JARVIS_LIVE_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(2);
let questions = PathBuf::from(env("JARVIS_LIVE_QUESTIONS"));
env("JARVIS_LIVE_LLM_URL"); // the services point the brain at it (llm.url)
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
@@ -208,21 +216,26 @@ async fn conversation_round_trip_on_real_discord() {
if let Ok(m) = std::env::var("JARVIS_MELO_PYTHON") {
args.extend(["--melo-python".to_string(), m]);
}
// e.g. "--stt-device cpu --stt-compute int8 --melo-device cpu" on a host without a GPU
if let Ok(extra) = std::env::var("JARVIS_LIVE_WORKER_ARGS") {
args.extend(extra.split_whitespace().map(String::from));
}
std::fs::write(data.join("config").join("settings.json"), serde_json::to_string_pretty(&json!({
"discord": {"guildId": guild.to_string(), "voiceChannelId": voice.to_string()},
// The "person" here is a bot, so bots must be heard; the recorded questions call "자비스".
"voice": {"listenToBots": true, "wakeWords": ["자비스"]},
"call": call_settings(speaker_id),
"voiceWorker": {"python": env("JARVIS_VOICE_PYTHON"), "cwd": root.join("../src"), "args": args},
"llm": {"url": env("JARVIS_LIVE_LLM_URL")},
})).unwrap()).unwrap();
std::env::set_var("JARVIS_DISCORD_TOKEN", &bot_token);
let services = tokio::time::timeout(Duration::from_secs(300), start_services(&data, Arc::new(Llm::new(&data)))).await
let mut services = tokio::time::timeout(Duration::from_secs(300), start_services(&data, Arc::new(Llm::new(&data)))).await
.expect("services start in time").expect("services start");
services.worker.wait_ready(Duration::from_secs(240)).await.expect("worker ready");
let core = services.core.clone();
let events: Arc<Mutex<Vec<(Instant, CoreEvent)>>> = Arc::default();
let ev2 = events.clone();
let mut rx = services.events;
let mut rx = std::mem::replace(&mut services.events, mpsc::unbounded_channel().1);
tokio::spawn(async move {
while let Some(e) = rx.recv().await {
ev2.lock().unwrap().push((Instant::now(), e));
@@ -240,6 +253,31 @@ async fn conversation_round_trip_on_real_discord() {
}
tokio::time::sleep(Duration::from_secs(2)).await; // the DAVE group settles after the join
Live { speaker_id, speaker_songbird, s_shards, services, core, events, call, ears, guild }
}
impl Live {
async fn stop(self) {
let _ = self.speaker_songbird.remove(GuildId::new(self.guild)).await;
self.s_shards.shutdown_all().await;
self.services.core.leave("test").await;
self.services.core.close().await;
self.services.worker.close();
self.services.worker_process.stop().await;
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn conversation_round_trip_on_real_discord() {
if std::env::var("JARVIS_LIVE_ROUND_TRIP").as_deref() != Ok("1") {
eprintln!("skipped: set JARVIS_LIVE_ROUND_TRIP=1");
return;
}
let live = start_live(|_| json!({})).await;
let rounds: usize = std::env::var("JARVIS_LIVE_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(2);
let questions = PathBuf::from(env("JARVIS_LIVE_QUESTIONS"));
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let Live { speaker_id, ref services, ref core, ref events, ref call, ref ears, .. } = live;
let refs: Value = serde_json::from_str(&std::fs::read_to_string(questions.join("refs.json")).unwrap()).unwrap();
let qs: Vec<(String, Vec<u8>)> = refs["samples"].as_array().unwrap().iter()
.map(|r| (r["text"].as_str().unwrap().to_owned(), std::fs::read(questions.join(r["file"].as_str().unwrap())).unwrap()))
@@ -355,12 +393,7 @@ async fn conversation_round_trip_on_real_discord() {
println!("live round trip {}", serde_json::to_string_pretty(&Value::Object(report.clone())).unwrap());
})).await;
let _ = speaker_songbird.remove(GuildId::new(guild)).await;
s_shards.shutdown_all().await;
services.core.leave("test").await;
services.core.close().await;
services.worker.close();
services.worker_process.stop().await;
live.stop().await;
if let Err(panic) = steps {
std::panic::resume_unwind(panic);
}
@@ -371,3 +404,76 @@ async fn conversation_round_trip_on_real_discord() {
}
}
/// Going on (conversation.spec.md), live: the person's own recordings of one thing said in pieces,
/// played with the pauses they really made, get one answer. Settings as the person's own app: they
/// are the only designated person, `addressed` mode, alone with Jarvis.
///
/// JARVIS_LIVE_GOING_ON=1 (the env of conversation_round_trip_on_real_discord, without the questions)
/// JARVIS_LIVE_PIECES=<dir with pieces.json: [{"name", "file"}], each file one 16 kHz mono wav of
/// the pieces and the silence between them> cargo test --release --test live_round_trip going_on -- --nocapture
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn going_on_on_real_discord() {
if std::env::var("JARVIS_LIVE_GOING_ON").as_deref() != Ok("1") {
eprintln!("skipped: set JARVIS_LIVE_GOING_ON=1");
return;
}
let dir = PathBuf::from(env("JARVIS_LIVE_PIECES"));
let seqs: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("pieces.json")).unwrap()).unwrap();
let live = start_live(|speaker| json!({"designated": [speaker.to_string()], "designatedOnly": true, "mode": "addressed"})).await;
let mut rows = vec![];
let steps = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
for s in seqs.as_array().unwrap() {
let wav = std::fs::read(dir.join(s["file"].as_str().unwrap())).unwrap();
until("Jarvis to finish speaking", 60_000, || !live.core.speaking()).await;
let before = live.events.lock().unwrap().len();
live.call.lock().await.play_only_input(Input::from(wav.clone()));
tokio::time::sleep(Duration::from_secs_f64(speech_end_seconds(&wav))).await;
// Done when nothing is playing and nothing new came for 10 s (at most 60 s).
let deadline = Instant::now() + Duration::from_secs(60);
let (mut seen, mut quiet_since) = (0, Instant::now());
while Instant::now() < deadline {
let n = live.events.lock().unwrap().len();
if n != seen || live.core.speaking() {
(seen, quiet_since) = (n, Instant::now());
} else if quiet_since.elapsed() > Duration::from_secs(10) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
let ev = live.events.lock().unwrap()[before..].to_vec();
let heard: Vec<String> = ev.iter().filter_map(|(_, e)| match e {
CoreEvent::Final(f) if f.heard.speaker_id == live.speaker_id => Some(f.text.clone()),
_ => None,
}).collect();
let answers: Vec<Value> = ev.iter().filter_map(|(_, e)| match e {
CoreEvent::ReplyText { id, text, failed } => {
let end = ev.iter().find_map(|(_, e)| match e {
CoreEvent::SpeakEnd(x) if &x.id == id => Some(x.clone()),
_ => None,
});
Some(json!({"text": text, "failed": failed, "played": end.as_ref().map(|x| x.played),
"cancelled": end.as_ref().map(|x| x.cancelled)}))
}
_ => None,
}).collect();
let asked = ev.iter().filter(|(_, e)| matches!(e, CoreEvent::AnswerAsked { .. })).count();
rows.push(json!({"name": s["name"], "heard": heard, "asked": asked, "answers": answers}));
println!("going on {}", rows.last().unwrap());
tokio::time::sleep(Duration::from_millis(1500)).await;
}
})).await;
live.stop().await;
if let Err(panic) = steps {
std::panic::resume_unwind(panic);
}
// One thing said in pieces: one answer heard to its end, and no other answer heard.
for r in &rows {
let heard = |a: &&Value| a["played"].as_u64().is_some_and(|p| p > 0);
let whole: Vec<&Value> = r["answers"].as_array().unwrap().iter().filter(heard)
.filter(|a| a["cancelled"] == json!(false)).collect();
let cut: Vec<&Value> = r["answers"].as_array().unwrap().iter().filter(heard)
.filter(|a| a["cancelled"] == json!(true)).collect();
assert!(whole.len() == 1 && cut.is_empty(), "{}: not one answer: {r}", r["name"]);
}
}