知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
refactor(linux): remove code comments
wqugurua3687c2b0132
diff --git a/linux/bin/cicada b/linux/bin/cicadaindex c48d11d..543dfd5 100755--- a/linux/bin/cicada+++ b/linux/bin/cicada@@ -1,5 +1,3 @@#!/bin/sh-# Starts Cicada from this tree (an install under ~/.local/lib/cicada, or a checkout's linux/).-# --dev: the dev build (own app id, records in ~/.local/share/cicada-dev, the control socket).here="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"PYTHONPATH="$here${PYTHONPATH:+:$PYTHONPATH}" exec python3 -m cicada.app "$@"diff --git a/linux/cicada/__init__.py b/linux/cicada/__init__.pyindex 1ba365d..ea66c64 100644--- a/linux/cicada/__init__.py+++ b/linux/cicada/__init__.py@@ -1,11 +1,7 @@-"""Cicada (知了) for Linux. `core` is the UI-free engine (stdlib only, runs and is tested on the-Mac too); `app` is the GTK desktop app."""-from pathlib import Path as _Pathdef _version() -> str:- # One version for every platform: VERSION at the repo root, copied next to cicada/ in a build.here = _Path(__file__).resolve().parent.parentfor p in (here / "VERSION", here.parent / "VERSION"):try:diff --git a/linux/cicada/app/__init__.py b/linux/cicada/app/__init__.pyindex 020a44e..2ae2839 100644--- a/linux/cicada/app/__init__.py+++ b/linux/cicada/app/__init__.py@@ -1,2 +1 @@-"""The GTK 3 desktop app: tray (when the desktop has one), notes window / subtitle bar, records,-settings, onboarding. Only system libraries: PyGObject, GTK 3, libpulse (through ctypes)."""+passdiff --git a/linux/cicada/app/aicheck_view.py b/linux/cicada/app/aicheck_view.pyindex adeb32b..51fdb18 100644--- a/linux/cicada/app/aicheck_view.py+++ b/linux/cicada/app/aicheck_view.py@@ -1,6 +1,3 @@-"""The AI service's check, step by step (AICheckView.swift): the settings and the onboarding show the-same list. Every step that ran shows its result; the one that failed says why in one line and-offers the one thing that fixes it. Also the words the tray, the checklist and 开始听 use."""from __future__ import annotationsfrom gi.repository import Gtk@@ -17,7 +14,6 @@ ICONS = {aicheck.OK: ("object-select-symbolic", "ok"), aicheck.FAIL: ("window-cldef recommended(app, kind: str) -> str | None:- """The service's first recommended text or hear model, when it isn't the one in use."""c = app.ling.config()models = c.provider.text_models if kind == "text" else c.provider.hear_modelscurrent = c.text_model if kind == "text" else c.hear_model@@ -30,7 +26,6 @@ def top_up_url(provider) -> str:def actions(app, change_key, recheck_in_step: bool = True) -> list:- """(title, run) for the failed step: one primary fix, at most one other."""from .settings_window import open_uriling = app.lingf = ling.check_result.failure@@ -40,7 +35,6 @@ def actions(app, change_key, recheck_in_step: bool = True) -> list:reason = f[1]recheck = [(L("重新检查"), app.recheck)] if recheck_in_step else []if reason == aicheck.UNREACHABLE:- # A proxy has nothing to do with a server on this computer or the local network.if is_nearby(ling.service_host):return recheckreturn [(L("怎么设置代理"), lambda: open_uri(aicheck.help_url(strings.language)))] + recheck@@ -63,8 +57,6 @@ def actions(app, change_key, recheck_in_step: bool = True) -> list:def steps_widget(app, change_key, recheck_in_step: bool = True, width_chars: int = 46) -> Gtk.Widget:- """The step list: a disc, the step's name and seconds; under the failed one, why, the proxy hint- and its buttons (the first dark)."""ling = app.lingr = ling.check_resultc = ling.config()@@ -117,13 +109,10 @@ def steps_widget(app, change_key, recheck_in_step: bool = True, width_chars: intdef show_steps(r) -> bool:- """The list shows while something is wrong or being checked; all passed folds into one line."""return r.running or r.failure is not None or r.busy or (r.at is not None and not r.passed)def passed_line(app) -> str | None:- """All passed, in one line: "文字 1.8 秒 · 听 2.1 秒", or "12 分钟前开会时用过" when the newest- evidence came from a meeting."""r = app.ling.check_resultif not r.passed or r.busy:return None@@ -139,8 +128,6 @@ def passed_line(app) -> str | None:def strip_words(app):- """(title, detail) for the tray's first item and the checklist: only failures the user must fix- (AIServiceStrip.swift). On Linux the service hears too, so nothing goes on without it."""ling = app.lingr = ling.check_resultif not ling.has_key or not r.needs_user:@@ -157,8 +144,6 @@ def strip_words(app):def blocking(app) -> str | None:- """What stops Cicada until the user changes something (AIServiceStrip.blocking): the tray's dot- and the notification. Not the network, a busy service or one that errs."""from ..core import problemling = app.lingif not ling.has_key:@@ -168,15 +153,11 @@ def blocking(app) -> str | None:def blocking_detail(app) -> str:- """The line under blocking(): why, unless that only says the title again (余额不足, 听不了声音,- 找不到模型), then where it's fixed."""why = app.ling.message() or ""return why if why and why != blocking(app) else L("在 设置 › AI 服务 里换一个")def key_hint(app, key: str):- """A pasted key that belongs elsewhere: (what it is, the service it fits or None), else None.- A management key can't call models; another service's key goes there with one click."""owner = aicheck.owner(key)if owner is None:return Nonediff --git a/linux/cicada/app/capture.py b/linux/cicada/app/capture.pyindex a6bd09f..0b88688 100644--- a/linux/cicada/app/capture.py+++ b/linux/cicada/app/capture.py@@ -1,12 +1,3 @@-"""System audio on Linux: the monitor of the default output, read through libpulse-simple (ctypes).-PulseAudio and PipeWire (through pipewire-pulse, Ubuntu's default since 22.10) both serve it, and-reading a monitor needs no permission. Cicada itself plays nothing while it listens, so unlike the-Mac's process tap there is nothing of its own to leave out.--Two things a meeting outlives: the default output changing (headphones plugged in, a Bluetooth-headset connecting; PipeWire moves the stream itself, plain PulseAudio leaves it on the old device,-so it is reopened when the default changes) and the sound server going away for a moment (suspend-and resume, a restart; the stream is reopened for up to 20 s before listening gives up)."""from __future__ import annotationsimport ctypes@@ -23,7 +14,7 @@ from ..core.support import LogPA_SAMPLE_S16LE = 3PA_STREAM_RECORD = 2-CHUNK = RATE // 10 # 100 ms per read, like a capture callback+CHUNK = RATE // 10class _Spec(ctypes.Structure):@@ -57,7 +48,6 @@ def _pulse():class _ServerInfo(ctypes.Structure):- # pa_server_info, as far as default_source_name._fields_ = [("user_name", ctypes.c_char_p), ("host_name", ctypes.c_char_p), ("server_version", ctypes.c_char_p),("server_name", ctypes.c_char_p), ("sample_spec", _Spec), ("default_sink_name", ctypes.c_char_p),("default_source_name", ctypes.c_char_p)]@@ -91,17 +81,14 @@ def _libpulse():def default_sink() -> str | None:- """The sound server's default output, or None when it can't be asked (a few ms, blocking)."""return _server_info().get("sink")def default_source() -> str | None:- """The sound server's default input, or None when it can't be asked."""return _server_info().get("source")def sources_text() -> str:- """`pactl list sources` in English (roommic.parse_sources reads it); empty without pactl."""try:return subprocess.run(["pactl", "list", "sources"], env={**os.environ, "LC_ALL": "C"}, capture_output=True,text=True, timeout=3).stdout@@ -132,11 +119,11 @@ def _server_info() -> dict:while time.monotonic() < deadline:l.pa_mainloop_iterate(loop, 0, None)state = l.pa_context_get_state(ctx)- if state in (5, 6): # FAILED, TERMINATED+ if state in (5, 6):return {}- if state == 4 and op is None: # READY+ if state == 4 and op is None:op = l.pa_context_get_server_info(ctx, got, None)- if op is not None and l.pa_operation_get_state(op) != 0: # no longer RUNNING+ if op is not None and l.pa_operation_get_state(op) != 0:l.pa_operation_unref(op)breaktime.sleep(0.005)@@ -156,9 +143,6 @@ def available() -> bool:class SystemAudio(AudioSource):- """16 kHz mono from "@DEFAULT_MONITOR@" (or a microphone, `device`): the server resamples and- downmixes for us. `name` is what the sound settings and GNOME's privacy menu show."""-def __init__(self, device: str = "@DEFAULT_MONITOR@", name: str | None = None):self.device = deviceself.name = name@@ -175,16 +159,13 @@ class SystemAudio(AudioSource):def _open(self, lib):spec = _Spec(PA_SAMPLE_S16LE, RATE, 1)- # fragsize: hand data over every 100 ms rather than in the server's default 2 s blocks.attr = _Attr(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, CHUNK * 2)err = ctypes.c_int(0)- # The stream's name is what the sound settings and GNOME's privacy menu show.s = lib.pa_simple_new(None, b"Cicada", PA_STREAM_RECORD, self.device.encode(), (self.name or L("知了 · 系统声音")).encode(),ctypes.byref(spec), None, ctypes.byref(attr), ctypes.byref(err))return s, (None if s else lib.strerror(err.value).decode())def _reopen(self, lib, why: str):- """The server went away: try again for a while (it is back within seconds after resume)."""deadline = time.monotonic() + 20while not self._stop.is_set() and time.monotonic() < deadline:time.sleep(1)@@ -224,7 +205,7 @@ class SystemAudio(AudioSource):sink = default_sink()continuereads += 1- if self.device == "@DEFAULT_MONITOR@" and reads % 30 == 0: # every 3 s: did the default output change?+ if self.device == "@DEFAULT_MONITOR@" and reads % 30 == 0:now = default_sink()if now and sink and now != sink:Log.d("tap: default output changed, reopening")diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.pyindex d4df08d..9f1287e 100644--- a/linux/cicada/app/debug.py+++ b/linux/cicada/app/debug.py@@ -1,39 +1,3 @@-"""The dev build's control socket ($XDG_RUNTIME_DIR/cicada-dev.sock, this user only), the Linux-counterpart of tools/lsctl and the Windows named pipe; scripts/cicadactl talks to it. One command-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|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- notes-tab notes|transcript | notes-search <text> | notes-wide on|off | onboarding-step <n> | settings-scroll <0-1>- records-search <text> (typed into the records window's Ctrl+F search) | records-search-step 1|-1 (Enter / the arrows):- how many meetings it finds, the shown one, its matches and the line being looked at- settings-models on|off (unfold 自己选模型)- ai-check-sim <reason|lowBalance|off> (every check ends this way: screenshots of each state) | ai-check (check now)- ask settings|fix|close (answer the 开始听 dialog a failed check put up) | settings-ai (设置 at AI 服务) | tray-menu- pill (the records window capsule's widget sizes)- listen-source system|room|both (听哪里) | room-mic [<source>|auto] | lines [<record id>] (each line's via)- online both|no (answer 线上也有人?) | room-mic-force <source>|"" (a null sink's monitor as the room mic)- hide notes | problem-wait <seconds>|off (how long unreachable lasts before its notification; off: 2 min)- codecs (AAC encoder / decoders here) | play [<seconds>] | pause | rate (next speed) | playstate (the shown record's- recording: state, time, length, rate, the highlighted line, following, the 回到正在播放 capsule, the scroll) |- follow (press 回到正在播放) | play-line <index> (click a line) | line-rect <index>|pill (on the screen) |- settings-general (设置 at 通用)- share <record id>[,full][,pw] | unshare <record id> | share-last (how the last ended) | shareSheet <record id>|""- share-ui scope notes|full | days 7|30|365 | names|pw|summary on|off | options (更改) | go | strip | back | confirm- | copy all|link|password | revoke | close | state- export-folder <path>|off|on (存到文件夹: choose a folder as 存到这里 does, and its check) |- export-state (folder, problem, index, the records not written yet) | export-all (也存一份) | export-retry |- export-choose (open 存到哪里, as 更改… does; answer it with the dialog itself)- voice <lang> | voice <lang>=<id> (the voice a language uses: "voice en=clone", "voice zh=灵小锋")- voice-clone <wav>|off|state (我自己的声音 from a 16 kHz WAV: Ming hears it, the Mac's checks, then kept; state- says the last result and the files' modes) | voice-preview [<lang>] (试听 in that language: what played)- voice-dialog open|feed <wav>|finish|play original|clone|save|close|state (the record sheet, a WAV as the mic)"""from __future__ import annotationsimport os@@ -80,7 +44,7 @@ def _serve(app, server) -> None:breakdata += chunkreply = _on_main(app, data.decode().strip())- except Exception as e: # noqa: BLE001 - report, don't kill the server+ except Exception as e: # noqa: BLE001reply = {"ok": False, "error": "%s: %s" % (type(e).__name__, e)}conn.sendall((jsonfmt.write(reply, pretty=False) + "\n").encode())@@ -139,8 +103,6 @@ def updates_notified():def _export(app, cmd: str, arg: str) -> dict:- """存到文件夹. Waits for the exporter's worker (it never waits for the main loop), so the reply- says what happened."""ex = app.folder_exportif cmd == "export-folder":if arg == "off":@@ -200,7 +162,6 @@ def command(app, line: str) -> dict:"endTimes": list(app.end_times) if app.end_times else None,"inCall": dict(app.end_watch.in_call) if app.end_watch else None}if cmd == "start":- # Later, not here: 开始听 may ask first (a deaf hear model), and its dialog runs its own loop.if not listen.listening:GLib.idle_add(lambda: app.toggle_listening() and False)return {"ok": True}@@ -230,41 +191,40 @@ def command(app, line: str) -> dict:d.response({"settings": Gtk.ResponseType.CANCEL, "fix": Gtk.ResponseType.ACCEPT}.get(arg, Gtk.ResponseType.CLOSE))return {"ok": True}if cmd == "tray-menu":- # The top-bar menu's items (opening it takes a real click on the top bar).if app.tray is None:return {"ok": False, "error": "no tray"}return {"ok": True, "items": [i.get_label() for i in app.tray.menu.get_children() if hasattr(i, "get_label")]}if cmd == "settings-ai":app.show_settings(ai=True)return {"ok": True}- if cmd in ("mic", "listen-source"): # 打开麦克风 (on|off); listen-source both|room|system, the old names+ if cmd in ("mic", "listen-source"):app.set_mic(arg in ("on", "both", "room"))return {"ok": True, "mic": app.mic_on, "source": listen.source_kind}- if cmd == "room-echo-sim": # pretend the speakers do (on) or don't (off) reach the room mic; real+ if cmd == "room-echo-sim":listen.echo_gate.forced = None if arg in ("", "real") else arg != "off"return {"ok": True, "echo": listen.echo_gate.echo}- if cmd == "room-echo": # the sound server's echo cancellation for the room mic (on|off), next start+ if cmd == "room-echo":app.room_echo_cancel = arg == "on"return {"ok": True}- if cmd == "room-mic-force": # any source as the room mic, e.g. a null sink's monitor ("" = off)+ if cmd == "room-mic-force":app.forced_room_mic = arg or Nonereturn {"ok": True, "forced": app.forced_room_mic}- if cmd == "room-mic": # which microphone 会议室 would use now; with an argument, choose it ("" = 自动)+ if cmd == "room-mic":if arg:app.settings.roomMic = "" if arg == "auto" else argapp.settings.save()return {"ok": True, "roomMic": app.settings.roomMic, "picked": app.room_mic()}- if cmd == "lines": # the live (or given) meeting's lines: where each was heard+ if cmd == "lines":s = app.store.get(arg or listen.session_id or "")return {"ok": True, "room": s.room if s else None,"lines": [[l.id, l.speaker, l.via, l.src[:50]] for l in s.lines] if s else []}if cmd == "stop":app.stop_listening()return {"ok": True}- if cmd == "updatecheck": # the Mac's updateCheck: check the feed now (CICADA_UPDATE_FEED in a dev build)+ if cmd == "updatecheck":app.updates.check_now()return {"ok": True}- if cmd == "updateinstall": # the Mac's updateInstall: what 安装并重新打开 does+ if cmd == "updateinstall":app.updates.install()return {"ok": True}if cmd == "updatestate":@@ -283,13 +243,13 @@ def command(app, line: str) -> dict:if cmd == "view":app.set_view(arg)return {"ok": True, "view": app.settings.view}- if cmd == "dock": # dock on|off: 在 Dock 中显示, as its switch sets it+ if cmd == "dock":if arg in ("on", "off"):app.set_show_in_dock(arg == "on")w = app.records_windowreturn {"ok": True, "on": app.settings.showInDock, "records": _window(w),"parked": w.parked if w is not None else None}- if cmd == "close" and arg == "records": # the ✕ of the records window+ if cmd == "close" and arg == "records":if app.records_window is not None:app.records_window.close()return {"ok": True}@@ -309,13 +269,12 @@ def command(app, line: str) -> dict:if cmd == "provider":app.set_ai_provider(arg)return {"ok": True, "ai": _ai(app)}- if cmd == "switch-to-ling": # the 改用 Ling on a status line (says whether it was offered)+ if cmd == "switch-to-ling":offered = app.can_switch_to_ling()Log.d("switchToLing offered=%s" % offered)app.switch_to_ling()return {"ok": True, "offered": offered, "ai": _ai(app)}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","notes": "aiCustomNotesBase"}.get(kind)@@ -341,7 +300,6 @@ def command(app, line: str) -> dict:return {"ok": True, "notes": _window(app.notes_window), "records": _window(app.records_window),"settings": _window(app.settings_window), "onboarding": _window(app.onboarding)}if cmd == "pill":- # The records window's capsule as a tree of allocations (checking it against the Mac's sizes).def tree(w, depth=0):a = w.get_allocation()ctx = w.get_style_context()@@ -353,7 +311,6 @@ def command(app, line: str) -> dict:return outreturn {"ok": True, "tree": tree(app.records_window.listen_box)} if app.records_window else {"ok": False}if cmd == "speakers":- # speakers on|off; speakers <session id>: the voices of a recordif arg in ("on", "off"):app.set_speaker_voices(arg == "on")return {"ok": True, "on": app.settings.speakerVoices}@@ -364,14 +321,13 @@ def command(app, line: str) -> dict:if cmd == "speak":if (arg == "on") != app.speak.active:app.toggle_speaking()- # echoCancelled: this press reads the talk key's echo canceller (else the plain mic, echo drop on)return {"ok": True, "speaking": app.speak.active, "echoCancelled": app.speak.echo_cancelled}if cmd.startswith("voice"):return _voice(app, cmd, arg)if cmd == "codecs":from . import mediareturn {"ok": True, **media.codecs(), "recordAudio": app.settings.recordAudio, "recording": listen.recording}- if cmd == "line-rect": # where transcript row <n> (or the 回到正在播放 capsule: "pill") is on the screen, for real clicks+ if cmd == "line-rect":w = app.records_windowwidget = w.back_pill if arg == "pill" else w._rows[int(arg)][1] if w is not None and int(arg) < len(w._rows) else Noneif widget is None or not widget.get_mapped():@@ -419,7 +375,6 @@ def command(app, line: str) -> dict:app.records_window.fill()return {"ok": True}if cmd == "append":- # A meeting growing line by line, as while listening: `append <id> <n>`.from ..core.models import TranscriptLinesid, n = arg.split()s = app.store.get(sid)@@ -468,7 +423,7 @@ def command(app, line: str) -> dict:w = app.records_windowif cmd == "records-search":w.search.set_text(arg)- w._searched(w.search) # now, not after SearchEntry's typing delay+ w._searched(w.search)else:w.step(int(arg or "1"))found = len(w._visible_sessions()) if w.query.strip() else None@@ -479,7 +434,6 @@ def command(app, line: str) -> dict:% (w.query, found, w.selected, len(w._matches), w._current or "-"))return rif cmd == "rename":- # `rename <id> <title>`; no title is 恢复自动标题.sid, _, title = arg.partition(" ")app.store.rename(sid, title)s = app.store.get(sid)@@ -492,13 +446,11 @@ def command(app, line: str) -> dict:app.folder_export.deleted(arg)return {"ok": True, "exists": app.store.get(arg) is not None, "live": app.store.live}if cmd == "notes-end":- # The notes window's 结束: `ask`, then `keep` (继续记录) or `end` (结束会议).app.show_notes()w = app.notes_window{"ask": w._ask_end, "keep": lambda: w._end_answer(False), "end": lambda: w._end_answer(True)}[arg]()return {"ok": True, "asking": getattr(w, "confirm_end", False), "listening": listen.listening}if cmd == "notes-status":- # How the notes window shows a state the network won't give on demand: `failed`, `invalidKey`…app.notes.status = argapp.changed()return {"ok": True, "status": app.notes.status}@@ -529,8 +481,6 @@ _share_last: dict = {}def _share(app, cmd: str, arg: str) -> dict:- """分享… (the Mac's share / unshare / shareSheet debug commands). The network runs on a thread:- `share` and `unshare` answer at once, `share-last` says how the last one ended."""from ..core import sharefrom . import share_dialogif cmd == "share-last":@@ -576,8 +526,6 @@ def _share(app, cmd: str, arg: str) -> dict:w.selected = argw.fill()return {"ok": True, **share_dialog.open_for(app, s, w).state()}- # share-ui scope notes|full | days 7|30|365 | names|pw|summary on|off | options | go | strip | back | confirm- # | copy all|link|password | revoke | close | stated = app.share_dialogif d is None:return {"ok": False, "error": "no share dialog"}@@ -624,16 +572,6 @@ def _fix_state(app, sid: str) -> dict:def _fixes(app, cmd: str, arg: str) -> dict:- """改正听错的词 (the Mac's fixes / heard / fixState / fixAnswer / fixLater / fixUndo / fixEdit /- fixRevert / vocabAdd / vocabState / resettle):- fixes on|off | ask-names on|off | heard <text>[|<translation>] (a finished sentence as if Ming heard it, in the- meeting being listened to: the record, the fixing request, the notes window all follow) |- fix-state [<id>] | fix-answer yes|no [<id>] | fix-later [<id>] | fix-undo | fix-revert <line> [<id>] |- fix-edit <line>=<text>[|one][|keep0][|@<id>] | vocab-add Morpho=莫拉、莫法[|…] | vocab-remove <word> |- vocab-state | fix-editor <line>=<text> (改这句… open in the records window) |- word-list [import <text>|edit <word>|delete <word>] (设置 › 词表 on screen) |- resettle <line>=<text> (the line heard again as <text>, then translated and fixed- again with the lines after it in view)"""words = arg.split()fx = app.fixes@@ -657,8 +595,6 @@ def _fixes(app, cmd: str, arg: str) -> dict:lang = listen._main.hint or "zh-CN"seg = SimpleNamespace(start=listen.heard_seconds, seconds=2.0, index=0, voiceprint=None,asked=app.settings.resolved_target(lang))- # `heard <text>|<translation>`: a line Ming translated, the usual path (the fixing request- # replaces its translation); without one, the path of a line Ming left untranslated.text, _, dst = arg.partition("|")heard = Heard(lang, text, dst or None)@@ -704,7 +640,6 @@ def _fixes(app, cmd: str, arg: str) -> dict:fx.undo()return {"ok": True}if cmd == "fix-editor":- # 改这句… open on a line of the record shown, with <text> typed in (the VM can't type Chinese).line_id, _, text = arg.partition("=")w = app.records_windowif w is None or not w.get_visible():@@ -712,8 +647,6 @@ def _fixes(app, cmd: str, arg: str) -> dict:w.edit_line(line_id, text or None)return {"ok": True}if cmd == "word-list":- # 设置 › 词表 on screen: `word-list` scrolls to it; `word-list import <text>` opens 粘贴导入 with- # <text> pasted ("|" for new lines); `word-list edit <word>` opens its spelling.app.show_settings()sw = app.settings_windowwl = sw.word_list@@ -723,7 +656,7 @@ def _fixes(app, cmd: str, arg: str) -> dict:wl.dialog_view.get_buffer().set_text(rest.replace("|", "\n"))elif kind == "edit":wl._edit(rest)- elif kind == "heard": # word-list heard <word>=<form>: typed into its 加一个容易听错的词+ elif kind == "heard":word, _, form = rest.partition("=")t = next((t for t in app.vocabulary.snapshot() if t.word == word), None)if t is not None:@@ -767,7 +700,6 @@ def _fixes(app, cmd: str, arg: str) -> dict:def _voice(app, cmd: str, arg: str) -> dict:- """我自己的声音 without a microphone: the network runs on a thread and `state` reads the result."""from ..core import voice_reference as vreffrom ..core import voices as voicemodfrom ..core.audio import PcmAudioSource, RATE, Wav@@ -854,7 +786,7 @@ def _voice(app, cmd: str, arg: str) -> dict:if d is None or d.window is None:return {"ok": False, "error": "no dialog"}r = d.recorder- if what == "feed": # the WAV as the microphone, in real time; the recording stops when it ends+ if what == "feed":d.consent = Truer.start(PcmAudioSource(rest))elif what == "finish":@@ -871,7 +803,6 @@ def _voice(app, cmd: str, arg: str) -> dict: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.lingreturn {"provider": c.provider.id, "base": c.base, "hearBase": c.hear_url, "text": c.text_model, "hear": c.hear_model, "voice": c.voice_model,"state": ling.key_state, "hears": ling.hears, "check": ling.check_result.summary(), "message": ling.message(),diff --git a/linux/cicada/app/folder_export_view.py b/linux/cicada/app/folder_export_view.pyindex 7cb98f3..69a4035 100644--- a/linux/cicada/app/folder_export_view.py+++ b/linux/cicada/app/folder_export_view.py@@ -1,8 +1,3 @@-"""存到文件夹 on screen (the Mac's FolderExportViews.swift): 设置 › 会后存一份's card, the 存到哪里 dialog-and the record's line under its title. The work is core/folder_export.py's.--Linux has no privacy prompt (the .deb isn't sandboxed): a folder Cicada can't write is its-permissions, so the Mac's 去系统设置 and "macOS 可能会问…" have no counterpart here."""from __future__ import annotationsimport os@@ -16,7 +11,6 @@ from . import uidef open_folder(path: str) -> None:- """Never creates it: under a drive that isn't mounted that would be a stray folder."""if not os.path.isdir(path):returntry:@@ -26,7 +20,6 @@ def open_folder(path: str) -> None:def documents_dir() -> str:- """GLib's XDG documents folder; unset, it answers the home folder: then xdg-user-dir, ~/Documents."""d = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS)if d and os.path.normpath(d) != os.path.normpath(os.path.expanduser("~")):return d@@ -34,9 +27,6 @@ def documents_dir() -> str:class FolderExportCard:- """设置 › 会后存一份. Rebuilt from a state key (as WordList is), so the window's show_all never brings- back a row that shouldn't show."""-def __init__(self, app, group, window):self.app = appself.window = window@@ -44,7 +34,6 @@ class FolderExportCard:self._key = Noneself.widget = group(L("会后存一份"), self.box)self.refresh()- # Opened again: a vault opened in Obsidian since may now hold the folder.window.connect("show", lambda *_: (setattr(self, "_vault_for", None), self.refresh()))def refresh(self) -> None:@@ -61,7 +50,7 @@ class FolderExportCard:sw = Gtk.Switch()sw.set_valign(Gtk.Align.CENTER)sw.set_active(ex.on)- sw.connect("notify::active", self._toggled) # after set_active: only the user's clicks+ sw.connect("notify::active", self._toggled)rows = [ui.prow(L("存到文件夹"), sw, L("纪要和文字记录存成 Markdown;文件夹同步到哪,内容就到哪"))]if ex.on and folder:short = fx.short_path(folder)@@ -74,12 +63,12 @@ class FolderExportCard:controls = ui.hbox(8)if key[-1]:tag = ui.text(L("Obsidian 库"), 11, "", wrap=False, ellipsize=False)- ui.pad(tag, 1, 6) # a margin: GTK 3 ignores CSS padding on an EventBox+ ui.pad(tag, 1, 6)t = ui.panel(tag, "foldertag")t.set_valign(Gtk.Align.CENTER)controls.pack_start(t, False, False, 0)opener = ui.soft_button(L("打开"), lambda: open_folder(folder))- opener.set_sensitive(key[-2]) # nothing to open while the folder is gone+ opener.set_sensitive(key[-2])controls.pack_start(opener, False, False, 0)controls.pack_start(ui.soft_button(L("更改…"), self._choose), False, False, 0)sub = ui.text(short, 11, "tertiary", wrap=False)@@ -97,7 +86,6 @@ class FolderExportCard:self.box.show_all()def _vault(self, folder):- """Obsidian 库 or not, read once per folder: refresh runs on every change, meetings included."""if not folder:return Noneif getattr(self, "_vault_for", None) != folder:@@ -108,7 +96,6 @@ class FolderExportCard:waiting = len(ex.index.pending)if ex.problem == fx.DENIED:title = LF("没有权限写入 %@", short)- # Linux asks no one: the folder's own permissions are what to change.detail = LF("%lld 场会议没存上,允许后自动补存", waiting) if waiting else L("改一下这个文件夹的权限,或换个文件夹")elif ex.problem == fx.MISSING:title, detail = LF("找不到 %@", short), L("接上或换个文件夹后自动补存")@@ -124,7 +111,6 @@ class FolderExportCard:elif ex.folder:ex.choose(ex.folder)else:- # Not inside the switch's own signal: the dialog's refresh replaces the switch.GLib.idle_add(lambda: self._choose() and False)def _choose(self) -> None:@@ -132,13 +118,11 @@ class FolderExportCard:if picked:self.app.folder_export.choose(picked)else:- self._key = None # the switch flipped on for a dialog that was cancelled: back off+ self._key = Noneself.refresh()def choose_folder(parent, current: str | None) -> str | None:- """存到哪里: an Obsidian vault first (a new Cicada folder in it), then Documents › Cicada, or any- folder through the system's folder dialog."""options = [(LF("Obsidian 库「%@」", os.path.basename(v)), L("在库里新建 Cicada 文件夹"), os.path.join(v, "Cicada"))for v in fx.all_vaults()[:3]]docs = documents_dir()@@ -147,18 +131,17 @@ def choose_folder(parent, current: str | None) -> str | None:d = Gtk.Dialog(transient_for=parent, modal=True)d.set_title(L("存到哪里"))d.set_resizable(False)- # The app's flat bar with only ×, not Yaru's dark one repeating the heading (the Mac's is a sheet).bar = Gtk.HeaderBar()bar.set_show_close_button(True)bar.set_decoration_layout(":close")- bar.set_custom_title(Gtk.Box()) # the heading below says it once+ bar.set_custom_title(Gtk.Box())ui.classes(bar, "cicada")d.set_titlebar(bar)ui.classes(d, "sheet")area = d.get_content_area()ui.classes(area, "sheet")body = ui.vbox(14, ui.text(L("存到哪里"), 15, "heading", bold=True, wrap=False))- ui.pad(body, 0, 20, 20, 20) # the bar above is the top margin+ ui.pad(body, 0, 20, 20, 20)body.set_size_request(380, -1)picks = ui.vbox(8)body.pack_start(picks, False, False, 0)@@ -214,7 +197,6 @@ def choose_folder(parent, current: str | None) -> str | None:def line_key(app, s):- """What the record's line says, so it is rebuilt only when that changes."""ex = app.folder_exportif not (ex.on and ex.folder and ex.ready(s)):return None@@ -223,7 +205,6 @@ def line_key(app, s):def record_line(app, s, show_in_folder):- """Under the record's title: where its file is, or why it isn't there yet. None: nothing to say."""key = line_key(app, s)if key is None:return Nonediff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.pyindex 0a686ec..1d5f1d7 100644--- a/linux/cicada/app/main.py+++ b/linux/cicada/app/main.py@@ -1,5 +1,3 @@-"""Entry point and Controller: wires the engines to the windows, as AppModel does on the Mac.-Engine events arrive on worker threads; everything that touches GTK runs on the main loop."""from __future__ import annotationsimport os@@ -11,9 +9,6 @@ import threadingimport timefrom datetime import datetime, timezone-# GNOME on Wayland gives a client no way to stay on top or refuse focus; its X11 server (XWayland,-# always there on Ubuntu) does, and Mutter honours "above" and the input hint for X11 windows. So-# the app speaks X11 whenever it can. Must be set before GTK loads.if os.environ.get("DISPLAY") and "GDK_BACKEND" not in os.environ:os.environ["GDK_BACKEND"] = "x11"@@ -38,12 +33,10 @@ from . import debug, tray, ui # noqa: E402from . import capture # noqa: E402from .capture import SystemAudio # noqa: E402-ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # linux/ or the installed tree+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))def resource_dirs() -> list:- """The strings tables: an installed tree has them under lproj/; a checkout reads the Mac's- Resources/ and linux/strings/ directly."""installed = os.path.join(ROOT, "lproj")if os.path.isdir(installed):return [installed]@@ -69,16 +62,13 @@ class Controller:self.application = applicationself.settings = AppSettings.load()strings.load(self.settings.ui_code, resource_dirs())- # 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.translator.google_off = self.settings.google_offself.listen = ListenEngine(self.ling, self.translator, self.store, self.notes, self.settings)- # 改正听错的词: the word list beside the records, and the fixes the translation brings back.from ..core import vocabularyfrom ..core.live_fixes import LiveFixesself.vocabulary = vocabulary.Vocabulary(vocabulary.default_path())@@ -88,31 +78,22 @@ class Controller:self.listen.fixes = self.fixesself.translator.fix_context = self.fixes.contextself.translator.on_fixes = self.fixes.received- # 同声传译: my microphone → the AI service → 知了 麦克风. The listen side's loudness feeds its echo check.from ..core.speak import SpeakEnginefrom .room import TALK_MIC, TALK_SINK, EchoCanceller, Player, VirtualMicself.room = VirtualMic()- # The talk key's microphone with the meeting's voices taken out, made with 知了 麦克风 (as the- # Mac makes its voice unit ahead): what I say while they talk goes out instead of being dropped.self.talk_echo = EchoCanceller(TALK_SINK, TALK_MIC, "talk-sink", agc_off=True)self._talk_echo_lock = threading.Lock()- # 电脑和会议室: the online voices taken out of the room mic (module-echo-cancel).self.echo = EchoCanceller()- # Debug (roomEcho on): the room mic through the canceller. Off by default, as on the Mac: there- # the system's echo cancellation let no echo through but lost most of what the table said;- # the measured gate (roommic.EchoGate) and EchoMatch are what's left on by default.self.room_echo_cancel = False- self.headset_default = False # the default input is a Bluetooth headset's (the room uses another mic)+ self.headset_default = Falseself.forced_room_mic = Noneself.speak = SpeakEngine(self.ling, self.translator, self.settings, self.store, self.listen, player=lambda: Player())self.listen.loudness = self.speak.loudness- # 说话人识别: voiceprints (native/voiceprint.c), Ling's guesses at names.from ..core import speakersself.speakers = speakers.Tagger()self.listen.speakers = self.speakersself.namer = speakers.Namer(self.ling, self.store, self.changed)self.listen.on_voice = self.namer.guess- # 保存会议录音: only where GStreamer can write AAC (stock Ubuntu can't, see media.py).self.listen.recorder = self._recorderthreading.Thread(target=self._finish_recordings, name="Rewrap", daemon=True).start()self.notes.voices = lambda: self.settings.speakerVoices@@ -122,7 +103,6 @@ class Controller:self.store.on_change(lambda _id: self.changed())self.store.on_words(self._words)self.ling.on_change(self.changed)- # 存到文件夹 (设置 › 通用): written once a record is settled, rewritten when it changes.from ..core.folder_export import FolderExporterself.folder_export = FolderExporter(self.store, self.settings)self.folder_export.settling = self.notes.settling@@ -132,25 +112,21 @@ class Controller:self.store.on_save(self.folder_export.saved)self.notes.final_done = self.folder_export.settledself.notes_window = None- self.share_dialog = None # 分享… (share_dialog.py), one at a time+ self.share_dialog = Noneself.records_window = Noneself.settings_window = Noneself.onboarding = Noneself.tray = Noneself._queued = False- self.launcher = os.path.join(ROOT, "bin", "cicada") # for 登录时启动- # 结束会议 (meeting_end.py): `ending` while a meeting is about to end by itself, `auto_ended`- # after one did (the capsule says so, and the next call starts a new meeting).+ self.launcher = os.path.join(ROOT, "bin", "cicada")self.end_watch = Noneself.ending = Noneself.auto_ended = False- self.fake_calls = None # debug: meeting apps pretending to be in a call- self.end_times = None # debug: (silence, countdown, grace) in seconds+ self.fake_calls = None+ self.end_times = Noneself._calls_busy = Falsefrom .updater import Updates- self.updates = Updates(self) # 新版本: GitHub Releases, the tray menu and 设置 › 关于- # Something only the user can fix, said beyond the notes window (problem.py): the tray's dot- # and, once a meeting while the window is put away, a notification.+ self.updates = Updates(self)from ..core.problem import Noticesself.notices = Notices()self._notified = False@@ -163,9 +139,8 @@ class Controller:return media.encoder() is not Nonedef _recorder(self, sid: str):- """The new meeting's recorder, or None (setting off, or no AAC encoder here)."""from . import media- media.rescan() # formats installed since launch record this meeting+ media.rescan()if not self.settings.recordAudio or media.encoder() is None:return Nonerec = media.Recorder(self.store.audio_path(sid))@@ -173,7 +148,6 @@ class Controller:return recdef _finish_recordings(self) -> None:- """A meeting the app didn't get to close: its system.aac becomes system.m4a now (the Mac's load())."""from . import mediafor sid in self.store.unfinished_audio():if media.finish(self.store.audio_path(sid)):@@ -187,9 +161,6 @@ class Controller:return Truedef check_problem(self) -> None:- """Every second and on each change: a notification when problem.Notices says one is due,- withdrawn once the service works again. Never a dialog: it would take the focus from the- meeting app."""from ..core import aicheck, problemreason = self.ling.check_result.reason if self.ling.has_key else Nonew = self.notes_window@@ -212,8 +183,6 @@ class Controller:Log.d("problem: withdrawn")def _notify_folder_denied(self) -> None:- """Once after a meeting, until a write works again (folder_export decides when): its own id,- so check_problem's withdraw never takes it away."""from ..core.folder_export import short_pathfolder = self.folder_export.folderif not folder:@@ -239,18 +208,16 @@ class Controller:passself.tray = tray.make(self, icon)def prepare():- self.talk_echo.remove() # left by a run that crashed: the speakers are the default output again- self.echo.remove() # left by a run that crashed during 电脑和会议室+ self.talk_echo.remove()+ self.echo.remove()if self.settings.speakEnabled:if self.room.create():self._make_talk_echo()else:self.room.leftovers()- if speak: # `cicada --speak` before Cicada was running: speak once 知了 麦克风 is there+ if speak:GLib.idle_add(lambda: self.toggle_speaking() and False)threading.Thread(target=prepare, daemon=True).start()- # Logging out or `kill` sends SIGTERM / SIGHUP: quit properly so 知了 麦克风 goes and the real- # microphone is the default again, the same as 退出.for sig in (signal.SIGTERM, signal.SIGHUP, signal.SIGINT):GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, sig, self._signalled, sig)if Paths.dev:@@ -260,30 +227,25 @@ class Controller:if self.settings.onboarded and self.ling.has_key:threading.Thread(target=self.ling.check, daemon=True).start()self._watch_network()- # Opened by hand, 知了 shows its window: a top-bar icon alone looks like nothing happened, and- # plain GNOME has no top bar icon at all. Only a login start (--background) with an icon to be- # reached through, set up already, stays out of the way. Not set up: the onboarding on top.if not background or self.tray is None or not self.settings.onboarded:self.show_records()if not self.settings.onboarded:GLib.timeout_add(500, lambda: self.show_onboarding() and False)reopened = self.updates.reopened()if reopened and self.settings.onboarded:- self.show_records() # where 已更新到 … is said, once+ self.show_records()self.records_window.toasts.show(reopened)self.updates.start()self.keep_in_dock()- self.folder_export.retry() # meetings that waited (a folder that wasn't there, or the app quit)+ self.folder_export.retry()def changed(self) -> None:- """Engine threads call this: one coalesced refresh on the main loop."""if self._queued:returnself._queued = Truedef run():self._queued = False- # 会议室 while 同声传译 hears me through the same microphone: what it hears is me.self.listen.set_muted(self.speak.active)if self.notes_window is not None:self.notes_window.refresh()@@ -301,8 +263,6 @@ class Controller:return FalseGLib.idle_add(run)- # Windows-def show_notes(self) -> None:if self.notes_window is None:from .notes_window import NotesWindow@@ -316,36 +276,28 @@ class Controller:from .records_window import RecordsWindowself.records_window = RecordsWindow(self)self.application.add_window(self.records_window)- # Coming forward: a folder fixed meanwhile (the Mac's didBecomeActive).self.records_window.connect("focus-in-event", lambda *_: self.folder_export.retry() or False)return self.records_windowdef show_records(self) -> None:from . import media- media.rescan() # a recording plays once the formats are installed, no restart+ media.rescan()w = self._records()if w.get_visible() and w.iconified:- # Minimized (keep_in_dock), Mutter won't bring it back for a request without a user's- # event time (the tray, a second launch): shown afresh instead, as when it was hidden.w.hide()w.fill()w.set_focus_on_map(True)- w.deiconify() # unmapped, this only clears GTK's "map it minimized" (keep_in_dock's iconify)+ w.deiconify()w.show_all()self.records_window.present()- self.records_window.set_focus(None) # not the search box: its placeholder would vanish+ self.records_window.set_focus(None)@propertydef records_open(self) -> bool:- """On screen: not hidden, nor minimized to keep the dock icon (a dialog over it would be too)."""w = self.records_windowreturn w is not None and w.get_visible() and not w.iconifieddef keep_in_dock(self) -> None:- """在 Dock 中显示 (the Mac's showInDock): GNOME's dock lists an app only while it has a window- there, and the notes window, a notification that never takes focus, has none. So while the- setting is on the records window stays, minimized, and clicking the dock icon brings it back.- Mapped minimized and never presented: the meeting app keeps the focus."""w = self.records_windowif not self.settings.showInDock or (w is not None and w.get_visible()):return@@ -353,13 +305,12 @@ class Controller:w.fill()w.parked = Truew.set_focus_on_map(False)- w.iconify() # before it's mapped: it starts minimized (WM_HINTS IconicState)+ w.iconify()w.show_all()- w.set_focus(None) # back from the dock, not in the search box: its placeholder would vanish+ w.set_focus(None)Log.d("dock: records window kept minimized")def set_show_in_dock(self, on: bool) -> None:- """设置 › 在 Dock 中显示. Off: as before it existed, the records window only while it's open."""self.settings.showInDock = onself.settings.save()w = self.records_window@@ -370,14 +321,10 @@ class Controller:Log.d("dock: %s" % ("on" if on else "off"))def show_settings(self, ai: bool = False, general: bool = False) -> None:- """设置; `ai`: at AI 服务 (its first section), where every AI problem is fixed; `general`: at 通用- (保存会议录音, from a record that has none)."""if self.settings_window is None:from .settings_window import SettingsWindowself.settings_window = SettingsWindow(self)self.application.add_window(self.settings_window)- # show_all() only on the way up: on an open window it would bring back what its "show"- # handlers hid (the key card under a custom service's own rows).if not self.settings_window.get_visible():self.settings_window.show_all()self.settings_window.present()@@ -386,39 +333,30 @@ class Controller:elif general:self.settings_window.scroll_to_general()- # Setup (会议记录 › 还差几步 and the capsule)-@propertydef setup_done(self) -> tuple:- """The setup steps as the onboarding numbers them (key, computer sound, sample): done by what- really happened, not by "the onboarding was finished" (Windows' SetupDone)."""s = self.settingsreturn self.key_works, s.heardSystemAudio or s.onboarded, s.sampleSeen or s.onboarded@propertydef key_works(self) -> bool:- """The key step is done: a key, and no failure only the user can fix (a check still running,- or one not run yet, doesn't undo it; busy counts as passed)."""f = self.ling.check_result.failurereturn self.ling.has_key and (f is None or f[1] in ("busy", "serverError"))@propertydef setup_left(self) -> int:- """Steps left before listening works; 0 once set up. 同声传译 is optional and never counted."""key, audio, sample = self.setup_doneif self.settings.onboarded and key:return 0return (not key) + (not audio) + (not sample)def setup_step_done(self, name: str) -> None:- """The onboarding heard the computer (heardSystemAudio) or played the sample (sampleSeen)."""if not getattr(self.settings, name):setattr(self.settings, name, True)self.settings.save()self.changed()def show_onboarding(self, step: int | None = None) -> None:- """The onboarding at `step`, or at the first step not done, over the records window."""from .onboarding import AUDIO, KEY, SAMPLE, Onboarding_, audio, _ = self.setup_donekey = self.ling.has_key@@ -430,7 +368,6 @@ class Controller:returnself.onboarding = Onboarding(self, at)self.application.add_window(self.onboarding)- # Over the records window, so closing it leaves a window to click, not an empty screen.if self.records_open:self.onboarding.set_transient_for(self.records_window)self.onboarding.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)@@ -445,7 +382,6 @@ class Controller:self.onboarding.present()def records_closed(self) -> None:- """The records window was closed: once, say 知了 is still in the top bar (it keeps running)."""if self.tray is None or self.settings.trayHintShown:returnself.settings.trayHintShown = True@@ -455,7 +391,6 @@ class Controller: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 namedif named(provider).id != provider or provider == self.settings.aiProvider:return@@ -464,8 +399,6 @@ class Controller:self.ai_changed()def can_switch_to_ling(self) -> bool:- """改用 Ling where another service is out of reach: only when a Ling key is already saved, so- the one click works without a trip to the settings. Read fresh: the key may have just been saved."""return self.settings.aiProvider != "ling" and AIKey(service=lambda: "ling").read() is not Nonedef switch_to_ling(self) -> None:@@ -473,8 +406,6 @@ 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", "voice", or a custom service's- "notes"; "" goes back to it)."""s = self.settingsp = s.aiProviderif kind == "text" and p == "ling":@@ -484,7 +415,7 @@ class Controller:if table is None:returnif kind == "notes":- p = "custom.notes" # the custom service's notes model ("": the translation one)+ p = "custom.notes"if model:table[p] = modelelse:@@ -493,45 +424,36 @@ class Controller:self.ai_changed()def ai_changed(self) -> None:- """The service, its address, models or key changed: forget the old check and check again."""self.translator.google_off = self.settings.google_offself.ling.key_changed()if self.ling.has_key:threading.Thread(target=self.ling.check, daemon=True).start()def set_custom_only(self, on: bool) -> None:- """语音和文字只发给你的服务: Google is never asked while the custom service is in use. Nothing- to check again: only where translations go changes."""self.settings.aiCustomOnly = onself.settings.save()self.translator.google_off = self.settings.google_offif self.settings_window is not None:- self.settings_window.show_key_state() # the switch, its grey line and the footnote+ self.settings_window.show_key_state()self.changed()def recheck(self) -> None:- """重新检查: the AI service, step by step, off the main loop."""if self.ling.has_key and not self.ling.check_result.running:threading.Thread(target=self.ling.check, daemon=True).start()def use_recommended(self, kind: str) -> None:- """换成推荐的: the service's first recommended text or hear model, then a fresh check. Only- ever on the user's click: the app never changes a model by itself."""p = self.ling.providermodels = p.text_models if kind == "text" else p.hear_modelsif models:self.set_ai_model(kind, models[0].id)def switch_service(self, provider: str, key: str) -> None:- """改用 <服务>: a key pasted for another service goes there, then it is checked."""self.settings.aiProvider = providerself.settings.save()self.key.save(key)self.ai_changed()def _watch_network(self) -> None:- """A change of route (Wi-Fi back, a proxy app's TUN) waits 3 s for the network to settle, then- the service is looked at again if it was unreachable. No timer otherwise."""monitor = Gio.NetworkMonitor.get_default()self._net_wait = None@@ -554,7 +476,6 @@ class Controller:returnself.settings.view = viewself.settings.save()- # A new window for the new layout: GTK won't shrink a mapped 620 px notes window to a bar.if self.notes_window is not None:visible = self.notes_window.get_visible()self.notes_window.destroy()@@ -565,34 +486,26 @@ class Controller:def settings_changed(self) -> None:self.changed()- # Listening-def toggle_listening(self) -> None:if self.listen.listening:self.stop_listening()else:self.start_listening(*self.heard_source())- # 听哪里-def room_mic(self) -> str:- """The microphone that hears the room now (roommic.pick). 知了 麦克风 as the default input- (同声传译 on) stands for the real microphone it took the place of."""- if self.forced_room_mic: # debug: a null sink's monitor standing in for one (a VM has no microphone)+ if self.forced_room_mic:return self.forced_room_micinputs = roommic.parse_sources(capture.sources_text())default = capture.default_source()if default == "cicada_mic":default = self.room.real_micpicked = roommic.pick(default, inputs, self.settings.roomMic)- if picked is None and not inputs: # no pactl to list them: the default, if it's a real one+ if picked is None and not inputs:picked = default or "@DEFAULT_SOURCE@"Log.d("room mic: %s (default %s, %d inputs)" % (picked, default, len(inputs)))return pickeddef heard_source(self):- """(source, kind) for 听哪里: the computer's audio, or the room through a microphone. For- 电脑和会议室 the computer's audio; the room side starts beside it (_start_room_side)."""if self.settings.listenSource == "both":return SystemAudio(), "both"if self.settings.listenSource == "room":@@ -607,9 +520,6 @@ class Controller:return self.settings.listenSource == "both"def set_mic(self, on: bool) -> None:- """打开麦克风 / 关闭麦克风, from the tray, the notes window or the debug pipe (the Mac's setMic):- the computer's audio is always heard, the mic adds the room to the same meeting. Not kept for- the next launch; turning it on while nothing is heard starts listening."""value = "both" if on else "system"if value == self.settings.listenSource:if on and not self.listen.listening:@@ -627,9 +537,6 @@ class Controller:self.changed()def _room_side_source(self):- """(source, gated) for 电脑和会议室's room side, or None without a microphone: the room mic- through the echo canceller; without one (or the sound server won't) the plain mic, gated- while the computer plays speech. 戴着耳机: nothing comes out of the speakers to cancel."""mic = self.room_mic()if mic is None:Log.d("hybrid: no microphone, the computer's audio only")@@ -650,8 +557,6 @@ class Controller:self.listen.start_room(*room)def _room_lost(self, why) -> None:- """The room side's microphone went away (unplugged, the sound server gone for 20 s): another- one takes over if there is one; otherwise the computer's audio goes on alone."""def run():if self.listen.listening and self.listen.hears_room_too and why:Log.d("hybrid: room microphone lost (%s)" % why)@@ -667,8 +572,6 @@ class Controller:self.echo.remove()def set_headphones(self, on: bool) -> None:- """戴着耳机 (同声传译's): whether a sentence said while they talk may be their voice from the- speakers. The room mic measures that for itself (roommic.EchoGate)."""if on == self.settings.speakHeadphones:returnself.settings.speakHeadphones = on@@ -677,29 +580,22 @@ class Controller:def _source_ended(self, kind: str):def ended(reason):- # A file that finished stops a little later, so its last sentence's pause is heard;- # a capture that failed stops now.if reason is None:GLib.timeout_add(1500, lambda: self.stop_listening() and False)returnLog.d("listen: source ended %s" % reason)- # Said where the subtitles would be (start() clears it), not silently stopped.self.listen.problem = L("没有可用的麦克风") if kind == "room" else L("系统声音中断")self.listen.problem_kind = "source"GLib.idle_add(lambda: self.stop_listening() and False)return endeddef recorded(self):- """(elapsed seconds, lines) of the live meeting, or None when nothing has been said yet."""s = self.store.get(self.listen.session_id) if self.listen.listening and self.listen.session_id else Noneif s is None or not s.lines:return Nonereturn (datetime.now(timezone.utc) - s.startedAt).total_seconds(), len(s.lines)def request_stop(self, parent=None) -> None:- """结束 from the tray, the records window, the subtitle bar or the shortcut (the Mac's- requestStop): a meeting with lines ends only after asking, 继续记录 the default so a stray- Return keeps it going. An empty one just stops. Starting needs no question."""if not self.listen.listening:self.toggle_listening()return@@ -708,8 +604,6 @@ class Controller:self.stop_listening()returnsid = self.listen.session_id- # Drawn in the app's own look (white sheet, ink and outline buttons), not the theme's message- # dialog with its icon and red button.dialog = Gtk.Dialog(transient_for=parent, modal=True)dialog.set_decorated(False)dialog.set_resizable(False)@@ -732,7 +626,6 @@ class Controller:keep.grab_focus()answer = dialog.run()dialog.destroy()- # The same meeting still running: it may have ended by itself while the question was open.if answer == Gtk.ResponseType.ACCEPT and self.listen.listening and self.listen.session_id == sid:self.stop_listening()@@ -742,8 +635,6 @@ class Controller:if not self.ling.has_key:self.show_onboarding()return- # The service hears for us: a known failure stops here with the fix, not in an empty window.- # Unknown or busy starts as usual; unreachable is looked at once more first.r = self.ling.check_resultif r.reason == "unreachable" and not checked:def again():@@ -755,7 +646,6 @@ class Controller:returnsource.on_ended = self._source_ended(kind)- # A new meeting's notes window starts without the last meeting's interpreted sentence.if not self.speak.active:self.speak.last = Noneself.speak.problem = None@@ -772,8 +662,6 @@ class Controller:self.changed()def _may_start(self, source, kind: str) -> bool:- """开始听 when the last check found the hear model deaf or the service unreachable: say so,- with 打开设置 and the one fix (换成推荐的并开始 / 重新检查并开始). False: not now."""from ..core import aicheckling = self.lingr = ling.check_result@@ -805,7 +693,7 @@ class Controller:dialog.connect("key-press-event", lambda _d, e: e.keyval == Gdk.KEY_Escape and dialog.response(Gtk.ResponseType.CLOSE))dialog.get_content_area().pack_start(ui.pad(ui.vbox(18, texts, row), 22, 22), True, True, 0)dialog.get_content_area().show_all()- self._asking = dialog # debug: screenshots, and answering it from the control socket+ self._asking = dialoganswer = dialog.run()self._asking = Nonedialog.destroy()@@ -813,7 +701,7 @@ class Controller:self.show_settings(ai=True)elif answer == Gtk.ResponseType.ACCEPT:if r.reason == aicheck.DEAF:- self.use_recommended("hear") # checks again; the meeting starts now+ self.use_recommended("hear")return Truedef again():@@ -822,8 +710,6 @@ class Controller:threading.Thread(target=again, daemon=True).start()return False- # 结束会议-def end_config(self) -> meeting_end.Config:s = self.settingsc = meeting_end.Config(follow_apps=s.endWithApp, silence=s.silenceEnd, silence_after=s.silenceMinutes * 60)@@ -832,8 +718,6 @@ class Controller:return cdef _watch_end(self) -> bool:- """Every 2 s: while listening, whether the meeting is over; after one ended by itself,- whether a meeting app started the next call. `pactl` runs off the main loop."""listening = self.listen.listening and self.end_watch is not Noneafter = not self.listen.listening and self.auto_endedif self._calls_busy or not (listening or after):@@ -869,8 +753,6 @@ class Controller:self.start_listening(*self.heard_source())def _words(self, sid: str) -> None:- """Words recognised in the live meeting (theirs or mine): the silence countdown stops now,- as on the Mac, not at the next tick."""def run():if self.end_watch is not None and self.listen.listening and sid == self.listen.session_id:self.end_watch.heard(time.time())@@ -890,12 +772,9 @@ class Controller:def _auto_end(self, reason, w) -> None:if reason.kind == "nobody":- # Nothing to keep or summarise: back to 开始听, not 会议已自动结束.Log.d("meeting end: nobody spoke for %d s, stopped" % w.config.silence_after)self.stop_listening()return- # Where the meeting really ended: a little after the last words, or at the hang-up if that- # was later.at = w.last_speech + 5if reason.kind == "app":at = max(at, time.time() - w.config.app_grace)@@ -904,7 +783,6 @@ class Controller:self.stop_listening(ended_at=datetime.fromtimestamp(at, timezone.utc), auto=True)def keep_recording(self) -> None:- """继续记录 on the ending prompt."""if self.end_watch is not None:self.end_watch.keep_going(time.time())self._set_ending(None)@@ -918,11 +796,7 @@ class Controller:def ending_left(self, p) -> int:return max(0, int(round(p.deadline - time.time())))- # 同声传译-def set_speak_enabled(self, on: bool) -> bool:- """Turning it on makes 知了 麦克风 (and the default input); off removes it. False if the sound- server wouldn't make the device."""if on and not self.room.on:if not self.room.create():return False@@ -937,12 +811,10 @@ class Controller:return Truedef _make_talk_echo(self) -> None:- """The talk key's echo canceller, in front of the output that is the default now. Not while- 电脑和会议室's debug canceller is (two in a row fight over the default output)."""real = self.room.real_micif not real or self.echo.on:return- with self._talk_echo_lock: # a press can ask again while the last one is still being made+ with self._talk_echo_lock:if self.talk_echo.ready(real):returnself.talk_echo.remove()@@ -957,7 +829,6 @@ class Controller:self.show_onboarding()returnif 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@@ -966,9 +837,6 @@ class Controller:self.speak.problem = L("没能建好知了麦克风")self.changed()return- # Me, from the microphone that was the default before 知了 麦克风 took its place: through the- # echo canceller made for it while the meeting still plays through that, else the plain mic- # (said over the meeting is dropped then) and the canceller is made again for the next time.real = self.room.real_miccancelled = bool(real) and self.talk_echo.ready(real)why = ""@@ -994,23 +862,19 @@ class Controller:self.ending = Noneself.auto_ended = auto- # stop() waits for Ming's last replies: off the main loop.-def run():sid = self.listen.session_idself.listen.stop(ended_at)if sid and self.store.get(sid) is not None:self.folder_export.ended(sid)if self.echo.on:- self.echo.remove() # the speakers are the default output again+ self.echo.remove()if sid and self.settings.speakerVoices:- self.namer.guess(sid, force=True) # the whole meeting read once more for names+ self.namer.guess(sid, force=True)self.changed()- GLib.idle_add(lambda: self.updates.meeting_ended() and False) # 会后安装+ GLib.idle_add(lambda: self.updates.meeting_ended() and False)threading.Thread(target=run, daemon=True).start()- # 说话人识别-@propertydef voices_available(self) -> bool:from ..core import speakers@@ -1023,13 +887,11 @@ class Controller:self.changed()def _speaker_edit(self, sid, change):- """Runs a speaker edit and returns what 撤销 puts back."""snap = self.store.voice_snapshot(sid)change()return snapdef rename_speaker(self, sid: str, voice: int, name):- """Name a voice ("" keeps 说话人 N, None goes back to Ling's guess). (toast text or None, snapshot)."""from ..core import speakerss = self.store.get(sid)if s is None:@@ -1042,7 +904,6 @@ class Controller:return (LF("%@ 已改成 %@", before, after) if after != before else None), snapdef merge_speaker(self, sid: str, frm: int, into: int):- """Two voices are one person. While listening the voiceprints merge too, which 撤销 can't take back."""from ..core import speakerss = self.store.get(sid)if s is None:@@ -1056,7 +917,6 @@ class Controller:return LF("%@ 已并入 %@", a, b), snapdef assign_lines(self, sid: str, ids: set, voice: int):- """These lines were someone else's."""from ..core import speakerss = self.store.get(sid)if s is None:@@ -1073,8 +933,6 @@ class Controller:Log.d("speakers: undo %s" % sid)def play_sample(self) -> None:- """The onboarding sample: heard straight from the file while it plays aloud for the user (the- system capture isn't running, so it isn't heard twice)."""path = sample_path()if path is None:Log.d("sample: no sample.wav")@@ -1090,7 +948,6 @@ class Controller:Log.d("sample: play failed %s" % type(e).__name__)def feed(self, path: str) -> None:- """Debug: a WAV heard as if the speakers played it, in real time."""self.start_listening(PcmAudioSource(path, 1.0), "file")def _signalled(self, sig) -> bool:@@ -1100,20 +957,20 @@ class Controller:def quit(self) -> None:if self.records_window is not None:- self.records_window.commit_delete() # a delete still showing 撤销 goes through+ self.records_window.commit_delete()def run():self.speak.cancel()- self.talk_echo.remove() # the speakers are the default output again+ self.talk_echo.remove()if self.room.on:- self.room.remove() # the real microphone is the default again+ self.room.remove()if self.echo.on:self.echo.remove()if self.listen.listening:sid = self.listen.session_idself.listen.stop()if sid and self.store.get(sid) is not None:- self.folder_export.ended(sid) # kept as waiting: written at the next launch+ self.folder_export.ended(sid)self.store.flush()GLib.idle_add(lambda: self.application.quit() and False)threading.Thread(target=run, daemon=True).start()@@ -1127,20 +984,17 @@ class App(Gtk.Application):def do_startup(self):Gtk.Application.do_startup(self)- self.hold() # a menu bar style app: no window doesn't mean quit+ self.hold()GLib.set_application_name(L("知了"))self.controller = Controller(self)- # `cicada --toggle` (a system keyboard shortcut runs it) reaches the running app as this action.toggle = Gio.SimpleAction.new("toggle", None)toggle.connect("activate", lambda *_: self.controller.request_stop())self.add_action(toggle)- speak = Gio.SimpleAction.new("speak", None) # `cicada --speak`: 开始 / 停止说+ speak = Gio.SimpleAction.new("speak", None)speak.connect("activate", lambda *_: self.controller.toggle_speaking())self.add_action(speak)- # The update notification's click and its 更新说明 button; a problem's 打开设置.for name, action in (("install-update", lambda: self.controller.updates.install()),("ai-settings", lambda: self.controller.show_settings(ai=True)),- # 纪要没存到文件夹: 设置 › 通用, where the row says what to do.("folder-settings", lambda: self.controller.show_settings(general=True)),("update-notes", lambda: self.controller.updates.open_notes())):a = Gio.SimpleAction.new(name, None)@@ -1157,8 +1011,6 @@ class App(Gtk.Application):GLib.idle_add(lambda: self.controller.toggle_listening() and False)def do_activate(self):- # A second launch lands here in the running instance: the records, and the onboarding on top- # while not set up (closed with ✕ earlier, it would otherwise never come back).if self.controller is not None and getattr(self, "_activated", False):self.controller.show_records()if not self.controller.settings.onboarded:@@ -1173,22 +1025,19 @@ def main(argv=None) -> int:argv.remove("--dev")GLib.set_prgname("cicada")app = App()- if "--background" in argv: # 登录时启动: stay in the top bar+ if "--background" in argv:argv.remove("--background")app.background = Truefor flag, action in (("--toggle", "toggle"), ("--speak", "speak")):if flag in argv:argv.remove(flag)if _remote(app.get_application_id(), action):- return 0 # the running instance starts or stops listening / speaking- # Not running yet: start, then listen / speak.+ return 0setattr(app, action + "_at_start", True)return app.run(argv)def _remote(app_id: str, action: str) -> bool:- """Activates the running instance's action over D-Bus (org.gtk.Actions), as GLib's own- remote activation does, without registering a second application."""try:bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)bus.call_sync(app_id, "/" + app_id.replace(".", "/"), "org.gtk.Actions", "Activate",diff --git a/linux/cicada/app/media.py b/linux/cicada/app/media.pyindex bf908f5..14d2f2b 100644--- a/linux/cicada/app/media.py+++ b/linux/cicada/app/media.py@@ -1,11 +1,3 @@-"""保存会议录音 and playing it back, through GStreamer (PyGObject; Gst and GstBase are the only typelibs-stock Ubuntu has, so appsrc is fed through its action signals, not GstApp).--Stock Ubuntu ships GStreamer with no AAC encoder or decoder: they come with the third-party media-formats (gstreamer1.0-libav and the like). So recording is offered only when an encoder is there,-and playing only when a decoder is; nothing is bundled and nothing is installed for the user. The-file is the Mac's: AAC mono at 32 kbit/s, ADTS while recording, rewrapped into system.m4a at the end-(core/aac.py)."""from __future__ import annotationsimport os@@ -20,7 +12,7 @@ try:gi.require_version("Gst", "1.0")from gi.repository import GstGst.init(None)-except (ImportError, ValueError) as _e: # no GStreamer introspection: neither records nor plays+except (ImportError, ValueError) as _e:Gst = NoneENCODERS = ("fdkaacenc", "avenc_aac", "voaacenc", "faac")@@ -35,7 +27,6 @@ def _has(name: str) -> bool:def encoder() -> str | None:- """The AAC encoder to record with, None when the meeting can't be saved as AAC here."""if not all(_has(e) for e in ("appsrc", "audioconvert", "audioresample", "aacparse", "mp4mux", "filesink")):return Nonereturn next((e for e in ENCODERS if _has(e)), None)@@ -46,9 +37,6 @@ def can_play() -> bool:def rescan() -> None:- """Looks again for what was missing: the third-party media formats installed while Cicada runs- (Settings says to) work without a restart. GStreamer read its plugin registry once at init; the- rescan takes ~0.1 s after a new plugin and nothing when none changed."""if Gst is None or (encoder() is not None and can_play()):returnGst.update_registry()@@ -57,7 +45,6 @@ def rescan() -> None:def codecs() -> dict:- """What this computer has (debug, the log)."""return {"gst": Gst is not None, "encoder": encoder(), "decoders": [d for d in DECODERS if _has(d)], "play": can_play()}@@ -71,7 +58,6 @@ def _make(name: str, **props):def _wait(pipeline, seconds: float):- """Blocks until the pipeline finishes or fails: the error's text, or None."""msg = pipeline.get_bus().timed_pop_filtered(int(seconds * Gst.SECOND), Gst.MessageType.EOS | Gst.MessageType.ERROR)if msg is None:return "timeout"@@ -82,9 +68,6 @@ def _wait(pipeline, seconds: float):class Recorder:- """One meeting's system.aac: 16 kHz mono samples in, AAC frames out as they are encoded, written- unbuffered so a crash loses at most the frame being written."""-def __init__(self, path: str):self.path = pathself.partial = aac.partial(path)@@ -95,7 +78,7 @@ class Recorder:caps=Gst.Caps.from_string("audio/x-raw,format=S16LE,rate=%d,channels=1,layout=interleaved" % RATE))coder = _make(enc)if coder.find_property("bitrate") is not None:- coder.set_property("bitrate", 32000) # the Mac's AVEncoderBitRateKey+ coder.set_property("bitrate", 32000)chain = [self.src, _make("audioconvert"), _make("audioresample"), coder, _make("aacparse"),_make("capsfilter", caps=Gst.Caps.from_string("audio/mpeg,mpegversion=4,stream-format=adts")),_make("filesink", location=self.partial, buffer_mode=2, sync=False, **{"async": False})]@@ -113,7 +96,6 @@ class Recorder:Log.d("record: %s with %s" % (os.path.basename(os.path.dirname(path)), enc))def write(self, samples) -> None:- """On the listening worker: never blocks it (appsrc queues)."""if self.failed:returnmsg = self.pipeline.get_bus().pop_filtered(Gst.MessageType.ERROR)@@ -129,7 +111,6 @@ class Recorder:self.src.emit("push-buffer", buf)def close(self) -> None:- """The last frames out to the file (blocks briefly)."""if self.pipeline is None:returnself.src.emit("end-of-stream")@@ -147,9 +128,6 @@ class Recorder:def finish(path: str, until: float | None = None) -> bool:- """system.aac → system.m4a without re-encoding (AudioFileWriter.finish), cut at `until` seconds.- A partial file beside an .m4a means the last rewrap was cut short: it is done again. Needs only- aacparse and mp4mux (plugins-good), so a stock computer can finish a recording too."""src = aac.partial(path)if not os.path.isfile(src) or Gst is None or not (_has("aacparse") and _has("mp4mux")):return False@@ -186,19 +164,14 @@ def finish(path: str, until: float | None = None) -> bool:class Player:- """A record's system.m4a in the records window (RecordingPlayer): play / pause, seek, 1× / 1.5× / 2×- at the same pitch (scaletempo). Lives on the main loop: the bus is watched there."""-def __init__(self, path: str, on_change=None):self.on_change = on_changeself.rate = 1.0self.playing = False- self.started = False # played at least once: the line at the playhead shows from then- # The transcript keeps the playing line in view. Scrolling it by hand stops that until a line is- # picked, the bar is moved or 回到正在播放 is pressed: following would yank the page away.+ self.started = Falseself.following = Trueself._length = 0.0- self._seeking = None # (where to, when): the position reads 0 while a flushing seek settles+ self._seeking = Nonepb = _make("playbin", uri=Gst.filename_to_uri(path))tempo = Gst.ElementFactory.make("scaletempo", None)if tempo is not None:@@ -208,7 +181,7 @@ class Player:bus.add_signal_watch()bus.connect("message::eos", self._eos)bus.connect("message::error", self._error)- pb.set_state(Gst.State.PAUSED) # prerolled: the length is known and the first play is instant+ pb.set_state(Gst.State.PAUSED)def close(self) -> None:if self.pb is None:@@ -235,7 +208,7 @@ class Player:if self._seeking is not None:to, at = self._seekingif abs(t - to) > 0.5 and time.monotonic() - at < 1.5:- return to # not there yet: where it is going, so the line being played doesn't jump back+ return toself._seeking = Nonereturn t@@ -244,7 +217,7 @@ class Player:self.pause()else:if self.length and self.time >= self.length - 0.1:- self.seek(0) # at the end: from the start again+ self.seek(0)self.play()def play(self) -> None:@@ -262,7 +235,6 @@ class Player:self._changed()def user_scrolled(self) -> None:- """The transcript was scrolled by hand while it plays."""if self.following and self.playing:self.following = Falseself._changed()@@ -277,7 +249,6 @@ class Player:self.play()def seek(self, t: float) -> None:- """Flushing and exact; at the speed chosen (a plain seek would go back to 1×)."""if self.pb is None:returnt = max(0.0, min(t, self.length or t))@@ -287,9 +258,8 @@ class Player:Gst.SeekType.SET, int(t * Gst.SECOND), Gst.SeekType.NONE, -1)def next_rate(self) -> None:- """1× → 1.5× → 2×."""self.rate = 1.0 if self.rate >= 2 else self.rate + 0.5- following = self.following # a new speed isn't a seek: scrolled away stays scrolled away+ following = self.followingself.seek(self.time)self.following = followingself._changed()diff --git a/linux/cicada/app/notes_window.py b/linux/cicada/app/notes_window.pyindex e8760da..9e403d1 100644--- a/linux/cicada/app/notes_window.py+++ b/linux/cicada/app/notes_window.py@@ -1,12 +1,3 @@-"""The window shown while listening: live notes (default) or the subtitle bar. Like the Mac's notes-panel it stays above other windows and never takes focus, so the user keeps typing in their meeting-app: an X11 window (the app runs on XWayland under GNOME's Wayland session, see main.py) with the-"above" state and an input hint of false, which the window manager honours.--Linux has no way to keep one window out of screen sharing (the portal shares whatever is on-screen), so unlike the Mac and Windows the footer always says 共享屏幕时此窗口可见, and 共享屏幕时-让对方看到 isn't offered. The notes panel follows the desktop's dark style; the subtitle bar is-always dark, to read over video."""from __future__ import annotationsfrom datetime import datetime, timezone@@ -32,9 +23,6 @@ class NotesWindow(Gtk.Window):self.set_focus_on_map(False)self.set_skip_taskbar_hint(True)self.set_skip_pager_hint(True)- # A notification-type window: Mutter keeps it in the top layer and doesn't move focus when- # it's clicked (a utility window still blinks the meeting app out of focus for ~0.1 s).- # The WM won't move such a window, so dragging is done here (_drag/_motion).self.set_type_hint(Gdk.WindowTypeHint.NOTIFICATION)self.set_wmclass("cicada", "Cicada")screen = self.get_screen()@@ -48,23 +36,21 @@ class NotesWindow(Gtk.Window):self.connect("button-press-event", self._drag)self.connect("motion-notify-event", self._motion)self.connect("button-release-event", lambda *_: setattr(self, "_grab", None))- self._bottom = None # the subtitle bar's bottom edge: it grows upward as text wraps+ self._bottom = Noneself.connect("configure-event", self._configured)self.connect("realize", lambda w: x11.never_take_focus(w.get_window()))- # Mutter flags it as demanding attention once it's mapped (just after map-event).self.connect("map-event", lambda w, _e: GLib.timeout_add(200, lambda: x11.no_attention(w.get_window()) or False) and False)self.connect("delete-event", lambda *_: self.hide() or True)self._queued = Falseself._built = Falseself._timer = None- # 纪要 / 文字记录, the search in the transcript and 纪要和原话并排 (NotesWindow.swift).self.tab = "notes"self.wide = Falseself.query = ""self.matches = []self.match_index = 0self._transcript_key = None- self._keys = False # taking the keyboard while the search is typed in+ self._keys = Falseself.connect("show", lambda *_: self._start_clock())self.connect("hide", lambda *_: self._stop_clock())self.render()@@ -78,8 +64,6 @@ class NotesWindow(Gtk.Window):def dark(self) -> bool:return self.subtitles or ui.prefers_dark()- # Moving and placing-def _drag(self, _w, event):Log.d("notes window: click at %d,%d, active=%s" % (event.x, event.y, self.is_active()))if event.button == 1:@@ -101,7 +85,6 @@ class NotesWindow(Gtk.Window):return Falsedef place(self) -> None:- """Notes at the top right, subtitles along the bottom, on the primary monitor's work area."""display = Gdk.Display.get_default()mon = display.get_primary_monitor() or display.get_monitor(0)area = mon.get_workarea()@@ -132,14 +115,13 @@ class NotesWindow(Gtk.Window):self._fill_header()s = self.app.store.get(self.app.listen.session_id) if self.app.listen.session_id else Noneif s is not None and not s.lines:- self._fill_live() # before the first line the state follows the sound+ self._fill_live()if self.footer_time is not None:self._fill_footer()self._fill_ending()return Truedef refresh(self) -> None:- """Changes come from engine threads (via the controller): coalesce them into one render."""if self._queued:returnself._queued = True@@ -150,8 +132,6 @@ class NotesWindow(Gtk.Window):return FalseGLib.idle_add(run)- # Layout-def _build(self) -> None:self._built = Trueouter = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)@@ -160,7 +140,6 @@ class NotesWindow(Gtk.Window):self.header = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=4)ui.pad(self.header, 8, 8, 4, 16)outer.pack_start(self.header, False, False, 0)- # 听哪里 while listening (正在听 · 会议室 换 ⌄): changed here, the same meeting goes on.self.source_row = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)self.source_row.set_no_show_all(True)if not self.subtitles:@@ -172,13 +151,10 @@ class NotesWindow(Gtk.Window):if self.subtitles:ui.pad(self.live, 0, 22, 16, 22)outer.pack_start(self.live, False, False, 0)- # The wrapper is what hides: show_all() skips a no_show_all widget's own children.self.speakwrap = Gtk.Box()self.speakwrap.pack_start(ui.pad(self.speakbox, 0, 22, 14, 22), True, True, 0)outer.pack_start(self.speakwrap, False, False, 0)else:- # Below the header: the ending strip (a meeting about to end by itself), the tabs, then- # the notes and / or the transcript (side by side when wide).self.ending_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)self.ending_wrap = ui.pad(ui.panel(ui.pad(self.ending_box, 14), "endingstrip"), 2, 12, 8, 12)self.tabs = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0, homogeneous=True)@@ -194,13 +170,9 @@ class NotesWindow(Gtk.Window):self.tabs_wrap = ui.pad(self.tabs, 2, 16, 10, 16)outer.pack_start(self.tabs_wrap, False, False, 0)outer.pack_start(self.ending_wrap, False, False, 0)- # This meeting's languages ("English → 简体中文", the Mac's languageLink) and, opened from- # it, the card that changes them; after the meeting, 改用…重新整理.self.lang_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)self.lang_wrap = ui.pad(self.lang_box, 0, 12, 8, 12)outer.pack_start(self.lang_wrap, False, False, 0)- # 改正听错的词: 这样改对吗? above both tabs (the window opens on 纪要, where a card in the- # transcript would never be seen), and the last decision with 撤销.self.fix_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)self.fix_wrap = ui.pad(self.fix_box, 0, 12, 8, 12)self.fix_wrap.set_no_show_all(True)@@ -224,8 +196,6 @@ class NotesWindow(Gtk.Window):self.transcript_col.pack_start(self.tscroll, True, True, 0)self.columns.pack_start(self.transcript_col, True, True, 0)outer.pack_start(self.columns, True, True, 0)- # What is being said, at the bottom as on the Mac: a dark card (a light one for states).- # Only under the notes: the transcript shows what is said in place.ui.pad(self.live, 12, 16)self.live_box = ui.panel(self.live, "livebox")ui.pad(self.live_box, 6, 12, 0, 12)@@ -252,7 +222,7 @@ class NotesWindow(Gtk.Window):for w in (self.ending_wrap, self.tabs_wrap, self.scroll, self.transcript_col, self.live_box):for c in w.get_children():c.show_all()- self.search_tools.hide() # until there is a query+ self.search_tools.hide()self.connect("key-press-event", self._key)self.connect("focus-out-event", lambda *_: self._take_keys(False) or False)@@ -260,7 +230,7 @@ class NotesWindow(Gtk.Window):if not self._built:self._build()ctx = self.panel.get_style_context()- if self.dark or self.subtitles: # the subtitle bar is dark, as on the Mac+ if self.dark or self.subtitles:ctx.add_class("dark")else:ctx.remove_class("dark")@@ -268,7 +238,6 @@ class NotesWindow(Gtk.Window):self._fill_live()self._fill_speak()if self.subtitles:- # Back to the text's height when a shorter line follows a long one (the bottom stays put).self.resize(self.get_size()[0], 1)if self.body is not None:self._layout()@@ -311,7 +280,6 @@ class NotesWindow(Gtk.Window):h.pack_end(ui.icon_button("view-dual-symbolic", L("收窄") if self.wide else L("纪要和原话并排"),lambda: self.set_wide(not self.wide), "on" if self.wide else "", focus=False), False, False, 0)if self.subtitles and self.app.ending is not None:- # The subtitle bar has no room for buttons: it says what will happen (the Mac's notice).p = self.app.endingnote = ui.text(self.app.ending_title(p) + " · " + LF("%lld 秒后结束", self.app.ending_left(p)), 12, "accent", wrap=False)h.pack_start(note, False, False, 8)@@ -319,8 +287,6 @@ class NotesWindow(Gtk.Window):self._fill_source()def _fill_source(self) -> None:- """麦克风 under the header (the Mac's 打开麦克风 beside 结束: here the header's mic icon is- 同声传译's): what the mic does now, and the button that turns it on or off."""row = self.source_rowui.clear(row)listen = self.app.listen@@ -336,13 +302,9 @@ class NotesWindow(Gtk.Window):row.pack_start(line, False, False, 0)for c in row.get_children():c.show_all()- row.show() # show_all() skips a no_show_all widget itself-- # 纪要 / 文字记录, side by side+ row.show()def _layout(self) -> None:- """What shows below the header: both columns when wide, else the chosen tab; the live- caption only under the notes."""session = self._session()heard = len(session.lines) if session else 0labels = {"notes": L("纪要"),@@ -365,7 +327,7 @@ class NotesWindow(Gtk.Window):if button.get_active():self.set_tab(value)elif value == self.tab:- button.set_active(True) # a segmented control: clicking the chosen tab keeps it+ button.set_active(True)def set_tab(self, tab: str) -> None:if tab not in ("notes", "transcript"):@@ -383,15 +345,13 @@ class NotesWindow(Gtk.Window):w = 820 if wide else 400self.set_size_request(w, 260)self.resize(w, self.get_size()[1])- self.move(max(0, x + w0 - w), y) # it grows to the left, keeping its right edge+ self.move(max(0, x + w0 - w), y)self.render()def _session(self):sid = self.app.listen.session_idreturn self.app.store.get(sid) if sid else None- # The search in the transcript-def _search_row(self) -> Gtk.Widget:self.search = Gtk.Entry()self.search.set_placeholder_text(L("搜索文字记录"))@@ -399,8 +359,6 @@ class NotesWindow(Gtk.Window):ui.classes(self.search, "search", "notes-search")self.search.connect("changed", self._searched)self.search.connect("activate", lambda *_: self.step(1))- # The window never takes focus, so typing in here needs it for a moment (as the Mac makes its- # panel key for a search): from the click until Esc, or until the pointer goes elsewhere.self.search.connect("button-press-event", lambda *_: self._take_keys(True) or False)self.count = ui.text("", 12, "tertiary", wrap=False, ellipsize=False)self.prev_b = ui.icon_button("go-up-symbolic", L("上一个"), lambda: self.step(-1), px=13, focus=False)@@ -475,10 +433,9 @@ class NotesWindow(Gtk.Window):names = speakers.names(session) if voices else {}pending = self.app.listen.listening and self.app.listen.pending > 0topics = [(t.start, t.title) for t in self.app.notes.notes.topics]- self._places = roommic.heard_both(lines) # 电脑和会议室: each of their lines says where+ self._places = roommic.heard_both(lines)key = (self._places, len(lines), lines[-1].id if lines else None, (lines[-1].dst or "") if lines else "", tuple(terms), current,tuple(sorted(nums.items())), tuple(sorted(names.items())), pending, tuple(topics),- # 改正听错的词: any line's fixes changing (a fix in, 改回, 对) redraws it.tuple((l.id, tuple((f.from_, f.to, f.ask, f.off, f.user) for f in l.fixes)) for l in lines if l.fixes))self._newest = lines[-1].id if lines and self.app.listen.listening else Noneself._fill_search_tools()@@ -507,11 +464,8 @@ class NotesWindow(Gtk.Window):live = ui.hbox(6, ui.text("•••", 11, "accent", wrap=False, ellipsize=False), ui.text(L("正在识别…"), 11, "tertiary", wrap=False))box.pack_start(live, False, False, 0)box.show_all()- # After the new rows are laid out: to the current match, to the newest line while listening- # (it follows what's said), else where the reader was.if target is not None and scroll:def to_match():- # PyGObject gives (x, y), or None when they share no toplevel.pos = target.translate_coordinates(box, 0, 0)if pos is not None:adj.set_value(max(0, pos[1] - adj.get_page_size() / 3))@@ -524,7 +478,6 @@ class NotesWindow(Gtk.Window):def _laid_out(self, *_):fn, self._after_layout = self._after_layout, Noneif fn is not None:- # Once now and once more when a column that just appeared (并排) has its final height.GLib.idle_add(lambda: fn() and False)GLib.timeout_add(150, lambda: fn() and False)@@ -556,8 +509,6 @@ class NotesWindow(Gtk.Window):applied = [(l.id, f) for f in l.fixes or [] if f.applied]if not applied:return row- # 改正听错的词: pointing at the line shows what each fixed word was heard as, with 改回. The newest- # line shows it open too: hover in a window that never takes focus is not to be counted on.sid = self._session().iddef revert(line_id, fix):@@ -567,7 +518,7 @@ class NotesWindow(Gtk.Window):if l.id == getattr(self, "_newest", None):return rowwords.set_no_show_all(True)- for c in words.get_children(): # ready, so show() alone reveals them+ for c in words.get_children():c.show_all()hover = Gtk.EventBox()hover.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK)@@ -581,19 +532,13 @@ class NotesWindow(Gtk.Window):hover.connect("leave-notify-event", left)return hover- # 改正听错的词-def _fill_fix(self) -> None:- """这样改对吗?: a name sound can't check, asked about once, clicks only (the window never takes- focus). 对 fixes every line waiting on it and adds it to 词表; × asks again after the meeting.- The Mac hides it while the window is shown to the other side; Linux can't keep the window out- of a share (the footer says so), so it is always shown. Then the last decision, with 撤销."""session = self._session()fx = self.app.fixesa = fx.asking(session.id) if session is not None else Nonetoast = fx.toast_text()key = (session.id if session else None, a[1].from_ if a else None, a[1].to if a else None, a[3] if a else 0,- a[0].id if a else None, fx.toast if toast else None, fx.can_undo) # the toast with its time+ a[0].id if a else None, fx.toast if toast else None, fx.can_undo)if key == getattr(self, "_fix_key", None):returnself._fix_key = key@@ -602,10 +547,9 @@ class NotesWindow(Gtk.Window):self.fix_box.pack_start(self._fix_card(session.id, *a), False, False, 0)if toast:self.fix_box.pack_start(ui.fix_toast(fx, toast), False, False, 0)- # Gone once its time is up.GLib.timeout_add(int(1000 * (live_fixes.TOAST_SECONDS + 0.2)), lambda: self.refresh() and False)self.fix_wrap.set_visible(a is not None or bool(toast))- for c in self.fix_box.get_children(): # show_all() stops at a no_show_all box+ for c in self.fix_box.get_children():c.show_all()def _fix_card(self, sid, line, fix, _position, of) -> Gtk.Widget:@@ -632,16 +576,11 @@ class NotesWindow(Gtk.Window):False, False, 0)return ui.panel(ui.pad(ui.vbox(8, head, row), 10, 12), "fixcard")- # Ending by itself-def _names(self) -> dict:from ..core.support import TARGETSreturn {code: name for name, code in TARGETS}def _fill_languages(self) -> None:- """While live: "English → 简体中文" (what they speak → the notes' language), which opens this- meeting's choice in place, not a popup (the window never takes focus). After the meeting: the- notes once more in the other language, when the meeting wasn't in mine."""listen = self.app.listennames = self._names()name = lambda c: names.get(c, c) # noqa: E731@@ -661,7 +600,6 @@ class NotesWindow(Gtk.Window):self._lang_key = keyui.clear(self.lang_box)if live:- # 12 px grey and underlined, as on the Mac: a quiet way in, not a button.link = Gtk.Button()label = ui.text((name(heard) if heard else L("自动")) + " → " + name(listen.notes_code(s.id)), 12, "secondary", wrap=False)label.set_markup(label.get_label().replace("<span ", '<span underline="single" ', 1))@@ -700,15 +638,12 @@ class NotesWindow(Gtk.Window):listen.notes_for[sid] = choicenotes.generate(sid)GLib.timeout_add(150, lambda: self.refresh() or False)- # A Latin name gets spaces in Chinese ("改用 English 重新整理"), unlike the Mac's one key;- # a Chinese one doesn't ("改用简体中文重新整理"). Both translate alike.label = name(other[1])spaced = label[:1].isascii()b = ui.button(LF("改用 %@ 重新整理" if spaced else "改用%@重新整理", label), again, "outline")b.set_can_focus(False)b.set_halign(Gtk.Align.START)self.lang_box.pack_start(b, False, False, 0)- # The box itself is no_show_all (it hides with the tabs), so show_all() on it does nothing.for c in self.lang_box.get_children():c.show_all()@@ -717,8 +652,6 @@ class NotesWindow(Gtk.Window):self._fill_languages()def _ask_end(self) -> None:- """结束 in the header (the Mac's askToEnd): nothing said yet just stops; otherwise the question- goes in the window, never a dialog, which would take the focus from the meeting."""if self.subtitles:self.app.request_stop()elif self.app.recorded() is None:@@ -734,9 +667,6 @@ class NotesWindow(Gtk.Window):self.app.stop_listening()def _fill_ending(self) -> None:- """已经 10 分钟没人说话 · 60 秒后结束 (MeetingEndingStrip): what will happen, and 继续记录 / 现在结束;- under it 结束这场会议? when 结束 was pressed. No timeout on the question: a strip that went- away under the pointer would let the click land on the notes."""if getattr(self, "ending_wrap", None) is None:returnlistening = self.app.listen.listening@@ -778,7 +708,7 @@ class NotesWindow(Gtk.Window):ui.retext(self._confirm_detail, LF("已记录 %@ · %lld 句。结束后停止收听,并整理一份完整版纪要。", clock(rec[0]), rec[1]))def _state_card(self, box, icon_name, tone, title, body, action=None, on_action=None) -> None:- self._state_shown = True # a state (waiting, no network…) sits on a light card, not the dark caption+ self._state_shown = Truerow = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)row.pack_start(ui.icon_tile(icon_name, 34, 16, tone), False, False, 0)texts = ui.vbox(1)@@ -799,8 +729,6 @@ class NotesWindow(Gtk.Window):return ling.check_result.reason if ling.has_key else Nonedef shows_problem(self, reason) -> bool:- """Whether this window, as it is laid out, says what's wrong (then no notification): the- subtitle bar and the live card only what stops hearing; the notes column the rest."""if not problem.blocking(reason) and reason != "unreachable":return Trueif self.subtitles or getattr(self, "body", None) is None:@@ -812,13 +740,11 @@ class NotesWindow(Gtk.Window):ui.clear(box)listen = self.app.listensession = self.app.store.get(listen.session_id) if listen.session_id else None- # What they said: my own sentences show in the 同声传译 strip below, not twice.theirs = [l for l in session.lines if l.speaker != "me"] if session else []line = theirs[-1] if theirs else Nonekind = listen.problem_kindself._state_shown = Falseif kind == "source":- # Saved only if something was heard before the audio service went away.body = L("音频服务已断开,本次会议记录已保存") if session is not None and session.lines else L("没能开始听")self._state_card(box, "audio-volume-muted-symbolic", "warn", listen.problem or L("系统声音中断"), body, L("开始听"),self.app.toggle_listening)@@ -831,8 +757,6 @@ class NotesWindow(Gtk.Window):self._state_card(box, "dialog-password-symbolic", "warn", listen.problem or L("Ling key 无效"),L("在设置里更换 Ling key") if ling else L("在 设置 › AI 服务 里换一个"), L("设置"), self.app.show_settings)elif problem.stops_hearing(self._reason()) and kind not in ("network", "busy"):- # Nothing is heard until it's fixed (no credit, a bad address…): said where the subtitles- # would be, with the way to fix it, not "等有人说话".from .aicheck_view import blocking, blocking_detailself._state_card(box, "dialog-warning-symbolic", "warn", blocking(self.app), blocking_detail(self.app),L("设置"), lambda: self.app.show_settings(ai=True))@@ -840,8 +764,6 @@ class NotesWindow(Gtk.Window):if listen.listening:hearing = listen.pending > 0 or listen.level >= 0.01room = listen.source_kind == "room"- # Busy or erring before anything was heard: said here, or it reads as a quiet meeting.- # In the wrapping line, not the one-line title, which would cut it off.trouble = listen.problem if kind == "busy" else Noneself._state_card(box, "audio-input-microphone-symbolic" if room else "audio-speakers-symbolic", "grey",L("正在识别…") if hearing else L("等有人说话"),@@ -852,7 +774,6 @@ class NotesWindow(Gtk.Window):L("点“开始听”,将电脑播放的声音转为双语字幕和纪要"))else:big = 22 if self.subtitles else 15- # 说话人识别: who said it, once voices are told apart ("说话人 2", or the name given).if self.app.settings.speakerVoices and session is not None and session.sourceFile is None:nums = speakers.numbers(session.lines)if line.id in nums:@@ -878,7 +799,6 @@ class NotesWindow(Gtk.Window):box.show_all()def _fill_speak(self) -> None:- """同声传译: where my sentence is (听 → 翻译 → 说), what I said and what they hear."""box = self.speakboxsp = self.app.speakshow = self.app.settings.speakEnabled and (sp.active or sp.last is not None or sp.problem is not None)@@ -888,7 +808,6 @@ class NotesWindow(Gtk.Window):returnfrom ..core.support import TARGETSnames = {c: n for n, c in TARGETS}- # Marked 同传 while on, as the Mac's live labels (theirs end in spaces for the text after them).stage = {"hearing": L("同传 · 你在说… ").rstrip(), "interpreting": L("同传 · 翻译中… ").rstrip(),"speaking": L("同传") + " · " + L("正在说") + " · " + names.get(sp.target, sp.target)}.get(sp.stage, L("同声传译"))top = ui.hbox(8)@@ -918,17 +837,12 @@ class NotesWindow(Gtk.Window):ui.retext(self.footer_time, L("刚刚更新") if ago < 10 else LF("%lld 秒前更新", ago) if ago < 60 else LF("%lld 分钟前更新", ago // 60))def _banner(self, body, engine) -> None:- """Why the notes stopped, above them, notes or not (the Mac's banner): one status line for a- dead key, a busy or unreachable service, or a round that failed; each says what waits and- what still works."""s = self._session()covered = engine.notes.coveredlast = s.lines[covered - 1].t if s is not None and 0 < covered <= len(s.lines) else 0.0reason = self._reason()ling = self.app.ling- # Who the line names: a custom service by its address, which says more than 这个服务.name = ling.service_label- # All but the key are about a round of the meeting going on now: a record opened later has none.live = self.app.listen.listeningstatus = engine.statusaction = on_action = None@@ -937,7 +851,6 @@ class NotesWindow(Gtk.Window):text = LF("key 失效了 · 纪要停在 %@", clock(last)) if last > 0 else L("key 失效了 · 纪要等新的 key")action, on_action = L("换 key"), lambda: self.app.show_settings(ai=True)elif problem.blocking(reason) and (reason in problem.NOTES_ONLY or not self.live_box.get_visible()):- # Only the user can fix it (the live card says it too, when it shows): what, and 打开设置.from .aicheck_view import blocking, blocking_detailrow = ui.hbox(10)row.pack_start(ui.vbox(2, ui.text(blocking(self.app), 12, "ink", bold=True, width_chars=24),@@ -949,21 +862,12 @@ class NotesWindow(Gtk.Window):body.pack_start(ui.pad(ui.panel(ui.pad(row, 12), "notice", "error"), 0, 0, 10, 0), False, False, 0)returnelif live and self.app.translator.google_off and self.app.translator.sentences_untranslated:- # 语音和文字只发给你的服务, and the service didn't translate the last sentence: it picks up- # by itself, and no 改用 Ling, which would send the meeting elsewhere.notes_wait = status in (notesmod.UNREACHABLE, notesmod.UPDATING) and ling.check_result.reason == "unreachable"tone = "waiting"text = LF("译文和纪要等 %@ 恢复 · 字幕先显示原文", name) if notes_wait else LF("译文等 %@ 恢复 · 字幕先显示原文", name)elif status == notesmod.RATE_LIMITED and live:- # A 429 holds hearing at the start gate and its retries wait it out: subtitles come late- # for a moment, not lost; the live card says so if hearing itself stays busy.tone, text = "waiting", LF("%@ 很忙 · 纪要稍后补上,字幕照常", name)elif status in (notesmod.UNREACHABLE, notesmod.UPDATING) and live and ling.check_result.reason == "unreachable":- # The network or the proxy, not the notes: it picks up by itself. Both: the notes' own- # request failed and the service answers nothing (notes that only timed out while- # translations came back retry next round). The retry that follows (UPDATING) hangs as- # long as a timeout: the line stays meanwhile. The service hears the meeting here, so the- # subtitles wait too.tone, text = "waiting", LF("字幕和纪要等 %@ 恢复 · 连上后自动继续", name)if self.app.can_switch_to_ling():action, on_action = L("改用 Ling"), self.app.switch_to_ling@@ -974,8 +878,6 @@ class NotesWindow(Gtk.Window):body.pack_start(ui.pad(ui.status_line(tone, text, action, on_action), 0, 0, 10, 0), False, False, 0)def _listening_view(self) -> Gtk.Widget:- """NotesListeningView: one quiet status row, then the notes' own shape waiting to be filled, so- the first version lands where the reader is already looking."""view = ui.vbox(22)row = ui.hbox(12, ui.sound_bars())row.pack_start(ui.text(L("有人开口后,约半分钟出第一版"), 13, "ink", width_chars=20), True, True, 0)@@ -1000,7 +902,6 @@ class NotesWindow(Gtk.Window):card.set_opacity(opacity)topics.pack_start(card, False, False, 0)view.pack_start(topics, False, False, 0)- # Wraps: the English chips don't fit one line in the narrow window.flow = ui.Wrap(6)flow.add(ui.pad(ui.text(L("会整理出"), 12, "tertiary", wrap=False, ellipsize=False), 4, 0))for t in (L("结论"), L("待办"), L("人名和术语"), L("鱼骨图")):@@ -1013,12 +914,9 @@ class NotesWindow(Gtk.Window):engine = self.app.notesn = engine.noteslistening = self.app.listen.listening- # The Mac's notesPane: notes; else the key; else a request actually out; else, while listening,- # the placeholder, which stays up after lines arrive until that first request goes out.session = self._session()generating = engine.status == notesmod.UPDATING and (session is None or engine.working_id == session.id)placeholder = n.is_empty and listening and not generating and engine.status not in (notesmod.NO_KEY, notesmod.INVALID_KEY)- # Kept across rebuilds (one per heard line) so its CSS animations don't start over.keep = getattr(self, "_listening", None) if placeholder else Nonefor c in body.get_children():if c is not keep:@@ -1031,7 +929,7 @@ class NotesWindow(Gtk.Window):self._listening = self._listening_view()body.pack_start(self._listening, False, False, 0)else:- body.reorder_child(keep, -1) # below the banner+ body.reorder_child(keep, -1)heard = len(session.lines) if session is not None else 0ui.retext(self._heard, LF("已听到 %lld 句", heard) if heard else "")self._heard.set_visible(heard > 0)@@ -1041,7 +939,7 @@ class NotesWindow(Gtk.Window):hint = {notesmod.NO_KEY: L("生成纪要需要 API key"),notesmod.UPDATING: L("正在整理纪要…")}.get(engine.status, "")if engine.status in (notesmod.INVALID_KEY, notesmod.RATE_LIMITED, notesmod.FAILED, notesmod.UNREACHABLE):- hint = "" # the banner says it+ hint = ""if hint:body.pack_start(ui.helper(hint), False, False, 0)body.show_all()diff --git a/linux/cicada/app/onboarding.py b/linux/cicada/app/onboarding.pyindex 53dbce6..92fddbc 100644--- a/linux/cicada/app/onboarding.py+++ b/linux/cicada/app/onboarding.py@@ -1,8 +1,3 @@-"""First run, the Mac's four steps (Onboarding.swift, canvas 知了 Linux · 补齐 Mac): the logo and a-labelled progress bar, a large left-aligned title, white cards, the next action bottom right; then a-closing page outside the count. One difference in order: Linux recognises speech with Ming, so nothing-works without the Ling key, and 接 Ling comes first (the Mac puts it third). So: Ling key → system audio-(no permission on Linux) → sample meeting → 同声传译, if wanted → where Cicada lives."""from __future__ import annotationsimport os@@ -29,8 +24,6 @@ class Onboarding(Gtk.Window):def __init__(self, app, step: int | None = None):super().__init__(title=L("知了"))self.app = app- # Fixed at the Mac's 860 x 640. Not set_resizable(False): GTK then sizes the window to its- # content's natural width, so wrapped (English) text would widen it instead of wrapping.geometry = Gdk.Geometry()geometry.min_width = geometry.max_width = 860geometry.min_height = geometry.max_height = 640@@ -43,8 +36,6 @@ class Onboarding(Gtk.Window):self.set_titlebar(bar)outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)ui.pad(outer, 6, 64, 36, 64)- # The page's real width as its minimum: GTK 3 sizes a window for its content at the content's- # minimum width, where every wrapped line wraps most, so the fixed 640 would be outgrown.outer.set_size_request(860 - 128, -1)self.head = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=14)outer.pack_start(self.head, False, False, 0)@@ -58,13 +49,13 @@ class Onboarding(Gtk.Window):self.levels = deque([0.0] * 8, maxlen=8)self.peak = 0.0self.meter = None- self.speak_setup = None # 同声传译: None until chosen here (then True / False)+ self.speak_setup = Noneself.connect("destroy", lambda *_: self._stop_tap())self.connect("key-press-event", self._key)self.step = step if step is not None and (step == KEY or app.ling.has_key) else AUDIO if app.ling.has_key else KEY- self.testing = None # 放一段测试声音: the player while it plays- self.tested = False # a test sound played and nothing was heard- self.device = None # the default output's name, once pactl has said it+ self.testing = None+ self.tested = False+ self.device = Noneself.render()def _key(self, _w, event) -> bool:@@ -90,18 +81,14 @@ class Onboarding(Gtk.Window):self._header()[self._key_step, self._audio_step, self._sample_step, self._speak_step, self._done_step][self.step]()self.show_all()- self.resize(860, 640) # back to the fixed size if a step's content asked for more+ self.resize(860, 640)def refresh(self) -> None:- """Engine changes (the sample being heard, 知了 麦克风 made, the key checked): only the step- that shows them."""if self.step == SAMPLE:GLib.idle_add(lambda: self._fill_sample() and False)elif self.step == KEY:GLib.idle_add(lambda: self._fill_key_steps() and False)- # Frame-def _header(self) -> None:self.head.pack_start(self.app_logo(34), False, False, 0)if self.step == DONE:@@ -167,7 +154,7 @@ class Onboarding(Gtk.Window):def _primary(self, text: str, action, arrow: bool = True, enabled: bool = True) -> Gtk.Button:b = ui.button(text, action, "bigbtn" if enabled else "bigbtn waiting", "go-next-symbolic" if arrow else None)- if arrow: # the arrow after the words, as on the Mac+ if arrow:box = b.get_child()img = box.get_children()[0]box.reorder_child(img, 1)@@ -182,8 +169,6 @@ class Onboarding(Gtk.Window):img = ui.icon("object-select-symbolic", 14)return ui.hbox(6, img, ui.text(text, 13, "ink", bold=True, wrap=False, ellipsize=False))- # 1. Ling key-def _key_step(self) -> None:if self.app.settings.aiProvider != "ling":self._other_step()@@ -239,7 +224,6 @@ 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)@@ -250,8 +234,6 @@ class Onboarding(Gtk.Window):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 providersp = providers.named(self.app.settings.aiProvider)self._title(L("用其他服务"), L("听、纪要和翻译都能用,模型已经选好。"))@@ -288,17 +270,15 @@ class Onboarding(Gtk.Window):GLib.idle_add(lambda: entry.grab_focus() and False)def _key_extras(self, width: int) -> None:- """Under the key field: a pasted key that belongs elsewhere, and the check step by step."""self.key_hint = ui.hbox(8)- self.key_hint.set_no_show_all(True) # no gap while empty- self.key_status.set_no_show_all(True) # shown when it has something to say+ self.key_hint.set_no_show_all(True)+ self.key_status.set_no_show_all(True)self.key_status.set_visible(False)self.key_steps = ui.vbox(0)self.key_steps_width = widthself._steps_shown = Nonedef _fill_key_steps(self) -> None:- """Where it broke and the one thing that fixes it, as in the settings; 继续 stays open."""from . import aicheck_viewling = self.app.lingr = ling.check_result@@ -380,7 +360,6 @@ class Onboarding(Gtk.Window):if not text.startswith("sk-"):self._key_problem(L("复制 sk- 开头的 key,回来粘贴"))return- # The prefix says whose key it is (AISettingsView.save does the same): never a silent switch.from . import aicheck_viewhint = aicheck_view.key_hint(self.app, text)self._key_hint(hint, text)@@ -408,8 +387,6 @@ class Onboarding(Gtk.Window):GLib.idle_add(done)threading.Thread(target=check, daemon=True).start()- # 2. System audio-def _audio_step(self) -> None:self._title(L("让知了听到电脑里的声音"), L("会议里对方说的话从电脑放出来,字幕和纪要都从这里来。不用麦克风,也不用授权。"))if self.device is None:@@ -436,7 +413,7 @@ class Onboarding(Gtk.Window):self.heard_row = ui.hbox(6)trailing = ui.hbox(12, meter, self.heard_row)source = self._row("audio-speakers-symbolic", L("电脑播放的声音"), self._device_line(), trailing)- self.device_label = source.get_children()[1].get_children()[1] # the row's detail line+ self.device_label = source.get_children()[1].get_children()[1]test = ui.button(L("正在播放…") if self.testing else L("放一段测试声音"), self._play_test, "accentbtn midbtn","media-playback-start-symbolic")test.set_sensitive(self.testing is None)@@ -447,19 +424,17 @@ class Onboarding(Gtk.Window):test.set_valign(Gtk.Align.CENTER)test_row.pack_end(test, False, False, 0)self._card(source, ui.pad(test_row, 16, 22))- # The two sounds side by side: people try speaking first, but this step hears the computer.sources = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12, homogeneous=True)sources.pack_start(self._source(L("对方的声音"), L("这一步"), [L("会议软件"), L("扬声器"), L("知了:字幕和纪要")], True), True, True, 0)sources.pack_start(self._source(L("你的声音 · 麦克风"), L("第 4 步再用"), [L("麦克风"), L("同声传译"), L("线上的人听到译文")], False), True, True, 0)self.page.pack_start(ui.gap(sources, 12), False, False, 0)self.sources = sources- sources.set_no_show_all(True) # _fill_silent decides, not the window's show_all- # Played and still nothing: most likely the sound goes to another output (an HDMI screen).+ sources.set_no_show_all(True)self.silent = Gtk.Box()self.page.pack_start(ui.gap(self.silent, 12), False, False, 0)self._fill_silent()self._back()- self.audio_hint = Gtk.Box() # 放一段测试声音 says what the old 音量条没动? hint said+ self.audio_hint = Gtk.Box()self.footer.pack_start(self.audio_hint, True, True, 0)self.audio_next = Gtk.Box()self.footer.pack_end(self.audio_next, False, False, 0)@@ -470,28 +445,23 @@ class Onboarding(Gtk.Window):if self.step != AUDIO:self.meter = Nonereturn False- for bar, level in zip(self.bars, list(self.levels)): # the capture thread appends meanwhile+ for bar, level in zip(self.bars, list(self.levels)):v = ui.loudness(level)bar.set_size_request(3, max(3, int(v * 18)))self._update_heard()return Truedef _source(self, title: str, badge: str, flow: list, on: bool) -> Gtk.Widget:- """One of the two sounds and where it goes, outlined in ink when it is this step's."""head = ui.hbox(8, ui.text(title, 14, "ink", bold=True, wrap=False),ui.panel(ui.text(badge, 11, "", bold=on, wrap=False, ellipsize=False), "badge" if on else "srcbadge"))- # One wrapping label, each step on a tinted ground (the last in ink when it is this step's):- # GTK 3 sizes a FlowBox for its narrowest layout, which would stretch the fixed-size window.words = []for i, word in enumerate(flow):last = on and i == len(flow) - 1words.append('<span background="%s" foreground="%s">\u00a0%s\u00a0</span>'% ("#15171C" if last else "#F3F4F6", "#FFFFFF" if last else "#15171C",- GLib.markup_escape_text(word).replace(" ", "\u00a0"))) # breaks only between steps+ GLib.markup_escape_text(word).replace(" ", "\u00a0")))path = ui.text("", 12, "", width_chars=36)path.set_markup('<span size="%d">%s</span>' % (round(12 * 768), ' <span foreground="#5A5F6B">→</span> '.join(words)))- # Whole words only: WORD_CHAR's one-character minimum width makes GTK 3 ask for a window as- # tall as the text would be one letter wide.path.set_line_wrap_mode(Pango.WrapMode.WORD)return ui.panel(ui.pad(ui.vbox(8, head, path), 12, 16, 10, 16), "srccard", "on" if on else "")@@ -499,14 +469,11 @@ class Onboarding(Gtk.Window):return LF("%@ · 只听声音,不录屏幕画面", self.device) if self.device else L("只听声音,不录屏幕画面")def _find_device(self) -> None:- """The default output's name ("内置音频 模拟立体声") through pactl, off the main loop; none- without pactl (the row then says only what it hears)."""name = Noneif shutil.which("pactl"):env = dict(os.environ, LC_ALL="C")try:sink = subprocess.run(["pactl", "get-default-sink"], capture_output=True, text=True, timeout=3, env=env).stdout.strip()- # Descriptions in the desktop's language: pactl translates them under LANG.sinks = subprocess.run(["pactl", "list", "sinks"], capture_output=True, text=True, timeout=3,env=dict(os.environ, LC_MESSAGES="C")).stdoutname = sink_description(sinks, sink)@@ -521,8 +488,6 @@ class Onboarding(Gtk.Window):GLib.idle_add(show)def _play_test(self) -> None:- """放一段测试声音: the sample's first 3 s through the default output, the device Cicada hears:- the bars move only if the sound really reaches the monitor."""from .main import sample_pathpath = sample_path()player = next((p for p in ("pw-play", "paplay", "aplay") if shutil.which(p)), None)@@ -545,7 +510,7 @@ class Onboarding(Gtk.Window):if self.step != AUDIO:return False- def settle(): # the last buffers arrive a moment after the player stops+ def settle():if self.step != AUDIO:return Falseself.tested = self.peak < 0.01@@ -558,12 +523,11 @@ class Onboarding(Gtk.Window):return Falsedef _fill_silent(self) -> None:- """The warning takes the two sounds' place, so the window keeps its fixed size."""ui.clear(self.silent)if self.tested:self.sources.hide()else:- for child in self.sources.get_children(): # show_all() skips a no_show_all widget+ for child in self.sources.get_children():child.show_all()self.sources.show()if not self.tested:@@ -576,7 +540,6 @@ class Onboarding(Gtk.Window):row.pack_start(ui.vbox(2, ui.text(L("测试声音放了,但知了没听到"), 14, "ink", bold=True, wrap=False),ui.text(L("看看声音是不是从别的设备出来(比如 HDMI 显示器),或被静音了。"), 13, "ink", width_chars=50)),True, True, 0)- # GNOME's own sound page; other desktops differ, so only there.if "GNOME" in os.environ.get("XDG_CURRENT_DESKTOP", "").upper() and shutil.which("gnome-control-center"):b = ui.button(L("打开声音设置"), lambda: subprocess.Popen(["gnome-control-center", "sound"]), "outline")b.set_valign(Gtk.Align.CENTER)@@ -602,15 +565,12 @@ class Onboarding(Gtk.Window):self.heard_row.pack_start(self._done_mark(L("已收到声音")), False, False, 0)else:self.heard_row.pack_start(ui.text(L("等声音…"), 13, "secondary", wrap=False), False, False, 0)- # 继续 stays grey until sound arrives, as on the Mac, but still works (a quiet machine).self.audio_next.pack_start(self._primary(L("继续"), lambda: self.go(SAMPLE), enabled=True), False, False, 0)if not heard:ui.classes(self.audio_next.get_children()[0], "waiting")self.heard_row.show_all()self.audio_next.show_all()- # 3. Sample-def _sample_step(self) -> None:self._title(L("放一段会议试试"), L("一段 9 秒的英文会议,字幕会跟着声音实时出来。"))self.stage = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)@@ -686,8 +646,6 @@ class Onboarding(Gtk.Window):self.app.setup_step_done("sampleSeen")self._fill_sample()- # 4. 同声传译-def _speak_step(self) -> None:app = self.appon = self.speak_setup if self.speak_setup is not None else app.settings.speakEnabled@@ -762,8 +720,6 @@ class Onboarding(Gtk.Window):set_gnome_shortcut("speak", self.app.launcher + (" --dev" if Paths.dev else "") + " --speak")self.render()- # Closing-def _done_step(self) -> None:tray = self.app.tray is not Noneself._title(L("好了,知了在顶栏") if tray else L("好了,可以开始了"),@@ -789,7 +745,6 @@ class Onboarding(Gtk.Window):self.footer.pack_end(self._primary(L("开始使用"), lambda: self.go(DONE + 1), arrow=False), False, False, 0)def _top_bar(self) -> Gtk.Widget:- """A slice of GNOME's top bar with Cicada's icon ringed: where to look once this window is gone."""bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)bar.set_size_request(-1, 32)act = ui.panel(ui.pad(ui.text(L("活动"), 12, "topbar-ink", wrap=False, ellipsize=False), 2, 10), "topbar-pill")@@ -823,7 +778,7 @@ class Onboarding(Gtk.Window):if self.testing is not None:player, self.testing = self.testing, Noneplayer.terminate()- threading.Thread(target=player.wait, daemon=True).start() # reaped, not left a zombie+ threading.Thread(target=player.wait, daemon=True).start()def _stop_tap(self) -> None:self._stop_test()diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.pyindex d7998a0..b894119 100644--- a/linux/cicada/app/records_window.py+++ b/linux/cicada/app/records_window.py@@ -1,7 +1,3 @@-"""会议记录, the main window: a header bar with 开始听 (or 正在听 · 结束) and the app menu; the-meetings grouped by day and searchable on the left; the chosen meeting's notes and its bilingual-transcript side by side on the right (stacked when the window is narrow). Export and delete answer-with a toast; delete can be undone for a few seconds before the record is really removed."""from __future__ import annotationsimport math@@ -32,40 +28,33 @@ class RecordsWindow(Gtk.Window):self.set_position(Gtk.WindowPosition.CENTER)self.set_wmclass("cicada", "Cicada")self.connect("delete-event", lambda *_: self.close_to_dock() or self.app.records_closed() or True)- # Minimized it isn't refilled on every change of a meeting; it catches up when it comes back.self.iconified = False- self.parked = False # minimized by 知了 to keep its dock icon (Controller.keep_in_dock)+ self.parked = Falseself.connect("window-state-event", self._state_changed)self.connect("hide", lambda *_: setattr(self, "iconified", False) or setattr(self, "parked", False))self.selected = None- self.pending_delete = None # a record deleted but still undoable+ self.pending_delete = Noneself.query = ""- # The search in the shown record (#33: a search opens the line, not just the meeting): its terms- # (misheard names too), the lines found, which one is being looked at.self.match_index = 0self._terms, self._matches, self._match_set, self._current = [], [], set(), None- self.mode = "both" # transcript: "both" or "dst"- self._both = False # the shown meeting has lines I said (同声传译): rows name 你 / 对方- self._nums, self._vnums, self._shown, self._speaker_key = {}, {}, {}, None # 说话人识别 on show+ self.mode = "both"+ self._both = False+ self._nums, self._vnums, self._shown, self._speaker_key = {}, {}, {}, Noneself._queued = False- self.player = None # the shown record's recording (media.Player), while it has one to play+ self.player = Noneself._player_sid = Noneself._dragging = False- self._hl_row = None # the transcript row at the playhead+ self._hl_row = Noneself._hl_line = None- self._bars = None # the bouncing bars on it while playing+ self._bars = Noneself._was_following = Trueself._scroll_anim = None- # 改这句…: the line being rewritten and what its editor opens with; the last fix toast shown.self._editing = Noneself._edit_start = ""self._fix_toast = Nonebar = Gtk.HeaderBar()bar.set_show_close_button(True)- # The title sits over the sidebar; the middle holds the listening capsule, as on the Mac.- # A stack, not a box: the pill cross-fades and changes width between states over 0.35 s, as- # the Mac's spring does, instead of jumping.self.listen_box = Gtk.Stack()self.listen_box.set_transition_type(Gtk.StackTransitionType.CROSSFADE)self.listen_box.set_transition_duration(350)@@ -78,7 +67,7 @@ class RecordsWindow(Gtk.Window):self.bar_side = ui.panel(ui.pad(ui.text(L("会议记录"), 13, "heading", bold=True, wrap=False), 0, 0, 0, 18), "sidebar-top")self.bar_side.set_size_request(260, -1)self.bar_side.get_child().set_valign(Gtk.Align.CENTER)- self.bar_side.set_no_show_all(True) # with the sidebar: hidden while there are no meetings+ self.bar_side.set_no_show_all(True)bar.pack_start(self.bar_side)bar.pack_end(self._app_menu())self.set_titlebar(bar)@@ -90,21 +79,17 @@ class RecordsWindow(Gtk.Window):overlay.add(root)self.add(overlay)- # Sidebarside = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)self.sidebar = ui.panel(side, "sidebar")self.sidebar.set_size_request(260, -1)- self.sidebar.set_no_show_all(True) # fill() decides: hidden while there are no meetings+ self.sidebar.set_no_show_all(True)self.search = Gtk.SearchEntry()self.search.set_placeholder_text(L("搜索标题和对话"))self.search.connect("search-changed", self._searched)- # Enter goes to the next line found, as Ctrl+G does; Shift+Ctrl+G to the one before.self.search.connect("activate", lambda *_: self.step(1))self.search.connect("next-match", lambda *_: self.step(1))self.search.connect("previous-match", lambda *_: self.step(-1))ui.classes(self.search, "search")- # "Ctrl F" at the field's right end while it's empty, as the Mac shows ⌘F; the clear icon- # takes its place once something is typed.search_box = Gtk.Overlay()search_box.add(self.search)hint = ui.text("Ctrl F", 11, "secondary", wrap=False, ellipsize=False)@@ -128,35 +113,25 @@ class RecordsWindow(Gtk.Window):side.show_all()root.pack_start(self.sidebar, False, False, 0)- # Contentself.right = Gtk.ScrolledWindow()self.right.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)self.content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)ui.pad(self.content, 6, 36, 28, 36)self.right.add(self.content)ui.classes(self.right, "sheet")- # Once the title scrolls away, a slim bar over the top of the page keeps the title, 导出…- # and the two columns' names in view (the Mac's pinned bar).- # A plain box shown and hidden: an overlay child takes the clicks under it even while a- # revealer hides its content.self.pinned = Gtk.Box()self.pinned.set_valign(Gtk.Align.START)self.pinned.set_no_show_all(True)page = Gtk.Overlay()page.add(self.right)page.add_overlay(self.pinned)- # Scrolled away from what is playing: one way back (the Mac's 回到正在播放 capsule).self.back_pill = self._back_pill()page.add_overlay(self.back_pill)- # The recording's player bar sits under the page, not in its header: the controls stay while- # the transcript scrolls.self.bottom = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)right_col = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)right_col.pack_start(page, True, True, 0)right_col.pack_start(self.bottom, False, False, 0)root.pack_start(right_col, True, True, 0)- # Only a hand scrolls with the wheel / touchpad or moves the scrollbar; the follower sets the- # adjustment, which emits neither.self.right.connect("scroll-event", self._hand_scrolled)self.right.get_vscrollbar().connect("change-value", self._hand_scrolled)self.top_box = None@@ -165,19 +140,15 @@ class RecordsWindow(Gtk.Window):self.connect("size-allocate", self._resized)self.connect("key-press-event", self._key)self._tick = GLib.timeout_add_seconds(1, self._clock)- # Closed: the recording stops; it is set up again when the window is next shown.self.connect("hide", lambda *_: (self._unload_player(), setattr(self, "_built_key", None)))self.fill()def _key(self, _w, event) -> bool:- """Ctrl+F searches (Ctrl+Q and Ctrl+, are app-wide accelerators)."""if event.state & Gdk.ModifierType.CONTROL_MASK and Gdk.keyval_name(event.keyval) in ("f", "F"):self.search.grab_focus()return Truereturn False- # Header bar-def _app_menu(self) -> Gtk.MenuButton:menu = Gtk.Menu()for label, action in ((L("显示实时纪要"), self.app.show_notes), (L("设置…"), self.app.show_settings),@@ -197,11 +168,6 @@ class RecordsWindow(Gtk.Window):return bdef _fill_listen_box(self) -> None:- """The listening switch, led by the logo (ListenPill.swift): a white capsule while idle- (logo, 知了, 开始听 or 会议已自动结束, the shortcut), an ink one while listening (the breathing- logo, 正在听, the level, the time, and 结束), and while the meeting is about to end by itself- a countdown ring round the logo, why, the seconds left and 继续记录. Built once per state;- the time, the level and the countdown update in place."""app = self.applisten = app.listenif listen.listening:@@ -219,7 +185,6 @@ class RecordsWindow(Gtk.Window):box.set_valign(Gtk.Align.CENTER)box.set_halign(Gtk.Align.CENTER)if state == "setup":- # Not set up yet: the capsule says how much is left and opens the onboarding there.b = Gtk.Button()inner = ui.hbox(9, self._logo(22), ui.text(L("知了"), 13, "ink", bold=True, wrap=False, ellipsize=False),ui.panel(Gtk.Box(), "pillsep"),@@ -230,7 +195,6 @@ class RecordsWindow(Gtk.Window):sep.set_valign(Gtk.Align.CENTER)b.add(inner)ui.classes(b, "listenpill")- # A key the check found failing is fixed in 设置 › AI 服务, not in the onboarding.b.connect("clicked", lambda *_: self.app.show_settings(ai=True) if self.app.ling.has_key and not self.app.key_workselse self.app.show_onboarding())b.get_accessible().set_name(L("继续设置"))@@ -300,7 +264,6 @@ class RecordsWindow(Gtk.Window):box.pack_start(self._live_pill(show, keep, ending=True), False, False, 0)box.show_all()stack.add(box)- # The first state appears as is; later ones cross-fade (and the old one goes once faded).stack.set_transition_type(Gtk.StackTransitionType.NONE if first else Gtk.StackTransitionType.CROSSFADE)stack.set_visible_child(box)@@ -320,16 +283,11 @@ class RecordsWindow(Gtk.Window):self._ring.set_from_pixbuf(ui.ring_pixbuf(left / self._ring_total))def _live_pill(self, show: Gtk.Widget, button: Gtk.Widget, ending: bool = False) -> Gtk.Widget:- """The ink capsule: 32 px high, 5 px in on the left and 4 px round the rest (ListenPill).- A plain box, not an EventBox: it honours CSS padding and has no window of its own, so the- breathing rings may run past its edge, as they do on the Mac."""pill = ui.classes(ui.hbox(10, show, button), "listenpill", "live", "ending" if ending else "on")pill.set_valign(Gtk.Align.CENTER)return pilldef _breathing_logo(self, px: int) -> Gtk.Widget:- """BreathingMark: two rings swell out of the logo in turn while Cicada listens."""- # Plain boxes, not panels: an EventBox's own window would clip the ring drawn outside it.inner = ui.classes(ui.hbox(0, self._logo(px)), "breathemark")outer = ui.classes(ui.hbox(0, inner), "breathemark", "late")outer.set_valign(Gtk.Align.CENTER)@@ -342,21 +300,18 @@ class RecordsWindow(Gtk.Window):if path:try:from gi.repository import GdkPixbuf- # A pixbuf, not a cairo surface: stock Ubuntu has no python3-gi-cairo.return Gtk.Image.new_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_size(path, px, px))except GLib.Error:passreturn ui.dot(True)def _shortcut_hint(self) -> str:- """The start / stop shortcut, when one is set ("Super ⇧ C", as the Mac shows ⌘R)."""from .settings_window import SHORTCUTS, gnome_shortcutif not gnome_shortcut("toggle"):return ""return SHORTCUTS["toggle"][2].replace(" + Shift + ", " ⇧ ")def _meter(self) -> bool:- """The level of what Cicada hears, newest on the right (LevelMeter): 8 bars, 15 px high."""if self._pill_state[0] != "live" or not self.app.listen.listening:return Falseself._levels = (self._levels + [ui.loudness(self.app.listen.level)])[-8:]@@ -370,7 +325,6 @@ class RecordsWindow(Gtk.Window):return Truedef close_to_dock(self) -> None:- """✕: hidden, or with 在 Dock 中显示 on, minimized: the dock lists 知了 only while it has a window."""if self.app.settings.showInDock:self.parked = Trueself.iconify()@@ -381,25 +335,18 @@ class RecordsWindow(Gtk.Window):if event.changed_mask & Gdk.WindowState.ICONIFIED and not event.new_window_state & Gdk.WindowState.WITHDRAWN:self.iconified = bool(event.new_window_state & Gdk.WindowState.ICONIFIED)if not self.iconified:- self.refresh() # back from the dock: what changed while it was minimized- # Mapped minimized, Mutter flicks it to normal and back within a few ms: only a- # window still up a moment later was brought back (by the dock, or Alt+Tab).+ self.refresh()GLib.timeout_add(200, self._restored)return Falsedef _restored(self) -> bool:if self.parked and not self.iconified and self.get_mapped() and self.is_active():self.parked = False- # Mapped minimized, it isn't drawn when it comes back (seen with the notes window up):- # presenting it, which it already is (active: the WM brought it back, not the flick),- # gets it drawn.self.present()self.set_focus(None)Log.d("dock: records window brought back")return False- # List-def refresh(self) -> None:if self._queued:return@@ -484,7 +431,7 @@ class RecordsWindow(Gtk.Window):def _searched(self, entry) -> None:if entry.get_text() == self.query:- return # SearchEntry's delayed signal for text already searched: keep the line being looked at+ returnself.query = entry.get_text()self.match_index = 0self.fill()@@ -501,10 +448,7 @@ class RecordsWindow(Gtk.Window):if self.query.strip():self._apply_search(scroll=True)- # The search in the shown record-def _match_bar(self) -> Gtk.Widget:- """Where the search is in the shown record: 本场 2 / 7, and a way to the previous and next line."""self.match_count = ui.text("", 12, "secondary", wrap=False, ellipsize=False)bar = ui.hbox(2)bar.pack_start(self.match_count, True, True, 0)@@ -524,7 +468,6 @@ class RecordsWindow(Gtk.Window):self.match_bar.set_visible(on)def _search_state(self, s) -> None:- """The search's terms and the lines it finds in `s` (none while there is no query or record)."""self._terms = transcript_search.terms(self.query, s.notes.terms if s.notes else []) if s is not None else []self._matches = transcript_search.matches(s.lines, self._terms) if s is not None else []self._match_set = set(self._matches)@@ -541,7 +484,6 @@ class RecordsWindow(Gtk.Window):self._apply_search(scroll=True)def _apply_search(self, scroll: bool) -> None:- """Marks the shown record's lines for the search; with `scroll`, goes to the line being looked at."""s = self.app.store.get(self.selected) if self.selected else Noneif s is None or self.columns is None or getattr(self, "_sid", None) != s.id:self._search_state(None)@@ -551,14 +493,11 @@ class RecordsWindow(Gtk.Window):if not scroll or self._current is None:returnidx = next(i for i, l in enumerate(s.lines) if l.id == self._current)- self._more_rows_until(idx + 1) # the batches may not have got that far yet+ self._more_rows_until(idx + 1)row = self._rows[idx][1]- # Once the rows just built are laid out, and again once a long page has its final height.GLib.idle_add(lambda: self._centre(row) or False)GLib.timeout_add(200, lambda: self._centre(row) or False)- # Detail-def _resized(self, _w, alloc) -> None:if self.columns is not None:want = Gtk.Orientation.HORIZONTAL if alloc.width >= 1000 else Gtk.Orientation.VERTICAL@@ -571,8 +510,6 @@ class RecordsWindow(Gtk.Window):pinned_heads = Nonedef _pinned_bar(self, s) -> Gtk.Widget:- """The title (a click goes back to the top), 导出… and ⋯; under them, side by side, the two- columns' names, so a long scroll still says which side is the notes."""title = Gtk.Button()ui.classes(title, "flat", "pinned-title")self.pinned_title = ui.text(session_store.display_title(s), 14, "heading", bold=True, wrap=False)@@ -589,8 +526,6 @@ class RecordsWindow(Gtk.Window):heads = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=40)heads.set_homogeneous(True)heads.pack_start(self._section_title(L("纪要")), True, True, 0)- # The transcript's side as its own head has it: 双语 / 只看译文 stays a click away (the Mac's- # bar keeps the transcript's language choice too).trans = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)trans.pack_start(self._section_title("%s %d" % (L("文字记录"), len(s.lines))), True, True, 0)if any(l.dst and l.dst != l.shown for l in s.lines):@@ -611,7 +546,6 @@ class RecordsWindow(Gtk.Window):return ui.panel(box, "pinned-bar")def _pin(self) -> None:- """Show the pinned bar while the title block is above the top of the page."""top = self.top_boxshow = top is not None and top.get_mapped() and \self.right.get_vadjustment().get_value() > top.get_allocation().y + top.get_allocation().height@@ -619,8 +553,6 @@ class RecordsWindow(Gtk.Window):self.pinned.set_visible(show)def _setup_page(self) -> Gtk.Widget:- """No meetings and not set up yet (Windows' Welcome › Checklist): what is left, ticked by what- really happened, each step opening the onboarding where it is. 同声传译 is optional."""app = self.appkey, audio, sample = app.setup_donefirst = 0 if not key else 1 if not audio else 2 if not sample else 3@@ -641,7 +573,6 @@ class RecordsWindow(Gtk.Window):speak = (LF("按 %@ 说话,线上的人听到翻译后的声音", SHORTCUTS["speak"][2].replace(" + Shift + ", " ⇧ "))if gnome_shortcut("speak") else L("点纪要窗的麦克风说话,线上的人听到翻译后的声音"))service = L("接上 Ling") if app.settings.aiProvider == "ling" else LF("接上 %@", app.ling.provider.name)- # A key that the check found failing: why, and 去修 opens 设置 › AI 服务 (not the onboarding).from . import aicheck_viewbroken = aicheck_view.strip_words(app) if app.ling.has_key and not key else Nonekey_line = (broken[1] or broken[0]) if broken else (L("只存在这台电脑上(只有你的账户能读)") if key else L("识别、翻译和纪要都靠它,约 1 分钟"))@@ -674,7 +605,7 @@ class RecordsWindow(Gtk.Window):texts = ui.vbox(1, head, sub)texts.set_valign(Gtk.Align.CENTER)row = ui.hbox(14, disc)- row.pack_start(texts, True, True, 0) # filled, so the words start at the left of every row+ row.pack_start(texts, True, True, 0)action = Noneif now and i == 0 and broken:action = ui.button(L("去修"), lambda: app.show_settings(ai=True), "darkbtn")@@ -699,7 +630,6 @@ class RecordsWindow(Gtk.Window):self.app.changed()def _welcome_page(self) -> Gtk.Widget:- """No meetings yet, set up (Views.swift › welcome): the logo, one line, 开始听 and the sample."""page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)page.set_halign(Gtk.Align.CENTER)page.set_valign(Gtk.Align.CENTER)@@ -774,7 +704,7 @@ class RecordsWindow(Gtk.Window):returnif empty:d.pack_start(self._welcome_page(), True, True, 0)- if self.app.tray is not None: # where 知了 is once this window is closed+ if self.app.tray is not None:hint = ui.text(L("关掉窗口后,知了在顶栏右上角"), 12, "secondary", wrap=False)hint.set_halign(Gtk.Align.END)d.pack_end(ui.pad(hint, 0, 18, 14, 0), False, False, 0)@@ -814,7 +744,7 @@ class RecordsWindow(Gtk.Window):self.player = media.Player(self.app.store.audio_path(s.id), on_change=self._player_changed)self._player_sid = s.idGLib.timeout_add(250, self._poll, self.player)- except Exception as e: # noqa: BLE001 - a file GStreamer can't open: no player, the record still shows+ except Exception as e: # noqa: BLE001Log.d("records: can't play %s" % type(e).__name__)self.player = Noneself._playable = self.player is not None@@ -823,14 +753,12 @@ class RecordsWindow(Gtk.Window):self.bottom.pack_start(self._player_bar(), False, False, 0)self.bottom.show_all()- # Title, meta, actionstop = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)left = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)self.title_label = ui.text(session_store.display_title(s), 22, "heading", bold=True, selectable=True, width_chars=36)left.pack_start(self.title_label, False, False, 0)self.meta_label = ui.text(self._meta(s, live), 12, "tertiary", wrap=False)left.pack_start(self.meta_label, False, False, 0)- # 存到文件夹: where this record's file is, or why it isn't there yet (not while it's live).self.export_slot = ui.hbox(0)self.export_slot.set_margin_top(5)self.export_slot.set_no_show_all(True)@@ -850,7 +778,6 @@ class RecordsWindow(Gtk.Window):if recording is not None:d.pack_start(ui.gap(recording, 14), False, False, 0)- # Notes | transcriptself.columns = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=40)self.columns.set_homogeneous(True)self.columns.set_margin_top(24)@@ -886,7 +813,6 @@ class RecordsWindow(Gtk.Window):if s.lines:src, dst = s.lines[0].srcLang, s.lines[0].dstLanglangs = " · " + (lang_name(src) if src == dst else lang_name(src) + " → " + lang_name(dst))- # Heard through a microphone in the room, and with the computer's audio too: as on the Mac.place = " · " + (L("电脑和会议室") if roommic.heard_both(s.lines) else L("会议室")) if s.room else ""return "%s · %s · %s%s%s" % (session_store._local_date(s.startedAt, L("M月d日 HH:mm")), L("正在听") if live else clock(s.duration),LF("%lld 句", len(s.lines)), langs, place)@@ -895,17 +821,12 @@ class RecordsWindow(Gtk.Window):return (id(s.notes), s.notes.updatedAt if s.notes else None, self.app.notes.working_id == s.id, live)def _update_detail(self, s, live) -> None:- """The same meeting changed (a new line while listening, new notes, a rename): touch only what- changed. Rebuilding a long transcript on every line froze the window for half a second."""if self._audio_state(s, live) != self._built_key[3]:- # The recording was rewrapped (or went missing) since: the player bar and the time links change.self._built_key = Noneself.show_detail()returnif (not self._both and s.sourceFile is None and any(l.speaker == "me" for l in s.lines)) or \self._speaker_state_key(s) != self._speaker_key:- # My first sentence, or voices newly on show / renamed / merged: every row may now say- # someone else, so a full rebuild (the same key would come straight back here).self._built_key = Noneself.show_detail()return@@ -930,7 +851,6 @@ class RecordsWindow(Gtk.Window):self._more_rows()def _refresh_rows(self, s) -> None:- """Rebuilds the rows shown so far whose line, speaker label or search marks changed."""starts = self._starts(s.lines)for i, l in enumerate(s.lines[:len(self._rows)]):if self._rows[i][0] != self._row_key(l, l.id in starts):@@ -939,25 +859,19 @@ class RecordsWindow(Gtk.Window):self.transcript.remove(old_row)old_row.destroy()self.transcript.pack_start(row, False, False, 0)- self.transcript.reorder_child(row, i + 1) # after the header+ self.transcript.reorder_child(row, i + 1)row.show_all()self._rows[i] = (k, row)- # The recording (保存会议录音)-def _audio_state(self, s, live):- """What shows under the title: "live" (it is being recorded), "ready" (a recording to play),- "missing" (the record says it has one, the file is gone), "none" (no recording), or None."""from . import mediaif live:return "live" if self.app.listen.recording else Nonepath = self.app.store.audio_path(s.id)if os.path.isfile(path):- # Without an AAC decoder (a record from a Mac on a stock computer) nothing true and- # useful can be said here: no bar.return "ready" if media.can_play() else Noneif os.path.isfile(aac.partial(path)):- return None # being rewrapped into system.m4a: the bar comes a moment later+ return Noneif s.hasAudio:return "missing"return "none" if s.lines else None@@ -969,7 +883,6 @@ class RecordsWindow(Gtk.Window):return ui.text(L("找不到录音,没法播放"), 12, "secondary")if audio == "none":if not self.app.can_record:- # 保存会议录音 can't be turned on here (no AAC encoder): no link to a greyed-out switch.return ui.text(L("这场会议没存录音 ·").rstrip(" ·"), 12, "secondary", wrap=False)line = ui.hbox(4, ui.text(L("这场会议没存录音 ·"), 12, "secondary", wrap=False, ellipsize=False))go = Gtk.Button()@@ -979,10 +892,9 @@ class RecordsWindow(Gtk.Window):go.connect("clicked", lambda *_: self.app.show_settings(general=True))line.pack_start(go, False, False, 0)return line- return None # "ready": the player bar is under the page (self.bottom)+ return Nonedef _player_bar(self) -> Gtk.Widget:- """Play / pause, where in the meeting, and the speed (RecordingPlayerBar), in a soft box."""p = self.playerself._pb_icon = ui.icon("media-playback-start-symbolic", 13)play = Gtk.Button()@@ -1009,7 +921,7 @@ class RecordsWindow(Gtk.Window):def moved(_w, _scroll, value):ui.retext(self._pb_time, clock(max(0, value)))if not self._dragging and self.player is not None:- self.player.seek(value) # the keyboard+ self.player.seek(value)return Falsescale.connect("change-value", moved)self._pb_scale = scale@@ -1026,7 +938,6 @@ class RecordsWindow(Gtk.Window):row.pack_start(rate, False, False, 0)self._player_changed()bar = ui.panel(ui.pad(row, 8, 14, 8, 10), "playerbar")- # At most 680 wide in the middle of the page, as on the Mac.bar.set_halign(Gtk.Align.CENTER)def fit(_w, alloc):@@ -1062,7 +973,6 @@ class RecordsWindow(Gtk.Window):self.back_pill.hide()def _poll(self, player) -> bool:- """Four times a second while a recording is loaded: the time, the bar, and the line being played."""if player is not self.player:return Falseif getattr(self, "_pb_play", None) is None or not self.get_visible():@@ -1080,18 +990,15 @@ class RecordsWindow(Gtk.Window):return Truedef _hand_scrolled(self, *_args) -> bool:- """The wheel, the touchpad or the scrollbar moved the page: stop following what plays."""if self.player is not None and self.player.playing:adj = self.right.get_vadjustment()- if adj.get_upper() > adj.get_page_size(): # nothing to scroll: nothing moved+ if adj.get_upper() > adj.get_page_size():self._stop_scroll_anim()self.player.user_scrolled()self._update_pill()return Falsedef _highlight(self, now: float, playing: bool, following: bool) -> None:- """The last line that began by now (a little ahead, so it lights as it starts) on a pale- accent; while playing, its bars bounce and the page keeps it in the middle until scrolled by hand."""s = self.app.store.get(self._player_sid) if self._player_sid else Noneif s is None:return@@ -1102,14 +1009,14 @@ class RecordsWindow(Gtk.Window):else:breakif idx >= len(self._rows) and getattr(self, "_loader", None) is not None:- self._more_rows_until(idx + 1) # played (or picked) past the rows built so far+ self._more_rows_until(idx + 1)row = self._rows[idx][1] if 0 <= idx < len(self._rows) else Noneself._hl_line = s.lines[idx] if idx >= 0 else Nonechanged = row is not self._hl_rowif changed:old, self._hl_row = self._hl_row, rowfor r, on in ((old, False), (row, True)):- if r is None or r.get_parent() is None: # a row rebuilt since (its line changed) is gone+ if r is None or r.get_parent() is None:continuectx = r.get_style_context()ctx.add_class("playing") if on else ctx.remove_class("playing")@@ -1122,7 +1029,6 @@ class RecordsWindow(Gtk.Window):self._update_pill()def _style_time(self, r) -> None:- """A row's time: accent and bold while it plays or is pointed at (with ▶ then), the link ink otherwise."""label = r.time_labelctx = r.get_style_context()on = ctx.has_class("playing") or ctx.has_class("hover")@@ -1137,7 +1043,6 @@ class RecordsWindow(Gtk.Window):ui.retext(label, label.get_text())def _set_bars(self, row) -> None:- """Three bars bouncing at the right edge of the row playing (PlayingBars); none while paused."""bars = self._barsslot = getattr(row, "bars_slot", None) if row is not None else Noneif bars is not None and (slot is None or bars.get_parent() is not slot):@@ -1146,7 +1051,6 @@ class RecordsWindow(Gtk.Window):self._bars = bars = Noneif slot is None or bars is not None:return- # CSS-filled boxes, not a drawing: stock Ubuntu has no python3-gi-cairo.moving = Gtk.Settings.get_default().get_property("gtk-enable-animations")bars, sticks = self._sticks("playbars", (8, 8, 8), Gtk.Align.END)bars.set_size_request(14, 12)@@ -1169,7 +1073,6 @@ class RecordsWindow(Gtk.Window):@staticmethoddef _sticks(cls: str, heights, align) -> tuple:- """A row of thin rounded bars (the Mac's capsules) of these heights, filled by CSS."""box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=2 if cls == "playbars" else 1)sticks = []for h in heights:@@ -1182,14 +1085,13 @@ class RecordsWindow(Gtk.Window):return box, sticksdef _back_pill(self) -> Gtk.Widget:- """回到正在播放 · m:ss: a dark capsule at the bottom of the page while it doesn't follow."""b = Gtk.Button()ui.classes(b, "backpill")wave, _ = self._sticks("pillwave", (5, 11, 7, 9, 4), Gtk.Align.CENTER)wave.set_valign(Gtk.Align.CENTER)self._pill_label = ui.text("", 13, "ink", bold=True, wrap=False, ellipsize=False)inner = ui.hbox(6, wave, self._pill_label)- inner.show_all() # the button itself is no_show_all: shown and hidden on its own+ inner.show_all()b.add(inner)b.set_halign(Gtk.Align.CENTER)b.set_valign(Gtk.Align.END)@@ -1199,7 +1101,6 @@ class RecordsWindow(Gtk.Window):return bdef follow_playing(self) -> None:- """回到正在播放: follow the recording again, and scroll back to it."""if self.player is None:returnself.player.follow()@@ -1218,7 +1119,6 @@ class RecordsWindow(Gtk.Window):self.back_pill.hide()def _centre(self, row) -> None:- """Scrolls the row to the middle of the page under the pinned bar, eased over 0.25 s."""pos = row.translate_coordinates(self.content, 0, 0)if pos is None:return@@ -1257,9 +1157,6 @@ class RecordsWindow(Gtk.Window):adj.set_value(max(0, min(y - adj.get_page_size() / 3, adj.get_upper() - adj.get_page_size())))def _more_menu(self, s) -> Gtk.MenuButton:- """The record as it is when pressed: 恢复自动标题 only for a renamed meeting the notes have- named, 删除 off for the live one (the Mac's context menu). The items stay; a menu filled- while it opens pops up empty, so they are updated on the press, before it opens."""menu = Gtk.Menu()sid = s.id@@ -1285,7 +1182,7 @@ class RecordsWindow(Gtk.Window):b = Gtk.MenuButton()b.set_popup(menu)b.connect("button-press-event", update)- b.connect("toggled", update) # the keyboard opens it too; the items are already right by then+ b.connect("toggled", update)b.add(ui.icon("view-more-symbolic"))b.set_tooltip_text(L("更多操作"))ui.classes(b, "outline")@@ -1298,7 +1195,6 @@ class RecordsWindow(Gtk.Window):col = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)col.set_valign(Gtk.Align.START)col.pack_start(self._section_title(L("纪要")), False, False, 0)- # Ling wrote "说话人 2" before anyone was named: the name given since shows instead.n = speakers.named(s.notes, self._speakers(s)[2])working = self.app.notes.working_id == s.idif n is None or n.is_empty:@@ -1318,7 +1214,6 @@ class RecordsWindow(Gtk.Window):col.pack_start(ui.gap(b, 12), False, False, 0)return colif n.summary:- # The summary in a soft card, as the Mac sets it apart.summary = ui.panel(ui.pad(ui.text(n.summary, 14, "body", selectable=True, width_chars=50), 13, 16), "summarycard")col.pack_start(ui.gap(summary, 10), False, False, 0)for t in n.topics:@@ -1330,7 +1225,7 @@ class RecordsWindow(Gtk.Window):for p in t.points:bullet = ui.text("•", 11, "tertiary", wrap=False, ellipsize=False)bullet.set_valign(Gtk.Align.START)- bullet.set_margin_top(2) # level with the first line of 13 px text+ bullet.set_margin_top(2)line = ui.hbox(9, bullet)line.pack_start(ui.text(p, 13, "body", selectable=True, width_chars=46), True, True, 0)col.pack_start(ui.gap(line, 6), False, False, 0)@@ -1363,10 +1258,8 @@ class RecordsWindow(Gtk.Window):has_dst = any(l.dst and l.dst != l.shown for l in s.lines)if has_dst:head.pack_end(ui.segmented([("both", L("双语")), ("dst", L("只看译文"))], self.mode, mode), False, False, 0)- # The review banner rides with the header, so the rows keep their places among col's children.self.fix_banner = ui.vbox(0)self._banner_key = None- # Inset as far as the rows' text, which sits 10 px inside their fill.col.pack_start(ui.pad(ui.vbox(0, head, self.fix_banner), 0, 10, 0, 10), False, False, 0)self.transcript = colself._both = s.sourceFile is None and any(l.speaker == "me" for l in s.lines)@@ -1386,14 +1279,10 @@ class RecordsWindow(Gtk.Window):self._more_rows(first=True)return col- # 说话人识别-def _speakers(self, s):- """(line id → number, voice → number, number → name) for the voices on show; empty when off."""if not self.app.settings.speakerVoices:return {}, {}, {}vnums = speakers.voice_numbers(s.lines)- # An imported file without voices on show has no "other side" to label.if not speakers.says_who(s, vnums):return {}, {}, {}return speakers.numbers(s.lines), vnums, (speakers.names(s) if vnums else {})@@ -1401,18 +1290,15 @@ class RecordsWindow(Gtk.Window):def _speaker_state_key(self, s):_n, vnums, shown = self._speakers(s)busy = s.id in self.app.namer.busy- # The room side's first line in 电脑和会议室: every line of theirs now says where it was heard.return (tuple(sorted(vnums.items())), tuple(sorted(shown.items())), str(sorted((s.voiceGuesses or {}).keys())), busy,roommic.heard_both(s.lines))def _row_key(self, l, start):fixes = tuple((f.from_, f.to, f.ask, f.off, f.user) for f in l.fixes or [])- # The search marks only lines it finds: typing a query doesn't rebuild the whole transcript.found = (tuple(self._terms), l.id == self._current) if l.id in self._match_set else Nonereturn (l.id, l.shown, l.dst, l.voice, start, fixes, self._editing == l.id, found)def _who(self, l):- """The label at a change of speaker, and its colour class."""if l.speaker == "me":return L("你"), "accent"n = self._nums.get(l.id)@@ -1427,7 +1313,6 @@ class RecordsWindow(Gtk.Window):lbl = ui.text(text, 11, cls, bold=True, wrap=False)if not self._vnums:return lbl- # A click on whose line it is: say it was someone else's (这句是谁说的).b = Gtk.Button()b.add(lbl)b.set_relief(Gtk.ReliefStyle.NONE)@@ -1456,8 +1341,6 @@ class RecordsWindow(Gtk.Window):self.toasts.show(text, L("撤销"), lambda: self.app.undo_speaker_edit(sid, snap), seconds=6)def _people(self, s) -> Gtk.Widget:- """Who is speaking, above the transcript: each person opens the editor; and a way out."""- # Chips wrap onto more lines rather than widen the window; each keeps its natural width in its cell.row = Gtk.FlowBox()row.set_selection_mode(Gtk.SelectionMode.NONE)row.set_column_spacing(6)@@ -1488,8 +1371,6 @@ class RecordsWindow(Gtk.Window):return ui.gap(line, 12)def _editor(self, chip, voice) -> None:- """One voice: its name (Ling's guess and people the notes mention a click away), or merge it- into another voice (SpeakerEditor)."""s = self.app.store.get(self._sid)if s is None or voice not in self._vnums:return@@ -1521,7 +1402,6 @@ class RecordsWindow(Gtk.Window):def apply():name = entry.get_text().strip()pop.popdown()- # Keeping Ling's name stores nothing, so a later, better guess can still replace it.if guess is not None and name == guess.name:self._edited(*self.app.rename_speaker(self._sid, voice, None))elif (s.voiceNames or {}).get(str(voice)) is not None or name:@@ -1572,14 +1452,12 @@ class RecordsWindow(Gtk.Window):def _row(self, l, start: bool = False):row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)- t = ui.text(clock(l.t), 11, "link", wrap=False, ellipsize=False) # times in the logo's orange ink+ t = ui.text(clock(l.t), 11, "link", wrap=False, ellipsize=False)t.set_size_request(44, -1)time_widget = tplay_icon = Noneplayable = getattr(self, "_playable", False)if playable:- # With a recording, a time plays from that line (the Mac's line times), and so does a- # click anywhere on the line; pointed at, it shows ▶ in the accent.t.set_size_request(-1, -1)play_icon = ui.icon("media-playback-start-symbolic", 8)ui.classes(play_icon, "accent")@@ -1598,8 +1476,6 @@ class RecordsWindow(Gtk.Window):time_widget.set_margin_top(2)row.pack_start(time_widget, False, False, 0)texts = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)- # Whose it is, where the speaker changes (as chat apps do): with voices told apart, or in a- # meeting I spoke in through 同声传译.if start and (self._both or self._vnums or self._places):label = self._speaker_label(l)if self._places and l.speaker != "me":@@ -1608,7 +1484,7 @@ class RecordsWindow(Gtk.Window):translated = l.dst and l.dst != l.shownterms = self._terms if l.id in self._match_set else []found = l.id == self._current- selectable = [] # the line's text: a drag over it selects, and must not play+ selectable = []if self._editing == l.id:texts.pack_start(self._line_editor(l), False, False, 0)else:@@ -1623,7 +1499,6 @@ class RecordsWindow(Gtk.Window):src.set_max_width_chars(46)selectable.append(src)texts.pack_start(src, False, False, 0)- # Pointing at a line: what its fixed words were heard as, 改回, and 改这句….tools = ui.hbox(8)applied = [(l.id, f) for f in l.fixes or [] if f.applied]if applied:@@ -1643,12 +1518,10 @@ class RecordsWindow(Gtk.Window):panel.time_play = play_iconpanel.bars_slot = Noneif playable:- # Where the bars bounce while this line plays: kept wide so the text doesn't move.panel.bars_slot = Gtk.Box()panel.bars_slot.set_size_request(14, -1)panel.bars_slot.set_margin_top(4)row.pack_end(panel.bars_slot, False, False, 0)- # 10 px of fill around the text, so the line playing reads as one rounded block.ui.pad(row, 9, 10, 9, 10)if self._editing != l.id:panel.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK |@@ -1676,8 +1549,6 @@ class RecordsWindow(Gtk.Window):return self._row_key(l, start), paneldef _tap_to_play(self, panel, labels, l) -> None:- """A click anywhere on the line plays from it; a drag (or a double click) that selects text- doesn't. The selectable labels take the presses over the text, so they report them too."""down = {}def press(_w, e):@@ -1692,7 +1563,7 @@ class RecordsWindow(Gtk.Window):if abs(e.x_root - at[0]) > 4 or abs(e.y_root - at[1]) > 4:return Falseif any(lb.get_selection_bounds()[0] for lb in labels):- return False # text selected (a drag that came back, a shift-click)+ return Falseself.play_line(l)return Falsefor w in [panel, *labels]:@@ -1700,16 +1571,12 @@ class RecordsWindow(Gtk.Window):w.connect("button-release-event", release)def play_line(self, l) -> None:- """Plays the recording from a line (also while paused); the page follows it again."""if self.player is None:returnself.player.play_from(l.t)self._highlight(l.t, True, True)- # 改正听错的词: 改这句…, the review banner, the toast-def _line_menu(self, event, line_id) -> bool:- """Right-click on a line: 改这句…."""if event.button != 3:return Falsemenu = Gtk.Menu()@@ -1722,14 +1589,13 @@ class RecordsWindow(Gtk.Window):return Truedef edit_line(self, line_id, start: str | None = None) -> None:- """Opens 改这句… on a line, with the line as shown (or `start`, the banner's suggestion)."""l = self.app.store.line(self._sid, line_id)if l is None:returnbefore = self._editingself._editing, self._edit_start = line_id, start if start is not None else l.shownif before is not None and before != line_id:- self._rebuild_row(before) # one editor at a time+ self._rebuild_row(before)self._rebuild_row(line_id)def _rebuild_row(self, line_id) -> None:@@ -1754,8 +1620,6 @@ class RecordsWindow(Gtk.Window):returndef _line_editor(self, l) -> Gtk.Widget:- """改这句…: the line as shown, to rewrite (the Mac's LineEditor). What changed becomes the user's- own fix, on every line heard the same way or only this one, and with 记进词表 the word list's."""fx, sid = self.app.fixes, self._sidbox = ui.vbox(8)entry = Gtk.Entry()@@ -1803,7 +1667,6 @@ class RecordsWindow(Gtk.Window):keep.set_sensitive(state["everywhere"])options.pack_start(all_, False, False, 0)options.pack_start(one, False, False, 0)- # Only a word for a word can teach the list: an added or dropped word can't.if swap:options.pack_start(keep, False, False, 0)options.show_all()@@ -1824,14 +1687,12 @@ class RecordsWindow(Gtk.Window):box.pack_start(foot, False, False, 0)def focus():entry.grab_focus()- entry.set_position(-1) # the caret at the end, not the whole line selected+ entry.set_position(-1)return FalseGLib.idle_add(focus)return boxdef _fill_fix_banner(self, s) -> None:- """Above a finished meeting's transcript (the Mac's FixReviewBanner): how many words were fixed,- and the ones waiting for the user, one at a time (对 / 不对 / 改成…)."""box = getattr(self, "fix_banner", None)if box is None:return@@ -1861,7 +1722,6 @@ class RecordsWindow(Gtk.Window):row.pack_start(left, True, True, 0)row.pack_start(ui.soft_button(L("对"), lambda: fx.answer(fix, True, s.id), dark=True), False, False, 0)row.pack_start(ui.soft_button(L("不对"), lambda: fx.answer(fix, False, s.id)), False, False, 0)- # 改成…: the editor on that line, to write what was really said.row.pack_start(ui.soft_button(L("改成…"), lambda: self.edit_line(line.id)), False, False, 0)for b in row.get_children()[1:]:b.set_valign(Gtk.Align.CENTER)@@ -1871,7 +1731,6 @@ class RecordsWindow(Gtk.Window):box.show_all()def fix_toast(self) -> None:- """The last fix decision, with 撤销, as this window's toast (once per decision)."""fx = self.app.fixestext = fx.toast_text()if text is None or fx.toast is self._fix_toast:@@ -1880,13 +1739,10 @@ class RecordsWindow(Gtk.Window):self.toasts.show(text, L("撤销") if fx.can_undo else None, fx.undo, seconds=6)def _starts(self, lines) -> set:- """Lines whose speaker label shows: a change of speaker, or in 电脑和会议室 of place too."""starts = speakers.run_starts(lines, self._nums)return starts | roommic.place_starts(lines) if self._places else startsdef _more_rows(self, first: bool = False) -> None:- """Rows not shown yet: the first screenful at once, the rest in batches between frames, so- a two-hour meeting opens instantly."""built = self._built_keydef step(count):@@ -1910,7 +1766,6 @@ class RecordsWindow(Gtk.Window):self._loader = GLib.idle_add(step, 200)def _more_rows_until(self, count: int) -> None:- """The rows up to `count` built now: the playhead got there before the batches did."""s = self.app.store.get(self._sid)if s is None:return@@ -1923,13 +1778,9 @@ class RecordsWindow(Gtk.Window):def _generate(self, sid) -> None:self.app.notes.generate(sid)- # Shown at once: the engine marks the record busy on its worker a moment later.GLib.timeout_add(150, lambda: self.refresh() or False)- # Actions-def _share_button(self, s) -> Gtk.Widget:- """分享…, beside 导出…: off while the meeting is live or has nothing in it (share_dialog.can_share)."""sid = s.idb = ui.button(L("分享…"), lambda: self.share(sid), "outline", "emblem-shared-symbolic")b.set_sensitive(share_dialog.can_share(self.app, s))@@ -1976,7 +1827,6 @@ class RecordsWindow(Gtk.Window):dialog.destroy()def delete(self, s) -> None:- """Hidden at once, removed when the toast goes without 撤销 (or when the app quits)."""if s.id == self.app.store.live:returnself.commit_delete()@@ -1988,19 +1838,16 @@ class RecordsWindow(Gtk.Window):self.pending_delete = Noneself.selected = s.idself.fill()- # Longer than an info toast: undo is the only way back.self.toasts.show(LF("已删除“%@”", session_store.display_title(s)), L("撤销"), undo, self.commit_delete, seconds=8)def commit_delete(self) -> None:sid, self.pending_delete = self.pending_delete, Noneif sid:self.app.store.delete(sid)- self.app.folder_export.deleted(sid) # its file in the folder stays+ self.app.folder_export.deleted(sid)def show_in_folder(path: str) -> None:- """Opens the file manager with the file selected (org.freedesktop.FileManager1), else the folder.- Asynchronous: a file manager that isn't running yet takes seconds to start."""uri = Gio.File.new_for_path(path).get_uri()folder = Gio.File.new_for_path(os.path.dirname(path)).get_uri()diff --git a/linux/cicada/app/room.py b/linux/cicada/app/room.pyindex 3f65d4f..b563d02 100644--- a/linux/cicada/app/room.py+++ b/linux/cicada/app/room.py@@ -1,13 +1,3 @@-"""知了 麦克风: the virtual microphone the meeting app hears the interpreted voice from (the Mac's-BlackHole, without a driver). Two modules of the sound server, made while 同声传译 is on and removed-when it's off or the app quits:-- module-null-sink cicada_room where Cicada plays the translated voice- module-remap-source cicada_mic that sink's monitor as a real microphone (apps list it)--Both PulseAudio and PipeWire (pipewire-pulse) load these. While it's on, 知了 麦克风 is also made the-default input, so a meeting app left on "default" (most browsers) uses it with no setup; the real-microphone is remembered, Cicada records me from it, and it is the default again afterwards."""from __future__ import annotationsimport ctypes@@ -18,7 +8,7 @@ import timefrom ..core.ling import TTS_RATEfrom ..core.strings import Lfrom ..core.support import Log, Paths-from .capture import _INFO_CB, PA_SAMPLE_S16LE, _Attr, _libpulse, _pulse, _Spec # one server-info type for both+from .capture import _INFO_CB, PA_SAMPLE_S16LE, _Attr, _libpulse, _pulse, _SpecSINK = "cicada_room"MIC = "cicada_mic"@@ -52,8 +42,6 @@ def _lib():class _Session:- """One connection to the sound server for a few blocking requests."""-def __init__(self):self.l = _lib()self.loop = self.l.pa_mainloop_new()@@ -139,14 +127,12 @@ class _Session:def _saved_path() -> str:- # Beside the log in the state folder: if Cicada is killed while 知了 麦克风 is the default input,- # the next launch still knows which microphone to give back.return os.path.join(os.path.dirname(Paths.log()), "real-mic")class VirtualMic:def __init__(self):- self.real_mic = self._load() # the input that was the default before: Cicada records me from it+ self.real_mic = self._load()self.on = False@staticmethod@@ -165,8 +151,6 @@ class VirtualMic:passdef leftovers(self) -> None:- """At launch with 同声传译 off: a killed Cicada may have left 知了 麦克风 as everyone's default- input, which would make every meeting app silent. Gives the real microphone back."""try:s = _Session()except OSError:@@ -182,14 +166,13 @@ class VirtualMic:if s.server().get("source") == MIC and self.real_mic:s.set_default_source(self.real_mic)for index in self._ours(s.modules()):- s.unload(index) # with no remembered mic the server falls back to a real one itself+ s.unload(index)def _ours(self, modules) -> list:return [i for i, name, arg in modules if name in ("module-null-sink", "module-remap-source")and (("sink_name=" + SINK) in arg or ("source_name=" + MIC) in arg)]def create(self) -> bool:- """Makes 知了 麦克风 and makes it the default input. Left over from a crash: removed first."""try:s = _Session()except OSError as e:@@ -202,10 +185,8 @@ class VirtualMic:for index in self._ours(s.modules()):s.unload(index)current = s.server().get("source")- # A real microphone to record me from; never our own (left as default after a crash).self.real_mic = current if current and current != MIC else self.real_micself._save()- # Quoted the way module arguments and property lists parse: names with spaces survive.sink_desc = L("知了 · 给会议的声音").replace("'", "")mic_desc = L("知了 麦克风").replace("'", "")a = s.load("module-null-sink", "sink_name=%s sink_properties=\"device.description='%s'\"" % (SINK, sink_desc))@@ -240,29 +221,12 @@ class VirtualMic:AEC_SINK = "cicada_aec_out"AEC_MIC = "cicada_aec_mic"-# 同声传译's own canceller: the talk key reads the microphone through it.TALK_SINK = "cicada_talk_out"TALK_MIC = "cicada_talk_mic"-# PulseAudio's WebRTC canceller turns on gain control unless told not to, which moves the-# microphone's own volume; off, as on the Mac. pipewire-pulse ignores these keys (its default is off).NO_AGC = 'aec_args="analog_gain_control=0 digital_gain_control=0"'class EchoCanceller:- """The meeting's voices taken out of a microphone (the Mac's voice-processing unit). One- sound-server module, module-echo-cancel (WebRTC's canceller, in PipeWire and PulseAudio):-- <sink> an output in front of the speakers, made the default while it runs: what it plays- goes on to the speakers and is what the canceller takes out (the meeting app's- voices). The canceller only hears what is played into it, so it has to be the- default; the speakers stay where the sound comes out.- <source> the microphone with them taken out-- Two of them: 电脑和会议室's room side (cicada_aec_*, debug only, the room stays unprocessed by- default) and 同声传译's talk key (cicada_talk_*, made with 知了 麦克风 so it has settled before a- press). Removed when they stop, on 退出, SIGTERM, and after a crash at the next launch; the output- that was the default is the default again each time."""-def __init__(self, sink: str = AEC_SINK, source: str = AEC_MIC, state: str = "real-sink",agc_off: bool = False):self.sink = sink@@ -270,7 +234,7 @@ class EchoCanceller:self.state = stateself.agc_off = agc_offself.on = False- self.mic = None # the microphone it was made on+ self.mic = Nonetry:with open(self._state_path()) as f:self.real_sink = f.read().strip() or None@@ -284,8 +248,6 @@ class EchoCanceller:return [i for i, name, arg in modules if name == "module-echo-cancel" and ("sink_name=" + self.sink) in arg]def create(self, mic: str) -> str | None:- """Puts the canceller between `mic` and the speakers; the source to listen to, or None when the- sound server won't (the caller then uses the plain mic)."""try:s = _Session()except OSError:@@ -296,7 +258,6 @@ class EchoCanceller:self._give_back(s)sink = s.server().get("sink")if not sink or sink.startswith("cicada_"):- # Another canceller of ours is the default already: two in a row fight over it.Log.d("echo cancel %s: the default output is %s, not made" % (self.sink, sink))return Noneself.real_sink = sink@@ -326,8 +287,6 @@ class EchoCanceller:s.close()def ready(self, mic: str) -> bool:- """Whether it is there for `mic` and still the default output: the meeting plays through it.- False after the output was changed (a headset, the sound settings) or the module went away."""if not self.on or mic != self.mic:return Falsetry:@@ -346,7 +305,6 @@ class EchoCanceller:s.unload(index)def remove(self) -> None:- """Also what launch does (a crash may have left it): harmless when there is nothing to remove."""try:s = _Session()except OSError:@@ -364,15 +322,13 @@ class EchoCanceller:class Player:- """Plays 24 kHz (or `rate`) mono 16-bit PCM into a sink: 知了 麦克风's (the room) or, for 试听, the speakers."""-def __init__(self, device: str | None = SINK, rate: int = TTS_RATE):lib = _pulse()lib.pa_simple_write.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_int)]lib.pa_simple_drain.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)]self.lib = libspec = _Spec(PA_SAMPLE_S16LE, rate, 1)- attr = _Attr(0xFFFFFFFF, rate // 5 * 2, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) # ~200 ms buffered+ attr = _Attr(0xFFFFFFFF, rate // 5 * 2, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF)err = ctypes.c_int(0)self.s = lib.pa_simple_new(None, b"Cicada", PA_STREAM_PLAYBACK, device.encode() if device else None,L("同声传译的声音").encode(), ctypes.byref(spec), None, ctypes.byref(attr), ctypes.byref(err))diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.pyindex 3ef94c7..8d6a81a 100644--- a/linux/cicada/app/settings_window.py+++ b/linux/cicada/app/settings_window.py@@ -1,6 +1,3 @@-"""设置, GNOME preferences style: groups of boxed-list rows, the title and a grey line on the left and-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 annotationsimport os@@ -41,7 +38,6 @@ def choice(options, current, on_change) -> Gtk.ComboBoxText:def target_options():- """跟随系统(简体中文 / English): my language, then what it becomes when they speak mine."""names = {code: name for name, code in TARGETS}prefs = system_languages()mine = my_language(prefs)@@ -49,8 +45,6 @@ def target_options():return [("system", LF("跟随系统(%@)", both))] + [(code, name) for name, code in TARGETS]-# 登录时启动: an XDG autostart entry, the file's presence being the setting.-def autostart_path() -> str:base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")return os.path.join(base, "autostart", "com.wquguru.cicada%s.desktop" % (".dev" if Paths.dev else ""))@@ -69,7 +63,6 @@ def set_autostart(on: bool, launcher: str) -> None:passreturnos.makedirs(os.path.dirname(path), exist_ok=True)- # --background: a login start stays in the top bar; opening 知了 by hand shows its window.with open(path, "w", encoding="utf-8") as f:f.write("[Desktop Entry]\nType=Application\nName=Cicada\nName[zh_CN]=知了\n""Exec=%s%s --background\nIcon=cicada\nTerminal=false\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n"@@ -77,7 +70,6 @@ def set_autostart(on: bool, launcher: str) -> None:def refresh_autostart(launcher: str) -> None:- """An autostart file from before --background (or from another install place) is rewritten."""path = autostart_path()try:with open(path, encoding="utf-8") as f:@@ -88,9 +80,7 @@ def refresh_autostart(launcher: str) -> None:set_autostart(True, launcher)-# GNOME custom keyboard shortcuts: `cicada --toggle` (开始 / 结束听) and `cicada --speak` (开始 / 停止说).--PREVIEW = { # what 试听 says, spoken text not UI (not L()): one per language a voice speaks+PREVIEW = {"en": "This is the voice the room will hear.", "zh": "这是对方会听到的声音。","ja": "これは相手に聞こえる声です。", "ko": "상대방에게 들리는 목소리입니다.","es": "Esta es la voz que oirán los demás.", "fr": "Voici la voix que les autres entendront.",@@ -107,7 +97,6 @@ def _custom_path(which: str) -> str:def gnome_shortcut(which: str):- """None off GNOME; "" when not added; else the key, as shown."""try:from gi.repository import Giosource = Gio.SettingsSchemaSource.get_default()@@ -117,7 +106,7 @@ def gnome_shortcut(which: str):if _custom_path(which) not in keys.get_strv("custom-keybindings"):return ""return SHORTCUTS[which][2]- except Exception: # noqa: BLE001 - any failure: treat as not GNOME+ except Exception: # noqa: BLE001return None@@ -162,16 +151,14 @@ class SettingsWindow(Gtk.Window):s.save()app.settings_changed()- # AI 服务: the service and its key, what works with it, and its models (AISettings.swift).self._ai_section(page)- # Languagesdef set_target(v):s.target = vsave()def set_notes(v):- app.listen.set_notes_language(v) # saves, and rewrites the live meeting's notes in it+ app.listen.set_notes_language(v)def set_ui(v):s.uiLanguage = v@@ -188,13 +175,11 @@ class SettingsWindow(Gtk.Window):page.pack_start(self._group(L("语言"), ui.boxed([ui.prow(L("翻译成"), combos[0]), ui.prow(L("纪要语言"), combos[1], L("实时纪要和完整版同一种语言")), ui_row])),False, False, 0)- # 词表 (改正听错的词), after 语言 as on the Mac.from .word_list import WordListself.word_list = WordList(app, self._group)self.word_list_group = self.word_list.widgetpage.pack_start(self.word_list_group, False, False, 0)- # While listeningswitch = Gtk.Switch()switch.set_active(autostart_enabled())switch.connect("notify::active", lambda w, _p: set_autostart(w.get_active(), app.launcher))@@ -215,14 +200,12 @@ class SettingsWindow(Gtk.Window):self._shortcut_row(),warn_row])), False, False, 0)- # 通用, the Mac's records section: what each meeting keeps.self.general = self._group(L("通用"), ui.boxed([self._record_row(), self._voices_row()]))page.pack_start(self.general, False, False, 0)- # 会后存一份 (存到文件夹), under 通用 as on the Mac.from .folder_export_view import FolderExportCardself.folder_card = FolderExportCard(app, self._group, self)page.pack_start(self.folder_card.widget, False, False, 0)- self.connect("show", lambda *_: app.folder_export.retry()) # a folder fixed meanwhile+ self.connect("show", lambda *_: app.folder_export.retry())room_group, room_combos = self._room_group()page.pack_start(room_group, False, False, 0)@@ -230,8 +213,6 @@ class SettingsWindow(Gtk.Window):page.pack_start(self._speak_group(combos), False, False, 0)page.pack_start(self._end_group(), False, False, 0)- # About- # 版本 with the update check under it and its button (UpdateViews' settings row).self.version_slot = ui.hbox(0)self.version_row = ui.prow(LF("版本 %@", VERSION + " · Linux"), self.version_slot, " ")rows = [self.version_row]@@ -257,7 +238,6 @@ class SettingsWindow(Gtk.Window):self.refresh_version()def refresh_version(self) -> None:- """The update line and button: 检查更新, 安装并重新打开 / 重试, nothing while downloading."""u = self.app.updatesdetail = u.detail()sub = next((w for w in _labels(self.version_row) if w.get_style_context().has_class("secondary")@@ -265,7 +245,6 @@ class SettingsWindow(Gtk.Window):if sub is not None:ui.retext(sub, detail or " ")ui.classes(sub, "err") if u.failure and u.update else sub.get_style_context().remove_class("err")- # The release page's address, when no browser opened: copyable.sub.set_selectable(bool(u.failure and u.update and not u.opened))key = (u.update is not None, u.progress is not None, bool(u.failure), u.check == "checking", u.after_meeting)if key == getattr(self, "_version_key", None):@@ -286,7 +265,6 @@ class SettingsWindow(Gtk.Window):self.version_slot.show_all()def _end_group(self) -> Gtk.Widget:- """结束会议: when a meeting ends by itself (meeting_end.py), as the Mac's settings say it."""s = self.app.settingsdef save():@@ -298,7 +276,6 @@ class SettingsWindow(Gtk.Window):minutes = ui.prow(L("多久算没人说话"), ui.segmented([(str(m), LF("%lld 分钟", m)) for m in (5, 10, 15, 30)],str(s.silenceMinutes),lambda v: (setattr(s, "silenceMinutes", int(v)), save())))- # Hidden after the window's show_all() (a no_show_all row would stay empty once shown).self.connect("show", lambda *_: minutes.set_visible(s.silenceEnd != "off"))def set_silence(v):@@ -311,12 +288,10 @@ class SettingsWindow(Gtk.Window):ui.prow(L("会议应用挂断后结束"), app_switch, L("Zoom、腾讯会议、飞书、Teams 等")), silence, minutes]))def _shortcut_row(self, which: str = "toggle") -> Gtk.Widget:- """From anywhere: GNOME runs `cicada --toggle` / `--speak` on a custom keyboard shortcut.- Added only when the user asks (it writes to their keyboard settings)."""title = L("开始 / 结束听的快捷键") if which == "toggle" else L("开始 / 停止说的快捷键")flag = " --toggle" if which == "toggle" else " --speak"state = gnome_shortcut(which)- if state is None: # not GNOME: say how+ if state is None:return ui.prow(title, None, LF("在系统的键盘设置里,把命令 %@ 绑到一个按键", self.app.launcher + flag))label = ui.text(state or "", 12, "secondary", wrap=False)@@ -332,8 +307,6 @@ class SettingsWindow(Gtk.Window):return ui.prow(title, box, L("在任何窗口里都能用"))def _record_row(self) -> Gtk.Widget:- """保存会议录音: on by default, as on the Mac; greyed out, saying why, without an AAC encoder.- Checked again each time Settings shows: the formats may have been installed meanwhile."""app = self.appsw = Gtk.Switch()sw.set_valign(Gtk.Align.CENTER)@@ -360,20 +333,15 @@ class SettingsWindow(Gtk.Window):return ui.prow(L("保存会议录音"), sw, subtitle_widget=hint)def scroll_to_general(self) -> None:- """Brings 通用 into view (the records window's 保存会议录音 link), once it is laid out."""def go():- # In the page's own coordinates (the viewport's are shifted by the current scroll).pos = self.general.translate_coordinates(self.scroll.get_child().get_child(), 0, 0)if pos is not None:self.scroll.get_vadjustment().set_value(max(0, pos[1] - 8))return False- # A window just shown isn't laid out yet, and its show handlers then hide rows above 通用: once- # it has a size, and again once those are gone.GLib.timeout_add(150, go)GLib.timeout_add(500, go)def _voices_row(self) -> Gtk.Widget:- """说话人识别: on by default, as on the Mac; off when this build has no voiceprint library."""app = self.appsw = Gtk.Switch()sw.set_valign(Gtk.Align.CENTER)@@ -385,7 +353,6 @@ class SettingsWindow(Gtk.Window):else L("这个版本缺少声纹组件,暂时用不了"))def _speak_group(self, combos) -> Gtk.Widget:- """同声传译: on/off (makes 知了 麦克风), my language, what they hear, the voice, 试听, the shortcut."""from ..core import voices as voicemodfrom ..core.support import TARGETSapp, s = self.app, self.app.settings@@ -420,7 +387,6 @@ class SettingsWindow(Gtk.Window):[(c, names.get(c, c)) for c in voicemod.ROOM_LANGUAGES], s.speakTo, set_to)voice = Gtk.ComboBoxText()voice.set_size_request(170, -1)- # 我自己的声音, under 声音: redrawn with the voices (a new recording, another service).clone_slot = Gtk.EventBox()def fill_clone():@@ -450,17 +416,16 @@ 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+ self._fill_voices = fill_voicesdef preview():code = app.speak.target- # In the voice's own language: a Japanese voice reading English says nothing about it.text = PREVIEW.get(code[:2], PREVIEW["en"]) if code != "zh-TW" else "這是對方會聽到的聲音。"from .room import Playerdef run():from ..core.support import Log- p = Player(None) # the speakers, not the room+ p = Player(None)start, n = time.monotonic(), 0try:for pcm in app.speak.speech(text, code, voice=app.speak.voice(code) or "US_Emma"):@@ -488,8 +453,6 @@ class SettingsWindow(Gtk.Window):short = self._shortcut_row("speak")dependents.append(short)rows.append(short)- # Without headphones a sentence said while they talk may be their voice from the speakers, so- # it is dropped; with them it's mine, and talking over each other is normal in a meeting.phones = Gtk.Switch()phones.set_active(s.speakHeadphones)phones.set_valign(Gtk.Align.CENTER)@@ -516,8 +479,6 @@ class SettingsWindow(Gtk.Window):return ui.vbox(6, self._group(L("同声传译"), ui.boxed(rows)), ui.pad(self.speak_status, 0, 4, 0, 4))def _clone_row(self) -> Gtk.Widget:- """我自己的声音 (VoicePicker.swift › cloneRow): 录制 until there is a recording, then how long- it is and how it will sound, with 重录 / 删除. Only Ling clones: elsewhere it says so."""app, s = self.app, self.app.settingscode = app.speak.targettitle = L("我自己的声音")@@ -547,7 +508,6 @@ class SettingsWindow(Gtk.Window):self._fill_voices()def remove_voice(self) -> None:- """The recording goes, and every language that used it is back on its default voice."""s = self.app.settingsvoice_reference.remove()s.speakVoices = {k: v for k, v in (s.speakVoices or {}).items() if v != voicemod.CLONE}@@ -556,8 +516,6 @@ class SettingsWindow(Gtk.Window):self._fill_voices()def _room_group(self):- """会议室: the microphone 打开麦克风 hears the room with (自动 picks as roommic.pick does). Whether- it hears the speakers is measured (roommic.EchoGate), not asked."""from ..core import roommicfrom . import captureapp = self.app@@ -574,7 +532,7 @@ class SettingsWindow(Gtk.Window):s.save()options = [("", LF("自动(%@)", auto_name) if auto_name else L("自动"))] + [(i.name, i.description) for i in inputs]if s.roomMic and all(v != s.roomMic for v, _ in options):- options.append((s.roomMic, s.roomMic)) # chosen before, not plugged in now+ options.append((s.roomMic, s.roomMic))mic = choice(options, s.roomMic, set_mic)rows = [ui.prow(L("麦克风"), mic, L("戴着蓝牙耳机时,自动用电脑自带的麦克风"))]return self._group(L("会议室"), ui.boxed(rows)), [mic]@@ -590,11 +548,7 @@ 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 providersapp, s = self.app, self.app.settingsself.provider_menu = choice([(p.id, "Ling" + L("(推荐)") if p.id == "ling" else L(p.name)) for p in providers.ALL],@@ -621,11 +575,9 @@ class SettingsWindow(Gtk.Window):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)- # A pasted key that belongs elsewhere (AISettings.swift › keyHint): what it is, 改用 <服务>.self.key_hint = ui.hbox(8)- self.key_hint.set_no_show_all(True) # no gap while empty+ self.key_hint.set_no_show_all(True)self.entry_row = ui.panel(ui.pad(ui.vbox(8, entry_row, self.key_hint), 12, 16), "prow")- # A custom service: one row per use instead of the key card (_custom_page).self.custom_page = self._custom_page()self.get_key = Gtk.Button()self.get_key_label = ui.text("", 13, "ink", wrap=False)@@ -635,16 +587,12 @@ class SettingsWindow(Gtk.Window):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)- # Everything inside it (the hint stays out on its own): show_all() on the window stops at- # entry_row, so a wrapper left hidden here kept the field from ever appearing.self.entry_row.get_child().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)- # The check, step by step, while something is wrong or being checked; OpenRouter's balance.self.steps = ui.vbox(0)self.steps_card = ui.panel(ui.pad(self.steps, 2, 14), "boxed")self.steps_card.set_no_show_all(True)@@ -653,14 +601,12 @@ class SettingsWindow(Gtk.Window):self.balance_strip.set_no_show_all(True)page.pack_start(ui.vbox(6, title, self.custom_page, self.key_group, self.steps_card, self.balance_strip,ui.pad(self.lock_line, 0, 2, 0, 2)), False, False, 0)- # What works with it (a custom service says so in its own rows).self.uses = ui.vbox(0)self.uses_group = self._group(L("现在能用的"), self.uses)self.uses_group.set_no_show_all(True)- for w in self.uses_group.get_children(): # show_all() stops at a no_show_all widget+ for w in self.uses_group.get_children():w.show_all()page.pack_start(self.uses_group, 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()@@ -675,23 +621,15 @@ class SettingsWindow(Gtk.Window):fold.get_child().show_all()page.pack_start(ui.vbox(6, fold, self.models, ui.pad(self.footnote, 0, 2, 0, 2)), False, False, 0)- # 其他(兼容 OpenAI): AISettings.swift › customPage, on a port-def _custom_page(self) -> Gtk.Widget:- """One row per use, each opening to its fields and how it's doing, each at its own address if- need be (a text model, a speech model and an audio model often run as separate servers):- 翻译和纪要, 同传声音 and 听对方 (the hear model, which also hears what I say). The fields are- built once; show_key_state only rewrites the headers and the status under them."""s = self.app.settingsself.custom_open: set = set()self.custom_heads: dict = {}self.custom_bodies: dict = {}- # 翻译和纪要self.custom_base = self._field("http://192.168.1.20:8000/v1", s.aiCustomBase)self.custom_base_bad = ui.text(L("地址要用 https;这台电脑和局域网里的服务可以用 http。"), 11, "stepwhy", width_chars=46)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 = 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)@@ -703,7 +641,6 @@ 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)- # "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):b.set_valign(Gtk.Align.CENTER)@@ -720,7 +657,6 @@ class SettingsWindow(Gtk.Window):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)self.custom_voice_base = self._field(L("跟上面一样"), s.aiCustomVoiceBase)@@ -728,7 +664,6 @@ class SettingsWindow(Gtk.Window):ui.hbox(8, self._label(L("模型")), self.custom_voice_model),ui.hbox(8, self._label(L("声音")), self.custom_voice),ui.hbox(8, self._label(L("地址")), self.custom_voice_base))- # 听对方: the hear model, at the text model's address unless it has its own.self.custom_hear = self._field(L("例如 qwen3-omni"), s.aiHearModels.get("custom", ""))self.custom_hear_base = self._field(L("跟上面一样"), s.aiCustomHearBase)self.custom_hear_status = ui.vbox(4)@@ -740,8 +675,6 @@ class SettingsWindow(Gtk.Window):("hear", L("听对方"), hear_body)):rows.append(ui.vbox(0, self._custom_head(sid, title), self._custom_body(sid, body)))hint = ui.text(L("每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。"), 12, "tertiary", width_chars=60)- # 语音和文字只发给你的服务 (AISettings.swift › onlyRow): Google is never asked. The grey line says- # what it costs, and while the service can't be reached, that new lines are the original only.self.only_switch = Gtk.Switch()self.only_switch.set_active(s.aiCustomOnly)self.only_switch.connect("notify::active", self._only_toggled)@@ -757,11 +690,7 @@ 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.settingshead = ui.hbox(8, self._subgroup(L("纪要")))head.pack_end(ui.segmented([("same", L("同一个服务")), ("own", L("另一个服务"))],@@ -790,7 +719,6 @@ class SettingsWindow(Gtk.Window):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))@@ -817,7 +745,6 @@ class SettingsWindow(Gtk.Window):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 = Falseself.app.ai_changed()@@ -836,7 +763,6 @@ class SettingsWindow(Gtk.Window):(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.lingc = ling.config()own = notes and c.notes_apart and c.for_notes.base != c.base@@ -844,11 +770,9 @@ class SettingsWindow(Gtk.Window):@staticmethoddef _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 aicheckt, n = r.translate, r.notesif n is None:@@ -893,7 +817,6 @@ class SettingsWindow(Gtk.Window):return ldef _custom_head(self, sid: str, title: str) -> Gtk.Widget:- """A row that opens to its fields: a state dot, the use, what it runs on, and how it's doing."""dot = Gtk.Box()dot.set_valign(Gtk.Align.CENTER)ui.classes(dot, "statedot")@@ -901,7 +824,6 @@ class SettingsWindow(Gtk.Window):trailing = ui.text("", 12, "tertiary", wrap=False, ellipsize=False)chevron = ui.icon("pan-end-symbolic", 12)left = ui.vbox(2, ui.text(title, 13, "ink", wrap=False), detail)- # The middle takes the room left over and keeps its text at the start (not centred in it).row = ui.hbox(10, dot)row.pack_start(left, True, True, 0)row.pack_end(chevron, False, False, 0)@@ -934,7 +856,6 @@ class SettingsWindow(Gtk.Window):self.custom_key.set_placeholder_text(L("本机和局域网服务可不填") if typed and providers.is_nearby(typed) else "sk-…")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:@@ -954,7 +875,6 @@ class SettingsWindow(Gtk.Window):self.custom_save.set_visible(True)def _show_custom(self) -> None:- """The custom rows' headers and status, from the settings and the last check."""from ..core import aicheck, providersfrom . import aicheck_viewapp = self.app@@ -969,7 +889,6 @@ class SettingsWindow(Gtk.Window):sens = not r.runningself.custom_save.set_sensitive(sens)self.custom_save.set_label(L("正在检查…") if r.running else L("保存并检查"))- # 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@@ -982,10 +901,9 @@ class SettingsWindow(Gtk.Window):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+ self.notes_own.set_visible(s.aiCustomNotesOwn)def head(sid, state, detail, trailing, tone=""):dot, d, t, _ = self.custom_heads[sid]@@ -999,7 +917,6 @@ class SettingsWindow(Gtk.Window):t.get_style_context().remove_class(cls)t.get_style_context().add_class(tone or "tertiary")- # 翻译和纪要text_failed = f is not None and f[0] != "hear"notes_down = f is None and r.notes_failedif not have:@@ -1025,7 +942,7 @@ class SettingsWindow(Gtk.Window):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+ slow = r.slow_line(google_off=s.aiCustomOnly)if slow:self.custom_text_status.pack_start(ui.text(slow, 12, "warn", width_chars=46), False, False, 0)if have and aicheck_view.show_steps(r) and (text_failed or r.running or r.busy):@@ -1042,7 +959,6 @@ class SettingsWindow(Gtk.Window):elif r.reason == aicheck.NO_JSON:self.custom_text_status.pack_start(ui.text(L("纪要写不了"), 11, "tertiary", wrap=False), False, False, 0)self.custom_text_status.show_all()- # 同传声音voice = (s.aiVoiceModels.get("custom") or "").strip()vhost = urllib.parse.urlsplit(c.voice_base or "").hostname or hostlast = ling.last_voice@@ -1050,7 +966,6 @@ class SettingsWindow(Gtk.Window):" · ".join(x for x in (vhost, voice, s.aiCustomVoice.strip()) if x) if voice else L("没填,同声传译用不了"),L("用不了") if not voice else (L("上次正常") if last[0] else L("上次没出声")) if last else None,"stepwhy" if last is not None and not last[0] and voice else "")- # 听对方hear_st = r["hear"]hear_failed = f is not None and f[0] == "hear"hhost = ling.hear_host@@ -1076,14 +991,11 @@ class SettingsWindow(Gtk.Window):self.custom_hear_status.pack_start(ui.text(L("地址要用 https;这台电脑和局域网里的服务可以用 http。"), 12, "stepwhy",width_chars=46), False, False, 0)self.custom_hear_status.show_all()- # 语音和文字只发给你的服务: set by a debug command too. Linux has no translation of its own to- # stand in while the service can't be reached.on = s.aiCustomOnlyif self.only_switch.get_active() != on:- self.only_switch.set_active(on) # _only_toggled sees it already saved+ self.only_switch.set_active(on)down = on and have and not r.running and f is not None and f[1] != aicheck.BUSYui.retext(self.only_detail, L("现在连不上:新字幕暂时只有原文") if down else L("不用 Google 翻译;说话时要等整句说完才出译文"))- # A service that isn't set up yet, or doesn't work, opens where it needs filling in.if not getattr(self, "_custom_opened", False):self._custom_opened = Trueif not r.passed or r.slow:@@ -1091,7 +1003,6 @@ class SettingsWindow(Gtk.Window):@staticmethoddef _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)@@ -1119,7 +1030,6 @@ class SettingsWindow(Gtk.Window):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:@@ -1138,7 +1048,7 @@ class SettingsWindow(Gtk.Window):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+ w.get_child().set_text(mid)if mid != getattr(self.app.ling.config(), kind + "_model"):self.app.set_ai_model(kind, mid)c.connect("changed", chosen)@@ -1148,9 +1058,6 @@ class SettingsWindow(Gtk.Window):return cdef _uses_rows(self) -> list:- """现在能用的 (AISettings.swift › usage), with 听对方 first: on the ports the service hears. Only- what the last result supports: when the service can't be reached or the key fails, nothing- says "用 ZenMux" in green."""from ..core import aicheckling = self.app.lingc = ling.config()@@ -1182,12 +1089,10 @@ class SettingsWindow(Gtk.Window):else L("换一个模型后可用") if reason == aicheck.NO_MODEL else later)))rows.append((L("翻译"),) + ((uses, "ok", L("整句用它;不行时换 Google")) if text_on else("Google", "off", L("先用 Google 翻译") if ling.has_key else L("没有 key 时照常可用"))))- # 改正听错的词: on Linux one more text request per sentence (Ming already translated it).fix_on = text_on and self.app.settings.fixMisheardrows.append((L("改正听错的词"), uses if fix_on else L("已关") if text_on else off, "ok" if fix_on else "off",L("每句多发一次文字请求") if fix_on else L("在“词表”里打开") if text_on else later))if ling.speaks and hear_on:- # 同传 hears me with the hear model first, then speaks with the voice model.if ling.last_voice is not None:note = L("上次同传时正常") if ling.last_voice[0] else L("上次同传没出声")else:@@ -1217,7 +1122,7 @@ class SettingsWindow(Gtk.Window):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":- return [] # its models are in its own rows (_custom_page)+ return []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("纪要和整句翻译"))]@@ -1243,7 +1148,6 @@ class SettingsWindow(Gtk.Window):if r.running or state == lingmod.CHECKING:icon_name, cls, label = "content-loading-symbolic", "secondary", L("正在检查…")elif f is not None and f[1] != aicheck.BUSY:- # Named after the step that failed: a missing model is not a connection problem.label = {"reach": L("暂时连不上"), "key": L("这个 key 用不了")}.get(f[0], L("模型用不了"))icon_name, cls = "dialog-warning-symbolic", "warn"elif r.busy:@@ -1266,7 +1170,6 @@ class SettingsWindow(Gtk.Window):self.recheck_button.set_sensitive(not r.running)self.remove_button.set_visible(bool(k))self.entry_row.set_visible(not k or state == lingmod.INVALID or (self.entry_row.get_visible() and bool(self.key_hint.get_children())))- # The steps, rebuilt when they change.steps_key = (r.summary(), r.at is None, c.text_model, c.hear_model, have)if steps_key != getattr(self, "_steps_shown", None):self._steps_shown = steps_key@@ -1274,7 +1177,7 @@ class SettingsWindow(Gtk.Window):if have and aicheck_view.show_steps(r):self.steps.pack_start(aicheck_view.steps_widget(app, self._change_key, recheck_in_step=False), False, False, 0)self.steps.show_all()- self.steps_card.get_child().show_all() # show_all stops at a no_show_all widget+ self.steps_card.get_child().show_all()self.steps_card.set_visible(True)else:self.steps_card.set_visible(False)@@ -1293,21 +1196,18 @@ class SettingsWindow(Gtk.Window):self.uses_group.set_visible(not custom)self.fold.set_visible(not custom)if custom:- self.steps_card.set_visible(False) # under 翻译和纪要 instead+ self.steps_card.set_visible(False)self.models.set_visible(False)self._show_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("你填的地址")if custom:- # Where the key goes: every use's address, the notes' only while they share it.from ..core.providers import hostshost = _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:- # The user's own machines aren't billed by use; the audio still leaves this computer- # for the hear model's address (never 声音不出本机 on a port).from ..core.providers import is_nearbycost = L("跑在你自己的机器上,不按量计费。") if c.base and is_nearby(c.base) else L("费用以这个服务为准。")if app.settings.aiCustomOnly:@@ -1318,7 +1218,6 @@ class SettingsWindow(Gtk.Window):else:ui.retext(self.footnote, LF("听的时候,电脑里的声音会发给 %@。", name) if p.id == "ling"else L("按所选模型计费。") + LF("听的时候,电脑里的声音会发给 %@。", name))- # 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), r.reason, r.busy, app.ling.last_voice)if shown != getattr(self, "ai_shown", None):@@ -1341,7 +1240,6 @@ class SettingsWindow(Gtk.Window):def save_key(self) -> None:app, s = self.app, self.app.settingsif 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.text()notes_model = self.notes_model.text()@@ -1349,7 +1247,7 @@ class SettingsWindow(Gtk.Window):s.aiModels["custom.notes"] = notes_modelelse:s.aiModels.pop("custom.notes", None)- if s.aiCustomNotesOwn: # 同一个服务 keeps the address typed before+ if s.aiCustomNotesOwn: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()@@ -1361,8 +1259,6 @@ class SettingsWindow(Gtk.Window):text = entry.get_text().strip()self._show_key_hint(None)if text:- # The prefix says whose key it is: a management key can't call models, and another- # service's key goes there with one click (never a silent switch).from . import aicheck_viewhint = aicheck_view.key_hint(app, text)if hint is not None:@@ -1372,7 +1268,6 @@ class SettingsWindow(Gtk.Window):returnentry.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("")@@ -1404,7 +1299,6 @@ class SettingsWindow(Gtk.Window):w.show_all()def _change_key(self) -> None:- """更换 key from a failed step: the field opens, focused."""self.entry_row.set_visible(True)self.key_entry.grab_focus()@@ -1419,7 +1313,6 @@ class SettingsWindow(Gtk.Window):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:@@ -1428,12 +1321,6 @@ def _hosts_words(hosts: list) -> str: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_pickself.same_label = same_label@@ -1449,7 +1336,6 @@ class ModelPicker: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)@@ -1467,14 +1353,12 @@ class ModelPicker: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:@@ -1506,7 +1390,7 @@ class ModelPicker: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 ""+ self.pick(mid)def _enter(self) -> None:q = self.text()@@ -1514,12 +1398,10 @@ class ModelPicker: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 = Falseq = 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))diff --git a/linux/cicada/app/share_dialog.py b/linux/cicada/app/share_dialog.pyindex af5cdbb..7fc67c5 100644--- a/linux/cicada/app/share_dialog.py+++ b/linux/cicada/app/share_dialog.py@@ -1,6 +1,3 @@-"""分享…: a meeting as a link on cicada.indaloop.app (the Mac's ShareViews.swift). Settings, then the-server's review, then the link (and its password) or what the review stopped. A meeting already-shared opens on its link. The network runs on a worker thread; the dialog never blocks the app."""from __future__ import annotationsimport threading@@ -26,7 +23,6 @@ def client() -> ShareClient:def can_share(app, s) -> bool:- """Not while the meeting is still going, nor before an import has its text, nor with nothing in it."""has_notes = s.notes is not None and not s.notes.is_emptyreturn bool(s.lines or has_notes) and s.id != app.store.live and not s.importing@@ -59,7 +55,7 @@ class ShareDialog:d.connect("destroy", lambda *_: self._gone())self.window = dself.body = ui.vbox(16)- self.body.set_size_request(372, -1) # 420 with the padding, as on the Mac+ self.body.set_size_request(372, -1)d.get_content_area().pack_start(ui.pad(self.body, 24), True, True, 0)r = ShareStore.read(s.id)if r is not None and r.expiresAt > time.time():@@ -68,14 +64,11 @@ class ShareDialog:self.render()d.show_all()- # Steps-def render(self) -> None:ui.clear(self.body){"settings": self._settings, "working": self._working, "blocked": self._blocked, "done": self._done,"failed": self._failed}[self.step]()self.body.show_all()- # Shrink back after a taller step, once the new content has its size.GLib.idle_add(lambda: self.window is not None and self.window.resize(1, 1) and False)def _header(self, title: str) -> None:@@ -120,7 +113,6 @@ class ShareDialog:if self.show_options:self._options(go)else:- # The choices already made, in one line; 更改 opens them in place.line = ui.hbox(8)line.pack_start(ui.text(share.summary(self.use_password, self.days, self.names), 13, "secondary", wrap=False),True, True, 0)@@ -141,7 +133,6 @@ class ShareDialog:self.window.set_default(go)def _options(self, go) -> None:- """Password, expiry, names and the preview's summary, as the Mac lists them once 更改 is pressed."""def password(v):self.use_password = vself.render()@@ -217,11 +208,7 @@ class ShareDialog:row.set_size_request(-1, 80)self.body.pack_start(row, False, False, 0)- # Blocked-def _left_after(self) -> bool:- """Would anything be left to share once the flagged parts are out? (A notes-only share whose- notes were flagged has nothing; the server would refuse an empty document.)"""notes_left = self.has_notes and not self.drop_notes and not any(h.get("part") == "notes" for h in self.hits)if self.scope != "full":return notes_left@@ -240,7 +227,7 @@ class ShareDialog:quote = self.s.lines[lines[0]].src if lines else ""q = ui.text(quote, 12, "secondary", width_chars=44)q.set_lines(2)- q.set_ellipsize(Pango.EllipsizeMode.END) # two lines at most+ q.set_ellipsize(Pango.EllipsizeMode.END)box = ui.vbox(3, ui.text("%s · %s" % (what, place), 12, "ink", bold=True, width_chars=44), q)return ui.panel(ui.pad(box, 10), "sharehit")@@ -275,14 +262,10 @@ class ShareDialog:self.drop_notes = Trueself.go()- # Done-def _message(self, r) -> str:return share.clipboard_text(r, session_store.display_title(self.s))def _copy_control(self, r) -> Gtk.Widget:- """复制 puts the link and the password on the clipboard as one message; with a password, its- arrow copies either alone, for whoever sends them apart."""def copy(text, what):self._copy(text, what)self.render()@@ -390,8 +373,6 @@ class ShareDialog:self.body.pack_start(self._buttons(ui.button(L("关闭"), self.close, "outline"),ui.button(L("重试"), self.go, "darkbtn")), False, False, 0)- # Parts-def _copy(self, text: str, what: str) -> None:Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).set_text(text, -1)self.copied = what@@ -422,7 +403,6 @@ class ShareDialog:self.window.destroy()def state(self) -> dict:- """For the control socket: where the dialog is and what it shows."""r = self.recordreturn {"step": self.step, "session": self.s.id, "scope": self.scope, "days": self.days, "names": self.names,"password": self.use_password, "summary": self.summary, "busy": self.busy, "confirm": self.confirm,@@ -433,7 +413,6 @@ class ShareDialog:def open_for(app, s, parent=None) -> ShareDialog:- """The one share dialog: a new record replaces whatever was open."""old = getattr(app, "share_dialog", None)if old is not None:old.close()diff --git a/linux/cicada/app/tray.py b/linux/cicada/app/tray.pyindex fe042af..6786525 100644--- a/linux/cicada/app/tray.py+++ b/linux/cicada/app/tray.py@@ -1,7 +1,3 @@-"""The tray icon (the Mac's menu bar panel), through Ayatana AppIndicator: Ubuntu's top bar shows it-(the AppIndicator extension ships enabled), as do KDE, Xfce and most others. Ubuntu installs the C-library but not its GObject typelib, so it's called through ctypes with our own Gtk.Menu. Plain GNOME-has no tray; then there is none, and the records window's header bar carries 开始听 instead."""from __future__ import annotationsimport ctypes@@ -12,7 +8,6 @@ from ..core.support import Logdef _gpointer(obj) -> int:- """The C pointer behind a PyGObject object (its __gpointer__ capsule)."""get = ctypes.pythonapi.PyCapsule_GetPointerget.restype = ctypes.c_void_pget.argtypes = [ctypes.py_object, ctypes.c_char_p]@@ -51,7 +46,6 @@ class Tray:self.lib = libself.icon = icon or "cicada"self.badged = (False, None)- # An absolute path works as the icon "name", so no icon theme install is needed.self.ind = lib.app_indicator_new(b"cicada", (icon or "cicada").encode(), self.CATEGORY_APPLICATION_STATUS)lib.app_indicator_set_status(self.ind, self.STATUS_ACTIVE)lib.app_indicator_set_title(self.ind, L("知了").encode())@@ -71,21 +65,16 @@ class Tray:i.set_sensitive(sensitive)menu.append(i)return i- # The AI service when only the user can fix it (AIServiceStrip.swift, the panel's top): what's- # wrong, and a click opens 设置 › AI 服务. One that stays until the user changes something also- # puts the dot on the icon (below).from .aicheck_view import blocking, strip_wordsbroken = strip_words(self.app)if broken:item("⚠ " + broken[0].rstrip("。.") + " · " + L("打开设置"), lambda: self.app.show_settings(ai=True))menu.append(Gtk.SeparatorMenuItem())- # A new version, with the accent dot the Mac's panel gives it; greyed while it downloads.upd = self.app.updates.menu_label()if upd:item("● " + upd, self.app.updates.install, sensitive=self.app.updates.progress is Noneand not self.app.updates.after_meeting)menu.append(Gtk.SeparatorMenuItem())- # A status header, as the design's tray menu: what's happening, then the actions.self.status_item = item(self._status(), None, False)if listening:self.detail_item = item(self._detail(), None, False)@@ -93,7 +82,6 @@ class Tray:self.detail_item = Nonemenu.append(Gtk.SeparatorMenuItem())item(L("结束") if listening else L("开始听"), self.app.request_stop)- # 麦克风, the Mac panel's 打开麦克风: on mid-meeting, the room joins the same meeting.if self.app.listen.source_kind != "file" or not listening:mic = Gtk.CheckMenuItem.new_with_label(L("麦克风"))mic.set_active(self.app.mic_on)@@ -108,16 +96,13 @@ class Tray:menu.append(Gtk.SeparatorMenuItem())item(LF("退出 %@", L("知了")), self.app.quit)menu.show_all()- menu.connect("show", lambda *_: self.app.updates.menu_opened()) # an hour-old check: check again+ menu.connect("show", lambda *_: self.app.updates.menu_opened())self.lib.app_indicator_set_menu(self.ind, _gpointer(menu))- self.menu = menu # the indicator holds a ref too; keep ours so Python doesn't free it early+ self.menu = menuself.lib.app_indicator_set_label(self.ind, (self._clock() if listening else "").encode(), b"")self._badge(self.app.updates.update, blocking(self.app))def _badge(self, update, problem) -> None:- """The Mac's menu bar dot on the top-bar icon: the same icon with an orange dot top right, for- something only the user can fix or else a new version. The icon's description says which (the- Mac's tooltip; screen readers and the indicator read it)."""on = problem is not None or update is not Nonedesc = L("知了") + (" · " + problem if problem else " · " + LF("有新版本 %@", update.version) if update else "")if (on, desc) == self.badged:@@ -146,7 +131,6 @@ class Tray:return LF("%@ · %lld 句", session_store.display_title(s), len(s.lines))def tick(self) -> None:- """Once a second while listening: the clock in the top bar and the menu's header."""if not self.app.listen.listening:returnself.status_item.set_label(self._status())@@ -156,9 +140,6 @@ class Tray:def badged_icon(icon: str) -> str | None:- """A copy of the app icon (an SVG, 100 units square) with the accent dot over its top right- corner and a white ring around it, written once under the data folder. The logo itself stays- in one place (site/icon.svg); this only adds the dot."""try:with open(icon, encoding="utf-8") as f:svg = f.read()diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.pyindex c24ac38..5948580 100644--- a/linux/cicada/app/ui.py+++ b/linux/cicada/app/ui.py@@ -1,8 +1,3 @@-"""The look: the Mac app's, drawn with GTK (canvas "知了 Linux · 对齐 Mac"). Its palette (AGENTS.md ›-Design): ground #F3F4F6, white sheets, ink #15171C, one accent #E8552B for "live", greys #5A5F6B /-#6B7080. Sizes are the Mac's numbers in px (text() turns them into points, which GTK renders 4/3-larger); every widget the theme would draw (switches, dropdowns, title buttons) is styled here, so-Yaru's orange and its large controls never show."""from __future__ import annotationsimport math@@ -482,7 +477,6 @@ def install_css() -> None:def prefers_dark() -> bool:- """GNOME's 外观 › 深色 (org.gnome.desktop.interface color-scheme), else the GTK theme's name."""try:source = Gio.SettingsSchemaSource.get_default()if source and source.lookup("org.gnome.desktop.interface", True):@@ -503,9 +497,6 @@ def classes(widget, *names):return widget-# The language text is tagged with, so fontconfig picks the matching CJK face: Japanese kanji drawn-# with the Chinese font look wrong to a Japanese reader (and the other way round). No CJK family is-# named in the CSS for that reason. Set from the UI language at start; content passes its own.DEFAULT_LANG = "zh-cn"@@ -526,8 +517,6 @@ def text(s: str, size: int = 13, cls: str = "ink", bold: bool = False, wrap: booif wrap:l.set_line_wrap(True)l.set_line_wrap_mode(Pango.WrapMode.WORD_CHAR)- # Wrapped text asks for a modest width and takes what it's given, so a long English line- # doesn't stretch its window.l.set_max_width_chars(width_chars)elif ellipsize:l.set_ellipsize(Pango.EllipsizeMode.END)@@ -536,16 +525,12 @@ def text(s: str, size: int = 13, cls: str = "ink", bold: bool = False, wrap: boodef retext(l: Gtk.Label, s: str) -> None:- """New text in a label made by text(), keeping its size, weight and language (set_text would drop them)."""size, lang, bold = l.cicada_format- # `size` is the Mac's number, in px: Pango sizes are points (4/3 px at 96 dpi), so 0.75 of it;- # in points, GNOME's text scaling still applies. Bold is the Mac's semibold (Noto has no 600).l.set_markup('<span size="%d" lang="%s"%s>%s</span>' % (round(size * 768), lang, ' weight="bold"' if bold else "", esc(s)))def marked(s: str, terms: list, size: int = 13, cls: str = "ink", current: bool = False, lang: str | None = None,width_chars: int = 40) -> Gtk.Label:- """text() with every search term highlighted in place (the current match in the accent)."""from ..core.transcript_search import spansl = text(s, size, cls, lang=lang, width_chars=width_chars)merged = spans(s, terms)@@ -565,9 +550,6 @@ def marked(s: str, terms: list, size: int = 13, cls: str = "ink", current: booldef fixed(line, size: int = 13, cls: str = "ink", terms: list = (), current: bool = False, lang: str | None = None,width_chars: int = 40) -> Gtk.Label:- """A line as shown (改正听错的词): each fixed word underlined in grey (the Mac's dotted underline;- Pango has no dotted one), a word waiting for the user on a pale wash. While searching, the search- marks instead."""from ..core.correction import applyif terms or not line.fixes:return marked(line.shown, list(terms), size, cls, current, lang=lang or line.srcLang, width_chars=width_chars)@@ -595,7 +577,6 @@ def fixed(line, size: int = 13, cls: str = "ink", terms: list = (), current: boodef fixed_words(items, on_revert) -> Gtk.Widget:- """Under a line: each fixed word, what it was heard as, and 改回. `items`: [(line id, fix)]."""from ..core.correction import labelw = Wrap(6)for line_id, f in items:@@ -608,7 +589,7 @@ def fixed_words(items, on_revert) -> Gtk.Widget:row.pack_start(lab, False, False, 0)b = Gtk.Button(label=L("改回"))classes(b, "fixlink")- b.set_can_focus(False) # the notes window never takes focus+ b.set_can_focus(False)b.connect("clicked", lambda *_a, i=line_id, f=f: on_revert(i, f))row.pack_start(b, False, False, 0)w.add(panel(pad(row, 3, 8), "fixchip"))@@ -616,7 +597,6 @@ def fixed_words(items, on_revert) -> Gtk.Widget:def soft_button(label: str, on_click, dark: bool = False) -> Gtk.Button:- """The Mac's SoftButton: dark for the answer, soft grey for the rest. Never takes focus."""b = Gtk.Button(label=label)classes(b, "darkbtn" if dark else "softbtn")b.set_can_focus(False)@@ -625,8 +605,6 @@ def soft_button(label: str, on_click, dark: bool = False) -> Gtk.Button:def fix_toast(fixes, message: str) -> Gtk.Widget:- """The last fix decision said back (the Mac's FixToast): dark, with 撤销 while there is something- to undo. Shown in place, not as an overlay: the notes window lays out top to bottom."""row = hbox(14)row.pack_start(text(message, 13, "", wrap=False), True, True, 0)if fixes.can_undo:@@ -686,7 +664,6 @@ def icon_button(icon_name: str, tooltip: str, on_click, extra: str = "", px: intdef link(label: str, on_click) -> Gtk.Button:- """A text action inside a sentence: rendered as a flat link-coloured button."""b = Gtk.Button(label=label)classes(b, "quietbtn")b.set_relief(Gtk.ReliefStyle.NONE)@@ -695,10 +672,6 @@ def link(label: str, on_click) -> Gtk.Button:def status_line(tone: str, s: str, action: str | None = None, on_action=None) -> Gtk.EventBox:- """A service in trouble, said the same way wherever it shows (the Mac's StatusLine): a dot, what- waits for what · what still works, and at most one action. Colour sits in the dot only, so a- passing wait doesn't read as a fault: "waiting" (yellow) comes back by itself, "needsyou" (red)- needs the user, "info" (grey) is just so they know."""row = hbox(8)d = Gtk.Box()d.set_size_request(6, 6)@@ -714,7 +687,7 @@ def status_line(tone: str, s: str, action: str | None = None, on_action=None) ->b.add(text(action, 12, "ink", bold=True, wrap=False, ellipsize=False))classes(b, "quietbtn", "statusaction")b.set_relief(Gtk.ReliefStyle.NONE)- b.set_can_focus(False) # the notes window never takes focus+ b.set_can_focus(False)b.set_valign(Gtk.Align.CENTER)b.connect("clicked", lambda *_: on_action())row.pack_end(b, False, False, 0)@@ -766,7 +739,6 @@ def clear(box: Gtk.Container) -> None:def panel(widget, *cls) -> Gtk.EventBox:- """A styled container (GTK 3 boxes don't draw backgrounds; an EventBox does)."""e = Gtk.EventBox()e.add(widget)classes(e, *cls)@@ -774,7 +746,6 @@ def panel(widget, *cls) -> Gtk.EventBox:def segmented(options, current, on_change) -> Gtk.Box:- """Two or three linked toggles, one checked: GNOME's view switcher in miniature."""box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)classes(box, "segmented")buttons = {}@@ -798,7 +769,6 @@ def segmented(options, current, on_change) -> Gtk.Box:def boxed(rows) -> Gtk.Widget:- """A boxed list: rows separated by hairlines inside one rounded white card."""box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)for i, r in enumerate(rows):if i:@@ -809,8 +779,6 @@ def boxed(rows) -> Gtk.Widget:def prow(title: str, control: Gtk.Widget | None = None, subtitle: str | None = None, title_widget=None,subtitle_widget=None) -> Gtk.Widget:- """One preferences row: title (and a grey subtitle) on the left, its control on the right.- `subtitle_widget`: a grey line the caller rewrites later, in place of `subtitle`."""row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)left = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=1)left.set_valign(Gtk.Align.CENTER)@@ -838,8 +806,6 @@ def icon_tile(icon_name: str, size: int = 64, glyph: int = 30, tone: str = "") -def breathing_dot(small: bool = False) -> Gtk.Widget:- """BreathingDot: an accent dot with a ring swelling out of it ("live", without blinking).- small: the Mac's 6 px one (the records list)."""d = dot(True)if small:d.set_size_request(6, 6)@@ -849,8 +815,6 @@ def breathing_dot(small: bool = False) -> Gtk.Widget:def ring_pixbuf(fraction: float, px: int = 26, track: str = "#3A3D45", color: str = "#E8552B"):- """The countdown ring around the logo (ListenPill's ending state), as an SVG: Ubuntu ships the SVG- pixbuf loader but not the cairo bindings a drawn widget would need."""from gi.repository import GdkPixbufr = 11.75c = 2 * math.pi * r@@ -867,11 +831,9 @@ def ring_pixbuf(fraction: float, px: int = 26, track: str = "#3A3D45", color: stdef place_tag(line) -> Gtk.Widget:- """现场 / 线上 beside the other side's label in a meeting that heard both (the Mac's PlaceTag): filled- for the room microphone, outlined for the computer's audio."""room = line.via == "room"l = text(L("现场") if room else L("线上"), 10, "", wrap=False, ellipsize=False)- pad(l, 0, 5) # a margin: GTK 3 ignores CSS padding on an EventBox+ pad(l, 0, 5)c = panel(l, "placetag", *(["room"] if room else []))c.set_valign(Gtk.Align.CENTER)c.set_tooltip_text(L("会议室的麦克风听到的") if room else L("电脑里放出来的"))@@ -879,17 +841,14 @@ def place_tag(line) -> Gtk.Widget:def me_tag() -> Gtk.Widget:- """My own line (the Mac's MeTag): said through 同声传译, so what the other side heard was its- translation. 你 in the accent, then an outlined 同传 pill."""pill = text(L("同传"), 10, "", wrap=False, ellipsize=False)- pad(pill, 1, 5) # a margin: GTK 3 ignores CSS padding on an EventBox+ pad(pill, 1, 5)p = panel(pill, "metag")p.set_valign(Gtk.Align.CENTER)box = hbox(5)- box.set_halign(Gtk.Align.START) # the tooltip covers the tag, not the row+ box.set_halign(Gtk.Align.START)box.pack_start(text(L("你"), 11, "accent", bold=True, wrap=False, ellipsize=False), False, False, 0)box.pack_start(p, False, False, 0)- # Linux turns it on and off (开始说, the shortcut), it has no key to hold: not the Mac's tooltip.box.set_tooltip_text(L("同声传译时说的,对方听到的是译文"))return box@@ -897,15 +856,13 @@ def me_tag() -> Gtk.Widget:def chip(s: str, now: bool = False) -> Gtk.Widget:l = text(s, 11, "", bold=True, wrap=False, ellipsize=False)if now:- pad(l, 1, 6) # a margin: GTK 3 ignores CSS padding on an EventBox+ pad(l, 1, 6)c = panel(l, "chip", "now" if now else "time")c.set_valign(Gtk.Align.BASELINE)return cclass _Fraction(Gtk.Bin):- """Gives its child `fraction` of the width it is given (the Mac's GeometryReader), asking for none."""-def __init__(self, child: Gtk.Widget, fraction: float):super().__init__()self.fraction = fraction@@ -919,15 +876,11 @@ class _Fraction(Gtk.Bin):class Wrap(Gtk.Fixed):- """The Mac's FlowLayout: children left to right at their natural size, wrapping onto the next- line. (A FlowBox lines its children up in columns, which spreads a row of chips apart.)"""-def __init__(self, spacing: int = 6):super().__init__()self.spacing = spacingdef _lines(self, width: int):- """[(row height, [(child, x, w, h)…])…] for this width."""lines, row, x, h = [], [], 0, 0for c in self.get_children():if not c.get_visible():@@ -971,7 +924,6 @@ class Wrap(Gtk.Fixed):def skeleton(fraction: float = 1.0, height: int = 12) -> Gtk.Widget:- """SkeletonBar: a placeholder line with a light sweeping across it (the .skeleton CSS)."""bar = Gtk.Box()bar.set_size_request(-1, height)classes(bar, "skeleton", "thin" if height < 10 else "")@@ -979,7 +931,6 @@ def skeleton(fraction: float = 1.0, height: int = 12) -> Gtk.Widget:def sound_bars() -> Gtk.Widget:- """SoundBars: four small orange bars rising and falling, "listening" at the size of a line of text."""row = hbox(3)for i in range(4):b = Gtk.Box()@@ -990,9 +941,6 @@ def sound_bars() -> Gtk.Widget:class Toasts:- """GNOME-style toast at the bottom of a window: one at a time, an optional action, gone after- a few seconds (or when the next one comes). `on_timeout` runs when it expires unacted."""-def __init__(self, overlay: Gtk.Overlay):self.revealer = Gtk.Revealer()self.revealer.set_transition_type(Gtk.RevealerTransitionType.SLIDE_UP)@@ -1041,13 +989,10 @@ class Toasts:def loudness(rms: float) -> float:- """-50 dBFS (a quiet room) to 0 dBFS on a log scale, so speech sits mid-bar instead of pinning it."""return 0.0 if rms <= 0 else max(0.0, min(1.0, (20 * math.log10(rms) + 50) / 50))def no_wheel(combo: Gtk.ComboBox, scroll: Gtk.ScrolledWindow) -> None:- """A GTK 3 dropdown changes its value under the mouse wheel; scrolling a page past one would- silently change (and save) a setting. The wheel scrolls the page instead."""def wheel(_w, event):adj = scroll.get_vadjustment()ok, _dx, dy = event.get_scroll_deltas()diff --git a/linux/cicada/app/updater.py b/linux/cicada/app/updater.pyindex d6498e5..e68152c 100644--- a/linux/cicada/app/updater.py+++ b/linux/cicada/app/updater.py@@ -1,8 +1,3 @@-"""What the tray menu and 设置 › 关于 show about new versions (the Mac's Updates): a newer release, a-manual check's result, download progress, and why installing in place failed. Checks at launch and-every 4 hours (a 15-minute tick that checks when due, so a laptop that sleeps still checks); a dev-build checks only when CICADA_UPDATE_FEED points at a test feed. While a meeting is being recorded-the update waits for it to end (会后安装) instead of ending it."""from __future__ import annotationsimport os@@ -19,10 +14,6 @@ from ..core.support import Log, Pathsdef open_uri(url: str, done=None) -> None:- """Opens `url` in the browser, then calls done(opened) on the main thread: True only when- something said it took it: the browser GIO names for the scheme, else xdg-open exiting cleanly- (waited for on a thread, up to 10 s: it can take a while to try its fallbacks and fail). Logged: a page- that doesn't open leaves no other trace."""def tell(opened):if done is not None:GLib.idle_add(lambda: done(opened) and False)@@ -38,15 +29,13 @@ def open_uri(url: str, done=None) -> None:code = p.wait(10)except subprocess.TimeoutExpired:Log.d("open: xdg-open still running after 10 s")- tell(False) # unconfirmed: say where the page is rather than claim it opened- p.wait() # reaped whenever it ends+ tell(False)+ p.wait()returnif code != 0:Log.d("open: xdg-open exited %d" % code)tell(code == 0)- # The scheme's handler, asked for by name: launch_default_for_uri, without one, reads the page- # through gvfs to guess its type, which blocked the main loop for minutes behind a bad network.scheme = url.split(":", 1)[0]browser = Gio.AppInfo.get_default_for_uri_scheme(scheme)if browser is None:@@ -65,16 +54,14 @@ class Updates:def __init__(self, app):self.app = appself.update: updates.Update | None = None- self.check = "idle" # idle | checking | upToDate | failed (the last manual check)- self.progress: float | None = None # 0…1 while downloading; the app quits and reopens when done- self.failure: str | None = None # why the last in-place update failed- self.opened = False # and whether the release page opened then- self.after_meeting = False # 会后安装: install once this meeting ends+ self.check = "idle"+ self.progress: float | None = None+ self.failure: str | None = None+ self.opened = False+ self.after_meeting = Falseself.installing = Falseself.started = False- self._inflight = False # one check at a time (the tray menu's "show" also fires as it's built)- # When the last check started, failed or not: a failed one isn't remembered on disk, and the- # menu is rebuilt (firing "show") whenever a check ends, so offline it would check again at once.+ self._inflight = Falseself._last_try: float | None = None@property@@ -127,10 +114,7 @@ class Updates:GLib.idle_add(done)threading.Thread(target=run, name="Updates", daemon=True).start()- # Installing-def install(self) -> None:- """安装并重新打开; while listening, 会后安装 (the meeting isn't cut short)."""u = self.updateif u is None or self.installing:return@@ -140,14 +124,12 @@ class Updates:self.app.changed()returnif updates.install_root() is None:- # A checkout or a build tree, not an install.sh install: nothing to replace in place.self._fail(L("请先用 install.sh 安装知了"), u)returnself.installing, self.failure, self.progress = True, None, 0.0self.app.changed()def progress(p):- # Whole percents only: every 64 KB would rebuild the tray menu hundreds of times.if self.progress is not None and int(p * 100) == int(self.progress * 100):return@@ -176,7 +158,6 @@ class Updates:self.app.quit()def _fail(self, why: str, u) -> None:- """Opens the release page, then says why, and whether the page really opened."""def done(opened):self.installing, self.progress, self.failure, self.opened = False, None, why, openedLog.d("update: in place failed; release page %s" % ("opened" if opened else "didn't open"))@@ -184,9 +165,6 @@ class Updates:open_uri(u.url, done)def notify_if_due(self) -> None:- """One desktop notification per version, for people who never open the tray menu; a click- installs (会后安装 while a meeting is on). Held while listening or speaking: meeting_ended- tells. Withdrawn once there's nothing newer (installed, or the release was pulled)."""u = self.updateif u is None:self.app.application.withdraw_notification("update")@@ -213,7 +191,6 @@ class Updates:self.install()def reopened(self) -> str | None:- """After an update reopened the app: the line to show once (已更新到 …), or None."""r = updates.take_result()if r is None:return None@@ -224,10 +201,7 @@ class Updates:self.failure = L("安装没有完成")return LF("没能更新到 %@,还是原来的版本", r[1])- # What the UI shows-def menu_label(self) -> str | None:- """The tray menu's first item, or None (no update)."""u = self.updateif u is None:return None@@ -238,7 +212,6 @@ class Updates:return LF("新版本 %@", u.version) + " · " + L("安装并重新打开")def detail(self) -> str:- """The grey line under 版本 in 设置 › 关于."""u = self.updateif u is not None:if self.progress is not None:@@ -246,7 +219,6 @@ class Updates:if self.failure and self.opened:return LF("没能自动更新:%@。已打开下载页", self.failure)if self.failure:- # No browser came up: the address to type, selectable in 设置 › 关于.return LF("没能自动更新:%@。请在浏览器里打开 %@ 下载", self.failure, u.url.split("://", 1)[-1])if self.after_meeting:return LF("有新版本 %@", u.version) + " · " + L("会议结束后安装")diff --git a/linux/cicada/app/voice_clone.py b/linux/cicada/app/voice_clone.pyindex e3f672a..0080fb0 100644--- a/linux/cicada/app/voice_clone.py+++ b/linux/cicada/app/voice_clone.py@@ -1,6 +1,3 @@-"""我自己的声音 (the Mac's VoiceCloneSheet and VoiceRecorder): read a passage for 10–15 s, Ming hears-what it says, listen to the original and to the clone, then keep it (voice_reference). The-recording stays in memory until 用这个声音; the network runs on worker threads."""from __future__ import annotationsimport threading@@ -18,8 +15,6 @@ from . import uidef own_and_other(app) -> tuple:- """My language, and one to interpret it into (the room's, else English or Chinese): Ming hears- the recording through the interpreting prompt, whose ORIGINAL line is what it says."""mine = app.settings.speak_from_codeother = app.speak.targetif voicemod.key(other) == voicemod.key(mine):@@ -28,16 +23,12 @@ def own_and_other(app) -> tuple:def transcribe(app, samples: array) -> str:- """What the recording says, as Ming hears it; "" when it heard nothing usable."""mine, other = own_and_other(app)heard = app.translator.interpret(Wav.bytes(samples), mine, other)return heard[0].strip() if heard else ""class Recorder:- """The microphone into memory, 16 kHz mono, stopping by itself at 15 s. Phases as on the Mac:- idle, recording, checking (Ming hears it), ready, failed (`why`). `on_change` comes on the main loop."""-def __init__(self, app, on_change):self.app = appself.on_change = on_change@@ -56,7 +47,6 @@ class Recorder:return len(self.samples) / RATEdef start(self, source=None) -> None:- """`source`: an AudioSource (a WAV for tests); else the real microphone, not 知了 麦克风."""from .capture import SystemAudioself.cancel()self._gen += 1@@ -74,7 +64,7 @@ class Recorder:with self._lock:self.samples.extend(samples)if samples:- self.level = (sum(x * x for x in samples) / len(samples)) ** 0.5 / 32768.0 # RMS; ui.loudness shows it+ self.level = (sum(x * x for x in samples) / len(samples)) ** 0.5 / 32768.0def ended(why):if gen != self._gen:@@ -82,7 +72,7 @@ class Recorder:if why:Log.d("voice clone: microphone ended %s" % why)GLib.idle_add(lambda: self._fail(L("麦克风没收到声音,请检查麦克风权限")) or False)- else: # a file ran out+ else:GLib.idle_add(lambda: self.finish() or False)source.on_samples = gotsource.on_ended = ended@@ -118,7 +108,6 @@ class Recorder:self.on_change()def finish(self) -> None:- """Stops and has Ming hear it; ready when it is long enough, understood and not too slow."""if self.phase != "recording":returnself._stop()@@ -165,13 +154,11 @@ class Recorder:class VoiceCloneDialog:- """The sheet: record, then review. `on_done(saved)` when it closes."""-def __init__(self, app, parent=None, on_done=None):self.app = appself.on_done = on_doneself.consent = False- self.playing = None # "original" or "clone" while one plays+ self.playing = Noneself._play_gen = 0self.recorder = Recorder(app, self.render)d = Gtk.Dialog(transient_for=parent, modal=True)@@ -182,7 +169,7 @@ class VoiceCloneDialog:d.connect("destroy", lambda *_: self._gone())self.window = dself.body = ui.vbox(16)- self.body.set_size_request(504, -1) # 560 with the padding, as on the Mac+ self.body.set_size_request(504, -1)d.get_content_area().pack_start(ui.pad(self.body, 28), True, True, 0)self._last = Noneself.render()@@ -218,13 +205,10 @@ class VoiceCloneDialog:if cb:cb(saved)- # Layout-def render(self) -> None:if self.window is None:returnr = self.recorder- # The meter ticks ten times a second: only its labels change then, not the whole sheet.shape = (r.phase, r.why, self.consent, self.playing, self.app.ling.speaks)if shape == self._last and r.phase == "recording" and hasattr(self, "_clock"):ui.retext(self._clock, clock(r.seconds))@@ -326,7 +310,7 @@ class VoiceCloneDialog:row.pack_start(b, False, False, 0)words = ui.vbox(2, ui.text(title, 13, "ink", bold=True, wrap=False), ui.text(detail, 12, "tertiary", wrap=False))for l in words.get_children():- l.set_max_width_chars(36) # one line each, cut short, so the sheet keeps the Mac's width+ l.set_max_width_chars(36)row.pack_start(words, True, True, 0)if tag:t = ui.text(tag, 11, "", wrap=False)@@ -335,15 +319,12 @@ class VoiceCloneDialog:row.pack_end(t, False, False, 0)return ui.panel(ui.pad(row, 12, 14), "voicewash" if accent else "")- # Actions-def rerecord(self) -> None:self._play_gen += 1self.playing = Noneself.recorder.start()def play(self, which: str) -> None:- """The original from memory, or the clone saying the sample line, on the speakers."""from .room import Playerif self.playing == which:self._play_gen += 1diff --git a/linux/cicada/app/word_list.py b/linux/cicada/app/word_list.pyindex 0aaaf17..e077867 100644--- a/linux/cicada/app/word_list.py+++ b/linux/cicada/app/word_list.py@@ -1,6 +1,3 @@-"""设置 › 词表 (the Mac's WordListSettings.swift): the switches for 改正听错的词, and the word list itself-(core/vocabulary.py): each word, what it has been heard as, where it came from and how often it fixed-a line. Everything is edited in place; changes count from the next sentence on."""from __future__ import annotationsfrom gi.repository import Gdk, GLib, Gtk@@ -13,13 +10,13 @@ from . import uiclass WordList:def __init__(self, app, group):self.app = app- self.group = group # SettingsWindow._group+ self.group = groupself.query = ""- self.deleted = None # (term, index): shown in its place with 撤销 for a few seconds+ self.deleted = Noneself._deleted_at = 0- self.editing = None # the word whose spelling is being changed- self.conflict = None # (word, heard, owner): a heard form typed that another word has- self.typing = {} # word → text typed into its 加一个容易听错的词 (kept through a refresh)+ self.editing = None+ self.conflict = None+ self.typing = {}self._key = Noneself.box = ui.vbox(14)self.refresh()@@ -61,8 +58,6 @@ class WordList:False, False, 0)self.box.show_all()- # The switches-def _switches(self) -> Gtk.Widget:app, s = self.app, self.app.settingsling = app.ling@@ -86,8 +81,6 @@ class WordList:self.app.settings.save()GLib.idle_add(lambda: self.refresh() and False)- # The list-def _head(self, terms) -> Gtk.Widget:head = ui.hbox(10)head.pack_start(ui.text(L("词"), 13, "secondary", bold=True, wrap=False, ellipsize=False), False, False, 0)@@ -108,7 +101,6 @@ class WordList:return ui.gap(head, 4)def _shown(self, terms) -> list:- """Most recently useful first, then the rest newest first."""from datetime import datetime, timezoneoldest = datetime.min.replace(tzinfo=timezone.utc)ordered = sorted(reversed(terms), key=lambda t: t.used or oldest, reverse=True)@@ -233,11 +225,7 @@ class WordList:self.app.vocabulary.insert(term, index)self.refresh()- # 粘贴导入-def _import(self) -> None:- """Many words at once, one per line, heard forms after "=". The counts follow what is pasted,- and the button says how many go in."""voc = self.app.vocabularytop = self.box.get_toplevel()d = Gtk.Dialog(transient_for=top if isinstance(top, Gtk.Window) else None, modal=True)diff --git a/linux/cicada/app/x11.py b/linux/cicada/app/x11.pyindex 1dd3514..81992b9 100644--- a/linux/cicada/app/x11.py+++ b/linux/cicada/app/x11.py@@ -1,9 +1,3 @@-"""The X11 details GTK 3 doesn't cover. With set_accept_focus(False) GTK still lists-WM_TAKE_FOCUS in WM_PROTOCOLS, so on every click Mutter hands focus away from the meeting app for a-moment (the "globally active" input model) before giving it back; a blip a browser-based meeting app-sees as blur. Listing only WM_DELETE_WINDOW (the "no input" model) leaves focus alone. And a window-Mutter maps over the focused one without focusing it is marked as demanding attention, which GTK-can't take back (no_attention)."""from __future__ import annotationsimport ctypes@@ -33,12 +27,10 @@ def _lib():def never_take_focus(gdk_window) -> None:- """Drops WM_TAKE_FOCUS from an X11 window's protocols. No-op off X11."""_protocols(gdk_window, False)def take_focus(gdk_window) -> None:- """Lists WM_TAKE_FOCUS again, for the moment the window needs the keyboard (its search)."""_protocols(gdk_window, True)@@ -71,9 +63,6 @@ class _Event(ctypes.Union):def no_attention(gdk_window) -> None:- """Takes back _NET_WM_STATE_DEMANDS_ATTENTION (an EWMH request to the root window). The notes- window gets it whenever it's shown over the meeting app; the dock then counts it as urgent and- spends the next click of 知了's icon on it (it can't take focus) instead of the records window."""xid = gdk_window.get_xid() if hasattr(gdk_window, "get_xid") else Noneif not xid:return@@ -84,10 +73,10 @@ def no_attention(gdk_window) -> None:returne = _Event()m = e.xclient- m.type, m.send_event, m.window, m.format = 33, 1, xid, 32 # ClientMessage+ m.type, m.send_event, m.window, m.format = 33, 1, xid, 32m.message_type = x.XInternAtom(d, b"_NET_WM_STATE", 0)- m.data[0], m.data[1], m.data[3] = 0, x.XInternAtom(d, b"_NET_WM_STATE_DEMANDS_ATTENTION", 0), 1 # remove; from an app- x.XSendEvent(d, x.XDefaultRootWindow(d), 0, (1 << 19) | (1 << 20), ctypes.byref(e)) # Substructure Notify | Redirect+ m.data[0], m.data[1], m.data[3] = 0, x.XInternAtom(d, b"_NET_WM_STATE_DEMANDS_ATTENTION", 0), 1+ x.XSendEvent(d, x.XDefaultRootWindow(d), 0, (1 << 19) | (1 << 20), ctypes.byref(e))x.XFlush(d)x.XCloseDisplay(d)except OSError as e:diff --git a/linux/cicada/core/__init__.py b/linux/cicada/core/__init__.pyindex 1b42523..2ae2839 100644--- a/linux/cicada/core/__init__.py+++ b/linux/cicada/core/__init__.py@@ -1,2 +1 @@-"""The engines: no GTK, no third-party packages. A port of the Android engine (android/core),-itself a port of the Windows one; prompts and the record format are the Mac's."""+passdiff --git a/linux/cicada/core/aac.py b/linux/cicada/core/aac.pyindex f1d91d6..0149ca3 100644--- a/linux/cicada/core/aac.py+++ b/linux/cicada/core/aac.py@@ -1,23 +1,16 @@-"""The meeting's recording, as on the Mac (AudioFiles.swift): AAC written as ADTS (`system.aac`) while-the meeting runs, which stays readable up to the last frame if the app is killed, then rewrapped into-`system.m4a` without re-encoding once it ends (or at the next launch). The GStreamer side is-app/media.py; this is the part that needs no GStreamer, so it tests on the Mac."""from __future__ import annotationsimport os-SAMPLES_PER_FRAME = 1024 # AAC-LC+SAMPLES_PER_FRAME = 1024_RATES = (96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350)def partial(path: str) -> str:- """system.m4a → system.aac (AudioFileWriter.partial)."""return os.path.splitext(path)[0] + ".aac"def frames(data: bytes):- """(offset, length, sample rate) of each whole ADTS frame; stops at the first damaged or cut one- (a meeting the app didn't get to close ends mid-frame)."""i = 0n = len(data)while i + 7 <= n:@@ -36,8 +29,6 @@ def seconds(data: bytes) -> float:def cut(data: bytes, until: float | None) -> bytes:- """The whole frames up to `until` seconds (all of them for None): the silent tail of a meeting that- ended by itself goes, as the Mac's export timeRange cuts it, and a torn last frame always goes."""end = 0t = 0.0for off, length, rate in frames(data):@@ -49,7 +40,6 @@ def cut(data: bytes, until: float | None) -> bytes:def trim(path: str, until: float | None) -> None:- """Cuts the ADTS file at `path` in place (see cut)."""with open(path, "rb") as f:data = f.read()kept = cut(data, until)diff --git a/linux/cicada/core/aicheck.py b/linux/cicada/core/aicheck.pyindex cd7a677..a355bea 100644--- a/linux/cicada/core/aicheck.py+++ b/linux/cicada/core/aicheck.py@@ -1,12 +1,3 @@-"""What the last look at the AI service found, step by step (AICheck.swift, plus the ports' 听对方):-can this computer reach it, does it take the key, does the text model answer, does the hear model-take audio. A failed step stops the ones after it, so the settings can say exactly where it broke-and offer the one thing that fixes it.--Most of the time the answer comes from real requests (hearing, notes, translation): every call-reports back here, so a meeting keeps the steps current without an extra request. A check runs-only when the service, a model or the key changes, at launch, on 重新检查, and when the network-changes while the service was unreachable. Stdlib only: the Mac runs these tests too."""from __future__ import annotationsimport copy@@ -24,17 +15,13 @@ REASONS = (UNREACHABLE, BAD_ADDRESS, INVALID_KEY, MGMT_KEY, NO_CREDIT, NO_MODEL,RUNNING, OK, BUSY_STATE, FAIL, SKIPPED, UNTESTED = "running", "ok", "busy", "fail", "skipped", "untested"-# Below this many dollars left, OpenRouter's balance is worth a word.LOW_BALANCE = 0.5TOP_UP = "https://openrouter.ai/settings/credits"-# A custom service whose sentence takes this long often misses the 6 s a translation is given and-# falls back to Google (AICheck.Speed.slowAfter).SLOW_AFTER = 3.0@dataclass(frozen=True)class Speed:- """A custom service: how long one real sentence took, and whether the model thought first."""seconds: floatthinks: bool@@ -46,29 +33,19 @@ class Speed:@dataclass(frozen=True)class State:kind: str = UNTESTED- seconds: float | None = None # ok: how long the request that proved it took (None: proved by another step's)- reason: str | None = None # fail- code: int | None = None # fail: the HTTP status, when there was one+ seconds: float | None = None+ reason: str | None = None+ code: int | None = Noneclass AICheck:- """The steps in order, when the newest result came in, whether it came from a real request- (`passive`), the proxy hint after `unreachable`, and OpenRouter's balance. Replaced whole, never- changed in place once shown: engine threads and the UI read it at the same time."""-def __init__(self):self.steps = {s: State() for s in STEPS}self.at: float | None = Noneself.passive = False- # proxy.hint: ("system",) a proxy is in use; ("dead", "host:port") it doesn't answer; ("pac",)- # GNOME's is automatic; ("app", port) a proxy app listens but no proxy is set; ("none",).self.proxy: tuple | None = Noneself.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 = Nonedef copy(self) -> "AICheck":@@ -82,7 +59,6 @@ class AICheck:@propertydef failure(self):- """(step, reason, code) of the first step that failed, else None."""for s in STEPS:st = self.steps[s]if st.kind == FAIL:@@ -100,7 +76,6 @@ class AICheck:@propertydef 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@@ -109,13 +84,10 @@ class AICheck:@propertydef passed(self) -> bool:- """Every step passed (busy counts; a step nothing has tested yet does not block)."""return self.at is not None and self.failure is None and not self.running@propertydef slow(self) -> bool:- """Text works but every sentence is slow (a thinking model): translations will fall back.- The hear model is a job of its own here: one that isn't set yet or can't hear doesn't hide it."""f = self.failurereturn (f is None or f[0] == "hear") and self.translate is not None and self.translate.slow@@ -125,7 +97,6 @@ class AICheck:@propertydef needs_user(self) -> bool:- """Something only the user can fix (a busy service, or one that errs, fixes itself)."""f = self.failureif f is None:return self.low_balance@@ -133,14 +104,10 @@ class AICheck:@propertydef down(self) -> bool:- """Nothing AI works: the service can't be reached, or won't take the key. A hear model at an- address of its own that can't be reached leaves the text model working."""f = self.failurereturn f is not None and f[0] != "hear" and f[1] in (UNREACHABLE, BAD_ADDRESS, INVALID_KEY, MGMT_KEY, NO_CREDIT)def fail(self, step: str, reason: str, code: int | None = None, reached: bool = True) -> None:- """`step` failed and the ones after it were never reached. `reached`: a reply came back, so- the steps before it passed (False when nothing was sent, like a management key)."""after = Falsefor s in STEPS:if s == step:@@ -154,8 +121,6 @@ class AICheck:self.proxy = Nonedef pass_up_to(self, step: str, seconds: float | None) -> None:- """One request proved every step up to `step` (a chat proves the address, the key and the- model). Clears what failed before; skipped steps after it are open again."""after = Falsefor s in STEPS:if after:@@ -168,10 +133,7 @@ class AICheck:self.steps[s] = State(OK)self.proxy = None- # Words-def message(self, service: str, host: str, text_model: str, hear_model: str) -> str | None:- """Why the failed step failed, in one sentence."""f = self.failureif f is None:return LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service) if self.busy else None@@ -184,15 +146,12 @@ class AICheck:NO_CREDIT: lambda: LF("%@ 账户余额不足。", service),NO_MODEL: lambda: LF("%@ 上找不到 %@ 这个模型。", service, text_model),NO_JSON: lambda: L("这个服务不支持 JSON,纪要写不了;翻译照常。"),- DEAF: lambda: LF("%@ 听不了声音。", hear_model or service), # no hear model yet: the service+ DEAF: lambda: LF("%@ 听不了声音。", hear_model or service),BUSY: lambda: LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service),SERVER_ERROR: lambda: LF("%@ 暂时出错(HTTP %lld),稍后再试。", service, code or 0),}[reason]()def slow_line(self, google_off: bool = False) -> str | None:- """Why translations are slow, and what to do (a custom service). Linux falls back to Google- too (Translator.translate, 6 s), so the Mac's words hold; with 语音和文字只发给你的服务- (`google_off`) a sentence over 6 s is given up on instead (AICheck.slowLine(googleOff:))."""if not self.slow:return Nonesecs = "%.1f" % self.translate.seconds@@ -205,8 +164,6 @@ class AICheck: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.notesif n is None or n.kind != FAIL:return None@@ -224,32 +181,25 @@ class AICheck:}.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- # A server on this computer or the local network: a proxy has nothing to do with it.if self.reason != UNREACHABLE or self.proxy is None or is_nearby(host):return Noneif self.proxy[0] == "system":return LF("开了代理也连不上:换一个节点,或检查代理软件是否放过 %@。", host)if self.proxy[0] == "dead":- # Linux: the proxy requests go through (the environment's or GNOME's) doesn't answer.return LF("代理 %@ 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。", self.proxy[1])if self.proxy[0] == "pac":- # GNOME's "automatic" needs a PAC file evaluated, which the app can't: requests go direct.return L("系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。")if self.proxy[0] == "app":- # As text: a number would be grouped ("7,890") on the Mac, which keys it this way.return LF("代理软件在运行(端口 %@),但没开系统代理。在代理软件里打开“系统代理”。", str(self.proxy[1]))return LF("这台电脑没开代理。在国内通常要开代理才能用 %@。", service)def balance_line(self, service: str) -> str | None:- """"OpenRouter 余额快用完了(还剩 $0.40)" when it is."""if not self.low_balance:return Nonereturn LF("%@ 余额快用完了(还剩 $%@)", service, "%.2f" % max(0.0, self.balance))def summary(self) -> str:- """Debug and logs: "reach=ok key=fail(invalidKey) text=skipped hear=skipped"."""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))@@ -278,9 +228,7 @@ def title(step: str, host: str) -> str:def classify(e: LingError, at: str, audio: bool = False):- """(step, reason, code) a failed request stops at, or None when it says nothing about the- service. `at` is the step the request was proving; `audio`: it carried audio for the hear model."""- from .ling import LingError # here: ling.py imports this module+ from .ling import LingErrork = e.kindif k in (LingError.NETWORK, LingError.TIMEOUT):return "reach", UNREACHABLE, None@@ -289,7 +237,7 @@ def classify(e: LingError, at: str, audio: bool = False):if k == LingError.RATE_LIMITED:return at, BUSY, Noneif k != LingError.HTTP:- return None # no key, a search essay, an unreadable reply+ return Nonecode = e.statusif code == 402:return "key", NO_CREDIT, code@@ -301,8 +249,6 @@ def classify(e: LingError, at: str, audio: bool = False):def owner(key: str):- """(service id, management) the prefix of a key says it belongs to: `sk-or-` OpenRouter,- `sk-payg` ZenMux, `sk-mgmt` ZenMux's management key (it can't call models). None: can't tell."""k = (key or "").strip()if k.startswith("sk-or-"):return "openrouter", False@@ -314,9 +260,6 @@ def owner(key: str):def listed(data) -> tuple:- """(every model id, the ids that take audio in) from a `/models` reply, as listed: unlike the- menus' catalog, recommended models are not added, so one the service dropped shows. Either is- None when the reply can't tell (no list; no model that declares its input modalities)."""root = parse_object(data) if isinstance(data, str) else dataids, hear, declared = set(), set(), Falsefor m in arr((root or {}).get("data")):@@ -336,8 +279,6 @@ def listed(data) -> tuple:def balance(key_info, credits) -> float | None:- """OpenRouter: dollars left from `/key` (`limit_remaining`, null without a key limit) and- `/credits` (bought minus used); the smaller one is what the next meeting can spend."""k = (obj((obj(key_info) or {}).get("data")) or {}).get("limit_remaining")k = float(k) if isinstance(k, (int, float)) and not isinstance(k, bool) else Noned = obj((obj(credits) or {}).get("data")) or {}@@ -348,7 +289,6 @@ def balance(key_info, credits) -> float | None:def simulated(reason: str) -> AICheck:- """A made-up result for `reason` (debug screenshots of every state)."""r = AICheck()if reason == BUSY:r.pass_up_to("hear", 1.4)@@ -367,14 +307,13 @@ def simulated(reason: str) -> AICheck:r.fail("hear", reason, 400)elif reason == SERVER_ERROR:r.fail("text", reason, 503)- else: # lowBalance: everything passed+ else:r.pass_up_to("hear", 1.4)r["text"] = State(OK, 1.2)return rdef relative(at: float, now: float | None = None) -> str:- """"12 分钟前开会时用过", from when a meeting last proved the service."""ago = max(0, int((now if now is not None else time.time()) - at))if ago < 60:return L("刚刚开会时用过")@@ -386,6 +325,5 @@ def relative(at: float, now: float | None = None) -> str:def help_url(language: str) -> str:- """The website's proxy help, in the UI language."""prefix = next(("/" + p for p in ("en", "ja", "ko") if (language or "").startswith(p)), "")return "https://cicada.indaloop.app%s/start/#proxy" % prefixdiff --git a/linux/cicada/core/audio.py b/linux/cicada/core/audio.pyindex e14f143..85a2d2a 100644--- a/linux/cicada/core/audio.py+++ b/linux/cicada/core/audio.py@@ -1,6 +1,3 @@-"""Where listening gets its sound: 16 kHz mono Int16 (array('h')), pushed from any thread. On Linux-the PulseAudio/PipeWire monitor of the speakers (app/capture.py); in tests, the CLI and the sample-meeting, a file."""from __future__ import annotationsimport math@@ -14,8 +11,6 @@ RATE = 16000class AudioSource:- """Set on_samples / on_ended before start(); both are called on the source's own thread.- on_ended(None) when a file finished, else why the source stopped."""on_samples = Noneon_ended = None@@ -27,8 +22,6 @@ class AudioSource:class PcmAudioSource(AudioSource):- """Plays 16 kHz samples into listening, in real time or as fast as it can (`speed` 0)."""-def __init__(self, load, speed: float = 1.0):self._load = load if callable(load) else (lambda: Wav.read_file(load))self.speed = speed@@ -41,13 +34,13 @@ class PcmAudioSource(AudioSource):def _run(self) -> None:try:pcm = self._load()- except Exception as e: # noqa: BLE001 - any unreadable file ends the source+ except Exception as e: # noqa: BLE001from .support import LogLog.d("file source: unreadable %s" % type(e).__name__)if self.on_ended:self.on_ended("unreadable")return- chunk = RATE // 10 # 100 ms, like a capture callback+ chunk = RATE // 10started = time.monotonic()i = 0while i < len(pcm) and not self._stopped:@@ -58,7 +51,6 @@ class PcmAudioSource(AudioSource):if wait > 0:time.sleep(wait)i += chunk- # A second of silence so the last sentence's pause is heard.if self.on_samples and not self._stopped:self.on_samples(array("h", bytes(RATE * 2)))if self.on_ended:@@ -89,7 +81,6 @@ class Wav:@staticmethoddef read(data: bytes) -> array:- """A PCM16 WAV of any rate and channel count, as 16 kHz mono."""if data[:4] != b"RIFF" or data[8:12] != b"WAVE":raise ValueError("not a WAV")pos = 12@@ -121,7 +112,6 @@ class Wav:@staticmethoddef resample(mono, rate: int) -> array:- """Box average then pick: plenty for speech going to a recognizer."""def clamp(x):return int(max(-32768, min(32767, x)))if rate == RATE:@@ -143,8 +133,6 @@ class Wav:def sink_description(pactl_sinks: str, name: str) -> str | None:- """The description of sink `name` in `pactl list sinks` output (the onboarding shows the default- output by it). The field names are English under LC_MESSAGES=C; the description stays translated."""if not name:return Nonecurrent = Nonediff --git a/linux/cicada/core/correction.py b/linux/cicada/core/correction.pyindex afe0eb2..a48b3bb 100644--- a/linux/cicada/core/correction.py+++ b/linux/cicada/core/correction.py@@ -1,5 +1,3 @@-"""改正听错的词: which of the AI service's proposed fixes to take, and the line as shown once they are-in. A port of the Mac's Correction.swift, rule for rule (its tests are in tests/test_fixes.py)."""from __future__ import annotationsimport os@@ -10,14 +8,10 @@ from .models import LineFixdef _word(c: str) -> bool:- """A character of a Latin word: ASCII letters and digits."""return c.isascii() and c.isalnum()def core(frm: str, to: str) -> tuple:- """The part an edit changes, as a word: "解除质压" → "解除质押" is "质压" → "质押" (at least two- characters, so one refusal doesn't block every 压 → 押), and a Latin word stays whole- ("Un450P三" → "Uniswap V3", not "450P三" → "iswap V3")."""a, b = frm, toi = 0while i < min(len(a), len(b)) and a[i] == b[i]:@@ -28,14 +22,12 @@ def core(frm: str, to: str) -> tuple:def from_edge(k):return (k < len(a) and _word(a[k])) or (k < len(b) and _word(b[k]))- # Only a change that starts or ends inside a Latin word takes the rest of the word.if from_edge(i):while i > 0 and _word(a[i - 1]):i -= 1if (len(a) - j - 1 >= 0 and _word(a[len(a) - j - 1])) or (len(b) - j - 1 >= 0 and _word(b[len(b) - j - 1])):while j > 0 and _word(a[len(a) - j]):j -= 1- # Two characters at least, taken from the Chinese side: "FFT制押" → "FFT质押" is "制押" → "质押".while len(a) - j - i < 2 or len(b) - j - i < 2:if j > 0 and not _word(a[len(a) - j]):j -= 1@@ -48,15 +40,10 @@ def core(frm: str, to: str) -> tuple:def label(f) -> tuple:- """A fix as the UI names it (听成 X → Y, 已改回 X): the changed words, or the whole fix when it- only adds or drops words ("in" → "in now", whose changed part alone would be "" → "now")."""cf, ct = core(f.from_, f.to)return (f.from_, f.to) if not cf or not ct else (cf, ct)def word(s: str, text: str) -> int:- """Where `s` stands as words of its own in `text` (its offset, or -1): a Latin edge of it never runs- on into a Latin word around it. `core` pads a fix to two characters, so the word list learned- "S平 → X平", which matched inside "iOS平台" and made it "iOX平台"."""if not s:return -1i = text.find(s)@@ -70,11 +57,8 @@ def word(s: str, text: str) -> int:def apply(fixes: list, src: str) -> tuple:- """The line as shown: each applied fix replaces its words where they still are. The marks are the- replaced words as (start, end) character offsets into the text, for the underline."""text = src- spans = [] # replacement and its character offset, kept valid as the text changes- # The user's own last: written against the line as it was shown, other fixes in.+ spans = []ordered = [f for f in fixes if f.user is not True] + [f for f in fixes if f.user is True]for f in ordered:if not f.applied or not f.from_:@@ -92,11 +76,6 @@ def apply(fixes: list, src: str) -> tuple:return text, marks-# Deciding which of the service's proposed fixes to take, without asking it again. Its own confidence-# isn't enough: in a 21-minute test it rated "快销 → 区块" and "苍蝇 → 方向" above 0.85. So a Chinese-# word may only be swapped for one that sounds alike, a Latin word only for a near spelling, and a new-# name only once the user says so.-APPLY, ASK, DROP = "apply", "ask", "drop"APPLY_AT = 0.6SPELLING_AT = 0.8@@ -105,15 +84,12 @@ ASK_AT = 0.8@dataclassclass Edit:- """A fix the service proposed: the subtitle's words, what was said, how sure it is."""from_: strto: strconfidence: floatdef decide(e: Edit, known, rejected) -> str:- """`known(heard, word)`: the user confirmed this heard form for this word (the word list).- `rejected(heard, word)`: they said no to it in this meeting."""cf, ct = core(e.from_, e.to)if not cf or not ct or cf.lower() == ct.lower() or rejected(e.from_, e.to) or rejected(cf, ct):return DROP@@ -128,22 +104,16 @@ def decide(e: Edit, known, rejected) -> str:if latin_from and latin_to and cf.isascii() and ct.isascii() and e.confidence >= SPELLING_AT \and cf.lower() != ct.lower() and distance(cf.lower(), ct.lower()) <= 2:return APPLY- # A new name (Chinese heard as a Latin name, or a respelled one): sound can't check it. A- # name has a capital or a digit; "X平台 → X platform" is a translation, and one 对 to it- # taught the word list 平台 → platform, which then rewrote every 平台 in the meeting.if latin_to and e.confidence >= ASK_AT and name_shaped(ct):return ASKreturn DROPdef name_shaped(s: str) -> bool:- """Latin text that could be a name: a capital or a digit in it (Morpho, GPT4o), not "platform"."""return any(c.isascii() and (c.isupper() or c.isdigit()) for c in s)def translation(heard: str, word: str) -> bool:- """A Chinese word "fixed" into a plain English one (平台 → platform): a translation, not a- misheard name."""return han(heard) and any(_latin_letter(c) for c in word) and word.isascii() and not name_shaped(word)@@ -151,10 +121,6 @@ def _latin_letter(c: str) -> bool:return c.isascii() and c.isalpha()-# Toneless pinyin per character. Ubuntu's Python has no Mandarin transform, so the table is the Mac's-# own: generated once from Apple's ICU/CLDR Han-Latin transform (kCFStringTransformMandarinLatin, then-# diacritics stripped) for U+4E00–U+9FFF, 20,924 characters, one "<char>\t<syllable>" per line. Data,-# not a dependency; the same readings the Mac compares, so both decide alike._PINYIN: dict | None = None@@ -172,7 +138,6 @@ def _table() -> dict:def pinyin(s: str) -> list:- """One toneless syllable per character; a character the table doesn't know stays itself."""t = _table()return [t.get(c, c.lower()) for c in s]@@ -189,8 +154,6 @@ def _split(syllable: str) -> tuple:def sounds_alike(a: str, b: str) -> bool:- """Same number of syllables, and on average three quarters alike: a syllable counts whole when- equal, half when its initial or its final matches (质/追, 销/照). 苍蝇/方向 is a quarter."""x, y = pinyin(a), pinyin(b)if len(x) != len(y) or not x:return False@@ -207,7 +170,6 @@ def sounds_alike(a: str, b: str) -> bool:def han(s: str) -> bool:- """Every character a Han ideograph (Swift's isIdeographic)."""def ideograph(c):o = ord(c)return (0x3400 <= o <= 0x4DBF or 0x4E00 <= o <= 0x9FFF or 0xF900 <= o <= 0xFAFF or 0x20000 <= o <= 0x3134F@@ -228,11 +190,6 @@ def distance(a: str, b: str) -> int:def parse(reply: str, subtitle: str):- """The service's reply to a sentence sent with fixes asked for: {"translation": "…", "fixes":- [{"from", "to", "confidence"}]} → (translation, [Edit]). None when it isn't that shape, and the- caller treats it as a failed translation. Fixes whose words aren't in the subtitle are dropped:- the service sometimes quotes them rephrased."""- # Asked for JSON in the prompt only: take the outermost {…}, fenced or not.a, b = reply.find("{"), reply.rfind("}")if a < 0 or b <= a:return None@@ -251,9 +208,6 @@ def parse(reply: str, subtitle: str):def merge(old: list, new: list) -> list:- """What a line's fixes become after the service answered for it again (a joined line, or a- recheck with the lines after it in view): the user's decisions stay (said no, said yes, wrote it),- and of the rest only what is proposed again. So a recheck that no longer proposes a fix takes it back."""kept = [f for f in old if f.off is True or f.user is True]fresh = []for n in new:@@ -264,14 +218,6 @@ def merge(old: list, new: list) -> list:def user_edit(shown: str, edited: str, src: str, fixes: list):- """改这句…: the user rewrote the line as shown. What changed, as a fix on top of the others: the- changed span grown to whole tokens (a Latin word, or one CJK character), and further, a token at a- time, until it holds a letter and is the only such span in the line. An added word ("lock that- in." → "lock that in now.") is then "in" → "in now" on this line, never "." on every line.- `swap` is whether words were replaced (not only added or dropped): only a swap may go to the rest- of the meeting and teach the word list. `heard` is the words in `src` when they are there, else- the heard words of the fix the user corrected again ("莫纳" → "Morpho" → "Monad").- (fix, heard, swap), or None: no change (Correction.swift's userEdit)."""new = edited.strip()if not new or new == shown:return None@@ -286,7 +232,6 @@ def user_edit(shown: str, edited: str, src: str, fixes: list):def latin(c: str) -> bool:return c.isascii() and c.isalnum()- # Tokens of the shown line, as (start, end): a run of ASCII letters and digits, else one character.tokens = []k = 0while k < len(a):@@ -304,7 +249,6 @@ def user_edit(shown: str, edited: str, src: str, fixes: list):t = next((t for t in tokens if t[0] <= end - 1 < t[1]), None)if t is not None:end = t[1]- # A dropped word ("in now." → "in.") grows too, so neither side of the fix is empty.while True:span = a[start:end]if any(c.isalnum() for c in span) and span and a.count(span) == 1 and b[start:len(b) - (len(a) - end)]:diff --git a/linux/cicada/core/ed25519.py b/linux/cicada/core/ed25519.pyindex 96333bb..5cf4c9d 100644--- a/linux/cicada/core/ed25519.py+++ b/linux/cicada/core/ed25519.py@@ -1,8 +1,3 @@-"""Ed25519 signatures (RFC 8032), for the share service's device key (share.py). Python's standard-library has none, Ubuntu desktop's libsodium isn't always there, and the Mac's stub libcrypto-aborts when loaded, so this is the RFC's reference algorithm in plain Python: extended twisted-Edwards coordinates, a few milliseconds a signature. Not constant-time; the key only names this computer-to the share service (rate limits, owning its links), and each link also needs its own token."""from __future__ import annotationsimport hashlib@@ -29,7 +24,7 @@ def _add(p, q):def _mul(s: int, p):- q = (0, 1, 1, 0) # the neutral point+ q = (0, 1, 1, 0)while s > 0:if s & 1:q = _add(q, p)diff --git a/linux/cicada/core/folder_export.py b/linux/cicada/core/folder_export.pyindex 7b1e186..d7e1e33 100644--- a/linux/cicada/core/folder_export.py+++ b/linux/cicada/core/folder_export.py@@ -1,10 +1,3 @@-"""存到文件夹: a settled meeting written as one Markdown file into a folder the user chose-(docs/folder-export.md, the Mac's FolderExport.swift). The file name and frontmatter are a contract-with the Mac and the other ports (Tests/fixtures/folder-export); the body is 导出…'s Markdown.--The exporter keeps an index beside the records (FolderExport.json): the folder, each record's file-and the records still to write. Every write runs on one worker thread, in order: rendering, writing-and updating the index, so two flushes never race over the same file."""from __future__ import annotationsimport errno@@ -20,22 +13,16 @@ from . import jsonfmt, session_storefrom .models import iso_read, iso_write, nowfrom .support import Log, Paths-DENIED = "denied" # the folder won't let Cicada write (its permissions)-MISSING = "missing" # the folder, or the drive it was on, is gone-FAILED = "failed" # anything else; `problem_message` says what+DENIED = "denied"+MISSING = "missing"+FAILED = "failed"PROBE = ".cicada-check"-# Path, wildcard and link characters some system or vault refuses (vaults sync between systems,-# so the union of their rules)._BANNED = set('/\\:*?"<>|#^[]')-# The format-def name(s) -> str:- """The record's own name: what the user called it, else the notes' title, else the imported- file's name. Never display_title, which is localized and carries a date."""renamed = s.renamed if s.renamed is not None else not s.title.startswith("会议 ")if renamed:return s.title@@ -51,8 +38,6 @@ def _trim(s: str) -> str:def safe_name(n: str) -> str:- """At most 120 UTF-8 bytes, cut at a code point (the spec's cut; Python's stdlib has no- grapheme clusters, and the Mac cuts at scalars too)."""spaced = "".join(" " if c in _BANNED or ord(c) < 0x20 else c for c in n)out = _trim(" ".join(spaced.split()))if len(out.encode("utf-8")) > 120:@@ -71,7 +56,6 @@ def _local(at: datetime, tz=None) -> datetime:def _offset(at: datetime) -> str:- """+08:00, +00:00 for UTC (never Z)."""off = at.utcoffset() or timedelta(0)minutes = int(off.total_seconds()) // 60sign = "-" if minutes < 0 else "+"@@ -91,7 +75,6 @@ def stem(s, tz=None) -> str:def file_name(st: str, taken) -> str:- """`stem.md`, or `stem 2.md`, `stem 3.md`… while `taken(name)` says that one is."""n = 1while True:candidate = "%s.md" % st if n == 1 else "%s %d.md" % (st, n)@@ -101,8 +84,6 @@ def file_name(st: str, taken) -> str:def quote(s: str) -> str:- """A JSON-style double-quoted string, which YAML reads as is. Not json.dumps: it writes \\b and- \\f, where the contract wants \\u0008 and \\u000c."""out = ['"']for c in s:if c == "\\":@@ -125,7 +106,7 @@ def quote(s: str) -> str:def frontmatter(s, tz=None) -> str:ended = s.endedAt or s.startedAt- languages = sorted({l.srcLang for l in s.lines}) # str order is code point order+ languages = sorted({l.srcLang for l in s.lines})notes = "none" if s.notes is None or s.notes.is_empty else ("final" if s.notes.final else "draft")minutes = max(0, int((ended - s.startedAt).total_seconds() // 60))return "".join([@@ -145,21 +126,16 @@ def frontmatter(s, tz=None) -> str:def document(s, voices: bool = False) -> str:- """The frontmatter, then exactly what 导出… writes."""return frontmatter(s) + session_store.markdown(s, voices=voices)-# Where to put it-def obsidian_configs() -> list:- """Obsidian's obsidian.json: the .deb / AppImage one, then the Flatpak's."""config = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")return [os.path.join(config, "obsidian", "obsidian.json"),os.path.expanduser("~/.var/app/md.obsidian.Obsidian/config/obsidian/obsidian.json")]def obsidian_vaults(text: str, exists=os.path.isdir) -> list:- """Obsidian's vaults (its obsidian.json), the most recently opened first; only ones that exist."""try:root = json.loads(text)except (ValueError, TypeError):@@ -191,7 +167,6 @@ def all_vaults() -> list:def vault_of(folder: str, vaults=None) -> str | None:- """The Obsidian vault the folder is in (or is), if any."""for v in all_vaults() if vaults is None else vaults:v = v.rstrip("/") or "/"if folder == v or folder.startswith(v + "/"):@@ -200,11 +175,9 @@ def vault_of(folder: str, vaults=None) -> str | None:def documents_dir() -> str:- """The XDG documents folder (xdg-user-dir DOCUMENTS), else ~/Documents. The app asks GLib first."""home = os.path.expanduser("~")try:out = subprocess.run(["xdg-user-dir", "DOCUMENTS"], capture_output=True, text=True, timeout=2).stdout.strip()- # Unset, it answers the home folder itself: not a documents folder.if out and os.path.normpath(out) != os.path.normpath(home):return outexcept (OSError, subprocess.SubprocessError):@@ -213,7 +186,6 @@ def documents_dir() -> str:def default_folder(vaults=None, documents: str | None = None) -> str:- """The suggestion: the most recently opened Obsidian vault's Cicada folder, else Documents › Cicada."""vaults = all_vaults() if vaults is None else vaultsif vaults:return os.path.join(vaults[0], "Cicada")@@ -221,14 +193,11 @@ def default_folder(vaults=None, documents: str | None = None) -> str:def short_path(folder: str) -> str:- """"工作笔记 › Cicada": the folder and the one it is in."""folder = os.path.normpath(folder)parent = os.path.dirname(folder)return "%s › %s" % (os.path.basename(parent) or parent, os.path.basename(folder) or folder)-# Writing (off the main loop)-def _classify(e: BaseException, folder: str) -> tuple:if isinstance(e, PermissionError) or getattr(e, "errno", None) in (errno.EACCES, errno.EPERM):return DENIED, ""@@ -238,8 +207,6 @@ def _classify(e: BaseException, folder: str) -> tuple:def ensure(folder: str) -> tuple | None:- """The folder exists, or is made when only it is missing: never a drive that isn't mounted, so- only the last folder, and only when its parent is there."""if os.path.exists(folder):return None if os.path.isdir(folder) else (MISSING, "")if not os.path.isdir(os.path.dirname(os.path.normpath(folder))):@@ -254,7 +221,6 @@ def ensure(folder: str) -> tuple | None:def probe(folder: str) -> tuple | None:- """Writes and removes a hidden file: the check after choosing a folder."""p = ensure(folder)if p is not None:return p@@ -269,8 +235,6 @@ def probe(folder: str) -> tuple | None:def write_atomic(path: str, data: bytes) -> None:- """A temporary file in the same folder, then renamed over: a vault or sync client never sees half- a file. Hidden, so a vault doesn't list it meanwhile; the umask's mode, like any saved file."""folder = os.path.dirname(path)tmp = os.path.join(folder, ".cicada-%s.tmp" % secrets.token_hex(4))try:@@ -286,8 +250,6 @@ def write_atomic(path: str, data: bytes) -> None:def write_jobs(jobs: list, folder: str, ours: dict) -> list:- """jobs: (id, stem, old name, bytes). Outcomes: ("wrote", id, name), ("unchanged", id) or- ("stopped", problem, message). Stops at the first problem: the rest would fail the same way."""p = ensure(folder)if p is not None:return [("stopped",) + p]@@ -312,10 +274,9 @@ def write_jobs(jobs: list, folder: str, ours: dict) -> list:passtry:write_atomic(path, data)- except Exception as e: # noqa: BLE001 - every failure is a problem shown, never a dead worker+ except Exception as e: # noqa: BLE001out.append(("stopped",) + _classify(e, folder))return out- # Renamed: the old file goes, only the one Cicada wrote.if old and old != n:try:os.remove(os.path.join(folder, old))@@ -327,12 +288,10 @@ def write_jobs(jobs: list, folder: str, ours: dict) -> list:class Index:- """FolderExport.json: the Mac's keys, written the way its JSONEncoder writes them."""-def __init__(self, folder: str = "", files=None, pending=None, lastFile=None, lastAt=None):self.folder = folder- self.files = dict(files or {}) # record id → the file name Cicada wrote- self.pending = list(pending or []) # records waiting to be written+ self.files = dict(files or {})+ self.pending = list(pending or [])self.lastFile = lastFileself.lastAt = lastAt@@ -357,26 +316,21 @@ class Index:def index_path() -> str:- """Beside the records' folder, as the Mac keeps it beside Sessions."""return os.path.join(Paths.data(), "FolderExport.json")class FolderExporter:- """Writes settled meetings into the chosen folder. Triggers come from any thread; the work runs- on one worker. `on_change` listeners fire on the worker (the app hops to its main loop);- `on_denied` is the one notification after a meeting, until a write works again."""-def __init__(self, store, settings, index_file: str | None = None, delay: float = 2.0):self.store = storeself.settings = settingsself.index_file = index_file or index_path()self.delay = delay- self.settling = lambda sid: False # the meeting's final notes pass is running or waiting- self.voices = lambda: False # 说话人识别 on: the body names voices, as 导出… does+ self.settling = lambda sid: False+ self.voices = lambda: Falseself.on_denied = None- self.problem = None # None, DENIED, MISSING or FAILED+ self.problem = Noneself.problem_message = ""- self.checking = False # checking a newly chosen folder+ self.checking = Falseself._gate = threading.RLock()self._work = ThreadPoolExecutor(max_workers=1, thread_name_prefix="FolderExport")self._timer = None@@ -416,19 +370,14 @@ class FolderExporter:return self.on and sid in self.index.pendingdef ready(self, s) -> bool:- """Ended, not being imported, with something said, and not the live meeting."""return s.endedAt is not None and not s.importing and bool(s.lines) and s.id != self.store.livedef unwritten(self) -> list:- """Settled records not written to this folder yet (以前的会议)."""with self._gate:files, pending = set(self.index.files), set(self.index.pending)return [s for s in self.store.all() if self.ready(s) and s.id not in files and s.id not in pending]- # Triggers-def ended(self, sid: str) -> None:- """A meeting ended: written once it is settled."""if not self.on:returnwith self._gate:@@ -438,7 +387,6 @@ class FolderExporter:self._schedule()def saved(self, sid: str) -> None:- """A record was saved: rewritten if it was written, written if it is waiting."""if not self.on:returnwith self._gate:@@ -449,14 +397,12 @@ class FolderExporter:self._schedule()def settled(self, sid: str) -> None:- """The meeting's final notes pass is over, done or not."""with self._gate:waiting = self.on and sid in self.index.pendingif waiting:self._schedule()def write_all(self) -> None:- """也存一份: every settled record not written yet. Never a notification."""if not self.on:returnids = [s.id for s in self.unwritten()]@@ -466,25 +412,19 @@ class FolderExporter:self._submit(False)def retry(self) -> None:- """At launch and when a window comes forward: what is still waiting."""with self._gate:waiting = self.on and bool(self.index.pending)if waiting:self._schedule(0.5, from_meeting=False)def deleted(self, sid: str) -> None:- """The record went; its file stays."""with self._gate:self.index.files.pop(sid, None)if sid in self.index.pending:self.index.pending.remove(sid)self._save()- # Choosing the folder-def choose(self, folder: str) -> None:- """A new folder (or the same one after a fix): a new index for a new folder, and a check that- it can be written now, while settings is open, rather than when a meeting ends."""folder = os.path.normpath(os.path.expanduser(folder))self.settings.exportFolder = folderself.settings.exportOn = True@@ -517,8 +457,6 @@ class FolderExporter:self.problem, self.problem_message = None, ""self._changed()- # Writing-def _schedule(self, delay: float | None = None, from_meeting: bool = True) -> None:with self._gate:if self._timer is not None:@@ -533,7 +471,6 @@ class FolderExporter:self._work.submit(self._flush, from_meeting)def wait(self) -> None:- """Until every write asked for so far is done (tests, the debug commands)."""with self._gate:t, self._timer = self._timer, Noneif t is not None and t.is_alive():@@ -544,7 +481,7 @@ class FolderExporter:def _flush(self, from_meeting: bool) -> None:try:self._flush_now(from_meeting)- except Exception as e: # noqa: BLE001 - keep the worker alive for the next try+ except Exception as e: # noqa: BLE001Log.d("folder export: flush failed %s" % type(e).__name__)def _flush_now(self, from_meeting: bool) -> None:@@ -564,7 +501,7 @@ class FolderExporter:continuetry:jobs.append((sid, stem(s), self.index.files.get(sid), document(s, self.voices()).encode("utf-8")))- except Exception as e: # noqa: BLE001 - one record that won't render must not hold up the rest+ except Exception as e: # noqa: BLE001Log.d("folder export: %s not rendered %s" % (sid, type(e).__name__))self._save()ours = dict(self.index.files)@@ -574,7 +511,7 @@ class FolderExporter:stopped = Nonewith self._gate:if self.index.folder != folder:- return # another folder was chosen meanwhile+ returnfor o in outcomes:if o[0] == "wrote":self.index.files[o[1]] = o[2]@@ -599,7 +536,6 @@ class FolderExporter:self.on_denied()def _save(self) -> None:- """Under the gate."""try:os.makedirs(os.path.dirname(self.index_file), exist_ok=True)write_atomic(self.index_file, jsonfmt.write(self.index.to_json()).encode("utf-8"))@@ -607,7 +543,6 @@ class FolderExporter:Log.d("folder export: index not saved %s" % type(e).__name__)def state(self) -> dict:- """For the debug socket."""with self._gate:return {"on": self.on, "folder": self.folder, "problem": self.problem, "message": self.problem_message,"checking": self.checking, "index": self.index.to_json(), "unwritten": [s.id for s in self.unwritten()]}diff --git a/linux/cicada/core/jsonfmt.py b/linux/cicada/core/jsonfmt.pyindex 159d181..4548bc6 100644--- a/linux/cicada/core/jsonfmt.py+++ b/linux/cicada/core/jsonfmt.py@@ -1,7 +1,3 @@-"""JSON written the way the Mac's JSONEncoder writes [.prettyPrinted, .sortedKeys], byte for byte:-`"key" : value`, two-space indent, `[\n\n ]` for an empty array, `\\/` for a slash, shortest-doubles with no ".0". The stdlib's json.dumps can't produce that spacing, so records are written-here; reading uses json.loads (ints stay ints, so a whole number reads and writes back unchanged)."""from __future__ import annotationsimport json@@ -21,7 +17,6 @@ def parse_object(text: str) -> dict | None:def number(d: float) -> str:- """Shortest round-trip digits, as Swift prints a Double: "2" not "2.0", no exponent."""if d != d or d in (float("inf"), float("-inf")):return "0"if d == int(d) and abs(d) < 1e15:@@ -50,7 +45,6 @@ def _emit(out: list[str], v, pretty: bool, depth: int) -> None:elif isinstance(v, str):_quote(out, v)elif isinstance(v, dict):- # Sorted like Swift's .sortedKeys; nulls are left out, as Swift leaves out nil optionals.items = sorted(((k, x) for k, x in v.items() if x is not None), key=lambda kv: kv[0])if not items:out.append("{\n\n" + " " * depth + "}" if pretty else "{}")@@ -101,8 +95,6 @@ def _quote(out: list[str], s: str) -> None:out.append('"')-# Lenient accessors for decoded JSON.-def obj(v) -> dict | None:return v if isinstance(v, dict) else Nonediff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.pyindex 0438533..6b99080 100644--- a/linux/cicada/core/ling.py+++ b/linux/cicada/core/ling.py@@ -1,4 +1,3 @@-"""The AI service (Ling by default, or another OpenAI-compatible one: providers.py) and the user's keys."""from __future__ import annotationsimport io@@ -19,10 +18,6 @@ from .support import Log, Pathsclass AIKey:- """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, service=None):self._path = pathself.service = service or (lambda: "ling")@@ -54,7 +49,6 @@ class AIKey:with self._lock:try: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(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)with os.fdopen(fd, "w", encoding="utf-8") as f:f.write(k)@@ -80,15 +74,12 @@ class AIKey:@staticmethoddef masked(key: str) -> str:- """"sk-••••••••••••3f9a" for display."""return "sk-…" if len(key) <= 8 else key[:3] + "•" * 12 + key[-4:]-# Priorities, most urgent first.SPEAK, TRANSLATE, NOTES = 0, 1, 2PRIORITY_NAMES = {SPEAK: "speak", TRANSLATE: "translate", NOTES: "notes"}-# Key states.NONE, UNCHECKED, CHECKING, OK, INVALID, UNREACHABLE = "none", "unchecked", "checking", "ok", "invalid", "unreachable"@@ -100,18 +91,17 @@ class LingError(Exception):super().__init__("http%d" % status if kind == self.HTTP else kind)self.kind = kindself.status = status- self.retry_after = retry_after # seconds the service asked us to wait (a 429's Retry-After)+ self.retry_after = retry_afterclass Response:def __init__(self, status: int, body: str, retry_after: str | None = None):self.status = statusself.body = body- self.retry_after = retry_after # the Retry-After header, as sent+ self.retry_after = retry_afterdef retry_after_seconds(value: str | None, now: float | None = None) -> float | None:- """A Retry-After header in seconds: a number, or an HTTP date. None when absent or unreadable."""if not value:return Nonetry:@@ -129,8 +119,6 @@ def retry_after_seconds(value: str | None, now: float | None = None) -> float |class Clock:- """Time for the start gate and its waits; tests hand in a fake that moves on by itself."""-@staticmethoddef now() -> float:return time.monotonic()@@ -141,8 +129,6 @@ class Clock:class StreamResponse:- """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 = statusself.lines = lines@@ -151,10 +137,6 @@ class StreamResponse:class UrlTransport:- """How requests leave the app: urllib through this computer's proxy (proxy.urlopen: the- environment's, else GNOME's manual one), or a fake in tests.- Raises TimeoutError on a timeout and OSError when the network fails."""-@staticmethoddef send(url: str, method: str, body: str | None, headers: dict, timeout: float) -> Response:req = urllib.request.Request(url, data=body.encode() if body is not None else None, method=method, headers=headers)@@ -173,8 +155,6 @@ class UrlTransport:@staticmethoddef stream(url: str, body: str, headers: dict, timeout: float) -> StreamResponse:- """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 = proxy.urlopen(req, timeout=timeout)@@ -193,7 +173,7 @@ class UrlTransport:def chunks():with r:while True:- b = r.read(4800) # 0.1 s at 24 kHz: playback starts early+ b = r.read(4800)if not b:returnyield b@@ -202,19 +182,16 @@ class UrlTransport:BASE = LING.baseTTS_MODEL = LING.voice_models[0].id-TTS_RATE = 24000 # Ming, Gemini TTS and Kokoro all speak 24 kHz+TTS_RATE = 24000AUDIO_MODEL = LING.hear_models[0].id-# Search essays (Ling.swift), and the canned refusal some audio prompts get.HIJACK_PREFIXES = ("根据现有检索证据", "暂未找到足够可靠的信息", "根据检索", "作为一个人工智能语言模型")-# The custom service's check: one real sentence, timed (Ling.swift › check).CHECK_SENTENCE = ("Translate the text into Simplified Chinese. Reply with the translation only.\n\n""We will ship the new version on Friday after the design review.")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)@@ -224,18 +201,14 @@ 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)+ self.paused_until = 0.0def _ling_config() -> AIConfig:@@ -243,50 +216,32 @@ def _ling_config() -> AIConfig:class LingClient:- """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+ spacing: float | None = Nonedef __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 = transportself.clock = clock or Clock()self.config = config or _ling_configself.key_state = NONE if self.current_key() is None else UNCHECKED- # Step by step, where the service stands (aicheck.py); `key_state` is its short form.self.check_result = aicheck.AICheck()- self.seconds: float | None = None # how long the last good check took- # The last time the room voice spoke (or failed to) through this service: (ok, time).+ self.seconds: float | None = Noneself.last_voice: tuple | None = None- # Words the "can't reach" hint from the proxy requests go through (proxy.py).self.proxy_hint = proxy.hint- # Debug control only: every check ends this way (a reason, or "lowBalance"), for screenshots.self.simulate: str | None = Noneself.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 = Noneself._listeners = []- # Every server's start gate (_Gate, by host) shares this one lock.self._gate = threading.Condition()self._gates: dict = {}self._seq = 0self._check_lock = threading.Lock()self._check_seq = 0- self._checking = 0 # a check's own requests aren't real ones: they don't feed `observe`- # Custom addresses that refused `chat_template_kwargs` (a strict gateway answers 400 or 422- # to a field it doesn't know): left out there until settings change.+ self._checking = 0self._plain_bases: set = set()def on_change(self, listener) -> None:@@ -301,8 +256,6 @@ class LingClient:return self.config().providerdef current_key(self) -> str | None:- """The key for the service in use. A custom service on this computer or the local network- may need none: ""."""c = self.config()k = self.key.read()if k is None and c.provider.id == "custom" and c.base and is_nearby(c.base):@@ -314,8 +267,6 @@ class LingClient:return self.current_key() is not Nonedef 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:@@ -324,7 +275,6 @@ class LingClient:@propertydef 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@@ -333,13 +283,10 @@ class LingClient:@propertydef 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@propertydef hears(self) -> bool | None:- """Whether the hear model takes audio: False when found deaf, True once proved (always on- Ling, whose Ming hears by design), None until something asked."""st = self.check_result["hear"]if st.kind == aicheck.FAIL and st.reason == aicheck.DEAF:return False@@ -349,19 +296,15 @@ class LingClient:@propertydef 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)@propertydef service_name(self) -> str:- """The service's name for messages ("这个服务" for a custom address, localized)."""p = self.providerreturn p.name if p.id != "custom" else strings.L("这个服务")@propertydef service_label(self) -> str:- """Who a status line names: a custom service by its address, which says more than 这个服务- and reads right in "The … key doesn't work"."""host = self.service_hostreturn host if self.provider.id == "custom" and host else self.service_name@@ -372,31 +315,26 @@ class LingClient:@propertydef hear_host(self) -> str:- """Where the hear model is asked (a custom service's own hear address, else the service's)."""c = self.config()return urllib.parse.urlsplit(c.hear_url or "").hostname or self.service_hostdef message(self) -> str | None:- """The failed step's sentence (or the busy note), in the UI language."""c = self.config()f = self.check_result.failurehost = self.hear_host if f is not None and f[0] == "hear" else self.service_hostreturn self.check_result.message(self.service_label, host, c.text_model, c.hear_model)def _classify(self, e: LingError, at: str, audio: bool = False):- """aicheck.classify, except that a hear model at an address of its own that can't be reached- stops at the hear step: the text model's address may be fine."""cl = aicheck.classify(e, at, audio)if audio and cl is not None and cl[1] == aicheck.UNREACHABLE and self.config().own_hear_address:return "hear", aicheck.UNREACHABLE, Nonereturn cldef 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_seq += 1self.check_result = aicheck.AICheck()self.key_state = NONE if self.current_key() is None else UNCHECKEDself.last_voice = None@@ -406,11 +344,6 @@ class LingClient:self._changed()def check(self) -> str:- """The cheapest requests that prove each step: Ling's tiny model, else one token from the- text model, then half a second of silence to the hear model (a 400 or 404 says it can't- take audio). A custom service must also return JSON (the notes need it); OpenRouter's key- and credits give the balance. The model list then tells whether the chosen models still- exist. Returns the short form (`key_state`)."""with self._check_lock:self._check_seq += 1seq = self._check_seq@@ -451,8 +384,6 @@ class LingClient:if c.is_ling:self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=10.0, model="Ling-3.0-tiny")elif c.provider.id == "custom":- # A real sentence, the way a meeting translates: one token says nothing about a model- # that thinks for six seconds before every answer.roots: list = []asked = time.monotonic()self.chat(CHECK_SENTENCE, "Translate.", SPEAK, max_tokens=120, timeout=30.0, reply=roots)@@ -462,7 +393,6 @@ class LingClient:self.seconds = time.monotonic() - startedr.pass_up_to("text", self.seconds)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:@@ -476,8 +406,6 @@ class LingClient:except LingError as e:if e.kind != LingError.HTTP:raise- # JSON mode refused (some hosts of a model do): meetings then ask without it, so- # what counts is whether the model still answers with a JSON object.try:said = self.chat(ask, "Reply.", SPEAK, max_tokens=20, timeout=30.0)except LingError:@@ -489,11 +417,11 @@ class LingClient:except Exception: # noqa: BLE001r.fail("reach", aicheck.UNREACHABLE)if r.failure is not None or c.is_ling:- return r # Ling's hearing is Ming: a meeting proves it, no probe+ return rif not c.hear_model:r.fail("hear", aicheck.DEAF)elif c.hear_url is None:- r.fail("hear", aicheck.BAD_ADDRESS) # its own address, typed but not valid+ r.fail("hear", aicheck.BAD_ADDRESS)else:started = time.monotonic()try:@@ -502,32 +430,26 @@ class LingClient:r["hear"] = aicheck.State(aicheck.OK, time.monotonic() - started)except LingError as e:if e.kind == LingError.HIJACKED:- r["hear"] = aicheck.State(aicheck.OK, time.monotonic() - started) # it answered: it took the audio+ r["hear"] = aicheck.State(aicheck.OK, time.monotonic() - started)else:self._failed(r, self._classify(e, "hear", audio=True), "hear")except Exception: # noqa: BLE001r.fail("hear" if c.own_hear_address else "reach", aicheck.UNREACHABLE)if c.provider.id == "openrouter" and r.failure is None:r.balance = aicheck.balance(self._get_json("key", k), self._get_json("credits", k))- if r.failure is None or r.failure[0] == "hear": # the menus want the models even when the hear one is deaf+ if r.failure is None or r.failure[0] == "hear":self.fetch_catalog()every, hear = self._listed- # 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.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 rdef _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@@ -549,7 +471,6 @@ class LingClient: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)@@ -570,9 +491,8 @@ class LingClient:@staticmethoddef _failed(r, classified, step: str) -> None:- """A check's request failed: busy passes (the key works), anything else stops there."""if classified is None:- r.pass_up_to(step, None) # a reply came (a search essay, odd JSON): the service answers+ r.pass_up_to(step, None)returnat, reason, code = classifiedif reason == aicheck.BUSY:@@ -585,7 +505,7 @@ class LingClient:if r.reason == aicheck.UNREACHABLE and r.proxy is None:try:r.proxy = self.proxy_hint()- except Exception: # noqa: BLE001 - it only words a hint+ except Exception: # noqa: BLE001r.proxy = Noneif self.simulate == "lowBalance":r.balance = 0.4@@ -601,8 +521,6 @@ class LingClient:return self.key_statedef _sync_key_state(self) -> None:- """The short form older callers read: invalid stops every request; a failure before the- hear step is "unreachable" with a reason; a deaf hear model leaves notes and translation ok."""if not self.has_key:self.key_state = NONEreturn@@ -619,13 +537,9 @@ class LingClient:self.seconds = r[s].secondsdef 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. `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:returnif notes:- # Sent before notes went back to translation's model and server: not theirs any more.if not self.config().notes_apart:returnif failure is not None:@@ -661,7 +575,6 @@ class LingClient:else:r.fail(step, reason, code)elif audio:- # Heard: says nothing about the text model, which keeps what it had.r.pass_up_to("key", None)r["hear"] = aicheck.State(aicheck.OK, seconds)else:@@ -671,7 +584,7 @@ class LingClient:if r.reason != aicheck.UNREACHABLE:r.proxy = Noneif [r[s] for s in aicheck.STEPS] == [old[s] for s in aicheck.STEPS] and old.passive and old.at is not None:- old.at = r.at # only the time: nothing worth repainting for+ old.at = r.atreturnnewly_unreachable = r.reason == aicheck.UNREACHABLE and old.reason != aicheck.UNREACHABLEself.check_result = r@@ -692,8 +605,6 @@ class LingClient:self._changed()def network_changed(self) -> bool:- """The network came back (or changed) while the service was unreachable: look again.- True when a check started."""r = self.check_resultif not self.has_key or r.reason != aicheck.UNREACHABLE or r.running:return False@@ -702,7 +613,6 @@ class LingClient:return Truedef _get_json(self, path: str, k: str):- """A GET under the service's address, as JSON; None when it fails (it only adds detail)."""c = self.config()try:res = self.transport.send(c.base + path, "GET", None, self._headers(k), 15.0)@@ -711,8 +621,6 @@ class LingClient:return jsonfmt.parse_object(res.body) if res.status == 200 else Nonedef 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:@@ -730,7 +638,6 @@ class LingClient: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_notesk = self.notes_key()@@ -749,15 +656,6 @@ class LingClient: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:- """One chat completion. `content` goes in the system message, `instruction` is the fixed user- message, `audio` (a WAV) goes before it for the hear model. Notes and heard audio retry 429s- with backoff (retry_waits); the rest fail fast so the caller can fall back. `patient` (the- final notes) keeps retrying for about a minute. A 429 holds every request start for a while- (_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). 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_apartif notes_side:@@ -765,7 +663,6 @@ class LingClient:k = self.notes_key() if notes_side else self.current_key()if k is None:raise LingError(LingError.NO_KEY)- # 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)@@ -785,7 +682,6 @@ class LingClient:name = PRIORITY_NAMES[priority]ticket = Nonewhile 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, base=c.base)started = time.monotonic()try:@@ -794,8 +690,6 @@ class LingClient:except LingError as e:if not (json_fallback and e.kind == LingError.HTTP and e.status == 400 and "response_format" in body):raise- # Some hosts of a model refuse JSON mode (on OpenRouter, Novita for Ling 3.1 Flash)- # 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, notes=notes_side)@@ -806,7 +700,6 @@ class LingClient:raise LingError(LingError.PARSE)finish = string(choice.get("finish_reason"))trimmed = text.strip()- # 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)@@ -834,8 +727,6 @@ class LingClient:def speech(self, text: str, voice: str | None = "UK_Charlotte", language: str | None = None, timeout: float = 20.0,reference: tuple | None = None):- """_speech, remembering how it went (现在能用的 › 同传声音 says so). Cut short on purpose (stop,- a new press) is neither."""try:yield from self._speech(text, voice, language, timeout, reference)except GeneratorExit:@@ -846,12 +737,6 @@ class LingClient:self.last_voice = (True, time.time())def _speech(self, text: str, voice: str | None, language: str | None, timeout: float, reference: tuple | None = None):- """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, or a voice cloned from `reference` (a WAV data URI and- what it says, voice_reference.reference), 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)@@ -862,7 +747,6 @@ class LingClient:if c.is_ling:body.update({"sample_rate": TTS_RATE, "stream": True, "stream_format": "sse"})if reference:- # The clip goes with every sentence: Ming takes longer to start (Ling.swift waits 30 s).body["references"] = [{"audio": reference[0], "text": reference[1]}]timeout = max(timeout, 30.0)else:@@ -870,7 +754,6 @@ class LingClient:if language:body["language_id"] = languageelse:- # OpenRouter documents no `stream` (it streams the bytes anyway); ZenMux needs it.if c.provider.id != "openrouter":body["stream"] = Trueids = [v.id for v in c.voices]@@ -921,10 +804,6 @@ class LingClient:return hdef _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, notes)except LingError as e:@@ -937,8 +816,6 @@ class LingClient:return rootdef _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:@@ -961,11 +838,7 @@ class LingClient:raise LingError(LingError.PARSE)return root- # Start gate: request starts ≥ `spacing` apart, the most urgent waiting one first, none while- # 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@@ -977,9 +850,6 @@ class LingClient:def _acquire(self, priority: int, spacing: float = 0.6, ticket: int | None = None,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 spacingwith self._gate:g = self._server(base)@@ -1008,10 +878,6 @@ class LingClient:raisedef _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.5with self._gate:g = self._server(base)@@ -1024,7 +890,6 @@ MAX_PAUSE = 30.0def answers_json(text: str | None) -> bool:- """A chat reply's text holds a JSON object (a fence or a sentence around it is fine)."""if not text:return Falsea, z = text.find("{"), text.rfind("}")@@ -1032,13 +897,6 @@ def answers_json(text: str | None) -> bool:def retry_waits(priority: int, audio: bool = False, patient: bool = False) -> list:- """Seconds before each retry of a 429 (Ling.swift › retryWaits). Notes retry a few times; the- rest fail fast so the caller can fall back, except heard audio. A meeting's: there a lost reply- loses the words, and Ling's 429s came in runs of up to ~10 s (two in a row lost a line with one- retry, about 2 a minute in 2026-11 testing), so it keeps at it for about 15 s. What the user says- (SPEAK) retries once: late into the room is worse than a short "try again". `patient` (the final notes)- keeps at it for about a minute: a model limited upstream (OpenRouter's Ling 3.1 by DeepInfra,- 2026-11) came back after ~15 s, and a meeting left without its notes is worse than notes a little late."""if priority == NOTES:return [1, 2, 4, 8, 16, 30] if patient else [1, 2, 4]if audio:@@ -1052,7 +910,6 @@ def _b64(s: str) -> bytes: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 wavat = 12diff --git a/linux/cicada/core/listen.py b/linux/cicada/core/listen.pyindex c6124b3..f84d9bd 100644--- a/linux/cicada/core/listen.py+++ b/linux/cicada/core/listen.py@@ -1,10 +1,3 @@-"""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).--Ming takes ~2.2 s whatever the segment's length, so segments overlap in flight: request starts still-go through LingClient's gate, and lines are delivered in segment order."""from __future__ import annotationsimport queue@@ -23,29 +16,22 @@ from .support import Log, english_name, is_cjk_languagefrom .translator import Translator_END = object()-# Segment numbers from here up are the room side's (the Mac's ListenEngine.roomIDs).ROOM_IDS = 1_000_000class RoomMix:- """电脑和会议室 keeps one recording, as the Mac does: the room lane's samples are added into the- computer's at the same place on the meeting's clock (each lane counts the samples it heard). The- computer's audio waits `DELAY` before it is written, so a room buffer that arrives a little after- the computer's is still mixed in; what the room says after the computer's last sample follows it."""-- DELAY = RATE # 1 s- LIMIT = 30 * RATE # the computer's audio stalled: older room audio goes rather than piling up+ DELAY = RATE+ LIMIT = 30 * RATEdef __init__(self, rec):self.rec = recself._lock = threading.Lock()- self._main = array("h") # the computer's audio not written yet- self._at = 0 # where on the clock self._main[0] is (everything before it is written)+ self._main = array("h")+ self._at = 0self._room = array("h")- self._room_at = 0 # where on the clock self._room[0] is+ self._room_at = 0def write(self, buf) -> None:- """The computer's audio (the main lane), in order."""with self._lock:self._main.extend(buf)out = self._take(len(self._main) - self.DELAY)@@ -53,13 +39,12 @@ class RoomMix:self.rec.write(out)def room(self, buf, at: int) -> None:- """The room lane's audio; `at`: its first sample's place on the clock."""with self._lock:end = self._room_at + len(self._room)if not self._room:self._room_at = atelif at > end:- self._room.frombytes(bytes(2 * (at - end))) # the room side stopped a while: silence+ self._room.frombytes(bytes(2 * (at - end)))elif at < end:buf = buf[end - at:]self._room.extend(buf)@@ -70,7 +55,6 @@ class RoomMix:self._room_at += overdef close(self) -> None:- """Everything still held goes into the file, then the recorder closes."""with self._lock:out = self._take(len(self._main))if self._room and self._room_at >= self._at:@@ -85,14 +69,12 @@ class RoomMix:self.rec.finish(until)def _drop(self, upto: int) -> None:- """Room audio for a place already written: too late to mix."""late = min(len(self._room), upto - self._room_at)if late > 0:del self._room[:late]self._room_at += latedef _take(self, n: int):- """The next `n` samples of the computer's audio with the room's added."""if n <= 0:return array("h")out, self._main = self._main[:n], self._main[n:]@@ -111,13 +93,9 @@ class RoomMix:class _Lane:- """One audio source's way through listening: its segments, their replies put back in order, its- last line and the language it hears. 电脑和会议室 runs two, as the Mac runs a main and a room- engine; each keeps its own language and pauses."""-def __init__(self, via: str | None = None, first: int = 0):- self.via = via # "room" on the lines of 电脑和会议室's room side- self.first = first # segment numbers start above this+ self.via = via+ self.first = firstself.source = Noneself.audio = Noneself.worker = None@@ -132,8 +110,8 @@ class _Lane:self.level = 0.0self.peak = 0.0self.heard_seconds = 0.0- self.gate = None # a microphone's VoiceGate (the room's noise, learnt)- self.muted = False # silence in place of the microphone (同声传译 is hearing me)+ self.gate = None+ self.muted = Falseclass ListenEngine:@@ -146,44 +124,34 @@ class ListenEngine:self._gate = threading.RLock()self._pool = ThreadPoolExecutor(max_workers=8, thread_name_prefix="Listen")self._main = _Lane()- self._room = None # 电脑和会议室's room side, while it runs- # Without echo cancellation the room mic hears silence while the computer plays speech.+ self._room = Noneself.echo_gate = EchoGate()self.gated = False- self._recent_online: list = [] # the computer's lines of the last 20 s, as EchoMatch.Heard- self._held: list = [] # room lines waiting EchoMatch.hold for the computer's line they may echo+ self._recent_online: list = []+ self._held: list = []self._main_loud_at = 0.0self._in_flight: list = []self._line_count = 0self._listeners = []self.listening = Falseself.session_id = None- # 保存会议录音: `recorder(sid)` gives the meeting's recorder (write(samples), close(), finish(until))- # or None; set by the app when GStreamer can encode AAC. What the main lane hears is written,- # buffer for buffer, so the file's clock is the lines' clock (t counts the samples heard);- # 电脑和会议室's room lane is added in at its place on that clock (RoomMix).self.recorder = Noneself._recording = None- self.source_kind = None # what this meeting is heard from ("system", "room", "file")- self.problem = None # the last error worth showing, cleared by the next good reply- # What kind of problem, for a state the UI can draw: "key", "busy", "network", "source".+ self.source_kind = None+ self.problem = Noneself.problem_kind = None- self._server_errors = 0 # stretches in a row the service answered with a 5xx- self.loudness = None # SpeakEngine's LoudnessLog: when the system audio was loud (the echo check)- # 说话人识别: a voiceprint per segment on its own thread while Ming hears it, labelled in order.- self.speakers = None # speakers.Tagger, set by the app- self.on_voice = None # called with the meeting's id when a line gets a voice (Ling may name it)- self.fixes = None # LiveFixes (改正听错的词), set by the app+ self._server_errors = 0+ self.loudness = None+ self.speakers = None+ self.on_voice = None+ self.fixes = Noneself._voice_pool = ThreadPoolExecutor(1, thread_name_prefix="Voiceprint")self._deliver_lock = threading.Lock()self._voices_waiting = 0- # 纪要语言 chosen for one meeting (the notes window's language card), over the setting.self.notes_for: dict = {}notes.language = lambda sid: english_name(self.notes_code(sid))translator.glossary = notes.glossary- # The main source's: level and peak (0 for a while means it is silent); the capture is alive while- # heard_seconds grows.@propertydef level(self) -> float:return self._main.level@@ -212,8 +180,6 @@ class ListenEngine:return self.settings.target_codedef meeting_language(self, sid: str | None) -> str | None:- """The language the other side spoke most in a meeting; while nothing is recorded yet, the one- the live meeting is being heard in (the Mac's meetingLanguage)."""s = self.store.get(sid) if sid else Nonecounts: dict = {}for l in (s.lines if s else []):@@ -227,12 +193,9 @@ class ListenEngine:return self.notes_for.get(sid, self.settings.notesLanguage)def notes_code(self, sid: str | None) -> str:- """The language a meeting's notes are written in (the Mac's notesLanguageCode)."""return self.settings.notes_code(self.notes_choice(sid), self.meeting_language(sid))def set_notes_language(self, choice: str, meeting_only: bool = False) -> None:- """纪要语言 changed, in the settings or for this meeting only: a different language during a- meeting rewrites its notes in it right away (the Mac's setNotesLanguage)."""live = self.session_id if self.listening else Nonebefore = self.notes_code(live) if live else Noneif meeting_only and live:@@ -247,13 +210,11 @@ class ListenEngine:@propertydef spoken(self):- """The language the other side has been speaking (the room's, when only the room has spoken)."""with self._gate:return self._main.hint or (self._room.hint if self._room is not None else None)@propertydef pending(self) -> int:- """Segments sent and not yet back: the UI shows "…" while this is above zero."""with self._gate:return sum(len(l.segments) for l in self._lanes())@@ -262,17 +223,13 @@ class ListenEngine:@propertydef recording(self) -> bool:- """This meeting is being recorded (保存会议录音 was on and AAC could be written when it began)."""return self.listening and self._recording is not None@propertydef hears_room_too(self) -> bool:- """电脑和会议室: the room side is running."""return self._room is not Nonedef start(self, source, kind: str, mic: bool = False) -> None:- """Listens to `source`; `mic` when it is a microphone in the room (会议室): speech is told- from the room's own noise, and the record says it was heard in the room."""if self.listening:returnsession = self.store.begin()@@ -294,10 +251,8 @@ class ListenEngine:try:rec = self.recorder(session.id)self._recording = RoomMix(rec) if rec is not None else None- except Exception as e: # noqa: BLE001 - a recording that can't start never stops listening+ except Exception as e: # noqa: BLE001Log.d("listen: no recording (%s)" % type(e).__name__)- # Listening before the source starts: a source that fails at once calls on_ended → stop(),- # which must see this meeting as running to end it.self.listening = Trueself._run(self._main)self.attach(source, mic)@@ -305,7 +260,6 @@ class ListenEngine:self._changed()def _run(self, lane, at: float = 0.0) -> None:- """`at`: where in the meeting this lane begins (seconds), so its lines' times are the meeting's."""segmenter = Segmenter()segmenter.consumed = clock = int(at * RATE)segmenter.on_segment = lambda seg: self._send(lane, seg)@@ -314,18 +268,15 @@ class ListenEngine:def work():nonlocal clock- # One worker owns the segmenter: audio callbacks only queue buffers.while True:buf = q.get()if buf is _END:breakseconds = len(buf) / RATEif lane.muted:- # Silence rather than nothing keeps the segmenter's clock in step.buf = array("h", bytes(len(buf) * 2))rec = self._recordingif rec is not None:- # The room side too, into the same file (#19): heard and kept, as on the Mac.if lane is self._main:rec.write(buf)else:@@ -333,7 +284,6 @@ class ListenEngine:clock += len(buf)now = time.monotonic()if lane is not self._main and self.gated:- # What the mic really hears, for EchoGate's measurement, before any silencing.self.echo_gate.room_level(Wav.rms(buf), seconds, now)if self.echo_gate.closed(now):buf = array("h", bytes(len(buf) * 2))@@ -343,7 +293,7 @@ class ListenEngine:gate.voiced(level, seconds)segmenter.threshold = gate.thresholdelif segmenter.threshold != Segmenter.threshold:- del segmenter.threshold # back on the computer's audio: the fixed gate+ del segmenter.thresholdsegmenter.feed(buf)lane.level = levellane.peak = max(lane.peak * 0.995, level)@@ -361,16 +311,12 @@ class ListenEngine:lane.worker.start()def attach(self, source, mic: bool = False) -> None:- """The meeting's source, now or in place of the one before (听哪里 changed mid-meeting): the- same segments and lines go on from the new one."""lane = self._mainold = lane.sourceif old is not None:old.on_samples = Noneold.stop()lane.gate = VoiceGate(adaptive=True) if mic else None- # Lines heard through a microphone say "room", so a meeting that changes between 会议室 and- # 电脑和会议室 still labels each line by where it was heard (one place alone shows no labels).lane.via = "room" if mic else Noneif mic and self.session_id:self.store.mark_room(self.session_id)@@ -381,19 +327,14 @@ class ListenEngine:Log.d("listen: source changed to %s" % ("a microphone" if mic else "the computer's audio"))def set_muted(self, on: bool) -> None:- """The room mic while 同声传译 hears me through the same microphone: my words aren't the room's."""for lane in self._lanes():if lane.gate is not None and lane.muted != on:lane.muted = onLog.d("listen: room mic %s" % ("muted" if on else "open"))def start_room(self, source, gated: bool) -> None:- """电脑和会议室: the room side, on its own microphone, beside the computer's audio. Its lines say- "room"; it keeps its own language and pauses. `gated`: no echo cancellation, so the room mic- hears silence while the computer plays speech."""if not self.listening or self._room is not None:return- # Another meeting may be another room or another output: echo is assumed until measured.forced = self.echo_gate.forcedself.echo_gate = EchoGate()self.echo_gate.forced = forced@@ -401,8 +342,6 @@ class ListenEngine:lane.gate = VoiceGate(adaptive=True)lane.muted = any(l.muted for l in self._lanes())self.gated = gated- # Started mid-meeting (听哪里 changed to 电脑和会议室): its clock starts where the meeting is,- # not at 00:00, or its lines would sort before everything said so far.self._run(lane, self._main.heard_seconds)with self._gate:self._room = lane@@ -414,7 +353,6 @@ class ListenEngine:self._changed()def stop_room(self) -> None:- """The room side stops; its lines still waiting for their echo check are what was said: kept."""with self._gate:lane, self._room = self._room, Noneif lane is None:@@ -426,9 +364,6 @@ class ListenEngine:self._changed()def stop(self, ended_at=None) -> None:- """Stops listening, waits (briefly) for segments still at Ming, ends the record (at `ended_at`- for a meeting that ended by itself) and starts the final notes. Blocks until the record is- saved: call off the main thread."""if not self.listening:returnself.listening = False@@ -443,13 +378,12 @@ class ListenEngine:sid = self.session_idrec, self._recording = self._recording, Noneif rec is not None:- rec.close() # every buffer the lane heard is in system.aac now+ rec.close()if sid is None:returnself.store.end(sid, ended_at)s = self.store.get(sid)if rec is not None and s is not None:- # Into system.m4a off this thread; a meeting that ended by itself loses its silent tail.until = s.duration if ended_at is not None else Noneself._pool.submit(rec.finish, until)Log.d("listen: stopped %s, %d lines" % (sid, self._line_count))@@ -475,8 +409,6 @@ class ListenEngine:wav = Wav.bytes(seg.samples)seg.voiceprint = Noneif self.voices_on:- # Subtitles wait for a line's voice, so on a CPU too slow to keep up a line goes unlabelled- # (对方) rather than every subtitle falling further behind.with self._gate:behind = self._voices_waiting >= 2if not behind:@@ -494,8 +426,6 @@ class ListenEngine:with self._gate:lane.segments[seg.index] = seglang = lane.hint- # Asked for what the meeting's language translates into; _record checks it against the- # language Ming actually heard ("follow system" turns my own language into the next one).seg.asked = self.settings.resolved_target(lang)self._changed()@@ -508,8 +438,6 @@ class ListenEngine:self._server_errors = 0self.problem = self.problem_kind = Noneexcept LingError as e:- # A server error (a gateway's 502) is said from the third in a row, as on the Mac: one- # isn't worth a banner, but a meeting with no subtitles and no reason is worse.with self._gate:self._server_errors = self._server_errors + 1 if server_error(e) else 0shown = not server_error(e) or self._server_errors >= SERVER_ERRORS_SHOWN@@ -529,8 +457,6 @@ class ListenEngine:self._in_flight = [x for x in self._in_flight if not x.done()]def _deliver(self, lane) -> None:- """Hands finished segments on in order: one slow reply holds back those after it. One thread- at a time, so lines (and their voices) are recorded strictly in segment order."""with self._deliver_lock:ready = []with self._gate:@@ -541,21 +467,17 @@ class ListenEngine:for seg, heard in ready:if heard is None:continue- if lane is not self._main: # the room side of 电脑和会议室+ if lane is not self._main:self._heard_in_room(lane, seg, heard)else:self._record(lane, seg, heard)self._heard_online(heard.original, seg.seconds)- if heard.original.strip(): # speech, which the room mic is silenced for (EchoGate)+ if heard.original.strip():self.echo_gate.heard_words(time.monotonic())if ready:self._changed()- # 电脑和会议室: the room's copy of an online sentence (EchoMatch)-def _heard_online(self, text: str, seconds: float) -> None:- """A sentence from the computer's audio, remembered to tell the room's copy of it; room lines- waiting for it that turn out to be its echo are dropped."""if self._room is None:returnnow = time.monotonic()@@ -569,8 +491,6 @@ class ListenEngine:Log.d("listen: room line dropped as an echo")def _heard_in_room(self, lane, seg, heard) -> None:- """A sentence from the room mic: an echo of the computer's audio is dropped; the rest waits a- moment for the computer's line it may echo, then is recorded where it was said."""now = time.monotonic()h = Heard(heard.original, now - seg.seconds, now)with self._gate:@@ -578,7 +498,6 @@ class ListenEngine:if EchoMatch.is_echo(h, online):Log.d("listen: room line dropped as an echo")return- # The computer has played nothing for a while: nothing for this to echo, no need to wait.if now - self._main_loud_at >= EchoMatch.window:self._record(lane, seg, heard)return@@ -606,8 +525,6 @@ class ListenEngine:self._record(*entry[:3])def _voice(self, seg, heard):- """The segment's voice, or None when unsure. A line with hardly a letter ("." from a breath or- a click) gets no voiceprint; like the Mac, every labelled segment counts towards its voice."""future = getattr(seg, "voiceprint", None)if future is None or sum(1 for c in heard.original if c.isalpha()) < 2:return None@@ -623,12 +540,8 @@ class ListenEngine:if sid is None:returntarget = self.settings.resolved_target(heard.lang)- # Ming translated into what the hint asked for: when the line turned out to be in another- # language, that translation is for the wrong reader, so the text translation redoes it.translation = heard.translation if getattr(seg, "asked", target) == target else Nonevoice = self._voice(seg, heard)- # The meeting's language moves only after two segments agree, so one misheard stretch doesn't- # flip the hint (the Mac waits for confidence the same way).with self._gate:h = lane.hintif h is None:@@ -644,7 +557,6 @@ class ListenEngine:lane.candidate, lane.votes = None, 0prev = lane.lastjoined = False- # Two voices never share a line: a half sentence joins only the same voice (or an unknown one).if prev is not None and continues(prev, seg.start - lane.last_end, heard) and (voice is None or prev.voice is None or voice == prev.voice):prev.src = join(prev.src, heard.original, heard.lang)@@ -667,10 +579,6 @@ class ListenEngine:self.on_voice(sid)if self.fixes is not None:self.fixes.apply_known(copy.id, sid)- # A joined sentence is translated again as a whole; a line Ming didn't translate gets text translation.- # 改正听错的词: a line Ming did translate goes to the text model too, for the fixes the Mac gets- # with every finished sentence's translation (Ming hears and translates in one call, so on- # Linux it is one more text request per line; its translation, as fixed, replaces Ming's).fixing = self.settings.fixMisheard and self.fixes is not Noneif (joined or line.dst is None or fixing) and line.srcLang != target:src = line.src@@ -680,11 +588,10 @@ class ListenEngine:if only_fix:dst = self.translator.fix(src, line.srcLang, target)if dst is None:- return # Ming's translation stays+ returnelse:dst = self.translator.translate(src, line.srcLang, target, Translator.SENTENCE)if dst is None:- # The notes window may now say the user's own service can't be reached.self._changed()returnwith self._gate:@@ -698,8 +605,6 @@ class ListenEngine:def continues(last, gap: float, nxt) -> bool:- """A segment continues the last line when the cut came mid-sentence: no sentence end on the last- line, a short gap, the same language, and the joined line not too long to read."""if gap > 0.8 or last.srcLang != nxt.lang:return Falsetext = last.src.rstrip()@@ -715,7 +620,6 @@ def join(a: str, b: str, lang: str) -> str:return a.rstrip() + b.lstrip() if cjk else a.rstrip() + " " + b.lstrip()-# Server errors in a row before listening says so (ListenEngine.swift's cloudFailures).SERVER_ERRORS_SHOWN = 3@@ -724,20 +628,15 @@ def server_error(e: LingError) -> bool:def problem(e: LingError, service: str, hear_model: 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 / 415 / 422) is a key-like problem:- 设置 fixes it, in the words of the settings' 听对方 step. A 5xx is the service's own trouble."""L, LF = strings.L, strings.LFling = service == "Ling"- service = service if ling else L(service) # 其他(兼容 OpenAI) is UI text; brand names stay as they are+ service = service if ling else L(service)if e.kind == LingError.HTTP and e.status in (400, 404, 415, 422) and not ling:return "key", LF("%@ 听不了声音。", hear_model or service)- # It answered, with an error: like busy, it passes by itself (AICheck's serverError words).if server_error(e):return "busy", LF("%@ 暂时出错(HTTP %lld),稍后再试。", service, e.status)kind = {LingError.NO_KEY: "key", LingError.INVALID_KEY: "key", LingError.RATE_LIMITED: "busy",LingError.NETWORK: "network", LingError.TIMEOUT: "network"}.get(e.kind)- # Out of reach: the service hears the meeting here, so subtitles wait along with the notes.away = LF("字幕和纪要等 %@ 恢复 · 连上后自动继续", service)if ling:text = {LingError.NO_KEY: L("需要 Ling key 才能听"), LingError.INVALID_KEY: L("Ling key 无效"),diff --git a/linux/cicada/core/live_fixes.py b/linux/cicada/core/live_fixes.pyindex 3f3fe1f..fd353b9 100644--- a/linux/cicada/core/live_fixes.py+++ b/linux/cicada/core/live_fixes.py@@ -1,8 +1,3 @@-"""改正听错的词, between the translation and the records (the Mac's LiveFixes.swift): which fixes a line-takes, which wait for the user (待确认), and what the user's answers and edits teach the word list.-Who wins: the user's own decisions, then the word list, then a recheck, then the first live guess.-UI-free and thread-safe (replies arrive on worker threads); the app shows `pending`, `asking` and-`toast` and passes taps back. `on_change` fires on whichever thread made the change."""from __future__ import annotationsimport threading@@ -15,9 +10,7 @@ from .models import LineFixfrom .strings import L, LFfrom .support import Log-# The card asks about at most this many names in a row; the rest wait for after the meeting.ASK_AT_ONCE = 3-# How long a toast (with 撤销) stays.TOAST_SECONDS = 6.0@@ -30,15 +23,13 @@ def _key(f: LineFix) -> str:class FixContext:- """What a finished sentence's request carries so the service can also point out misheard words."""-def __init__(self, words: list, topic: str | None = None, recent: list | None = None,following: list | None = None, summary: str | None = None):- self.topic = topic # the meeting's title once it has one: the field tells "质押" from "制约"- self.words = words # the user's word list (Vocabulary.prompt_lines)- self.recent = recent or [] # the lines just before, as shown- self.following = following or [] # on a second pass: the lines after it- self.summary = summary # the notes' summary so far+ self.topic = topic+ self.words = words+ self.recent = recent or []+ self.following = following or []+ self.summary = summaryclass LiveFixes:@@ -48,15 +39,10 @@ class LiveFixes:self.settings = settingsself.on_change = Noneself._gate = threading.RLock()- # Fixes said no to in this meeting ("from→to"), and how often each heard form was turned down- # overall this run: twice and it leaves the word list.self._refused: set = set()self._refusals: dict = {}- # 稍后再看 on the card: still waiting, but asked again only after the meeting.self._deferred: set = set()- # What 撤销 puts back: the lines' fixes and the word list as they were.self._undo: list = []- # The last thing the user did, said back with 撤销 for a few seconds: (text, monotonic time).self.toast = Nonedef meeting_started(self) -> None:@@ -67,10 +53,7 @@ class LiveFixes:if self.on_change is not None:self.on_change()- # The service's proposals-def context(self, text: str) -> FixContext | None:- """What a finished sentence's request carries; None while fixing is off."""if not self.settings.fixMisheard:return Nonectx = FixContext(self.vocabulary.prompt_lines())@@ -87,8 +70,6 @@ class LiveFixes:return ctxdef received(self, text: str, edits: list) -> None:- """The service's proposals for a line heard as `text` (none at all is an answer too: on a- second pass it takes back what isn't proposed again)."""if not self.settings.fixMisheard:returnhit = self.store.line_heard(text)@@ -102,7 +83,6 @@ class LiveFixes:Log.d("fix %s c=%.2f line=%s" % (verdict, e.confidence, line.id))if verdict == correction.APPLY:fresh.append(LineFix(e.from_, e.to))- # A listed word counts as used whichever way the fix was found (a sound-alike too).self.vocabulary.used(correction.core(e.from_, e.to)[1])elif verdict == correction.ASK and self.settings.askNames:fresh.append(LineFix(e.from_, e.to, ask=True))@@ -114,8 +94,6 @@ class LiveFixes:self._set(fixes, line.id, sid)def apply_known(self, line_id: str, sid: str) -> None:- """The word list's confirmed heard forms, fixed without asking anyone: also with no AI service.- Two characters at least, so a single 压 never turns into 押 everywhere."""if not self.settings.fixMisheard:returnwith self._gate:@@ -127,8 +105,6 @@ class LiveFixes:out = list(fixes)for t in self.vocabulary.snapshot():for h in t.heard:- # A heard form two words claim (两个都留) is never fixed silently. A translation a yes taught- # before that was refused (平台 → platform) isn't either; one the user typed is.if len(h) < 2 or correction.word(h, src) < 0 or _pair(h, t.word) in self._refused \or (t.source != "user" and correction.translation(h, t.word)) or self.vocabulary.owners(h, t.word):continue@@ -144,10 +120,7 @@ class LiveFixes:self.store.set_fixes(sid, line_id, fixes)self._changed()- # 待确认-def pending(self, sid: str) -> list:- """待确认 in a meeting: each (from → to) once, oldest first, as (line, fix)."""seen, out = set(), []for l in self.store.lines(sid):for f in l.fixes or []:@@ -157,8 +130,6 @@ class LiveFixes:return outdef asking(self, sid: str):- """What the notes window's card asks now: (line, fix, position, of), not what was put off- (稍后再看), and only the first few, so a burst of names doesn't keep the card up all meeting."""with self._gate:open_ = [p for p in self.pending(sid) if _key(p[1]) not in self._deferred]if not open_:@@ -166,15 +137,12 @@ class LiveFixes:return open_[0][0], open_[0][1], 1, min(len(open_), ASK_AT_ONCE)def later(self, fix: LineFix, sid: str) -> None:- """× on the card: asked again after the meeting (the record's banner, 人名和术语)."""with self._gate:self._remember(sid, [])self._deferred.add(_key(fix))self._say(L("已收进人名和术语,稍后再看"))def answer(self, fix: LineFix, yes: bool, sid: str) -> None:- """对 / 不对 on a waiting fix: every line in the meeting waiting on the same change follows, and- a yes goes into the word list so the next meeting fixes it without asking."""c = correction.core(fix.from_, fix.to)with self._gate:touched = [l for l in self.store.lines(sid)@@ -194,7 +162,6 @@ class LiveFixes:self._set(fixes, l.id, sid)if yes:self.vocabulary.confirm(c[0], c[1])- # The rest of the meeting heard the same way follows now, not with the next line.for l in others:self.apply_known(l.id, sid)else:@@ -203,12 +170,10 @@ class LiveFixes:self._say(LF("已改 %@ → %@,记进词表", c[0], c[1]) if yes else LF("这场不再问 %@", c[0]))def revert(self, fix: LineFix, line_id: str, sid: str) -> None:- """改回: this line goes back to what was heard, and the meeting stops making this change."""with self._gate:l = self.store.line(sid, line_id)if l is None or not l.fixes:return- # The one still on: an earlier, already undone copy of the same change may sit before it.same = [i for i, f in enumerate(l.fixes) if f.from_ == fix.from_ and f.to == fix.to]k = next((i for i in same if l.fixes[i].applied), same[0] if same else None)if k is None:@@ -227,12 +192,7 @@ class LiveFixes:Log.d("fix reverted line=%s" % line_id)self._say(LF("已改回 %@,这场不再改", correction.label(fix)[0]))- # 改这句…-def same_heard(self, line_id: str, sid: str, edited: str):- """How many lines of the meeting the same edit would change ("整场同样听成 木娜 的 2 处都改"):- (heard, count, swap), or None when the edit changes nothing. An edit that only adds or drops- words stays on its line (count 1, nothing to learn)."""l = self.store.line(sid, line_id)if l is None:return None@@ -243,8 +203,6 @@ class LiveFixes:return e[1], max(1, n), e[2]def edit(self, line_id: str, sid: str, edited: str, everywhere: bool, remember: bool) -> int:- """The user rewrote a line (改这句…): what changed becomes their own fix, on this line or on every- line showing the same words, and with `remember` the heard form joins the word list."""with self._gate:l = self.store.line(sid, line_id)e = correction.user_edit(l.shown, edited, l.src, l.fixes or []) if l else None@@ -257,31 +215,23 @@ class LiveFixes:for t in targets:fixes = []for f in t.fixes or []:- # The same change made again replaces any earlier copy (say, one undone with 改回).if f.from_ == fix.from_ and f.to == fix.to:continuef = f.copy()- # A guess still waiting on the same words is answered by the edit: not that.if f.ask is True and (heard in f.from_ or f.from_ in heard):f.ask, f.off = None, Truefixes.append(f)self._set(fixes + [fix.copy()], t.id, sid)word = correction.core(fix.from_, fix.to)[1].strip()- # Only a change made everywhere teaches the word list (a one-off must not), and only a- # word for a word (`learnable`).learned = remember and everywhere and learnable(heard, word) is not Noneif learned:self.vocabulary.confirm(heard, word, source="user")Log.d("fix edited lines=%d learned=%s" % (len(targets), learned))- # A swap reads as the words swapped; an added or dropped word as the span it changed- # ("in → in now", not "in → now").a, b = (heard, word) if swap else (fix.from_, fix.to)self._say(LF("已改 %lld 处:%@ → %@,记进词表", len(targets), a, b) if learnedelse LF("已改 %lld 处:%@ → %@", len(targets), a, b))return len(targets)- # 撤销-def _remember(self, sid: str, line_ids: list) -> None:lines = {l.id: l for l in self.store.lines(sid)}before = {i: [f.copy() for f in (lines[i].fixes or [])] for i in line_ids if i in lines}@@ -310,13 +260,11 @@ class LiveFixes:self._changed()def toast_text(self) -> str | None:- """The toast while it is still up."""t = self.toastreturn t[0] if t and time.monotonic() - t[1] < TOAST_SECONDS else Nonedef fixed_words(lines: list) -> list:- """The words fixed in a meeting, most fixed first: (word, heard forms, count) (人名和术语)."""out: dict = {}for l in lines:for f in l.fixes or []:diff --git a/linux/cicada/core/meeting_end.py b/linux/cicada/core/meeting_end.pyindex 61057fe..361b4d5 100644--- a/linux/cicada/core/meeting_end.py+++ b/linux/cicada/core/meeting_end.py@@ -1,12 +1,3 @@-"""When a meeting is over (MeetingEnd.swift), so one nobody ended doesn't run on for hours and pull the-next video or meeting into its notes.--Two signals, as on the Mac. The main one: a meeting app (Zoom, 腾讯会议…) that was reading a-microphone during this meeting lets go of it, which is what hanging up looks like from outside; a-short grace covers switching devices. The fallback, for meetings in a browser or in the room: nothing-was recognised for a while ("nothing recognised" counts lines, not sound, so background music doesn't-keep a meeting alive). While a meeting app is still in a call, silence doesn't count. Pure: the-controller ticks it with the clock and `calls()`."""from __future__ import annotationsimport os@@ -22,14 +13,11 @@ class Config:self.follow_apps = follow_appsself.silence = silenceself.silence_after = silence_after- self.countdown = countdown # how long the 没人说话 prompt waits before ending- self.app_grace = app_grace # after a hang-up: a device switch drops the mic for a moment+ self.countdown = countdown+ self.app_grace = app_graceclass Reason:- """Why the meeting ends: `app` hung up (its name), `silence`, or `nobody` spoke at all (nothing to- keep, so it just stops, without a countdown)."""-def __init__(self, kind: str, name: str = ""):self.kind = kindself.name = name@@ -55,24 +43,19 @@ class MeetingEndWatch:self.config = configself.pending: Pending | None = Noneself.last_speech = start- self.in_call: dict = {} # meeting apps seen in a call during this meeting (id → name)+ self.in_call: dict = {}def heard(self, now: float) -> None:- """Words were recognised (theirs or mine): a silence countdown stops. A hang-up doesn't: the- next video would talk over it."""self.last_speech = nowif self.pending is not None and self.pending.reason.kind == "silence":self.pending = Nonedef keep_going(self, now: float) -> None:- """继续记录: forget the hang-up and start counting silence again."""self.pending = Noneself.last_speech = nowself.in_call = {}def tick(self, now: float, calls: dict, said: bool) -> Reason | None:- """`calls`: meeting apps reading a microphone now. `said`: the meeting has lines. One without- keeps listening for the silence time, then stops quietly. Returns why it ends now, if it does."""c = self.configin_a_call = c.follow_apps and bool(calls)if not said:@@ -86,7 +69,7 @@ class MeetingEndWatch:self.in_call.update(calls)hung_up = bool(self.in_call) and all(k not in calls for k in self.in_call)if app_pending and not hung_up:- self.pending = None # rejoined+ self.pending = Noneif hung_up and (self.pending is None or self.pending.reason.kind == "silence"):name = self.in_call[sorted(self.in_call)[0]]self.pending = Pending(Reason("app", name), now + c.app_grace)@@ -104,8 +87,6 @@ class MeetingEndWatch:return None-# Dedicated meeting apps on Linux, by the program that opens the microphone (lower case) → the name-# shown. Browsers aren't here, as on the Mac: a browser holding a mic isn't necessarily a meeting.MEETING_APPS = {"zoom": "Zoom", "zoomwebinar": "Zoom","wemeetapp": "腾讯会议", "wemeet": "腾讯会议",@@ -120,9 +101,6 @@ _PROP = re.compile(r'^\s+([a-z0-9_.\-]+) = "(.*)"\s*$')def parse_source_outputs(text: str, own_pid: int | None = None) -> dict:- """`pactl list source-outputs` (LC_ALL=C) → the meeting apps reading a microphone: {program: name}.- A stream recording a speaker's monitor (stream.capture.sink, as Cicada's own capture does) isn't- a microphone, and Cicada's own streams never count."""out = {}for block in re.split(r"^Source Output #\d+\s*$", text, flags=re.M)[1:]:props = {}@@ -140,7 +118,6 @@ def parse_source_outputs(text: str, own_pid: int | None = None) -> dict:if program in MEETING_APPS:out[program] = MEETING_APPS[program]break- # One app opening two streams is one call; Zoom's two names are one app.names = {}for program, name in sorted(out.items()):names.setdefault(name, program)@@ -148,7 +125,6 @@ def parse_source_outputs(text: str, own_pid: int | None = None) -> dict:def calls() -> dict:- """The meeting apps reading a microphone now, from the sound server (PipeWire or PulseAudio)."""try:r = subprocess.run(["pactl", "list", "source-outputs"], capture_output=True, text=True, timeout=3,env={**os.environ, "LC_ALL": "C"})diff --git a/linux/cicada/core/models.py b/linux/cicada/core/models.pyindex ee22ce8..7914686 100644--- a/linux/cicada/core/models.py+++ b/linux/cicada/core/models.py@@ -1,6 +1,3 @@-"""The meeting record, field for field the Mac app's `session.json` (SessionStore.swift, Notes.swift),-so a record moves between the platforms unchanged. Each type maps to and from a JSON object;-jsonfmt.write sorts the keys and leaves out nulls, as the Mac's encoder does."""from __future__ import annotationsfrom dataclasses import dataclass, field@@ -11,7 +8,6 @@ from . import jsonfmtdef iso_write(at: datetime) -> str:- """Whole seconds, UTC, "Z": what Swift's `.iso8601` writes (and expects back)."""return at.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")@@ -33,16 +29,15 @@ def now() -> datetime:@dataclassclass TranscriptLine:- id: str = "" # "h<n>-<segment>" for heard lines, "m<n>" for the user's own- t: float = 0.0 # seconds from the start of the session- speaker: str = "them" # "them" (heard) or "me" (the Mac's microphone)+ id: str = ""+ t: float = 0.0+ speaker: str = "them"src: str = ""dst: str | None = NonesrcLang: str = ""dstLang: str = ""- voice: int | None = None # experimental voice id on the Mac; Linux doesn't tell voices apart- via: str | None = None # 电脑和会议室: "room" when the room mic heard it; absent for the computer's audio- # Words the AI service fixed (correction.py); `src` stays what was heard. None when there are none.+ voice: int | None = None+ via: str | None = Nonefixes: list | None = Nonedef copy(self) -> "TranscriptLine":@@ -51,7 +46,6 @@ class TranscriptLine:@propertydef shown(self) -> str:- """What the line says once its fixes are in: shown, searched, exported and read by the notes."""if not self.fixes:return self.srcfrom .correction import apply@@ -73,14 +67,11 @@ class TranscriptLine:@dataclassclass LineFix:- """A word the AI service said speech recognition got wrong in a finished line ("莫拉" → "Morpho"),- the Mac's LineFix (Correction.swift). The line keeps what was heard, so a reader that doesn't know- fixes still shows the heard text; a fix whose words are no longer in the line is skipped."""from_: str = ""to: str = ""- ask: bool | None = None # waiting for the user (a name sound can't check): not applied until confirmed- off: bool | None = None # the user said no (改回 or 不对): kept so the line isn't fixed that way again- user: bool | None = None # the user's own: said 对, or wrote it (改这句…); no later pass drops it+ ask: bool | None = None+ off: bool | None = None+ user: bool | None = None@propertydef applied(self) -> bool:@@ -99,7 +90,6 @@ class LineFix:def _num(v, fallback):- """Keeps an int an int, so "start" : 0 writes back as 0."""n = num(v)return fallback if n is None else n@@ -122,7 +112,7 @@ class NoteItem:text: str = ""owner: str | None = Nonesupport: int = 0- t: float | None = None # when it was said (first evidence line)+ t: float | None = Nonedef to_json(self) -> dict:return {"text": self.text, "owner": self.owner, "support": self.support, "t": self.t}@@ -133,7 +123,6 @@ class NoteItem:@propertydef owner_shown(self) -> str | None:- """The owner as stored ("你", "对方", "说话人2" or a name) in the UI language (Notes.swift's ownerShown)."""from .strings import L, LFo = self.ownerif not o:@@ -147,7 +136,6 @@ class NoteItem:@propertydef with_owner(self) -> str:- """The to-do with its owner after it: "(对方)" in Chinese, " (Them)" in English."""from .strings import LFshown = self.owner_shownreturn self.text + (LF("待办的负责人 %@", shown) if shown else "")@@ -155,7 +143,6 @@ class NoteItem:@dataclassclass NoteTerm:- """A name or term as the notes settled on it, and how speech recognition heard it."""name: str = ""note: str = ""heard: list = field(default_factory=list)@@ -170,13 +157,10 @@ class NoteTerm:@staticmethoddef ordered(terms: list) -> list:- """Corrected spellings first: what a reader can't work out alone."""return [t for t in terms if t.heard] + [t for t in terms if not t.heard]@staticmethoddef keeping_order(old: list, new: list) -> list:- """The reply's terms in the order they were shown before, new ones after: the model often- returns the same names reshuffled, which would make the chips jump on every update."""rank: dict = {}for i, t in enumerate(old):rank.setdefault(t.name, i)@@ -188,7 +172,7 @@ class FishboneBranch:label: str = ""detail: str = ""t: float | None = None- support: int = 0 # how many transcript lines back this branch; 0 is shown as weak+ support: int = 0def to_json(self) -> dict:return {"label": self.label, "detail": self.detail, "t": self.t, "support": self.support}@@ -217,14 +201,13 @@ class NoteTopic:title: str = ""summary: str = ""points: list = field(default_factory=list)- pointTimes: list | None = None # when each point was said, parallel to points+ pointTimes: list | None = Nonefishbone: Fishbone | None = Nonedef point_time(self, i: int) -> float | None:return self.pointTimes[i] if self.pointTimes is not None and i < len(self.pointTimes) else Nonedef to_json(self) -> dict:- # pointTimes keeps its nulls: Swift writes [12.4, null].return {"start": self.start, "title": self.title, "summary": self.summary, "points": list(self.points),"pointTimes": self.pointTimes, "fishbone": self.fishbone.to_json() if self.fishbone else None}@@ -239,14 +222,13 @@ class NoteTopic:@dataclassclass MeetingNotes:- """Written by Ling while the meeting runs, rewritten over the whole transcript when it ends."""title: str | None = Nonesummary: str = ""topics: list = field(default_factory=list)conclusions: list = field(default_factory=list)todos: list = field(default_factory=list)terms: list = field(default_factory=list)- covered: int = 0 # how many transcript lines these notes cover+ covered: int = 0final: bool = FalseupdatedAt: datetime | None = None@@ -285,14 +267,10 @@ class Session:renamed: bool | None = NonevoiceNames: dict | None = NonevoiceGuesses: dict | None = None- # An imported recording (the Mac's 导入录音): its file name, where it was, and true until- # transcribing it finished. Linux doesn't import yet; the fields are kept so a record survives.sourceFile: str | None = NonesourcePath: str | None = Noneimporting: bool | None = None- # Heard through the microphone in the room (the Mac's 会议室) for some or all of it.room: bool | None = None- # Keys this version doesn't know (a newer Mac's), written back as they came so a record survives.extra: dict = field(default_factory=dict)KEYS = ("id", "title", "startedAt", "endedAt", "lines", "hasAudio", "notes", "renamed", "voiceNames",@@ -300,8 +278,6 @@ class Session:@propertydef duration(self) -> float:- """Until it ended; a record that never got an end (the app quit mid-meeting) runs to its last- line rather than to now. The live meeting shows its own clock."""if self.endedAt is not None:return (self.endedAt - self.startedAt).total_seconds()return self.lines[-1].t if self.lines else 0.0diff --git a/linux/cicada/core/notes.py b/linux/cicada/core/notes.pyindex ce78be1..2308a32 100644--- a/linux/cicada/core/notes.py+++ b/linux/cicada/core/notes.py@@ -1,9 +1,3 @@-"""Keeps the live meeting's notes up to date: every ~45 s with new speech, one Ling call sends the-current notes plus the new lines and gets the notes back as JSON, rewriting only the last topics; a-final pass rewrites them over the whole transcript when the meeting ends (a long meeting in parts,-merged). A failed or odd reply never replaces good notes.-The prompt and parsing are the Mac's (Notes.swift, via the Windows and Android ports), so every-platform writes the same notes."""from __future__ import annotationsimport math@@ -21,8 +15,6 @@ from .support import Log, clock, written_inINTERVAL = 45.0IDLE, UPDATING, NO_KEY, INVALID_KEY, RATE_LIMITED, FAILED = "idle", "updating", "noKey", "invalidKey", "rateLimited", "failed"-# The notes' own request couldn't reach the service (network, proxy, timeout); another request-# failing, such as naming speakers, never sets it.UNREACHABLE = "unreachable"@@ -30,7 +22,7 @@ class NotesEngine:def __init__(self, ling, store):self.ling = lingself.store = store- self.voices = lambda: False # 说话人识别 on: lines go as 说话人N or the name given (set by the app)+ self.voices = lambda: Falseself._gate = threading.RLock()self._work = ThreadPoolExecutor(max_workers=1, thread_name_prefix="NotesWork")self._ticker = None@@ -42,17 +34,13 @@ class NotesEngine:self._listeners = []self.notes = MeetingNotes()self.status = IDLE- self.shown_id = None # the session the notes belong to (stays set after the meeting ends)- self.language = lambda sid: "Simplified Chinese" # a meeting's notes language (English name), from 纪要语言- self.working_id = None # the record being written now, for a "正在整理纪要…" next to it- # Final passes asked for and not over yet (queued in a pool, running or waiting their turn),- # and the call when one is over, notes written or not (存到文件夹 waits for it).+ self.shown_id = None+ self.language = lambda sid: "Simplified Chinese"+ self.working_id = Noneself._finals: list = []self.final_done = Nonedef settling(self, sid: str) -> bool:- """The meeting's final pass is still to come, running or waiting: also while the meeting is- still this engine's own, before listening's pool gets to finish()."""with self._gate:return sid == self._session_id or sid in self._finals@@ -72,7 +60,6 @@ class NotesEngine:l()def glossary(self) -> list:- """Names for the translation glossary: "江充 (note; misheard as 江松, 江冲)"."""out = []for t in self.notes.terms[:30]:out.append("%s (%s)" % (t.name, t.note) if not t.heard else "%s (%s; misheard as %s)" % (t.name, t.note, ", ".join(t.heard)))@@ -103,7 +90,6 @@ class NotesEngine:self._ticker = Nonedef finish(self) -> None:- """The meeting ended: one last pass over the whole transcript. Blocks until it's written."""with self._gate:self._stop_ticker()sid = self._session_id@@ -118,40 +104,32 @@ class NotesEngine:self.shown_id = sids = self.store.get(sid)self.notes = (s.notes if s else None) or MeetingNotes()- # A round that failed belongs to the meeting it ran for, not to the record opened now.if self._session_id is None and self.status in (FAILED, UNREACHABLE, RATE_LIMITED):self.status = IDLEself._changed()def rewrite(self) -> None:- """The live meeting's notes again from its first line (纪要语言 changed): the Mac's rewrite."""with self._gate:sid = self._session_idif sid is not None:self._work.submit(self._update, sid, False, True)def generate(self, sid: str) -> None:- """Notes for a finished meeting that has none (runs in the background)."""with self._gate:self._finals.append(sid)self._work.submit(self._update, sid, True)def _sync_key(self) -> None:- """The status follows the key, as on the Mac (`NotesEngine.tick`)."""ling = self.ling- # A key was added or replaced since the last failure.if self.status in (NO_KEY, INVALID_KEY) and ling.usable and ling.key_state != CHECKING:self.status = IDLEif self.status == IDLE and not ling.has_key:self.status = NO_KEY- # A key that was just checked and refused says so, rather than asking for a key again.if self.status in (NO_KEY, IDLE) and ling.has_key and ling.key_state == INVALID:self.status = INVALID_KEYdef _tick(self) -> None:with self._gate:- # The service answers again (the check after a network change, or any other request): the- # banner goes now, not after the next round, which runs on its usual 45 s.recovered = self.status == UNREACHABLE and self.ling.check_result.reason != "unreachable"if recovered:self.status = IDLE@@ -166,22 +144,20 @@ class NotesEngine:if s is None or len(s.lines) <= self.notes.covered:returnsince = time.time() - self._last_attempt- # First notes as soon as there is something to say, then every 45 s.due = (len(s.lines) >= 3 or since > 20) if self.notes.is_empty else since >= INTERVALif not due:returnself._work.submit(self._update, sid, False)def _update(self, sid: str, final: bool, fresh: bool = False) -> None:- over = None # a final pass that ends here without running+ over = Nonestart = Falsewith self._gate:if self._in_flight:if final:- # One waiting slot: the pass it held won't run, so that one is over.over, self._pending_final = self._pending_final, sidelif fresh:- self._pending_fresh = sid # after the round in the old language+ self._pending_fresh = sidelse:session = self.store.get(sid)if session is None or not session.lines:@@ -209,9 +185,6 @@ class NotesEngine:voices = self.voices()shown = speakers.names(session) if voices else {}started_at = lines[0].t if lines else 0.0- # A live update returns only the last topics: when it rewrote them all, its reply grew with- # the meeting until, about an hour in, it was cut off at max_tokens or fell into a loop and- # the notes stopped updating. The final pass still rewrites everything once.frozen = 0 if final or fresh else max(0, len(base.topics) - EDITABLE_TOPICS)p = prompt(base, lines, frm, lang, final, shown, voices, frozen)nxt = self._long_final(lines, shown, voices, lang, started_at) if final else None@@ -272,8 +245,6 @@ class NotesEngine:self._update(again, final=False, fresh=True)def _long_final(self, lines: list, names: dict, voices: bool, lang: str, started_at: float) -> MeetingNotes | None:- """A long meeting's final pass: each part noted on its own, all at once, then merged into one.- None when a step fails: the caller then makes one pass over the whole transcript, as before."""ranges = parts(lines)if len(ranges) <= 1:return None@@ -297,7 +268,6 @@ class NotesEngine:if root is None:Log.d("notes: final part %d/%d failed, one pass instead" % (i + 1, len(ranges)))return None- # Without its topics: given them, the merge wrote them all back out and was cut off.root.pop("topics", None)notes.append(jsonfmt.write(root, pretty=False))topics += thinned(parsed.topics, part_topics(len(ranges)), lines[ranges[i].stop - 1].t)@@ -323,28 +293,18 @@ def _min(a, b):return b if a is None else a if b is None else min(a, b)-# The most topics the final notes have (the prompt says so too; the model doesn't always listen).MAX_TOPICS = 8-# Live notes once stopped at 8 topics and poured the rest of the meeting into the last one, whose-# summary grew into a wall of "最新…又…补充…": past this, the two shortest neighbouring settled-# topics are joined instead, so the newest can start.LIVE_MAX_TOPICS = 12-# How many of the last topics a live update may rewrite; earlier ones stay as they are.EDITABLE_TOPICS = 2-# A topic summary longer than this is a log the model kept appending to, not one sentence.TOPIC_SUMMARY_LIMIT = 160def heard_as_said(terms: list, lines: list) -> list:- """Terms keep only the heard forms the recognizer really wrote (`src`). The notes read lines with- fixes in, so a wrong fix came back as a heard form ("X平台 heard as platform"), went to the- translator and the next fix's request as a known mishearing, and was proposed again."""srcs = [l.src.casefold() for l in lines]return [replace(t, heard=[h for h in t.heard if any(h.casefold() in s for s in srcs)]) for t in terms]def shortened(summary: str) -> str:- """A runaway topic summary cut back to its first sentence (or to the limit, with "…")."""if len(summary) <= TOPIC_SUMMARY_LIMIT:return summaryhead = summary[:TOPIC_SUMMARY_LIMIT]@@ -353,11 +313,6 @@ def shortened(summary: str) -> str:def merge(old: list, frozen: int, returned: list) -> list:- """A live reply's topics after the `frozen` ones it was told to leave alone: with some frozen, at- most the editable ones plus one new, from the end (the model sometimes echoes the whole list),- never a copy of a frozen one, each summary kept to one sentence; and no more than- LIVE_MAX_TOPICS in all (past that, settled neighbours are joined). A reply with no topics of its- own keeps the ones it had."""kept = list(old[:frozen])fixed = {t.title for t in kept}own = [t for t in returned if t.title not in fixed]@@ -367,7 +322,6 @@ def merge(old: list, frozen: int, returned: list) -> list:tail = [replace(t, summary=shortened(t.summary)) for t in tail]tail = capped(tail, LIVE_MAX_TOPICS - min(len(kept), 1))while len(kept) + len(tail) > LIVE_MAX_TOPICS and len(kept) >= 2:- # The pair spanning the least time, its end being the next topic's start.ends = [t.start for t in kept[1:]] + [tail[0].start]i = min(range(len(kept) - 1), key=lambda j: ends[j + 1] - kept[j].start)kept[i] = joined(kept[i], kept[i + 1])@@ -376,8 +330,6 @@ def merge(old: list, frozen: int, returned: list) -> list:def joined(a: NoteTopic, b: NoteTopic) -> NoteTopic:- """Two neighbouring topics as one: both titles and summaries, and up to the 4 points the prompt- allows, taken evenly from each."""from_a = min(len(a.points), max(2, 4 - len(b.points)))from_b = min(len(b.points), 4 - from_a)times = [a.point_time(i) for i in range(from_a)] + [b.point_time(i) for i in range(from_b)]@@ -388,7 +340,6 @@ def joined(a: NoteTopic, b: NoteTopic) -> NoteTopic:def capped(topics: list, count: int) -> list:- """At most `count` topics (at least one): the points of any after that go into the last kept."""topics = list(topics)while len(topics) > max(1, count):extra = topics.pop()@@ -400,8 +351,6 @@ def capped(topics: list, count: int) -> list:def carry_times(old: MeetingNotes, nxt: MeetingNotes) -> None:- """The model echoes points it already had without evidence: keep the times they had, and a point- keeps the time it was first heard."""known = {}for t in old.topics:for i, p in enumerate(t.points):@@ -411,7 +360,6 @@ def carry_times(old: MeetingNotes, nxt: MeetingNotes) -> None:for t in nxt.topics:times = [_min(t.point_time(i), known.get(p)) for i, p in enumerate(t.points)]t.pointTimes = times if any(x is not None for x in times) else None- # A topic starts no later than its first point (the reply dates it from the lines it cites now).first = min((x for x in times if x is not None), default=None)if first is not None and first < t.start:t.start = first@@ -427,18 +375,13 @@ def written(notes: MeetingNotes, language: str) -> bool:return written_in(notes.summary + "".join(t.title for t in notes.topics), language)-# Prompt (Notes.swift › prompt, word for word)-def prompt(notes: MeetingNotes, lines: list, frm: int, language: str, final: bool, names: dict | None = None,voices: bool = False, frozen: int = 0, part: tuple | None = None) -> str:- """`frozen`: the first topics, settled, sent as a list and not returned. `part`: in a long- meeting's final pass, which part `frm:len(lines)` is (1-based index, count)."""nums = speakers.numbers(lines) if voices else {}names = names or {}def line(i):l = lines[i]- # A named voice goes as its name: notes then say "George" rather than "说话人2".who = "你" if l.speaker == "me" else ((names.get(nums[l.id]) or "说话人%d" % nums[l.id]) if l.id in nums else ("对方" if not nums else "未识别"))return "[L%d %s %s] %s" % (i + 1, clock(l.t), who, l.shown)@@ -460,8 +403,6 @@ def prompt(notes: MeetingNotes, lines: list, frm: int, language: str, final: boop += ("%s (id, mm:ss, speaker 对方=the other side / 你=me / a name or 说话人N=one person on the other side, told apart by voice and possibly wrong / 未识别=someone on the other side not identified, text). Speech recognition makes mistakes, often in names: correct them from context, and write a public figure's name as the news spells it.\n"% ("Transcript" if final else "New lines"))p += "\n".join(line(i) for i in range(frm, len(lines)))- # The model splits too eagerly when only told how long a topic should be: say plainly whether- # this update may start one.if final and frm < len(lines):span = lines[-1].t - lines[frm].tmost = max(1, min(part_topics(part[1]) if part else MAX_TOPICS, int(span / 180) + 1))@@ -476,7 +417,6 @@ def prompt(notes: MeetingNotes, lines: list, frm: int, language: str, final: boodef _format(language: str, voices: bool, final: bool, frozen: int) -> str:- """The reply's JSON shape and the rules for its contents."""return ("Return the full notes as one JSON object with exactly these keys:\n""{\"title\": \"the meeting's name: what it is about, a few words\",\n"" \"summary\": \"2-3 sentences on the whole meeting so far\",\n"@@ -505,16 +445,11 @@ def _format(language: str, voices: bool, final: bool, frozen: int) -> str:"" if final else "; add at most one new topic per update", language))-# Long meetings--# How a long meeting's final pass is split: over SPLIT_MINUTES, into equal parts by time of at most-# PART_MINUTES. One pass covered a 91-minute meeting but only the first hour of a 4-hour one.SPLIT_MINUTES = 100.0PART_MINUTES = 60.0def parts(lines: list) -> list:- """The final pass's parts as ranges of line indices."""if not lines:return []first, last = lines[0].t, lines[-1].t@@ -534,21 +469,14 @@ def parts(lines: list) -> list:def part_topics(n: int) -> int:- """Each part's share of the topics: the merge keeps them as they are, so every part has some."""return max(2, MAX_TOPICS // max(1, n))def thinned(topics: list, count: int, end: float) -> list:- """At most `count` of a part's `topics`, neighbours joined: a part's reply often has more topics- than asked. Keeping the first ones lost the end of the part, and keeping some spread from first to- last kept a topic's "(续)" stub at the part's end and dropped the topic itself. The same subject- twice is joined first, under the first one's title; then the pair spanning the least time (to the- next topic's start, or `end` for the last), as live notes do."""topics = list(topics)while len(topics) > max(1, count):pairs = range(len(topics) - 1)same = next((i for i in pairs if subject(topics[i].title) == subject(topics[i + 1].title)), None)- # min() keeps the first of equal spans, as the Mac does.i = same if same is not None else min(pairs, key=lambda j: (topics[j + 2].start if j + 2 < len(topics) else end) - topics[j].start)one = joined(topics[i], topics[i + 1])@@ -559,7 +487,6 @@ def thinned(topics: list, count: int, end: float) -> list:def subject(title: str) -> str:- """A topic title without a trailing bracket ("预算评审(续)", "Budget (cont.)"): what it is about."""t = title.strip()if not t or t[-1] not in "))":return t@@ -568,9 +495,6 @@ def subject(title: str) -> str:def merge_prompt(parts: list, lines: list, language: str, voices: bool) -> str:- """The whole meeting's title, summary, conclusions, to-dos and terms from its parts' notes (the- replies as they came, with their evidence line ids). Asked to merge topics too, the model kept the- first parts' and dropped the rest, so topics are joined in code."""p = ("You keep notes for a meeting that has just ended. It was long, so each part was noted on its own; below are those notes, in time order (JSON; evidence ids are transcript lines, L1 the first). Merge them into the notes for the whole meeting.\n""Write the notes in %s. Return JSON only.\n\n" % language)for i, part in enumerate(parts):@@ -582,9 +506,6 @@ def merge_prompt(parts: list, lines: list, language: str, voices: bool) -> str:def _compact_json(n: MeetingNotes, frm: int = 0) -> str:- """The current notes as sent back to the model (no bookkeeping fields), topics from `frm` (earlier- ones go as a list of titles). Insertion order, like the Kotlin LinkedHashMap; jsonfmt sorts keys,- which the model doesn't mind."""o = {}if n.title is not None:o["title"] = n.title@@ -597,10 +518,7 @@ def _compact_json(n: MeetingNotes, frm: int = 0) -> str:return jsonfmt.write(o, pretty=False)-# Parse-def parse(raw: str, times: list, started_at: float) -> MeetingNotes | None:- """Lenient: missing keys become empty, evidence ids are checked against the transcript."""a = raw.find("{")b = raw.rfind("}")if a < 0 or b <= a:@@ -639,7 +557,6 @@ def parse(raw: str, times: list, started_at: float) -> MeetingNotes | None:fish = Nonef = obj(t.get("fishbone"))if f is not None:- # A branch's time from its lines, as a point's: the model's own "t" came back past the end.branches = [FishboneBranch(label=s(br.get("label")), detail=s(br.get("detail")),t=time_of(br.get("evidence")) if line_numbers(br.get("evidence")) else num(br.get("t")),support=len(line_numbers(br.get("evidence")))) for br in objects(f.get("branches"))]@@ -654,8 +571,6 @@ def parse(raw: str, times: list, started_at: float) -> MeetingNotes | None:continuepoints.append(text)point_times.append(time_of(po.get("evidence")) if po is not None else None)- # When it was first said, from its lines: the model's own start drifts by tens of minutes in a- # long meeting (a topic said at 51-85 min came back as starting at 23).said = [x for x in [time_of(t.get("evidence"))] + point_times if x is not None]start = min(said) if said else num(t.get("start"))n.topics.append(NoteTopic(start=started_at if start is None else start, title=topic_title, summary=s(t.get("summary")),@@ -673,6 +588,5 @@ def parse(raw: str, times: list, started_at: float) -> MeetingNotes | None:name = s(t.get("name"))if name:terms.append(NoteTerm(name=name, note=s(t.get("note")), heard=[s(h) for h in arr(t.get("heard")) if s(h) and s(h) != name]))- # The model keeps every term it ever had: bound the glossary, keeping the misheard ones.n.terms = NoteTerm.ordered(terms)[:20] if len(terms) > 20 else termsreturn None if n.is_empty else ndiff --git a/linux/cicada/core/problem.py b/linux/cicada/core/problem.pyindex 984bc73..9b90bc3 100644--- a/linux/cicada/core/problem.py+++ b/linux/cicada/core/problem.py@@ -1,19 +1,10 @@-"""Something only the user can fix, said beyond the settings (the Mac's AIServiceStrip.blocking and-its menu bar dot). Plain GNOME has no top bar icon and the notes window may be put away while you-meet, so on Linux it is also a desktop notification: once a meeting for a failure that stays until-you change something, and once for a service that has been unreachable for 2 minutes (shorter is-usually the network catching its breath). Never while the notes window shows it already. Stdlib-only: the Mac runs these tests too."""from __future__ import annotationsfrom . import aicheckfrom .strings import L, LF-# Stay until the key, the account, a model or the address changes: not the network, a busy service-# or one that errs. DEAF is the ports' own: the service hears for us, so nothing goes on without it.BLOCKING = (aicheck.INVALID_KEY, aicheck.MGMT_KEY, aicheck.NO_CREDIT, aicheck.NO_MODEL,aicheck.BAD_ADDRESS, aicheck.NO_JSON, aicheck.DEAF)-# Only the notes and the full translations stop; the subtitles go on (the hear model is fine).NOTES_ONLY = (aicheck.NO_MODEL, aicheck.NO_JSON)UNREACHABLE_AFTER = 120.0@@ -27,7 +18,6 @@ def stops_hearing(reason: str | None) -> bool:def title(reason: str | None, service: str, text_model: str, hear_model: str) -> str | None:- """The Mac's words for a blocking failure (AIServiceStrip.blocking), plus 听不了声音; None otherwise."""if not blocking(reason):return Nonereturn {aicheck.INVALID_KEY: lambda: LF("%@ 的 key 用不了", service),@@ -38,20 +28,16 @@ def title(reason: str | None, service: str, text_model: str, hear_model: str) ->class Notices:- """When to notify, per meeting: `start` at 开始听, `tick` every second and on each change."""-def __init__(self, wait: float = UNREACHABLE_AFTER):self.wait = waitself.sent: set = set()- self.since: float | None = None # unreachable, while listening, since then+ self.since: float | None = Nonedef start(self) -> None:self.sent = set()self.since = Nonedef tick(self, now: float, listening: bool, reason: str | None, shown: bool) -> str | None:- """"blocking" or "unreachable" when a notification is due now (counted as sent), else None.- `shown`: the notes window is up and says it."""if reason == aicheck.UNREACHABLE and listening:if self.since is None:self.since = nowdiff --git a/linux/cicada/core/providers.py b/linux/cicada/core/providers.pyindex 8df7099..de43831 100644--- a/linux/cicada/core/providers.py+++ b/linux/cicada/core/providers.py@@ -1,13 +1,3 @@-"""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 annotationsimport base64@@ -21,27 +11,27 @@ 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+ note: str = ""@dataclass(frozen=True)class CloudVoice:id: str- gender: str # "女" / "男", a Chinese UI key+ gender: str@dataclass(frozen=True)class Provider:id: strname: str- base: str | None # None for "custom": the user's address- site: str | None # where to create a key+ base: str | None+ site: str | Nonetext_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)+ voice_models: tuple = ()+ voices: tuple = ()clones: bool = False- spacing: float = 0.1 # Ling allows ~2 request starts a second; the aggregators far more+ spacing: float = 0.1@propertydef has_voices(self) -> bool:@@ -71,8 +61,6 @@ ZENMUX = Provider(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)@@ -85,7 +73,7 @@ def named(raw: str) -> Provider:def _host(host_or_url: str) -> str:s = (host_or_url or "").strip()if "://" not in s and s.count(":") > 1 and "/" not in s:- return s.strip("[]").lower() # a bare IPv6 address+ return s.strip("[]").lower()try:host = urllib.parse.urlsplit(s if "://" in s else "http://" + s).hostnameexcept ValueError:@@ -94,14 +82,10 @@ def _host(host_or_url: str) -> str:def is_local(host_or_url: str) -> bool:- """This computer."""return _host(host_or_url) in ("localhost", "127.0.0.1", "::1")def is_nearby(host_or_url: str) -> bool:- """This computer or the local network (AIProvider.isNearby): plain http is allowed and a key- isn't needed. Private IPv4 (10/8, 172.16/12, 192.168/16), link-local, Tailscale's 100.64/10,- IPv6 unique and link-local addresses, and `.local` names."""h = _host(host_or_url)if is_local(h) or h.endswith(".local"):return True@@ -117,8 +101,6 @@ def is_nearby(host_or_url: str) -> bool:def custom_base(raw: str) -> str | None:- """The address as typed, normalized: https, or http only on this computer or the local network- (Ollama, LM Studio, a GPU box at home or work, a Tailscale address); ends in "/"."""s = (raw or "").strip()if not s:return None@@ -139,9 +121,6 @@ def custom_base(raw: str) -> str | None:def thought(root: dict) -> bool:- """The model thought before answering, which makes every translation slow (AIConfig.thought):- a `reasoning_content` (or `reasoning`) field, reasoning tokens in the usage, or a `<think>`- block in the answer."""choices = arr((root or {}).get("choices"))message = obj((obj(choices[0]) or {}).get("message")) if choices else Nonemessage = message or {}@@ -159,49 +138,37 @@ def thought(root: dict) -> bool:@dataclassclass 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+ base: str | Nonetext_model: strhear_model: str- voice_model: str | None = None # None: no voices with this service+ voice_model: str | None = Nonevoice_base: str | None = Nonecustom_voice: str | None = Noneextra: dict = field(default_factory=dict)- # Where the hear model is asked: a custom service's own hear address (the text model and an- # 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 = Nonenotes_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@propertydef 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 Noneor self.notes_own_service)@propertydef 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 selfreturn replace(self, text_model=self.notes_model or self.text_model, base=self.notes_base or self.base)@propertydef hear_url(self) -> str | None:- """The address every hear call (and the check's hear step) goes to."""return self.base if self.hear_base is None else (self.hear_base or None)@propertydef own_hear_address(self) -> bool:- """The hear model is at an address of its own, not the text model's."""return self.hear_base is not None and self.hear_base != self.base@property@@ -214,7 +181,6 @@ class AIConfig:@propertydef 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":@@ -222,10 +188,6 @@ class AIConfig:return self.provider.voicesdef shape(self, body: dict, max_tokens: int, template_kwargs: bool = True) -> None:- """Each service turns thinking off its own way (AIConfig.shape on the Mac). A custom service- gets `chat_template_kwargs` (vLLM, SGLang and llama.cpp pass it to the chat template, which- is how Qwen3 turns thinking off); `template_kwargs` False leaves it out for a server that- refused it."""body["max_tokens"] = max_tokensbody["temperature"] = 0.2if self.is_ling:@@ -236,8 +198,6 @@ class AIConfig:body["chat_template_kwargs"] = {"enable_thinking": 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}}@@ -247,7 +207,6 @@ class AIConfig: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.aiVoiceModelsif p.id == "ling":@@ -258,12 +217,8 @@ def config_from(settings) -> AIConfig:voice = (voices.get("custom") or "").strip()voice_base = custom_base(settings.aiCustomVoiceBase) if settings.aiCustomVoiceBase.strip() else basename = settings.aiCustomVoice.strip()- # 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- # 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))@@ -282,9 +237,6 @@ _NOT_CHAT = re.compile(r"(embed|whisper|tts|asr|transcribe|dall-e|image|moderatidef 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_objectroot = parse_object(data) if isinstance(data, str) else dataids = []@@ -299,7 +251,7 @@ def catalog(data: str | dict, recommended: list, hears: bool) -> list:if outs and "text" not in outs:continueif ins and ins == ["audio"]:- continue # speech-to-text only: no prompt, no translation+ continueif hears and "audio" not in ins:continueif not outs and _NOT_CHAT.search(mid):@@ -310,9 +262,6 @@ def catalog(data: str | dict, recommended: list, hears: bool) -> list: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 = []@@ -324,7 +273,5 @@ def hosts(c: AIConfig, notes: bool = True) -> list:def only_host(c: AIConfig) -> str | 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 Nonediff --git a/linux/cicada/core/proxy.py b/linux/cicada/core/proxy.pyindex b3b0ab2..38fe30c 100644--- a/linux/cicada/core/proxy.py+++ b/linux/cicada/core/proxy.py@@ -1,15 +1,3 @@-"""How the app's requests reach the internet, and the words of the "can't reach the AI service" hint-(ProxyHint.swift). The app never sets a proxy; it uses the one this computer has:--- the environment's `https_proxy` (`http_proxy` for http://), as urllib always did, or `all_proxy`- (an HTTP or SOCKS5 proxy);-- else GNOME's 设置 › 网络 › 网络代理 set to manual, which isn't passed to apps' environments: its- HTTPS proxy, else the HTTP one (use-same-proxy, GNOME's default), else its SOCKS host, except for- the hosts it says to ignore. The website's proxy help sends Linux users exactly there.--"Automatic" (a PAC file) needs a JavaScript engine to evaluate, so requests go direct then, and the-hint says so rather than claiming a proxy is on. Every request (AI service, translation, updates)-goes through `urlopen` here."""from __future__ import annotationsimport ast@@ -27,17 +15,11 @@ import urllib.requestfrom .support import Log-# Ports common proxy apps listen on (Clash 7890, Clash Verge 7897, SOCKS 1080).PORTS = (7890, 7897, 1080)-# A host the hint asks about: any public one (GNOME's ignore list names local ones).PROBE_URL = "https://openrouter.ai/"class Route:- """`kind`: "direct"; "env" (urllib reads the environment itself, no_proxy included); "http" or- "socks" through `host`:`port`, from `origin` ("env" or "gnome"). `url` is the HTTP proxy as- urllib takes it (credentials in it stay out of logs: `where` is host:port only)."""-def __init__(self, kind: str, host: str = "", port: int = 0, origin: str = "", url: str = ""):self.kind, self.host, self.port, self.origin, self.url = kind, host, port, origin, url@@ -55,19 +37,16 @@ class Route:return "Route(%s)" % " ".join(str(p) for p in self.key()[:4] if p)-# GNOME's settings-def _gsettings_dump() -> str:try:r = subprocess.run(["gsettings", "list-recursively", "org.gnome.system.proxy"],capture_output=True, text=True, timeout=2)return r.stdout if r.returncode == 0 else ""except (OSError, subprocess.SubprocessError):- return "" # no gsettings (not GNOME, or the Mac running the tests)+ return ""def parse_gnome(text: str) -> dict:- """`gsettings list-recursively org.gnome.system.proxy` as {"mode": "manual", "https.host": …}."""out: dict = {}for line in text.splitlines():parts = line.split(None, 2)@@ -75,7 +54,7 @@ def parse_gnome(text: str) -> dict:continuechild = parts[0][len("org.gnome.system.proxy"):].lstrip(".")raw = parts[2].strip()- if raw.startswith("@"): # a typed empty value: "@as []"+ if raw.startswith("@"):raw = raw.split(None, 1)[1] if " " in raw else ""raw = {"true": "True", "false": "False"}.get(raw, raw)try:@@ -91,8 +70,6 @@ _gnome_lock = threading.Lock()def gnome(read=None, ttl: float = 3.0) -> dict:- """GNOME's proxy settings, read again after `ttl` seconds: partial translations ask several- times a second, and a changed setting applies within moments, no restart."""global _gnome_cacheif read is not None:return parse_gnome(read())@@ -107,8 +84,6 @@ def gnome(read=None, ttl: float = 3.0) -> dict:def ignored(host: str, port: int, patterns) -> bool:- """GNOME's ignore-hosts (GSimpleProxyResolver's forms): "example.com", ".example.com" and- "*.example.com" all match it and its subdomains; an address or a CIDR range; any with ":port"."""host = host.strip("[]").lower().rstrip(".")try:addr = ipaddress.ip_address(host)@@ -119,10 +94,10 @@ def ignored(host: str, port: int, patterns) -> bool:if not p:continuewant_port = None- if p.startswith("[") and "]" in p: # "[::1]:8080"+ if p.startswith("[") and "]" in p:p, _, rest = p[1:].partition("]")want_port = int(rest[1:]) if rest.startswith(":") and rest[1:].isdigit() else None- elif p.count(":") == 1: # "example.com:8080" (an IPv6 address has several colons)+ elif p.count(":") == 1:p, _, pp = p.partition(":")want_port = int(pp) if pp.isdigit() else Noneif want_port is not None and want_port != port:@@ -142,8 +117,6 @@ def ignored(host: str, port: int, patterns) -> bool:return False-# Which way a request goes-def _env(env, *names) -> str:for n in names:v = (env.get(n) or env.get(n.upper()) or "").strip()@@ -153,7 +126,6 @@ def _env(env, *names) -> str:def _proxy_url(value: str):- """("http"|"socks", host, port, url) for a proxy URL, or None when it isn't one we can use."""if "://" not in value:value = "http://" + valueu = urllib.parse.urlsplit(value)@@ -171,17 +143,15 @@ def _proxy_url(value: str):def route(url: str, env=None, settings=None) -> Route:- """How a request to `url` leaves the app. `env` and `settings` (parse_gnome's) are for tests."""env = os.environ if env is None else envu = urllib.parse.urlsplit(url)if u.scheme not in ("http", "https") or not u.hostname:- return Route("direct") # file:// (tests, a local feed)+ return Route("direct")port = u.port or (443 if u.scheme == "https" else 80)if _env(env, u.scheme + "_proxy"):return Route("env", origin="env")every = _env(env, "all_proxy")if every:- # urllib ignores all_proxy; Clash's "copy proxy command" sets it, often as socks5://.p = _proxy_url(every)no = _env(env, "no_proxy")if p and not (no and urllib.request.proxy_bypass_environment(u.hostname, {"no": no})):@@ -207,8 +177,6 @@ def route(url: str, env=None, settings=None) -> Route:return Route("direct")-# SOCKS5 (RFC 1928), no authentication: the name is resolved by the proxy, as socks5h does.-def _recv(sock, n: int) -> bytes:data = b""while len(data) < n:@@ -286,19 +254,15 @@ def opener(r: Route):def urlopen(req, timeout: float):- """urllib.request.urlopen, through this computer's proxy (route)."""url = req.full_url if isinstance(req, urllib.request.Request) else reqr = route(url)- if r.key() != _said[0] and url.startswith("http"): # a file:// test feed would flip it back and forth+ if r.key() != _said[0] and url.startswith("http"):_said[0] = r.key()Log.d("net: %s%s" % (r.kind, " %s %s" % (r.origin, r.where) if r.where else ""))return opener(r).open(req, timeout=timeout)-# The hint-def listening(port: int, timeout: float = 0.3) -> bool:- """Something accepts a TCP connection on 127.0.0.1:`port` within `timeout`. Nothing is sent."""return reachable("127.0.0.1", port, timeout)@@ -311,9 +275,6 @@ def reachable(host: str, port: int, timeout: float = 1.0) -> bool:def hint(env=None, gsettings=None, probe=listening, reach=reachable) -> tuple:- """("system",) a proxy is in use and answers; ("dead", "host:port") the proxy in use doesn't- answer; ("pac",) GNOME's proxy is automatic, which the app can't use; ("app", port) a proxy app- listens but no proxy is set; ("none",). See AICheck.proxy_line."""env = os.environ if env is None else envsettings = gnome(gsettings) if gsettings is not None else gnome()r = route(PROBE_URL, env, settings)diff --git a/linux/cicada/core/roommic.py b/linux/cicada/core/roommic.pyindex f57d94d..259ccf3 100644--- a/linux/cicada/core/roommic.py+++ b/linux/cicada/core/roommic.py@@ -1,13 +1,9 @@-"""会议室: listening to the people in the room through a real microphone instead of what the computer-plays (the Mac's RoomMic.swift). Pure: which microphone, and when a block of it counts as speech.-The capture itself is app/capture.py's SystemAudio on a source instead of a monitor."""from __future__ import annotationsimport threadingfrom .support import Log-# Sources Cicada makes itself (app/room.py's 知了 麦克风), never a room microphone.OURS = ("cicada_mic",)@@ -26,8 +22,6 @@ class Input:def parse_sources(text: str) -> list:- """The inputs in `LC_ALL=C pactl list sources`. A monitor of an output, a source a module made- (no device.api: 知了 麦克风, an echo canceller, a remap) or one of ours is virtual: it hears no room."""out = []block: dict = {}props: dict = {}@@ -61,10 +55,6 @@ def parse_sources(text: str) -> list:def pick(default: str | None, inputs: list, chosen: str = "") -> str | None:- """The microphone that hears the room (RoomMicPlan.pick): the one chosen in 设置 › 会议室 while it- is there; else the default input, unless it is virtual (同声传译 makes 知了 麦克风 the default) or a- Bluetooth headset's (it hears the wearer, not the table, and drops to call quality while open);- then the computer's own microphone, then any real one."""real = [i for i in inputs if not i.virtual]if chosen and any(i.name == chosen for i in real):return chosen@@ -79,11 +69,6 @@ def pick(default: str | None, inputs: list, chosen: str = "") -> str | None:class VoiceGate:- """When a block of audio counts as speech (the Mac's VoiceGate). The computer's own audio is- digital silence between words, so a fixed -40 dBFS works there. A room mic always hears the room- (a fan, the street), and a voice across the table can be quieter than -40 dBFS: there the line- sits at twice the room's own noise. The noise is the quietest moment of each second (the gaps- between words, even while people talk on and on), taken low over the last half minute."""fixed = 0.01lowest = 0.0015@@ -117,11 +102,7 @@ class VoiceGate:return on-# 电脑和会议室: the computer's audio and the room microphone at once, each heard on its own.-def heard_both(lines) -> bool:- """The room mic and the computer's audio both brought in the other side's lines, so each one says- where it was heard (the Mac's RecordList.heardBoth). Read from the lines, not stored."""room = online = Falsefor l in lines:if l.speaker != "them":@@ -136,7 +117,6 @@ def heard_both(lines) -> bool:def place_starts(lines) -> set:- """Lines of the other side's where the place changes from the line before: their label shows again."""out, last, first = set(), None, Truefor l in lines:key = "me" if l.speaker == "me" else l.via@@ -147,26 +127,14 @@ def place_starts(lines) -> set:class EchoGate:- """打开麦克风 while the computer plays a meeting, without the sound server's echo cancellation: the- room mic hears the remote voices again from the speakers (the Mac's EchoGate, same rules). The- room mic hears silence while the computer plays speech, until `hang` after it, but only when- that is needed and only for speech:-- - Echo is measured: the room mic's loud end while the computer is loud over its floor while the- computer is quiet. Headphones or a meeting mic leave it where it was, and then nothing is- silenced, so people at the table are heard over a remote speaker too. Until there is enough- to tell (and whenever it is unclear) the speakers are taken to echo.- - Music isn't speech: a loud stretch the computer's side has recognized no words in for `music`- seconds stops closing the gate; words close it again. Longer than the Mac's 4 s: here words- only come back after a whole segment has gone to the service."""hang = 0.4music = 20.0stretch_gap = 1.5- during = 0.15 # computer audio this recent makes a room block "during"- quiet_after = 1.0 # …this long ago, "the computer is quiet"- echo_ratio = 3.0 # at or over: echo; under clear_ratio: none+ during = 0.15+ quiet_after = 1.0+ echo_ratio = 3.0clear_ratio = 2.0- enough = 3.0 # seconds of each a decision needs+ enough = 3.0window = 20.0def __init__(self):@@ -175,10 +143,10 @@ class EchoGate:self._last_loud = float("-inf")self._stretch_start = float("-inf")self._last_words = float("-inf")- self._during: list = [] # (t, rms, seconds) while the computer is loud+ self._during: list = []self._quiet: list = []self._echo = True- self.forced = None # debug (roomEchoSim): pretend the measurement says this+ self.forced = None@propertydef echo(self) -> bool:@@ -194,7 +162,6 @@ class EchoGate:return self._music(now)def hold(self, now: float) -> None:- """A loud block of the computer's audio."""with self._lock:if now - self._last_loud > self.stretch_gap:self._stretch_start = now@@ -213,7 +180,6 @@ class EchoGate:return now < self._untildef room_level(self, rms: float, seconds: float, now: float) -> None:- """A block of what the room mic heard, before any silencing."""with self._lock:since = now - self._last_loudif since <= self.during:@@ -239,9 +205,6 @@ class EchoGate:@classmethoddef ratio(cls, during: list, quiet: list):- """The room mic's loud end (a fifth of it louder) while the computer is loud over its floor- (the quietest fifth) while it is quiet, or None without `enough` of both. People at the table- talking over the computer raise it too: that errs on the side of echo."""if sum(s for _, s in during) < cls.enough or sum(s for _, s in quiet) < cls.enough:return Noned = sorted(r for r, _ in during)@@ -257,13 +220,9 @@ class Heard:class EchoMatch:- """电脑和会议室's last line of defence against hearing an online sentence twice: once from the- computer's audio, once more from the speakers into the room mic (the Mac's EchoMatch). A room line- made mostly of what the computer played around the same time is dropped, matched by containment- in word pairs (characters for Chinese, Japanese and Korean)."""- window = 3.0 # seconds around the room line where the computer's lines count- hold = 2.5 # how long a room line waits for the computer's line it may echo- contained = 0.6 # share of the room line found in the computer's lines that makes it an echo+ window = 3.0+ hold = 2.5+ contained = 0.6@classmethoddef is_echo(cls, room: Heard, online: list) -> bool:@@ -274,7 +233,7 @@ class EchoMatch:if not r:return Falseo = [units(x.text) for x in near]- if len(r) <= 2: # a word or two ("OK", "对"): the very same words near it+ if len(r) <= 2:return any(x == r for x in o)mine = set(_pairs(r))theirs = set(p for x in o for p in _pairs(x))@@ -288,7 +247,6 @@ def _cjk(c: str) -> bool:def units(text: str) -> list:- """Lower-case words, each CJK character on its own; punctuation and spacing don't count."""out, word = [], ""for c in text.lower():if _cjk(c):diff --git a/linux/cicada/core/segmenter.py b/linux/cicada/core/segmenter.pyindex 6907296..0fc158f 100644--- a/linux/cicada/core/segmenter.py+++ b/linux/cicada/core/segmenter.py@@ -1,7 +1,3 @@-"""Cuts the audio into stretches of speech by loudness alone: a pause of 0.6 s ends one, and one that-runs to 8 s is cut at its quietest moment in the last 2 s, so a word is split as rarely as possible-(Ming has no word timings to put it back together). Not thread-safe: fed from the listening worker-only. Same numbers as the Windows and Android Segmenters."""from __future__ import annotationsimport math@@ -10,20 +6,16 @@ from collections import dequefrom .audio import RATE, Wav-FRAME = 480 # 30 ms-STEP = 160 # 10 ms: a key click is judged in these, as the Mac's VoiceActivity does-ONSET = 3 # steps of sound before it counts as speech+FRAME = 480+STEP = 160+ONSET = 3PRE_ROLL = 0.15TAIL = 0.15CUT_WINDOW = 2.0-# A first-order high-pass at 100 Hz, for how much of a sound is above it (_rumble).HIGH_PASS = 1.0 / (1.0 + 2.0 * math.pi * 100.0 / RATE)class Segment:- """A stretch of speech to send to Ming: where it starts (seconds since listening began) and its- 16 kHz mono samples."""-def __init__(self, index: int, start: float, samples: array):self.index = indexself.start = start@@ -35,34 +27,32 @@ class Segment:class Segmenter:- # The Mac AudioRouter's gate (about -40 dBFS). A room microphone's segmenter has it set by- # roommic.VoiceGate as the room's noise is learnt.threshold = 0.01pause = 0.6max_length = 8.0min_speech = 0.25- min_word = 0.2 # a word on its own (_isolated): this much over gate / 4 ("Thanks." at -36 dBFS: 0.21 s)- steady = 2.0 # frames' 90th / 10th percentile below this: not speech…- dips = 2.5 # …unless the median is this far over the 10th percentile, quiet ones held at gate / 8- short = 2.0 # a sound up to this long, with real quiet (gate / 4) on both sides…- swell = 10 ** (10 / 20) # …that swells and fades by 10 dB is a word: see _isolated- fade = 10 ** (30 / 20) # its rise and fade reach this far under its loudest step (or gate / 4 if lower)- voiced = 0.15 # a word's full frames crossing zero under this often (per sample) have voice in them: see _voiced- above = 0.25 # under this share of its loud frames' energy over 100 Hz: rumble, not speech+ min_word = 0.2+ steady = 2.0+ dips = 2.5+ short = 2.0+ swell = 10 ** (10 / 20)+ fade = 10 ** (30 / 20)+ voiced = 0.15+ above = 0.25def __init__(self):self.pending = array("h")self.current = array("h")self.levels: list = []- self.highs: list = [] # per frame of `current`: its level over 100 Hz- self.speech: list = [] # per frame of `current`: whether it held speech (_speech)- self.sounding = 0 # 10 ms steps of sound in a row so far- self.carried = False # the sound that made the last frame speech began in the frame before- self._hx = 0.0 # the high-pass's last input and output, carried from frame to frame+ self.highs: list = []+ self.speech: list = []+ self.sounding = 0+ self.carried = False+ self._hx = 0.0self._hy = 0.0self.before: deque = deque()- self.idle: deque = deque(maxlen=int(self.pause * RATE / FRAME)) # levels of the last quiet frames- self.lead = None # the quietest of those when the open segment began (None: it didn't begin in quiet)+ self.idle: deque = deque(maxlen=int(self.pause * RATE / FRAME))+ self.lead = Noneself.consumed = 0self.current_start = 0.0self.quiet = 0@@ -78,14 +68,10 @@ class Segmenter:del self.pending[:whole]def flush(self) -> None:- """Ends the open segment (listening stopped)."""if len(self.current):self._close(len(self.current) - self.quiet * FRAME + int(TAIL * RATE))def _speech(self, frame) -> bool:- """Whether the frame holds speech: sound that has lasted 30 ms, judged in 10 ms steps against the- line, so a lone key click (a few ms) neither opens a segment nor breaks the pause that ends- one (VoiceActivity.swift's onset). The pre-roll then reaches back to where that sound began."""said = Falsecarried = self.sounding > 0for i in range(0, len(frame), STEP):@@ -112,7 +98,6 @@ class Segmenter:while len(self.before) > PRE_ROLL * RATE / FRAME + 1:self.before.popleft()return- # One frame more when the sound began in the last quiet one.while len(self.before) > PRE_ROLL * RATE / FRAME + self.carried:self.before.popleft()self.current_start = now - len(self.before) * FRAME / RATE@@ -137,7 +122,6 @@ class Segmenter:if self.quiet * FRAME >= self.pause * RATE:self._close(len(self.current) - self.quiet * FRAME + int(TAIL * RATE))elif len(self.current) >= self.max_length * RATE:- # The quietest frame in the last 2 s; the rest starts the next segment.frm = max(1, len(self.levels) - int(CUT_WINDOW * RATE / FRAME))cut = frmfor i in range(frm, len(self.levels)):@@ -146,19 +130,6 @@ class Segmenter:self._close(cut * FRAME)def _steady(self, levels) -> bool:- """Steady sound just over the gate (a fan, hum, hiss) isn't speech: its loud frames barely vary- (90th / 10th percentile about 1.1; speech, even over such a floor, 3 and up). Given one, Ming- writes a stock sentence in the hint's language ("I'm going to show you a couple of things").- Speech buried under steady noise goes too; system audio rarely carries it. Every frame from- the first loud one to the last counts, the quiet ones held at the gate: counting only the- loud ones dropped quiet speech (under about -30 dBFS), whose dips fall below the gate.- A voice so quiet that its loudest frames barely clear the gate (about -38 dBFS: 6 of 6 lines- lost in testing) still pauses between syllables, its quietest tenth of frames far under its- median (8 dB and more); noise near the gate stays within about 6 dB of its median. So a flat- top is steady only when it has no such dips, measured with quiet frames held at gate / 8.- Very low rumble (brown noise with almost nothing over 20 Hz) can look like that and gets- through more often than before (about 1 in 3 segments, was 1 in 5); what Ming makes of it- still meets the hear filter (translator.is_noise)."""loud = [i for i, l in enumerate(levels) if l >= self.threshold]if len(loud) < 2:return False@@ -170,22 +141,6 @@ class Segmenter:return low[int(0.5 * (len(low) - 1))] < self.dips * low[int(0.1 * (len(low) - 1))]def _isolated(self, levels) -> bool:- """A short word on its own: a sound up to `short` that rises out of real quiet and falls back- into it (under gate / 4, about -52 dBFS, in the 0.6 s before it and in the pause after),- and that swells and fades by 10 dB or more: at least 5% of its 10 ms steps (and 3 of them),- from where it rises to where it fades, are that far under its 90th percentile. Such a word- ("Thanks.", "Good morning everyone,") is one smooth syllable or a run of voiced ones, so the- steady test, which looks for dips inside, dropped it even at -26 dBFS; and a quiet one- ("Thanks." at -36 dBFS) has under 0.25 s over the gate, so it needs `min_word` over gate / 4- instead (a knock with a 150 ms tail has 0.15 s). A fan, hum or hiss is there on both sides;- a short burst of one in silence has at most one low step at each edge (its 5th percentile- stays within 2 dB, 9 dB with 50 ms fades), and Ming makes up a sentence for a hum or fan- burst. Not for a forced cut, whose end isn't a pause.- Where it rises and fades: over gate / 4, or 30 dB under its loudest step if that's lower;- over gate / 4 alone, a quiet word lost its rise and fade (an "s" or breath at -55 dBFS) and- only its flat top was left. 30 ms frames and their 10th percentile put Samantha's "Good- morning everyone." at 7.5 to 11.4 dB depending on where the frames fell, so it came and- went with a few ms of lead-in; 10 ms steps and their 5th percentile give it 14.6 to 16.5."""loud = [i for i, l in enumerate(levels) if l >= self.threshold]if not loud or (loud[-1] - loud[0] + 1) * FRAME > self.short * RATE:return False@@ -201,11 +156,6 @@ class Segmenter:return low < len(body) and body[int(0.9 * (len(body) - 1))] >= self.swell * body[low] and self._voiced(levels)def _voiced(self, levels) -> bool:- """Whether a word has voice in it: 2 or more of its full frames (within 3 dB of its 90th- percentile) cross zero under `voiced` times a sample. Voiced speech crosses slowly (every- voice tested had full frames at 0.01 to 0.06); a hiss crosses about every other sample (0.46- and up) and, faded in and out over 0.3 s, swells like a word. Edge frames half silence- cross slowly whatever they hold, hence full frames only and more than one."""full = sorted(levels)[int(0.9 * (len(levels) - 1))] / math.sqrt(2)slow = 0for i, l in enumerate(levels):@@ -218,8 +168,6 @@ class Segmenter:return slow >= 2def _high(self, frame) -> float:- """The frame's level over 100 Hz (RMS after the high-pass), the filter running on across frames.- A plain loop, not sum(): every port adds in the same order and gets the same number."""a, x0, y, total = HIGH_PASS, self._hx, self._hy, 0.0for x in frame:y = a * (y + x - x0)@@ -229,12 +177,6 @@ class Segmenter:return math.sqrt(total / len(frame)) / 32768 if len(frame) else 0.0def _rumble(self, levels, highs) -> bool:- """Rumble, not speech: under a quarter of the loud frames' energy is over 100 Hz. Speech keeps- nearly all of it there (-0.3 to -1 dB in testing, the low male voices included); brown noise- with almost nothing over 20 Hz keeps -20 to -28 dB, and Ming made a sentence of 15 of 17 such- segments ("I'm going to go ahead and start the meeting."), which the loudness rules can't- tell from a voice. Brown noise up to about 12 Hz keeps -10 dB and goes too; a 50 Hz hum or a- fan keeps about -5 dB and is left to the steady test."""full = above = 0.0for l, h in zip(levels, highs):if l >= self.threshold:@@ -243,7 +185,6 @@ class Segmenter:return above < self.above * fulldef _close(self, end_at: int) -> None:- """Emits current[:end] and keeps what follows as the start of the next segment."""end = max(0, min(end_at, len(self.current)))samples = self.current[:end]rest = self.current[end:]@@ -268,7 +209,6 @@ class Segmenter:self.on_segment(Segment(self.index, round(start * 1000) / 1000.0, samples))elif speech:self.index += 1- # A forced cut carries on with the remainder; after a pause the remainder is silence.if any(rest_speech):self.current_start = start + end / RATEself.lead = Nonediff --git a/linux/cicada/core/session_store.py b/linux/cicada/core/session_store.pyindex 620a1fe..7278eb7 100644--- a/linux/cicada/core/session_store.py+++ b/linux/cicada/core/session_store.py@@ -1,6 +1,3 @@-"""The meeting records: one folder per meeting under Sessions/<yyyyMMdd-HHmmss>/ with session.json,-as on the Mac. Saves are debounced by 1.5 s; a meeting with no lines is removed when it ends.-Thread-safe; listeners fire on whichever thread made the change."""from __future__ import annotationsimport os@@ -22,20 +19,16 @@ class SessionStore:self._listeners = []self._word_listeners = []self._save_listeners = []- self.live: str | None = None # the meeting being listened to (the Mac's liveID)+ self.live: str | None = Noneself._load()def on_change(self, listener) -> None:self._listeners.append(listener)def on_words(self, listener) -> None:- """`listener(sid)` the moment recognised words land in a record: a new line (theirs or mine)- or a half sentence that grew. What 结束会议 counts as someone speaking (MeetingEndWatch.heard)."""self._word_listeners.append(listener)def on_save(self, listener) -> None:- """`listener(sid)` after a record was written to disk (存到文件夹 follows its changes). Fires on- the thread that saved it."""self._save_listeners.append(listener)def _words(self, sid: str) -> None:@@ -50,13 +43,9 @@ class SessionStore:return os.path.join(Paths.sessions(), sid)def audio_path(self, sid: str) -> str:- """What was heard, as on the Mac: system.m4a in the meeting's folder (system.aac while it is- being recorded, see aac.py)."""return os.path.join(self._folder(sid), "system.m4a")def unfinished_audio(self) -> list:- """Meetings whose recording is still the partial file (the app quit mid-meeting, or before- rewrapping it): their ids, to finish at launch as the Mac's load() does."""with self._gate:out = []for s in self._sessions.values():@@ -88,7 +77,6 @@ class SessionStore:Log.d("store: skipped %s: %s" % (name, type(e).__name__))def all(self) -> list:- """Newest first."""with self._gate:return sorted(self._sessions.values(), key=lambda s: s.startedAt, reverse=True)@@ -97,13 +85,11 @@ class SessionStore:return self._sessions.get(sid)def snapshot(self, sid: str) -> Session | None:- """A copy of a record no other thread changes while it is read (a file being written from it)."""with self._gate:s = self._sessions.get(sid)return Session.read(s.write()) if s else Nonedef lines(self, sid: str) -> list:- """A copy of a record's lines, safe to read while listening adds to them."""with self._gate:s = self._sessions.get(sid)return [l.copy() for l in s.lines] if s else []@@ -128,23 +114,17 @@ class SessionStore:def change(s):for i, l in enumerate(s.lines):if l.id == line.id:- # Whose line it is stays as stored: a joined half sentence keeps the earlier- # line's voice, and the user's 这句是谁说的 isn't undone by a retranslation.line.voice = l.voice- # Its fixes too (改正听错的词): the engine's copy of a line never carries them.line.fixes = l.fixesif len(line.src) > len(l.src):- grew.append(True) # a half sentence joined: new words, not a retranslation+ grew.append(True)s.lines[i] = linereturnself._mutate(sid, change)if grew:self._words(sid)- # 改正听错的词 (SessionStore.swift)-def set_fixes(self, sid: str, line_id: str, fixes: list) -> None:- """A line's fixes: what the AI service proposed and the user decided. None when empty."""with self._gate:s = self._sessions.get(sid)l = next((x for x in s.lines if x.id == line_id), None) if s else None@@ -153,15 +133,12 @@ class SessionStore:self._mutate(sid, lambda s: [setattr(x, "fixes", [f.copy() for f in fixes] or None) for x in s.lines if x.id == line_id])def line(self, sid: str, line_id: str):- """A copy of one line, or None."""with self._gate:s = self._sessions.get(sid)l = next((x for x in s.lines if x.id == line_id), None) if s else Nonereturn l.copy() if l else Nonedef line_heard(self, text: str):- """The line a reply was for, by its text as heard: (meeting id, a copy of the line), the newest- such line in the live meeting. Older meetings never: "好的。" is in all of them."""with self._gate:s = self._sessions.get(self.live) if self.live else Noneif s is None:@@ -169,10 +146,7 @@ class SessionStore:l = next((x for x in reversed(s.lines) if x.src == text), None)return (s.id, l.copy()) if l else None- # Voices (说话人识别, SessionStore.swift)-def set_line_voices(self, sid: str, ids: set, voice: int) -> None:- """The user says a line (or a paragraph of them) was someone else's: those lines take that voice."""def change(s):for l in s.lines:if l.id in ids and l.speaker == "them":@@ -180,7 +154,6 @@ class SessionStore:self._mutate(sid, change)def voice_snapshot(self, sid: str):- """Who said what, taken before a speaker edit so 撤销 can put it back."""with self._gate:s = self._sessions.get(sid)if s is None:@@ -193,13 +166,12 @@ class SessionStore:def change(s):for l in s.lines:- if l.id in voices: # lines heard since keep the voice they were given+ if l.id in voices:l.voice = voices[l.id]s.voiceNames, s.voiceGuesses = vnames, guessesself._mutate(sid, change)def set_voice_name(self, sid: str, voice: int, name) -> None:- """The user names a voice. None drops their name (Ling's guess shows again); "" keeps 说话人 N."""def change(s):vn = dict(s.voiceNames or {})if name is None:@@ -210,8 +182,6 @@ class SessionStore:self._mutate(sid, change)def set_voice_guesses(self, sid: str, guesses: dict, refuted: dict | None = None) -> None:- """Ling's latest guesses; earlier ones stay for voices it no longer mentions, unless it now named- them without evidence (refuted, voice → name): then that earlier name goes too."""refuted = refuted or {}if not guesses and not refuted:return@@ -227,7 +197,6 @@ class SessionStore:self._mutate(sid, change)def merge_voice(self, sid: str, frm: int, into: int) -> None:- """The user said two voices are the same person: `frm`'s lines become `into`'s."""if frm == into:return@@ -238,7 +207,6 @@ class SessionStore:if s.voiceNames is not None and str(frm) in s.voiceNames:vn = dict(s.voiceNames)moved = vn.pop(str(frm))- # A turned-down guess ("") stays with the voice it was about; a real name moves over.if str(into) not in vn and moved:vn[str(into)] = moveds.voiceNames = vn or None@@ -251,7 +219,6 @@ class SessionStore:self._mutate(sid, change)def mark_room(self, sid: str) -> None:- """The meeting is (now) heard in the room: its record says 会议室 (the Mac's markLiveInRoom)."""with self._gate:s = self._sessions.get(sid)if s is None or s.room:@@ -262,8 +229,6 @@ class SessionStore:self._mutate(sid, lambda s: setattr(s, "notes", notes))def rename(self, sid: str, title: str) -> None:- """As on the Mac: the shown title unchanged is no rename (the notes may still name it later),- and an empty one goes back to the automatic title (恢复自动标题)."""t = title.strip()with self._gate:s = self._sessions.get(sid)@@ -278,8 +243,6 @@ class SessionStore:self._mutate(sid, change)def end(self, sid: str, ended_at=None) -> None:- """The meeting ended (at `ended_at` when it ended by itself a while ago): kept if anything was- said, removed otherwise."""with self._gate:s = self._sessions.get(sid)if self.live == sid:@@ -288,7 +251,6 @@ class SessionStore:returns.endedAt = max(ended_at, s.startedAt) if ended_at is not None else now()empty = not s.lines- # The recording is rewrapped into system.m4a afterwards: either file means it has one.path = self.audio_path(sid)s.hasAudio = os.path.isfile(path) or (os.path.isfile(aac.partial(path)) and os.path.getsize(aac.partial(path)) > 0)if empty:@@ -299,7 +261,6 @@ class SessionStore:self._fire(sid)def delete(self, sid: str) -> None:- """Never the live meeting (`live` is its id): listening would go on into a record that's gone."""with self._gate:if sid == self.live:Log.d("store: not deleting the live meeting %s" % sid)@@ -310,7 +271,6 @@ class SessionStore:self._fire(sid)def import_session(self, s: Session) -> None:- """A record from elsewhere (a Mac's session.json): added as it is, saved now."""with self._gate:self._sessions[s.id] = sself._mark_dirty(s.id)@@ -336,7 +296,6 @@ class SessionStore:self._timer.start()def flush(self) -> None:- """Writes every changed record now."""with self._gate:writes = [(sid, self._sessions[sid].write()) for sid in self._dirty if sid in self._sessions]self._dirty.clear()@@ -356,14 +315,11 @@ class SessionStore:def default_title(at: datetime) -> str:- """The stored default title is always Chinese ("会议 11月1日 14:30"), as on the Mac; the UI shows- display_title instead."""l = at.astimezone()return "会议 %d月%d日 %02d:%02d" % (l.month, l.day, l.hour, l.minute)def _local_date(at: datetime, pattern: str) -> str:- """The Mac's date patterns the strings tables carry ("M月d日 HH:mm", "MMM d", "yyyy年M月d日")."""l = at.astimezone()months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]out = []@@ -396,14 +352,11 @@ def _local_date(at: datetime, pattern: str) -> str:def display_title(s: Session) -> str:- """The user's own title, else the date and the name the notes gave the meeting, else the default- title in the UI language (Session.displayTitle)."""renamed = s.renamed if s.renamed is not None else not s.title.startswith("会议 ")if renamed:return s.titlename = s.notes.title if s.notes else Noneif not name:- # An imported file is known by its name until the notes give it one.if s.sourceFile:return os.path.splitext(s.sourceFile)[0]return strings.L("会议") + " " + _local_date(s.startedAt, strings.L("M月d日 HH:mm"))@@ -411,19 +364,16 @@ def display_title(s: Session) -> str:return _local_date(s.startedAt, strings.L("M月d日" if this_year else "yyyy年M月d日")) + " " + name-# The Mac's dateText(_, "yMMMdHHmm"), as its DateFormatter writes it in each UI language._DATE_TIME = {"zh-Hans": "y年M月d日 HH:mm", "en": "MMM d, y 'at' HH:mm", "ja": "y年M月d日 H:mm", "ko": "y년 M월 d일 HH:mm"}def header(s: Session) -> str:- """"2026年11月4日 12:30 · 24 分钟" (TranscriptExport.header)."""mins = int(s.duration // 60)when = _local_date(s.startedAt, _DATE_TIME.get(strings.language, _DATE_TIME["zh-Hans"]))return when + " · " + (strings.L("不到 1 分钟") if mins < 1 else strings.LF("%lld 分钟", mins))def notes_markdown(n) -> str:- """The notes as Markdown, empty when there are none (TranscriptExport.notesMarkdown)."""L = strings.Lif n is None or n.is_empty:return ""@@ -449,12 +399,9 @@ def notes_markdown(n) -> str:def markdown(s: Session, voices: bool = False) -> str:- """The record as Markdown, the Mac's export line for line (TranscriptExport.markdown): title, date- · length, the notes, then each line as **[mm:ss] who** with the translation quoted under it."""nums = speakers.numbers(s.lines) if voices else {}shown = speakers.names(s) if nums else {}out = ["# %s\n\n%s\n\n" % (display_title(s), header(s))]- # Names given since Ling wrote "说话人 6" show in the notes too, as in the window.notes = notes_markdown(speakers.named(s.notes, shown))if notes:out.append(notes + "## %s\n\n" % strings.L("文字记录"))diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.pyindex d685946..d23e6b3 100644--- a/linux/cicada/core/settings.py+++ b/linux/cicada/core/settings.py@@ -1,4 +1,3 @@-"""The app's settings, in settings.json beside the key (never the key itself: it has its own file)."""from __future__ import annotationsimport os@@ -11,11 +10,9 @@ DEFAULT_MODEL = "Ling-3.1-flash"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, # 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).+ "target": "system",+ "notesLanguage": "mine",+ "model": DEFAULT_MODEL,"aiProvider": "ling","aiModels": {},"aiHearModels": {},@@ -23,51 +20,32 @@ class AppSettings:"aiCustomBase": "","aiCustomVoiceBase": "","aiCustomVoice": "",- # 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,- "view": "notes", # "notes" (the notes window, default) or "subtitles" (the subtitle bar)- "showInCapture": False, # 共享屏幕时让对方看到 (Linux can't hide it; see NotesWindow)+ "view": "notes",+ "showInCapture": False,"onboarded": False,- # The setup checklist (会议记录 › 还差几步): the onboarding heard the computer's sound / played the sample."heardSystemAudio": False,"sampleSeen": False,- "speakLater": False, # 还差几步 › 同声传译 › 以后再说- "trayHintShown": False, # 知了还在顶栏, said once after the records window is first closed- "showInDock": True, # 在 Dock 中显示 (the Mac's): in the dock for as long as 知了 runs- "uiLanguage": "system", # "system", "zh-Hans", "en", "ja" or "ko"- # 同声传译: what I say is interpreted and spoken into 知了 麦克风 (the Mac's speakEnabled etc.).- # 保存会议录音 (the Mac's recordAudio): system.m4a beside session.json, when GStreamer has an AAC encoder.+ "speakLater": False,+ "trayHintShown": False,+ "showInDock": True,+ "uiLanguage": "system","recordAudio": True,- # 存到文件夹 (the Mac's keys): settled meetings also written as Markdown into exportFolder (a- # path; "" until one is chosen). See folder_export.py."exportOn": False,"exportFolder": "",- # 会中改正听错的词 (the Mac's keys): finished sentences carry the word list to the AI service, which- # points out misheard words (correction.py); askNames: a new name is asked about once."fixMisheard": True,"askNames": True,- "speakerVoices": True, # 说话人识别: tell the other side's voices apart (说话人 1、2…), as on the Mac+ "speakerVoices": True,"speakEnabled": False,- "speakFrom": "system", # the language I speak; "system" = the subtitles' language- "speakTo": "room", # what the room hears; "room" = the language they have been speaking- "speakVoices": {}, # Ming voice per language key ("en": "US_Emma")- "speakHeadphones": False, # 戴着耳机: skip the echo guard, talking over them is fine- # 打开麦克风 (the Mac's listenSource): "both" while the mic is on (people online and in the- # room, each heard on its own), else "system"; never kept for the next launch. roomMic: the- # room's microphone, "" = 自动.+ "speakFrom": "system",+ "speakTo": "room",+ "speakVoices": {},+ "speakHeadphones": False,"listenSource": "system","roomMic": "",- # 结束会议 (meeting_end.py), the Mac's keys: end when the meeting app hangs up; when nobody- # speaks, "prompt" (count down, then end), "end" or "off", after silenceMinutes."endWithApp": True,"silenceEnd": "prompt","silenceMinutes": 10,@@ -82,32 +60,24 @@ class AppSettings:@propertydef target_code(self) -> str:- """My language: the translate-to choice, or under "follow system" the Mac's myLanguage."""return my_language(system_languages()) if self.target == "system" else self.targetdef resolved_target(self, source: str | None) -> str:- """What lines in `source` translate into: under "follow system", the next system language when- they speak mine (the Mac's resolvedTarget)."""return follow_system_target(source, system_languages()) if self.target == "system" else self.targetdef ai_config(self):- """The AI service in use, its address and models (what LingClient calls with)."""from .providers import config_fromreturn 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)."""return meeting if (choice or self.notesLanguage) == "source" and meeting else self.target_code@propertydef google_off(self) -> bool:- """语音和文字只发给你的服务 in effect: on, and the custom service in use."""return self.aiProvider == "custom" and self.aiCustomOnly@propertydef hears_room(self) -> bool:- """The room microphone is open: 会议室 or 电脑和会议室."""return self.listenSource != "system"@property@@ -137,10 +107,8 @@ class AppSettings:o = jsonfmt.parse_object(f.read())if o is not None:kw = {k: o[k] for k, d in AppSettings.FIELDS.items() if k in o and type(o[k]) is type(d)}- # 纪要语言 was "system" or a language code before it took the Mac's two choices.if kw.get("notesLanguage") not in (None, "mine", "source"):kw["notesLanguage"] = "mine"- # Every launch starts with the microphone off.kw.pop("listenSource", None)return AppSettings(**kw)except OSError as e:diff --git a/linux/cicada/core/share.py b/linux/cicada/core/share.pyindex 166e2a8..48d8fe4 100644--- a/linux/cicada/core/share.py+++ b/linux/cicada/core/share.py@@ -1,16 +1,3 @@-"""A meeting shared as a link on cicada.indaloop.app: the Mac's ShareProjection.swift and-ShareClient.swift. Three parts:--- `doc`: the share document (v1), made from a record. Only whitelisted fields leave the computer:- never the record's file paths, Ling's guesses at names with the lines they came from, or its own- bookkeeping. Speakers are 说话人 N unless the user chose to show names. Same bytes as the Mac- (Tests/fixtures/share); the server (server/src/doc.js) reads exactly these fields.-- `ShareStore`: what this computer keeps about each link (Shares/<record id>.json, 0600 in a 0700- folder): the manage token and password live only there, never in the record, exports or logs.-- `ShareClient`: no accounts. This computer is an Ed25519 key made on first use (share-device.json,- 0600), registered once with a small proof of work; every write is signed (method, path, time,- nonce, body hash), as server/src/auth.js checks. Not an AI call, so not LingClient: the review- runs on the server."""from __future__ import annotationsimport base64@@ -32,11 +19,8 @@ BASE = "https://cicada.indaloop.app"ITERATIONS = 210_000DAYS = (7, 30, 365)-# The document-def _round(t: float) -> float:- """One decimal, half away from zero (Swift's .rounded(), not Python's banker's round)."""x = t * 10r = math.floor(abs(x) + 0.5)return math.copysign(r, x) / 10@@ -47,7 +31,6 @@ def _base(code: str) -> str:def languages(lines) -> list:- """The meeting's usual direction ("en" → "zh"), by the most lines; ties go to the earliest."""count, first = {}, {}for i, l in enumerate(lines):if l.dst is None:@@ -62,14 +45,12 @@ def languages(lines) -> list:def kept_lines(s, scope: str, removed=()) -> list:- """The record's line indices that go out, in order: what the server's line numbers count."""if scope != "full":return []return [i for i, l in enumerate(s.lines) if i not in removed and l.src]def doc(s, scope: str, names: bool, removed=frozenset(), drop_notes: bool = False) -> dict:- """`removed`: indices into the record's lines the user took out; `drop_notes` leaves the notes out."""from .session_store import display_titlenums = speakers.numbers(s.lines)name_map = speakers.names(s) if names else {}@@ -120,7 +101,6 @@ def _round_whole(x: float) -> float:def _plain(v):- """Whole doubles as integers (605, not 605.0), as Swift's encoder writes them."""if isinstance(v, float) and v == int(v) and abs(v) < 1e15:return int(v)if isinstance(v, dict):@@ -131,16 +111,11 @@ def _plain(v):def encode(d: dict) -> bytes:- """Compact, sorted keys, slashes and non-ASCII as they are: the Mac's [.sortedKeys, .withoutEscapingSlashes]."""return json.dumps(_plain(d), sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")-# Review hits-def record_lines(hits: list, kept: list) -> set:- """The record's line indices behind the review's hits ({part, from, to, questions}), given which- record lines were sent (`kept`)."""out = set()for h in hits:if h.get("part") != "lines":@@ -163,7 +138,6 @@ def category(q: str) -> str:def message(code: str) -> str:- """What a failed share says, by the server's code (ShareSheet.message)."""if code in ("rate_limited", "too_many_shares"):return L("分享得太频繁了,请稍后再试。")return L({"review_unavailable": "敏感内容检查暂时不可用,没有检查就不会分享。请稍后再试。",@@ -173,24 +147,18 @@ def message(code: str) -> str:def summary(password: bool, days: int, names: bool) -> str:- """The settings already chosen, in one line (无密码 · 7 天有效 · 不显示名字); 更改 opens them."""return " · ".join((L("密码保护") if password else L("无密码"),L("1 年有效") if days == 365 else LF("%lld 天有效", days),L("显示名字") if names else L("不显示名字")))def clipboard_text(r: "ShareRecord", title: str, now: float | None = None) -> str:- """What 复制 puts on the clipboard, in the UI's language (ShareSheet.clipboardText): the title,- the link on a line of its own (chat apps then make it a link), the password and how long it- stays open."""left = r.days_left(now)valid = L("1 年内有效") if left >= 365 else LF("%lld 天内有效", left)last = LF("密码:%@(%@)", r.password, valid) if r.password else validreturn "\n".join((LF("「%@」会议记录", title), r.url, last))-# Passwords-_WORDS = ("amber apple arrow aspen basil beach birch bloom brook cedar cherry cloud coral comet dawn delta dune ember fern ""field flint frost grove harbor hazel honey iris island jade lake lark lemon lily linen maple meadow mint moss ""olive orbit pearl pine plum pond quartz rain reed river ruby sage sand shell silk sky slate snow spruce stone "@@ -198,13 +166,10 @@ _WORDS = ("amber apple arrow aspen basil beach birch bloom brook cedar cherry cldef verifier(password: str, salt: bytes, iterations: int = ITERATIONS) -> bytes:- """PBKDF2-SHA256, 32 bytes: what the browser derives from the password (site/share.js). The- server keeps only its hash, so the password itself never leaves either side."""return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations, 32)def make_password() -> str:- """"ruby-41-lake": easy to read out and type; the server limits how many can be tried."""return "%s-%d-%s" % (secrets.choice(_WORDS), 10 + secrets.randbelow(90), secrets.choice(_WORDS))@@ -216,11 +181,8 @@ def unb64(s: str) -> bytes:return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))-# Local storage-def write_secret(path: str, data: bytes) -> bool:- """A file only this user can read, created 0600 from the start in a 0700 folder."""try:os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)@@ -234,8 +196,6 @@ def write_secret(path: str, data: bytes) -> bool:class ShareRecord:- """A link this computer made: `expiresAt` and `createdAt` are Unix seconds."""-def __init__(self, id: str, url: str, token: str, expiresAt: float, scope: str, password: str | None, createdAt: float):self.id, self.url, self.token, self.expiresAt = id, url, token, expiresAtself.scope, self.password, self.createdAt = scope, password, createdAt@@ -258,7 +218,6 @@ class ShareRecord:return Nonedef days_left(self, now: float | None = None) -> int:- # The server sets the expiry by its own clock: an hour's slack keeps a fresh 7-day link at 7.return max(1, math.ceil((self.expiresAt - (time.time() if now is None else now) - 3600) / 86400))@@ -268,8 +227,6 @@ def _utc(t: float):class ShareStore:- """Shares/<record id>.json, 0600 in a 0700 folder, beside the records' folder."""-@staticmethoddef folder() -> str:return os.path.join(Paths.data(), "Shares")@@ -313,12 +270,8 @@ class ShareStore:return out-# The client-def proof_of_work(pub: bytes) -> bytes:- """20 leading zero bits of sha256(public key ‖ 8-byte big-endian nonce): about a million- hashes, a few seconds in Python. Run it off the main loop."""head = hashlib.sha256(pub)n = 0while True:@@ -338,8 +291,6 @@ class Failure(Exception):class Outcome:- """"shared" (record), "blocked" (hits, kept: the record lines sent) or "failed" (code)."""-def __init__(self, kind: str, record: ShareRecord | None = None, hits=None, kept=None, code: str | None = None,retry_after: int | None = None):self.kind, self.record, self.hits, self.kept, self.code, self.retry_after = kind, record, hits or [], kept or [], code, retry_after@@ -354,7 +305,6 @@ def _version() -> str:def http(method: str, url: str, body: bytes | None, headers: dict, timeout: float = 90) -> tuple:- """(status, body bytes) through this computer's proxy; a refused status is an answer, not an error."""req = urllib.request.Request(url, data=body, method=method, headers=headers)try:with proxy.urlopen(req, timeout=timeout) as r:@@ -384,9 +334,6 @@ class Options:class ShareClient:- """Blocking calls: run them on a worker thread. `transport(method, url, body, headers)` →- (status, bytes); tests pass a fake. CICADA_SHARE_SERVER points a dev build at a local Worker."""-def __init__(self, transport=http, base: str | None = None, platform: str = "linux", version: str | None = None):self.transport = transportself.base = (base or os.environ.get("CICADA_SHARE_SERVER") or BASE).rstrip("/")@@ -415,7 +362,6 @@ class ShareClient:write_secret(self.device_file(), json.dumps(o, sort_keys=True).encode())def device(self, force: bool = False) -> tuple:- """(private key seed, device id), registering this computer with the server first if needed."""seed, o = self._load()if not force and o.get("device") and o.get("server") == self.base:return seed, o["device"]@@ -450,7 +396,6 @@ class ShareClient:return self.transport(method, self.base + path, body, h)def signed(self, method: str, path: str, body: bytes | None = None, headers: dict | None = None) -> tuple:- """A signed call; registers again once if the server no longer knows this computer."""signer = self.device()status, data = self._send(method, path, body, headers or {}, signer)if status == 401 and _code(data) == "unknown_device":@@ -467,8 +412,6 @@ class ShareClient:v = verifier(o.password, salt)body["password"] = {"salt": b64url(salt), "iter": ITERATIONS, "hash": b64url(hashlib.sha256(v).digest())}data = json.dumps(_plain(body), ensure_ascii=False, separators=(",", ":")).encode("utf-8")- # The same meeting, content and settings sent again (the answer was lost) gets the same link- # back; any other setting makes a new share.settings = "%s|%d|%s|%s|%s" % (o.scope, o.days, _b(o.names), o.password or "", _b(o.summary_in_preview))idem = s.id + "-" + hashlib.sha256(encode(d) + settings.encode("utf-8")).digest()[:8].hex()try:@@ -503,12 +446,10 @@ class ShareClient:retry_after=obj.get("retryAfter") if isinstance(obj.get("retryAfter"), int) else None)def revoke(self, r: ShareRecord, sid: str | None) -> bool:- """Turns the link off on the server and forgets it here. `sid` None: the record is being replaced."""try:status, data = self.signed("DELETE", "/api/v1/shares/" + r.id, None, {"Authorization": "Bearer " + r.token})except Failure:return False- # 404: already gone (or never ours); either way nothing to keep.ok = status in (204, 404)if not ok:Log.d("share: revoke failed %d %s" % (status, _code(data) or "?"))@@ -517,7 +458,6 @@ class ShareClient:return okdef stats(self, ids: list) -> dict:- """id → {id, expiresAt, state, views} for this computer's links among `ids`."""if not ids:return {}try:diff --git a/linux/cicada/core/speak.py b/linux/cicada/core/speak.pyindex 9291715..6f75898 100644--- a/linux/cicada/core/speak.py+++ b/linux/cicada/core/speak.py@@ -1,17 +1,3 @@-"""同声传译 (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 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).--Without headphones my microphone also hears the other side through the speakers. The app reads it-through the sound server's echo canceller when it can (app/room.py), which takes their voices out, so-what I say over them goes out. From the plain microphone, a sentence heard while the system audio was-loud for most of it is dropped instead, so the room doesn't get its own words back. UI-free like-ListenEngine: on_change is called on worker threads."""from __future__ import annotationsimport queue@@ -35,9 +21,6 @@ _END = object()class LoudnessLog:- """When the system audio was loud: (monotonic time, loud) per buffer, the last minute. Fed by- listening, read by the echo check."""-def __init__(self):self._items: deque = deque(maxlen=600)self._lock = threading.Lock()@@ -52,14 +35,10 @@ class LoudnessLog:return sum(span) / len(span) if span else 0.0-ECHO = 0.5 # from the plain mic, drop a sentence if the system audio was loud for more than half of it+ECHO = 0.5def echo_dropped(listening: bool, headphones: bool, loud: float, echo_cancelled: bool) -> bool:- """Whether a sentence may be the other side's voice from the speakers, not mine. Only from the- plain microphone (the Mac's rule): through the echo canceller their voices are taken out, and- dropping what I say over them is what the canceller is there to stop. Unknown (not listening, so- nothing measured the system audio) or 戴着耳机: kept."""return listening and not headphones and not echo_cancelled and loud > ECHO@@ -72,23 +51,23 @@ class SpeakEngine:self.settings = settingsself.store = storeself.listen = listen- self.player = player # make() -> object with write(pcm bytes), drain(), close(); 24 kHz mono s16+ self.player = playerself.loudness = LoudnessLog()self._listeners = []self._source = Noneself._audio = Noneself._work: queue.Queue = queue.Queue()- self._gen = 0 # bumped by cancel(): sentences queued before it are never spoken+ self._gen = 0self._pool = ThreadPoolExecutor(max_workers=3, thread_name_prefix="Interpret")self._worker = Noneself._feeder = Noneself.active = False- self.stage = "idle" # idle, hearing, interpreting, speaking- self.last = None # (original, translation) of the last sentence spoken- self.problem = None # the last thing worth saying (a sentence not spoken, a missing voice)+ self.stage = "idle"+ self.last = None+ self.problem = Noneself.level = 0.0self.spoken = 0- self.echo_cancelled = False # this press reads the echo-cancelled microphone+ self.echo_cancelled = Falseself._me = 0def on_change(self, listener) -> None:@@ -98,15 +77,12 @@ class SpeakEngine:for l in list(self._listeners):l()- # Languages-@propertydef source(self) -> str:return self.settings.speak_from_code@propertydef target(self) -> str:- """What the room hears: "room" follows the language they have been speaking."""to = self.settings.speakToif to != "room":return to@@ -116,14 +92,10 @@ class SpeakEngine:return "en" if voicemod.key(self.source) != "en" else "zh-CN"def voice(self, code: str) -> str | None:- """The voice id for a language: a Ming voice (or the service's), or voicemod.CLONE."""choice = (self.settings.speakVoices or {}).get(voicemod.key(code))return voicemod.chosen(choice, code, self.ling.config(), voice_reference.exists())def speech(self, text: str, code: str, voice: str | None = None):- """The voice for `text` in `code`'s language, as 24 kHz PCM chunks (a generator). The user's- own voice that fails before its first sound (Ming refused the clip, or took too long) says- the sentence in the language's default voice instead, as the Mac falls back to its own."""config = self.ling.config()voice = voice or self.voice(code)language = voicemod.ming_language(code, config)@@ -144,25 +116,20 @@ class SpeakEngine:Log.d("speak: own voice failed %s, the default voice instead" % e)yield from self.ling.speech(text, voice=voicemod.default_voice(code, config), language=language)- # Running-def start(self, mic, echo_cancelled: bool = False, why: str = "") -> None:- """`echo_cancelled`: `mic` is the echo canceller's source (the meeting's voices taken out), so- nothing said over them is dropped; `why` says why not, for the log."""if self.active:returnself.echo_cancelled = echo_cancelledself.active = Trueself.stage = "hearing"self.problem = None- self.last = None # the strip starts empty, not on a sentence from an earlier time+ self.last = Nonesegmenter = Segmenter()gen = self._genaudio: queue.Queue = queue.Queue()self._audio = audiodef emitted(seg):- # Interpreted at once, while the sentence before may still be playing; spoken in order.ended = time.monotonic()self._work.put((gen, seg, self._pool.submit(self._interpret, seg, ended - seg.seconds, ended, echo_cancelled)))segmenter.on_segment = emitted@@ -200,8 +167,6 @@ class SpeakEngine:self._changed()def cancel(self) -> None:- """同声传译 off or 退出: stop, and nothing still waiting is said (知了 麦克风 is going away).- A plain stop() still says what I finished before pressing it, as releasing the key does on the Mac."""self._gen += 1self.stop()@@ -213,14 +178,13 @@ class SpeakEngine:Log.d("speak: segment %d dropped, cancelled before it was said" % seg.index)continueself._say(seg, job.result(), gen)- except Exception as e: # noqa: BLE001 - one bad sentence never stops the next+ except Exception as e: # noqa: BLE001Log.d("speak: sentence failed %s" % type(e).__name__)finally:self.stage = "hearing" if self.active else "idle"self._changed()def _interpret(self, seg, start: float, end: float, echo_cancelled: bool = False):- """(original, translation, source, target, ended, voice chunks) or None, on the pool."""listening = self.listen is not None and self.listen.listeningloud = self.loudness.fraction(start, end) if listening else 0.0if listening:@@ -228,7 +192,6 @@ class SpeakEngine:seg.index, seg.seconds, round(loud * 100), "echo cancelled" if echo_cancelled else "plain mic"))if echo_dropped(listening, self.settings.speakHeadphones, loud, echo_cancelled):Log.d("speak: segment %d dropped, the system audio was playing (echo)" % seg.index)- # Said, so the user knows: talking over them (or no headphones) is why it didn't go out.self.problem = strings.L("对方在说话时说的,没有说出去")self._changed()return None@@ -244,17 +207,13 @@ class SpeakEngine:Log.d("speak: interpret failed %s" % e)heard = Noneif heard is None:- # Never the original, never a guess.self.problem = strings.L("这句没翻译成 · 没有说出去")Log.d("speak: segment %d %.1fs not interpreted, not spoken" % (seg.index, seg.seconds))return Noneoriginal, translation = heardif filler(original):- # The room's hush or an echo's tail cut as a segment: Ming hears 嗯, the room would hear "Hmm."Log.d("speak: segment %d only a filler, not spoken" % seg.index)return None- # The voice starts now, on its own thread: ready the moment the sentence before stops playing,- # instead of each sentence waiting out Ming's first chunk after the last one's playback.return original, translation, source, target, end, self._fetch(translation, target)def _fetch(self, text: str, target: str) -> queue.Queue:@@ -289,11 +248,11 @@ class SpeakEngine:while True:pcm = chunks.get(timeout=30)if pcm is _END or gen != self._gen:- break # finished, or stopped mid-sentence+ breakif isinstance(pcm, LingError):raise pcmif lag is None:- lag = time.monotonic() - ended # what the room waits: end of my sentence → its voice+ lag = time.monotonic() - endedif out is not None:out.write(pcm)n += 1@@ -310,11 +269,9 @@ class SpeakEngine:self.spoken += 1Log.d("speak: segment %d %.1fs -> %s, voice %.1f s, lag %.2f s after the sentence, %d chunks"% (seg.index, seg.seconds, target, played / 2 / TTS_RATE, lag or 0, n))- # Stamped when I started the sentence, not when its voice finished (the Mac's secondsAgo).self._record(original, translation, source, target, time.monotonic() - (ended - seg.seconds))def _record(self, original, translation, source, target, ago: float = 0.0) -> None:- """My sentence in the meeting's record, as the Mac writes it (speaker "me", ids m<n>)."""if self.store is None or self.listen is None or not self.listen.listening or not self.listen.session_id:returnsid = self.listen.session_id@@ -331,8 +288,6 @@ FILLERS = {"嗯", "啊", "呃", "哦", "唔", "额", "噢", "哎", "um", "uh", "def filler(text: str) -> bool:- """Nothing but fillers (嗯, 啊, um, hmm…), whatever the punctuation (the Mac's PressSpeech.filler).- A heading with nothing after it ("翻译结果:", "Translation:") is the model's answer to noise, too."""trimmed = text.strip()if 0 < len(trimmed) <= 12 and trimmed[-1] in "::":return Truediff --git a/linux/cicada/core/speakers.py b/linux/cicada/core/speakers.pyindex ac6aa0b..4c01caa 100644--- a/linux/cicada/core/speakers.py+++ b/linux/cicada/core/speakers.py@@ -1,10 +1,3 @@-"""说话人识别: telling the other side's voices apart (SpeakerID.swift). Each heard line's audio becomes a-voiceprint (WeSpeaker ResNet34-LM, VoxCeleb, CC BY 4.0), voiceprints are grouped as they arrive, and a-voice is only named once it has a few lines. The thresholds are the Mac's (tuned on AMI meetings).--The model runs in native/voiceprint.c (libcicada-voice), loaded with ctypes: a stock Ubuntu desktop has no-BLAS and Python can't run a ResNet in real time. Without the library or the weights the feature is-unavailable and listening carries on as before."""from __future__ import annotationsimport copy@@ -18,10 +11,7 @@ from . import stringsfrom .support import Log, clock-# Voiceprints-def _root() -> str:- # linux/ in the source tree, cicada-linux/ in the installed one: the folder holding cicada/.return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))@@ -49,7 +39,7 @@ class Voiceprints:def __init__(self, lib, model):self._lib = libself._model = model- self._lock = threading.Lock() # one at a time: each already uses up to four cores+ self._lock = threading.Lock()@staticmethoddef load() -> "Voiceprints | None":@@ -73,7 +63,6 @@ class Voiceprints:return Voiceprints(lib, model)def embed(self, samples) -> list | None:- """A unit-length 256-d voiceprint of 16 kHz mono 16-bit samples (an array('h')), or None when too short."""n = len(samples)if n < self.MIN_SECONDS * 16000:return None@@ -84,12 +73,7 @@ class Voiceprints:return list(out) if ok else None-# Grouping-class VoiceClusterer:- """Groups voiceprints as lines arrive, never revising a line already labelled. A line joins the- closest voice when similar enough; a long line unlike every voice starts a new one; anything else- stays unlabelled ("对方"). Tuned on AMI dev meetings (VoiceClusterer, SpeakerID.swift)."""NEW_SECONDS = 2.0JOIN = 0.5START_NEW = 0.5@@ -98,11 +82,10 @@ class VoiceClusterer:self.sums: list = []def merge(self, frm: int, into: int) -> None:- """The user said two voices are one: later lines like either go to `into`."""if not (0 <= frm < len(self.sums) and 0 <= into < len(self.sums)) or frm == into:returnself.sums[into] = [a + b for a, b in zip(self.sums[into], self.sums[frm])]- self.sums[frm] = [0.0] * len(self.sums[frm]) # never the closest again+ self.sums[frm] = [0.0] * len(self.sums[frm])def label(self, v: list, seconds: float) -> int | None:best, best_sim = -1, -1.0@@ -122,8 +105,6 @@ class VoiceClusterer:class Tagger:- """Voiceprints on their own thread (while Ming hears the same segment), labelled in arrival order."""-def __init__(self):self._model = Noneself._tried = False@@ -143,7 +124,6 @@ class Tagger:return self._modeldef reset(self) -> None:- """A new meeting: forget the voices of the last one."""with self._gate:self.clusterer = VoiceClusterer()@@ -162,8 +142,6 @@ class Tagger:return self.clusterer.label(vector, seconds)-# What the transcript shows (SpeakerLabels)-SHOWN_AFTER = 5@@ -174,17 +152,12 @@ def _cjk(c: str) -> bool:def substantive(text: str) -> bool:- """A line long enough to say whose voice it is: three words, or four characters of Chinese,- Japanese or Korean. "Yeah." or a stray "." don't count towards a name."""if sum(1 for w in text.split() if any(c.isalpha() for c in w)) >= 3:return Truereturn sum(1 for c in text if _cjk(c)) >= 4def voice_numbers(lines) -> dict:- """Voice id → 1-based speaker number for the voices on show: a voice gets one once it has- SHOWN_AFTER substantive lines, and only when two voices have, so a one-to-one call stays 对方.- Numbers follow the order voices got there, so a number never moves once shown."""count, reached = {}, {}for i, l in enumerate(lines):if l.speaker != "them" or l.voice is None or not substantive(l.src):@@ -199,13 +172,11 @@ def voice_numbers(lines) -> dict:def numbers(lines) -> dict:- """Line id → speaker number; lines without one show as 对方."""number = voice_numbers(lines)return {l.id: number[l.voice] for l in lines if l.speaker == "them" and l.voice in number}def names(s) -> dict:- """Speaker number → name: the user's, else Ling's guess (unless the user turned it down)."""if s.voiceNames is None and s.voiceGuesses is None:return {}out = {}@@ -220,7 +191,6 @@ def names(s) -> dict:def guessed(s) -> dict:- """Speaker number → Ling's guess, for the voices whose shown name is that guess."""out = {}for v, n in voice_numbers(s.lines).items():if (s.voiceNames or {}).get(str(v)) is None and (s.voiceGuesses or {}).get(str(v)) is not None:@@ -229,7 +199,6 @@ def guessed(s) -> dict:def run_starts(lines, nums: dict) -> set:- """Lines where the speaker changes: the transcript names the speaker there only, as chat apps do."""out, last = set(), Nonefor l in lines:key = "me" if l.speaker == "me" else ("n%d" % nums[l.id] if l.id in nums else "?")@@ -240,19 +209,14 @@ def run_starts(lines, nums: dict) -> set:def label(number: int, shown: dict) -> str:- """"George", else "说话人 2"."""return shown.get(number) or strings.LF("说话人 %lld", number)def says_who(s, nums: dict) -> bool:- """Whether lines say who spoke. An imported file has no "other side" to call 对方: its lines are- named only once its voices are told apart (TranscriptExport.named)."""return s.sourceFile is None or bool(nums)def speaker_name(line, nums: dict, shown: dict) -> str:- """你 · 同传 (said through 同声传译), a speaker, 对方 (no voices told apart) or 未识别 (a voice not on- show) (TranscriptExport.speakerName)."""if line.speaker == "me":return strings.L("你 · 同传")if line.id in nums:@@ -261,14 +225,13 @@ def speaker_name(line, nums: dict, shown: dict) -> str:def named(notes, shown: dict):- """The notes as shown: Ling wrote "说话人 6" before anyone named them; show the name since given."""if not shown or notes is None:return notesdef swap(text):if text is None or ("说话人" not in text and "Speaker" not in text):return text- for n, name in sorted(shown.items(), key=lambda kv: -kv[0]): # 说话人 12 before 说话人 1+ for n, name in sorted(shown.items(), key=lambda kv: -kv[0]):for form in ("说话人 %d" % n, "说话人%d" % n, "Speaker %d" % n):text = text.replace(form, name)return text@@ -288,8 +251,6 @@ def shown_count(lines) -> int:return len(set(numbers(lines).values()))-# People the notes mention (NoteTerm.people)-ROLES = ["首席", "执行官", "主席", "总裁", "董事", "经理", "创始人", "记者", "主持", "研究员", "分析师", "教授", "老师","教师", "官员", "部长", "议员", "候选人", "嘉宾", "发言人", "CEO", "CFO", "CTO", "host", "analyst", "reporter", "founder"]@@ -299,8 +260,6 @@ def people(terms) -> list:def suggestions(s, voice: int) -> list:- """For renaming a voice: its current name, Ling's guess, then people the notes mention, without- names other voices already have; at most four (SpeakerEditor.suggestions)."""nums = voice_numbers(s.lines)number = nums.get(voice)shown = names(s)@@ -318,8 +277,6 @@ def suggestions(s, voice: int) -> list:return out[:4]-# Names from the conversation (SpeakerNameGuess), Ling's prompt word for word-INSTRUCTION = ("Who are the people labelled 说话人N? Name one only when the transcript makes it clear: they ""introduce themselves on a line labelled with their own 说话人N; someone addresses them by name just "@@ -332,11 +289,10 @@ INSTRUCTION = ("you are unsure of. Reply as JSON: {\"speakers\": [{\"speaker\": 2, \"name\": \"George\", \"evidence\": \"L12\"}]}, ""the evidence being the line with the name; an empty list if none. Check each name's spelling before replying.")-EVIDENCE_REACH = 2 # "Okay, Amos, thank you" comes right after Amos's last words+EVIDENCE_REACH = 2def content(s) -> str | None:- """The transcript as Ling sees it, newest 400 lines, with speaker labels; None when no voices are shown."""nums = numbers(s.lines)if not nums:return None@@ -349,10 +305,7 @@ def content(s) -> str | None:def read(reply: str, s):- """(found: voice → VoiceGuess, refuted: voice → name). A name given on a line the voice neither said- nor spoke next to is refuted; a name Ling gives two voices goes to the one with more lines."""from .models import VoiceGuess- # Without JSON mode (a host that refuses it) the object may come in a fence or a sentence.a, z = reply.find("{"), reply.rfind("}")try:obj = json.loads(reply[a:z + 1]) if 0 <= a < z else None@@ -402,7 +355,6 @@ def read(reply: str, s):def holds(g, v: int, s) -> bool:- """Whether a stored guess still stands: its evidence line is found again and the voice speaks there."""if "“" not in g.evidence:return Trueat, quote = g.evidence.split("“", 1)@@ -417,9 +369,6 @@ def holds(g, v: int, s) -> bool:class Namer:- """Asks Ling for names on its own: once two voices are on show, again every 20 lines, and once more- when the meeting ends. Guesses go straight into the meeting (voiceGuesses); the user corrects."""-def __init__(self, ling, store, changed=None):self.ling = lingself.store = store@@ -441,7 +390,7 @@ class Namer:returnnums = voice_numbers(s.lines)if all((s.voiceNames or {}).get(str(v)) is not None for v in nums):- return # everyone already has a name the user gave+ returnself.busy.add(sid)self._asked[sid] = len(s.lines)diff --git a/linux/cicada/core/strings.py b/linux/cicada/core/strings.pyindex 9f2061a..fb21d93 100644--- a/linux/cicada/core/strings.py+++ b/linux/cicada/core/strings.py@@ -1,8 +1,3 @@-"""UI text. The Chinese text is the key, as on the Mac, and the translations are the Mac's own-`Resources/{en,ja,ko}.lproj/Localizable.strings`, plus `Linux.strings` (linux/strings/<lang>.lproj)-for text only the Linux app has, and the Mac's `Localizable.stringsdict` for plurals ("1 line",-"2 lines"). Placeholders are the Mac's `%@`, filled in order (or `%1$@`). Never for prompts, logs or-stored values."""from __future__ import annotationsimport os@@ -14,8 +9,6 @@ language = "zh-Hans"def load(ui: str, folders: list) -> None:- """Loads the table for `ui` ("en", "ja", "ko"; anything else is Chinese) from each folder's- <lang>.lproj/{Localizable,Linux}.strings, later folders over earlier ones."""global _table, _plurals, languagehead = ui.replace("_", "-").split("-")[0]language = head if head in ("en", "ja", "ko") else "zh-Hans"@@ -36,14 +29,11 @@ def load(ui: str, folders: list) -> None:def parse_plurals(data: bytes) -> dict:- """The Mac's Localizable.stringsdict: key → {"NSStringLocalizedFormatKey": format, variable →- {"one": …, "other": …}}."""d = plistlib.loads(data)return {k: v for k, v in d.items() if isinstance(v, dict) and isinstance(v.get("NSStringLocalizedFormatKey"), str)}def _category(n) -> str:- # Only English has more than one form among the app's languages: "one" for exactly 1.return "one" if language == "en" and isinstance(n, (int, float)) and n == 1 else "other"@@ -53,8 +43,6 @@ def L(key: str) -> str:def LF(key: str, *args) -> str:- """L() with the Mac's `%@` placeholders, filled in order. A key in the stringsdict takes its- plural form for the number: `%#@n@` (or `%2$#@n@`) becomes variable n's "one" or "other" text."""plural = _plurals.get(key)text = plural["NSStringLocalizedFormatKey"] if plural else L(key)out = []@@ -75,8 +63,7 @@ def LF(key: str, *args) -> str:out.append(form.replace("%lld", str(n)).replace("%ld", str(n)).replace("%d", str(n)))i = end + 1continue- # %@, and the Mac's numbers (%lld, %d) the same way: the Mac keys 说话人 N as "说话人 %lld".- if text.startswith("%%", i): # a literal %, as in the Mac's "%lld%%"+ if text.startswith("%%", i):out.append("%")i += 2continue@@ -99,7 +86,6 @@ def LF(key: str, *args) -> str:def parse(text: str) -> dict:- """`"key" = "value";` lines, with /* */ and // comments and \\" \\\\ \\n escapes."""result = {}i = 0n = len(text)diff --git a/linux/cicada/core/support.py b/linux/cicada/core/support.pyindex 4f32461..a484211 100644--- a/linux/cicada/core/support.py+++ b/linux/cicada/core/support.py@@ -1,4 +1,3 @@-"""Paths, the debug log and languages."""from __future__ import annotationsimport os@@ -9,9 +8,6 @@ from datetime import datetimeclass Paths:- """Where the app keeps its files, by the XDG rules: records in ~/.local/share/cicada, settings- and the Ling key in ~/.config/cicada. Dev builds use "cicada-dev" so they never touch real- records. Tests and the CLI point everything at one folder with CICADA_HOME."""dev = os.environ.get("CICADA_DEV") == "1"home_override: str | None = None@@ -49,14 +45,12 @@ class Paths:@classmethoddef 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@classmethoddef log(cls) -> str:- """~/.local/state/cicada/debug.log (XDG state, private to the user), not a shared /tmp file."""if cls.log_override:return cls.log_overrideh = cls._home()@@ -72,7 +66,6 @@ class Paths:class Log:- """The debug log: timings and states, never meeting text or the key."""_gate = threading.Lock()echo = False@@ -89,7 +82,6 @@ class Log:print(line, file=sys.stderr)-# The languages the Mac app offers (Languages.swift), as translation codes.SOURCES = [("English", "en"), ("日本語", "ja"), ("中文", "zh-CN"), ("한국어", "ko"),("Español", "es"), ("Français", "fr"), ("Deutsch", "de"), ("Português", "pt")]TARGETS = [("简体中文", "zh-CN"), ("繁體中文", "zh-TW"), ("English", "en"), ("日本語", "ja"),@@ -104,12 +96,10 @@ _ENGLISH = {"zh-CN": "Simplified Chinese", "zh-TW": "Traditional Chinese", "zh":def english_name(code: str) -> str:- """"Simplified Chinese", "Japanese": the names prompts use."""return _ENGLISH.get(code) or _ENGLISH.get(code.split("-")[0].lower()) or codedef from_system(tag: str) -> str:- """A system UI language ("zh_CN.UTF-8", "zh-Hant-HK", "en_US") as a translation code."""parts = tag.split(".")[0].split("@")[0].replace("_", "-").split("-")if parts[0] != "zh":return parts[0] or "en"@@ -117,8 +107,6 @@ def from_system(tag: str) -> str:def system_languages() -> list:- """The desktop's languages, most preferred first: LANGUAGE is a list ("en_US:zh_CN"), the- locale variables add one each. What the Mac reads as Locale.preferredLanguages."""out = []for var in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"):for v in (os.environ.get(var) or "").split(":"):@@ -128,15 +116,10 @@ def system_languages() -> list:def my_language(prefs: list) -> str:- """The reader's own language under "follow system" (the Mac's myLanguage): Chinese when the- system list has it, otherwise the first system language."""return from_system(next((p for p in prefs if p.startswith("zh")), prefs[0] if prefs else "zh_CN"))def follow_system_target(source: str | None, prefs: list) -> str:- """What "follow system" translates into (the Mac's followSystemTarget): my language, unless that- is what they speak; then the next system language, or between Chinese and English when the- system has only one."""mine = my_language(prefs)if source is None or source != mine:return mine@@ -144,7 +127,6 @@ def follow_system_target(source: str | None, prefs: list) -> str:def system_language() -> str:- """The desktop's language, as POSIX locale variables give it."""for var in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"):v = os.environ.get(var)if v and v not in ("C", "POSIX", "C.UTF-8"):@@ -153,7 +135,6 @@ def system_language() -> str:def normalize(reported: str | None, fallback: str) -> str:- """Normalizes what Ming says the language is ("zh", "zh-Hans", "cmn") to a source code."""if not reported or not reported.strip():return fallbackr = reported.strip().strip('.`"')@@ -183,8 +164,6 @@ def is_cjk_language(code: str) -> bool:def in_script(text: str, target: str) -> bool:- """Whether text is in the target's script: Chinese, Japanese and Korean targets need some CJK,- others must not be mostly CJK (TranslationService.cleanTranslation's check)."""letters, cjk = _count(text)if letters == 0:return True@@ -192,7 +171,6 @@ def in_script(text: str, target: str) -> bool:def written_in(text: str, english_language: str) -> bool:- """Notes' check: CJK languages need a fair share (names and numbers stay Latin)."""letters, cjk = _count(text)if letters == 0:return Truediff --git a/linux/cicada/core/transcript_search.py b/linux/cicada/core/transcript_search.pyindex 697a66e..73be1aa 100644--- a/linux/cicada/core/transcript_search.py+++ b/linux/cicada/core/transcript_search.py@@ -1,11 +1,7 @@-"""Searching a meeting's lines, shared by the notes window and the records window, so a search finds-the same lines (misheard names included) and marks them the same way in both (the Mac's-TranscriptSearch.swift)."""from __future__ import annotationsdef terms(query: str, notes: list = ()) -> list:- """The query, plus every way the notes say that name was heard (江充 also finds 江松)."""q = query.strip()if not q:return []@@ -25,20 +21,16 @@ def line_matches(line, terms_: list) -> bool:def matches(lines: list, terms_: list) -> list:- """The ids of the lines a search finds, in order."""if not terms_:return []return [l.id for l in lines if line_matches(l, terms_)]def spans(text: str, terms_: list) -> list:- """Where each term is in `text` (case-insensitive), as merged (start, end) pairs: every occurrence- gets marked."""low = text.lower()found = []for t in terms_:t = t.lower()- # lower() can change a string's length (İ): then its offsets don't fit `text`, so leave it unmarked.if not t or len(low) != len(text):continuei = low.find(t)diff --git a/linux/cicada/core/translator.py b/linux/cicada/core/translator.pyindex 7795aad..dfe004c 100644--- a/linux/cicada/core/translator.py+++ b/linux/cicada/core/translator.py@@ -1,6 +1,3 @@-"""Translation and recognition through the cloud (the Windows design): listening sends each stretch-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 annotationsimport re@@ -16,7 +13,6 @@ from .support import Log, english_name, in_script, normalize@dataclassclass Heard:- """What Ming heard in one stretch of audio."""lang: stroriginal: strtranslation: str | None@@ -29,30 +25,18 @@ class Translator:self._google_backoff_until = 0.0self._last_unreachable_try = 0.0self._google_off = False- # The last finished sentence came back untranslated (TranslationHealth.sentencesUntranslated):- # with Google left out, the notes window says the translation waits for the user's service.self.sentences_untranslated = False- # Names and terms the notes have settled on, e.g. "江充 (…; misheard as 江松)".self.glossary = lambda: []- # 改正听错的词 (set by the app): `fix_context(text)` is what a finished sentence's request carries- # (None: fixing is off, the request is the plain translation), `on_fixes(text, edits)` gets the- # fixes proposed for a sentence by its text as heard.self.fix_context = lambda text: Noneself.on_fixes = Nonedef hear(self, wav: bytes, target: str, hint: str | None) -> Heard | None:- """One stretch of speech (16 kHz mono WAV) heard and interpreted. `hint` is the language the- meeting has been in, which keeps Ming from flipping on a short or accented stretch. None when- there was no speech or the reply wasn't in the three-line form; never a guess."""- # 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.0reply = self.ling.chat(hear_prompt(target, hint, self.glossary()), hear_instruction(target), TRANSLATE,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):- """What I said (16 kHz mono WAV) and its translation, or None. Never a guess: an untranslated- sentence must not be spoken into the room."""if source == target or not self.ling.usable:return Nonereply = self.ling.chat(interpret_prompt(source, target, self.glossary()), interpret_instruction(source, target), SPEAK,@@ -62,11 +46,6 @@ class Translator:DRAFT, SENTENCE = "draft", "sentence"def _ling_worth_trying(self) -> bool:- """A text model that answers nothing costs every line its timeout before Google gets it- (Translator.swift › lingWorthTrying). That happens here when a custom service hears at an- address of its own that still answers. While the check says the text side is unreachable,- one line in 15 s still goes to it, so a server that is back is noticed without a check.- Lines translate on a pool: two in the same instant may both try, which is harmless."""f = self.ling.check_result.failureif f is None or f[1] != "unreachable" or f[0] == "hear":return True@@ -78,8 +57,6 @@ class Translator:@propertydef google_off(self) -> bool:- """语音和文字只发给你的服务 (custom service only, set by the app): Google is never asked, so the- text stays with the user's service. A stale backoff goes with it either way."""return self._google_off@google_off.setter@@ -91,10 +68,8 @@ class Translator:self.sentences_untranslated = Falsedef translate(self, text: str, source: str, target: str, kind: str) -> str | None:- """Ling (finished sentences only) → Google. None when both fail."""if source == target:return text- # Partial text only ever goes to Google: left out, it shows the original until the sentence ends.if kind == self.DRAFT and self._google_off:return Noneout = self._translate(text, source, target, kind)@@ -103,19 +78,12 @@ class Translator:return outdef fix(self, text: str, source: str, target: str) -> str | None:- """改正听错的词 for a line Ming already translated: the same request as a finished sentence's- (translation and fixes in one), never Google. The translation as fixed, or None (fixing off,- no AI service, or no usable reply), and then the line keeps Ming's."""if source == target or not self.ling.usable or not self._ling_worth_trying():return Nonectx = self.fix_context(text)return self._via_ling_fixing(text, source, target, ctx) if ctx is not None else Nonedef _via_ling_fixing(self, text: str, source: str, target: str, ctx) -> str | None:- """The translation and the misheard words in one request (Translator.swift › viaLingFixing). No- JSON mode: some hosts refuse it, and the retry without it would cost every line a second round- trip; the prompt asks for JSON instead. Proposals only: correction.decide picks which to take.- A reply that isn't the JSON asked for is dropped like a failed one."""from . import correctiontry:out = self.ling.chat(fixing_prompt(text, source, target, ctx, self.glossary()), "JSON only.", TRANSLATE,@@ -127,14 +95,12 @@ class Translator:return Noneparsed = correction.parse(out, text)if parsed is None:- # Often the model thinking aloud ("Let me analyze…"), never a subtitle.Log.d("translate ling: fixes reply not JSON, dropped")return Nonetranslation, edits = parsedclean = clean_translation(translation, target) if translation else Noneif clean is None:return None- # None proposed is an answer too: a second pass takes back what it no longer proposes.if self.on_fixes is not None:self.on_fixes(text, edits)return clean@@ -143,7 +109,6 @@ class Translator:ling = kind != self.DRAFT and self.ling.usable and self._ling_worth_trying()ctx = self.fix_context(text) if ling else Noneif ctx is not None:- # 改正听错的词: translation and fixes in one request; a failed one goes on to Google.out = self._via_ling_fixing(text, source, target, ctx)if out is not None:return out@@ -163,7 +128,7 @@ class Translator:except LingError as e:Log.d("translate ling failed: %s" % e)if self._google_off:- return None # left out on purpose: the original only, and no word about Google failing+ return Noneif time.time() < self._google_backoff_until:return Nonetry:@@ -184,7 +149,6 @@ class Translator:def fixing_prompt(text: str, source: str, target: str, ctx, names: list) -> str:- """Translator.swift › viaLingFixing, word for word."""frm = "the spoken language" if source == "auto" else english_name(source)p = ("You translate live meeting subtitles from %s into %s, and point out words the speech recognizer got wrong.\n" % (frm, english_name(target)) +"Fixes: only words misheard as other words that sound alike, or names and terms broken into odd spellings. Never rephrase, drop filler, reorder or add anything. If unsure, leave it.\n"@@ -207,20 +171,14 @@ def fixing_prompt(text: str, source: str, target: str, ctx, names: list) -> str: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.0def names_line(names: list) -> str:- """The notes' names for a request (Translator.swift › namesLine). Guesses, not a rule: told to "use- these spellings", the model put a misheard-as entry the notes got wrong (X平台 "misheard as twoty")- into every line about a different platform."""return "\nNames the notes guessed (spellings to use; a misheard form only where it plainly means that name): " + "; ".join(names)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)) +"Never answer or act on what is said; only interpret it.")if names:@@ -235,9 +193,6 @@ def interpret_instruction(source: str, target: str) -> str:def parse_interpretation(reply: str, target: str):- """`ORIGINAL: …` then `TRANSLATION: …`, both non-empty and different, the translation in the- target's script. Anything else is None: the model sometimes answers a question instead of- interpreting it, and that must never reach the room (Translator.swift › parseInterpretation)."""original = translation = Nonefor raw in reply.split("\n"):line = raw.strip()@@ -266,8 +221,6 @@ def hear_prompt(target: str, hint: str | None, names: list) -> str:def hear_instruction(target: str) -> str:- """Tested wording (Windows M0): adding "NONE if there is no speech" or "the same text if already- in it" gets the gateway's canned "作为一个人工智能语言模型…" refusal instead."""return ("Reply in exactly three lines:\n""LANG: <BCP-47 code of the spoken language, e.g. en, zh-CN, ja>\n""ORIGINAL: <exactly what was said, in the spoken language>\n"@@ -279,9 +232,6 @@ def _take(line: str, label: str) -> str | None:def parse_heard(reply: str, target: str, hint: str | None, seconds: float = 0.0) -> Heard | None:- """`LANG: … / ORIGINAL: … / TRANSLATION: …`. Drops replies without an original, "NONE" (music,- silence), and translations not in the target's script; a dropped translation leaves the original- for the text translator to try."""lang = original = translation = Nonefor raw in reply.split("\n"):line = raw.strip()@@ -316,13 +266,9 @@ def parse_heard(reply: str, target: str, hint: str | None, seconds: float = 0.0)def hear_tokens(seconds: float) -> int:- """Room for a reply to `seconds` of audio: a fast talker's original and translation fit; a reply- that runs on repeating itself ("滴答" ×800 from typing) stops early. 0: unknown."""return 800 if seconds <= 0 else min(800, int(60 + 40 * seconds))-# Ming describing the audio instead of transcribing it: "(无语音内容)", "[Music]", "这段音频是一段旋律,-# 没有说话声。". A bracketed note beside real words ("(笑)好的") keeps the words._ANNOTATION = re.compile(r"[((\[【][^))\]】]*[))\]】]|♪")_NO_SPEECH = ("没有说话", "无语音", "没有语音", "没有人声", "无人声", "没有人说话", "无人说话",@@ -339,15 +285,9 @@ _FILLERS = (def is_noise(original: str, seconds: float = 0.0) -> bool:- """Ming writes something for every stretch it is sent, speech or not (it can't be asked for NONE,- see hear_instruction): hold music, a ringback tone, a fan or typing came back as "嗯。", "嗯,嗯,嗯…"- or "滴答" ×800. That is noise: fillers only, one short sound six or more times over, or more than- anyone says in `seconds` (0: unknown). A short real answer ("对", "好的", "喂,能听到吗") stays.- Same rules and lists as the Android and Windows ports."""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 Truewords, word = [], ""@@ -361,7 +301,6 @@ def is_noise(original: str, seconds: float = 0.0) -> bool:words.append(word)if not words or all(_filler_word(w) for w in words):return True- # Each CJK character is a unit, as a word is elsewhere.units = [u for w in words for u in (list(w) if any(_cjk(c) for c in w) else [w])]n = len(units)for p in range(1, 5):@@ -374,7 +313,6 @@ _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 = ""for c in raw:if len(w) < 2 or w[-1] != c or w[-2] != c:@@ -397,7 +335,6 @@ _ABOUT = ("translat", "subtitle", "garbled", "transcri", "asr", "speech recognit_ZH_ABOUT = ("字幕", "翻译")_ZH_REMARK = ("请提供", "似乎", "看起来", "无法", "乱码", "没有附上", "您只发送")-# "Translate." in each target language, letters only and lowercased._INSTRUCTION_ECHOES = frozenset(("翻译", "翻譯", "translate", "翻訳", "翻訳して", "翻訳する", "翻訳してください", "번역", "번역해", "번역하세요", "번역해주세요","traducir", "traduce", "traduzca", "traduire", "traduisez", "traduis", "übersetzen", "übersetze", "traduzir", "traduza",@@ -405,9 +342,6 @@ _INSTRUCTION_ECHOES = frozenset((def clean_translation(reply: str, target: str) -> str | None:- """Ling sometimes comments on a garbled subtitle instead of translating it ("The subtitle appears- to be…"). Remark lines go, a "Translation:" label is stripped, and what is left must be in the- target's script; None lets the next provider try. Port of cleanTranslation."""answer = reply.split("</think>")[-1]kept = []for raw in answer.split("\n"):@@ -432,9 +366,6 @@ def clean_translation(reply: str, target: str) -> str | None:output = output.strip()if not output:return None- # Ling translated the fixed "Translate." instruction instead of the subtitle ("翻译。" for an empty- # subtitle, or for "Translate this into Chinese please."); the next provider translates it. Port of- # instructionEchoes.if "".join(c for c in output.lower() if c.isalpha()) in _INSTRUCTION_ECHOES:return Nonereturn output if in_script(output, target) else Nonediff --git a/linux/cicada/core/updates.py b/linux/cicada/core/updates.pyindex ada78de..fb8f173 100644--- a/linux/cicada/core/updates.py+++ b/linux/cicada/core/updates.py@@ -1,9 +1,3 @@-"""New versions (the Mac's UpdateChecker and Updater): GitHub Releases is read at launch and when a-check is due, the newest release that ships the Linux tarball is offered, and installing it-downloads the tarball, checks it against the release's checksums.txt, unpacks it and hands it to a-small script that runs its install.sh once the app has quit, then opens Cicada again.--UI-free and stdlib only: the app shows the state, this module finds, fetches and checks."""from __future__ import annotationsimport hashlib@@ -24,16 +18,10 @@ import urllib.requestfrom . import jsonfmt, proxyfrom .support import Log, Paths-# The list, not releases/latest: every platform shares one version, and a release that only ships-# the Mac or Windows has no Linux tarball, so the newest Linux release may be further down.FEED = "https://api.github.com/repos/wquguru/cicada/releases?per_page=20"-# How often a running app checks, and how old a check must be before a manual-ish one (the tray-# menu, waking) checks again. GitHub allows 60 anonymous API calls an hour.EVERY = 4 * 60 * 60STALE = 60 * 60USER_AGENT = "Cicada-Linux"-# Downloading: seconds without a byte before it counts as stalled (each read, not the whole file),-# and how many times a cut-off download is picked up again.STALL = 30ATTEMPTS = 3@@ -50,21 +38,16 @@ class Update:class Failure(Exception):- """Why installing in place didn't work, said to the user beside the release page: a- Mac string key and its values, translated by the app."""-def __init__(self, key: str, *args):super().__init__(key)self.key, self.args = key, argsdef feed() -> str:- """CICADA_UPDATE_FEED points at another release JSON (a list or one release); file:// works."""return os.environ.get("CICADA_UPDATE_FEED") or FEEDdef is_newer(a: str, than: str) -> bool:- """Dotted numeric versions: "2.10.0" is newer than "2.9.1"."""def parts(v):out = []for p in v.strip().lstrip("v").split("."):@@ -84,7 +67,6 @@ def is_newer(a: str, than: str) -> bool:def due(last: float | None, now: float, after: float) -> bool:if last is None:return True- # A clock set back leaves `last` in the future: check rather than wait for it.return now - last >= after or last > now@@ -99,8 +81,6 @@ def decode(data: bytes) -> list | None:def newest_linux(releases: list) -> Update | None:- """The newest published release with the Linux tarball. One without it carries only other- platforms (Linux had no change), so it is skipped, not offered."""best = Nonefor r in releases:if not isinstance(r, dict) or r.get("draft") or r.get("prerelease"):@@ -119,7 +99,6 @@ def newest_linux(releases: list) -> Update | None:def checksum_for(text: str, name: str) -> str | None:- """The SHA-256 of `name` in a sha256sum listing ("<hex> <name>", or "<hex> *<name>")."""for line in text.splitlines():parts = line.strip().split(None, 1)if len(parts) == 2 and parts[1].lstrip("*") == name:@@ -127,8 +106,6 @@ def checksum_for(text: str, name: str) -> str | None:return None-# Where the last successful check is remembered (the Mac keeps it in UserDefaults).-def _state_file() -> str:return os.path.join(Paths.data(), "updates.json")@@ -163,7 +140,6 @@ def _remember(when: float) -> None:def notified() -> str | None:- """The version the update notification was last shown for: one per version."""v = _state().get("notified")return v if isinstance(v, str) else None@@ -173,19 +149,16 @@ def remember_notified(version: str) -> None:def should_notify(version: str, told: str | None, busy: bool) -> bool:- """A notification per version, none while listening or speaking (the meeting's end tells)."""return not busy and version != tolddef _get(url: str, timeout: float = 20, headers=None):req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/vnd.github+json",**(headers or {})})- return proxy.urlopen(req, timeout=timeout) # our feed, or file:// in tests+ return proxy.urlopen(req, timeout=timeout)def why(e: BaseException) -> str:- """A failure for the log: its kind and reason, with any URL in it left out (a URL may carry a- token one day; the host is logged on its own)."""if isinstance(e, urllib.error.HTTPError):return "HTTP %d" % e.codeif isinstance(e, urllib.error.URLError) and isinstance(e.reason, BaseException):@@ -199,14 +172,12 @@ def _host(url: str) -> str:def check(current: str) -> tuple:- """(ok, update): ok is False when the feed couldn't be reached or answered oddly; update is a- release newer than `current`, or None. Blocking: run it off the main thread."""try:with _get(feed()) as r:if getattr(r, "status", 200) not in (200, None):return False, Nonereleases = decode(r.read())- except Exception as e: # noqa: BLE001 - offline, rate-limited, private repo (404): all silent+ except Exception as e: # noqa: BLE001Log.d("update: check failed (%s)" % type(e).__name__)return False, Noneif releases is None:@@ -217,26 +188,20 @@ def check(current: str) -> tuple:return True, (u if u and is_newer(u.version, current) else None)-# Installing-def install_root() -> str | None:- """The install this app runs from, when it's one install.sh made (~/.local/lib/cicada): only- that can be replaced in place. A checkout or a build tree gets the release page instead."""here = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))lib = os.path.realpath(os.path.expanduser("~/.local/lib/cicada"))return here if os.path.realpath(here) == lib and os.path.isfile(os.path.join(here, "VERSION")) else Nonedef _download(url: str, to: str, progress, expected: int = 0, attempts: int = ATTEMPTS) -> None:- """A slow link is fine (a 13 MB release took 100 s in a VM behind a proxy): only `STALL` seconds- without a byte counts as failing, and a cut-off download picks up where it stopped (Range)."""got, total = 0, 0with open(to, "wb") as f:for attempt in range(1, attempts + 1):try:with _get(url, timeout=STALL, headers={"Range": "bytes=%d-" % got} if got else None) as r:if got and getattr(r, "status", None) != 206:- f.seek(0) # the server sent the whole file again+ f.seek(0)f.truncate()got = 0if not got:@@ -253,7 +218,7 @@ def _download(url: str, to: str, progress, expected: int = 0, attempts: int = ATraise http.client.IncompleteRead(b"", total - got)returnexcept urllib.error.HTTPError:- raise # the server said no: asking again won't change it+ raiseexcept (OSError, http.client.HTTPException) as e:Log.d("update: download from %s stopped at %d of %d bytes, try %d of %d (%s)"% (_host(url), got, total, attempt, attempts, why(e)))@@ -262,20 +227,16 @@ def _download(url: str, to: str, progress, expected: int = 0, attempts: int = ATdef _safe_extract(tar_path: str, into: str) -> None:- """Unpacks only regular files and folders that stay inside `into`: a tarball that names- absolute paths, "..", links or devices is refused rather than trusted."""root = os.path.realpath(into)with tarfile.open(tar_path, "r:gz") as t:for m in t.getmembers():target = os.path.realpath(os.path.join(root, m.name))if not (m.isfile() or m.isdir()) or os.path.isabs(m.name) or not target.startswith(root + os.sep):raise Failure("更新包无效")- t.extractall(root) # noqa: S202 - every member checked above+ t.extractall(root) # noqa: S202def prepare(u: Update, progress=None) -> str:- """Downloads and checks the release; returns the unpacked tree (…/cicada-linux) ready for its- install.sh. Raises Failure with a reason to show. Blocking: run it off the main thread."""if not u.tarball or not u.checksums:raise Failure("这个版本没有可安装的文件")work = tempfile.mkdtemp(prefix="cicada-update-")@@ -306,10 +267,8 @@ def prepare(u: Update, progress=None) -> str:raise Failure("更新包无效") from Noneif got != u.version:raise Failure("下载的不是预期的版本")- # The new version's own dependency check, before anything is replaced or the app quits.r = subprocess.run(["sh", os.path.join(tree, "install.sh"), "--check"], capture_output=True, text=True)if r.returncode != 0:- # install.sh says which packages are missing (and the apt line); shown as it is.raise Failure("%@", (r.stdout or r.stderr).strip() or "The update package is invalid")return treeexcept BaseException:@@ -318,12 +277,10 @@ def prepare(u: Update, progress=None) -> str:def marker_file() -> str:- """Left by the swap script for the reopened app: "ok <version>" or "failed <version>"."""return os.path.join(Paths.data(), "update-result")def take_result() -> tuple | None:- """("ok"|"failed", version) once after an update reopened the app, then forgotten."""p = marker_file()try:with open(p, encoding="utf-8") as f:@@ -335,9 +292,6 @@ def take_result() -> tuple | None:def hand_over(tree: str, version: str, argv: list) -> None:- """Starts the script that waits for this process to quit, runs the new install.sh and opens- Cicada again with the same arguments; the caller quits next. If install.sh fails the old- install is untouched (it only replaces after its checks), so that one reopens."""pid = os.getpid()os.makedirs(Paths.data(), exist_ok=True)marker = marker_file()diff --git a/linux/cicada/core/vocabulary.py b/linux/cicada/core/vocabulary.pyindex eb2c2ea..8aa7f32 100644--- a/linux/cicada/core/vocabulary.py+++ b/linux/cicada/core/vocabulary.py@@ -1,7 +1,3 @@-"""词表: the spellings the user stands behind, and how speech recognition has misheard each (the Mac's-Vocabulary.swift). Only these let a new name be fixed without asking: names the notes guess are often-wrong, so they stay suggestions until the user confirms one. One JSON file beside the records-(vocabulary.json, the Mac's format); not a secret, so not one of the 0600 key files. Thread-safe."""from __future__ import annotationsimport os@@ -14,7 +10,6 @@ from . import correction, jsonfmtfrom .models import iso_read, iso_write, nowfrom .support import Log, Paths-# More would make every sentence's request long, and more terms means more wrong swaps.LIMIT = 300_SEPARATORS = "、,,;;"@@ -22,8 +17,8 @@ _SEPARATORS = "、,,;;"@dataclassclass Term:word: str- heard: list = field(default_factory=list) # wrong forms the recognizer produced, confirmed or typed by the user- source: str = "user" # "user" (added or imported), "live" (confirmed during a meeting)+ heard: list = field(default_factory=list)+ source: str = "user"fixes: int = 0used: datetime | None = None@@ -51,7 +46,6 @@ class ImportResult:def key(s: str) -> str:- """Same word whatever its width, case or spacing ("AAVE" is "aave")."""return " ".join(unicodedata.normalize("NFKC", s).lower().split())@@ -64,10 +58,6 @@ def _edge(c: str) -> bool:def learnable(heard: str, word: str):- """What a fix can teach the list, or None (Vocabulary.swift's learnable): both sides trimmed of- spaces and punctuation, no punctuation inside, short, and a real swap. An edit that only adds or- drops words around the heard ones ("我来" → "OK我来") or ends on a full stop ("持。" → "讲。")- teaches nothing."""def trim(s: str) -> str:a, b = 0, len(s)while a < b and _edge(s[a]):@@ -87,8 +77,6 @@ def default_path() -> str:def parse(text: str) -> list:- """粘贴导入: one per line, heard forms after "=" ("Morpho = 莫拉、莫法"). Each non-empty line as- (line number, word, heard); a word too long or with control characters comes back as "" (skipped)."""out = []for i, raw in enumerate(text.splitlines()):line = raw.strip()@@ -142,9 +130,6 @@ class Vocabulary:return any(key(t.word) == w and any(key(x) == h for x in t.heard) for t in self.terms)def confirm(self, heard: str, word: str, source: str = "live") -> None:- """The user said yes to a fix (or added it): the word, and the form it was heard as. A pair- that isn't a word for a word (`learnable`) adds nothing. A yes in a meeting never teaches a- translation (平台 → platform): it would rewrite that word everywhere after."""if heard:pair = learnable(heard, word)if pair is None or (source != "user" and correction.translation(*pair)):@@ -160,7 +145,6 @@ class Vocabulary:self._save()def forget(self, heard: str, word: str) -> None:- """A heard form the user turned down twice (or took off in 词表) stops being one."""with self._gate:i = self._find(word)if i is None:@@ -169,7 +153,6 @@ class Vocabulary:self._save()def rename(self, word: str, new: str) -> None:- """词表 › click a word: its spelling changes; what it was heard as stays with it."""n = new.strip()with self._gate:i = self._find(word)@@ -177,7 +160,6 @@ class Vocabulary:returnj = self._find(n)if j is not None and j != i:- # Renamed onto a word already there: the two become one.for h in self.terms[i].heard:if not any(key(x) == key(h) for x in self.terms[j].heard):self.terms[j].heard.append(h)@@ -187,13 +169,11 @@ class Vocabulary:self._save()def owners(self, heard: str, except_word: str | None = None) -> list:- """The other words a heard form already belongs to ("莫拉" is Morpho's)."""with self._gate:return [t.word for t in self.terms if any(key(x) == key(heard) for x in t.heard)and key(t.word) != key(except_word or "")]def insert(self, term: Term, index: int) -> None:- """Back where it was, after 撤销 on a delete."""with self._gate:if self._find(term.word) is not None:return@@ -201,7 +181,6 @@ class Vocabulary:self._save()def restore(self, saved: list) -> None:- """撤销: the list as it was."""with self._gate:if saved == self.terms:return@@ -223,14 +202,12 @@ class Vocabulary:self._save()def prompt_lines(self) -> list:- """For the request: the most recently useful first, "Morpho (heard as 莫拉, 莫法)"."""oldest = datetime.min.replace(tzinfo=now().tzinfo)with self._gate:ts = sorted(self.terms, key=lambda t: t.used or oldest, reverse=True)[:LIMIT]return [t.word if not t.heard else "%s (heard as %s)" % (t.word, ", ".join(t.heard)) for t in ts]def preview(self, text: str) -> ImportResult:- """What 粘贴导入 would do, before it does it (the sheet's counts and its button)."""r = ImportResult()seen = set()with self._gate:@@ -271,8 +248,6 @@ class Vocabulary:if not self.path:returnwith self._gate:- # The Mac writes this file without escaping slashes (.withoutEscapingSlashes); an escaped- # slash is always "\/" here, after an even run of backslashes, so the swap is exact.text = jsonfmt.write([t.to_json() for t in self.terms]).replace("\\/", "/")try:os.makedirs(os.path.dirname(self.path), exist_ok=True)diff --git a/linux/cicada/core/voice_reference.py b/linux/cicada/core/voice_reference.pyindex 9e1fb24..63e21f9 100644--- a/linux/cicada/core/voice_reference.py+++ b/linux/cicada/core/voice_reference.py@@ -1,8 +1,3 @@-"""The user's own voice (Voices.swift › VoiceReference): the recording Ming clones it from,-`voice/reference.wav` (16 kHz mono, 10–15 s) and `voice/reference.txt` (what it says, as Ming-heard it) in the config folder. The folder is 0700 and the files 0600, like the key; they never go-into a record, an export or the log, and leave the computer only inside a speech request to Ling.-UI-free: the settings window records, this keeps, checks and hands it to LingClient.speech."""from __future__ import annotationsimport base64@@ -14,14 +9,9 @@ from array import arrayfrom .audio import RATE, Wavfrom .support import Paths-# The issue's advice (#32): the reference goes with every sentence, so a longer one makes each-# sentence later. Under 10 s Ming has too little to go on; recording stops by itself at 15.MIN_SECONDS = 10.0MAX_SECONDS = 15.0-# Ming copies the recording's pace into every sentence (Voices.swift › slowCharacters): below these-# (characters a second for Chinese, Japanese and Korean, words otherwise) the clone is too slow for-# a meeting; reading the passage at an ordinary pace gives 3.5–5 and 2.3–3.SLOW_CHARACTERS = 2.5SLOW_WORDS = 1.6@@ -60,7 +50,6 @@ def duration() -> float:def reference() -> tuple[str, str] | None:- """What Ming needs: the clip as a data URI and its transcript."""t = (text() or "").strip()if not t:return None@@ -73,7 +62,6 @@ def reference() -> tuple[str, str] | None:def _private(path: str, mode: int, data: bytes) -> None:- """Written 0600 from the first byte, then swapped in, so a half-written clip is never used."""tmp = path + ".tmp"fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)try:@@ -85,7 +73,6 @@ def _private(path: str, mode: int, data: bytes) -> None:def save(samples: array, transcript: str) -> None:- """16 kHz mono samples and what they say."""os.makedirs(folder(), mode=0o700, exist_ok=True)os.chmod(folder(), 0o700)_private(audio_path(), 0o600, Wav.bytes(trim(samples)))@@ -100,15 +87,12 @@ def remove() -> None:shutil.rmtree(folder(), ignore_errors=True)-# Pace-def is_cjk(ch: str) -> bool:o = ord(ch)return 0x3040 <= o <= 0x30FF or 0x3400 <= o <= 0x4DBF or 0x4E00 <= o <= 0x9FFF or 0xAC00 <= o <= 0xD7AF or 0xF900 <= o <= 0xFAFFdef tokens(s: str) -> list:- """Characters for Chinese, Japanese and Korean, words otherwise (SpeakTest.swift › tokens)."""out, word = [], ""for ch in s:if is_cjk(ch):@@ -127,7 +111,6 @@ def tokens(s: str) -> list:def _speech_windows(samples, rate: int = RATE):- """(first, last, size): the 20 ms windows within 35 dB of the loudest one; None when silent."""size = max(1, int(rate * 0.02))levels = []for i in range(0, len(samples), size):@@ -141,7 +124,6 @@ def _speech_windows(samples, rate: int = RATE):def speech_span(samples, rate: int = RATE) -> float | None:- """Seconds from the first to the last 20 ms window within 35 dB of the loudest one."""w = _speech_windows(samples, rate)return None if w is None else (w[1] - w[0] + 1) * w[2] / rate@@ -150,9 +132,6 @@ TRIM_PAD = 0.2def trim(samples, rate: int = RATE):- """The recording without the quiet before and after the reading, 0.2 s kept each side. Ming- copies the clip's ending: a second of silence after the last word (the pause before 读完了)- made every cloned sentence come back as 0.4 s of nothing (measured 2026-11 against Ling)."""w = _speech_windows(samples, rate)if w is None:return samples@@ -161,7 +140,6 @@ def trim(samples, rate: int = RATE):def pace(transcript: str, samples, rate: int = RATE) -> float | None:- """Characters or words a second of speech; None when there is no speech to measure."""units = len(tokens(transcript))span = speech_span(samples, rate)if units == 0 or span is None or span <= 0.5:@@ -175,11 +153,10 @@ def is_slow(transcript: str, p: float) -> bool:return p < (SLOW_CHARACTERS if characters * 2 >= len(t) else SLOW_WORDS)-_saved_pace = None # (mtime, slow)+_saved_pace = Nonedef saved_is_slow() -> bool:- """The saved recording is read too slowly (worked out once per recording)."""global _saved_pacetry:mtime = os.path.getmtime(audio_path())@@ -198,7 +175,6 @@ def saved_is_slow() -> bool:def passage(code: str) -> str:- """The passage to read, in the user's own language (Voices.swift › passage)."""k = (code or "en").split("-")[0].lower()if k == "zh":return "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。请大家先看一下屏幕上的议程。"@@ -209,8 +185,6 @@ def passage(code: str) -> str:def check(samples, transcript: str) -> str | None:- """Why a recording can't be used ("short", "unclear", "slow"), or None; the Mac's order. Long- enough is measured on the reading itself (trim), not the quiet around it."""if len(trim(samples)) / RATE < MIN_SECONDS:return "short"if len(transcript.strip()) < 6:diff --git a/linux/cicada/core/voices.py b/linux/cicada/core/voices.pyindex cbc6c7d..04083f6 100644--- a/linux/cicada/core/voices.py+++ b/linux/cicada/core/voices.py@@ -1,12 +1,7 @@-"""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 annotationsdef key(code: str) -> str:- """"zh" for zh-CN / zh-TW, "en" for en-US."""return (code or "en").split("-")[0].lower() or "en"@@ -17,7 +12,6 @@ def ming_language(code: str, config=None) -> str | None:return k if k in ("ja", "ko", "de", "fr", "es") else None-# (voice, name, tags as Chinese keys)_CATALOG = {"en": [("US_Emma", "Emma", ["女", "美式", "自然对话"]), ("UK_George", "George", ["男", "英式", "稳重"]),("UK_Charlotte", "Charlotte", ["女", "英式", "平稳"])],@@ -26,12 +20,10 @@ _CATALOG = {}_OTHER = [("US_Emma", "Emma", ["女"]), ("UK_George", "George", ["男"])]-# The languages the room can hear: those Ming speaks.ROOM_LANGUAGES = ["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de"]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)@@ -45,18 +37,14 @@ def default_voice(code: str, config=None) -> str | None:return v[0][0] if v else None-CLONE = "clone" # the user's own voice (voice_reference), stored in speakVoices like a Ming voice+CLONE = "clone"def clones(config) -> bool:- """Only Ling clones the user's voice (providers.py)."""return config is None or bool(getattr(config.provider, "clones", False))def chosen(choice: str | None, code: str, config=None, has_reference: bool = False) -> str | None:- """The voice a language uses: the choice while the service in use can speak it, else the default- (AppModel.voiceID). The user's own voice needs its recording and Ling; a Ming voice saved- before switching services isn't sent elsewhere. Either comes back with that service."""if choice == CLONE:return CLONE if has_reference and clones(config) else default_voice(code, config)names = [v for v, _n, _t in voices(code, config)]@@ -64,7 +52,6 @@ def chosen(choice: str | None, code: str, config=None, has_reference: bool = Faldef sample(code: str) -> str:- """A short line to try a voice with, in the language it will speak (VoiceCatalog.sample)."""return {"zh": "谢谢大家。我们来看一下上线时间表,并确定谁负责麦克风测试。","ja": "皆さん、ありがとうございます。発売スケジュールを確認しましょう。",diff --git a/linux/cli.py b/linux/cli.pyindex 3e8ceff..88a96dd 100755--- a/linux/cli.py+++ b/linux/cli.py@@ -56,7 +56,6 @@ def key_file() -> str | 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)@@ -132,7 +131,7 @@ def main(args: list) -> int:passdef close(self):- out.extend(bytes(24000 // 2 * 2)) # half a second between sentences+ out.extend(bytes(24000 // 2 * 2))eng = SpeakEngine(ling, Translator(ling), settings, player=Collect)eng.on_change(lambda: eng.last and eng.stage == "speaking" and print(" %s\n → %s" % eng.last, flush=True))done = threading.Event()diff --git a/linux/native/build.sh b/linux/native/build.shindex b0c096c..5d20725 100755--- a/linux/native/build.sh+++ b/linux/native/build.sh@@ -1,7 +1,4 @@#!/bin/bash-# Builds the voiceprint library (voiceprint.c) for this machine into $1 (default native/out):-# libcicada-voice-<arch>.so on Linux, libcicada-voice.dylib on the Mac (unit tests only).-# Release builds come from CI on Ubuntu 22.04, so the .so loads on 22.04 and 24.04 alike.set -euo pipefailhere="$(cd "$(dirname "$0")" && pwd)"out="${1:-$here/out}"diff --git a/linux/native/voiceprint.c b/linux/native/voiceprint.cindex 1b8aa22..118775c 100644--- a/linux/native/voiceprint.c+++ b/linux/native/voiceprint.c@@ -28,17 +28,16 @@#define MAX_THREADS 4#if defined(__GNUC__) && defined(__x86_64__) && !defined(__clang__)-/* One .so for every x86_64 machine: the GEMM also built for AVX2, picked at load. */#define FAST __attribute__((target_clones("avx2", "default")))#else#define FAST#endiftypedef struct {- int type; /* 1 conv, 2 add */+ int type;int src, src2, dst, cin, cout, k, stride, relu;float *w, *b;- int last_use_src, last_use_src2; /* free a slot after its last reader */+ int last_use_src, last_use_src2;} Op;typedef struct {@@ -55,7 +54,7 @@ static float half(uint16_t h) {uint32_t s = (uint32_t)(h & 0x8000) << 16, e = (h >> 10) & 0x1F, m = h & 0x3FF, bits;if (e == 0) {if (m == 0) bits = s;- else { /* subnormal */+ else {e = 127 - 15 + 1;while (!(m & 0x400)) { m <<= 1; e--; }bits = s | (e << 23) | ((m & 0x3FF) << 13);@@ -87,7 +86,6 @@ static float *read_f32(FILE *f, size_t n) {static void tables(Model *m) {for (int i = 0; i < FRAME; i++)m->window[i] = powf(0.5f - 0.5f * cosf(2 * (float)M_PI * (float)i / (float)(FRAME - 1)), 0.85f);- /* `BINS` rows of `COLS` weights, the Nyquist column zero, as in Kaldi (Fbank.melBanks). */double lo = 1127 * log(1 + 20 / 700.0), hi = 1127 * log(1 + 8000 / 700.0), delta = (hi - lo) / (BINS + 1);memset(m->mel, 0, sizeof m->mel);for (int b = 0; b < BINS; b++) {@@ -140,7 +138,6 @@ void *cvp_load(const char *path) {m->fc_b = read_f32(f, m->dims);m->mean = read_f32(f, m->dims);if (!m->fc || !m->fc_b || !m->mean) goto fail;- /* A slot is freed after the op that reads it last. */for (int i = 0; i < m->nops; i++) {Op *o = &m->ops[i];o->last_use_src = o->last_use_src2 = 1;@@ -159,7 +156,6 @@ fail:return NULL;}-/* In-place radix-2 FFT of NFFT complex values. */static void fft(const Model *m, float *re, float *im) {for (int i = 1, j = 0; i < NFFT; i++) {int bit = NFFT >> 1;@@ -183,7 +179,6 @@ static void fft(const Model *m, float *re, float *im) {}}-/* Frames x BINS, row-major (Fbank.compute). Returns the frame count. */int cvp_fbank(void *model, const float *samples, int n, float *out) {const Model *m = model;if (n < FRAME) return 0;@@ -213,8 +208,6 @@ int cvp_fbank(void *model, const float *samples, int n, float *out) {return frames;}-/* ---- the ResNet ---- */-typedef struct {const Op *o;const float *in;@@ -224,8 +217,6 @@ typedef struct {pthread_mutex_t *lock;} ConvJob;-/* c_q[j] += a_q * b[j] for eight output channels: restrict parameters (GCC ignores them on locals) let- * the compiler see the rows never overlap, so the loop over pixels vectorizes (NEON, SSE, AVX2). */static inline __attribute__((always_inline)) void axpy8(const float *restrict b, int nt, const float *a,float *restrict c0, float *restrict c1, float *restrict c2, float *restrict c3,float *restrict c4, float *restrict c5, float *restrict c6, float *restrict c7) {@@ -241,7 +232,6 @@ static inline __attribute__((always_inline)) void axpy1(const float *restrict b,for (int j = 0; j < nt; j++) c[j] += a * b[j];}-/* C[rows][nt] = W[rows][K] . col[K][nt], 8 output channels at a time so each col row is read once per 8. */FAST static void gemm(const float *w, int K, int rows, const float *col, int nt, float *acc) {int r = 0;float a8[8];@@ -272,7 +262,6 @@ static void *conv_worker(void *arg) {pthread_mutex_unlock(j->lock);if (t >= j->tiles) break;int p0 = t * j->tile, nt = P - p0 < j->tile ? P - p0 : j->tile;- /* im2col for pixels p0..p0+nt */int pad = o->k / 2;for (int ci = 0; ci < o->cin; ci++)for (int ky = 0; ky < o->k; ky++)@@ -304,7 +293,6 @@ static float *conv(const Op *o, const float *in, int h, int w, int *ho, int *wo,int K = o->cin * o->k * o->k, P = *ho * *wo;float *out = malloc((size_t)o->cout * P * sizeof(float));if (!out) return NULL;- /* The column tile stays within ~256 KB of cache. */int tile = 65536 / K;tile = tile < 32 ? 32 : tile > 512 ? 512 : tile;tile -= tile % 8;@@ -319,7 +307,6 @@ static float *conv(const Op *o, const float *in, int h, int w, int *ho, int *wo,return out;}-/* A unit-length voiceprint of 16 kHz mono samples in -1...1 into out[dims]. 0, or -1 when too short. */int cvp_embed(void *model, const float *samples, int n, float *out, int threads) {Model *m = model;if (n < MIN_SECONDS * RATE) return -1;@@ -339,7 +326,6 @@ int cvp_embed(void *model, const float *samples, int n, float *out, int threads)float mean = (float)(sum / frames);for (int f = 0; f < frames; f++) feats[(size_t)f * BINS + b] -= mean;}- /* [frames][BINS] -> [1][BINS][frames]: height is frequency, width is time. */float **slot = calloc(m->nslots, sizeof(float *));int *hs = calloc(m->nslots, sizeof(int)), *ws = calloc(m->nslots, sizeof(int)), *cs = calloc(m->nslots, sizeof(int));float *x = malloc((size_t)frames * BINS * sizeof(float));@@ -370,7 +356,6 @@ int cvp_embed(void *model, const float *samples, int n, float *out, int threads)}int result = -1;if (ok) {- /* Statistics pooling over time: mean, then unbiased std + 1e-8, per (channel, frequency). */const float *t = slot[last];int rows = cs[last] * hs[last], w = ws[last];float *z = malloc((size_t)rows * 2 * sizeof(float));@@ -414,7 +399,6 @@ void cvp_free(void *model) {free(m);}-/* The same for 16-bit samples, as the segmenter keeps them. */int cvp_embed_s16(void *model, const int16_t *samples, int n, float *out, int threads) {if (n > MAX_SECONDS * RATE) n = (int)(MAX_SECONDS * RATE);float *f = malloc((size_t)(n > 0 ? n : 1) * sizeof(float));diff --git a/linux/packaging/install.sh b/linux/packaging/install.shindex 9f74fbf..577eb5b 100755--- a/linux/packaging/install.sh+++ b/linux/packaging/install.sh@@ -1,14 +1,10 @@#!/bin/sh-# Installs Cicada for this user, no sudo: the app in ~/.local/lib/cicada, `cicada` in-# ~/.local/bin, the menu entry and icon in ~/.local/share. Run it again to update; --remove undoes it; --check only checks the libraries-# (records and the Ling key stay in ~/.local/share/cicada and ~/.config/cicada).set -esrc="$(cd "$(dirname "$0")" && pwd)"lib="$HOME/.local/lib/cicada"; bin="$HOME/.local/bin"; share="$HOME/.local/share"if [ "$1" = "--remove" ]; thenrm -rf "$lib" "$bin/cicada" "$share/applications/com.wquguru.cicada.desktop" "$share/icons/hicolor/scalable/apps/cicada.svg" \"${XDG_CONFIG_HOME:-$HOME/.config}/autostart/com.wquguru.cicada.desktop"- # The 开始 / 结束听 keyboard shortcut, if it was added in 设置 (it would run a removed program).python3 - <<'PY' 2>/dev/null || truefrom gi.repository import Gioschema = "org.gnome.settings-daemon.plugins.media-keys"@@ -24,15 +20,13 @@ missing=""python3 -c 'import gi; gi.require_version("Gtk", "3.0"); from gi.repository import Gtk' 2>/dev/null || missing="$missing python3-gi gir1.2-gtk-3.0"python3 -c 'import ctypes.util, sys; sys.exit(0 if ctypes.util.find_library("pulse-simple") else 1)' || missing="$missing libpulse0"if [ -n "$missing" ]; then echo "Cicada needs:$missing (sudo apt install$missing)"; exit 1; fi-# --check: only the checks above (an update runs the new version's before anything is replaced).[ "$1" = "--check" ] && exit 0rm -rf "$lib" && mkdir -p "$lib" "$bin" "$share/applications" "$share/icons/hicolor/scalable/apps"cp -R "$src/cicada" "$src/lproj" "$src/bin" "$lib/"[ -f "$src/sample.wav" ] && cp "$src/sample.wav" "$lib/"-# 说话人识别: the voiceprint weights and libcicada-voice-<arch>.so (speakers.py looks for them here).for d in models lib; do [ -d "$src/$d" ] && cp -R "$src/$d" "$lib/"; done-cp "$src/cicada.svg" "$lib/" # the tray and window icon, by path-cp "$src/VERSION" "$lib/" # read by cicada/__init__.py+cp "$src/cicada.svg" "$lib/"+cp "$src/VERSION" "$lib/"ln -sf "$lib/bin/cicada" "$bin/cicada"sed "s|@BIN@|$lib/bin/cicada|" "$src/com.wquguru.cicada.desktop" > "$share/applications/com.wquguru.cicada.desktop"cp "$src/cicada.svg" "$share/icons/hicolor/scalable/apps/cicada.svg"diff --git a/linux/scripts/build.sh b/linux/scripts/build.shindex c4c0dda..78675e1 100755--- a/linux/scripts/build.sh+++ b/linux/scripts/build.sh@@ -1,7 +1,4 @@#!/bin/bash-# Builds the installable tree build/cicada-linux/ and build/cicada-linux-<version>.tar.gz: the Python-# package, the strings tables (the Mac's Localizable.strings and .stringsdict, plus Linux.strings),-# the sample meeting as 16 kHz WAV, the menu entry, the icon and install.sh. Runs on the Mac or on Linux.set -euo pipefailhere="$(cd "$(dirname "$0")/.." && pwd)"root="$(dirname "$here")"@@ -16,15 +13,12 @@ for lang in zh-Hans en ja ko; do[ -f "$here/strings/$lang.lproj/Linux.strings" ] && cp "$here/strings/$lang.lproj/Linux.strings" "$out/lproj/$lang.lproj/"donemkdir -p "$out/bin" && cp "$here/bin/cicada" "$out/bin/"-# 说话人识别: the voiceprint weights and libcicada-voice-<arch>.so for each architecture built so far-# (native/out: CI builds x86_64 and aarch64 on Ubuntu 22.04; on Linux this machine's is built here).mkdir -p "$out/models" "$out/lib" && cp "$here/models/voiceprint.bin" "$out/models/"if [ "$(uname)" = Linux ] && [ ! -f "$here/native/out/libcicada-voice-$(uname -m).so" ] && command -v "${CC:-gcc}" >/dev/null; then"$here/native/build.sh"ficp "$here"/native/out/libcicada-voice-*.so "$out/lib/" 2>/dev/null || echo "note: no voiceprint library in this build (说话人识别 unavailable)" >&2-cp "$root/VERSION" "$out/" # read by cicada/__init__.py-# The sample meeting as 16 kHz mono WAV: the file source reads WAV only, and Linux may lack an AAC decoder.+cp "$root/VERSION" "$out/"sample="$root/Resources/sample/sample.m4a"if command -v afconvert >/dev/null; then afconvert -f WAVE -d LEI16@16000 -c 1 "$sample" "$out/sample.wav"elif command -v ffmpeg >/dev/null; then ffmpeg -loglevel error -y -i "$sample" -ac 1 -ar 16000 -c:a pcm_s16le "$out/sample.wav"diff --git a/linux/scripts/convert-voiceprint.py b/linux/scripts/convert-voiceprint.pyindex 52fadf8..9e8ec05 100644--- a/linux/scripts/convert-voiceprint.py+++ b/linux/scripts/convert-voiceprint.py@@ -1,17 +1,4 @@#!/usr/bin/env python3-"""Converts the WeSpeaker ResNet34-LM speaker model (VoxCeleb, CC BY 4.0) into linux/models/voiceprint.bin,-the voiceprint model behind 分出对方的每个人 on Linux. The same ONNX file the Mac's Core ML model comes-from (scripts/convert-voiceprint.py), sha256 7bb2f06e9df17cdf1ef14ee8a15ab08ed28e8d0ef5054ee135741560df2ec068.-Developer-only, run once; stdlib only (a protobuf reader for the parts of ONNX this model uses).--usage: python3 linux/scripts/convert-voiceprint.py voxceleb_resnet34_LM.onnx linux/models/voiceprint.bin--The file, little-endian: b"CVP1", u32 op count, then each op- 1 conv: u32 src dst cin cout kernel stride relu, f16 weights [cout][cin][k][k], f32 bias [cout]- 2 add: u32 a b dst relu-then the head: u32 channels freq dims, f16 fc [dims][channels*freq*2], f32 fc bias [dims], f32 mean_vec [dims].-Slot 0 is the input [1][80][T]; the last op's dst is the trunk's output. BatchNorm is already folded into-the convs in this export; statistics pooling (mean, unbiased std + 1e-8) is in the C code."""import hashlibimport structimport sys@@ -125,10 +112,9 @@ def main(src, out):def slot(name):return slots.setdefault(name, len(slots))- # The trunk starts at Unsqueeze(Transpose(feats)): [1, 1, 80, T].start = next(n for n in nodes if n["op"] == "Unsqueeze")["out"][0]slot(start)- produced = {start} # the trunk's tensors; Adds in the pooling work on other things+ produced = {start}ops = []for n in nodes:op = n["op"]@@ -148,7 +134,7 @@ def main(src, out):elif op == "Relu" and n["in"][0] in produced:assert ops[-1]["dst"] == n["in"][0], "relu not right after its op"ops[-1]["relu"] = 1- ops[-1]["dst"] = n["out"][0] # the relu's output is the op's output+ ops[-1]["dst"] = n["out"][0]produced.add(n["out"][0])blob = bytearray(b"CVP1")blob += struct.pack("<I", len(ops))@@ -159,7 +145,7 @@ def main(src, out):else:blob += struct.pack("<5I", 2, slot(o["a"]), slot(o["b"]), slot(o["dst"]), o["relu"])trunk_end = ops[-1]["dst"]- assert trunk_end == "343", trunk_end # the last Relu before pooling+ assert trunk_end == "343", trunk_endfc, bias, mean = inits["model.seg_1.weight"], inits["model.seg_1.bias"], inits["mean_vec"]dims, flat = fc["dims"]blob += struct.pack("<3I", 256, flat // 512, dims)diff --git a/linux/scripts/smoke.sh b/linux/scripts/smoke.shindex 6bd4be1..31d5c50 100755--- a/linux/scripts/smoke.sh+++ b/linux/scripts/smoke.sh@@ -1,11 +1,7 @@#!/bin/bash-# Starts the dev build in the current desktop session (or under xvfb-run in CI), checks that the-# windows open and that the speakers' monitor is heard, then quits. No Ling key needed: a fake one-# lets listening start; Ming's replies fail, which is fine, the capture is what's checked.-# linux/scripts/smoke.sh (inside the session: linux/vm/vmctl.sh ssh does that)set -euo pipefailhere="$(cd "$(dirname "$0")/.." && pwd)"-ctl="$here/scripts/cicadactl"; [ -x "$ctl" ] || ctl="$here/bin/cicadactl" # a checkout, or a build tree with it copied in+ctl="$here/scripts/cicadactl"; [ -x "$ctl" ] || ctl="$here/bin/cicadactl"export CICADA_HOME="${CICADA_HOME:-$(mktemp -d)}"[ -f "$CICADA_HOME/ling-api-key" ] || { printf 'sk-smoke-test-key' > "$CICADA_HOME/ling-api-key"; chmod 600 "$CICADA_HOME/ling-api-key"; }printf '{"onboarded" : true}' > "$CICADA_HOME/settings.json"@@ -16,7 +12,6 @@ for _ in $(seq 1 50); do "$ctl" state >/dev/null 2>&1 && break; sleep 0.2; done"$ctl" state | grep -q '"ok":true' || { echo "app didn't start"; cat "$CICADA_HOME/app.out"; exit 1; }"$ctl" show records >/dev/null"$ctl" start >/dev/null-# A second of 440 Hz to the default output; the monitor must hear it.python3 - "$CICADA_HOME/tone.wav" <<'PY'import math, struct, sys, wavew = wave.open(sys.argv[1], "wb"); w.setnchannels(1); w.setsampwidth(2); w.setframerate(16000)@@ -29,7 +24,6 @@ state="$("$ctl" state)"echo "$state""$ctl" windowspython3 -c 'import json,sys; s=json.loads(sys.argv[1]); assert s["listening"], "not listening"; assert s["peak"] > 0.05, "monitor heard nothing (peak %s)" % s["peak"]' "$state"-# SMOKE_VOICES=1 (CI, on the installed tarball): 说话人识别 must load, i.e. the shipped library links here.[ -z "${SMOKE_VOICES:-}" ] || python3 -c 'import json,sys; assert json.loads(sys.argv[1])["speakers"]["available"], "voiceprint library did not load"' "$state""$ctl" stop >/dev/null"$ctl" quit >/dev/null || truediff --git a/linux/scripts/strings.py b/linux/scripts/strings.pyindex 2a45cab..5802f9b 100644--- a/linux/scripts/strings.py+++ b/linux/scripts/strings.py@@ -1,8 +1,4 @@#!/usr/bin/env python3-"""Lists Linux UI text with no translation: every L("…") / LF("…") key in linux/cicada that is in-neither the Mac's Resources/<lang>.lproj/Localizable.strings nor linux/strings/<lang>.lproj/Linux.strings.---write appends the missing keys to Linux.strings as TODO lines (value = the Chinese). Keys in-Linux.strings that nothing uses are listed too."""import pathlibimport reimport sys@@ -40,7 +36,6 @@ for lang in ["en", "ja", "ko"]:f.write("/* Linux-only UI text; the Mac's Localizable.strings covers the rest. Check: linux/scripts/strings.py */\n")for k in missing:f.write(f'"{k}" = "{k}"; /* TODO */\n')- # Linux-only text nothing uses any more: a stale copy drifts from the Mac's wording unnoticed.unused = [k for k in table(mine) if k not in keys]if unused:missing_any = Truediff --git a/linux/scripts/test.sh b/linux/scripts/test.shindex ff13708..c934cce 100755--- a/linux/scripts/test.sh+++ b/linux/scripts/test.sh@@ -1,9 +1,7 @@#!/bin/bash-# The voiceprint library, unit tests for the engines (no network, no GTK), the translation check, and a syntax check of the app.set -euo pipefailhere="$(cd "$(dirname "$0")/.." && pwd)"cd "$here"-# The voiceprint library, so its test checks it against the Mac's model (needs a C compiler).native/build.sh >/dev/nullpython3 -m unittest discover -s tests -qpython3 scripts/strings.pydiff --git a/linux/tests/test_aicheck.py b/linux/tests/test_aicheck.pyindex 39d68bf..67ba221 100644--- a/linux/tests/test_aicheck.py+++ b/linux/tests/test_aicheck.py@@ -1,6 +1,3 @@-"""AI 服务检查 (AICheckTests.swift, plus the ports' 听对方 step): which step a failure stops at and-why, what passes, key prefixes, OpenRouter's balance, the models a service lists, the proxy hint,-and whole checks against a fake service, including results from real requests."""from __future__ import annotationsimport os@@ -40,7 +37,6 @@ class Rules(unittest.TestCase):self.assertEqual(("text", "noModel", 404), c(LingError(LingError.HTTP, 404), "text"))self.assertEqual(("key", "serverError", 400), c(LingError(LingError.HTTP, 400), "key"))self.assertEqual(("text", "serverError", 503), c(LingError(LingError.HTTP, 503), "text"))- # The hear model: what says "this model takes no audio".for code in (400, 404, 415, 422):self.assertEqual(("hear", "deaf", code), c(LingError(LingError.HTTP, code), "hear", True))self.assertEqual(("hear", "serverError", 500), c(LingError(LingError.HTTP, 500), "hear", True))@@ -52,7 +48,6 @@ class Rules(unittest.TestCase):r.fail("key", "invalidKey")self.assertEqual(["ok", "fail", "skipped", "skipped"], kinds(r))self.assertEqual(("key", "invalidKey", None), r.failure)- # Nothing sent (a management key): the steps before it are not claimed.r = AICheck()r.fail("key", "mgmtKey", reached=False)self.assertEqual(["untested", "fail", "skipped", "skipped"], kinds(r))@@ -80,7 +75,7 @@ class Rules(unittest.TestCase):self.assertFalse(r.needs_user)r.fail("hear", "deaf", 400)self.assertTrue(r.needs_user)- self.assertFalse(r.down) # notes and translation still work+ self.assertFalse(r.down)def test_not_passed_until_a_result(self):r = AICheck()@@ -113,10 +108,8 @@ class Rules(unittest.TestCase):every, hear = aicheck.listed(jsonfmt.write(MODELS))self.assertIn("x/text-only", every)self.assertEqual({"qwen/qwen3.8-omni-flash"}, hear)- # OpenRouter keeps them under `architecture`._, hear = aicheck.listed({"data": [{"id": "a", "architecture": {"input_modalities": ["audio", "text"]}}]})self.assertEqual({"a"}, hear)- # Nothing about modalities: can't tell who hears.every, hear = aicheck.listed({"data": [{"id": "a"}]})self.assertEqual({"a"}, every)self.assertIsNone(hear)@@ -155,21 +148,16 @@ class Rules(unittest.TestCase):class ProxyHint(unittest.TestCase):def test_cases(self):- # More in test_proxy.py.nothing = lambda: "" # noqa: E731up, down = (lambda h, p: True), (lambda h, p: False) # noqa: E731gnome = ("org.gnome.system.proxy mode '%s'\norg.gnome.system.proxy.https host '10.0.2.2'\n""org.gnome.system.proxy.https port 7890\n")self.assertEqual(("system",), proxy.hint({"https_proxy": "http://10.0.2.2:7890"}, nothing, lambda p: False, up))- # GNOME's manual proxy: requests go through it now, so "a proxy is on" is true when it answers.self.assertEqual(("system",), proxy.hint({}, lambda: gnome % "manual", lambda p: False, up))- # One that doesn't answer isn't "a proxy is on, try another server".self.assertEqual(("dead", "10.0.2.2:7890"), proxy.hint({}, lambda: gnome % "manual", lambda p: True, down))- # Automatic (PAC) isn't used: requests go direct, so it isn't "a proxy is on" either.self.assertEqual(("pac",), proxy.hint({}, lambda: gnome % "auto", lambda p: False, up))self.assertEqual(("app", 7897), proxy.hint({}, lambda: gnome % "none", lambda p: p == 7897, up))self.assertEqual(("none",), proxy.hint({"https_proxy": " "}, nothing, lambda p: False, up))- # all_proxy, which urllib ignored, counts now that requests go through it.self.assertEqual(("dead", "127.0.0.1:1"), proxy.hint({"all_proxy": "socks5://127.0.0.1:1"}, nothing, lambda p: False, down))def test_words(self):@@ -183,7 +171,7 @@ class ProxyHint(unittest.TestCase):r.proxy = hintself.assertEqual(words, r.proxy_line("ZenMux", "zenmux.ai"))r.fail("key", "invalidKey")- self.assertIsNone(r.proxy_line("ZenMux", "zenmux.ai")) # only after "can't reach"+ self.assertIsNone(r.proxy_line("ZenMux", "zenmux.ai"))def test_help_url(self):self.assertEqual("https://cicada.indaloop.app/start/#proxy", aicheck.help_url("zh-Hans"))@@ -191,7 +179,6 @@ class ProxyHint(unittest.TestCase):def service(text=200, hear=200, models=MODELS, json_ok=True, key_info=None, credits=None):- """A fake service: the text model's status, the hear model's, its `/models`."""def respond(url, body):if url.endswith("/models"):return Response(200, jsonfmt.write(models)) if models is not None else Response(404, "")@@ -235,23 +222,19 @@ 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 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"})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"})- self.assertEqual(OK, ling.check()) # notes and translation still work+ self.assertEqual(OK, ling.check())self.assertEqual(("hear", "deaf", 400), ling.check_result.failure)self.assertFalse(ling.hears)self.assertFalse(ling.can_hear)- # It takes the request, but the service doesn't list it as taking audio.ling, _ = self.client(service(), aiHearModels={"zenmux": "x/text-only"})ling.check()self.assertEqual(("hear", "deaf", None), ling.check_result.failure)- # A service that says nothing about modalities can't make it deaf.ling, _ = self.client(service(models={"data": [{"id": "inclusionai/ling-3.0-flash"}]}))ling.check()self.assertIsNone(ling.check_result.failure)@@ -326,7 +309,6 @@ class Checks(Base):ling.chat("c", "i", TRANSLATE)self.assertEqual(("key", "invalidKey", None), ling.check_result.failure)self.assertTrue(ling.check_result.passive)- # A server error in a meeting changes nothing.status["text"] = 200ling.key_state = OKling.chat("c", "i", TRANSLATE)@@ -335,7 +317,6 @@ class Checks(Base):with self.assertRaises(LingError):ling.chat("c", "i", TRANSLATE)self.assertIsNone(ling.check_result.failure)- # The hear model refusing audio in a meeting: deaf, the text model keeps its ok.status["text"] = 415with self.assertRaises(LingError):ling.chat("c", "i", TRANSLATE, audio=silence_wav())@@ -353,7 +334,7 @@ class Checks(Base):ling, s = self.client(service())seq = ling._check_seqr = aicheck.simulated("invalidKey")- ling.key_changed() # the settings changed while that check ran+ ling.key_changed()ling._finish_check(r, ling.config(), seq)self.assertIsNone(ling.check_result.failure)diff --git a/linux/tests/test_core.py b/linux/tests/test_core.pyindex 25483ce..8887cc8 100644--- a/linux/tests/test_core.py+++ b/linux/tests/test_core.py@@ -1,6 +1,3 @@-"""Unit tests for the engines (no network: LingClient runs against a fake transport). The Windows and-Android suites' cases, plus byte-for-byte checks of the Mac's JSON format.- python3 -m unittest discover -s linux/tests (scripts/test.sh)"""from __future__ import annotationsimport math@@ -105,27 +102,22 @@ MAC = """{def tone(seconds, amp=0.3, syllables=True, wobble=0.0):- """A 300 Hz tone that swells and fades four times a second like syllables; steady when not, or- rising and falling by `wobble` twice a second like a fan."""env = (lambda i: 0.55 + 0.45 * math.sin(2 * math.pi * 4 * i / 16000)) if syllables else \(lambda i: 1.0 + wobble * math.sin(2 * math.pi * 0.5 * i / 16000))return array("h", (int(math.sin(2 * math.pi * 300 * i / 16000) * env(i) * amp * 32767) for i in range(int(seconds * 16000))))def word(seconds, amp):- """One word on its own ("Thanks."): a 300 Hz tone that swells from nothing and fades back."""n = int(seconds * 16000)return array("h", (int(math.sin(2 * math.pi * 300 * i / 16000) * math.sin(math.pi * i / n) ** 2 * amp * 32767) for i in range(n)))def hz(freq, seconds, amp):- """A sine at `freq` that swells and fades four times a second like syllables."""return array("h", (int(math.sin(2 * math.pi * freq * i / 16000) * (0.55 + 0.45 * math.sin(2 * math.pi * 4 * i / 16000)) * amp * 32767)for i in range(int(seconds * 16000))))def hiss(seconds, amp):- """A 7 kHz tone faded in and out over 0.3 s: crosses zero like a hiss, swells like a word."""n = int(seconds * 16000)return array("h", (int(math.sin(2 * math.pi * 7000 * i / 16000) * min(1, i / 4800, (n - i) / 4800) * amp * 32767) for i in range(n)))@@ -135,7 +127,6 @@ def silence(seconds):def keys(seconds):- """Typing: a key click every 0.2 s, 6 ms of decaying crackle peaking near -12 dBFS (scripts/vad-clips.py)."""out = silence(seconds)for at in range(1600, len(out) - 96, 3200):for k in range(96):@@ -164,7 +155,7 @@ def cut(*parts):class Fake:def __init__(self, respond, speech=None):self.respond = respond- self.speech = speech # body -> list of SSE lines+ self.speech = speechself.calls = []self.spoken = []self.lock = threading.Lock()@@ -192,8 +183,6 @@ def client(fake, clock=None):class FakeClock:- """The start gate's time, moved on by each wait instead of waiting (one thread only)."""-def __init__(self):self.start = self.t = 1000.0self.waits = []@@ -249,13 +238,11 @@ class Records(Base):self.assertEqual(MAC, s.write())def test_keeps_the_macs_voiceprint_matches(self):- # The Mac's voiceprint library (1.10) adds voiceProfiles / voiceSuggestions: kept on save.ref = '{\n "1" : {\n "id" : "6F9619FF-8B86-D011-B42D-00C04FC964FF",\n "name" : "Emma",\n "similarity" : 0.75\n }\n }'text = MAC[:-2] + ',\n "voiceProfiles" : ' + ref + ',\n "voiceSuggestions" : ' + ref + '\n}'self.assertEqual(text, Session.read(text).write())def test_keeps_where_a_line_was_heard(self):- # 电脑和会议室 on the Mac: a room line says "via" : "room"; written back unchanged.text = MAC.replace(' "t" : 2.5,\n "voice" : 1\n', ' "t" : 2.5,\n "via" : "room",\n "voice" : 1\n')self.assertNotEqual(MAC, text)s = Session.read(text)@@ -295,7 +282,6 @@ class Records(Base):self.assertTrue(session_store.markdown(store.get(s.id)).startswith("# 我的会\n"))def test_keeps_room_and_keys_it_does_not_know(self):- # A Mac record heard in the room (会议室), plus a key from a newer Mac: written back unchanged.o = jsonfmt.parse(MAC)o["room"] = Trueo["zFuture"] = {"a": [1, "x"]}@@ -310,12 +296,10 @@ class Records(Base):s = store.begin(datetime(2026, 1, 1, 2, tzinfo=timezone.utc))store.set_notes(s.id, MeetingNotes(title="路线评审", summary="x"))shown = session_store.display_title(store.get(s.id))- # Saving the title as shown is no rename: the notes may still name the meeting later.store.rename(s.id, " " + shown + " ")self.assertIsNone(store.get(s.id).renamed)store.rename(s.id, "我的会")self.assertEqual(("我的会", True), (store.get(s.id).title, store.get(s.id).renamed))- # 恢复自动标题: back to the stored default and the notes' name.store.rename(s.id, "")self.assertEqual((session_store.default_title(s.startedAt), False), (store.get(s.id).title, store.get(s.id).renamed))self.assertEqual(shown, session_store.display_title(store.get(s.id)))@@ -353,7 +337,6 @@ class Hearing(Base):self.assertEqual("ja", parse_heard("lang: ja-JP\noriginal: はい\ntranslation: 是", "zh-CN", None).lang)def test_drops_noise(self):- # Same cases as the Android and Windows ports' noise tests.for o in ("嗯。", "Mm.", "uh, um", "呃呃呃呃呃", "嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯。", "滴答" * 50,"hmmmm", "うーん", "음…", "喂?", "No no no no no no","(无语音内容)", "[Music]", "♪♪", "这段音频是一段旋律,没有说话声。", "There is no speech in this audio."):@@ -368,7 +351,6 @@ class Hearing(Base):self.assertEqual((800, 380, 800), (hear_tokens(0), hear_tokens(8.0), hear_tokens(30.0)))def test_follow_system_as_on_the_mac(self):- # FollowSystemTests, with Linux locale names.for prefs, mine in ((["zh_CN.UTF-8"], "zh-CN"), (["en_US.UTF-8"], "en"), (["en_CA", "zh_CN"], "zh-CN"),(["ja_JP", "zh_TW"], "zh-TW"), (["ja_JP", "en_US"], "ja"), ([], "zh-CN")):self.assertEqual(mine, support.my_language(prefs), prefs)@@ -419,15 +401,12 @@ class Hearing(Base):self.assertEqual("Hello", clean_translation("Here is the translation:\nHello", "en"))self.assertIsNone(clean_translation("请提供需要翻译的字幕内容", "en"))self.assertIsNone(clean_translation("Hello", "zh-CN"))- # Ling translated the fixed "Translate." instruction instead of the subtitle.self.assertIsNone(clean_translation("翻译。", "zh-CN"))self.assertIsNone(clean_translation("Translate.", "en"))self.assertEqual("好的,翻译。", clean_translation("好的,翻译。", "zh-CN"))self.assertEqual("Done.", clean_translation("<think>x</think>Done.", "en"))def test_an_unreachable_service_is_tried_once_in_15_seconds(self):- # Translator.swift › lingWorthTrying: while the check says the text model is out of reach,- # lines go straight to Google but for one in 15 s; a hear model at its own address doesn't count.from cicada.core import aichecktried = []@@ -500,34 +479,22 @@ class Segmenting(Base):self.assertAlmostEqual(got[1].start, got[0].start + got[0].seconds, delta=0.001)def test_key_clicks_are_not_speech(self):- # Clicks in a pause don't hold it open: the sentences either side stay apart.got = cut(tone(2.0), keys(1.5), tone(1.5), silence(1.0))self.assertEqual(2, len(got))self.assertAlmostEqual(3.35, got[1].start, delta=0.06)- # Nor does typing alone make a segment.self.assertEqual(0, len(cut(silence(0.5), keys(3.0), silence(1.0))))def test_ignores_clicks(self):self.assertEqual(0, len(cut(silence(1.0), tone(0.1), silence(1.0))))self.assertEqual(0, len(cut(tone(3.0, 0.002))))- # A steady hum over the gate isn't speech: Ming would make up a sentence for it.self.assertEqual(0, len(cut(tone(3.0, 0.02, syllables=False), silence(1.0))))self.assertEqual(1, len(cut(tone(3.0), silence(1.0))))- # Quiet speech, whose dips fall below the gate, is too.self.assertEqual(1, len(cut(tone(3.0, 0.03), silence(1.0))))- # A voice whose loudest frames barely clear the gate still dips far between syllables…self.assertEqual(1, len(cut(tone(3.0, 0.022), silence(1.0))))- # …a hum at the gate that slowly rises and falls doesn't.self.assertEqual(0, len(cut(tone(4.0, 0.016, syllables=False, wobble=0.3), silence(1.0))))- # A word on its own, out of quiet and back: quiet ("Thanks.", 0.2 s over the gate) or one- # smooth run of voice ("Good morning everyone,", no dips inside) is still a word…self.assertEqual(1, len(cut(silence(1.0), word(0.4, 0.028), silence(1.0))))self.assertEqual(1, len(cut(silence(1.0), word(1.2, 0.022), silence(1.0))))- # A quiet word's flat top whose fade (an "s", a breath) falls under gate / 4 still swells:- # Samantha's "Good morning everyone." opening a meeting at -34 dBFS was dropped.self.assertEqual(1, len(cut(silence(1.0), tone(0.5, 0.022, syllables=False), tone(0.15, 0.0025, syllables=False), silence(1.0))))- # Wherever the 30 ms frames fall (a few ms more lead-in), a quiet phrase with brief dips between- # its words stays a word, and a hum or a faded hiss in silence stays out.flat = lambda s, a: tone(s, a, syllables=False)phrase = flat(0.35, 0.022) + flat(0.04, 0.0055) + flat(0.4, 0.022) + flat(0.04, 0.0055) + flat(0.35, 0.022) + flat(0.06, 0.0025)for ms in range(0, 30, 2):@@ -535,11 +502,8 @@ class Segmenting(Base):self.assertEqual(1, len(cut(lead, phrase, silence(1.0))), ms)self.assertEqual(0, len(cut(lead, flat(1.0, 0.03), silence(1.0))), ms)self.assertEqual(0, len(cut(lead, hiss(1.0, 0.03), silence(1.0))), ms)- # …a short hum in silence, which doesn't swell and fade, isn't; nor is a knock.self.assertEqual(0, len(cut(silence(1.0), tone(1.0, 0.03, syllables=False), silence(1.0))))self.assertEqual(0, len(cut(silence(1.0), word(0.15, 0.3), silence(1.0))))- # Rumble far under 100 Hz is no voice however it swells (Ming makes sentences of it); a- # voice as low as 100 Hz keeps half its energy over the high-pass and stays.self.assertEqual(0, len(cut(silence(1.0), hz(12, 3.0, 0.1), silence(1.0))))self.assertEqual(1, len(cut(silence(1.0), hz(100, 3.0, 0.3), silence(1.0))))@@ -558,7 +522,6 @@ class Notes(Base):self.assertEqual([t.name for t in NoteTerm.keeping_order(terms("A,B,C"), terms("E,B,D"))], ["B", "E", "D"])def test_status_follows_the_key_as_on_the_mac(self):- # A key the check refused is "invalid", not "no key"; a fixed key goes back to idle.from cicada.core import ling as lingmodstore = SessionStore()ling = client(Fake(lambda body: reply("{}")))@@ -575,8 +538,6 @@ class Notes(Base):self.assertEqual(notesmod.IDLE, notes.status)def test_final_pass_settles(self):- """存到文件夹 waits while the final pass is to come or running, and hears when it is over, with- notes or without (no lines, a failed reply)."""store = SessionStore()ling = client(Fake(lambda body: reply("not json")))notes = NotesEngine(ling, store)@@ -595,8 +556,6 @@ class Notes(Base):self.assertEqual([s.id, "nothing-here"], done)def test_unreachable_is_the_notes_own_and_clears_when_the_service_answers(self):- # NotesWindow.swift › banner: only the notes' own network failure says "can't reach", it ends- # when anything reaches the service again, and a record opened later doesn't inherit it.store = SessionStore()down = [True]@@ -621,7 +580,6 @@ class Notes(Base):self.assertEqual(notesmod.IDLE, notes.status, "no meeting going on: a failed round isn't the record's")def test_notes_language_as_on_the_mac(self):- # "mine" or "source"; one meeting's choice over the setting; a change while live rewrites.store = SessionStore()settings = AppSettings(target="zh-CN", notesLanguage="source")ling = client(Fake(lambda body: reply("{}")))@@ -680,8 +638,6 @@ class Notes(Base):self.assertIsNone(notesmod.parse("{}", [], 0.0))def test_terms_keep_only_forms_the_recognizer_wrote(self):- """A heard form only a fix wrote ("platform" for 平台) isn't one: it would teach the translator- and the next fix the same mistake."""l = TranscriptLine(id="a", t=0, speaker="them", src="我们 twoty 平台", dst=None, srcLang="zh-CN", dstLang="en")l.fixes = [LineFix("平台", "platform")]terms = [NoteTerm(name="X平台", note="n", heard=["Xplatform", "platform", "Twoty"])]@@ -712,8 +668,6 @@ class Notes(Base):self.assertTrue(notesmod.written(MeetingNotes(summary="讨论发布 Stripe"), "Simplified Chinese"))self.assertFalse(notesmod.written(MeetingNotes(summary="We talked"), "Simplified Chinese"))- # Live notes rewrite only their last topics, so a long meeting's reply stays small (NotesTests.swift).-@staticmethoddef _topic(start, title, points=("p",), times=None):return NoteTopic(start=float(start), title=title, summary="s", points=list(points), pointTimes=times)@@ -724,12 +678,10 @@ class Notes(Base):def test_keeps_frozen_topics_and_takes_the_replys_tail(self):old = [self._topic(i * 100, "t%d" % i) for i in range(5)]- # The model echoed everything, renamed the current topic and added one.reply = [self._topic(0, "t0"), self._topic(100, "t1 改"), self._topic(300, "t3"), self._topic(400, "t4 改"), self._topic(500, "t5")]self.assertEqual(["t0", "t1", "t2", "t3", "t4 改", "t5"], [t.title for t in notesmod.merge(old, 3, reply)])def test_nothing_frozen_keeps_every_topic(self):- # The first update over many lines: nothing to echo, so every topic is the model's own.reply = [self._topic(i * 100, "t%d" % i) for i in range(5)]self.assertEqual(reply, notesmod.merge([], 0, reply))self.assertEqual(reply, notesmod.merge([self._topic(0, "t0")], 0, reply))@@ -740,8 +692,6 @@ class Notes(Base):self.assertEqual(old, notesmod.merge(old, 1, [self._topic(0, "a")]))def test_full_live_notes_join_the_shortest_settled_pair(self):- # Twelve topics, t3 and t4 the shortest neighbours (t3 to t5 is 100 s): a new topic still- # starts, and those two become one.starts = [0, 100, 200, 300, 330, 400, 600, 700, 800, 900, 1000, 1100]old = [self._topic(x, "t%d" % i, ["a%d" % i, "b%d" % i, "c%d" % i]) for i, x in enumerate(starts)]reply = [self._topic(1000, "t10"), self._topic(1100, "t11"), self._topic(1200, "t12")]@@ -770,7 +720,6 @@ class Notes(Base):self.assertTrue("第二个话题" in json and "当前话题" in json)self.assertIn("returning only the topics in the current notes and at most one new one after them", p)self.assertNotIn("in total. A topic", p)- # A full rewrite has nothing frozen.self.assertNotIn("Earlier topics", notesmod.prompt(notes, self._lines(24), 20, "Simplified Chinese", False))def test_live_prompt_asks_for_one_sentence_summaries(self):@@ -780,7 +729,6 @@ class Notes(Base):self.assertIn("never append to it", p)def test_long_meetings_split_by_time(self):- # A line every 10 s: 90 min stays whole, 4 h becomes four parts of an hour.self.assertEqual([range(0, 540)], notesmod.parts(self._lines(540)))four = notesmod.parts(self._lines(1440))self.assertEqual(4, len(four))@@ -799,7 +747,6 @@ class Notes(Base):self.assertIn('Part 2 of 2:\n{"summary":"b"}', merge)self.assertIn("Return the full notes as one JSON object", merge)self.assertIn('"topics": []', merge)- # Each of three parts gets two of the eight topics.self.assertIn("use at most 2 topics", p)def test_topic_starts_when_its_lines_were_said(self):@@ -819,22 +766,18 @@ class Notes(Base):self.assertEqual(3, len(notesmod.thinned(ten[:3], 4, 3000)))def test_part_topics_keep_a_topic_over_its_continuation(self):- # A 2.5-hour meeting's last part, asked for 2 topics, came back with 3: the budget topic's- # end as its own. Kept first and last, the budget topic at 125 min was lost.part = [self._topic(6000, "营销发布安排", ["a"]), self._topic(7500, "预算评审", ["b"]),self._topic(8982, "预算评审(续)", ["c"])]kept = notesmod.thinned(part, 2, 8990)self.assertEqual(["营销发布安排", "预算评审"], [t.title for t in kept])self.assertEqual([6000, 7500], [t.start for t in kept])self.assertEqual(["b", "c"], list(kept[1].points))- # Told apart by time alone, the stub still joins the topic it ends.other = [self._topic(6000, "营销发布安排"), self._topic(7500, "预算评审"), self._topic(8982, "收尾")]self.assertEqual([6000, 7500], [t.start for t in notesmod.thinned(other, 2, 8990)])self.assertEqual("Budget review", notesmod.subject("Budget review (cont.)"))self.assertEqual("(续)", notesmod.subject("(续)"))def test_long_final_in_parts_then_merged(self):- # Four hours: four part calls at once, then one merge; topics come from the parts.store = SessionStore()s = store.begin()for l in self._lines(1440):@@ -859,13 +802,10 @@ class Notes(Base):self.assertIn("Part 4 of 4:", asked[-1])self.assertNotIn("话题1-0", asked[-1], "the parts go to the merge without their topics")self.assertEqual("全程讨论", n.summary)- # Three topics a part, two asked for: the pair spanning the least time is joined.self.assertEqual([t for k in range(1, 5) for t in ("话题%d-0 / 话题%d-1" % (k, k), "话题%d-2" % k)], [t.title for t in n.topics])self.assertTrue(n.final)def test_notes_prompt_matches_the_android_port(self):- """The same prompt text as android/core Notes.kt, checked against its source so a change- on one side shows up here."""src = os.path.join(REPO, "android/core/src/main/kotlin/cicada/Notes.kt")if not os.path.isfile(src):self.skipTest("no Android source")@@ -873,7 +813,6 @@ class Notes(Base):kt = f.read()p = notesmod.prompt(MeetingNotes(), [TranscriptLine(t=1.0, src="x")], 0, "English", final=True)for rule in [l for l in p.split("\n") if l.startswith("- ")]:- # The topic limit is filled in (live and final differ): check the rule from after it.rule = rule.split("in total. ", 1)[-1] if rule.startswith("- Topics in time order") else ruleprobe = rule.replace('"', '\\"')[:60]self.assertIn(probe, kt, rule)@@ -888,18 +827,17 @@ class Strings(Base):self.assertEqual("2 lines", strings.LF("%lld 句", 2))self.assertEqual("0 lines", strings.LF("%lld 句", 0))self.assertEqual("Heard 1 line", strings.LF("已听到 %lld 句", 1))- self.assertEqual("Standup · 1 line", strings.LF("%@ · %lld 句", "Standup", 1)) # positional %2$#@n@+ self.assertEqual("Standup · 1 line", strings.LF("%@ · %lld 句", "Standup", 1))self.assertEqual("Recorded 03:15 · 7 lines. Ending stops listening and writes the full notes.",strings.LF("已记录 %@ · %lld 句。结束后停止收听,并整理一份完整版纪要。", "03:15", 7))self.assertEqual("1 line", strings.LF("说了 %lld 句", 1))self.assertEqual("Live notes", strings.L("实时纪要"))strings.load("ja", res)- self.assertEqual("1文", strings.LF("%lld 句", 1)) # no stringsdict: the .strings value+ self.assertEqual("1文", strings.LF("%lld 句", 1))finally:strings.load("zh-Hans", res)def test_todo_owner_in_the_ui_language(self):- # The notes store the transcript's Chinese label; it shows in the UI language (Notes.swift's withOwner).res = [os.path.join(REPO, "Resources"), os.path.join(REPO, "linux", "strings")]todo = lambda owner: NoteItem(text="Ship it", owner=owner)try:@@ -961,8 +899,6 @@ class Ling(Base):self.assertEqual(LingError.HIJACKED, e.exception.kind)def test_heard_audio_rides_out_a_run_of_429s(self):- # Ling's 429s come in runs (two in a row lost a line with one retry): heard audio backs off- # 1, 2, 4 s and gets through; text translation fails at once so the caller can fall back.clock = FakeClock()replies = [Response(429, "")] * 3 + [reply("LANG: en\nORIGINAL: Hi.\nTRANSLATION: 嗨。")]fake = Fake(lambda b: replies.pop(0))@@ -993,7 +929,6 @@ class Ling(Base):replies = [Response(429, "", retry_after="5"), reply("ok")]self.assertEqual("ok", client(Fake(lambda b: replies.pop(0)), clock).chat("c", "i", NOTES))self.assertTrue(5 <= clock.waits[0] <= 5.5, clock.waits)- # Asked to wait minutes: an outage, so the line goes now rather than after it.fake = Fake(lambda b: Response(429, "", retry_after="120"))with self.assertRaises(LingError):client(fake, FakeClock()).chat("c", "i", TRANSLATE, model=AUDIO_MODEL, audio=bytes([1]))@@ -1011,12 +946,10 @@ class Ling(Base):ling = client(fake, clock)with self.assertRaises(LingError):ling.chat("first", "i", TRANSLATE)- # A translation that wouldn't retry fails at once, without spending a request on the limit...with self.assertRaises(LingError) as e:ling.chat("second", "i", TRANSLATE)self.assertEqual(LingError.RATE_LIMITED, e.exception.kind)self.assertEqual(1, len(fake.calls))- # ...and one that would waits at the gate until the pause is over, then goes.self.assertEqual("notes", ling.chat("notes", "i", NOTES))self.assertEqual(2, len(fake.calls))self.assertTrue(1 <= clock.waits[0] <= 1.5, clock.waits)@@ -1041,7 +974,6 @@ class Ling(Base):for t in (a, b):t.join()self.assertEqual(["a", "a", "b"], [content(x[1], 0) for x in fake.calls])- # b, queued during the pause, didn't start until it was over.self.assertGreaterEqual(fake.calls[2][0] - fake.calls[0][0], 1.0)def test_marks_a_bad_key(self):@@ -1059,7 +991,6 @@ class Ling(Base):a = threading.Thread(target=ling.chat, args=("first", "i", NOTES))a.start()time.sleep(0.02)- # Queued while the gate is closed: the translation goes before the earlier notes call.b = threading.Thread(target=ling.chat, args=("notes", "i", NOTES))b.start()time.sleep(0.02)@@ -1074,8 +1005,6 @@ class Ling(Base):class Listening(Base):def test_end_to_end_with_a_fake_ming(self):- # Two stretches of "speech", told apart by length (1 s, then 1.6 s); the fake Ming answers- # the first one slower, and lines still come out in order.def respond(body):if "Ming-3.0-audio-flash" in body:url = content(body, 1)[0]["audio_url"]["url"]@@ -1104,8 +1033,6 @@ class Listening(Base):self.assertIsNotNone(s.endedAt)def test_server_errors_in_a_row_are_said_and_clear_on_the_next_line(self):- # A gateway answering 502 to every stretch: no subtitles, so from the third in a row the notes- # window says the service is erring (not the network); the next stretch heard clears it.heard = []seen = []@@ -1121,7 +1048,6 @@ class Listening(Base):store = SessionStore()engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target="zh-CN"))engine.on_change(lambda: seen.append(engine.problem))- # Four times real time: each reply is back before the next stretch goes, as in a meeting.src = PcmAudioSource(lambda: concat(*[x for _ in range(4) for x in (tone(1.0), silence(3.0))]), speed=4)ended = threading.Event()src.on_ended = lambda why: ended.set()@@ -1161,8 +1087,6 @@ class Listening(Base):self.assertEqual([], [p for p in seen if p], "two blips: nothing to say yet")def test_follow_system_translates_my_own_language_into_the_next(self):- # They speak Chinese, my language: the first stretch was asked for Chinese (nothing heard- # yet), so its translation is dropped for the text translation; the next is asked for English.asked = []def respond(body):@@ -1176,7 +1100,6 @@ class Listening(Base):settings = AppSettings()settings.resolved_target = lambda src: "en" if src == "zh-CN" else "zh-CN"engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), settings)- # Four times real time: the first reply is back before the second stretch is sent, as in a meeting.src = PcmAudioSource(lambda: concat(tone(1.0), silence(3.0), tone(1.6), silence(1.0)), speed=4)ended = threading.Event()src.on_ended = lambda why: ended.set()@@ -1263,7 +1186,6 @@ class Speaking(Base):self.assertIsNotNone(eng.problem)def test_a_filler_alone_is_not_spoken(self):- # A hush or an echo's tail cut as a segment: Ming hears 嗯 and the room would hear "Hmm."eng, fake, player = self._engine("ORIGINAL: 嗯。\nTRANSLATION: Hmm.")self._say(eng, concat(tone(1.2), silence(1.0)))self.assertEqual(0, eng.spoken)@@ -1280,7 +1202,7 @@ class Speaking(Base):def write(pcm, _w=player.write):if not fetched:fetched.append(len(fake.spoken))- slow.wait(1.5) # the first sentence still playing+ slow.wait(1.5)fetched.append(len(fake.spoken))_w(pcm)player.write = write@@ -1302,7 +1224,6 @@ class Speaking(Base):todos=[NoteItem(text="发说明", owner="你")], terms=[NoteTerm(name="Ling", note="模型")])local = s.startedAt.astimezone()when = "%d年%d月%d日 %02d:%02d" % (local.year, local.month, local.day, local.hour, local.minute)- # TranscriptExport.markdown on the Mac, character for character.self.assertEqual("# %s\n\n%s · 24 分钟\n\n" % (session_store.display_title(s), when) +"## 纪要\n\n定了周五。\n\n### 00:00 上线时间\n\n讨论日期\n\n- 周五\n\n**为什么推迟?**\n\n- 测试:还没跑完\n\n"@@ -1332,8 +1253,6 @@ class Speaking(Base):self.assertIsNotNone(eng.problem, "and the user is told")def test_through_the_echo_canceller_talking_over_them_goes_out(self):- # The talk key read the microphone through module-echo-cancel: their voices are taken out,- # so what I say over them is mine and is sent (the Mac's rule since 96205f8).class Listening:listening = Truespoken = "en"@@ -1406,7 +1325,6 @@ def them(i, voice, text="we should ship this on Friday", t=None):class Speakers(Base):def test_the_voiceprint_is_the_macs(self):- # The C library against the Mac's Core ML model on the same audio (linux/tests/voiceprint-ref.json).import jsonimport waveif speakers.library_path() is None or speakers.model_path() is None:@@ -1455,7 +1373,7 @@ class Speakers(Base):self.assertEqual({2: "George"}, speakers.names(got))self.assertEqual("说话人 1", speakers.label(1, speakers.names(got)))store.set_voice_name(s.id, 0, "Emma")- store.set_voice_name(s.id, 1, "") # 不是 TA: 说话人 2 again+ store.set_voice_name(s.id, 1, "")self.assertEqual({1: "Emma"}, speakers.names(store.get(s.id)))store.merge_voice(s.id, 2, 0)self.assertEqual(6, sum(1 for l in store.get(s.id).lines if l.voice == 0))@@ -1485,7 +1403,6 @@ class Speakers(Base):self.assertTrue(found[1].evidence.startswith("00:40 “Thanks"))self.assertEqual({0: "Christina"}, refuted)self.assertEqual(({}, {}), speakers.read("not json", s))- # Without JSON mode (a host that refuses it) the reply may come fenced.fenced, _ = speakers.read('```json\n{"speakers": [{"speaker": 2, "name": "George", "evidence": "L11"}]}\n```', s)self.assertEqual("George", fenced[1].name)self.assertIn("说话人1", speakers.content(s))@@ -1499,9 +1416,7 @@ class Speakers(Base):self.assertIn("对方] ", notesmod.prompt(MeetingNotes(), lines, 0, "Chinese", False))def _halves(self, voices):- # Ming cuts "so we will ship" | "on Friday then." mid-sentence; `voices` says whose each half is.def respond(body):- # Both halves go to Ming at once: answer by the audio's length (1.0 s, then 1.4 s).if "Ming-3.0-audio-flash" not in body:return reply("{}")first = len(content(body, 1)[0]["audio_url"]["url"]) < 60000@@ -1550,7 +1465,7 @@ class Speakers(Base):passdef embed(self, samples):- time.sleep(0.6) # a CPU that can't keep up+ time.sleep(0.6)return [1.0]def label(self, vector, seconds):diff --git a/linux/tests/test_custom.py b/linux/tests/test_custom.pyindex 7f24e60..ed5c89d 100644--- a/linux/tests/test_custom.py+++ b/linux/tests/test_custom.py@@ -1,7 +1,3 @@-"""其他(兼容 OpenAI)for self-hosted models (AIProviderTests.swift): plain http on the local network,-thinking turned off through the chat template (and left out for a server that refuses it), the-check's real sentence and what it says about a thinking model, and the hear model at an address of-its own."""from __future__ import annotationsimport os@@ -81,7 +77,6 @@ class Shape(unittest.TestCase):return rootself.assertFalse(providers.thought(r({"content": "周五发布。"})))self.assertTrue(providers.thought(r({"content": "周五发布。", "reasoning_content": "The user wants…"})))- # A reasoning parser on the server: the answer itself sits in reasoning_content.self.assertTrue(providers.thought(r({"content": "", "reasoning_content": "周五发布。"})))self.assertTrue(providers.thought(r({"content": "周五发布。", "reasoning": "hmm"})))self.assertTrue(providers.thought(r({"content": "<think>hmm</think>周五发布。"})))@@ -102,7 +97,6 @@ class Shape(unittest.TestCase):self.assertIn("4.2", r.slow_line())self.assertIn("思考", r.slow_line())self.assertIn("Google", r.slow_line())- # 语音和文字只发给你的服务: no Google to fall back on, the sentence is given up on.self.assertNotIn("Google", r.slow_line(google_off=True))self.assertIn("不等它了", r.slow_line(google_off=True))self.assertIn("思考", r.slow_line(google_off=True))@@ -113,7 +107,6 @@ class Shape(unittest.TestCase):r.translate = aicheck.Speed(0.5, False)self.assertIsNone(r.slow_line())self.assertIn("translate=0.5s", r.summary())- # The hear model is a job of its own: not filled in yet, it doesn't hide a thinking text model.r = aicheck.AICheck()r.pass_up_to("text", 4.2)r.translate = aicheck.Speed(4.2, True)@@ -143,15 +136,12 @@ class TemplateKwargs(Base):self.assertEqual(2, len(fake.sent))self.assertIn("chat_template_kwargs", fake.sent[0][1])self.assertNotIn("chat_template_kwargs", fake.sent[1][1])- # Not sent there again…ling.chat("x", "Translate.", TRANSLATE)self.assertEqual(3, len(fake.sent))self.assertNotIn("chat_template_kwargs", fake.sent[2][1])- # …until settings change.ling.key_changed()ling.chat("x", "Translate.", TRANSLATE)self.assertIn("chat_template_kwargs", fake.sent[3][1])- # A refused request never showed as a missing model.self.assertIsNone(ling.check_result.failure)def test_a_400_both_ways_is_not_the_field(self):@@ -163,11 +153,9 @@ class TemplateKwargs(Base):self.assertEqual(2, len(fake.sent))fake.respond = lambda u, b: answer()ling.chat("x", "Translate.", TRANSLATE)- self.assertIn("chat_template_kwargs", fake.sent[-1][1]) # nothing remembered+ self.assertIn("chat_template_kwargs", fake.sent[-1][1])def test_a_refusal_for_something_else_keeps_thinking_off(self):- # No JSON mode on this server (OpenRouter's Novita for Ling 3.1 Flash): 400 with or without- # the kwargs. Asked again without JSON mode.fake = Fake(lambda u, b: Response(400, "{}") if "response_format" in b else answer("好"))ling, _ = self.client(fake, "custom", key=None, **custom())self.assertEqual("好", ling.chat("x", "Notes.", TRANSLATE, json=True))@@ -222,7 +210,6 @@ class Check(Base):ling, _ = self.client(Fake(respond), "custom", key=None, **custom())ling.check()self.assertIsNone(ling.check_result.failure)- # One that can't answer JSON at all still fails.fake = Fake(lambda u, b: Response(404, "") if u.endswith("/models") else Response(400, "{}") if "response_format" in b else answer())ling, _ = self.client(fake, "custom", key=None, **custom())ling.check()@@ -252,7 +239,6 @@ class HearAddress(Base):self.assertEqual("http://192.168.1.30:8001/v1/", c.hear_url)self.assertEqual("http://192.168.1.20:8000/v1/", c.base)self.assertTrue(c.own_hear_address)- # Typed but not valid: nowhere to send audio (not the text address).c = AppSettings(aiProvider="custom", **custom(aiCustomHearBase="http://gpu.example.com/v1")).ai_config()self.assertIsNone(c.hear_url)z = AppSettings(aiProvider="zenmux", aiCustomHearBase="http://192.168.1.30/v1").ai_config()@@ -296,8 +282,6 @@ class HearAddress(Base):class AuthFake(Fake):- """Fake, also keeping the key each request carried (`auth`, in order)."""-def __init__(self, respond):super().__init__(respond)self.auth = []@@ -311,8 +295,6 @@ 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"},@@ -328,11 +310,9 @@ class NotesApart(Base):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])@@ -344,7 +324,6 @@ class NotesApart(Base):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)@@ -361,7 +340,6 @@ class NotesApart(Base):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_resultself.assertEqual(aicheck.INVALID_KEY, r.notes.reason)self.assertIsNone(r.failure)@@ -369,7 +347,6 @@ class NotesApart(Base):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)@@ -382,25 +359,21 @@ class NotesApart(Base):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.+ self.assertTrue(c.notes_apart)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 = Trueself.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)@@ -418,9 +391,7 @@ class NotesApart(Base):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)@@ -443,13 +414,11 @@ class NotesApart(Base):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") elseanswer('{"ok": true}' if "JSON object" in b else "周五发布。"))ling.notes_key_file.save("sk-notes-222222222")@@ -470,13 +439,11 @@ class NotesApart(Base):class StubLing:- """The service, for the translator alone: answers each sentence, or fails."""-def __init__(self, answer=None):self.usable = True- self.answer = answer # None: the service can't be reached+ self.answer = answerself.asked = []- self.check_result = aicheck.AICheck() # not checked yet: every sentence is tried+ self.check_result = aicheck.AICheck()def chat(self, prompt, user, priority, **kw):self.asked.append(prompt)@@ -489,8 +456,6 @@ GOOGLE = Response(200, '[[["周五发布。","We ship on Friday",null,null,1]]]'class GoogleOff(unittest.TestCase):- """语音和文字只发给你的服务 (issue #15, TranslatorTests.swift › GoogleOffTests): Google is never asked."""-def translator(self, ling, google=GOOGLE):from cicada.core.translator import Translatorfake = Fake(lambda u, b: google)@@ -504,7 +469,7 @@ class GoogleOff(unittest.TestCase):for _ in range(3):self.assertIsNone(t.translate("We ship on Friday", "en", "zh-CN", Translator.DRAFT))self.assertEqual([], fake.sent)- self.assertEqual([], ling.asked) # partial text never goes to the AI service either+ self.assertEqual([], ling.asked)self.assertFalse(t.sentences_untranslated)def test_finished_sentences_go_to_the_service_only(self):@@ -544,7 +509,7 @@ class GoogleOff(unittest.TestCase):s = AppSettings(aiProvider="custom", aiCustomOnly=True, **custom())self.assertTrue(s.google_off)s.aiProvider = "ling"- self.assertFalse(s.google_off) # kept, but inert+ self.assertFalse(s.google_off)self.assertTrue(s.aiCustomOnly)self.assertFalse(AppSettings(aiProvider="custom", **custom()).google_off)diff --git a/linux/tests/test_fixes.py b/linux/tests/test_fixes.pyindex 08e5bc6..76759f8 100644--- a/linux/tests/test_fixes.py+++ b/linux/tests/test_fixes.py@@ -1,6 +1,3 @@-"""改正听错的词: the record's fixes, read and written as the Mac does (mac-fixes-session.json is a record-the Mac dev build wrote), and the line as shown in display, search and export.- python3 -m unittest discover -s linux/tests (scripts/test.sh)"""from __future__ import annotationsimport os@@ -53,7 +50,7 @@ class RecordFormat(Base):s = Session(id="x", title="t", lines=[line])self.assertNotIn("fixes", s.write())line.fixes = []- self.assertNotIn("fixes", s.write()) # none is absent, as the Mac stores nil+ self.assertNotIn("fixes", s.write())line.fixes = [LineFix("a", "b")]back = Session.read(s.write()).lines[0]self.assertEqual(back.shown, "b")@@ -104,15 +101,12 @@ def verdict(frm, to, c, known=(), rejected=()):class Correction(unittest.TestCase):- """The Mac's CorrectionTests: cases from a 21-minute meeting recording (a DeFi team's weekly)."""-def test_sound_alike_chinese_is_applied(self):self.assertEqual(verdict("解除质压", "解除质押", 0.9), APPLY)- self.assertNotEqual(verdict("跳便是", "跳变", 0.9), APPLY) # a word dropped: not a sound fix+ self.assertNotEqual(verdict("跳便是", "跳变", 0.9), APPLY)self.assertEqual(verdict("两个代笔", "两个代币", 0.9), APPLY)self.assertEqual(verdict("管理房", "管理方", 0.9), APPLY)self.assertEqual(verdict("追压", "质押", 0.85), APPLY)- # Only the changed part is compared: 花/概 share nothing, though the phrase around them does.self.assertEqual(verdict("花了大花", "花了大概", 0.85), DROP)self.assertEqual(verdict("FFT制押", "FFT质押", 0.9), APPLY)@@ -127,7 +121,7 @@ class Correction(unittest.TestCase):def test_spelling_fix_needs_high_confidence(self):self.assertEqual(verdict("cransfer", "transfer", 0.85), APPLY)self.assertEqual(verdict("cransfer", "transfer", 0.7), DROP)- self.assertEqual(verdict("bos", "BOS", 0.9), DROP) # case only+ self.assertEqual(verdict("bos", "BOS", 0.9), DROP)def test_new_names_are_asked(self):self.assertEqual(verdict("莫拉", "Morpho", 0.85), ASK)@@ -136,7 +130,6 @@ class Correction(unittest.TestCase):self.assertEqual(verdict("莫纳", "Morpho", 0.7), DROP)def test_learned_words_stay_whole(self):- """A learned "S平 → X平" never reaches into "iOS平台"; on its own it still applies."""self.assertEqual(correction.word("S平", "iOS平台很好"), -1)self.assertEqual(correction.word("A工", "DATA工具"), -1)self.assertNotEqual(correction.word("S平", "在S平台上"), -1)@@ -145,7 +138,6 @@ class Correction(unittest.TestCase):self.assertEqual(apply([LineFix("S平", "X平")], "iOS平台和S平台")[0], "iOS平台和X平台")def test_translations_are_not_asked(self):- """A translation isn't a misheard name: one 对 to "X平台 → X platform" taught 平台 → platform."""self.assertEqual(verdict("X平台", "X platform", 0.9), DROP)self.assertEqual(verdict("平台", "platform", 0.95), DROP)self.assertEqual(verdict("respons", "responsible", 0.85), DROP)@@ -167,7 +159,6 @@ class Correction(unittest.TestCase):self.assertEqual(core("Un450P三", "Uniswap V3"), ("Un450P三", "Uniswap V3"))self.assertEqual(core("解释这个莫拉的", "解释这个Morpho的"), ("莫拉", "Morpho"))self.assertEqual(core("找了cransfer记录", "找了transfer记录"), ("cransfer", "transfer"))- # A Chinese change next to a Latin word leaves the word out.self.assertEqual(core("FFT制押", "FFT质押"), ("制押", "质押"))def test_pinyin_is_the_macs(self):@@ -218,30 +209,23 @@ class Correction(unittest.TestCase):self.assertEqual(correction.label(LineFix("解除质压", "解除质押")), ("质压", "质押"))def test_added_word_stays_on_its_line_and_never_matches_punctuation(self):- # "now" added before the full stop: the fix is the last word, unique in the line, not ".".line = "Great, let's lock that in."fix, _, swap = correction.user_edit(line, "Great, let's lock that in now.", line, [])self.assertEqual((fix.from_, fix.to, swap), ("in", "in now", False))self.assertEqual(apply([fix], line)[0], "Great, let's lock that in now.")- # A word added at the start.fix, _, swap = correction.user_edit(line, "OK Great, let's lock that in.", line, [])self.assertEqual((fix.from_, fix.to, swap), ("Great", "OK Great", False))- # A word that appears twice: grown until the span is unique.line = "in the room in the hall"fix = correction.user_edit(line, "in the room inside the hall", line, [])[0]self.assertEqual(apply([fix], line)[0], "in the room inside the hall")- # Chinese: an inserted word takes its neighbour.line = "好的我来看一下"fix, _, swap = correction.user_edit(line, "好的OK我来看一下", line, [])self.assertEqual(apply([fix], line)[0], "好的OK我来看一下")self.assertFalse(swap)- # A real swap is still a swap.self.assertTrue(correction.user_edit("我木娜找了", "我Monad找了", "我木娜找了", [])[2])class Vocab(Base):- """The Mac's VocabularyTests."""-def test_import_lines_with_heard_forms(self):v = Vocabulary(None)r = v.import_text("Uniswap V3\nMorpho = 莫拉、莫法\n\n" + "长" * 41 + "\n巡检=寻检,巡练")@@ -298,7 +282,7 @@ class Vocab(Base):text = f.read()self.assertTrue(text.startswith('[\n {\n "fixes" : 1,\n "heard" : [\n "莫拉"\n ],\n "source" : "user",\n'' "used" : "2026-11-07T07:08:01Z",\n "word" : "Morpho"\n },'))- self.assertIn('"word" : "A/B"', text) # slashes unescaped, as the Mac's encoder writes them+ self.assertIn('"word" : "A/B"', text)self.assertIn('"heard" : [\n\n ]', text)def test_reads_the_macs_file(self):@@ -332,9 +316,6 @@ class Vocab(Base):class Live(Base):- """The Mac's LiveFixesTests: who wins on a line, the user's decisions, then the word list, then the- recheck, then the first guess."""-def setup(self, texts):store = session_store.SessionStore()s = store.begin()@@ -367,7 +348,6 @@ class Live(Base):self.assertEqual(fx.edit("l0", sid, "我Monad找了一个", everywhere=True, remember=True), 2)self.assertEqual(store.line(sid, "l1").shown, "Monad那边也有")self.assertTrue(fx.vocabulary.knows("木娜", "Monad"))- # A later pass can't override what the user wrote.fx.received(store.line(sid, "l1").src, [Edit("木娜", "Mona", 0.95)])self.assertEqual(store.line(sid, "l1").shown, "Monad那边也有")fx.undo()@@ -445,9 +425,6 @@ class Live(Base):class Request(Base):- """The translation request with fixes: the Mac's prompt word for word, no JSON mode, and a reply- that isn't the JSON asked for falls through like a failed one."""-def test_prompt_and_reply(self):from test_core import Fake, client, replybodies = []diff --git a/linux/tests/test_folder_export.py b/linux/tests/test_folder_export.pyindex 198c3c1..723bc71 100644--- a/linux/tests/test_folder_export.py+++ b/linux/tests/test_folder_export.py@@ -1,5 +1,3 @@-"""存到文件夹: the file name and frontmatter are a contract with the Mac and the other ports-(Tests/fixtures/folder-export), then the exporter against a folder in a temporary directory."""from __future__ import annotationsimport json@@ -61,7 +59,6 @@ class FormatTests(unittest.TestCase):def test_escapes(self):for given, want in cases()["escapes"]:self.assertEqual(want, fx.quote(given), given)- # Short forms only for \n \r \t; json.dumps would write \b and \f.self.assertEqual('"\\u0008\\u000c\\u001f"', fx.quote("\b\f\x1f"))def test_collisions(self):@@ -69,7 +66,6 @@ class FormatTests(unittest.TestCase):self.assertEqual(c["want"], fx.file_name(c["stem"], lambda n, t=c["taken"]: n in t))def test_name_precedence(self):- """The user's title, else the notes', else the imported file's; never the display title."""s = session()s.renamed = Falses.title = default_title(s.startedAt)@@ -79,7 +75,6 @@ class FormatTests(unittest.TestCase):s.sourceFile = "Weekly sync.m4a"self.assertEqual("Weekly sync", fx.name(s))self.assertIn('source: "file"\nnotes: "none"', fx.frontmatter(s))- # An older record (no `renamed`): any title but the default one is the user's.s.renamed = Nones.title = "周会"self.assertEqual("周会", fx.name(s))@@ -157,21 +152,17 @@ class ExporterTests(unittest.TestCase):self.assertIn("\n---\n# 产品路线评审\n", text)self.assertEqual([], self.ex.index.pending)self.assertEqual(name, self.ex.index.lastFile)- # Unchanged: not written again.mtime = os.stat(os.path.join(self.folder, name)).st_mtime_nsself.ex.saved("20261106-140000")self.ex.wait()self.assertEqual(mtime, os.stat(os.path.join(self.folder, name)).st_mtime_ns)- # Renamed: the file moves.self.store.rename("20261106-140000", "路线")self.store.flush()self.ex.saved("20261106-140000")self.ex.wait()self.assertEqual([name.replace("产品路线评审", "路线")], self.files())- # Deleted in Cicada: the file stays.self.ex.deleted("20261106-140000")self.assertEqual(1, len(self.files()))- # The index survives a restart.self.assertEqual(self.ex.index.folder, self.exporter().index.folder)def test_never_overwrites_a_foreign_file(self):@@ -218,19 +209,19 @@ class ExporterTests(unittest.TestCase):self.ex.wait()self.assertEqual({}, self.ex.index.files)self.assertEqual(2, len(self.ex.unwritten()))- self.assertEqual(2, len(self.files())) # the old folder's files stay+ self.assertEqual(2, len(self.files()))def test_missing_then_back(self):self.ex.choose(self.folder)self.ex.wait()s = self.add()- shutil.rmtree(os.path.dirname(self.folder)) # the drive went+ shutil.rmtree(os.path.dirname(self.folder))self.ex.ended(s.id)self.ex.wait()self.assertEqual(fx.MISSING, self.ex.problem)self.assertEqual([s.id], self.ex.index.pending)self.assertEqual(0, self.denied)- os.makedirs(os.path.dirname(self.folder)) # back: only the last folder is made again+ os.makedirs(os.path.dirname(self.folder))self.ex.retry()self.ex.wait()self.assertIsNone(self.ex.problem)@@ -246,7 +237,7 @@ class ExporterTests(unittest.TestCase):self.ex.write_all()self.ex.wait()self.assertEqual(fx.DENIED, self.ex.problem)- self.assertEqual(0, self.denied) # never for 也存一份+ self.assertEqual(0, self.denied)self.ex.ended("20261106-140000")self.ex.wait()self.ex.ended("20261106-150000")diff --git a/linux/tests/test_hybrid.py b/linux/tests/test_hybrid.pyindex 135615a..97cf8f1 100644--- a/linux/tests/test_hybrid.py+++ b/linux/tests/test_hybrid.py@@ -1,5 +1,3 @@-"""听哪里 on Linux: 会议室 (a microphone in the room) and 电脑和会议室 (both at once), the Mac's-HybridTests / HybridRecordTests case for case where the logic is shared."""from __future__ import annotationsimport threading@@ -74,7 +72,6 @@ class Microphones(Base):self.assertEqual("Jabra SPEAK 510 Mono", usb.description)def test_picks_like_the_mac(self):- # RoomMicPlan: the default unless virtual or a Bluetooth headset's, then the built-in one.inputs = parse_sources(PACTL)usb = "alsa_input.usb-Jabra_Speak_510-00.mono-fallback"built_in = "alsa_input.pci-0000_00_05.0.analog-stereo"@@ -82,10 +79,8 @@ class Microphones(Base):self.assertEqual(built_in, pick("bluez_input.AA_BB_CC_DD_EE_FF.0", inputs))self.assertEqual(built_in, pick("cicada_mic", inputs))self.assertEqual(built_in, pick(None, inputs))- # Chosen in 设置 › 会议室, while it is plugged in.self.assertEqual(usb, pick(built_in, inputs, chosen=usb))self.assertEqual(built_in, pick(built_in, inputs, chosen="gone"))- # Only a headset: better than nothing.bt = [Input("bt", bluetooth=True), Input("cicada_mic", virtual=True)]self.assertEqual("bt", pick("cicada_mic", bt))self.assertIsNone(pick(None, [Input("m", virtual=True)]))@@ -95,13 +90,11 @@ class Microphones(Base):self.assertFalse(fixed.voiced(0.006))g = VoiceGate(adaptive=True)self.assertEqual(0.004, g.threshold)- # Ten seconds of a quiet room (0.001) with talk at 0.006.for i in range(100):g.voiced(0.001 if i % 10 == 0 else 0.006, 0.1)self.assertLess(g.threshold, 0.003)self.assertGreaterEqual(g.threshold, VoiceGate.lowest)self.assertTrue(g.voiced(0.006))- # A loud room: the line never goes over the fixed gate.for _ in range(400):g.voiced(0.05, 0.1)self.assertEqual(VoiceGate.fixed, g.threshold)@@ -125,7 +118,7 @@ def run(e, pcm, mic):class Room(Base):- QUIET = concat(silence(3.5), tone(1.0, amp=0.01), silence(1.0)) # a voice across the table, under -40 dBFS+ QUIET = concat(silence(3.5), tone(1.0, amp=0.01), silence(1.0))def test_a_quiet_voice_in_the_room_is_heard(self):store = SessionStore()@@ -167,7 +160,6 @@ class Room(Base):src = PcmAudioSource(lambda: self.QUIET, speed=0)ended = threading.Event()src.on_ended = lambda why: ended.set()- # Muted before any audio arrives: the worker replaces it with silence.e.start(PcmAudioSource(lambda: silence(0.1), speed=0), "room", mic=True)e.set_muted(True)e.attach(src, mic=True)@@ -183,11 +175,8 @@ def h(text, start, end):class EchoMatchTests(Base):- """The Mac's EchoMatchTests, case for case."""-def test_the_rooms_copy_of_a_remote_sentence_is_an_echo(self):online = [h("Revenue grew by 12%, mostly from the new region.", 10, 14)]- # Heard worse from the speakers, and a word lost.self.assertTrue(EchoMatch.is_echo(h("revenue grew by 12% mostly from new region", 10.3, 14.2), online))def test_cut_differently_still_matches(self):@@ -221,12 +210,9 @@ def line(i, speaker="them", via=None):class Places(Base):- """The Mac's HybridRecordTests."""-def test_only_a_meeting_that_heard_both_shows_places(self):self.assertFalse(heard_both([line("a"), line("b")]))self.assertFalse(heard_both([line("a", via="room"), line("b", via="room")]))- # My own lines (同声传译) don't make it a meeting that heard the computer.self.assertFalse(heard_both([line("a", via="room"), line("b", "me")]))self.assertTrue(heard_both([line("a", via="room"), line("b")]))@@ -240,7 +226,7 @@ class Places(Base):while t < EchoGate.music - 1:g.hold(t)t += 0.1- self.assertTrue(g.closed(t)) # no words yet: still taken for speech+ self.assertTrue(g.closed(t))while t < EchoGate.music + 1:g.hold(t)t += 0.1@@ -248,7 +234,7 @@ class Places(Base):t += EchoGate.hang + 0.01g.hold(t)self.assertFalse(g.closed(t + 0.01))- g.heard_words(t + 0.1) # someone talks over it: words close it again+ g.heard_words(t + 0.1)g.hold(t + 0.2)self.assertTrue(g.closed(t + 0.3))@@ -265,12 +251,12 @@ class Places(Base):def test_headphones_keep_the_room_open(self):g = EchoGate()- self.assertTrue(g.echo) # until measured+ self.assertTrue(g.echo)t = self._play(g, 0, 0.001)self.assertFalse(g.echo)g.hold(t + 1)self.assertFalse(g.closed(t + 1.1))- self._play(g, t + 100, 0.03) # the speakers reach the mic again+ self._play(g, t + 100, 0.03)self.assertTrue(g.echo)self.assertIsNone(EchoGate.ratio([(0.001, 1)], [(0.001, 10)]))@@ -279,7 +265,6 @@ ONLINE = "Revenue grew by 12%, mostly from the new region."def both_engine(store, room_text):- """The computer plays a 1 s sentence; the room mic hears 1.6 s at the same time."""def respond(body):if "Ming-3.0-audio-flash" not in body:return reply("{}")@@ -325,7 +310,6 @@ class Both(Base):self.assertEqual([(None, ONLINE)], [(l.via, l.src) for l in s.lines])def test_a_room_side_started_mid_meeting_keeps_the_meetings_clock(self):- # 听哪里 changed to 电脑和会议室 two seconds in: the room's line is timed after them, not at 00:00.store = SessionStore()e = both_engine(store, "I think we should check the numbers for Europe first.")main = PcmAudioSource(lambda: concat(tone(1.0), silence(1.0)), speed=0)diff --git a/linux/tests/test_meeting_end.py b/linux/tests/test_meeting_end.pyindex 6924f38..dc1a7e6 100644--- a/linux/tests/test_meeting_end.py+++ b/linux/tests/test_meeting_end.py@@ -1,4 +1,3 @@-"""MeetingEndWatch, the Mac's MeetingEndTests case for case, and reading meeting apps off `pactl`."""from __future__ import annotationsimport os@@ -79,7 +78,7 @@ class MeetingEndTests(unittest.TestCase):w = watch()self.assertIsNone(w.tick(at(5_000), ZOOM, True))self.assertIsNone(w.pending)- plain = watch(follow_apps=False) # without following apps, a call says nothing+ plain = watch(follow_apps=False)self.assertIsNone(plain.tick(at(600), ZOOM, True))self.assertEqual("silence", plain.pending.reason.kind)@@ -97,7 +96,7 @@ class MeetingEndTests(unittest.TestCase):w.tick(at(10), ZOOM, False)self.assertIsNone(w.tick(at(500), {}, False))self.assertIsNone(w.pending)- w.heard(at(5_001)) # a call that ended before anyone spoke is forgotten once someone does+ w.heard(at(5_001))self.assertIsNone(w.tick(at(5_002), {}, True))self.assertIsNone(w.pending)@@ -146,9 +145,6 @@ class MicStreamTests(unittest.TestCase):class HeardWordsTests(unittest.TestCase):- """What counts as someone speaking: recognised words landing (a line, mine too, or a half- sentence that grew), as the Mac counts recognised text. A retranslation isn't speech."""-def test_words_fire_on_new_and_grown_lines_only(self):import tempfilefrom cicada.core.models import TranscriptLinediff --git a/linux/tests/test_problem.py b/linux/tests/test_problem.pyindex 377dfa8..a78f0d9 100644--- a/linux/tests/test_problem.py+++ b/linux/tests/test_problem.py@@ -1,5 +1,3 @@-"""Something only the user can fix (problem.py, the Mac's AIServiceStrip.blocking): which reasons-count, and when the notification is due."""from __future__ import annotationsimport os@@ -45,11 +43,11 @@ class When(unittest.TestCase):def test_blocking_once_a_meeting_only_while_listening_and_put_away(self):n = Notices()n.start()- self.assertIsNone(n.tick(0, False, "invalidKey", False)) # not listening- self.assertIsNone(n.tick(1, True, "invalidKey", True)) # the notes window says it+ self.assertIsNone(n.tick(0, False, "invalidKey", False))+ self.assertIsNone(n.tick(1, True, "invalidKey", True))self.assertEqual("blocking", n.tick(2, True, "invalidKey", False))self.assertIsNone(n.tick(3, True, "invalidKey", False))- self.assertIsNone(n.tick(4, True, "noCredit", False)) # another one, same meeting+ self.assertIsNone(n.tick(4, True, "noCredit", False))n.start()self.assertEqual("blocking", n.tick(5, True, "noCredit", False))@@ -71,13 +69,12 @@ class When(unittest.TestCase):n = Notices()n.start()n.tick(0, True, "unreachable", False)- n.tick(100, True, None, False) # back+ n.tick(100, True, None, False)self.assertIsNone(n.tick(110, True, "unreachable", False))self.assertIsNone(n.tick(200, True, "unreachable", False))self.assertEqual("unreachable", n.tick(230, True, "unreachable", False))def test_unreachable_counts_while_the_window_shows_it(self):- # Down for 2 minutes with the window up, then put away: due at once.n = Notices()n.start()n.tick(0, True, "unreachable", True)diff --git a/linux/tests/test_providers.py b/linux/tests/test_providers.pyindex 62f7849..0253471 100644--- a/linux/tests/test_providers.py+++ b/linux/tests/test_providers.py@@ -1,5 +1,3 @@-"""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 annotationsimport base64@@ -21,13 +19,11 @@ from cicada.core.translator import Translator, is_noise # noqa: E402class Fake:- """Answers every request with `respond(url, body)`; speech with `speech(url, body)`."""-def __init__(self, respond, speech=None):self.respond = respondself.speech = speech- self.sent = [] # (url, body or "")- self.streamed = [] # (url, body)+ self.sent = []+ self.streamed = []def send(self, url, method, body, headers, timeout):self.sent.append((url, body or ""))@@ -74,7 +70,6 @@ class Table(Base):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)@@ -93,7 +88,7 @@ class Table(Base):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("http://api.example.com/v1"))self.assertIsNone(providers.custom_base(" "))def test_settings_keep_the_service_across_a_restart(self):@@ -164,7 +159,6 @@ 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]@@ -173,7 +167,6 @@ class Client(Base):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"])@@ -193,7 +186,7 @@ class Client(Base):self.assertEqual(OK, ling.check())self.assertFalse(ling.hears)self.assertFalse(ling.can_hear)- self.assertTrue(ling.usable) # notes and translation still work+ self.assertTrue(ling.usable)self.assertIn("a/b", ling.text_catalog)s.aiHearModels.clear()ling.key_changed()@@ -220,15 +213,12 @@ class Client(Base):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()])))@@ -263,10 +253,8 @@ class Words(Base):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])- # A gateway's 502 in front of the server: the service's trouble, not the network or the key.self.assertEqual(("busy", "ZenMux 暂时出错(HTTP 502),稍后再试。"), problem(LingError(LingError.HTTP, 502), "ZenMux"))self.assertEqual(("busy", "Ling 暂时出错(HTTP 503),稍后再试。"), problem(LingError(LingError.HTTP, 503), "Ling"))- # 其他(兼容 OpenAI) is UI text: in English it reads as the settings name it.from cicada.core import stringsres = [os.path.join(os.path.dirname(__file__), "..", "..", "Resources")]strings.load("en", res)diff --git a/linux/tests/test_proxy.py b/linux/tests/test_proxy.pyindex bb09a3e..59527a1 100644--- a/linux/tests/test_proxy.py+++ b/linux/tests/test_proxy.py@@ -1,5 +1,3 @@-"""Which way requests go (proxy.py): the environment's proxy, else GNOME's manual one (HTTPS, the HTTP-one, else SOCKS), its ignore-hosts, and real requests through a fake HTTP proxy and a fake SOCKS5 one."""from __future__ import annotationsimport http.server@@ -45,7 +43,7 @@ class Settings(unittest.TestCase):self.assertIs(True, s["use-same-proxy"])self.assertEqual(("10.0.2.2", 7890), (s["https.host"], s["https.port"]))self.assertEqual([], s["ftp.host"])- self.assertEqual({}, proxy.parse_gnome("")) # no gsettings: the Mac running the tests+ self.assertEqual({}, proxy.parse_gnome(""))def test_ignore_hosts(self):pats = ["localhost", "127.0.0.0/8", "::1", ".corp.example", "*.lan", "intra.example:8080", "10.1.2.3"]@@ -73,7 +71,7 @@ class Routes(unittest.TestCase):self.assertEqual("direct", proxy.route("https://zenmux.ai/", {}, s).kind)def test_gnome_ignores_and_other_modes(self):- self.assertEqual("direct", proxy.route("http://127.0.0.1:11434/v1", {}, gnome()).kind) # a local service+ self.assertEqual("direct", proxy.route("http://127.0.0.1:11434/v1", {}, gnome()).kind)self.assertEqual("direct", proxy.route("https://localhost/", {}, gnome()).kind)self.assertEqual("direct", proxy.route("https://zenmux.ai/", {}, gnome(mode="auto")).kind)self.assertEqual("direct", proxy.route("https://zenmux.ai/", {}, gnome(mode="none")).kind)@@ -82,14 +80,14 @@ class Routes(unittest.TestCase):def test_environment_first(self):env = {"https_proxy": "http://127.0.0.1:7897"}- self.assertEqual("env", proxy.route("https://zenmux.ai/", env, gnome()).kind) # urllib reads it- self.assertEqual("10.0.2.2:7891", proxy.route("http://example.com/", env, gnome()).where) # no http_proxy+ self.assertEqual("env", proxy.route("https://zenmux.ai/", env, gnome()).kind)+ self.assertEqual("10.0.2.2:7891", proxy.route("http://example.com/", env, gnome()).where)self.assertEqual("env", proxy.route("https://zenmux.ai/", {"HTTPS_PROXY": "http://h:1"}, {}).kind)self.assertEqual("10.0.2.2:7890", proxy.route("https://zenmux.ai/", {"https_proxy": " "}, gnome()).where)r = proxy.route("https://zenmux.ai/", {"all_proxy": "socks5://127.0.0.1:7890"}, gnome())self.assertEqual(("socks", "127.0.0.1", 7890, "env"), r.key()[:4])r = proxy.route("https://zenmux.ai/", {"ALL_PROXY": "http://u:[email protected]:7890"}, {})- self.assertEqual(("http", "127.0.0.1:7890"), (r.kind, r.where)) # credentials stay out of `where`+ self.assertEqual(("http", "127.0.0.1:7890"), (r.kind, r.where))self.assertEqual("direct", proxy.route("https://zenmux.ai/", {"all_proxy": "socks5://h:1", "no_proxy": "zenmux.ai"}, gnome()).kind)@@ -123,7 +121,6 @@ class _Echo(http.server.BaseHTTPRequestHandler):class _Socks(socketserver.BaseRequestHandler):- """A SOCKS5 proxy without authentication that remembers the name it was asked for."""asked: list = []def handle(self):@@ -160,8 +157,6 @@ class _Socks(socketserver.BaseRequestHandler):class Through(unittest.TestCase):- """Real requests: the opener a route picks carries them through the proxy."""-def serve(self, server):threading.Thread(target=server.serve_forever, daemon=True).start()self.addCleanup(server.server_close)@@ -169,7 +164,6 @@ class Through(unittest.TestCase):return server.server_address[1]def test_http_proxy(self):- # An HTTP proxy gets the absolute URL; the echo server plays the proxy here.port = self.serve(http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Echo))r = proxy.Route("http", "127.0.0.1", port, "gnome", "http://127.0.0.1:%d" % port)with proxy.opener(r).open(urllib.request.Request("http://cicada.invalid/x"), timeout=5) as resp:@@ -182,7 +176,7 @@ class Through(unittest.TestCase):_Socks.asked.clear()with proxy.opener(r).open(urllib.request.Request("http://localhost:%d/y" % web), timeout=5) as resp:self.assertEqual(b"path=/y", resp.read())- self.assertEqual([("localhost", web)], _Socks.asked) # the name, resolved by the proxy+ self.assertEqual([("localhost", web)], _Socks.asked)def test_dead_socks_is_an_oserror(self):s = socket.socket()diff --git a/linux/tests/test_recording.py b/linux/tests/test_recording.pyindex 8fa6d42..f29d9b7 100644--- a/linux/tests/test_recording.py+++ b/linux/tests/test_recording.py@@ -1,5 +1,3 @@-"""保存会议录音's parts that need no GStreamer: the ADTS file (core/aac.py), the record's hasAudio, and-the listening engine handing the recorder every sample the lines are timed by."""from __future__ import annotationsimport os@@ -13,7 +11,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, os.path.dirname(HERE))sys.path.insert(0, HERE)-import test_core as tc # noqa: E402 - its helpers; a module import, so its tests aren't collected twice+import test_core as tc # noqa: E402from cicada.core import aac # noqa: E402from cicada.core.audio import RATE, PcmAudioSource # noqa: E402from cicada.core.listen import ListenEngine, RoomMix # noqa: E402@@ -26,7 +24,6 @@ from cicada.core.translator import Translator # noqa: E402def adts(n: int, rate_index: int = 8, body: int = 20) -> bytes:- """n ADTS frames (16 kHz by default) with `body` bytes each."""length = 7 + bodyhead = bytes([0xFF, 0xF1, 0x40 | (rate_index << 2), 0x40 | ((length >> 11) & 0x03),(length >> 3) & 0xFF, ((length & 0x07) << 5) | 0x1F, 0xFC])@@ -40,13 +37,13 @@ class Adts(unittest.TestCase):self.assertAlmostEqual(250 * 1024 / 16000, aac.seconds(data))def test_a_torn_last_frame_goes(self):- data = adts(10) + adts(1)[:12] # killed mid-write+ data = adts(10) + adts(1)[:12]self.assertEqual(adts(10), aac.cut(data, None))def test_cuts_at_the_meetings_end(self):- data = adts(100) # 6.4 s+ data = adts(100)kept = aac.cut(data, 3.0)- self.assertAlmostEqual(3.008, aac.seconds(kept), places=3) # whole frames, up to the first one past 3 s+ self.assertAlmostEqual(3.008, aac.seconds(kept), places=3)self.assertEqual(data, aac.cut(data, 60))def test_partial_name(self):@@ -65,7 +62,6 @@ class HasAudio(tc.Base):self.assertTrue(store.get(s.id).hasAudio)with open(os.path.join(os.path.dirname(store.audio_path(s.id)), "session.json"), encoding="utf-8") as f:self.assertIn('"hasAudio" : true', f.read())- # The app quit before rewrapping: the next launch finds it.self.assertEqual([s.id], SessionStore().unfinished_audio())def test_without_one_it_says_none(self):@@ -124,7 +120,6 @@ class Recording(tc.Base):store, engine = self.engine()rec, heard = self.run_meeting(engine)self.assertTrue(rec.closed)- # The lines' clock is the samples the lane heard: the file holds exactly those.self.assertEqual(round(heard * RATE), rec.samples)self.assertTrue(rec.finished.wait(5))self.assertIsNone(rec.until)@@ -148,17 +143,14 @@ class Recording(tc.Base):def loud(pcm, a, b):- """The largest sample between a and b seconds."""return max((abs(v) for v in pcm[int(a * RATE):int(b * RATE)]), default=0)class Mix(unittest.TestCase):- """电脑和会议室: the room mic goes into the meeting's one recording, at its place on the clock (#19)."""-def test_the_room_is_added_where_it_was_heard(self):rec = FakeRecorder()mix = RoomMix(rec)- for i in range(30): # 3 s of the computer at 1000, in 0.1 s buffers; the room at 500 from 1 s to 2 s+ for i in range(30):mix.write(array("h", [1000] * 1600))if 10 <= i < 20:mix.room(array("h", [500] * 1600), i * 1600)@@ -174,7 +166,7 @@ class Mix(unittest.TestCase):mix = RoomMix(rec)for i in range(20):mix.write(array("h", [0] * 1600))- if i >= 5: # the room's buffer for each 0.1 s arrives half a second after the computer's+ if i >= 5:mix.room(array("h", [700] * 1600), (i - 5) * 1600)mix.close()self.assertEqual(700, min(rec.pcm[:int(1.5 * RATE)]))@@ -184,7 +176,7 @@ class Mix(unittest.TestCase):mix = RoomMix(rec)mix.write(array("h", [30000] * 1600))mix.room(array("h", [30000] * 1600), 0)- mix.room(array("h", [800] * 1600), 2 * RATE) # the computer stopped sending: the room goes on+ mix.room(array("h", [800] * 1600), 2 * RATE)mix.close()self.assertEqual(32767, rec.pcm[0])self.assertEqual(2 * RATE + 1600, rec.samples)@@ -197,7 +189,6 @@ class Mix(unittest.TestCase):e = both_engine(store, "x")rec = FakeRecorder()e.recorder = lambda sid: rec- # In real time, as the sound server sends them: the computer's tone 0-1 s, the room's 0.5-2.1 s.main = PcmAudioSource(lambda: tc.concat(tc.tone(1.0), tc.silence(1.0)), speed=1)room = PcmAudioSource(lambda: tc.concat(tc.silence(0.5), tc.tone(1.6, amp=0.2), tc.silence(0.4)), speed=1)done = [threading.Event(), threading.Event()]diff --git a/linux/tests/test_share.py b/linux/tests/test_share.pyindex a2f8863..7ad4f1b 100644--- a/linux/tests/test_share.py+++ b/linux/tests/test_share.py@@ -1,7 +1,3 @@-"""分享…: the share document is a contract with the server (server/src/doc.js) and the Mac, so the-same record must give the same bytes (Tests/fixtures/share); plus the password, the Ed25519-signatures (RFC 8032) and the client against a fake server (never the real one: production limits-how many devices an address may register)."""from __future__ import annotationsimport hashlib@@ -30,7 +26,6 @@ def session() -> Session:class ShareDocTests(unittest.TestCase):def setUp(self):- # Other suites switch the UI language; the document's speaker words follow it.strings.load("zh-Hans", [os.path.join(REPO, "Resources")])def test_fixture_bytes(self):@@ -59,7 +54,6 @@ class ShareDocTests(unittest.TestCase):def test_speaker_numbers_without_names(self):s = session()- # Two voices with five substantive lines each get numbers; their names stay out.s.lines = [TranscriptLine(id="v%d" % i, t=float(i), speaker="them", src="this is line number %d" % i,dst="第 %d 句话" % i, srcLang="en", dstLang="zh", voice=3 if i % 2 == 0 else 7)for i in range(10)]@@ -68,7 +62,7 @@ class ShareDocTests(unittest.TestCase):def test_rounding_and_numbers(self):s = session()- s.lines[0].t = 0.25 # half away from zero, as Swift rounds: 0.3, not Python's 0.2+ s.lines[0].t = 0.25s.lines[1].dst = s.lines[1].srcd = share.doc(s, "full", False)self.assertEqual(0.3, d["lines"][0]["t"])@@ -81,14 +75,12 @@ class ShareDocTests(unittest.TestCase):def test_password(self):salt = bytes([1] * 16)- # Same as the browser's crypto.subtle PBKDF2-SHA256, 32 bytes (server/test/api.test.mjs).v = share.verifier("ruby-41-lake", salt, 1000)self.assertEqual("eab69fcd00a0517794c156495dd76ad1fbfb036ea03df3d59a68a33519009c81", v.hex())self.assertNotEqual(v, share.verifier("ruby-41-laka", salt, 1000))self.assertEqual(3, len(share.make_password().split("-")))def test_blocked_hits_map_back(self):- # The server counts lines of what was sent; the app maps them back to the record.hits = [{"part": "lines", "from": 2, "to": 3, "questions": ["credential"]}, {"part": "notes", "questions": []}]self.assertEqual({4, 5}, share.record_lines(hits, [0, 1, 4, 5, 6]))@@ -98,7 +90,6 @@ class ShareDocTests(unittest.TestCase):self.assertEqual("服务器出了问题,请稍后再试。", share.message("whatever"))def test_clipboard_message(self):- # One message, three lines, in the UI's language; days left round up, a year reads as a year.now = 1_000_000.0r = share.ShareRecord("a", "https://x/s/a", "t", now + 6.5 * 86400, "notes", "ruby-41-lake", now)self.assertEqual("「周会」会议记录\nhttps://x/s/a\n密码:ruby-41-lake(7 天内有效)", share.clipboard_text(r, "周会", now))@@ -116,7 +107,6 @@ class ShareDocTests(unittest.TestCase):class Ed25519Tests(unittest.TestCase):- # RFC 8032 §7.1, tests 1–3: secret key, public key, message, signature.VECTORS = [("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60","d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "",@@ -139,8 +129,6 @@ class Ed25519Tests(unittest.TestCase):class FakeServer:- """server/src's contract in miniature: registration with proof of work, signed requests."""-def __init__(self):self.keys = {}self.calls = []diff --git a/linux/tests/test_transcript_search.py b/linux/tests/test_transcript_search.pyindex cad3e9d..a20a147 100644--- a/linux/tests/test_transcript_search.py+++ b/linux/tests/test_transcript_search.py@@ -1,5 +1,3 @@-"""The search in a meeting's lines, shared by the notes window and the records window (the Mac's-TranscriptSearchTests)."""from __future__ import annotationsimport os@@ -21,10 +19,8 @@ class TranscriptSearchTests(unittest.TestCase):def test_a_name_also_finds_how_it_was_misheard(self):notes = [NoteTerm(name="江充", note="", heard=["江松"]), NoteTerm(name="Ling", note="", heard=[])]self.assertEqual(ts.terms("江充", notes), ["江充", "江松"])- # Searching the misheard form finds the right one too; an unrelated term stays out.self.assertEqual(ts.terms(" 江松 ", notes), ["江松", "江充"])self.assertEqual(ts.terms(" ", notes), [])- # A query inside a name, and a name inside the query, both bring the forms in, case aside.self.assertEqual(ts.terms("ling", notes), ["ling", "Ling"])self.assertEqual(ts.terms("问江充吧", notes), ["问江充吧", "江充", "江松"])@@ -42,7 +38,6 @@ class TranscriptSearchTests(unittest.TestCase):def test_every_occurrence_is_marked(self):self.assertEqual(ts.spans("Budget, budget, done", ["budget"]), [(0, 6), (8, 14)])- # Overlapping terms mark one stretch.self.assertEqual(ts.spans("江充江松", ["江充", "充江"]), [(0, 3)])self.assertEqual(ts.spans("nothing", ["budget"]), [])diff --git a/linux/tests/test_updates.py b/linux/tests/test_updates.pyindex 54b50a7..03e1d74 100644--- a/linux/tests/test_updates.py+++ b/linux/tests/test_updates.py@@ -1,5 +1,3 @@-"""Updates: the Mac's UpdateTests case for case, then downloading, checking and unpacking a release-from a file:// feed, the way the app installs one."""from __future__ import annotationsimport hashlib@@ -88,8 +86,6 @@ class Schedule(unittest.TestCase):class Install(unittest.TestCase):- """A release on disk: a tarball like scripts/build.sh makes, its checksums, and a feed."""-def setUp(self):self.dir = tempfile.mkdtemp()Paths.home_override = os.path.join(self.dir, "home")@@ -201,7 +197,6 @@ class Notify(unittest.TestCase):class _Flaky(http.server.BaseHTTPRequestHandler):- """Serves BODY with Range; the first request is cut off halfway, or stalls when `stall`."""protocol_version = "HTTP/1.1"requests: list = []stall = False@@ -235,7 +230,6 @@ class Download(unittest.TestCase):Paths.home_override = os.path.join(self.dir, "home")os.makedirs(Paths.data(), exist_ok=True)self.addCleanup(setattr, Paths, "home_override", None)- # A proxy in the shell running the tests would carry these local requests off through it.for k in ("http_proxy", "https_proxy", "all_proxy", "no_proxy"):for name in (k, k.upper()):if name in os.environ:@@ -258,7 +252,7 @@ class Download(unittest.TestCase):self.assertEqual(BODY, f.read())self.assertEqual([None, "bytes=%d-" % (len(BODY) // 2)], _Flaky.requests)self.assertIn("stopped at %d of %d bytes, try 1 of 3 (IncompleteRead" % (len(BODY) // 2, len(BODY)), self.log())- self.assertNotIn("http://", self.log()) # the host only+ self.assertNotIn("http://", self.log())def test_a_stall_is_a_timeout_per_read_not_for_the_whole_file(self):_Flaky.stall = True@@ -269,7 +263,7 @@ class Download(unittest.TestCase):updates._download(self.url, to, None)with open(to, "rb") as f:self.assertEqual(BODY, f.read())- self.assertRegex(self.log(), r"try 1 of 3 \((timeout|TimeoutError): timed out\)") # socket.timeout's name varies+ self.assertRegex(self.log(), r"try 1 of 3 \((timeout|TimeoutError): timed out\)")def test_giving_up_says_why(self):with self.assertRaises(OSError):diff --git a/linux/tests/test_voice_clone.py b/linux/tests/test_voice_clone.pyindex 3052928..1167dbd 100644--- a/linux/tests/test_voice_clone.py+++ b/linux/tests/test_voice_clone.py@@ -1,5 +1,3 @@-"""我自己的声音 (issue #32): the recording kept like the key, Ming's request with `references`, the-voice a language falls back to, and the Mac's pace and length checks."""from __future__ import annotationsimport base64@@ -89,17 +87,14 @@ class Pace(unittest.TestCase):self.assertEqual(["大", "家", "好", "hello", "it's", "2"], vref.tokens("大家好, Hello it’s 2!"))def test_too_slow_is_caught_like_the_mac(self):- # 54 characters over 12 s of speech: 4.5 a second, an ordinary pace.self.assertIsNone(vref.check(concat(silence(0.5), tone(12), silence(0.5)), PASSAGE))p = vref.pace(PASSAGE, concat(silence(1), tone(12), silence(2)))self.assertAlmostEqual(len(vref.tokens(PASSAGE)) / 12, p, delta=0.05, msg="silence at both ends left out")- # The same over 14 s of a recital at a third of it.self.assertEqual("slow", vref.check(tone(14), PASSAGE[:30]))self.assertTrue(vref.is_slow("hello there everyone", 1.5))self.assertFalse(vref.is_slow("hello there everyone", 2.0))def test_the_quiet_around_the_reading_is_cut(self):- # A second of silence after the last word made Ming answer every sentence with 0.4 s of nothing.cut = vref.trim(concat(silence(1.5), tone(11), silence(1.2)))self.assertAlmostEqual(11 + 2 * vref.TRIM_PAD, len(cut) / 16000, delta=0.05)self.assertEqual(16000 * 3, len(vref.trim(silence(3))), "nothing to cut by in silence")diff --git a/linux/vm/click.py b/linux/vm/click.pyindex 60d8745..3eb54ad 100644--- a/linux/vm/click.py+++ b/linux/vm/click.py@@ -1,9 +1,4 @@#!/usr/bin/env python3-"""Clicks at x,y on the VM's screen with a virtual absolute pointer made through /dev/uinput (run-with sudo, inside the guest). GNOME's compositor sees it as a real device, so the click goes-through Mutter's focus rules, which xdotool (XWayland only) and QEMU's pointer here don't reach.- sudo python3 click.py 1515 89 a click- sudo python3 click.py 1515 89 --to 900 300 press there, drag to 900,300, release"""import fcntlimport osimport struct@@ -24,13 +19,12 @@ for ev in (EV_KEY, EV_ABS):fcntl.ioctl(fd, UI_SET_KEYBIT, BTN_LEFT)for a in (ABS_X, ABS_Y):fcntl.ioctl(fd, UI_SET_ABSBIT, a)-# struct uinput_user_dev: name[80], input_id (4 x u16), ff_effects_max, absmax[64], absmin[64], absfuzz[64], absflat[64]absmax = [0] * 64absmax[ABS_X], absmax[ABS_Y] = w - 1, h - 1dev = struct.pack("80sHHHHI", b"cicada-test-pointer", 3, 1, 1, 1, 0) + struct.pack("64i", *absmax) + struct.pack("64i", *([0] * 64)) * 3os.write(fd, dev)fcntl.ioctl(fd, UI_DEV_CREATE)-time.sleep(1.0) # let libinput pick the new device up+time.sleep(1.0)def emit(t, c, v):diff --git a/linux/vm/focus_probe.py b/linux/vm/focus_probe.pyindex cca01b7..11a0a78 100644--- a/linux/vm/focus_probe.py+++ b/linux/vm/focus_probe.py@@ -1,7 +1,4 @@#!/usr/bin/env python3-"""A stand-in meeting app for the focus test: a maximized native-Wayland GTK window with a text box-that logs every focus change to /tmp/focus-probe.log. Click Cicada's notes window (real input through-QEMU) and this window must stay active."""import osimport timediff --git a/linux/vm/focus_test.sh b/linux/vm/focus_test.shindex 7685ad4..44e80ca 100755--- a/linux/vm/focus_test.sh+++ b/linux/vm/focus_test.sh@@ -1,8 +1,4 @@#!/bin/bash-# Inside the VM's session (vmctl.sh ssh): the focus test. A maximized native-Wayland "meeting app"-# (focus_probe.py) has focus; Cicada's notes window is shown; real clicks (click.py, uinput) land on-# the notes window's body and on its 字幕 link. Then type from the host (vmctl.sh type ok) and read-# /tmp/focus-probe.log: the probe must never go inactive and must get the text.bin="$(cd "$(dirname "$0")" && pwd)"pkill -f "focus_probe[.]py" ; pkill -f "python3 -m cicada[.]app"; sleep 1rm -f /tmp/focus-probe.log@@ -18,10 +14,9 @@ setsid -f "$bin/cicada" --dev >/tmp/cicada-app.out 2>&1 </dev/null; sleep 4"$bin/cicadactl" show notes; sleep 1geo="$("$bin/cicadactl" windows)"; echo "$geo"read -r x y w <<<"$(python3 -c 'import json,sys; n=json.loads(sys.argv[1])["notes"]; print(n["x"], n["y"], n["w"])' "$geo")"-sudo python3 "$bin/click.py" $((x + w / 2)) $((y + 340)); sleep 0.5 # the notes body-sudo python3 "$bin/click.py" $((x + w - 112)) $((y + 34)); sleep 1.5 # the 切到字幕条 icon, third from the right+sudo python3 "$bin/click.py" $((x + w / 2)) $((y + 340)); sleep 0.5+sudo python3 "$bin/click.py" $((x + w - 112)) $((y + 34)); sleep 1.5"$bin/cicadactl" state | python3 -c 'import json,sys; print("view:", json.load(sys.stdin)["view"])'-# Dragging moves it (the app moves the window itself: the WM won't move a notification window)."$bin/cicadactl" view notes >/dev/null; sleep 1before="$("$bin/cicadactl" windows | python3 -c 'import json,sys; n=json.load(sys.stdin)["notes"]; print(n["x"], n["y"])')"read -r x y <<<"$before"diff --git a/linux/vm/fullscreen_probe.py b/linux/vm/fullscreen_probe.pyindex 384be3c..3e23eac 100644--- a/linux/vm/fullscreen_probe.py+++ b/linux/vm/fullscreen_probe.py@@ -1,5 +1,4 @@#!/usr/bin/env python3-"""A stand-in for a full-screen video player: a native-Wayland GTK window, full screen, black."""import osos.environ["GDK_BACKEND"] = "wayland"import gi # noqa: E402diff --git a/linux/vm/long_session.py b/linux/vm/long_session.pyindex ce7e5d8..b9e9af5 100644--- a/linux/vm/long_session.py+++ b/linux/vm/long_session.py@@ -1,6 +1,4 @@#!/usr/bin/env python3-"""Writes a synthetic long meeting (N lines, bilingual, with notes) into the dev build's records,-for checking how the UI copes. long_session.py 1500"""import json, os, sysn = int(sys.argv[1]) if len(sys.argv) > 1 else 1500sid = "20261101-090000"diff --git a/linux/vm/push.sh b/linux/vm/push.shindex de87998..8bfad81 100755--- a/linux/vm/push.sh+++ b/linux/vm/push.sh@@ -1,6 +1,4 @@#!/bin/bash-# Copies the built tree (linux/scripts/build.sh) into the test VM as ~/cicada-linux, with the dev-# tools (cicadactl, smoke.sh, the focus test) in its bin/. Stops a running dev build first.set -euo pipefailhere="$(cd "$(dirname "$0")/.." && pwd)"VM="${VM:-$HOME/VMs/cicada-ubuntu}"@@ -8,7 +6,6 @@ o=(-q -i "$VM/vm_key" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/nulssh "${o[@]}" -p 2223 [email protected] 'pkill -f "python3 -m cicada[.]app" || true; rm -rf ~/cicada-linux'scp "${o[@]}" -P 2223 -r "$here/build/cicada-linux" [email protected]:scp "${o[@]}" -P 2223 "$here/scripts/cicadactl" "$here/scripts/smoke.sh" "$here/vm/focus_probe.py" "$here/vm/fullscreen_probe.py" "$here/vm/set_scale.py" "$here/vm/long_session.py" "$here/vm/click.py" "$here/vm/focus_test.sh" [email protected]:cicada-linux/bin/-# The voiceprint library for the VM's architecture (the Mac can't link Linux binaries): built there.scp "${o[@]}" -P 2223 -q "$here/native/voiceprint.c" "$here/native/build.sh" [email protected]:cicada-linux/lib/ssh "${o[@]}" -p 2223 [email protected] 'cd ~/cicada-linux/lib && command -v gcc >/dev/null && bash build.sh . && rm -f voiceprint.c build.sh || echo "no gcc in the VM: sudo apt install build-essential"'echo "pushed to ~/cicada-linux"diff --git a/linux/vm/run.sh b/linux/vm/run.shindex 496f655..8cc838d 100755--- a/linux/vm/run.sh+++ b/linux/vm/run.sh@@ -1,9 +1,4 @@#!/bin/bash-# Runs the Ubuntu 24.04 arm64 desktop test VM under QEMU (HVF), headless: VNC on :2, the QEMU-# monitor on $VM/monitor.sock (screendump works whatever the compositor allows), SSH on-# localhost:2223. First run builds the disk from the cloud image and cloud-init installs a GNOME-# desktop with auto-login, so the app runs in a real session.-# VM=~/VMs/cicada-ubuntu linux/vm/run.sh # needs noble-arm64.img and vm_key in $VMset -euo pipefailhere="$(cd "$(dirname "$0")" && pwd)"VM="${VM:-$HOME/VMs/cicada-ubuntu}"@@ -19,8 +14,6 @@ if [ ! -f disk.qcow2 ]; thenrm -f seed.iso && hdiutil makehybrid -quiet -iso -joliet -default-volume-name cidata -o seed.iso seedfi-# A real (if silent) sound card, so PipeWire makes a proper sink whose monitor we capture. Virtio:-# the guest froze loading snd-hda-intel for the emulated Intel HDA under HVF.qemu-system-aarch64 \-name cicada-ubuntu -machine virt,highmem=on -accel hvf -cpu host -smp 4 -m 6G \-drive if=pflash,format=raw,readonly=on,file="$share/edk2-aarch64-code.fd" \diff --git a/linux/vm/set_scale.py b/linux/vm/set_scale.pyindex 1c34fae..e9af8b1 100644--- a/linux/vm/set_scale.py+++ b/linux/vm/set_scale.py@@ -1,6 +1,4 @@#!/usr/bin/env python3-"""Sets the VM's monitor scale through Mutter's DisplayConfig D-Bus API (fractional scaling must be-on: org.gnome.mutter experimental-features 'scale-monitor-framebuffer'). set_scale.py 1.25"""import sysfrom gi.repository import Gio, GLibwant = float(sys.argv[1])diff --git a/linux/vm/vmctl.sh b/linux/vm/vmctl.shindex 5e5f751..6ae9d2a 100755--- a/linux/vm/vmctl.sh+++ b/linux/vm/vmctl.sh@@ -1,26 +1,24 @@#!/bin/bash-# Small helpers for the Ubuntu test VM.-# vmctl.sh ssh [cmd…] run in the VM as cicada (inside the desktop session's environment)-# vmctl.sh shot out.png screenshot of the VM's screen through the QEMU monitor-# vmctl.sh wake a key press through QEMU (wakes a blanked screen)-# vmctl.sh type abc types through QEMU's keyboard-# vmctl.sh stopset -euo pipefailVM="${VM:-$HOME/VMs/cicada-ubuntu}"-# One shared connection (ControlMaster): QEMU's user networking here wedged after many short ones.ssh_=(ssh -q -i "$VM/vm_key" -p 2223 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null-o ConnectTimeout=8 -o ControlMaster=auto -o ControlPath="$VM/ssh.sock" -o ControlPersist=600 [email protected])case "${1:-}" inssh) shift; if [ $# -eq 0 ]; then exec "${ssh_[@]}"; fi- # The GNOME session's bus, display and audio, so commands act inside the logged-in desktop.exec "${ssh_[@]}" "export XDG_RUNTIME_DIR=/run/user/\$(id -u) DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/\$(id -u)/bus WAYLAND_DISPLAY=wayland-0 DISPLAY=:0 XAUTHORITY=\$(ls /run/user/\$(id -u)/.mutter-Xwaylandauth.* 2>/dev/null | head -1); $*" ;;shot) out="$(cd "$(dirname "${2:?out.png}")" && pwd)/$(basename "$2")"; ppm="${out%.png}.ppm"printf 'screendump %s\n' "$ppm" | nc -U -w 2 "$VM/monitor.sock" >/dev/null; sleep 1sips -s format png "$ppm" --out "$out" >/dev/null && rm -f "$ppm" && echo "$out" ;;- # Real input through QEMU (xdotool only reaches XWayland, not the compositor): wakes a blanked screen.wake) printf 'sendkey shift\n' | nc -U -w 2 "$VM/monitor.sock" >/dev/null ;;- # Typing through QEMU's keyboard (lowercase letters and digits).type) for ((i = 0; i < ${#2}; i++)); do printf 'sendkey %s\n' "${2:i:1}"; sleep 0.2; done | nc -U -w 3 "$VM/monitor.sock" >/dev/null ;;stop) printf 'system_powerdown\n' | nc -U -w 2 "$VM/monitor.sock" >/dev/null || true ;;- *) sed -n 2,8p "$0"; exit 1 ;;+ *) cat >&2 <<'USAGE'+Small helpers for the Ubuntu test VM.+ vmctl.sh ssh [cmd…] run in the VM as cicada (inside the desktop session's environment)+ vmctl.sh shot out.png screenshot of the VM's screen through the QEMU monitor+ vmctl.sh wake a key press through QEMU (wakes a blanked screen)+ vmctl.sh type abc types through QEMU's keyboard+ vmctl.sh stop+USAGE+ exit 1 ;;esac