// 語音服務: 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, resolve_key, 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(); let borrowed = |k: ProviderKind| if own.is_empty() { resolve_key(k, &st.provider(k).api_key) } 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() }); } } VoiceKind::Xai => (resolve_base(ProviderKind::Xai, &st.provider(ProviderKind::Xai).base_url), 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 的金鑰", } } 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), } } Err(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 { zhconv::zhconv(text, zhconv::Variant::ZhTW) } else { text.to_string() } } // ---------- 說 ---------- /// `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 }; 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, 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 mut b = vec![]; for (k, v) in fields { b.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n").as_bytes()); } b.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{file_name}\"\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 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", ""), "三公里"); } #[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 speaking_sends_the_words_and_gets_mp3() { let (base, seen) = serve_once("ID3fake-mp3", "audio/mpeg"); let mp3 = speak(&engine(VoiceKind::Xai, &base, "xai-k"), "## 好的\n- **已經**整理好了 [看](https://x.y)", "", "zh", 1.0).unwrap(); assert_eq!(mp3, b"ID3fake-mp3"); 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("ID3x", "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))); // A bot's own voice wins; ElevenLabs puts it in the address. let (base, seen) = serve_once("ID3y", "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()); } #[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"); } }