// 語音服務: speech to text (聽) and text to speech (說) through an API, run where the keys are // (the brain). Screens and the phone only record and play; they send the recording here and get // text back, or send text and get sound (MP3) back. Three kinds of service (設定 › 語音): // OpenAI 相容 POST {base}/audio/transcriptions, {base}/audio/speech — OpenAI, Groq, a Whisper // server of your own (speaches); the address decides which // xAI POST /v1/stt (the file last), /v1/tts // ElevenLabs POST /v1/speech-to-text (Scribe), /v1/text-to-speech/{voice} use crate::model::{State, VoiceEngine, VoiceKind}; use crate::providers::{resolve_base, ProviderKind}; use serde_json::{json, Value}; use std::time::Duration; pub const OPENAI_BASE: &str = "https://api.openai.com/v1"; pub const ELEVENLABS_BASE: &str = "https://api.elevenlabs.io/v1"; /// OpenAI's transcription models, newest first: the 4o ones and whisper-1 stop on 2027-02-26 /// (developers.openai.com/api/docs/deprecations), and an unknown model just tries the next. pub const OPENAI_LISTEN_MODELS: [&str; 3] = ["gpt-transcribe", "gpt-4o-mini-transcribe", "whisper-1"]; /// Answers longer than this are read only up to here (a chat answer, not a book). pub const MAX_SPEAK_CHARS: usize = 4000; pub const NOT_SET: &str = "還沒設定語音:請到「設定 → 語音」選一個服務。"; /// A voice service, ready to call: where, with which key, which model and voice. #[derive(Clone, Debug, PartialEq, Default)] pub struct Engine { pub kind: VoiceKind, pub base: String, pub key: String, pub model: String, pub voice: String, } /// What this brain can do with voice right now. #[derive(Clone, Debug, PartialEq, Default)] pub struct Engines { pub listen: Option, pub speak: Option, } impl Engines { pub fn of(st: &State) -> Engines { Engines { listen: resolve(&st.voice.listen, st, false), speak: resolve(&st.voice.speak, st, true) } } } /// The service set up in 設定 › 語音 with its key, or None when it can't be called (off, or no /// key). An empty key borrows 設定 › 模型's for the same service. On a screen the keys read /// "••••(已設定,在大腦上)": set up, on the brain. pub fn resolve(e: &VoiceEngine, st: &State, speak: bool) -> Option { let own = e.api_key.trim().to_string(); // (A key from the environment goes only to the service's own address: resolve_key_for.) let borrowed = |k: ProviderKind| if own.is_empty() { crate::providers::resolve_key_for(k, &st.provider(k).api_key, &st.provider(k).base_url) } else { own.clone() }; let (base, key) = match e.kind { VoiceKind::Off => return None, VoiceKind::OpenAi => { let base = e.base_url.trim().trim_end_matches('/').to_string(); if base.is_empty() || base == OPENAI_BASE { (OPENAI_BASE.to_string(), borrowed(ProviderKind::OpenAi)) } else { // A server of your own may need no key at all. return Some(Engine { kind: e.kind, base, key: own, model: e.model.trim().to_string(), voice: e.voice.trim().to_string() }); } } // (The voice's own key is xAI's: it goes to xAI's own address, not wherever the chat // provider was pointed.) VoiceKind::Xai => (if own.is_empty() { resolve_base(ProviderKind::Xai, &st.provider(ProviderKind::Xai).base_url) } else { ProviderKind::Xai.default_base_url().to_string() }, borrowed(ProviderKind::Xai)), VoiceKind::ElevenLabs => (if e.base_url.trim().is_empty() { ELEVENLABS_BASE.to_string() } else { e.base_url.trim().trim_end_matches('/').to_string() }, own), }; if key.is_empty() { return None; } // ElevenLabs reads with a voice of the person's choosing; there is no usual one. if speak && e.kind == VoiceKind::ElevenLabs && e.voice.trim().is_empty() { return None; } Some(Engine { kind: e.kind, base, key, model: e.model.trim().to_string(), voice: e.voice.trim().to_string() }) } /// Why `resolve` gave nothing, in a sentence for 設定 › 語音. pub fn missing(e: &VoiceEngine, speak: bool) -> &'static str { match e.kind { VoiceKind::Off => "關閉", VoiceKind::OpenAi => "需要 OpenAI 的金鑰(這裡,或 設定 › 模型 › OpenAI)", VoiceKind::Xai => "需要 xAI 的金鑰(這裡,或 設定 › 模型 › xAI)", VoiceKind::ElevenLabs if speak && !e.api_key.trim().is_empty() => "選一個聲音", VoiceKind::ElevenLabs => "需要 ElevenLabs 的金鑰", } } /// The voice service next to this brain (`make server` with voice: ANYBOT_VOICE_URL): 聽 and 說 /// use it wherever 設定 › 語音 has nothing (what the person chose stays). `speak_model` empty: /// it doesn't read aloud. Once per address: what is turned off later stays off. True when /// something changed. pub fn own_server(v: &mut crate::model::VoiceSettings, url: &str, listen_model: &str, speak_model: &str, voice: &str) -> bool { if v.from_server == url { return false; } v.from_server = url.to_string(); let mut changed = true; if v.listen.kind == VoiceKind::Off && !listen_model.is_empty() { v.listen = VoiceEngine { kind: VoiceKind::OpenAi, base_url: url.into(), model: listen_model.into(), ..Default::default() }; changed = true; } if v.speak.kind == VoiceKind::Off && !speak_model.is_empty() { v.speak = VoiceEngine { kind: VoiceKind::OpenAi, base_url: url.into(), model: speak_model.into(), voice: voice.into(), ..Default::default() }; changed = true; } changed } pub fn label(k: VoiceKind) -> &'static str { match k { VoiceKind::Off => "關閉", VoiceKind::OpenAi => "OpenAI 相容", VoiceKind::Xai => "xAI(Grok)", VoiceKind::ElevenLabs => "ElevenLabs", } } // ---------- 聽 ---------- /// The recording as text, in the person's Chinese when it was Chinese ([`spoken_in`]). /// `name` carries the format (voice.m4a, voice.webm, voice.wav…); `lang` is the spoken language /// ("" = detect); `ui` is the language of the window or phone that asked. pub fn transcribe(e: &Engine, audio: &[u8], name: &str, lang: &str, ui: &str) -> Result { if audio.len() < 1000 { return Err("沒有錄到聲音。".into()); } let text = match e.kind { VoiceKind::Off => return Err(NOT_SET.into()), VoiceKind::OpenAi => openai_listen(e, audio, name, lang)?, VoiceKind::Xai => { // Options before the file: xAI ignores fields sent after it. `format` (numbers as // digits) needs a language. let mut f = vec![]; if !lang.is_empty() { f.push(("language", lang.to_string())); f.push(("format", "true".into())); } let v = post_form(&format!("{}/stt", e.base), &bearer(&e.key), &f, name, audio, "xAI")?; text_of(&v) } VoiceKind::ElevenLabs => { let mut f = vec![("model_id", if e.model.is_empty() { "scribe_v2".to_string() } else { e.model.clone() })]; if !lang.is_empty() { f.push(("language_code", lang.to_string())); } let v = post_form(&format!("{}/speech-to-text", e.base), &[("xi-api-key", e.key.clone())], &f, name, audio, "ElevenLabs")?; text_of(&v) } }; Ok(spoken_in(&text, ui, lang)) } /// OpenAI 相容: the model asked for, or (at OpenAI) the newest that this account has. fn openai_listen(e: &Engine, audio: &[u8], name: &str, lang: &str) -> Result { let models: Vec = if !e.model.is_empty() { vec![e.model.clone()] } else if e.base == OPENAI_BASE { OPENAI_LISTEN_MODELS.iter().map(|m| m.to_string()).collect() } else { vec!["whisper-1".into()] }; let mut last = String::new(); for m in &models { let mut f = vec![("model", m.clone()), ("response_format", "json".to_string())]; if !lang.is_empty() { f.push(("language", lang.to_string())); } match post_form(&format!("{}/audio/transcriptions", e.base), &bearer(&e.key), &f, name, audio, "OpenAI 相容") { Ok(v) => return Ok(text_of(&v)), // A model this account or server doesn't have: try the next. Err(err) if err.contains("HTTP 404") || err.contains("HTTP 400") => last = err, Err(err) => return Err(err), } } // speaches before its model is down (the brain asks for it at start: fetch_model). if last.contains("not installed locally") { return Err("語音服務還在準備模型(第一次要下載約 1.6 GB),請過幾分鐘再試。".into()); } Err(last) } /// A voice server of your own (speaches) downloads a model only when asked: POST /// {base}/models/{model}; one it has answers at once. The service may come up after the brain, /// so this waits for it (about 5 minutes) before giving up. pub fn fetch_model(base: &str, model: &str) -> Result<(), String> { let url = format!("{}/models/{}", base.trim_end_matches('/'), model); let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(60 * 60))).http_status_as_error(false).build().into(); let mut last = String::new(); for _ in 0..30 { match agent.post(&url).send(&[][..]) { Ok(r) if r.status().is_success() => return Ok(()), Ok(mut r) => { let said: String = r.body_mut().read_to_string().unwrap_or_default().chars().take(200).collect(); return Err(format!("語音服務沒能下載 {model}(HTTP {}):{said}", r.status().as_u16())); } Err(e) => last = e.to_string(), } std::thread::sleep(Duration::from_secs(10)); } Err(format!("連不上語音服務({base}):{last}")) } fn text_of(v: &Value) -> String { v["text"].as_str().unwrap_or("").trim().to_string() } /// Recognisers write Mandarin in Simplified characters (xAI always, Whisper often), and with /// mainland words (软件 for 軟體): for a Traditional Chinese window, Traditional with Taiwan /// wording, like the bots' replies. Japanese (it has kana) keeps its own kanji. pub fn spoken_in(text: &str, ui_lang: &str, spoken: &str) -> String { let kana = text.chars().any(|c| ('\u{3040}'..='\u{30ff}').contains(&c)); if ui_lang == "zh-TW" && spoken != "ja" && !kana { cjk_punct(&zhconv::zhconv(text, zhconv::Variant::ZhTW)) } else { text.to_string() } } /// Whisper writes ASCII , ? ! : ; in Chinese sentences: next to a Chinese character they become /// the full-width ones (,?!:;). Between English words or digits (1,000) they stay. fn cjk_punct(s: &str) -> String { let han = |c: Option<&char>| c.is_some_and(|c| ('\u{3400}'..='\u{9fff}').contains(c) || ('\u{3000}'..='\u{303f}').contains(c) || ('\u{ff00}'..='\u{ffef}').contains(c)); let cs: Vec = s.chars().collect(); let mut out = String::with_capacity(s.len()); let mut i = 0; while i < cs.len() { let wide = match cs[i] { ',' => Some(','), '?' => Some('?'), '!' => Some('!'), ':' => Some(':'), ';' => Some(';'), _ => None, }; let next = cs[i + 1..].iter().find(|c| **c != ' '); match wide { Some(w) if han(out.chars().last().as_ref()) || han(next) => { out.push(w); // (The space Whisper puts after an ASCII comma has no place after a wide one.) while cs.get(i + 1) == Some(&' ') { i += 1; } } _ => out.push(cs[i]), } i += 1; } out } // ---------- 說 ---------- /// `text` read aloud as MP3. `voice` (a bot's own; empty = the one in 設定 › 語音), `lang` the /// language it is in ("" = let the service tell), `speed` 1.0 = normal. pub fn speak(e: &Engine, text: &str, voice: &str, lang: &str, speed: f32) -> Result, String> { let words: String = speakable(text).chars().take(MAX_SPEAK_CHARS).collect(); if words.is_empty() { return Err("沒有可以唸的文字。".into()); } let voice = if voice.trim().is_empty() { e.voice.clone() } else { voice.trim().to_string() }; let speed = if speed > 0.0 { speed.clamp(0.5, 2.0) } else { 1.0 }; let mp3 = speak_with(e, &words, voice, lang, speed)?; // A service can answer 200 with no sound at all (speaches can't say Chinese: its espeak has // no "zh"); that is a failure to say, not silence to play. if mp3.len() < 512 { return Err(format!("{} 的語音服務沒有產生聲音(可能不支援這個語言或聲音)。", label(e.kind))); } Ok(mp3) } fn speak_with(e: &Engine, words: &str, voice: String, lang: &str, speed: f32) -> Result, String> { match e.kind { VoiceKind::Off => Err(NOT_SET.into()), VoiceKind::OpenAi => { let at_openai = e.base == OPENAI_BASE; let model = if !e.model.is_empty() { e.model.clone() } else if at_openai { "gpt-4o-mini-tts".into() } else { "tts-1".into() }; let voice = if voice.is_empty() { "alloy".to_string() } else { voice }; let body = json!({"model": model, "input": words, "voice": voice, "response_format": "mp3", "speed": speed}); post_json(&format!("{}/audio/speech", e.base), &bearer(&e.key), &body, "OpenAI 相容") } VoiceKind::Xai => { let voice = if voice.is_empty() { "eve".to_string() } else { voice }; let lang = if lang.is_empty() { "auto" } else { lang }; let body = json!({"text": words, "voice_id": voice, "language": lang, "output_format": {"codec": "mp3"}, "speed": speed}); post_json(&format!("{}/tts", e.base), &bearer(&e.key), &body, "xAI") } VoiceKind::ElevenLabs => { if voice.is_empty() { return Err("ElevenLabs 要先選一個聲音(設定 → 語音)。".into()); } let model = if e.model.is_empty() { "eleven_multilingual_v2".to_string() } else { e.model.clone() }; let mut body = json!({"text": words, "model_id": model}); if (speed - 1.0).abs() > 0.01 { // (ElevenLabs reads between 0.7× and 1.2×.) body["voice_settings"] = json!({"speed": speed.clamp(0.7, 1.2)}); } post_json(&format!("{}/text-to-speech/{}?output_format=mp3_44100_128", e.base, crate::httpd::url_encode(&voice)), &[("xi-api-key", e.key.clone())], &body, "ElevenLabs") } } } /// A chat answer as words to say: no Markdown marks, link addresses or code. pub fn speakable(text: &str) -> String { let mut out = String::new(); let mut in_code = false; for line in text.lines() { let l = line.trim(); if l.starts_with("```") { in_code = !in_code; if in_code { out.push_str("(程式碼略過)\n"); } continue; } if in_code { continue; } let l = l.trim_start_matches(['#', '-', '*', '>', ' ']).replace("**", "").replace('`', ""); let l = l.split("](").next().unwrap_or(&l).replace('[', ""); if !l.is_empty() { out.push_str(&l); out.push('\n'); } } out.trim().to_string() } /// The voices the service offers: (id, what to show). pub fn voices(e: &Engine) -> Result, String> { match e.kind { VoiceKind::Off => Err(NOT_SET.into()), VoiceKind::OpenAi if e.base == OPENAI_BASE => Ok(["alloy", "ash", "ballad", "coral", "echo", "fable", "nova", "onyx", "sage", "shimmer", "verse"].iter().map(|v| (v.to_string(), v.to_string())).collect()), VoiceKind::OpenAi => Err("這個服務沒有提供聲音清單:請直接填聲音的名稱。".into()), VoiceKind::Xai => { let v = get_json(&format!("{}/tts/voices", e.base), &bearer(&e.key), "xAI")?; Ok(v["voices"].as_array().into_iter().flatten().filter_map(|x| x["voice_id"].as_str()).map(|id| (id.to_string(), id.to_string())).collect()) } VoiceKind::ElevenLabs => { let v = get_json(&format!("{}/voices", e.base), &[("xi-api-key", e.key.clone())], "ElevenLabs")?; Ok(v["voices"].as_array().into_iter().flatten().filter_map(|x| Some((x["voice_id"].as_str()?.to_string(), x["name"].as_str().unwrap_or("").to_string()))).collect()) } } } // ---------- HTTP ---------- fn bearer(key: &str) -> Vec<(&'static str, String)> { if key.is_empty() { vec![] } else { vec![("Authorization", format!("Bearer {key}"))] } } fn agent() -> ureq::Agent { ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(120))).http_status_as_error(false).build().into() } /// The recording's media type, from its name. pub fn audio_type(name: &str) -> &'static str { match name.rsplit('.').next().unwrap_or("").to_ascii_lowercase().as_str() { "wav" => "audio/wav", "webm" => "audio/webm", "ogg" | "opus" => "audio/ogg", "mp3" => "audio/mpeg", "flac" => "audio/flac", _ => "audio/mp4", } } /// A multipart form: the fields, then the audio file last. pub fn form(fields: &[(&str, String)], file_name: &str, audio: &[u8], boundary: &str) -> Vec { let clean = |s: &str| -> String { s.chars().filter(|&c| !matches!(c, '"' | '\\' | '\r' | '\n' | '\0')).collect() }; let safe_file = clean(file_name); let mut b = vec![]; for (k, v) in fields { let sk = clean(k); b.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{sk}\"\r\n\r\n{v}\r\n").as_bytes()); } b.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{safe_file}\"\r\nContent-Type: {}\r\n\r\n", audio_type(file_name)).as_bytes()); b.extend_from_slice(audio); b.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); b } fn post_form(url: &str, headers: &[(&str, String)], fields: &[(&str, String)], name: &str, audio: &[u8], who: &str) -> Result { let boundary = format!("anybot{}", chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0)); let body = form(fields, name, audio, &boundary); let mut req = agent().post(url).header("Content-Type", &format!("multipart/form-data; boundary={boundary}")); for (k, v) in headers { req = req.header(*k, v); } let (status, bytes) = answer(req.send(&body[..]), who)?; serde_json::from_slice(&bytes).map_err(|_| format!("{who} 的回答看不懂(HTTP {status})")) } fn post_json(url: &str, headers: &[(&str, String)], body: &Value, who: &str) -> Result, String> { let mut req = agent().post(url).header("Content-Type", "application/json"); for (k, v) in headers { req = req.header(*k, v); } answer(req.send(body.to_string().as_bytes()), who).map(|(_, b)| b) } fn get_json(url: &str, headers: &[(&str, String)], who: &str) -> Result { let mut req = agent().get(url); for (k, v) in headers { req = req.header(*k, v); } let (_, bytes) = answer(req.call(), who)?; serde_json::from_slice(&bytes).map_err(|_| format!("{who} 的回答看不懂")) } /// The body of a 200, or what went wrong in words. fn answer(r: Result, ureq::Error>, who: &str) -> Result<(u16, Vec), String> { let mut r = r.map_err(|e| format!("連不上 {who} 的語音服務:{e}"))?; let status = r.status().as_u16(); let bytes = r.body_mut().with_config().limit(64 * 1024 * 1024).read_to_vec().unwrap_or_default(); if status == 200 { return Ok((status, bytes)); } let said: String = String::from_utf8_lossy(&bytes).chars().take(200).collect(); Err(match status { 401 | 403 => format!("{who} 不接受這把金鑰(HTTP {status}):{said}"), _ => format!("{who} 的語音服務失敗(HTTP {status}):{said}"), }) } #[cfg(test)] mod tests { use super::*; use crate::model::{ProviderSettings, VoiceSettings}; use std::io::{Read, Write}; /// One request to a local server: what it was sent, and `reply` (with `ctype`) back. fn serve_once(reply: &'static str, ctype: &'static str) -> (String, std::thread::JoinHandle) { let server = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://127.0.0.1:{}/v1", server.local_addr().unwrap().port()); let h = std::thread::spawn(move || { let (mut s, _) = server.accept().unwrap(); s.set_read_timeout(Some(Duration::from_millis(800))).unwrap(); let mut buf = vec![0u8; 65536]; let mut got = vec![]; while let Ok(n) = s.read(&mut buf) { if n == 0 { break; } got.extend_from_slice(&buf[..n]); let text = String::from_utf8_lossy(&got); // The whole request is in: a form's closing line, or a JSON body as long as it said. let done = text.contains("--\r\n") || text.split_once("\r\n\r\n").map(|(h, b)| { let len = h.lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length: ").and_then(|v| v.trim().parse::().ok())); len.map(|n| b.len() >= n).unwrap_or(h.starts_with("GET")) }).unwrap_or(false); if done { break; } } let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", reply.len()).as_bytes()); let _ = s.write_all(reply.as_bytes()); String::from_utf8_lossy(&got).to_string() }); (base, h) } fn engine(kind: VoiceKind, base: &str, key: &str) -> Engine { Engine { kind, base: base.into(), key: key.into(), ..Default::default() } } fn state_with(voice: VoiceSettings, keys: &[(&str, &str)]) -> State { let mut st = State::first_run(); st.voice = voice; for (k, v) in keys { st.providers.insert(k.to_string(), ProviderSettings { api_key: v.to_string(), ..Default::default() }); } st } #[test] fn only_a_service_that_can_be_called_is_ready() { let on = |kind, key: &str| VoiceEngine { kind, api_key: key.into(), ..Default::default() }; // Off, or no key anywhere: not ready (the mic stays hidden). let st = state_with(VoiceSettings { listen: on(VoiceKind::Xai, ""), ..Default::default() }, &[]); assert_eq!(Engines::of(&st).listen, None); assert_eq!(Engines::of(&State::first_run()), Engines::default()); // xAI borrows 設定 › 模型's key. let st = state_with(VoiceSettings { listen: on(VoiceKind::Xai, ""), ..Default::default() }, &[("xai", "xai-k")]); let l = Engines::of(&st).listen.unwrap(); assert_eq!((l.base.as_str(), l.key.as_str()), ("https://api.x.ai/v1", "xai-k")); // Its own key wins. let st = state_with(VoiceSettings { listen: on(VoiceKind::Xai, "own"), ..Default::default() }, &[("xai", "xai-k")]); assert_eq!(Engines::of(&st).listen.unwrap().key, "own"); // OpenAI at its own address borrows OpenAI's key; a server of your own needs none. let st = state_with(VoiceSettings { listen: on(VoiceKind::OpenAi, ""), ..Default::default() }, &[("openai", "sk-o")]); assert_eq!(Engines::of(&st).listen.unwrap().base, OPENAI_BASE); let own = VoiceEngine { kind: VoiceKind::OpenAi, base_url: "http://voice:8000/v1/".into(), ..Default::default() }; let st = state_with(VoiceSettings { listen: own, ..Default::default() }, &[]); assert_eq!(Engines::of(&st).listen.unwrap().base, "http://voice:8000/v1"); // ElevenLabs reads only with a voice picked. let st = state_with(VoiceSettings { speak: on(VoiceKind::ElevenLabs, "el"), ..Default::default() }, &[]); assert_eq!(Engines::of(&st).speak, None); assert_eq!(missing(&st.voice.speak, true), "選一個聲音"); // On a screen the brain's keys read as set. let st = state_with(VoiceSettings { speak: on(VoiceKind::Xai, "••••(已設定,在大腦上)"), ..Default::default() }, &[]); assert!(Engines::of(&st).speak.is_some()); } #[test] fn an_older_save_keeps_voice_only_where_it_worked() { let mut st = state_with(VoiceSettings::default(), &[("openai", "sk-o")]); st.bots = State::samples().bots; st.bots[0].voice = "Meijia".into(); st.carry_voice_over(); assert_eq!((st.voice.listen.kind, st.voice.speak.kind, st.voice.saved), (VoiceKind::OpenAi, VoiceKind::Off, true)); assert!(st.bots.iter().all(|b| b.voice.is_empty()), "macOS voices mean nothing to a service"); // Only Grok: voice never worked there, so it starts off. let mut st = state_with(VoiceSettings::default(), &[("xai", "xai-k")]); st.carry_voice_over(); assert_eq!(st.voice.listen.kind, VoiceKind::Off); // Once: turned off later, it stays off. let mut st = state_with(VoiceSettings { saved: true, ..Default::default() }, &[("openai", "sk-o")]); st.carry_voice_over(); assert_eq!(st.voice.listen.kind, VoiceKind::Off); assert!(State::first_run().voice.saved); } #[test] fn a_voice_service_on_the_server_is_used_where_nothing_else_is() { let mut v = VoiceSettings::default(); assert!(own_server(&mut v, "http://voice:8000/v1", "whisper-m", "kokoro", "zf_xiaobei")); assert_eq!((v.listen.kind, v.listen.base_url.as_str(), v.listen.model.as_str()), (VoiceKind::OpenAi, "http://voice:8000/v1", "whisper-m")); assert_eq!((v.speak.model.as_str(), v.speak.voice.as_str()), ("kokoro", "zf_xiaobei")); // What the person chose stays; nothing to do the second time. let mut v = VoiceSettings { speak: VoiceEngine { kind: VoiceKind::Xai, ..Default::default() }, ..Default::default() }; assert!(own_server(&mut v, "http://voice:8000/v1", "whisper-m", "kokoro", "")); assert_eq!((v.listen.kind, v.speak.kind), (VoiceKind::OpenAi, VoiceKind::Xai)); assert!(!own_server(&mut v, "http://voice:8000/v1", "whisper-m", "kokoro", "")); // Turned off later: it stays off. v.listen.kind = VoiceKind::Off; assert!(!own_server(&mut v, "http://voice:8000/v1", "whisper-m", "kokoro", "")); assert_eq!(v.listen.kind, VoiceKind::Off); // No speaking model: 說 is left alone. let mut v = VoiceSettings::default(); own_server(&mut v, "http://voice:8000/v1", "whisper-m", "", ""); assert_eq!(v.speak.kind, VoiceKind::Off); } #[test] fn mandarin_comes_back_in_the_windows_chinese() { let heard = "帮我把手机里的照片依照月份整理好,软件更新完再提醒我"; assert_eq!(spoken_in(heard, "zh-TW", ""), "幫我把手機裡的照片依照月份整理好,軟體更新完再提醒我"); assert_eq!(spoken_in("会議は明日です", "zh-TW", ""), "会議は明日です"); assert_eq!(spoken_in("会议", "zh-TW", "ja"), "会议"); assert_eq!(spoken_in(heard, "en", ""), heard); // A word-by-word converter: 里 it doesn't know as 裡 stays 里, never 公裡. assert_eq!(spoken_in("三公里", "zh-TW", ""), "三公里"); // Whisper writes ASCII commas in Chinese; between English words they stay. assert_eq!(spoken_in("幫我打開Chrome,搜尋Tesla FSD,好嗎?", "zh-TW", ""), "幫我打開Chrome,搜尋Tesla FSD,好嗎?"); assert_eq!(spoken_in("Hello, world? Yes!", "zh-TW", ""), "Hello, world? Yes!"); assert_eq!(spoken_in("我要1,000元", "zh-TW", ""), "我要1,000元"); } #[test] fn xai_hears_with_the_options_before_the_file() { let (base, seen) = serve_once(r#"{"text":"明天下午三点开会","language":"zh-cn"}"#, "application/json"); let text = transcribe(&engine(VoiceKind::Xai, &base, "xai-k"), &[7u8; 2048], "voice.webm", "zh", "zh-TW").unwrap(); let req = seen.join().unwrap(); assert_eq!(text, "明天下午三點開會"); assert!(req.starts_with("POST /v1/stt") && req.contains("Bearer xai-k") && req.contains("Content-Type: audio/webm")); let (lang, fmt, file) = (req.find("name=\"language\"\r\n\r\nzh").unwrap(), req.find("name=\"format\"\r\n\r\ntrue").unwrap(), req.find("name=\"file\"").unwrap()); assert!(lang < file && fmt < file); } #[test] fn openai_compatible_and_elevenlabs_hear() { let (base, seen) = serve_once(r#"{"text":"hello there"}"#, "application/json"); let mut e = engine(VoiceKind::OpenAi, &base, ""); e.model = "Systran/faster-whisper-medium".into(); assert_eq!(transcribe(&e, &[7u8; 2048], "voice.m4a", "", "en").unwrap(), "hello there"); let req = seen.join().unwrap(); assert!(req.starts_with("POST /v1/audio/transcriptions") && req.contains("faster-whisper-medium") && !req.contains("Authorization")); let (base, seen) = serve_once(r#"{"text":"ok","language_code":"en"}"#, "application/json"); assert_eq!(transcribe(&engine(VoiceKind::ElevenLabs, &base, "el-k"), &[7u8; 2048], "voice.wav", "en", "en").unwrap(), "ok"); let req = seen.join().unwrap(); assert!(req.starts_with("POST /v1/speech-to-text") && req.to_ascii_lowercase().contains("xi-api-key: el-k") && req.contains("scribe_v2")); // Too short to be speech: not sent at all. assert!(transcribe(&engine(VoiceKind::Xai, "http://127.0.0.1:1", "k"), &[0u8; 10], "voice.m4a", "", "zh-TW").unwrap_err().contains("沒有錄到")); } #[test] fn a_model_is_asked_for_and_a_missing_one_is_explained() { let (base, seen) = serve_once(r#"{"message":"Model downloaded"}"#, "application/json"); fetch_model(&base, "deepdml/faster-whisper-large-v3-turbo-ct2").unwrap(); assert!(seen.join().unwrap().starts_with("POST /v1/models/deepdml/faster-whisper-large-v3-turbo-ct2 ")); // What speaches says before the model is down, in words the person can act on. let server = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://127.0.0.1:{}/v1", server.local_addr().unwrap().port()); let h = std::thread::spawn(move || { use std::io::{Read, Write}; let (mut s, _) = server.accept().unwrap(); s.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); let mut buf = vec![0u8; 65536]; let _ = s.read(&mut buf); let _ = s.read(&mut buf); let reply = r#"{"detail":"Model 'x' is not installed locally. You can download the model using `POST /v1/models`"}"#; let _ = s.write_all(format!("HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len()).as_bytes()); }); let mut e = engine(VoiceKind::OpenAi, &base, ""); e.model = "x".into(); let err = transcribe(&e, &[7u8; 4000], "voice.m4a", "", "zh-TW").unwrap_err(); h.join().unwrap(); assert!(err.contains("還在準備模型"), "{err}"); } #[test] fn speaking_sends_the_words_and_gets_mp3() { // (Real sound is more than a few bytes; less is no sound.) let fake: &'static str = Box::leak(format!("ID3{}", "x".repeat(600)).into_boxed_str()); let (base, seen) = serve_once(fake, "audio/mpeg"); let mp3 = speak(&engine(VoiceKind::Xai, &base, "xai-k"), "## 好的\n- **已經**整理好了 [看](https://x.y)", "", "zh", 1.0).unwrap(); assert_eq!(mp3, fake.as_bytes()); let req = seen.join().unwrap(); let body: Value = serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap(); assert!(req.starts_with("POST /v1/tts")); assert_eq!((body["text"].as_str(), body["voice_id"].as_str(), body["language"].as_str(), body["output_format"]["codec"].as_str()), (Some("好的\n已經整理好了 看"), Some("eve"), Some("zh"), Some("mp3"))); let (base, seen) = serve_once(fake, "audio/mpeg"); let mut e = engine(VoiceKind::OpenAi, &base, "k"); e.voice = "zf_xiaobei".into(); speak(&e, "你好", "", "", 1.25).unwrap(); let req = seen.join().unwrap(); let body: Value = serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap(); assert!(req.starts_with("POST /v1/audio/speech")); assert_eq!((body["voice"].as_str(), body["response_format"].as_str(), body["speed"].as_f64()), (Some("zf_xiaobei"), Some("mp3"), Some(1.25))); // 200 with no sound (speaches can't say Chinese: espeak has no "zh"): said, not played. let (base, seen) = serve_once("", "audio/mpeg"); let err = speak(&engine(VoiceKind::OpenAi, &base, ""), "你好", "zf_xiaobei", "zh", 1.0).unwrap_err(); seen.join().unwrap(); assert!(err.contains("沒有產生聲音"), "{err}"); // A bot's own voice wins; ElevenLabs puts it in the address. let (base, seen) = serve_once(fake, "audio/mpeg"); let mut e = engine(VoiceKind::ElevenLabs, &base, "el"); e.voice = "default-voice".into(); speak(&e, "hi", "bot-voice", "", 1.0).unwrap(); assert!(seen.join().unwrap().starts_with("POST /v1/text-to-speech/bot-voice?output_format=mp3")); } /// The real xAI, both ways: `ANYBOT_TEST_XAI_KEY=… cargo test --bin anybot xai_for_real -- --ignored`. #[test] #[ignore] fn xai_for_real() { let key = std::env::var("ANYBOT_TEST_XAI_KEY").expect("ANYBOT_TEST_XAI_KEY"); let e = engine(VoiceKind::Xai, "https://api.x.ai/v1", &key); let mp3 = speak(&e, "好的,我已經把下載資料夾裡的照片整理好了,軟體也更新完了。", "", "zh", 1.0).unwrap(); assert!(mp3.len() > 10_000, "{} bytes", mp3.len()); let heard = transcribe(&e, &mp3, "voice.mp3", "zh", "zh-TW").unwrap(); assert!(heard.contains("照片") && heard.contains("軟體") && !heard.contains("软"), "{heard}"); assert!(!voices(&e).unwrap().is_empty()); } /// A real OpenAI-compatible server (your own speaches): ANYBOT_TEST_OAI_BASE=http://127.0.0.1:8000/v1 /// ANYBOT_TEST_OAI_LISTEN= ANYBOT_TEST_CLIP= [ANYBOT_TEST_OAI_SPEAK= /// ANYBOT_TEST_OAI_VOICE= ANYBOT_TEST_OUT=] cargo test --bin anybot own_server_for_real -- --ignored --nocapture #[test] #[ignore] fn own_server_for_real() { let var = |k: &str| std::env::var(k).unwrap_or_default(); let mut e = engine(VoiceKind::OpenAi, &var("ANYBOT_TEST_OAI_BASE"), ""); e.model = var("ANYBOT_TEST_OAI_LISTEN"); let clip = std::path::PathBuf::from(var("ANYBOT_TEST_CLIP")); let audio = std::fs::read(&clip).unwrap(); let name = format!("voice.{}", clip.extension().and_then(|x| x.to_str()).unwrap_or("m4a")); let t = std::time::Instant::now(); fetch_model(&e.base, &e.model).unwrap(); println!("模型就緒({:.0} 秒)", t.elapsed().as_secs_f32()); let t = std::time::Instant::now(); let heard = transcribe(&e, &audio, &name, "zh", "zh-TW").unwrap(); println!("聽({},{:.1} 秒):{heard}", e.model, t.elapsed().as_secs_f32()); if !var("ANYBOT_TEST_OAI_SPEAK").is_empty() { let mut s = engine(VoiceKind::OpenAi, &var("ANYBOT_TEST_OAI_BASE"), ""); s.model = var("ANYBOT_TEST_OAI_SPEAK"); let t = std::time::Instant::now(); let mp3 = speak(&s, "好的,我已經把下載資料夾裡的照片整理好了,總共四十八張。", &var("ANYBOT_TEST_OAI_VOICE"), "zh", 1.0).unwrap(); println!("說({},{:.1} 秒):{} bytes", s.model, t.elapsed().as_secs_f32(), mp3.len()); std::fs::write(var("ANYBOT_TEST_OUT"), &mp3).unwrap(); } } #[test] fn answers_are_cleaned_for_speaking() { let t = "## 行程\n- **上午**:赤崁樓\n```\nls -la\n```\n看 [地圖](https://x.y)"; assert_eq!(speakable(t), "行程\n上午:赤崁樓\n(程式碼略過)\n看 地圖"); assert_eq!(audio_type("voice.webm"), "audio/webm"); assert_eq!(audio_type("voice.M4A"), "audio/mp4"); } }