From 70b208e1bd728e347a9121c17d0bcd761e7c2458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 10 Nov 2026 22:38:41 +0800 Subject: [PATCH] Voice input: xAI when there's no OpenAI key, and in Traditional Chinese MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Speech to text only knew OpenAI's key, borrowed from the AI providers, so with Grok alone set up the mic recorded and then failed for a key nobody had. Now OpenAI's key is used when there is one, else xAI's POST /v1/stt (options before the file, the file last; checked with a real Mandarin clip). Without either, the mic and 語音聊天 say so before recording instead of after. xAI answers Mandarin in Simplified characters ("zh-cn") and OpenAI often does too: in a Traditional Chinese window the text becomes Traditional with Taiwan wording (zhconv, like the bots' replies). Japanese, which has kana, keeps its own kanji. A stopgap: voice moves to the server next (one engine for every screen, set up in its own 語音 settings). --- src/app/attach_ui.rs | 30 +++++--- src/voice.rs | 167 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 182 insertions(+), 15 deletions(-) diff --git a/src/app/attach_ui.rs b/src/app/attach_ui.rs index e193d33..f7db2eb 100644 --- a/src/app/attach_ui.rs +++ b/src/app/attach_ui.rs @@ -219,11 +219,25 @@ impl App { self.att.voice_rx.is_some() } + /// Who turns the person's speech into text: their OpenAI key, else their xAI key. + fn stt(&self) -> Result { + let side = |k: ProviderKind| { + let ps = self.state.provider(k); + (providers::resolve_base(k, &ps.base_url), providers::resolve_key(k, &ps.api_key)) + }; + crate::voice::pick_stt(side(ProviderKind::OpenAi), side(ProviderKind::Xai)).ok_or_else(|| crate::voice::NO_STT_KEY.to_string()) + } + /// The mic button: start, or stop and turn the recording into text. pub(super) fn voice_toggle(&mut self, ctx: &egui::Context, bot_id: u64) { if self.voice_stop(ctx) { return; } + // Say so before the person talks, not after (it used to record, then fail for the key). + if let Err(e) = self.stt() { + self.att.error = Some(e); + return; + } crate::voice::stop_speaking(); match crate::voice::start() { Ok(r) => self.att.voice = Some((bot_id, r)), @@ -235,15 +249,13 @@ impl App { fn voice_stop(&mut self, ctx: &egui::Context) -> bool { let Some((id, rec)) = self.att.voice.take() else { return false }; let lang = self.state.bot(id).map(|b| b.voice_lang.clone()).unwrap_or_default(); - let ps = self.state.provider(ProviderKind::OpenAi); - let base = providers::resolve_base(ProviderKind::OpenAi, &ps.base_url); - let key = providers::resolve_key(ProviderKind::OpenAi, &ps.api_key); + let stt = self.stt(); let (tx, rx) = channel(); self.att.voice_rx = Some(rx); let c = ctx.clone(); std::thread::spawn(move || { let r = rec.finish().and_then(|f| { - let t = crate::voice::transcribe_lang(&base, &key, &f, &lang); + let t = stt.and_then(|s| crate::voice::transcribe(&s, &f, &lang)); let _ = std::fs::remove_file(&f); t }); @@ -314,6 +326,10 @@ impl App { impl App { pub(super) fn call_start(&mut self, bot_id: u64) { + if let Err(e) = self.stt() { + self.att.error = Some(e); + return; + } crate::voice::stop_speaking(); self.att.call = Some((bot_id, CallPhase::Listening)); self.att.call_rec = None; @@ -352,15 +368,13 @@ impl App { if self.att.call_rec.as_mut().map(|r| r.done()).unwrap_or(false) { let rec = self.att.call_rec.take().unwrap(); let lang = self.state.bot(bot_id).map(|b| b.voice_lang.clone()).unwrap_or_default(); - let ps = self.state.provider(ProviderKind::OpenAi); - let base = providers::resolve_base(ProviderKind::OpenAi, &ps.base_url); - let key = providers::resolve_key(ProviderKind::OpenAi, &ps.api_key); + let stt = self.stt(); let (tx, rx) = channel(); self.att.call_rx = Some(rx); let c = ctx.clone(); std::thread::spawn(move || { let r = rec.finish().and_then(|f| { - let t = crate::voice::transcribe_lang(&base, &key, &f, &lang); + let t = stt.and_then(|s| crate::voice::transcribe(&s, &f, &lang)); let _ = std::fs::remove_file(&f); t }); diff --git a/src/voice.rs b/src/voice.rs index 81fb87c..8b6dc5a 100644 --- a/src/voice.rs +++ b/src/voice.rs @@ -1,7 +1,7 @@ // 語音輸入: hold a short recording from the microphone, turn it into text, put it in the message // box (the original: 聽寫 / transcribeAudio through its server). Here the recording uses macOS's -// own AVAudioRecorder (through osascript, no extra install) and the text comes from an -// OpenAI-compatible /audio/transcriptions endpoint with the person's own key. +// own AVAudioRecorder (through osascript, no extra install) and the text comes from the person's +// own key: OpenAI's /audio/transcriptions, or xAI's /stt when only Grok is set up. use std::path::PathBuf; use std::process::{Child, Command, Stdio}; @@ -208,11 +208,16 @@ impl Recording { /// Same, telling the service the spoken language (ISO 639-1, e.g. "zh"; empty = detect). pub fn multipart_lang(model: &str, file_name: &str, audio: &[u8], boundary: &str, lang: &str) -> Vec { - let mut b = vec![]; let mut fields = vec![("model", model), ("response_format", "json")]; if !lang.is_empty() { fields.push(("language", lang)); } + form(&fields, file_name, audio, boundary) +} + +/// A multipart form: the fields, then the audio file last. +fn form(fields: &[(&str, &str)], 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()); } @@ -223,22 +228,108 @@ pub fn multipart_lang(model: &str, file_name: &str, audio: &[u8], boundary: &str b } +/// Who turns speech into text, with whose key. +#[derive(Clone, Debug, PartialEq)] +pub enum Stt { + /// OpenAI's /audio/transcriptions ([`MODELS`] in order). + OpenAi { base: String, key: String }, + /// xAI's /stt (Grok's speech to text). + Xai { base: String, key: String }, +} + +pub const NO_STT_KEY: &str = "語音轉文字要用 OpenAI 或 xAI(Grok)的金鑰:請到「設定 → AI 供應商」填入其中一個。"; + +/// OpenAI's when it has a key, else xAI's: (base URL, key) of each. None: neither has a key. +pub fn pick_stt(openai: (String, String), xai: (String, String)) -> Option { + if !openai.1.trim().is_empty() { + return Some(Stt::OpenAi { base: openai.0, key: openai.1.trim().to_string() }); + } + if !xai.1.trim().is_empty() { + return Some(Stt::Xai { base: xai.0, key: xai.1.trim().to_string() }); + } + None +} + +/// Speech to text, in the window's Chinese when it was Chinese ([`spoken_in`]). +pub fn transcribe(stt: &Stt, file: &std::path::Path, lang: &str) -> Result { + let text = match stt { + Stt::OpenAi { base, key } => transcribe_lang(base, key, file, lang)?, + Stt::Xai { base, key } => transcribe_xai(base, key, file, lang)?, + }; + Ok(spoken_in(&text, &crate::i18n::lang(), lang)) +} + +/// Recognisers write Mandarin in Simplified characters (xAI always, OpenAI often), and with +/// mainland words (软件 for 軟體): in 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() + } +} + +/// The voice file's name in the form (the services tell the format by it and by the header). +fn upload_name(file: &std::path::Path) -> &'static str { + if file.extension().and_then(|e| e.to_str()) == Some("wav") { + "voice.wav" + } else { + "voice.m4a" + } +} + +fn stt_agent() -> ureq::Agent { + ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(120))).http_status_as_error(false).build().into() +} + +/// xAI's speech to text (POST {base}/stt, the file last; the answer's `text`). With a language it +/// also writes numbers and amounts as digits (`format`, which needs one). +pub fn transcribe_xai(base_url: &str, api_key: &str, file: &std::path::Path, lang: &str) -> Result { + let audio = std::fs::read(file).map_err(|e| e.to_string())?; + let boundary = format!("anybot{}", chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0)); + let mut fields = vec![]; + if !lang.is_empty() { + fields.push(("language", lang)); + fields.push(("format", "true")); + } + let body = form(&fields, upload_name(file), &audio, &boundary); + let url = format!("{}/stt", base_url.trim_end_matches('/')); + let resp = stt_agent() + .post(&url) + .header("Authorization", &format!("Bearer {}", api_key.trim())) + .header("Content-Type", &format!("multipart/form-data; boundary={boundary}")) + .send(&body[..]); + match resp { + Ok(mut r) => { + let status = r.status().as_u16(); + let text = r.body_mut().read_to_string().unwrap_or_default(); + if status != 200 { + return Err(format!("轉文字失敗(xAI,HTTP {status}):{}", text.chars().take(200).collect::())); + } + let v: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + Ok(v["text"].as_str().unwrap_or("").trim().to_string()) + } + Err(e) => Err(format!("連不上語音轉文字服務(xAI):{e}")), + } +} + /// The spoken languages offered for voice chat (the original: 語言 Auto-detect…): (code, name). pub const SPOKEN: [(&str, &str); 6] = [("", "自動偵測"), ("zh", "中文"), ("en", "English"), ("ja", "日本語"), ("ko", "한국어"), ("es", "Español")]; pub fn transcribe_lang(base_url: &str, api_key: &str, file: &std::path::Path, lang: &str) -> Result { if api_key.trim().is_empty() { - return Err("語音轉文字要用 OpenAI 的金鑰:請到「設定 → AI 供應商 → OpenAI」填入。".into()); + return Err(NO_STT_KEY.into()); } let audio = std::fs::read(file).map_err(|e| e.to_string())?; let boundary = format!("anybot{}", chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0)); let url = format!("{}/audio/transcriptions", base_url.trim_end_matches('/')); - let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(120))).http_status_as_error(false).build().into(); + let agent = stt_agent(); let mut last = String::new(); for model in MODELS { - let name = if file.extension().and_then(|e| e.to_str()) == Some("wav") { "voice.wav" } else { "voice.m4a" }; - let body = multipart_lang(model, name, &audio, &boundary, lang); + let body = multipart_lang(model, upload_name(file), &audio, &boundary, lang); let resp = agent .post(&url) .header("Authorization", &format!("Bearer {}", api_key.trim())) @@ -463,4 +554,66 @@ mod tests { assert!(req.contains("Bearer sk-test") && req.contains("name=\"model\"\r\n\r\ngpt-4o-mini-transcribe") && req.contains("filename=\"voice.m4a\"")); assert!(transcribe_lang("http://127.0.0.1:1", "", &std::path::PathBuf::from("/x"), "").unwrap_err().contains("OpenAI")); } + + #[test] + fn speech_goes_to_whichever_key_there_is() { + let side = |base: &str, key: &str| (base.to_string(), key.to_string()); + let (oa, xa) = ("https://api.openai.com/v1", "https://api.x.ai/v1"); + assert_eq!(pick_stt(side(oa, "sk-o"), side(xa, "xai-k")), Some(Stt::OpenAi { base: oa.into(), key: "sk-o".into() })); + // Only Grok set up (no OpenAI key): xAI's speech to text. + assert_eq!(pick_stt(side(oa, " "), side(xa, "xai-k")), Some(Stt::Xai { base: xa.into(), key: "xai-k".into() })); + assert_eq!(pick_stt(side(oa, ""), side(xa, "")), None); + assert!(NO_STT_KEY.contains("OpenAI") && NO_STT_KEY.contains("xAI")); + } + + #[test] + fn mandarin_comes_back_in_the_windows_chinese() { + // What xAI really answers for a Taiwanese speaker (language "zh-cn"). + let heard = "帮我把手机里的照片依照月份整理好,软件更新完再提醒我"; + assert_eq!(spoken_in(heard, "zh-TW", ""), "幫我把手機裡的照片依照月份整理好,軟體更新完再提醒我"); + assert_eq!(spoken_in(heard, "zh-TW", "zh"), "幫我把手機裡的照片依照月份整理好,軟體更新完再提醒我"); + // A word-by-word converter: 里 it doesn't know as 裡 stays 里 (資料夾里), never 公裡. + assert_eq!(spoken_in("三公里", "zh-TW", ""), "三公里"); + // Japanese keeps its own kanji; other windows keep what was heard. + assert_eq!(spoken_in("会議は明日です", "zh-TW", ""), "会議は明日です"); + assert_eq!(spoken_in("会议", "zh-TW", "ja"), "会议"); + assert_eq!(spoken_in(heard, "en", ""), heard); + assert_eq!(spoken_in("Book a table for two", "zh-TW", ""), "Book a table for two"); + } + + #[test] + fn xai_request_is_well_formed() { + let server = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = server.local_addr().unwrap().port(); + let seen = std::thread::spawn(move || { + let (mut s, _) = server.accept().unwrap(); + s.set_read_timeout(Some(Duration::from_secs(5))).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]); + if got.windows(4).any(|w| w == b"--\r\n") { + break; + } + } + let reply = "{\"text\":\"明天下午三点开会\",\"language\":\"zh-cn\",\"duration\":2.2}"; + let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len()).as_bytes()); + String::from_utf8_lossy(&got).to_string() + }); + let f = std::env::temp_dir().join(format!("anybot-xai-test-{}.m4a", std::process::id())); + std::fs::write(&f, vec![7u8; 2048]).unwrap(); + let text = transcribe_xai(&format!("http://127.0.0.1:{port}/v1"), "xai-test", &f, "zh").unwrap(); + let req = seen.join().unwrap(); + let _ = std::fs::remove_file(&f); + assert_eq!(text, "明天下午三点开会"); + assert!(req.starts_with("POST /v1/stt"), "{}", &req[..40.min(req.len())]); + assert!(req.contains("Bearer xai-test") && req.contains("filename=\"voice.m4a\"")); + // Options come before the file: xAI ignores fields sent after it. + 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); + assert!(!req.contains("name=\"model\"")); + } }