819 lines
37 KiB
Rust
819 lines
37 KiB
Rust
// 語音 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;
|
||
use std::hash::{Hash, Hasher};
|
||
|
||
/// 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<String, String> {
|
||
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<Vec<u8>, 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<Vec<(String, String)>, 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<Mutex<Option<String>>>,
|
||
/// 會議錄音 being turned into text here (on the brain): (bot, answer).
|
||
meetings: Vec<(u64, Receiver<Result<String, String>>)>,
|
||
/// 設定 › 語音 › 試試看: recording, then waiting for its text, then what was heard.
|
||
test_rec: Option<crate::voice::Recording>,
|
||
test_rx: Option<Receiver<Result<String, String>>>,
|
||
test_said: Option<Result<String, String>>,
|
||
/// 試聽's trouble, or a picked voice's, and which 聲音 row it belongs under.
|
||
test_note: Arc<Mutex<Option<String>>>,
|
||
test_note_at: String,
|
||
/// The voices 說 offers: fetched the first time a 聲音 menu opens, kept until 說 changes.
|
||
voices_rx: Option<Receiver<Result<Vec<(String, String)>, String>>>,
|
||
voice_list: Vec<(String, String)>,
|
||
voices_err: String,
|
||
/// Which 說 (service, address, key) the list is for.
|
||
voices_for: u64,
|
||
/// The list (or why there is none) came this frame: an open menu is measured again.
|
||
voices_arrived: bool,
|
||
/// The layer the last 聲音 menu was drawn on (to measure it again, before it draws).
|
||
menu_layer: Option<egui::LayerId>,
|
||
}
|
||
|
||
/// What a 聲音 row shows and offers.
|
||
pub(super) struct VoiceRow {
|
||
/// The chosen voice by name, or what an empty choice means.
|
||
pub(super) shown: String,
|
||
/// 「預設(eve)」, the menu's first item; none when there is nothing to fall back on
|
||
/// (ElevenLabs: a voice must be picked).
|
||
default: Option<String>,
|
||
/// The voice an empty choice speaks in (played when 預設 is picked).
|
||
fallback: String,
|
||
}
|
||
|
||
/// Where 設定 › 語音's 試聽 and 聲音 put their trouble.
|
||
const SETTINGS_NOTE: &str = "settings";
|
||
|
||
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<Instant> {
|
||
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);
|
||
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() {
|
||
self.voice_preview(voice, SETTINGS_NOTE);
|
||
}
|
||
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.voice_note(SETTINGS_NOTE) {
|
||
ui.add(egui::Label::new(RichText::new(&e).size(FONT_XS).color(p.danger)).truncate()).on_hover_text(e);
|
||
}
|
||
});
|
||
}
|
||
|
||
/// 試試看: 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 sample sentence in `voice` (empty: what 說 uses unasked); trouble shows under the row
|
||
/// named `at`.
|
||
pub(super) fn voice_preview(&mut self, voice: &str, at: &str) {
|
||
let via = self.voice_via();
|
||
let voice = voice.to_string();
|
||
*self.vo.test_note.lock().unwrap() = None;
|
||
self.vo.test_note_at = at.to_string();
|
||
crate::voice::say(move || via.sound(SAMPLE, &voice, "", 1.0), self.vo.test_note.clone());
|
||
}
|
||
|
||
/// What went wrong playing a voice, when it was played from the row named `at`.
|
||
pub(super) fn voice_note(&self, at: &str) -> Option<String> {
|
||
(self.vo.test_note_at == at).then(|| self.vo.test_note.lock().unwrap().clone()).flatten()
|
||
}
|
||
|
||
/// A 聲音 row: the chosen voice by name, or 「預設(…)」 for an empty one. `inherit` is what an
|
||
/// empty choice falls back to before the service's own voice (a bot's: 設定 › 語音's).
|
||
pub(super) fn voice_row(&mut self, ctx: &egui::Context, voice: &str, inherit: &str) -> VoiceRow {
|
||
self.voices_poll();
|
||
// (Here, before the menu draws: the menu saves its own size at the end of its frame.)
|
||
if let (true, Some(layer)) = (self.vo.voices_arrived, self.vo.menu_layer) {
|
||
remeasure_menu(ctx, layer);
|
||
}
|
||
let kind = self.state.voice.speak.kind;
|
||
// Fetched as the row shows, not when its menu opens: the menu then opens with them (and
|
||
// ElevenLabs' ids like 21m00Tcm4TlvDq8ikWAM show as names). Once per 說.
|
||
self.voices_want(ctx);
|
||
let fallback = if inherit.is_empty() { speech::usual_voice(kind).unwrap_or_default().to_string() } else { inherit.to_string() };
|
||
let default = (!fallback.is_empty()).then(|| format!("{}({})", t("預設"), self.voice_name(&fallback)));
|
||
let shown = if !voice.is_empty() {
|
||
self.voice_name(voice)
|
||
} else {
|
||
default.clone().unwrap_or_else(|| t("還沒選"))
|
||
};
|
||
VoiceRow { shown, default, fallback }
|
||
}
|
||
|
||
/// The 聲音 menu: 「預設(…)」, then the voices the service offers (fetched the first time it
|
||
/// opens). With no list (the service has none, or it failed) the name is typed instead.
|
||
/// Picking one plays the sample sentence in it; trouble shows under the row named `at`.
|
||
pub(super) fn voice_menu(&mut self, ui: &mut egui::Ui, voice: &mut String, row: &VoiceRow, at: &str) {
|
||
let p = self.pal;
|
||
self.voices_want(ui.ctx());
|
||
self.vo.menu_layer = Some(ui.layer_id());
|
||
ui.set_min_width(VOICE_MENU_WIDTH);
|
||
let mut picked = None;
|
||
if let Some(d) = &row.default {
|
||
if ui.selectable_label(voice.is_empty(), d).clicked() {
|
||
picked = Some(String::new());
|
||
}
|
||
}
|
||
// A name typed before (one the list doesn't have) still shows as the chosen one.
|
||
if !voice.is_empty() && !self.vo.voice_list.is_empty() && !self.vo.voice_list.iter().any(|(id, _)| id == voice) {
|
||
let _ = ui.selectable_label(true, voice.as_str());
|
||
}
|
||
for (id, name) in &self.vo.voice_list {
|
||
if ui.selectable_label(voice == id, voice_label(id, name)).clicked() {
|
||
picked = Some(id.clone());
|
||
}
|
||
}
|
||
if self.vo.voices_rx.is_some() {
|
||
ui.horizontal(|ui| {
|
||
chat_ui::spinner(ui, 14.0, p.text3);
|
||
ui.label(RichText::new(t("正在載入聲音…")).size(FONT_SM).color(p.text3));
|
||
});
|
||
} else if !self.vo.voices_err.is_empty() {
|
||
ui.add_space(sp::S1);
|
||
ui.add(egui::Label::new(RichText::new(&self.vo.voices_err).size(FONT_XS).color(p.text3)).wrap());
|
||
// (A width of its own: in a menu, "as wide as there is room" has no end.)
|
||
ui.add(egui::TextEdit::singleline(voice).hint_text(t("輸入聲音名稱")).desired_width(ui.available_width().min(VOICE_MENU_WIDTH)));
|
||
if ui.add(egui::Button::new(RichText::new(t("再試一次")).size(FONT_XS).color(p.text2)).frame(false)).clicked() {
|
||
// (The next frame fetches it again.)
|
||
self.vo.voices_err.clear();
|
||
}
|
||
}
|
||
if let Some(v) = picked {
|
||
let play = if v.is_empty() { row.fallback.clone() } else { v.clone() };
|
||
*voice = v;
|
||
if !play.is_empty() {
|
||
self.voice_preview(&play, at);
|
||
}
|
||
ui.close();
|
||
}
|
||
}
|
||
|
||
/// 設定 › 語音 › 說's 聲音: a field like the others (its name above), the menu in it.
|
||
fn voice_field(&mut self, ui: &mut egui::Ui, voice: &mut String) {
|
||
let p = self.pal;
|
||
let row = self.voice_row(ui.ctx(), voice, "");
|
||
form_row(ui, "聲音", p, |ui| {
|
||
egui::ComboBox::from_id_salt("speak-voice")
|
||
.selected_text(RichText::new(&row.shown).size(FONT_SM))
|
||
.width(ui.available_width())
|
||
.height(VOICE_MENU_HEIGHT)
|
||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||
.show_ui(ui, |ui| self.voice_menu(ui, voice, &row, SETTINGS_NOTE));
|
||
});
|
||
}
|
||
|
||
/// The voice's name from the service's list (ElevenLabs': "Rachel"), else as given.
|
||
fn voice_name(&self, id: &str) -> String {
|
||
self.vo.voice_list.iter().find(|(v, _)| v == id).map(|(v, name)| voice_label(v, name)).unwrap_or_else(|| id.to_string())
|
||
}
|
||
|
||
/// Fetch the voices, unless they are here, coming, or just failed (「再試一次」 clears that).
|
||
fn voices_want(&mut self, ctx: &egui::Context) {
|
||
if !self.vo.voice_list.is_empty() || self.vo.voices_rx.is_some() || !self.vo.voices_err.is_empty() {
|
||
return;
|
||
}
|
||
let via = self.voice_via();
|
||
let (tx, rx) = channel();
|
||
self.vo.voices_rx = Some(rx);
|
||
let c = ctx.clone();
|
||
std::thread::spawn(move || {
|
||
let _ = tx.send(via.voices());
|
||
c.request_repaint();
|
||
});
|
||
}
|
||
|
||
/// The list of voices, when it has come; dropped when 說 is changed (another service, address
|
||
/// or key offers other voices).
|
||
fn voices_poll(&mut self) {
|
||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||
let e = &self.state.voice.speak;
|
||
(e.kind, &e.base_url, &e.api_key).hash(&mut h);
|
||
let now = h.finish();
|
||
self.vo.voices_arrived = false;
|
||
if now != self.vo.voices_for {
|
||
self.vo.voices_for = now;
|
||
self.vo.voice_list.clear();
|
||
self.vo.voices_err.clear();
|
||
self.vo.voices_rx = None;
|
||
}
|
||
if let Some(rx) = &self.vo.voices_rx {
|
||
if let Ok(r) = rx.try_recv() {
|
||
self.vo.voices_rx = None;
|
||
self.vo.voices_arrived = true;
|
||
match r {
|
||
Ok(list) if list.is_empty() => self.vo.voices_err = t("這個服務沒有列出聲音。"),
|
||
Ok(list) => {
|
||
self.vo.voice_list = list;
|
||
self.vo.voices_err.clear();
|
||
}
|
||
Err(e) => self.vo.voices_err = e,
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Let an open menu take its new size: egui keeps a menu the height it opened at, so the list or
|
||
/// the 「輸入聲音名稱」 field arriving under 「正在載入聲音…」 was cut off.
|
||
fn remeasure_menu(ctx: &egui::Context, layer: egui::LayerId) {
|
||
if let Some(mut st) = egui::AreaState::load(ctx, layer.id) {
|
||
st.size = None;
|
||
ctx.memory_mut(|m| m.areas_mut().set_state(layer, st));
|
||
ctx.request_repaint();
|
||
}
|
||
}
|
||
|
||
/// A voice in the menu: its name when the service gives one, else its id.
|
||
fn voice_label(id: &str, name: &str) -> String {
|
||
if name.trim().is_empty() {
|
||
id.to_string()
|
||
} else {
|
||
name.to_string()
|
||
}
|
||
}
|
||
|
||
/// 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<String> {
|
||
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);
|
||
|
||
/// The 聲音 menu: wide enough for 「預設(Rachel)」 and a typed name, tall enough for ElevenLabs' list.
|
||
const VOICE_MENU_WIDTH: f32 = 220.0;
|
||
const VOICE_MENU_HEIGHT: f32 = 320.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("新的回答"));
|
||
}
|
||
}
|