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.
This commit is contained in:
王性驊 2026-11-10 22:58:18 +08:00
parent 70b208e1bd
commit 40d1d9707a
14 changed files with 1560 additions and 675 deletions

View File

@ -1245,25 +1245,39 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 聊天裡你的訊息上方顯示附件;點一下用預設的 App 打開。
- Bot 工作中送出附件時,文字內容會補充給正在進行的工作(圖片要等下一回合)。
### 語音設定(設定 › 語音)
- 語音是獨立的設定,分成「聽」(把你說的話轉成文字)和「說」(把回答唸出來),各自選一個服務:關閉、OpenAI 相容(OpenAI、Groq、自己架的 Whisper 伺服器,看網址)、xAI(Grok)、ElevenLabs。
- 金鑰留空時,借用「設定 › 模型」裡同一家的金鑰(xAI;OpenAI 的網址才借 OpenAI 的)。自己架的伺服器可以不用金鑰。
- 全部在大腦處理:每台電腦和手機只負責錄音和播放,錄音送到大腦轉文字,朗讀的聲音也由大腦產生,所以每一台的結果都一樣;金鑰只放在大腦。
- **沒有設定時,麥克風、語音聊天、會議錄音、朗讀都不會出現**;設定好就自動出現在每台電腦和手機上。
- 每一邊顯示「✓ 可以用」或缺什麼;「聽」有「試試看(說一句話)」,「說」有「試聽」和「載入聲音清單」。
- 中文辨識結果會轉成繁體和台灣用語(xAI 和 Whisper 常回簡體);日文不轉。
- 從舊版升級:原本有 OpenAI 金鑰(語音輸入本來就能用)的人,「聽」自動設成 OpenAI;其他人預設關閉。舊的 macOS 聲音名稱(美佳…)會清掉。
- OpenAI 的轉文字模型依序試 gpt-transcribe、gpt-4o-mini-transcribe、whisper-1(後兩個 OpenAI 在 2027-02-26 停用)。
### 語音輸入
- 輸入框的麥克風圖示:按一下開始錄音,變成紅色閃爍的「● 分:秒 完成」;再按一下停止,顯示「轉成文字…」,完成後文字放進輸入框(接在原本的文字後面),由你檢查後送出。
- 錄音用 macOS 內建的錄音功能,不用另外安裝。第一次 macOS 會問麥克風權限;被拒絕時 AnyBot 會打開「系統設定 → 隱私權與安全性 → 麥克風」。
- 轉文字用「設定 → AI 供應商 → OpenAI」的金鑰(依序試 gpt-4o-mini-transcribe、whisper-1)。沒有金鑰時會說明要去哪裡填。
- 輸入框的麥克風圖示(設定好「聽」才有):按一下開始錄音,變成紅色閃爍的「● 分:秒 完成」;再按一下停止,顯示「轉成文字…」,完成後文字放進輸入框(接在原本的文字後面),由你檢查後送出。
- Mac 用內建的錄音功能,不用另外安裝;第一次 macOS 會問麥克風權限,被拒絕時 AnyBot 會打開「系統設定 → 隱私權與安全性 → 麥克風」。手機用瀏覽器錄音。
- 最長 10 分鐘(估計值),到了自動停止。
### 語音聊天(朗讀回答)
### 會議錄音
- 輸入框的喇叭圖示:打開後,這個 Bot 每次回答完都會用 macOS 內建語音唸出來(中文用台灣的「美佳」)。標題、粗體、連結會整理成好唸的文字,程式碼只說「程式碼略過」。
- 正在唸的時候按喇叭會停止這一段;開始語音輸入時也會先停。再按一次(沒在唸時)就關閉朗讀。
- 搭配語音輸入,就能用說的跟 Bot 來回對話。每個 Bot 各自記住開或關。
- Bot 選單或對話詳細資訊的「加入會議」:最長 2 小時。結束後錄音交給大腦,大腦在背景轉成文字,再把文字記錄當附件交給這個 Bot 整理重點、決定和待辦(不受帳號伺服器一次 35 秒的限制)。轉不成時,Bot 的對話裡會說原因。
### 朗讀回答
- 對話詳細資訊 › 語音聊天 ›「朗讀每個回答」(設定好「說」才有):這個 Bot 每次回答完就唸出來。標題、粗體、連結會整理成好唸的文字,程式碼只說「程式碼略過」;太長的回答只唸前 4,000 字。
- 每個 Bot 可以有自己的聲音(留空就用語音設定的)、速度、語言。
- 手機:長按 Bot 的訊息 →「唸出來」。
### 通話模式(即時語音對話)
- 聊天頂部的「通話」:開始後不用按任何鍵。AnyBot 一直聽,你講完(安靜 1.2 秒,估計值)就停止錄音、轉成文字、送給 Bot;Bot 回答後用語音唸出來,唸完再繼續聽。30 秒沒人說話就繼續等下一句。
- 頂部紅色按鈕顯示目前在做什麼:「● 正在聽… / 聽懂中… / 想一下… / 正在說… 結束通話」,按一下結束。
- Bot 要你允許某個操作時,會等你按完再繼續。轉文字用 OpenAI 的金鑰;聲音偵測用 macOS 錄音器的音量(大於 −38 dB 算有說話,估計值)。
- 原版用 xAI 的即時語音服務;AnyBot 是「聽 → 回答 → 唸」的輪流方式,不能在 Bot 說話時插話(按結束或喇叭可以打斷)。
- 輸入框右邊的語音聊天按鈕(「聽」和「說」都設定好才有):開始後不用按任何鍵。AnyBot 一直聽,你講完(安靜 1.2 秒,估計值)就停止錄音、轉成文字、送給 Bot;Bot 回答後唸出來,唸完再繼續聽。30 秒沒人說話就繼續等下一句。
- 輸入框旁顯示目前在做什麼:「正在聽… / 聽懂中… / 想一下… / 正在說…」,按紅色按鈕結束。
- Bot 要你允許某個操作時,會等你按完再繼續。聲音偵測用錄音的音量(大於 −38 dB 算有說話,估計值)。
- 是「聽 → 回答 → 唸」的輪流方式,不能在 Bot 說話時插話(按結束可以打斷)。
### 分享 Bot(匯出、匯入)

View File

