Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(linux): use OpenRouter, ZenMux or any OpenAI-compatible service when Ling isn't an option

wqugurua1ba49e703da
diff --git a/AGENTS.md b/AGENTS.md
index 8fd25b1..52f06bb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,7 +13,7 @@ Cicada (知了, formerly Live Subs) turns what a computer plays into live transl
- AI keys live only in 0600 files (`AIKey`): never UserDefaults, logs or exports.
- Every AI call goes through `LingClient` (rate gate, priorities, `thinking: disabled`, content in the system message). Partial text is translated by Google, never Ling.
- Never speak untranslated text into the room. Never bundle the GPL BlackHole driver; download it and check its pinned SHA-256.
-- Only the Mac app recognizes on the device: don't claim 声音不出本机 for the ports (Ming, Ling key required).
+- Only the Mac app recognizes on the device: don't claim 声音不出本机 for the ports (a cloud AI service hears the audio).
- The notes window is a non-activating panel with `sharingType = .none`: it must never take focus, and stays out of screen captures unless the user turns on 共享屏幕时让对方看到 (then it shows a badge).
- Mac: UI and engine state are `@MainActor`; audio callbacks hand buffers to `AudioRouter`'s queue.
- Don't change the release bundle id `com.wquguru.cicada` or the ad-hoc designated requirement: permissions are tied to them.
diff --git a/linux/AGENTS.md b/linux/AGENTS.md
index 7f22b3c..c079bec 100644
--- a/linux/AGENTS.md
+++ b/linux/AGENTS.md
@@ -3,9 +3,9 @@
The Linux port: listening, and 同声传译 (speaking into the room through the 知了 麦克风 virtual mic). The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). Commands, layout and how to verify are in `README.md`; the plan is `docs/linux-plan.md`.
- Python 3, PyGObject and GTK 3, PulseAudio / PipeWire through `libpulse-simple`: only what Ubuntu desktop ships, no pip packages. `cicada/core` is stdlib only and must run and test on the Mac.
-- The key: `AIKey` in `cicada/core/ling.py`, the 0600 `ling-api-key` file in `~/.config/cicada`.
+- Keys: `AIKey` in `cicada/core/ling.py`, one 0600 file per AI service in `~/.config/cicada` (`ling-api-key`, `ai-key-<service>`, as on the Mac). The services and their recommended models are `cicada/core/providers.py`; every call reads the service from settings through `LingClient.config`.
- The notes window floats and never takes focus (XWayland, notification type). Linux can't keep it out of screen sharing, so it always says it may be shared; don't claim otherwise.
-- 知了 麦克风 is two sound-server modules (`cicada/app/room.py`), never a driver. While on it is the default input; every way out (off, 退出, SIGTERM, a crash then the next launch) gives the real microphone back. Never speak what Ming didn't interpret.
+- 知了 麦克风 is two sound-server modules (`cicada/app/room.py`), never a driver. While on it is the default input; every way out (off, 退出, SIGTERM, a crash then the next launch) gives the real microphone back. Never speak what the AI service didn't interpret.
- 说话人识别 runs the Mac's voiceprint model in `native/voiceprint.c` (our own C, ctypes; no BLAS on Ubuntu). It must stay equal to the Mac: the voiceprint test checks it against a Core ML reference, and clustering thresholds, labels and Ling's name prompt are the Mac's. The Mac can't link Linux binaries: CI builds the `.so` per architecture on 22.04, `vm/push.sh` builds it in the VM.
- The look is the Mac's (canvas 知了 Linux · 对齐 Mac): sizes are the Mac's numbers in px through `ui.text` (which converts to points), bold only where the Mac is semibold, and every widget the theme draws is styled in `ui.py` (no Yaru orange or discs). Check a UI change against the canvas at the same size, not just that it works.
- Shared UI text comes from `Resources/*.lproj/Localizable.strings`; Linux-only text is in `strings/`. Run `python3 scripts/strings.py` after changing either.
diff --git a/linux/README.md b/linux/README.md
index e80b0a2..123f612 100644
--- a/linux/README.md
+++ b/linux/README.md
@@ -3,7 +3,7 @@
Cicada 的 Linux 版:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录;打开同声传译后,把你说的话翻成对方的语言,用“知了 麦克风”传进会议。方案和取舍见 [docs/linux-plan.md](../docs/linux-plan.md)。
- 原生:Python 3 + PyGObject + GTK 3,声音走 PulseAudio / PipeWire(`libpulse-simple`,读默认输出的 monitor,不用授权)。只用 Ubuntu 桌面自带的库,不用 pip 包。
-- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求返回语言、原文和译文;需要 Ling key。和 Windows、Android 同一套做法。
+- 识别:分段发给 AI 服务的“听的模型”,一次请求返回语言、原文和译文。默认 Ling 的 Ming(`Ming-3.0-audio-flash`);用不了 Ling 时可在 设置 › AI 服务 换成 OpenRouter、ZenMux 或兼容 OpenAI 的自建服务(`cicada/core/providers.py`,推荐的听写模型是 Qwen 3.8 Omni Flash,比 Ming 慢 1–2 秒,测试见 `tools/audio-probe`),纪要、翻译和同传声音跟着换,只有“用你自己的声音”只能用 Ling。都需要一个 key,声音都会发到所选服务。和 Windows、Android 同一套做法。
- 纪要窗:浮在最上面、点它也不抢焦点(app 走 XWayland,窗口类型是 notification;GNOME 的 Wayland 不给普通窗口这两个能力)。**Linux 没法让窗口避开屏幕共享**,所以纪要窗一直带“可能被共享”。
- 纪要、记录格式(逐字节和 Mac 一致)、提示词、文案都和 Mac 版一致;英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Linux 独有的在 `strings/`。
- 同声传译:声音服务器里建一个虚拟麦克风“知了 麦克风”(`module-null-sink` + `module-remap-source`,PipeWire 和 PulseAudio 都行,不用装驱动),打开时设成默认输入,关掉或退出时把原来的麦克风还回去(被 `kill -9` 后下次启动也会还)。点纪要窗的麦克风、托盘的“开始说”或快捷键(Super + Shift + S,`cicada --speak`)开始 / 停止;Ming 一次请求识别并翻译,Ming 的声音流式播进知了 麦克风,下一句的声音在上一句播完前就已经在取。对方的声音从扬声器漏进麦克风的那句会丢掉,不说出去。
@@ -34,7 +34,7 @@ python3 cli.py speak ../windows/spike/clips/zh.wav --from zh-CN --to en --out /t
python3 cli.py roundtrip ~/Library/Application\ Support/LiveSubs/Sessions/*/session.json
```
-`cli.py` 读 Mac 版的 key 文件,不打印 key;环境里的代理会传给 urllib。
+`cli.py` 读 Mac 版的 key 文件,不打印 key;环境里的代理会传给 urllib。`--provider zenmux|openrouter`(可加 `--hear-model <id>`)换 AI 服务,读对应的 `ai-key-<服务>`。
## 安装(用户)
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index c6cb5c4..c2c793a 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -4,9 +4,11 @@ per connection, one JSON line back. Never in release builds.
state | start | stop | feed <wav> | sample | view notes|subtitles | show records|notes|settings|onboarding
target <code> | key-reload | windows | select <record id> | append <record id> <n> (a growing meeting)
+ provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> (设置 › AI 服务; "" back to the recommended)
speak-enable on|off | speak on|off (同声传译) | quit
calls <program=name,…>|none|real (meeting apps in a call) | endtimes <silence> <countdown> <grace>|off | endkeep
notes-tab notes|transcript | notes-search <text> | notes-wide on|off | onboarding-step <n> | settings-scroll <0-1>
+ settings-models on|off (unfold 自己选模型)
pill (the records window capsule's widget sizes)"""
from __future__ import annotations
@@ -115,7 +117,7 @@ def command(app, line: str) -> dict:
"lines": len(s.lines) if s else 0, "last": {"src": last.src, "dst": last.dst, "lang": last.srcLang} if last else None,
"pending": listen.pending, "problem": listen.problem, "problemKind": listen.problem_kind, "heardSeconds": round(listen.heard_seconds, 1),
"peak": round(listen.peak, 4), "notes": {"title": n.title, "topics": len(n.topics), "status": app.notes.status, "final": n.final},
- "key": app.ling.key_state, "view": app.settings.view, "target": app.settings.target_code,
+ "key": app.ling.key_state, "ai": _ai(app), "view": app.settings.view, "target": app.settings.target_code,
"ui": __import__("cicada.core.strings", fromlist=["language"]).language, "records": len(app.store.all()),
"tray": app.tray is not None, "home": Paths.data(),
"speak": {"enabled": app.settings.speakEnabled, "room": app.room.on, "active": app.speak.active, "stage": app.speak.stage,
@@ -164,6 +166,13 @@ def command(app, line: str) -> dict:
app.ling.key_changed()
threading.Thread(target=app.ling.check, daemon=True).start()
return {"ok": True}
+ if cmd == "provider":
+ app.set_ai_provider(arg)
+ return {"ok": True, "ai": _ai(app)}
+ if cmd == "ai-model":
+ kind, _, model = arg.partition(" ")
+ app.set_ai_model(kind, model.strip())
+ return {"ok": True, "ai": _ai(app)}
if cmd == "windows":
return {"ok": True, "notes": _window(app.notes_window), "records": _window(app.records_window),
"settings": _window(app.settings_window), "onboarding": _window(app.onboarding)}
@@ -268,6 +277,10 @@ def command(app, line: str) -> dict:
adj = app.settings_window.get_child().get_vadjustment()
adj.set_value(float(arg) * (adj.get_upper() - adj.get_page_size()))
return {"ok": True}
+ if cmd == "settings-models":
+ app.show_settings()
+ app.settings_window._toggle_models(arg != "off")
+ return {"ok": True}
if cmd == "onboarding-step":
app.show_onboarding()
app.onboarding.go(int(arg))
@@ -276,3 +289,11 @@ def command(app, line: str) -> dict:
app.quit()
return {"ok": True}
return {"ok": False, "error": "unknown command " + cmd}
+
+
+def _ai(app) -> dict:
+ """The AI service in use and what its last check found (never the key itself)."""
+ c, ling = app.ling.config(), app.ling
+ return {"provider": c.provider.id, "base": c.base, "text": c.text_model, "hear": c.hear_model, "voice": c.voice_model,
+ "state": ling.key_state, "hears": ling.hears, "problem": list(ling.problem) if ling.problem else None,
+ "catalog": [len(ling.text_catalog), len(ling.hear_catalog)], "keyFile": os.path.basename(app.key.path)}
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
index 2a229a6..1f79aa3 100644
--- a/linux/cicada/app/main.py
+++ b/linux/cicada/app/main.py
@@ -68,15 +68,15 @@ class Controller:
self.application = application
self.settings = AppSettings.load()
strings.load(self.settings.ui_code, resource_dirs())
- self.key = AIKey()
- self.ling = LingClient(self.key)
- self.ling.model = self.settings.model
+ # The AI service in use (设置 › AI 服务): its key file, address and models, read on every call.
+ self.key = AIKey(service=lambda: self.settings.aiProvider)
+ self.ling = LingClient(self.key, config=self.settings.ai_config)
self.store = SessionStore()
self.notes = NotesEngine(self.ling, self.store)
# 纪要语言 for notes written outside a meeting too (生成纪要 in the records window).
self.translator = Translator(self.ling)
self.listen = ListenEngine(self.ling, self.translator, self.store, self.notes, self.settings)
- # 同声传译: my microphone → Ming → 知了 麦克风. The listen side's loudness feeds its echo check.
+ # 同声传译: my microphone → the AI service → 知了 麦克风. The listen side's loudness feeds its echo check.
from ..core.speak import SpeakEngine
from .room import Player, VirtualMic
self.room = VirtualMic()
@@ -271,6 +271,38 @@ class Controller:
n.set_body(L("从右上角的知了图标打开会议记录,或开始听。"))
self.application.send_notification("still-here", n)
+ def set_ai_provider(self, provider: str) -> None:
+ """设置 › AI 服务: another service, with its own key file and models; checked again."""
+ from ..core.providers import named
+ if named(provider).id != provider or provider == self.settings.aiProvider:
+ return
+ self.settings.aiProvider = provider
+ self.settings.save()
+ self.ai_changed()
+
+ def set_ai_model(self, kind: str, model: str) -> None:
+ """A model chosen over the recommended one ("text", "hear" or "voice"; "" goes back to it)."""
+ s = self.settings
+ p = s.aiProvider
+ if kind == "text" and p == "ling":
+ s.model = model or s.FIELDS["model"]
+ else:
+ table = {"text": s.aiModels, "hear": s.aiHearModels, "voice": s.aiVoiceModels}.get(kind)
+ if table is None:
+ return
+ if model:
+ table[p] = model
+ else:
+ table.pop(p, None)
+ s.save()
+ self.ai_changed()
+
+ def ai_changed(self) -> None:
+ """The service, its address, models or key changed: forget the old check and check again."""
+ self.ling.key_changed()
+ if self.ling.has_key:
+ threading.Thread(target=self.ling.check, daemon=True).start()
+
def set_view(self, view: str) -> None:
if view not in ("notes", "subtitles") or view == self.settings.view:
return
@@ -486,6 +518,11 @@ class Controller:
if not self.ling.has_key:
self.show_onboarding()
return
+ if self.ling.usable and not self.ling.speaks:
+ # A service without a speech model: say why now, not "没听清" for every sentence.
+ self.speak.problem = L("这个服务不能出声音")
+ self.changed()
+ return
if not self.settings.speakEnabled or not self.room.on:
if not self.set_speak_enabled(True):
self.speak.problem = L("没能建好知了麦克风")
diff --git a/linux/cicada/app/notes_window.py b/linux/cicada/app/notes_window.py
index 6d6df88..c47a4fd 100644
--- a/linux/cicada/app/notes_window.py
+++ b/linux/cicada/app/notes_window.py
@@ -693,10 +693,13 @@ class NotesWindow(Gtk.Window):
body = L("音频服务已断开,本次会议记录已保存") if session is not None and session.lines else L("没能开始听")
self._state_card(box, "audio-volume-muted-symbolic", "warn", L("系统声音中断"), body, L("开始听"), self.app.toggle_listening)
elif kind == "network" and (line is None or listen.listening):
- self._state_card(box, "network-offline-symbolic", "warn", L("连不上 Ling"), L("请检查网络。恢复后会自动继续,断开期间的声音无法识别"))
+ service = self.app.ling.provider.name
+ self._state_card(box, "network-offline-symbolic", "warn", L("连不上 Ling") if service == "Ling" else LF("连不上 %@", service),
+ L("请检查网络。恢复后会自动继续,断开期间的声音无法识别"))
elif kind == "key":
+ ling = self.app.ling.provider.id == "ling"
self._state_card(box, "dialog-password-symbolic", "warn", listen.problem or L("Ling key 无效"),
- L("在设置里更换 Ling key"), L("设置"), self.app.show_settings)
+ L("在设置里更换 Ling key") if ling else L("在 设置 › AI 服务 里换一个"), L("设置"), self.app.show_settings)
elif line is None:
if listen.listening:
hearing = listen.pending > 0 or listen.level >= 0.01
diff --git a/linux/cicada/app/onboarding.py b/linux/cicada/app/onboarding.py
index d710960..8fabaca 100644
--- a/linux/cicada/app/onboarding.py
+++ b/linux/cicada/app/onboarding.py
@@ -103,7 +103,7 @@ class Onboarding(Gtk.Window):
self.head.pack_start(self.app_logo(34), False, False, 0)
if self.step == DONE:
return
- names = [L("接 Ling"), L("听声音"), L("看效果"), L("同声传译")]
+ names = [L("接 Ling") if self.app.settings.aiProvider == "ling" else L("接 AI 服务"), L("听声音"), L("看效果"), L("同声传译")]
bars = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6, homogeneous=True)
for i, name in enumerate(names):
cap = ui.panel(Gtk.Box(), "stepbar", "on" if i <= self.step else "")
@@ -182,6 +182,9 @@ class Onboarding(Gtk.Window):
# 1. Ling key
def _key_step(self) -> None:
+ if self.app.settings.aiProvider != "ling":
+ self._other_step()
+ return
self._title(L("接上 Ling"), L("识别、翻译和纪要都靠它,约 1 分钟。"))
entry = Gtk.Entry()
entry.set_visibility(False)
@@ -233,6 +236,52 @@ class Onboarding(Gtk.Window):
hint = ui.text(L("只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)"), 13, "secondary", wrap=False)
self.footer.pack_start(hint, True, True, 0)
self.footer.pack_end(self._primary(L("继续"), self._key_next), False, False, 0)
+ # A way out for people who can't use Ling: another service, saying what it lacks.
+ self.footer.pack_end(ui.link(L("用不了 Ling?"), lambda: self._switch("openrouter")), False, False, 0)
+ GLib.idle_add(lambda: entry.grab_focus() and False)
+
+ OTHERS = ("openrouter", "zenmux")
+
+ def _switch(self, provider: str) -> None:
+ self.app.set_ai_provider(provider)
+ self.render()
+
+ def _other_step(self) -> None:
+ """用其他服务 (OnboardingKey.swift › otherEntry): OpenRouter or ZenMux, their key, and what
+ they lack. A custom address is set up in 设置 › AI 服务."""
+ from ..core import providers
+ p = providers.named(self.app.settings.aiProvider)
+ self._title(L("用其他服务"), L("听、纪要和翻译都能用,模型已经选好。"))
+ entry = Gtk.Entry()
+ entry.set_visibility(False)
+ entry.set_placeholder_text(LF("粘贴 %@ 的 key", p.name))
+ ui.classes(entry, "keyentry")
+ entry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "view-reveal-symbolic")
+ entry.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY, L("显示 key"))
+ entry.connect("icon-press", lambda e, *_: e.set_visibility(not e.get_visibility()))
+ entry.connect("activate", lambda *_: self._save_key(entry.get_text()))
+ self.key_entry = entry
+ self.key_status = ui.text("", 13, "secondary", width_chars=40)
+ top = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
+ choices = ui.segmented([(i, providers.named(i).name) for i in self.OTHERS], p.id if p.id in self.OTHERS else self.OTHERS[0],
+ lambda v: v != self.app.settings.aiProvider and self._switch(v))
+ top.pack_start(choices, False, False, 0)
+ if p.site:
+ top.pack_end(ui.button(LF("打开 %@", p.name) + " ↗", lambda: open_uri(p.site), "outline midbtn"), False, False, 0)
+ field = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
+ field.pack_start(entry, True, True, 0)
+ field.pack_start(ui.button(L("粘贴并检查"), self._paste, "darkbtn midbtn"), False, False, 0)
+ lacks = ui.hbox(4, ui.text(L("少了:"), 12, "secondary", wrap=False),
+ ui.text(L("用你自己的声音"), 12, "ink", bold=True, wrap=False),
+ ui.text(L("(只有 Ling 支持)"), 12, "secondary", wrap=False))
+ lacks = ui.panel(ui.pad(lacks, 8, 10), "raised")
+ card = ui.panel(ui.pad(ui.vbox(14, top, field, self.key_status, lacks), 22), "bigcard")
+ self.page.pack_start(ui.gap(card, 24), False, False, 0)
+ if self.app.ling.has_key and self.app.ling.key_state == lingmod.OK:
+ self._key_ok()
+ self.footer.pack_start(ui.link(L("‹ 还是用 Ling"), lambda: self._switch("ling")), False, False, 0)
+ self.footer.pack_start(ui.text(LF("仅保存在本机当前账户下,仅发送至 %@", p.name), 13, "secondary", wrap=False), True, True, 0)
+ self.footer.pack_end(self._primary(L("继续"), self._key_next), False, False, 0)
GLib.idle_add(lambda: entry.grab_focus() and False)
def _key_next(self) -> None:
@@ -247,7 +296,9 @@ class Onboarding(Gtk.Window):
def _paste(self) -> None:
text = (Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).wait_for_text() or "").strip()
if not text.startswith("sk-"):
- self._key_problem(L("剪贴板里没有 sk- 开头的 key,先在 Ling 开放平台复制。"))
+ name = self.app.ling.provider.name
+ self._key_problem(L("剪贴板里没有 sk- 开头的 key,先在 Ling 开放平台复制。") if name == "Ling"
+ else LF("剪贴板里没有 sk- 开头的 key,请先去 %@ 复制。", name))
return
self.key_entry.set_text(text)
self._save_key(text)
@@ -285,8 +336,9 @@ class Onboarding(Gtk.Window):
self._key_ok()
GLib.timeout_add(700, lambda: (self.step == KEY and self.go(AUDIO)) and False)
else:
+ name = self.app.ling.provider.name
self._key_problem(L("这个 key 无效,请检查是否复制完整,或重新创建一个") if state == lingmod.INVALID
- else L("连不上 Ling,检查网络或代理"))
+ else L("连不上 Ling,检查网络或代理") if name == "Ling" else LF("连不上 %@,请检查网络或代理", name))
return False
GLib.idle_add(done)
threading.Thread(target=check, daemon=True).start()
diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.py
index 799764f..859c8a1 100644
--- a/linux/cicada/app/records_window.py
+++ b/linux/cicada/app/records_window.py
@@ -438,7 +438,8 @@ class RecordsWindow(Gtk.Window):
from .settings_window import SHORTCUTS, gnome_shortcut
speak = (LF("按 %@ 说话,对方听到翻译后的声音", SHORTCUTS["speak"][2].replace(" + Shift + ", " ⇧ "))
if gnome_shortcut("speak") else L("点纪要窗的麦克风说话,对方听到翻译后的声音"))
- steps = ((L("接上 Ling"), L("只存在这台电脑上(只有你的账户能读)") if key else L("识别、翻译和纪要都靠它,约 1 分钟"), key),
+ service = L("接上 Ling") if app.settings.aiProvider == "ling" else LF("接上 %@", app.ling.provider.name)
+ steps = ((service, L("只存在这台电脑上(只有你的账户能读)") if key else L("识别、翻译和纪要都靠它,约 1 分钟"), key),
(L("听一下电脑里的声音"), L("放一段测试声音,看音量条动起来"), audio),
(L("看看效果"), L("一段 9 秒的英文会议,字幕和纪要一句句出来"), sample),
(L("同声传译"), L("以后在设置 › 同声传译里打开") if app.settings.speakLater and not app.settings.speakEnabled
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index 008ccab..19bcaf3 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -1,6 +1,6 @@
"""设置, GNOME preferences style: groups of boxed-list rows, the title and a grey line on the left and
-the control on the right. Ling key, languages, what shows while listening (and 登录时启动), the
-model, about."""
+the control on the right. AI 服务 (the service, its key, what works with it, its models), languages,
+what shows while listening (and 登录时启动), 同声传译, 结束会议, about."""
from __future__ import annotations
import os
@@ -153,45 +153,14 @@ class SettingsWindow(Gtk.Window):
ui.pad(page, 8, 32, 28, 32)
scroll.add(page)
self.add(scroll)
+ self.scroll = scroll
def save():
s.save()
app.settings_changed()
- # Ling key
- self.key_line = ui.text("", 13, "ink mono", wrap=False)
- self.key_status = ui.hbox(6)
- key_left = ui.vbox(4, self.key_line, self.key_status)
- self.change_button = ui.button(L("更换…"), self._toggle_entry, "outline")
- self.remove_button = ui.button(L("删除"), self.remove_key, "dangertext")
- key_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
- key_row.pack_start(key_left, True, True, 0)
- for b in (self.change_button, self.remove_button):
- b.set_valign(Gtk.Align.CENTER)
- key_row.pack_start(b, False, False, 0)
- key_row = ui.panel(ui.pad(key_row, 10, 14), "prow")
- self.key_entry = Gtk.Entry()
- self.key_entry.set_visibility(False)
- self.key_entry.set_placeholder_text("sk-…")
- self.key_entry.connect("activate", lambda *_: self.save_key())
- self.key_entry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "view-reveal-symbolic")
- self.key_entry.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY, L("显示 key"))
- self.key_entry.connect("icon-press", lambda e, *_: e.set_visibility(not e.get_visibility()))
- entry_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
- entry_row.pack_start(self.key_entry, True, True, 0)
- entry_row.pack_start(ui.button(L("保存"), self.save_key, "darkbtn"), False, False, 0)
- self.entry_row = ui.panel(ui.pad(entry_row, 12, 16), "prow")
- get_key = Gtk.Button()
- get_key.add(ui.pad(ui.hbox(8, ui.text(L("获取 Ling key"), 13, "ink", wrap=False)), 10, 14))
- get_key.get_child().pack_end(ui.icon("external-link-symbolic", 14), False, False, 0)
- ui.classes(get_key, "linkrow")
- get_key.connect("clicked", lambda *_: open_uri(LING_PLATFORM))
- # Shown and hidden by show_key_state; show_all() must leave them alone.
- self.entry_row.set_no_show_all(True)
- entry_row.show_all()
- self.key_group = ui.boxed([key_row, self.entry_row, get_key])
- page.pack_start(self._group(L("Ling key"), self.key_group,
- L("只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)")), False, False, 0)
+ # AI 服务: the service and its key, what works with it, and its models (AISettings.swift).
+ self._ai_section(page)
# Languages
def set_target(v):
@@ -237,17 +206,6 @@ class SettingsWindow(Gtk.Window):
page.pack_start(self._speak_group(combos), False, False, 0)
page.pack_start(self._end_group(), False, False, 0)
- # Model
- def set_model(v):
- s.model = v
- app.ling.model = v
- save()
- model = choice([("Ling-3.1-flash", "Ling-3.1-flash"), ("Ling-3.0-flash", "Ling-3.0-flash")], s.model, set_model)
- combos.append(model)
- page.pack_start(self._group(L("模型"), ui.boxed([
- ui.prow(L("翻译与纪要模型"), model, L("3.1 更准;3.0 更快、更省")),
- ui.prow(L("语音识别"), ui.text(L("Ming(云端)"), 12, "tertiary", wrap=False))])), False, False, 0)
-
# About
# 版本 with the update check under it and its button (UpdateViews' settings row).
self.version_slot = ui.hbox(0)
@@ -270,6 +228,7 @@ class SettingsWindow(Gtk.Window):
for c in combos:
ui.no_wheel(c, scroll)
app.ling.on_change(lambda: GLib.idle_add(self.show_key_state))
+ self.ai_shown = None
self.connect("show", lambda *_: self.show_key_state())
self.refresh_version()
@@ -399,7 +358,7 @@ class SettingsWindow(Gtk.Window):
code = app.speak.target
voice.handler_block_by_func(set_voice) if getattr(voice, "_wired", False) else None
voice.remove_all()
- for v, n, tags in voicemod.voices(code):
+ for v, n, tags in voicemod.voices(code, app.ling.config()):
voice.append(v, "%s · %s" % (n, "、".join(L(t) for t in tags)))
voice.set_active_id(app.speak.voice(code) or "")
if getattr(voice, "_wired", False):
@@ -413,6 +372,7 @@ class SettingsWindow(Gtk.Window):
fill_voices()
voice.connect("changed", set_voice)
voice._wired = True
+ self._fill_voices = fill_voices # again when the AI service (and so its voices) changes
def preview():
code = app.speak.target
@@ -425,7 +385,8 @@ class SettingsWindow(Gtk.Window):
p = Player(None) # the speakers, not the room
start, n = time.monotonic(), 0
try:
- for pcm in app.ling.speech(text, voice=app.speak.voice(code) or "US_Emma", language=voicemod.ming_language(code)):
+ for pcm in app.ling.speech(text, voice=app.speak.voice(code) or "US_Emma",
+ language=voicemod.ming_language(code, app.ling.config())):
n += len(pcm)
p.write(pcm)
p.drain()
@@ -436,6 +397,7 @@ class SettingsWindow(Gtk.Window):
p.close()
threading.Thread(target=run, daemon=True).start()
voice_box = ui.hbox(8, voice, ui.button(L("试听"), preview, "outline"))
+ self.voice_box = voice_box
combos.extend([mine, theirs, voice])
for title, control, sub in ((L("我说"), mine, None),
(L("对方听到"), theirs, L("跟随对方时,对方说什么语言就翻成什么")),
@@ -484,46 +446,260 @@ class SettingsWindow(Gtk.Window):
if self.entry_row.get_visible():
self.key_entry.grab_focus()
+ # AI 服务
+
+ def _ai_section(self, page) -> None:
+ """The service menu, its key (and a custom service's address), what works with it, and the
+ models chosen for it. Rebuilt in parts by show_key_state as the service and its check change."""
+ from ..core import providers
+ app, s = self.app, self.app.settings
+ self.provider_menu = choice([(p.id, "Ling" + L("(推荐)") if p.id == "ling" else L(p.name)) for p in providers.ALL],
+ s.aiProvider, app.set_ai_provider)
+ self.key_line = ui.text("", 13, "ink mono", wrap=False)
+ self.key_status = ui.hbox(6)
+ key_left = ui.vbox(4, self.key_line, self.key_status)
+ self.change_button = ui.button(L("更换…"), self._toggle_entry, "outline")
+ self.remove_button = ui.button(L("删除"), self.remove_key, "dangertext")
+ key_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
+ key_row.pack_start(key_left, True, True, 0)
+ for b in (self.change_button, self.remove_button):
+ b.set_valign(Gtk.Align.CENTER)
+ key_row.pack_start(b, False, False, 0)
+ key_row = ui.panel(ui.pad(key_row, 10, 14), "prow")
+ self.key_entry = Gtk.Entry()
+ self.key_entry.set_visibility(False)
+ self.key_entry.set_placeholder_text("sk-…")
+ self.key_entry.connect("activate", lambda *_: self.save_key())
+ self.key_entry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "view-reveal-symbolic")
+ self.key_entry.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY, L("显示 key"))
+ self.key_entry.connect("icon-press", lambda e, *_: e.set_visibility(not e.get_visibility()))
+ entry_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
+ entry_row.pack_start(self.key_entry, True, True, 0)
+ entry_row.pack_start(ui.button(L("保存并检查"), self.save_key, "darkbtn"), False, False, 0)
+ self.entry_row = ui.panel(ui.pad(entry_row, 12, 16), "prow")
+ # A custom service: its address and models come before a key can be checked.
+ self.custom_base = self._field("https://api.example.com/v1", s.aiCustomBase)
+ self.custom_text = self._field(L("例如 qwen3:14b"), s.aiModels.get("custom", ""))
+ self.custom_hear = self._field(L("例如 qwen3-omni"), s.aiHearModels.get("custom", ""))
+ self.custom_rows = ui.boxed([ui.prow(L("地址"), self.custom_base), ui.prow(L("文字模型"), self.custom_text, L("纪要和整句翻译")),
+ ui.prow(L("听的模型"), self.custom_hear, L("要能输入音频:听对方和“我说”都用它"))])
+ self.custom_rows.set_no_show_all(True)
+ self.custom_rows.get_child().show_all()
+ self.get_key = Gtk.Button()
+ self.get_key_label = ui.text("", 13, "ink", wrap=False)
+ self.get_key.add(ui.pad(ui.hbox(8, self.get_key_label), 10, 14))
+ self.get_key.get_child().pack_end(ui.icon("external-link-symbolic", 14), False, False, 0)
+ ui.classes(self.get_key, "linkrow")
+ self.get_key.connect("clicked", lambda *_: open_uri(app.ling.provider.site or ""))
+ self.get_key.set_no_show_all(True)
+ self.get_key.get_child().show_all()
+ # Shown and hidden by show_key_state; show_all() must leave them alone.
+ self.entry_row.set_no_show_all(True)
+ entry_row.show_all()
+ self.key_group = ui.boxed([key_row, self.entry_row, self.get_key])
+ title = ui.hbox(8, ui.pad(ui.text(L("AI 服务"), 12, "group-title", bold=True, wrap=False), 0, 0, 0, 2))
+ title.pack_end(self.provider_menu, False, False, 0)
+ self.lock_line = ui.text("", 11, "tertiary", width_chars=60)
+ page.pack_start(ui.vbox(6, title, self.custom_rows, self.key_group, ui.pad(self.lock_line, 0, 2, 0, 2)), False, False, 0)
+ # What works with it.
+ self.uses = ui.vbox(0)
+ page.pack_start(self._group(L("现在能用的"), self.uses), False, False, 0)
+ # Its models, folded away: the recommended ones are already chosen.
+ self.models = ui.vbox(0)
+ self.models.set_no_show_all(True)
+ fold = Gtk.Button()
+ self.fold_label = ui.text(L("自己选模型") + " ›", 12, "secondary", wrap=False)
+ fold.add(self.fold_label)
+ ui.classes(fold, "linkrow")
+ fold.set_halign(Gtk.Align.START)
+ fold.connect("clicked", lambda *_: self._toggle_models())
+ self.footnote = ui.text("", 11, "tertiary", width_chars=60)
+ page.pack_start(ui.vbox(6, fold, self.models, ui.pad(self.footnote, 0, 2, 0, 2)), False, False, 0)
+
+ def _field(self, placeholder: str, value: str) -> Gtk.Entry:
+ e = Gtk.Entry()
+ e.set_placeholder_text(placeholder)
+ e.set_text(value)
+ e.set_width_chars(26)
+ e.connect("activate", lambda *_: self.save_key())
+ return e
+
+ def _toggle_models(self, on: bool | None = None) -> None:
+ on = not self.models.get_visible() if on is None else on
+ self.models.set_visible(on)
+ if on:
+ self.models.foreach(lambda w: w.show_all())
+ ui.retext(self.fold_label, L("自己选模型") + (" ⌄" if on else " ›"))
+
+ def _model_menu(self, kind: str, current: str, recommended, listed: list) -> Gtk.Widget:
+ """Recommended models first, with why, then everything the service lists; a name can be typed."""
+ c = Gtk.ComboBoxText.new_with_entry()
+ seen = set()
+ for m in recommended:
+ c.append(m.id, m.id + (" · " + L(m.note) if m.note else ""))
+ seen.add(m.id)
+ for mid in listed:
+ if mid not in seen:
+ c.append(mid, mid)
+ seen.add(mid)
+ if current not in seen:
+ c.append(current, current)
+ c.set_active_id(current)
+ c.get_child().set_text(current)
+ c.get_child().set_width_chars(26)
+
+ def chosen(w):
+ mid = w.get_active_id()
+ if mid is not None:
+ w.get_child().set_text(mid) # the id, not the label with its note
+ if mid != getattr(self.app.ling.config(), kind + "_model"):
+ self.app.set_ai_model(kind, mid)
+ c.connect("changed", chosen)
+ c.get_child().connect("activate", lambda e: self.app.set_ai_model(kind, e.get_text().strip()))
+ if getattr(self, "scroll", None) is not None:
+ ui.no_wheel(c, self.scroll)
+ return c
+
+ def _uses_rows(self) -> list:
+ """现在能用的 (AISettings.swift › usage), with 听对方 first: on the ports the service hears."""
+ ling = self.app.ling
+ c = ling.config()
+ name = L(c.provider.name) if c.provider.id == "custom" else c.provider.name
+ on = ling.usable
+ uses = LF("用 %@", name)
+ rows = []
+ if not on:
+ hear = (L("需要 key"), "off", L("填好 key 后可用"))
+ elif ling.hears is False:
+ hear = (L("还不能用"), "off", L("这个模型听不了声音,换一个支持音频输入的"))
+ elif c.is_ling:
+ hear = (uses, "ok", L("Ming 一次识别并翻译"))
+ else:
+ hear = (uses, "ok", c.hear_model + " · " + L("比 Ling 晚 1–2 秒出字"))
+ rows.append((L("听对方"),) + hear)
+ rows.append((L("实时纪要"),) + ((uses, "ok", L("会中每 45 秒更新")) if on else (L("需要 key"), "off", L("填好 key 后可用"))))
+ rows.append((L("翻译"),) + ((uses, "ok", L("整句用它;不行时换 Google")) if on else ("Google", "off", L("没有 key 时照常可用"))))
+ if ling.speaks:
+ rows.append((L("同传声音"), uses, "ok", L("Ming 的声音") if c.is_ling else c.voice_model))
+ else:
+ rows.append((L("同传声音"), L("用不了"), "off", L("这个服务不能出声音") if on else L("填好 key 后可用")))
+ if not c.is_ling:
+ rows.append((L("你自己的声音"), L("只有 Ling"), "ling", L("换用 Ling 才有")))
+ out = []
+ for title, tag, style, note in rows:
+ label = ui.text(tag, 11, "", bold=True, wrap=False, ellipsize=False)
+ chip = ui.panel(ui.pad(label, 2, 8), "aitag", style)
+ out.append(ui.prow(title, chip, note))
+ return out
+
+ def _model_rows(self) -> list:
+ app = self.app
+ c = app.ling.config()
+ p = c.provider
+ if p.id == "ling":
+ menu = choice([(m.id, m.id) for m in p.text_models], c.text_model, lambda v: app.set_ai_model("text", v))
+ if getattr(self, "scroll", None) is not None:
+ ui.no_wheel(menu, self.scroll)
+ return [ui.prow(L("文字模型"), menu, L("3.1 更准;3.0 更快、更省")),
+ ui.prow(L("听的模型"), ui.text(c.hear_model, 12, "tertiary", wrap=False), L("Ming 一次识别并翻译"))]
+ if p.id == "custom":
+ self.custom_voice_model = self._field(L("例如 kokoro"), app.settings.aiVoiceModels.get("custom", ""))
+ self.custom_voice = self._field(L("例如 af_heart"), app.settings.aiCustomVoice)
+ self.custom_voice_base = self._field(L("跟上面一样"), app.settings.aiCustomVoiceBase)
+ return [ui.prow(L("声音模型"), self.custom_voice_model, L("需支持 /audio/speech;不填则同声传译用不了")),
+ ui.prow(L("声音"), self.custom_voice), ui.prow(L("地址"), self.custom_voice_base)]
+ rows = [ui.prow(L("听的模型"), self._model_menu("hear", c.hear_model, p.hear_models, app.ling.hear_catalog),
+ L("听对方和“我说”都用它")),
+ ui.prow(L("文字模型"), self._model_menu("text", c.text_model, p.text_models, app.ling.text_catalog), L("纪要和整句翻译"))]
+ if p.has_voices:
+ rows.append(ui.prow(L("声音模型"), self._model_menu("voice", c.voice_model, p.voice_models, []), L("同传念给对方")))
+ return rows
+
def show_key_state(self) -> bool:
- k = self.app.key.read() or ""
- state = self.app.ling.key_state
+ app = self.app
+ c = app.ling.config()
+ p = c.provider
+ k = app.ling.current_key()
+ state = app.ling.key_state
+ name = L(p.name) if p.id == "custom" else p.name
ui.clear(self.key_status)
- have = bool(k)
- ui.retext(self.key_line, AIKey.masked(k) if have else L("还没填 API key"))
+ have = k is not None
+ ui.retext(self.key_line, AIKey.masked(k) if k else (L("本机服务,不用 key") if have else
+ (L("还没填好") if p.id == "custom" else L("还没填 API key"))))
+ problem = None
+ if app.ling.problem:
+ problem = LF(app.ling.problem[0], *[L(a) if isinstance(a, str) else a for a in app.ling.problem[1:]])
icon_name, cls, label = {
- lingmod.OK: ("object-select-symbolic", "ok", L("可以用")),
+ lingmod.OK: ("object-select-symbolic", "ok", L("已连接") +
+ " · " + LF("%@ · 响应约 %@ 秒", c.text_model, "%.1f" % (app.ling.seconds or 0))),
lingmod.CHECKING: ("content-loading-symbolic", "secondary", L("正在检查…")),
- lingmod.INVALID: ("dialog-error-symbolic", "warn", L("这个 key 无效,请检查是否复制完整,或重新创建一个")),
- lingmod.UNREACHABLE: ("network-offline-symbolic", "warn", L("连不上 Ling,检查网络或代理")),
+ lingmod.INVALID: ("dialog-error-symbolic", "warn", LF("%@ 提示 key 无效,请检查是否复制完整,或重新创建一个", name)),
+ lingmod.UNREACHABLE: ("network-offline-symbolic", "warn", problem or LF("连不上 %@,请检查网络或代理", name)),
}.get(state, (None, "secondary", ""))
+ if state == lingmod.OK and problem:
+ icon_name, cls, label = "dialog-warning-symbolic", "warn", problem
if have and label:
if icon_name:
img = ui.icon(icon_name, 14)
ui.classes(img, cls)
self.key_status.pack_start(img, False, False, 0)
- self.key_status.pack_start(ui.text(label, 12, cls, width_chars=36), False, False, 0)
+ self.key_status.pack_start(ui.text(label, 12, cls, width_chars=48), False, False, 0)
self.key_status.show_all()
self.key_status.set_visible(have and bool(label))
- self.change_button.set_visible(have)
- self.remove_button.set_visible(have)
- self.entry_row.set_visible(not have or state == lingmod.INVALID)
+ self.change_button.set_visible(bool(k))
+ self.remove_button.set_visible(bool(k))
+ self.entry_row.set_visible(not k or state == lingmod.INVALID)
+ self.custom_rows.set_visible(p.id == "custom")
+ self.get_key.set_visible(p.site is not None and not k)
+ ui.retext(self.get_key_label, L("获取 Ling key") if p.id == "ling" else LF("打开 %@", name))
+ host = (c.base or "").split("//")[-1].split("/")[0] or L("你填的地址")
+ ui.retext(self.lock_line, L("仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)") if p.id == "ling"
+ else LF("仅保存在本机当前账户下,仅发送至 %@", host) if p.id == "custom" else LF("仅保存在本机当前账户下,仅发送至 %@(%@)", name, host))
+ sent = host if p.id == "custom" else name
+ ui.retext(self.footnote, LF("听的时候,电脑里的声音会发给 %@。", sent) if p.id == "ling"
+ else L("按所选模型计费。") + LF("听的时候,电脑里的声音会发给 %@。", sent))
+ # The rows that depend on the service and what its check found.
+ shown = (p.id, state, app.ling.hears, bool(k), c.text_model, c.hear_model, c.voice_model,
+ len(app.ling.text_catalog), len(app.ling.hear_catalog))
+ if shown != getattr(self, "ai_shown", None):
+ self.ai_shown = shown
+ ui.clear(self.uses)
+ self.uses.pack_start(ui.boxed(self._uses_rows()), False, False, 0)
+ self.uses.show_all()
+ ui.clear(self.models)
+ self.models.pack_start(ui.boxed(self._model_rows()), False, False, 0)
+ if self.models.get_visible():
+ self.models.foreach(lambda w: w.show_all())
+ if self.provider_menu.get_active_id() != p.id:
+ self.provider_menu.set_active_id(p.id)
+ if hasattr(self, "_fill_voices"):
+ self._fill_voices()
+ if hasattr(self, "voice_box"):
+ self.voice_box.set_sensitive(app.ling.speaks or not app.ling.usable)
return False
def save_key(self) -> None:
+ app, s = self.app, self.app.settings
+ if s.aiProvider == "custom":
+ # The address and models typed so far, kept even before a key.
+ s.aiCustomBase = self.custom_base.get_text().strip()
+ s.aiModels["custom"] = self.custom_text.get_text().strip()
+ s.aiHearModels["custom"] = self.custom_hear.get_text().strip()
+ if hasattr(self, "custom_voice_model"):
+ s.aiVoiceModels["custom"] = self.custom_voice_model.get_text().strip()
+ s.aiCustomVoice = self.custom_voice.get_text().strip()
+ s.aiCustomVoiceBase = self.custom_voice_base.get_text().strip()
+ s.save()
text = self.key_entry.get_text().strip()
- if not text.startswith("sk-"):
- self.key_entry.set_placeholder_text(L("复制 sk- 开头的 key,回来粘贴"))
+ if text:
+ if not app.key.save(text):
+ return
self.key_entry.set_text("")
- return
- if not self.app.key.save(text):
- return
- self.key_entry.set_text("")
- self.app.ling.key_changed()
- threading.Thread(target=self.app.ling.check, daemon=True).start()
+ app.ai_changed()
def remove_key(self) -> None:
self.app.key.remove()
- self.app.ling.key_changed()
+ self.app.ai_changed()
@staticmethod
def _open_folder(path) -> None:
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
index b138000..af02ecc 100644
--- a/linux/cicada/app/ui.py
+++ b/linux/cicada/app/ui.py
@@ -116,6 +116,13 @@ button.iconbtn.on { background-color: #F3F4F6; color: #15171C; }
.warnrow label { color: #5A2A16; }
.group-title { font-weight: 700; color: #6B7080; }
+.aitag { border-radius: 6px; }
+.aitag.ok { background-color: #E3F3EA; }
+.aitag.ok label { color: #1F6B3A; }
+.aitag.off { background-color: #F2F3F5; }
+.aitag.off label { color: #5A5F6B; }
+.aitag.ling { background-color: #FDEEE8; }
+.aitag.ling label { color: #B23A12; }
.chip { background-color: #F2F3F5; border-radius: 5px; padding: 1px 6px; color: #15171C; }
.chip.now { background-color: #E8552B; color: #FFFFFF; }
.chip.time { background-color: transparent; padding: 0; color: #B33A14; }
@@ -252,6 +259,7 @@ entry.keyentry { border-radius: 10px; min-height: 34px; }
.stepbar { background-color: #DDDEE2; border-radius: 2px; min-height: 4px; }
.stepbar.on { background-color: #15171C; }
.bigcard { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 18px; }
+.raised { background-color: #F6F7F9; border-radius: 8px; }
.midcard { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 12px; }
.tipcard { background-color: #FFFFFF; border-radius: 14px; }
.hair { background-color: #E4E6EA; min-height: 1px; }
diff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.py
index 3978126..a61463d 100644
--- a/linux/cicada/core/ling.py
+++ b/linux/cicada/core/ling.py
@@ -1,7 +1,7 @@
-"""Ling (ant-ling.com), OpenAI-compatible, and the user's key."""
+"""The AI service (Ling by default, or another OpenAI-compatible one: providers.py) and the user's keys."""
from __future__ import annotations
-import base64
+import io
import os
import random
import socket
@@ -9,72 +9,73 @@ import threading
import time
import urllib.error
import urllib.request
+import wave
from . import jsonfmt
from .jsonfmt import arr, obj, string
-from .settings import DEFAULT_MODEL
+from .providers import LING, AIConfig, catalog, is_local
from .support import Log, Paths
class AIKey:
- """The user's Ling key, only ever in the `ling-api-key` file, mode 0600, in ~/.config/cicada (as
- on the Mac): never in settings, logs or exports."""
+ """The user's AI keys, one file per service (`ling-api-key`, `ai-key-<service>`), mode 0600, in
+ ~/.config/cicada (as on the Mac): never in settings, logs or exports. `service` says which one
+ is in use; `path` pins one file (cli.py reads the Mac's)."""
- def __init__(self, path: str | None = None):
+ def __init__(self, path: str | None = None, service=None):
self._path = path
- self._cached = None
- self._loaded = False
+ self.service = service or (lambda: "ling")
+ self._cache: dict = {}
self._lock = threading.Lock()
@property
def path(self) -> str:
- return self._path or Paths.key_file()
+ return self._path or Paths.key_file(self.service())
def read(self) -> str | None:
+ path = self.path
with self._lock:
- if self._loaded:
- return self._cached
- self._loaded = True
+ if path in self._cache:
+ return self._cache[path]
+ value = None
try:
- if os.path.isfile(self.path):
- with open(self.path, encoding="utf-8") as f:
- self._cached = f.read().strip() or None
- else:
- self._cached = None
+ if os.path.isfile(path):
+ with open(path, encoding="utf-8") as f:
+ value = f.read().strip() or None
except OSError as e:
Log.d("ai key: read failed %s" % type(e).__name__)
- self._cached = None
- return self._cached
+ self._cache[path] = value
+ return value
def save(self, key: str) -> bool:
k = key.strip()
+ path = self.path
with self._lock:
try:
- os.makedirs(os.path.dirname(self.path), mode=0o700, exist_ok=True)
+ os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
# Created 0600 from the start: the key is never readable by others, even briefly.
- fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(k)
- os.chmod(self.path, 0o600)
- self._cached = k
- self._loaded = True
+ os.chmod(path, 0o600)
+ self._cache[path] = k
return True
except OSError as e:
Log.d("ai key: save failed %s" % type(e).__name__)
return False
def remove(self) -> None:
+ path = self.path
with self._lock:
try:
- os.remove(self.path)
+ os.remove(path)
except OSError:
pass
- self._cached = None
- self._loaded = True
+ self._cache[path] = None
def reload(self) -> None:
with self._lock:
- self._loaded = False
+ self._cache.clear()
@staticmethod
def masked(key: str) -> str:
@@ -107,9 +108,13 @@ class Response:
class StreamResponse:
- def __init__(self, status: int, lines):
+ """A reply read as it arrives: `lines` (server-sent events) or, for raw audio, `chunks` (bytes)."""
+
+ def __init__(self, status: int, lines, content_type: str = "text/event-stream", chunks=None):
self.status = status
- self.lines = lines # an iterator of text lines (SSE)
+ self.lines = lines
+ self.content_type = content_type
+ self.chunks = chunks
class UrlTransport:
@@ -131,10 +136,10 @@ class UrlTransport:
raise TimeoutError() from e
raise OSError(str(e.reason)) from e
-
@staticmethod
def stream(url: str, body: str, headers: dict, timeout: float) -> StreamResponse:
- """A POST whose reply is read line by line as it arrives (Ming's server-sent speech)."""
+ """A POST whose reply is read as it arrives (speech): by line for server-sent events, else in
+ raw pieces (OpenRouter's speech streams the PCM bytes themselves)."""
req = urllib.request.Request(url, data=body.encode(), method="POST", headers=headers)
try:
r = urllib.request.urlopen(req, timeout=timeout)
@@ -149,30 +154,63 @@ class UrlTransport:
with r:
for raw in r:
yield raw.decode("utf-8", "replace").rstrip("\r\n")
- return StreamResponse(r.status, lines())
+ def chunks():
+ with r:
+ while True:
+ b = r.read(4800) # 0.1 s at 24 kHz: playback starts early
+ if not b:
+ return
+ yield b
+ return StreamResponse(r.status, lines(), r.headers.get("Content-Type") or "", chunks())
-BASE = "https://api.ant-ling.com/v1/"
-TTS_MODEL = "Ming-3.0-tts-0.5B"
-TTS_RATE = 24000
-AUDIO_MODEL = "Ming-3.0-audio-flash"
+
+BASE = LING.base
+TTS_MODEL = LING.voice_models[0].id
+TTS_RATE = 24000 # Ming, Gemini TTS and Kokoro all speak 24 kHz
+AUDIO_MODEL = LING.hear_models[0].id
# Search essays (Ling.swift), and the canned refusal some audio prompts get.
HIJACK_PREFIXES = ("根据现有检索证据", "暂未找到足够可靠的信息", "根据检索", "作为一个人工智能语言模型")
+def silence_wav(seconds: float = 0.5) -> bytes:
+ """A short quiet WAV (16 kHz mono 16-bit), to ask a model whether it takes audio at all."""
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(16000)
+ w.writeframes(b"\x00\x00" * int(16000 * seconds))
+ return buf.getvalue()
+
+
+def _ling_config() -> AIConfig:
+ return AIConfig(LING, LING.base, LING.text_models[0].id, LING.hear_models[0].id, LING.voice_models[0].id, LING.base)
+
+
class LingClient:
- """One instance for the app: the account allows about 2 requests per second across every model,
- so request *starts* go through one gate (≥ 0.6 s apart, overlapping is fine) in priority order.
- Two gateway quirks shape every call (see Ling.swift): thinking is always disabled, and the
- content goes in the system message with a fixed user instruction, because a question-like user
- message gets a search essay back; such replies are dropped. Calls block: run them off the UI thread."""
- spacing = 0.6
-
- def __init__(self, key: AIKey, transport=UrlTransport):
+ """One instance for the app, for whichever AI service the settings name (`config`). Request
+ *starts* go through one gate in priority order: Ling allows about 2 a second across every model
+ (≥ 0.6 s apart, overlapping is fine), the aggregators far more. Ling's gateway shapes every call
+ (see Ling.swift): thinking is always disabled, and the content goes in the system message with
+ a fixed user instruction, because a question-like user message gets a search essay back; such
+ replies are dropped. The other services get the same messages. Calls block: run them off the
+ UI thread."""
+ spacing: float | None = None # tests only: overrides the service's
+
+ def __init__(self, key: AIKey, transport=UrlTransport, config=None):
self.key = key
self.transport = transport
- self.model = DEFAULT_MODEL
- self.key_state = NONE if key.read() is None else UNCHECKED
+ self.config = config or _ling_config
+ self.key_state = NONE if self.current_key() is None else UNCHECKED
+ # Why the last check failed, shown under the key: a Mac string key and its arguments for LF()
+ # ("连不上 %@,请检查网络或代理", "ZenMux"); None when it didn't.
+ self.problem: tuple | None = None
+ self.seconds: float | None = None # how long the last good check took
+ # Whether the hear model takes audio: None until a check asked (always True on Ling).
+ self.hears: bool | None = None
+ self.text_catalog: list = []
+ self.hear_catalog: list = []
self.rate_limited_at = None
self._listeners = []
self._gate = threading.Condition()
@@ -187,51 +225,147 @@ class LingClient:
for l in list(self._listeners):
l()
+ @property
+ def provider(self):
+ return self.config().provider
+
+ def current_key(self) -> str | None:
+ """The key for the service in use. A custom service on this computer may need none: ""."""
+ c = self.config()
+ k = self.key.read()
+ if k is None and c.provider.id == "custom" and c.base and is_local(c.base):
+ return ""
+ return k
+
@property
def has_key(self) -> bool:
- return self.key.read() is not None
+ return self.current_key() is not None
@property
def usable(self) -> bool:
return self.has_key and self.key_state != INVALID
+ @property
+ def speaks(self) -> bool:
+ """Voices in the room from this service. Linux has no system voice to fall back on."""
+ return self.usable and self.config().has_voices
+
+ @property
+ def can_hear(self) -> bool:
+ """Listening and 同声传译 can work: the hear model wasn't found to refuse audio."""
+ return self.usable and self.hears is not False and bool(self.config().hear_model)
+
def key_changed(self) -> None:
- self.key_state = NONE if self.key.read() is None else UNCHECKED
+ """The key, the service or its models changed: forget what the last check found."""
+ self.key.reload()
+ self.key_state = NONE if self.current_key() is None else UNCHECKED
+ self.problem = None
+ self.hears = True if self.config().is_ling else None
+ self.text_catalog, self.hear_catalog = [], []
self._changed()
def check(self) -> str:
- """A tiny request that says whether the key works."""
+ """The cheapest request that proves the key: Ling's tiny model, else one token from the text
+ model. The others' hear model must also take audio (half a second of silence), and a custom
+ service must return JSON (the notes need it)."""
self.key_state = CHECKING
+ self.problem = None
self._changed()
+ c = self.config()
+ name = c.provider.name if c.provider.id != "custom" else "这个服务"
+ started = time.monotonic()
+ state = UNREACHABLE
try:
- self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=10.0, model="Ling-3.0-tiny")
+ if c.is_ling:
+ self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=10.0, model="Ling-3.0-tiny")
+ self.seconds = time.monotonic() - started
+ self.hears = True
+ else:
+ if c.base is None or not c.text_model:
+ raise LingError(LingError.NO_KEY)
+ self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=20.0)
+ self.seconds = time.monotonic() - started
+ if c.provider.id == "custom":
+ try:
+ self.chat("Reply with the JSON object {\"ok\": true}.", "Reply.", SPEAK, json=True, max_tokens=20, timeout=20.0)
+ except LingError as e:
+ if e.kind == LingError.HTTP:
+ self.problem = ("这个服务不支持 JSON(HTTP %lld),纪要用不了", e.status)
+ else:
+ raise
+ self.hears = self._hears(c)
state = OK
except LingError as e:
state = {LingError.NO_KEY: NONE, LingError.INVALID_KEY: INVALID,
LingError.RATE_LIMITED: OK}.get(e.kind, UNREACHABLE) # a busy key is still a good key
+ if e.kind == LingError.HTTP and e.status in (400, 404):
+ self.problem = (("找不到模型,或地址不对(HTTP %lld)", e.status) if c.provider.id == "custom"
+ else ("%@ 拒绝了请求(HTTP %lld),请检查模型名", name, e.status))
+ elif state == UNREACHABLE:
+ self.problem = ("连不上 %@,请检查网络或代理", name)
except Exception: # noqa: BLE001
state = UNREACHABLE
+ self.problem = ("连不上 %@,请检查网络或代理", name)
self.key_state = state
+ Log.d("ai %s: key check -> %s%s" % (c.provider.id, state, "" if self.hears is not False else " (hear model refuses audio)"))
self._changed()
+ if state == OK and not c.is_ling:
+ self.fetch_catalog()
return state
+ def _hears(self, c: AIConfig) -> bool | None:
+ """Whether the hear model takes audio: a 400 or 404 says no; anything else can't tell."""
+ if not c.hear_model:
+ return False
+ try:
+ self.chat("Transcribe the audio.", "Reply with what is said, or NONE.", SPEAK, max_tokens=10, timeout=20.0,
+ model=c.hear_model, audio=silence_wav())
+ return True
+ except LingError as e:
+ if e.kind == LingError.HTTP and e.status in (400, 404, 415, 422):
+ return False
+ if e.kind == LingError.HIJACKED:
+ return True
+ return None
+
+ def fetch_catalog(self) -> None:
+ """The service's models, for the model menus: those that chat, and those that hear. Quietly
+ just the recommended ones when the service has no `/models`."""
+ c = self.config()
+ k = self.current_key()
+ if c.is_ling or k is None or c.base is None:
+ return
+ try:
+ res = self.transport.send(c.base + "models", "GET", None, self._headers(k), 20.0)
+ except (OSError, TimeoutError):
+ return
+ if res.status != 200:
+ return
+ self.text_catalog = catalog(res.body, [m.id for m in c.provider.text_models], hears=False)
+ self.hear_catalog = catalog(res.body, [m.id for m in c.provider.hear_models], hears=True)
+ Log.d("ai %s: %d models, %d hear" % (c.provider.id, len(self.text_catalog), len(self.hear_catalog)))
+ self._changed()
+
def chat(self, content: str, instruction: str, priority: int, json: bool = False, max_tokens: int = 1024,
timeout: float = 30.0, model: str | None = None, audio: bytes | None = None) -> str:
"""One chat completion. `content` goes in the system message, `instruction` is the fixed user
- message, `audio` (a WAV) goes before it for Ming. Notes retry 429s with backoff; heard audio
- gets one retry (a lost reply loses the words); the rest fail fast so the caller can fall back."""
- k = self.key.read()
+ message, `audio` (a WAV) goes before it for the hear model. Notes retry 429s with backoff;
+ heard audio gets one retry (a lost reply loses the words); the rest fail fast so the caller
+ can fall back."""
+ k = self.current_key()
if k is None:
raise LingError(LingError.NO_KEY)
if self.key_state == INVALID:
raise LingError(LingError.INVALID_KEY)
- user = instruction if audio is None else [
- {"type": "audio_url", "audio_url": {"url": "data:audio/wav;base64," + base64.b64encode(audio).decode()}},
- {"type": "text", "text": instruction},
- ]
- body = {"model": model or self.model,
+ c = self.config()
+ if c.base is None:
+ raise LingError(LingError.NO_KEY)
+ model = model or c.text_model
+ user = instruction if audio is None else [c.audio_part(audio, model), {"type": "text", "text": instruction}]
+ body = {"model": model,
"messages": [{"role": "system", "content": content}, {"role": "user", "content": user}],
- "max_tokens": max_tokens, "temperature": 0.2, "thinking": {"type": "disabled"}, "stream": False}
+ "stream": False}
+ c.shape(body, max_tokens)
if json:
body["response_format"] = {"type": "json_object"}
payload = jsonfmt.write(body, pretty=False)
@@ -240,10 +374,10 @@ class LingClient:
attempt = 1
name = PRIORITY_NAMES[priority]
while True:
- self._acquire(priority)
+ self._acquire(priority, c.provider.spacing)
started = time.monotonic()
try:
- root = self._post("chat/completions", payload, k, timeout)
+ root = self._post(c.base + "chat/completions", payload, k, timeout)
choices = arr(root.get("choices"))
choice = obj(choices[0]) if choices else None
text = string((obj(choice.get("message")) or {}).get("content")) if choice else None
@@ -251,12 +385,13 @@ class LingClient:
raise LingError(LingError.PARSE)
finish = string(choice.get("finish_reason"))
trimmed = text.strip()
- if finish is None or trimmed.startswith(HIJACK_PREFIXES):
+ # Ling's search essays come without a finish reason; other services may simply omit it.
+ if (finish is None and c.is_ling) or trimmed.startswith(HIJACK_PREFIXES):
Log.d("ling: %s search-style reply dropped" % name)
raise LingError(LingError.HIJACKED)
usage = obj(root.get("usage")) or {}
- Log.d("ling: %s ok %d ms tokens=%s/%s" % (name, (time.monotonic() - started) * 1000,
- usage.get("prompt_tokens"), usage.get("completion_tokens")))
+ Log.d("ai %s: %s ok %d ms tokens=%s/%s" % (c.provider.id, name, (time.monotonic() - started) * 1000,
+ usage.get("prompt_tokens"), usage.get("completion_tokens")))
if self.rate_limited_at is not None:
self.rate_limited_at = None
self._changed()
@@ -274,22 +409,32 @@ class LingClient:
delay *= 2
attempt += 1
- def speech(self, text: str, voice: str = "UK_Charlotte", language: str | None = None, timeout: float = 20.0):
- """Ming's voice for `text`, as raw 24 kHz mono 16-bit PCM chunks while they arrive (a generator).
- `language` is Ming's language_id, needed for Japanese, Korean, German, French and Spanish
- (Ling.swift › speech)."""
- k = self.key.read()
+ def speech(self, text: str, voice: str | None = "UK_Charlotte", language: str | None = None, timeout: float = 20.0):
+ """The service's voice for `text`, as raw 24 kHz mono 16-bit PCM chunks while they arrive (a
+ generator). On Ling, `voice` is Ming's and `language` its language_id, needed for Japanese,
+ Korean, German, French and Spanish (Ling.swift › speech); elsewhere the configured speech
+ model and `voice`. Replies come three ways and all are read: server-sent base64 chunks (Ling,
+ ZenMux), raw PCM (OpenRouter), or one JSON `{"audio": <WAV>}`."""
+ k = self.current_key()
if k is None:
raise LingError(LingError.NO_KEY)
- body = {"model": TTS_MODEL, "input": text, "response_format": "pcm", "sample_rate": TTS_RATE,
- "stream": True, "stream_format": "sse", "voice": voice}
- if language:
- body["language_id"] = language
- self._acquire(SPEAK)
+ c = self.config()
+ if not c.has_voices:
+ raise LingError(LingError.NO_KEY)
+ body = {"model": c.voice_model, "input": text, "response_format": "pcm"}
+ if c.is_ling:
+ body.update({"sample_rate": TTS_RATE, "stream": True, "stream_format": "sse", "voice": voice or "UK_Charlotte"})
+ if language:
+ body["language_id"] = language
+ else:
+ # OpenRouter documents no `stream` (it streams the bytes anyway); ZenMux needs it.
+ if c.provider.id != "openrouter":
+ body["stream"] = True
+ ids = [v.id for v in c.voices]
+ body["voice"] = voice if voice in ids else (ids[0] if ids else (c.custom_voice or "Kore"))
+ self._acquire(SPEAK, c.provider.spacing)
try:
- res = self.transport.stream(BASE + "audio/speech", jsonfmt.write(body, pretty=False), {
- "Authorization": "Bearer " + k, "Content-Type": "application/json", "User-Agent": "Cicada-Linux/0.1",
- }, timeout)
+ res = self.transport.stream(c.voice_base + "audio/speech", jsonfmt.write(body, pretty=False), self._headers(k), timeout)
except TimeoutError:
raise LingError(LingError.TIMEOUT) from None
except OSError:
@@ -301,24 +446,40 @@ class LingClient:
if res.status == 429:
raise LingError(LingError.RATE_LIMITED)
if res.status != 200:
+ Log.d("ai %s: speech HTTP %d" % (c.provider.id, res.status))
raise LingError(LingError.HTTP, res.status)
- for line in res.lines:
- if not line.startswith("data:"):
- continue
- obj = jsonfmt.parse_object(line[5:].strip())
- if obj is None:
- continue
- if obj.get("type") == "speech.audio.done":
- break
- audio = obj.get("audio")
- if isinstance(audio, str) and audio:
- yield base64.b64decode(audio)
-
- def _post(self, path: str, payload: str, k: str, timeout: float) -> dict:
+ kind = res.content_type or ""
+ if "event-stream" in kind or res.chunks is None:
+ for line in res.lines:
+ if not line.startswith("data:"):
+ continue
+ o = jsonfmt.parse_object(line[5:].strip())
+ if o is None:
+ continue
+ if o.get("type") == "speech.audio.done":
+ break
+ audio = o.get("audio")
+ if isinstance(audio, str) and audio:
+ yield _b64(audio)
+ elif "json" in kind:
+ o = jsonfmt.parse_object(b"".join(res.chunks).decode("utf-8", "replace"))
+ audio = (o or {}).get("audio")
+ if not isinstance(audio, str):
+ raise LingError(LingError.PARSE)
+ yield pcm_from_wav(_b64(audio))
+ else:
+ for b in res.chunks:
+ yield b
+
+ def _headers(self, k: str) -> dict:
+ h = {"Content-Type": "application/json", "User-Agent": "Cicada-Linux/0.1"}
+ if k:
+ h["Authorization"] = "Bearer " + k
+ return h
+
+ def _post(self, url: str, payload: str, k: str, timeout: float) -> dict:
try:
- res = self.transport.send(BASE + path, "POST", payload, {
- "Authorization": "Bearer " + k, "Content-Type": "application/json", "User-Agent": "Cicada-Linux/0.1",
- }, timeout)
+ res = self.transport.send(url, "POST", payload, self._headers(k), timeout)
except TimeoutError:
raise LingError(LingError.TIMEOUT) from None
except OSError as e:
@@ -341,7 +502,8 @@ class LingClient:
# Start gate: request starts ≥ `spacing` apart, the most urgent waiting one first.
- def _acquire(self, priority: int) -> None:
+ def _acquire(self, priority: int, spacing: float = 0.6) -> None:
+ spacing = LingClient.spacing if LingClient.spacing is not None else spacing
with self._gate:
self._seq += 1
me = (priority, self._seq)
@@ -349,7 +511,7 @@ class LingClient:
try:
while True:
head = min(self._waiting)
- wait = self.spacing - (time.monotonic() - self._last_start)
+ wait = spacing - (time.monotonic() - self._last_start)
if head == me and wait <= 0:
self._waiting.remove(me)
self._last_start = time.monotonic()
@@ -361,3 +523,21 @@ class LingClient:
self._waiting.remove(me)
self._gate.notify_all()
raise
+
+
+def _b64(s: str) -> bytes:
+ import base64
+ return base64.b64decode(s)
+
+
+def pcm_from_wav(wav: bytes) -> bytes:
+ """The samples of a WAV (its `data` chunk); the bytes themselves when there's no header."""
+ if wav[:4] != b"RIFF":
+ return wav
+ at = 12
+ while at + 8 <= len(wav):
+ size = int.from_bytes(wav[at + 4:at + 8], "little")
+ if wav[at:at + 4] == b"data":
+ return wav[at + 8:at + 8 + size]
+ at += 8 + size + (size & 1)
+ return b""
diff --git a/linux/cicada/core/listen.py b/linux/cicada/core/listen.py
index 022d783..23c9c94 100644
--- a/linux/cicada/core/listen.py
+++ b/linux/cicada/core/listen.py
@@ -1,4 +1,5 @@
-"""Listening end to end: audio → segments → Ming (language, original, translation in one call) →
+"""Listening end to end: audio → segments → the AI service's hear model (Ming on Ling: language,
+original, translation in one call) →
lines in the record, plus live notes. UI-free; the app shows the record and listens to on_change
(called on worker threads: hand it to the GTK main loop).
@@ -233,17 +234,7 @@ class ListenEngine:
heard = self.translator.hear(wav, seg.asked, lang)
self.problem = self.problem_kind = None
except LingError as e:
- self.problem_kind = {
- LingError.NO_KEY: "key", LingError.INVALID_KEY: "key", LingError.RATE_LIMITED: "busy",
- LingError.NETWORK: "network", LingError.TIMEOUT: "network",
- }.get(e.kind)
- self.problem = {
- LingError.NO_KEY: strings.L("需要 Ling key 才能听"),
- LingError.INVALID_KEY: strings.L("Ling key 无效"),
- LingError.RATE_LIMITED: strings.L("Ling 太忙,稍后再试"),
- LingError.NETWORK: strings.L("连不上 Ling,检查网络或代理"),
- LingError.TIMEOUT: strings.L("连不上 Ling,检查网络或代理"),
- }.get(e.kind)
+ self.problem_kind, self.problem = problem(e, self.ling.provider.name)
Log.d("listen: segment %d failed %s" % (seg.index, e))
except Exception as e: # noqa: BLE001
Log.d("listen: segment %d failed %s" % (seg.index, type(e).__name__))
@@ -365,3 +356,23 @@ def continues(last, gap: float, nxt) -> bool:
def join(a: str, b: str, lang: str) -> str:
cjk = lang.startswith(("zh", "ja"))
return a.rstrip() + b.lstrip() if cjk else a.rstrip() + " " + b.lstrip()
+
+
+def problem(e: LingError, service: str):
+ """(kind, what to say) for a stretch that couldn't be heard. Ling keeps its own words; another
+ service is named. A hear model that refuses audio (400 / 404) is a key-like problem: 设置 fixes it."""
+ L, LF = strings.L, strings.LF
+ ling = service == "Ling"
+ if e.kind == LingError.HTTP and e.status in (400, 404) and not ling:
+ return "key", L("这个模型听不了声音,换一个支持音频输入的")
+ kind = {LingError.NO_KEY: "key", LingError.INVALID_KEY: "key", LingError.RATE_LIMITED: "busy",
+ LingError.NETWORK: "network", LingError.TIMEOUT: "network"}.get(e.kind)
+ if ling:
+ text = {LingError.NO_KEY: L("需要 Ling key 才能听"), LingError.INVALID_KEY: L("Ling key 无效"),
+ LingError.RATE_LIMITED: L("Ling 太忙,稍后再试"), LingError.NETWORK: L("连不上 Ling,检查网络或代理"),
+ LingError.TIMEOUT: L("连不上 Ling,检查网络或代理")}.get(e.kind)
+ else:
+ text = {LingError.NO_KEY: LF("需要 %@ 的 key 才能听", service), LingError.INVALID_KEY: LF("%@ 的 key 无效", service),
+ LingError.RATE_LIMITED: LF("%@ 太忙,稍后再试", service), LingError.NETWORK: LF("连不上 %@", service),
+ LingError.TIMEOUT: LF("连不上 %@", service)}.get(e.kind)
+ return kind, text
diff --git a/linux/cicada/core/providers.py b/linux/cicada/core/providers.py
new file mode 100644
index 0000000..c6e8282
--- /dev/null
+++ b/linux/cicada/core/providers.py
@@ -0,0 +1,203 @@
+"""The AI services the port can use (AIProviders.swift, plus what hears audio). Ling is the
+reference: Ming hears each stretch of audio and answers language, original and translation in one
+call, and only Ling clones the user's voice. The others are OpenAI-compatible and hear through an
+audio-input chat model with the same prompt (tools/audio-probe measured them against Ming, 2026-11:
+about as accurate, 0.5–2 s slower). OpenAI itself is left out: a port needs a model that hears,
+and its audio models are untested.
+
+Recommended models come first in every menu and are the defaults. For hearing, the first is the one
+that wrote nothing for a clip without speech: a made-up line ends up in the notes and, when
+interpreting, in the room."""
+from __future__ import annotations
+
+import base64
+import re
+import urllib.parse
+from dataclasses import dataclass, field
+
+from .jsonfmt import arr, obj, string
+
+
+@dataclass(frozen=True)
+class Model:
+ id: str
+ note: str = "" # why it is recommended: a Chinese UI key, localized where shown
+
+
+@dataclass(frozen=True)
+class CloudVoice:
+ id: str
+ gender: str # "女" / "男", a Chinese UI key
+
+
+@dataclass(frozen=True)
+class Provider:
+ id: str
+ name: str
+ base: str | None # None for "custom": the user's address
+ site: str | None # where to create a key
+ text_models: tuple = ()
+ hear_models: tuple = ()
+ voice_models: tuple = () # empty: this service can't speak into the room here
+ voices: tuple = () # of `voice_models` (Gemini TTS: the same names in every language)
+ clones: bool = False
+ spacing: float = 0.1 # Ling allows ~2 request starts a second; the aggregators far more
+
+ @property
+ def has_voices(self) -> bool:
+ return bool(self.voice_models)
+
+
+GEMINI_VOICES = (CloudVoice("Kore", "女"), CloudVoice("Aoede", "女"), CloudVoice("Charon", "男"), CloudVoice("Puck", "男"))
+
+LING = Provider(
+ "ling", "Ling", "https://api.ant-ling.com/v1/", "https://chat.ant-ling.com/platform/api",
+ text_models=(Model("Ling-3.1-flash", "更准"), Model("Ling-3.0-flash", "更快、更省")),
+ hear_models=(Model("Ming-3.0-audio-flash"),),
+ voice_models=(Model("Ming-3.0-tts-0.5B"),), clones=True, spacing=0.6)
+
+OPENROUTER = Provider(
+ "openrouter", "OpenRouter", "https://openrouter.ai/api/v1/", "https://openrouter.ai/settings/keys",
+ text_models=(Model("inclusionai/ling-3.1-flash", "和 Ling 同款"), Model("qwen/qwen3.8-flash", "中文好")),
+ hear_models=(Model("qwen/qwen3.8-omni-flash", "没人说话时不乱写"), Model("google/gemini-3.1-flash-lite", "最快,偶尔把杂音写成字")),
+ voice_models=(Model("google/gemini-3.8-flash-tts", "效果和价格最均衡"), Model("google/gemini-3.8-flash-lite-tts", "更省")),
+ voices=GEMINI_VOICES)
+
+ZENMUX = Provider(
+ "zenmux", "ZenMux", "https://zenmux.ai/api/v1/", "https://zenmux.ai/settings/keys",
+ text_models=(Model("inclusionai/ling-3.0-flash", "和 Ling 同款"), Model("qwen/qwen3.8-flash", "中文好")),
+ hear_models=(Model("qwen/qwen3.8-omni-flash", "没人说话时不乱写"), Model("bytedance/doubao-seed-2.0-mini", "更快"),
+ Model("google/gemini-3.1-flash-lite", "最快,偶尔把杂音写成字")),
+ voice_models=(Model("google/gemini-3.8-flash-tts", "效果和价格最均衡"), Model("google/gemini-3.8-flash-lite-tts", "更省")),
+ voices=GEMINI_VOICES)
+
+# Any OpenAI-compatible address (a company gateway, Ollama…). Its hear model must take audio in;
+# voices only when the user names a speech model.
+CUSTOM = Provider("custom", "其他(兼容 OpenAI)", None, None)
+
+ALL = (LING, OPENROUTER, ZENMUX, CUSTOM)
+
+
+def named(raw: str) -> Provider:
+ return next((p for p in ALL if p.id == raw), LING)
+
+
+def is_local(host_or_url: str) -> bool:
+ u = host_or_url if "://" in host_or_url else "http://" + host_or_url
+ host = urllib.parse.urlsplit(u).hostname or host_or_url
+ return host in ("localhost", "127.0.0.1", "::1")
+
+
+def custom_base(raw: str) -> str | None:
+ """The address as typed, normalized: https, or http only on this computer; ends in "/"."""
+ s = (raw or "").strip()
+ if not s:
+ return None
+ if "://" not in s:
+ s = ("http://" if is_local(s) else "https://") + s
+ if not s.endswith("/"):
+ s += "/"
+ parts = urllib.parse.urlsplit(s)
+ if not parts.hostname:
+ return None
+ if parts.scheme == "https":
+ return s
+ return s if parts.scheme == "http" and is_local(parts.hostname) else None
+
+
+@dataclass
+class AIConfig:
+ """What one call needs to know about the service in use, resolved from settings each time."""
+ provider: Provider
+ base: str | None # None: a custom service without a valid address yet
+ text_model: str
+ hear_model: str
+ voice_model: str | None = None # None: no voices with this service
+ voice_base: str | None = None
+ custom_voice: str | None = None
+ extra: dict = field(default_factory=dict)
+
+ @property
+ def is_ling(self) -> bool:
+ return self.provider.id == "ling"
+
+ @property
+ def has_voices(self) -> bool:
+ return self.voice_model is not None and self.voice_base is not None
+
+ @property
+ def voices(self) -> tuple:
+ """The voices the room can pick from with this service (Ling's are in voices.py)."""
+ if not self.has_voices or self.is_ling:
+ return ()
+ if self.provider.id == "custom":
+ return (CloudVoice(self.custom_voice, ""),) if self.custom_voice else ()
+ return self.provider.voices
+
+ def shape(self, body: dict, max_tokens: int) -> None:
+ """Each service turns thinking off its own way (AIConfig.shape on the Mac)."""
+ body["max_tokens"] = max_tokens
+ body["temperature"] = 0.2
+ if self.is_ling:
+ body["thinking"] = {"type": "disabled"}
+ elif self.provider.id in ("openrouter", "zenmux"):
+ body["reasoning"] = {"enabled": False}
+
+ def audio_part(self, wav: bytes, model: str) -> dict:
+ """One WAV in a user message: Ming takes a data URL; the others the standard `input_audio`,
+ except that Qwen's omni models want the data URL inside it (DashScope's form)."""
+ b64 = base64.b64encode(wav).decode()
+ if self.is_ling:
+ return {"type": "audio_url", "audio_url": {"url": "data:audio/wav;base64," + b64}}
+ if model.split("/")[-1].startswith("qwen"):
+ b64 = "data:audio/wav;base64," + b64
+ return {"type": "input_audio", "input_audio": {"data": b64, "format": "wav"}}
+
+
+def config_from(settings) -> AIConfig:
+ """The service, its address and models from the app's settings (Settings.swift › aiConfig)."""
+ p = named(settings.aiProvider)
+ models, hears, voices = settings.aiModels, settings.aiHearModels, settings.aiVoiceModels
+ if p.id == "ling":
+ text = settings.model if settings.model in [m.id for m in p.text_models] else p.text_models[0].id
+ return AIConfig(p, p.base, text, p.hear_models[0].id, p.voice_models[0].id, p.base)
+ if p.id == "custom":
+ base = custom_base(settings.aiCustomBase)
+ voice = (voices.get("custom") or "").strip()
+ voice_base = custom_base(settings.aiCustomVoiceBase) if settings.aiCustomVoiceBase.strip() else base
+ name = settings.aiCustomVoice.strip()
+ return AIConfig(p, base, (models.get("custom") or "").strip(), (hears.get("custom") or "").strip(),
+ voice or None, voice_base if voice else None, name or None)
+ return AIConfig(p, p.base, models.get(p.id) or p.text_models[0].id, hears.get(p.id) or p.hear_models[0].id,
+ voices.get(p.id) or p.voice_models[0].id, p.base)
+
+
+_NOT_CHAT = re.compile(r"(embed|whisper|tts|transcribe|dall-e|image|moderation|realtime|sora|search|video|seedance|wan\d)")
+
+
+def catalog(data: str | dict, recommended: list, hears: bool) -> list:
+ """Model ids from a `/models` reply, recommended ones first: those that answer in text, and for
+ `hears` only those that take audio in. ZenMux lists modalities at the top level, OpenRouter under
+ `architecture`; a service that says nothing keeps everything but obvious non-chat names."""
+ from .jsonfmt import parse_object
+ root = parse_object(data) if isinstance(data, str) else data
+ ids = []
+ for m in arr((root or {}).get("data")):
+ m = obj(m) or {}
+ mid = string(m.get("id"))
+ if not mid or mid.endswith(":batch"):
+ continue
+ a = obj(m.get("architecture")) or {}
+ ins = arr(m.get("input_modalities") or a.get("input_modalities"))
+ outs = arr(m.get("output_modalities") or a.get("output_modalities"))
+ if outs and "text" not in outs:
+ continue
+ if ins and ins == ["audio"]:
+ continue # speech-to-text only: no prompt, no translation
+ if hears and "audio" not in ins:
+ continue
+ if not outs and _NOT_CHAT.search(mid):
+ continue
+ ids.append(mid)
+ rest = sorted(i for i in ids if i not in recommended)
+ return list(recommended) + rest
diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.py
index 53944d0..d855f2a 100644
--- a/linux/cicada/core/settings.py
+++ b/linux/cicada/core/settings.py
@@ -13,7 +13,16 @@ class AppSettings:
FIELDS = {
"target": "system", # what subtitles translate into; "system" follows the desktop language
"notesLanguage": "mine", # 纪要语言, the Mac's: "mine" (my language) or "source" (the meeting's own)
- "model": DEFAULT_MODEL,
+ "model": DEFAULT_MODEL, # Ling's text model (the others' are in aiModels)
+ # AI 服务 (Settings.swift's keys): the service, and per service the models chosen over its
+ # recommended ones. aiHearModels is the port's own: what hears the audio (Ming on Ling).
+ "aiProvider": "ling",
+ "aiModels": {},
+ "aiHearModels": {},
+ "aiVoiceModels": {},
+ "aiCustomBase": "",
+ "aiCustomVoiceBase": "",
+ "aiCustomVoice": "",
"view": "notes", # "notes" (the notes window, default) or "subtitles" (the subtitle bar)
"showInCapture": False, # 共享屏幕时让对方看到 (Linux can't hide it; see NotesWindow)
"onboarded": False,
@@ -52,6 +61,11 @@ class AppSettings:
they speak mine (the Mac's resolvedTarget)."""
return follow_system_target(source, system_languages()) if self.target == "system" else self.target
+ def ai_config(self):
+ """The AI service in use, its address and models (what LingClient calls with)."""
+ from .providers import config_from
+ return config_from(self)
+
def notes_code(self, choice: str | None = None, meeting: str | None = None) -> str:
"""The notes' language for a 纪要语言 choice (this one's when None): the meeting's own language
(`meeting`, the one it was heard in) for "source", else mine (the Mac's notesLanguageCode)."""
diff --git a/linux/cicada/core/speak.py b/linux/cicada/core/speak.py
index 0e53562..2fe476f 100644
--- a/linux/cicada/core/speak.py
+++ b/linux/cicada/core/speak.py
@@ -1,7 +1,8 @@
"""同声传译 (the Mac's 说): what I say into my microphone, interpreted and spoken into the meeting.
-Each sentence (cut by the same Segmenter as listening) goes to Ming's audio model, which returns
-what was said and its translation in one call; the translation is voiced by Ming's TTS and played
+Each sentence (cut by the same Segmenter as listening) goes to the AI service's hear model (Ming on
+Ling), which returns what was said and its translation in one call; the translation is voiced by the
+service's speech model (Ming's TTS on Ling) and played
into 知了 麦克风, the virtual microphone the meeting app uses. Sentences play one after another, in
order. A sentence that couldn't be interpreted is never spoken (AGENTS.md: never speak untranslated
text into the room).
@@ -100,8 +101,9 @@ class SpeakEngine:
def voice(self, code: str) -> str | None:
chosen = (self.settings.speakVoices or {}).get(voicemod.key(code))
- names = [v for v, _n, _t in voicemod.voices(code)]
- return chosen if chosen in names else voicemod.default_voice(code)
+ config = self.ling.config()
+ names = [v for v, _n, _t in voicemod.voices(code, config)]
+ return chosen if chosen in names else voicemod.default_voice(code, config)
# Running
@@ -209,7 +211,7 @@ class SpeakEngine:
def run():
try:
- for pcm in self.ling.speech(text, voice=self.voice(target), language=voicemod.ming_language(target)):
+ for pcm in self.ling.speech(text, voice=self.voice(target), language=voicemod.ming_language(target, self.ling.config())):
chunks.put(pcm)
chunks.put(_END)
except LingError as e:
diff --git a/linux/cicada/core/support.py b/linux/cicada/core/support.py
index 99e9324..4f32461 100644
--- a/linux/cicada/core/support.py
+++ b/linux/cicada/core/support.py
@@ -48,8 +48,9 @@ class Paths:
return os.path.join(cls.config(), "settings.json")
@classmethod
- def key_file(cls) -> str:
- return os.path.join(cls.config(), "ling-api-key")
+ def key_file(cls, service: str = "ling") -> str:
+ """One key file per AI service, named as on the Mac."""
+ return os.path.join(cls.config(), "ling-api-key" if service == "ling" else "ai-key-" + service)
log_override: str | None = None
diff --git a/linux/cicada/core/translator.py b/linux/cicada/core/translator.py
index e9ada69..0c2c364 100644
--- a/linux/cicada/core/translator.py
+++ b/linux/cicada/core/translator.py
@@ -1,6 +1,6 @@
"""Translation and recognition through the cloud (the Windows design): listening sends each stretch
-of audio to Ming's audio model, which returns the language, the original and the translation in one
-call. Text translation is Ling first, then Google. Calls block."""
+of audio to the AI service's hear model (Ming on Ling), which returns the language, the original and
+the translation in one call. Text translation is the AI service first, then Google. Calls block."""
from __future__ import annotations
import re
@@ -10,7 +10,7 @@ from dataclasses import dataclass
from . import jsonfmt
from .jsonfmt import arr
-from .ling import AUDIO_MODEL, SPEAK, TRANSLATE, LingError, UrlTransport
+from .ling import SPEAK, TRANSLATE, LingError, UrlTransport
from .support import Log, english_name, in_script, normalize
@@ -37,7 +37,7 @@ class Translator:
# 16 kHz mono 16-bit after the 44-byte header: the length caps the reply and catches a runaway one.
seconds = max(0, len(wav) - 44) / 32000.0
reply = self.ling.chat(hear_prompt(target, hint, self.glossary()), hear_instruction(target), TRANSLATE,
- max_tokens=hear_tokens(seconds), timeout=12.0, model=AUDIO_MODEL, audio=wav)
+ max_tokens=hear_tokens(seconds), timeout=hear_timeout(self.ling), model=self.ling.config().hear_model, audio=wav)
return parse_heard(reply, target, hint, seconds)
def interpret(self, wav: bytes, source: str, target: str):
@@ -46,7 +46,7 @@ class Translator:
if source == target or not self.ling.usable:
return None
reply = self.ling.chat(interpret_prompt(source, target, self.glossary()), interpret_instruction(source, target), SPEAK,
- max_tokens=800, timeout=12.0, model=AUDIO_MODEL, audio=wav)
+ max_tokens=800, timeout=hear_timeout(self.ling), model=self.ling.config().hear_model, audio=wav)
return parse_interpretation(reply, target)
DRAFT, SENTENCE = "draft", "sentence"
@@ -89,6 +89,12 @@ class Translator:
return None
+def hear_timeout(ling) -> float:
+ """Ming answers in ~2 s; the other services' hear models in 3–4 s, but now and then over 12 s
+ (Qwen on ZenMux, 2026-11), and a stretch given up on is words lost."""
+ return 12.0 if ling.config().is_ling else 20.0
+
+
def interpret_prompt(source: str, target: str, names: list) -> str:
"""Translator.swift › interpret, word for word."""
p = ("You are an interpreter from %s into %s. " % (english_name(source), english_name(target)) +
@@ -217,6 +223,9 @@ def is_noise(original: str, seconds: float = 0.0) -> bool:
text = _ANNOTATION.sub(" ", original.lower())
if any(r in text for r in _NO_SPEECH):
return True
+ # A clock instead of words ("00:00"): what some of the other services' models write for a beep.
+ if _CLOCK.match(text.strip()):
+ return True
words, word = [], ""
for c in text:
if c.isalnum():
@@ -237,6 +246,9 @@ def is_noise(original: str, seconds: float = 0.0) -> bool:
return seconds > 0 and n > max(12.0, 12 * seconds)
+_CLOCK = re.compile(r"^\d{1,2}(:\d{2}){1,2}[.。]?$")
+
+
def _filler_word(raw: str) -> bool:
"""Made of fillers only, a held sound shortened first: "嗯嗯嗯", "hmmmm"; "えーと" is not."""
w = ""
diff --git a/linux/cicada/core/voices.py b/linux/cicada/core/voices.py
index a2b8d37..2daffd4 100644
--- a/linux/cicada/core/voices.py
+++ b/linux/cicada/core/voices.py
@@ -1,6 +1,7 @@
-"""Ming's voices for what the room hears (Voices.swift › VoiceCatalog.ming): hand-picked natural
-ones per language; for languages Ming has no native voice for, Emma and George speak them with
-`language_id`. Linux has no system voice worth sending into a meeting, so only these."""
+"""The voices for what the room hears (Voices.swift › VoiceCatalog). On Ling, Ming's: hand-picked
+natural ones per language; for languages Ming has no native voice for, Emma and George speak them
+with `language_id`. On another service, its speech model's voices, the same in every language.
+Linux has no system voice worth sending into a meeting, so only these."""
from __future__ import annotations
@@ -9,7 +10,9 @@ def key(code: str) -> str:
return (code or "en").split("-")[0].lower() or "en"
-def ming_language(code: str) -> str | None:
+def ming_language(code: str, config=None) -> str | None:
+ if config is not None and not config.is_ling:
+ return None
k = key(code)
return k if k in ("ja", "ko", "de", "fr", "es") else None
@@ -27,13 +30,16 @@ _OTHER = [("US_Emma", "Emma", ["女"]), ("UK_George", "George", ["男"])]
ROOM_LANGUAGES = ["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de"]
-def voices(code: str) -> list:
+def voices(code: str, config=None) -> list:
+ """(voice, name, tags) for a language. `config` is the AI service in use (None: Ling)."""
+ if config is not None and not config.is_ling:
+ return [(v.id, v.id, [v.gender] if v.gender else []) for v in config.voices]
k = key(code)
if k in _CATALOG:
return _CATALOG[k]
return _OTHER if k in ("ja", "ko", "de", "fr", "es") else []
-def default_voice(code: str) -> str | None:
- v = voices(code)
+def default_voice(code: str, config=None) -> str | None:
+ v = voices(code, config)
return v[0][0] if v else None
diff --git a/linux/cli.py b/linux/cli.py
index e0e74f9..3e8ceff 100755
--- a/linux/cli.py
+++ b/linux/cli.py
@@ -10,8 +10,11 @@
cli.py segments <file.wav> where the segmenter cuts
cli.py roundtrip <session.json>… [--diff] reads and writes records, says if a byte changed
+ --provider ling|openrouter|zenmux the AI service (default ling), with its recommended models;
+ --hear-model <id> another hear model on it
+
Records go to CICADA_HOME (default: a temp folder). The key comes from CICADA_KEY_FILE, else this
-app's own key file, else the Mac app's; it is never printed."""
+app's own key file for the service, else the Mac app's; it is never printed."""
from __future__ import annotations
import os
@@ -25,7 +28,7 @@ sys.path.insert(0, HERE)
from cicada.core import strings # noqa: E402
from cicada.core.audio import PcmAudioSource, Wav # noqa: E402
-from cicada.core.ling import AUDIO_MODEL, TRANSLATE, AIKey, LingClient # noqa: E402
+from cicada.core.ling import TRANSLATE, AIKey, LingClient # noqa: E402
from cicada.core.listen import ListenEngine # noqa: E402
from cicada.core.models import Session # noqa: E402
from cicada.core.notes import NotesEngine # noqa: E402
@@ -36,18 +39,27 @@ from cicada.core.support import Log, Paths, clock # noqa: E402
from cicada.core.translator import Translator, hear_instruction, hear_prompt, parse_heard # noqa: E402
+SERVICE = "ling"
+
+
def key_file() -> str | None:
env = os.environ.get("CICADA_KEY_FILE")
if env:
return env
- for p in (os.path.expanduser("~/.config/cicada/ling-api-key"),
- os.path.expanduser("~/Library/Application Support/LiveSubs Dev/ling-api-key"),
- os.path.expanduser("~/Library/Application Support/LiveSubs/ling-api-key")):
+ name = "ling-api-key" if SERVICE == "ling" else "ai-key-" + SERVICE
+ for p in (os.path.expanduser("~/.config/cicada/" + name),
+ os.path.expanduser("~/Library/Application Support/LiveSubs Dev/" + name),
+ os.path.expanduser("~/Library/Application Support/LiveSubs/" + name)):
if os.path.isfile(p):
return p
return None
+def client(settings: AppSettings) -> LingClient:
+ """The AI service the settings name, with the key file found for it."""
+ return LingClient(AIKey(key_file(), service=lambda: SERVICE), config=settings.ai_config)
+
+
def main(args: list) -> int:
if not args:
print(__doc__)
@@ -56,6 +68,15 @@ def main(args: list) -> int:
def opt(name, fallback):
return args[args.index(name) + 1] if name in args and args.index(name) + 1 < len(args) else fallback
strings.load(opt("--ui", "zh-Hans"), [os.path.join(HERE, "..", "Resources"), os.path.join(HERE, "strings")])
+ global SERVICE
+ SERVICE = opt("--provider", "ling")
+ hear = opt("--hear-model", "")
+
+ def make_settings(**kw) -> AppSettings:
+ s = AppSettings(aiProvider=SERVICE, **kw)
+ if hear:
+ s.aiHearModels[SERVICE] = hear
+ return s
cmd = args[0]
if cmd == "segments":
pcm = Wav.read_file(args[1])
@@ -87,10 +108,10 @@ def main(args: list) -> int:
b[at] if at < len(b) else None))
return 0 if changed == 0 else 1
if cmd == "hear":
- ling = LingClient(AIKey(key_file()))
+ ling = client(make_settings())
target = opt("--target", "zh-CN")
r = ling.chat(hear_prompt(target, None, []), hear_instruction(target), TRANSLATE, max_tokens=800, timeout=20.0,
- model=AUDIO_MODEL, audio=Wav.bytes(Wav.read_file(args[1])))
+ model=ling.config().hear_model, audio=Wav.bytes(Wav.read_file(args[1])))
print(r)
print("->", parse_heard(r, target, None))
return 0
@@ -99,9 +120,8 @@ def main(args: list) -> int:
from array import array as _array
from cicada.core.speak import SpeakEngine
Log.echo = "--log" in args
- key = AIKey(key_file())
- ling = LingClient(key)
- settings = AppSettings(target=opt("--from", "zh-CN"), speakTo=opt("--to", "en"))
+ settings = make_settings(target=opt("--from", "zh-CN"), speakTo=opt("--to", "en"))
+ ling = client(settings)
out = bytearray()
class Collect:
@@ -135,12 +155,11 @@ def main(args: list) -> int:
Log.echo = "--log" in args
if not os.environ.get("CICADA_HOME"):
Paths.home_override = tempfile.mkdtemp(prefix="cicada-cli-")
- key = AIKey(key_file())
- if key.read() is None:
- print("no Ling key (set CICADA_KEY_FILE)")
+ settings = make_settings(target=opt("--target", "zh-CN"))
+ ling = client(settings)
+ if not ling.has_key:
+ print("no %s key (set CICADA_KEY_FILE)" % SERVICE)
return 2
- settings = AppSettings(target=opt("--target", "zh-CN"))
- ling = LingClient(key)
store = SessionStore()
notes = NotesEngine(ling, store)
engine = ListenEngine(ling, Translator(ling), store, notes, settings)
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index e1ebafe..1b744e6 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -141,3 +141,31 @@
"可选" = "Optional";
"以后再说" = "Not now";
"关掉窗口后,知了在顶栏右上角" = "After you close this, Cicada stays in the top bar";
+
+/* AI 服务: other services than Ling */
+"连不上 %@" = "Can't connect to %@";
+"在 设置 › AI 服务 里换一个" = "Change it in Settings › AI Service";
+"接 AI 服务" = "AI service";
+"注册或登录后点“创建令牌”" = "Sign up or log in, then click “Create token”";
+"听、纪要和翻译都能用,模型已经选好。" = "Listening, notes and translation all work, with the models already chosen.";
+"仅保存在本机当前账户下,仅发送至 %@" = "Stored only for this account on this computer, sent only to %@";
+"接上 %@" = "Connect %@";
+"同声传译的声音" = "Interpreter voice";
+"例如 qwen3-omni" = "e.g. qwen3-omni";
+"听的模型" = "Listening model";
+"要能输入音频:听对方和“我说”都用它" = "Must take audio in: used for Listen and for Speak";
+"还不能用" = "Not yet";
+"这个模型听不了声音,换一个支持音频输入的" = "This model can't take audio. Choose one that accepts audio input";
+"Ming 一次识别并翻译" = "Ming recognizes and translates in one step";
+"比 Ling 晚 1–2 秒出字" = "Text appears 1–2 s later than with Ling";
+"用不了" = "Unavailable";
+"这个服务不能出声音" = "This service can't speak";
+"需支持 /audio/speech;不填则同声传译用不了" = "Must support /audio/speech; without one, interpreting won't work";
+"听对方和“我说”都用它" = "Used for Listen and for Speak";
+"本机服务,不用 key" = "Local service, no key needed";
+"听的时候,电脑里的声音会发给 %@。" = "While listening, your computer's audio is sent to %@.";
+"按所选模型计费。" = "Billed by the models you choose. ";
+"需要 %@ 的 key 才能听" = "Needs a %@ key to listen";
+"%@ 的 key 无效" = "%@ key is invalid";
+"%@ 太忙,稍后再试" = "%@ is busy. Try again shortly";
+"仅保存在本机当前账户下,仅发送至 %@(%@)" = "Stored only for this account on this computer, sent only to %1$@ (%2$@)";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index f0f089e..ba63ddb 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -141,3 +141,31 @@
"可选" = "任意";
"以后再说" = "あとで";
"关掉窗口后,知了在顶栏右上角" = "閉じても Cicada は右上のトップバーにあります";
+
+/* AI 服务: other services than Ling */
+"连不上 %@" = "%@ に接続できません";
+"在 设置 › AI 服务 里换一个" = "設定 › AI サービスで変更してください";
+"接 AI 服务" = "AI サービス";
+"注册或登录后点“创建令牌”" = "登録またはログインして「トークンを作成」をクリック";
+"听、纪要和翻译都能用,模型已经选好。" = "聞き取り・議事メモ・翻訳がすべて使えます。モデルは選択済みです。";
+"仅保存在本机当前账户下,仅发送至 %@" = "このコンピュータのこのアカウントにのみ保存され、%@ にのみ送信されます";
+"接上 %@" = "%@ に接続";
+"同声传译的声音" = "通訳の音声";
+"例如 qwen3-omni" = "例:qwen3-omni";
+"听的模型" = "聞き取りモデル";
+"要能输入音频:听对方和“我说”都用它" = "音声入力に対応している必要があります。相手の聞き取りと「話す」の両方で使います";
+"还不能用" = "まだ使えません";
+"这个模型听不了声音,换一个支持音频输入的" = "このモデルは音声を聞き取れません。音声入力に対応したモデルに変えてください";
+"Ming 一次识别并翻译" = "Ming が一度で認識と翻訳を行います";
+"比 Ling 晚 1–2 秒出字" = "Ling より文字が 1〜2 秒遅れて出ます";
+"用不了" = "使えません";
+"这个服务不能出声音" = "このサービスは音声を出せません";
+"需支持 /audio/speech;不填则同声传译用不了" = "/audio/speech に対応している必要があります。空欄だと通訳は使えません";
+"听对方和“我说”都用它" = "相手の聞き取りと「話す」の両方で使います";
+"本机服务,不用 key" = "ローカルサービスのため key は不要です";
+"听的时候,电脑里的声音会发给 %@。" = "聞き取り中は、コンピュータの音声が %@ に送信されます。";
+"按所选模型计费。" = "選んだモデルに応じて課金されます。";
+"需要 %@ 的 key 才能听" = "聞き取りには %@ の key が必要です";
+"%@ 的 key 无效" = "%@ の key が無効です";
+"%@ 太忙,稍后再试" = "%@ が混み合っています。しばらくしてからもう一度お試しください";
+"仅保存在本机当前账户下,仅发送至 %@(%@)" = "このコンピュータのこのアカウントにのみ保存され、%1$@(%2$@)にのみ送信されます";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 3eb2ff9..5fb856f 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -141,3 +141,31 @@
"可选" = "선택";
"以后再说" = "나중에";
"关掉窗口后,知了在顶栏右上角" = "창을 닫아도 Cicada는 오른쪽 위 상단 바에 있어요";
+
+/* AI 服务: other services than Ling */
+"连不上 %@" = "%@에 연결할 수 없음";
+"在 设置 › AI 服务 里换一个" = "설정 › AI 서비스에서 바꾸세요";
+"接 AI 服务" = "AI 서비스";
+"注册或登录后点“创建令牌”" = "가입하거나 로그인한 뒤 ‘토큰 만들기’를 누르세요";
+"听、纪要和翻译都能用,模型已经选好。" = "듣기, 회의록, 번역 모두 사용할 수 있고 모델은 이미 골라 두었습니다.";
+"仅保存在本机当前账户下,仅发送至 %@" = "이 컴퓨터의 현재 계정에만 저장되고 %@에만 전송됩니다";
+"接上 %@" = "%@ 연결";
+"同声传译的声音" = "통역 음성";
+"例如 qwen3-omni" = "예: qwen3-omni";
+"听的模型" = "듣기 모델";
+"要能输入音频:听对方和“我说”都用它" = "오디오 입력을 지원해야 합니다. 상대방 듣기와 ‘말하기’에 모두 쓰입니다";
+"还不能用" = "아직 안 됨";
+"这个模型听不了声音,换一个支持音频输入的" = "이 모델은 오디오를 들을 수 없습니다. 오디오 입력을 지원하는 모델로 바꾸세요";
+"Ming 一次识别并翻译" = "Ming이 한 번에 인식하고 번역합니다";
+"比 Ling 晚 1–2 秒出字" = "Ling보다 글자가 1~2초 늦게 나옵니다";
+"用不了" = "사용 불가";
+"这个服务不能出声音" = "이 서비스는 음성을 낼 수 없습니다";
+"需支持 /audio/speech;不填则同声传译用不了" = "/audio/speech를 지원해야 합니다. 비워 두면 통역을 쓸 수 없습니다";
+"听对方和“我说”都用它" = "상대방 듣기와 ‘말하기’에 모두 쓰입니다";
+"本机服务,不用 key" = "로컬 서비스라 key가 필요 없습니다";
+"听的时候,电脑里的声音会发给 %@。" = "듣는 동안 컴퓨터의 소리가 %@(으)로 전송됩니다.";
+"按所选模型计费。" = "선택한 모델에 따라 요금이 부과됩니다. ";
+"需要 %@ 的 key 才能听" = "들으려면 %@ key가 필요합니다";
+"%@ 的 key 无效" = "%@ key가 유효하지 않습니다";
+"%@ 太忙,稍后再试" = "%@이(가) 바쁩니다. 잠시 후 다시 시도하세요";
+"仅保存在本机当前账户下,仅发送至 %@(%@)" = "이 컴퓨터의 현재 계정에만 저장되고 %1$@(%2$@)에만 전송됩니다";
diff --git a/linux/tests/test_providers.py b/linux/tests/test_providers.py
new file mode 100644
index 0000000..9e76873
--- /dev/null
+++ b/linux/tests/test_providers.py
@@ -0,0 +1,274 @@
+"""AI 服务: the service table, how each one's requests are shaped, per-service keys, and the client
+against each service (no network: a fake transport that records where each request went)."""
+from __future__ import annotations
+
+import base64
+import os
+import sys
+import tempfile
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.dirname(HERE))
+
+from cicada.core import jsonfmt, providers, voices # noqa: E402
+from cicada.core.ling import (INVALID, NONE, OK, TRANSLATE, AIKey, LingClient, LingError, Response, # noqa: E402
+ StreamResponse, pcm_from_wav)
+from cicada.core.listen import problem # noqa: E402
+from cicada.core.settings import AppSettings # noqa: E402
+from cicada.core.support import Paths # noqa: E402
+from cicada.core.translator import Translator, is_noise # noqa: E402
+
+
+class Fake:
+ """Answers every request with `respond(url, body)`; speech with `speech(url, body)`."""
+
+ def __init__(self, respond, speech=None):
+ self.respond = respond
+ self.speech = speech
+ self.sent = [] # (url, body or "")
+ self.streamed = [] # (url, body)
+
+ def send(self, url, method, body, headers, timeout):
+ self.sent.append((url, body or ""))
+ return self.respond(url, body or "")
+
+ def stream(self, url, body, headers, timeout):
+ self.streamed.append((url, body))
+ return self.speech(url, body)
+
+
+def reply(content, finish="stop"):
+ choice = {"message": {"content": content}}
+ if finish is not None:
+ choice["finish_reason"] = finish
+ return Response(200, jsonfmt.write({"choices": [choice]}, pretty=False))
+
+
+class Base(unittest.TestCase):
+ def setUp(self):
+ self.home = tempfile.mkdtemp(prefix="cicada-providers-")
+ Paths.home_override = self.home
+ Paths.log_override = os.path.join(self.home, "debug.log")
+ LingClient.spacing = 0.0
+
+ def tearDown(self):
+ LingClient.spacing = None
+ Paths.home_override = None
+ Paths.log_override = None
+
+ def client(self, fake, provider="zenmux", key="sk-test-0000000000", **kw):
+ s = AppSettings(aiProvider=provider, **kw)
+ k = AIKey(service=lambda: s.aiProvider)
+ if key:
+ k.save(key)
+ return LingClient(k, fake, config=s.ai_config), s
+
+
+class Table(Base):
+ def test_defaults_are_the_recommended_models(self):
+ c = AppSettings(aiProvider="zenmux").ai_config()
+ self.assertEqual("https://zenmux.ai/api/v1/", c.base)
+ self.assertEqual("qwen/qwen3.8-omni-flash", c.hear_model)
+ self.assertEqual("inclusionai/ling-3.0-flash", c.text_model)
+ self.assertEqual("google/gemini-3.8-flash-tts", c.voice_model)
+ ling = AppSettings().ai_config()
+ self.assertEqual(("Ming-3.0-audio-flash", "Ling-3.1-flash"), (ling.hear_model, ling.text_model))
+ # Ling keeps its own key ("model"); a service never named falls back to Ling.
+ self.assertEqual("Ling-3.0-flash", AppSettings(model="Ling-3.0-flash").ai_config().text_model)
+ self.assertEqual("ling", providers.named("openai").id)
+
+ def test_chosen_models_and_a_custom_service(self):
+ s = AppSettings(aiProvider="openrouter", aiHearModels={"openrouter": "google/gemini-3.1-flash-lite"})
+ self.assertEqual("google/gemini-3.1-flash-lite", s.ai_config().hear_model)
+ s = AppSettings(aiProvider="custom", aiCustomBase="localhost:11434/v1", aiModels={"custom": "qwen3:14b"})
+ c = s.ai_config()
+ self.assertEqual("http://localhost:11434/v1/", c.base)
+ self.assertEqual("", c.hear_model)
+ self.assertFalse(c.has_voices)
+ s.aiVoiceModels["custom"], s.aiCustomVoice = "kokoro", "af_heart"
+ self.assertEqual(("kokoro", "http://localhost:11434/v1/"), (s.ai_config().voice_model, s.ai_config().voice_base))
+ self.assertEqual(["af_heart"], [v.id for v in s.ai_config().voices])
+
+ def test_custom_address(self):
+ self.assertEqual("https://api.example.com/v1/", providers.custom_base("api.example.com/v1"))
+ self.assertEqual("http://127.0.0.1:1234/v1/", providers.custom_base("127.0.0.1:1234/v1"))
+ self.assertIsNone(providers.custom_base("http://api.example.com/v1")) # http only on this computer
+ self.assertIsNone(providers.custom_base(" "))
+
+ def test_settings_keep_the_service_across_a_restart(self):
+ s = AppSettings(aiProvider="zenmux", aiHearModels={"zenmux": "bytedance/doubao-seed-2.0-mini"})
+ s.save()
+ back = AppSettings.load()
+ self.assertEqual("zenmux", back.aiProvider)
+ self.assertEqual("bytedance/doubao-seed-2.0-mini", back.ai_config().hear_model)
+
+ def test_each_service_turns_thinking_off_its_own_way(self):
+ for pid, key, value in (("ling", "thinking", {"type": "disabled"}), ("zenmux", "reasoning", {"enabled": False}),
+ ("openrouter", "reasoning", {"enabled": False})):
+ body = {}
+ AppSettings(aiProvider=pid).ai_config().shape(body, 100)
+ self.assertEqual(value, body[key])
+ self.assertEqual(100, body["max_tokens"])
+ body = {}
+ AppSettings(aiProvider="custom", aiCustomBase="https://x.example/v1").ai_config().shape(body, 5)
+ self.assertNotIn("reasoning", body)
+ self.assertNotIn("thinking", body)
+
+ def test_audio_goes_in_the_form_each_model_takes(self):
+ wav = bytes([1, 2, 3])
+ ling = AppSettings().ai_config().audio_part(wav, "Ming-3.0-audio-flash")
+ self.assertEqual({"type": "audio_url", "audio_url": {"url": "data:audio/wav;base64,AQID"}}, ling)
+ zen = AppSettings(aiProvider="zenmux").ai_config()
+ self.assertEqual({"type": "input_audio", "input_audio": {"data": "AQID", "format": "wav"}},
+ zen.audio_part(wav, "google/gemini-3.1-flash-lite"))
+ self.assertEqual("data:audio/wav;base64,AQID", zen.audio_part(wav, "qwen/qwen3.8-omni-flash")["input_audio"]["data"])
+
+ def test_catalog_lists_chat_models_and_those_that_hear(self):
+ data = {"data": [
+ {"id": "qwen/qwen3.8-omni-flash", "input_modalities": ["text", "image", "audio", "video"], "output_modalities": ["text"]},
+ {"id": "x/asr-only", "input_modalities": ["audio"], "output_modalities": ["text"]},
+ {"id": "x/text-model", "architecture": {"input_modalities": ["text"], "output_modalities": ["text"]}},
+ {"id": "x/tts", "input_modalities": ["text"], "output_modalities": ["audio"]},
+ {"id": "x/embed-1"},
+ {"id": "google/gemini-3.1-flash-lite:batch", "input_modalities": ["audio", "text"], "output_modalities": ["text"]},
+ ]}
+ self.assertEqual(["rec/one", "qwen/qwen3.8-omni-flash"], providers.catalog(data, ["rec/one"], hears=True))
+ self.assertEqual(["qwen/qwen3.8-omni-flash", "x/text-model"], providers.catalog(data, [], hears=False))
+
+
+class Keys(Base):
+ def test_one_file_per_service_0600(self):
+ s = AppSettings()
+ k = AIKey(service=lambda: s.aiProvider)
+ k.save("sk-ling-000000000")
+ s.aiProvider = "zenmux"
+ self.assertIsNone(k.read())
+ k.save("sk-zen-0000000000")
+ self.assertTrue(k.path.endswith("ai-key-zenmux"))
+ self.assertEqual(0o600, os.stat(k.path).st_mode & 0o777)
+ s.aiProvider = "ling"
+ self.assertEqual("sk-ling-000000000", k.read())
+ self.assertNotIn("sk-", open(Paths.settings(), encoding="utf-8").read() if os.path.exists(Paths.settings()) else "")
+
+ def test_a_local_custom_service_needs_no_key(self):
+ ling, s = self.client(Fake(lambda u, b: reply("ok")), "custom", key=None, aiCustomBase="localhost:11434/v1",
+ aiModels={"custom": "qwen3:14b"})
+ self.assertEqual("", ling.current_key())
+ self.assertTrue(ling.has_key)
+ s.aiCustomBase = "https://api.example.com/v1"
+ self.assertFalse(ling.has_key)
+
+
+class Client(Base):
+ def test_requests_go_to_the_service_in_its_shape(self):
+ fake = Fake(lambda u, b: reply("LANG: en\nORIGINAL: Hi.\nTRANSLATION: 嗨。", finish=None))
+ ling, _ = self.client(fake)
+ # No finish reason: Ling's search essays come without one, other services may just omit it.
+ r = ling.chat("c", "i", TRANSLATE, model="qwen/qwen3.8-omni-flash", audio=bytes([1]))
+ self.assertIn("ORIGINAL: Hi.", r)
+ url, body = fake.sent[0]
+ self.assertEqual("https://zenmux.ai/api/v1/chat/completions", url)
+ b = jsonfmt.parse(body)
+ self.assertEqual({"enabled": False}, b["reasoning"])
+ self.assertNotIn("thinking", b)
+ self.assertEqual("input_audio", b["messages"][1]["content"][0]["type"])
+ # Text calls use the service's text model.
+ ling.chat("c", "i", TRANSLATE)
+ self.assertEqual("inclusionai/ling-3.0-flash", jsonfmt.parse(fake.sent[1][1])["model"])
+
+ def test_ling_still_drops_replies_without_a_finish_reason(self):
+ ling, _ = self.client(Fake(lambda u, b: reply("fine", finish=None)), "ling")
+ with self.assertRaises(LingError) as e:
+ ling.chat("c", "i", TRANSLATE)
+ self.assertEqual(LingError.HIJACKED, e.exception.kind)
+
+ def test_check_finds_a_hear_model_that_refuses_audio(self):
+ def respond(url, body):
+ if url.endswith("models"):
+ return Response(200, jsonfmt.write({"data": [{"id": "a/b", "input_modalities": ["text"], "output_modalities": ["text"]}]}))
+ return Response(400, "{}") if "input_audio" in body else reply("OK")
+ ling, s = self.client(Fake(respond), aiHearModels={"zenmux": "x/text-only"})
+ self.assertEqual(OK, ling.check())
+ self.assertFalse(ling.hears)
+ self.assertFalse(ling.can_hear)
+ self.assertTrue(ling.usable) # notes and translation still work
+ self.assertIn("a/b", ling.text_catalog)
+ s.aiHearModels.clear()
+ ling.key_changed()
+ self.assertIsNone(ling.hears)
+
+ def test_check_says_why(self):
+ ling, _ = self.client(Fake(lambda u, b: Response(401, "")))
+ self.assertEqual(INVALID, ling.check())
+ ling, _ = self.client(Fake(lambda u, b: Response(404, "")))
+ ling.check()
+ self.assertEqual(("%@ 拒绝了请求(HTTP %lld),请检查模型名", "ZenMux", 404), ling.problem)
+ ling, _ = self.client(Fake(lambda u, b: Response(200, "")), "openrouter", key=None)
+ self.assertEqual(NONE, ling.key_state)
+
+ def test_speech_from_each_service(self):
+ def sse(url, body):
+ chunk = base64.b64encode(b"\x01\x00\x02\x00").decode()
+ return StreamResponse(200, iter(["data: " + jsonfmt.write({"audio": chunk}, pretty=False), "data: {\"type\": \"speech.audio.done\"}"]))
+ fake = Fake(lambda u, b: reply("ok"), sse)
+ ling, _ = self.client(fake)
+ self.assertEqual([b"\x01\x00\x02\x00"], list(ling.speech("Hello", voice="Puck", language="ja")))
+ url, body = fake.streamed[0]
+ b = jsonfmt.parse(body)
+ self.assertEqual("https://zenmux.ai/api/v1/audio/speech", url)
+ self.assertEqual(("google/gemini-3.8-flash-tts", "Puck", True), (b["model"], b["voice"], b["stream"]))
+ self.assertNotIn("language_id", b)
+ # A voice that isn't this service's (a Ming name left in settings) becomes its first one.
+ list(ling.speech("Hello", voice="US_Emma"))
+ self.assertEqual("Kore", jsonfmt.parse(fake.streamed[1][1])["voice"])
+ # OpenRouter streams the PCM bytes themselves, without `stream`.
+ raw = Fake(lambda u, b: reply("ok"), lambda u, b: StreamResponse(200, iter(()), "audio/pcm", iter([b"\x05\x00", b"\x06\x00"])))
+ ling, _ = self.client(raw, "openrouter")
+ self.assertEqual([b"\x05\x00", b"\x06\x00"], list(ling.speech("Hi", voice=None)))
+ self.assertNotIn("stream", jsonfmt.parse(raw.streamed[0][1]))
+ # One JSON with a WAV in it.
+ wav = b"RIFF\x00\x00\x00\x00WAVEfmt \x10\x00\x00\x00" + bytes(16) + b"data\x04\x00\x00\x00\x07\x00\x08\x00"
+ one = Fake(lambda u, b: reply("ok"), lambda u, b: StreamResponse(
+ 200, iter(()), "application/json", iter([jsonfmt.write({"audio": base64.b64encode(wav).decode()}).encode()])))
+ ling, _ = self.client(one, "custom", aiCustomBase="https://x.example/v1", aiVoiceModels={"custom": "kokoro"}, aiCustomVoice="af_heart")
+ self.assertEqual([b"\x07\x00\x08\x00"], list(ling.speech("Hi", voice="af_heart")))
+ self.assertEqual(b"\x07\x00\x08\x00", pcm_from_wav(wav))
+
+ def test_no_voice_model_no_speech(self):
+ ling, _ = self.client(Fake(lambda u, b: reply("ok")), "custom", aiCustomBase="https://x.example/v1", aiModels={"custom": "m"})
+ self.assertFalse(ling.speaks)
+ with self.assertRaises(LingError):
+ list(ling.speech("Hi"))
+
+ def test_hearing_uses_the_hear_model(self):
+ fake = Fake(lambda u, b: reply("LANG: en\nORIGINAL: We ship on Friday.\nTRANSLATION: 我们周五发布。"))
+ ling, _ = self.client(fake, aiHearModels={"zenmux": "bytedance/doubao-seed-2.0-mini"})
+ heard = Translator(ling).hear(b"RIFF" + bytes(40) + bytes(32000), "zh-CN", None)
+ self.assertEqual("我们周五发布。", heard.translation)
+ self.assertEqual("bytedance/doubao-seed-2.0-mini", jsonfmt.parse(fake.sent[0][1])["model"])
+
+
+class Words(Base):
+ def test_voices_follow_the_service(self):
+ zen = AppSettings(aiProvider="zenmux").ai_config()
+ self.assertEqual(["Kore", "Aoede", "Charon", "Puck"], [v for v, _n, _t in voices.voices("ja", zen)])
+ self.assertIsNone(voices.ming_language("ja", zen))
+ self.assertEqual("ja", voices.ming_language("ja", AppSettings().ai_config()))
+ self.assertEqual("US_Emma", voices.default_voice("en"))
+
+ def test_problems_name_the_service(self):
+ self.assertEqual("key", problem(LingError(LingError.HTTP, 400), "ZenMux")[0])
+ self.assertIn("ZenMux", problem(LingError(LingError.NETWORK), "ZenMux")[1])
+ self.assertEqual(("network", "连不上 Ling"), problem(LingError(LingError.TIMEOUT), "Ling"))
+ self.assertIsNone(problem(LingError(LingError.HTTP, 400), "Ling")[0])
+
+ def test_a_clock_is_not_speech(self):
+ for made_up in ("00:00", "00:00.", "1:02:03"):
+ self.assertTrue(is_noise(made_up, 1.2), made_up)
+ for said in ("Hello.", "3 点", "15%", "好的"):
+ self.assertFalse(is_noise(said, 1.2), said)
+
+
+if __name__ == "__main__":
+ unittest.main()