// 語音 in the window: 語音輸入 (the mic), 會議錄音, 語音聊天 and 朗讀, and 設定 › 語音. // Only recording and playing happen here. The words and the sound come from the brain's voice // service (speech.rs): this AnyBot's own when it is the brain, else its brain's, through the // account. With no service set up there is no mic, no 語音聊天 and no 朗讀 at all. use super::attach_ui::CallPhase; use super::*; use crate::model::{VoiceEngine, VoiceKind}; use crate::remote::Cmd; use crate::speech; /// Where this window's voice goes. #[derive(Clone)] pub(super) enum VoiceVia { /// A screen of another AnyBot: its brain, through the account. Brain(crate::remote::Settings), /// This AnyBot is the brain: its own 設定 › 語音. Here(speech::Engines), } impl VoiceVia { /// A recording as text. pub(super) fn hear(&self, file: &std::path::Path, lang: &str) -> Result { let audio = std::fs::read(file).map_err(|e| format!("讀不到錄音:{e}"))?; let name = format!("voice.{}", file.extension().and_then(|e| e.to_str()).unwrap_or("m4a")); match self { VoiceVia::Brain(s) => crate::remote::sync_voice_transcribe(s, &audio, &name, lang), VoiceVia::Here(e) => match &e.listen { Some(l) => speech::transcribe(l, &audio, &name, lang, &crate::i18n::lang()), None => Err(speech::NOT_SET.into()), }, } } /// Words as MP3. pub(super) fn sound(&self, text: &str, voice: &str, lang: &str, speed: f32) -> Result, String> { match self { VoiceVia::Brain(s) => crate::remote::sync_voice_speech(s, &serde_json::json!({"text": text, "voice": voice, "lang": lang, "speed": speed})), VoiceVia::Here(e) => match &e.speak { Some(sp) => speech::speak(sp, text, voice, lang, speed), None => Err(speech::NOT_SET.into()), }, } } fn voices(&self) -> Result, String> { match self { VoiceVia::Brain(s) => crate::remote::sync_voice_voices(s), VoiceVia::Here(e) => e.speak.as_ref().map(speech::voices).unwrap_or_else(|| Err(speech::NOT_SET.into())), } } } /// 會議錄音 prompt: what the bot is asked to do with the transcript. const MEETING_ASK: &str = "這是剛才會議的文字記錄,請整理:重點、做了哪些決定、待辦事項(誰、做什麼、什麼時候)。"; /// What 試聽 says. const SAMPLE: &str = "你好,我是你的 Bot。這是我說話的聲音。"; #[derive(Default)] pub struct VoiceUi { /// What went wrong getting or playing sound (a thread's), shown under the message box. note: Arc>>, /// 會議錄音 being turned into text here (on the brain): (bot, answer). meetings: Vec<(u64, Receiver>)>, /// 設定 › 語音 › 試試看: recording, then waiting for its text, then what was heard. test_rec: Option, test_rx: Option>>, test_said: Option>, /// 試聽's trouble. test_note: Arc>>, /// The voices 說 offers (loaded when asked). voices_rx: Option, String>>>, pub(super) voice_list: Vec<(String, String)>, voices_err: String, } impl App { pub(super) fn voice_via(&self) -> VoiceVia { if self.mir.on { VoiceVia::Brain(self.state.remote.clone()) } else { VoiceVia::Here(speech::Engines::of(&self.state)) } } /// 設定 › 語音 has 聽 (on a screen: the brain's, whose keys show as set). pub(super) fn can_listen(&self) -> bool { speech::resolve(&self.state.voice.listen, &self.state, false).is_some() } pub(super) fn can_speak(&self) -> bool { speech::resolve(&self.state.voice.speak, &self.state, true).is_some() } // ---------- 語音輸入、會議錄音 ---------- pub(super) fn voice_recording(&self, bot_id: u64) -> Option { self.att.voice.as_ref().filter(|(id, _)| *id == bot_id).map(|(_, r)| r.started) } pub(super) fn voice_busy(&self) -> bool { self.att.voice_rx.is_some() } /// 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; } if !self.can_listen() { self.att.error = Some(speech::NOT_SET.into()); return; } crate::voice::stop_speaking(); match crate::voice::start() { Ok(r) => self.att.voice = Some((bot_id, r)), Err(e) => self.att.error = Some(e), } } /// Stop the recording that is running and turn it into text (false: none was running). 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 via = self.voice_via(); if std::mem::take(&mut self.att.meeting) { self.meeting_hand_over(id, rec, lang, via); return true; } 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 = via.hear(&f, &lang); let _ = std::fs::remove_file(&f); t }); let _ = tx.send((id, r)); c.request_repaint(); }); true } /// 會議記錄: a long recording that becomes a transcript for the bot to summarize. pub(super) fn start_meeting(&mut self, ctx: &egui::Context, bot_id: u64) { if self.att.voice.is_some() { return; } self.att.meeting = true; self.voice_toggle(ctx, bot_id); if self.att.voice.is_none() { self.att.meeting = false; } } pub(super) fn meeting_on(&self) -> bool { self.att.meeting && self.att.voice.is_some() } /// A meeting can run longer than the account lets one request wait (35 s): the recording goes /// to the brain, which turns it into text when it can and gives it to the bot itself. fn meeting_hand_over(&mut self, bot: u64, rec: crate::voice::Recording, lang: String, via: VoiceVia) { let VoiceVia::Brain(s) = via else { match rec.finish() { Ok(f) => self.meeting_job(bot, f, lang, true), Err(e) => self.att.error = Some(e), } return; }; let note = self.vo.note.clone(); std::thread::spawn(move || { let r = rec.finish().and_then(|f| { let bytes = std::fs::read(&f).map_err(|e| e.to_string()); let _ = std::fs::remove_file(&f); let ext = f.extension().and_then(|e| e.to_str()).unwrap_or("m4a").to_string(); let path = crate::remote::sync_upload(&s, bot, &format!("會議錄音.{ext}"), &bytes?)?; crate::remote::sync_post(&s, "act", &serde_json::json!({"bot": bot, "action": "meeting", "path": path, "lang": lang})).map(|_| ()) }); *note.lock().unwrap() = Some(match r { Ok(()) => "會議錄音交給大腦了:轉成文字後會自動交給 Bot 整理。".into(), Err(e) => format!("會議錄音沒能交給大腦:{e}"), }); }); } /// Here, on the brain: the recording becomes text, then goes to the bot with the ask. pub(super) fn meeting_job(&mut self, bot: u64, file: PathBuf, lang: String, remove: bool) { let via = VoiceVia::Here(speech::Engines::of(&self.state)); let (tx, rx) = channel(); self.vo.meetings.push((bot, rx)); std::thread::spawn(move || { let r = via.hear(&file, &lang); if remove { let _ = std::fs::remove_file(&file); } let _ = tx.send(r); }); } /// Put the text where the person was typing; hand finished meetings to their bot. pub(super) fn voice_poll(&mut self, ctx: &egui::Context) { let max = if self.att.meeting { crate::voice::MEETING_MAX_SECS } else { crate::voice::MAX_SECS }; if self.att.voice.as_ref().is_some_and(|(_, r)| r.started.elapsed().as_secs() >= max) { // What was recorded up to the limit is kept and turned into text like any recording. self.att.error = Some(format!("錄音最長 {},已經停止;錄到的部分正在轉成文字。", crate::voice::length_words(max))); self.voice_stop(ctx); } if let Some(e) = self.vo.note.lock().unwrap().take() { self.att.error = Some(e); } let Some(rx) = &self.att.voice_rx else { return }; if let Ok((id, r)) = rx.try_recv() { self.att.voice_rx = None; match r { Ok(t) if t.is_empty() => self.att.error = Some("沒有聽到說話。".into()), Ok(t) => { let d = self.drafts.entry(id).or_default(); if !d.is_empty() && !d.ends_with([' ', '\n']) { d.push(' '); } d.push_str(&t); } Err(e) => self.att.error = Some(e), } } } pub(super) fn meetings_poll(&mut self, ctx: &egui::Context) { let mut done = vec![]; self.vo.meetings.retain(|(bot, rx)| match rx.try_recv() { Ok(r) => { done.push((*bot, r)); false } Err(std::sync::mpsc::TryRecvError::Empty) => true, Err(_) => false, }); for (bot, r) in done { let stored = r.and_then(|t| if t.is_empty() { Err("錄音裡沒有聽到說話".into()) } else { Ok(t) }).and_then(|t| { let dir = std::env::temp_dir().join("anybot-meetings"); let _ = std::fs::create_dir_all(&dir); let file = dir.join(format!("會議記錄 {}.txt", chrono::Local::now().format("%Y-%m-%d %H%M"))); std::fs::write(&file, &t).map_err(|e| e.to_string())?; let a = crate::attach::store(bot, &file); let _ = std::fs::remove_file(&file); a }); match stored { Ok(a) => self.remote_cmd(ctx, Cmd::Send { bot, text: MEETING_ASK.into(), attachments: vec![a.path], from: String::new() }), // Said in the chat: the person may be at another screen, or the phone. Err(e) => { if let Some(b) = self.state.bot_mut(bot) { let mut m = Message::assistant(&format!("會議錄音沒能轉成文字:{e}"), ""); m.error = true; b.messages.push(m); } self.mark(); } } } } // ---------- 朗讀 ---------- /// Read `text` aloud with this bot's voice, speed and language. pub(super) fn read_aloud(&mut self, bot_id: u64, text: &str) { let Some(b) = self.state.bot(bot_id) else { return }; let (voice, lang, speed) = (b.voice.clone(), b.voice_lang.clone(), if b.voice_rate > 0.0 { b.voice_rate } else { 1.0 }); let (via, text) = (self.voice_via(), text.to_string()); crate::voice::say(move || via.sound(&text, &voice, &lang, speed), self.vo.note.clone()); } // ---------- 通話模式 ---------- pub(super) fn call_start(&mut self, bot_id: u64) { if !self.can_listen() || !self.can_speak() { self.att.error = Some(speech::NOT_SET.into()); return; } crate::voice::stop_speaking(); self.att.call = Some((bot_id, CallPhase::Listening)); self.att.call_rec = None; self.att.call_rx = None; } pub(super) fn call_end(&mut self) { if let Some(r) = self.att.call_rec.take() { r.cancel(); } crate::voice::stop_speaking(); self.att.call = None; self.att.call_rx = None; } pub(super) fn call_state(&self) -> Option<(u64, CallPhase)> { self.att.call } /// Listen → understand → the bot answers → it's read aloud → listen again. pub(super) fn call_poll(&mut self, ctx: &egui::Context) { let Some((bot_id, phase)) = self.att.call else { return }; ctx.request_repaint_after(std::time::Duration::from_millis(150)); match phase { CallPhase::Listening => { if self.att.call_rec.is_none() { match crate::voice::listen() { Ok(r) => self.att.call_rec = Some(r), Err(e) => { self.att.error = Some(e); self.call_end(); } } return; } 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 via = self.voice_via(); 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 = via.hear(&f, &lang); let _ = std::fs::remove_file(&f); t }); let _ = tx.send(r); c.request_repaint(); }); self.att.call = Some((bot_id, CallPhase::Transcribing)); } } CallPhase::Transcribing => { let Some(rx) = &self.att.call_rx else { return }; if let Ok(r) = rx.try_recv() { self.att.call_rx = None; match r { Ok(t) if !t.trim().is_empty() => { self.drafts.insert(bot_id, t); self.send(ctx, bot_id); self.att.call = Some((bot_id, CallPhase::Thinking)); } // Nothing said: keep listening; a real error ends the call. Err(e) if !e.contains("沒有聽到") && !e.contains("沒有錄到") => { self.att.error = Some(e); self.call_end(); } _ => self.att.call = Some((bot_id, CallPhase::Listening)), } } } CallPhase::Thinking => { if !self.streams.contains_key(&bot_id) && !self.approvals.contains_key(&bot_id) { let answer = self.state.bot(bot_id).and_then(|b| b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty())).map(|m| m.text.clone()); // Answers are read here, not by the 朗讀 switch (no double reading). if let Some(a) = answer { self.read_aloud(bot_id, &a); } self.att.call = Some((bot_id, CallPhase::Speaking)); } } CallPhase::Speaking => { if !crate::voice::speaking() { // A read-aloud that failed ends the call, said under the box. if self.vo.note.lock().unwrap().is_some() { self.call_end(); } else { self.att.call = Some((bot_id, CallPhase::Listening)); } } } } } // ---------- 設定 › 語音 ---------- pub(super) fn voice_settings(&mut self, ui: &mut egui::Ui) { let p = self.pal; hint(ui, t("語音由大腦處理:每台電腦和手機都把錄音送到這裡設定的服務轉成文字,朗讀也一樣。沒有設定時,麥克風、語音聊天、會議錄音和朗讀都不會出現。"), p); if self.mir.on { hint(ui, t("這些是大腦的設定,改了會存在大腦上;金鑰也只放在大腦。"), p); } ui.add_space(4.0); let mut v = self.state.voice.clone(); setting_card(ui, p, |ui| { setting_title(ui, "聽", "把你說的話變成文字:語音輸入、語音聊天和會議錄音都用它。", p); engine_form(ui, p, &mut v.listen, false, "listen"); if v.listen.kind != VoiceKind::Off { let ok = speech::resolve(&v.listen, &self.state, false).is_some(); ui.add_space(4.0); self.status_line(ui, ok, speech::missing(&v.listen, false)); if ok { self.listen_test(ui); } } }); ui.add_space(10.0); setting_card(ui, p, |ui| { setting_title(ui, "說", "把回答唸出來:朗讀和語音聊天都用它。", p); engine_form(ui, p, &mut v.speak, true, "speak"); if v.speak.kind == VoiceKind::Off { return; } self.voice_picker(ui, &mut v.speak.voice, "speak-voice"); let ok = speech::resolve(&v.speak, &self.state, true).is_some(); ui.add_space(4.0); self.status_line(ui, ok, speech::missing(&v.speak, true)); if !ok { return; } ui.horizontal(|ui| { if ui.button(t("試聽")).clicked() { let via = self.voice_via(); let voice = v.speak.voice.clone(); *self.vo.test_note.lock().unwrap() = None; crate::voice::say(move || via.sound(SAMPLE, &voice, "", 1.0), self.vo.test_note.clone()); } if crate::voice::speaking() { chat_ui::spinner(ui, 14.0, p.text3); ui.ctx().request_repaint_after(std::time::Duration::from_millis(200)); } if let Some(e) = self.vo.test_note.lock().unwrap().clone() { ui.label(RichText::new(e).size(FONT_XS).color(p.danger)); } }); }); if v != self.state.voice { self.state.voice = v; self.mark(); } } fn status_line(&self, ui: &mut egui::Ui, ok: bool, why: &str) { let p = self.pal; let (mark, text, col) = if ok { ("✓", t("可以用"), Color32::from_rgb(0x2e, 0xa0, 0x43)) } else { ("·", t(why), p.text3) }; ui.label(RichText::new(format!("{mark} {text}")).size(FONT_SM).color(col)); } /// 試試看: record a sentence, show what the service heard. fn listen_test(&mut self, ui: &mut egui::Ui) { let p = self.pal; if let Some(rx) = &self.vo.test_rx { if let Ok(r) = rx.try_recv() { self.vo.test_rx = None; self.vo.test_said = Some(r); } } ui.horizontal(|ui| { if self.vo.test_rec.is_some() { if ui.button(t("● 說完了")).clicked() { let rec = self.vo.test_rec.take().unwrap(); let via = self.voice_via(); let (tx, rx) = channel(); self.vo.test_rx = Some(rx); let c = ui.ctx().clone(); std::thread::spawn(move || { let r = rec.finish().and_then(|f| { let t = via.hear(&f, ""); let _ = std::fs::remove_file(&f); t }); let _ = tx.send(r); c.request_repaint(); }); } ui.label(RichText::new(t("正在錄音:說一句話,再按「說完了」")).size(FONT_XS).color(p.text3)); ui.ctx().request_repaint_after(std::time::Duration::from_millis(200)); } else if self.vo.test_rx.is_some() { chat_ui::spinner(ui, 14.0, p.text3); ui.label(RichText::new(t("聽懂中…")).size(FONT_XS).color(p.text3)); ui.ctx().request_repaint_after(std::time::Duration::from_millis(200)); } else if ui.button(t("試試看(說一句話)")).clicked() { crate::voice::stop_speaking(); self.vo.test_said = None; match crate::voice::start() { Ok(r) => self.vo.test_rec = Some(r), Err(e) => self.vo.test_said = Some(Err(e)), } } }); match &self.vo.test_said { Some(Ok(text)) if text.is_empty() => { ui.label(RichText::new(t("沒有聽到說話。")).size(FONT_SM).color(p.text3)); } Some(Ok(text)) => { ui.label(RichText::new(format!("{}「{text}」", t("聽到:"))).size(FONT_SM).color(p.text)); } Some(Err(e)) => { ui.label(RichText::new(e).size(FONT_SM).color(p.danger)); } None => {} } } /// The voice: picked from what the service offers (loaded when asked), or typed. pub(super) fn voice_picker(&mut self, ui: &mut egui::Ui, voice: &mut String, salt: &str) { let p = self.pal; if let Some(rx) = &self.vo.voices_rx { if let Ok(r) = rx.try_recv() { self.vo.voices_rx = None; match r { Ok(list) => { self.vo.voice_list = list; self.vo.voices_err.clear(); } Err(e) => self.vo.voices_err = e, } } } ui.horizontal(|ui| { ui.label(RichText::new(t("聲音")).size(FONT_SM).color(p.text2)); ui.add(egui::TextEdit::singleline(voice).hint_text(t("留空:服務預設的聲音")).desired_width(200.0)); if !self.vo.voice_list.is_empty() { egui::ComboBox::from_id_salt(salt).selected_text(t("選一個…")).height(320.0).show_ui(ui, |ui| { for (id, name) in &self.vo.voice_list { let label = if name.is_empty() || name == id { id.clone() } else { format!("{name}({id})") }; if ui.selectable_label(voice == id, label).clicked() { *voice = id.clone(); } } }); } else if self.vo.voices_rx.is_some() { chat_ui::spinner(ui, 14.0, p.text3); } else if ui.button(t("載入聲音清單")).clicked() { let via = self.voice_via(); let (tx, rx) = channel(); self.vo.voices_rx = Some(rx); let c = ui.ctx().clone(); std::thread::spawn(move || { let _ = tx.send(via.voices()); c.request_repaint(); }); } }); if !self.vo.voices_err.is_empty() { ui.label(RichText::new(&self.vo.voices_err).size(FONT_XS).color(p.text3)); } } } /// One side of 設定 › 語音: which service, and how to reach it. fn engine_form(ui: &mut egui::Ui, p: Palette, e: &mut VoiceEngine, speak: bool, salt: &str) { ui.horizontal(|ui| { ui.label(RichText::new(t("服務")).size(FONT_SM).color(p.text2)); egui::ComboBox::from_id_salt(("voice-kind", salt)).selected_text(t(speech::label(e.kind))).show_ui(ui, |ui| { for k in [VoiceKind::Off, VoiceKind::OpenAi, VoiceKind::Xai, VoiceKind::ElevenLabs] { if ui.selectable_label(e.kind == k, t(speech::label(k))).clicked() && e.kind != k { // Another service: its own address, model and voice (the key may carry over // only when it was borrowed, i.e. empty). *e = VoiceEngine { kind: k, ..Default::default() }; } } }); }); let field = |ui: &mut egui::Ui, label: &str, v: &mut String, hint_text: &str, secret: bool| { ui.horizontal(|ui| { ui.label(RichText::new(t(label)).size(FONT_SM).color(p.text2)); ui.add(egui::TextEdit::singleline(v).hint_text(t(hint_text)).password(secret).desired_width(f32::INFINITY)); }); }; match e.kind { VoiceKind::Off => {} VoiceKind::OpenAi => { ui.horizontal(|ui| { ui.label(RichText::new(t("快速填入")).size(FONT_SM).color(p.text2)); // (base, listen model, speak model, speak voice) let presets: [(&str, &str, &str, &str, &str); 3] = [ ("OpenAI", "", "", "", ""), ("Groq", "https://api.groq.com/openai/v1", "whisper-large-v3-turbo", "", ""), // `make server` with voice (speaches). It can't say Chinese, so only for 聽. ("自己的伺服器", "http://voice:8000/v1", "deepdml/faster-whisper-large-v3-turbo-ct2", "", ""), ]; for (name, base, lm, sm, sv) in presets { if speak && name != "OpenAI" { continue; } if ui.small_button(t(name)).clicked() { e.base_url = base.into(); e.model = if speak { sm.into() } else { lm.into() }; if speak { e.voice = sv.into(); } } } }); field(ui, "網址", &mut e.base_url, "留空:OpenAI(https://api.openai.com/v1)", false); field(ui, "金鑰", &mut e.api_key, "留空:OpenAI 用 設定 › 模型 的金鑰;自己的伺服器可以不用", true); field(ui, "模型", &mut e.model, if speak { "留空:gpt-4o-mini-tts(OpenAI)/tts-1" } else { "留空:OpenAI 用最新的轉文字模型/whisper-1" }, false); } VoiceKind::Xai => { field(ui, "金鑰", &mut e.api_key, "留空:用 設定 › 模型 › xAI 的金鑰", true); } VoiceKind::ElevenLabs => { field(ui, "金鑰", &mut e.api_key, "ElevenLabs 的 API 金鑰", true); field(ui, "模型", &mut e.model, if speak { "留空:eleven_multilingual_v2" } else { "留空:scribe_v2" }, false); } } }