AnyBot/src/app/voice_ui.rs

601 lines
27 KiB
Rust
Raw Normal View History

Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
// 語音 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<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.
test_note: Arc<Mutex<Option<String>>>,
/// The voices 說 offers (loaded when asked).
voices_rx: Option<Receiver<Result<Vec<(String, String)>, 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<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 {
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
Ok(a) => self.remote_cmd(ctx, Cmd::Send { bot, text: MEETING_ASK.into(), attachments: vec![a.path], from: String::new(), memories: None }),
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
// 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", "", ""),
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
];
for (name, base, lm, sm, sv) in presets {
if speak && name != "OpenAI" {
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
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);
}
}
}