Server voice service: Whisper on the brain's own server, checked for real
`make server` now asks whether to run a voice service there (and the kept-setup menu can add or remove it): speaches, Whisper large-v3-turbo on the CPU, behind the brain only (no published port), enabled with COMPOSE_PROFILES=voice so it composes with the Tailscale and LAN files. The brain sees ANYBOT_VOICE_URL, fills 設定 › 語音 › 聽 with it once (what is changed later stays), and asks the service for its model at each start: this build downloads only when asked (it has no PRELOAD_MODELS, and the 0.8.2-cpu tag is older still, so the image is pinned by the digest that was tested). Tested end to end on 12 CPU cores with the compose file itself: first start 404 s to download the model, later starts 1 s; 11 s of Mandarin mixed with English (Chrome, Tesla FSD) in 3.4–3.6 s, every word right. small is three times faster and slipped a character. Reading aloud stays with another service: speaches can't say Chinese (its espeak has no "zh"), English works. From the same test: a service that answers 200 with no sound is now an error said in words (it was played as silence), Whisper's ASCII punctuation in Chinese becomes full-width (,?!), and speaches' "not installed locally" says the model is still on its way.
This commit is contained in:
parent
40d1d9707a
commit
12c9944dee
|
|
@ -1255,6 +1255,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
|||
- 中文辨識結果會轉成繁體和台灣用語(xAI 和 Whisper 常回簡體);日文不轉。
|
||||
- 從舊版升級:原本有 OpenAI 金鑰(語音輸入本來就能用)的人,「聽」自動設成 OpenAI;其他人預設關閉。舊的 macOS 聲音名稱(美佳…)會清掉。
|
||||
- OpenAI 的轉文字模型依序試 gpt-transcribe、gpt-4o-mini-transcribe、whisper-1(後兩個 OpenAI 在 2027-02-26 停用)。
|
||||
- 伺服器上的大腦可以自己架語音服務(`make server` 會問):Whisper 在 CPU 上轉文字,大腦第一次啟動時自動把「聽」設成它(之後改掉就不再動)。它不會念中文,「說」請另外選。
|
||||
- 服務回了 200 卻沒有聲音(例如不支援那個語言)時,會說「沒有產生聲音」,不會靜靜地什麼都沒唸。
|
||||
|
||||
### 語音輸入
|
||||
|
||||
|
|
|
|||
|
|
@ -74,8 +74,32 @@ services:
|
|||
# images and the box image build. DOCKER_HOST is the plain `docker` CLI default, which is
|
||||
# what src/cloudbox.rs uses when its own docker_host setting is empty.
|
||||
DOCKER_HOST: "tcp://docker-socket-proxy:2375"
|
||||
# 語音 on this server (the voice service below, when it is on): 設定 › 語音 is filled in
|
||||
# with it once; what you choose there afterwards stays.
|
||||
ANYBOT_VOICE_URL: "${ANYBOT_VOICE_URL:-}"
|
||||
ANYBOT_VOICE_LISTEN_MODEL: "${ANYBOT_VOICE_LISTEN_MODEL:-}"
|
||||
ANYBOT_VOICE_SPEAK_MODEL: "${ANYBOT_VOICE_SPEAK_MODEL:-}"
|
||||
ANYBOT_VOICE_VOICE: "${ANYBOT_VOICE_VOICE:-}"
|
||||
volumes:
|
||||
- anybot-data:/data
|
||||
# 語音 (optional: ./setup.sh asks; COMPOSE_PROFILES=voice in .env turns it on): speech to text
|
||||
# (Whisper) on this server's CPU for every screen and phone, with no key. speaches (MIT) speaks
|
||||
# OpenAI's audio API. No port is published: only the brain reaches it, at http://voice:8000/v1.
|
||||
# The model is downloaded once, into voice-models. (It reads English aloud but not Chinese:
|
||||
# reading aloud is set in 設定 › 語音, e.g. xAI.)
|
||||
voice:
|
||||
# The build checked with AnyBot (latest-cpu of 2025-09-19; the 0.8.2-cpu tag is older).
|
||||
image: ghcr.io/speaches-ai/speaches@sha256:21e3df06d842fb7802ab470dd77c25f0e8c0d22950e8d8c6ae886e851af53ef8
|
||||
profiles: ["voice"]
|
||||
restart: unless-stopped
|
||||
# The brain asks it for ANYBOT_VOICE_LISTEN_MODEL at each start (this build has no
|
||||
# PRELOAD_MODELS): downloaded the first time, found at once after that.
|
||||
environment:
|
||||
WHISPER__COMPUTE_TYPE: "int8"
|
||||
# Stay loaded: the first sentence after a quiet hour shouldn't wait for a model to load.
|
||||
WHISPER__TTL: "-1"
|
||||
volumes:
|
||||
- voice-models:/home/ubuntu/.cache/huggingface/hub
|
||||
docker-socket-proxy:
|
||||
# https://github.com/Tecnativa/docker-socket-proxy: a small nginx in front of the Docker
|
||||
# socket with an endpoint allowlist. Keep this list minimal: adding an API here widens what
|
||||
|
|
@ -100,3 +124,4 @@ volumes:
|
|||
relay-data:
|
||||
caddy-data:
|
||||
anybot-data:
|
||||
voice-models:
|
||||
|
|
|
|||
|
|
@ -18,6 +18,16 @@ DRY=0
|
|||
[ "${1:-}" = "--dry-run" ] && DRY=1
|
||||
AUTO=0
|
||||
[ -n "${ANYBOT_SETUP_USER:-}" ] && [ -n "${ANYBOT_SETUP_PASSWORD:-}" ] && AUTO=1
|
||||
# 語音 on this server (docker-compose's voice service, speaches): speech to text with Whisper on
|
||||
# the CPU. large-v3-turbo got every word of a Mandarin test right, about 3.5 s for 11 s of speech
|
||||
# on 12 cores; Systran/faster-whisper-small is three times faster and slips a word now and then
|
||||
# (ANYBOT_VOICE_LISTEN_MODEL=… before ./setup.sh). Reading aloud stays with a service chosen in
|
||||
# 設定 › 語音 (xAI…): speaches 0.8.2 can't say Chinese (its espeak has no "zh").
|
||||
VOICE_URL=http://voice:8000/v1
|
||||
VOICE_LISTEN=${ANYBOT_VOICE_LISTEN_MODEL:-deepdml/faster-whisper-large-v3-turbo-ct2}
|
||||
voice_lines() {
|
||||
printf "COMPOSE_PROFILES='voice'\nANYBOT_VOICE_URL='%s'\nANYBOT_VOICE_LISTEN_MODEL='%s'\n" "$VOICE_URL" "$VOICE_LISTEN"
|
||||
}
|
||||
|
||||
# ---------- looks ----------
|
||||
if [ -t 1 ]; then
|
||||
|
|
@ -160,9 +170,25 @@ if [ $WARNED = 1 ]; then card_close; pause; else card_close; sleep 1; fi
|
|||
if [ -f .env ] && [ -f Caddyfile ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
if grep -q "^COMPOSE_PROFILES=.*voice" .env; then
|
||||
VOICE_OPT="拿掉語音服務|不再在這台轉文字(設定 › 語音 可以改用 xAI、OpenAI 等)"
|
||||
else
|
||||
VOICE_OPT="加上語音服務|在這台的 CPU 上把說的話轉成文字,不用金鑰(第一次下載約 1.6 GB 的模型)"
|
||||
fi
|
||||
choose KEEP "這台已經設定過了(${ANYBOT_RELAY_PUBLIC_URL:-})" \
|
||||
"用現有設定,更新並重新啟動|拉下最新版、重建、重新啟動,帳號和 Bot 都不變" \
|
||||
"重新設定|網址、帳號或金鑰要改"
|
||||
"重新設定|網址、帳號或金鑰要改" \
|
||||
"$VOICE_OPT"
|
||||
if [ "$KEEP" = 2 ]; then
|
||||
# Toggle the voice service in the kept .env, then update and restart like 0.
|
||||
if grep -q "^COMPOSE_PROFILES=.*voice" .env; then
|
||||
(umask 077; grep -v -e '^COMPOSE_PROFILES=' -e '^ANYBOT_VOICE_' .env >.env.new) && mv .env.new .env
|
||||
else
|
||||
(umask 077; { grep -v -e '^COMPOSE_PROFILES=' -e '^ANYBOT_VOICE_' .env; voice_lines; } >.env.new) && mv .env.new .env
|
||||
fi
|
||||
set -a; . ./.env; set +a
|
||||
KEEP=0
|
||||
fi
|
||||
if [ "$KEEP" = 0 ]; then
|
||||
DOMAIN=${ANYBOT_RELAY_PUBLIC_URL#https://}; USERNAME=$ANYBOT_USER; INVITE=${ANYBOT_RELAY_INVITE:-}; BRAIN=${ANYBOT_HOST_NAME:-}
|
||||
LANIP=${ANYBOT_LAN_IP:-}
|
||||
|
|
@ -255,6 +281,15 @@ if [ "${SKIP:-0}" != 1 ]; then
|
|||
BRAIN="雲端大腦"
|
||||
break
|
||||
done
|
||||
# ---------- 語音 ----------
|
||||
# Without questions only when asked for (ANYBOT_SETUP_VOICE=1): it downloads about 1.6 GB.
|
||||
if [ "$AUTO" = 1 ]; then
|
||||
[ "${ANYBOT_SETUP_VOICE:-}" = 1 ] && VOICE=0 || VOICE=1
|
||||
else
|
||||
choose VOICE "要在這台架語音服務嗎?" \
|
||||
"要|在這台的 CPU 上把說的話轉成文字,每台電腦和手機都用它,不用金鑰、不花錢。第一次會下載約 1.6 GB 的模型。朗讀另外在 App 的 設定 › 語音 選(例如 xAI)" \
|
||||
"先不要|之後可以再執行一次 ./setup.sh 加上;或在 App 的 設定 › 語音 改用 xAI、OpenAI 等服務"
|
||||
fi
|
||||
# Only this account (others can be let in later: ANYBOT_RELAY_INVITE in .env). AI keys are set
|
||||
# in the app (設定 › 模型); they stay on the brain.
|
||||
INVITE=""; XAI=""; ANT=""; OAI=""; GEM=""; RESTORE=""
|
||||
|
|
@ -280,6 +315,7 @@ if [ "${SKIP:-0}" != 1 ]; then
|
|||
11) q COMPOSE_FILE "docker-compose.yml:docker-compose.tailscale.yml:docker-compose.lan.yml" ;;
|
||||
01) q COMPOSE_FILE "docker-compose.yml:docker-compose.lan.yml" ;;
|
||||
esac
|
||||
[ "$VOICE" = 0 ] && voice_lines
|
||||
} >.env
|
||||
chmod 600 .env
|
||||
umask 022
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ A Linux host (≥2 GB RAM) plus one of: a **domain** (A record, 80/443; HTTPS ce
|
|||
curl -fsSL https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.sh | sh -s -- server
|
||||
```
|
||||
|
||||
It asks three questions (URL, account, password), installs Docker if needed, gets HTTPS, creates the account, starts the brain. Update later with `cd ~/AnyBot && make server` (“keep settings, update, restart”). Release archives (built by Gitea Actions on `v*` tags) avoid building on the server: download `AnyBot-<ver>-server-<arch>.tar.gz`, unpack, `cd deploy/server && ./setup.sh`.
|
||||
It asks a few questions (URL, account, password, and whether to run a voice service there), installs Docker if needed, gets HTTPS, creates the account, starts the brain. Update later with `make update-server`, or `cd ~/AnyBot && make server` (“keep settings, update, restart”, or “add / remove the voice service”). The voice service is Whisper ([speaches](https://speaches.ai), large-v3-turbo) on the server's CPU: speech to text for every screen and phone with no key, about 1.6 GB of model, internal only (`ANYBOT_SETUP_VOICE=1` for unattended setups, `ANYBOT_VOICE_LISTEN_MODEL=Systran/faster-whisper-small` for speed). It can't read Chinese aloud: pick a service for 設定 › 語音 › 說 (e.g. xAI). Release archives (built by Gitea Actions on `v*` tags) avoid building on the server: download `AnyBot-<ver>-server-<arch>.tar.gz`, unpack, `cd deploy/server && ./setup.sh`.
|
||||
|
||||
## Method B — a Mac as the brain (home, Tailscale)
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,9 @@
|
|||
curl -fsSL https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.sh | sh -s -- server
|
||||
```
|
||||
|
||||
只問三件事:網域、帳號、密碼。會自動申請 HTTPS 憑證、建立帳號、啟動大腦。完成畫面會告訴你手機和電腦怎麼連。之後在伺服器上執行 `cd ~/AnyBot && make server`,可以選「用現有設定,更新並重新啟動」。
|
||||
只問幾件事:網域、帳號、密碼,以及要不要在這台架語音服務。會自動申請 HTTPS 憑證、建立帳號、啟動大腦。完成畫面會告訴你手機和電腦怎麼連。之後在伺服器上執行 `cd ~/AnyBot && make server`,可以選「用現有設定,更新並重新啟動」或「加上/拿掉語音服務」;平常更新用 `make update-server`。
|
||||
|
||||
**語音服務**(選配):在這台的 CPU 上用 Whisper([speaches](https://speaches.ai),large-v3-turbo)把說的話轉成文字,每台電腦和手機的麥克風都用它,不用金鑰、不花錢。第一次下載約 1.6 GB 的模型;11 秒的中文約 3.5 秒轉完(12 核測得)。想快一點:設定前 `ANYBOT_VOICE_LISTEN_MODEL=Systran/faster-whisper-small`(約快三倍,偶爾錯一個字)。它只開在伺服器內部,不對外。朗讀(把回答唸出來)它目前不會中文,請在 App 的 設定 › 語音 › 說 選 xAI 之類的服務。不用問題的設定方式加 `ANYBOT_SETUP_VOICE=1`。
|
||||
|
||||
有發行檔時(推 `v*` tag 後由 Gitea Actions 產生,見 [release.md](release.md)),也可以不在伺服器上編譯:下載 `AnyBot-<版本>-server-<架構>.tar.gz`,解開後 `cd deploy/server && ./setup.sh`。
|
||||
|
||||
|
|
|
|||
16
src/app.rs
16
src/app.rs
|
|
@ -3954,6 +3954,22 @@ impl App {
|
|||
app.state.remote.device_link = true;
|
||||
app.dirty = true;
|
||||
}
|
||||
// 語音 next to this brain (`make server` with voice: docker-compose's voice service).
|
||||
if let Some(url) = std::env::var("ANYBOT_VOICE_URL").ok().map(|u| u.trim().to_string()).filter(|u| !u.is_empty()) {
|
||||
let var = |k: &str| std::env::var(k).unwrap_or_default();
|
||||
if crate::speech::own_server(&mut app.state.voice, &url, &var("ANYBOT_VOICE_LISTEN_MODEL"), &var("ANYBOT_VOICE_SPEAK_MODEL"), &var("ANYBOT_VOICE_VOICE")) {
|
||||
eprintln!("AnyBot:語音用這台伺服器的語音服務({url})");
|
||||
app.dirty = true;
|
||||
}
|
||||
// Its model is downloaded when asked (once; then each start finds it at once).
|
||||
let model = var("ANYBOT_VOICE_LISTEN_MODEL");
|
||||
if !model.is_empty() {
|
||||
std::thread::spawn(move || match crate::speech::fetch_model(&url, &model) {
|
||||
Ok(()) => eprintln!("AnyBot:語音服務的模型就緒({model})"),
|
||||
Err(e) => eprintln!("AnyBot:{e}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
app.serve_join();
|
||||
app.background(ctx);
|
||||
if let Some(port) = crate::remote::lan_port() {
|
||||
|
|
|
|||
|
|
@ -569,10 +569,11 @@ fn engine_form(ui: &mut egui::Ui, p: Palette, e: &mut VoiceEngine, speak: bool,
|
|||
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"),
|
||||
// `make server` with voice (speaches). It can't say Chinese, so only for 聽.
|
||||
("自己的伺服器", "http://voice:8000/v1", "deepdml/faster-whisper-large-v3-turbo-ct2", "", ""),
|
||||
];
|
||||
for (name, base, lm, sm, sv) in presets {
|
||||
if speak && name == "Groq" {
|
||||
if speak && name != "OpenAI" {
|
||||
continue;
|
||||
}
|
||||
if ui.small_button(t(name)).clicked() {
|
||||
|
|
|
|||
|
|
@ -360,6 +360,10 @@ pub struct VoiceSettings {
|
|||
pub speak: VoiceEngine,
|
||||
/// Written by an AnyBot that has 設定 › 語音 (false: an older save, see State::load_from).
|
||||
pub saved: bool,
|
||||
/// The voice service next to this brain that was filled in once (speech::own_server): turned
|
||||
/// off afterwards, it stays off.
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub from_server: String,
|
||||
}
|
||||
|
||||
/// One voice service and how to reach it.
|
||||
|
|
|
|||
183
src/speech.rs
183
src/speech.rs
|
|
@ -85,6 +85,27 @@ pub fn missing(e: &VoiceEngine, speak: bool) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
/// The voice service next to this brain (`make server` with voice: ANYBOT_VOICE_URL): 聽 and 說
|
||||
/// use it wherever 設定 › 語音 has nothing (what the person chose stays). `speak_model` empty:
|
||||
/// it doesn't read aloud. Once per address: what is turned off later stays off. True when
|
||||
/// something changed.
|
||||
pub fn own_server(v: &mut crate::model::VoiceSettings, url: &str, listen_model: &str, speak_model: &str, voice: &str) -> bool {
|
||||
if v.from_server == url {
|
||||
return false;
|
||||
}
|
||||
v.from_server = url.to_string();
|
||||
let mut changed = true;
|
||||
if v.listen.kind == VoiceKind::Off && !listen_model.is_empty() {
|
||||
v.listen = VoiceEngine { kind: VoiceKind::OpenAi, base_url: url.into(), model: listen_model.into(), ..Default::default() };
|
||||
changed = true;
|
||||
}
|
||||
if v.speak.kind == VoiceKind::Off && !speak_model.is_empty() {
|
||||
v.speak = VoiceEngine { kind: VoiceKind::OpenAi, base_url: url.into(), model: speak_model.into(), voice: voice.into(), ..Default::default() };
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub fn label(k: VoiceKind) -> &'static str {
|
||||
match k {
|
||||
VoiceKind::Off => "關閉",
|
||||
|
|
@ -151,9 +172,34 @@ fn openai_listen(e: &Engine, audio: &[u8], name: &str, lang: &str) -> Result<Str
|
|||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
// speaches before its model is down (the brain asks for it at start: fetch_model).
|
||||
if last.contains("not installed locally") {
|
||||
return Err("語音服務還在準備模型(第一次要下載約 1.6 GB),請過幾分鐘再試。".into());
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
|
||||
/// A voice server of your own (speaches) downloads a model only when asked: POST
|
||||
/// {base}/models/{model}; one it has answers at once. The service may come up after the brain,
|
||||
/// so this waits for it (about 5 minutes) before giving up.
|
||||
pub fn fetch_model(base: &str, model: &str) -> Result<(), String> {
|
||||
let url = format!("{}/models/{}", base.trim_end_matches('/'), model);
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(60 * 60))).http_status_as_error(false).build().into();
|
||||
let mut last = String::new();
|
||||
for _ in 0..30 {
|
||||
match agent.post(&url).send(&[][..]) {
|
||||
Ok(r) if r.status().is_success() => return Ok(()),
|
||||
Ok(mut r) => {
|
||||
let said: String = r.body_mut().read_to_string().unwrap_or_default().chars().take(200).collect();
|
||||
return Err(format!("語音服務沒能下載 {model}(HTTP {}):{said}", r.status().as_u16()));
|
||||
}
|
||||
Err(e) => last = e.to_string(),
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(10));
|
||||
}
|
||||
Err(format!("連不上語音服務({base}):{last}"))
|
||||
}
|
||||
|
||||
fn text_of(v: &Value) -> String {
|
||||
v["text"].as_str().unwrap_or("").trim().to_string()
|
||||
}
|
||||
|
|
@ -164,12 +210,44 @@ fn text_of(v: &Value) -> String {
|
|||
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)
|
||||
cjk_punct(&zhconv::zhconv(text, zhconv::Variant::ZhTW))
|
||||
} else {
|
||||
text.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whisper writes ASCII , ? ! : ; in Chinese sentences: next to a Chinese character they become
|
||||
/// the full-width ones (,?!:;). Between English words or digits (1,000) they stay.
|
||||
fn cjk_punct(s: &str) -> String {
|
||||
let han = |c: Option<&char>| c.is_some_and(|c| ('\u{3400}'..='\u{9fff}').contains(c) || ('\u{3000}'..='\u{303f}').contains(c) || ('\u{ff00}'..='\u{ffef}').contains(c));
|
||||
let cs: Vec<char> = s.chars().collect();
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut i = 0;
|
||||
while i < cs.len() {
|
||||
let wide = match cs[i] {
|
||||
',' => Some(','),
|
||||
'?' => Some('?'),
|
||||
'!' => Some('!'),
|
||||
':' => Some(':'),
|
||||
';' => Some(';'),
|
||||
_ => None,
|
||||
};
|
||||
let next = cs[i + 1..].iter().find(|c| **c != ' ');
|
||||
match wide {
|
||||
Some(w) if han(out.chars().last().as_ref()) || han(next) => {
|
||||
out.push(w);
|
||||
// (The space Whisper puts after an ASCII comma has no place after a wide one.)
|
||||
while cs.get(i + 1) == Some(&' ') {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
_ => out.push(cs[i]),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---------- 說 ----------
|
||||
|
||||
/// `text` read aloud as MP3. `voice` (a bot's own; empty = the one in 設定 › 語音), `lang` the
|
||||
|
|
@ -181,6 +259,16 @@ pub fn speak(e: &Engine, text: &str, voice: &str, lang: &str, speed: f32) -> Res
|
|||
}
|
||||
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 };
|
||||
let mp3 = speak_with(e, &words, voice, lang, speed)?;
|
||||
// A service can answer 200 with no sound at all (speaches can't say Chinese: its espeak has
|
||||
// no "zh"); that is a failure to say, not silence to play.
|
||||
if mp3.len() < 512 {
|
||||
return Err(format!("{} 的語音服務沒有產生聲音(可能不支援這個語言或聲音)。", label(e.kind)));
|
||||
}
|
||||
Ok(mp3)
|
||||
}
|
||||
|
||||
fn speak_with(e: &Engine, words: &str, voice: String, lang: &str, speed: f32) -> Result<Vec<u8>, String> {
|
||||
match e.kind {
|
||||
VoiceKind::Off => Err(NOT_SET.into()),
|
||||
VoiceKind::OpenAi => {
|
||||
|
|
@ -433,6 +521,27 @@ mod tests {
|
|||
assert!(State::first_run().voice.saved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_voice_service_on_the_server_is_used_where_nothing_else_is() {
|
||||
let mut v = VoiceSettings::default();
|
||||
assert!(own_server(&mut v, "http://voice:8000/v1", "whisper-m", "kokoro", "zf_xiaobei"));
|
||||
assert_eq!((v.listen.kind, v.listen.base_url.as_str(), v.listen.model.as_str()), (VoiceKind::OpenAi, "http://voice:8000/v1", "whisper-m"));
|
||||
assert_eq!((v.speak.model.as_str(), v.speak.voice.as_str()), ("kokoro", "zf_xiaobei"));
|
||||
// What the person chose stays; nothing to do the second time.
|
||||
let mut v = VoiceSettings { speak: VoiceEngine { kind: VoiceKind::Xai, ..Default::default() }, ..Default::default() };
|
||||
assert!(own_server(&mut v, "http://voice:8000/v1", "whisper-m", "kokoro", ""));
|
||||
assert_eq!((v.listen.kind, v.speak.kind), (VoiceKind::OpenAi, VoiceKind::Xai));
|
||||
assert!(!own_server(&mut v, "http://voice:8000/v1", "whisper-m", "kokoro", ""));
|
||||
// Turned off later: it stays off.
|
||||
v.listen.kind = VoiceKind::Off;
|
||||
assert!(!own_server(&mut v, "http://voice:8000/v1", "whisper-m", "kokoro", ""));
|
||||
assert_eq!(v.listen.kind, VoiceKind::Off);
|
||||
// No speaking model: 說 is left alone.
|
||||
let mut v = VoiceSettings::default();
|
||||
own_server(&mut v, "http://voice:8000/v1", "whisper-m", "", "");
|
||||
assert_eq!(v.speak.kind, VoiceKind::Off);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mandarin_comes_back_in_the_windows_chinese() {
|
||||
let heard = "帮我把手机里的照片依照月份整理好,软件更新完再提醒我";
|
||||
|
|
@ -442,6 +551,10 @@ mod tests {
|
|||
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", ""), "三公里");
|
||||
// Whisper writes ASCII commas in Chinese; between English words they stay.
|
||||
assert_eq!(spoken_in("幫我打開Chrome,搜尋Tesla FSD,好嗎?", "zh-TW", ""), "幫我打開Chrome,搜尋Tesla FSD,好嗎?");
|
||||
assert_eq!(spoken_in("Hello, world? Yes!", "zh-TW", ""), "Hello, world? Yes!");
|
||||
assert_eq!(spoken_in("我要1,000元", "zh-TW", ""), "我要1,000元");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -471,16 +584,43 @@ mod tests {
|
|||
assert!(transcribe(&engine(VoiceKind::Xai, "http://127.0.0.1:1", "k"), &[0u8; 10], "voice.m4a", "", "zh-TW").unwrap_err().contains("沒有錄到"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_model_is_asked_for_and_a_missing_one_is_explained() {
|
||||
let (base, seen) = serve_once(r#"{"message":"Model downloaded"}"#, "application/json");
|
||||
fetch_model(&base, "deepdml/faster-whisper-large-v3-turbo-ct2").unwrap();
|
||||
assert!(seen.join().unwrap().starts_with("POST /v1/models/deepdml/faster-whisper-large-v3-turbo-ct2 "));
|
||||
// What speaches says before the model is down, in words the person can act on.
|
||||
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 || {
|
||||
use std::io::{Read, Write};
|
||||
let (mut s, _) = server.accept().unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_millis(500))).unwrap();
|
||||
let mut buf = vec![0u8; 65536];
|
||||
let _ = s.read(&mut buf);
|
||||
let _ = s.read(&mut buf);
|
||||
let reply = r#"{"detail":"Model 'x' is not installed locally. You can download the model using `POST /v1/models`"}"#;
|
||||
let _ = s.write_all(format!("HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len()).as_bytes());
|
||||
});
|
||||
let mut e = engine(VoiceKind::OpenAi, &base, "");
|
||||
e.model = "x".into();
|
||||
let err = transcribe(&e, &[7u8; 4000], "voice.m4a", "", "zh-TW").unwrap_err();
|
||||
h.join().unwrap();
|
||||
assert!(err.contains("還在準備模型"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn speaking_sends_the_words_and_gets_mp3() {
|
||||
let (base, seen) = serve_once("ID3fake-mp3", "audio/mpeg");
|
||||
// (Real sound is more than a few bytes; less is no sound.)
|
||||
let fake: &'static str = Box::leak(format!("ID3{}", "x".repeat(600)).into_boxed_str());
|
||||
let (base, seen) = serve_once(fake, "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");
|
||||
assert_eq!(mp3, fake.as_bytes());
|
||||
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 (base, seen) = serve_once(fake, "audio/mpeg");
|
||||
let mut e = engine(VoiceKind::OpenAi, &base, "k");
|
||||
e.voice = "zf_xiaobei".into();
|
||||
speak(&e, "你好", "", "", 1.25).unwrap();
|
||||
|
|
@ -488,8 +628,13 @@ mod tests {
|
|||
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)));
|
||||
// 200 with no sound (speaches can't say Chinese: espeak has no "zh"): said, not played.
|
||||
let (base, seen) = serve_once("", "audio/mpeg");
|
||||
let err = speak(&engine(VoiceKind::OpenAi, &base, ""), "你好", "zf_xiaobei", "zh", 1.0).unwrap_err();
|
||||
seen.join().unwrap();
|
||||
assert!(err.contains("沒有產生聲音"), "{err}");
|
||||
// A bot's own voice wins; ElevenLabs puts it in the address.
|
||||
let (base, seen) = serve_once("ID3y", "audio/mpeg");
|
||||
let (base, seen) = serve_once(fake, "audio/mpeg");
|
||||
let mut e = engine(VoiceKind::ElevenLabs, &base, "el");
|
||||
e.voice = "default-voice".into();
|
||||
speak(&e, "hi", "bot-voice", "", 1.0).unwrap();
|
||||
|
|
@ -509,6 +654,34 @@ mod tests {
|
|||
assert!(!voices(&e).unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// A real OpenAI-compatible server (your own speaches): ANYBOT_TEST_OAI_BASE=http://127.0.0.1:8000/v1
|
||||
/// ANYBOT_TEST_OAI_LISTEN=<model> ANYBOT_TEST_CLIP=<a Mandarin recording> [ANYBOT_TEST_OAI_SPEAK=<model>
|
||||
/// ANYBOT_TEST_OAI_VOICE=<voice> ANYBOT_TEST_OUT=<mp3 to write>] cargo test --bin anybot own_server_for_real -- --ignored --nocapture
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn own_server_for_real() {
|
||||
let var = |k: &str| std::env::var(k).unwrap_or_default();
|
||||
let mut e = engine(VoiceKind::OpenAi, &var("ANYBOT_TEST_OAI_BASE"), "");
|
||||
e.model = var("ANYBOT_TEST_OAI_LISTEN");
|
||||
let clip = std::path::PathBuf::from(var("ANYBOT_TEST_CLIP"));
|
||||
let audio = std::fs::read(&clip).unwrap();
|
||||
let name = format!("voice.{}", clip.extension().and_then(|x| x.to_str()).unwrap_or("m4a"));
|
||||
let t = std::time::Instant::now();
|
||||
fetch_model(&e.base, &e.model).unwrap();
|
||||
println!("模型就緒({:.0} 秒)", t.elapsed().as_secs_f32());
|
||||
let t = std::time::Instant::now();
|
||||
let heard = transcribe(&e, &audio, &name, "zh", "zh-TW").unwrap();
|
||||
println!("聽({},{:.1} 秒):{heard}", e.model, t.elapsed().as_secs_f32());
|
||||
if !var("ANYBOT_TEST_OAI_SPEAK").is_empty() {
|
||||
let mut s = engine(VoiceKind::OpenAi, &var("ANYBOT_TEST_OAI_BASE"), "");
|
||||
s.model = var("ANYBOT_TEST_OAI_SPEAK");
|
||||
let t = std::time::Instant::now();
|
||||
let mp3 = speak(&s, "好的,我已經把下載資料夾裡的照片整理好了,總共四十八張。", &var("ANYBOT_TEST_OAI_VOICE"), "zh", 1.0).unwrap();
|
||||
println!("說({},{:.1} 秒):{} bytes", s.model, t.elapsed().as_secs_f32(), mp3.len());
|
||||
std::fs::write(var("ANYBOT_TEST_OUT"), &mp3).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_are_cleaned_for_speaking() {
|
||||
let t = "## 行程\n- **上午**:赤崁樓\n```\nls -la\n```\n看 [地圖](https://x.y)";
|
||||
|
|
|
|||
Loading…
Reference in New Issue