// 語音 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; use crate::theme::sp; /// 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(), memories: None, member: false }), // 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(); } } } } // ---------- 朗讀 ---------- /// 朗讀每個回答: the answer of a turn that just ended well, read on this computer. Not in a /// call (it reads its own answers), and not on a brain without a window: nobody hears it there, /// and a server's voice service would be paid for nothing. pub(super) fn read_reply(&mut self, bot_id: u64) { if self.demo || self.headless || !self.can_speak() { return; } let in_call = self.call_state().map(|c| c.0 == bot_id).unwrap_or(false); let answer = self.state.bot(bot_id).filter(|b| b.speak_replies && !in_call).and_then(|b| b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty() && !m.error)).map(|m| m.text.clone()); if let Some(a) = answer { self.read_aloud(bot_id, &a); } } /// 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); // Before sending: here the answer's (empty) message is added at once. self.att.call_from = self.state.bot(bot_id).map(|b| b.messages.len()).unwrap_or(0); self.send(ctx, bot_id); self.att.call_asked = Some(std::time::Instant::now()); self.att.call_seen = false; 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) { self.att.call_seen = true; return; } // Read the answer to what was just said: one after it in the chat. On a screen of a // brain the question goes to the brain first and the bot shows up as working only a // moment later; until then "not working" isn't "done", and the last answer in the // chat is the one before (it was read instead, and the new one never). let answer = self.state.bot(bot_id).and_then(|b| call_answer(&b.messages, self.att.call_from)); if let Some(a) = answer { // Answers are read here, not by the 朗讀 switch (no double reading). self.read_aloud(bot_id, &a); self.att.call = Some((bot_id, CallPhase::Speaking)); } else if self.att.call_seen || self.att.call_asked.map(|t| t.elapsed() > CALL_NO_START).unwrap_or(true) { // It worked and said nothing, or the question never got going: listen again. self.att.call = Some((bot_id, CallPhase::Listening)); } } 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; let mut v = self.state.voice.clone(); // One group like every settings page: 聽 and 說 are rows with their service on the right; // the fields a service needs unfold under its row, each name above its box. section(ui, "語音服務", p); rows_card(ui, p, |ui| { let ok = speech::resolve(&v.listen, &self.state, false).is_some(); let status = engine_status(&v.listen, ok, false); card_row(ui, p, "聽(語音轉文字)", &status, "把你說的話變成文字:語音輸入、語音聊天和會議錄音都用它。每台電腦和手機的錄音都送到大腦,由這裡選的服務轉成文字。", |ui| engine_picker(ui, &mut v.listen, "listen")); if v.listen.kind != VoiceKind::Off { engine_fields(ui, p, &mut v.listen, false); if ok { self.listen_test(ui); } ui.add_space(sp::S3); } let ok = speech::resolve(&v.speak, &self.state, true).is_some(); let status = engine_status(&v.speak, ok, true); card_row(ui, p, "說(朗讀)", &status, "把回答唸出來:朗讀和語音聊天都用它。每台電腦和手機的朗讀都由大腦用這裡選的服務產生。", |ui| engine_picker(ui, &mut v.speak, "speak")); if v.speak.kind != VoiceKind::Off { engine_fields(ui, p, &mut v.speak, true); self.voice_field(ui, &mut v.speak.voice, "speak-voice"); if ok { self.speak_test(ui, &v.speak.voice); } ui.add_space(sp::S3); } }); ui.add_space(sp::S2); hint(ui, "沒選服務時,麥克風、語音聊天、會議錄音和朗讀都不會出現。", p); if self.mir.on { hint(ui, "這些是大腦的設定,改了會存在大腦上;金鑰也只放在大腦。", p); } if v != self.state.voice { self.state.voice = v; self.mark(); } } /// 試聽: the sample sentence in the chosen voice. fn speak_test(&mut self, ui: &mut egui::Ui, voice: &str) { let p = self.pal; ui.add_space(sp::S3); ui.horizontal(|ui| { if ui.add(secondary_button("試聽")).clicked() { let via = self.voice_via(); let voice = voice.to_string(); *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.add(egui::Label::new(RichText::new(e).size(FONT_XS).color(p.danger)).truncate()); } }); } /// 試試看: 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.add_space(sp::S3); ui.horizontal(|ui| { if self.vo.test_rec.is_some() { if ui.add(secondary_button("● 說完了")).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.add(secondary_button("試試看(說一句話)")).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)), } } }); if self.vo.test_said.is_some() { ui.add_space(sp::S1); } 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; self.voices_poll(); // Somewhere narrow (the bot's side panel) the box gets a line of its own: the one long row // was wider than the panel, and that pushed the whole panel under the chat. if ui.available_width() < VOICE_ROW_MIN_WIDTH { ui.horizontal(|ui| { ui.label(RichText::new(t("聲音")).size(FONT_SM).color(p.text2)); ui.with_layout(Layout::right_to_left(Align::Center), |ui| self.voice_list_button(ui, voice, salt)); }); ui.add(egui::TextEdit::singleline(voice).hint_text(t("留空:服務預設的聲音")).desired_width(f32::INFINITY)); } else { 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)); self.voice_list_button(ui, voice, salt); }); } if !self.vo.voices_err.is_empty() { ui.label(RichText::new(&self.vo.voices_err).size(FONT_XS).color(p.text3)); } } /// 設定 › 語音's 聲音: a field like the others (its name above), the box and the list button. fn voice_field(&mut self, ui: &mut egui::Ui, voice: &mut String, salt: &str) { let p = self.pal; self.voices_poll(); form_row(ui, "聲音", p, |ui| { ui.with_layout(Layout::right_to_left(Align::Center), |ui| { self.voice_list_button(ui, voice, salt); ui.add(egui::TextEdit::singleline(voice).hint_text(t("留空:服務預設的聲音")).desired_width(ui.available_width())); }); }); if !self.vo.voices_err.is_empty() { ui.add(egui::Label::new(RichText::new(&self.vo.voices_err).size(FONT_XS).color(p.text3)).truncate()); } } /// The list of voices, when it has come. fn voices_poll(&mut self) { 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, } } } } /// 「選一個…」 once the service's voices are loaded, 「載入聲音清單」 before. fn voice_list_button(&mut self, ui: &mut egui::Ui, voice: &mut String, salt: &str) { let p = self.pal; 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(); }); } } } /// The answer to what was said in a call: the last thing the bot wrote after message `from` (the /// chat's length when it was sent), never an answer from before it. fn call_answer(msgs: &[Message], from: usize) -> Option { msgs.iter().skip(from).rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty()).map(|m| m.text.clone()) } /// How long a call waits for the bot to start on what was said before it listens again (a brain /// reached through the account server shows it working within a second or two). const CALL_NO_START: std::time::Duration = std::time::Duration::from_secs(45); /// Room the one-row voice picker needs (聲音, a 200 px box, 載入聲音清單); narrower, it takes two. const VOICE_ROW_MIN_WIDTH: f32 = 360.0; /// The service menu on 聽's and 說's rows: wide enough for 「OpenAI 相容」 and 「xAI(Grok)」. const VOICE_KIND_WIDTH: f32 = 140.0; /// 聽's or 說's line under its name: nothing when off, else whether it works or what it lacks. fn engine_status(e: &VoiceEngine, ok: bool, speak: bool) -> String { match (e.kind, ok) { (VoiceKind::Off, _) => String::new(), (_, true) => t("可以用"), (_, false) => t(speech::missing(e, speak)), } } /// Which service (the control at the right end of 聽's or 說's row). fn engine_picker(ui: &mut egui::Ui, e: &mut VoiceEngine, salt: &str) { egui::ComboBox::from_id_salt(("voice-kind", salt)).selected_text(t(speech::label(e.kind))).width(VOICE_KIND_WIDTH).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() }; } } }); } /// How to reach the chosen service: its fields under its row, each name above its box. fn engine_fields(ui: &mut egui::Ui, p: Palette, e: &mut VoiceEngine, speak: bool) { let field = |ui: &mut egui::Ui, label: &str, v: &mut String, placeholder: &str, secret: bool| { form_row(ui, label, p, |ui| { ui.add(egui::TextEdit::singleline(v).hint_text(t(placeholder)).password(secret).desired_width(ui.available_width())); }); }; match e.kind { VoiceKind::Off => {} VoiceKind::OpenAi => { form_row(ui, "快速填入", p, |ui| { // (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.add(secondary_button(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); } } } #[cfg(test)] mod tests { use super::*; #[test] fn a_call_reads_the_new_answer_never_the_one_before() { let mut msgs = vec![Message::user("第一句"), Message::assistant("上一個回答", "")]; let from = msgs.len(); // Sent: on a screen of a brain only the question is there at first, and the bot isn't // working yet. The answer before must not be taken for this one. msgs.push(Message::user("第二句")); assert_eq!(call_answer(&msgs, from), None); // Here: the answer's message is added empty at once, then fills in. msgs.push(Message::assistant("", "")); assert_eq!(call_answer(&msgs, from), None); msgs.last_mut().unwrap().text = "新的回答".into(); assert_eq!(call_answer(&msgs, from).as_deref(), Some("新的回答")); } }