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): notes can use their own model, or another OpenAI-compatible service with its own address and key

wquguru5f26aea53cf6
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index d1d85f3..3455016 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -4,8 +4,9 @@ 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) |
- ai-base text|voice|hear <url> (其他(兼容 OpenAI)'s addresses; "" for voice/hear: the text one)
+ provider ling|openrouter|zenmux|custom | ai-model hear|text|voice|notes <id> (设置 › AI 服务; "" back to the recommended) |
+ ai-base text|voice|hear|notes <url> (其他(兼容 OpenAI)'s addresses; "" for voice/hear/notes: the text one)
+ ai-notes same|own (纪要: 同一个服务 / 另一个服务, the Mac's aiCustomNotesOwn)
ai-custom-only on|off (语音和文字只发给你的服务, the Mac's aiCustomOnly)
speak-enable on|off | speak on|off (同声传译) | quit
calls <program=name,…>|none|real (meeting apps in a call) | endtimes <silence> <countdown> <grace>|off | endkeep
@@ -276,13 +277,19 @@ def command(app, line: str) -> dict:
if cmd == "ai-base":
# A custom service's addresses: text, voice or hear ("" for voice and hear: the text one).
kind, _, url = arg.partition(" ")
- field = {"text": "aiCustomBase", "voice": "aiCustomVoiceBase", "hear": "aiCustomHearBase"}.get(kind)
+ field = {"text": "aiCustomBase", "voice": "aiCustomVoiceBase", "hear": "aiCustomHearBase",
+ "notes": "aiCustomNotesBase"}.get(kind)
if field is None:
- return {"ok": False, "error": "ai-base text|voice|hear <url>"}
+ return {"ok": False, "error": "ai-base text|voice|hear|notes <url>"}
setattr(app.settings, field, url.strip())
app.settings.save()
app.ai_changed()
return {"ok": True, "ai": _ai(app)}
+ if cmd == "ai-notes":
+ app.settings.aiCustomNotesOwn = arg == "own"
+ app.settings.save()
+ app.ai_changed()
+ return {"ok": True, "ai": _ai(app)}
if cmd == "ai-custom-only":
app.set_custom_only(arg == "on")
return {"ok": True, "ai": _ai(app)}
@@ -707,5 +714,7 @@ def _ai(app) -> dict:
"keyWorks": app.key_works, "asking": getattr(app, "_asking", None) is not None,
"lastVoice": list(ling.last_voice) if ling.last_voice else None, "simulate": ling.simulate,
"catalog": [len(ling.text_catalog), len(ling.hear_catalog)], "keyFile": os.path.basename(app.key.path),
+ "notes": {"apart": c.notes_apart, "base": c.for_notes.base, "model": c.for_notes.text_model,
+ "ownKey": ling.notes_has_own_key, "catalog": len(ling.notes_catalog)},
"customOnly": app.settings.aiCustomOnly, "googleOff": app.translator.google_off,
"sentencesUntranslated": app.translator.sentences_untranslated}
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
index da8059e..4067147 100644
--- a/linux/cicada/app/main.py
+++ b/linux/cicada/app/main.py
@@ -447,15 +447,18 @@ class Controller:
self.set_ai_provider("ling")
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)."""
+ """A model chosen over the recommended one ("text", "hear", "voice", or a custom service's
+ "notes"; "" 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)
+ table = {"text": s.aiModels, "hear": s.aiHearModels, "voice": s.aiVoiceModels, "notes": s.aiModels}.get(kind)
if table is None:
return
+ if kind == "notes":
+ p = "custom.notes" # the custom service's notes model ("": the translation one)
if model:
table[p] = model
else:
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index 8ecf1ec..6847a1c 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -9,7 +9,7 @@ import threading
import time
import urllib.parse
-from gi.repository import Gdk, GLib, Gtk
+from gi.repository import Gdk, GLib, Gtk, Pango
from .. import VERSION
from ..core import ling as lingmod
@@ -632,13 +632,8 @@ class SettingsWindow(Gtk.Window):
self.custom_base_bad.set_no_show_all(True)
self.custom_base.connect("changed", lambda *_: self._custom_base_typed())
# The models the service lists, once fetched; a name can always be typed.
- self.custom_text = Gtk.ComboBoxText.new_with_entry()
- self.custom_text.get_child().set_text(s.aiModels.get("custom", ""))
- self.custom_text.get_child().set_placeholder_text(L("例如 qwen3:14b"))
- self.custom_text.get_child().set_width_chars(26)
- self.custom_text.get_child().connect("activate", lambda *_: self.save_key())
- self.custom_text.connect("changed", self._custom_model_picked)
- self._custom_listed = None
+ self.custom_text = ModelPicker(self._label(L("模型")), s.aiModels.get("custom", ""), L("例如 qwen3:14b"),
+ self._custom_model_picked, lambda: self._refetch(False))
self.custom_key_line = ui.text("", 13, "ink mono", wrap=False)
self.custom_key = Gtk.Entry()
self.custom_key.set_visibility(False)
@@ -648,18 +643,23 @@ class SettingsWindow(Gtk.Window):
self.custom_remove = ui.button(L("移除 key"), self.remove_key, "dangertext")
self.custom_save = ui.button(L("保存并检查"), self.save_key, "darkbtn")
key_row = ui.hbox(8, self._label("key"), self.custom_key_line)
- # Up to 保存并检查: "Optional on this computer or your local network" doesn't fit 26 characters.
+ # "Optional on this computer or your local network" doesn't fit 26 characters.
key_row.pack_start(self.custom_key, True, True, 0)
- for b in (self.custom_change, self.custom_remove, self.custom_save):
+ for b in (self.custom_change, self.custom_remove):
b.set_valign(Gtk.Align.CENTER)
key_row.pack_end(b, False, False, 0)
self.custom_key_hint = ui.hbox(8)
self.custom_key_hint.set_no_show_all(True)
self.custom_text_status = ui.vbox(6)
self.custom_editing = False
- text_body = ui.vbox(8, ui.hbox(8, self._label(L("地址")), self.custom_base), self.custom_base_bad,
- ui.hbox(8, self._label(L("模型")), self.custom_text), key_row, self.custom_key_hint,
- self.custom_text_status)
+ sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
+ ui.classes(sep, "hairline")
+ save_row = ui.hbox(8)
+ save_row.pack_end(self.custom_save, False, False, 0)
+ text_body = ui.vbox(8, self._subgroup(L("翻译")),
+ ui.hbox(8, self._label(L("地址")), self.custom_base), self.custom_base_bad,
+ key_row, self.custom_key_hint, self.custom_text.widget,
+ sep, self._notes_group(), save_row, self.custom_text_status)
# 同传声音: Linux has no voice of its own to fall back on.
self.custom_voice_model = self._field(L("例如 qwen3-tts"), s.aiVoiceModels.get("custom", ""))
self.custom_voice = self._field(L("例如 vivian"), s.aiCustomVoice)
@@ -697,6 +697,130 @@ class SettingsWindow(Gtk.Window):
body.set_visible(False)
return page
+ # 纪要: AISettings.swift › notesGroup
+
+ def _notes_group(self) -> Gtk.Widget:
+ """The same service as translation (another model at most), or another one with its own
+ address and key. Switching back keeps what was typed."""
+ s = self.app.settings
+ head = ui.hbox(8, self._subgroup(L("纪要")))
+ head.pack_end(ui.segmented([("same", L("同一个服务")), ("own", L("另一个服务"))],
+ "own" if s.aiCustomNotesOwn else "same", self._notes_own_picked), False, False, 0)
+ self.notes_base = self._field(L("跟上面一样"), s.aiCustomNotesBase)
+ self.notes_base_bad = ui.text(L("地址要用 https;这台电脑和局域网里的服务可以用 http。"), 11, "stepwhy", width_chars=46)
+ self.notes_base_bad.set_no_show_all(True)
+ self.notes_key_line = ui.text("", 13, "ink mono", wrap=False)
+ self.notes_key = Gtk.Entry()
+ self.notes_key.set_visibility(False)
+ self.notes_key.set_width_chars(26)
+ self.notes_key.set_placeholder_text(L("不填就用上面的 key"))
+ self.notes_key.connect("activate", lambda *_: self.save_key())
+ self.notes_change = ui.button(L("更换"), self._notes_change_key, "outline")
+ self.notes_remove = ui.button(L("移除"), self._notes_remove_key, "dangertext")
+ self.notes_editing = False
+ key_row = ui.hbox(8, self._label("key"), self.notes_key_line)
+ key_row.pack_start(self.notes_key, True, True, 0)
+ for b in (self.notes_change, self.notes_remove):
+ b.set_valign(Gtk.Align.CENTER)
+ key_row.pack_end(b, False, False, 0)
+ self.notes_own = ui.vbox(8, ui.hbox(8, self._label(L("地址")), self.notes_base), self.notes_base_bad, key_row)
+ self.notes_own.set_no_show_all(True)
+ for w in self.notes_own.get_children():
+ w.show_all()
+ self.notes_own.set_visible(s.aiCustomNotesOwn)
+ self.notes_model = ModelPicker(self._label(L("模型")), s.aiModels.get("custom.notes", ""), L("和翻译模型一样"),
+ self._notes_model_picked, lambda: self._refetch(True), same_label=L("和翻译模型一样"))
+ # The grey helper, or why the notes' own model or server doesn't work.
+ self.notes_line = ui.text("", 11, "tertiary", width_chars=46)
+ return ui.vbox(8, head, self.notes_own, self.notes_model.widget,
+ ui.pad(self.notes_line, 0, 0, 0, 42))
+
+ def _notes_own_picked(self, value: str) -> None:
+ s = self.app.settings
+ own = value == "own"
+ if own == s.aiCustomNotesOwn:
+ return
+ s.aiCustomNotesOwn = own
+ if own:
+ s.aiCustomNotesBase = self.notes_base.get_text().strip()
+ s.save()
+ self.notes_own.set_visible(own)
+ self.app.ai_changed()
+
+ def _notes_model_picked(self, mid: str) -> None:
+ self.save_key()
+
+ def _notes_change_key(self) -> None:
+ self.notes_editing = True
+ self.notes_key.set_text("")
+ self._show_notes_key()
+ self.notes_key.grab_focus()
+
+ def _notes_remove_key(self) -> None:
+ """Notes go back to the translation key."""
+ self.app.ling.notes_key_file.remove()
+ self.notes_editing = False
+ self.app.ai_changed()
+
+ def _show_notes_key(self) -> None:
+ ling = self.app.ling
+ own = ling.notes_key_file.read() if ling.notes_has_own_key else None
+ editing = not own or self.notes_editing
+ self.notes_key_line.set_visible(not editing)
+ ui.retext(self.notes_key_line, AIKey.masked(own) if own else "")
+ self.notes_key.set_visible(editing)
+ self.notes_change.set_visible(not editing)
+ self.notes_remove.set_visible(not editing)
+ n = ling.check_result.notes
+ bad = n is not None and n.reason == lingmod.aicheck.INVALID_KEY
+ (self.notes_key.get_style_context().add_class if bad else self.notes_key.get_style_context().remove_class)("error")
+
+ def _refetch(self, notes: bool) -> None:
+ """重新获取: the list of the address a model menu shows (the notes' own, or the service's)."""
+ ling = self.app.ling
+ c = ling.config()
+ own = notes and c.notes_apart and c.for_notes.base != c.base
+ threading.Thread(target=ling.fetch_notes_catalog if own else ling.fetch_catalog, daemon=True).start()
+
+ @staticmethod
+ def _subgroup(title: str) -> Gtk.Widget:
+ """翻译 / 纪要 inside 翻译和纪要: 12 px semibold, ink."""
+ return ui.text(title, 12, "ink", bold=True, wrap=False)
+
+ def _check_rows(self, c, r) -> Gtk.Widget:
+ """After a check with notes apart: one row each, what it runs and how it did."""
+ from ..core import aicheck
+ t, n = r.translate, r.notes
+ if n is None:
+ notes_text, notes_ok = "", True
+ elif n.kind == aicheck.OK:
+ notes_text, notes_ok = LF("能写纪要 · %@ 秒", "%.1f" % (n.seconds or 0)), True
+ elif n.kind == aicheck.RUNNING:
+ notes_text, notes_ok = L("正在检查…"), True
+ elif n.reason in (aicheck.INVALID_KEY, aicheck.MGMT_KEY):
+ notes_text, notes_ok = L("key 不对"), False
+ else:
+ notes_text, notes_ok = L("纪要写不了"), False
+
+ def row(use, model, ok, result):
+ dot = Gtk.Box()
+ dot.set_valign(Gtk.Align.CENTER)
+ ui.classes(dot, "statedot", "ok" if ok else "error")
+ name = ui.text(use, 12, "ink", wrap=False, ellipsize=False)
+ name.set_size_request(34, -1)
+ m = ui.text(model, 12, "secondary mono", wrap=False)
+ m.set_ellipsize(Pango.EllipsizeMode.MIDDLE)
+ line = ui.hbox(10, dot, name)
+ line.pack_start(m, True, True, 0)
+ line.pack_end(ui.text(result, 12, "ok" if ok else "stepwhy", wrap=False, ellipsize=False), False, False, 0)
+ line.set_size_request(-1, 36)
+ return ui.pad(line, 0, 12)
+ sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
+ ui.classes(sep, "hairline")
+ return ui.panel(ui.vbox(0, row(L("翻译"), c.text_model, True,
+ LF("翻一句 %@ 秒", "%.1f" % t.seconds) + " · " + (L("会先思考") if t.thinks else L("不思考"))),
+ sep, row(L("纪要"), c.for_notes.text_model, notes_ok, notes_text)), "boxed")
+
def _only_toggled(self, w, _p) -> None:
if w.get_active() != self.app.settings.aiCustomOnly:
self.app.set_custom_only(w.get_active())
@@ -749,12 +873,9 @@ class SettingsWindow(Gtk.Window):
self.custom_base_bad.set_visible(bool(typed) and providers.custom_base(typed) is None)
self.custom_key.set_placeholder_text(L("本机和局域网服务可不填") if typed and providers.is_nearby(typed) else "sk-…")
- def _custom_model_picked(self, combo) -> None:
- """A model picked from the service's list saves and checks it (typing waits for Enter)."""
- mid = combo.get_active_id()
- if mid is not None and mid != self.app.settings.aiModels.get("custom", ""):
- combo.get_child().set_text(mid)
- self.save_key()
+ def _custom_model_picked(self, mid: str) -> None:
+ """A model picked from the service's list (or typed, then Enter) saves and checks it."""
+ self.save_key()
def _custom_change_key(self) -> None:
self.custom_editing = True
@@ -788,16 +909,23 @@ class SettingsWindow(Gtk.Window):
sens = not r.running
self.custom_save.set_sensitive(sens)
self.custom_save.set_label(L("正在检查…") if r.running else L("保存并检查"))
- # The model menu: what the service lists, once fetched.
- listed = tuple(ling.text_catalog)
- if listed != self._custom_listed:
- self._custom_listed = listed
- typed = self.custom_text.get_child().get_text()
- self.custom_text.remove_all()
- for mid in listed:
- self.custom_text.append(mid, mid)
- self.custom_text.get_child().set_text(typed)
- self.custom_text.set_button_sensitivity(Gtk.SensitivityType.ON if listed else Gtk.SensitivityType.OFF)
+ # The model menus: what each address lists, once fetched.
+ host = urllib.parse.urlsplit(c.base or "").hostname or ""
+ self.custom_text.fill(ling.text_catalog, host)
+ notes_elsewhere = c.notes_apart and c.for_notes.base != c.base
+ notes_host = urllib.parse.urlsplit(c.for_notes.base or "").hostname or host
+ self.notes_model.fill(ling.notes_catalog if notes_elsewhere else ling.text_catalog, notes_host)
+ self.notes_base_bad.set_visible(s.aiCustomNotesOwn and c.notes_bad_address)
+ self._show_notes_key()
+ shared = not ling.notes_has_own_key
+ why = r.notes_line(notes_host, c.for_notes.text_model, shared) if have else None
+ for cls in ("stepwhy", "tertiary"):
+ self.notes_line.get_style_context().remove_class(cls)
+ self.notes_line.get_style_context().add_class("stepwhy" if why else "tertiary")
+ # The Mac's sizes: 12 for the red line, 11 for the grey one (retext applies the size).
+ self.notes_line.cicada_format = (12 if why else 11,) + tuple(self.notes_line.cicada_format[1:])
+ ui.retext(self.notes_line, why or L("用来写实时纪要、识别说话人,默认和翻译用同一个"))
+ self.notes_own.set_visible(s.aiCustomNotesOwn) # a debug command may have switched it
def head(sid, state, detail, trailing, tone=""):
dot, d, t, _ = self.custom_heads[sid]
@@ -812,15 +940,15 @@ class SettingsWindow(Gtk.Window):
t.get_style_context().add_class(tone or "tertiary")
# 翻译和纪要
- host = urllib.parse.urlsplit(c.base or "").hostname or ""
text_failed = f is not None and f[0] != "hear"
+ notes_down = f is None and r.notes_failed
if not have:
state = ""
elif r.running:
state = "live"
elif text_failed:
state = "error"
- elif r.slow or r.busy:
+ elif r.slow or r.busy or r.notes_failed:
state = "warn"
else:
state = "ok" if r.passed or (f is not None and f[0] == "hear") else ""
@@ -828,12 +956,14 @@ class SettingsWindow(Gtk.Window):
trailing = L("正在检查…")
elif text_failed and have:
trailing = {"reach": L("暂时连不上"), "key": L("这个 key 用不了")}.get(f[0], L("模型用不了"))
+ elif notes_down and have:
+ trailing = L("纪要写不了")
elif r.translate is not None:
trailing = LF("翻一句 %@ 秒", "%.1f" % r.translate.seconds)
else:
trailing = None
- head("text", state, "%s · %s" % (host, c.text_model) if host and c.text_model else L("填上地址和模型"), trailing,
- "warn" if r.slow else "stepwhy" if text_failed and have else "")
+ head("text", state, self._text_detail(c, host), trailing,
+ "stepwhy" if have and (text_failed or notes_down) else "warn" if r.slow else "")
ui.clear(self.custom_text_status)
slow = r.slow_line(google_off=s.aiCustomOnly) # this page is the custom service's
if slow:
@@ -842,6 +972,8 @@ class SettingsWindow(Gtk.Window):
card = ui.panel(ui.pad(aicheck_view.steps_widget(app, self._custom_change_key, recheck_in_step=False,
width_chars=40), 2, 12), "boxed")
self.custom_text_status.pack_start(card, False, False, 0)
+ elif (r.passed or (f is not None and f[0] == "hear")) and c.notes_apart and r.translate is not None:
+ self.custom_text_status.pack_start(self._check_rows(c, r), False, False, 0)
elif r.passed or (f is not None and f[0] == "hear"):
facts = [L("能写纪要")]
if r.translate is not None:
@@ -897,6 +1029,20 @@ class SettingsWindow(Gtk.Window):
if not r.passed or r.slow:
self._custom_toggle("text", True)
+ @staticmethod
+ def _text_detail(c, host: str) -> str:
+ """"192.168.1.20 · qwen-mt-turbo", then the notes' model, or their own server after a bar."""
+ if not host or not c.text_model:
+ return L("填上地址和模型")
+ line = "%s · %s" % (host, c.text_model)
+ if not c.notes_apart:
+ return line
+ n = c.for_notes
+ nhost = urllib.parse.urlsplit(n.base or "").hostname
+ if nhost and n.base != c.base:
+ return line + " | %s · %s" % (nhost, n.text_model)
+ return line if n.text_model == c.text_model else line + " · " + n.text_model
+
def _field(self, placeholder: str, value: str) -> Gtk.Entry:
e = Gtk.Entry()
e.set_placeholder_text(placeholder)
@@ -1093,6 +1239,10 @@ class SettingsWindow(Gtk.Window):
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("你填的地址")
+ if custom:
+ # Where the key goes: every use's address, the notes' only while they share it.
+ from ..core.providers import hosts
+ host = _hosts_words(hosts(c, notes=not app.ling.notes_has_own_key))
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))
if custom:
@@ -1101,8 +1251,8 @@ class SettingsWindow(Gtk.Window):
from ..core.providers import is_nearby
cost = L("跑在你自己的机器上,不按量计费。") if c.base and is_nearby(c.base) else L("费用以这个服务为准。")
if app.settings.aiCustomOnly:
- from ..core.providers import only_host
- ui.retext(self.footnote, cost + LF("会议的语音和文字只发给 %@,不经过 Google 等外部服务。", only_host(c) or L("你填的地址")))
+ from ..core.providers import hosts
+ ui.retext(self.footnote, cost + LF("会议的语音和文字只发给 %@,不经过 Google 等外部服务。", _hosts_words(hosts(c))))
else:
ui.retext(self.footnote, cost + LF("听的时候,电脑里的声音会发给 %@。", app.ling.hear_host or L("你填的地址")))
else:
@@ -1133,7 +1283,14 @@ class SettingsWindow(Gtk.Window):
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_child().get_text().strip()
+ s.aiModels["custom"] = self.custom_text.text()
+ notes_model = self.notes_model.text()
+ if notes_model:
+ s.aiModels["custom.notes"] = notes_model
+ else:
+ s.aiModels.pop("custom.notes", None)
+ if s.aiCustomNotesOwn: # 同一个服务 keeps the address typed before
+ s.aiCustomNotesBase = self.notes_base.get_text().strip()
s.aiHearModels["custom"] = self.custom_hear.get_text().strip()
s.aiCustomHearBase = self.custom_hear_base.get_text().strip()
s.aiVoiceModels["custom"] = self.custom_voice_model.get_text().strip()
@@ -1155,6 +1312,11 @@ class SettingsWindow(Gtk.Window):
return
entry.set_text("")
self.custom_editing = False
+ # Notes' own key (另一个服务): saved here too; it goes only to the notes' address.
+ nk = self.notes_key.get_text().strip()
+ if s.aiProvider == "custom" and nk and s.aiCustomNotesOwn and app.ling.notes_key_file.save(nk):
+ self.notes_key.set_text("")
+ self.notes_editing = False
app.ai_changed()
def _show_key_hint(self, hint, key: str = "") -> None:
@@ -1196,6 +1358,114 @@ class SettingsWindow(Gtk.Window):
open_uri("file://" + path)
+def _hosts_words(hosts: list) -> str:
+ """One host, "a 和 b", or 你填的地址 for more (AISettings.swift › customHosts)."""
+ if len(hosts) == 1:
+ return hosts[0]
+ if len(hosts) == 2:
+ return LF("%@ 和 %@", hosts[0], hosts[1])
+ return L("你填的地址")
+
+
+class ModelPicker:
+ """A custom service's model (AISettings.swift › ModelPicker): the names its `/models` lists, in
+ the menu and searched as you type, and any name typed that it doesn't list (an alias, a model it
+ hides): 用 X(列表里没有). Enter takes the only match, else what was typed. `same_label`: a first
+ choice that clears the value (和翻译模型一样). Without a list it is a plain field. Picking calls
+ `on_pick`; 重新获取 calls `refetch`."""
+
+ def __init__(self, label: Gtk.Widget, value: str, placeholder: str, on_pick, refetch, same_label: str | None = None):
+ self.on_pick = on_pick
+ self.same_label = same_label
+ self.catalog: tuple = ()
+ self._filling = False
+ self.combo = Gtk.ComboBoxText.new_with_entry()
+ self.entry = self.combo.get_child()
+ self._action = False
+ self.entry.connect("changed", lambda *_: self._typed())
+ self.entry.set_text(value)
+ self.entry.set_placeholder_text(same_label or placeholder)
+ self.entry.set_width_chars(26)
+ self.entry.connect("activate", lambda *_: self._enter())
+ self.combo.connect("changed", self._chosen)
+ self.combo.set_button_sensitivity(Gtk.SensitivityType.OFF)
+ # Search: every listed name that contains what's typed, any case.
+ self.store = Gtk.ListStore(str)
+ self.completion = Gtk.EntryCompletion()
+ self.completion.set_model(self.store)
+ self.completion.set_text_column(0)
+ self.completion.set_minimum_key_length(1)
+ self.completion.set_match_func(lambda _c, key, it: key.strip().lower() in (self.store[it][0] or "").lower())
+ self.completion.connect("match-selected", lambda _c, model, it: (self.pick(model[it][0]), True)[1])
+ self.completion.connect("action-activated", lambda *_: self.pick(self.text()))
+ self.entry.set_completion(self.completion)
+ self.refetch_button = ui.button(L("重新获取"), refetch, "outline")
+ self.refetch_button.set_valign(Gtk.Align.CENTER)
+ self.refetch_button.set_no_show_all(True)
+ self.footer = ui.text("", 11, "tertiary", wrap=False)
+ self.footer.set_no_show_all(True)
+ row = ui.hbox(8, label)
+ row.pack_start(self.combo, True, True, 0)
+ row.pack_end(self.refetch_button, False, False, 0)
+ # The list's line sits under the field, past the row's label (34 px and the 8 px gap).
+ self.widget = ui.vbox(4, row, ui.pad(self.footer, 0, 0, 0, 42))
+
+ def text(self) -> str:
+ return self.entry.get_text().strip()
+
+ def fill(self, catalog, host: str) -> None:
+ """The names `host` lists (empty: none, or not fetched yet). Keeps what's typed."""
+ listed = tuple(catalog)
+ self.refetch_button.set_visible(bool(host))
+ if listed == self.catalog:
+ return
+ self.catalog = listed
+ typed = self.entry.get_text()
+ self._filling = True
+ self.combo.remove_all()
+ if listed and self.same_label:
+ self.combo.append("", self.same_label)
+ for mid in listed:
+ self.combo.append(mid, mid)
+ self.store.clear()
+ for mid in listed:
+ self.store.append([mid])
+ self.entry.set_text(typed)
+ self._filling = False
+ self.combo.set_button_sensitivity(Gtk.SensitivityType.ON if listed else Gtk.SensitivityType.OFF)
+ self.entry.set_tooltip_text(None if listed else L("这个地址没列出模型,直接填名字"))
+ ui.retext(self.footer, LF("%@ 列出 %lld 个模型", host, len(listed)) if listed else "")
+ self.footer.set_visible(bool(listed))
+
+ def pick(self, mid: str) -> None:
+ self._filling = True
+ self.entry.set_text(mid)
+ self._filling = False
+ self.on_pick(mid)
+
+ def _chosen(self, combo) -> None:
+ mid = combo.get_active_id()
+ if mid is not None and not self._filling:
+ self.pick(mid) # the id: 和翻译模型一样 is ""
+
+ def _enter(self) -> None:
+ q = self.text()
+ matches = [m for m in self.catalog if q.lower() in m.lower()] if q else list(self.catalog)
+ self.pick(matches[0] if len(matches) == 1 else q)
+
+ def _typed(self) -> None:
+ """用 X(列表里没有), under the matches, while what's typed isn't a listed name."""
+ if self._action:
+ self.completion.delete_action(0)
+ self._action = False
+ q = self.text()
+ # Names in mono, as on the Mac; the placeholder (和翻译模型一样) in the UI font.
+ (self.entry.get_style_context().add_class if q else self.entry.get_style_context().remove_class)("mono")
+ if q and self.catalog and q not in self.catalog:
+ self.completion.insert_action_text(0, LF("用 %@(列表里没有)", q))
+ self._action = True
+
+
def _labels(w) -> list:
out = [w] if isinstance(w, Gtk.Label) else []
if hasattr(w, "get_children"):
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
index 5c6934d..7bfa3e7 100644
--- a/linux/cicada/app/ui.py
+++ b/linux/cicada/app/ui.py
@@ -79,6 +79,7 @@ combobox arrow { -gtk-icon-source: -gtk-icontheme("pan-down-symbolic"); min-widt
combobox cellview, combobox button label { font-size: 12px; }
entry { background-image: none; background-color: #FFFFFF; border: 1px solid #E4E6EA; box-shadow: none; border-radius: 7px; min-height: 26px; padding: 0 9px; font-size: 13px; color: #15171C; caret-color: #15171C; }
entry:focus { border-color: #E8552B; box-shadow: 0 0 0 2px rgba(232,85,43,0.18); }
+entry.error { border-color: #B3261E; }
entry.search { background-color: #E8EAEE; border-color: transparent; min-height: 28px; font-size: 12px; }
entry.search:focus { background-color: #FFFFFF; }
entry selection, label selection { background-color: rgba(232,85,43,0.22); color: #15171C; }
@@ -200,6 +201,7 @@ button.iconbtn.on { background-color: #F3F4F6; color: #15171C; }
.breathemark.late { animation-delay: 1.1s; }
.idledot { background-color: #C9CCD3; border-radius: 4px; min-width: 7px; min-height: 7px; }
/* The custom service's per-use rows: how each use is doing (AISettings.swift sectionHeader). */
+separator.hairline { background-color: #E4E6EA; min-height: 1px; margin: 4px 0; }
.statedot { background-color: #C9CCD3; border-radius: 4px; min-width: 8px; min-height: 8px; }
.statedot.ok { background-color: #1F7A45; }
.statedot.warn { background-color: #8A5A00; }
diff --git a/linux/cicada/core/aicheck.py b/linux/cicada/core/aicheck.py
index 6c10b8a..cd7a677 100644
--- a/linux/cicada/core/aicheck.py
+++ b/linux/cicada/core/aicheck.py
@@ -66,6 +66,10 @@ class AICheck:
self.balance: float | None = None
# A custom service: the real sentence the check translated (Speed).
self.translate: Speed | None = None
+ # A custom service whose notes go to another model or server: how that one answered (a State:
+ # running, ok or fail). None while notes use the translation model (then the steps say it
+ # all). A notes failure doesn't stop translation: `failure` and `passed` stay about it.
+ self.notes: State | None = None
def copy(self) -> "AICheck":
return copy.deepcopy(self)
@@ -92,7 +96,12 @@ class AICheck:
@property
def running(self) -> bool:
- return any(st.kind == RUNNING for st in self.steps.values())
+ return any(st.kind == RUNNING for st in self.steps.values()) or (self.notes is not None and self.notes.kind == RUNNING)
+
+ @property
+ def notes_failed(self) -> bool:
+ """Translation works but the notes' own model or server doesn't (a busy one fixes itself)."""
+ return self.notes is not None and self.notes.kind == FAIL and self.notes.reason != BUSY
@property
def busy(self) -> bool:
@@ -195,6 +204,25 @@ class AICheck:
return LF("这个模型先思考再回答,翻一句要 %@ 秒,超过 6 秒会改用 Google。在服务端关掉思考,或换一个不思考的模型。", secs)
return LF("翻一句要 %@ 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。", secs)
+ def notes_line(self, host: str, model: str, shared_key: bool) -> str | None:
+ """The notes' own model or server's problem, in one sentence. `shared_key`: notes use the
+ translation key, so a refused key wants one of their own."""
+ n = self.notes
+ if n is None or n.kind != FAIL:
+ return None
+ reason = n.reason
+ if reason in (INVALID_KEY, MGMT_KEY):
+ return LF("%@ 不认上面的 key,给它单独填一个。", host) if shared_key else LF("%@ 说这个 key 无效,可能没复制全,或已删除。", host)
+ if reason == SERVER_ERROR:
+ return LF("%@ 暂时出错(HTTP %lld),稍后再试。", host, n.code or 0)
+ return {
+ UNREACHABLE: lambda: LF("这台电脑访问不到 %@。", host),
+ BAD_ADDRESS: lambda: L("地址要用 https;这台电脑和局域网里的服务可以用 http。"),
+ NO_CREDIT: lambda: LF("%@ 账户余额不足。", host),
+ NO_MODEL: lambda: LF("%@ 上找不到 %@ 这个模型。", host, model),
+ NO_JSON: lambda: L("这个模型没按要求返回 JSON,写不了纪要。换一个通用模型。"),
+ }.get(reason, lambda: None)()
+
def proxy_line(self, service: str, host: str) -> str | None:
"""Under "can't reach": what this computer's proxy looks like, and what to do."""
from .providers import is_nearby
@@ -222,16 +250,7 @@ class AICheck:
def summary(self) -> str:
"""Debug and logs: "reach=ok key=fail(invalidKey) text=skipped hear=skipped"."""
- out = []
- for s in STEPS:
- st = self.steps[s]
- if st.kind == OK:
- v = "ok" if st.seconds is None else "ok(%.1fs)" % st.seconds
- elif st.kind == FAIL:
- v = "fail(%s%s)" % (st.reason, "" if st.code is None else " %d" % st.code)
- else:
- v = st.kind
- out.append("%s=%s" % (s, v))
+ out = ["%s=%s" % (s, _state(self.steps[s])) for s in STEPS]
if self.proxy is not None:
out.append("proxy=" + ":".join(str(p) for p in self.proxy))
if self.balance is not None:
@@ -240,9 +259,19 @@ class AICheck:
out.append("passive")
if self.translate is not None:
out.append("translate=%.1fs%s" % (self.translate.seconds, " thinks" if self.translate.thinks else ""))
+ if self.notes is not None:
+ out.append("notes=" + _state(self.notes))
return " ".join(out)
+def _state(st: State) -> str:
+ if st.kind == OK:
+ return "ok" if st.seconds is None else "ok(%.1fs)" % st.seconds
+ if st.kind == FAIL:
+ return "fail(%s%s)" % (st.reason, "" if st.code is None else " %d" % st.code)
+ return st.kind
+
+
def title(step: str, host: str) -> str:
return {"reach": lambda: LF("连上 %@", host), "key": lambda: L("key 可以用"),
"text": lambda: L("纪要和翻译"), "hear": lambda: L("听对方")}[step]()
diff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.py
index ba72b72..5bde2c9 100644
--- a/linux/cicada/core/ling.py
+++ b/linux/cicada/core/ling.py
@@ -224,6 +224,20 @@ def silence_wav(seconds: float = 0.5) -> bytes:
return buf.getvalue()
+# The key file of the custom service's notes server (另一个服务), named as on the Mac.
+NOTES_KEY = "custom-notes"
+
+
+class _Gate:
+ """One server's request starts (by host): notes on another server don't wait behind
+ translation, and its 429 doesn't hold translation back."""
+
+ def __init__(self):
+ self.waiting: list = []
+ self.last_start = -1e9
+ self.paused_until = 0.0 # after a 429 no request starts here before this (clock time)
+
+
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)
@@ -238,8 +252,10 @@ class LingClient:
UI thread."""
spacing: float | None = None # tests only: overrides the service's
- def __init__(self, key: AIKey, transport=UrlTransport, config=None, clock=None):
+ def __init__(self, key: AIKey, transport=UrlTransport, config=None, clock=None, notes_key: AIKey | None = None):
self.key = key
+ # 另一个服务's own key for notes; without one, notes use `key` ("不填就用上面的 key").
+ self.notes_key_file = notes_key or AIKey(service=lambda: NOTES_KEY)
self.transport = transport
self.clock = clock or Clock()
self.config = config or _ling_config
@@ -255,15 +271,16 @@ class LingClient:
self.simulate: str | None = None
self.text_catalog: list = []
self.hear_catalog: list = []
+ # Notes' own server's text models from its `/models` (empty while notes share translation's address).
+ self.notes_catalog: list = []
# Every model id the service lists, and those that take audio, to tell whether the chosen
# ones still exist (None: the service can't tell).
self._listed: tuple = (None, None)
self.rate_limited_at = None
self._listeners = []
+ # Every server's start gate (_Gate, by host) shares this one lock.
self._gate = threading.Condition()
- self._waiting = []
- self._last_start = -1e9
- self._paused_until = 0.0 # after a 429 no request starts before this (clock time)
+ self._gates: dict = {}
self._seq = 0
self._check_lock = threading.Lock()
self._check_seq = 0
@@ -296,6 +313,20 @@ class LingClient:
def has_key(self) -> bool:
return self.current_key() is not None
+ def notes_key(self) -> str | None:
+ """The key notes are sent with: with 另一个服务, their own key file if there is one, else the
+ translation key."""
+ if self.config().notes_own_service:
+ own = self.notes_key_file.read()
+ if own is not None:
+ return own
+ return self.current_key()
+
+ @property
+ def notes_has_own_key(self) -> bool:
+ """Notes have a key file of their own (另一个服务 only)."""
+ return self.config().notes_own_service and self.notes_key_file.read() is not None
+
@property
def usable(self) -> bool:
return self.has_key and self.key_state != INVALID
@@ -356,13 +387,14 @@ class LingClient:
def key_changed(self) -> None:
"""The key, the service or its models changed: forget what the last check found."""
self.key.reload()
+ self.notes_key_file.reload()
with self._check_lock:
self._check_seq += 1 # a check still running for the old settings is dropped
self.check_result = aicheck.AICheck()
self.key_state = NONE if self.current_key() is None else UNCHECKED
self.last_voice = None
self._plain_bases = set()
- self.text_catalog, self.hear_catalog = [], []
+ self.text_catalog, self.hear_catalog, self.notes_catalog = [], [], []
self._listed = (None, None)
self._changed()
@@ -392,13 +424,13 @@ class LingClient:
with self._check_lock:
self._checking += 1
try:
- r = self._run_check(r, c, k)
+ r = self._run_check(r, c, k, seq)
finally:
with self._check_lock:
self._checking -= 1
return self._finish_check(r, c, seq)
- def _run_check(self, r, c: AIConfig, k: str):
+ def _run_check(self, r, c: AIConfig, k: str, seq: int = 0):
if self.simulate:
return aicheck.simulated(self.simulate)
if c.provider.id == "custom" and c.base is None:
@@ -422,7 +454,15 @@ class LingClient:
self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=20.0)
self.seconds = time.monotonic() - started
r.pass_up_to("text", self.seconds)
- if c.provider.id == "custom":
+ if c.notes_apart:
+ # Notes at their own model or server: their failure is theirs, translation goes on.
+ r.notes = aicheck.State(aicheck.RUNNING)
+ with self._check_lock:
+ if seq == self._check_seq:
+ self.check_result = r.copy()
+ self._changed()
+ r.notes = self._check_notes(c)
+ elif c.provider.id == "custom":
ask = "Reply with the JSON object {\"ok\": true}."
try:
self.chat(ask, "Reply.", SPEAK, json=True, max_tokens=20, timeout=30.0, json_fallback=False)
@@ -465,14 +505,62 @@ class LingClient:
if r.failure is None or r.failure[0] == "hear": # the menus want the models even when the hear one is deaf
self.fetch_catalog()
every, hear = self._listed
- # A model the service no longer lists fails here, before a meeting finds out.
- if every is not None and c.text_model and c.text_model not in every:
- r.fail("text", aicheck.NO_MODEL)
+ # A model the service no longer lists fails here, before a meeting finds out. One a real
+ # request just went through exists whatever the list says (an alias, a name typed by hand).
+ if every is not None and c.text_model and r["text"].kind == aicheck.UNTESTED:
+ if c.text_model not in every:
+ r.fail("text", aicheck.NO_MODEL)
+ else:
+ r["text"] = aicheck.State(aicheck.OK)
# The list is the text address's: a hear model elsewhere isn't in it.
- elif hear is not None and not c.own_hear_address and c.hear_model not in hear and r.failure is None:
+ if hear is not None and not c.own_hear_address and c.hear_model not in hear and r.failure is None:
r.fail("hear", aicheck.DEAF)
return r
+ def _check_notes(self, config: AIConfig):
+ """Notes' own model or server: one JSON request the way a meeting's notes ask, then (another
+ address) its model list for the menu. Straight to the server, not through `chat`: notes'
+ 429 retries are a meeting's, not a check's."""
+ if config.notes_bad_address:
+ return aicheck.State(aicheck.FAIL, reason=aicheck.BAD_ADDRESS)
+ c = config.for_notes
+ k = self.notes_key()
+ if k is None or c.base is None:
+ return aicheck.State(aicheck.FAIL, reason=aicheck.INVALID_KEY)
+ body = {"model": c.text_model,
+ "messages": [{"role": "system", "content": "Reply with the JSON object {\"ok\": true}."},
+ {"role": "user", "content": "Reply."}],
+ "stream": False}
+ c.shape(body, 20, template_kwargs=c.base not in self._plain_bases)
+ body["response_format"] = {"type": "json_object"}
+ asked = time.monotonic()
+ try:
+ self._acquire(SPEAK, c.provider.spacing, base=c.base)
+ try:
+ self._post_chat(c.base, body, k, 60.0, notes=True)
+ result = aicheck.State(aicheck.OK, time.monotonic() - asked)
+ except LingError as e:
+ if not (e.kind == LingError.HTTP and e.status in (400, 422)):
+ raise
+ # JSON mode refused: meetings then ask without it, so what counts is a JSON answer.
+ del body["response_format"]
+ try:
+ root = self._post_chat(c.base, body, k, 60.0, notes=True)
+ except LingError:
+ root = None
+ choices = arr((root or {}).get("choices"))
+ said = string((obj((obj(choices[0]) or {}).get("message")) or {}).get("content")) if choices else None
+ result = (aicheck.State(aicheck.OK, time.monotonic() - asked) if answers_json(said)
+ else aicheck.State(aicheck.FAIL, reason=aicheck.NO_JSON, code=e.status))
+ except LingError as e:
+ _, reason, code = aicheck.classify(e, "text") or ("text", aicheck.SERVER_ERROR, None)
+ result = aicheck.State(aicheck.FAIL, reason=reason, code=code)
+ except Exception: # noqa: BLE001
+ result = aicheck.State(aicheck.FAIL, reason=aicheck.UNREACHABLE)
+ if c.base != config.base:
+ self.fetch_notes_catalog()
+ return result
+
@staticmethod
def _failed(r, classified, step: str) -> None:
"""A check's request failed: busy passes (the key works), anything else stops there."""
@@ -523,11 +611,33 @@ class LingClient:
if r[s].kind == aicheck.OK and r[s].seconds is not None:
self.seconds = r[s].seconds
- def observe(self, failure: LingError | None, seconds: float = 0.0, audio: bool = False) -> None:
+ def observe(self, failure: LingError | None, seconds: float = 0.0, audio: bool = False, notes: bool = False) -> None:
"""A real request (hearing, notes, translation) came back: keep the steps current without a
- check. One server error in a meeting isn't worth repainting the settings for."""
+ check. One server error in a meeting isn't worth repainting the settings for. `notes`: it
+ went to the notes' own model or server, whose result is theirs alone."""
if self._checking or self.simulate or not self.has_key:
return
+ if notes:
+ # Sent before notes went back to translation's model and server: not theirs any more.
+ if not self.config().notes_apart:
+ return
+ if failure is not None:
+ cl = aicheck.classify(failure, "text")
+ if cl is None or cl[1] == aicheck.SERVER_ERROR:
+ return
+ now = aicheck.State(aicheck.FAIL, reason=cl[1], code=cl[2])
+ else:
+ now = aicheck.State(aicheck.OK, seconds)
+ with self._check_lock:
+ old = self.check_result
+ if old.running or (old.notes is not None and old.notes.kind == aicheck.OK and now.kind == aicheck.OK):
+ return
+ r = old.copy()
+ r.notes = now
+ self.check_result = r
+ Log.d("ai: notes from a real request -> %s" % r.summary())
+ self._changed()
+ return
with self._check_lock:
old = self.check_result
if old.running:
@@ -612,6 +722,23 @@ class LingClient:
Log.d("ai %s: %d models, %d hear" % (c.provider.id, len(self.text_catalog), len(self.hear_catalog)))
self._changed()
+ def fetch_notes_catalog(self) -> None:
+ """Notes' own address's text models, for its menu. Quietly empty when it has no `/models`."""
+ c = self.config()
+ n = c.for_notes
+ k = self.notes_key()
+ if not c.notes_apart or n.base is None or n.base == c.base or k is None:
+ return
+ try:
+ res = self.transport.send(n.base + "models", "GET", None, self._headers(k), 20.0)
+ except (OSError, TimeoutError):
+ return
+ if res.status != 200:
+ return
+ self.notes_catalog = catalog(res.body, [], hears=False)
+ Log.d("ai notes: %d models" % len(self.notes_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, patient: bool = False,
reply: list | None = None, json_fallback: bool = True) -> str:
@@ -622,13 +749,19 @@ class LingClient:
(_rate_limited), and a retry keeps its place in the queue, so lines stay in order. Audio goes
to the hear model's address (`hear_url`). `reply`, when given, gets the whole JSON reply. A JSON
request refused with 400 is asked again without JSON mode unless `json_fallback` is off (the
- check asks again itself)."""
- k = self.current_key()
+ check asks again itself). Notes (实时纪要, 说话人) go to their own model, server and key when
+ the custom service sets them (`AIConfig.for_notes`)."""
+ c = self.config()
+ notes_side = priority == NOTES and audio is None and c.notes_apart
+ if notes_side:
+ c = c.for_notes
+ k = self.notes_key() if notes_side else self.current_key()
if k is None:
raise LingError(LingError.NO_KEY)
- if self.key_state == INVALID:
+ # A refused notes key stops only notes; translation's stops everything but those.
+ if (self.check_result.notes is not None and self.check_result.notes.reason == aicheck.INVALID_KEY) if notes_side \
+ else self.key_state == INVALID:
raise LingError(LingError.INVALID_KEY)
- c = self.config()
base = c.base if audio is None else c.hear_url
if base is None:
raise LingError(LingError.NO_KEY)
@@ -646,11 +779,11 @@ class LingClient:
ticket = None
while True:
# One that wouldn't retry fails at once while the service is cooling down: its caller falls back.
- ticket = self._acquire(priority, c.provider.spacing, ticket, fail_if_paused=not waits)
+ ticket = self._acquire(priority, c.provider.spacing, ticket, fail_if_paused=not waits, base=c.base)
started = time.monotonic()
try:
try:
- root = self._post_chat(base, body, k, timeout)
+ root = self._post_chat(base, body, k, timeout, notes=notes_side)
except LingError as e:
if not (json_fallback and e.kind == LingError.HTTP and e.status == 400 and "response_format" in body):
raise
@@ -658,7 +791,7 @@ class LingClient:
# while the model answers JSON anyway: the prompt asks for it, the parsers find it.
Log.d("ling: %s JSON mode refused (400), asking again without it" % name)
del body["response_format"]
- root = self._post_chat(base, body, k, timeout)
+ root = self._post_chat(base, body, k, timeout, notes=notes_side)
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
@@ -676,15 +809,15 @@ class LingClient:
if self.rate_limited_at is not None:
self.rate_limited_at = None
self._changed()
- self.observe(None, time.monotonic() - started, audio is not None)
+ self.observe(None, time.monotonic() - started, audio is not None, notes=notes_side)
if reply is not None:
reply.append(root)
return trimmed
except LingError as e:
- self.observe(e, audio=audio is not None)
+ self.observe(e, audio=audio is not None, notes=notes_side)
if e.kind != LingError.RATE_LIMITED:
raise
- wait = self._rate_limited(waits[min(attempt, len(waits)) - 1] if waits else 1.0, e.retry_after)
+ wait = self._rate_limited(waits[min(attempt, len(waits)) - 1] if waits else 1.0, e.retry_after, base=c.base)
if attempt > len(waits) or wait is None:
self.rate_limited_at = time.time()
self._changed()
@@ -772,23 +905,25 @@ class LingClient:
h["Authorization"] = "Bearer " + k
return h
- def _post_chat(self, base: str, body: dict, k: str, timeout: float) -> dict:
+ def _post_chat(self, base: str, body: dict, k: str, timeout: float, notes: bool = False) -> dict:
"""A chat completion. A custom server that refuses `chat_template_kwargs` (400 or 422) is
asked again without it, and once that works it isn't sent there again until settings change
(Ling.swift › postChat). A 400 the plain request gets too is the model's or the audio's, not
the field's: that one is raised and nothing is remembered."""
try:
- return self._post(base + "chat/completions", jsonfmt.write(body, pretty=False), k, timeout)
+ return self._post(base + "chat/completions", jsonfmt.write(body, pretty=False), k, timeout, notes)
except LingError as e:
if not (e.kind == LingError.HTTP and e.status in (400, 422) and "chat_template_kwargs" in body):
raise
plain = {kk: v for kk, v in body.items() if kk != "chat_template_kwargs"}
- root = self._post(base + "chat/completions", jsonfmt.write(plain, pretty=False), k, timeout)
+ root = self._post(base + "chat/completions", jsonfmt.write(plain, pretty=False), k, timeout, notes)
Log.d("ai custom: chat_template_kwargs refused (HTTP %d), sent without it from now on" % e.status)
self._plain_bases.add(base)
return root
- def _post(self, url: str, payload: str, k: str, timeout: float) -> dict:
+ def _post(self, url: str, payload: str, k: str, timeout: float, notes: bool = False) -> dict:
+ """`notes`: it went with the notes' own key or to their server, so a refused key is theirs,
+ not translation's."""
try:
res = self.transport.send(url, "POST", payload, self._headers(k), timeout)
except TimeoutError:
@@ -797,7 +932,7 @@ class LingClient:
Log.d("ling: network error %s" % type(e).__name__)
raise LingError(LingError.NETWORK) from None
if res.status in (401, 403):
- if self.key_state != INVALID:
+ if not notes and self.key_state != INVALID:
self.key_state = INVALID
self._changed()
raise LingError(LingError.INVALID_KEY)
@@ -812,46 +947,60 @@ class LingClient:
return root
# Start gate: request starts ≥ `spacing` apart, the most urgent waiting one first, none while
- # the service is cooling down after a 429.
+ # the server is cooling down after a 429. One per server (by host).
+
+ def _server(self, base: str | None = None) -> _Gate:
+ """The gate of the server at `base` (None: the service's own). Called with `_gate` held."""
+ if base is None:
+ c = self.config()
+ base = c.base or c.provider.base
+ host = urllib.parse.urlsplit(base or "").hostname or ""
+ g = self._gates.get(host)
+ if g is None:
+ g = self._gates[host] = _Gate()
+ return g
def _acquire(self, priority: int, spacing: float = 0.6, ticket: int | None = None,
- fail_if_paused: bool = False) -> int:
- """Waits for this request's turn to start. `ticket` is a retry's first one, which keeps its
- place ahead of requests queued after it. Returns the ticket."""
+ fail_if_paused: bool = False, base: str | None = None) -> int:
+ """Waits for this request's turn to start at the server at `base` (None: the service's).
+ `ticket` is a retry's first one, which keeps its place ahead of requests queued after it.
+ Returns the ticket."""
spacing = LingClient.spacing if LingClient.spacing is not None else spacing
with self._gate:
- if fail_if_paused and self._paused_until > self.clock.now():
+ g = self._server(base)
+ if fail_if_paused and g.paused_until > self.clock.now():
raise LingError(LingError.RATE_LIMITED)
if ticket is None:
self._seq += 1
ticket = self._seq
me = (priority, ticket)
- self._waiting.append(me)
+ g.waiting.append(me)
try:
while True:
- head = min(self._waiting)
+ head = min(g.waiting)
now = self.clock.now()
- wait = max(spacing - (now - self._last_start), self._paused_until - now)
+ wait = max(spacing - (now - g.last_start), g.paused_until - now)
if head == me and wait <= 0:
- self._waiting.remove(me)
- self._last_start = now
+ g.waiting.remove(me)
+ g.last_start = now
self._gate.notify_all()
return ticket
self.clock.wait(self._gate, wait if head == me else None)
except BaseException:
- if me in self._waiting:
- self._waiting.remove(me)
+ if me in g.waiting:
+ g.waiting.remove(me)
self._gate.notify_all()
raise
- def _rate_limited(self, backoff: float, retry_after: float | None) -> float | None:
+ def _rate_limited(self, backoff: float, retry_after: float | None, base: str | None = None) -> float | None:
"""After a 429: no request starts for `backoff` seconds, or as long as the service asked
(Retry-After; Ling sends none), plus a little jitter. The queue waits at the gate instead of
each request spending its retries on the same limit. None when the service asks for longer
than MAX_PAUSE: that is an outage, not a busy moment (the gate still holds for MAX_PAUSE)."""
wait = max(backoff, retry_after or 0.0) + random.random() * 0.5
with self._gate:
- self._paused_until = max(self._paused_until, self.clock.now() + min(wait, MAX_PAUSE))
+ g = self._server(base)
+ g.paused_until = max(g.paused_until, self.clock.now() + min(wait, MAX_PAUSE))
self._gate.notify_all()
return wait if wait <= MAX_PAUSE else None
diff --git a/linux/cicada/core/providers.py b/linux/cicada/core/providers.py
index 9501d7e..8df7099 100644
--- a/linux/cicada/core/providers.py
+++ b/linux/cicada/core/providers.py
@@ -13,7 +13,7 @@ from __future__ import annotations
import base64
import re
import urllib.parse
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from .jsonfmt import arr, obj, string
@@ -172,6 +172,27 @@ class AIConfig:
# audio model often run as separate servers). None: the text address; "" (only from
# config_from): an address typed that isn't valid.
hear_base: str | None = None
+ # A custom service's notes (实时纪要, 说话人): another model, and with 另一个服务 another server
+ # with its own key. None: the same as translation.
+ notes_model: str | None = None
+ notes_base: str | None = None
+ # 另一个服务 is picked: notes use their own key file when there is one.
+ notes_own_service: bool = False
+ # 另一个服务 with an address that can't be used (http to the internet): notes fail the check.
+ notes_bad_address: bool = False
+
+ @property
+ def notes_apart(self) -> bool:
+ """Notes go somewhere translation doesn't: they get their own check, result and start gate."""
+ return self.provider.id == "custom" and (self.notes_model is not None or self.notes_base is not None
+ or self.notes_own_service)
+
+ @property
+ def for_notes(self) -> "AIConfig":
+ """What a notes call is sent with: notes' model at notes' address, the rest as translation."""
+ if not self.notes_apart:
+ return self
+ return replace(self, text_model=self.notes_model or self.text_model, base=self.notes_base or self.base)
@property
def hear_url(self) -> str | None:
@@ -240,8 +261,19 @@ def config_from(settings) -> AIConfig:
# The hear model's own address (empty: the text model's); "" marks one typed that isn't valid.
typed = (getattr(settings, "aiCustomHearBase", "") or "").strip()
hear_base = (custom_base(typed) or "") if typed else None
- 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, hear_base=hear_base)
+ # Notes (Settings.swift › aiConfig): their model (empty or the translation one: none of their
+ # own), and with 另一个服务 their address (empty or the same: translation's). Off keeps the
+ # address typed, so switching back and forth loses nothing.
+ text = (models.get("custom") or "").strip()
+ notes_model = (models.get("custom.notes") or "").strip()
+ own = bool(getattr(settings, "aiCustomNotesOwn", False))
+ notes_typed = (getattr(settings, "aiCustomNotesBase", "") or "").strip() if own else ""
+ notes_base = custom_base(notes_typed) if notes_typed else None
+ return AIConfig(p, base, text, (hears.get("custom") or "").strip(),
+ voice or None, voice_base if voice else None, name or None, hear_base=hear_base,
+ notes_model=None if not notes_model or notes_model == text else notes_model,
+ notes_base=None if notes_base == base else notes_base, notes_own_service=own,
+ notes_bad_address=bool(notes_typed) and notes_base is 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)
@@ -277,10 +309,22 @@ def catalog(data: str | dict, recommended: list, hears: bool) -> list:
return list(recommended) + rest
+def hosts(c: AIConfig, notes: bool = True) -> list:
+ """Every host a custom service's uses go to, in order, once each: text, notes (when at their own
+ address; `notes` False leaves them out), hear, and the voice if set up (AISettings.swift ›
+ customHosts, keyHosts)."""
+ urls = [c.base] + ([c.for_notes.base] if notes and c.notes_apart else []) + [c.hear_url] \
+ + ([c.voice_base] if c.has_voices else [])
+ out = []
+ for u in urls:
+ h = urllib.parse.urlsplit(u).hostname if u else None
+ if h and h not in out:
+ out.append(h)
+ return out
+
+
def only_host(c: AIConfig) -> str | None:
- """Where a custom service's audio and text go, when every use shares one host (text, hear, and
- the voice if set up); None when they differ (AISettings.swift › customHosts)."""
- urls = [c.base, c.hear_url] + ([c.voice_base] if c.has_voices else [])
- hosts = {urllib.parse.urlsplit(u).hostname for u in urls if u}
- hosts.discard(None)
- return hosts.pop() if len(hosts) == 1 else None
+ """Where a custom service's audio and text go, when every use shares one host; None when they
+ differ."""
+ h = hosts(c)
+ return h[0] if len(h) == 1 else None
diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.py
index 7089319..21dbbef 100644
--- a/linux/cicada/core/settings.py
+++ b/linux/cicada/core/settings.py
@@ -26,6 +26,11 @@ class AppSettings:
# The custom service's hear model at an address of its own (the port's, like the Mac's
# aiCustomHearBase); empty: the same address as the text model.
"aiCustomHearBase": "",
+ # The custom service's notes (the Mac's keys): 另一个服务, at its own address (empty: the same
+ # one) with its own key in the `custom-notes` key file. Off keeps the address. The notes
+ # model is aiModels["custom.notes"] (empty: the translation model).
+ "aiCustomNotesOwn": False,
+ "aiCustomNotesBase": "",
# 语音和文字只发给你的服务 (the Mac's aiCustomOnly): with the custom service, Google Translate is
# never asked. Kept when another service is picked, but only acts on the custom one.
"aiCustomOnly": False,
diff --git a/linux/tests/test_aicheck.py b/linux/tests/test_aicheck.py
index f9b0d90..39d68bf 100644
--- a/linux/tests/test_aicheck.py
+++ b/linux/tests/test_aicheck.py
@@ -235,10 +235,11 @@ class Checks(Base):
self.assertEqual(("text", "noModel", 404), ling.check_result.failure)
self.assertEqual(["ok", "ok", "fail", "skipped"], kinds(ling.check_result))
self.assertTrue(ling.usable)
- # One the service answers but no longer lists.
+ # One the service answers but doesn't list (an alias, a name typed by hand): a real request
+ # just went through, so it exists whatever the list says (Ling.swift › check, 2026-11).
ling, _ = self.client(service(), aiModels={"zenmux": "old/model"})
- ling.check()
- self.assertEqual(("text", "noModel", None), ling.check_result.failure)
+ self.assertEqual(OK, ling.check())
+ self.assertIsNone(ling.check_result.failure)
def test_a_deaf_hear_model(self):
ling, _ = self.client(service(hear=400), aiHearModels={"zenmux": "x/text-only"})
diff --git a/linux/tests/test_custom.py b/linux/tests/test_custom.py
index bf14e95..7f24e60 100644
--- a/linux/tests/test_custom.py
+++ b/linux/tests/test_custom.py
@@ -15,7 +15,8 @@ sys.path.insert(0, os.path.dirname(HERE))
from test_providers import Base, Fake, reply # noqa: E402
from cicada.core import aicheck, jsonfmt, providers # noqa: E402
-from cicada.core.ling import OK, TRANSLATE, LingError, Response, silence_wav # noqa: E402
+from cicada.core.ling import INVALID, NOTES, OK, TRANSLATE, LingError, Response, silence_wav # noqa: E402
+from cicada.core.support import Paths # noqa: E402
from cicada.core.settings import AppSettings # noqa: E402
@@ -294,6 +295,180 @@ class HearAddress(Base):
self.assertFalse(any("input_audio" in b for _u, b in fake.sent))
+class AuthFake(Fake):
+ """Fake, also keeping the key each request carried (`auth`, in order)."""
+
+ def __init__(self, respond):
+ super().__init__(respond)
+ self.auth = []
+
+ def send(self, url, method, body, headers, timeout):
+ self.auth.append(headers.get("Authorization"))
+ return super().send(url, method, body, headers, timeout)
+
+
+MAIN, NOTES_AT = "https://main.example/v1/", "https://notes.example/v1/"
+
+
+class NotesApart(Base):
+ """Notes on their own model, or another server with its own key (LingTests.swift › Notes apart)."""
+
+ def notes_client(self, fake, own: bool, **kw):
+ kw.setdefault("aiCustomNotesBase", NOTES_AT if own else "")
+ s = dict(aiCustomBase=MAIN, aiModels={"custom": "mt", "custom.notes": "big"}, aiHearModels={"custom": "omni"},
+ aiCustomNotesOwn=own, **kw)
+ return self.client(fake, "custom", key="sk-main-1111111111", **s)
+
+ def test_notes_go_to_their_model_and_server_translation_stays(self):
+ fake = AuthFake(lambda u, b: answer("{}"))
+ ling, _ = self.notes_client(fake, own=True)
+ ling.notes_key_file.save("sk-notes-222222222")
+ ling.chat("x", "Notes.", NOTES, json=True)
+ ling.chat("y", "Translate.", TRANSLATE)
+ self.assertEqual(["big", "mt"], [jsonfmt.parse_object(b)["model"] for _u, b in fake.sent])
+ self.assertEqual([NOTES_AT + "chat/completions", MAIN + "chat/completions"], [u for u, _b in fake.sent])
+ self.assertEqual(["Bearer sk-notes-222222222", "Bearer sk-main-1111111111"], fake.auth)
+ # Its own key file, named as on the Mac, 0600.
+ path = os.path.join(Paths.config(), "ai-key-custom-notes")
+ self.assertEqual(path, ling.notes_key_file.path)
+ self.assertEqual(0o600, os.stat(path).st_mode & 0o777)
+ # Hearing is never notes: it stays at the hear address with the translation key.
+ ling.chat("z", "Hear.", NOTES, model="omni", audio=silence_wav())
+ self.assertEqual(MAIN + "chat/completions", fake.sent[-1][0])
+ self.assertEqual("Bearer sk-main-1111111111", fake.auth[-1])
+
+ def test_notes_without_their_own_key_use_the_translation_key(self):
+ fake = AuthFake(lambda u, b: answer("{}"))
+ ling, _ = self.notes_client(fake, own=True)
+ self.assertFalse(ling.notes_has_own_key)
+ ling.chat("x", "Notes.", NOTES)
+ self.assertEqual("Bearer sk-main-1111111111", fake.auth[-1])
+ self.assertTrue(fake.sent[-1][0].startswith(NOTES_AT))
+ # The same service, another model: same address and key, even with a notes key on file.
+ same, _ = self.notes_client(fake, own=False)
+ same.notes_key_file.save("sk-notes-222222222")
+ self.assertFalse(same.notes_has_own_key)
+ same.chat("x", "Notes.", NOTES)
+ self.assertTrue(fake.sent[-1][0].startswith(MAIN))
+ self.assertEqual("Bearer sk-main-1111111111", fake.auth[-1])
+ self.assertEqual("big", jsonfmt.parse_object(fake.sent[-1][1])["model"])
+
+ def test_a_refused_notes_key_leaves_translation_working(self):
+ fake = AuthFake(lambda u, b: Response(401, "{}") if '"big"' in b else answer("好"))
+ ling, _ = self.notes_client(fake, own=True)
+ with self.assertRaises(LingError) as e:
+ ling.chat("x", "Notes.", NOTES)
+ self.assertEqual(LingError.INVALID_KEY, e.exception.kind)
+ self.assertNotEqual(INVALID, ling.key_state)
+ self.assertEqual("好", ling.chat("y", "Translate.", TRANSLATE))
+ # The real request told the notes, and only them: the next notes call doesn't go out.
+ r = ling.check_result
+ self.assertEqual(aicheck.INVALID_KEY, r.notes.reason)
+ self.assertIsNone(r.failure)
+ sent = len(fake.sent)
+ with self.assertRaises(LingError):
+ ling.chat("x", "Notes.", NOTES)
+ self.assertEqual(sent, len(fake.sent))
+ # A refused translation key still stops translation.
+ fake.respond = lambda u, b: Response(401, "{}")
+ with self.assertRaises(LingError):
+ ling.chat("y", "Translate.", TRANSLATE)
+ self.assertEqual(INVALID, ling.key_state)
+
+ def test_notes_fall_back_to_translation_until_set(self):
+ plain = providers.AIConfig(providers.CUSTOM, MAIN, "mt", "h")
+ self.assertFalse(plain.notes_apart)
+ self.assertEqual(plain, plain.for_notes)
+ model = providers.AIConfig(providers.CUSTOM, MAIN, "mt", "h", notes_model="big")
+ self.assertTrue(model.notes_apart)
+ self.assertEqual(("big", MAIN), (model.for_notes.text_model, model.for_notes.base))
+ # Only the custom service splits.
+ ling = providers.AIConfig(providers.LING, providers.LING.base, "x", "h", notes_model="big")
+ self.assertFalse(ling.notes_apart)
+ self.assertEqual("x", ling.for_notes.text_model)
+ # From the settings: the translation model or address chosen again is no split.
+ c = AppSettings(aiProvider="custom", aiCustomBase=MAIN, aiModels={"custom": "mt", "custom.notes": " mt "}).ai_config()
+ self.assertFalse(c.notes_apart)
+ c = AppSettings(aiProvider="custom", aiCustomBase=MAIN, aiModels={"custom": "mt"}, aiCustomNotesOwn=True,
+ aiCustomNotesBase="main.example/v1").ai_config()
+ self.assertIsNone(c.notes_base)
+ self.assertTrue(c.notes_apart) # 另一个服务 alone: its own key may differ
+ # 同一个服务 keeps the address typed, unused.
+ s = AppSettings(aiProvider="custom", aiCustomBase=MAIN, aiModels={"custom": "mt"}, aiCustomNotesOwn=False,
+ aiCustomNotesBase=NOTES_AT)
+ self.assertFalse(s.ai_config().notes_apart)
+ self.assertEqual(NOTES_AT, s.aiCustomNotesBase)
+ s.aiCustomNotesOwn = True
+ self.assertEqual(NOTES_AT, s.ai_config().for_notes.base)
+ # http to the internet can't be used.
+ s.aiCustomNotesBase = "http://notes.example/v1"
+ c = s.ai_config()
+ self.assertTrue(c.notes_bad_address)
+ self.assertEqual(MAIN, c.for_notes.base)
+
+ def test_settings_keep_notes_across_a_restart(self):
+ s = AppSettings(aiProvider="custom", aiCustomNotesOwn=True, aiCustomNotesBase=NOTES_AT,
+ aiModels={"custom": "mt", "custom.notes": "big"})
+ s.save()
+ back = AppSettings.load()
+ self.assertTrue(back.aiCustomNotesOwn)
+ self.assertEqual(NOTES_AT, back.aiCustomNotesBase)
+ self.assertEqual("big", back.aiModels["custom.notes"])
+
+ def test_a_429_at_the_notes_server_does_not_hold_translation(self):
+ ling, _ = self.notes_client(AuthFake(lambda u, b: answer()), own=True)
+ ling._rate_limited(10.0, None, base=NOTES_AT)
+ # Translation (no retries: it fails at once while its server cools down) goes on…
+ self.assertEqual("周五发布。", ling.chat("y", "Translate.", TRANSLATE))
+ # …while the notes' server waits.
+ with self.assertRaises(LingError) as e:
+ ling._acquire(TRANSLATE, fail_if_paused=True, base=NOTES_AT)
+ self.assertEqual(LingError.RATE_LIMITED, e.exception.kind)
+
+ def test_the_check_tests_notes_on_their_side(self):
+ listed = {"data": [{"id": "big"}, {"id": "bigger"}]}
+
+ def respond(url, body):
+ if url.endswith("/models"):
+ return Response(200, jsonfmt.write(listed)) if url.startswith(NOTES_AT) else Response(404, "")
+ if url.startswith(NOTES_AT):
+ return Response(401, "{}")
+ return answer("NONE" if "input_audio" in body else "周五发布。")
+ fake = AuthFake(respond)
+ ling, _ = self.notes_client(fake, own=True)
+ self.assertEqual(OK, ling.check())
+ r = ling.check_result
+ self.assertIsNone(r.failure)
+ self.assertTrue(r.passed)
+ self.assertEqual(aicheck.FAIL, r.notes.kind)
+ self.assertTrue(r.notes_failed)
+ self.assertIn("notes=fail(invalidKey)", r.summary())
+ # Translation's JSON probe isn't asked: notes are tested where they go.
+ main_json = [b for u, b in fake.sent if u.startswith(MAIN) and "json_object" in b]
+ self.assertEqual([], main_json)
+ self.assertIn("不认上面的 key", r.notes_line("notes.example", "big", shared_key=True))
+ self.assertIn("key 无效", r.notes_line("notes.example", "big", shared_key=False))
+ self.assertEqual(["big", "bigger"], ling.notes_catalog)
+ # Their own key, which works.
+ fake.respond = lambda u, b: (Response(404, "") if u.endswith("/models") else
+ answer('{"ok": true}' if "JSON object" in b else "周五发布。"))
+ ling.notes_key_file.save("sk-notes-222222222")
+ ling.key_changed()
+ self.assertEqual(OK, ling.check())
+ self.assertEqual(aicheck.OK, ling.check_result.notes.kind)
+ self.assertIsNone(ling.check_result.notes_line("notes.example", "big", True))
+ notes_req = [a for (u, _b), a in zip(fake.sent, fake.auth) if u.startswith(NOTES_AT) and "chat" in u]
+ self.assertEqual(["Bearer sk-notes-222222222"], notes_req[-1:])
+
+ def test_a_bad_notes_address_fails_only_notes(self):
+ fake = AuthFake(lambda u, b: Response(404, "") if u.endswith("/models") else answer())
+ ling, _ = self.notes_client(fake, own=True, aiCustomNotesBase="http://notes.example/v1")
+ self.assertEqual(OK, ling.check())
+ self.assertEqual(aicheck.BAD_ADDRESS, ling.check_result.notes.reason)
+ self.assertIn("局域网", ling.check_result.notes_line("x", "big", True))
+ self.assertFalse(any("notes.example" in u for u, _b in fake.sent))
+
+
class StubLing:
"""The service, for the translator alone: answers each sentence, or fails."""