@ -497,6 +497,7 @@ const LUCIDE = {
"trash": '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
"reply": '<polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/>',
"smile-plus": '<path d="M22 11v1a10 10 0 1 1-9-10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" x2="9.01" y1="9" y2="9"/><line x1="15" x2="15.01" y1="9" y2="9"/><path d="M16 5h6"/><path d="M19 2v6"/>',
"audio-lines": '<path d="M2 10v3"/><path d="M6 6v11"/><path d="M10 3v18"/><path d="M14 8v7"/><path d="M18 5v13"/><path d="M22 10v3"/>',
"mic": '<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/>',
"arrow-up": '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',
"arrow-down": '<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',
@ -576,7 +577,7 @@ function phoneTheme() { try { return localStorage.getItem("anybot.theme") || "";
function applyTheme() { const t = phoneTheme(); if (t) document.documentElement.dataset.theme = t; else delete document.documentElement.dataset.theme; }
applyTheme();
const S = {
const S = { voice: {},
relay: false, token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "",
version: 0, bots: [], approvals: [], pages: [], models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner",
open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, audit: {}, settings: null, polling: false,
@ -798,6 +799,7 @@ async function start() {
function apply(v) {
S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac;
S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.models = v.models || []; S.sections = v.sections || null; S.role = v.role || "owner";
S.voice = v.voice || {}; micShown();
const t = cur();
if (t.v === "home") renderHome();
else if (t.v === "chat") { chatHead(); loadChat(); renderDock(); }
@ -1126,6 +1128,7 @@ function msgMenu(i) {
const m = S.msgs[i]; if (!m) return;
const items = [];
if (m.text) items.push({icon: "copy", label: "複製", on: () => copyText(m.text)});
if (m.text && m.role !== "user" && S.voice.speak) items.push({icon: "audio-lines", label: "唸出來", on: () => speakText(m.text)});
if (m.text && owner()) items.push({icon: "reply", label: "引用回覆", on: () => { S.quote = {text: plain(m.text).slice(0, 300), raw: m.text}; renderQuote(); $("input").focus(); }});
if (m.text && owner() && m.role === "user") items.push({icon: "sparkles", label: "教我做(學這一回合)", on: async () => { if (await app("skillify", {prompt: plain(m.text).slice(0, 200)}, 0, "已存成技能,下次說名字就會照做")) again(); }});
const lastBot = [...S.msgs].reverse().find((x) => x.role !== "user" && x.text);
@ -1231,19 +1234,55 @@ function renderChips() {
$("chips").querySelectorAll("button").forEach((b) => b.onclick = () => { S.pending.splice(+b.dataset.i, 1); renderChips(); });
renderSendBtn();
}
// 語音輸入: the phone's own speech recognition writes into the box (nothing is recorded here).
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
// 語音輸入: record here; the brain's voice service (設定 › 語音) turns it into text, the same as
// on every screen. The mic shows only when the brain says it can hear.
const CAN_REC = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia && window.MediaRecorder);
// The brain writes Mandarin in Traditional characters for a Traditional Chinese phone.
const UI_LANG = /^zh-(tw|hk|mo|hant)/i.test(navigator.language || "") ? "zh-TW" : (navigator.language || "");
let rec = null;
if (!SR) $("b-mic").style.display = "none";
$("b-mic").onclick = () => {
function micShown() { $("b-mic").style.display = S.voice.listen && CAN_REC ? "" : "none"; }
micShown();
$("b-mic").onclick = async () => {
if (rec) { rec.stop(); return; }
rec = new SR(); rec.lang = "zh-TW"; rec.interimResults = true; rec.continuous = true;
const before = input.value ? input.value + " " : "";
rec.onresult = (e) => { input.value = before + [...e.results].map((r) => r[0].transcript).join(""); input.dispatchEvent(new Event("input")); };
rec.onend = () => { rec = null; $("b-mic").classList.remove("rec"); $("b-mic").title = "開始語音輸入"; };
rec.onerror = (e) => { if (e.error !== "aborted") toast(e.error === "not-allowed" ? "沒有允許使用麥克風" : "語音輸入停了"); };
try { rec.start(); $("b-mic").classList.add("rec"); $("b-mic").title = "停止聽寫"; toast("正在聆聽…"); } catch (_) { rec = null; }
let stream;
try { stream = await navigator.mediaDevices.getUserMedia({audio: true}); } catch (_) { toast("沒有允許使用麥克風"); return; }
const type = ["audio/webm;codecs=opus", "audio/mp4", "audio/webm", "audio/ogg"].find((t) => MediaRecorder.isTypeSupported && MediaRecorder.isTypeSupported(t)) || "";
const r = new MediaRecorder(stream, type ? {mimeType: type} : {});
const chunks = [];
r.ondataavailable = (e) => { if (e.data && e.data.size) chunks.push(e.data); };
r.onstop = async () => {
stream.getTracks().forEach((t) => t.stop());
rec = null; $("b-mic").classList.remove("rec"); $("b-mic").title = "開始語音輸入";
const mime = r.mimeType || type || "audio/webm";
const ext = mime.includes("mp4") ? "m4a" : mime.includes("ogg") ? "ogg" : "webm";
const blob = new Blob(chunks, {type: mime});
if (blob.size < 1000) { toast("沒有錄到聲音"); return; }
toast("轉成文字中…");
try {
const v = await api(base() + "api/voice/transcribe?name=voice." + ext + "&ui=" + encodeURIComponent(UI_LANG), {method: "POST", body: blob, headers: {"Content-Type": "application/octet-stream"}});
if (!v.text) { toast("沒有聽到說話"); return; }
input.value = (input.value ? input.value + " " : "") + v.text; input.dispatchEvent(new Event("input"));
} catch (err) { toast(err.message); }
};
r.start(); rec = r;
$("b-mic").classList.add("rec"); $("b-mic").title = "停止並轉成文字"; toast("正在錄音…再按一次結束");
};
// 朗讀: the brain's voice service reads a message; the phone only plays it.
let player = null;
async function speakText(text) {
if (player) { player.pause(); player = null; }
// Made while the tap still counts, so the phone lets it play once the sound arrives.
const a = new Audio(); a.play().catch(() => {}); player = a;
toast("準備朗讀…");
try {
const r = await api(base() + "api/voice/speech", {json: {text}, raw: true});
if (!r.ok) { let e = ""; try { e = (await r.json()).error || ""; } catch (_) {} throw new Error(e || "HTTP " + r.status); }
const url = URL.createObjectURL(await r.blob());
if (player !== a) { URL.revokeObjectURL(url); return; }
a.onended = () => URL.revokeObjectURL(url);
a.src = url; await a.play();
} catch (err) { toast(err.message || "朗讀失敗"); }
}
$("b-newchat").onclick = async () => {
if (!await confirmSheet("開始新對話?", "目前的對話會留在「過去的對話」裡。", "開始新對話", false)) return;
try { await api(base() + `api/bots/${S.open}/new`, {json: {}}); S.unfold = {}; toast("已開始新對話"); setTimeout(() => loadChat(true), 500); } catch (e) { toast(e.message); }

View File

@ -36,6 +36,7 @@ mod markdown_ui;
mod welcome_ui;
mod mirror_ui;
mod pages_ui;
mod voice_ui;
// Sidebar rules from index.eager-app: defaults `FT={expandedWidth:280}` (),
// clamp `jT(..,240,400)` (), and the drag rule in `QJe` ():
@ -94,6 +95,7 @@ enum SettingsTab {
Computers,
Review,
Vault,
Voice,
Updates,
Remote,
}
@ -201,6 +203,8 @@ pub struct App {
/// Bot 的電腦 viewer, rebuild dialog and the computers page.
cu: computers_ui::ComputerUi,
vault: vault_ui::VaultUi,
/// 語音: 設定 › 語音, 朗讀 and 會議錄音 on the brain.
vo: voice_ui::VoiceUi,
md: markdown_ui::MdState,
/// The page open large (頁面): its id, and an older revision when looking at one.
page_view: Option<(u64, Option<u32>)>,
@ -341,6 +345,7 @@ impl App {
jump_bottom: None,
cu: Default::default(),
vault: Default::default(),
vo: Default::default(),
md: Default::default(),
page_view: None,
att: Default::default(),
@ -440,6 +445,19 @@ impl App {
app.settings_tab = SettingsTab::Providers;
app.settings_provider = ProviderKind::Anthropic;
}
// 設定 › 語音, set up (voicesettings) or not (voiceoff), and a chat with voice on (voicechat).
Ok(v @ ("voicesettings" | "voiceoff" | "voicechat")) => {
if v != "voiceoff" {
app.state.voice.listen = crate::model::VoiceEngine { kind: crate::model::VoiceKind::Xai, api_key: "xai-demo".into(), ..Default::default() };
app.state.voice.speak = crate::model::VoiceEngine { kind: crate::model::VoiceKind::Xai, api_key: "xai-demo".into(), voice: "eve".into(), ..Default::default() };
}
if v == "voicechat" {
app.state.selected = 1;
} else {
app.show_settings = true;
app.settings_tab = SettingsTab::Voice;
}
}
Ok("editor") => {
app.edit_bot = app.state.bot(5).cloned().map(|mut b| {
b.allow_rules = vec!["edit_file".into(), "shell:npm install".into()];
@ -1198,10 +1216,9 @@ impl App {
}
if outcome == TurnOutcome::Success && !self.demo {
let in_call = self.call_state().map(|c| c.0 == bot_id).unwrap_or(false);
if let Some(b) = self.state.bot(bot_id).filter(|b| b.speak_replies && !in_call) {
if let Some(m) = b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty() && !m.error) {
crate::voice::speak_as(&m.text, &b.voice, b.voice_rate);
}
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.filter(|_| self.can_speak()) {
self.read_aloud(bot_id, &a);
}
}
if outcome == TurnOutcome::Success {
@ -2077,7 +2094,7 @@ impl App {
}
});
}
if menu_ui::item(ui, p, Icon::Record, "錄會議").on_hover_text(t("用麥克風錄下會議,結束後轉成文字記錄交給這個 Bot 整理")).clicked() {
if self.can_listen() && menu_ui::item(ui, p, Icon::Record, "錄會議").on_hover_text(t("用麥克風錄下會議,結束後轉成文字記錄交給這個 Bot 整理")).clicked() {
let ctx = ui.ctx().clone();
self.state.selected = id;
self.start_meeting(&ctx, id);
@ -2697,6 +2714,9 @@ impl App {
if round_tool(ui, crate::icons::Icon::Stop, colour, ink).on_hover_text(t("停止")).clicked() {
self.stop(bot.id);
}
} else if !in_call && !(self.can_listen() && self.can_speak()) {
// No voice set up: no 語音聊天, just the send arrow, resting.
round_tool(ui, crate::icons::Icon::ArrowUp, p.active, p.text3).on_hover_text(t("輸入訊息後傳送"));
} else {
let fill = if in_call { Color32::from_rgb(0xfc, 0x2c, 0x3e) } else { colour };
let tip = match call {
@ -2723,7 +2743,7 @@ impl App {
ctx.request_repaint_after(std::time::Duration::from_millis(100));
} else if self.voice_busy() {
chat_ui::spinner(ui, 18.0, p.text3);
} else if round_tool(ui, crate::icons::Icon::Mic, p.hover, p.text2).on_hover_text(t("開始語音輸入")).clicked() {
} else if self.can_listen() && round_tool(ui, crate::icons::Icon::Mic, p.hover, p.text2).on_hover_text(t("開始語音輸入")).clicked() {
self.voice_toggle(ctx, bot.id);
}
if let Some((id, phase)) = call {
@ -3281,7 +3301,7 @@ impl App {
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
use crate::icons::Icon;
for (tab, name, icon) in [(SettingsTab::General, "一般", Icon::Gear), (SettingsTab::Providers, "模型", Icon::Sparkle), (SettingsTab::Channels, "整合", Icon::Chat), (SettingsTab::Computers, "電腦", Icon::Monitor), (SettingsTab::Review, "權限", Icon::Shield), (SettingsTab::Vault, "保險庫", Icon::Vault), (SettingsTab::Updates, "更新", Icon::CloudDownload)] {
for (tab, name, icon) in [(SettingsTab::General, "一般", Icon::Gear), (SettingsTab::Providers, "模型", Icon::Sparkle), (SettingsTab::Channels, "整合", Icon::Chat), (SettingsTab::Computers, "電腦", Icon::Monitor), (SettingsTab::Review, "權限", Icon::Shield), (SettingsTab::Vault, "保險庫", Icon::Vault), (SettingsTab::Voice, "語音", Icon::Mic), (SettingsTab::Updates, "更新", Icon::CloudDownload)] {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), egui::Sense::click());
let on = self.settings_tab == tab || (tab == SettingsTab::General && self.settings_tab == SettingsTab::Remote);
if on || r.hovered() {
@ -3453,6 +3473,9 @@ impl App {
}
});
}
SettingsTab::Voice => {
egui::ScrollArea::vertical().id_salt("voice-settings").auto_shrink([false, false]).max_height(page_h - 60.0).show(ui, |ui| self.voice_settings(ui));
}
SettingsTab::Vault => {
self.vault_page(ui);
}
@ -3771,6 +3794,8 @@ impl App {
self.channels_poll(ctx);
}
self.remote_tick(ctx);
// 會議錄音 turned into text here go to their bot (a brain on a server has no window).
self.meetings_poll(ctx);
self.tick_routines(ctx);
self.watchdog();
self.poll_fetches();

View File

@ -10,14 +10,14 @@ pub struct AttachUi {
picked: Option<Receiver<(u64, Vec<PathBuf>)>>,
pub(super) thumbs: HashMap<String, Option<egui::TextureHandle>>,
pub error: Option<String>,
voice: Option<(u64, crate::voice::Recording)>,
voice_rx: Option<Receiver<(u64, Result<String, String>)>>,
pub(super) voice: Option<(u64, crate::voice::Recording)>,
pub(super) voice_rx: Option<Receiver<(u64, Result<String, String>)>>,
/// The recording is a meeting (longer; becomes a transcript to summarize).
pub meeting: bool,
/// 通話模式: the bot being talked to, and where the call is.
pub call: Option<(u64, CallPhase)>,
call_rec: Option<crate::voice::Recording>,
call_rx: Option<Receiver<Result<String, String>>>,
pub(super) call_rec: Option<crate::voice::Recording>,
pub(super) call_rx: Option<Receiver<Result<String, String>>>,
}
#[derive(Clone, Copy, PartialEq, Debug)]
@ -207,218 +207,3 @@ impl App {
self.att.pending.get(&bot_id).map(|v| !v.is_empty()).unwrap_or(false)
}
}
// ---------- 語音輸入 ----------
impl App {
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()
}
/// Who turns the person's speech into text: their OpenAI key, else their xAI key.
fn stt(&self) -> Result<crate::voice::Stt, String> {
let side = |k: ProviderKind| {
let ps = self.state.provider(k);
(providers::resolve_base(k, &ps.base_url), providers::resolve_key(k, &ps.api_key))
};
crate::voice::pick_stt(side(ProviderKind::OpenAi), side(ProviderKind::Xai)).ok_or_else(|| crate::voice::NO_STT_KEY.to_string())
}
/// The mic button: start, or stop and turn the recording into text.
pub(super) fn voice_toggle(&mut self, ctx: &egui::Context, bot_id: u64) {
if self.voice_stop(ctx) {
return;
}
// Say so before the person talks, not after (it used to record, then fail for the key).
if let Err(e) = self.stt() {
self.att.error = Some(e);
return;
}
crate::voice::stop_speaking();
match crate::voice::start() {
Ok(r) => self.att.voice = Some((bot_id, r)),
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 stt = self.stt();
let (tx, rx) = channel();
self.att.voice_rx = Some(rx);
let c = ctx.clone();
std::thread::spawn(move || {
let r = rec.finish().and_then(|f| {
let t = stt.and_then(|s| crate::voice::transcribe(&s, &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()
}
/// Put the text where the person was typing.
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 (it was thrown away: two hours of a meeting, gone at the last second).
self.voice_stop(ctx);
self.att.error = Some(format!("錄音最長 {},已經停止;錄到的部分正在轉成文字。", crate::voice::length_words(max)));
}
let Some(rx) = &self.att.voice_rx else { return };
if let Ok((id, r)) = rx.try_recv() {
self.att.voice_rx = None;
let meeting = std::mem::take(&mut self.att.meeting);
match r {
Ok(t) if t.is_empty() => self.att.error = Some("沒有聽到說話。".into()),
Ok(t) if meeting => {
// The transcript goes with the message as a file; the bot is asked to sum it up.
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")));
match std::fs::write(&file, &t).map_err(|e| e.to_string()).and_then(|_| crate::attach::store(id, &file)) {
Ok(a) => {
self.att.pending.entry(id).or_default().push(a);
self.drafts.insert(id, "這是剛才會議的文字記錄,請整理:重點、做了哪些決定、待辦事項(誰、做什麼、什麼時候)。".into());
}
Err(e) => self.att.error = Some(format!("存不了會議記錄:{e}")),
}
}
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),
}
}
}
}
// ---------- 通話模式 ----------
impl App {
pub(super) fn call_start(&mut self, bot_id: u64) {
if let Err(e) = self.stt() {
self.att.error = Some(e);
return;
}
crate::voice::stop_speaking();
self.att.call = Some((bot_id, CallPhase::Listening));
self.att.call_rec = None;
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 stt = self.stt();
let (tx, rx) = channel();
self.att.call_rx = Some(rx);
let c = ctx.clone();
std::thread::spawn(move || {
let r = rec.finish().and_then(|f| {
let t = stt.and_then(|s| crate::voice::transcribe(&s, &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("沒有聽到") => {
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 {
let (v, r) = self.state.bot(bot_id).map(|b| (b.voice.clone(), b.voice_rate)).unwrap_or_default();
crate::voice::speak_as(&a, &v, if r > 0.0 { r } else { 1.0 });
}
self.att.call = Some((bot_id, CallPhase::Speaking));
}
}
CallPhase::Speaking => {
if !crate::voice::speaking() {
self.att.call = Some((bot_id, CallPhase::Listening));
}
}
}
}
}

View File

@ -58,6 +58,16 @@ fn redact(top: &mut Value) {
for c in top["channels"].as_array_mut().into_iter().flatten() {
hide(&mut c["token"]);
}
// 設定 › 語音's own keys (ElevenLabs, or one just for voice).
if let Some(v) = top.get_mut("voice").and_then(Value::as_object_mut) {
for side in ["listen", "speak"] {
if let Some(e) = v.get_mut(side).and_then(Value::as_object_mut) {
if let Some(k) = e.get_mut("api_key") {
hide(k);
}
}
}
}
for m in top["mcp_servers"].as_array_mut().into_iter().flatten() {
for k in ["env", "headers"] {
for v in m[k].as_object_mut().into_iter().flat_map(|o| o.values_mut()) {
@ -1302,9 +1312,13 @@ mod tests {
#[test]
fn keys_stay_on_the_brain() {
let mut v = json!({"remote": {"host_token": "x"}, "providers": {"xai": {"api_key": "sk-1"}, "openai": {"api_key": ""}}, "channels": [{"id": 4, "token": "t"}]});
let mut v = json!({"remote": {"host_token": "x"}, "providers": {"xai": {"api_key": "sk-1"}, "openai": {"api_key": ""}}, "channels": [{"id": 4, "token": "t"}], "voice": {"listen": {"kind": "eleven_labs", "api_key": "el-1"}, "speak": {"kind": "xai", "api_key": ""}}});
let old = v.clone();
redact(&mut v);
assert_eq!((v["voice"]["listen"]["api_key"].as_str(), v["voice"]["speak"]["api_key"].as_str()), (Some(REDACTED), Some("")));
let mut voice = v["voice"].clone();
unredact(&mut voice, &old["voice"]);
assert_eq!(voice["listen"]["api_key"], "el-1");
assert!(v.get("remote").is_none());
assert_eq!(v["providers"]["xai"]["api_key"], REDACTED);
assert_eq!(v["providers"]["openai"]["api_key"], "");

View File

@ -125,7 +125,9 @@ impl App {
panel_card(ui, p, |ui| {
open_channels = panel_row(ui, p, Some(crate::icons::Icon::Chat), &t("新增至 Slack"), "", true).clicked();
new_routine = panel_row(ui, p, Some(crate::icons::Icon::Clock), &t("建立例行工作"), "", true).clicked();
meeting = panel_row(ui, p, Some(crate::icons::Icon::Calendar), &meeting_label, "", true).clicked();
if self.can_listen() || self.meeting_on() {
meeting = panel_row(ui, p, Some(crate::icons::Icon::Calendar), &meeting_label, "", true).clicked();
}
});
if open_channels {
self.show_settings = true;
@ -135,7 +137,12 @@ impl App {
self.drafts.insert(bot.id, t("幫我建立一個例行任務:"));
}
if meeting {
self.voice_toggle(ctx, bot.id);
// (It used to start plain voice input: the meeting ended up in the message box.)
if self.meeting_on() {
self.voice_toggle(ctx, bot.id);
} else {
self.start_meeting(ctx, bot.id);
}
}
// 例行任務 (when it has some)
if !bot.routines.is_empty() {
@ -270,35 +277,30 @@ impl App {
self.edit_bot = Some((bot.clone(), false));
}
}
// 語音聊天: 語音、速度、語言
// 語音聊天: 聲音、速度、語言 (only with 設定 › 語音 set up: no voice, no section).
let (listen, speak) = (self.can_listen(), self.can_speak());
if !listen && !speak {
return;
}
panel_title(ui, "語音聊天", p);
let mut b2 = bot.clone();
let mut changed = false;
panel_card(ui, p, |ui| {
let voices = crate::voice::voices();
let shown = if b2.voice.is_empty() { t("自動") } else { b2.voice.clone() };
panel_select(ui, p, "語音", ("voice", bot.id), &shown, |ui| {
if ui.selectable_label(b2.voice.is_empty(), t("自動(依語言)")).clicked() {
b2.voice.clear();
changed = true;
}
for (name, lang) in voices.iter().take(80) {
if ui.selectable_label(b2.voice == *name, format!("{name} · {lang}")).clicked() {
b2.voice = name.clone();
changed = true;
crate::voice::speak_as(&t("你好,我是你的 Bot。"), name, b2.voice_rate);
if speak {
let before = b2.voice.clone();
ui.add_space(4.0);
Frame::new().inner_margin(Margin::symmetric(10, 0)).show(ui, |ui| self.voice_picker(ui, &mut b2.voice, &format!("bot-voice-{}", bot.id)));
changed |= b2.voice != before;
let rate = if b2.voice_rate > 0.0 { b2.voice_rate } else { 1.0 };
panel_select(ui, p, "速度", ("rate", bot.id), &format!("{}x", trim_rate(rate)), |ui| {
for s in crate::voice::SPEEDS {
if ui.selectable_label((rate - s).abs() < 0.01, format!("{}x", trim_rate(s))).clicked() {
b2.voice_rate = s;
changed = true;
}
}
}
});
let rate = if b2.voice_rate > 0.0 { b2.voice_rate } else { 1.0 };
panel_select(ui, p, "速度", ("rate", bot.id), &format!("{}x", trim_rate(rate)), |ui| {
for s in crate::voice::SPEEDS {
if ui.selectable_label((rate - s).abs() < 0.01, format!("{}x", trim_rate(s))).clicked() {
b2.voice_rate = s;
changed = true;
}
}
});
});
}
let lang_name = crate::voice::SPOKEN.iter().find(|l| l.0 == b2.voice_lang).map(|l| t(l.1)).unwrap_or_else(|| b2.voice_lang.clone());
panel_select(ui, p, "語言", ("lang", bot.id), &lang_name, |ui| {
for (code, name) in crate::voice::SPOKEN {
@ -308,6 +310,9 @@ impl App {
}
}
});
if !speak {
return;
}
// 朗讀回答 (AnyBot: read every answer aloud, not only in a call).
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click());
ui.painter().text(rect.left_center() + vec2(10.0, 0.0), egui::Align2::LEFT_CENTER, t("朗讀每個回答"), egui::FontId::proportional(13.0), p.text);

View File

@ -16,6 +16,8 @@ pub struct RemoteUi {
last_publish: Option<Instant>,
/// The settings the server threads were last given.
pushed: Option<Settings>,
/// And the voice service.
voice: crate::speech::Engines,
pw1: String,
pw2: String,
relay_url: String,
@ -93,6 +95,12 @@ impl App {
return;
}
self.remote_apply_settings();
// 設定 › 語音 with its keys, for the phone's and the screens' recordings.
let voice = crate::speech::Engines::of(&self.state);
if self.rm.voice != voice {
remote::hub().set_voice(voice.clone());
self.rm.voice = voice;
}
for c in remote::hub().take_cmds() {
// A screen of another brain has no bots of its own to run phone requests on.
if self.mir.on && !matches!(c, Cmd::DeviceAdded(_) | Cmd::DeviceSeen(_)) {
@ -349,8 +357,16 @@ impl App {
remote::hub().publish(view);
}
fn remote_cmd(&mut self, ctx: &egui::Context, c: Cmd) {
pub(super) fn remote_cmd(&mut self, ctx: &egui::Context, c: Cmd) {
match c {
Cmd::Meeting { bot, path, lang } => {
// Only a recording the app itself stored (uploaded into its attachments).
let root = crate::model::State::path().parent().map(|p| p.join("attachments")).and_then(|p| p.canonicalize().ok());
match (std::path::Path::new(&path).canonicalize().ok(), root) {
(Some(f), Some(root)) if f.starts_with(&root) && f.is_file() => self.meeting_job(bot, f, lang, true),
_ => {}
}
}
Cmd::Send { bot, text, attachments, from } => {
if self.state.bot(bot).is_none() {
return;

599
src/app/voice_ui.rs Normal file
View File

@ -0,0 +1,599 @@
// 語音 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 {
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", "", ""),
("自己的伺服器", "http://voice:8000/v1", "Systran/faster-whisper-medium", "speaches-ai/Kokoro-82M-v1.0-ONNX", "zf_xiaobei"),
];
for (name, base, lm, sm, sv) in presets {
if speak && name == "Groq" {
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);
}
}
}

View File

@ -83,6 +83,24 @@ pub const ROWS: &[(&str, &str, &str)] = &[
("有更新的版本:", "A newer version is available: ", "新しいバージョンがあります:"),
("已是最新版本", "Up to date", "最新です"),
("回到最新訊息", "Jump to latest", "最新のメッセージへ"),
("聽", "Listen", "聞く"),
("說", "Speak", "話す"),
("服務", "Service", "サービス"),
("金鑰", "Key", "キー"),
("網址", "Address", "アドレス"),
("聲音", "Voice", "声"),
("試聽", "Play a sample", "試聴"),
("可以用", "Ready", "使えます"),
("快速填入", "Fill in", "入力例"),
("載入聲音清單", "Load voices", "声の一覧を読み込む"),
("試試看(說一句話)", "Try it (say something)", "試す(ひとこと話す)"),
("OpenAI 相容", "OpenAI-compatible", "OpenAI 互換"),
("自己的伺服器", "Your own server", "自分のサーバー"),
("輸入訊息後傳送", "Type a message to send", "メッセージを入力して送信"),
("選一個…", "Pick one…", "選ぶ…"),
("聽到:", "Heard: ", "聞き取り:"),
("● 說完了", "● Done", "● 話し終えた"),
("留空:服務預設的聲音", "Empty: the service's usual voice", "空欄:サービスの標準の声"),
("允許在「你的電腦」上執行", "Allow running on “Your computer”", "「あなたのコンピューター」での実行を許可"),
("🔒 由你的管理員設定,無法變更", "🔒 Set by your administrator; can't be changed", "🔒 管理者が設定しているため変更できません"),
("名稱,例如 工作站", "Name, e.g. Workstation", "名前(例:ワークステーション)"),

View File

@ -50,6 +50,7 @@ mod routines;
mod setup;
mod teach;
mod share;
mod speech;
mod teams;
mod theme;
mod tools;

View File

@ -350,6 +350,44 @@ pub enum Accent {
Black,
}
/// 設定 › 語音: who hears the person (聽) and who reads answers aloud (說). It all runs where the
/// keys are, on the brain: every screen and the phone send their recording there and get the
/// answer's sound back, so they behave the same and nothing depends on the device.
#[derive(Clone, Serialize, Deserialize, Debug, Default, PartialEq)]
#[serde(default)]
pub struct VoiceSettings {
pub listen: VoiceEngine,
pub speak: VoiceEngine,
/// Written by an AnyBot that has 設定 › 語音 (false: an older save, see State::load_from).
pub saved: bool,
}
/// One voice service and how to reach it.
#[derive(Clone, Serialize, Deserialize, Debug, Default, PartialEq)]
#[serde(default)]
pub struct VoiceEngine {
pub kind: VoiceKind,
/// OpenAI 相容: the server's address ending in /v1 (empty: OpenAI's own).
pub base_url: String,
/// Empty: the key under 設定 › 模型 for the same service (xAI; OpenAI at its own address).
pub api_key: String,
/// Empty: the service's usual model.
pub model: String,
/// 說: the voice (empty: the service's usual one).
pub voice: String,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Default, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum VoiceKind {
#[default]
Off,
/// Anything with OpenAI's audio API: OpenAI, Groq, a Whisper server of your own.
OpenAi,
Xai,
ElevenLabs,
}
#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct ProviderSettings {
#[serde(default)]
@ -458,6 +496,9 @@ pub struct State {
/// 語言: "auto" (follow the Mac) or one of i18n::LANGS.
#[serde(default = "auto_lang")]
pub language: String,
/// 設定 › 語音.
#[serde(default)]
pub voice: VoiceSettings,
}
fn auto_lang() -> String {
@ -555,6 +596,7 @@ impl State {
}
};
s.drop_untouched_samples();
s.carry_voice_over();
for b in s.bots.iter_mut() {
b.repair_interrupted();
}
@ -611,6 +653,23 @@ impl State {
/// Older versions started with five sample bots. If they are all still there and were never
/// used (no chat, routine or memory, nothing renamed) and there is nothing else, it is a fresh
/// install: start empty, with the guide, like a new one.
/// A save from before 設定 › 語音: voice input worked through the OpenAI key, so whoever had
/// one keeps it (as 聽 = OpenAI); everyone else starts with voice off. Once.
pub fn carry_voice_over(&mut self) {
if self.voice.saved {
return;
}
self.voice.saved = true;
// A bot's voice was a macOS one (美佳…), which no voice service knows.
for b in self.bots.iter_mut() {
b.voice.clear();
}
let openai = crate::providers::resolve_key(crate::providers::ProviderKind::OpenAi, &self.provider(crate::providers::ProviderKind::OpenAi).api_key);
if self.voice.listen.kind == VoiceKind::Off && !openai.is_empty() {
self.voice.listen = VoiceEngine { kind: VoiceKind::OpenAi, ..Default::default() };
}
}
pub fn drop_untouched_samples(&mut self) {
let samples = Self::sample_bots();
let untouched = |b: &Bot| {
@ -779,6 +838,7 @@ impl State {
messages_no_ask: false,
loose_index: None,
folded: vec![],
voice: VoiceSettings { saved: true, ..Default::default() },
}
}

View File

@ -134,6 +134,8 @@ pub enum Cmd {
RestoreThread { bot: u64, index: usize },
/// 清除聊天記錄 from a screen of this brain (the chat lives here).
Clear { bot: u64 },
/// 會議錄音 from a screen (uploaded here first): turn it into text, then hand it to the bot.
Meeting { bot: u64, path: String, lang: String },
/// A new phone signed in (to remember), or one was signed out.
DeviceAdded(Device),
DeviceSeen(String),
@ -165,6 +167,8 @@ pub struct Hub {
fails: Mutex<HashMap<String, (u32, Instant)>>,
relay_status: Mutex<String>,
sync: Mutex<Vec<SyncReq>>,
/// 設定 › 語音 with its keys: what the phone's and the screens' recordings go through.
voice: Mutex<crate::speech::Engines>,
}
/// 大腦: another AnyBot of this account (a screen) asks for what changed, or sends its edits.
@ -185,7 +189,7 @@ pub struct SyncReq {
pub fn hub() -> &'static Hub {
static H: OnceLock<Hub> = OnceLock::new();
H.get_or_init(|| Hub { view: Mutex::new(View::default()), changed: Condvar::new(), cmds: Mutex::new(vec![]), repaint: Mutex::new(None), settings: Mutex::new(Settings::default()), fails: Mutex::new(HashMap::new()), relay_status: Mutex::new(String::new()), sync: Mutex::new(vec![]) })
H.get_or_init(|| Hub { view: Mutex::new(View::default()), changed: Condvar::new(), cmds: Mutex::new(vec![]), repaint: Mutex::new(None), settings: Mutex::new(Settings::default()), fails: Mutex::new(HashMap::new()), relay_status: Mutex::new(String::new()), sync: Mutex::new(vec![]), voice: Mutex::new(Default::default()) })
}
static VERSION: AtomicU64 = AtomicU64::new(1);
@ -232,6 +236,12 @@ impl Hub {
pub fn settings(&self) -> Settings {
self.settings.lock().unwrap().clone()
}
pub fn set_voice(&self, v: crate::speech::Engines) {
*self.voice.lock().unwrap() = v;
}
pub fn voice(&self) -> crate::speech::Engines {
self.voice.lock().unwrap().clone()
}
pub fn relay_status(&self) -> String {
self.relay_status.lock().unwrap().clone()
}
@ -393,6 +403,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
"pages": pages,
"models": if role == "member" { vec![] } else { v.models.clone() },
"sections": v.sections,
// 語音: the mic shows only when this brain can hear (and read aloud).
"voice": {"listen": hub().voice().listen.is_some(), "speak": hub().voice().speak.is_some()},
}))
}
// 頁面: the whole page (or an older version with ?rev=N), and its charts drawn as SVG.
@ -473,6 +485,14 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
hub().push(cmd);
Resp::json(&json!({"ok": true}))
}
// 語音: the phone's and the screens' recordings become text here, and answers sound.
("POST", ["api", "voice", "transcribe"] | ["api", "sync", "voice", "transcribe"]) => voice_transcribe(&req),
("POST", ["api", "voice", "speech"] | ["api", "sync", "voice", "speech"]) => voice_speech(&req),
("POST", ["api", "sync", "voice", "voices"]) => match hub().voice().speak.map(|e| crate::speech::voices(&e)) {
Some(Ok(v)) => Resp::json(&json!({"voices": v})),
Some(Err(err)) => Resp::error(502, &err),
None => Resp::error(409, crate::speech::NOT_SET),
},
("GET", ["api", "screen", which]) => screen(which, &s),
("POST", ["api", "screen", which]) => screen_input(which, &req.json(), &s),
("POST", ["api", "device", "run"]) => device_run(&req.json(), &s, via_relay, req.header("x-anybot-from")),
@ -559,6 +579,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
"resume" => Cmd::Resume { bot },
"restore" => Cmd::RestoreThread { bot, index: b["index"].as_u64().unwrap_or(0) as usize },
"clear" => Cmd::Clear { bot },
"meeting" => Cmd::Meeting { bot, path: b["path"].as_str().unwrap_or("").to_string(), lang: b["lang"].as_str().unwrap_or("").to_string() },
_ => return Resp::error(404, "沒有這個動作"),
};
hub().push(cmd);
@ -585,6 +606,31 @@ fn phone_act(action: &str, body: Value, role: &str) -> Resp {
}
}
/// A recording (the body; ?name=voice.webm says its format, ?lang= the spoken language, ?ui=
/// the asker's window language) → {text}, through 設定 › 語音's 聽.
fn voice_transcribe(req: &Req) -> Resp {
let Some(e) = hub().voice().listen else { return Resp::error(409, crate::speech::NOT_SET) };
// Only the format from the name the asker gave.
let ext = req.query.get("name").and_then(|n| n.rsplit('.').next()).filter(|x| ["m4a", "mp4", "webm", "wav", "ogg", "opus", "mp3", "flac"].contains(&x.to_ascii_lowercase().as_str())).unwrap_or("m4a").to_ascii_lowercase();
let lang = req.query.get("lang").cloned().unwrap_or_default();
let ui = req.query.get("ui").cloned().unwrap_or_else(crate::i18n::lang);
match crate::speech::transcribe(&e, &req.body, &format!("voice.{ext}"), &lang, &ui) {
Ok(text) => Resp::json(&json!({"text": text})),
Err(err) => Resp::error(502, &err),
}
}
/// {text, voice, lang, speed} → MP3, through 設定 › 語音's 說.
fn voice_speech(req: &Req) -> Resp {
let Some(e) = hub().voice().speak else { return Resp::error(409, crate::speech::NOT_SET) };
let b = req.json();
let text = b["text"].as_str().unwrap_or("");
match crate::speech::speak(&e, text, b["voice"].as_str().unwrap_or(""), b["lang"].as_str().unwrap_or(""), b["speed"].as_f64().unwrap_or(1.0) as f32) {
Ok(mp3) => Resp::bytes("audio/mpeg", mp3),
Err(err) => Resp::error(502, &err),
}
}
/// The bots' computer's screen, small (the phone's 電腦 card and a hand-off), as JPEG.
fn box_thumb() -> Resp {
let Some(img) = crate::cloudbox::thumbnail(480) else { return Resp::error(404, "Bot 的電腦沒有開著") };
@ -603,7 +649,7 @@ pub fn role_allows(role: &str, method: &str, path: &[&str]) -> bool {
// 大腦: the owner's other AnyBots showing this one's bots.
"mirror" => sync,
"owner" | "admin" => !device && !sync,
"member" => matches!((method, path), ("GET", ["api", "state"]) | ("GET", ["api", "bots", _]) | ("GET", ["api", "pages", ..]) | ("GET", ["api", "file"]) | ("POST", ["api", "bots", _, "send" | "read" | "upload"])),
"member" => matches!((method, path), ("GET", ["api", "state"]) | ("GET", ["api", "bots", _]) | ("GET", ["api", "pages", ..]) | ("GET", ["api", "file"]) | ("POST", ["api", "bots", _, "send" | "read" | "upload"]) | ("POST", ["api", "voice", "transcribe" | "speech"])),
_ => false,
}
}
@ -1404,6 +1450,27 @@ pub fn sync_upload(s: &Settings, bot: u64, name: &str, bytes: &[u8]) -> Result<S
v["path"].as_str().map(String::from).ok_or("大腦沒有收下檔案".into())
}
/// 語音 on the brain: a recording (`name` says its format) → its text.
pub fn sync_voice_transcribe(s: &Settings, audio: &[u8], name: &str, lang: &str) -> Result<String, String> {
let v = to_brain(s, "POST", "/voice/transcribe", &[("name", name.to_string()), ("lang", lang.to_string()), ("ui", crate::i18n::lang())], audio, 60)?;
Ok(v["text"].as_str().unwrap_or("").to_string())
}
/// 語音 on the brain: {text, voice, lang, speed} → MP3.
pub fn sync_voice_speech(s: &Settings, body: &Value) -> Result<Vec<u8>, String> {
let (st, bytes) = to_brain_raw(s, "POST", "/voice/speech", &[], body.to_string().as_bytes(), 60)?;
if st == 200 {
return Ok(bytes);
}
Err(answer_value(st, &bytes, "大腦").err().unwrap_or_else(|| format!("大腦的語音服務失敗(HTTP {st})")))
}
/// 語音 on the brain: the voices its 說 service offers, (id, name).
pub fn sync_voice_voices(s: &Settings) -> Result<Vec<(String, String)>, String> {
let v = to_brain(s, "POST", "/voice/voices", &[], b"{}", 30)?;
Ok(v["voices"].as_array().into_iter().flatten().filter_map(|x| Some((x[0].as_str()?.to_string(), x[1].as_str().unwrap_or("").to_string()))).collect())
}
/// The brain's bots' computer as a JPEG (`thumb`: the small picture that never wakes it).
pub fn sync_screen(s: &Settings, thumb: bool) -> Result<Vec<u8>, String> {
let (st, bytes) = to_brain_raw(s, "GET", "/screen", &[("thumb", if thumb { "1" } else { "0" }.to_string())], &[], 30)?;
@ -1703,6 +1770,58 @@ pub fn page() -> Resp {
mod tests {
use super::*;
fn voice_req(path: &str, role: &str, body: &[u8]) -> Req {
let (path, q) = path.split_once('?').unwrap_or((path, ""));
let query = q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect();
let headers = [("x-anybot-role".to_string(), role.to_string())].into_iter().collect();
Req { method: "POST".into(), path: path.into(), query, headers, body: body.to_vec(), peer: String::new() }
}
/// The phone's and the screens' recordings go through the brain's 設定 › 語音.
#[test]
fn the_brain_hears_for_the_phone_and_the_screens() {
let server = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://127.0.0.1:{}/v1", server.local_addr().unwrap().port());
let fake = std::thread::spawn(move || {
use std::io::{Read, Write};
for _ in 0..2 {
let (mut s, _) = server.accept().unwrap();
s.set_read_timeout(Some(Duration::from_millis(500))).unwrap();
let (mut buf, mut got) = (vec![0u8; 65536], vec![]);
while let Ok(n) = s.read(&mut buf) {
if n == 0 {
break;
}
got.extend_from_slice(&buf[..n]);
if got.windows(4).any(|w| w == b"--\r\n") {
break;
}
}
let reply = r#"{"text":"帮我开灯"}"#;
let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len()).as_bytes());
}
});
// Not set up: said so, and the phone hides its mic.
hub().set_voice(Default::default());
let r = handle(voice_req("/api/voice/transcribe?name=voice.webm", "owner", &[7u8; 4000]), true);
assert_eq!(r.status, 409);
let e = crate::speech::Engine { kind: crate::model::VoiceKind::Xai, base, key: "k".into(), ..Default::default() };
hub().set_voice(crate::speech::Engines { listen: Some(e), speak: None });
// A member may talk too; the phone says it is a Traditional Chinese one.
let r = handle(voice_req("/api/voice/transcribe?name=voice.webm&ui=zh-TW", "member", &[7u8; 4000]), true);
assert_eq!(r.status, 200, "{}", String::from_utf8_lossy(&r.body));
let v: Value = serde_json::from_slice(&r.body).unwrap();
assert_eq!(v["text"], "幫我開燈");
// A screen of this brain, through the account.
let r = handle(voice_req("/api/sync/voice/transcribe?name=voice.m4a&ui=zh-TW", "mirror", &[7u8; 4000]), true);
assert_eq!(r.status, 200);
// Nothing to read aloud with: 409, not a crash.
let r = handle(voice_req("/api/voice/speech", "owner", br#"{"text":"hi"}"#), true);
assert_eq!(r.status, 409);
fake.join().unwrap();
hub().set_voice(Default::default());
}
#[test]
fn model_requests_go_only_to_private_addresses() {
assert!(private_host("10.184.10.252") && private_host("192.168.1.5") && private_host("localhost") && private_host("nas.local"));

519
src/speech.rs Normal file
View File

@ -0,0 +1,519 @@
// 語音服務: speech to text (聽) and text to speech (說) through an API, run where the keys are
// (the brain). Screens and the phone only record and play; they send the recording here and get
// text back, or send text and get sound (MP3) back. Three kinds of service (設定 › 語音):
// OpenAI 相容 POST {base}/audio/transcriptions, {base}/audio/speech — OpenAI, Groq, a Whisper
// server of your own (speaches); the address decides which
// xAI POST /v1/stt (the file last), /v1/tts
// ElevenLabs POST /v1/speech-to-text (Scribe), /v1/text-to-speech/{voice}
use crate::model::{State, VoiceEngine, VoiceKind};
use crate::providers::{resolve_base, resolve_key, ProviderKind};
use serde_json::{json, Value};
use std::time::Duration;
pub const OPENAI_BASE: &str = "https://api.openai.com/v1";
pub const ELEVENLABS_BASE: &str = "https://api.elevenlabs.io/v1";
/// OpenAI's transcription models, newest first: the 4o ones and whisper-1 stop on 2027-02-26
/// (developers.openai.com/api/docs/deprecations), and an unknown model just tries the next.
pub const OPENAI_LISTEN_MODELS: [&str; 3] = ["gpt-transcribe", "gpt-4o-mini-transcribe", "whisper-1"];
/// Answers longer than this are read only up to here (a chat answer, not a book).
pub const MAX_SPEAK_CHARS: usize = 4000;
pub const NOT_SET: &str = "還沒設定語音:請到「設定 → 語音」選一個服務。";
/// A voice service, ready to call: where, with which key, which model and voice.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Engine {
pub kind: VoiceKind,
pub base: String,
pub key: String,
pub model: String,
pub voice: String,
}
/// What this brain can do with voice right now.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Engines {
pub listen: Option<Engine>,
pub speak: Option<Engine>,
}
impl Engines {
pub fn of(st: &State) -> Engines {
Engines { listen: resolve(&st.voice.listen, st, false), speak: resolve(&st.voice.speak, st, true) }
}
}
/// The service set up in 設定 › 語音 with its key, or None when it can't be called (off, or no
/// key). An empty key borrows 設定 › 模型's for the same service. On a screen the keys read
/// "••••(已設定,在大腦上)": set up, on the brain.
pub fn resolve(e: &VoiceEngine, st: &State, speak: bool) -> Option<Engine> {
let own = e.api_key.trim().to_string();
let borrowed = |k: ProviderKind| if own.is_empty() { resolve_key(k, &st.provider(k).api_key) } else { own.clone() };
let (base, key) = match e.kind {
VoiceKind::Off => return None,
VoiceKind::OpenAi => {
let base = e.base_url.trim().trim_end_matches('/').to_string();
if base.is_empty() || base == OPENAI_BASE {
(OPENAI_BASE.to_string(), borrowed(ProviderKind::OpenAi))
} else {
// A server of your own may need no key at all.
return Some(Engine { kind: e.kind, base, key: own, model: e.model.trim().to_string(), voice: e.voice.trim().to_string() });
}
}
VoiceKind::Xai => (resolve_base(ProviderKind::Xai, &st.provider(ProviderKind::Xai).base_url), borrowed(ProviderKind::Xai)),
VoiceKind::ElevenLabs => (if e.base_url.trim().is_empty() { ELEVENLABS_BASE.to_string() } else { e.base_url.trim().trim_end_matches('/').to_string() }, own),
};
if key.is_empty() {
return None;
}
// ElevenLabs reads with a voice of the person's choosing; there is no usual one.
if speak && e.kind == VoiceKind::ElevenLabs && e.voice.trim().is_empty() {
return None;
}
Some(Engine { kind: e.kind, base, key, model: e.model.trim().to_string(), voice: e.voice.trim().to_string() })
}
/// Why `resolve` gave nothing, in a sentence for 設定 › 語音.
pub fn missing(e: &VoiceEngine, speak: bool) -> &'static str {
match e.kind {
VoiceKind::Off => "關閉",
VoiceKind::OpenAi => "需要 OpenAI 的金鑰(這裡,或 設定 › 模型 › OpenAI)",
VoiceKind::Xai => "需要 xAI 的金鑰(這裡,或 設定 › 模型 › xAI)",
VoiceKind::ElevenLabs if speak && !e.api_key.trim().is_empty() => "選一個聲音",
VoiceKind::ElevenLabs => "需要 ElevenLabs 的金鑰",
}
}
pub fn label(k: VoiceKind) -> &'static str {
match k {
VoiceKind::Off => "關閉",
VoiceKind::OpenAi => "OpenAI 相容",
VoiceKind::Xai => "xAI(Grok)",
VoiceKind::ElevenLabs => "ElevenLabs",
}
}
// ---------- 聽 ----------
/// The recording as text, in the person's Chinese when it was Chinese ([`spoken_in`]).
/// `name` carries the format (voice.m4a, voice.webm, voice.wav…); `lang` is the spoken language
/// ("" = detect); `ui` is the language of the window or phone that asked.
pub fn transcribe(e: &Engine, audio: &[u8], name: &str, lang: &str, ui: &str) -> Result<String, String> {
if audio.len() < 1000 {
return Err("沒有錄到聲音。".into());
}
let text = match e.kind {
VoiceKind::Off => return Err(NOT_SET.into()),
VoiceKind::OpenAi => openai_listen(e, audio, name, lang)?,
VoiceKind::Xai => {
// Options before the file: xAI ignores fields sent after it. `format` (numbers as
// digits) needs a language.
let mut f = vec![];
if !lang.is_empty() {
f.push(("language", lang.to_string()));
f.push(("format", "true".into()));
}
let v = post_form(&format!("{}/stt", e.base), &bearer(&e.key), &f, name, audio, "xAI")?;
text_of(&v)
}
VoiceKind::ElevenLabs => {
let mut f = vec![("model_id", if e.model.is_empty() { "scribe_v2".to_string() } else { e.model.clone() })];
if !lang.is_empty() {
f.push(("language_code", lang.to_string()));
}
let v = post_form(&format!("{}/speech-to-text", e.base), &[("xi-api-key", e.key.clone())], &f, name, audio, "ElevenLabs")?;
text_of(&v)
}
};
Ok(spoken_in(&text, ui, lang))
}
/// OpenAI 相容: the model asked for, or (at OpenAI) the newest that this account has.
fn openai_listen(e: &Engine, audio: &[u8], name: &str, lang: &str) -> Result<String, String> {
let models: Vec<String> = if !e.model.is_empty() {
vec![e.model.clone()]
} else if e.base == OPENAI_BASE {
OPENAI_LISTEN_MODELS.iter().map(|m| m.to_string()).collect()
} else {
vec!["whisper-1".into()]
};
let mut last = String::new();
for m in &models {
let mut f = vec![("model", m.clone()), ("response_format", "json".to_string())];
if !lang.is_empty() {
f.push(("language", lang.to_string()));
}
match post_form(&format!("{}/audio/transcriptions", e.base), &bearer(&e.key), &f, name, audio, "OpenAI 相容") {
Ok(v) => return Ok(text_of(&v)),
// A model this account or server doesn't have: try the next.
Err(err) if err.contains("HTTP 404") || err.contains("HTTP 400") => last = err,
Err(err) => return Err(err),
}
}
Err(last)
}
fn text_of(v: &Value) -> String {
v["text"].as_str().unwrap_or("").trim().to_string()
}
/// Recognisers write Mandarin in Simplified characters (xAI always, Whisper often), and with
/// mainland words (软件 for 軟體): for a Traditional Chinese window, Traditional with Taiwan
/// wording, like the bots' replies. Japanese (it has kana) keeps its own kanji.
pub fn spoken_in(text: &str, ui_lang: &str, spoken: &str) -> String {
let kana = text.chars().any(|c| ('\u{3040}'..='\u{30ff}').contains(&c));
if ui_lang == "zh-TW" && spoken != "ja" && !kana {
zhconv::zhconv(text, zhconv::Variant::ZhTW)
} else {
text.to_string()
}
}
// ---------- 說 ----------
/// `text` read aloud as MP3. `voice` (a bot's own; empty = the one in 設定 › 語音), `lang` the
/// language it is in ("" = let the service tell), `speed` 1.0 = normal.
pub fn speak(e: &Engine, text: &str, voice: &str, lang: &str, speed: f32) -> Result<Vec<u8>, String> {
let words: String = speakable(text).chars().take(MAX_SPEAK_CHARS).collect();
if words.is_empty() {
return Err("沒有可以唸的文字。".into());
}
let voice = if voice.trim().is_empty() { e.voice.clone() } else { voice.trim().to_string() };
let speed = if speed > 0.0 { speed.clamp(0.5, 2.0) } else { 1.0 };
match e.kind {
VoiceKind::Off => Err(NOT_SET.into()),
VoiceKind::OpenAi => {
let at_openai = e.base == OPENAI_BASE;
let model = if !e.model.is_empty() { e.model.clone() } else if at_openai { "gpt-4o-mini-tts".into() } else { "tts-1".into() };
let voice = if voice.is_empty() { "alloy".to_string() } else { voice };
let body = json!({"model": model, "input": words, "voice": voice, "response_format": "mp3", "speed": speed});
post_json(&format!("{}/audio/speech", e.base), &bearer(&e.key), &body, "OpenAI 相容")
}
VoiceKind::Xai => {
let voice = if voice.is_empty() { "eve".to_string() } else { voice };
let lang = if lang.is_empty() { "auto" } else { lang };
let body = json!({"text": words, "voice_id": voice, "language": lang, "output_format": {"codec": "mp3"}, "speed": speed});
post_json(&format!("{}/tts", e.base), &bearer(&e.key), &body, "xAI")
}
VoiceKind::ElevenLabs => {
if voice.is_empty() {
return Err("ElevenLabs 要先選一個聲音(設定 → 語音)。".into());
}
let model = if e.model.is_empty() { "eleven_multilingual_v2".to_string() } else { e.model.clone() };
let mut body = json!({"text": words, "model_id": model});
if (speed - 1.0).abs() > 0.01 {
// (ElevenLabs reads between 0.7× and 1.2×.)
body["voice_settings"] = json!({"speed": speed.clamp(0.7, 1.2)});
}
post_json(&format!("{}/text-to-speech/{}?output_format=mp3_44100_128", e.base, voice), &[("xi-api-key", e.key.clone())], &body, "ElevenLabs")
}
}
}
/// A chat answer as words to say: no Markdown marks, link addresses or code.
pub fn speakable(text: &str) -> String {
let mut out = String::new();
let mut in_code = false;
for line in text.lines() {
let l = line.trim();
if l.starts_with("```") {
in_code = !in_code;
if in_code {
out.push_str("(程式碼略過)\n");
}
continue;
}
if in_code {
continue;
}
let l = l.trim_start_matches(['#', '-', '*', '>', ' ']).replace("**", "").replace('`', "");
let l = l.split("](").next().unwrap_or(&l).replace('[', "");
if !l.is_empty() {
out.push_str(&l);
out.push('\n');
}
}
out.trim().to_string()
}
/// The voices the service offers: (id, what to show).
pub fn voices(e: &Engine) -> Result<Vec<(String, String)>, String> {
match e.kind {
VoiceKind::Off => Err(NOT_SET.into()),
VoiceKind::OpenAi if e.base == OPENAI_BASE => Ok(["alloy", "ash", "ballad", "coral", "echo", "fable", "nova", "onyx", "sage", "shimmer", "verse"].iter().map(|v| (v.to_string(), v.to_string())).collect()),
VoiceKind::OpenAi => Err("這個服務沒有提供聲音清單:請直接填聲音的名稱。".into()),
VoiceKind::Xai => {
let v = get_json(&format!("{}/tts/voices", e.base), &bearer(&e.key), "xAI")?;
Ok(v["voices"].as_array().into_iter().flatten().filter_map(|x| x["voice_id"].as_str()).map(|id| (id.to_string(), id.to_string())).collect())
}
VoiceKind::ElevenLabs => {
let v = get_json(&format!("{}/voices", e.base), &[("xi-api-key", e.key.clone())], "ElevenLabs")?;
Ok(v["voices"].as_array().into_iter().flatten().filter_map(|x| Some((x["voice_id"].as_str()?.to_string(), x["name"].as_str().unwrap_or("").to_string()))).collect())
}
}
}
// ---------- HTTP ----------
fn bearer(key: &str) -> Vec<(&'static str, String)> {
if key.is_empty() {
vec![]
} else {
vec![("Authorization", format!("Bearer {key}"))]
}
}
fn agent() -> ureq::Agent {
ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(120))).http_status_as_error(false).build().into()
}
/// The recording's media type, from its name.
pub fn audio_type(name: &str) -> &'static str {
match name.rsplit('.').next().unwrap_or("").to_ascii_lowercase().as_str() {
"wav" => "audio/wav",
"webm" => "audio/webm",
"ogg" | "opus" => "audio/ogg",
"mp3" => "audio/mpeg",
"flac" => "audio/flac",
_ => "audio/mp4",
}
}
/// A multipart form: the fields, then the audio file last.
pub fn form(fields: &[(&str, String)], file_name: &str, audio: &[u8], boundary: &str) -> Vec<u8> {
let mut b = vec![];
for (k, v) in fields {
b.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n").as_bytes());
}
b.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{file_name}\"\r\nContent-Type: {}\r\n\r\n", audio_type(file_name)).as_bytes());
b.extend_from_slice(audio);
b.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
b
}
fn post_form(url: &str, headers: &[(&str, String)], fields: &[(&str, String)], name: &str, audio: &[u8], who: &str) -> Result<Value, String> {
let boundary = format!("anybot{}", chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0));
let body = form(fields, name, audio, &boundary);
let mut req = agent().post(url).header("Content-Type", &format!("multipart/form-data; boundary={boundary}"));
for (k, v) in headers {
req = req.header(*k, v);
}
let (status, bytes) = answer(req.send(&body[..]), who)?;
serde_json::from_slice(&bytes).map_err(|_| format!("{who} 的回答看不懂(HTTP {status})"))
}
fn post_json(url: &str, headers: &[(&str, String)], body: &Value, who: &str) -> Result<Vec<u8>, String> {
let mut req = agent().post(url).header("Content-Type", "application/json");
for (k, v) in headers {
req = req.header(*k, v);
}
answer(req.send(body.to_string().as_bytes()), who).map(|(_, b)| b)
}
fn get_json(url: &str, headers: &[(&str, String)], who: &str) -> Result<Value, String> {
let mut req = agent().get(url);
for (k, v) in headers {
req = req.header(*k, v);
}
let (_, bytes) = answer(req.call(), who)?;
serde_json::from_slice(&bytes).map_err(|_| format!("{who} 的回答看不懂"))
}
/// The body of a 200, or what went wrong in words.
fn answer(r: Result<ureq::http::Response<ureq::Body>, ureq::Error>, who: &str) -> Result<(u16, Vec<u8>), String> {
let mut r = r.map_err(|e| format!("連不上 {who} 的語音服務:{e}"))?;
let status = r.status().as_u16();
let bytes = r.body_mut().with_config().limit(64 * 1024 * 1024).read_to_vec().unwrap_or_default();
if status == 200 {
return Ok((status, bytes));
}
let said: String = String::from_utf8_lossy(&bytes).chars().take(200).collect();
Err(match status {
401 | 403 => format!("{who} 不接受這把金鑰(HTTP {status}):{said}"),
_ => format!("{who} 的語音服務失敗(HTTP {status}):{said}"),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{ProviderSettings, VoiceSettings};
use std::io::{Read, Write};
/// One request to a local server: what it was sent, and `reply` (with `ctype`) back.
fn serve_once(reply: &'static str, ctype: &'static str) -> (String, std::thread::JoinHandle<String>) {
let server = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://127.0.0.1:{}/v1", server.local_addr().unwrap().port());
let h = std::thread::spawn(move || {
let (mut s, _) = server.accept().unwrap();
s.set_read_timeout(Some(Duration::from_millis(800))).unwrap();
let mut buf = vec![0u8; 65536];
let mut got = vec![];
while let Ok(n) = s.read(&mut buf) {
if n == 0 {
break;
}
got.extend_from_slice(&buf[..n]);
let text = String::from_utf8_lossy(&got);
// The whole request is in: a form's closing line, or a JSON body as long as it said.
let done = text.contains("--\r\n") || text.split_once("\r\n\r\n").map(|(h, b)| {
let len = h.lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length: ").and_then(|v| v.trim().parse::<usize>().ok()));
len.map(|n| b.len() >= n).unwrap_or(h.starts_with("GET"))
}).unwrap_or(false);
if done {
break;
}
}
let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", reply.len()).as_bytes());
let _ = s.write_all(reply.as_bytes());
String::from_utf8_lossy(&got).to_string()
});
(base, h)
}
fn engine(kind: VoiceKind, base: &str, key: &str) -> Engine {
Engine { kind, base: base.into(), key: key.into(), ..Default::default() }
}
fn state_with(voice: VoiceSettings, keys: &[(&str, &str)]) -> State {
let mut st = State::first_run();
st.voice = voice;
for (k, v) in keys {
st.providers.insert(k.to_string(), ProviderSettings { api_key: v.to_string(), ..Default::default() });
}
st
}
#[test]
fn only_a_service_that_can_be_called_is_ready() {
let on = |kind, key: &str| VoiceEngine { kind, api_key: key.into(), ..Default::default() };
// Off, or no key anywhere: not ready (the mic stays hidden).
let st = state_with(VoiceSettings { listen: on(VoiceKind::Xai, ""), ..Default::default() }, &[]);
assert_eq!(Engines::of(&st).listen, None);
assert_eq!(Engines::of(&State::first_run()), Engines::default());
// xAI borrows 設定 › 模型's key.
let st = state_with(VoiceSettings { listen: on(VoiceKind::Xai, ""), ..Default::default() }, &[("xai", "xai-k")]);
let l = Engines::of(&st).listen.unwrap();
assert_eq!((l.base.as_str(), l.key.as_str()), ("https://api.x.ai/v1", "xai-k"));
// Its own key wins.
let st = state_with(VoiceSettings { listen: on(VoiceKind::Xai, "own"), ..Default::default() }, &[("xai", "xai-k")]);
assert_eq!(Engines::of(&st).listen.unwrap().key, "own");
// OpenAI at its own address borrows OpenAI's key; a server of your own needs none.
let st = state_with(VoiceSettings { listen: on(VoiceKind::OpenAi, ""), ..Default::default() }, &[("openai", "sk-o")]);
assert_eq!(Engines::of(&st).listen.unwrap().base, OPENAI_BASE);
let own = VoiceEngine { kind: VoiceKind::OpenAi, base_url: "http://voice:8000/v1/".into(), ..Default::default() };
let st = state_with(VoiceSettings { listen: own, ..Default::default() }, &[]);
assert_eq!(Engines::of(&st).listen.unwrap().base, "http://voice:8000/v1");
// ElevenLabs reads only with a voice picked.
let st = state_with(VoiceSettings { speak: on(VoiceKind::ElevenLabs, "el"), ..Default::default() }, &[]);
assert_eq!(Engines::of(&st).speak, None);
assert_eq!(missing(&st.voice.speak, true), "選一個聲音");
// On a screen the brain's keys read as set.
let st = state_with(VoiceSettings { speak: on(VoiceKind::Xai, "••••(已設定,在大腦上)"), ..Default::default() }, &[]);
assert!(Engines::of(&st).speak.is_some());
}
#[test]
fn an_older_save_keeps_voice_only_where_it_worked() {
let mut st = state_with(VoiceSettings::default(), &[("openai", "sk-o")]);
st.bots = State::samples().bots;
st.bots[0].voice = "Meijia".into();
st.carry_voice_over();
assert_eq!((st.voice.listen.kind, st.voice.speak.kind, st.voice.saved), (VoiceKind::OpenAi, VoiceKind::Off, true));
assert!(st.bots.iter().all(|b| b.voice.is_empty()), "macOS voices mean nothing to a service");
// Only Grok: voice never worked there, so it starts off.
let mut st = state_with(VoiceSettings::default(), &[("xai", "xai-k")]);
st.carry_voice_over();
assert_eq!(st.voice.listen.kind, VoiceKind::Off);
// Once: turned off later, it stays off.
let mut st = state_with(VoiceSettings { saved: true, ..Default::default() }, &[("openai", "sk-o")]);
st.carry_voice_over();
assert_eq!(st.voice.listen.kind, VoiceKind::Off);
assert!(State::first_run().voice.saved);
}
#[test]
fn mandarin_comes_back_in_the_windows_chinese() {
let heard = "帮我把手机里的照片依照月份整理好,软件更新完再提醒我";
assert_eq!(spoken_in(heard, "zh-TW", ""), "幫我把手機裡的照片依照月份整理好,軟體更新完再提醒我");
assert_eq!(spoken_in("会議は明日です", "zh-TW", ""), "会議は明日です");
assert_eq!(spoken_in("会议", "zh-TW", "ja"), "会议");
assert_eq!(spoken_in(heard, "en", ""), heard);
// A word-by-word converter: 里 it doesn't know as 裡 stays 里, never 公裡.
assert_eq!(spoken_in("三公里", "zh-TW", ""), "三公里");
}
#[test]
fn xai_hears_with_the_options_before_the_file() {
let (base, seen) = serve_once(r#"{"text":"明天下午三点开会","language":"zh-cn"}"#, "application/json");
let text = transcribe(&engine(VoiceKind::Xai, &base, "xai-k"), &[7u8; 2048], "voice.webm", "zh", "zh-TW").unwrap();
let req = seen.join().unwrap();
assert_eq!(text, "明天下午三點開會");
assert!(req.starts_with("POST /v1/stt") && req.contains("Bearer xai-k") && req.contains("Content-Type: audio/webm"));
let (lang, fmt, file) = (req.find("name=\"language\"\r\n\r\nzh").unwrap(), req.find("name=\"format\"\r\n\r\ntrue").unwrap(), req.find("name=\"file\"").unwrap());
assert!(lang < file && fmt < file);
}
#[test]
fn openai_compatible_and_elevenlabs_hear() {
let (base, seen) = serve_once(r#"{"text":"hello there"}"#, "application/json");
let mut e = engine(VoiceKind::OpenAi, &base, "");
e.model = "Systran/faster-whisper-medium".into();
assert_eq!(transcribe(&e, &[7u8; 2048], "voice.m4a", "", "en").unwrap(), "hello there");
let req = seen.join().unwrap();
assert!(req.starts_with("POST /v1/audio/transcriptions") && req.contains("faster-whisper-medium") && !req.contains("Authorization"));
let (base, seen) = serve_once(r#"{"text":"ok","language_code":"en"}"#, "application/json");
assert_eq!(transcribe(&engine(VoiceKind::ElevenLabs, &base, "el-k"), &[7u8; 2048], "voice.wav", "en", "en").unwrap(), "ok");
let req = seen.join().unwrap();
assert!(req.starts_with("POST /v1/speech-to-text") && req.to_ascii_lowercase().contains("xi-api-key: el-k") && req.contains("scribe_v2"));
// Too short to be speech: not sent at all.
assert!(transcribe(&engine(VoiceKind::Xai, "http://127.0.0.1:1", "k"), &[0u8; 10], "voice.m4a", "", "zh-TW").unwrap_err().contains("沒有錄到"));
}
#[test]
fn speaking_sends_the_words_and_gets_mp3() {
let (base, seen) = serve_once("ID3fake-mp3", "audio/mpeg");
let mp3 = speak(&engine(VoiceKind::Xai, &base, "xai-k"), "## 好的\n- **已經**整理好了 [看](https://x.y)", "", "zh", 1.0).unwrap();
assert_eq!(mp3, b"ID3fake-mp3");
let req = seen.join().unwrap();
let body: Value = serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap();
assert!(req.starts_with("POST /v1/tts"));
assert_eq!((body["text"].as_str(), body["voice_id"].as_str(), body["language"].as_str(), body["output_format"]["codec"].as_str()), (Some("好的\n已經整理好了 看"), Some("eve"), Some("zh"), Some("mp3")));
let (base, seen) = serve_once("ID3x", "audio/mpeg");
let mut e = engine(VoiceKind::OpenAi, &base, "k");
e.voice = "zf_xiaobei".into();
speak(&e, "你好", "", "", 1.25).unwrap();
let req = seen.join().unwrap();
let body: Value = serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap();
assert!(req.starts_with("POST /v1/audio/speech"));
assert_eq!((body["voice"].as_str(), body["response_format"].as_str(), body["speed"].as_f64()), (Some("zf_xiaobei"), Some("mp3"), Some(1.25)));
// A bot's own voice wins; ElevenLabs puts it in the address.
let (base, seen) = serve_once("ID3y", "audio/mpeg");
let mut e = engine(VoiceKind::ElevenLabs, &base, "el");
e.voice = "default-voice".into();
speak(&e, "hi", "bot-voice", "", 1.0).unwrap();
assert!(seen.join().unwrap().starts_with("POST /v1/text-to-speech/bot-voice?output_format=mp3"));
}
/// The real xAI, both ways: `ANYBOT_TEST_XAI_KEY=… cargo test --bin anybot xai_for_real -- --ignored`.
#[test]
#[ignore]
fn xai_for_real() {
let key = std::env::var("ANYBOT_TEST_XAI_KEY").expect("ANYBOT_TEST_XAI_KEY");
let e = engine(VoiceKind::Xai, "https://api.x.ai/v1", &key);
let mp3 = speak(&e, "好的,我已經把下載資料夾裡的照片整理好了,軟體也更新完了。", "", "zh", 1.0).unwrap();
assert!(mp3.len() > 10_000, "{} bytes", mp3.len());
let heard = transcribe(&e, &mp3, "voice.mp3", "zh", "zh-TW").unwrap();
assert!(heard.contains("照片") && heard.contains("軟體") && !heard.contains("软"), "{heard}");
assert!(!voices(&e).unwrap().is_empty());
}
#[test]
fn answers_are_cleaned_for_speaking() {
let t = "## 行程\n- **上午**:赤崁樓\n```\nls -la\n```\n看 [地圖](https://x.y)";
assert_eq!(speakable(t), "行程\n上午:赤崁樓\n(程式碼略過)\n看 地圖");
assert_eq!(audio_type("voice.webm"), "audio/webm");
assert_eq!(audio_type("voice.M4A"), "audio/mp4");
}
}

View File

@ -1,7 +1,7 @@
// 語音輸入: hold a short recording from the microphone, turn it into text, put it in the message
// box (the original: 聽寫 / transcribeAudio through its server). Here the recording uses macOS's
// own AVAudioRecorder (through osascript, no extra install) and the text comes from the person's
// own key: OpenAI's /audio/transcriptions, or xAI's /stt when only Grok is set up.
// 語音 on this device: only recording from the microphone and playing sound. What was said is
// turned into text, and answers into sound, by the brain's voice service (speech.rs), the same
// for every screen and the phone. macOS records with its own AVAudioRecorder (through osascript,
// no extra install); elsewhere cpal does (mic.rs).
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
@ -21,9 +21,6 @@ pub fn length_words(secs: u64) -> String {
}
}
/// Transcription models tried in order.
pub const MODELS: [&str; 2] = ["gpt-4o-mini-transcribe", "whisper-1"];
const RECORDER: &str = r#"ObjC.import('AVFoundation');
ObjC.import('Foundation');
function run(argv) {
@ -205,415 +202,89 @@ impl Recording {
}
}
/// Same, telling the service the spoken language (ISO 639-1, e.g. "zh"; empty = detect).
pub fn multipart_lang(model: &str, file_name: &str, audio: &[u8], boundary: &str, lang: &str) -> Vec<u8> {
let mut fields = vec![("model", model), ("response_format", "json")];
if !lang.is_empty() {
fields.push(("language", lang));
}
form(&fields, file_name, audio, boundary)
}
/// A multipart form: the fields, then the audio file last.
fn form(fields: &[(&str, &str)], file_name: &str, audio: &[u8], boundary: &str) -> Vec<u8> {
let mut b = vec![];
for (k, v) in fields {
b.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n").as_bytes());
}
let kind = if file_name.ends_with(".wav") { "audio/wav" } else { "audio/mp4" };
b.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{file_name}\"\r\nContent-Type: {kind}\r\n\r\n").as_bytes());
b.extend_from_slice(audio);
b.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
b
}
/// Who turns speech into text, with whose key.
#[derive(Clone, Debug, PartialEq)]
pub enum Stt {
/// OpenAI's /audio/transcriptions ([`MODELS`] in order).
OpenAi { base: String, key: String },
/// xAI's /stt (Grok's speech to text).
Xai { base: String, key: String },
}
pub const NO_STT_KEY: &str = "語音轉文字要用 OpenAI 或 xAI(Grok)的金鑰:請到「設定 → AI 供應商」填入其中一個。";
/// OpenAI's when it has a key, else xAI's: (base URL, key) of each. None: neither has a key.
pub fn pick_stt(openai: (String, String), xai: (String, String)) -> Option<Stt> {
if !openai.1.trim().is_empty() {
return Some(Stt::OpenAi { base: openai.0, key: openai.1.trim().to_string() });
}
if !xai.1.trim().is_empty() {
return Some(Stt::Xai { base: xai.0, key: xai.1.trim().to_string() });
}
None
}
/// Speech to text, in the window's Chinese when it was Chinese ([`spoken_in`]).
pub fn transcribe(stt: &Stt, file: &std::path::Path, lang: &str) -> Result<String, String> {
let text = match stt {
Stt::OpenAi { base, key } => transcribe_lang(base, key, file, lang)?,
Stt::Xai { base, key } => transcribe_xai(base, key, file, lang)?,
};
Ok(spoken_in(&text, &crate::i18n::lang(), lang))
}
/// Recognisers write Mandarin in Simplified characters (xAI always, OpenAI often), and with
/// mainland words (软件 for 軟體): in a Traditional Chinese window, Traditional with Taiwan
/// wording, like the bots' replies. Japanese (it has kana) keeps its own kanji.
pub fn spoken_in(text: &str, ui_lang: &str, spoken: &str) -> String {
let kana = text.chars().any(|c| ('\u{3040}'..='\u{30ff}').contains(&c));
if ui_lang == "zh-TW" && spoken != "ja" && !kana {
zhconv::zhconv(text, zhconv::Variant::ZhTW)
} else {
text.to_string()
}
}
/// The voice file's name in the form (the services tell the format by it and by the header).
fn upload_name(file: &std::path::Path) -> &'static str {
if file.extension().and_then(|e| e.to_str()) == Some("wav") {
"voice.wav"
} else {
"voice.m4a"
}
}
fn stt_agent() -> ureq::Agent {
ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(120))).http_status_as_error(false).build().into()
}
/// xAI's speech to text (POST {base}/stt, the file last; the answer's `text`). With a language it
/// also writes numbers and amounts as digits (`format`, which needs one).
pub fn transcribe_xai(base_url: &str, api_key: &str, file: &std::path::Path, lang: &str) -> Result<String, String> {
let audio = std::fs::read(file).map_err(|e| e.to_string())?;
let boundary = format!("anybot{}", chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0));
let mut fields = vec![];
if !lang.is_empty() {
fields.push(("language", lang));
fields.push(("format", "true"));
}
let body = form(&fields, upload_name(file), &audio, &boundary);
let url = format!("{}/stt", base_url.trim_end_matches('/'));
let resp = stt_agent()
.post(&url)
.header("Authorization", &format!("Bearer {}", api_key.trim()))
.header("Content-Type", &format!("multipart/form-data; boundary={boundary}"))
.send(&body[..]);
match resp {
Ok(mut r) => {
let status = r.status().as_u16();
let text = r.body_mut().read_to_string().unwrap_or_default();
if status != 200 {
return Err(format!("轉文字失敗(xAI,HTTP {status}):{}", text.chars().take(200).collect::<String>()));
}
let v: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
Ok(v["text"].as_str().unwrap_or("").trim().to_string())
}
Err(e) => Err(format!("連不上語音轉文字服務(xAI):{e}")),
}
}
/// The spoken languages offered for voice chat (the original: 語言 Auto-detect…): (code, name).
pub const SPOKEN: [(&str, &str); 6] = [("", "自動偵測"), ("zh", "中文"), ("en", "English"), ("ja", "日本語"), ("ko", "한국어"), ("es", "Español")];
pub fn transcribe_lang(base_url: &str, api_key: &str, file: &std::path::Path, lang: &str) -> Result<String, String> {
if api_key.trim().is_empty() {
return Err(NO_STT_KEY.into());
}
let audio = std::fs::read(file).map_err(|e| e.to_string())?;
let boundary = format!("anybot{}", chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0));
let url = format!("{}/audio/transcriptions", base_url.trim_end_matches('/'));
let agent = stt_agent();
let mut last = String::new();
for model in MODELS {
let body = multipart_lang(model, upload_name(file), &audio, &boundary, lang);
let resp = agent
.post(&url)
.header("Authorization", &format!("Bearer {}", api_key.trim()))
.header("Content-Type", &format!("multipart/form-data; boundary={boundary}"))
.send(&body[..]);
match resp {
Ok(mut r) => {
let status = r.status().as_u16();
let text = r.body_mut().read_to_string().unwrap_or_default();
if status == 200 {
let v: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
return Ok(v["text"].as_str().unwrap_or("").trim().to_string());
}
last = format!("轉文字失敗(HTTP {status}):{}", text.chars().take(200).collect::<String>());
// An unknown model: try the next one.
if status != 404 && status != 400 {
break;
}
}
Err(e) => {
last = format!("連不上語音轉文字服務:{e}");
break;
}
}
}
Err(last)
}
/// The voices installed on this Mac: (name, language code), Chinese and English first.
pub fn voices() -> Vec<(String, String)> {
static V: std::sync::OnceLock<Vec<(String, String)>> = std::sync::OnceLock::new();
V.get_or_init(|| {
if !cfg!(target_os = "macos") {
let out = Command::new("espeak-ng").arg("--voices").output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default();
return parse_espeak_voices(&out);
}
let out = Command::new("say").args(["-v", "?"]).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default();
parse_voices(&out)
})
.clone()
}
pub fn parse_voices(out: &str) -> Vec<(String, String)> {
let mut v: Vec<(String, String)> = out
.lines()
.filter_map(|l| {
let head = l.split('#').next()?.trim_end();
let (name, lang) = head.rsplit_once(char::is_whitespace)?;
let lang = lang.trim();
lang.contains('_').then(|| (name.trim().to_string(), lang.to_string()))
})
.filter(|(n, _)| !n.is_empty())
.collect();
let rank = |l: &str| if l.starts_with("zh_TW") { 0 } else if l.starts_with("zh") { 1 } else if l.starts_with("en") { 2 } else if l.starts_with("ja") { 3 } else { 4 };
v.sort_by(|a, b| rank(&a.1).cmp(&rank(&b.1)).then(a.0.cmp(&b.0)));
v
}
/// `espeak-ng --voices` (Linux): "Pty Language Age/Gender VoiceName File Other" →
/// (language code to pass to -v, language as zh_CN / en_US).
pub fn parse_espeak_voices(out: &str) -> Vec<(String, String)> {
let mut v: Vec<(String, String)> = out
.lines()
.skip(1)
.filter_map(|l| {
let lang = l.split_whitespace().nth(1)?.to_string();
let norm = match lang.as_str() {
"cmn" => "zh_CN".to_string(),
"yue" => "zh_HK".to_string(),
"cmn-latn-pinyin" => return None,
l => {
let mut parts = l.splitn(2, '-');
let a = parts.next().unwrap_or("");
match parts.next() {
Some(b) => format!("{a}_{}", b.to_uppercase()),
None => format!("{a}_{}", a.to_uppercase()),
}
}
};
Some((lang, norm))
})
.collect();
let rank = |l: &str| if l.starts_with("zh") { 1 } else if l.starts_with("en") { 2 } else if l.starts_with("ja") { 3 } else { 4 };
v.sort_by(|a, b| rank(&a.1).cmp(&rank(&b.1)).then(a.0.cmp(&b.0)));
// One entry per language (espeak-ng lists some twice, e.g. yue with and without Jyutping).
v.dedup_by(|a, b| a.0 == b.0);
v
}
// ---------- 語音聊天: reading answers aloud ----------
static SPEAKER: std::sync::Mutex<Option<Child>> = std::sync::Mutex::new(None);
/// Markdown → words worth saying.
pub fn speakable(text: &str) -> String {
let mut out = String::new();
let mut in_code = false;
for line in text.lines() {
let l = line.trim();
if l.starts_with("```") {
in_code = !in_code;
if in_code {
out.push_str("(程式碼略過)\n");
}
continue;
}
if in_code {
continue;
}
let l = l.trim_start_matches(['#', '-', '*', '>', ' ']).replace("**", "").replace('`', "");
let l = l.split("](").next().unwrap_or(&l).replace('[', "");
if !l.is_empty() {
out.push_str(&l);
out.push('\n');
}
}
out.trim().to_string()
}
/// The voice for the text: Taiwanese Mandarin (美佳) when it has Chinese, else the system voice.
pub fn voice_for(text: &str) -> Option<&'static str> {
text.chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)).then_some(if cfg!(target_os = "macos") { "Meijia" } else { "cmn" })
}
/// Words per minute of the system voices at 1x (`say`'s usual rate).
pub const BASE_RATE: f32 = 175.0;
/// The speeds offered (the original: 速度 1x…).
pub const SPEEDS: [f32; 5] = [0.75, 1.0, 1.25, 1.5, 2.0];
/// Read aloud with a chosen voice ("" = pick by language) and speed (1.0 = normal).
pub fn speak_as(text: &str, voice: &str, rate: f32) {
stop_speaking();
let words = speakable(text);
if words.is_empty() {
return;
}
// Linux: espeak-ng takes the same -v (voice) and -s (words per minute, 175 by default).
let mut c = Command::new(if cfg!(target_os = "macos") { "say" } else { "espeak-ng" });
if !voice.trim().is_empty() {
c.args(["-v", voice.trim()]);
} else if let Some(v) = voice_for(&words) {
c.args(["-v", v]);
}
if (rate - 1.0).abs() > 0.01 {
c.args([if cfg!(target_os = "macos") { "-r" } else { "-s" }, &format!("{}", (BASE_RATE * rate.clamp(0.5, 3.0)).round())]);
}
if let Ok(child) = c.arg(&words).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() {
*SPEAKER.lock().unwrap() = Some(child);
// ---------- 播放 ----------
/// Each `say` gets a number; a newer one (or `stop_speaking`) makes the older one stop.
static PLAY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static PLAYING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Get the sound (`fetch`: from the brain) and play it, instead of whatever was playing. What
/// goes wrong lands in `note`. `speaking()` is true from now until it has finished.
pub fn say(fetch: impl FnOnce() -> Result<Vec<u8>, String> + Send + 'static, note: std::sync::Arc<std::sync::Mutex<Option<String>>>) {
use std::sync::atomic::Ordering::SeqCst;
let gen = PLAY_GEN.fetch_add(1, SeqCst) + 1;
PLAYING.store(true, SeqCst);
std::thread::spawn(move || {
let r = fetch().and_then(|mp3| if PLAY_GEN.load(SeqCst) == gen { play(mp3, gen) } else { Ok(()) });
if PLAY_GEN.load(SeqCst) == gen {
if let Err(e) = r {
*note.lock().unwrap() = Some(e);
}
PLAYING.store(false, SeqCst);
}
});
}
/// MP3 out of the speakers, until it ends or a newer `say` / `stop_speaking` comes.
fn play(mp3: Vec<u8>, gen: u64) -> Result<(), String> {
use std::sync::atomic::Ordering::SeqCst;
let mut sink = rodio::DeviceSinkBuilder::open_default_sink().map_err(|_| "找不到可以播放聲音的裝置".to_string())?;
sink.log_on_drop(false);
let dec = rodio::Decoder::new(std::io::Cursor::new(mp3)).map_err(|_| "語音服務傳回的聲音放不出來".to_string())?;
let player = rodio::Player::connect_new(sink.mixer());
player.append(dec);
while !player.empty() {
if PLAY_GEN.load(SeqCst) != gen {
player.stop();
break;
}
std::thread::sleep(Duration::from_millis(50));
}
Ok(())
}
pub fn stop_speaking() {
if let Some(mut c) = SPEAKER.lock().unwrap().take() {
let _ = c.kill();
}
use std::sync::atomic::Ordering::SeqCst;
PLAY_GEN.fetch_add(1, SeqCst);
PLAYING.store(false, SeqCst);
}
pub fn speaking() -> bool {
let mut g = SPEAKER.lock().unwrap();
match g.as_mut().map(|c| c.try_wait()) {
Some(Ok(None)) => true,
_ => {
*g = None;
false
}
}
PLAYING.load(std::sync::atomic::Ordering::SeqCst)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Write};
#[test]
fn answers_are_cleaned_for_speaking() {
let t = "## 行程\n- **上午**:赤崁樓\n```\nls -la\n```\n看 [地圖](https://x.y)";
assert_eq!(speakable(t), "行程\n上午:赤崁樓\n(程式碼略過)\n看 地圖");
assert_eq!(voice_for("你好"), Some(if cfg!(target_os = "macos") { "Meijia" } else { "cmn" }));
let e = parse_espeak_voices("Pty Language Age/Gender VoiceName File Other Languages\n 5 cmn --/M Chinese_(Mandarin) sit/cmn (zh-cmn 5)(zh 5)\n 2 en-us --/M English_(America) gmw/en-US (en 3)\n");
assert_eq!(e[0], ("cmn".to_string(), "zh_CN".to_string()));
assert_eq!(e[1], ("en-us".to_string(), "en_US".to_string()));
let v = parse_voices("Samantha en_US # Hello\nMeijia zh_TW # 你好\nGrandma (Chinese (Taiwan)) zh_TW # 你好\n");
assert_eq!(v[0].1, "zh_TW");
assert!(v.iter().any(|x| x.0 == "Grandma (Chinese (Taiwan))"));
assert_eq!(v.last().unwrap().0, "Samantha");
let body = String::from_utf8_lossy(&multipart_lang("m", "a.m4a", b"x", "B", "zh")).to_string();
assert!(body.contains("name=\"language\"\r\n\r\nzh"));
assert_eq!(voice_for("hello"), None);
}
#[test]
fn transcription_request_is_well_formed() {
let server = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = server.local_addr().unwrap().port();
let seen = std::thread::spawn(move || {
let (mut s, _) = server.accept().unwrap();
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut buf = vec![0u8; 65536];
let mut got = vec![];
while let Ok(n) = s.read(&mut buf) {
if n == 0 {
break;
}
got.extend_from_slice(&buf[..n]);
if got.windows(4).any(|w| w == b"--\r\n") {
break;
}
}
let reply = "{\"text\":\"你好,幫我排行程\"}";
let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len()).as_bytes());
String::from_utf8_lossy(&got).to_string()
});
let f = std::env::temp_dir().join(format!("anybot-voice-test-{}.m4a", std::process::id()));
std::fs::write(&f, vec![7u8; 2048]).unwrap();
let text = transcribe_lang(&format!("http://127.0.0.1:{port}/v1"), "sk-test", &f, "").unwrap();
let req = seen.join().unwrap();
let _ = std::fs::remove_file(&f);
assert_eq!(text, "你好,幫我排行程");
assert!(req.starts_with("POST /v1/audio/transcriptions"));
assert!(req.contains("Bearer sk-test") && req.contains("name=\"model\"\r\n\r\ngpt-4o-mini-transcribe") && req.contains("filename=\"voice.m4a\""));
assert!(transcribe_lang("http://127.0.0.1:1", "", &std::path::PathBuf::from("/x"), "").unwrap_err().contains("OpenAI"));
}
#[test]
fn speech_goes_to_whichever_key_there_is() {
let side = |base: &str, key: &str| (base.to_string(), key.to_string());
let (oa, xa) = ("https://api.openai.com/v1", "https://api.x.ai/v1");
assert_eq!(pick_stt(side(oa, "sk-o"), side(xa, "xai-k")), Some(Stt::OpenAi { base: oa.into(), key: "sk-o".into() }));
// Only Grok set up (no OpenAI key): xAI's speech to text.
assert_eq!(pick_stt(side(oa, " "), side(xa, "xai-k")), Some(Stt::Xai { base: xa.into(), key: "xai-k".into() }));
assert_eq!(pick_stt(side(oa, ""), side(xa, "")), None);
assert!(NO_STT_KEY.contains("OpenAI") && NO_STT_KEY.contains("xAI"));
}
#[test]
fn mandarin_comes_back_in_the_windows_chinese() {
// What xAI really answers for a Taiwanese speaker (language "zh-cn").
let heard = "帮我把手机里的照片依照月份整理好,软件更新完再提醒我";
assert_eq!(spoken_in(heard, "zh-TW", ""), "幫我把手機裡的照片依照月份整理好,軟體更新完再提醒我");
assert_eq!(spoken_in(heard, "zh-TW", "zh"), "幫我把手機裡的照片依照月份整理好,軟體更新完再提醒我");
// A word-by-word converter: 里 it doesn't know as 裡 stays 里 (資料夾里), never 公裡.
assert_eq!(spoken_in("三公里", "zh-TW", ""), "三公里");
// Japanese keeps its own kanji; other windows keep what was heard.
assert_eq!(spoken_in("会議は明日です", "zh-TW", ""), "会議は明日です");
assert_eq!(spoken_in("会议", "zh-TW", "ja"), "会议");
assert_eq!(spoken_in(heard, "en", ""), heard);
assert_eq!(spoken_in("Book a table for two", "zh-TW", ""), "Book a table for two");
}
#[test]
fn xai_request_is_well_formed() {
let server = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = server.local_addr().unwrap().port();
let seen = std::thread::spawn(move || {
let (mut s, _) = server.accept().unwrap();
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut buf = vec![0u8; 65536];
let mut got = vec![];
while let Ok(n) = s.read(&mut buf) {
if n == 0 {
break;
}
got.extend_from_slice(&buf[..n]);
if got.windows(4).any(|w| w == b"--\r\n") {
break;
}
}
let reply = "{\"text\":\"明天下午三点开会\",\"language\":\"zh-cn\",\"duration\":2.2}";
let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len()).as_bytes());
String::from_utf8_lossy(&got).to_string()
});
let f = std::env::temp_dir().join(format!("anybot-xai-test-{}.m4a", std::process::id()));
std::fs::write(&f, vec![7u8; 2048]).unwrap();
let text = transcribe_xai(&format!("http://127.0.0.1:{port}/v1"), "xai-test", &f, "zh").unwrap();
let req = seen.join().unwrap();
let _ = std::fs::remove_file(&f);
assert_eq!(text, "明天下午三点开会");
assert!(req.starts_with("POST /v1/stt"), "{}", &req[..40.min(req.len())]);
assert!(req.contains("Bearer xai-test") && req.contains("filename=\"voice.m4a\""));
// Options come before the file: xAI ignores fields sent after it.
let (lang, fmt, file) = (req.find("name=\"language\"\r\n\r\nzh").unwrap(), req.find("name=\"format\"\r\n\r\ntrue").unwrap(), req.find("name=\"file\"").unwrap());
assert!(lang < file && fmt < file);
assert!(!req.contains("name=\"model\""));
fn a_newer_say_or_stop_ends_the_playing() {
let note = std::sync::Arc::new(std::sync::Mutex::new(None));
// The service failing: said in the note, and nothing is playing after.
say(|| Err("xAI 不接受這把金鑰".into()), note.clone());
let t = Instant::now();
while speaking() && t.elapsed() < Duration::from_secs(2) {
std::thread::sleep(Duration::from_millis(10));
}
assert!(!speaking());
assert_eq!(note.lock().unwrap().as_deref(), Some("xAI 不接受這把金鑰"));
// Stopped while the sound was still on its way: it never plays, and says nothing.
let quiet = std::sync::Arc::new(std::sync::Mutex::new(None));
say(|| {
std::thread::sleep(Duration::from_millis(150));
Err("late".into())
}, quiet.clone());
assert!(speaking());
stop_speaking();
assert!(!speaking());
std::thread::sleep(Duration::from_millis(250));
assert!(!speaking() && quiet.lock().unwrap().is_none());
assert_eq!(length_words(7_200), "2 小時");
}
}