Skip to content

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

feat(linux): add the Linux app for Ubuntu with live notes, meeting records and Interpreting

wquguru921670896078
diff --git a/linux/AGENTS.md b/linux/AGENTS.md
new file mode 100644
index 0000000..7f22b3c
--- /dev/null
+++ b/linux/AGENTS.md
@@ -0,0 +1,13 @@
+# AGENTS.md (Linux)
+
+The Linux port: listening, and 同声传译 (speaking into the room through the 知了 麦克风 virtual mic). The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). Commands, layout and how to verify are in `README.md`; the plan is `docs/linux-plan.md`.
+
+- Python 3, PyGObject and GTK 3, PulseAudio / PipeWire through `libpulse-simple`: only what Ubuntu desktop ships, no pip packages. `cicada/core` is stdlib only and must run and test on the Mac.
+- The key: `AIKey` in `cicada/core/ling.py`, the 0600 `ling-api-key` file in `~/.config/cicada`.
+- The notes window floats and never takes focus (XWayland, notification type). Linux can't keep it out of screen sharing, so it always says it may be shared; don't claim otherwise.
+- 知了 麦克风 is two sound-server modules (`cicada/app/room.py`), never a driver. While on it is the default input; every way out (off, 退出, SIGTERM, a crash then the next launch) gives the real microphone back. Never speak what Ming didn't interpret.
+- 说话人识别 runs the Mac's voiceprint model in `native/voiceprint.c` (our own C, ctypes; no BLAS on Ubuntu). It must stay equal to the Mac: the voiceprint test checks it against a Core ML reference, and clustering thresholds, labels and Ling's name prompt are the Mac's. The Mac can't link Linux binaries: CI builds the `.so` per architecture on 22.04, `vm/push.sh` builds it in the VM.
+- The look is the Mac's (canvas 知了 Linux · 对齐 Mac): sizes are the Mac's numbers in px through `ui.text` (which converts to points), bold only where the Mac is semibold, and every widget the theme draws is styled in `ui.py` (no Yaru orange or discs). Check a UI change against the canvas at the same size, not just that it works.
+- Shared UI text comes from `Resources/*.lproj/Localizable.strings`; Linux-only text is in `strings/`. Run `python3 scripts/strings.py` after changing either.
+- Verify with `scripts/test.sh` and `scripts/smoke.sh`, then in the VM (`vm/`) with `scripts/cicadactl`. Real hardware, other desktops and real screen sharing need a person.
+- Commits use the `(linux)` scope: `feat(linux):` / `fix(linux):` are this platform's release notes.
diff --git a/linux/CLAUDE.md b/linux/CLAUDE.md
new file mode 100644
index 0000000..43c994c
--- /dev/null
+++ b/linux/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/linux/README.md b/linux/README.md
new file mode 100644
index 0000000..a84fac9
--- /dev/null
+++ b/linux/README.md
@@ -0,0 +1,62 @@
+# 知了 Linux 版
+
+Cicada 的 Linux 版:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录;打开同声传译后,把你说的话翻成对方的语言,用“知了 麦克风”传进会议。方案和取舍见 [docs/linux-plan.md](../docs/linux-plan.md)。
+
+- 原生:Python 3 + PyGObject + GTK 3,声音走 PulseAudio / PipeWire(`libpulse-simple`,读默认输出的 monitor,不用授权)。只用 Ubuntu 桌面自带的库,不用 pip 包。
+- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求返回语言、原文和译文;需要 Ling key。和 Windows、Android 同一套做法。
+- 纪要窗:浮在最上面、点它也不抢焦点(app 走 XWayland,窗口类型是 notification;GNOME 的 Wayland 不给普通窗口这两个能力)。**Linux 没法让窗口避开屏幕共享**,所以纪要窗一直带“可能被共享”。
+- 纪要、记录格式(逐字节和 Mac 一致)、提示词、文案都和 Mac 版一致;英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Linux 独有的在 `strings/`。
+- 同声传译:声音服务器里建一个虚拟麦克风“知了 麦克风”(`module-null-sink` + `module-remap-source`,PipeWire 和 PulseAudio 都行,不用装驱动),打开时设成默认输入,关掉或退出时把原来的麦克风还回去(被 `kill -9` 后下次启动也会还)。点纪要窗的麦克风、托盘的“开始说”或快捷键(Super + Shift + S,`cicada --speak`)开始 / 停止;Ming 一次请求识别并翻译,Ming 的声音流式播进知了 麦克风,下一句的声音在上一句播完前就已经在取。对方的声音从扬声器漏进麦克风的那句会丢掉,不说出去。
+- 说话人识别(默认打开,和 Mac 一样):每句话的声音算一个声纹,按 Mac 的阈值分组,标出说话人 1、2…,Ling 从对话里认出名字;会议记录里可以改名、合并、把一句改给别人,都能撤销。声纹模型和 Mac 是同一个(WeSpeaker ResNet34-LM,VoxCeleb,CC BY 4.0),由 `scripts/convert-voiceprint.py` 转成 `models/voiceprint.bin`;Ubuntu 桌面没有矩阵库、Python 也跑不动 ResNet,所以推理在我们自己的 C 代码里(`native/voiceprint.c`,不用第三方库),每个架构编一个 `libcicada-voice-<arch>.so` 随包附带。和 Mac 的 Core ML 结果余弦相似度 1.0000;在 4 核 arm64 虚拟机里 5 秒的一句约 0.3 秒。没有这个库时功能显示不可用,听照常。
+- 支持 Ubuntu 22.04 / 24.04 桌面版。
+
+## 目录
+
+| 路径 | 内容 |
+|---|---|
+| `cicada/core` | 不依赖界面的引擎(只用 Python 标准库,Mac 上也能运行、测试) |
+| `cicada/app` | GTK 应用:托盘、纪要窗 / 字幕条、会议记录、设置、引导、开发版的控制 socket |
+| `native/` | 声纹推理(C)和 `build.sh`:Mac 上编 `.dylib` 给单元测试用,Linux 上编 `.so` |
+| `models/` | 声纹模型权重(fp16,13 MB) |
+| `cli.py` | 在 Mac 上用 WAV 跑完整流程、检查会议记录 |
+| `tests/` | 单元测试(`unittest`) |
+| `packaging/` | 菜单项、`install.sh` |
+| `vm/` | Ubuntu 测试虚拟机(QEMU) |
+
+## 命令(在 Mac 上)
+
+```bash
+scripts/test.sh # 单元测试、文案检查、语法检查
+scripts/build.sh # build/cicada-linux/ 和 build/cicada-linux-<版本>.tar.gz
+python3 scripts/strings.py # 查缺翻译的文案(--write 追加 TODO)
+python3 cli.py listen ../windows/spike/clips/en.wav --target zh-CN --notes # 真实调用 Ming 和 Ling
+python3 cli.py speak ../windows/spike/clips/zh.wav --from zh-CN --to en --out /tmp/out.wav # 同声传译一句一句地跑
+python3 cli.py roundtrip ~/Library/Application\ Support/LiveSubs/Sessions/*/session.json
+```
+
+`cli.py` 读 Mac 版的 key 文件,不打印 key;环境里的代理会传给 urllib。
+
+## 安装(用户)
+
+```bash
+tar xzf Cicada-<版本>-Linux.tar.gz && cicada-linux/install.sh
+```
+
+装到 `~/.local`,不用 sudo,之后从应用列表打开“知了”。缺 `python3-gi`、`gir1.2-gtk-3.0`、`libpulse0` 时会提示用 apt 装(Ubuntu 桌面版默认都有)。
+
+## 在虚拟机里验证
+
+```bash
+VM=~/VMs/cicada-ubuntu linux/vm/run.sh # 第一次:放好 noble-arm64.img(Ubuntu 云镜像)和 vm_key,cloud-init 装 GNOME
+linux/vm/vmctl.sh ssh 'uptime' # 在登录着的桌面会话里执行
+linux/vm/vmctl.sh shot shot.png # 截屏(QEMU,不受 Wayland 截图限制)
+linux/scripts/build.sh && linux/vm/push.sh # 把 build/cicada-linux 和测试工具放进虚拟机的 ~/cicada-linux
+```
+
+在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。
+
+焦点:`bin/focus_test.sh` 开一个最大化的“会议 app”(`focus_probe.py`),用 `click.py`(uinput,真实指针)点纪要窗和“字幕”链接,再在 Mac 上 `linux/vm/vmctl.sh type ok`;`/tmp/focus-probe.log` 里不能出现 `active=False`,最后一行应是 `text=…ok`。xdotool 只到 XWayland,测不了这个。
+
+再检查:放一段视频再 `start`,字幕跟得上;中文和英文界面都看一遍。
+
+需要真人和真机:x86_64 真机、真实声卡和蓝牙耳机、切换输出设备、KDE 等其他桌面、会议软件的屏幕共享。
diff --git a/linux/bin/cicada b/linux/bin/cicada
new file mode 100755
index 0000000..c48d11d
--- /dev/null
+++ b/linux/bin/cicada
@@ -0,0 +1,5 @@
+#!/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__.py
new file mode 100644
index 0000000..1ba365d
--- /dev/null
+++ b/linux/cicada/__init__.py
@@ -0,0 +1,18 @@
+"""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 _Path
+
+
+def _version() -> str:
+ # One version for every platform: VERSION at the repo root, copied next to cicada/ in a build.
+ here = _Path(__file__).resolve().parent.parent
+ for p in (here / "VERSION", here.parent / "VERSION"):
+ try:
+ return p.read_text(encoding="utf-8").strip()
+ except OSError:
+ pass
+ return "0"
+
+
+VERSION = _version()
diff --git a/linux/cicada/app/__init__.py b/linux/cicada/app/__init__.py
new file mode 100644
index 0000000..020a44e
--- /dev/null
+++ b/linux/cicada/app/__init__.py
@@ -0,0 +1,2 @@
+"""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)."""
diff --git a/linux/cicada/app/__main__.py b/linux/cicada/app/__main__.py
new file mode 100644
index 0000000..ac7e395
--- /dev/null
+++ b/linux/cicada/app/__main__.py
@@ -0,0 +1,5 @@
+import sys
+
+from .main import main
+
+sys.exit(main())
diff --git a/linux/cicada/app/capture.py b/linux/cicada/app/capture.py
new file mode 100644
index 0000000..53a481b
--- /dev/null
+++ b/linux/cicada/app/capture.py
@@ -0,0 +1,227 @@
+"""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 annotations
+
+import ctypes
+import ctypes.util
+import threading
+import time
+from array import array
+
+from ..core.audio import RATE, AudioSource
+from ..core.strings import L
+from ..core.support import Log
+
+PA_SAMPLE_S16LE = 3
+PA_STREAM_RECORD = 2
+CHUNK = RATE // 10 # 100 ms per read, like a capture callback
+
+
+class _Spec(ctypes.Structure):
+ _fields_ = [("format", ctypes.c_int), ("rate", ctypes.c_uint32), ("channels", ctypes.c_uint8)]
+
+
+class _Attr(ctypes.Structure):
+ _fields_ = [("maxlength", ctypes.c_uint32), ("tlength", ctypes.c_uint32), ("prebuf", ctypes.c_uint32),
+ ("minreq", ctypes.c_uint32), ("fragsize", ctypes.c_uint32)]
+
+
+_lib = None
+
+
+def _pulse():
+ global _lib
+ if _lib is None:
+ name = ctypes.util.find_library("pulse-simple") or "libpulse-simple.so.0"
+ lib = ctypes.CDLL(name)
+ lib.pa_simple_new.restype = ctypes.c_void_p
+ lib.pa_simple_new.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p,
+ ctypes.POINTER(_Spec), ctypes.c_void_p, ctypes.POINTER(_Attr), ctypes.POINTER(ctypes.c_int)]
+ lib.pa_simple_read.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_int)]
+ lib.pa_simple_free.argtypes = [ctypes.c_void_p]
+ pulse = ctypes.CDLL(ctypes.util.find_library("pulse") or "libpulse.so.0")
+ pulse.pa_strerror.restype = ctypes.c_char_p
+ pulse.pa_strerror.argtypes = [ctypes.c_int]
+ lib.strerror = pulse.pa_strerror
+ _lib = lib
+ return _lib
+
+
+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)]
+
+
+_INFO_CB = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(_ServerInfo), ctypes.c_void_p)
+_full = None
+
+
+def _libpulse():
+ global _full
+ if _full is None:
+ l = ctypes.CDLL(ctypes.util.find_library("pulse") or "libpulse.so.0")
+ l.pa_mainloop_new.restype = ctypes.c_void_p
+ l.pa_mainloop_get_api.restype = ctypes.c_void_p
+ l.pa_mainloop_get_api.argtypes = [ctypes.c_void_p]
+ l.pa_mainloop_iterate.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]
+ l.pa_mainloop_free.argtypes = [ctypes.c_void_p]
+ l.pa_context_new.restype = ctypes.c_void_p
+ l.pa_context_new.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
+ l.pa_context_connect.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_void_p]
+ l.pa_context_get_state.argtypes = [ctypes.c_void_p]
+ l.pa_context_get_server_info.restype = ctypes.c_void_p
+ l.pa_context_get_server_info.argtypes = [ctypes.c_void_p, _INFO_CB, ctypes.c_void_p]
+ l.pa_operation_get_state.argtypes = [ctypes.c_void_p]
+ l.pa_operation_unref.argtypes = [ctypes.c_void_p]
+ l.pa_context_disconnect.argtypes = [ctypes.c_void_p]
+ l.pa_context_unref.argtypes = [ctypes.c_void_p]
+ _full = l
+ return _full
+
+
+def default_sink() -> str | None:
+ """The sound server's default output, or None when it can't be asked (a few ms, blocking)."""
+ try:
+ l = _libpulse()
+ except OSError:
+ return None
+ loop = l.pa_mainloop_new()
+ ctx = l.pa_context_new(l.pa_mainloop_get_api(loop), b"Cicada")
+ found = {}
+
+ @_INFO_CB
+ def got(_c, info, _u):
+ if info and info.contents.default_sink_name:
+ found["sink"] = info.contents.default_sink_name.decode()
+ try:
+ if l.pa_context_connect(ctx, None, 0, None) < 0:
+ return None
+ deadline = time.monotonic() + 1.0
+ op = None
+ 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
+ return None
+ if state == 4 and op is None: # READY
+ 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
+ l.pa_operation_unref(op)
+ break
+ time.sleep(0.005)
+ return found.get("sink")
+ finally:
+ l.pa_context_disconnect(ctx)
+ l.pa_context_unref(ctx)
+ l.pa_mainloop_free(loop)
+
+
+def available() -> bool:
+ try:
+ _pulse()
+ return True
+ except OSError:
+ return False
+
+
+class SystemAudio(AudioSource):
+ """16 kHz mono from "@DEFAULT_MONITOR@": the server resamples and downmixes for us."""
+
+ def __init__(self, device: str = "@DEFAULT_MONITOR@"):
+ self.device = device
+ self._stop = threading.Event()
+ self._thread = None
+
+ def start(self) -> None:
+ self._stop.clear()
+ self._thread = threading.Thread(target=self._run, name="SystemAudio", daemon=True)
+ self._thread.start()
+
+ def stop(self) -> None:
+ self._stop.set()
+
+ 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(), 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() + 20
+ while not self._stop.is_set() and time.monotonic() < deadline:
+ time.sleep(1)
+ s, err = self._open(lib)
+ if s:
+ Log.d("tap: reconnected after %s" % why)
+ return s
+ return None
+
+ def _run(self) -> None:
+ try:
+ lib = _pulse()
+ except OSError as e:
+ Log.d("tap: no libpulse (%s)" % e)
+ self._end("no libpulse")
+ return
+ s, why = self._open(lib)
+ if not s:
+ Log.d("tap: can't open %s: %s" % (self.device, why))
+ self._end(why)
+ return
+ sink = default_sink()
+ Log.d("tap: %s s16le %d Hz mono (output %s)" % (self.device, RATE, "known" if sink else "unknown"))
+ buf = ctypes.create_string_buffer(CHUNK * 2)
+ err = ctypes.c_int(0)
+ reads = 0
+ try:
+ while not self._stop.is_set():
+ if lib.pa_simple_read(s, buf, CHUNK * 2, ctypes.byref(err)) < 0:
+ why = lib.strerror(err.value).decode()
+ Log.d("tap: read failed %s" % why)
+ lib.pa_simple_free(s)
+ s = self._reopen(lib, why)
+ if s is None:
+ self._end(why)
+ return
+ sink = default_sink()
+ continue
+ reads += 1
+ if self.device == "@DEFAULT_MONITOR@" and reads % 30 == 0: # every 3 s: did the default output change?
+ now = default_sink()
+ if now and sink and now != sink:
+ Log.d("tap: default output changed, reopening")
+ lib.pa_simple_free(s)
+ s, why = self._open(lib)
+ if not s:
+ s = self._reopen(lib, why or "reopen")
+ if s is None:
+ self._end(why)
+ return
+ sink = now or sink
+ samples = array("h")
+ samples.frombytes(buf.raw)
+ cb = self.on_samples
+ if cb:
+ cb(samples)
+ finally:
+ if s:
+ lib.pa_simple_free(s)
+
+ def _end(self, why) -> None:
+ cb = self.on_ended
+ if cb:
+ cb(why)
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
new file mode 100644
index 0000000..76564ae
--- /dev/null
+++ b/linux/cicada/app/debug.py
@@ -0,0 +1,266 @@
+"""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)
+ 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>
+ pill (the records window capsule's widget sizes)"""
+from __future__ import annotations
+
+import os
+import socket
+import threading
+
+from gi.repository import GLib
+
+from ..core import jsonfmt
+from ..core.support import Log, Paths
+
+
+def path() -> str:
+ return os.path.join(os.environ.get("XDG_RUNTIME_DIR") or "/tmp", "cicada-dev.sock")
+
+
+def start(app) -> None:
+ p = path()
+ try:
+ os.unlink(p)
+ except OSError:
+ pass
+ server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ old = os.umask(0o077)
+ try:
+ server.bind(p)
+ finally:
+ os.umask(old)
+ server.listen(4)
+ threading.Thread(target=_serve, args=(app, server), name="Debug", daemon=True).start()
+ Log.d("debug: listening on %s" % p)
+
+
+def _serve(app, server) -> None:
+ while True:
+ conn, _ = server.accept()
+ with conn:
+ try:
+ data = b""
+ while not data.endswith(b"\n"):
+ chunk = conn.recv(4096)
+ if not chunk:
+ break
+ data += chunk
+ reply = _on_main(app, data.decode().strip())
+ except Exception as e: # noqa: BLE001 - report, don't kill the server
+ reply = {"ok": False, "error": "%s: %s" % (type(e).__name__, e)}
+ conn.sendall((jsonfmt.write(reply, pretty=False) + "\n").encode())
+
+
+def _on_main(app, line: str) -> dict:
+ done = threading.Event()
+ box = {}
+
+ def run():
+ try:
+ box["r"] = command(app, line)
+ except Exception as e: # noqa: BLE001
+ box["r"] = {"ok": False, "error": "%s: %s" % (type(e).__name__, e)}
+ done.set()
+ return False
+ GLib.idle_add(run)
+ done.wait(10)
+ return box.get("r", {"ok": False, "error": "timeout"})
+
+
+def _window(w) -> dict | None:
+ if w is None:
+ return None
+ x, y = w.get_position()
+ width, height = w.get_size()
+ gdk = w.get_window()
+ return {"visible": w.get_visible(), "x": x, "y": y, "w": width, "h": height, "title": w.get_title(),
+ "xid": gdk.get_xid() if gdk is not None and hasattr(gdk, "get_xid") else None,
+ "acceptFocus": w.get_accept_focus(), "active": w.is_active()}
+
+
+def _speakers(app, s) -> dict:
+ from ..core import speakers
+ out = {"on": app.settings.speakerVoices, "available": app.voices_available, "model": app.speakers._model is not None}
+ if s is not None:
+ vnums = speakers.voice_numbers(s.lines)
+ out.update({"voices": sorted({l.voice for l in s.lines if l.voice is not None}),
+ "shown": {str(v): n for v, n in vnums.items()}, "names": {str(k): v for k, v in speakers.names(s).items()},
+ "tagged": sum(1 for l in s.lines if l.voice is not None), "lines": len(s.lines),
+ "byVoice": [[l.id, l.voice, l.src[:40]] for l in s.lines]})
+ return out
+
+
+def command(app, line: str) -> dict:
+ parts = line.split(" ", 1)
+ cmd, arg = parts[0], (parts[1] if len(parts) > 1 else "")
+ listen = app.listen
+ if cmd == "state":
+ sid = listen.session_id
+ s = app.store.get(sid) if sid else None
+ last = s.lines[-1] if s and s.lines else None
+ n = app.notes.notes
+ return {"ok": True, "listening": listen.listening, "session": sid, "source": listen.source_kind,
+ "lines": len(s.lines) if s else 0, "last": {"src": last.src, "dst": last.dst, "lang": last.srcLang} if last else None,
+ "pending": listen.pending, "problem": listen.problem, "problemKind": listen.problem_kind, "heardSeconds": round(listen.heard_seconds, 1),
+ "peak": round(listen.peak, 4), "notes": {"title": n.title, "topics": len(n.topics), "status": app.notes.status, "final": n.final},
+ "key": app.ling.key_state, "view": app.settings.view, "target": app.settings.target_code,
+ "ui": __import__("cicada.core.strings", fromlist=["language"]).language, "records": len(app.store.all()),
+ "tray": app.tray is not None, "home": Paths.data(),
+ "speak": {"enabled": app.settings.speakEnabled, "room": app.room.on, "active": app.speak.active, "stage": app.speak.stage,
+ "spoken": app.speak.spoken, "problem": app.speak.problem, "to": app.speak.target,
+ "last": list(app.speak.last) if app.speak.last else None},
+ "speakers": _speakers(app, s),
+ "ending": {"title": app.ending_title(app.ending), "left": app.ending_left(app.ending),
+ "reason": repr(app.ending.reason)} if app.ending else None,
+ "autoEnded": app.auto_ended, "fakeCalls": app.fake_calls,
+ "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":
+ app.toggle_listening() if not listen.listening else None
+ return {"ok": True}
+ if cmd == "stop":
+ app.stop_listening()
+ return {"ok": True}
+ if cmd == "feed":
+ if not os.path.isfile(arg):
+ return {"ok": False, "error": "no such file"}
+ app.feed(arg)
+ return {"ok": True}
+ if cmd == "sample":
+ app.play_sample()
+ return {"ok": True}
+ if cmd == "view":
+ app.set_view(arg)
+ return {"ok": True, "view": app.settings.view}
+ if cmd == "show":
+ {"records": app.show_records, "notes": app.show_notes, "settings": app.show_settings,
+ "onboarding": app.show_onboarding}[arg]()
+ return {"ok": True}
+ if cmd == "target":
+ app.settings.target = arg
+ app.settings.save()
+ return {"ok": True, "target": app.settings.target_code}
+ if cmd == "key-reload":
+ app.key.reload()
+ app.ling.key_changed()
+ threading.Thread(target=app.ling.check, daemon=True).start()
+ return {"ok": True}
+ if cmd == "windows":
+ return {"ok": True, "notes": _window(app.notes_window), "records": _window(app.records_window),
+ "settings": _window(app.settings_window), "onboarding": _window(app.onboarding)}
+ 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()
+ out = ["%s%s %dx%d+%d+%d %s" % (" " * depth, type(w).__name__, a.width, a.height, a.x, a.y,
+ ".".join(ctx.list_classes()))]
+ if hasattr(w, "get_children") and depth < 8:
+ for c in w.get_children():
+ out += tree(c, depth + 1)
+ return out
+ return {"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 record
+ if arg in ("on", "off"):
+ app.set_speaker_voices(arg == "on")
+ return {"ok": True, "on": app.settings.speakerVoices}
+ return {"ok": True, **_speakers(app, app.store.get(arg))}
+ if cmd == "speak-enable":
+ return {"ok": app.set_speak_enabled(arg == "on"), "enabled": app.settings.speakEnabled, "realMic": app.room.real_mic}
+ if cmd == "speak":
+ if (arg == "on") != app.speak.active:
+ app.toggle_speaking()
+ return {"ok": True, "speaking": app.speak.active}
+ if cmd == "select":
+ app.show_records()
+ app.records_window.selected = arg
+ 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 TranscriptLine
+ sid, n = arg.split()
+ s = app.store.get(sid)
+ if s is None:
+ return {"ok": False, "error": "no such record"}
+ base = len(s.lines)
+
+ def add(i=[0]):
+ k = base + i[0]
+ app.store.append(sid, TranscriptLine(id="h%d-%d" % (k + 1, k + 1), t=k * 4.2, src="Appended line %d." % (k + 1),
+ dst="追加的第 %d 句。" % (k + 1), srcLang="en", dstLang="zh-CN"))
+ i[0] += 1
+ return i[0] < int(n)
+ GLib.timeout_add(300, add)
+ return {"ok": True}
+ if cmd == "calls":
+ if arg == "real":
+ app.fake_calls = None
+ elif arg in ("", "none"):
+ app.fake_calls = {}
+ else:
+ app.fake_calls = dict(p.split("=", 1) for p in arg.split(","))
+ return {"ok": True, "fakeCalls": app.fake_calls}
+ if cmd == "realcalls":
+ from ..core import meeting_end
+ return {"ok": True, "calls": meeting_end.calls()}
+ if cmd == "endtimes":
+ app.end_times = None if arg in ("", "off") else tuple(float(x) for x in arg.split())
+ return {"ok": True, "endTimes": app.end_times}
+ if cmd == "endkeep":
+ app.keep_recording()
+ return {"ok": True}
+ if cmd in ("notes-tab", "notes-search", "notes-wide"):
+ app.show_notes()
+ w = app.notes_window
+ if cmd == "notes-tab":
+ w.set_tab(arg)
+ elif cmd == "notes-search":
+ w.set_tab("transcript")
+ w.search.set_text(arg)
+ else:
+ w.set_wide(arg == "on")
+ return {"ok": True, "tab": w.tab, "wide": w.wide, "matches": len(w.matches), "match": w.match_index}
+ if cmd == "rename":
+ # `rename <id> <title>`; no title is 恢复自动标题.
+ sid, _, title = arg.partition(" ")
+ app.store.rename(sid, title)
+ s = app.store.get(sid)
+ from ..core import session_store
+ return {"ok": s is not None, "title": s.title if s else None, "renamed": s.renamed if s else None,
+ "shown": session_store.display_title(s) if s else None}
+ if cmd == "delete":
+ app.store.delete(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 = arg
+ app.changed()
+ return {"ok": True, "status": app.notes.status}
+ if cmd == "settings-scroll":
+ app.show_settings()
+ adj = app.settings_window.get_child().get_vadjustment()
+ adj.set_value(float(arg) * (adj.get_upper() - adj.get_page_size()))
+ return {"ok": True}
+ if cmd == "onboarding-step":
+ app.show_onboarding()
+ app.onboarding.go(int(arg))
+ return {"ok": True, "step": app.onboarding.step}
+ if cmd == "quit":
+ app.quit()
+ return {"ok": True}
+ return {"ok": False, "error": "unknown command " + cmd}
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
new file mode 100644
index 0000000..7474ddc
--- /dev/null
+++ b/linux/cicada/app/main.py
@@ -0,0 +1,630 @@
+"""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 annotations
+
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import threading
+import time
+from 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"
+
+import gi # noqa: E402
+
+gi.require_version("Gtk", "3.0")
+gi.require_version("Gdk", "3.0")
+from gi.repository import Gdk, Gio, GLib, Gtk # noqa: E402
+
+from ..core import strings # noqa: E402
+from ..core.audio import PcmAudioSource # noqa: E402
+from ..core import meeting_end # noqa: E402
+from ..core.ling import AIKey, LingClient # noqa: E402
+from ..core.listen import ListenEngine # noqa: E402
+from ..core.notes import NotesEngine # noqa: E402
+from ..core.session_store import SessionStore # noqa: E402
+from ..core.settings import AppSettings # noqa: E402
+from ..core.strings import L, LF # noqa: E402
+from ..core.support import Log, Paths, clock, english_name # noqa: E402
+from ..core.translator import Translator # noqa: E402
+from . import debug, tray, ui # noqa: E402
+from .capture import SystemAudio # noqa: E402
+
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # linux/ or the installed tree
+
+
+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]
+ return [os.path.join(ROOT, "..", "Resources"), os.path.join(ROOT, "strings")]
+
+
+def icon_path() -> str | None:
+ for p in (os.path.join(ROOT, "cicada.svg"), os.path.join(ROOT, "..", "site", "icon.svg")):
+ if os.path.isfile(p):
+ return os.path.abspath(p)
+ return None
+
+
+def sample_path() -> str | None:
+ for p in (os.path.join(ROOT, "sample.wav"), os.path.join(ROOT, "build", "cicada-linux", "sample.wav")):
+ if os.path.isfile(p):
+ return p
+ return None
+
+
+class Controller:
+ def __init__(self, application: Gtk.Application):
+ self.application = application
+ self.settings = AppSettings.load()
+ strings.load(self.settings.ui_code, resource_dirs())
+ self.key = AIKey()
+ self.ling = LingClient(self.key)
+ self.ling.model = self.settings.model
+ self.store = SessionStore()
+ self.notes = NotesEngine(self.ling, self.store)
+ # 纪要语言 for notes written outside a meeting too (生成纪要 in the records window).
+ self.notes.language = lambda: english_name(self.settings.notes_code)
+ self.translator = Translator(self.ling)
+ self.listen = ListenEngine(self.ling, self.translator, self.store, self.notes, self.settings)
+ # 同声传译: my microphone → Ming → 知了 麦克风. The listen side's loudness feeds its echo check.
+ from ..core.speak import SpeakEngine
+ from .room import Player, VirtualMic
+ self.room = VirtualMic()
+ self.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 speakers
+ self.speakers = speakers.Tagger()
+ self.listen.speakers = self.speakers
+ self.namer = speakers.Namer(self.ling, self.store, self.changed)
+ self.listen.on_voice = self.namer.guess
+ self.notes.voices = lambda: self.settings.speakerVoices
+ self.speak.on_change(self.changed)
+ self.listen.on_change(self.changed)
+ self.notes.on_change(self.changed)
+ self.store.on_change(lambda _id: self.changed())
+ self.store.on_words(self._words)
+ self.ling.on_change(self.changed)
+ self.notes_window = None
+ self.records_window = None
+ self.settings_window = None
+ self.onboarding = None
+ self.tray = None
+ self._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.end_watch = None
+ self.ending = None
+ self.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._calls_busy = False
+ GLib.timeout_add_seconds(1, self._tick)
+ GLib.timeout_add_seconds(2, self._watch_end)
+
+ def _tick(self) -> bool:
+ if self.tray is not None and self.listen.listening:
+ self.tray.tick()
+ return True
+
+ def launch(self, speak: bool = False) -> None:
+ ui.install_css()
+ lang = strings.language
+ ui.DEFAULT_LANG = ui.pango_lang({"zh-Hans": "zh-CN"}.get(lang, lang)) if lang != "en" else ui.pango_lang(self.settings.notes_code)
+ backend = type(Gdk.Display.get_default()).__name__
+ Log.d("app: launch %s %s on %s, session %s" % ("dev" if Paths.dev else "release", sys.version.split()[0], backend,
+ os.environ.get("XDG_SESSION_TYPE", "?")))
+ icon = icon_path()
+ if icon:
+ try:
+ Gtk.Window.set_default_icon_from_file(icon)
+ except GLib.Error:
+ pass
+ self.tray = tray.make(self, icon)
+ def prepare():
+ (self.room.create if self.settings.speakEnabled else self.room.leftovers)()
+ if speak: # `cicada --speak` before Cicada was running: speak once 知了 麦克风 is there
+ 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:
+ debug.start(self)
+ if not self.settings.onboarded:
+ self.show_onboarding()
+ else:
+ if self.ling.has_key:
+ threading.Thread(target=self.ling.check, daemon=True).start()
+ # Without a tray (plain GNOME has none) the records window is how the app is reached.
+ if self.tray is None:
+ self.show_records()
+
+ def changed(self) -> None:
+ """Engine threads call this: one coalesced refresh on the main loop."""
+ if self._queued:
+ return
+ self._queued = True
+
+ def run():
+ self._queued = False
+ if self.notes_window is not None:
+ self.notes_window.refresh()
+ if self.records_window is not None:
+ self.records_window.refresh()
+ if self.onboarding is not None:
+ self.onboarding.refresh()
+ if self.tray is not None:
+ self.tray.update()
+ return False
+ GLib.idle_add(run)
+
+ # Windows
+
+ def show_notes(self) -> None:
+ if self.notes_window is None:
+ from .notes_window import NotesWindow
+ self.notes_window = NotesWindow(self)
+ self.application.add_window(self.notes_window)
+ self.notes_window.refresh()
+ self.notes_window.show_all()
+
+ def show_records(self) -> None:
+ if self.records_window is None:
+ from .records_window import RecordsWindow
+ self.records_window = RecordsWindow(self)
+ self.application.add_window(self.records_window)
+ self.records_window.fill()
+ self.records_window.show_all()
+ self.records_window.present()
+ self.records_window.set_focus(None) # not the search box: its placeholder would vanish
+
+ def show_settings(self) -> None:
+ if self.settings_window is None:
+ from .settings_window import SettingsWindow
+ self.settings_window = SettingsWindow(self)
+ self.application.add_window(self.settings_window)
+ self.settings_window.show_all()
+ self.settings_window.present()
+
+ def show_onboarding(self) -> None:
+ if self.onboarding is not None:
+ self.onboarding.present()
+ return
+ from .onboarding import Onboarding
+ self.onboarding = Onboarding(self)
+ self.application.add_window(self.onboarding)
+
+ def closed(*_):
+ self.onboarding = None
+ if self.tray is None and self.settings.onboarded:
+ self.show_records()
+ self.onboarding.connect("destroy", closed)
+ self.onboarding.show_all()
+ self.onboarding.present()
+
+ def set_view(self, view: str) -> None:
+ if view not in ("notes", "subtitles") or view == self.settings.view:
+ return
+ self.settings.view = view
+ self.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()
+ self.notes_window = None
+ if visible:
+ self.show_notes()
+
+ def settings_changed(self) -> None:
+ self.changed()
+
+ # Listening
+
+ def toggle_listening(self) -> None:
+ if self.listen.listening:
+ self.stop_listening()
+ else:
+ self.start_listening(SystemAudio(), "system")
+
+ def 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 None
+ if s is None or not s.lines:
+ return None
+ return (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
+ rec = self.recorded()
+ if rec is None:
+ self.stop_listening()
+ return
+ sid = 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)
+ dialog.set_keep_above(True)
+ ui.classes(dialog, "endask")
+ body = ui.vbox(6, ui.text(L("结束这场会议?"), 15, "ink", bold=True, width_chars=34),
+ ui.text(LF("已记录 %@ · %lld 句。结束后停止收听,并整理一份完整版纪要。", clock(rec[0]), rec[1]),
+ 12, "secondary", width_chars=34))
+ keep = ui.button(L("继续记录"), lambda: dialog.response(Gtk.ResponseType.CANCEL), "outline")
+ end = ui.button(L("结束会议"), lambda: dialog.response(Gtk.ResponseType.ACCEPT), "darkbtn")
+ row = ui.hbox(8)
+ row.set_halign(Gtk.Align.END)
+ row.pack_start(keep, False, False, 0)
+ row.pack_start(end, False, False, 0)
+ area = dialog.get_content_area()
+ area.pack_start(ui.pad(ui.vbox(18, body, row), 22, 22), True, True, 0)
+ area.show_all()
+ keep.set_can_default(True)
+ keep.grab_default()
+ 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()
+
+ def start_listening(self, source, kind: str) -> None:
+ if self.listen.listening:
+ return
+ if not self.ling.has_key:
+ self.show_onboarding()
+ return
+
+ 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)
+ return
+ Log.d("listen: source ended %s" % reason)
+ # Said where the subtitles would be (start() clears it), not silently stopped.
+ self.listen.problem = L("系统声音中断")
+ self.listen.problem_kind = "source"
+ GLib.idle_add(lambda: self.stop_listening() and False)
+ source.on_ended = ended
+ self.auto_ended = False
+ self.ending = None
+ self.end_watch = meeting_end.MeetingEndWatch(self.end_config(), time.time())
+ self.listen.start(source, kind)
+ self.show_notes()
+ self.changed()
+
+ # 结束会议
+
+ def end_config(self) -> meeting_end.Config:
+ s = self.settings
+ c = meeting_end.Config(follow_apps=s.endWithApp, silence=s.silenceEnd, silence_after=s.silenceMinutes * 60)
+ if self.end_times:
+ c.silence_after, c.countdown, c.app_grace = self.end_times
+ return c
+
+ def _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 None
+ after = not self.listen.listening and self.auto_ended
+ if self._calls_busy or not (listening or after):
+ return True
+ follow = self.settings.endWithApp
+ if not follow and not listening:
+ return True
+ self._calls_busy = True
+
+ def read():
+ calls = (self.fake_calls if self.fake_calls is not None else meeting_end.calls()) if follow else {}
+
+ def apply():
+ self._calls_busy = False
+ self._end_tick(calls)
+ return False
+ GLib.idle_add(apply)
+ threading.Thread(target=read, daemon=True).start()
+ return True
+
+ def _end_tick(self, calls: dict) -> None:
+ now = time.time()
+ if self.listen.listening and self.end_watch is not None:
+ w = self.end_watch
+ w.config = self.end_config()
+ s = self.store.get(self.listen.session_id) if self.listen.session_id else None
+ reason = w.tick(now, calls, bool(s and s.lines))
+ self._set_ending(w.pending)
+ if reason is not None:
+ self._auto_end(reason, w)
+ elif not self.listen.listening and self.auto_ended and self.settings.endWithApp and calls:
+ Log.d("meeting end: a meeting app started a call, starting a new meeting")
+ self.start_listening(SystemAudio(), "system")
+
+ 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())
+ self._set_ending(self.end_watch.pending)
+ return False
+ GLib.idle_add(run)
+
+ def _set_ending(self, p) -> None:
+ if p == self.ending:
+ return
+ if p is not None:
+ Log.d("meeting end: pending %r, ends in %d s" % (p.reason, p.deadline - time.time()))
+ elif self.ending is not None:
+ Log.d("meeting end: pending cleared")
+ self.ending = p
+ self.changed()
+
+ 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 + 5
+ if reason.kind == "app":
+ at = max(at, time.time() - w.config.app_grace)
+ at = min(at, time.time())
+ Log.d("meeting end: ended by itself (%r), end time %d s ago" % (reason, time.time() - at))
+ 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)
+ Log.d("meeting end: kept going")
+
+ def ending_title(self, p) -> str:
+ if p.reason.kind == "app":
+ return LF("%@ 已挂断", p.reason.name)
+ return LF("已经 %lld 分钟没人说话", max(1, round(self.end_config().silence_after / 60)))
+
+ 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 and not self.room.create():
+ return False
+ if not on:
+ self.speak.cancel()
+ self.room.remove()
+ self.settings.speakEnabled = on
+ self.settings.save()
+ self.changed()
+ return True
+
+ def toggle_speaking(self) -> None:
+ if self.speak.active:
+ self.speak.stop()
+ return
+ if not self.ling.has_key:
+ self.show_onboarding()
+ return
+ if not self.settings.speakEnabled or not self.room.on:
+ if not self.set_speak_enabled(True):
+ self.speak.problem = L("没能建好知了麦克风")
+ self.changed()
+ return
+ # Me, from the microphone that was the default before 知了 麦克风 took its place.
+ mic = SystemAudio(self.room.real_mic or "@DEFAULT_SOURCE@")
+
+ def ended(reason):
+ if reason:
+ Log.d("speak: microphone ended %s" % reason)
+ self.speak.problem = L("没有可用的麦克风")
+ GLib.idle_add(lambda: self.speak.stop() or False)
+ mic.on_ended = ended
+ self.speak.start(mic)
+ self.show_notes()
+
+ def stop_listening(self, ended_at=None, auto: bool = False) -> None:
+ self.end_watch = None
+ self.ending = None
+ self.auto_ended = auto
+
+ # stop() waits for Ming's last replies: off the main loop.
+ def run():
+ sid = self.listen.session_id
+ self.listen.stop(ended_at)
+ if sid and self.settings.speakerVoices:
+ self.namer.guess(sid, force=True) # the whole meeting read once more for names
+ self.changed()
+ threading.Thread(target=run, daemon=True).start()
+
+ # 说话人识别
+
+ @property
+ def voices_available(self) -> bool:
+ from ..core import speakers
+ return speakers.library_path() is not None and speakers.model_path() is not None
+
+ def set_speaker_voices(self, on: bool) -> None:
+ self.settings.speakerVoices = on
+ self.settings.save()
+ Log.d("speakers: %s" % ("on" if on else "off"))
+ 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 snap
+
+ def 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 speakers
+ s = self.store.get(sid)
+ if s is None:
+ return None, None
+ n = speakers.voice_numbers(s.lines).get(voice, 0)
+ before = speakers.label(n, speakers.names(s))
+ snap = self._speaker_edit(sid, lambda: self.store.set_voice_name(sid, voice, name))
+ after = speakers.label(n, speakers.names(self.store.get(sid)))
+ Log.d("speakers: renamed a voice in %s" % sid)
+ return (LF("%@ 已改成 %@", before, after) if after != before else None), snap
+
+ def 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 speakers
+ s = self.store.get(sid)
+ if s is None:
+ return None, None
+ nums, shown = speakers.voice_numbers(s.lines), speakers.names(s)
+ a, b = speakers.label(nums.get(frm, 0), shown), speakers.label(nums.get(into, 0), shown)
+ snap = self._speaker_edit(sid, lambda: self.store.merge_voice(sid, frm, into))
+ if self.listen.listening and self.listen.session_id == sid:
+ self.speakers.merge(frm, into)
+ Log.d("speakers: merged two voices in %s" % sid)
+ return LF("%@ 已并入 %@", a, b), snap
+
+ def assign_lines(self, sid: str, ids: set, voice: int):
+ """These lines were someone else's."""
+ from ..core import speakers
+ s = self.store.get(sid)
+ if s is None:
+ return None, None
+ first = next((l for l in s.lines if l.id in ids), None)
+ snap = self._speaker_edit(sid, lambda: self.store.set_line_voices(sid, ids, voice))
+ s2 = self.store.get(sid)
+ who = speakers.label(speakers.voice_numbers(s2.lines).get(voice, 0), speakers.names(s2))
+ return LF("%@ 这句已改给 %@", clock(first.t) if first else "", who), snap
+
+ def undo_speaker_edit(self, sid: str, snap) -> None:
+ if snap is not None:
+ self.store.restore(sid, snap)
+ 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")
+ return
+ if self.listen.listening:
+ return
+ player = next((p for p in ("pw-play", "paplay", "aplay") if shutil.which(p)), None)
+ self.start_listening(PcmAudioSource(path, 1.0), "file")
+ if player and self.listen.listening:
+ try:
+ subprocess.Popen([player, path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ except OSError as e:
+ 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:
+ Log.d("app: signal %d, quitting" % sig)
+ self.quit()
+ return False
+
+ def quit(self) -> None:
+ if self.records_window is not None:
+ self.records_window.commit_delete() # a delete still showing 撤销 goes through
+
+ def run():
+ self.speak.cancel()
+ if self.room.on:
+ self.room.remove() # the real microphone is the default again
+ if self.listen.listening:
+ self.listen.stop()
+ self.store.flush()
+ GLib.idle_add(lambda: self.application.quit() and False)
+ threading.Thread(target=run, daemon=True).start()
+
+
+class App(Gtk.Application):
+ def __init__(self):
+ super().__init__(application_id="com.wquguru.cicada.dev" if Paths.dev else "com.wquguru.cicada",
+ flags=Gio.ApplicationFlags.FLAGS_NONE)
+ self.controller = None
+
+ def do_startup(self):
+ Gtk.Application.do_startup(self)
+ self.hold() # a menu bar style app: no window doesn't mean quit
+ 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.connect("activate", lambda *_: self.controller.toggle_speaking())
+ self.add_action(speak)
+ for name, action, keys in (("quit", self.controller.quit, ["<Control>q"]),
+ ("settings", self.controller.show_settings, ["<Control>comma"])):
+ a = Gio.SimpleAction.new(name, None)
+ a.connect("activate", lambda _a, _p, f=action: f())
+ self.add_action(a)
+ self.set_accels_for_action("app." + name, keys)
+ self.controller.launch(speak=getattr(self, "speak_at_start", False))
+ if getattr(self, "toggle_at_start", False):
+ GLib.idle_add(lambda: self.controller.toggle_listening() and False)
+
+ def do_activate(self):
+ # A second launch lands here in the running instance: open the records.
+ if self.controller is not None and self.controller.settings.onboarded and getattr(self, "_activated", False):
+ self.controller.show_records()
+ self._activated = True
+
+
+def main(argv=None) -> int:
+ argv = list(sys.argv if argv is None else argv)
+ if "--dev" in argv:
+ Paths.dev = True
+ argv.remove("--dev")
+ GLib.set_prgname("cicada")
+ app = App()
+ for 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.
+ setattr(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",
+ GLib.Variant("(sava{sv})", (action, [], {})), None, Gio.DBusCallFlags.NO_AUTO_START, 3000, None)
+ return True
+ except GLib.Error:
+ return False
diff --git a/linux/cicada/app/notes_window.py b/linux/cicada/app/notes_window.py
new file mode 100644
index 0000000..147f6b2
--- /dev/null
+++ b/linux/cicada/app/notes_window.py
@@ -0,0 +1,752 @@
+"""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 annotations
+
+from datetime import datetime, timezone
+
+from gi.repository import Gdk, GLib, Gtk
+
+from ..core import notes as notesmod
+from ..core import speakers
+from ..core.strings import L, LF
+from ..core.support import Log, clock
+from . import ui, x11
+
+
+class NotesWindow(Gtk.Window):
+ def __init__(self, app):
+ super().__init__(type=Gtk.WindowType.TOPLEVEL)
+ self.app = app
+ self.set_title(L("知了"))
+ self.set_decorated(False)
+ self.set_keep_above(True)
+ self.set_accept_focus(False)
+ 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()
+ visual = screen.get_rgba_visual()
+ if visual is not None and screen.is_composited():
+ self.set_visual(visual)
+ self.set_app_paintable(True)
+ ui.classes(self, "notes-window")
+ self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.BUTTON1_MOTION_MASK)
+ self._grab = None
+ 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.connect("configure-event", self._configured)
+ self.connect("realize", lambda w: x11.never_take_focus(w.get_window()))
+ self.connect("delete-event", lambda *_: self.hide() or True)
+ self._queued = False
+ self._built = False
+ self._timer = None
+ # 纪要 / 文字记录, the search in the transcript and 纪要和原话并排 (NotesWindow.swift).
+ self.tab = "notes"
+ self.wide = False
+ self.query = ""
+ self.matches = []
+ self.match_index = 0
+ self._transcript_key = None
+ self._keys = False # taking the keyboard while the search is typed in
+ self.connect("show", lambda *_: self._start_clock())
+ self.connect("hide", lambda *_: self._stop_clock())
+ self.render()
+ self.place()
+
+ @property
+ def subtitles(self) -> bool:
+ return self.app.settings.view == "subtitles"
+
+ @property
+ 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:
+ x, y = self.get_position()
+ self._grab = (event.x_root - x, event.y_root - y)
+ return False
+
+ def _motion(self, _w, event):
+ if self._grab is not None:
+ x, y = int(event.x_root - self._grab[0]), int(event.y_root - self._grab[1])
+ self.move(x, y)
+ if self._bottom is not None:
+ self._bottom = y + self.get_size()[1]
+ return False
+
+ def _configured(self, _w, event):
+ if self.subtitles and self._bottom is not None and self._grab is None and event.y + event.height != self._bottom:
+ self.move(event.x, self._bottom - event.height)
+ return False
+
+ def 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()
+ if self.subtitles:
+ w = min(860, area.width - 40)
+ self.set_size_request(w, -1)
+ self.resize(w, 1)
+ self._bottom = area.y + area.height - 16
+ self.move(area.x + (area.width - w) // 2, self._bottom - 120)
+ else:
+ h = min(680, area.height - 40)
+ w = 820 if self.wide else 400
+ self.set_size_request(w, 260)
+ self.resize(w, h)
+ self.move(area.x + area.width - w - 12, area.y + 12)
+
+ def _start_clock(self):
+ if self._timer is None:
+ self._timer = GLib.timeout_add_seconds(1, self._tick)
+
+ def _stop_clock(self):
+ if self._timer is not None:
+ GLib.source_remove(self._timer)
+ self._timer = None
+
+ def _tick(self):
+ if self.app.listen.listening:
+ self._fill_header()
+ s = self.app.store.get(self.app.listen.session_id) if self.app.listen.session_id else None
+ if s is not None and not s.lines:
+ self._fill_live() # before the first line the state follows the sound
+ if self.footer_time is not None:
+ self._fill_footer()
+ self._fill_ending()
+ return True
+
+ def refresh(self) -> None:
+ """Changes come from engine threads (via the controller): coalesce them into one render."""
+ if self._queued:
+ return
+ self._queued = True
+
+ def run():
+ self._queued = False
+ self.render()
+ return False
+ GLib.idle_add(run)
+
+ # Layout
+
+ def _build(self) -> None:
+ self._built = True
+ outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
+ self.panel = ui.panel(outer, "panel")
+ ui.pad(self.panel, 8)
+ 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)
+ self.live = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
+ self.body = None
+ self.footer_time = None
+ self.speakbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
+ 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)
+ ui.classes(self.tabs, "segmented", "big")
+ self.tab_buttons = {}
+ for value in ("notes", "transcript"):
+ b = Gtk.ToggleButton()
+ b.add(ui.text("", 13, "", wrap=False, ellipsize=False))
+ b.set_can_focus(False)
+ b.connect("toggled", self._tab_toggled, value)
+ self.tab_buttons[value] = b
+ self.tabs.pack_start(b, True, True, 0)
+ 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)
+ self.columns = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0, homogeneous=True)
+ self.scroll = Gtk.ScrolledWindow()
+ self.scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
+ self.body = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
+ ui.pad(self.body, 6, 18, 12, 18)
+ self.scroll.add(self.body)
+ self.columns.pack_start(self.scroll, True, True, 0)
+ self.transcript_col = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
+ self.transcript_col.pack_start(self._search_row(), False, False, 0)
+ self.tscroll = Gtk.ScrolledWindow()
+ self.tscroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
+ self.transcript = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=14)
+ ui.pad(self.transcript, 4, 18, 12, 18)
+ self.tscroll.add(self.transcript)
+ self._after_layout = None
+ self.transcript.connect("size-allocate", self._laid_out)
+ 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)
+ outer.pack_start(self.live_box, False, False, 0)
+ for w in (self.ending_wrap, self.tabs_wrap, self.scroll, self.transcript_col, self.live_box):
+ w.set_no_show_all(True)
+ speak_panel = ui.panel(ui.pad(self.speakbox, 10, 16), "speakbox")
+ self.speakwrap = Gtk.Box()
+ self.speakwrap.pack_start(ui.pad(speak_panel, 8, 12, 0, 12), True, True, 0)
+ outer.pack_start(self.speakwrap, False, False, 0)
+ footer = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
+ ui.pad(footer, 9, 16)
+ eye = ui.icon("view-reveal-symbolic", 12)
+ ui.classes(eye, "secondary")
+ footer.pack_start(eye, False, False, 0)
+ footer.pack_start(ui.text(L("共享屏幕时此窗口可见"), 11, "tertiary", wrap=False), False, False, 0)
+ self.footer_time = ui.text("", 11, "tertiary", wrap=False)
+ footer.pack_end(self.footer_time, False, False, 0)
+ outer.pack_start(ui.panel(footer, "footer"), False, False, 0)
+ self.add(self.panel)
+ self.speakwrap.set_no_show_all(True)
+ self.panel.show_all()
+ if self.body is not None:
+ 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.connect("key-press-event", self._key)
+ self.connect("focus-out-event", lambda *_: self._take_keys(False) or False)
+
+ def render(self) -> None:
+ 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
+ ctx.add_class("dark")
+ else:
+ ctx.remove_class("dark")
+ self._fill_header()
+ 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()
+ self._fill_ending()
+ adj = self.scroll.get_vadjustment()
+ keep = adj.get_value()
+ self._fill_body()
+ self._fill_footer()
+ GLib.idle_add(lambda: adj.set_value(keep) and False)
+ self._fill_transcript()
+
+ def _fill_header(self) -> None:
+ h = self.header
+ ui.clear(h)
+ listen = self.app.listen
+ session = self.app.store.get(listen.session_id) if listen.session_id else None
+ h.pack_start(ui.breathing_dot() if listen.listening else ui.dot(False), False, False, 4)
+ if listen.listening and session is not None:
+ h.pack_start(ui.text(L("正在听"), 13, "ink", bold=True, wrap=False, ellipsize=False), False, False, 2)
+ t = ui.text(clock((datetime.now(timezone.utc) - session.startedAt).total_seconds()), 13, "tertiary", wrap=False, ellipsize=False)
+ h.pack_start(t, False, False, 0)
+ else:
+ h.pack_start(ui.text(L("知了"), 13, "ink", bold=True, wrap=False, ellipsize=False), False, False, 2)
+ h.pack_end(ui.icon_button("window-close-symbolic", L("隐藏纪要(继续听)") if not self.subtitles else L("隐藏字幕条(继续听)"),
+ self.hide, focus=False), False, False, 0)
+ if listen.listening:
+ h.pack_end(ui.icon_button("media-playback-stop-symbolic", L("结束"), self._ask_end, "stop", 14, focus=False), False, False, 0)
+ else:
+ h.pack_end(ui.icon_button("media-record-symbolic", L("开始听"), self.app.toggle_listening, "stop", 14, focus=False), False, False, 0)
+ if self.app.settings.speakEnabled:
+ speaking = self.app.speak.active
+ h.pack_end(ui.icon_button("audio-input-microphone-symbolic", L("停止说") if speaking else L("开始说"),
+ self.app.toggle_speaking, "stop" if speaking else "", focus=False), False, False, 0)
+ if self.subtitles:
+ h.pack_end(ui.icon_button("x-office-document-symbolic", L("切到实时纪要"), lambda: self.app.set_view("notes"), focus=False), False, False, 0)
+ else:
+ h.pack_end(ui.icon_button("media-view-subtitles-symbolic", L("切到字幕条"), lambda: self.app.set_view("subtitles"), focus=False), False, False, 0)
+ 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.ending
+ note = 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)
+ h.show_all()
+
+ # 纪要 / 文字记录, side by side
+
+ 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 0
+ labels = {"notes": L("纪要"),
+ "transcript": LF("文字记录 · %lld", heard) if self.app.notes.notes.is_empty and heard else L("文字记录")}
+ self._setting_tab = True
+ for value, b in self.tab_buttons.items():
+ b.set_active(value == self.tab)
+ ui.retext(b.get_child(), labels[value])
+ self._setting_tab = False
+ self.tabs_wrap.set_visible(not self.wide)
+ self.scroll.set_visible(self.wide or self.tab == "notes")
+ self.transcript_col.set_visible(self.wide or self.tab == "transcript")
+ self.live_box.set_visible(not self.wide and self.tab == "notes")
+ ctx = self.columns.get_style_context()
+ (ctx.add_class if self.wide else ctx.remove_class)("wide")
+
+ def _tab_toggled(self, button, value) -> None:
+ if getattr(self, "_setting_tab", False):
+ return
+ 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
+
+ def set_tab(self, tab: str) -> None:
+ if tab not in ("notes", "transcript"):
+ return
+ self.tab = tab
+ if tab == "notes":
+ self._take_keys(False)
+ self.render()
+
+ def set_wide(self, wide: bool) -> None:
+ self.wide = wide
+ self._transcript_key = None
+ x, y = self.get_position()
+ w0 = self.get_size()[0]
+ w = 820 if wide else 400
+ self.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.render()
+
+ def _session(self):
+ sid = self.app.listen.session_id
+ return 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("搜索文字记录"))
+ self.search.set_icon_from_icon_name(Gtk.EntryIconPosition.PRIMARY, "system-search-symbolic")
+ 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)
+ self.next_b = ui.icon_button("go-down-symbolic", L("下一个"), lambda: self.step(1), px=13, focus=False)
+ self.clear_b = ui.icon_button("window-close-symbolic", L("清除"), lambda: self.search.set_text(""), px=12, focus=False)
+ self.search_tools = ui.hbox(2, self.count, self.prev_b, self.next_b, self.clear_b)
+ row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
+ row.pack_start(self.search, True, True, 0)
+ row.pack_start(self.search_tools, False, False, 0)
+ return ui.pad(row, 0, 16, 10, 16)
+
+ def _take_keys(self, on: bool) -> None:
+ if on == self._keys or self.get_window() is None:
+ return
+ self._keys = on
+ Log.d("notes window: %s the keyboard for the search" % ("takes" if on else "gives back"))
+ self.set_accept_focus(on)
+ if on:
+ x11.take_focus(self.get_window())
+ self.get_window().focus(Gtk.get_current_event_time())
+ self.present_with_time(Gtk.get_current_event_time())
+ self.search.grab_focus()
+ else:
+ x11.never_take_focus(self.get_window())
+
+ def _key(self, _w, event) -> bool:
+ name = Gdk.keyval_name(event.keyval)
+ if name == "Escape":
+ if self.search.get_text():
+ self.search.set_text("")
+ else:
+ self._take_keys(False)
+ return True
+ if event.state & Gdk.ModifierType.CONTROL_MASK and name in ("f", "F"):
+ self.set_tab("transcript")
+ self._take_keys(True)
+ return True
+ return False
+
+ def _searched(self, entry) -> None:
+ self.query = entry.get_text()
+ self.match_index = 0
+ if self.query.strip() and not self.wide and self.tab != "transcript":
+ self.set_tab("transcript")
+ return
+ self._fill_transcript(scroll=True)
+
+ def step(self, d: int) -> None:
+ if not self.matches:
+ return
+ self.match_index = (self.match_index + d) % len(self.matches)
+ self._fill_transcript(scroll=True)
+
+ def _terms(self) -> list:
+ """The query, plus every way the notes say that name was heard (江充 also finds 江松)."""
+ q = self.query.strip()
+ if not q:
+ return []
+ out = [q]
+ for t in self.app.notes.notes.terms:
+ forms = [t.name] + list(t.heard)
+ if any(f and (q.lower() in f.lower() or f.lower() in q.lower()) for f in forms):
+ out += [f for f in forms if f and f not in out]
+ return out
+
+ def _fill_transcript(self, scroll: bool = False) -> None:
+ if not self.transcript_col.get_visible():
+ return
+ session = self._session()
+ lines = session.lines if session else []
+ terms = self._terms()
+ low = [t.lower() for t in terms]
+
+ def hit(l):
+ return any(t in l.src.lower() or t in (l.dst or "").lower() for t in low)
+ self.matches = [l.id for l in lines if hit(l)] if terms else []
+ if self.matches:
+ self.match_index %= len(self.matches)
+ current = self.matches[self.match_index] if self.matches else None
+ voices = self.app.settings.speakerVoices and session is not None and session.sourceFile is None
+ nums = speakers.numbers(lines) if voices else {}
+ names = speakers.names(session) if voices else {}
+ pending = self.app.listen.listening and self.app.listen.pending > 0
+ topics = [(t.start, t.title) for t in self.app.notes.notes.topics]
+ key = (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))
+ self._fill_search_tools()
+ if key == self._transcript_key and not scroll:
+ return
+ self._transcript_key = key
+ box = self.transcript
+ adj = self.tscroll.get_vadjustment()
+ keep = adj.get_value()
+ ui.clear(box)
+ target = None
+ if not lines:
+ box.pack_start(ui.gap(ui.text(L("说话的内容会出现在这里"), 13, "tertiary"), 8), False, False, 0)
+ nxt = 0
+ for l in lines:
+ while nxt < len(topics) and topics[nxt][0] <= l.t:
+ box.pack_start(ui.text(clock(topics[nxt][0]) + " · " + topics[nxt][1], 11, "tertiary", bold=True, wrap=False), False, False, 0)
+ nxt += 1
+ row = self._line(l, nums, names, terms, l.id == current)
+ if terms and not hit(l):
+ row.set_opacity(0.45)
+ if l.id == current:
+ target = row
+ box.pack_start(row, False, False, 0)
+ if pending:
+ 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():
+ ok, _x, y = target.translate_coordinates(box, 0, 0)
+ if ok:
+ adj.set_value(max(0, y - adj.get_page_size() / 3))
+ self._after_layout = to_match
+ elif not terms and self.app.listen.listening:
+ self._after_layout = lambda: adj.set_value(adj.get_upper())
+ elif target is None or not scroll:
+ self._after_layout = lambda: adj.set_value(keep)
+
+ def _laid_out(self, *_):
+ fn, self._after_layout = self._after_layout, None
+ if 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)
+
+ def _fill_search_tools(self) -> None:
+ searching = bool(self.query.strip())
+ self.search_tools.set_visible(searching)
+ if searching:
+ ui.retext(self.count, "%d / %d" % (self.match_index + 1, len(self.matches)) if self.matches else L("无结果"))
+ for b in (self.prev_b, self.next_b):
+ b.set_sensitive(bool(self.matches))
+
+ def _line(self, l, nums, names, terms, current) -> Gtk.Widget:
+ row = ui.vbox(2)
+ top = ui.hbox(8)
+ if l.speaker == "me":
+ top.pack_start(ui.text(L("你"), 11, "accent", bold=True, wrap=False, ellipsize=False), False, False, 0)
+ elif l.id in nums:
+ n = nums[l.id]
+ top.pack_start(ui.text(speakers.label(n, names), 11, "spk%d" % ((n - 1) % 4 + 1), bold=True, wrap=False, ellipsize=False), False, False, 0)
+ top.pack_start(ui.text(clock(l.t), 11, "tertiary", wrap=False, ellipsize=False), False, False, 0)
+ row.pack_start(top, False, False, 0)
+ if l.dst and l.dst != l.src:
+ row.pack_start(ui.marked(l.src, terms, 12, "secondary", current, lang=l.srcLang), False, False, 0)
+ row.pack_start(ui.marked(l.dst or l.src, terms, 13, "ink", current, lang=l.dstLang if l.dst else l.srcLang), False, False, 0)
+ return row
+
+ # Ending by itself
+
+ 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:
+ self.app.toggle_listening()
+ else:
+ self.confirm_end = True
+ self._fill_ending()
+
+ def _end_answer(self, end: bool) -> None:
+ self.confirm_end = False
+ self._fill_ending()
+ if end and self.app.listen.listening:
+ 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:
+ return
+ listening = self.app.listen.listening
+ p = self.app.ending if listening else None
+ rec = self.app.recorded() if listening and getattr(self, "confirm_end", False) else None
+ if rec is None:
+ self.confirm_end = False
+ self.ending_wrap.set_visible(p is not None or rec is not None)
+ if p is None and rec is None:
+ self._ending_key = None
+ return
+ key = (repr(p.reason) if p is not None else None, rec is not None)
+ if key != getattr(self, "_ending_key", None):
+ self._ending_key = key
+ ui.clear(self.ending_box)
+ self._ending_detail = self._confirm_detail = None
+ if p is not None:
+ self._ending_detail = ui.text("", 12, "secondary", wrap=False)
+ self.ending_box.pack_start(ui.vbox(3, ui.text(self.app.ending_title(p), 14, "ink", bold=True, width_chars=30),
+ self._ending_detail), False, False, 0)
+ keep = ui.button(L("继续记录"), self.app.keep_recording, "darkbtn")
+ now = ui.button(L("现在结束"), self.app.toggle_listening, "outline")
+ for b in (keep, now):
+ b.set_can_focus(False)
+ self.ending_box.pack_start(ui.hbox(8, keep, now), False, False, 0)
+ if rec is not None:
+ self._confirm_detail = ui.text("", 12, "secondary", width_chars=30)
+ self.ending_box.pack_start(ui.vbox(3, ui.text(L("结束这场会议?"), 14, "ink", bold=True, width_chars=30),
+ self._confirm_detail), False, False, 0)
+ keep = ui.button(L("继续记录"), lambda: self._end_answer(False), "outline")
+ end = ui.button(L("结束会议"), lambda: self._end_answer(True), "darkbtn")
+ for b in (keep, end):
+ b.set_can_focus(False)
+ self.ending_box.pack_start(ui.hbox(8, keep, end), False, False, 0)
+ self.ending_box.show_all()
+ if self._ending_detail is not None:
+ ui.retext(self._ending_detail, LF("%lld 秒后结束会议并整理纪要", self.app.ending_left(p)))
+ if self._confirm_detail is not None:
+ 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
+ row = 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)
+ if title:
+ texts.pack_start(ui.text(title, 13, "ink", bold=True, wrap=False), False, False, 0)
+ texts.pack_start(ui.text(body, 12, "secondary", width_chars=30), False, False, 0)
+ texts.set_valign(Gtk.Align.CENTER)
+ row.pack_start(texts, True, True, 0)
+ if action:
+ b = ui.button(action, on_action, "outline")
+ b.set_valign(Gtk.Align.CENTER)
+ b.set_can_focus(False)
+ row.pack_end(b, False, False, 0)
+ box.pack_start(row, False, False, 0)
+
+ def _fill_live(self) -> None:
+ box = self.live
+ ui.clear(box)
+ listen = self.app.listen
+ session = 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 None
+ kind = listen.problem_kind
+ self._state_shown = False
+ if 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", L("系统声音中断"), body, L("开始听"), self.app.toggle_listening)
+ elif kind == "network" and (line is None or listen.listening):
+ self._state_card(box, "network-offline-symbolic", "warn", L("连不上 Ling"), L("请检查网络。恢复后会自动继续,断开期间的声音无法识别"))
+ elif kind == "key":
+ self._state_card(box, "dialog-password-symbolic", "warn", listen.problem or L("Ling key 无效"),
+ L("在设置里更换 Ling key"), L("设置"), self.app.show_settings)
+ elif line is None:
+ if listen.listening:
+ hearing = listen.pending > 0 or listen.level >= 0.01
+ self._state_card(box, "audio-speakers-symbolic", "grey",
+ L("正在识别…") if hearing else L("等有人说话"),
+ L("正在听电脑播放的声音,有声音后约 3 秒出字幕"))
+ else:
+ self._state_card(box, "audio-speakers-symbolic", "grey", None,
+ 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:
+ n = nums[line.id]
+ box.pack_start(ui.text(speakers.label(n, speakers.names(session)), 11, "spk%d" % ((n - 1) % 4 + 1),
+ bold=True, wrap=False), False, False, 0)
+ if line.dst and line.dst != line.src:
+ box.pack_start(ui.text(line.src, 13 if self.subtitles else 12, "secondary",
+ wrap=not self.subtitles, width_chars=60, lang=line.srcLang), False, False, 0)
+ box.pack_start(ui.text(line.dst or line.src, big, "ink", bold=True, width_chars=60 if self.subtitles else 30,
+ lang=line.dstLang if line.dst else line.srcLang), False, False, 0)
+ if not self.subtitles and (listen.pending > 0 or kind == "busy"):
+ foot = ui.hbox(6)
+ foot.pack_start(ui.text("•••", 11, "accent", wrap=False, ellipsize=False), False, False, 0)
+ foot.pack_start(ui.text(listen.problem if kind == "busy" else L("正在识别…"), 11, "secondary", wrap=False), False, False, 0)
+ box.pack_start(ui.gap(foot, 6), False, False, 0)
+ if getattr(self, "live_box", None) is not None:
+ ctx = self.live_box.get_style_context()
+ (ctx.add_class if self._state_shown else ctx.remove_class)("light")
+ box.show_all()
+
+ def _fill_speak(self) -> None:
+ """同声传译: where my sentence is (听 → 翻译 → 说), what I said and what they hear."""
+ box = self.speakbox
+ sp = self.app.speak
+ show = self.app.settings.speakEnabled and (sp.active or sp.last is not None or sp.problem is not None)
+ ui.clear(box)
+ self.speakwrap.set_visible(show)
+ if not show:
+ return
+ from ..core.support import TARGETS
+ names = {c: n for n, c in TARGETS}
+ stage = {"hearing": L("正在听你说…"), "interpreting": L("正在翻译…"),
+ "speaking": L("正在说") + " · " + names.get(sp.target, sp.target)}.get(sp.stage, L("同声传译"))
+ top = ui.hbox(8)
+ mic = ui.icon("audio-input-microphone-symbolic", 14)
+ ui.classes(mic, "accent" if sp.active else "secondary")
+ top.pack_start(mic, False, False, 0)
+ top.pack_start(ui.text(stage if sp.active else L("同声传译"), 11, "secondary", bold=True, wrap=False), False, False, 0)
+ box.pack_start(top, False, False, 0)
+ if sp.last:
+ original, translation = sp.last
+ if not self.subtitles:
+ box.pack_start(ui.text(LF("你说:%@", original), 11, "secondary", width_chars=34, lang=sp.source), False, False, 0)
+ box.pack_start(ui.text(LF("对方听到:%@", translation), 13 if not self.subtitles else 15, "ink", bold=True,
+ width_chars=34 if not self.subtitles else 70, lang=sp.target), False, False, 0)
+ if sp.problem:
+ box.pack_start(ui.text(sp.problem, 11, "warn", width_chars=34), False, False, 0)
+ for child in self.speakwrap.get_children():
+ child.show_all()
+
+ def _fill_footer(self) -> None:
+ n = self.app.notes.notes
+ when = n.updatedAt if not n.is_empty else None
+ if when is None:
+ ui.retext(self.footer_time, "")
+ return
+ ago = max(0, int((datetime.now(timezone.utc) - when).total_seconds()))
+ ui.retext(self.footer_time, LF("纪要 %@ 秒前更新", ago) if ago < 60 else LF("纪要 %@ 分钟前更新", ago // 60))
+
+ def _banner(self, body, engine) -> None:
+ """Why the notes stopped, above them, notes or not (the Mac's banner): a dead key, too many
+ requests, or a round that failed; each says where the notes stop."""
+ s = self._session()
+ covered = engine.notes.covered
+ last = s.lines[covered - 1].t if s is not None and 0 < covered <= len(s.lines) else 0.0
+ if engine.status == notesmod.INVALID_KEY:
+ text, tone = LF("key 已失效(令牌被删或免费额度用尽),纪要停留在 %@。", clock(last)), "error"
+ elif engine.status == notesmod.RATE_LIMITED:
+ text, tone = LF("请求过于频繁,稍后会自动重试。纪要停留在 %@。", clock(last)), ""
+ elif engine.status == notesmod.FAILED:
+ text, tone = L("这轮没整理好,下一轮会自动重试。"), ""
+ else:
+ return
+ row = ui.hbox(10)
+ row.pack_start(ui.text(text, 12, "ink", width_chars=24), True, True, 0)
+ if tone == "error":
+ b = ui.button(L("更换 key"), self.app.show_settings, "darkbtn")
+ b.set_can_focus(False)
+ b.set_valign(Gtk.Align.CENTER)
+ row.pack_end(b, False, False, 0)
+ card = ui.panel(ui.pad(row, 12), "notice", *([tone] if tone else []))
+ body.pack_start(ui.pad(card, 0, 0, 10, 0), False, False, 0)
+
+ def _fill_body(self) -> None:
+ body = self.body
+ ui.clear(body)
+ engine = self.app.notes
+ n = engine.notes
+ listening = self.app.listen.listening
+ self._banner(body, engine)
+ if n.is_empty:
+ hint = {notesmod.NO_KEY: L("生成纪要需要 API key"),
+ notesmod.UPDATING: L("正在整理纪要…")}.get(engine.status, L("会中每 45 秒更新") if listening else "")
+ if engine.status in (notesmod.INVALID_KEY, notesmod.RATE_LIMITED, notesmod.FAILED):
+ hint = "" # the banner says it
+ if hint:
+ body.pack_start(ui.helper(hint), False, False, 0)
+ body.show_all()
+ return
+ if n.title:
+ body.pack_start(ui.text(n.title, 15, "heading", bold=True, width_chars=30), False, False, 0)
+ if n.summary:
+ body.pack_start(ui.gap(ui.text(n.summary, 13, "body", width_chars=30), 6), False, False, 0)
+ for i, t in enumerate(n.topics):
+ now = listening and i == len(n.topics) - 1
+ row = ui.hbox(8, ui.chip(clock(t.start)))
+ row.pack_start(ui.text(t.title, 13, "ink", bold=True, width_chars=24), True, True, 0)
+ if now:
+ badge = ui.panel(ui.pad(ui.text(L("正在讨论"), 11, "", wrap=False, ellipsize=False), 1, 6), "badge")
+ badge.set_valign(Gtk.Align.CENTER)
+ row.pack_start(badge, False, False, 0)
+ body.pack_start(ui.gap(row, 16), False, False, 0)
+ for p in t.points:
+ body.pack_start(ui.gap(ui.text(p, 13, "body", width_chars=30), 4), False, False, 0)
+ for title, items in ((L("结论"), [c.text for c in n.conclusions]),
+ (L("待办"), [t.text + (" · " + t.owner if t.owner else "") for t in n.todos])):
+ if not items:
+ continue
+ body.pack_start(ui.gap(ui.text(title, 11, "tertiary", bold=True), 16), False, False, 0)
+ for it in items:
+ body.pack_start(ui.gap(ui.text(("☐ " if title == L("待办") else "") + it, 13, "body", width_chars=30), 4), False, False, 0)
+ if engine.status == notesmod.UPDATING:
+ body.pack_start(ui.gap(ui.helper(L("正在整理纪要…")), 14), False, False, 0)
+ body.show_all()
diff --git a/linux/cicada/app/onboarding.py b/linux/cicada/app/onboarding.py
new file mode 100644
index 0000000..6b32134
--- /dev/null
+++ b/linux/cicada/app/onboarding.py
@@ -0,0 +1,563 @@
+"""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 annotations
+
+import threading
+from collections import deque
+
+from gi.repository import Gdk, GLib, Gtk
+
+from ..core import ling as lingmod
+from ..core.audio import Wav
+from ..core.strings import L, LF
+from ..core.support import TARGETS
+from . import ui
+from .capture import SystemAudio
+from .settings_window import LING_PLATFORM, SHORTCUTS, choice, gnome_shortcut, open_uri, set_gnome_shortcut, target_options
+
+KEY, AUDIO, SAMPLE, SPEAK, DONE = range(5)
+STEPS = 4
+
+
+class Onboarding(Gtk.Window):
+ def __init__(self, app):
+ 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 = 860
+ geometry.min_height = geometry.max_height = 640
+ self.set_geometry_hints(None, geometry, Gdk.WindowHints.MIN_SIZE | Gdk.WindowHints.MAX_SIZE)
+ self.set_position(Gtk.WindowPosition.CENTER)
+ self.set_wmclass("cicada", "Cicada")
+ bar = Gtk.HeaderBar()
+ bar.set_show_close_button(True)
+ ui.classes(bar, "cicada", "ground-bar")
+ self.set_titlebar(bar)
+ outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
+ ui.pad(outer, 6, 64, 36, 64)
+ self.head = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=14)
+ outer.pack_start(self.head, False, False, 0)
+ self.page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
+ outer.pack_start(self.page, True, True, 0)
+ self.footer = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)
+ self.footer.set_size_request(-1, 44)
+ outer.pack_end(self.footer, False, False, 0)
+ self.add(ui.panel(outer, "ground"))
+ self.tap = None
+ self.levels = deque([0.0] * 8, maxlen=8)
+ self.peak = 0.0
+ self.meter = None
+ self.speak_setup = None # 同声传译: None until chosen here (then True / False)
+ self.connect("destroy", lambda *_: self._stop_tap())
+ self.connect("key-press-event", self._key)
+ self.step = AUDIO if app.ling.has_key else KEY
+ self.render()
+
+ def _key(self, _w, event) -> bool:
+ if event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter) and self.next_action is not None and not isinstance(self.get_focus(), Gtk.Entry):
+ self.next_action()
+ return True
+ return False
+
+ def go(self, step: int) -> None:
+ self._stop_tap()
+ if step > DONE:
+ self.app.settings.onboarded = True
+ self.app.settings.save()
+ self.destroy()
+ return
+ self.step = max(KEY, step)
+ self.render()
+
+ def render(self) -> None:
+ for box in (self.head, self.page, self.footer):
+ ui.clear(box)
+ self.next_action = None
+ 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
+
+ def refresh(self) -> None:
+ """Engine changes (the sample being heard, 知了 麦克风 made): only the step that shows them."""
+ if self.step == SAMPLE:
+ GLib.idle_add(lambda: self._fill_sample() and False)
+
+ # Frame
+
+ def _header(self) -> None:
+ self.head.pack_start(self.app_logo(34), False, False, 0)
+ if self.step == DONE:
+ return
+ names = [L("接 Ling"), L("听声音"), L("看效果"), L("同声传译")]
+ bars = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6, homogeneous=True)
+ for i, name in enumerate(names):
+ cap = ui.panel(Gtk.Box(), "stepbar", "on" if i <= self.step else "")
+ cap.set_size_request(-1, 4)
+ label = ui.text(name, 11, "ink" if i == self.step else "secondary", bold=i == self.step, wrap=False)
+ bars.pack_start(ui.vbox(7, cap, label), True, True, 0)
+ bars.set_margin_top(8)
+ bars.get_accessible().set_name(LF("第 %lld 步,共 %lld 步:%@", self.step + 1, STEPS, names[self.step]))
+ self.head.pack_start(bars, True, True, 0)
+
+ def app_logo(self, px: int) -> Gtk.Widget:
+ from .main import icon_path
+ path = icon_path()
+ if path:
+ try:
+ from gi.repository import GdkPixbuf
+ img = Gtk.Image.new_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_size(path, px, px))
+ img.set_valign(Gtk.Align.START)
+ return img
+ except GLib.Error:
+ pass
+ return ui.dot(True)
+
+ def _title(self, title: str, sub: str) -> None:
+ t = ui.text(title, 26, "heading", bold=True, width_chars=40)
+ self.page.pack_start(ui.gap(t, 24 if self.step != DONE else 28), False, False, 0)
+ self.page.pack_start(ui.gap(ui.text(sub, 14, "secondary", width_chars=70), 8), False, False, 0)
+
+ def _card(self, *rows, gap: int = 24) -> Gtk.Widget:
+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
+ for i, r in enumerate(rows):
+ if i:
+ sep = ui.panel(Gtk.Box(), "hair")
+ sep.set_size_request(-1, 1)
+ box.pack_start(ui.pad(sep, 0, 22), False, False, 0)
+ box.pack_start(r, False, False, 0)
+ card = ui.panel(box, "bigcard")
+ self.page.pack_start(ui.gap(card, gap), False, False, 0)
+ return card
+
+ def _row(self, icon_name: str | None, title: str, detail: str, trailing: Gtk.Widget | None = None, number: int | None = None) -> Gtk.Widget:
+ row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)
+ if icon_name:
+ row.pack_start(ui.icon_tile(icon_name, 44, 20, "grey"), False, False, 0)
+ elif number is not None:
+ n = ui.panel(ui.text(str(number), 12, "", bold=True, wrap=False, ellipsize=False), "stepnum")
+ n.set_size_request(24, 24)
+ n.get_child().set_halign(Gtk.Align.CENTER)
+ n.set_valign(Gtk.Align.START)
+ row.pack_start(n, False, False, 0)
+ texts = ui.vbox(4, ui.text(title, 15, "ink", bold=True, width_chars=34), ui.text(detail, 13, "secondary", width_chars=40))
+ texts.set_valign(Gtk.Align.CENTER)
+ row.pack_start(texts, True, True, 0)
+ if trailing is not None:
+ trailing.set_valign(Gtk.Align.CENTER)
+ row.pack_end(trailing, False, False, 0)
+ return ui.pad(row, 20, 22)
+
+ 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
+ box = b.get_child()
+ img = box.get_children()[0]
+ box.reorder_child(img, 1)
+ if enabled:
+ self.next_action = action
+ return b
+
+ def _back(self) -> None:
+ self.footer.pack_start(ui.button(L("上一步"), lambda: self.go(self.step - 1), "quietbtn bigquiet"), False, False, 0)
+
+ def _done_mark(self, text: str) -> Gtk.Widget:
+ 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:
+ self._title(L("接上 Ling"), L("识别、翻译和纪要都靠它,约 1 分钟。"))
+ entry = Gtk.Entry()
+ entry.set_visibility(False)
+ entry.set_placeholder_text("sk-…")
+ ui.classes(entry, "keyentry")
+ entry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "view-reveal-symbolic")
+ entry.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY, L("显示 key"))
+ entry.connect("icon-press", lambda e, *_: e.set_visibility(not e.get_visibility()))
+ self.key_status = ui.text("", 13, "secondary", width_chars=40)
+ self.key_entry = entry
+ platform = ui.button(L("打开 Ling 开放平台") + " ↗", lambda: open_uri(LING_PLATFORM), "outline midbtn")
+ paste = ui.button(L("粘贴并检查"), self._paste, "darkbtn midbtn")
+ field = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
+ field.pack_start(entry, True, True, 0)
+ field.pack_start(paste, False, False, 0)
+ second = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=14)
+ n = ui.panel(ui.text("2", 12, "", bold=True, wrap=False, ellipsize=False), "stepnum")
+ n.set_size_request(24, 24)
+ n.get_child().set_halign(Gtk.Align.CENTER)
+ n.set_valign(Gtk.Align.START)
+ second.pack_start(n, False, False, 0)
+ second.pack_start(ui.vbox(10, ui.text(L("复制 sk- 开头的 key,回来粘贴"), 15, "ink", bold=True, width_chars=34), field, self.key_status),
+ True, True, 0)
+ steps = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
+ steps.pack_start(self._row(None, L("在 Ling 开放平台创建 key"), L("注册或登录后点“创建令牌”"), platform, number=1), False, False, 0)
+ sep = ui.panel(Gtk.Box(), "hair")
+ sep.set_size_request(-1, 1)
+ steps.pack_start(ui.pad(sep, 0, 22), False, False, 0)
+ steps.pack_start(ui.pad(second, 20, 22), False, False, 0)
+ left = ui.panel(steps, "bigcard")
+ perks = ui.vbox(4, ui.text(L("Ling 每月赠送 ¥10 额度"), 15, "ink", bold=True, width_chars=20),
+ ui.text(L("约够 10–50 小时会议"), 13, "secondary", width_chars=20))
+ items = ui.vbox(10)
+ for title, sub in ((L("实时纪要"), L("会中每 45 秒更新")), (L("更准的翻译"), L("人名、术语前后一致")),
+ (L("自然人声"), L("同传约 2 秒出声"))):
+ items.pack_start(ui.vbox(1, ui.text(title, 13, "ink", bold=True, wrap=False), ui.text(sub, 12, "tertiary", width_chars=22)),
+ False, False, 0)
+ sep2 = ui.panel(Gtk.Box(), "hair")
+ sep2.set_size_request(-1, 1)
+ right = ui.panel(ui.pad(ui.vbox(14, perks, sep2, items), 20), "bigcard")
+ right.set_size_request(236, -1)
+ row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)
+ row.pack_start(left, True, True, 0)
+ row.pack_start(right, False, False, 0)
+ self.page.pack_start(ui.gap(row, 24), False, False, 0)
+ entry.connect("activate", lambda *_: self._save_key(entry.get_text()))
+ if self.app.ling.has_key and self.app.ling.key_state == lingmod.OK:
+ self._key_ok()
+ 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)
+ GLib.idle_add(lambda: entry.grab_focus() and False)
+
+ def _key_next(self) -> None:
+ text = self.key_entry.get_text().strip()
+ if text:
+ self._save_key(text)
+ elif self.app.ling.has_key:
+ self.go(AUDIO)
+ else:
+ self._key_problem(L("复制 sk- 开头的 key,回来粘贴"))
+
+ def _paste(self) -> None:
+ text = (Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).wait_for_text() or "").strip()
+ if not text.startswith("sk-"):
+ self._key_problem(L("剪贴板里没有 sk- 开头的 key,先在 Ling 开放平台复制。"))
+ return
+ self.key_entry.set_text(text)
+ self._save_key(text)
+
+ def _key_problem(self, text: str) -> None:
+ ctx = self.key_status.get_style_context()
+ ctx.remove_class("secondary")
+ ctx.add_class("warn")
+ ui.retext(self.key_status, text)
+
+ def _key_ok(self) -> None:
+ ctx = self.key_status.get_style_context()
+ ctx.remove_class("warn")
+ ctx.add_class("ok")
+ ui.retext(self.key_status, L("已连接") + " · " + L("现在可以用了"))
+
+ def _save_key(self, text: str) -> None:
+ text = text.strip()
+ if not text.startswith("sk-"):
+ self._key_problem(L("复制 sk- 开头的 key,回来粘贴"))
+ return
+ self.app.key.save(text)
+ self.app.ling.key_changed()
+ ctx = self.key_status.get_style_context()
+ ctx.remove_class("warn")
+ ui.retext(self.key_status, L("正在检查…"))
+
+ def check():
+ state = self.app.ling.check()
+
+ def done():
+ if self.step != KEY:
+ return False
+ if state == lingmod.OK:
+ self._key_ok()
+ GLib.timeout_add(700, lambda: (self.step == KEY and self.go(AUDIO)) and False)
+ else:
+ self._key_problem(L("这个 key 无效,请检查是否复制完整,或重新创建一个") if state == lingmod.INVALID
+ else L("连不上 Ling,检查网络"))
+ return False
+ 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.tap is None:
+ self.tap = SystemAudio()
+
+ def heard(buf):
+ level = Wav.rms(buf)
+ self.levels.append(level)
+ self.peak = max(self.peak, level)
+ self.tap.on_samples = heard
+ self.tap.start()
+ self.meter = GLib.timeout_add(80, self._meter_tick)
+ self.bars = []
+ meter = ui.hbox(3)
+ meter.set_size_request(-1, 18)
+ for _ in range(8):
+ b = ui.panel(Gtk.Box(), "meterbar")
+ b.set_size_request(3, 3)
+ b.set_valign(Gtk.Align.END)
+ meter.pack_start(b, False, False, 0)
+ self.bars.append(b)
+ self.heard_row = ui.hbox(6)
+ trailing = ui.hbox(12, meter, self.heard_row)
+ self._card(self._row("audio-speakers-symbolic", L("听电脑里的声音"), L("只听声音,不录屏幕画面"), trailing))
+ self._back()
+ self.audio_hint = ui.text(L("音量条没动?放段视频或音乐试试"), 13, "secondary", wrap=False)
+ 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)
+ self._heard_shown = None
+ self._update_heard()
+
+ def _meter_tick(self) -> bool:
+ if self.step != AUDIO:
+ self.meter = None
+ return False
+ for bar, level in zip(self.bars, list(self.levels)): # the capture thread appends meanwhile
+ v = ui.loudness(level)
+ bar.set_size_request(3, max(3, int(v * 18)))
+ self._update_heard()
+ return True
+
+ def _update_heard(self) -> None:
+ heard = self.peak >= 0.01
+ if self._heard_shown == heard:
+ return
+ self._heard_shown = heard
+ ui.clear(self.heard_row)
+ ui.clear(self.audio_next)
+ self.audio_hint.set_opacity(0 if heard else 1)
+ if heard:
+ 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)
+ self.stage.set_valign(Gtk.Align.END)
+ stage = ui.panel(ui.pad(self.stage, 16), "samplestage")
+ stage.set_size_request(-1, 184)
+ self.page.pack_start(ui.gap(stage, 18), False, False, 0)
+ s = self.app.settings
+
+ def set_target(v):
+ s.target = v
+ s.save()
+ self.app.settings_changed()
+ self.heard_value = ui.text("", 13, "ink", bold=True, wrap=False, ellipsize=False)
+ combos = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12, homogeneous=True)
+ for label, control in ((L("听到"), self.heard_value), (L("翻译成"), choice(target_options(), s.target, set_target))):
+ r = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
+ r.pack_start(ui.text(label, 13, "secondary", wrap=False), False, False, 0)
+ control.set_valign(Gtk.Align.CENTER)
+ r.pack_end(control, False, False, 0)
+ card = ui.panel(ui.pad(r, 0, 14), "midcard")
+ card.set_size_request(-1, 44)
+ r.set_valign(Gtk.Align.CENTER)
+ combos.pack_start(card, True, True, 0)
+ self.page.pack_start(ui.gap(combos, 14), False, False, 0)
+ teaser = ui.text(L("开会时,纪要会跟着字幕一起更新。"), 14, "ink", bold=True, wrap=False)
+ self.page.pack_start(ui.gap(ui.panel(ui.pad(teaser, 12, 18), "midcard"), 14), False, False, 0)
+ self._back()
+ self.footer.pack_start(Gtk.Box(), True, True, 0)
+ self.sample_buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)
+ self.footer.pack_end(self.sample_buttons, False, False, 0)
+ self._fill_sample()
+
+ def _fill_sample(self) -> None:
+ if self.step != SAMPLE or not hasattr(self, "stage"):
+ return
+ listen = self.app.listen
+ s = self.app.store.get(listen.session_id) if listen.session_id else None
+ line = s.lines[-1] if s and s.lines else None
+ playing = listen.listening and listen.source_kind == "file"
+ ui.clear(self.stage)
+ if line is not None:
+ if line.dst and line.dst != line.src:
+ src = ui.text(line.src, 12, "stage-dim", width_chars=60, lang=line.srcLang)
+ src.set_justify(Gtk.Justification.CENTER)
+ src.set_xalign(0.5)
+ self.stage.pack_start(src, False, False, 0)
+ dst = ui.text(line.dst or line.src, 17, "stage-ink", bold=True, width_chars=50, lang=line.dstLang)
+ dst.set_justify(Gtk.Justification.CENTER)
+ dst.set_xalign(0.5)
+ self.stage.pack_start(dst, False, False, 0)
+ elif playing:
+ t = ui.text(L("正在识别…"), 14, "stage-dim", wrap=False)
+ t.set_xalign(0.5)
+ self.stage.pack_start(t, False, False, 0)
+ else:
+ play = ui.button(L("播放示例"), self._play, "pillkeep bigplay", "media-playback-start-symbolic")
+ play.set_halign(Gtk.Align.CENTER)
+ self.stage.set_valign(Gtk.Align.CENTER)
+ self.stage.pack_start(play, False, False, 0)
+ if line is not None or playing:
+ self.stage.set_valign(Gtk.Align.END)
+ self.stage.show_all()
+ from .records_window import lang_name
+ ui.retext(self.heard_value, LF("自动 · %@", lang_name(line.srcLang)) if line is not None else L("自动识别"))
+ ui.clear(self.sample_buttons)
+ self.sample_buttons.pack_start(self._primary(L("继续"), lambda: self.go(SPEAK)), False, False, 0)
+ self.sample_buttons.show_all()
+
+ def _play(self) -> None:
+ self.app.play_sample()
+ self._fill_sample()
+
+ # 4. 同声传译
+
+ def _speak_step(self) -> None:
+ app = self.app
+ on = self.speak_setup if self.speak_setup is not None else app.settings.speakEnabled
+ lang = dict((c, n) for n, c in TARGETS).get(app.settings.speak_from_code, app.settings.speak_from_code)
+ head = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=24)
+ texts = ui.vbox(8, ui.text(L("开会时要说外语吗?"), 26, "heading", bold=True, width_chars=24),
+ ui.text(LF("点一下“开始说”或按快捷键说%@,对方听到翻译后的语音。", lang), 14, "secondary", width_chars=50))
+ head.pack_start(texts, True, True, 0)
+ if on:
+ head.pack_end(self._keycaps(), False, False, 0)
+ self.page.pack_start(ui.gap(head, 24), False, False, 0)
+ if not on:
+ row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=14, homogeneous=True)
+ for title, detail, action in ((L("要,现在设置"), L("约 1 分钟,会建一个“知了 麦克风”,不用装驱动"), self._speak_yes),
+ (L("先不用"), L("以后在设置 › 同声传译里打开"), lambda: self.go(DONE))):
+ b = Gtk.Button()
+ b.add(ui.pad(ui.vbox(8, ui.text(title, 16, "ink", bold=True, wrap=False), ui.text(detail, 13, "secondary", width_chars=30)), 22))
+ ui.classes(b, "choicecard")
+ b.connect("clicked", lambda _b, a=action: a())
+ row.pack_start(b, True, True, 0)
+ self.page.pack_start(ui.gap(row, 28), False, False, 0)
+ self._back()
+ return
+ made = app.room.on
+ mic_state = self._done_mark(L("已建好")) if made else ui.text(L("没能建好知了麦克风"), 13, "warn", wrap=False)
+ keys = gnome_shortcut("speak")
+ if keys:
+ key_state = self._done_mark(L("已添加"))
+ elif keys is None:
+ key_state = ui.text(L("在系统的键盘设置里绑定"), 12, "secondary", wrap=False)
+ else:
+ key_state = ui.button(L("添加这个快捷键"), self._add_shortcut, "outline midbtn")
+ self._card(self._row(None, L("知了 麦克风"), L("译文从这里传给会议软件,不用安装驱动"), mic_state),
+ self._row(None, L("开始 / 停止说的快捷键"), L("在任何窗口里都能用"), key_state), gap=22)
+ tip = ui.text(L("在会议软件里把麦克风选成“知了 麦克风”(或“默认”),并戴上耳机:外放时对方的声音会被当成你说的。"),
+ 13, "ink", width_chars=80)
+ self.page.pack_start(ui.gap(ui.panel(ui.pad(tip, 12, 16), "endingstrip"), 14), False, False, 0)
+ if self.speak_setup:
+ self.footer.pack_start(ui.button(L("先不用了"), self._speak_no, "quietbtn bigquiet"), False, False, 0)
+ else:
+ self._back()
+ self.footer.pack_start(Gtk.Box(), True, True, 0)
+ self.footer.pack_end(self._primary(L("完成"), lambda: self.go(DONE), arrow=False), False, False, 0)
+
+ def _keycaps(self) -> Gtk.Widget:
+ caps = ui.hbox(6)
+ for k, w in (("Super", 72), ("⇧", 52), ("S", 52)):
+ label = ui.text(k, 11, "secondary", wrap=False, ellipsize=False)
+ label.set_valign(Gtk.Align.END)
+ label.set_halign(Gtk.Align.START)
+ cap = ui.panel(ui.pad(label, 6, 8, 7, 8), "keycap")
+ cap.set_size_request(w, 52)
+ caps.pack_start(cap, False, False, 0)
+ hint = ui.text(L("可在设置中更改"), 11, "tertiary", wrap=False)
+ hint.set_halign(Gtk.Align.END)
+ box = ui.vbox(6, caps, hint)
+ box.set_valign(Gtk.Align.START)
+ return box
+
+ def _speak_yes(self) -> None:
+ self.speak_setup = True
+ self.app.set_speak_enabled(True)
+ self.render()
+
+ def _speak_no(self) -> None:
+ self.speak_setup = None
+ self.app.set_speak_enabled(False)
+ self.render()
+
+ def _add_shortcut(self) -> None:
+ from ..core.support import Paths
+ 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 None
+ self._title(L("好了,知了在顶栏") if tray else L("好了,可以开始了"),
+ L("接下来会打开会议记录窗口,之后从右上角的图标找到它。") if tray
+ else L("接下来会打开会议记录窗口;开会时在这里点“开始听”。"))
+ if tray:
+ self.page.pack_start(ui.gap(self._top_bar(), 24), False, False, 0)
+ tips = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12, homogeneous=True)
+ speak_keys = gnome_shortcut("speak")
+ items = [(L("开会时点它") if tray else L("开会时点“开始听”"), L("开始听,出字幕和纪要"))]
+ if self.app.settings.speakEnabled:
+ items.append((LF("按 %@ 说话", SHORTCUTS["speak"][2].replace(" + Shift + ", " ⇧ ")) if speak_keys else L("点纪要窗的麦克风说话"),
+ L("对方听到翻译后的语音")))
+ items.append((L("会后看记录"), L("每场会都存在会议记录里")))
+ for title, sub in items:
+ tips.pack_start(ui.panel(ui.pad(ui.vbox(4, ui.text(title, 14, "ink", bold=True, wrap=False),
+ ui.text(sub, 12, "tertiary", width_chars=22)), 16), "tipcard"), True, True, 0)
+ self.page.pack_start(ui.gap(tips, 24), False, False, 0)
+ if not tray:
+ note = ui.text(L("顶栏没有知了的图标?装上 AppIndicator 扩展,就能从顶栏打开知了。"), 12, "secondary", wrap=False)
+ self.page.pack_start(ui.gap(note, 18), False, False, 0)
+ self.footer.pack_start(Gtk.Box(), True, True, 0)
+ 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")
+ act.set_valign(Gtk.Align.CENTER)
+ bar.pack_start(act, False, False, 0)
+ from datetime import datetime
+ clock = ui.text(datetime.now().strftime("%H:%M"), 12, "topbar-ink", bold=True, wrap=False, ellipsize=False)
+ bar.set_center_widget(clock)
+ for name in ("battery-full-symbolic", "audio-volume-high-symbolic", "network-wireless-signal-excellent-symbolic"):
+ img = ui.icon(name, 14)
+ ui.classes(img, "topbar-ink")
+ bar.pack_end(img, False, False, 0)
+ ring = ui.panel(self.app_logo(16), "topbar-ring")
+ ring.set_size_request(26, 24)
+ ring.get_child().set_halign(Gtk.Align.CENTER)
+ ring.get_child().set_valign(Gtk.Align.CENTER)
+ ring.set_valign(Gtk.Align.CENTER)
+ bar.pack_end(ring, False, False, 0)
+ top = ui.panel(ui.pad(bar, 0, 14), "topbar")
+ arrow = ui.vbox(4, ui.icon("go-up-symbolic", 14), ui.text(L("就是它"), 13, "link", bold=True, wrap=False, ellipsize=False))
+ arrow.get_children()[0].get_style_context().add_class("link")
+ arrow.set_halign(Gtk.Align.END)
+ arrow.set_margin_end(96)
+ arrow.set_margin_top(8)
+ below = Gtk.Box()
+ below.set_size_request(-1, 76)
+ below.pack_end(arrow, False, False, 0)
+ return ui.panel(ui.vbox(0, top, below), "bigcard", "clip")
+
+ def _stop_tap(self) -> None:
+ if self.meter is not None:
+ GLib.source_remove(self.meter)
+ self.meter = None
+ if self.tap is not None:
+ self.tap.on_samples = None
+ self.tap.stop()
+ self.tap = None
diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.py
new file mode 100644
index 0000000..a033184
--- /dev/null
+++ b/linux/cicada/app/records_window.py
@@ -0,0 +1,959 @@
+"""会议记录, 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 annotations
+
+import os
+import time
+from datetime import datetime, timedelta, timezone
+
+from gi.repository import Gdk, Gio, GLib, Gtk
+
+from ..core import session_store, speakers
+from ..core.strings import L, LF
+from ..core.support import SOURCES, TARGETS, Log, clock
+from . import ui
+
+LANG_NAMES = {code: name for name, code in SOURCES + TARGETS}
+
+
+def lang_name(code: str) -> str:
+ return LANG_NAMES.get(code) or LANG_NAMES.get(code.split("-")[0], code)
+
+
+class RecordsWindow(Gtk.Window):
+ def __init__(self, app):
+ super().__init__(title=L("会议记录") + " · " + L("知了"))
+ self.app = app
+ self.set_default_size(1180, 760)
+ self.set_size_request(720, 480)
+ self.set_position(Gtk.WindowPosition.CENTER)
+ self.set_wmclass("cicada", "Cicada")
+ self.connect("delete-event", lambda *_: self.hide() or True)
+ self.selected = None
+ self.pending_delete = None # a record deleted but still undoable
+ self.query = ""
+ 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._queued = False
+
+ bar = 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)
+ self.listen_box.set_hhomogeneous(False)
+ self.listen_box.set_vhomogeneous(False)
+ self.listen_box.set_interpolate_size(True)
+ self.listen_box.set_valign(Gtk.Align.CENTER)
+ bar.set_custom_title(self.listen_box)
+ ui.classes(bar, "cicada", "records-bar")
+ 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)
+ bar.pack_start(self.bar_side)
+ bar.pack_end(self._app_menu())
+ self.set_titlebar(bar)
+
+ overlay = Gtk.Overlay()
+ self.toasts = ui.Toasts(overlay)
+ root = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
+ ui.classes(root, "sheet")
+ overlay.add(root)
+ self.add(overlay)
+
+ # Sidebar
+ side = 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.search = Gtk.SearchEntry()
+ self.search.set_placeholder_text(L("搜索标题和对话"))
+ self.search.connect("search-changed", self._searched)
+ 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)
+ hint.set_halign(Gtk.Align.END)
+ hint.set_valign(Gtk.Align.CENTER)
+ hint.set_margin_end(10)
+ search_box.add_overlay(hint)
+ search_box.set_overlay_pass_through(hint, True)
+ self.search.connect("changed", lambda e: hint.set_visible(not e.get_text()))
+ ui.pad(search_box, 2, 10, 8, 10)
+ side.pack_start(search_box, False, False, 0)
+ left_scroll = Gtk.ScrolledWindow()
+ left_scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
+ self.list = Gtk.ListBox()
+ self.list.set_selection_mode(Gtk.SelectionMode.SINGLE)
+ self.list.connect("row-selected", self._row_selected)
+ self.list.set_header_func(self._header)
+ left_scroll.add(self.list)
+ side.pack_start(left_scroll, True, True, 0)
+ side.show_all()
+ root.pack_start(self.sidebar, False, False, 0)
+
+ # Content
+ self.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")
+ root.pack_start(self.right, True, True, 0)
+ self.columns = None
+ self.connect("size-allocate", self._resized)
+ self.connect("key-press-event", self._key)
+ self._tick = GLib.timeout_add_seconds(1, self._clock)
+ 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 True
+ return 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),
+ (L("重看新手引导"), self.app.show_onboarding), (None, None), (L("退出知了"), self.app.quit)):
+ if label is None:
+ menu.append(Gtk.SeparatorMenuItem())
+ continue
+ item = Gtk.MenuItem(label=label)
+ item.connect("activate", lambda _i, a=action: a())
+ menu.append(item)
+ menu.show_all()
+ b = Gtk.MenuButton()
+ b.set_popup(menu)
+ b.add(ui.icon("open-menu-symbolic"))
+ b.set_tooltip_text(L("主菜单"))
+ ui.classes(b, "iconbtn")
+ return b
+
+ def _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.app
+ listen = app.listen
+ if listen.listening:
+ state = "ending" if app.ending is not None else "live"
+ else:
+ state = "auto" if app.auto_ended else "idle"
+ key = (state, app.ending.reason.kind + app.ending.reason.name if state == "ending" else "")
+ if key != getattr(self, "_pill_state", None):
+ first = getattr(self, "_pill_state", None) is None
+ self._pill_state = key
+ stack = self.listen_box
+ old = stack.get_children()
+ box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
+ box.set_valign(Gtk.Align.CENTER)
+ box.set_halign(Gtk.Align.CENTER)
+ if state in ("idle", "auto"):
+ 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"),
+ ui.text(L("会议已自动结束") if state == "auto" else L("开始听"), 13, "ink", bold=True,
+ wrap=False, ellipsize=False))
+ sep = inner.get_children()[2]
+ sep.set_size_request(1, 14)
+ sep.set_valign(Gtk.Align.CENTER)
+ keys = self._shortcut_hint()
+ if keys:
+ inner.pack_start(ui.text(keys, 11, "secondary", wrap=False, ellipsize=False), False, False, 0)
+ b.add(inner)
+ ui.classes(b, "listenpill")
+ b.connect("clicked", lambda *_: self.app.toggle_listening())
+ b.get_accessible().set_name(L("开始听"))
+ box.pack_start(b, False, False, 0)
+ elif state == "live":
+ show = Gtk.Button()
+ inner = ui.hbox(10, self._breathing_logo(22), ui.text(L("正在听"), 13, "ink", bold=True, wrap=False, ellipsize=False))
+ self._bars = []
+ meter = ui.hbox(2)
+ meter.set_valign(Gtk.Align.CENTER)
+ for _ in range(8):
+ bar = ui.panel(Gtk.Box(), "meterbar")
+ bar.set_size_request(3, 3)
+ bar.set_valign(Gtk.Align.CENTER)
+ meter.pack_start(bar, False, False, 0)
+ self._bars.append(bar)
+ self._levels = [0.0] * 8
+ inner.pack_start(meter, False, False, 0)
+ self._pill_time = ui.classes(ui.text("", 13, "ink", wrap=False, ellipsize=False), "tnum")
+ inner.pack_start(self._pill_time, False, False, 0)
+ show.add(inner)
+ ui.classes(show, "pillshow")
+ show.set_tooltip_text(L("显示实时纪要") if self.app.settings.view == "notes" else L("显示字幕条"))
+ show.connect("clicked", lambda *_: self.app.show_notes())
+ end = ui.button(L("结束"), lambda: self.app.request_stop(self), "pillend")
+ end.set_valign(Gtk.Align.CENTER)
+ end.get_accessible().set_name(L("结束会议"))
+ box.pack_start(self._live_pill(show, end), False, False, 0)
+ GLib.timeout_add(80, self._meter)
+ else:
+ show = Gtk.Button()
+ ring = Gtk.Overlay()
+ self._ring = Gtk.Image()
+ self._ring_total = max(1.0, app.ending.deadline - time.time())
+ ring.add(self._ring)
+ logo = self._logo(16)
+ logo.set_halign(Gtk.Align.CENTER)
+ logo.set_valign(Gtk.Align.CENTER)
+ ring.add_overlay(logo)
+ ring.set_valign(Gtk.Align.CENTER)
+ self._pill_left = ui.classes(ui.text("", 13, "countdown", wrap=False, ellipsize=False), "tnum")
+ inner = ui.hbox(10, ring, ui.text(app.ending_title(app.ending), 13, "ink", bold=True, wrap=False, ellipsize=False),
+ self._pill_left)
+ show.add(inner)
+ ui.classes(show, "pillshow")
+ show.set_tooltip_text(L("显示实时纪要") if self.app.settings.view == "notes" else L("显示字幕条"))
+ show.connect("clicked", lambda *_: self.app.show_notes())
+ keep = ui.button(L("继续记录"), self.app.keep_recording, "pillkeep")
+ keep.set_valign(Gtk.Align.CENTER)
+ 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)
+
+ def drop():
+ for c in old:
+ if c.get_parent() is stack:
+ c.destroy()
+ return False
+ GLib.timeout_add(400, drop)
+ if state == "live":
+ s = self.app.store.get(listen.session_id) if listen.session_id else None
+ secs = (datetime.now(timezone.utc) - s.startedAt).total_seconds() if s else 0
+ ui.retext(self._pill_time, clock(secs))
+ elif state == "ending":
+ left = app.ending_left(app.ending)
+ ui.retext(self._pill_left, LF("%lld 秒后结束", left))
+ 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 pill
+
+ def _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)
+ outer.set_halign(Gtk.Align.CENTER)
+ return outer
+
+ def _logo(self, px: int) -> Gtk.Widget:
+ from .main import icon_path
+ path = icon_path()
+ 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:
+ pass
+ return 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_shortcut
+ if 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 False
+ self._levels = (self._levels + [ui.loudness(self.app.listen.level)])[-8:]
+ for bar, v in zip(self._bars, self._levels):
+ bar.set_size_request(3, max(3, int(v * 15)))
+ return True
+
+ def _clock(self) -> bool:
+ if self.get_visible() and self.app.listen.listening:
+ self._fill_listen_box()
+ return True
+
+ # List
+
+ def refresh(self) -> None:
+ if self._queued:
+ return
+ self._queued = True
+
+ def run():
+ self._queued = False
+ if self.get_visible():
+ self.fill()
+ return False
+ GLib.idle_add(run)
+
+ def _visible_sessions(self) -> list:
+ q = self.query.strip().lower()
+ out = []
+ for s in self.app.store.all():
+ if s.id == self.pending_delete:
+ continue
+ if q and q not in session_store.display_title(s).lower() and not any(
+ q in l.src.lower() or q in (l.dst or "").lower() for l in s.lines):
+ continue
+ out.append(s)
+ return out
+
+ def _group(self, s) -> str:
+ day = s.startedAt.astimezone().date()
+ today = datetime.now().date()
+ if day == today:
+ return L("今天")
+ if day == today - timedelta(days=1):
+ return L("昨天")
+ return L("更早")
+
+ def _header(self, row, before) -> None:
+ g = getattr(row, "group", None)
+ if before is None or getattr(before, "group", None) != g:
+ l = ui.text(g, 11, "group-label", bold=True, wrap=False)
+ ui.pad(l, 12 if before is not None else 4, 20, 4, 20)
+ row.set_header(l)
+ else:
+ row.set_header(None)
+
+ def fill(self) -> None:
+ self._fill_listen_box()
+ listen = self.app.listen
+ sessions = self._visible_sessions()
+ everything = [s for s in self.app.store.all() if s.id != self.pending_delete]
+ self._filling = True
+ for row in self.list.get_children():
+ self.list.remove(row)
+ for s in sessions:
+ live = listen.listening and listen.session_id == s.id
+ when = s.startedAt.astimezone()
+ start = "%02d:%02d" % (when.hour, when.minute) if self._group(s) != L("更早") else session_store._local_date(s.startedAt, L("M月d日"))
+ meta = (L("正在听") + " · " + start) if live else start + " · " + clock(s.duration)
+ title_row = ui.hbox(8)
+ if live:
+ title_row.pack_start(ui.breathing_dot(small=True), False, False, 0)
+ title_row.pack_start(ui.text(session_store.display_title(s), 13, "ink", wrap=False), True, True, 0)
+ box = ui.vbox(1, title_row, ui.text(meta, 11, "accent" if live else "tertiary", wrap=False))
+ ui.pad(box, 7, 10)
+ row = Gtk.ListBoxRow()
+ row.add(box)
+ row.session_id = s.id
+ row.group = self._group(s)
+ self.list.add(row)
+ self.list.show_all()
+ self.sidebar.set_visible(bool(everything))
+ if not sessions:
+ self.selected = None if not everything else self.selected
+ elif self.selected not in [s.id for s in sessions]:
+ self.selected = sessions[0].id
+ for row in self.list.get_children():
+ if row.session_id == self.selected:
+ self.list.select_row(row)
+ self._filling = False
+ self.show_detail(empty=not everything, no_match=bool(everything) and not sessions)
+
+ def _searched(self, entry) -> None:
+ self.query = entry.get_text()
+ self.fill()
+
+ def _row_selected(self, _list, row) -> None:
+ if row is None or getattr(self, "_filling", False):
+ return
+ if row.session_id != self.selected:
+ self.selected = row.session_id
+ self.show_detail()
+ self.right.get_vadjustment().set_value(0)
+
+ # 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
+ if self.columns.get_orientation() != want:
+ self.columns.set_orientation(want)
+ self.columns.set_homogeneous(want == Gtk.Orientation.HORIZONTAL)
+
+ def _status_page(self, icon_name, title, body, actions) -> Gtk.Widget:
+ page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
+ page.set_halign(Gtk.Align.CENTER)
+ page.set_valign(Gtk.Align.CENTER)
+ page.set_vexpand(True)
+ page.pack_start(ui.icon_tile(icon_name, 80, 36, "grey"), False, False, 0)
+ t = ui.text(title, 17, "heading", bold=True, wrap=False)
+ t.set_halign(Gtk.Align.CENTER)
+ page.pack_start(ui.gap(t, 22), False, False, 0)
+ b = ui.text(body, 13, "secondary", width_chars=44)
+ b.set_justify(Gtk.Justification.CENTER)
+ b.set_halign(Gtk.Align.CENTER)
+ page.pack_start(ui.gap(b, 8), False, False, 0)
+ if actions:
+ row = ui.hbox(10, *actions)
+ row.set_halign(Gtk.Align.CENTER)
+ page.pack_start(ui.gap(row, 22), False, False, 0)
+ page.set_margin_top(120)
+ return page
+
+ def show_detail(self, empty: bool = False, no_match: bool = False) -> None:
+ started = time.monotonic()
+ self._show_detail(empty, no_match)
+ Log.d("records: detail in %d ms" % ((time.monotonic() - started) * 1000))
+
+ def _show_detail(self, empty: bool = False, no_match: bool = False) -> None:
+ d = self.content
+ keep = self.right.get_vadjustment().get_value()
+ if empty or no_match:
+ ui.clear(d)
+ self.columns = None
+ self._built_key = None
+ if empty:
+ d.pack_start(self._status_page("audio-speakers-symbolic", L("还没有会议记录"),
+ L("点“开始听”,将电脑播放的声音转为双语字幕和纪要"),
+ [ui.button(L("开始听"), self.app.toggle_listening, "accentbtn pill"),
+ ui.button(L("播放示例会议"), self.app.play_sample, "outline pill")]), True, True, 0)
+ d.show_all()
+ return
+ if no_match:
+ d.pack_start(self._status_page("system-search-symbolic", L("没有找到"), LF("没有标题或对话含有“%@”", self.query.strip()), []), True, True, 0)
+ d.show_all()
+ return
+ s = self.app.store.get(self.selected) if self.selected else None
+ if s is None:
+ ui.clear(d)
+ self.columns = None
+ self._built_key = None
+ d.show_all()
+ return
+ live = self.app.listen.listening and self.app.listen.session_id == s.id
+ key = (s.id, self.mode, live)
+ if getattr(self, "_built_key", None) == key and self.columns is not None:
+ self._update_detail(s, live)
+ return
+ ui.clear(d)
+ self._built_key = key
+
+ # Title, meta, actions
+ top = 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)
+ top.pack_start(left, True, True, 0)
+ actions = ui.hbox(8)
+ actions.set_valign(Gtk.Align.START)
+ actions.pack_start(ui.button(L("导出…"), lambda: self.export(s), "outline", "document-save-symbolic"), False, False, 0)
+ actions.pack_start(self._more_menu(s), False, False, 0)
+ top.pack_end(actions, False, False, 0)
+ d.pack_start(top, False, False, 0)
+
+ # Notes | transcript
+ self.columns = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=40)
+ self.columns.set_homogeneous(True)
+ self.columns.set_margin_top(24)
+ self.notes_col = self._notes_column(s, live)
+ self._notes_key = self._notes_state(s, live)
+ self.columns.pack_start(self.notes_col, True, True, 0)
+ self.columns.pack_start(self._transcript_column(s), True, True, 0)
+ d.pack_start(self.columns, False, False, 0)
+ self._resized(self, self.get_allocation())
+ d.show_all()
+ GLib.idle_add(lambda: self.right.get_vadjustment().set_value(keep) and False)
+
+ def _meta(self, s, live) -> str:
+ langs = ""
+ if s.lines:
+ src, dst = s.lines[0].srcLang, s.lines[0].dstLang
+ langs = " · " + (lang_name(src) if src == dst else lang_name(src) + " → " + lang_name(dst))
+ return "%s · %s · %d %s%s" % (session_store._local_date(s.startedAt, L("M月d日 HH:mm")), L("正在听") if live else clock(s.duration),
+ len(s.lines), L("句"), langs)
+
+ def _notes_state(self, s, live):
+ 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 (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 = None
+ self.show_detail()
+ return
+ ui.retext(self.title_label, session_store.display_title(s))
+ ui.retext(self.meta_label, self._meta(s, live))
+ state = self._notes_state(s, live)
+ if state != self._notes_key:
+ self._notes_key = state
+ new = self._notes_column(s, live)
+ self.columns.remove(self.notes_col)
+ self.notes_col.destroy()
+ self.notes_col = new
+ self.columns.pack_start(new, True, True, 0)
+ self.columns.reorder_child(new, 0)
+ new.show_all()
+ self._nums = speakers.numbers(s.lines) if self._vnums else {}
+ starts = speakers.run_starts(s.lines, self._nums)
+ for i, l in enumerate(s.lines[:len(self._rows)]):
+ if self._rows[i][0] != self._row_key(l, l.id in starts):
+ old_row = self._rows[i][1]
+ k, row = self._row(l, l.id in starts)
+ 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
+ row.show_all()
+ self._rows[i] = (k, row)
+ self._more_rows()
+
+ 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
+
+ def current():
+ return self.app.store.get(sid)
+ items = []
+ for label, action in ((L("重命名…"), lambda: current() and self.rename(current())),
+ (L("恢复自动标题"), lambda: self.app.store.rename(sid, "")),
+ (L("删除"), lambda: current() and self.delete(current()))):
+ item = Gtk.MenuItem(label=label)
+ item.connect("activate", lambda _i, a=action: a())
+ menu.append(item)
+ items.append(item)
+ menu.show_all()
+
+ def update(*_):
+ cur = current()
+ renamed = cur is not None and (cur.renamed if cur.renamed is not None else not cur.title.startswith("会议 "))
+ items[1].set_visible(bool(renamed and cur.notes is not None and cur.notes.title))
+ items[2].set_sensitive(sid != self.app.store.live)
+ return False
+ update()
+ 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.add(ui.icon("view-more-symbolic"))
+ b.set_tooltip_text(L("更多操作"))
+ ui.classes(b, "outline")
+ return b
+
+ def _section_title(self, s: str) -> Gtk.Label:
+ return ui.text(s, 12, "tertiary", bold=True, wrap=False)
+
+ def _notes_column(self, s, live) -> Gtk.Widget:
+ 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.id
+ if n is None or n.is_empty:
+ if working:
+ row = ui.hbox(10)
+ sp = Gtk.Spinner()
+ sp.start()
+ row.pack_start(sp, False, False, 0)
+ row.pack_start(ui.text(L("正在整理纪要…"), 13, "secondary", wrap=False), False, False, 0)
+ col.pack_start(ui.gap(row, 14), False, False, 0)
+ elif live:
+ col.pack_start(ui.gap(ui.text(L("会中每 45 秒更新"), 13, "secondary"), 12), False, False, 0)
+ else:
+ col.pack_start(ui.gap(ui.text(L("这场会议还没有纪要"), 13, "secondary"), 12), False, False, 0)
+ b = ui.button(L("生成纪要"), lambda: self._generate(s.id), "darkbtn")
+ b.set_halign(Gtk.Align.START)
+ col.pack_start(ui.gap(b, 12), False, False, 0)
+ return col
+ if 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:
+ row = ui.hbox(10, ui.chip(clock(t.start)))
+ row.pack_start(ui.text(t.title, 14, "ink", bold=True, selectable=True, width_chars=40), True, True, 0)
+ col.pack_start(ui.gap(row, 22), False, False, 0)
+ if t.summary:
+ col.pack_start(ui.gap(ui.text(t.summary, 12, "tertiary", selectable=True, width_chars=50), 4), False, False, 0)
+ 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
+ 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)
+ cards = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
+ cards.set_homogeneous(True)
+ for title, items in ((L("结论"), [c.text for c in n.conclusions]),
+ (L("待办"), ["☐ " + t.text + (" · " + t.owner if t.owner else "") for t in n.todos])):
+ if not items:
+ continue
+ inner = ui.vbox(6, ui.text(title, 12, "tertiary", bold=True, wrap=False))
+ for it in items:
+ inner.pack_start(ui.text(it, 13, "ink", selectable=True, width_chars=22), False, False, 0)
+ ui.pad(inner, 14, 16)
+ cards.pack_start(ui.panel(inner, "softcard"), True, True, 0)
+ if cards.get_children():
+ col.pack_start(ui.gap(cards, 24), False, False, 0)
+ if working:
+ col.pack_start(ui.gap(ui.helper(L("正在整理纪要…")), 14), False, False, 0)
+ return col
+
+ def _transcript_column(self, s) -> Gtk.Widget:
+ col = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
+ col.set_valign(Gtk.Align.START)
+ head = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
+ head.pack_start(self._section_title(L("文字记录")), True, True, 0)
+
+ def mode(v):
+ self.mode = v
+ self.show_detail()
+ has_dst = any(l.dst and l.dst != l.src for l in s.lines)
+ if has_dst:
+ head.pack_end(ui.segmented([("both", L("双语")), ("dst", L("只看译文"))], self.mode, mode), False, False, 0)
+ col.pack_start(head, False, False, 0)
+ self.transcript = col
+ self._both = s.sourceFile is None and any(l.speaker == "me" for l in s.lines)
+ self._nums, self._vnums, self._shown = self._speakers(s)
+ self._speaker_key = self._speaker_state_key(s)
+ self._sid = s.id
+ if self._vnums:
+ col.pack_start(self._people(s), False, False, 0)
+ self._rows = []
+ self._loader = None
+ 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 or s.sourceFile is not None:
+ return {}, {}, {}
+ vnums = speakers.voice_numbers(s.lines)
+ return speakers.numbers(s.lines), vnums, (speakers.names(s) if vnums else {})
+
+ def _speaker_state_key(self, s):
+ _n, vnums, shown = self._speakers(s)
+ busy = s.id in self.app.namer.busy
+ return (tuple(sorted(vnums.items())), tuple(sorted(shown.items())), str(sorted((s.voiceGuesses or {}).keys())), busy)
+
+ def _row_key(self, l, start):
+ return (l.id, l.src, l.dst, l.voice, start)
+
+ 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)
+ if n is not None:
+ return speakers.label(n, self._shown), "spk%d" % ((n - 1) % 4 + 1)
+ return speakers.speaker_name(l, self._nums, self._shown), "secondary"
+
+ def _speaker_label(self, l):
+ text, cls = self._who(l)
+ lbl = ui.text(text, 11, cls, bold=True, wrap=False)
+ if l.speaker == "me" or 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)
+ b.set_halign(Gtk.Align.START)
+ ui.classes(b, "spklabel")
+ b.set_tooltip_text(L("这句是谁说的"))
+ b.connect("clicked", lambda w: self._assign_menu(w, l))
+ return b
+
+ def _assign_menu(self, widget, l) -> None:
+ menu = Gtk.Menu()
+ head = Gtk.MenuItem(label=L("这句是谁说的"))
+ head.set_sensitive(False)
+ menu.append(head)
+ for v, n in sorted(self._vnums.items(), key=lambda kv: kv[1]):
+ item = Gtk.MenuItem(label=speakers.label(n, self._shown) + (" ✓" if l.voice == v else ""))
+ item.connect("activate", lambda _i, v=v: self._edited(*self.app.assign_lines(self._sid, {l.id}, v)))
+ menu.append(item)
+ menu.show_all()
+ menu.attach_to_widget(widget, None)
+ menu.popup_at_widget(widget, Gdk.Gravity.SOUTH_WEST, Gdk.Gravity.NORTH_WEST, None)
+
+ def _edited(self, text, snap) -> None:
+ sid = self._sid
+ if text:
+ 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)
+ row.set_row_spacing(6)
+ row.set_min_children_per_line(1)
+ row.set_max_children_per_line(6)
+ row.set_valign(Gtk.Align.START)
+ guessed = speakers.guessed(s)
+ for v, n in sorted(self._vnums.items(), key=lambda kv: kv[1]):
+ chip = Gtk.Button()
+ box = ui.hbox(5)
+ box.pack_start(ui.text("●", 9, "spk%d" % ((n - 1) % 4 + 1), wrap=False, ellipsize=False), False, False, 0)
+ box.pack_start(ui.text(speakers.label(n, self._shown), 11, "ink", bold=True, wrap=False, ellipsize=False), False, False, 0)
+ chip.add(box)
+ ui.classes(chip, "spkchip")
+ chip.set_tooltip_text(L("Ling 从对话里认出,点一下可以改") if n in guessed else L("改名字,或和别人合并"))
+ chip.connect("clicked", lambda w, v=v: self._editor(w, v))
+ chip.set_halign(Gtk.Align.START)
+ child = Gtk.FlowBoxChild()
+ child.add(chip)
+ row.add(child)
+ off = ui.link(L("不准?关掉"), lambda: self.app.set_speaker_voices(False))
+ off.set_tooltip_text(L("关掉说话人识别,记录里的名字一起收起"))
+ line = ui.hbox(8)
+ line.pack_start(row, True, True, 0)
+ off.set_valign(Gtk.Align.START)
+ line.pack_end(off, False, False, 0)
+ 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
+ n = self._vnums[voice]
+ guess = speakers.guessed(s).get(n)
+ pop = Gtk.Popover(relative_to=chip)
+ box = ui.vbox(10)
+ ui.pad(box, 14, 16)
+ head = ui.hbox(6)
+ head.pack_start(ui.text("●", 10, "spk%d" % ((n - 1) % 4 + 1), wrap=False, ellipsize=False), False, False, 0)
+ head.pack_start(ui.text(speakers.label(n, self._shown), 13, "ink", bold=True, wrap=False), False, False, 0)
+ said = sum(1 for l in s.lines if l.voice == voice)
+ head.pack_start(ui.text(LF("说了 %lld 句", said), 11, "tertiary", wrap=False), False, False, 0)
+ box.pack_start(head, False, False, 0)
+ box.pack_start(ui.text(L("是谁"), 11, "secondary", bold=True, wrap=False), False, False, 0)
+ entry = Gtk.Entry()
+ entry.set_placeholder_text(L("输入名字"))
+ entry.set_text(self._shown.get(n, ""))
+ entry.set_width_chars(24)
+ picks = speakers.suggestions(s, voice)
+ if picks:
+ flow = ui.hbox(6)
+ for name in picks:
+ b = ui.button(name, lambda name=name: (entry.set_text(name), entry.grab_focus()), "pick" + (" chosen" if name == self._shown.get(n) else ""))
+ flow.pack_start(b, False, False, 0)
+ box.pack_start(flow, False, False, 0)
+ box.pack_start(entry, False, False, 0)
+
+ 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:
+ self._edited(*self.app.rename_speaker(self._sid, voice, name))
+ entry.connect("activate", lambda *_: apply())
+ if guess is not None:
+ g = ui.hbox(8)
+ g.pack_start(ui.text(LF("Ling 从对话里认出:%@", guess.evidence) if guess.evidence else L("Ling 从对话里认出"),
+ 11, "secondary", width_chars=30), True, True, 0)
+
+ def not_them():
+ pop.popdown()
+ self._edited(*self.app.rename_speaker(self._sid, voice, ""))
+ g.pack_end(ui.link(L("不是 TA"), not_them), False, False, 0)
+ box.pack_start(g, False, False, 0)
+ elif self._sid in self.app.namer.busy:
+ box.pack_start(ui.text(L("Ling 正在从对话里找名字…"), 11, "tertiary", wrap=False), False, False, 0)
+ others = sorted(((v, m) for v, m in self._vnums.items() if v != voice), key=lambda kv: kv[1])
+ if others:
+ box.pack_start(ui.text(L("其实是同一个人"), 11, "secondary", bold=True, wrap=False), False, False, 0)
+ merges = ui.hbox(6)
+
+ def merge(into):
+ pop.popdown()
+ self._edited(*self.app.merge_speaker(self._sid, voice, into))
+ for v, m in others[:3]:
+ merges.pack_start(ui.button(LF("并入 %@", speakers.label(m, self._shown)), lambda v=v: merge(v), "pick"), False, False, 0)
+ if len(others) > 3:
+ more = Gtk.MenuButton(label=L("更多"))
+ ui.classes(more, "pick")
+ menu = Gtk.Menu()
+ for v, m in others[3:]:
+ item = Gtk.MenuItem(label=LF("并入 %@", speakers.label(m, self._shown)))
+ item.connect("activate", lambda _i, v=v: merge(v))
+ menu.append(item)
+ menu.show_all()
+ more.set_popup(menu)
+ merges.pack_start(more, False, False, 0)
+ box.pack_start(merges, False, False, 0)
+ buttons = ui.hbox(8)
+ buttons.pack_end(ui.button(L("完成"), apply, "darkbtn"), False, False, 0)
+ buttons.pack_end(ui.button(L("取消"), pop.popdown, "outline"), False, False, 0)
+ box.pack_start(buttons, False, False, 0)
+ pop.add(box)
+ box.show_all()
+ pop.popup()
+ entry.grab_focus()
+
+ 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.set_size_request(44, -1)
+ t.set_valign(Gtk.Align.START)
+ t.set_margin_top(2)
+ row.pack_start(t, 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):
+ texts.pack_start(self._speaker_label(l), False, False, 0)
+ translated = l.dst and l.dst != l.src
+ texts.pack_start(ui.text(l.dst if translated else l.src, 13, "ink", selectable=True, width_chars=46,
+ lang=l.dstLang if translated else l.srcLang), False, False, 0)
+ if translated and self.mode == "both":
+ texts.pack_start(ui.text(l.src, 12, "tertiary", selectable=True, width_chars=46, lang=l.srcLang), False, False, 0)
+ row.pack_start(texts, True, True, 0)
+ ui.pad(row, 9, 0, 9, 0)
+ return self._row_key(l, start), ui.panel(row, "transcript-row")
+
+ def _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_key
+
+ def step(count):
+ if self._built_key != built:
+ return False
+ s = self.app.store.get(built[0])
+ if s is None:
+ return False
+ lines = s.lines
+ starts = speakers.run_starts(lines, self._nums)
+ for l in lines[len(self._rows):len(self._rows) + count]:
+ k, row = self._row(l, l.id in starts)
+ self.transcript.pack_start(row, False, False, 0)
+ row.show_all()
+ self._rows.append((k, row))
+ if len(self._rows) < len(lines):
+ return True
+ self._loader = None
+ return False
+ if step(60 if first else 200) and self._loader is None:
+ self._loader = GLib.idle_add(step, 200)
+
+ 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 export(self, s) -> None:
+ dialog = Gtk.FileChooserDialog(title=L("导出"), transient_for=self, action=Gtk.FileChooserAction.SAVE)
+ dialog.add_buttons(L("取消"), Gtk.ResponseType.CANCEL, L("保存"), Gtk.ResponseType.ACCEPT)
+ dialog.set_do_overwrite_confirmation(True)
+ dialog.set_current_name(session_store.display_title(s).replace("/", "-") + ".md")
+ docs = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) or os.path.expanduser("~")
+ dialog.set_current_folder(docs)
+ path = dialog.get_filename() if dialog.run() == Gtk.ResponseType.ACCEPT else None
+ dialog.destroy()
+ if not path:
+ return
+ try:
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(session_store.markdown(s, voices=self.app.settings.speakerVoices))
+ except OSError:
+ self.toasts.show(L("保存失败"))
+ return
+ self.toasts.show(LF("已导出“%@”", os.path.basename(path)), L("在文件夹中显示"), lambda: show_in_folder(path))
+
+ def rename(self, s) -> None:
+ dialog = Gtk.Dialog(title=L("重命名"), transient_for=self, modal=True)
+ dialog.add_buttons(L("取消"), Gtk.ResponseType.CANCEL, L("重命名"), Gtk.ResponseType.OK)
+ dialog.set_default_response(Gtk.ResponseType.OK)
+ entry = Gtk.Entry()
+ entry.set_text(session_store.display_title(s))
+ entry.set_activates_default(True)
+ entry.set_width_chars(36)
+ area = dialog.get_content_area()
+ ui.pad(area, 12, 16)
+ area.add(entry)
+ dialog.show_all()
+ if dialog.run() == Gtk.ResponseType.OK and entry.get_text().strip():
+ self.app.store.rename(s.id, entry.get_text())
+ 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:
+ return
+ self.commit_delete()
+ self.pending_delete = s.id
+ self.selected = None
+ self.fill()
+
+ def undo():
+ self.pending_delete = None
+ self.selected = s.id
+ self.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, None
+ if sid:
+ self.app.store.delete(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()
+
+ def fallback():
+ try:
+ Gio.AppInfo.launch_default_for_uri(folder, None)
+ except GLib.Error:
+ pass
+
+ def done(bus, result):
+ try:
+ bus.call_finish(result)
+ except GLib.Error:
+ fallback()
+ try:
+ bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+ bus.call("org.freedesktop.FileManager1", "/org/freedesktop/FileManager1", "org.freedesktop.FileManager1",
+ "ShowItems", GLib.Variant("(ass)", ([uri], "")), None, Gio.DBusCallFlags.NONE, 10000, None, done)
+ except GLib.Error:
+ fallback()
diff --git a/linux/cicada/app/room.py b/linux/cicada/app/room.py
new file mode 100644
index 0000000..ae22130
--- /dev/null
+++ b/linux/cicada/app/room.py
@@ -0,0 +1,269 @@
+"""知了 麦克风: 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 annotations
+
+import ctypes
+import ctypes.util
+import os
+import time
+
+from ..core.ling import TTS_RATE
+from ..core.strings import L
+from ..core.support import Log, Paths
+from .capture import _INFO_CB, PA_SAMPLE_S16LE, _Attr, _libpulse, _pulse, _Spec # one server-info type for both
+
+SINK = "cicada_room"
+MIC = "cicada_mic"
+PA_STREAM_PLAYBACK = 1
+
+
+class _ModuleInfo(ctypes.Structure):
+ _fields_ = [("index", ctypes.c_uint32), ("name", ctypes.c_char_p), ("argument", ctypes.c_char_p)]
+
+
+_MODULE_CB = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(_ModuleInfo), ctypes.c_int, ctypes.c_void_p)
+_INDEX_CB = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p)
+_SUCCESS_CB = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p)
+
+
+def _lib():
+ l = _libpulse()
+ if not getattr(l, "_room_ready", False):
+ l.pa_context_load_module.restype = ctypes.c_void_p
+ l.pa_context_load_module.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, _INDEX_CB, ctypes.c_void_p]
+ l.pa_context_unload_module.restype = ctypes.c_void_p
+ l.pa_context_unload_module.argtypes = [ctypes.c_void_p, ctypes.c_uint32, _SUCCESS_CB, ctypes.c_void_p]
+ l.pa_context_get_module_info_list.restype = ctypes.c_void_p
+ l.pa_context_get_module_info_list.argtypes = [ctypes.c_void_p, _MODULE_CB, ctypes.c_void_p]
+ l.pa_context_set_default_source.restype = ctypes.c_void_p
+ l.pa_context_set_default_source.argtypes = [ctypes.c_void_p, ctypes.c_char_p, _SUCCESS_CB, ctypes.c_void_p]
+ l._room_ready = True
+ return l
+
+
+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()
+ self.ctx = self.l.pa_context_new(self.l.pa_mainloop_get_api(self.loop), b"Cicada")
+ self.ok = self.l.pa_context_connect(self.ctx, None, 0, None) >= 0 and self._ready()
+
+ def _ready(self) -> bool:
+ deadline = time.monotonic() + 2
+ while time.monotonic() < deadline:
+ self.l.pa_mainloop_iterate(self.loop, 0, None)
+ state = self.l.pa_context_get_state(self.ctx)
+ if state == 4:
+ return True
+ if state in (5, 6):
+ return False
+ time.sleep(0.005)
+ return False
+
+ def wait(self, op) -> None:
+ if not op:
+ return
+ deadline = time.monotonic() + 3
+ while time.monotonic() < deadline and self.l.pa_operation_get_state(op) == 0:
+ self.l.pa_mainloop_iterate(self.loop, 0, None)
+ time.sleep(0.003)
+ self.l.pa_operation_unref(op)
+
+ def server(self) -> dict:
+ out = {}
+
+ @_INFO_CB
+ def got(_c, info, _u):
+ if info:
+ i = info.contents
+ out["sink"] = i.default_sink_name.decode() if i.default_sink_name else None
+ out["source"] = i.default_source_name.decode() if i.default_source_name else None
+ self.wait(self.l.pa_context_get_server_info(self.ctx, got, None))
+ return out
+
+ def modules(self) -> list:
+ found = []
+
+ @_MODULE_CB
+ def got(_c, info, eol, _u):
+ if eol == 0 and info:
+ i = info.contents
+ found.append((i.index, (i.name or b"").decode(), (i.argument or b"").decode()))
+ self.wait(self.l.pa_context_get_module_info_list(self.ctx, got, None))
+ return found
+
+ def load(self, name: str, args: str):
+ box = {}
+
+ @_INDEX_CB
+ def got(_c, index, _u):
+ box["index"] = index
+ self.wait(self.l.pa_context_load_module(self.ctx, name.encode(), args.encode(), got, None))
+ index = box.get("index")
+ return None if index is None or index == 0xFFFFFFFF else index
+
+ def unload(self, index: int) -> None:
+ @_SUCCESS_CB
+ def done(_c, _ok, _u):
+ pass
+ self.wait(self.l.pa_context_unload_module(self.ctx, index, done, None))
+
+ def set_default_source(self, name: str) -> None:
+ @_SUCCESS_CB
+ def done(_c, _ok, _u):
+ pass
+ self.wait(self.l.pa_context_set_default_source(self.ctx, name.encode(), done, None))
+
+ def close(self) -> None:
+ self.l.pa_context_disconnect(self.ctx)
+ self.l.pa_context_unref(self.ctx)
+ self.l.pa_mainloop_free(self.loop)
+
+
+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.on = False
+
+ @staticmethod
+ def _load():
+ try:
+ with open(_saved_path()) as f:
+ return f.read().strip() or None
+ except OSError:
+ return None
+
+ def _save(self) -> None:
+ try:
+ with open(_saved_path(), "w") as f:
+ f.write(self.real_mic or "")
+ except OSError:
+ pass
+
+ def 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:
+ return
+ try:
+ if s.ok and self._ours(s.modules()):
+ Log.d("room: removing 知了 麦克风 left by an earlier run")
+ self._give_back(s)
+ finally:
+ s.close()
+
+ def _give_back(self, s) -> None:
+ 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
+
+ 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:
+ Log.d("room: no libpulse (%s)" % e)
+ return False
+ try:
+ if not s.ok:
+ Log.d("room: can't reach the sound server")
+ return False
+ 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_mic
+ self._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))
+ b = s.load("module-remap-source", "master=%s.monitor source_name=%s source_properties=\"device.description='%s'\""
+ % (SINK, MIC, mic_desc))
+ if a is None or b is None:
+ Log.d("room: modules not loaded (%s, %s)" % (a, b))
+ for index in self._ours(s.modules()):
+ s.unload(index)
+ return False
+ s.set_default_source(MIC)
+ self.on = True
+ Log.d("room: 知了 麦克风 ready, recording me from the previous default input")
+ return True
+ finally:
+ s.close()
+
+ def remove(self) -> None:
+ try:
+ s = _Session()
+ except OSError:
+ return
+ try:
+ if not s.ok:
+ return
+ self._give_back(s)
+ self.on = False
+ Log.d("room: 知了 麦克风 removed")
+ finally:
+ s.close()
+
+
+class Player:
+ """Plays 24 kHz mono 16-bit PCM into a sink: 知了 麦克风's (the room) or, for 试听, the speakers."""
+
+ def __init__(self, device: str | None = SINK):
+ 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 = lib
+ spec = _Spec(PA_SAMPLE_S16LE, TTS_RATE, 1)
+ attr = _Attr(0xFFFFFFFF, TTS_RATE // 5 * 2, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) # ~200 ms buffered
+ 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))
+ if not self.s:
+ Log.d("room: can't play to %s: %s" % (device, lib.strerror(err.value).decode()))
+ self._odd = b""
+
+ def write(self, pcm: bytes) -> None:
+ if not self.s:
+ return
+ data = self._odd + pcm
+ if len(data) % 2:
+ self._odd, data = data[-1:], data[:-1]
+ else:
+ self._odd = b""
+ err = ctypes.c_int(0)
+ self.lib.pa_simple_write(self.s, data, len(data), ctypes.byref(err))
+
+ def drain(self) -> None:
+ if self.s:
+ err = ctypes.c_int(0)
+ self.lib.pa_simple_drain(self.s, ctypes.byref(err))
+
+ def close(self) -> None:
+ if self.s:
+ self.lib.pa_simple_free(self.s)
+ self.s = None
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
new file mode 100644
index 0000000..6698893
--- /dev/null
+++ b/linux/cicada/app/settings_window.py
@@ -0,0 +1,484 @@
+"""设置, GNOME preferences style: groups of boxed-list rows, the title and a grey line on the left and
+the control on the right. Ling key, languages, what shows while listening (and 登录时启动), the
+model, about."""
+from __future__ import annotations
+
+import os
+import subprocess
+import threading
+import time
+
+from gi.repository import Gdk, GLib, Gtk
+
+from .. import VERSION
+from ..core import ling as lingmod
+from ..core.ling import AIKey
+from ..core.strings import L, LF
+from ..core.support import TARGETS, Paths, follow_system_target, my_language, system_languages
+from . import ui
+
+LING_PLATFORM = "https://chat.ant-ling.com/platform/api"
+
+
+def open_uri(uri: str) -> None:
+ try:
+ Gtk.show_uri_on_window(None, uri, Gtk.get_current_event_time())
+ except GLib.Error:
+ subprocess.Popen(["xdg-open", uri], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+
+
+def choice(options, current, on_change) -> Gtk.ComboBoxText:
+ c = Gtk.ComboBoxText()
+ for value, label in options:
+ c.append(value, label)
+ c.set_active_id(current if current in [o[0] for o in options] else options[0][0])
+ c.connect("changed", lambda w: on_change(w.get_active_id()))
+ c.set_size_request(170, -1)
+ return c
+
+
+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)
+ both = " / ".join(names.get(c, c) for c in (mine, follow_system_target(mine, prefs)))
+ 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 ""))
+
+
+def autostart_enabled() -> bool:
+ return os.path.isfile(autostart_path())
+
+
+def set_autostart(on: bool, launcher: str) -> None:
+ path = autostart_path()
+ if not on:
+ try:
+ os.remove(path)
+ except OSError:
+ pass
+ return
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8") as f:
+ f.write("[Desktop Entry]\nType=Application\nName=Cicada\nName[zh_CN]=知了\n"
+ "Exec=%s%s\nIcon=cicada\nTerminal=false\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n"
+ % (launcher, " --dev" if Paths.dev else ""))
+
+
+# GNOME custom keyboard shortcuts: `cicada --toggle` (开始 / 结束听) and `cicada --speak` (开始 / 停止说).
+
+PREVIEW = { # what 试听 says, spoken text not UI (not L()): one per language a voice speaks
+ "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.",
+ "de": "So klingt die Stimme, die die anderen hören.",
+}
+SHORTCUTS = {"toggle": ("cicada", "<Super><Shift>c", "Super + Shift + C"),
+ "speak": ("cicada-speak", "<Super><Shift>s", "Super + Shift + S")}
+MEDIA_KEYS = "org.gnome.settings-daemon.plugins.media-keys"
+CUSTOM = "org.gnome.settings-daemon.plugins.media-keys.custom-keybinding"
+
+
+def _custom_path(which: str) -> str:
+ return "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/%s%s/" % (SHORTCUTS[which][0], "-dev" if Paths.dev else "")
+
+
+def gnome_shortcut(which: str):
+ """None off GNOME; "" when not added; else the key, as shown."""
+ try:
+ from gi.repository import Gio
+ source = Gio.SettingsSchemaSource.get_default()
+ if not source or not source.lookup(MEDIA_KEYS, True):
+ return None
+ keys = Gio.Settings.new(MEDIA_KEYS)
+ 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
+ return None
+
+
+def set_gnome_shortcut(which: str, command: str) -> None:
+ from gi.repository import Gio
+ keys = Gio.Settings.new(MEDIA_KEYS)
+ paths = keys.get_strv("custom-keybindings")
+ if _custom_path(which) not in paths:
+ keys.set_strv("custom-keybindings", paths + [_custom_path(which)])
+ one = Gio.Settings.new_with_path(CUSTOM, _custom_path(which))
+ one.set_string("name", "Cicada" if which == "toggle" else "Cicada · 同声传译")
+ one.set_string("command", command)
+ one.set_string("binding", SHORTCUTS[which][1])
+
+
+class SettingsWindow(Gtk.Window):
+ def __init__(self, app):
+ super().__init__(title=L("设置") + " · " + L("知了"))
+ self.app = app
+ self.set_default_size(640, 760)
+ self.set_position(Gtk.WindowPosition.CENTER)
+ self.set_wmclass("cicada", "Cicada")
+ self.connect("delete-event", lambda *_: self.hide() or True)
+ self.connect("key-press-event", lambda _w, e: (self.hide() or True) if e.keyval == Gdk.KEY_Escape else False)
+ bar = Gtk.HeaderBar()
+ bar.set_show_close_button(True)
+ bar.set_title(L("设置"))
+ ui.classes(bar, "cicada", "ground-bar")
+ self.set_titlebar(bar)
+ s = app.settings
+
+ scroll = Gtk.ScrolledWindow()
+ scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
+ ui.classes(scroll, "ground")
+ page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
+ ui.pad(page, 8, 32, 28, 32)
+ scroll.add(page)
+ self.add(scroll)
+
+ def save():
+ s.save()
+ app.settings_changed()
+
+ # Ling key
+ self.key_line = ui.text("", 13, "ink mono", wrap=False)
+ self.key_status = ui.hbox(6)
+ key_left = ui.vbox(4, self.key_line, self.key_status)
+ self.change_button = ui.button(L("更换…"), self._toggle_entry, "outline")
+ self.remove_button = ui.button(L("删除"), self.remove_key, "dangertext")
+ key_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
+ key_row.pack_start(key_left, True, True, 0)
+ for b in (self.change_button, self.remove_button):
+ b.set_valign(Gtk.Align.CENTER)
+ key_row.pack_start(b, False, False, 0)
+ key_row = ui.panel(ui.pad(key_row, 10, 14), "prow")
+ self.key_entry = Gtk.Entry()
+ self.key_entry.set_visibility(False)
+ self.key_entry.set_placeholder_text("sk-…")
+ self.key_entry.connect("activate", lambda *_: self.save_key())
+ self.key_entry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "view-reveal-symbolic")
+ self.key_entry.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY, L("显示 key"))
+ self.key_entry.connect("icon-press", lambda e, *_: e.set_visibility(not e.get_visibility()))
+ entry_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
+ entry_row.pack_start(self.key_entry, True, True, 0)
+ entry_row.pack_start(ui.button(L("保存"), self.save_key, "darkbtn"), False, False, 0)
+ self.entry_row = ui.panel(ui.pad(entry_row, 12, 16), "prow")
+ get_key = Gtk.Button()
+ get_key.add(ui.pad(ui.hbox(8, ui.text(L("获取 Ling key"), 13, "ink", wrap=False)), 10, 14))
+ get_key.get_child().pack_end(ui.icon("external-link-symbolic", 14), False, False, 0)
+ ui.classes(get_key, "linkrow")
+ get_key.connect("clicked", lambda *_: open_uri(LING_PLATFORM))
+ # Shown and hidden by show_key_state; show_all() must leave them alone.
+ self.entry_row.set_no_show_all(True)
+ entry_row.show_all()
+ self.key_group = ui.boxed([key_row, self.entry_row, get_key])
+ page.pack_start(self._group(L("Ling key"), self.key_group,
+ L("仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)")), False, False, 0)
+
+ # Languages
+ def set_target(v):
+ s.target = v
+ save()
+
+ def set_notes(v):
+ s.notesLanguage = v
+ save()
+
+ def set_ui(v):
+ s.uiLanguage = v
+ save()
+ combos = [choice(target_options(), s.target, set_target),
+ choice([("system", L("和字幕一样"))] + [(c, n) for n, c in TARGETS], s.notesLanguage, set_notes),
+ choice([("system", L("跟随系统")), ("zh-Hans", "简体中文"), ("en", "English"), ("ja", "日本語"), ("ko", "한국어")],
+ s.uiLanguage, set_ui)]
+ ui_row = ui.prow(L("界面语言"), combos[2], L("重启知了后生效"))
+ page.pack_start(self._group(L("语言"), ui.boxed([ui.prow(L("翻译成"), combos[0]), ui.prow(L("纪要语言"), combos[1]), ui_row])),
+ False, False, 0)
+
+ # While listening
+ switch = Gtk.Switch()
+ switch.set_active(autostart_enabled())
+ switch.connect("notify::active", lambda w, _p: set_autostart(w.get_active(), app.launcher))
+ warn = ui.hbox(12)
+ warn_icon = ui.icon("view-reveal-symbolic", 15)
+ ui.classes(warn_icon, "warn")
+ warn_icon.set_valign(Gtk.Align.START)
+ warn.pack_start(warn_icon, False, False, 0)
+ warn.pack_start(ui.text(L("Linux 下共享屏幕时对方能看到纪要窗。共享前点它右上角的 × 隐藏,知了会继续听。"), 12, "", width_chars=50), True, True, 0)
+ warn_row = ui.panel(ui.pad(warn, 10, 14), "warnrow")
+ page.pack_start(self._group(L("正在听时"), ui.boxed([
+ ui.prow(L("悬浮窗"), ui.segmented([("notes", L("实时纪要")), ("subtitles", L("字幕条"))], s.view, app.set_view)),
+ ui.prow(L("登录时启动"), switch, L("登录后在顶栏待命")),
+ self._voices_row(),
+ self._shortcut_row(),
+ warn_row])), False, False, 0)
+
+ page.pack_start(self._speak_group(combos), False, False, 0)
+ page.pack_start(self._end_group(), False, False, 0)
+
+ # Model
+ def set_model(v):
+ s.model = v
+ app.ling.model = v
+ save()
+ model = choice([("Ling-3.1-flash", "Ling-3.1-flash"), ("Ling-3.0-flash", "Ling-3.0-flash")], s.model, set_model)
+ combos.append(model)
+ page.pack_start(self._group(L("模型"), ui.boxed([
+ ui.prow(L("翻译与纪要模型"), model, L("3.1 更准;3.0 更快、更省")),
+ ui.prow(L("语音识别"), ui.text(L("Ming(云端)"), 12, "tertiary", wrap=False))])), False, False, 0)
+
+ # About
+ rows = [ui.prow(L("版本"), ui.text(VERSION + " · Linux", 12, "tertiary", wrap=False))]
+ for label, action in ((L("打开记录文件夹"), lambda: self._open_folder(Paths.sessions())),
+ (L("打开日志"), lambda: open_uri("file://" + Paths.log())),
+ (L("重看新手引导"), app.show_onboarding)):
+ b = Gtk.Button()
+ inner = ui.hbox(8, ui.text(label, 13, "ink", wrap=False))
+ chevron = ui.icon("go-next-symbolic", 12)
+ ui.classes(chevron, "tertiary")
+ inner.pack_end(chevron, False, False, 0)
+ b.add(ui.pad(inner, 10, 14))
+ ui.classes(b, "linkrow")
+ b.connect("clicked", lambda _b, a=action: a())
+ rows.append(b)
+ page.pack_start(self._group(L("关于"), ui.boxed(rows)), False, False, 0)
+
+ for c in combos:
+ ui.no_wheel(c, scroll)
+ app.ling.on_change(lambda: GLib.idle_add(self.show_key_state))
+ self.connect("show", lambda *_: self.show_key_state())
+
+ 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.settings
+
+ def save():
+ s.save()
+ self.app.settings_changed()
+ app_switch = Gtk.Switch()
+ app_switch.set_active(s.endWithApp)
+ app_switch.connect("notify::active", lambda w, _p: (setattr(s, "endWithApp", w.get_active()), save()))
+ 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):
+ s.silenceEnd = v
+ save()
+ minutes.set_visible(v != "off")
+ silence = ui.prow(L("没人说话时"), ui.segmented([("prompt", L("提醒后结束")), ("end", L("直接结束")), ("off", L("一直记录"))],
+ s.silenceEnd, set_silence), L("按识别出的话算,背景音乐不算"))
+ return self._group(L("结束会议"), ui.boxed([
+ 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
+ return ui.prow(title, None, LF("在系统的键盘设置里,把命令 %@ 绑到一个按键", self.app.launcher + flag))
+ label = ui.text(state or "", 12, "secondary", wrap=False)
+
+ def add():
+ set_gnome_shortcut(which, self.app.launcher + (" --dev" if Paths.dev else "") + flag)
+ ui.retext(label, SHORTCUTS[which][2])
+ button.set_visible(False)
+ button = ui.button(L("添加"), add, "outline")
+ box = ui.hbox(8, label, button)
+ if state:
+ button.set_visible(False)
+ button.set_no_show_all(True)
+ return ui.prow(title, box, L("在任何窗口里都能用"))
+
+ def _voices_row(self) -> Gtk.Widget:
+ """说话人识别: on by default, as on the Mac; off when this build has no voiceprint library."""
+ app = self.app
+ sw = Gtk.Switch()
+ sw.set_valign(Gtk.Align.CENTER)
+ ok = app.voices_available
+ sw.set_active(ok and app.settings.speakerVoices)
+ sw.set_sensitive(ok)
+ sw.connect("notify::active", lambda w, _p: app.set_speaker_voices(w.get_active()))
+ return ui.prow(L("说话人识别"), sw, L("按声音标出说话人 1、2…,只在这台电脑上处理") if ok
+ 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 voicemod
+ from ..core.support import TARGETS
+ app, s = self.app, self.app.settings
+ names = {c: n for n, c in TARGETS}
+ rows = []
+ switch = Gtk.Switch()
+ switch.set_active(s.speakEnabled)
+ dependents = []
+
+ def toggled(w, _p):
+ on = w.get_active()
+ if on != s.speakEnabled and not app.set_speak_enabled(on):
+ w.set_active(False)
+ self.speak_status.set_visible(True)
+ ui.retext(self.speak_status, L("没能建好知了麦克风"))
+ for d in dependents:
+ d.set_sensitive(s.speakEnabled)
+ switch.connect("notify::active", toggled)
+ rows.append(ui.prow(L("同声传译"), switch, L("你说的话翻译后,用“知了 麦克风”传给对方")))
+
+ def set_from(v):
+ s.speakFrom = v
+ s.save()
+
+ def set_to(v):
+ s.speakTo = v
+ s.save()
+ fill_voices()
+ mine = choice([("system", LF("和字幕一样(%@)", names.get(s.target_code, s.target_code)))] + [(c, n) for n, c in TARGETS],
+ s.speakFrom, set_from)
+ theirs = choice([("room", LF("跟随对方(%@)", names.get(app.speak.target, app.speak.target)))] +
+ [(c, names.get(c, c)) for c in voicemod.ROOM_LANGUAGES], s.speakTo, set_to)
+ voice = Gtk.ComboBoxText()
+ voice.set_size_request(170, -1)
+
+ def fill_voices():
+ code = app.speak.target
+ voice.handler_block_by_func(set_voice) if getattr(voice, "_wired", False) else None
+ voice.remove_all()
+ for v, n, tags in voicemod.voices(code):
+ voice.append(v, "%s · %s" % (n, "、".join(L(t) for t in tags)))
+ voice.set_active_id(app.speak.voice(code) or "")
+ if getattr(voice, "_wired", False):
+ voice.handler_unblock_by_func(set_voice)
+
+ def set_voice(w):
+ v = w.get_active_id()
+ if v:
+ s.speakVoices[voicemod.key(app.speak.target)] = v
+ s.save()
+ fill_voices()
+ voice.connect("changed", set_voice)
+ voice._wired = True
+
+ def 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 Player
+
+ def run():
+ from ..core.support import Log
+ p = Player(None) # the speakers, not the room
+ start, n = time.monotonic(), 0
+ try:
+ for pcm in app.ling.speech(text, voice=app.speak.voice(code) or "US_Emma", language=voicemod.ming_language(code)):
+ n += len(pcm)
+ p.write(pcm)
+ p.drain()
+ Log.d("speak: preview %s %.1f s of voice in %.1f s" % (code, n / 2 / 24000, time.monotonic() - start))
+ except Exception as e: # noqa: BLE001
+ Log.d("speak: preview failed %s" % type(e).__name__)
+ finally:
+ p.close()
+ threading.Thread(target=run, daemon=True).start()
+ voice_box = ui.hbox(8, voice, ui.button(L("试听"), preview, "outline"))
+ combos.extend([mine, theirs, voice])
+ for title, control, sub in ((L("我说"), mine, None),
+ (L("对方听到"), theirs, L("跟随对方时,对方说什么语言就翻成什么")),
+ (L("声音"), voice_box, None)):
+ r = ui.prow(title, control, sub)
+ dependents.append(r)
+ rows.append(r)
+ 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)
+
+ def phones_toggled(sw, _p):
+ s.speakHeadphones = sw.get_active()
+ s.save()
+ phones.connect("notify::active", phones_toggled)
+ phones_row = ui.prow(L("戴着耳机"), phones, L("和对方同时说的话也会传出去"))
+ dependents.append(phones_row)
+ rows.append(phones_row)
+ tip = ui.hbox(12)
+ tip_icon = ui.icon("audio-headphones-symbolic", 15)
+ ui.classes(tip_icon, "warn")
+ tip_icon.set_valign(Gtk.Align.START)
+ tip.pack_start(tip_icon, False, False, 0)
+ tip.pack_start(ui.text(L("在会议软件里把麦克风选成“知了 麦克风”(或“默认”),并戴上耳机:外放时对方的声音会被当成你说的。"),
+ 12, "", width_chars=50), True, True, 0)
+ rows.append(ui.panel(ui.pad(tip, 10, 14), "warnrow"))
+ for d in dependents:
+ d.set_sensitive(s.speakEnabled)
+ self.speak_status = ui.text("", 11, "warn", width_chars=60)
+ self.speak_status.set_no_show_all(True)
+ return ui.vbox(6, self._group(L("同声传译"), ui.boxed(rows)), ui.pad(self.speak_status, 0, 4, 0, 4))
+
+ def _group(self, title, body, footer=None) -> Gtk.Widget:
+ box = ui.vbox(6, ui.pad(ui.text(title, 12, "group-title", bold=True, wrap=False), 0, 0, 0, 2), body)
+ if footer:
+ box.pack_start(ui.pad(ui.text(footer, 11, "tertiary", width_chars=60), 0, 2, 0, 2), False, False, 0)
+ return box
+
+ def _toggle_entry(self) -> None:
+ self.entry_row.set_visible(not self.entry_row.get_visible())
+ if self.entry_row.get_visible():
+ self.key_entry.grab_focus()
+
+ def show_key_state(self) -> bool:
+ k = self.app.key.read() or ""
+ state = self.app.ling.key_state
+ ui.clear(self.key_status)
+ have = bool(k)
+ ui.retext(self.key_line, AIKey.masked(k) if have else L("还没填 API key"))
+ icon_name, cls, label = {
+ lingmod.OK: ("object-select-symbolic", "ok", L("可以用")),
+ lingmod.CHECKING: ("content-loading-symbolic", "secondary", L("正在检查…")),
+ lingmod.INVALID: ("dialog-error-symbolic", "warn", L("这个 key 无效,请检查是否复制完整,或重新创建一个")),
+ lingmod.UNREACHABLE: ("network-offline-symbolic", "warn", L("连不上 Ling,检查网络")),
+ }.get(state, (None, "secondary", ""))
+ if have and label:
+ if icon_name:
+ img = ui.icon(icon_name, 14)
+ ui.classes(img, cls)
+ self.key_status.pack_start(img, False, False, 0)
+ self.key_status.pack_start(ui.text(label, 12, cls, width_chars=36), False, False, 0)
+ self.key_status.show_all()
+ self.key_status.set_visible(have and bool(label))
+ self.change_button.set_visible(have)
+ self.remove_button.set_visible(have)
+ self.entry_row.set_visible(not have or state == lingmod.INVALID)
+ return False
+
+ def save_key(self) -> None:
+ text = self.key_entry.get_text().strip()
+ if not text.startswith("sk-"):
+ self.key_entry.set_placeholder_text(L("复制 sk- 开头的 key,回来粘贴"))
+ self.key_entry.set_text("")
+ return
+ if not self.app.key.save(text):
+ return
+ self.key_entry.set_text("")
+ self.app.ling.key_changed()
+ threading.Thread(target=self.app.ling.check, daemon=True).start()
+
+ def remove_key(self) -> None:
+ self.app.key.remove()
+ self.app.ling.key_changed()
+
+ @staticmethod
+ def _open_folder(path) -> None:
+ os.makedirs(path, exist_ok=True)
+ open_uri("file://" + path)
diff --git a/linux/cicada/app/tray.py b/linux/cicada/app/tray.py
new file mode 100644
index 0000000..d2e9153
--- /dev/null
+++ b/linux/cicada/app/tray.py
@@ -0,0 +1,114 @@
+"""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 annotations
+
+import ctypes
+import ctypes.util
+
+from ..core.strings import L
+from ..core.support import Log
+
+
+def _gpointer(obj) -> int:
+ """The C pointer behind a PyGObject object (its __gpointer__ capsule)."""
+ get = ctypes.pythonapi.PyCapsule_GetPointer
+ get.restype = ctypes.c_void_p
+ get.argtypes = [ctypes.py_object, ctypes.c_char_p]
+ return get(obj.__gpointer__, None)
+
+
+def make(app, icon: str | None):
+ for name in ("ayatana-appindicator3", "appindicator3"):
+ path = ctypes.util.find_library(name)
+ if not path:
+ continue
+ try:
+ return Tray(app, ctypes.CDLL(path), icon)
+ except (OSError, AttributeError) as e:
+ Log.d("tray: %s unusable (%s)" % (name, e))
+ Log.d("tray: no AppIndicator, records window instead")
+ return None
+
+
+class Tray:
+ CATEGORY_APPLICATION_STATUS = 0
+ STATUS_ACTIVE = 1
+
+ def __init__(self, app, lib, icon):
+ from gi.repository import Gtk
+ self.app = app
+ self.Gtk = Gtk
+ lib.app_indicator_new.restype = ctypes.c_void_p
+ lib.app_indicator_new.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]
+ for f in ("app_indicator_set_status",):
+ getattr(lib, f).argtypes = [ctypes.c_void_p, ctypes.c_int]
+ lib.app_indicator_set_menu.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+ lib.app_indicator_set_title.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
+ lib.app_indicator_set_label.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p]
+ self.lib = lib
+ # 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())
+ self.menu = None
+ self.update()
+ Log.d("tray: AppIndicator")
+
+ def update(self) -> None:
+ Gtk = self.Gtk
+ listening = self.app.listen.listening
+ menu = Gtk.Menu()
+
+ def item(label, action, sensitive=True):
+ i = Gtk.MenuItem(label=label)
+ if action:
+ i.connect("activate", lambda *_: action())
+ i.set_sensitive(sensitive)
+ menu.append(i)
+ return i
+ # 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)
+ else:
+ self.detail_item = None
+ menu.append(Gtk.SeparatorMenuItem())
+ item(L("结束") if listening else L("开始听"), self.app.request_stop)
+ if self.app.settings.speakEnabled:
+ item(L("停止说") if self.app.speak.active else L("开始说"), self.app.toggle_speaking)
+ item(L("显示纪要"), self.app.show_notes)
+ item(L("打开会议记录"), self.app.show_records)
+ item(L("设置…"), self.app.show_settings)
+ menu.append(Gtk.SeparatorMenuItem())
+ item(L("退出知了"), self.app.quit)
+ menu.show_all()
+ 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.lib.app_indicator_set_label(self.ind, (self._clock() if listening else "").encode(), b"")
+
+ def _clock(self) -> str:
+ from datetime import datetime, timezone
+ from ..core.support import clock
+ s = self.app.store.get(self.app.listen.session_id) if self.app.listen.session_id else None
+ return clock((datetime.now(timezone.utc) - s.startedAt).total_seconds()) if s else ""
+
+ def _status(self) -> str:
+ return (L("正在听") + " · " + self._clock()) if self.app.listen.listening else L("知了")
+
+ def _detail(self) -> str:
+ from ..core import session_store
+ s = self.app.store.get(self.app.listen.session_id) if self.app.listen.session_id else None
+ if s is None:
+ return ""
+ return "%s · %d %s" % (session_store.display_title(s), len(s.lines), L("句"))
+
+ 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:
+ return
+ self.status_item.set_label(self._status())
+ if self.detail_item is not None:
+ self.detail_item.set_label(self._detail())
+ self.lib.app_indicator_set_label(self.ind, self._clock().encode(), b"")
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
new file mode 100644
index 0000000..d6ad60e
--- /dev/null
+++ b/linux/cicada/app/ui.py
@@ -0,0 +1,653 @@
+"""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 annotations
+
+import math
+
+import gi
+
+gi.require_version("Gtk", "3.0")
+gi.require_version("Gdk", "3.0")
+from gi.repository import Gdk, Gio, GLib, Gtk, Pango # noqa: E402
+
+CSS = b"""
+* { font-family: "Noto Sans", sans-serif; font-size: 13px; }
+.ground { background-color: #F3F4F6; }
+.sheet, .sheet viewport { background-color: #FFFFFF; }
+.soft-bar { background-color: #F3F4F6; }
+
+/* Header bars: flat, the window buttons small glyphs (the Mac's quiet chrome, not Yaru's discs). */
+headerbar.cicada { background-image: none; background-color: #FFFFFF; border: none; box-shadow: none; min-height: 44px; padding: 0 6px; }
+headerbar.cicada.ground-bar { background-color: #F3F4F6; }
+headerbar.cicada .title { font-weight: 700; font-size: 13px; color: #15171C; }
+headerbar.cicada button.titlebutton { background-image: none; background-color: transparent; border: none; box-shadow: none; min-width: 26px; min-height: 26px; padding: 0; margin: 0 1px; border-radius: 6px; color: #6B7080; -gtk-icon-shadow: none; }
+headerbar.cicada button.titlebutton:hover { background-color: rgba(21,23,28,0.07); color: #15171C; }
+headerbar.cicada button.titlebutton image { -gtk-icon-transform: scale(0.8); }
+headerbar.cicada separator { background: none; min-width: 4px; }
+headerbar.records-bar { padding-left: 0; }
+.sidebar-top { background-color: #F3F4F6; border-right: 1px solid #E4E6EA; margin: 0; }
+
+.ink { color: #15171C; }
+.body { color: #3D4149; }
+.secondary { color: #5A5F6B; }
+.tertiary { color: #6B7080; }
+.accent { color: #E8552B; }
+.link { color: #B33A14; }
+.warn { color: #B23A12; }
+.ok { color: #1F6B3A; }
+.heading { font-weight: 700; color: #15171C; }
+.mono { font-family: "Ubuntu Sans Mono", monospace; }
+
+/* Buttons: 28 px, 12 px text, 7 px corners, as on the Mac. */
+button { min-height: 22px; font-size: 12px; -gtk-icon-shadow: none; text-shadow: none; }
+button.pill { border-radius: 14px; padding: 3px 12px; }
+button.accentbtn { background-image: none; background-color: #E8552B; color: #FFFFFF; border: none; box-shadow: none; font-weight: 500; }
+button.accentbtn:hover { background-color: #D44A22; }
+button.accentbtn image, button.darkbtn image { color: #FFFFFF; }
+button.darkbtn { background-image: none; background-color: #15171C; color: #FFFFFF; border: none; box-shadow: none; border-radius: 7px; padding: 4px 14px; }
+button.darkbtn:hover { background-color: #2A2D34; }
+button.darkbtn.pill { border-radius: 14px; }
+button.livepill { background-image: none; background-color: #FDEEE8; color: #B33A14; border: none; box-shadow: none; }
+button.outline { background-image: none; background-color: #FFFFFF; border: 1px solid #E4E6EA; box-shadow: none; border-radius: 7px; padding: 3px 10px; color: #15171C; }
+button.outline:hover { background-color: #F6F7F9; }
+button.quietbtn { background-image: none; background-color: transparent; border: none; box-shadow: none; border-radius: 7px; padding: 3px 8px; color: #15171C; }
+button.quietbtn:hover { background-color: rgba(21,23,28,0.06); }
+button.dangertext { background-image: none; background-color: transparent; border: none; box-shadow: none; color: #B3261E; padding: 3px 10px; }
+button.dangertext:hover { background-color: rgba(179,38,30,0.07); }
+button.iconbtn { background-image: none; background-color: transparent; border: none; box-shadow: none; border-radius: 7px; min-width: 28px; min-height: 28px; padding: 0; color: #5A5F6B; }
+button.iconbtn:hover { background-color: rgba(21,23,28,0.07); color: #15171C; }
+button.iconbtn.stop { background-color: #FDEEE8; color: #E8552B; }
+button.iconbtn.stop image { color: #E8552B; }
+button.linkrow { background-image: none; background-color: transparent; border: none; box-shadow: none; border-radius: 0; padding: 0; }
+button.linkrow:hover { background-color: #F6F7F9; }
+
+/* The widgets the theme would draw. */
+switch { background-image: none; background-color: #D5D8DE; border: none; box-shadow: none; border-radius: 10px; min-width: 15px; min-height: 18px; font-size: 0; color: transparent; }
+switch:checked { background-color: #15171C; }
+switch slider { background-image: none; background-color: #FFFFFF; border: none; border-radius: 8px; min-width: 14px; min-height: 14px; margin: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.25); }
+switch image { color: transparent; -gtk-icon-transform: scale(0); }
+combobox button, combobox button.combo { background-image: none; background-color: #FFFFFF; border: 1px solid #E4E6EA; box-shadow: none; border-radius: 6px; min-height: 22px; padding: 1px 6px 1px 8px; color: #15171C; }
+combobox button:hover { background-color: #F6F7F9; }
+combobox arrow { -gtk-icon-source: -gtk-icontheme("pan-down-symbolic"); min-width: 12px; min-height: 12px; color: #6B7080; }
+combobox cellview, combobox button label { font-size: 12px; }
+entry { background-image: none; background-color: #FFFFFF; border: 1px solid #E4E6EA; box-shadow: none; border-radius: 7px; min-height: 26px; padding: 0 9px; font-size: 13px; color: #15171C; caret-color: #15171C; }
+entry:focus { border-color: #E8552B; box-shadow: 0 0 0 2px rgba(232,85,43,0.18); }
+entry.search { background-color: #E8EAEE; border-color: transparent; min-height: 28px; font-size: 12px; }
+entry.search:focus { background-color: #FFFFFF; }
+entry selection, label selection { background-color: rgba(232,85,43,0.22); color: #15171C; }
+popover, popover.background { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 10px; box-shadow: 0 8px 24px rgba(21,23,28,0.14); padding: 0; }
+menu, .menu, .context-menu { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 8px; padding: 4px; }
+menu menuitem, .menu menuitem { font-size: 13px; padding: 4px 10px; border-radius: 5px; min-height: 22px; color: #15171C; }
+menu menuitem:hover, .menu menuitem:hover { background-color: #F2F3F5; color: #15171C; }
+menu menuitem:disabled label { color: #6B7080; font-size: 11px; }
+scrollbar { background-color: transparent; border: none; }
+scrollbar slider { background-color: rgba(21,23,28,0.22); border: none; border-radius: 4px; min-width: 6px; min-height: 6px; }
+scrollbar slider:hover { background-color: rgba(21,23,28,0.38); }
+tooltip, tooltip.background { background-color: #15171C; border-radius: 6px; border: none; box-shadow: none; }
+tooltip label { color: #FFFFFF; font-size: 12px; }
+spinner { color: #6B7080; }
+
+.segmented { background-color: #F2F3F5; border-radius: 8px; padding: 2px; }
+.segmented button { background-image: none; background-color: transparent; border: none; box-shadow: none; border-radius: 6px; min-height: 22px; padding: 0 10px; color: #5A5F6B; font-size: 12px; }
+.segmented.big { border-radius: 10px; padding: 3px; }
+.segmented.big button { min-height: 28px; border-radius: 8px; font-size: 13px; }
+.segmented button:checked label { font-weight: 700; color: #15171C; }
+.panel.dark .segmented { background-color: #2A2C32; }
+.panel.dark .segmented button:checked { background-color: #3A3D45; }
+.panel.dark .segmented button:checked label { color: #F2F3F5; }
+.segmented button:checked { background-color: #FFFFFF; color: #15171C; box-shadow: 0 1px 2px rgba(0,0,0,0.10); font-weight: 500; }
+
+.endingstrip { background-color: #FDEEE8; border-radius: 12px; }
+.notice { background-color: #F2F3F5; border-radius: 12px; }
+dialog.endask { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 12px; }
+.notice.error { background-color: #FDECEA; }
+.panel.dark .endingstrip { background-color: rgba(232,85,43,0.16); }
+entry.notes-search { min-height: 32px; font-size: 13px; border-radius: 9px; }
+.panel.dark entry.notes-search { background-color: #2A2C32; color: #F2F3F5; }
+button.iconbtn.on { background-color: #F3F4F6; color: #15171C; }
+.panel.dark button.iconbtn.on { background-color: #34363D; }
+.wide > scrolledwindow:first-child { border-right: 1px solid #EEF0F3; }
+.boxed { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 12px; }
+.prow-top { border-top: 1px solid #EEF0F3; }
+.warnrow { background-color: #FFF8F3; border-radius: 0 0 12px 12px; }
+.warnrow label { color: #5A2A16; }
+.group-title { font-weight: 700; color: #6B7080; }
+
+.chip { background-color: #F2F3F5; border-radius: 5px; padding: 1px 6px; color: #15171C; }
+.chip.now { background-color: #E8552B; color: #FFFFFF; }
+.chip.time { background-color: transparent; padding: 0; color: #B33A14; }
+.badge { background-color: #FDEEE8; border-radius: 5px; padding: 0 6px; color: #B33A14; }
+.softcard { background-color: #F5F6F8; border-radius: 12px; }
+.summarycard { background-color: #F5F6F8; border-radius: 12px; }
+.icon-tile { background-color: #FDEEE8; border-radius: 16px; }
+.icon-tile image { color: #E8552B; }
+.icon-tile.grey { background-color: #F3F4F6; }
+.icon-tile.grey image { color: #5A5F6B; }
+.icon-tile.warn { background-color: #FDEEE8; }
+.icon-tile.warn image { color: #B23A12; }
+.wavebar { background-color: #C9CCD3; border-radius: 3px; }
+.wavebar.on { background-color: #E8552B; }
+.dotstep { background-color: #C9CCD3; border-radius: 3px; min-width: 6px; min-height: 6px; }
+.dotstep.on { background-color: #E8552B; min-width: 18px; }
+.livedot { background-color: #E8552B; border-radius: 4px; min-width: 7px; min-height: 7px; box-shadow: 0 0 0 3px rgba(232,85,43,0.18); }
+/* "Live" without blinking (BreathingDot / BreathingMark): a ring swells out and fades. GTK has no
+ transforms, so the ring is a growing box-shadow; GNOME's Reduce Animation turns CSS animations off. */
+@keyframes breathe-dot { from { box-shadow: 0 0 0 0 rgba(232,85,43,0.6); } to { box-shadow: 0 0 0 6px rgba(232,85,43,0); } }
+/* BreathingMark scales a logo-sized rounded square 1 -> 1.7 behind the 22 px logo: what shows is a band
+ growing to 7.7 px, which is what a spread shadow from the logo's own rounded edge draws. */
+@keyframes breathe-mark { from { box-shadow: 0 0 0 0 rgba(232,85,43,0.55); } to { box-shadow: 0 0 0 8px rgba(232,85,43,0); } }
+/* BreathingDot (6 px, ring 1 -> 2.6): a 4.8 px band. */
+@keyframes breathe-dot6 { from { box-shadow: 0 0 0 0 rgba(232,85,43,0.6); } to { box-shadow: 0 0 0 5px rgba(232,85,43,0); } }
+.livedot.small { min-width: 6px; min-height: 6px; border-radius: 3px; box-shadow: none; }
+.livedot.small.breathing { animation: breathe-dot6 2s ease-out infinite; }
+.livedot.breathing { animation: breathe-dot 2s ease-out infinite; }
+.breathemark { border-radius: 6px; animation: breathe-mark 2.2s ease-out infinite; }
+.breathemark.late { animation-delay: 1.1s; }
+.idledot { background-color: #C9CCD3; border-radius: 4px; min-width: 7px; min-height: 7px; }
+
+.sidebar { background-color: #F3F4F6; border-right: 1px solid #E4E6EA; }
+.sidebar list, .sidebar viewport { background-color: #F3F4F6; }
+.sidebar list row { border-radius: 8px; margin: 0 10px; padding: 0; }
+.sidebar list row:selected, .sidebar list row:selected:hover { background-color: #E3E5EA; }
+.sidebar list row:selected label { color: #15171C; }
+.sidebar list row:hover { background-color: #ECEEF1; }
+.group-label { font-weight: 700; color: #6B7080; }
+.transcript-row { border-top: 1px solid #EEF0F3; }
+.spk1 { color: #0F7B6C; } .spk2 { color: #7A4CC2; } .spk3 { color: #B03A7A; } .spk4 { color: #8A5A00; }
+button.spkchip { background-image: none; background-color: #F2F3F5; border: none; box-shadow: none; border-radius: 11px; padding: 0 9px; min-height: 22px; }
+button.spkchip:hover { background-color: #E8EAEE; }
+button.spklabel { background-image: none; background-color: transparent; border: none; box-shadow: none; padding: 0 4px 0 0; min-height: 0; }
+button.spklabel:hover { background-color: #F3F4F6; }
+button.pick { background-image: none; background-color: #FFFFFF; border: 1px solid #E4E6EA; box-shadow: none; border-radius: 7px; padding: 1px 9px; min-height: 24px; }
+button.pick.chosen { background-color: #15171C; color: #FFFFFF; border-color: #15171C; }
+button.underline label { text-decoration-line: underline; }
+
+/* The listening capsule in the records window's header (ListenPill.swift). */
+button.listenpill { background-image: none; background-color: #FFFFFF; border: 1px solid #E4E6EA; box-shadow: none; border-radius: 16px; min-height: 30px; padding: 0 12px 0 6px; }
+button.listenpill:hover { background-color: #F8F9FA; }
+.listenpill.live { background-color: #15171C; border-radius: 16px; padding: 4px 4px 4px 5px; min-height: 24px; }
+/* monospacedDigit: the clock and the countdown don't shift every second. */
+.listenpill.live.ending { padding-left: 4px; }
+label.tnum { font-feature-settings: "tnum"; }
+/* In the header bar Yaru pads every button to 36 px; the capsule's are the Mac's 24. */
+headerbar .listenpill.live button.pillshow, headerbar .listenpill.live button.pillend, headerbar .listenpill.live button.pillkeep {
+ min-height: 24px; margin: 0; padding-top: 0; padding-bottom: 0; border: none; }
+headerbar .listenpill.live button.pillshow { padding: 0; }
+.listenpill.live label { color: #FFFFFF; }
+button.pillshow { background-image: none; background-color: transparent; border: none; box-shadow: none; padding: 0; min-height: 24px; }
+button.pillend { background-image: none; background-color: #2F323A; color: #FFFFFF; border: none; box-shadow: none; border-radius: 12px; min-height: 24px; padding: 0 12px; font-weight: 700; }
+button.pillend:hover { background-color: #3A3D46; }
+button.pillend label { color: #FFFFFF; }
+button.pillkeep { background-image: none; background-color: #FFFFFF; color: #15171C; border: none; box-shadow: none; border-radius: 12px; min-height: 24px; padding: 0 12px; font-weight: 700; }
+button.pillkeep:hover { background-color: #ECEEF1; }
+button.pillkeep label { color: #15171C; }
+.listenpill.live button.pillkeep label { color: #15171C; }
+.listenpill.live label.countdown { color: #F4A58C; }
+.listenpill.live label.dim { color: #BDC0C7; }
+.pillsep { background-color: #E4E6EA; min-width: 1px; min-height: 14px; }
+.meterbar { background-color: #E8552B; border-radius: 2px; }
+.toast { background-color: #15171C; border-radius: 10px; padding: 2px 4px 2px 14px; box-shadow: 0 6px 18px rgba(0,0,0,0.22); }
+.toast label { color: #F2F3F5; }
+.toast button { background-image: none; background-color: rgba(255,255,255,0.12); color: #FFFFFF; border: none; box-shadow: none; border-radius: 6px; padding: 1px 10px; }
+.toast button label { color: #FFFFFF; }
+
+.notes-window { background-color: transparent; }
+.panel .speakbox { background-color: #FDEEE8; border-radius: 12px; }
+.panel.dark .speakbox { background-color: rgba(232,85,43,0.14); }
+.panel { background-color: #FFFFFF; border-radius: 14px; border: 1px solid #E4E6EA; }
+/* The live caption: a dark card at the bottom of the notes window, as on the Mac. */
+.panel .livebox { background-color: #15171C; border-radius: 14px; }
+.panel .livebox .ink, .panel .livebox .heading { color: #FFFFFF; }
+.panel .livebox .secondary, .panel .livebox .tertiary { color: #BDC0C7; }
+.panel .livebox .accent { color: #F08A6C; }
+.panel .livebox .spk1 { color: #5CC8B5; } .panel .livebox .spk2 { color: #B79BF0; }
+.panel .livebox .spk3 { color: #F08FBF; } .panel .livebox .spk4 { color: #E3B45C; }
+.panel .livebox .icon-tile.grey { background-color: #2A2C32; }
+.panel .livebox .icon-tile.grey image, .panel .livebox .icon-tile.warn image { color: #BDC0C7; }
+.panel .livebox .icon-tile.warn { background-color: rgba(232,85,43,0.22); }
+.panel .livebox button.outline { background-color: #2A2C32; border-color: #3A3C43; color: #F2F3F5; }
+.panel .livebox.light { background-color: #F3F4F6; }
+.panel .livebox.light .ink, .panel .livebox.light .heading { color: #15171C; }
+.panel .livebox.light .secondary, .panel .livebox.light .tertiary { color: #5A5F6B; }
+.panel .livebox.light .icon-tile.grey { background-color: #FFFFFF; }
+.panel .livebox.light .icon-tile.grey image { color: #5A5F6B; }
+.panel .livebox.light .icon-tile.warn image { color: #B23A12; }
+.panel .livebox.light button.outline { background-color: #FFFFFF; border-color: #E4E6EA; color: #15171C; }
+.panel .footer { border-top: none; }
+.panel.dark .livebox.light { background-color: #2A2C32; }
+.panel.dark .livebox.light .ink, .panel.dark .livebox.light .heading { color: #F2F3F5; }
+.panel.dark .livebox.light .secondary, .panel.dark .livebox.light .tertiary { color: #A3A7B1; }
+.panel.dark .livebox.light .icon-tile.grey { background-color: #34363D; }
+.panel.dark .livebox.light .icon-tile.grey image { color: #A3A7B1; }
+.panel.dark .livebox.light button.outline { background-color: #34363D; border-color: #3A3C43; color: #F2F3F5; }
+.panel.dark { background-color: #1F2025; border-color: #34363D; }
+.panel.dark .livebox { background-color: #2E3037; }
+.panel.dark .ink, .panel.dark .heading, .panel.dark button.iconbtn, .panel.dark button.iconbtn image { color: #F2F3F5; }
+.panel.dark .body { color: #D4D6DB; }
+.panel.dark .secondary, .panel.dark .tertiary { color: #A3A7B1; }
+.panel.dark .chip { background-color: #34363D; color: #F2F3F5; }
+.panel.dark .chip.now { background-color: #E8552B; }
+.panel.dark .chip.time { background-color: transparent; color: #F08A6C; }
+.panel.dark .link { color: #F08A6C; }
+.panel.dark .badge { background-color: rgba(232,85,43,0.18); color: #F08A6C; }
+.panel.dark button.iconbtn:hover { background-color: rgba(255,255,255,0.08); }
+.panel.dark button.iconbtn.stop { background-color: rgba(232,85,43,0.18); }
+.panel.dark button.iconbtn.stop image { color: #E8552B; }
+.panel.dark .icon-tile.grey { background-color: #34363D; }
+.panel.dark .icon-tile.grey image { color: #A3A7B1; }
+.panel.dark .icon-tile.warn { background-color: rgba(232,85,43,0.16); }
+.panel.dark button.outline { background-color: #2A2C32; border-color: #3A3C43; color: #F2F3F5; }
+
+levelbar trough { min-height: 6px; padding: 0; border: none; background-color: #ECEEF1; border-radius: 3px; }
+levelbar block { min-height: 6px; border: none; border-radius: 3px; }
+levelbar block.filled, levelbar block.low, levelbar block.high, levelbar block.full { background-color: #E8552B; }
+levelbar block.empty { background-color: transparent; }
+entry.keyentry { border-radius: 10px; min-height: 34px; }
+
+/* Onboarding (Onboarding.swift): 860 x 640 on the ground, white 18 px cards, a 44 px ink button. */
+.stepbar { background-color: #DDDEE2; border-radius: 2px; min-height: 4px; }
+.stepbar.on { background-color: #15171C; }
+.bigcard { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 18px; }
+.midcard { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 12px; }
+.tipcard { background-color: #FFFFFF; border-radius: 14px; }
+.hair { background-color: #E4E6EA; min-height: 1px; }
+.stepnum { background-color: #15171C; border-radius: 12px; min-width: 24px; min-height: 24px; }
+.stepnum label { color: #FFFFFF; }
+button.bigbtn { background-image: none; background-color: #15171C; color: #FFFFFF; border: none; box-shadow: none; border-radius: 12px; min-height: 44px; padding: 0 28px; font-size: 14px; font-weight: 700; }
+button.bigbtn:hover { background-color: #2A2D34; }
+button.bigbtn label, button.bigbtn image { color: #FFFFFF; }
+button.bigbtn.waiting { background-color: #DDDEE2; }
+button.bigbtn.waiting label, button.bigbtn.waiting image { color: #5A5F6B; }
+button.bigquiet { font-size: 13px; color: #5A5F6B; }
+button.bigquiet label { color: #5A5F6B; }
+button.midbtn { min-height: 36px; border-radius: 10px; padding: 0 16px; font-size: 13px; font-weight: 700; }
+button.outline.midbtn { border-color: #D6D6D6; }
+.samplestage { background-color: #23262D; border-radius: 18px; }
+.stage-dim { color: #BDC0C7; }
+.stage-ink { color: #FFFFFF; }
+button.bigplay { min-height: 36px; border-radius: 18px; padding: 0 18px; font-size: 13px; }
+button.bigplay image { color: #15171C; }
+button.choicecard { background-image: none; background-color: #FFFFFF; border: 1px solid #E4E6EA; box-shadow: none; border-radius: 16px; padding: 0; }
+button.choicecard:hover { border-color: #15171C; }
+.keycap { background-color: #FFFFFF; border: 1px solid #D6D6D6; border-bottom-width: 4px; border-radius: 10px; }
+.topbar { background-color: #1D1E22; border-radius: 17px 17px 0 0; }
+.topbar-ink { color: #E9EAEE; }
+.topbar-pill { background-color: #34363C; border-radius: 10px; }
+.topbar-ring { background-color: rgba(232,85,43,0.22); border: 1.5px solid #E8552B; border-radius: 7px; }
+"""
+
+
+def install_css() -> None:
+ provider = Gtk.CssProvider()
+ provider.load_from_data(CSS)
+ Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
+
+
+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):
+ s = Gio.Settings.new("org.gnome.desktop.interface")
+ if "color-scheme" in s.list_keys() and s.get_string("color-scheme") == "prefer-dark":
+ return True
+ except GLib.Error:
+ pass
+ theme = Gtk.Settings.get_default().get_property("gtk-theme-name") or ""
+ return theme.lower().endswith("-dark")
+
+
+def classes(widget, *names):
+ ctx = widget.get_style_context()
+ for n in names:
+ for one in (n or "").split():
+ ctx.add_class(one)
+ 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"
+
+
+def pango_lang(code: str | None) -> str:
+ c = (code or "").lower()
+ if c.startswith("zh"):
+ return "zh-tw" if ("tw" in c or "hant" in c or "hk" in c) else "zh-cn"
+ return c.split("-")[0] or DEFAULT_LANG
+
+
+def text(s: str, size: int = 13, cls: str = "ink", bold: bool = False, wrap: bool = True, selectable: bool = False,
+ ellipsize: bool = True, width_chars: int = 40, lang: str | None = None) -> Gtk.Label:
+ l = Gtk.Label()
+ l.set_xalign(0)
+ l.cicada_format = (size, pango_lang(lang) if lang else DEFAULT_LANG, bold)
+ retext(l, s)
+ classes(l, cls)
+ if 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)
+ l.set_selectable(selectable)
+ return l
+
+
+def 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) -> Gtk.Label:
+ """text() with every search term highlighted in place (the current match in the accent)."""
+ l = text(s, size, cls, lang=lang)
+ low = s.lower()
+ spans = []
+ for t in terms:
+ t = t.lower()
+ i = low.find(t) if t else -1
+ while i >= 0:
+ spans.append((i, i + len(t)))
+ i = low.find(t, i + len(t))
+ if not spans:
+ return l
+ spans.sort()
+ merged = []
+ for a, b in spans:
+ if merged and a <= merged[-1][1]:
+ merged[-1] = (merged[-1][0], max(b, merged[-1][1]))
+ else:
+ merged.append((a, b))
+ mark = ' background="#E8552B" foreground="#FFFFFF"' if current else ' background="#FBE0D5"'
+ out, at = [], 0
+ for a, b in merged:
+ out.append(esc(s[at:a]))
+ out.append("<span%s>%s</span>" % (mark, esc(s[a:b])))
+ at = b
+ out.append(esc(s[at:]))
+ size_, lang_, bold = l.cicada_format
+ l.set_markup('<span size="%d" lang="%s"%s>%s</span>' % (round(size_ * 768), lang_, ' weight="bold"' if bold else "", "".join(out)))
+ return l
+
+
+def helper(s: str) -> Gtk.Label:
+ return text(s, 11, "tertiary")
+
+
+def heading(s: str, size: int = 16) -> Gtk.Label:
+ return text(s, size, "heading", bold=True)
+
+
+def esc(s: str) -> str:
+ return GLib.markup_escape_text(s)
+
+
+def icon(name: str, px: int = 16) -> Gtk.Image:
+ img = Gtk.Image.new_from_icon_name(name, Gtk.IconSize.BUTTON)
+ img.set_pixel_size(px)
+ return img
+
+
+def button(label: str, on_click, style: str = "outline", icon_name: str | None = None) -> Gtk.Button:
+ b = Gtk.Button()
+ if icon_name:
+ box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
+ box.pack_start(icon(icon_name, 16), False, False, 0)
+ box.pack_start(Gtk.Label(label=label), False, False, 0)
+ box.set_halign(Gtk.Align.CENTER)
+ b.add(box)
+ else:
+ b.set_label(label)
+ for s in style.split():
+ classes(b, s)
+ b.connect("clicked", lambda *_: on_click())
+ return b
+
+
+def icon_button(icon_name: str, tooltip: str, on_click, extra: str = "", px: int = 15, focus: bool = True) -> Gtk.Button:
+ b = Gtk.Button()
+ b.add(icon(icon_name, px))
+ b.set_tooltip_text(tooltip)
+ b.get_accessible().set_name(tooltip)
+ classes(b, "iconbtn", extra)
+ b.set_can_focus(focus)
+ b.connect("clicked", lambda *_: on_click())
+ return b
+
+
+def 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)
+ b.connect("clicked", lambda *_: on_click())
+ return b
+
+
+def dot(live: bool) -> Gtk.Widget:
+ d = Gtk.Box()
+ d.set_size_request(9, 9)
+ d.set_valign(Gtk.Align.CENTER)
+ classes(d, "livedot" if live else "idledot")
+ return d
+
+
+def vbox(spacing: int = 0, *children) -> Gtk.Box:
+ b = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=spacing)
+ for c in children:
+ b.pack_start(c, False, False, 0)
+ return b
+
+
+def hbox(spacing: int = 0, *children) -> Gtk.Box:
+ b = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=spacing)
+ for c in children:
+ b.pack_start(c, False, False, 0)
+ return b
+
+
+def pad(widget, top: int, right: int | None = None, bottom: int | None = None, left: int | None = None):
+ right = top if right is None else right
+ bottom = top if bottom is None else bottom
+ left = right if left is None else left
+ widget.set_margin_top(top)
+ widget.set_margin_end(right)
+ widget.set_margin_bottom(bottom)
+ widget.set_margin_start(left)
+ return widget
+
+
+def gap(widget, top: int):
+ widget.set_margin_top(top)
+ return widget
+
+
+def clear(box: Gtk.Container) -> None:
+ for c in box.get_children():
+ box.remove(c)
+ c.destroy()
+
+
+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)
+ return e
+
+
+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 = {}
+ lock = {"busy": False}
+
+ def toggled(btn, value):
+ if lock["busy"]:
+ return
+ lock["busy"] = True
+ for v, b in buttons.items():
+ b.set_active(v == value)
+ lock["busy"] = False
+ on_change(value)
+ for value, label in options:
+ b = Gtk.ToggleButton(label=label)
+ b.set_active(value == current)
+ b.connect("toggled", toggled, value)
+ buttons[value] = b
+ box.pack_start(b, False, False, 0)
+ return 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:
+ classes(r, "prow-top")
+ box.pack_start(r, False, False, 0)
+ return panel(box, "boxed")
+
+
+def prow(title: str, control: Gtk.Widget | None = None, subtitle: str | None = None, title_widget=None) -> Gtk.Widget:
+ """One preferences row: title (and a grey subtitle) on the left, its control on the right."""
+ row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
+ left = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=1)
+ left.set_valign(Gtk.Align.CENTER)
+ left.pack_start(title_widget or text(title, 13, "ink", wrap=False, ellipsize=False), False, False, 0)
+ if subtitle:
+ left.pack_start(text(subtitle, 11, "tertiary", width_chars=50), False, False, 0)
+ row.pack_start(left, True, True, 0)
+ if control is not None:
+ control.set_valign(Gtk.Align.CENTER)
+ row.pack_end(control, False, False, 0)
+ return panel(pad(row, 10, 14), "prow")
+
+
+def icon_tile(icon_name: str, size: int = 64, glyph: int = 30, tone: str = "") -> Gtk.Widget:
+ img = icon(icon_name, glyph)
+ img.set_halign(Gtk.Align.CENTER)
+ img.set_valign(Gtk.Align.CENTER)
+ t = panel(img, "icon-tile", tone)
+ t.set_size_request(size, size)
+ t.set_halign(Gtk.Align.CENTER)
+ t.set_valign(Gtk.Align.CENTER)
+ return t
+
+
+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)
+ classes(d, "small")
+ classes(d, "breathing")
+ return d
+
+
+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 GdkPixbuf
+ r = 11.75
+ c = 2 * math.pi * r
+ f = max(0.0, min(1.0, fraction))
+ svg = ('<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 26 26">'
+ '<circle cx="13" cy="13" r="%.2f" fill="none" stroke="%s" stroke-width="2.5"/>'
+ '<circle cx="13" cy="13" r="%.2f" fill="none" stroke="%s" stroke-width="2.5" stroke-linecap="round"'
+ ' stroke-dasharray="%.2f %.2f" transform="rotate(-90 13 13)"%s/></svg>'
+ % (px, px, r, track, r, color, c * f, c, "" if f > 0 else ' stroke-opacity="0"'))
+ loader = GdkPixbuf.PixbufLoader.new_with_type("svg")
+ loader.write(svg.encode())
+ loader.close()
+ return loader.get_pixbuf()
+
+
+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
+ c = panel(l, "chip", "now" if now else "time")
+ c.set_valign(Gtk.Align.BASELINE)
+ return c
+
+
+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)
+ self.revealer.set_halign(Gtk.Align.CENTER)
+ self.revealer.set_valign(Gtk.Align.END)
+ self.revealer.set_margin_bottom(24)
+ overlay.add_overlay(self.revealer)
+ self._timer = None
+ self._expire = None
+
+ def show(self, message: str, action: str | None = None, on_action=None, on_timeout=None, seconds: int = 5) -> None:
+ self.dismiss(run_timeout=True)
+ row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=14)
+ row.pack_start(text(message, 13, "", wrap=False), False, False, 0)
+ if action:
+ def act(*_):
+ self._expire = None
+ self.dismiss(run_timeout=False)
+ if on_action:
+ on_action()
+ b = Gtk.Button(label=action)
+ b.connect("clicked", act)
+ row.pack_start(b, False, False, 0)
+ box = panel(pad(row, 5, 5, 5, 14), "toast")
+ for c in self.revealer.get_children():
+ self.revealer.remove(c)
+ self.revealer.add(box)
+ box.show_all()
+ self.revealer.set_reveal_child(True)
+ self._expire = on_timeout
+ self._timer = GLib.timeout_add_seconds(seconds, self._timed_out)
+
+ def _timed_out(self):
+ self._timer = None
+ self.dismiss(run_timeout=True)
+ return False
+
+ def dismiss(self, run_timeout: bool = True) -> None:
+ if self._timer is not None:
+ GLib.source_remove(self._timer)
+ self._timer = None
+ expire, self._expire = self._expire, None
+ self.revealer.set_reveal_child(False)
+ if run_timeout and expire:
+ expire()
+
+
+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()
+ if not ok:
+ dy = {Gdk.ScrollDirection.UP: -1, Gdk.ScrollDirection.DOWN: 1}.get(event.direction, 0)
+ adj.set_value(adj.get_value() + dy * 60)
+ return True
+ combo.connect("scroll-event", wheel)
diff --git a/linux/cicada/app/x11.py b/linux/cicada/app/x11.py
new file mode 100644
index 0000000..e9cd58e
--- /dev/null
+++ b/linux/cicada/app/x11.py
@@ -0,0 +1,55 @@
+"""The one X11 detail 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."""
+from __future__ import annotations
+
+import ctypes
+import ctypes.util
+
+from ..core.support import Log
+
+_x = None
+
+
+def _lib():
+ global _x
+ if _x is None:
+ x = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6")
+ x.XOpenDisplay.restype = ctypes.c_void_p
+ x.XOpenDisplay.argtypes = [ctypes.c_char_p]
+ x.XInternAtom.restype = ctypes.c_ulong
+ x.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]
+ x.XSetWMProtocols.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong), ctypes.c_int]
+ x.XFlush.argtypes = [ctypes.c_void_p]
+ x.XCloseDisplay.argtypes = [ctypes.c_void_p]
+ _x = x
+ return _x
+
+
+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)
+
+
+def _protocols(gdk_window, focus: bool) -> None:
+ xid = gdk_window.get_xid() if hasattr(gdk_window, "get_xid") else None
+ if not xid:
+ return
+ try:
+ x = _lib()
+ d = x.XOpenDisplay(None)
+ if not d:
+ return
+ names = [b"WM_DELETE_WINDOW"] + ([b"WM_TAKE_FOCUS"] if focus else [])
+ atoms = (ctypes.c_ulong * len(names))(*[x.XInternAtom(d, n, 0) for n in names])
+ x.XSetWMProtocols(d, xid, atoms, len(names))
+ x.XFlush(d)
+ x.XCloseDisplay(d)
+ except OSError as e:
+ Log.d("x11: protocols not set (%s)" % e)
diff --git a/linux/cicada/core/__init__.py b/linux/cicada/core/__init__.py
new file mode 100644
index 0000000..1b42523
--- /dev/null
+++ b/linux/cicada/core/__init__.py
@@ -0,0 +1,2 @@
+"""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."""
diff --git a/linux/cicada/core/audio.py b/linux/cicada/core/audio.py
new file mode 100644
index 0000000..56467e2
--- /dev/null
+++ b/linux/cicada/core/audio.py
@@ -0,0 +1,142 @@
+"""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 annotations
+
+import math
+import struct
+import sys
+import threading
+import time
+from array import array
+
+RATE = 16000
+
+
+class 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 = None
+ on_ended = None
+
+ def start(self) -> None:
+ raise NotImplementedError
+
+ def stop(self) -> None:
+ raise NotImplementedError
+
+
+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
+ self._stopped = False
+
+ def start(self) -> None:
+ self._stopped = False
+ threading.Thread(target=self._run, name="PcmAudioSource", daemon=True).start()
+
+ def _run(self) -> None:
+ try:
+ pcm = self._load()
+ except Exception as e: # noqa: BLE001 - any unreadable file ends the source
+ from .support import Log
+ Log.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
+ started = time.monotonic()
+ i = 0
+ while i < len(pcm) and not self._stopped:
+ if self.on_samples:
+ self.on_samples(pcm[i:i + chunk])
+ if self.speed > 0:
+ wait = started + (i + chunk) / RATE / self.speed - time.monotonic()
+ 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:
+ self.on_ended(None)
+
+ def stop(self) -> None:
+ self._stopped = True
+
+
+def _le(a: array) -> array:
+ if sys.byteorder != "little":
+ a = array("h", a)
+ a.byteswap()
+ return a
+
+
+class Wav:
+ @staticmethod
+ def bytes(pcm: array, rate: int = RATE) -> bytes:
+ data = _le(pcm).tobytes()
+ return (b"RIFF" + struct.pack("<I", 36 + len(data)) + b"WAVEfmt " +
+ struct.pack("<IHHIIHH", 16, 1, 1, rate, rate * 2, 2, 16) + b"data" + struct.pack("<I", len(data)) + data)
+
+ @staticmethod
+ def read_file(path: str) -> array:
+ with open(path, "rb") as f:
+ return Wav.read(f.read())
+
+ @staticmethod
+ def 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
+ channels, rate = 1, RATE
+ while pos + 8 <= len(data):
+ cid = data[pos:pos + 4]
+ size = struct.unpack("<I", data[pos + 4:pos + 8])[0]
+ body = pos + 8
+ if cid == b"fmt ":
+ fmt, channels, rate = struct.unpack("<HHI", data[body:body + 8])
+ bits = struct.unpack("<H", data[body + 14:body + 16])[0]
+ if fmt not in (1, 0xFFFE) or bits != 16:
+ raise ValueError("only 16-bit PCM WAV")
+ elif cid == b"data":
+ raw = data[body:body + min(size, len(data) - body)]
+ raw = raw[:len(raw) // (2 * channels) * 2 * channels]
+ s = array("h")
+ s.frombytes(raw)
+ s = _le(s)
+ if channels == 1 and rate == RATE:
+ return s
+ if channels == 1:
+ mono = s
+ else:
+ mono = array("d", (sum(s[f * channels:(f + 1) * channels]) / channels for f in range(len(s) // channels)))
+ return Wav.resample(mono, rate)
+ pos = body + size + (size & 1)
+ raise ValueError("no data chunk")
+
+ @staticmethod
+ def 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:
+ return array("h", (clamp(x) for x in mono))
+ window = max(1, rate // RATE)
+ count = len(mono) * RATE // rate
+ out = array("h", bytes(count * 2))
+ for i in range(count):
+ start = i * rate // RATE
+ stop = min(len(mono), start + window)
+ out[i] = clamp(sum(mono[start:stop]) / max(1, stop - start))
+ return out
+
+ @staticmethod
+ def rms(buf) -> float:
+ if not len(buf):
+ return 0.0
+ return math.sqrt(sum(x * x for x in buf) / len(buf)) / 32768
diff --git a/linux/cicada/core/jsonfmt.py b/linux/cicada/core/jsonfmt.py
new file mode 100644
index 0000000..159d181
--- /dev/null
+++ b/linux/cicada/core/jsonfmt.py
@@ -0,0 +1,137 @@
+"""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 annotations
+
+import json
+from decimal import Decimal
+
+
+def parse(text: str):
+ return json.loads(text)
+
+
+def parse_object(text: str) -> dict | None:
+ try:
+ v = json.loads(text)
+ except (ValueError, TypeError):
+ return None
+ return v if isinstance(v, dict) else 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:
+ return str(int(d))
+ s = repr(d)
+ if "e" in s or "E" in s:
+ s = format(Decimal(s).normalize(), "f")
+ return s
+
+
+def write(value, pretty: bool = True) -> str:
+ out: list[str] = []
+ _emit(out, value, pretty, 0)
+ return "".join(out)
+
+
+def _emit(out: list[str], v, pretty: bool, depth: int) -> None:
+ if v is None:
+ out.append("null")
+ elif isinstance(v, bool):
+ out.append("true" if v else "false")
+ elif isinstance(v, int):
+ out.append(str(v))
+ elif isinstance(v, float):
+ out.append(number(v))
+ 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 "{}")
+ return
+ out.append("{")
+ for n, (k, x) in enumerate(items):
+ if n:
+ out.append(",")
+ if pretty:
+ out.append("\n" + " " * (depth + 1))
+ _quote(out, k)
+ out.append(" : " if pretty else ":")
+ _emit(out, x, pretty, depth + 1)
+ if pretty:
+ out.append("\n" + " " * depth)
+ out.append("}")
+ elif isinstance(v, (list, tuple)):
+ if not v:
+ out.append("[\n\n" + " " * depth + "]" if pretty else "[]")
+ return
+ out.append("[")
+ for n, x in enumerate(v):
+ if n:
+ out.append(",")
+ if pretty:
+ out.append("\n" + " " * (depth + 1))
+ _emit(out, x, pretty, depth + 1)
+ if pretty:
+ out.append("\n" + " " * depth)
+ out.append("]")
+ else:
+ _quote(out, str(v))
+
+
+_ESC = {'"': '\\"', "\\": "\\\\", "/": "\\/", "\n": "\\n", "\r": "\\r", "\t": "\\t", "\b": "\\b", "\f": "\\f"}
+
+
+def _quote(out: list[str], s: str) -> None:
+ out.append('"')
+ for c in s:
+ e = _ESC.get(c)
+ if e is not None:
+ out.append(e)
+ elif c < " ":
+ out.append("\\u%04x" % ord(c))
+ else:
+ out.append(c)
+ out.append('"')
+
+
+# Lenient accessors for decoded JSON.
+
+def obj(v) -> dict | None:
+ return v if isinstance(v, dict) else None
+
+
+def arr(v) -> list:
+ return v if isinstance(v, list) else []
+
+
+def string(v) -> str | None:
+ return v if isinstance(v, str) else None
+
+
+def num(v) -> float | None:
+ if isinstance(v, bool):
+ return None
+ if isinstance(v, (int, float)):
+ return v
+ if isinstance(v, str):
+ try:
+ return float(v.strip())
+ except ValueError:
+ return None
+ return None
+
+
+def integer(v) -> int | None:
+ n = num(v)
+ return None if n is None else int(n)
+
+
+def boolean(v) -> bool | None:
+ return v if isinstance(v, bool) else None
diff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.py
new file mode 100644
index 0000000..3978126
--- /dev/null
+++ b/linux/cicada/core/ling.py
@@ -0,0 +1,363 @@
+"""Ling (ant-ling.com), OpenAI-compatible, and the user's key."""
+from __future__ import annotations
+
+import base64
+import os
+import random
+import socket
+import threading
+import time
+import urllib.error
+import urllib.request
+
+from . import jsonfmt
+from .jsonfmt import arr, obj, string
+from .settings import DEFAULT_MODEL
+from .support import Log, Paths
+
+
+class AIKey:
+ """The user's Ling key, only ever in the `ling-api-key` file, mode 0600, in ~/.config/cicada (as
+ on the Mac): never in settings, logs or exports."""
+
+ def __init__(self, path: str | None = None):
+ self._path = path
+ self._cached = None
+ self._loaded = False
+ self._lock = threading.Lock()
+
+ @property
+ def path(self) -> str:
+ return self._path or Paths.key_file()
+
+ def read(self) -> str | None:
+ with self._lock:
+ if self._loaded:
+ return self._cached
+ self._loaded = True
+ try:
+ if os.path.isfile(self.path):
+ with open(self.path, encoding="utf-8") as f:
+ self._cached = f.read().strip() or None
+ else:
+ self._cached = None
+ except OSError as e:
+ Log.d("ai key: read failed %s" % type(e).__name__)
+ self._cached = None
+ return self._cached
+
+ def save(self, key: str) -> bool:
+ k = key.strip()
+ with self._lock:
+ try:
+ os.makedirs(os.path.dirname(self.path), mode=0o700, exist_ok=True)
+ # Created 0600 from the start: the key is never readable by others, even briefly.
+ fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ f.write(k)
+ os.chmod(self.path, 0o600)
+ self._cached = k
+ self._loaded = True
+ return True
+ except OSError as e:
+ Log.d("ai key: save failed %s" % type(e).__name__)
+ return False
+
+ def remove(self) -> None:
+ with self._lock:
+ try:
+ os.remove(self.path)
+ except OSError:
+ pass
+ self._cached = None
+ self._loaded = True
+
+ def reload(self) -> None:
+ with self._lock:
+ self._loaded = False
+
+ @staticmethod
+ def 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, 2
+PRIORITY_NAMES = {SPEAK: "speak", TRANSLATE: "translate", NOTES: "notes"}
+
+# Key states.
+NONE, UNCHECKED, CHECKING, OK, INVALID, UNREACHABLE = "none", "unchecked", "checking", "ok", "invalid", "unreachable"
+
+
+class LingError(Exception):
+ NO_KEY, INVALID_KEY, RATE_LIMITED, HIJACKED, TIMEOUT, HTTP, NETWORK, PARSE = (
+ "NoKey", "InvalidKey", "RateLimited", "Hijacked", "Timeout", "Http", "Network", "Parse")
+
+ def __init__(self, kind: str, status: int = 0):
+ super().__init__("http%d" % status if kind == self.HTTP else kind)
+ self.kind = kind
+ self.status = status
+
+
+class Response:
+ def __init__(self, status: int, body: str):
+ self.status = status
+ self.body = body
+
+
+class StreamResponse:
+ def __init__(self, status: int, lines):
+ self.status = status
+ self.lines = lines # an iterator of text lines (SSE)
+
+
+class UrlTransport:
+ """How requests leave the app: urllib (which honours http_proxy / https_proxy), or a fake in tests.
+ Raises TimeoutError on a timeout and OSError when the network fails."""
+
+ @staticmethod
+ def 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)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ return Response(r.status, r.read().decode("utf-8", "replace"))
+ except urllib.error.HTTPError as e:
+ return Response(e.code, e.read().decode("utf-8", "replace") if e.fp else "")
+ except socket.timeout as e:
+ raise TimeoutError() from e
+ except urllib.error.URLError as e:
+ if isinstance(e.reason, socket.timeout):
+ raise TimeoutError() from e
+ raise OSError(str(e.reason)) from e
+
+
+ @staticmethod
+ def stream(url: str, body: str, headers: dict, timeout: float) -> StreamResponse:
+ """A POST whose reply is read line by line as it arrives (Ming's server-sent speech)."""
+ req = urllib.request.Request(url, data=body.encode(), method="POST", headers=headers)
+ try:
+ r = urllib.request.urlopen(req, timeout=timeout)
+ except urllib.error.HTTPError as e:
+ return StreamResponse(e.code, iter(()))
+ except socket.timeout as e:
+ raise TimeoutError() from e
+ except urllib.error.URLError as e:
+ raise OSError(str(e.reason)) from e
+
+ def lines():
+ with r:
+ for raw in r:
+ yield raw.decode("utf-8", "replace").rstrip("\r\n")
+ return StreamResponse(r.status, lines())
+
+
+BASE = "https://api.ant-ling.com/v1/"
+TTS_MODEL = "Ming-3.0-tts-0.5B"
+TTS_RATE = 24000
+AUDIO_MODEL = "Ming-3.0-audio-flash"
+# Search essays (Ling.swift), and the canned refusal some audio prompts get.
+HIJACK_PREFIXES = ("根据现有检索证据", "暂未找到足够可靠的信息", "根据检索", "作为一个人工智能语言模型")
+
+
+class LingClient:
+ """One instance for the app: the account allows about 2 requests per second across every model,
+ so request *starts* go through one gate (≥ 0.6 s apart, overlapping is fine) in priority order.
+ Two gateway quirks shape every call (see Ling.swift): thinking is always disabled, and the
+ content goes in the system message with a fixed user instruction, because a question-like user
+ message gets a search essay back; such replies are dropped. Calls block: run them off the UI thread."""
+ spacing = 0.6
+
+ def __init__(self, key: AIKey, transport=UrlTransport):
+ self.key = key
+ self.transport = transport
+ self.model = DEFAULT_MODEL
+ self.key_state = NONE if key.read() is None else UNCHECKED
+ self.rate_limited_at = None
+ self._listeners = []
+ self._gate = threading.Condition()
+ self._waiting = []
+ self._last_start = 0.0
+ self._seq = 0
+
+ def on_change(self, listener) -> None:
+ self._listeners.append(listener)
+
+ def _changed(self) -> None:
+ for l in list(self._listeners):
+ l()
+
+ @property
+ def has_key(self) -> bool:
+ return self.key.read() is not None
+
+ @property
+ def usable(self) -> bool:
+ return self.has_key and self.key_state != INVALID
+
+ def key_changed(self) -> None:
+ self.key_state = NONE if self.key.read() is None else UNCHECKED
+ self._changed()
+
+ def check(self) -> str:
+ """A tiny request that says whether the key works."""
+ self.key_state = CHECKING
+ self._changed()
+ try:
+ self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=10.0, model="Ling-3.0-tiny")
+ state = OK
+ except LingError as e:
+ state = {LingError.NO_KEY: NONE, LingError.INVALID_KEY: INVALID,
+ LingError.RATE_LIMITED: OK}.get(e.kind, UNREACHABLE) # a busy key is still a good key
+ except Exception: # noqa: BLE001
+ state = UNREACHABLE
+ self.key_state = state
+ self._changed()
+ return state
+
+ def chat(self, content: str, instruction: str, priority: int, json: bool = False, max_tokens: int = 1024,
+ timeout: float = 30.0, model: str | None = None, audio: bytes | None = None) -> str:
+ """One chat completion. `content` goes in the system message, `instruction` is the fixed user
+ message, `audio` (a WAV) goes before it for Ming. Notes retry 429s with backoff; heard audio
+ gets one retry (a lost reply loses the words); the rest fail fast so the caller can fall back."""
+ k = self.key.read()
+ if k is None:
+ raise LingError(LingError.NO_KEY)
+ if self.key_state == INVALID:
+ raise LingError(LingError.INVALID_KEY)
+ user = instruction if audio is None else [
+ {"type": "audio_url", "audio_url": {"url": "data:audio/wav;base64," + base64.b64encode(audio).decode()}},
+ {"type": "text", "text": instruction},
+ ]
+ body = {"model": model or self.model,
+ "messages": [{"role": "system", "content": content}, {"role": "user", "content": user}],
+ "max_tokens": max_tokens, "temperature": 0.2, "thinking": {"type": "disabled"}, "stream": False}
+ if json:
+ body["response_format"] = {"type": "json_object"}
+ payload = jsonfmt.write(body, pretty=False)
+ attempts = 4 if priority == NOTES else 2 if audio is not None else 1
+ delay = 1.0
+ attempt = 1
+ name = PRIORITY_NAMES[priority]
+ while True:
+ self._acquire(priority)
+ started = time.monotonic()
+ try:
+ root = self._post("chat/completions", payload, k, timeout)
+ choices = arr(root.get("choices"))
+ choice = obj(choices[0]) if choices else None
+ text = string((obj(choice.get("message")) or {}).get("content")) if choice else None
+ if text is None:
+ raise LingError(LingError.PARSE)
+ finish = string(choice.get("finish_reason"))
+ trimmed = text.strip()
+ if finish is None or trimmed.startswith(HIJACK_PREFIXES):
+ Log.d("ling: %s search-style reply dropped" % name)
+ raise LingError(LingError.HIJACKED)
+ usage = obj(root.get("usage")) or {}
+ Log.d("ling: %s ok %d ms tokens=%s/%s" % (name, (time.monotonic() - started) * 1000,
+ usage.get("prompt_tokens"), usage.get("completion_tokens")))
+ if self.rate_limited_at is not None:
+ self.rate_limited_at = None
+ self._changed()
+ return trimmed
+ except LingError as e:
+ if e.kind != LingError.RATE_LIMITED:
+ raise
+ if attempt >= attempts:
+ self.rate_limited_at = time.time()
+ self._changed()
+ raise
+ wait = delay + random.random() * 0.5
+ Log.d("ling: %s 429, retry in %.1f s" % (name, wait))
+ time.sleep(wait)
+ delay *= 2
+ attempt += 1
+
+ def speech(self, text: str, voice: str = "UK_Charlotte", language: str | None = None, timeout: float = 20.0):
+ """Ming's voice for `text`, as raw 24 kHz mono 16-bit PCM chunks while they arrive (a generator).
+ `language` is Ming's language_id, needed for Japanese, Korean, German, French and Spanish
+ (Ling.swift › speech)."""
+ k = self.key.read()
+ if k is None:
+ raise LingError(LingError.NO_KEY)
+ body = {"model": TTS_MODEL, "input": text, "response_format": "pcm", "sample_rate": TTS_RATE,
+ "stream": True, "stream_format": "sse", "voice": voice}
+ if language:
+ body["language_id"] = language
+ self._acquire(SPEAK)
+ try:
+ res = self.transport.stream(BASE + "audio/speech", jsonfmt.write(body, pretty=False), {
+ "Authorization": "Bearer " + k, "Content-Type": "application/json", "User-Agent": "Cicada-Linux/0.1",
+ }, timeout)
+ except TimeoutError:
+ raise LingError(LingError.TIMEOUT) from None
+ except OSError:
+ raise LingError(LingError.NETWORK) from None
+ if res.status in (401, 403):
+ self.key_state = INVALID
+ self._changed()
+ raise LingError(LingError.INVALID_KEY)
+ if res.status == 429:
+ raise LingError(LingError.RATE_LIMITED)
+ if res.status != 200:
+ raise LingError(LingError.HTTP, res.status)
+ for line in res.lines:
+ if not line.startswith("data:"):
+ continue
+ obj = jsonfmt.parse_object(line[5:].strip())
+ if obj is None:
+ continue
+ if obj.get("type") == "speech.audio.done":
+ break
+ audio = obj.get("audio")
+ if isinstance(audio, str) and audio:
+ yield base64.b64decode(audio)
+
+ def _post(self, path: str, payload: str, k: str, timeout: float) -> dict:
+ try:
+ res = self.transport.send(BASE + path, "POST", payload, {
+ "Authorization": "Bearer " + k, "Content-Type": "application/json", "User-Agent": "Cicada-Linux/0.1",
+ }, timeout)
+ except TimeoutError:
+ raise LingError(LingError.TIMEOUT) from None
+ except OSError as e:
+ Log.d("ling: network error %s" % type(e).__name__)
+ raise LingError(LingError.NETWORK) from None
+ if res.status in (401, 403):
+ if self.key_state != INVALID:
+ self.key_state = INVALID
+ self._changed()
+ raise LingError(LingError.INVALID_KEY)
+ if res.status == 429:
+ raise LingError(LingError.RATE_LIMITED)
+ if res.status != 200:
+ Log.d("ling: HTTP %d" % res.status)
+ raise LingError(LingError.HTTP, res.status)
+ root = jsonfmt.parse_object(res.body)
+ if root is None:
+ raise LingError(LingError.PARSE)
+ return root
+
+ # Start gate: request starts ≥ `spacing` apart, the most urgent waiting one first.
+
+ def _acquire(self, priority: int) -> None:
+ with self._gate:
+ self._seq += 1
+ me = (priority, self._seq)
+ self._waiting.append(me)
+ try:
+ while True:
+ head = min(self._waiting)
+ wait = self.spacing - (time.monotonic() - self._last_start)
+ if head == me and wait <= 0:
+ self._waiting.remove(me)
+ self._last_start = time.monotonic()
+ self._gate.notify_all()
+ return
+ self._gate.wait(wait if head == me else None)
+ except BaseException:
+ if me in self._waiting:
+ self._waiting.remove(me)
+ self._gate.notify_all()
+ raise
diff --git a/linux/cicada/core/listen.py b/linux/cicada/core/listen.py
new file mode 100644
index 0000000..ba68b42
--- /dev/null
+++ b/linux/cicada/core/listen.py
@@ -0,0 +1,331 @@
+"""Listening end to end: audio → segments → Ming (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 annotations
+
+import queue
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor, wait
+
+from . import strings
+from .audio import RATE, Wav
+from .ling import LingError
+from .models import TranscriptLine
+from .segmenter import Segmenter
+from .support import Log, english_name, is_cjk_language
+from .translator import Translator
+
+_END = object()
+
+
+class ListenEngine:
+ def __init__(self, ling, translator, store, notes, settings):
+ self.ling = ling
+ self.translator = translator
+ self.store = store
+ self.notes = notes
+ self.settings = settings
+ self._gate = threading.RLock()
+ self._pool = ThreadPoolExecutor(max_workers=8, thread_name_prefix="Listen")
+ self._source = None
+ self._audio = None
+ self._worker = None
+ self._done: dict = {}
+ self._segments: dict = {}
+ self._in_flight: list = []
+ self._next = 1
+ self._line_count = 0
+ self._last = None
+ self._last_end = 0.0
+ self._hint = None
+ self._candidate = None
+ self._votes = 0
+ self._listeners = []
+ self.listening = False
+ self.session_id = None
+ self.source_kind = None # what this meeting is heard from ("system", "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.problem_kind = None
+ self.level = 0.0
+ self.heard_seconds = 0.0 # the capture is alive while this grows
+ self.peak = 0.0 # 0 for a while means the source is silent
+ 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._voice_pool = ThreadPoolExecutor(1, thread_name_prefix="Voiceprint")
+ self._deliver_lock = threading.Lock()
+ self._voices_waiting = 0
+ translator.glossary = notes.glossary
+
+ def on_change(self, listener) -> None:
+ self._listeners.append(listener)
+
+ def _changed(self) -> None:
+ for l in list(self._listeners):
+ l()
+
+ @property
+ def target(self) -> str:
+ return self.settings.target_code
+
+ @property
+ def spoken(self):
+ with self._gate:
+ return self._hint
+
+ @property
+ def pending(self) -> int:
+ """Segments sent and not yet back: the UI shows "…" while this is above zero."""
+ with self._gate:
+ return len(self._segments)
+
+ def start(self, source, kind: str) -> None:
+ if self.listening:
+ return
+ session = self.store.begin()
+ self.session_id = session.id
+ self.source_kind = kind
+ with self._gate:
+ self._done.clear()
+ self._segments.clear()
+ self._in_flight.clear()
+ self._next, self._line_count, self._last, self._last_end = 1, 0, None, 0.0
+ self._hint, self._candidate, self._votes, self.problem = None, None, 0, None
+ self.problem_kind = None
+ self.heard_seconds = 0.0
+ self.peak = 0.0
+ self.notes.language = lambda: english_name(self.settings.notes_code)
+ self.notes.begin(session.id)
+ if self.speakers is not None:
+ self.speakers.reset()
+ segmenter = Segmenter()
+ segmenter.on_segment = self._send
+ q: queue.Queue = queue.Queue()
+ self._audio = q
+
+ def work():
+ # One worker owns the segmenter: audio callbacks only queue buffers.
+ while True:
+ buf = q.get()
+ if buf is _END:
+ break
+ segmenter.feed(buf)
+ self.level = Wav.rms(buf)
+ self.peak = max(self.peak * 0.995, self.level)
+ if self.loudness is not None:
+ self.loudness.add(self.level >= Segmenter.threshold)
+ self.heard_seconds += len(buf) / RATE
+ segmenter.flush()
+ self._worker = threading.Thread(target=work, name="ListenWorker", daemon=True)
+ self._worker.start()
+ self._source = source
+ source.on_samples = q.put
+ # 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 = True
+ source.start()
+ Log.d("listen: started %s source=%s target=%s" % (session.id, kind, self.target))
+ 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:
+ return
+ self.listening = False
+ if self._source is not None:
+ self._source.on_samples = None
+ self._source.stop()
+ if self._audio is not None:
+ self._audio.put(_END)
+ if self._worker is not None:
+ self._worker.join(5)
+ with self._gate:
+ waiting = list(self._in_flight)
+ wait(waiting, timeout=15)
+ sid = self.session_id
+ if sid is None:
+ return
+ self.store.end(sid, ended_at)
+ Log.d("listen: stopped %s, %d lines" % (sid, self._line_count))
+ self._changed()
+ self._pool.submit(self.notes.finish)
+
+ @property
+ def voices_on(self) -> bool:
+ return bool(self.speakers is not None and getattr(self.settings, "speakerVoices", False) and self.speakers.available)
+
+ def _send(self, seg) -> None:
+ wav = Wav.bytes(seg.samples)
+ seg.voiceprint = None
+ if 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 >= 2
+ if not behind:
+ self._voices_waiting += 1
+ if behind:
+ Log.d("speakers: voiceprints behind, segment %d left unlabelled" % seg.index)
+ else:
+ def embed(samples=seg.samples):
+ try:
+ return self.speakers.embed(samples)
+ finally:
+ with self._gate:
+ self._voices_waiting -= 1
+ seg.voiceprint = self._voice_pool.submit(embed)
+ with self._gate:
+ self._segments[seg.index] = seg
+ lang = self._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()
+
+ def job():
+ heard = None
+ started = time.monotonic()
+ try:
+ heard = self.translator.hear(wav, seg.asked, lang)
+ self.problem = self.problem_kind = None
+ except LingError as e:
+ self.problem_kind = {
+ LingError.NO_KEY: "key", LingError.INVALID_KEY: "key", LingError.RATE_LIMITED: "busy",
+ LingError.NETWORK: "network", LingError.TIMEOUT: "network",
+ }.get(e.kind)
+ self.problem = {
+ LingError.NO_KEY: strings.L("需要 Ling key 才能听"),
+ LingError.INVALID_KEY: strings.L("Ling key 无效"),
+ LingError.RATE_LIMITED: strings.L("Ling 太忙,稍后再试"),
+ LingError.NETWORK: strings.L("连不上 Ling"),
+ LingError.TIMEOUT: strings.L("连不上 Ling"),
+ }.get(e.kind)
+ Log.d("listen: segment %d failed %s" % (seg.index, e))
+ except Exception as e: # noqa: BLE001
+ Log.d("listen: segment %d failed %s" % (seg.index, type(e).__name__))
+ Log.d("listen: segment %d %.1fs -> %s in %d ms" % (seg.index, seg.seconds, heard.lang if heard else "nothing",
+ (time.monotonic() - started) * 1000))
+ with self._gate:
+ self._done[seg.index] = heard
+ self._deliver()
+ f = self._pool.submit(job)
+ with self._gate:
+ self._in_flight.append(f)
+ self._in_flight = [x for x in self._in_flight if not x.done()]
+
+ def _deliver(self) -> 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:
+ while self._next in self._done:
+ heard = self._done.pop(self._next)
+ ready.append((self._segments.pop(self._next), heard))
+ self._next += 1
+ for seg, heard in ready:
+ if heard is not None:
+ self._record(seg, heard)
+ if ready:
+ self._changed()
+
+ 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
+ try:
+ vector = future.result(timeout=20)
+ except Exception as e: # noqa: BLE001
+ Log.d("speakers: voiceprint failed %s" % type(e).__name__)
+ return None
+ return self.speakers.label(vector, seg.seconds)
+
+ def _record(self, seg, heard) -> None:
+ sid = self.session_id
+ if sid is None:
+ return
+ target = 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 None
+ voice = 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 = self._hint
+ if h is None:
+ self._hint = heard.lang
+ elif heard.lang != h:
+ if self._candidate == heard.lang:
+ self._votes += 1
+ else:
+ self._candidate, self._votes = heard.lang, 1
+ if self._votes >= 2:
+ self._hint, self._candidate, self._votes = self._candidate, None, 0
+ else:
+ self._candidate, self._votes = None, 0
+ prev = self._last
+ joined = 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 - self._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)
+ prev.dst = None if prev.dst is None or translation is None else join(prev.dst, translation, target)
+ line = prev
+ joined = True
+ else:
+ self._line_count += 1
+ line = TranscriptLine(id="h%d-%d" % (self._line_count, seg.index), t=seg.start, speaker="them",
+ src=heard.original, dst=translation, srcLang=heard.lang, dstLang=target,
+ voice=voice)
+ self._last = line
+ self._last_end = seg.start + seg.seconds
+ copy = line.copy()
+ if joined:
+ self.store.replace(sid, copy)
+ else:
+ self.store.append(sid, copy)
+ if voice is not None and self.on_voice is not None:
+ self.on_voice(sid)
+ # A joined sentence is translated again as a whole; a line Ming didn't translate gets text translation.
+ if (joined or line.dst is None) and line.srcLang != target:
+ src = line.src
+
+ def retranslate():
+ dst = self.translator.translate(src, line.srcLang, target, Translator.SENTENCE)
+ with self._gate:
+ if dst is None or line.src != src:
+ return
+ line.dst = dst
+ updated = line.copy()
+ self.store.replace(sid, updated)
+ self._changed()
+ self._pool.submit(retranslate)
+
+
+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 False
+ text = last.src.rstrip()
+ if not text or text[-1] in ".!?。!?…":
+ return False
+ cjk = is_cjk_language(nxt.lang)
+ size = len(text) + len(nxt.original) if cjk else len((text + " " + nxt.original).split())
+ return size <= (80 if cjk else 45)
+
+
+def join(a: str, b: str, lang: str) -> str:
+ cjk = lang.startswith(("zh", "ja"))
+ return a.rstrip() + b.lstrip() if cjk else a.rstrip() + " " + b.lstrip()
diff --git a/linux/cicada/core/meeting_end.py b/linux/cicada/core/meeting_end.py
new file mode 100644
index 0000000..61057fe
--- /dev/null
+++ b/linux/cicada/core/meeting_end.py
@@ -0,0 +1,157 @@
+"""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 annotations
+
+import os
+import re
+import subprocess
+
+PROMPT, END, OFF = "prompt", "end", "off"
+
+
+class Config:
+ def __init__(self, follow_apps: bool = True, silence: str = PROMPT, silence_after: float = 600,
+ countdown: float = 60, app_grace: float = 30):
+ self.follow_apps = follow_apps
+ self.silence = silence
+ self.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
+
+
+class 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 = kind
+ self.name = name
+
+ def __eq__(self, other):
+ return isinstance(other, Reason) and (self.kind, self.name) == (other.kind, other.name)
+
+ def __repr__(self):
+ return "%s(%s)" % (self.kind, self.name) if self.name else self.kind
+
+
+class Pending:
+ def __init__(self, reason: Reason, deadline: float):
+ self.reason = reason
+ self.deadline = deadline
+
+ def __eq__(self, other):
+ return isinstance(other, Pending) and (self.reason, self.deadline) == (other.reason, other.deadline)
+
+
+class MeetingEndWatch:
+ def __init__(self, config: Config, start: float):
+ self.config = config
+ self.pending: Pending | None = None
+ self.last_speech = start
+ self.in_call: dict = {} # meeting apps seen in a call during this meeting (id → name)
+
+ 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 = now
+ if self.pending is not None and self.pending.reason.kind == "silence":
+ self.pending = None
+
+ def keep_going(self, now: float) -> None:
+ """继续记录: forget the hang-up and start counting silence again."""
+ self.pending = None
+ self.last_speech = now
+ self.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.config
+ in_a_call = c.follow_apps and bool(calls)
+ if not said:
+ self.in_call = dict(calls) if c.follow_apps else {}
+ self.pending = None
+ if c.silence != OFF and not in_a_call and now - self.last_speech >= c.silence_after:
+ return Reason("nobody")
+ return None
+ app_pending = self.pending is not None and self.pending.reason.kind == "app"
+ if c.follow_apps:
+ 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
+ if 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)
+ elif app_pending:
+ self.pending = None
+ if self.pending is None and c.silence != OFF and not in_a_call and now - self.last_speech >= c.silence_after:
+ if c.silence == END:
+ return Reason("silence")
+ self.pending = Pending(Reason("silence"), now + c.countdown)
+ if (c.silence == OFF or in_a_call) and self.pending is not None and self.pending.reason.kind == "silence":
+ self.pending = None
+ if self.pending is not None and now >= self.pending.deadline:
+ p, self.pending = self.pending, None
+ return p.reason
+ 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": "腾讯会议",
+ "feishu": "飞书", "bytedance-feishu": "飞书", "lark": "Lark",
+ "dingtalk": "钉钉", "com.alibabainc.dingtalk": "钉钉",
+ "teams": "Teams", "teams-for-linux": "Teams", "teams-insiders": "Teams",
+ "webex": "Webex", "ciscocollabhost": "Webex",
+ "skypeforlinux": "Skype", "discord": "Discord",
+}
+
+_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 = {}
+ for line in block.splitlines():
+ m = _PROP.match(line)
+ if m:
+ props[m.group(1)] = m.group(2)
+ if props.get("stream.capture.sink") == "true":
+ continue
+ if own_pid is not None and props.get("application.process.id") == str(own_pid):
+ continue
+ for key in ("application.process.binary", "application.id", "application.name"):
+ v = props.get(key, "").lower()
+ program = os.path.basename(v).split(" ")[0] if v else ""
+ 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)
+ return {program: name for name, program in names.items()}
+
+
+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"})
+ except (OSError, subprocess.SubprocessError):
+ return {}
+ return parse_source_outputs(r.stdout, os.getpid()) if r.returncode == 0 else {}
diff --git a/linux/cicada/core/models.py b/linux/cicada/core/models.py
new file mode 100644
index 0000000..fc312fb
--- /dev/null
+++ b/linux/cicada/core/models.py
@@ -0,0 +1,269 @@
+"""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 annotations
+
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+
+from .jsonfmt import arr, boolean, integer, num, obj, string
+from . import jsonfmt
+
+
+def 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")
+
+
+def iso_read(text: str | None) -> datetime | None:
+ if not text:
+ return None
+ try:
+ return datetime.strptime(text.replace("Z", "+0000"), "%Y-%m-%dT%H:%M:%S%z")
+ except ValueError:
+ try:
+ return datetime.fromisoformat(text.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+
+def now() -> datetime:
+ return datetime.now(timezone.utc).replace(microsecond=0)
+
+
+@dataclass
+class 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)
+ src: str = ""
+ dst: str | None = None
+ srcLang: str = ""
+ dstLang: str = ""
+ voice: int | None = None # experimental voice id on the Mac; Linux doesn't tell voices apart
+
+ def copy(self) -> "TranscriptLine":
+ return TranscriptLine(self.id, self.t, self.speaker, self.src, self.dst, self.srcLang, self.dstLang, self.voice)
+
+ def to_json(self) -> dict:
+ return {"id": self.id, "t": self.t, "speaker": self.speaker, "src": self.src, "dst": self.dst,
+ "srcLang": self.srcLang, "dstLang": self.dstLang, "voice": self.voice}
+
+ @staticmethod
+ def from_json(o: dict) -> "TranscriptLine":
+ return TranscriptLine(id=string(o.get("id")) or "", t=_num(o.get("t"), 0.0), speaker=string(o.get("speaker")) or "them",
+ src=string(o.get("src")) or "", dst=string(o.get("dst")), srcLang=string(o.get("srcLang")) or "",
+ dstLang=string(o.get("dstLang")) or "", voice=integer(o.get("voice")))
+
+
+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
+
+
+@dataclass
+class VoiceGuess:
+ name: str = ""
+ evidence: str = ""
+
+ def to_json(self) -> dict:
+ return {"name": self.name, "evidence": self.evidence}
+
+ @staticmethod
+ def from_json(o: dict) -> "VoiceGuess":
+ return VoiceGuess(string(o.get("name")) or "", string(o.get("evidence")) or "")
+
+
+@dataclass
+class NoteItem:
+ text: str = ""
+ owner: str | None = None
+ support: int = 0
+ t: float | None = None # when it was said (first evidence line)
+
+ def to_json(self) -> dict:
+ return {"text": self.text, "owner": self.owner, "support": self.support, "t": self.t}
+
+ @staticmethod
+ def from_json(o: dict) -> "NoteItem":
+ return NoteItem(string(o.get("text")) or "", string(o.get("owner")), integer(o.get("support")) or 0, num(o.get("t")))
+
+
+@dataclass
+class 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)
+
+ def to_json(self) -> dict:
+ return {"name": self.name, "note": self.note, "heard": list(self.heard)}
+
+ @staticmethod
+ def from_json(o: dict) -> "NoteTerm":
+ return NoteTerm(string(o.get("name")) or "", string(o.get("note")) or "",
+ [x for x in arr(o.get("heard")) if isinstance(x, str)])
+
+ @staticmethod
+ def 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]
+
+
+@dataclass
+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
+
+ def to_json(self) -> dict:
+ return {"label": self.label, "detail": self.detail, "t": self.t, "support": self.support}
+
+ @staticmethod
+ def from_json(o: dict) -> "FishboneBranch":
+ return FishboneBranch(string(o.get("label")) or "", string(o.get("detail")) or "", num(o.get("t")), integer(o.get("support")) or 0)
+
+
+@dataclass
+class Fishbone:
+ question: str = ""
+ branches: list = field(default_factory=list)
+
+ def to_json(self) -> dict:
+ return {"question": self.question, "branches": [b.to_json() for b in self.branches]}
+
+ @staticmethod
+ def from_json(o: dict) -> "Fishbone":
+ return Fishbone(string(o.get("question")) or "", [FishboneBranch.from_json(b) for b in arr(o.get("branches")) if isinstance(b, dict)])
+
+
+@dataclass
+class NoteTopic:
+ start: float = 0.0
+ title: str = ""
+ summary: str = ""
+ points: list = field(default_factory=list)
+ pointTimes: list | None = None # when each point was said, parallel to points
+ fishbone: Fishbone | None = None
+
+ def point_time(self, i: int) -> float | None:
+ return self.pointTimes[i] if self.pointTimes is not None and i < len(self.pointTimes) else None
+
+ def 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}
+
+ @staticmethod
+ def from_json(o: dict) -> "NoteTopic":
+ pt = o.get("pointTimes")
+ return NoteTopic(start=_num(o.get("start"), 0.0), title=string(o.get("title")) or "", summary=string(o.get("summary")) or "",
+ points=[p for p in arr(o.get("points")) if isinstance(p, str)],
+ pointTimes=[num(x) for x in pt] if isinstance(pt, list) else None,
+ fishbone=Fishbone.from_json(o["fishbone"]) if isinstance(o.get("fishbone"), dict) else None)
+
+
+@dataclass
+class MeetingNotes:
+ """Written by Ling while the meeting runs, rewritten over the whole transcript when it ends."""
+ title: str | None = None
+ summary: 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
+ final: bool = False
+ updatedAt: datetime | None = None
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.summary and not self.topics
+
+ def to_json(self) -> dict:
+ return {"title": self.title, "summary": self.summary, "topics": [t.to_json() for t in self.topics],
+ "conclusions": [c.to_json() for c in self.conclusions], "todos": [t.to_json() for t in self.todos],
+ "terms": [t.to_json() for t in self.terms], "covered": self.covered, "final": self.final,
+ "updatedAt": iso_write(self.updatedAt) if self.updatedAt else None}
+
+ @staticmethod
+ def from_json(o: dict) -> "MeetingNotes":
+ def objs(key):
+ return [x for x in arr(o.get(key)) if isinstance(x, dict)]
+ return MeetingNotes(title=string(o.get("title")), summary=string(o.get("summary")) or "",
+ topics=[NoteTopic.from_json(t) for t in objs("topics")],
+ conclusions=[NoteItem.from_json(c) for c in objs("conclusions")],
+ todos=[NoteItem.from_json(c) for c in objs("todos")],
+ terms=[NoteTerm.from_json(c) for c in objs("terms")],
+ covered=integer(o.get("covered")) or 0, final=boolean(o.get("final")) or False,
+ updatedAt=iso_read(string(o.get("updatedAt"))))
+
+
+@dataclass
+class Session:
+ id: str = ""
+ title: str = ""
+ startedAt: datetime = field(default_factory=now)
+ endedAt: datetime | None = None
+ lines: list = field(default_factory=list)
+ hasAudio: bool = False
+ notes: MeetingNotes | None = None
+ renamed: bool | None = None
+ voiceNames: dict | None = None
+ voiceGuesses: 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 = None
+ sourcePath: str | None = None
+ importing: 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",
+ "voiceGuesses", "sourceFile", "sourcePath", "importing", "room")
+
+ @property
+ def 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.0
+
+ def to_json(self) -> dict:
+ return {**self.extra, "id": self.id, "title": self.title, "startedAt": iso_write(self.startedAt),
+ "endedAt": iso_write(self.endedAt) if self.endedAt else None, "lines": [l.to_json() for l in self.lines],
+ "hasAudio": self.hasAudio, "notes": self.notes.to_json() if self.notes else None, "renamed": self.renamed,
+ "voiceNames": self.voiceNames,
+ "voiceGuesses": {k: v.to_json() for k, v in self.voiceGuesses.items()} if self.voiceGuesses is not None else None,
+ "sourceFile": self.sourceFile, "sourcePath": self.sourcePath, "importing": self.importing,
+ "room": self.room}
+
+ @staticmethod
+ def from_json(o: dict) -> "Session":
+ vn = obj(o.get("voiceNames"))
+ vg = obj(o.get("voiceGuesses"))
+ return Session(id=string(o.get("id")) or "", title=string(o.get("title")) or "",
+ startedAt=iso_read(string(o.get("startedAt"))) or datetime.fromtimestamp(0, timezone.utc),
+ endedAt=iso_read(string(o.get("endedAt"))),
+ lines=[TranscriptLine.from_json(l) for l in arr(o.get("lines")) if isinstance(l, dict)],
+ hasAudio=boolean(o.get("hasAudio")) or False,
+ notes=MeetingNotes.from_json(o["notes"]) if isinstance(o.get("notes"), dict) else None,
+ renamed=boolean(o.get("renamed")),
+ voiceNames={k: (string(v) or "") for k, v in vn.items()} if vn is not None else None,
+ voiceGuesses={k: VoiceGuess.from_json(obj(v) or {}) for k, v in vg.items()} if vg is not None else None,
+ sourceFile=string(o.get("sourceFile")), sourcePath=string(o.get("sourcePath")),
+ importing=boolean(o.get("importing")), room=boolean(o.get("room")),
+ extra={k: v for k, v in o.items() if k not in Session.KEYS})
+
+ @staticmethod
+ def read(text: str) -> "Session | None":
+ o = jsonfmt.parse_object(text)
+ return Session.from_json(o) if o is not None else None
+
+ def write(self) -> str:
+ return jsonfmt.write(self.to_json())
diff --git a/linux/cicada/core/notes.py b/linux/cicada/core/notes.py
new file mode 100644
index 0000000..64d699e
--- /dev/null
+++ b/linux/cicada/core/notes.py
@@ -0,0 +1,362 @@
+"""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 whole notes back as JSON; a final pass rewrites them
+over the whole transcript when the meeting ends. 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 annotations
+
+import re
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+from . import jsonfmt, speakers
+from .jsonfmt import arr, num, obj
+from .ling import NOTES, LingError
+from .models import Fishbone, FishboneBranch, MeetingNotes, NoteItem, NoteTerm, NoteTopic, now
+from .support import Log, clock, written_in
+
+INTERVAL = 45.0
+IDLE, UPDATING, NO_KEY, INVALID_KEY, RATE_LIMITED, FAILED = "idle", "updating", "noKey", "invalidKey", "rateLimited", "failed"
+
+
+class NotesEngine:
+ def __init__(self, ling, store):
+ self.ling = ling
+ self.store = store
+ self.voices = lambda: False # 说话人识别 on: lines go as 说话人N or the name given (set by the app)
+ self._gate = threading.RLock()
+ self._work = ThreadPoolExecutor(max_workers=1, thread_name_prefix="NotesWork")
+ self._ticker = None
+ self._session_id = None
+ self._in_flight = False
+ self._pending_final = None
+ self._last_attempt = 0.0
+ 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: "Simplified Chinese" # the notes' language (English name), from 纪要语言
+ self.working_id = None # the record being written now, for a "正在整理纪要…" next to it
+
+ def on_change(self, listener) -> None:
+ self._listeners.append(listener)
+
+ def _changed(self) -> None:
+ for l in list(self._listeners):
+ 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)))
+ return out
+
+ def begin(self, sid: str) -> None:
+ with self._gate:
+ self._session_id = sid
+ self.shown_id = sid
+ s = self.store.get(sid)
+ self.notes = (s.notes if s else None) or MeetingNotes()
+ self.status = IDLE if self.ling.has_key else NO_KEY
+ self._last_attempt = time.time()
+ self._stop_ticker()
+ stop = threading.Event()
+
+ def loop():
+ while not stop.wait(5.0):
+ self._tick()
+ self._ticker = stop
+ threading.Thread(target=loop, name="Notes", daemon=True).start()
+ self._changed()
+
+ def _stop_ticker(self) -> None:
+ if self._ticker is not None:
+ self._ticker.set()
+ self._ticker = None
+
+ def 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
+ self._session_id = None
+ if sid is not None:
+ self._update(sid, final=True)
+
+ def show(self, sid: str) -> None:
+ with self._gate:
+ self.shown_id = sid
+ s = self.store.get(sid)
+ self.notes = (s.notes if s else None) or MeetingNotes()
+ self._changed()
+
+ def generate(self, sid: str) -> None:
+ """Notes for a finished meeting that has none (runs in the background)."""
+ self._work.submit(self._update, sid, True)
+
+ def _tick(self) -> None:
+ with self._gate:
+ if self.status == NO_KEY and self.ling.usable:
+ self.status = IDLE
+ sid = self._session_id
+ if sid is None or self._in_flight:
+ return
+ s = self.store.get(sid)
+ if s is None or len(s.lines) <= self.notes.covered:
+ return
+ since = 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 >= INTERVAL
+ if not due:
+ return
+ self._work.submit(self._update, sid, False)
+
+ def _update(self, sid: str, final: bool) -> None:
+ with self._gate:
+ if self._in_flight:
+ if final:
+ self._pending_final = sid
+ return
+ session = self.store.get(sid)
+ if session is None or not session.lines:
+ return
+ if not self.ling.has_key:
+ self.status = NO_KEY
+ self._changed()
+ return
+ self._in_flight = True
+ self.working_id = sid
+ self._last_attempt = time.time()
+ self.status = UPDATING
+ base = MeetingNotes() if final else (self.notes if sid == self.shown_id else (session.notes or MeetingNotes()))
+ self._changed()
+ try:
+ lines = self.store.lines(sid)
+ frm = 0 if final else min(base.covered, len(lines))
+ lang = self.language()
+ shown = speakers.names(session) if self.voices() else {}
+ p = prompt(base, lines, frm, lang, final, shown, self.voices())
+ nxt = None
+ for attempt in range(1, 3 if final else 2):
+ raw = self.ling.chat(p, "Update the notes. Write them in %s." % lang, NOTES, json=True, max_tokens=6000, timeout=90.0)
+ parsed = parse(raw, [l.t for l in lines], lines[0].t if lines else 0.0)
+ if parsed is None:
+ break
+ if written(parsed, lang):
+ nxt = parsed
+ break
+ Log.d("notes: %s reply not in %s (attempt %d), dropped" % ("final" if final else "live", lang, attempt))
+ if nxt is None:
+ Log.d("notes: no usable reply, kept the previous notes")
+ self.status = FAILED
+ return
+ carry_times(base, nxt)
+ nxt.title = nxt.title or base.title or (session.notes.title if session.notes else None)
+ nxt.covered = len(lines)
+ nxt.updatedAt = now()
+ nxt.final = final
+ with self._gate:
+ if sid == self.shown_id:
+ self.notes = nxt
+ self.store.set_notes(sid, nxt)
+ self.status = IDLE
+ Log.d("notes: %s update %d new lines -> %d topics, %d terms" % (
+ "final" if final else "live", len(lines) - frm, len(nxt.topics), len(nxt.terms)))
+ except LingError as e:
+ self.status = {LingError.INVALID_KEY: INVALID_KEY, LingError.RATE_LIMITED: RATE_LIMITED,
+ LingError.NO_KEY: NO_KEY}.get(e.kind, FAILED)
+ Log.d("notes: update failed %s" % e)
+ except Exception as e: # noqa: BLE001
+ self.status = FAILED
+ Log.d("notes: update failed %s" % type(e).__name__)
+ finally:
+ with self._gate:
+ self._in_flight = False
+ self.working_id = None
+ queued = self._pending_final
+ self._pending_final = None
+ self._changed()
+ if queued is not None:
+ self._update(queued, final=True)
+
+
+def _min(a, b):
+ return b if a is None else a if b is None else min(a, b)
+
+
+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):
+ pt = t.point_time(i)
+ if pt is not None:
+ known.setdefault(p, pt)
+ 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
+ items = {}
+ for i in old.conclusions + old.todos:
+ if i.t is not None:
+ items.setdefault(i.text, i.t)
+ for i in nxt.conclusions + nxt.todos:
+ i.t = _min(i.t, items.get(i.text))
+
+
+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) -> str:
+ 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.src)
+ current = "{}" if notes.is_empty else _compact_json(notes)
+ context = max(0, frm - 2)
+ p = ("You keep notes for a meeting %s.\n" % ("that has just ended. Rewrite them from the whole transcript" if final
+ else "that is still going on. Update them with the new lines") +
+ "Write the notes in %s. Return JSON only.\n" % language)
+ if not final:
+ p += "Current notes (JSON):\n%s\n\n" % current
+ if context < frm:
+ p += "Already covered (context only):\n" + "\n".join(line(i) for i in range(context, frm)) + "\n\n"
+ p += ("%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)))
+ if final and lines:
+ span = lines[-1].t - lines[0].t
+ most = max(1, min(8, int(span / 180) + 1))
+ p += "\n\nThis meeting ran %s: use at most %d topic%s." % (clock(span), most, "" if most == 1 else "s")
+ elif not final and notes.topics and lines and lines[-1].t - notes.topics[-1].start < 120:
+ topic = notes.topics[-1]
+ p += ("\n\nThe current topic \"%s\" started at %s, under 2 minutes ago: do not start a new topic in this update; add the new lines to it."
+ % (topic.title, clock(topic.start)))
+ elif not final and not notes.topics:
+ p += "\n\nThese are the first lines: make one topic."
+ p += ("\n\nReturn 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"
+ " \"topics\": [{\"start\": seconds, \"title\": \"short title\", \"summary\": \"one sentence\", \"points\": [{\"text\": \"key point\", \"evidence\": [\"L4\"]}], \"evidence\": [\"L3\"],\n"
+ " \"fishbone\": null or {\"question\": \"the problem or question\", \"branches\": [{\"label\": \"2-6 words\", \"detail\": \"one short line\", \"t\": seconds, \"evidence\": [\"L5\"]}]}}],\n"
+ " \"conclusions\": [{\"text\": \"...\", \"evidence\": [\"L7\", \"L8\"]}],\n"
+ " \"todos\": [{\"text\": \"...\", \"owner\": %s, \"evidence\": [\"L9\"]}],\n"
+ " \"terms\": [{\"name\": \"correct spelling\", \"note\": \"who or what, a few words\", \"heard\": [\"how it was misrecognised\"]}]}\n"
+ "Rules (be brief: these notes are read at a glance during the meeting):\n"
+ "- title: a name for the whole meeting, like a calendar entry (at most 12 Chinese characters or 6 words; no date, no quotes, not \"会议\" alone). Keep the current title unless the meeting's subject has clearly changed.\n"
+ "- summary: at most 3 short sentences.\n"
+ "- Topics in time order, at most 8 in total. A topic is a stretch of the meeting, usually 3-10 minutes, not a single remark: start a new one only when the subject clearly changes and the current topic started at least 2 minutes before the newest line%s. Otherwise add to the current one, and merge small neighbouring topics. Keep earlier topics as they are unless new lines correct them. The last topic is the one being discussed now.\n"
+ "- At most 4 points per topic, each one short phrase. Merge rather than repeat.\n"
+ "- At most 5 conclusions and only real to-dos (often none).\n"
+ "- Add a fishbone only to a topic that discusses causes, reasons or factors (3-5 branches); otherwise null.\n"
+ "- Every topic, point, branch, conclusion and to-do needs evidence: the ids of the lines that say it. Never state anything the transcript does not say.\n"
+ "- terms: at most 10 in total, replacing less useful ones rather than adding: first names the transcript misspells (heard), then the people, places and jargon a reader would not know. Leave out what everyone knows (a famous company, index or politician) unless it was misheard. name is the correct spelling in the transcript's language (no translation in brackets); heard lists only the wrong forms the transcript used; note is a few words.\n"
+ "- Write the meeting title and every summary, title, point, branch, conclusion and to-do in %s, even when the transcript is in another language. Only term names keep the transcript's spelling.\n"
+ "- Write about what was said, never about the transcript or recognition quality.\n"
+ "- Use empty arrays when there is nothing. No markdown, no text outside the JSON."
+ % ('"对方" or "你" or null' if not nums else
+ 'the person\'s label from the transcript (a name like "George", or "说话人2"), "你", or null when unclear',
+ "" if final else "; add at most one new topic per update", language))
+ return p
+
+
+def _compact_json(n: MeetingNotes) -> str:
+ """The current notes as sent back to the model (no bookkeeping fields). 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
+ o["summary"] = n.summary
+ o["topics"] = [{"start": t.start, "title": t.title, "summary": t.summary, "points": list(t.points),
+ "fishbone": t.fishbone.to_json() if t.fishbone else None} for t in n.topics]
+ o["conclusions"] = [c.text for c in n.conclusions]
+ o["todos"] = [t.text for t in n.todos]
+ o["terms"] = [t.to_json() for t in n.terms]
+ 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:
+ return None
+ root = jsonfmt.parse_object(raw[a:b + 1])
+ if root is None:
+ return None
+
+ def s(v):
+ return v.strip() if isinstance(v, str) else ""
+
+ def line_numbers(v):
+ out = set()
+ for i in arr(v):
+ m = re.search(r"\d+", s(i))
+ if m:
+ n = int(m.group())
+ if 1 <= n <= len(times):
+ out.add(n)
+ return out
+
+ def time_of(v):
+ ns = line_numbers(v)
+ return times[min(ns) - 1] if ns else None
+
+ def objects(v):
+ return [x for x in arr(v) if isinstance(x, dict)]
+
+ n = MeetingNotes(summary=s(root.get("summary")))
+ title = s(root.get("title")).strip("\"“”「」《》")
+ n.title = title or None
+ for t in objects(root.get("topics")):
+ topic_title = s(t.get("title"))
+ if not topic_title:
+ continue
+ fish = None
+ f = obj(t.get("fishbone"))
+ if f is not None:
+ branches = [FishboneBranch(label=s(br.get("label")), detail=s(br.get("detail")), t=num(br.get("t")),
+ support=len(line_numbers(br.get("evidence")))) for br in objects(f.get("branches"))]
+ branches = [x for x in branches if x.label]
+ if len(branches) >= 2:
+ fish = Fishbone(s(f.get("question")), branches)
+ points, point_times = [], []
+ for p in arr(t.get("points")):
+ po = obj(p)
+ text = s(po.get("text")) if po is not None else s(p)
+ if not text:
+ continue
+ points.append(text)
+ point_times.append(time_of(po.get("evidence")) if po is not None else None)
+ start = 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")),
+ points=points, pointTimes=point_times if any(x is not None for x in point_times) else None,
+ fishbone=fish))
+
+ def items(key):
+ out = [NoteItem(text=s(i.get("text")), owner=s(i.get("owner")) or None, support=len(line_numbers(i.get("evidence"))),
+ t=time_of(i.get("evidence"))) for i in objects(root.get(key))]
+ return [i for i in out if i.text]
+ n.conclusions = items("conclusions")
+ n.todos = items("todos")
+ terms = []
+ for t in objects(root.get("terms")):
+ 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 terms
+ return None if n.is_empty else n
diff --git a/linux/cicada/core/segmenter.py b/linux/cicada/core/segmenter.py
new file mode 100644
index 0000000..386f57d
--- /dev/null
+++ b/linux/cicada/core/segmenter.py
@@ -0,0 +1,124 @@
+"""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 annotations
+
+from array import array
+from collections import deque
+
+from .audio import RATE, Wav
+
+FRAME = 480 # 30 ms
+PRE_ROLL = 0.15
+TAIL = 0.15
+CUT_WINDOW = 2.0
+
+
+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 = index
+ self.start = start
+ self.samples = samples
+
+ @property
+ def seconds(self) -> float:
+ return len(self.samples) / RATE
+
+
+class Segmenter:
+ threshold = 0.01 # the Mac AudioRouter's gate (about -40 dBFS)
+ pause = 0.6
+ max_length = 8.0
+ min_speech = 0.25
+
+ def __init__(self):
+ self.pending = array("h")
+ self.current = array("h")
+ self.levels: list = []
+ self.before: deque = deque()
+ self.consumed = 0
+ self.current_start = 0.0
+ self.quiet = 0
+ self.loud = 0
+ self.index = 0
+ self.on_segment = None
+
+ def feed(self, samples) -> None:
+ self.pending.extend(samples)
+ whole = len(self.pending) // FRAME * FRAME
+ for i in range(0, whole, FRAME):
+ self._step(self.pending[i:i + FRAME])
+ 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 _step(self, frame: array) -> None:
+ level = Wav.rms(frame)
+ loud = level >= self.threshold
+ now = self.consumed / RATE
+ self.consumed += len(frame)
+ if not len(self.current):
+ if not loud:
+ self.before.append(frame)
+ while len(self.before) > PRE_ROLL * RATE / FRAME:
+ self.before.popleft()
+ return
+ self.current_start = now - len(self.before) * FRAME / RATE
+ for f in self.before:
+ self.current.extend(f)
+ self.levels.append(0.0)
+ self.before.clear()
+ self.quiet = self.loud = 0
+ self.current.extend(frame)
+ self.levels.append(level)
+ if loud:
+ self.quiet = 0
+ self.loud += 1
+ else:
+ self.quiet += 1
+ 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 = frm
+ for i in range(frm, len(self.levels)):
+ if self.levels[i] < self.levels[cut]:
+ cut = i
+ self._close(cut * FRAME)
+
+ def _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:]
+ rest_levels = self.levels[min(len(self.levels), end // FRAME):]
+ start = self.current_start
+ speech = self.loud * FRAME >= self.min_speech * RATE
+ self.current = array("h")
+ self.levels = []
+ self.quiet = self.loud = 0
+ if speech and self.on_segment:
+ self.index += 1
+ 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(l >= self.threshold for l in rest_levels):
+ self.current_start = start + end / RATE
+ self.current.extend(rest)
+ self.levels = list(rest_levels)
+ trailing = 0
+ for l in reversed(self.levels):
+ if l >= self.threshold:
+ break
+ trailing += 1
+ self.quiet = trailing
+ self.loud = sum(1 for l in self.levels if l >= self.threshold)
diff --git a/linux/cicada/core/session_store.py b/linux/cicada/core/session_store.py
new file mode 100644
index 0000000..43c13bd
--- /dev/null
+++ b/linux/cicada/core/session_store.py
@@ -0,0 +1,390 @@
+"""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 annotations
+
+import os
+import shutil
+import threading
+from datetime import datetime, timezone
+
+from . import speakers, strings
+from .models import Session, now
+from .support import Log, Paths, clock
+
+
+class SessionStore:
+ def __init__(self):
+ self._gate = threading.RLock()
+ self._sessions: dict = {}
+ self._dirty: set = set()
+ self._timer = None
+ self._listeners = []
+ self._word_listeners = []
+ self.live: str | None = None # the meeting being listened to (the Mac's liveID)
+ self._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 _words(self, sid: str) -> None:
+ for l in list(getattr(self, "_word_listeners", [])):
+ l(sid)
+
+ def _fire(self, sid: str) -> None:
+ for l in list(self._listeners):
+ l(sid)
+
+ def _folder(self, sid: str) -> str:
+ return os.path.join(Paths.sessions(), sid)
+
+ def _load(self) -> None:
+ root = Paths.sessions()
+ if not os.path.isdir(root):
+ return
+ for name in os.listdir(root):
+ path = os.path.join(root, name, "session.json")
+ if not os.path.isfile(path):
+ continue
+ try:
+ with open(path, encoding="utf-8") as f:
+ s = Session.read(f.read())
+ if s is not None:
+ self._sessions[s.id] = s
+ except (OSError, ValueError) as e:
+ 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)
+
+ def get(self, sid: str) -> Session | None:
+ with self._gate:
+ return self._sessions.get(sid)
+
+ def 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 []
+
+ def begin(self, at: datetime | None = None) -> Session:
+ at = (at or now()).replace(microsecond=0)
+ local = at.astimezone()
+ sid = local.strftime("%Y%m%d-%H%M%S")
+ s = Session(id=sid, title=default_title(at), startedAt=at)
+ with self._gate:
+ self._sessions[sid] = s
+ self.live = sid
+ return s
+
+ def append(self, sid: str, line) -> None:
+ self._mutate(sid, lambda s: s.lines.append(line))
+ self._words(sid)
+
+ def replace(self, sid: str, line) -> None:
+ grew = []
+
+ 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
+ if len(line.src) > len(l.src):
+ grew.append(True) # a half sentence joined: new words, not a retranslation
+ s.lines[i] = line
+ return
+ self._mutate(sid, change)
+ if grew:
+ self._words(sid)
+
+ # 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":
+ l.voice = voice
+ 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:
+ return None
+ return ({l.id: l.voice for l in s.lines}, dict(s.voiceNames) if s.voiceNames is not None else None,
+ dict(s.voiceGuesses) if s.voiceGuesses is not None else None)
+
+ def restore(self, sid: str, snap) -> None:
+ voices, vnames, guesses = snap
+
+ def change(s):
+ for l in s.lines:
+ if l.id in voices: # lines heard since keep the voice they were given
+ l.voice = voices[l.id]
+ s.voiceNames, s.voiceGuesses = vnames, guesses
+ self._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:
+ vn.pop(str(voice), None)
+ else:
+ vn[str(voice)] = name.strip()
+ s.voiceNames = vn or None
+ 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
+
+ def change(s):
+ allg = dict(s.voiceGuesses or {})
+ for v, name in refuted.items():
+ if v not in guesses and allg.get(str(v)) is not None and allg[str(v)].name == name:
+ del allg[str(v)]
+ for v, g in guesses.items():
+ allg[str(v)] = g
+ s.voiceGuesses = allg or None
+ 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
+
+ def change(s):
+ for l in s.lines:
+ if l.voice == frm:
+ l.voice = into
+ 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)] = moved
+ s.voiceNames = vn or None
+ if s.voiceGuesses is not None and str(frm) in s.voiceGuesses:
+ vg = dict(s.voiceGuesses)
+ moved = vg.pop(str(frm))
+ if str(into) not in vg:
+ vg[str(into)] = moved
+ s.voiceGuesses = vg or None
+ self._mutate(sid, change)
+
+ def set_notes(self, sid: str, notes) -> None:
+ 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)
+ if s is None or t == display_title(s):
+ return
+
+ def change(s):
+ if t:
+ s.title, s.renamed = t, True
+ else:
+ s.title, s.renamed = default_title(s.startedAt), False
+ 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:
+ self.live = None
+ if s is None:
+ return
+ s.endedAt = max(ended_at, s.startedAt) if ended_at is not None else now()
+ empty = not s.lines
+ if empty:
+ self.delete(sid)
+ else:
+ self._mark_dirty(sid)
+ self.flush()
+ 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)
+ return
+ self._sessions.pop(sid, None)
+ self._dirty.discard(sid)
+ shutil.rmtree(self._folder(sid), ignore_errors=True)
+ 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] = s
+ self._mark_dirty(s.id)
+ self.flush()
+ self._fire(s.id)
+
+ def _mutate(self, sid: str, change) -> None:
+ with self._gate:
+ s = self._sessions.get(sid)
+ if s is None:
+ return
+ change(s)
+ self._mark_dirty(sid)
+ self._fire(sid)
+
+ def _mark_dirty(self, sid: str) -> None:
+ with self._gate:
+ self._dirty.add(sid)
+ if self._timer:
+ self._timer.cancel()
+ self._timer = threading.Timer(1.5, self.flush)
+ self._timer.daemon = True
+ 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()
+ for sid, text in writes:
+ try:
+ folder = self._folder(sid)
+ os.makedirs(folder, exist_ok=True)
+ tmp = os.path.join(folder, "session.json.tmp")
+ with open(tmp, "w", encoding="utf-8") as f:
+ f.write(text)
+ os.replace(tmp, os.path.join(folder, "session.json"))
+ except OSError as e:
+ Log.d("store: save failed %s" % type(e).__name__)
+
+
+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 = []
+ i = 0
+ while i < len(pattern):
+ c = pattern[i]
+ j = i
+ while j < len(pattern) and pattern[j] == c:
+ j += 1
+ run = j - i
+ if c == "'":
+ k = pattern.find("'", i + 1)
+ out.append(pattern[i + 1:k if k > 0 else len(pattern)])
+ i = (k + 1) if k > 0 else len(pattern)
+ continue
+ if c == "y":
+ out.append(str(l.year))
+ elif c == "M":
+ out.append(months[l.month - 1] if run >= 3 else ("%02d" % l.month if run == 2 else str(l.month)))
+ elif c == "d":
+ out.append("%02d" % l.day if run == 2 else str(l.day))
+ elif c == "H":
+ out.append("%02d" % l.hour if run == 2 else str(l.hour))
+ elif c == "m":
+ out.append("%02d" % l.minute)
+ else:
+ out.append(pattern[i:j])
+ i = j
+ return "".join(out)
+
+
+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.title
+ name = s.notes.title if s.notes else None
+ if 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"))
+ this_year = s.startedAt.astimezone().year == datetime.now().year
+ 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.L
+ if n is None or n.is_empty:
+ return ""
+ b = ["## %s\n\n%s\n\n" % (L("纪要"), n.summary)]
+ for t in n.topics:
+ b.append("### %s %s\n\n" % (clock(t.start), t.title))
+ if t.summary:
+ b.append(t.summary + "\n\n")
+ for p in t.points:
+ b.append("- %s\n" % p)
+ if t.fishbone is not None:
+ b.append("\n**%s**\n\n" % t.fishbone.question)
+ for br in t.fishbone.branches:
+ b.append("- %s:%s\n" % (br.label, br.detail))
+ b.append("\n")
+ if n.conclusions:
+ b.append("### %s\n\n" % L("结论") + "".join("- %s\n" % c.text for c in n.conclusions) + "\n")
+ if n.todos:
+ b.append("### %s\n\n" % L("待办") + "".join("- [ ] %s%s\n" % (t.text, "(%s)" % t.owner if t.owner else "") for t in n.todos) + "\n")
+ if n.terms:
+ b.append("### %s\n\n" % L("人名和术语") + "".join("- **%s** %s\n" % (t.name, t.note) for t in n.terms) + "\n")
+ return "".join(b)
+
+
+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("文字记录"))
+ for l in s.lines:
+ # An imported file has no "other side" to name.
+ who = (" " + speakers.speaker_name(l, nums, shown)) if s.sourceFile is None else ""
+ out.append("**[%s]%s** \n%s\n" % (clock(l.t), who, l.src))
+ if l.dst and l.dst != l.src:
+ out.append("> %s\n" % l.dst)
+ out.append("\n")
+ return "".join(out)
diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.py
new file mode 100644
index 0000000..e87014c
--- /dev/null
+++ b/linux/cicada/core/settings.py
@@ -0,0 +1,84 @@
+"""The app's settings, in settings.json beside the key (never the key itself: it has its own file)."""
+from __future__ import annotations
+
+import os
+
+from . import jsonfmt
+from .support import Log, Paths, follow_system_target, my_language, system_language, system_languages
+
+DEFAULT_MODEL = "Ling-3.1-flash"
+
+
+class AppSettings:
+ FIELDS = {
+ "target": "system", # what subtitles translate into; "system" follows the desktop language
+ "notesLanguage": "system", # 纪要语言; "system" is the same as the subtitles'
+ "model": DEFAULT_MODEL,
+ "view": "notes", # "notes" (the notes window, default) or "subtitles" (the subtitle bar)
+ "showInCapture": False, # 共享屏幕时让对方看到 (Linux can't hide it; see NotesWindow)
+ "onboarded": False,
+ "uiLanguage": "system", # "system", "zh-Hans", "en", "ja" or "ko"
+ # 同声传译: what I say is interpreted and spoken into 知了 麦克风 (the Mac's speakEnabled etc.).
+ "speakerVoices": True, # 说话人识别: tell the other side's voices apart (说话人 1、2…), as on the Mac
+ "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
+ # 结束会议 (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,
+ }
+
+ def __init__(self, **kw):
+ for k, v in self.FIELDS.items():
+ v = kw.get(k, v)
+ setattr(self, k, dict(v) if isinstance(v, dict) else v)
+
+ @property
+ def 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.target
+
+ def 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.target
+
+ @property
+ def notes_code(self) -> str:
+ return self.target_code if self.notesLanguage == "system" else self.notesLanguage
+
+ @property
+ def speak_from_code(self) -> str:
+ return self.target_code if self.speakFrom == "system" else self.speakFrom
+
+ @property
+ def ui_code(self) -> str:
+ return system_language() if self.uiLanguage == "system" else self.uiLanguage
+
+ def to_json(self) -> dict:
+ return {k: getattr(self, k) for k in self.FIELDS}
+
+ def save(self) -> None:
+ try:
+ os.makedirs(Paths.config(), exist_ok=True)
+ with open(Paths.settings(), "w", encoding="utf-8") as f:
+ f.write(jsonfmt.write(self.to_json()))
+ except OSError as e:
+ Log.d("settings: save failed %s" % type(e).__name__)
+
+ @staticmethod
+ def load() -> "AppSettings":
+ try:
+ if os.path.isfile(Paths.settings()):
+ with open(Paths.settings(), encoding="utf-8") as f:
+ 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)}
+ return AppSettings(**kw)
+ except OSError as e:
+ Log.d("settings: unreadable, defaults used (%s)" % type(e).__name__)
+ return AppSettings()
diff --git a/linux/cicada/core/speak.py b/linux/cicada/core/speak.py
new file mode 100644
index 0000000..27e3f8e
--- /dev/null
+++ b/linux/cicada/core/speak.py
@@ -0,0 +1,274 @@
+"""同声传译 (the Mac's 说): what I say into my microphone, interpreted and spoken into the meeting.
+
+Each sentence (cut by the same Segmenter as listening) goes to Ming's audio model, which returns
+what was said and its translation in one call; the translation is voiced by Ming's TTS and played
+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; a sentence heard
+while the system audio was loud for most of it is dropped, so the room doesn't get its own words
+back. UI-free like ListenEngine: on_change is called on worker threads."""
+from __future__ import annotations
+
+import queue
+import threading
+import time
+from collections import deque
+from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime, timezone
+
+from . import strings
+from . import voices as voicemod
+from .audio import RATE, Wav
+from .ling import LingError, TTS_RATE
+from .models import TranscriptLine
+from .segmenter import Segmenter
+from .support import Log
+
+_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()
+
+ def add(self, loud: bool) -> None:
+ with self._lock:
+ self._items.append((time.monotonic(), loud))
+
+ def fraction(self, start: float, end: float) -> float:
+ with self._lock:
+ span = [l for t, l in self._items if start <= t <= end]
+ return sum(span) / len(span) if span else 0.0
+
+
+class SpeakEngine:
+ ECHO = 0.5 # drop a sentence if the system audio was loud for more than half of it
+
+ def __init__(self, ling, translator, settings, store=None, listen=None, player=None):
+ self.ling = ling
+ self.translator = translator
+ self.settings = settings
+ self.store = store
+ self.listen = listen
+ self.player = player # make() -> object with write(pcm bytes), drain(), close(); 24 kHz mono s16
+ self.loudness = LoudnessLog()
+ self._listeners = []
+ self._source = None
+ self._audio = None
+ self._work: queue.Queue = queue.Queue()
+ self._gen = 0 # bumped by cancel(): sentences queued before it are never spoken
+ self._pool = ThreadPoolExecutor(max_workers=3, thread_name_prefix="Interpret")
+ self._worker = None
+ self._feeder = None
+ self.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.level = 0.0
+ self.spoken = 0
+ self._me = 0
+
+ def on_change(self, listener) -> None:
+ self._listeners.append(listener)
+
+ def _changed(self) -> None:
+ for l in list(self._listeners):
+ l()
+
+ # Languages
+
+ @property
+ def source(self) -> str:
+ return self.settings.speak_from_code
+
+ @property
+ def target(self) -> str:
+ """What the room hears: "room" follows the language they have been speaking."""
+ to = self.settings.speakTo
+ if to != "room":
+ return to
+ heard = self.listen.spoken if self.listen is not None else None
+ if heard and voicemod.key(heard) != voicemod.key(self.source):
+ return heard
+ return "en" if voicemod.key(self.source) != "en" else "zh-CN"
+
+ def voice(self, code: str) -> str | None:
+ chosen = (self.settings.speakVoices or {}).get(voicemod.key(code))
+ names = [v for v, _n, _t in voicemod.voices(code)]
+ return chosen if chosen in names else voicemod.default_voice(code)
+
+ # Running
+
+ def start(self, mic) -> None:
+ if self.active:
+ return
+ self.active = True
+ self.stage = "hearing"
+ self.problem = None
+ self.last = None # the strip starts empty, not on a sentence from an earlier time
+ segmenter = Segmenter()
+ gen = self._gen
+ audio: queue.Queue = queue.Queue()
+ self._audio = audio
+
+ def 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)))
+ segmenter.on_segment = emitted
+
+ def feed():
+ while True:
+ buf = audio.get()
+ if buf is _END:
+ break
+ segmenter.feed(buf)
+ self.level = Wav.rms(buf)
+ segmenter.flush()
+ self._feeder = threading.Thread(target=feed, name="SpeakFeed", daemon=True)
+ self._feeder.start()
+ if self._worker is None or not self._worker.is_alive():
+ self._worker = threading.Thread(target=self._run, name="Speak", daemon=True)
+ self._worker.start()
+ self._source = mic
+ mic.on_samples = audio.put
+ mic.start()
+ Log.d("speak: started %s -> %s" % (self.source, self.target))
+ self._changed()
+
+ def stop(self) -> None:
+ if not self.active:
+ return
+ self.active = False
+ if self._source is not None:
+ self._source.on_samples = None
+ self._source.stop()
+ if self._audio is not None:
+ self._audio.put(_END)
+ Log.d("speak: stopped, %d sentences spoken" % self.spoken)
+ 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 += 1
+ self.stop()
+
+ def _run(self) -> None:
+ while True:
+ gen, seg, job = self._work.get()
+ try:
+ if gen != self._gen:
+ Log.d("speak: segment %d dropped, cancelled before it was said" % seg.index)
+ continue
+ self._say(seg, job.result(), gen)
+ except Exception as e: # noqa: BLE001 - one bad sentence never stops the next
+ Log.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):
+ """(original, translation, source, target, ended, voice chunks) or None, on the pool."""
+ listening = self.listen is not None and self.listen.listening
+ if listening and not self.settings.speakHeadphones and self.loudness.fraction(start, end) > self.ECHO:
+ 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
+ source, target = self.source, self.target
+ if self.voice(target) is None:
+ self.problem = strings.L("这种语言还没有可用的声音")
+ return None
+ self.stage = "interpreting"
+ self._changed()
+ try:
+ heard = self.translator.interpret(Wav.bytes(seg.samples), source, target)
+ except LingError as e:
+ Log.d("speak: interpret failed %s" % e)
+ heard = None
+ if 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 None
+ original, translation = heard
+ # 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:
+ chunks: queue.Queue = queue.Queue()
+
+ def run():
+ try:
+ for pcm in self.ling.speech(text, voice=self.voice(target), language=voicemod.ming_language(target)):
+ chunks.put(pcm)
+ chunks.put(_END)
+ except LingError as e:
+ chunks.put(e)
+ except Exception as e: # noqa: BLE001
+ chunks.put(LingError(LingError.NETWORK))
+ Log.d("speak: voice fetch failed %s" % type(e).__name__)
+ threading.Thread(target=run, name="SpeakVoice", daemon=True).start()
+ return chunks
+
+ def _say(self, seg, interpreted, gen: int = 0) -> None:
+ if interpreted is None:
+ return
+ original, translation, source, target, ended, chunks = interpreted
+ self.problem = None
+ self.last = (original, translation)
+ self.stage = "speaking"
+ self._changed()
+ n = 0
+ played = 0
+ lag = None
+ out = self.player() if self.player else None
+ try:
+ while True:
+ pcm = chunks.get(timeout=30)
+ if pcm is _END or gen != self._gen:
+ break # finished, or stopped mid-sentence
+ if isinstance(pcm, LingError):
+ raise pcm
+ if lag is None:
+ lag = time.monotonic() - ended # what the room waits: end of my sentence → its voice
+ if out is not None:
+ out.write(pcm)
+ n += 1
+ played += len(pcm)
+ if out is not None:
+ out.drain()
+ except (LingError, queue.Empty) as e:
+ Log.d("speak: voice failed %s" % e)
+ self.problem = strings.L("连不上 Ling")
+ finally:
+ if out is not None:
+ out.close()
+ if n:
+ self.spoken += 1
+ Log.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:
+ return
+ sid = self.listen.session_id
+ s = self.store.get(sid)
+ if s is None:
+ return
+ self._me += 1
+ t = round(max(0.0, (datetime.now(timezone.utc) - s.startedAt).total_seconds() - ago), 3)
+ self.store.append(sid, TranscriptLine(id="m%d" % self._me, t=t, speaker="me", src=original, dst=translation,
+ srcLang=source, dstLang=target))
diff --git a/linux/cicada/core/speakers.py b/linux/cicada/core/speakers.py
new file mode 100644
index 0000000..f7b136e
--- /dev/null
+++ b/linux/cicada/core/speakers.py
@@ -0,0 +1,459 @@
+"""说话人识别: 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 annotations
+
+import copy
+import ctypes
+import json
+import os
+import platform
+import threading
+
+from . import strings
+from .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__))))
+
+
+def library_path() -> str | None:
+ env = os.environ.get("CICADA_VOICE_LIB")
+ if env:
+ return env if os.path.isfile(env) else None
+ name = "libcicada-voice.dylib" if platform.system() == "Darwin" else "libcicada-voice-%s.so" % platform.machine()
+ for folder in ("lib", os.path.join("native", "out")):
+ p = os.path.join(_root(), folder, name)
+ if os.path.isfile(p):
+ return p
+ return None
+
+
+def model_path() -> str | None:
+ p = os.path.join(_root(), "models", "voiceprint.bin")
+ return p if os.path.isfile(p) else None
+
+
+class Voiceprints:
+ MIN_SECONDS = 0.5
+ DIMS = 256
+
+ def __init__(self, lib, model):
+ self._lib = lib
+ self._model = model
+ self._lock = threading.Lock() # one at a time: each already uses up to four cores
+
+ @staticmethod
+ def load() -> "Voiceprints | None":
+ lib_file, weights = library_path(), model_path()
+ if lib_file is None or weights is None:
+ Log.d("speakers: no voiceprint %s" % ("library" if lib_file is None else "model"))
+ return None
+ try:
+ lib = ctypes.CDLL(lib_file)
+ except OSError as e:
+ Log.d("speakers: voiceprint library failed to load (%s)" % e)
+ return None
+ lib.cvp_load.restype = ctypes.c_void_p
+ lib.cvp_load.argtypes = [ctypes.c_char_p]
+ lib.cvp_embed_s16.restype = ctypes.c_int
+ lib.cvp_embed_s16.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]
+ model = lib.cvp_load(weights.encode())
+ if not model:
+ Log.d("speakers: voiceprint model failed to load")
+ return None
+ 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
+ buf = (ctypes.c_int16 * n).from_buffer_copy(samples.tobytes() if hasattr(samples, "tobytes") else bytes(samples))
+ out = (ctypes.c_float * self.DIMS)()
+ with self._lock:
+ ok = self._lib.cvp_embed_s16(self._model, buf, n, out, 0) == 0
+ 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.0
+ JOIN = 0.5
+ START_NEW = 0.5
+
+ def __init__(self):
+ 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:
+ return
+ self.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
+
+ def label(self, v: list, seconds: float) -> int | None:
+ best, best_sim = -1, -1.0
+ for i, s in enumerate(self.sums):
+ dot = sum(a * b for a, b in zip(v, s))
+ sq = sum(b * b for b in s)
+ sim = dot / max(sq ** 0.5, 1.1920929e-07)
+ if sim > best_sim:
+ best_sim, best = sim, i
+ if best >= 0 and best_sim >= self.JOIN:
+ self.sums[best] = [a + b for a, b in zip(self.sums[best], v)]
+ return best
+ if seconds >= self.NEW_SECONDS and (not self.sums or best_sim < self.START_NEW):
+ self.sums.append(list(v))
+ return len(self.sums) - 1
+ return None
+
+
+class Tagger:
+ """Voiceprints on their own thread (while Ming hears the same segment), labelled in arrival order."""
+
+ def __init__(self):
+ self._model = None
+ self._tried = False
+ self._load_lock = threading.Lock()
+ self.clusterer = VoiceClusterer()
+ self._gate = threading.Lock()
+
+ @property
+ def available(self) -> bool:
+ return self.model() is not None
+
+ def model(self):
+ with self._load_lock:
+ if not self._tried:
+ self._tried = True
+ self._model = Voiceprints.load()
+ return self._model
+
+ def reset(self) -> None:
+ """A new meeting: forget the voices of the last one."""
+ with self._gate:
+ self.clusterer = VoiceClusterer()
+
+ def merge(self, frm: int, into: int) -> None:
+ with self._gate:
+ self.clusterer.merge(frm, into)
+
+ def embed(self, samples):
+ m = self.model()
+ return m.embed(samples) if m is not None else None
+
+ def label(self, vector, seconds: float) -> int | None:
+ if vector is None:
+ return None
+ with self._gate:
+ return self.clusterer.label(vector, seconds)
+
+
+# What the transcript shows (SpeakerLabels)
+
+SHOWN_AFTER = 5
+
+
+def _cjk(c: str) -> bool:
+ o = ord(c)
+ return (0x3400 <= o <= 0x4DBF or 0x4E00 <= o <= 0x9FFF or 0xF900 <= o <= 0xFAFF or 0x20000 <= o <= 0x3FFFF
+ or 0x3040 <= o <= 0x30FF or 0xAC00 <= o <= 0xD7A3 or o in (0x3005, 0x3006, 0x3007))
+
+
+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 True
+ return sum(1 for c in text if _cjk(c)) >= 4
+
+
+def 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):
+ continue
+ count[l.voice] = count.get(l.voice, 0) + 1
+ if count[l.voice] == SHOWN_AFTER:
+ reached[l.voice] = i
+ shown = sorted(reached, key=lambda v: reached[v])
+ if len(shown) < 2:
+ return {}
+ return {v: n + 1 for n, v in enumerate(shown)}
+
+
+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 = {}
+ for v, n in voice_numbers(s.lines).items():
+ mine = (s.voiceNames or {}).get(str(v))
+ if mine is not None:
+ if mine:
+ out[n] = mine
+ elif (s.voiceGuesses or {}).get(str(v)) is not None:
+ out[n] = s.voiceGuesses[str(v)].name
+ return out
+
+
+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:
+ out[n] = s.voiceGuesses[str(v)]
+ return out
+
+
+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(), None
+ for l in lines:
+ key = "me" if l.speaker == "me" else ("n%d" % nums[l.id] if l.id in nums else "?")
+ if key != last:
+ out.add(l.id)
+ last = key
+ return out
+
+
+def label(number: int, shown: dict) -> str:
+ """"George", else "说话人 2"."""
+ return shown.get(number) or strings.LF("说话人 %lld", number)
+
+
+def speaker_name(line, nums: dict, shown: dict) -> str:
+ """你, 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:
+ return label(nums[line.id], shown)
+ return strings.L("对方") if not nums else strings.L("未识别")
+
+
+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 notes
+
+ def 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 form in ("说话人 %d" % n, "说话人%d" % n, "Speaker %d" % n):
+ text = text.replace(form, name)
+ return text
+ n = copy.deepcopy(notes)
+ n.summary = swap(n.summary)
+ for t in n.topics:
+ t.title, t.summary = swap(t.title), swap(t.summary)
+ t.points = [swap(p) for p in t.points]
+ for c in n.conclusions:
+ c.text, c.owner = swap(c.text), swap(c.owner)
+ for t in n.todos:
+ t.text, t.owner = swap(t.text), swap(t.owner)
+ return n
+
+
+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"]
+
+
+def people(terms) -> list:
+ return [t.name for t in terms if any(r.lower() in (t.note or "").lower() for r in ROLES)]
+
+
+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)
+ taken = {v for k, v in shown.items() if k != number}
+ out = []
+ g = (s.voiceGuesses or {}).get(str(voice))
+ if g is not None:
+ out.append(g.name)
+ for t in people(s.notes.terms if s.notes else []):
+ if t not in out and t not in taken:
+ out.append(t)
+ mine = shown.get(number)
+ if mine and mine not in out:
+ out.insert(0, mine)
+ 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 "
+ "before or after they speak (\"Thanks, George\" right after 说话人1's answer: 说话人1 is George); "
+ "or others name them as they speak. A name on a 对方 line, or far from any line of 说话人N (an advert, "
+ "a clip, people introducing themselves on another show), is not theirs. Speech recognition writes "
+ "names by ear and often misspells them: for a public figure (an official, an executive, a presenter) "
+ "recognisable from the name and what is said, write the name as the news spells it (\"Jensen Hwang\" "
+ "→ \"Jensen Huang\"); otherwise as written. Leave out anyone "
+ "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
+
+
+def 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
+ out = ["Meeting transcript. Speakers: 你 = the user; 说话人N = one person on the other side, told apart by voice; "
+ "对方 = someone on the other side, not identified.\n"]
+ for i, l in enumerate(s.lines[-400:]):
+ who = "你" if l.speaker == "me" else ("说话人%d" % nums[l.id] if l.id in nums else "对方")
+ out.append("[L%d %s %s] %s\n" % (i + 1, clock(l.t), who, l.src))
+ return "".join(out)
+
+
+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
+ try:
+ obj = json.loads(reply)
+ except ValueError:
+ return {}, {}
+ lst = obj.get("speakers") if isinstance(obj, dict) else None
+ if not isinstance(lst, list):
+ return {}, {}
+ voice_of = {n: v for v, n in voice_numbers(s.lines).items()}
+ lines = s.lines[-400:]
+
+ def count(v):
+ return sum(1 for l in s.lines if l.voice == v)
+ found, refuted = {}, {}
+ for item in lst:
+ if not isinstance(item, dict):
+ continue
+ try:
+ n = int(str(item.get("speaker")))
+ except ValueError:
+ continue
+ v = voice_of.get(n)
+ name = item.get("name")
+ if v is None or not isinstance(name, str) or not name.strip() or len(name.strip()) > 40:
+ continue
+ name = name.strip()
+ e = str(item.get("evidence", ""))
+ digits = ""
+ for c in e[next((k for k, c in enumerate(e) if c.isdigit()), len(e)):]:
+ if not c.isdigit():
+ break
+ digits += c
+ i = int(digits) - 1 if digits else -1
+ near = lines[max(0, i - EVIDENCE_REACH):i + EVIDENCE_REACH + 1] if 0 <= i < len(lines) else []
+ if not any(l.speaker == "them" and l.voice == v for l in near):
+ refuted[v] = name
+ continue
+ other = next((k for k, g in found.items() if g.name == name), None)
+ if other is not None:
+ if count(other) >= count(v):
+ continue
+ del found[other]
+ l = lines[i]
+ quote = l.src[:60] + "…" if len(l.src) > 60 else l.src
+ found[v] = VoiceGuess(name, "%s “%s”" % (clock(l.t), quote))
+ return found, refuted
+
+
+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 True
+ at, quote = g.evidence.split("“", 1)
+ at = at.strip()
+ quote = quote[:-1] if quote.endswith("”") else quote
+ quote = quote.split("…")[0]
+ for i, l in enumerate(s.lines):
+ if clock(l.t) == at and l.src.startswith(quote):
+ return any(x.speaker == "them" and x.voice == v
+ for x in s.lines[max(0, i - EVIDENCE_REACH):i + EVIDENCE_REACH + 1])
+ return True
+
+
+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 = ling
+ self.store = store
+ self.changed = changed
+ self.busy: set = set()
+ self._asked: dict = {}
+ self._gate = threading.Lock()
+
+ def guess(self, sid: str, force: bool = False) -> None:
+ from .ling import NOTES, LingError
+ s = self.store.get(sid)
+ if s is None or not self.ling.has_key:
+ return
+ with self._gate:
+ if sid in self.busy or not (force or len(s.lines) >= self._asked.get(sid, -1000) + 20):
+ return
+ text = content(s)
+ if text is None:
+ return
+ nums = 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
+ self.busy.add(sid)
+ self._asked[sid] = len(s.lines)
+
+ def run():
+ try:
+ reply = self.ling.chat(text, INSTRUCTION, NOTES, json=True, max_tokens=300)
+ found, refuted = read(reply, s)
+ for key, g in (s.voiceGuesses or {}).items():
+ try:
+ v = int(key)
+ except ValueError:
+ continue
+ if v not in found and not holds(g, v, s):
+ refuted[v] = g.name
+ self.store.set_voice_guesses(sid, found, refuted)
+ Log.d("speakers: names %d found, %d without evidence" % (len(found), len(refuted)))
+ except LingError as e:
+ Log.d("speakers: names, ling failed %s" % e)
+ finally:
+ with self._gate:
+ self.busy.discard(sid)
+ if self.changed:
+ self.changed()
+ threading.Thread(target=run, name="SpeakerNames", daemon=True).start()
diff --git a/linux/cicada/core/strings.py b/linux/cicada/core/strings.py
new file mode 100644
index 0000000..539b431
--- /dev/null
+++ b/linux/cicada/core/strings.py
@@ -0,0 +1,102 @@
+"""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. Placeholders are the Mac's `%@`, filled in order (or `%1$@`).
+Never for prompts, logs or stored values."""
+from __future__ import annotations
+
+import os
+
+_table: dict = {}
+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, language
+ head = ui.replace("_", "-").split("-")[0]
+ language = head if head in ("en", "ja", "ko") else "zh-Hans"
+ t: dict = {}
+ for folder in folders:
+ for name in ("Localizable.strings", "Linux.strings"):
+ path = os.path.join(folder, language + ".lproj", name)
+ if os.path.isfile(path):
+ with open(path, encoding="utf-8") as f:
+ t.update(parse(f.read()))
+ _table = t
+
+
+def L(key: str) -> str:
+ v = _table.get(key)
+ return v if v else key
+
+
+def LF(key: str, *args) -> str:
+ """L() with the Mac's `%@` placeholders, filled in order."""
+ text = L(key)
+ out = []
+ nxt = 0
+ i = 0
+ while i < len(text):
+ # %@, and the Mac's numbers (%lld, %d) the same way: the Mac keys 说话人 N as "说话人 %lld".
+ m = next((t for t in ("%@", "%lld", "%d") if text.startswith(t, i)), None)
+ if m:
+ out.append(str(args[nxt]) if nxt < len(args) else "")
+ nxt += 1
+ i += len(m)
+ continue
+ if text[i] == "%" and i + 3 < len(text) and text[i + 1].isdigit() and text[i + 2] == "$":
+ spec = next((t for t in ("@", "lld", "d") if text.startswith(t, i + 3)), None)
+ if spec:
+ n = int(text[i + 1]) - 1
+ out.append(str(args[n]) if 0 <= n < len(args) else "")
+ i += 3 + len(spec)
+ continue
+ out.append(text[i])
+ i += 1
+ return "".join(out)
+
+
+def parse(text: str) -> dict:
+ """`"key" = "value";` lines, with /* */ and // comments and \\" \\\\ \\n escapes."""
+ result = {}
+ i = 0
+ n = len(text)
+
+ def read():
+ nonlocal i
+ while i < n:
+ if text[i] == '"':
+ break
+ if text.startswith("/*", i):
+ e = text.find("*/", i + 2)
+ i = n if e < 0 else e + 2
+ continue
+ if text.startswith("//", i):
+ e = text.find("\n", i)
+ i = n if e < 0 else e + 1
+ continue
+ i += 1
+ if i >= n:
+ return None
+ i += 1
+ b = []
+ while i < n and text[i] != '"':
+ if text[i] == "\\" and i + 1 < n:
+ i += 1
+ b.append({"n": "\n", "t": "\t"}.get(text[i], text[i]))
+ else:
+ b.append(text[i])
+ i += 1
+ i += 1
+ return "".join(b)
+
+ while True:
+ k = read()
+ if k is None:
+ break
+ v = read()
+ if v is None:
+ break
+ result[k] = v
+ return result
diff --git a/linux/cicada/core/support.py b/linux/cicada/core/support.py
new file mode 100644
index 0000000..99e9324
--- /dev/null
+++ b/linux/cicada/core/support.py
@@ -0,0 +1,204 @@
+"""Paths, the debug log and languages."""
+from __future__ import annotations
+
+import os
+import tempfile
+import threading
+import sys
+from datetime import datetime
+
+
+class 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
+
+ @classmethod
+ def _name(cls) -> str:
+ return "cicada-dev" if cls.dev else "cicada"
+
+ @classmethod
+ def _home(cls) -> str | None:
+ return cls.home_override or os.environ.get("CICADA_HOME") or None
+
+ @classmethod
+ def data(cls) -> str:
+ h = cls._home()
+ if h:
+ return h
+ base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
+ return os.path.join(base, cls._name())
+
+ @classmethod
+ def config(cls) -> str:
+ h = cls._home()
+ if h:
+ return h
+ base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
+ return os.path.join(base, cls._name())
+
+ @classmethod
+ def sessions(cls) -> str:
+ return os.path.join(cls.data(), "Sessions")
+
+ @classmethod
+ def settings(cls) -> str:
+ return os.path.join(cls.config(), "settings.json")
+
+ @classmethod
+ def key_file(cls) -> str:
+ return os.path.join(cls.config(), "ling-api-key")
+
+ log_override: str | None = None
+
+ @classmethod
+ def 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_override
+ h = cls._home()
+ if h:
+ return os.path.join(h, "debug.log")
+ base = os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state")
+ folder = os.path.join(base, cls._name())
+ try:
+ os.makedirs(folder, mode=0o700, exist_ok=True)
+ except OSError:
+ return os.path.join(tempfile.gettempdir(), cls._name() + "-debug.log")
+ return os.path.join(folder, "debug.log")
+
+
+class Log:
+ """The debug log: timings and states, never meeting text or the key."""
+ _gate = threading.Lock()
+ echo = False
+
+ @classmethod
+ def d(cls, message: str) -> None:
+ line = datetime.now().strftime("%H:%M:%S.%f")[:-3] + " " + message
+ with cls._gate:
+ try:
+ with open(Paths.log(), "a", encoding="utf-8") as f:
+ f.write(line + "\n")
+ except OSError:
+ pass
+ if cls.echo:
+ 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"),
+ ("한국어", "ko"), ("Español", "es"), ("Français", "fr"), ("Deutsch", "de"), ("Português", "pt")]
+
+_ENGLISH = {"zh-CN": "Simplified Chinese", "zh-TW": "Traditional Chinese", "zh": "Chinese", "en": "English",
+ "ja": "Japanese", "ko": "Korean", "es": "Spanish", "fr": "French", "de": "German", "pt": "Portuguese",
+ "it": "Italian", "ru": "Russian", "ar": "Arabic", "hi": "Hindi", "th": "Thai", "vi": "Vietnamese",
+ "id": "Indonesian", "ms": "Malay", "tr": "Turkish", "nl": "Dutch", "pl": "Polish", "sv": "Swedish",
+ "uk": "Ukrainian", "he": "Hebrew", "el": "Greek", "cs": "Czech", "da": "Danish", "fi": "Finnish",
+ "no": "Norwegian", "hu": "Hungarian", "ro": "Romanian", "yue": "Cantonese"}
+
+
+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 code
+
+
+def 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"
+ return "zh-TW" if any(p in ("Hant", "TW", "HK", "MO") for p in parts) else "zh-CN"
+
+
+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(":"):
+ if v and v not in ("C", "POSIX", "C.UTF-8") and v not in out:
+ out.append(v)
+ return out or ["en_US"]
+
+
+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
+ return next((c for c in map(from_system, prefs) if c != mine), "en" if mine.startswith("zh") else "zh-CN")
+
+
+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"):
+ return v.split(":")[0]
+ return "en_US"
+
+
+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 fallback
+ r = reported.strip().strip('.`"')
+ head = r.replace("_", "-").split("-")[0].lower()
+ if head in ("zh", "cmn", "yue"):
+ return "zh-TW" if "tw" in r.lower() or "hant" in r.lower() else "zh-CN"
+ return head if len(head) in (2, 3) else fallback
+
+
+def _is_cjk(c: str) -> bool:
+ cp = ord(c)
+ return 0x3040 <= cp <= 0x9FFF or 0xAC00 <= cp <= 0xD7AF
+
+
+def _count(text: str):
+ letters = cjk = 0
+ for c in text:
+ if c.isalpha():
+ letters += 1
+ if _is_cjk(c):
+ cjk += 1
+ return letters, cjk
+
+
+def is_cjk_language(code: str) -> bool:
+ return code.startswith(("zh", "ja", "ko"))
+
+
+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
+ return cjk > 0 if is_cjk_language(target) else cjk * 2 <= letters
+
+
+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 True
+ wants = any(w in english_language for w in ("Chinese", "Japanese", "Korean"))
+ return cjk * 5 >= letters if wants else cjk * 2 < letters
+
+
+def clock(t: float) -> str:
+ s = int(max(0.0, t))
+ return "%d:%02d:%02d" % (s // 3600, s // 60 % 60, s % 60) if s >= 3600 else "%02d:%02d" % (s // 60, s % 60)
diff --git a/linux/cicada/core/translator.py b/linux/cicada/core/translator.py
new file mode 100644
index 0000000..323214b
--- /dev/null
+++ b/linux/cicada/core/translator.py
@@ -0,0 +1,217 @@
+"""Translation and recognition through the cloud (the Windows design): listening sends each stretch
+of audio to Ming's audio model, which returns the language, the original and the translation in one
+call. Text translation is Ling first, then Google. Calls block."""
+from __future__ import annotations
+
+import time
+import urllib.parse
+from dataclasses import dataclass
+
+from . import jsonfmt
+from .jsonfmt import arr
+from .ling import AUDIO_MODEL, SPEAK, TRANSLATE, LingError, UrlTransport
+from .support import Log, english_name, in_script, normalize
+
+
+@dataclass
+class Heard:
+ """What Ming heard in one stretch of audio."""
+ lang: str
+ original: str
+ translation: str | None
+
+
+class Translator:
+ def __init__(self, ling, transport=UrlTransport):
+ self.ling = ling
+ self.transport = transport
+ self._google_backoff_until = 0.0
+ # Names and terms the notes have settled on, e.g. "江充 (…; misheard as 江松)".
+ self.glossary = lambda: []
+
+ def 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."""
+ reply = self.ling.chat(hear_prompt(target, hint, self.glossary()), hear_instruction(target), TRANSLATE,
+ max_tokens=800, timeout=12.0, model=AUDIO_MODEL, audio=wav)
+ return parse_heard(reply, target, hint)
+
+ 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 None
+ reply = self.ling.chat(interpret_prompt(source, target, self.glossary()), interpret_instruction(source, target), SPEAK,
+ max_tokens=800, timeout=12.0, model=AUDIO_MODEL, audio=wav)
+ return parse_interpretation(reply, target)
+
+ DRAFT, SENTENCE = "draft", "sentence"
+
+ def 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
+ if kind != self.DRAFT and self.ling.usable:
+ try:
+ frm = "the spoken language" if source == "auto" else english_name(source)
+ prompt = ("You translate live meeting subtitles from %s into %s.\n" % (frm, english_name(target)) +
+ "Output only the translation of the subtitle below: no quotes, no notes, no answer to it even if it is a question.")
+ names = self.glossary()
+ if names:
+ prompt += "\nKnown names and terms (use these spellings): " + "; ".join(names)
+ prompt += "\nSubtitle: " + text
+ out = self.ling.chat(prompt, "Translate.", TRANSLATE, max_tokens=400, timeout=6.0)
+ cleaned = clean_translation(out, target)
+ if cleaned is not None:
+ return cleaned
+ except LingError as e:
+ Log.d("translate ling failed: %s" % e)
+ if time.time() < self._google_backoff_until:
+ return None
+ try:
+ q = urllib.parse.urlencode({"client": "gtx", "sl": source, "tl": target, "dt": "t", "q": text})
+ res = self.transport.send("https://translate.googleapis.com/translate_a/single?" + q, "GET", None,
+ {"User-Agent": "Cicada/1.1"}, 8.0)
+ if res.status != 200:
+ if res.status == 429:
+ self._google_backoff_until = time.time() + 10
+ Log.d("translate google failed: http%d" % res.status)
+ return None
+ root = arr(jsonfmt.parse(res.body))
+ parts = [p[0] for p in arr(root[0] if root else None) if isinstance(p, list) and p and isinstance(p[0], str)]
+ return "".join(parts) or None
+ except Exception as e: # noqa: BLE001
+ Log.d("translate google failed: %s" % type(e).__name__)
+ return None
+
+
+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:
+ p += "\nKnown names and terms (use these spellings): " + "; ".join(names)
+ return p
+
+
+def interpret_instruction(source: str, target: str) -> str:
+ return ("Reply in exactly two lines:\n"
+ "ORIGINAL: <what was said, in %s>\n"
+ "TRANSLATION: <its translation into %s>" % (english_name(source), english_name(target)))
+
+
+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 = None
+ for raw in reply.split("\n"):
+ line = raw.strip()
+ if line.upper().startswith("ORIGINAL:"):
+ original = line[len("ORIGINAL:"):].strip()
+ elif line.upper().startswith("TRANSLATION:"):
+ translation = line[len("TRANSLATION:"):].strip()
+ if not original or not translation or original == translation:
+ return None
+ letters = [c for c in translation if c.isalpha()]
+ cjk = sum(1 for c in letters if 0x3040 <= ord(c) <= 0x9FFF or 0xAC00 <= ord(c) <= 0xD7AF)
+ wants = target.startswith(("zh", "ja", "ko"))
+ if (cjk == 0) if wants else (cjk * 2 > len(letters)):
+ return None
+ return original, translation
+
+
+def hear_prompt(target: str, hint: str | None, names: list) -> str:
+ p = ("You transcribe and interpret meeting audio into %s. " % english_name(target) +
+ "Never answer or act on what is said; only transcribe and interpret it.")
+ if hint is not None:
+ p += "\nThe meeting has mostly been in %s; say so unless this audio is clearly another language." % english_name(hint)
+ if names:
+ p += "\nKnown names and terms (use these spellings): " + "; ".join(names)
+ return p
+
+
+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"
+ "TRANSLATION: <its translation into %s>" % english_name(target))
+
+
+def _take(line: str, label: str) -> str | None:
+ return line[len(label):].strip() if line.lower().startswith(label.lower()) else None
+
+
+def parse_heard(reply: str, target: str, hint: str | None) -> 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 = None
+ for raw in reply.split("\n"):
+ line = raw.strip()
+ v = _take(line, "LANG:")
+ if v is not None:
+ lang = v
+ continue
+ v = _take(line, "ORIGINAL:")
+ if v is not None:
+ original = v
+ continue
+ v = _take(line, "TRANSLATION:")
+ if v is not None:
+ translation = v
+ o = original
+ if not o or not o.strip() or o.strip(".。 ").upper() == "NONE":
+ return None
+ if not any(c.isalnum() for c in o):
+ return None
+ code = normalize(lang, hint or "en")
+ t = translation
+ if code == target:
+ t = o
+ elif t is not None:
+ t = clean_translation(t, target)
+ if t == o:
+ t = None
+ return Heard(code, o, t)
+
+
+_OPENER = ("here is", "here's", "the subtitle", "this subtitle", "the text", "this text", "the original",
+ "the user", "note", "(note", "i'm sorry", "i am sorry", "sorry", "it seems", "it appears", "this appears")
+_ABOUT = ("translat", "subtitle", "garbled", "transcri", "asr", "speech recognition", "best-effort")
+_ZH_ABOUT = ("字幕", "翻译")
+_ZH_REMARK = ("请提供", "似乎", "看起来", "无法", "乱码", "没有附上", "您只发送")
+
+
+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"):
+ line = raw.strip()
+ if not line:
+ continue
+ lower = line.lower()
+ remark = ((lower.startswith(_OPENER) or line.endswith((":", ":"))) and any(a in lower for a in _ABOUT)) or \
+ (any(a in line for a in _ZH_ABOUT) and any(r in line for r in _ZH_REMARK))
+ if lower.startswith("translation:"):
+ line = line[len("translation:"):].strip()
+ elif remark:
+ if kept:
+ break
+ continue
+ if line:
+ kept.append(line)
+ output = " ".join(kept)
+ for o, c in (('"', '"'), ("“", "”"), ("「", "」")):
+ if len(output) >= 2 and output.startswith(o) and output.endswith(c) and o not in output[1:-1]:
+ output = output[1:-1]
+ output = output.strip()
+ if not output:
+ return None
+ return output if in_script(output, target) else None
diff --git a/linux/cicada/core/voices.py b/linux/cicada/core/voices.py
new file mode 100644
index 0000000..a2b8d37
--- /dev/null
+++ b/linux/cicada/core/voices.py
@@ -0,0 +1,39 @@
+"""Ming's voices for what the room hears (Voices.swift › VoiceCatalog.ming): hand-picked natural
+ones per language; for languages Ming has no native voice for, Emma and George speak them with
+`language_id`. Linux has no system voice worth sending into a meeting, so only these."""
+from __future__ import annotations
+
+
+def key(code: str) -> str:
+ """"zh" for zh-CN / zh-TW, "en" for en-US."""
+ return (code or "en").split("-")[0].lower() or "en"
+
+
+def ming_language(code: str) -> str | None:
+ k = key(code)
+ 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", ["女", "英式", "平稳"])],
+ "zh": [("灵小雅", "小雅", ["女", "清亮", "播报"]), ("灵小棠", "小棠", ["女", "温和", "沉稳"]),
+ ("灵小锋", "小锋", ["男", "温暖", "亲切"]), ("灵卓然", "卓然", ["男", "沉着", "清楚"])],
+}
+_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) -> list:
+ k = key(code)
+ if k in _CATALOG:
+ return _CATALOG[k]
+ return _OTHER if k in ("ja", "ko", "de", "fr", "es") else []
+
+
+def default_voice(code: str) -> str | None:
+ v = voices(code)
+ return v[0][0] if v else None
diff --git a/linux/cli.py b/linux/cli.py
new file mode 100755
index 0000000..e0e74f9
--- /dev/null
+++ b/linux/cli.py
@@ -0,0 +1,194 @@
+#!/usr/bin/env python3
+"""cicada-cli: the Linux engines without the desktop (runs on the Mac too).
+
+ cli.py listen <file.wav> [--target zh-CN] [--speed 1|0] [--notes] [--log]
+ Plays the file into ListenEngine as if the speakers were playing it, prints each line as it is
+ recorded, then the record's folder. --notes waits for the final notes and prints them.
+ cli.py hear <file.wav> [--target zh-CN] one file to Ming, raw reply printed
+ cli.py speak <file.wav> [--from zh-CN] [--to en] [--out out.wav]
+ 同声传译 on a recording: each sentence interpreted, voiced by Ming, written to --out (24 kHz)
+ cli.py segments <file.wav> where the segmenter cuts
+ cli.py roundtrip <session.json>… [--diff] reads and writes records, says if a byte changed
+
+Records go to CICADA_HOME (default: a temp folder). The key comes from CICADA_KEY_FILE, else this
+app's own key file, else the Mac app's; it is never printed."""
+from __future__ import annotations
+
+import os
+import sys
+import tempfile
+import threading
+import time
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+
+from cicada.core import strings # noqa: E402
+from cicada.core.audio import PcmAudioSource, Wav # noqa: E402
+from cicada.core.ling import AUDIO_MODEL, TRANSLATE, AIKey, LingClient # noqa: E402
+from cicada.core.listen import ListenEngine # noqa: E402
+from cicada.core.models import Session # noqa: E402
+from cicada.core.notes import NotesEngine # noqa: E402
+from cicada.core.segmenter import Segmenter # noqa: E402
+from cicada.core.session_store import SessionStore # noqa: E402
+from cicada.core.settings import AppSettings # noqa: E402
+from cicada.core.support import Log, Paths, clock # noqa: E402
+from cicada.core.translator import Translator, hear_instruction, hear_prompt, parse_heard # noqa: E402
+
+
+def key_file() -> str | None:
+ env = os.environ.get("CICADA_KEY_FILE")
+ if env:
+ return env
+ for p in (os.path.expanduser("~/.config/cicada/ling-api-key"),
+ os.path.expanduser("~/Library/Application Support/LiveSubs Dev/ling-api-key"),
+ os.path.expanduser("~/Library/Application Support/LiveSubs/ling-api-key")):
+ if os.path.isfile(p):
+ return p
+ return None
+
+
+def main(args: list) -> int:
+ if not args:
+ print(__doc__)
+ return 2
+
+ def opt(name, fallback):
+ return args[args.index(name) + 1] if name in args and args.index(name) + 1 < len(args) else fallback
+ strings.load(opt("--ui", "zh-Hans"), [os.path.join(HERE, "..", "Resources"), os.path.join(HERE, "strings")])
+ cmd = args[0]
+ if cmd == "segments":
+ pcm = Wav.read_file(args[1])
+ got = []
+ seg = Segmenter()
+ seg.on_segment = got.append
+ for i in range(0, len(pcm), 1600):
+ seg.feed(pcm[i:i + 1600])
+ seg.flush()
+ for s in got:
+ print("%3d %7.2fs %5.2fs" % (s.index, s.start, s.seconds))
+ print("%d segments, %.1fs of speech" % (len(got), sum(s.seconds for s in got)))
+ return 0
+ if cmd == "roundtrip":
+ changed = 0
+ for path in [a for a in args[1:] if not a.startswith("--")]:
+ with open(path, encoding="utf-8") as f:
+ original = f.read()
+ s = Session.read(original)
+ written = s.write() if s else None
+ same = written == original
+ changed += 0 if same else 1
+ print("%s %s (%d lines%s)" % ("same " if same else "CHANGED", path, len(s.lines) if s else 0,
+ ", notes" if s and s.notes else ""))
+ if not same and "--diff" in args and written is not None:
+ a, b = original.split("\n"), written.split("\n")
+ at = next((i for i in range(len(a)) if i >= len(b) or a[i] != b[i]), len(a))
+ print(" first difference at line %d:\n mac: %s\n linux: %s" % (at + 1, a[at] if at < len(a) else None,
+ b[at] if at < len(b) else None))
+ return 0 if changed == 0 else 1
+ if cmd == "hear":
+ ling = LingClient(AIKey(key_file()))
+ target = opt("--target", "zh-CN")
+ r = ling.chat(hear_prompt(target, None, []), hear_instruction(target), TRANSLATE, max_tokens=800, timeout=20.0,
+ model=AUDIO_MODEL, audio=Wav.bytes(Wav.read_file(args[1])))
+ print(r)
+ print("->", parse_heard(r, target, None))
+ return 0
+ if cmd == "speak":
+ import struct
+ from array import array as _array
+ from cicada.core.speak import SpeakEngine
+ Log.echo = "--log" in args
+ key = AIKey(key_file())
+ ling = LingClient(key)
+ settings = AppSettings(target=opt("--from", "zh-CN"), speakTo=opt("--to", "en"))
+ out = bytearray()
+
+ class Collect:
+ def write(self, pcm):
+ out.extend(pcm)
+
+ def drain(self):
+ pass
+
+ def close(self):
+ out.extend(bytes(24000 // 2 * 2)) # half a second between sentences
+ 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()
+ src = PcmAudioSource(args[1], 0)
+ src.on_ended = lambda why: done.set()
+ eng.start(src)
+ done.wait()
+ time.sleep(1)
+ while not eng._work.empty() or eng.stage not in ("hearing", "idle"):
+ time.sleep(0.2)
+ eng.stop()
+ path = opt("--out", "speak-out.wav")
+ pcm = _array("h")
+ pcm.frombytes(bytes(out))
+ with open(path, "wb") as f:
+ f.write(Wav.bytes(pcm, rate=24000))
+ print("%d sentences spoken, %.1f s of voice in %s" % (eng.spoken, len(pcm) / 24000, path))
+ return 0
+ if cmd == "listen":
+ Log.echo = "--log" in args
+ if not os.environ.get("CICADA_HOME"):
+ Paths.home_override = tempfile.mkdtemp(prefix="cicada-cli-")
+ key = AIKey(key_file())
+ if key.read() is None:
+ print("no Ling key (set CICADA_KEY_FILE)")
+ return 2
+ settings = AppSettings(target=opt("--target", "zh-CN"))
+ ling = LingClient(key)
+ store = SessionStore()
+ notes = NotesEngine(ling, store)
+ engine = ListenEngine(ling, Translator(ling), store, notes, settings)
+ shown = {}
+ lock = threading.Lock()
+ started = time.monotonic()
+
+ def changed():
+ sid = engine.session_id
+ if sid is None:
+ return
+ with lock:
+ for l in store.lines(sid):
+ text = "%s\n%s→ %s" % (l.src, " " * 17, l.dst or "…")
+ if shown.get(l.id) == text:
+ continue
+ tag = "upd" if l.id in shown else "new"
+ shown[l.id] = text
+ print("[%5.1f] %s %s %-5s %s" % (time.monotonic() - started, tag, clock(l.t), l.srcLang, text), flush=True)
+ engine.on_change(changed)
+ ended = threading.Event()
+ src = PcmAudioSource(args[1], float(opt("--speed", "1")))
+ src.on_ended = lambda why: ended.set()
+ engine.start(src, "file")
+ ended.wait()
+ time.sleep(1.5)
+ engine.stop()
+ sid = engine.session_id
+ if "--notes" in args:
+ for _ in range(120):
+ s = store.get(sid)
+ if s and s.notes and s.notes.final:
+ break
+ time.sleep(1)
+ store.flush()
+ s = store.get(sid)
+ print("\n%d lines in %s" % (len(s.lines) if s else 0, os.path.join(Paths.sessions(), sid)))
+ if s and s.notes:
+ n = s.notes
+ print("notes%s: %s\n %s" % (" (final)" if n.final else "", n.title, n.summary))
+ for t in n.topics:
+ print(" %s %s: %s" % (clock(t.start), t.title, " / ".join(t.points)))
+ for t in n.todos:
+ print(" [ ] %s (%s)" % (t.text, t.owner))
+ return 0
+ print("unknown command", cmd)
+ return 2
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/linux/models/voiceprint.bin b/linux/models/voiceprint.bin
new file mode 100644
index 0000000..f543469
Binary files /dev/null and b/linux/models/voiceprint.bin differ
diff --git a/linux/native/.gitignore b/linux/native/.gitignore
new file mode 100644
index 0000000..89f9ac0
--- /dev/null
+++ b/linux/native/.gitignore
@@ -0,0 +1 @@
+out/
diff --git a/linux/native/build.sh b/linux/native/build.sh
new file mode 100755
index 0000000..b0c096c
--- /dev/null
+++ b/linux/native/build.sh
@@ -0,0 +1,13 @@
+#!/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 pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+out="${1:-$here/out}"
+mkdir -p "$out"
+if [ "$(uname)" = Darwin ]; then
+ /usr/bin/clang -O3 -Wall -Wextra -shared -fPIC -o "$out/libcicada-voice.dylib" "$here/voiceprint.c"
+else
+ ${CC:-gcc} -O3 -Wall -Wextra -shared -fPIC -pthread -o "$out/libcicada-voice-$(uname -m).so" "$here/voiceprint.c" -lm
+fi
diff --git a/linux/native/voiceprint.c b/linux/native/voiceprint.c
new file mode 100644
index 0000000..1b8aa22
--- /dev/null
+++ b/linux/native/voiceprint.c
@@ -0,0 +1,426 @@
+/* 分出对方的每个人 on Linux: the Mac's voiceprint (WeSpeaker ResNet34-LM, VoxCeleb, CC BY 4.0) without
+ * Core ML. A stock Ubuntu desktop has no BLAS and Python can't run a ResNet in real time, so the model
+ * runs here, built into libcicada-voice.so for each architecture and loaded with ctypes. Our own code:
+ * no third-party library. Weights come from linux/scripts/convert-voiceprint.py.
+ *
+ * The steps match SpeakerID.swift (Fbank, Voiceprints.embed) so a Linux voiceprint is the Mac's:
+ * Kaldi fbank (16 kHz, 25 ms Povey windows every 10 ms, DC removed, pre-emphasis 0.97, 512-point power
+ * spectrum, 80 mel bins 20 Hz to 8 kHz, natural log), per-bin mean removed over the clip, the ResNet
+ * trunk, statistics pooling (mean, unbiased std + 1e-8), the 256-d layer minus mean_vec, unit length. */
+#define _GNU_SOURCE
+#include <math.h>
+#include <float.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#define BINS 80
+#define FRAME 400
+#define SHIFT 160
+#define NFFT 512
+#define COLS (NFFT / 2 + 1)
+#define RATE 16000
+#define MIN_SECONDS 0.5
+#define MAX_SECONDS 20.0
+#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
+#endif
+
+typedef struct {
+ int type; /* 1 conv, 2 add */
+ 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 */
+} Op;
+
+typedef struct {
+ int nops, nslots;
+ Op *ops;
+ int channels, freq, dims;
+ float *fc, *fc_b, *mean;
+ float window[FRAME];
+ float mel[BINS * COLS];
+ float cos_t[NFFT / 2], sin_t[NFFT / 2];
+} Model;
+
+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 */
+ e = 127 - 15 + 1;
+ while (!(m & 0x400)) { m <<= 1; e--; }
+ bits = s | (e << 23) | ((m & 0x3FF) << 13);
+ }
+ } else if (e == 31) bits = s | 0x7F800000 | (m << 13);
+ else bits = s | ((e - 15 + 127) << 23) | (m << 13);
+ float f;
+ memcpy(&f, &bits, 4);
+ return f;
+}
+
+static int read_all(FILE *f, void *p, size_t n) { return fread(p, 1, n, f) == n; }
+
+static float *read_f16(FILE *f, size_t n) {
+ uint16_t *h = malloc(n * 2);
+ float *out = malloc(n * sizeof(float));
+ if (!h || !out || !read_all(f, h, n * 2)) { free(h); free(out); return NULL; }
+ for (size_t i = 0; i < n; i++) out[i] = half(h[i]);
+ free(h);
+ return out;
+}
+
+static float *read_f32(FILE *f, size_t n) {
+ float *out = malloc(n * sizeof(float));
+ if (!out || !read_all(f, out, n * sizeof(float))) { free(out); return NULL; }
+ return out;
+}
+
+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++) {
+ double left = lo + b * delta, center = left + delta, right = center + delta;
+ for (int k = 0; k < NFFT / 2; k++) {
+ double x = 1127 * log(1 + (double)k * RATE / NFFT / 700);
+ double v = fmin((x - left) / (center - left), (right - x) / (right - center));
+ if (v > 0) m->mel[b * COLS + k] = (float)v;
+ }
+ }
+ for (int i = 0; i < NFFT / 2; i++) {
+ m->cos_t[i] = (float)cos(-2 * M_PI * i / NFFT);
+ m->sin_t[i] = (float)sin(-2 * M_PI * i / NFFT);
+ }
+}
+
+void *cvp_load(const char *path) {
+ FILE *f = fopen(path, "rb");
+ if (!f) return NULL;
+ char magic[4];
+ uint32_t n;
+ Model *m = calloc(1, sizeof(Model));
+ if (!m || !read_all(f, magic, 4) || memcmp(magic, "CVP1", 4) || !read_all(f, &n, 4)) goto fail;
+ m->nops = (int)n;
+ m->ops = calloc(n, sizeof(Op));
+ for (uint32_t i = 0; i < n; i++) {
+ uint32_t t;
+ Op *o = &m->ops[i];
+ if (!read_all(f, &t, 4)) goto fail;
+ o->type = (int)t;
+ if (t == 1) {
+ uint32_t v[7];
+ if (!read_all(f, v, sizeof v)) goto fail;
+ o->src = v[0]; o->dst = v[1]; o->cin = v[2]; o->cout = v[3]; o->k = v[4]; o->stride = v[5]; o->relu = v[6];
+ o->src2 = -1;
+ o->w = read_f16(f, (size_t)o->cout * o->cin * o->k * o->k);
+ o->b = read_f32(f, o->cout);
+ if (!o->w || !o->b) goto fail;
+ } else if (t == 2) {
+ uint32_t v[4];
+ if (!read_all(f, v, sizeof v)) goto fail;
+ o->src = v[0]; o->src2 = v[1]; o->dst = v[2]; o->relu = v[3];
+ } else goto fail;
+ if (o->dst + 1 > m->nslots) m->nslots = o->dst + 1;
+ }
+ uint32_t head[3];
+ if (!read_all(f, head, sizeof head)) goto fail;
+ m->channels = head[0]; m->freq = head[1]; m->dims = head[2];
+ m->fc = read_f16(f, (size_t)m->dims * m->channels * m->freq * 2);
+ 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;
+ for (int j = i + 1; j < m->nops; j++) {
+ Op *p = &m->ops[j];
+ if (p->src == o->src || p->src2 == o->src) o->last_use_src = 0;
+ if (o->src2 >= 0 && (p->src == o->src2 || p->src2 == o->src2)) o->last_use_src2 = 0;
+ }
+ }
+ tables(m);
+ fclose(f);
+ return m;
+fail:
+ fclose(f);
+ free(m);
+ 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;
+ for (; j & bit; bit >>= 1) j ^= bit;
+ j ^= bit;
+ if (i < j) {
+ float t = re[i]; re[i] = re[j]; re[j] = t;
+ t = im[i]; im[i] = im[j]; im[j] = t;
+ }
+ }
+ for (int len = 2; len <= NFFT; len <<= 1) {
+ int step = NFFT / len;
+ for (int i = 0; i < NFFT; i += len)
+ for (int k = 0; k < len / 2; k++) {
+ float wr = m->cos_t[k * step], wi = m->sin_t[k * step];
+ int a = i + k, b = i + k + len / 2;
+ float xr = re[b] * wr - im[b] * wi, xi = re[b] * wi + im[b] * wr;
+ re[b] = re[a] - xr; im[b] = im[a] - xi;
+ re[a] += xr; im[a] += xi;
+ }
+ }
+}
+
+/* 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;
+ int frames = 1 + (n - FRAME) / SHIFT;
+ if (!out) return frames;
+ float frame[NFFT], im[NFFT], power[COLS];
+ for (int f = 0; f < frames; f++) {
+ const float *s = samples + (size_t)f * SHIFT;
+ float mean = 0;
+ for (int i = 0; i < FRAME; i++) { frame[i] = s[i] * 32768; mean += frame[i]; }
+ mean /= FRAME;
+ for (int i = 0; i < FRAME; i++) frame[i] -= mean;
+ for (int i = FRAME - 1; i > 0; i--) frame[i] -= 0.97f * frame[i - 1];
+ frame[0] -= 0.97f * frame[0];
+ for (int i = 0; i < FRAME; i++) frame[i] *= m->window[i];
+ for (int i = FRAME; i < NFFT; i++) frame[i] = 0;
+ memset(im, 0, sizeof im);
+ fft(m, frame, im);
+ for (int k = 0; k < COLS; k++) power[k] = frame[k] * frame[k] + im[k] * im[k];
+ for (int b = 0; b < BINS; b++) {
+ const float *w = m->mel + b * COLS;
+ float acc = 0;
+ for (int k = 0; k < COLS; k++) acc += w[k] * power[k];
+ out[(size_t)f * BINS + b] = logf(acc > FLT_EPSILON ? acc : FLT_EPSILON);
+ }
+ }
+ return frames;
+}
+
+/* ---- the ResNet ---- */
+
+typedef struct {
+ const Op *o;
+ const float *in;
+ float *out;
+ int h, w, ho, wo;
+ int tile, tiles, next;
+ 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) {
+ float a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], a6 = a[6], a7 = a[7];
+ for (int j = 0; j < nt; j++) {
+ float x = b[j];
+ c0[j] += a0 * x; c1[j] += a1 * x; c2[j] += a2 * x; c3[j] += a3 * x;
+ c4[j] += a4 * x; c5[j] += a5 * x; c6[j] += a6 * x; c7[j] += a7 * x;
+ }
+}
+
+static inline __attribute__((always_inline)) void axpy1(const float *restrict b, int nt, float a, float *restrict c) {
+ 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];
+ for (; r + 8 <= rows; r += 8) {
+ float *c = acc + (size_t)r * nt;
+ memset(c, 0, (size_t)8 * nt * sizeof(float));
+ for (int k = 0; k < K; k++) {
+ for (int q = 0; q < 8; q++) a8[q] = w[(size_t)(r + q) * K + k];
+ axpy8(col + (size_t)k * nt, nt, a8, c, c + nt, c + 2 * nt, c + 3 * nt, c + 4 * nt, c + 5 * nt, c + 6 * nt, c + 7 * nt);
+ }
+ }
+ for (; r < rows; r++) {
+ float *c = acc + (size_t)r * nt;
+ memset(c, 0, nt * sizeof(float));
+ for (int k = 0; k < K; k++) axpy1(col + (size_t)k * nt, nt, w[(size_t)r * K + k], c);
+ }
+}
+
+static void *conv_worker(void *arg) {
+ ConvJob *j = arg;
+ const Op *o = j->o;
+ int K = o->cin * o->k * o->k, P = j->ho * j->wo;
+ float *col = malloc((size_t)K * j->tile * sizeof(float));
+ float *acc = malloc((size_t)o->cout * j->tile * sizeof(float));
+ for (;;) {
+ pthread_mutex_lock(j->lock);
+ int t = j->next++;
+ 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++)
+ for (int kx = 0; kx < o->k; kx++) {
+ float *row = col + (size_t)((ci * o->k + ky) * o->k + kx) * nt;
+ const float *plane = j->in + (size_t)ci * j->h * j->w;
+ for (int q = 0; q < nt; q++) {
+ int p = p0 + q, y = (p / j->wo) * o->stride + ky - pad, x = (p % j->wo) * o->stride + kx - pad;
+ row[q] = (y >= 0 && y < j->h && x >= 0 && x < j->w) ? plane[(size_t)y * j->w + x] : 0.f;
+ }
+ }
+ gemm(o->w, K, o->cout, col, nt, acc);
+ for (int co = 0; co < o->cout; co++) {
+ float *dst = j->out + (size_t)co * P + p0;
+ const float *a = acc + (size_t)co * nt;
+ float bias = o->b[co];
+ if (o->relu) for (int q = 0; q < nt; q++) { float v = a[q] + bias; dst[q] = v > 0 ? v : 0; }
+ else for (int q = 0; q < nt; q++) dst[q] = a[q] + bias;
+ }
+ }
+ free(col);
+ free(acc);
+ return NULL;
+}
+
+static float *conv(const Op *o, const float *in, int h, int w, int *ho, int *wo, int threads) {
+ *ho = (h + 2 * (o->k / 2) - o->k) / o->stride + 1;
+ *wo = (w + 2 * (o->k / 2) - o->k) / o->stride + 1;
+ 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;
+ pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
+ ConvJob job = {o, in, out, h, w, *ho, *wo, tile, (P + tile - 1) / tile, 0, &lock};
+ pthread_t ids[MAX_THREADS];
+ int started = 0;
+ for (int i = 1; i < threads; i++)
+ if (pthread_create(&ids[started], NULL, conv_worker, &job) == 0) started++;
+ conv_worker(&job);
+ for (int i = 0; i < started; i++) pthread_join(ids[i], NULL);
+ 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;
+ if (n > MAX_SECONDS * RATE) n = (int)(MAX_SECONDS * RATE);
+ if (threads <= 0) {
+ long cpus = sysconf(_SC_NPROCESSORS_ONLN);
+ threads = cpus > 0 ? (int)cpus : 1;
+ }
+ if (threads > MAX_THREADS) threads = MAX_THREADS;
+ int frames = cvp_fbank(m, samples, n, NULL);
+ if (frames < 50) return -1;
+ float *feats = malloc((size_t)frames * BINS * sizeof(float));
+ cvp_fbank(m, samples, n, feats);
+ for (int b = 0; b < BINS; b++) {
+ double sum = 0;
+ for (int f = 0; f < frames; f++) sum += feats[(size_t)f * BINS + b];
+ 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));
+ for (int b = 0; b < BINS; b++)
+ for (int f = 0; f < frames; f++) x[(size_t)b * frames + f] = feats[(size_t)f * BINS + b];
+ free(feats);
+ slot[0] = x; hs[0] = BINS; ws[0] = frames; cs[0] = 1;
+ int last = 0, ok = 1;
+ for (int i = 0; i < m->nops && ok; i++) {
+ Op *o = &m->ops[i];
+ if (o->type == 1) {
+ int ho, wo;
+ float *y = conv(o, slot[o->src], hs[o->src], ws[o->src], &ho, &wo, threads);
+ if (!y) { ok = 0; break; }
+ slot[o->dst] = y; hs[o->dst] = ho; ws[o->dst] = wo; cs[o->dst] = o->cout;
+ } else {
+ size_t len = (size_t)cs[o->src] * hs[o->src] * ws[o->src];
+ float *y = malloc(len * sizeof(float));
+ if (!y) { ok = 0; break; }
+ const float *a = slot[o->src], *b = slot[o->src2];
+ if (o->relu) for (size_t q = 0; q < len; q++) { float v = a[q] + b[q]; y[q] = v > 0 ? v : 0; }
+ else for (size_t q = 0; q < len; q++) y[q] = a[q] + b[q];
+ slot[o->dst] = y; hs[o->dst] = hs[o->src]; ws[o->dst] = ws[o->src]; cs[o->dst] = cs[o->src];
+ }
+ if (o->last_use_src && o->src != o->dst) { free(slot[o->src]); slot[o->src] = NULL; }
+ if (o->src2 >= 0 && o->last_use_src2 && o->src2 != o->src) { free(slot[o->src2]); slot[o->src2] = NULL; }
+ last = o->dst;
+ }
+ 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));
+ for (int r = 0; r < rows; r++) {
+ const float *v = t + (size_t)r * w;
+ double mu = 0, var = 0;
+ for (int q = 0; q < w; q++) mu += v[q];
+ mu /= w;
+ for (int q = 0; q < w; q++) var += (v[q] - mu) * (v[q] - mu);
+ var = w > 1 ? var / (w - 1) : 0;
+ z[r] = (float)mu;
+ z[rows + r] = (float)sqrt(var + 1e-8);
+ }
+ double norm = 0;
+ for (int d = 0; d < m->dims; d++) {
+ const float *wr = m->fc + (size_t)d * rows * 2;
+ double acc = m->fc_b[d];
+ for (int q = 0; q < rows * 2; q++) acc += wr[q] * z[q];
+ out[d] = (float)(acc - m->mean[d]);
+ norm += (double)out[d] * out[d];
+ }
+ free(z);
+ if (norm > 0) {
+ float s = (float)(1 / sqrt(norm));
+ for (int d = 0; d < m->dims; d++) out[d] *= s;
+ result = 0;
+ }
+ }
+ for (int i = 0; i < m->nslots; i++) free(slot[i]);
+ free(slot); free(hs); free(ws); free(cs);
+ return result;
+}
+
+int cvp_dims(void *model) { return ((Model *)model)->dims; }
+
+void cvp_free(void *model) {
+ Model *m = model;
+ if (!m) return;
+ for (int i = 0; i < m->nops; i++) { free(m->ops[i].w); free(m->ops[i].b); }
+ free(m->ops); free(m->fc); free(m->fc_b); free(m->mean);
+ 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));
+ if (!f) return -1;
+ for (int i = 0; i < n; i++) f[i] = samples[i] / 32768.f;
+ int r = cvp_embed(model, f, n, out, threads);
+ free(f);
+ return r;
+}
diff --git a/linux/packaging/com.wquguru.cicada.desktop b/linux/packaging/com.wquguru.cicada.desktop
new file mode 100644
index 0000000..4ac12bc
--- /dev/null
+++ b/linux/packaging/com.wquguru.cicada.desktop
@@ -0,0 +1,14 @@
+[Desktop Entry]
+Type=Application
+Name=Cicada
+Name[zh_CN]=知了
+Name[ja]=知了
+Name[ko]=知了
+Comment=Live translated subtitles and meeting notes for what your computer plays
+Comment[zh_CN]=把电脑播放的声音变成双语字幕和会议纪要
+Exec=@BIN@
+Icon=cicada
+Terminal=false
+Categories=AudioVideo;Audio;
+StartupWMClass=Cicada
+StartupNotify=false
diff --git a/linux/packaging/install.sh b/linux/packaging/install.sh
new file mode 100755
index 0000000..2d8a350
--- /dev/null
+++ b/linux/packaging/install.sh
@@ -0,0 +1,36 @@
+#!/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
+# (records and the Ling key stay in ~/.local/share/cicada and ~/.config/cicada).
+set -e
+src="$(cd "$(dirname "$0")" && pwd)"
+lib="$HOME/.local/lib/cicada"; bin="$HOME/.local/bin"; share="$HOME/.local/share"
+if [ "$1" = "--remove" ]; then
+ rm -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 || true
+from gi.repository import Gio
+schema = "org.gnome.settings-daemon.plugins.media-keys"
+if Gio.SettingsSchemaSource.get_default().lookup(schema, True):
+ keys = Gio.Settings.new(schema)
+ ours = {"/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/%s/" % n for n in ("cicada", "cicada-speak")}
+ keys.set_strv("custom-keybindings", [p for p in keys.get_strv("custom-keybindings") if p not in ours])
+ Gio.Settings.sync()
+PY
+ echo "Cicada removed."; exit 0
+fi
+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
+rm -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/"
+cp "$src/cicada.svg" "$lib/" # the tray and window icon, by path
+cp "$src/VERSION" "$lib/" # read by cicada/__init__.py
+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"
+gtk-update-icon-cache -q "$share/icons/hicolor" 2>/dev/null || true
+echo "Cicada installed: open it from the app grid (知了 / Cicada)."
diff --git a/linux/scripts/build.sh b/linux/scripts/build.sh
new file mode 100755
index 0000000..77a5ee3
--- /dev/null
+++ b/linux/scripts/build.sh
@@ -0,0 +1,34 @@
+#!/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 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 pipefail
+here="$(cd "$(dirname "$0")/.." && pwd)"
+root="$(dirname "$here")"
+version="$(tr -d '[:space:]' < "$root/VERSION")"
+out="$here/build/cicada-linux"
+rm -rf "$out" && mkdir -p "$out/lproj"
+rsync -a --exclude __pycache__ "$here/cicada" "$out/"
+for lang in zh-Hans en ja ko; do
+ mkdir -p "$out/lproj/$lang.lproj"
+ cp "$root/Resources/$lang.lproj/Localizable.strings" "$out/lproj/$lang.lproj/"
+ [ -f "$here/strings/$lang.lproj/Linux.strings" ] && cp "$here/strings/$lang.lproj/Linux.strings" "$out/lproj/$lang.lproj/"
+done
+mkdir -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"
+fi
+cp "$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.
+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"
+else echo "warning: no afconvert or ffmpeg, the build has no sample meeting" >&2; fi
+cp "$here/packaging/com.wquguru.cicada.desktop" "$here/packaging/install.sh" "$out/"
+cp "$root/site/icon.svg" "$out/cicada.svg"
+tar -C "$here/build" -czf "$here/build/cicada-linux-$version.tar.gz" cicada-linux
+echo "build/cicada-linux-$version.tar.gz"
diff --git a/linux/scripts/cicadactl b/linux/scripts/cicadactl
new file mode 100755
index 0000000..c54b867
--- /dev/null
+++ b/linux/scripts/cicadactl
@@ -0,0 +1,32 @@
+#!/usr/bin/env python3
+"""Drives the running dev build through its control socket (cicada/app/debug.py has the commands):
+ cicadactl state | start | stop | feed <wav> | sample | view notes|subtitles | show records|notes|settings|onboarding
+ target <code> | key-reload | windows | quit
+ calls <program=name,…>|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep
+ notes-tab notes|transcript | notes-search <text> | notes-wide on|off | onboarding-step <n> | settings-scroll <0-1>
+Run it inside the Linux session (linux/vm/vmctl.sh ssh does that for the test VM)."""
+import os
+import socket
+import sys
+
+if len(sys.argv) < 2:
+ print(__doc__)
+ sys.exit(2)
+path = os.path.join(os.environ.get("XDG_RUNTIME_DIR") or "/tmp", "cicada-dev.sock")
+args = sys.argv[1:]
+if args[0] == "feed" and len(args) > 1:
+ args[1] = os.path.abspath(args[1])
+s = socket.socket(socket.AF_UNIX)
+try:
+ s.connect(path)
+except OSError as e:
+ print('{"ok":false,"error":"no dev build running (%s)"}' % e)
+ sys.exit(1)
+s.sendall((" ".join(args) + "\n").encode())
+data = b""
+while not data.endswith(b"\n"):
+ chunk = s.recv(65536)
+ if not chunk:
+ break
+ data += chunk
+print(data.decode().strip())
diff --git a/linux/scripts/convert-voiceprint.py b/linux/scripts/convert-voiceprint.py
new file mode 100644
index 0000000..52fadf8
--- /dev/null
+++ b/linux/scripts/convert-voiceprint.py
@@ -0,0 +1,172 @@
+#!/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 hashlib
+import struct
+import sys
+
+SHA256 = "7bb2f06e9df17cdf1ef14ee8a15ab08ed28e8d0ef5054ee135741560df2ec068"
+
+
+def varint(b, i):
+ r = s = 0
+ while True:
+ c = b[i]
+ i += 1
+ r |= (c & 0x7F) << s
+ if c < 0x80:
+ return r, i
+ s += 7
+
+
+def fields(b):
+ i, n = 0, len(b)
+ while i < n:
+ key, i = varint(b, i)
+ f, w = key >> 3, key & 7
+ if w == 0:
+ v, i = varint(b, i)
+ elif w == 1:
+ v, i = b[i:i + 8], i + 8
+ elif w == 2:
+ ln, i = varint(b, i)
+ v, i = b[i:i + ln], i + ln
+ elif w == 5:
+ v, i = b[i:i + 4], i + 4
+ else:
+ raise ValueError("wire type %d" % w)
+ yield f, w, v
+
+
+def ints(w, v):
+ if w != 2:
+ return [v if v < 1 << 63 else v - (1 << 64)]
+ out, i = [], 0
+ while i < len(v):
+ x, i = varint(v, i)
+ out.append(x if x < 1 << 63 else x - (1 << 64))
+ return out
+
+
+def tensor(b):
+ t = {"dims": [], "raw": None, "float": []}
+ for f, w, v in fields(b):
+ if f == 1:
+ t["dims"] += ints(w, v)
+ elif f == 8:
+ t["name"] = v.decode()
+ elif f == 9:
+ t["raw"] = v
+ elif f == 4:
+ t["float"] += list(struct.unpack("<%df" % (len(v) // 4), v)) if w == 2 else [struct.unpack("<f", v)[0]]
+ return t
+
+
+def floats(t):
+ return list(struct.unpack("<%df" % (len(t["raw"]) // 4), t["raw"])) if t["raw"] is not None else t["float"]
+
+
+def node(b):
+ n = {"in": [], "out": [], "attrs": {}}
+ for f, w, v in fields(b):
+ if f == 1:
+ n["in"].append(v.decode())
+ elif f == 2:
+ n["out"].append(v.decode())
+ elif f == 4:
+ n["op"] = v.decode()
+ elif f == 5:
+ a = {"ints": []}
+ for g, x, y in fields(v):
+ if g == 1:
+ a["name"] = y.decode()
+ elif g == 3:
+ a["i"] = ints(x, y)[0]
+ elif g == 8:
+ a["ints"] += ints(x, y)
+ n["attrs"][a["name"]] = a
+ return n
+
+
+def load(path):
+ data = open(path, "rb").read()
+ if hashlib.sha256(data).hexdigest() != SHA256:
+ sys.exit("not the pinned voxceleb_resnet34_LM.onnx")
+ graph = next(v for f, _w, v in fields(data) if f == 7)
+ nodes, inits = [], {}
+ for f, _w, v in fields(graph):
+ if f == 1:
+ nodes.append(node(v))
+ elif f == 5:
+ t = tensor(v)
+ inits[t["name"]] = t
+ return nodes, inits
+
+
+def f16(values) -> bytes:
+ return struct.pack("<%de" % len(values), *values)
+
+
+def main(src, out):
+ nodes, inits = load(src)
+ slots = {}
+
+ 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
+ ops = []
+ for n in nodes:
+ op = n["op"]
+ if op == "Conv" and n["in"][0] in produced:
+ w, b = inits[n["in"][1]], inits[n["in"][2]]
+ cout, cin, kh, kw = w["dims"]
+ stride = n["attrs"]["strides"]["ints"]
+ pads = n["attrs"]["pads"]["ints"]
+ assert kh == kw and stride[0] == stride[1] and n["attrs"]["group"]["i"] == 1, n
+ assert (kh == 3 and pads == [1, 1, 1, 1]) or (kh == 1 and pads == [0, 0, 0, 0] and stride[0] == 2), (kh, pads, stride)
+ ops.append({"op": "conv", "src": n["in"][0], "dst": n["out"][0], "cin": cin, "cout": cout, "k": kh,
+ "stride": stride[0], "relu": 0, "w": floats(w), "b": floats(b)})
+ produced.add(n["out"][0])
+ elif op == "Add" and all(x in produced for x in n["in"]):
+ ops.append({"op": "add", "a": n["in"][0], "b": n["in"][1], "dst": n["out"][0], "relu": 0})
+ produced.add(n["out"][0])
+ 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
+ produced.add(n["out"][0])
+ blob = bytearray(b"CVP1")
+ blob += struct.pack("<I", len(ops))
+ for o in ops:
+ if o["op"] == "conv":
+ blob += struct.pack("<8I", 1, slot(o["src"]), slot(o["dst"]), o["cin"], o["cout"], o["k"], o["stride"], o["relu"])
+ blob += f16(o["w"]) + struct.pack("<%df" % o["cout"], *o["b"])
+ 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
+ fc, 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)
+ blob += f16(floats(fc)) + struct.pack("<%df" % dims, *floats(bias)) + struct.pack("<%df" % dims, *floats(mean))
+ open(out, "wb").write(blob)
+ print("%d ops, %d slots, %.1f MB" % (len(ops), len(slots), len(blob) / 1e6))
+
+
+if __name__ == "__main__":
+ main(sys.argv[1], sys.argv[2])
diff --git a/linux/scripts/smoke.sh b/linux/scripts/smoke.sh
new file mode 100755
index 0000000..7b21953
--- /dev/null
+++ b/linux/scripts/smoke.sh
@@ -0,0 +1,35 @@
+#!/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 pipefail
+here="$(cd "$(dirname "$0")/.." && pwd)"
+ctl="$here/scripts/cicadactl"; [ -x "$ctl" ] || ctl="$here/bin/cicadactl" # a checkout, or a build tree with it copied in
+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"
+"$here/bin/cicada" --dev > "$CICADA_HOME/app.out" 2>&1 &
+app=$!
+trap 'kill $app 2>/dev/null || true' EXIT
+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, wave
+w = wave.open(sys.argv[1], "wb"); w.setnchannels(1); w.setsampwidth(2); w.setframerate(16000)
+w.writeframes(b"".join(struct.pack("<h", int(12000 * math.sin(2 * math.pi * 440 * i / 16000))) for i in range(32000))); w.close()
+PY
+sleep 1
+(command -v pw-play >/dev/null && pw-play "$CICADA_HOME/tone.wav") || paplay "$CICADA_HOME/tone.wav"
+sleep 1
+state="$("$ctl" state)"
+echo "$state"
+"$ctl" windows
+python3 -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"
+"$ctl" stop >/dev/null
+"$ctl" quit >/dev/null || true
+wait $app 2>/dev/null || true
+echo "smoke: ok"
diff --git a/linux/scripts/strings.py b/linux/scripts/strings.py
new file mode 100644
index 0000000..ac163c0
--- /dev/null
+++ b/linux/scripts/strings.py
@@ -0,0 +1,42 @@
+#!/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)."""
+import pathlib
+import re
+import sys
+
+here = pathlib.Path(__file__).resolve().parent.parent
+root = here.parent
+keys = []
+for f in sorted((here / "cicada").rglob("*.py")):
+ for k in re.findall(r'\bLF?\("((?:[^"\\]|\\.)*)"', f.read_text(encoding="utf-8")):
+ if k not in keys:
+ keys.append(k)
+
+
+def table(path):
+ if not path.exists():
+ return {}
+ return dict(re.findall(r'^"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)";', path.read_text(encoding="utf-8"), re.M))
+
+
+missing_any = False
+for lang in ["en", "ja", "ko"]:
+ mine = here / f"strings/{lang}.lproj/Linux.strings"
+ have = {**table(root / f"Resources/{lang}.lproj/Localizable.strings"), **table(mine)}
+ missing = [k for k in keys if k not in have]
+ if missing:
+ missing_any = True
+ print(f"{lang}: {len(missing)} missing")
+ for k in missing:
+ print(f" {k}")
+ if "--write" in sys.argv:
+ mine.parent.mkdir(parents=True, exist_ok=True)
+ new = not mine.exists()
+ with mine.open("a", encoding="utf-8") as f:
+ if new:
+ 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')
+sys.exit(1 if missing_any else 0)
diff --git a/linux/scripts/test.sh b/linux/scripts/test.sh
new file mode 100755
index 0000000..ff13708
--- /dev/null
+++ b/linux/scripts/test.sh
@@ -0,0 +1,11 @@
+#!/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 pipefail
+here="$(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/null
+python3 -m unittest discover -s tests -q
+python3 scripts/strings.py
+python3 -m py_compile cicada/app/*.py cicada/core/*.py cli.py
+echo "linux: ok"
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
new file mode 100644
index 0000000..7085c2c
--- /dev/null
+++ b/linux/strings/en.lproj/Linux.strings
@@ -0,0 +1,144 @@
+/* Linux-only UI text; the Mac's Localizable.strings covers the rest. Check: linux/scripts/strings.py */
+"可能被共享" = "May be shared";
+"等有人说话" = "Waiting for someone to speak";
+"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "Click “Start listening” and what your PC plays becomes bilingual subtitles and notes";
+"请求过于频繁,稍后会自动重试。" = "Too many requests; retrying shortly.";
+"连不上 Ling,检查网络" = "Can't reach Ling; check your network";
+"识别、翻译和纪要都靠它,约 1 分钟。" = "Recognition, translation and notes all run on it. About a minute.";
+"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。" = "Cicada listens to what your PC plays. No microphone, no permission needed.";
+"听到了" = "Heard it";
+"放一段视频或音乐,看这条有没有跳动" = "Play a video or some music and watch this bar move";
+"播放一段约 9 秒的示例会议,看字幕和纪要怎么出现。" = "Play a 9-second sample meeting and watch the subtitles and notes appear.";
+"示例会议" = "Sample meeting";
+"纪要窗口不会抢走焦点,一直浮在最上面。" = "The notes window never takes focus and stays on top.";
+"播放示例" = "Play sample";
+"显示纪要" = "Show notes";
+"还没有会议记录" = "No meetings yet";
+"句" = "lines";
+"重命名" = "Rename";
+"保存失败" = "Couldn't save";
+"好" = "OK";
+"删除“%@”?删除后无法恢复。" = "Delete “%@”? This can't be undone.";
+"Ling key" = "Ling key";
+"删除 key" = "Remove key";
+"只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)" = "Stored only on this computer (readable only by your account) and sent only to Ling (ant-ling.com)";
+"重新打开知了后生效" = "Takes effect after reopening Cicada";
+"和字幕一样" = "Same as subtitles";
+"界面语言" = "App language";
+"Linux 无法让窗口避开屏幕共享:共享屏幕前先关掉纪要窗" = "Linux can't keep a window out of screen sharing: close the notes window before you share your screen";
+"纪要和翻译" = "Notes and translation";
+"语音识别用 Ming(云端),一次请求同时返回原文和译文" = "Speech recognition uses Ming (cloud): one request returns both the original and the translation";
+"关于" = "About";
+"打开记录所在文件夹" = "Open the records folder";
+"重新看一遍引导" = "Show the introduction again";
+"可以用" = "Works";
+"需要 Ling key 才能听" = "Listening needs a Ling key";
+"Ling key 无效" = "The Ling key is invalid";
+"Ling 太忙,稍后再试" = "Ling is busy; trying again shortly";
+"会议" = "Meeting";
+"M月d日 HH:mm" = "MMM d HH:mm";
+"M月d日" = "MMM d";
+"声音来源停了" = "The sound source stopped";
+/* The redesign (canvas 知了 Linux 版界面重设计); copy polished and translated with gemini-4-argon, reviewed. */
+"系统声音中断" = "System audio interrupted";
+"共享屏幕时此窗口可见" = "Visible in screen shares";
+"隐藏纪要(继续听)" = "Hide notes (keep listening)";
+"隐藏字幕条(继续听)" = "Hide subtitle bar (keep listening)";
+"切到实时纪要" = "Switch to live notes";
+"切到字幕条" = "Switch to subtitle bar";
+"音频服务已断开,本次会议记录已保存" = "Audio disconnected, meeting saved";
+"连不上 Ling" = "Can't connect to Ling";
+"请检查网络。恢复后会自动继续,断开期间的声音无法识别" = "Check your network. Will resume automatically; audio while offline is lost";
+"在设置里更换 Ling key" = "Change Ling key in Settings";
+"正在识别…" = "Recognizing…";
+"正在听电脑播放的声音,有声音后约 3 秒出字幕" = "Listening to computer audio. Subtitles appear ~3s after sound starts";
+"点“开始听”,将电脑播放的声音转为双语字幕和纪要" = "Click \"Start listening\" to turn computer audio into bilingual subtitles and notes";
+"纪要 %@ 秒前更新" = "Updated %@s ago";
+"纪要 %@ 分钟前更新" = "Updated %@ min ago";
+"正在讨论" = "Discussing";
+"填入 Ling key" = "Enter Ling key";
+"用于语音识别、翻译和生成纪要,约需 1 分钟。" = "Used for speech recognition, translation, and notes. Takes ~1 min.";
+"显示 key" = "Show key";
+"在 Ling 开放平台点“创建令牌”,复制 sk- 开头的密钥。" = "Click \"Create token\" on Ling Open Platform and copy the key starting with sk-.";
+"测试系统声音" = "Test system audio";
+"知了直接获取电脑播放的声音,不占用麦克风,也无需额外授权。" = "Cicada captures computer audio directly without using the mic or extra permissions.";
+"音量条没动?放段视频或音乐试试" = "Meter not moving? Try playing a video or music";
+"已收到声音" = "Audio detected";
+"等声音…" = "Waiting for audio…";
+"看一段示例会议" = "Watch a sample meeting";
+"约 9 秒,字幕和纪要会出现在屏幕右上角。" = "Takes ~9s. Subtitles and notes will appear at the top right.";
+"点击不抢焦点" = "Clicks don't steal focus";
+"隐藏后继续听" = "Keep listening when hidden";
+"跳过" = "Skip";
+"搜索标题和对话" = "Search titles and transcripts";
+"重看新手引导" = "Replay welcome guide";
+"退出知了" = "Quit Cicada";
+"主菜单" = "Main menu";
+"更早" = "Earlier";
+"播放示例会议" = "Play sample meeting";
+"没有找到" = "Not found";
+"没有标题或对话含有“%@”" = "No titles or transcripts contain \"%@\"";
+"重命名…" = "Rename…";
+"更多操作" = "More actions";
+"已导出“%@”" = "Exported \"%@\"";
+"在文件夹中显示" = "Show in folder";
+"已删除“%@”" = "Deleted \"%@\"";
+"更换…" = "Change…";
+"获取 Ling key" = "Get Ling key";
+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "Saved locally under your account and sent only to Ling (ant-ling.com)";
+"重启知了后生效" = "Takes effect after restarting Cicada";
+"Linux 下共享屏幕时对方能看到纪要窗。共享前点它右上角的 × 隐藏,知了会继续听。" = "On Linux, the notes window is visible when sharing your screen. Click × at its top right to hide it before sharing; Cicada will keep listening.";
+"正在听时" = "While listening";
+"悬浮窗" = "Floating window";
+"登录时启动" = "Launch at login";
+"登录后在顶栏待命" = "Stand by in top bar after login";
+"翻译与纪要模型" = "Translation & notes model";
+"Ming(云端)" = "Ming (cloud)";
+"版本" = "Version";
+"打开记录文件夹" = "Open meetings folder";
+"打开会议记录" = "Open meetings";
+"没能开始听" = "Couldn't start listening";
+"知了 · 系统声音" = "Cicada · System audio";
+"开始 / 结束听的快捷键" = "Start / stop listening shortcut";
+"在系统的键盘设置里,把命令 %@ 绑到一个按键" = "In your system keyboard settings, bind the command %@ to a key";
+"添加" = "Add";
+"在任何窗口里都能用" = "Works from any window";
+/* 同声传译 */
+"没能建好知了麦克风" = "Couldn't set up the Cicada microphone";
+"停止说" = "Stop speaking";
+"开始说" = "Start speaking";
+"正在听你说…" = "Listening to you…";
+"知了 · 给会议的声音" = "Cicada · Voice for the meeting";
+"知了 麦克风" = "Cicada Microphone";
+"开始 / 停止说的快捷键" = "Start / stop speaking shortcut";
+"你说的话翻译后,用“知了 麦克风”传给对方" = "What you say is translated and sent to them through “Cicada Microphone”";
+"和字幕一样(%@)" = "Same as subtitles (%@)";
+"在会议软件里把麦克风选成“知了 麦克风”(或“默认”),并戴上耳机:外放时对方的声音会被当成你说的。" = "In your meeting app, choose “Cicada Microphone” (or “Default”) as the microphone, and wear headphones: on speakers, their voice is taken for yours.";
+"这种语言还没有可用的声音" = "No voice is available for this language yet";
+"没听清,这句没有说出去" = "Didn't catch that; this sentence wasn't spoken";
+"对方在说话时说的,没有说出去" = "Said while they were talking, so not sent";
+"你说:%@" = "You said: %@";
+"对方听到:%@" = "They hear: %@";
+"戴着耳机" = "Wearing headphones";
+"和对方同时说的话也会传出去" = "What you say while they talk goes out too";
+"按声音标出说话人 1、2…,只在这台电脑上处理" = "Labels lines Speaker 1, 2… by voice, on this computer only";
+"这个版本缺少声纹组件,暂时用不了" = "This build lacks the voiceprint component, so this is unavailable";
+/* Onboarding and 结束会议 (canvas 知了 Linux · 补齐 Mac); the last two override the Mac's, which say Mac. */
+"接上 Ling" = "Connect Ling";
+"点一下“开始说”或按快捷键说%@,对方听到翻译后的语音。" = "Click “Start speaking” or press the shortcut and speak %@; they hear it translated.";
+"约 1 分钟,会建一个“知了 麦克风”,不用装驱动" = "About a minute; adds a “Cicada Microphone”, no driver to install";
+"已建好" = "Ready";
+"已添加" = "Added";
+"在系统的键盘设置里绑定" = "Bind it in the system keyboard settings";
+"添加这个快捷键" = "Add this shortcut";
+"译文从这里传给会议软件,不用安装驱动" = "The translation reaches your meeting app through it; no driver needed";
+"好了,知了在顶栏" = "All set. Cicada lives in the top bar";
+"好了,可以开始了" = "All set";
+"接下来会打开会议记录窗口;开会时在这里点“开始听”。" = "Your meetings window opens next; click “Start listening” there in a meeting.";
+"开会时点“开始听”" = "Click “Start listening” in a meeting";
+"按 %@ 说话" = "Press %@ to speak";
+"点纪要窗的麦克风说话" = "Click the mic in the notes window to speak";
+"顶栏没有知了的图标?装上 AppIndicator 扩展,就能从顶栏打开知了。" = "No Cicada icon in the top bar? Install the AppIndicator extension to open Cicada from there.";
+"活动" = "Activities";
+"让知了听到电脑里的声音" = "Let Cicada hear your computer";
+"听电脑里的声音" = "Hear the computer's audio";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
new file mode 100644
index 0000000..c85ab08
--- /dev/null
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -0,0 +1,144 @@
+/* Linux-only UI text; the Mac's Localizable.strings covers the rest. Check: linux/scripts/strings.py */
+"可能被共享" = "共有される可能性";
+"等有人说话" = "誰かが話すのを待っています";
+"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "「聞き取り開始」を押すと、PC で再生される音声が 2 言語の字幕とメモになります";
+"请求过于频繁,稍后会自动重试。" = "リクエストが多すぎます。まもなく自動で再試行します。";
+"连不上 Ling,检查网络" = "Ling に接続できません。ネットワークを確認してください";
+"识别、翻译和纪要都靠它,约 1 分钟。" = "認識・翻訳・メモはすべてこれで動きます。約 1 分。";
+"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。" = "知了は PC で再生される音声を聞きます。マイクも許可も不要です。";
+"听到了" = "聞こえました";
+"放一段视频或音乐,看这条有没有跳动" = "動画や音楽を再生して、このバーが動くか確認してください";
+"播放一段约 9 秒的示例会议,看字幕和纪要怎么出现。" = "約 9 秒のサンプル会議を再生して、字幕とメモが出る様子を見てみましょう。";
+"示例会议" = "サンプル会議";
+"纪要窗口不会抢走焦点,一直浮在最上面。" = "メモウィンドウはフォーカスを奪わず、常に最前面に表示されます。";
+"播放示例" = "サンプルを再生";
+"显示纪要" = "メモを表示";
+"还没有会议记录" = "まだ会議の記録はありません";
+"句" = "件";
+"重命名" = "名前を変更";
+"保存失败" = "保存できませんでした";
+"好" = "OK";
+"删除“%@”?删除后无法恢复。" = "「%@」を削除しますか?元に戻せません。";
+"Ling key" = "Ling キー";
+"删除 key" = "キーを削除";
+"只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)" = "このコンピュータにのみ保存され(あなたのアカウントだけが読めます)、Ling(ant-ling.com)にのみ送信されます";
+"重新打开知了后生效" = "知了を開き直すと反映されます";
+"和字幕一样" = "字幕と同じ";
+"界面语言" = "表示言語";
+"Linux 无法让窗口避开屏幕共享:共享屏幕前先关掉纪要窗" = "Linux では画面共有からウィンドウを隠せません。画面を共有する前にメモウィンドウを閉じてください";
+"纪要和翻译" = "メモと翻訳";
+"语音识别用 Ming(云端),一次请求同时返回原文和译文" = "音声認識は Ming(クラウド)を使い、1 回のリクエストで原文と訳文を返します";
+"关于" = "情報";
+"打开记录所在文件夹" = "記録のフォルダを開く";
+"重新看一遍引导" = "はじめのガイドをもう一度見る";
+"可以用" = "使用できます";
+"需要 Ling key 才能听" = "聞き取りには Ling キーが必要です";
+"Ling key 无效" = "Ling キーが無効です";
+"Ling 太忙,稍后再试" = "Ling が混み合っています。まもなく再試行します";
+"会议" = "会議";
+"M月d日 HH:mm" = "M月d日 HH:mm";
+"M月d日" = "M月d日";
+"声音来源停了" = "音声の取得が止まりました";
+/* The redesign (canvas 知了 Linux 版界面重设计); copy polished and translated with gemini-4-argon, reviewed. */
+"系统声音中断" = "システム音声が中断されました";
+"共享屏幕时此窗口可见" = "画面共有時にこのウィンドウは表示されます";
+"隐藏纪要(继续听)" = "議事メモを隠す(聞き取りを継続)";
+"隐藏字幕条(继续听)" = "字幕バーを隠す(聞き取りを継続)";
+"切到实时纪要" = "ライブ議事メモに切り替え";
+"切到字幕条" = "字幕バーに切り替え";
+"音频服务已断开,本次会议记录已保存" = "音声サービスが切断されました。今回の会議の記録は保存済みです";
+"连不上 Ling" = "Lingに接続できません";
+"请检查网络。恢复后会自动继续,断开期间的声音无法识别" = "ネットワークを確認してください。復旧後に自動再開しますが、切断中の音声は認識できません";
+"在设置里更换 Ling key" = "設定でLing keyを変更";
+"正在识别…" = "認識中…";
+"正在听电脑播放的声音,有声音后约 3 秒出字幕" = "PCの再生音を聞き取り中。音声検出から約3秒で字幕が表示されます";
+"点“开始听”,将电脑播放的声音转为双语字幕和纪要" = "「聞き取りを開始」をクリックして、PCの再生音を二か国語字幕と議事メモに変換します";
+"纪要 %@ 秒前更新" = "議事メモを%@秒前に更新";
+"纪要 %@ 分钟前更新" = "議事メモを%@分前に更新";
+"正在讨论" = "議論中";
+"填入 Ling key" = "Ling keyを入力";
+"用于语音识别、翻译和生成纪要,约需 1 分钟。" = "音声認識・翻訳・議事メモの作成に使用します。所要時間は約1分です。";
+"显示 key" = "keyを表示";
+"在 Ling 开放平台点“创建令牌”,复制 sk- 开头的密钥。" = "Lingオープンプラットフォームで「トークンを作成」をクリックし、sk-で始まるキーをコピーします。";
+"测试系统声音" = "システム音声をテスト";
+"知了直接获取电脑播放的声音,不占用麦克风,也无需额外授权。" = "CicadaはPCの再生音を直接取得するため、マイクを占有せず、追加の権限も不要です。";
+"音量条没动?放段视频或音乐试试" = "音量バーが動きませんか?動画や音楽を再生してみてください";
+"已收到声音" = "音声を検出しました";
+"等声音…" = "音声を待機中…";
+"看一段示例会议" = "サンプル会議を見る";
+"约 9 秒,字幕和纪要会出现在屏幕右上角。" = "約9秒間、画面右上に字幕と議事メモが表示されます。";
+"点击不抢焦点" = "クリックしてもフォーカスを奪わない";
+"隐藏后继续听" = "非表示でも聞き取りを継続";
+"跳过" = "スキップ";
+"搜索标题和对话" = "タイトルと会話を検索";
+"重看新手引导" = "チュートリアルを再表示";
+"退出知了" = "Cicadaを終了";
+"主菜单" = "メインメニュー";
+"更早" = "以前";
+"播放示例会议" = "サンプル会議を再生";
+"没有找到" = "見つかりません";
+"没有标题或对话含有“%@”" = "「%@」を含むタイトルや会話はありません";
+"重命名…" = "名前を変更…";
+"更多操作" = "その他の操作";
+"已导出“%@”" = "「%@」を書き出しました";
+"在文件夹中显示" = "フォルダに表示";
+"已删除“%@”" = "「%@」を削除しました";
+"更换…" = "変更…";
+"获取 Ling key" = "Ling keyを取得";
+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "このPCの現在のアカウントにのみ保存され、Ling(ant-ling.com)にのみ送信されます";
+"重启知了后生效" = "Cicadaの再起動後に有効になります";
+"Linux 下共享屏幕时对方能看到纪要窗。共享前点它右上角的 × 隐藏,知了会继续听。" = "Linuxで画面共有すると、相手に議事メモウィンドウが見えます。共有前に右上の × をクリックして隠しても、Cicadaは聞き取りを続けます。";
+"正在听时" = "聞き取り中";
+"悬浮窗" = "フローティングウィンドウ";
+"登录时启动" = "ログイン時に起動";
+"登录后在顶栏待命" = "ログイン後、トップバーに常駐";
+"翻译与纪要模型" = "翻訳・議事メモモデル";
+"Ming(云端)" = "Ming(クラウド)";
+"版本" = "バージョン";
+"打开记录文件夹" = "記録フォルダを開く";
+"打开会议记录" = "会議の記録を開く";
+"没能开始听" = "聞き取りを開始できませんでした";
+"知了 · 系统声音" = "知了 · システム音声";
+"开始 / 结束听的快捷键" = "聞き取りの開始 / 終了ショートカット";
+"在系统的键盘设置里,把命令 %@ 绑到一个按键" = "システムのキーボード設定で、コマンド %@ をキーに割り当ててください";
+"添加" = "追加";
+"在任何窗口里都能用" = "どのウィンドウからでも使えます";
+/* 同声传译 */
+"没能建好知了麦克风" = "知了マイクを作成できませんでした";
+"停止说" = "話すのをやめる";
+"开始说" = "話し始める";
+"正在听你说…" = "あなたの声を聞き取り中…";
+"知了 · 给会议的声音" = "知了 · 会議向けの音声";
+"知了 麦克风" = "知了 マイク";
+"开始 / 停止说的快捷键" = "話す開始 / 停止のショートカット";
+"你说的话翻译后,用“知了 麦克风”传给对方" = "あなたの発言を翻訳し、「知了 マイク」で相手に届けます";
+"和字幕一样(%@)" = "字幕と同じ(%@)";
+"在会议软件里把麦克风选成“知了 麦克风”(或“默认”),并戴上耳机:外放时对方的声音会被当成你说的。" = "会議アプリでマイクを「知了 マイク」(または「デフォルト」)にし、ヘッドホンを使ってください。スピーカーだと相手の声があなたの発言として扱われます。";
+"这种语言还没有可用的声音" = "この言語で使える音声はまだありません";
+"没听清,这句没有说出去" = "聞き取れませんでした。この文は伝えていません";
+"对方在说话时说的,没有说出去" = "相手が話している間の発言なので、送っていません";
+"你说:%@" = "あなた:%@";
+"对方听到:%@" = "相手に届く:%@";
+"戴着耳机" = "ヘッドホンを使用中";
+"和对方同时说的话也会传出去" = "相手が話している間の発言も送ります";
+"按声音标出说话人 1、2…,只在这台电脑上处理" = "声で話者 1、2… を区別します。処理はこのコンピュータ内だけ";
+"这个版本缺少声纹组件,暂时用不了" = "このビルドには声紋コンポーネントがないため使えません";
+/* Onboarding and 结束会议 (canvas 知了 Linux · 补齐 Mac); the last two override the Mac's, which say Mac. */
+"接上 Ling" = "Ling に接続";
+"点一下“开始说”或按快捷键说%@,对方听到翻译后的语音。" = "「話す」をクリックするかショートカットを押して%@で話すと、相手には翻訳された音声が届きます。";
+"约 1 分钟,会建一个“知了 麦克风”,不用装驱动" = "約 1 分。「知了 マイク」を作ります。ドライバーは不要です";
+"已建好" = "作成済み";
+"已添加" = "追加済み";
+"在系统的键盘设置里绑定" = "システムのキーボード設定で割り当てます";
+"添加这个快捷键" = "このショートカットを追加";
+"译文从这里传给会议软件,不用安装驱动" = "訳した音声はここから会議アプリに届きます。ドライバーは不要です";
+"好了,知了在顶栏" = "準備完了。知了はトップバーにあります";
+"好了,可以开始了" = "準備完了";
+"接下来会打开会议记录窗口;开会时在这里点“开始听”。" = "このあと会議の記録ウインドウが開きます。会議中はそこで「聞き始める」をクリックします。";
+"开会时点“开始听”" = "会議中に「聞き始める」";
+"按 %@ 说话" = "%@ で話す";
+"点纪要窗的麦克风说话" = "メモウインドウのマイクをクリックして話す";
+"顶栏没有知了的图标?装上 AppIndicator 扩展,就能从顶栏打开知了。" = "トップバーに知了のアイコンがない場合は、AppIndicator 拡張機能を入れるとそこから開けます。";
+"活动" = "アクティビティ";
+"让知了听到电脑里的声音" = "Cicada にパソコンの音を聞かせる";
+"听电脑里的声音" = "パソコンの音声を聞く";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
new file mode 100644
index 0000000..8bf8989
--- /dev/null
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -0,0 +1,143 @@
+/* Linux-only UI text; the Mac's Localizable.strings covers the rest. Check: linux/scripts/strings.py */
+"可能被共享" = "공유될 수 있음";
+"等有人说话" = "누군가 말하기를 기다리는 중";
+"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "‘듣기 시작’을 누르면 PC에서 재생되는 소리가 이중 언어 자막과 노트가 됩니다";
+"请求过于频繁,稍后会自动重试。" = "요청이 너무 많습니다. 잠시 후 자동으로 다시 시도합니다.";
+"连不上 Ling,检查网络" = "Ling에 연결할 수 없습니다. 네트워크를 확인하세요";
+"识别、翻译和纪要都靠它,约 1 分钟。" = "인식, 번역, 노트 모두 이것으로 동작합니다. 약 1분.";
+"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。" = "Cicada는 PC에서 재생되는 소리를 듣습니다. 마이크도 권한도 필요 없습니다.";
+"听到了" = "들립니다";
+"放一段视频或音乐,看这条有没有跳动" = "동영상이나 음악을 재생하고 이 막대가 움직이는지 보세요";
+"播放一段约 9 秒的示例会议,看字幕和纪要怎么出现。" = "약 9초짜리 샘플 회의를 재생해 자막과 노트가 나타나는 모습을 보세요.";
+"示例会议" = "샘플 회의";
+"纪要窗口不会抢走焦点,一直浮在最上面。" = "메모 창은 포커스를 가져가지 않고 항상 맨 위에 표시됩니다.";
+"播放示例" = "샘플 재생";
+"显示纪要" = "메모 보기";
+"还没有会议记录" = "아직 회의 기록이 없습니다";
+"句" = "줄";
+"重命名" = "이름 바꾸기";
+"保存失败" = "저장하지 못했습니다";
+"好" = "확인";
+"删除“%@”?删除后无法恢复。" = "‘%@’을(를) 삭제할까요? 되돌릴 수 없습니다.";
+"Ling key" = "Ling 키";
+"删除 key" = "키 삭제";
+"只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)" = "이 컴퓨터에만 저장되며(내 계정만 읽을 수 있음) Ling(ant-ling.com)에만 전송됩니다";
+"重新打开知了后生效" = "Cicada를 다시 열면 적용됩니다";
+"和字幕一样" = "자막과 같게";
+"界面语言" = "앱 언어";
+"Linux 无法让窗口避开屏幕共享:共享屏幕前先关掉纪要窗" = "Linux에서는 화면 공유에서 창을 숨길 수 없습니다. 화면을 공유하기 전에 메모 창을 닫으세요";
+"纪要和翻译" = "노트와 번역";
+"语音识别用 Ming(云端),一次请求同时返回原文和译文" = "음성 인식은 Ming(클라우드)을 쓰며, 한 번의 요청으로 원문과 번역을 함께 받습니다";
+"关于" = "정보";
+"打开记录所在文件夹" = "기록 폴더 열기";
+"重新看一遍引导" = "안내 다시 보기";
+"可以用" = "사용 가능";
+"需要 Ling key 才能听" = "듣기에는 Ling 키가 필요합니다";
+"Ling key 无效" = "Ling 키가 유효하지 않습니다";
+"Ling 太忙,稍后再试" = "Ling이 바쁩니다. 잠시 후 다시 시도합니다";
+"会议" = "회의";
+"M月d日 HH:mm" = "M월 d일 HH:mm";
+"M月d日" = "M월 d일";
+"声音来源停了" = "소리 입력이 멈췄습니다";
+/* The redesign (canvas 知了 Linux 版界面重设计); copy polished and translated with gemini-4-argon, reviewed. */
+"系统声音中断" = "시스템 오디오 중단됨";
+"共享屏幕时此窗口可见" = "화면 공유 시 이 창이 보입니다";
+"隐藏纪要(继续听)" = "회의록 숨기기 (계속 듣기)";
+"隐藏字幕条(继续听)" = "자막 바 숨기기 (계속 듣기)";
+"切到实时纪要" = "실시간 회의록으로 전환";
+"切到字幕条" = "자막 바로 전환";
+"音频服务已断开,本次会议记录已保存" = "오디오 서비스 연결이 끊어졌으며 이번 회의 기록이 저장되었습니다";
+"连不上 Ling" = "Ling에 연결할 수 없음";
+"请检查网络。恢复后会自动继续,断开期间的声音无法识别" = "네트워크를 확인하세요. 복구 후 자동으로 재개되며, 끊긴 동안의 소리는 인식되지 않습니다";
+"在设置里更换 Ling key" = "설정에서 Ling key 변경";
+"正在识别…" = "인식 중…";
+"正在听电脑播放的声音,有声音后约 3 秒出字幕" = "컴퓨터 소리를 듣는 중입니다. 소리가 나면 약 3초 후 자막이 표시됩니다";
+"点“开始听”,将电脑播放的声音转为双语字幕和纪要" = "\"듣기 시작\"을 클릭하여 컴퓨터 소리를 이중 언어 자막과 회의록으로 변환하세요";
+"纪要 %@ 秒前更新" = "%@초 전에 회의록 업데이트됨";
+"纪要 %@ 分钟前更新" = "%@분 전에 회의록 업데이트됨";
+"正在讨论" = "논의 중";
+"填入 Ling key" = "Ling key 입력";
+"用于语音识别、翻译和生成纪要,约需 1 分钟。" = "음성 인식, 번역 및 회의록 작성에 사용됩니다. 약 1분 소요됩니다.";
+"显示 key" = "key 표시";
+"在 Ling 开放平台点“创建令牌”,复制 sk- 开头的密钥。" = "Ling 오픈 플랫폼에서 \"토큰 생성\"을 클릭하고 sk-로 시작하는 키를 복사하세요.";
+"测试系统声音" = "시스템 오디오 테스트";
+"知了直接获取电脑播放的声音,不占用麦克风,也无需额外授权。" = "Cicada는 마이크를 사용하거나 추가 권한 없이 컴퓨터에서 재생되는 소리를 직접 가져옵니다.";
+"音量条没动?放段视频或音乐试试" = "음량 바가 움직이지 않나요? 동영상이나 음악을 재생해 보세요";
+"已收到声音" = "소리 감지됨";
+"等声音…" = "소리 대기 중…";
+"看一段示例会议" = "샘플 회의 보기";
+"约 9 秒,字幕和纪要会出现在屏幕右上角。" = "약 9초 동안 화면 오른쪽 상단에 자막과 회의록이 표시됩니다.";
+"点击不抢焦点" = "클릭 시 포커스 뺏지 않음";
+"隐藏后继续听" = "숨긴 후에도 계속 듣기";
+"跳过" = "건너뛰기";
+"搜索标题和对话" = "제목 및 대화 검색";
+"重看新手引导" = "시작 가이드 다시 보기";
+"退出知了" = "Cicada 종료";
+"主菜单" = "주 메뉴";
+"更早" = "이전";
+"播放示例会议" = "샘플 회의 재생";
+"没有找到" = "결과 없음";
+"没有标题或对话含有“%@”" = "\"%@\"이(가) 포함된 제목이나 대화가 없습니다";
+"重命名…" = "이름 바꾸기…";
+"更多操作" = "추가 작업";
+"已导出“%@”" = "\"%@\" 내보냄";
+"在文件夹中显示" = "폴더에 표시";
+"已删除“%@”" = "\"%@\" 삭제됨";
+"更换…" = "변경…";
+"获取 Ling key" = "Ling key 받기";
+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "이 기기의 현재 계정에만 저장되며 Ling(ant-ling.com)으로만 전송됩니다";
+"重启知了后生效" = "Cicada를 다시 시작하면 적용됩니다";
+"Linux 下共享屏幕时对方能看到纪要窗。共享前点它右上角的 × 隐藏,知了会继续听。" = "Linux에서 화면을 공유하면 상대방에게 회의록 창이 보입니다. 공유하기 전에 창 오른쪽 상단의 ×를 눌러 숨기세요. Cicada는 계속 듣습니다.";
+"正在听时" = "듣는 중일 때";
+"悬浮窗" = "플로팅 창";
+"登录时启动" = "로그인 시 시작";
+"登录后在顶栏待命" = "로그인 후 상단 바에서 대기";
+"翻译与纪要模型" = "번역 및 회의록 모델";
+"Ming(云端)" = "Ming (클라우드)";
+"版本" = "버전";
+"打开记录文件夹" = "기록 폴더 열기";
+"打开会议记录" = "회의 기록 열기";
+"没能开始听" = "듣기를 시작하지 못했습니다";
+"知了 · 系统声音" = "知了 · 시스템 오디오";
+"开始 / 结束听的快捷键" = "듣기 시작 / 종료 단축키";
+"在系统的键盘设置里,把命令 %@ 绑到一个按键" = "시스템 키보드 설정에서 명령 %@을(를) 키에 지정하세요";
+"添加" = "추가";
+"在任何窗口里都能用" = "어느 창에서나 사용할 수 있습니다";
+/* 同声传译 */
+"没能建好知了麦克风" = "知了 마이크를 만들지 못했습니다";
+"停止说" = "말하기 중지";
+"开始说" = "말하기 시작";
+"正在听你说…" = "말씀을 듣는 중…";
+"知了 · 给会议的声音" = "知了 · 회의용 음성";
+"知了 麦克风" = "知了 마이크";
+"开始 / 停止说的快捷键" = "말하기 시작 / 중지 단축키";
+"你说的话翻译后,用“知了 麦克风”传给对方" = "말씀을 번역해 “知了 마이크”로 상대에게 전달합니다";
+"和字幕一样(%@)" = "자막과 같게 (%@)";
+"在会议软件里把麦克风选成“知了 麦克风”(或“默认”),并戴上耳机:外放时对方的声音会被当成你说的。" = "회의 앱에서 마이크를 “知了 마이크”(또는 “기본값”)로 선택하고 헤드폰을 쓰세요. 스피커로 들으면 상대의 목소리가 내 말로 처리됩니다.";
+"这种语言还没有可用的声音" = "이 언어에서 사용할 수 있는 음성이 아직 없습니다";
+"没听清,这句没有说出去" = "잘 듣지 못해 이 문장은 전달하지 않았습니다";
+"对方在说话时说的,没有说出去" = "상대방이 말하는 중이라 보내지 않았어요";
+"你说:%@" = "내 말: %@";
+"对方听到:%@" = "상대가 듣는 말: %@";
+"戴着耳机" = "헤드폰 사용 중";
+"和对方同时说的话也会传出去" = "상대방이 말하는 중에 한 말도 보내요";
+"按声音标出说话人 1、2…,只在这台电脑上处理" = "목소리로 화자 1, 2…를 구분해요. 이 컴퓨터에서만 처리해요";
+"这个版本缺少声纹组件,暂时用不了" = "이 빌드에는 성문 구성 요소가 없어 사용할 수 없어요";
+/* Onboarding and 结束会议 (canvas 知了 Linux · 补齐 Mac); the last two override the Mac's, which say Mac. */
+"接上 Ling" = "Ling 연결";
+"点一下“开始说”或按快捷键说%@,对方听到翻译后的语音。" = "“말하기”를 누르거나 단축키를 눌러 %@로 말하면 상대는 번역된 음성을 듣습니다.";
+"约 1 分钟,会建一个“知了 麦克风”,不用装驱动" = "약 1분. ‘知了 마이크’를 만듭니다. 드라이버 설치는 필요 없습니다";
+"已建好" = "준비됨";
+"已添加" = "추가됨";
+"在系统的键盘设置里绑定" = "시스템 키보드 설정에서 지정하세요";
+"添加这个快捷键" = "이 단축키 추가";
+"译文从这里传给会议软件,不用安装驱动" = "번역된 음성이 여기서 회의 앱으로 전달됩니다. 드라이버는 필요 없습니다";
+"好了,知了在顶栏" = "준비 완료. 知了는 상단 바에 있습니다";
+"好了,可以开始了" = "준비 완료";
+"接下来会打开会议记录窗口;开会时在这里点“开始听”。" = "이어서 회의 기록 창이 열립니다. 회의 중에는 거기서 ‘듣기 시작’을 누르세요.";
+"开会时点“开始听”" = "회의 중에 ‘듣기 시작’";
+"按 %@ 说话" = "%@ 눌러 말하기";
+"点纪要窗的麦克风说话" = "노트 창의 마이크를 눌러 말하기";
+"顶栏没有知了的图标?装上 AppIndicator 扩展,就能从顶栏打开知了。" = "상단 바에 知了 아이콘이 없나요? AppIndicator 확장을 설치하면 거기서 열 수 있습니다.";
+"活动" = "현재 활동";
+"让知了听到电脑里的声音" = "Cicada가 컴퓨터 소리를 듣게 하세요";
diff --git a/linux/tests/test_core.py b/linux/tests/test_core.py
new file mode 100644
index 0000000..a069563
--- /dev/null
+++ b/linux/tests/test_core.py
@@ -0,0 +1,929 @@
+"""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 annotations
+
+import math
+import os
+import shutil
+import stat
+import sys
+import tempfile
+import threading
+import time
+import unittest
+from array import array
+from datetime import datetime, timedelta, timezone
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.dirname(HERE))
+REPO = os.path.dirname(os.path.dirname(HERE))
+
+from cicada.core import jsonfmt, strings, support # noqa: E402
+from cicada.core.audio import PcmAudioSource, Wav # noqa: E402
+from cicada.core.ling import AUDIO_MODEL, INVALID, NOTES, TRANSLATE, AIKey, LingClient, LingError, Response # noqa: E402
+from cicada.core.listen import ListenEngine, continues, join # noqa: E402
+from cicada.core.models import Fishbone, FishboneBranch, MeetingNotes, NoteItem, NoteTerm, NoteTopic, Session, TranscriptLine # noqa: E402
+from cicada.core import notes as notesmod # noqa: E402
+from cicada.core.notes import NotesEngine # noqa: E402
+from cicada.core.segmenter import Segmenter # noqa: E402
+from cicada.core import session_store # noqa: E402
+from cicada.core.session_store import SessionStore # noqa: E402
+from cicada.core.settings import AppSettings # noqa: E402
+from cicada.core.support import Paths # noqa: E402
+from cicada.core.translator import Heard, Translator, clean_translation, parse_heard, parse_interpretation # noqa: E402
+from cicada.core.ling import StreamResponse # noqa: E402
+from cicada.core.speak import SpeakEngine # noqa: E402
+from cicada.core import speakers # noqa: E402
+from cicada.core.models import VoiceGuess # noqa: E402
+
+MAC = """{
+ "endedAt" : "2026-11-02T15:24:12Z",
+ "hasAudio" : true,
+ "id" : "20261102-101639",
+ "lines" : [
+ {
+ "dst" : "Hello \\/ \\"hi\\"",
+ "dstLang" : "en",
+ "id" : "h1-1",
+ "speaker" : "them",
+ "src" : "你好",
+ "srcLang" : "zh-CN",
+ "t" : 2.5,
+ "voice" : 1
+ }
+ ],
+ "notes" : {
+ "conclusions" : [
+
+ ],
+ "covered" : 1,
+ "final" : true,
+ "summary" : "总结",
+ "terms" : [
+ {
+ "heard" : [
+
+ ],
+ "name" : "鸟哥",
+ "note" : "分享者"
+ }
+ ],
+ "title" : "标题",
+ "todos" : [
+ {
+ "owner" : "你",
+ "support" : 3,
+ "t" : 202.4,
+ "text" : "记录"
+ }
+ ],
+ "topics" : [
+ {
+ "pointTimes" : [
+ 12.4,
+ null
+ ],
+ "points" : [
+ "a",
+ "b"
+ ],
+ "start" : 0,
+ "summary" : "s",
+ "title" : "t"
+ }
+ ],
+ "updatedAt" : "2026-11-02T15:24:40Z"
+ },
+ "startedAt" : "2026-11-02T15:16:39Z",
+ "title" : "会议 11月2日 10:16",
+ "voiceNames" : {
+ "1" : "Emma"
+ }
+}"""
+
+
+def tone(seconds, amp=0.3):
+ return array("h", (int(math.sin(2 * math.pi * 300 * i / 16000) * amp * 32767) for i in range(int(seconds * 16000))))
+
+
+def silence(seconds):
+ return array("h", bytes(int(seconds * 16000) * 2))
+
+
+def concat(*parts):
+ out = array("h")
+ for p in parts:
+ out.extend(p)
+ return out
+
+
+def cut(*parts):
+ got = []
+ seg = Segmenter()
+ seg.on_segment = got.append
+ for p in parts:
+ for i in range(0, len(p), 1600):
+ seg.feed(p[i:i + 1600])
+ seg.flush()
+ return got
+
+
+class Fake:
+ def __init__(self, respond, speech=None):
+ self.respond = respond
+ self.speech = speech # body -> list of SSE lines
+ self.calls = []
+ self.spoken = []
+ self.lock = threading.Lock()
+
+ def stream(self, url, body, headers, timeout):
+ with self.lock:
+ self.spoken.append(body)
+ return StreamResponse(200, iter(self.speech(body) if self.speech else []))
+
+ def send(self, url, method, body, headers, timeout):
+ with self.lock:
+ self.calls.append((time.monotonic(), body or ""))
+ return self.respond(body or "")
+
+
+def reply(content, finish="stop"):
+ return Response(200, jsonfmt.write({"choices": [{"message": {"content": content}, "finish_reason": finish}],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1}}, pretty=False))
+
+
+def client(fake):
+ key = AIKey()
+ key.save("sk-test-0000000000")
+ return LingClient(key, fake)
+
+
+def content(body, i):
+ return jsonfmt.parse(body)["messages"][i]["content"]
+
+
+class Base(unittest.TestCase):
+ def setUp(self):
+ self.home = tempfile.mkdtemp(prefix="cicada-tests-")
+ Paths.home_override = self.home
+ Paths.log_override = os.path.join(self.home, "debug.log")
+ self.spacing = LingClient.spacing
+
+ def tearDown(self):
+ LingClient.spacing = self.spacing
+ Paths.home_override = None
+ Paths.log_override = None
+ shutil.rmtree(self.home, ignore_errors=True)
+
+
+class Records(Base):
+ def test_session_json_matches_the_mac(self):
+ s = Session(id="20261103-101611", title="会议 11月3日 10:16", startedAt=datetime(2026, 11, 3, 15, 16, 11, tzinfo=timezone.utc),
+ lines=[TranscriptLine(id="h1-1", t=2.7636849899291995, src="你好/世界", srcLang="zh-CN", dstLang="en")])
+ j = s.write()
+ self.assertIn('"startedAt" : "2026-11-03T15:16:11Z"', j)
+ self.assertIn("你好\\/世界", j)
+ self.assertNotIn('"dst"', j)
+ self.assertNotIn("endedAt", j)
+ self.assertNotIn("notes", j)
+ self.assertIn("2.7636849899291995", j)
+ self.assertTrue(j.startswith('{\n "hasAudio" : false,\n "id" : '))
+
+ def test_reads_a_mac_record_and_writes_it_back_byte_for_byte(self):
+ s = Session.read(MAC)
+ self.assertEqual(1, len(s.lines))
+ self.assertEqual(1, s.lines[0].voice)
+ self.assertEqual('Hello / "hi"', s.lines[0].dst)
+ self.assertEqual("Emma", s.voiceNames["1"])
+ self.assertEqual(12.4, s.notes.topics[0].point_time(0))
+ self.assertIsNone(s.notes.topics[0].point_time(1))
+ self.assertEqual(MAC, s.write())
+
+ def test_json_edge_cases(self):
+ self.assertEqual("3", jsonfmt.number(3.0))
+ self.assertEqual("0.0001", jsonfmt.number(0.0001))
+ self.assertEqual("0.00001", jsonfmt.number(0.00001))
+ self.assertEqual("-1.5", jsonfmt.number(-1.5))
+ parsed = jsonfmt.parse('{"a":[1,2.5,"x中\\n",true,null,{}],"b":-3e2}')
+ self.assertEqual('{"a":[1,2.5,"x中\\n",true,null,{}],"b":-300}', jsonfmt.write(parsed, pretty=False))
+ self.assertIsNone(jsonfmt.parse_object("not json"))
+ self.assertEqual('"a\\u0001"', jsonfmt.write("a\x01"))
+
+ def test_store_saves_and_drops_empty_meetings(self):
+ store = SessionStore()
+ empty = store.begin(datetime(2026, 1, 1, 1, tzinfo=timezone.utc))
+ store.end(empty.id)
+ self.assertIsNone(store.get(empty.id))
+ self.assertFalse(os.path.exists(os.path.join(Paths.sessions(), empty.id)))
+ s = store.begin(datetime(2026, 1, 1, 2, tzinfo=timezone.utc))
+ store.append(s.id, TranscriptLine(id="h1-1", src="hi", srcLang="en", dstLang="zh-CN"))
+ store.end(s.id)
+ path = os.path.join(Paths.sessions(), s.id, "session.json")
+ self.assertTrue(os.path.isfile(path))
+ with open(path, encoding="utf-8") as f:
+ self.assertEqual(1, len(Session.read(f.read()).lines))
+ self.assertIsNotNone(SessionStore().get(s.id))
+ self.assertTrue(s.title.startswith("会议 "))
+ md = session_store.markdown(store.get(s.id))
+ self.assertIn("**[00:00] 对方** \nhi\n", md)
+ self.assertNotIn("## 文字记录", md, "only under notes, as on the Mac")
+ store.rename(s.id, "我的会")
+ 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"] = True
+ o["zFuture"] = {"a": [1, "x"]}
+ text = jsonfmt.write(o)
+ s = Session.read(text)
+ self.assertTrue(s.room)
+ self.assertEqual(text, s.write())
+
+ def test_rename_as_on_the_mac(self):
+ strings.load("zh-Hans", [os.path.join(REPO, "Resources")])
+ store = SessionStore()
+ 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)))
+
+ def test_the_live_meeting_cannot_be_deleted(self):
+ store = SessionStore()
+ s = store.begin(datetime(2026, 1, 1, 2, tzinfo=timezone.utc))
+ store.append(s.id, TranscriptLine(id="h1-1", src="hi", srcLang="en", dstLang="zh-CN"))
+ store.delete(s.id)
+ self.assertIsNotNone(store.get(s.id))
+ store.end(s.id)
+ self.assertIsNone(store.live)
+ store.delete(s.id)
+ self.assertIsNone(store.get(s.id))
+
+ def test_display_title(self):
+ strings.load("zh-Hans", [os.path.join(REPO, "Resources")])
+ s = Session(title="会议 1月1日 10:00", startedAt=datetime.now(timezone.utc), notes=MeetingNotes(title="路线评审", summary="x"))
+ self.assertTrue(session_store.display_title(s).endswith(" 路线评审"))
+ s.renamed = True
+ s.title = "我的会"
+ self.assertEqual("我的会", session_store.display_title(s))
+
+
+class Hearing(Base):
+ def test_parses_ming_replies(self):
+ h = parse_heard("LANG: en\nORIGINAL: Hello there.\nTRANSLATION: 你好。", "zh-CN", None)
+ self.assertEqual(("en", "Hello there.", "你好。"), (h.lang, h.original, h.translation))
+ self.assertIsNone(parse_heard("作为一个人工智能语言模型,这个问题超出我目前的学习范围了", "zh-CN", None))
+ self.assertIsNone(parse_heard("LANG: en\nORIGINAL: NONE\nTRANSLATION: 无", "zh-CN", None))
+ self.assertIsNone(parse_heard("LANG: en\nORIGINAL: ...\nTRANSLATION: …", "zh-CN", None))
+ same = parse_heard("LANG: zh\nORIGINAL: 好的\nTRANSLATION: OK", "zh-CN", "en")
+ self.assertEqual(("zh-CN", "好的"), (same.lang, same.translation))
+ self.assertIsNone(parse_heard("LANG: en\nORIGINAL: Hi\nTRANSLATION: Hi again", "zh-CN", None).translation)
+ self.assertEqual("ja", parse_heard("lang: ja-JP\noriginal: はい\ntranslation: 是", "zh-CN", None).lang)
+
+ 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)
+ for prefs in (["en_CA", "zh_CN"], ["zh_CN", "en_US"], ["ja_JP", "en_US"], ["en_US"]):
+ mine = support.my_language(prefs)
+ for source in ("en", "ja", "ko", "zh-CN", None):
+ if source != mine:
+ self.assertEqual(mine, support.follow_system_target(source, prefs))
+ self.assertEqual("en", support.follow_system_target("zh-CN", ["en_CA", "zh_CN"]))
+ self.assertEqual("en", support.follow_system_target("ja", ["ja_JP", "en_US"]))
+ self.assertEqual("en", support.follow_system_target("zh-CN", ["zh_CN"]))
+ self.assertEqual("zh-CN", support.follow_system_target("en", ["en_US"]))
+ old = {k: os.environ.get(k) for k in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")}
+ try:
+ for k in old:
+ os.environ.pop(k, None)
+ os.environ["LANGUAGE"], os.environ["LANG"] = "en_US:zh_CN", "en_US.UTF-8"
+ self.assertEqual(["en_US", "zh_CN", "en_US.UTF-8"], support.system_languages())
+ s = AppSettings()
+ self.assertEqual("zh-CN", s.target_code)
+ self.assertEqual("en", s.resolved_target("zh-CN"))
+ self.assertEqual("zh-CN", s.resolved_target("ja"))
+ self.assertEqual("ja", AppSettings(target="ja").resolved_target("ja"))
+ finally:
+ for k, v in old.items():
+ os.environ.pop(k, None)
+ if v is not None:
+ os.environ[k] = v
+
+ def test_normalizes_languages(self):
+ self.assertEqual("zh-CN", support.normalize("zh-Hans", "en"))
+ self.assertEqual("zh-TW", support.normalize("zh-TW", "en"))
+ self.assertEqual("zh-CN", support.normalize("cmn", "en"))
+ self.assertEqual("en", support.normalize("en-US", "ja"))
+ self.assertEqual("ja", support.normalize("", "ja"))
+ self.assertEqual("zh-TW", support.from_system("zh-Hant-HK"))
+ self.assertEqual("zh-CN", support.from_system("zh_CN.UTF-8"))
+ self.assertEqual("zh-TW", support.from_system("zh_TW.UTF-8"))
+ self.assertEqual("en", support.from_system("en_GB.UTF-8"))
+ self.assertEqual("Simplified Chinese", support.english_name("zh-CN"))
+ self.assertEqual("Japanese", support.english_name("ja"))
+ self.assertEqual("01:05", support.clock(65.9))
+ self.assertEqual("1:00:01", support.clock(3601.0))
+
+ def test_cleans_translations(self):
+ self.assertEqual("你好", clean_translation("Translation: 你好", "zh-CN"))
+ self.assertEqual("你好", clean_translation("“你好”", "zh-CN"))
+ self.assertEqual("Hello", clean_translation("Here is the translation:\nHello", "en"))
+ self.assertIsNone(clean_translation("请提供需要翻译的字幕内容", "en"))
+ self.assertIsNone(clean_translation("Hello", "zh-CN"))
+ self.assertEqual("Done.", clean_translation("<think>x</think>Done.", "en"))
+
+ def test_joins_cut_sentences(self):
+ last = TranscriptLine(src="We finished the migration and", srcLang="en")
+ self.assertTrue(continues(last, 0.2, Heard("en", "the error rate dropped.", None)))
+ self.assertFalse(continues(last, 1.5, Heard("en", "next", None)))
+ self.assertFalse(continues(TranscriptLine(src="Done.", srcLang="en"), 0.1, Heard("en", "Next", None)))
+ self.assertFalse(continues(last, 0.1, Heard("ja", "はい", None)))
+ self.assertEqual("我们完成了迁移", join("我们完成了", "迁移", "zh-CN"))
+ self.assertEqual("a b", join("a ", " b", "en"))
+
+
+class Segmenting(Base):
+ def test_segments_on_pauses(self):
+ got = cut(silence(0.5), tone(2.0), silence(1.0), tone(1.5), silence(1.0))
+ self.assertEqual(2, len(got))
+ self.assertAlmostEqual(0.35, got[0].start, delta=0.05)
+ self.assertAlmostEqual(3.35, got[1].start, delta=0.05)
+ self.assertTrue(2.1 <= got[0].seconds <= 2.4, got[0].seconds)
+
+ def test_cuts_long_speech_at_its_quietest_moment(self):
+ got = cut(tone(7.0), tone(0.3, 0.004), tone(4.0), silence(1.0))
+ self.assertEqual(2, len(got))
+ self.assertTrue(6.9 <= got[0].seconds <= 7.4, got[0].seconds)
+ self.assertTrue(all(s.seconds <= 8.0 for s in got))
+ self.assertAlmostEqual(got[1].start, got[0].start + got[0].seconds, delta=0.001)
+
+ 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))))
+
+ def test_wav_round_trip(self):
+ pcm = tone(0.5)
+ self.assertEqual(pcm, Wav.read(Wav.bytes(pcm)))
+ self.assertEqual(16000, len(Wav.resample(array("d", bytes(48000 * 8)), 48000)))
+ stereo = Wav.bytes(array("h", [100, 300] * 8000), rate=16000).replace(b"\x01\x00\x01\x00\x80>", b"\x01\x00\x02\x00\x80>", 1)
+ self.assertEqual(array("h", [200] * 8000), Wav.read(stereo))
+
+
+class Notes(Base):
+ def test_parses_notes(self):
+ raw = """```json
+ {"title": "“发布评审”", "summary": "讨论发布。",
+ "topics": [{"start": 0, "title": "进展", "summary": "一句", "points": [{"text": "迁移完成", "evidence": ["L2"]}, "旧格式要点", {"text": "", "evidence": []}],
+ "fishbone": {"question": "为何延期", "branches": [{"label": "测试", "detail": "x", "t": 3, "evidence": ["L1"]}, {"label": "设计", "detail": "y", "evidence": ["L9"]}]}}],
+ "conclusions": [{"text": "周五上线", "evidence": ["L1", "L2", "L99"]}],
+ "todos": [{"text": "发说明", "owner": "", "evidence": ["L2"]}],
+ "terms": [{"name": "Stripe", "note": "支付", "heard": ["Stripe", "Strip"]}]}
+ ```"""
+ n = notesmod.parse(raw, [1.0, 5.0], 0.0)
+ self.assertEqual("发布评审", n.title)
+ self.assertEqual(2, len(n.topics[0].points))
+ self.assertEqual(5.0, n.topics[0].point_time(0))
+ self.assertIsNone(n.topics[0].point_time(1))
+ self.assertEqual(2, len(n.topics[0].fishbone.branches))
+ self.assertEqual(0, n.topics[0].fishbone.branches[1].support)
+ self.assertEqual(2, n.conclusions[0].support)
+ self.assertIsNone(n.todos[0].owner)
+ self.assertEqual(["Strip"], n.terms[0].heard)
+ self.assertIsNone(notesmod.parse("not json", [], 0.0))
+ self.assertIsNone(notesmod.parse("{}", [], 0.0))
+
+ def test_keeps_earliest_times(self):
+ old = MeetingNotes(topics=[NoteTopic(title="t", points=["a"], pointTimes=[3.0])], todos=[NoteItem(text="x", t=2.0)])
+ nxt = MeetingNotes(topics=[NoteTopic(title="t", points=["a", "b"], pointTimes=[9.0, None])], todos=[NoteItem(text="x", t=8.0)])
+ notesmod.carry_times(old, nxt)
+ self.assertEqual(3.0, nxt.topics[0].point_time(0))
+ self.assertEqual(2.0, nxt.todos[0].t)
+
+ def test_notes_prompt_is_the_macs(self):
+ lines = [TranscriptLine(t=1.0, src="你好", speaker="them"), TranscriptLine(t=65.0, src="我来说", speaker="me")]
+ p = notesmod.prompt(MeetingNotes(), lines, 0, "Simplified Chinese", final=False)
+ self.assertTrue(p.startswith("You keep notes for a meeting that is still going on. Update them with the new lines.\nWrite the notes in Simplified Chinese. Return JSON only.\n"))
+ self.assertIn("[L1 00:01 对方] 你好\n[L2 01:05 你] 我来说", p)
+ self.assertIn("These are the first lines: make one topic.", p)
+ self.assertTrue(p.endswith("No markdown, no text outside the JSON."))
+ f = notesmod.prompt(MeetingNotes(), lines, 0, "English", final=True)
+ self.assertIn("This meeting ran 01:04: use at most 1 topic.", f)
+ self.assertTrue(notesmod.written(MeetingNotes(summary="讨论发布 Stripe"), "Simplified Chinese"))
+ self.assertFalse(notesmod.written(MeetingNotes(summary="We talked"), "Simplified Chinese"))
+
+ 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")
+ with open(src, encoding="utf-8") as f:
+ 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("- ")]:
+ probe = rule.replace('"', '\\"')[:60]
+ self.assertIn(probe, kt, rule)
+
+
+class Strings(Base):
+ def test_loads_the_macs_translations(self):
+ res = [os.path.join(REPO, "Resources"), os.path.join(REPO, "linux", "strings")]
+ strings.load("en_US.UTF-8", res)
+ self.assertEqual("Live notes", strings.L("实时纪要"))
+ self.assertEqual("没有这条", strings.L("没有这条"))
+ strings.load("zh-Hans", res)
+ self.assertEqual("实时纪要", strings.L("实时纪要"))
+ t = strings.parse('/* c */\n"a \\"b\\"" = "x\\ny";\n// line\n"%@ 分钟" = "%@ min";')
+ self.assertEqual("x\ny", t['a "b"'])
+ self.assertEqual("%@ min", t["%@ 分钟"])
+ self.assertEqual("3 分钟", strings.LF("%@ 分钟", 3))
+ self.assertEqual("b a", strings.LF("%2$@ %1$@", "a", "b"))
+
+ def test_key_file_is_private(self):
+ key = AIKey()
+ self.assertTrue(key.save("sk-test-0000000000"))
+ self.assertEqual(0o600, stat.S_IMODE(os.stat(Paths.key_file()).st_mode))
+ AppSettings().save()
+ with open(Paths.settings(), encoding="utf-8") as f:
+ self.assertNotIn("sk-", f.read())
+ self.assertEqual("sk-••••••••••••0000", AIKey.masked("sk-test-0000000000"))
+
+
+class Ling(Base):
+ def test_request_shape(self):
+ fake = Fake(lambda b: reply("ok"))
+ client(fake).chat("the content", "Translate.", TRANSLATE, model=AUDIO_MODEL, audio=bytes([1, 2, 3]))
+ body = jsonfmt.parse(fake.calls[0][1])
+ self.assertEqual("disabled", body["thinking"]["type"])
+ self.assertEqual("system", body["messages"][0]["role"])
+ self.assertEqual("the content", content(fake.calls[0][1], 0))
+ user = content(fake.calls[0][1], 1)
+ self.assertEqual("audio_url", user[0]["type"])
+ self.assertEqual("data:audio/wav;base64,AQID", user[0]["audio_url"]["url"])
+ self.assertEqual("Translate.", user[1]["text"])
+
+ def test_drops_hijacked_and_refused_replies(self):
+ for r, finish in (("根据现有检索证据,……", "stop"), ("作为一个人工智能语言模型,这个问题超出……", "stop"), ("fine", None)):
+ ling = client(Fake(lambda b, r=r, f=finish: reply(r, f)))
+ with self.assertRaises(LingError) as e:
+ ling.chat("c", "i", TRANSLATE)
+ self.assertEqual(LingError.HIJACKED, e.exception.kind)
+
+ def test_retries_audio_once_when_busy(self):
+ n = [0]
+
+ def respond(b):
+ n[0] += 1
+ return Response(429, "") if n[0] == 1 else reply("LANG: en\nORIGINAL: Hi.\nTRANSLATION: 嗨。")
+ r = client(Fake(respond)).chat("c", "i", TRANSLATE, model=AUDIO_MODEL, audio=bytes([1]))
+ self.assertIn("ORIGINAL: Hi.", r)
+ self.assertEqual(2, n[0])
+ with self.assertRaises(LingError) as e:
+ client(Fake(lambda b: Response(429, ""))).chat("c", "i", TRANSLATE)
+ self.assertEqual(LingError.RATE_LIMITED, e.exception.kind)
+
+ def test_marks_a_bad_key(self):
+ ling = client(Fake(lambda b: Response(401, "")))
+ with self.assertRaises(LingError) as e:
+ ling.chat("c", "i", TRANSLATE)
+ self.assertEqual(LingError.INVALID_KEY, e.exception.kind)
+ self.assertEqual(INVALID, ling.key_state)
+ self.assertFalse(ling.usable)
+
+ def test_gate_spaces_starts_and_serves_priority_first(self):
+ LingClient.spacing = 0.2
+ fake = Fake(lambda b: reply("ok"))
+ ling = client(fake)
+ 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)
+ c = threading.Thread(target=ling.chat, args=("translate", "i", TRANSLATE))
+ c.start()
+ for t in (a, b, c):
+ t.join()
+ self.assertEqual(["first", "translate", "notes"], [content(x[1], 0) for x in fake.calls])
+ for i in range(1, len(fake.calls)):
+ self.assertGreaterEqual(fake.calls[i][0] - fake.calls[i - 1][0], 0.18)
+
+
+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"]
+ first = len(url) < 60000
+ if first:
+ time.sleep(0.4)
+ return reply("LANG: en\nORIGINAL: First one.\nTRANSLATION: 第一句。" if first else
+ "LANG: en\nORIGINAL: Second one.\nTRANSLATION: 第二句。")
+ return reply("{}")
+ LingClient.spacing = 0.05
+ ling = client(Fake(respond))
+ store = SessionStore()
+ notes = NotesEngine(ling, store)
+ engine = ListenEngine(ling, Translator(ling), store, notes, AppSettings(target="zh-CN"))
+ src = PcmAudioSource(lambda: concat(tone(1.0), silence(1.0), tone(1.6), silence(1.0)), speed=0)
+ ended = threading.Event()
+ src.on_ended = lambda why: ended.set()
+ engine.start(src, "file")
+ ended.wait(10)
+ time.sleep(0.1)
+ engine.stop()
+ s = store.get(engine.session_id)
+ self.assertEqual(["First one.", "Second one."], [l.src for l in s.lines])
+ self.assertEqual("第一句。", s.lines[0].dst)
+ self.assertEqual("h1-1", s.lines[0].id)
+ self.assertIsNotNone(s.endedAt)
+
+ 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):
+ if "Ming-3.0-audio-flash" in body:
+ asked.append(content(body, 0))
+ return reply("LANG: zh\nORIGINAL: 大家好。\nTRANSLATION: %s" % ("Hello all." if "into English" in asked[-1] else "大家好。"))
+ return reply("{}")
+ LingClient.spacing = 0.05
+ ling = client(Fake(respond))
+ store = SessionStore()
+ 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()
+ engine.start(src, "file")
+ ended.wait(10)
+ time.sleep(0.3)
+ engine.stop()
+ lines = store.get(engine.session_id).lines
+ self.assertTrue(all(l.dstLang == "en" for l in lines))
+ self.assertNotIn("大家好。", [l.dst for l in lines])
+ self.assertIn("into Simplified Chinese", asked[0])
+ self.assertIn("into English", asked[-1])
+
+
+def sse(*chunks):
+ import base64
+ return ["data: " + jsonfmt.write({"type": "speech.audio.delta", "audio": base64.b64encode(c).decode()}, pretty=False) for c in chunks] + \
+ ["", "data: {\"type\":\"speech.audio.done\"}"]
+
+
+class Player:
+ def __init__(self):
+ self.data = b""
+ self.closed = 0
+
+ def write(self, pcm):
+ self.data += pcm
+
+ def drain(self):
+ pass
+
+ def close(self):
+ self.closed += 1
+
+
+class Speaking(Base):
+ def test_parses_interpretations(self):
+ self.assertEqual(("你好", "Hello"), parse_interpretation("ORIGINAL: 你好\nTRANSLATION: Hello", "en"))
+ self.assertIsNone(parse_interpretation("Sure! Here is my answer.", "en"), "an answer is not an interpretation")
+ self.assertIsNone(parse_interpretation("ORIGINAL: 你好\nTRANSLATION: 你好", "en"), "untranslated")
+ self.assertIsNone(parse_interpretation("ORIGINAL: 你好\nTRANSLATION: 你好吗", "en"), "wrong script")
+ self.assertIsNone(parse_interpretation("ORIGINAL: hi\nTRANSLATION:", "zh-CN"), "empty")
+
+ def test_streams_ming_voice(self):
+ fake = Fake(lambda b: reply("ok"), speech=lambda b: sse(b"\x01\x00", b"\x02\x00"))
+ pcm = list(client(fake).speech("Hello", voice="US_Emma", language=None))
+ self.assertEqual([b"\x01\x00", b"\x02\x00"], pcm)
+ body = jsonfmt.parse(fake.spoken[0])
+ self.assertEqual(("Ming-3.0-tts-0.5B", "US_Emma", 24000, True), (body["model"], body["voice"], body["sample_rate"], body["stream"]))
+ self.assertNotIn("language_id", body)
+
+ def _engine(self, interpret_reply, listen=None):
+ LingClient.spacing = 0.01
+ fake = Fake(lambda b: reply(interpret_reply), speech=lambda b: sse(b"\x10\x00" * 100))
+ ling = client(fake)
+ player = Player()
+ settings = AppSettings(target="zh-CN", speakTo="en")
+ eng = SpeakEngine(ling, Translator(ling), settings, listen=listen, player=lambda: player)
+ return eng, fake, player
+
+ def _say(self, eng, pcm):
+ src = PcmAudioSource(lambda: pcm, speed=0)
+ done = threading.Event()
+ src.on_ended = lambda why: done.set()
+ eng.start(src)
+ done.wait(5)
+ time.sleep(0.6)
+ eng.stop()
+
+ def test_speaks_the_translation_into_the_room(self):
+ eng, fake, player = self._engine("ORIGINAL: 我们周五上线\nTRANSLATION: We launch on Friday")
+ self._say(eng, concat(tone(1.2), silence(1.0)))
+ self.assertEqual(1, eng.spoken)
+ self.assertEqual(b"\x10\x00" * 100, player.data)
+ self.assertEqual("We launch on Friday", jsonfmt.parse(fake.spoken[0])["input"])
+ self.assertIn("into English", content(fake.calls[0][1], 0))
+
+ def test_never_speaks_what_was_not_interpreted(self):
+ eng, fake, player = self._engine("I think the launch should be on Friday, here is why...")
+ self._say(eng, concat(tone(1.2), silence(1.0)))
+ self.assertEqual(0, eng.spoken)
+ self.assertEqual([], fake.spoken, "nothing sent to the voice")
+ self.assertEqual(b"", player.data)
+ self.assertIsNotNone(eng.problem)
+
+ def test_fetches_the_next_voice_while_the_last_one_plays(self):
+ eng, fake, player = self._engine("ORIGINAL: 你好\nTRANSLATION: Hello")
+ fetched = []
+ slow = threading.Event()
+
+ def write(pcm, _w=player.write):
+ if not fetched:
+ fetched.append(len(fake.spoken))
+ slow.wait(1.5) # the first sentence still playing
+ fetched.append(len(fake.spoken))
+ _w(pcm)
+ player.write = write
+ self._say(eng, concat(tone(1.2), silence(1.0), tone(1.2), silence(1.0)))
+ slow.set()
+ time.sleep(0.3)
+ self.assertEqual(2, eng.spoken)
+ self.assertEqual(2, fetched[1], "the second voice was asked for before the first finished playing")
+
+ def test_export_names_who_said_each_line(self):
+ s = Session(title="会议", startedAt=datetime(2026, 1, 1, tzinfo=timezone.utc), lines=[
+ TranscriptLine(id="h1-1", t=1, src="Hi", dst="你好", srcLang="en", dstLang="zh-CN"),
+ TranscriptLine(id="m1", t=3, speaker="me", src="我们周五上线", dst="We launch on Friday", srcLang="zh-CN", dstLang="en")])
+ strings.load("zh-Hans", [os.path.join(REPO, "Resources")])
+ s.endedAt = s.startedAt + timedelta(minutes=24, seconds=30)
+ s.notes = MeetingNotes(title="上线", summary="定了周五。", topics=[NoteTopic(
+ title="上线时间", start=0, summary="讨论日期", points=["周五"],
+ fishbone=Fishbone(question="为什么推迟?", branches=[FishboneBranch(label="测试", detail="还没跑完")]))],
+ 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"
+ "### 待办\n\n- [ ] 发说明(你)\n\n### 人名和术语\n\n- **Ling** 模型\n\n## 文字记录\n\n"
+ "**[00:01] 对方** \nHi\n> 你好\n\n**[00:03] 你** \n我们周五上线\n> We launch on Friday\n\n",
+ session_store.markdown(s))
+ s.sourceFile = "call.m4a"
+ self.assertIn("**[00:01]** \nHi\n", session_store.markdown(s), "an imported file names nobody")
+
+ def test_drops_the_other_sides_voice_heard_through_the_speakers(self):
+ class Listening:
+ listening = True
+ spoken = "en"
+ session_id = None
+ eng, fake, player = self._engine("ORIGINAL: 你好\nTRANSLATION: Hello", listen=Listening())
+ stop = threading.Event()
+
+ def loud():
+ while not stop.is_set():
+ eng.loudness.add(True)
+ time.sleep(0.02)
+ threading.Thread(target=loud, daemon=True).start()
+ self._say(eng, concat(tone(1.2), silence(1.0)))
+ stop.set()
+ self.assertEqual(0, eng.spoken)
+ self.assertEqual([], fake.calls, "not even sent to Ming")
+ self.assertIsNotNone(eng.problem, "and the user is told")
+
+ def test_with_headphones_talking_over_them_still_goes_out(self):
+ class Listening:
+ listening = True
+ spoken = "en"
+ session_id = None
+ eng, fake, player = self._engine("ORIGINAL: 你好\nTRANSLATION: Hello", listen=Listening())
+ eng.settings.speakHeadphones = True
+ for _ in range(200):
+ eng.loudness.add(True)
+ self._say(eng, concat(tone(1.2), silence(1.0)))
+ self.assertEqual(1, eng.spoken)
+
+ def test_cancel_drops_what_is_still_waiting(self):
+ eng, fake, player = self._engine("ORIGINAL: 你好\nTRANSLATION: Hello")
+ src = PcmAudioSource(lambda: concat(tone(1.2), silence(1.0)), speed=0)
+ done = threading.Event()
+ src.on_ended = lambda why: done.set()
+ eng.start(src)
+ done.wait(5)
+ eng.cancel()
+ time.sleep(0.8)
+ self.assertEqual(0, eng.spoken)
+ self.assertEqual(b"", player.data)
+
+
+def unit(seed, dims=256):
+ import random
+ r = random.Random(seed)
+ v = [r.gauss(0, 1) for _ in range(dims)]
+ n = math.sqrt(sum(x * x for x in v))
+ return [x / n for x in v]
+
+
+def near(v, seed, mix=0.3):
+ w = unit(seed)
+ out = [a + mix * b for a, b in zip(v, w)]
+ n = math.sqrt(sum(x * x for x in out))
+ return [x / n for x in out]
+
+
+def them(i, voice, text="we should ship this on Friday", t=None):
+ return TranscriptLine(id="h%d-%d" % (i, i), t=t if t is not None else float(i), src=text, srcLang="en", dstLang="zh-CN", voice=voice)
+
+
+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 json
+ import wave
+ if speakers.library_path() is None or speakers.model_path() is None:
+ self.skipTest("no voiceprint library: native/build.sh")
+ with open(os.path.join(HERE, "voiceprint-ref.json")) as f:
+ ref = json.load(f)
+ w = wave.open(os.path.join(REPO, ref["clip"]))
+ w.setpos(ref["start"] * 16000)
+ pcm = array("h", w.readframes(ref["seconds"] * 16000))
+ v = speakers.Voiceprints.load().embed(pcm)
+ self.assertGreater(sum(a * b for a, b in zip(v, ref["coreml"])), 0.999)
+ self.assertIsNone(speakers.Voiceprints.load().embed(pcm[:4000]), "under half a second")
+
+ def test_clusterer_matches_the_mac(self):
+ c = speakers.VoiceClusterer()
+ a, b = unit(1), unit(2)
+ self.assertIsNone(c.label(a, 1.5), "too short to start a voice")
+ self.assertEqual(0, c.label(a, 3))
+ self.assertEqual(1, c.label(b, 3))
+ self.assertEqual(0, c.label(near(a, 7), 1.0), "joins the closest voice even when short")
+ self.assertEqual(1, c.label(near(b, 8), 3))
+ c.merge(1, 0)
+ self.assertEqual(0, c.label(near(b, 9), 3), "after a merge, either voice goes to the one kept")
+
+ def test_numbers_wait_for_two_voices_with_five_lines(self):
+ lines = [them(i, 0) for i in range(5)]
+ self.assertEqual({}, speakers.voice_numbers(lines), "one voice: still 对方")
+ lines += [them(10 + i, 1) for i in range(4)] + [them(20, 1, "ok")]
+ self.assertEqual({}, speakers.voice_numbers(lines), "a short line doesn't count")
+ lines.append(them(21, 1))
+ self.assertEqual({0: 1, 1: 2}, speakers.voice_numbers(lines))
+ self.assertTrue(speakers.substantive("我们周五上线"))
+ self.assertFalse(speakers.substantive("好的"))
+
+ def test_names_merges_and_undo(self):
+ strings.load("zh-Hans", [os.path.join(REPO, "Resources")])
+ store = SessionStore()
+ s = store.begin()
+ for i in range(5):
+ store.append(s.id, them(i, 0))
+ store.append(s.id, them(10 + i, 1))
+ store.append(s.id, them(30, 2))
+ snap = store.voice_snapshot(s.id)
+ store.set_voice_guesses(s.id, {1: VoiceGuess("George", "00:10 “Thanks, George”")})
+ got = store.get(s.id)
+ 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
+ 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))
+ store.restore(s.id, snap)
+ got = store.get(s.id)
+ self.assertEqual(({}, None, None), (speakers.names(got), got.voiceNames, got.voiceGuesses))
+ self.assertEqual(1, sum(1 for l in got.lines if l.voice == 2))
+ md = session_store.markdown(got, voices=True)
+ self.assertIn("**[00:00] 说话人 1**", md)
+ self.assertIn("**[00:30] 未识别**", md)
+ notes = MeetingNotes(summary="说话人 2 会发说明", topics=[NoteTopic(title="说话人2 的计划")])
+ named = speakers.named(notes, {2: "George"})
+ self.assertEqual(("George 会发说明", "George 的计划"), (named.summary, named.topics[0].title))
+ self.assertEqual("说话人 2 会发说明", notes.summary, "the stored notes are untouched")
+
+ def test_ling_names_need_evidence_near_the_voice(self):
+ s = Session(title="会议", startedAt=datetime(2026, 1, 1, tzinfo=timezone.utc))
+ for i in range(5):
+ s.lines.append(them(2 * i, 0, t=2.0 * i))
+ s.lines.append(them(2 * i + 1, 1, t=2.0 * i + 1))
+ s.lines.append(them(40, 1, "Thanks so much, George, that was clear", t=40))
+ found, refuted = speakers.read('{"speakers": [{"speaker": 2, "name": "George", "evidence": "L11"},'
+ '{"speaker": 1, "name": "Christina", "evidence": "L99"}]}', s)
+ self.assertEqual("George", found[1].name)
+ self.assertTrue(found[1].evidence.startswith("00:40 “Thanks"))
+ self.assertEqual({0: "Christina"}, refuted)
+ self.assertEqual(({}, {}), speakers.read("not json", s))
+ self.assertIn("说话人1", speakers.content(s))
+
+ def test_notes_prompt_names_the_voices(self):
+ lines = [them(i, i % 2) for i in range(10)] + [them(20, None)]
+ p = notesmod.prompt(MeetingNotes(), lines, 0, "Chinese", False, {2: "George"}, voices=True)
+ self.assertIn(" 说话人1] ", p)
+ self.assertIn("George] ", p)
+ self.assertIn("未识别] ", p)
+ 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
+ return reply("LANG: en\nORIGINAL: so we will ship\nTRANSLATION: 所以我们会发布" if first else
+ "LANG: en\nORIGINAL: on Friday then.\nTRANSLATION: 那就周五。")
+ order = iter(voices)
+
+ class Voices:
+ available = True
+
+ def reset(self):
+ pass
+
+ def embed(self, samples):
+ return [float(next(order))]
+
+ def label(self, vector, seconds):
+ return int(vector[0])
+ LingClient.spacing = 0.05
+ ling = client(Fake(respond))
+ store = SessionStore()
+ engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target="zh-CN"))
+ engine.speakers = Voices()
+ heard = []
+ engine.on_voice = heard.append
+ src = PcmAudioSource(lambda: concat(tone(1.0), silence(0.8), tone(1.4), silence(1.0)), speed=0)
+ ended = threading.Event()
+ src.on_ended = lambda why: ended.set()
+ engine.start(src, "file")
+ ended.wait(10)
+ time.sleep(0.2)
+ engine.stop()
+ return [(l.voice, l.src) for l in store.get(engine.session_id).lines], heard
+
+ def test_slow_voiceprints_never_hold_subtitles_back(self):
+ LingClient.spacing = 0.01
+ ling = client(Fake(lambda b: reply("LANG: en\nORIGINAL: We should ship it on Friday.\nTRANSLATION: 我们周五发布。")
+ if "Ming-3.0-audio-flash" in b else reply("{}")))
+ store = SessionStore()
+ engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target="zh-CN"))
+
+ class Slow:
+ available = True
+
+ def reset(self):
+ pass
+
+ def embed(self, samples):
+ time.sleep(0.6) # a CPU that can't keep up
+ return [1.0]
+
+ def label(self, vector, seconds):
+ return 0
+ engine.speakers = Slow()
+ pcm = concat(*([tone(1.0), silence(1.0)] * 5))
+ src = PcmAudioSource(lambda: pcm, speed=0)
+ ended = threading.Event()
+ src.on_ended = lambda why: ended.set()
+ engine.start(src, "file")
+ ended.wait(10)
+ time.sleep(2.5)
+ engine.stop()
+ voices = [l.voice for l in store.get(engine.session_id).lines]
+ self.assertEqual(5, len(voices))
+ self.assertIn(None, voices, "some lines went unlabelled rather than waiting")
+ self.assertIn(0, voices)
+
+ def test_a_half_sentence_joins_only_the_same_voice(self):
+ lines, heard = self._halves([1, 2])
+ self.assertEqual([(1, "so we will ship"), (2, "on Friday then.")], lines)
+ self.assertEqual(2, len(heard))
+ lines, _ = self._halves([1, 1])
+ self.assertEqual([(1, "so we will ship on Friday then.")], lines, "the same voice: one sentence")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/linux/tests/test_meeting_end.py b/linux/tests/test_meeting_end.py
new file mode 100644
index 0000000..6924f38
--- /dev/null
+++ b/linux/tests/test_meeting_end.py
@@ -0,0 +1,173 @@
+"""MeetingEndWatch, the Mac's MeetingEndTests case for case, and reading meeting apps off `pactl`."""
+from __future__ import annotations
+
+import os
+import sys
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from cicada.core.meeting_end import END, OFF, PROMPT, Config, MeetingEndWatch, Pending, Reason, parse_source_outputs # noqa: E402
+
+T0 = 1_000_000.0
+ZOOM = {"zoom": "Zoom"}
+
+
+def watch(silence=PROMPT, follow_apps=True):
+ return MeetingEndWatch(Config(follow_apps=follow_apps, silence=silence), T0)
+
+
+def at(s):
+ return T0 + s
+
+
+class MeetingEndTests(unittest.TestCase):
+ def test_hang_up_ends_after_the_grace(self):
+ w = watch()
+ self.assertIsNone(w.tick(at(10), ZOOM, True))
+ self.assertIsNone(w.tick(at(20), {}, True))
+ self.assertEqual(Pending(Reason("app", "Zoom"), at(50)), w.pending)
+ self.assertIsNone(w.tick(at(49), {}, True))
+ self.assertEqual(Reason("app", "Zoom"), w.tick(at(50), {}, True))
+
+ def test_rejoining_within_the_grace_keeps_going(self):
+ w = watch()
+ w.tick(at(10), ZOOM, True)
+ w.tick(at(20), {}, True)
+ self.assertIsNone(w.tick(at(30), ZOOM, True))
+ self.assertIsNone(w.pending)
+
+ def test_speech_does_not_cancel_a_hang_up(self):
+ w = watch()
+ w.tick(at(10), ZOOM, True)
+ w.tick(at(20), {}, True)
+ w.heard(at(25))
+ self.assertEqual(Reason("app", "Zoom"), w.tick(at(50), {}, True))
+
+ def test_keep_going_forgets_the_hang_up(self):
+ w = watch()
+ w.tick(at(10), ZOOM, True)
+ w.tick(at(20), {}, True)
+ w.keep_going(at(30))
+ self.assertIsNone(w.tick(at(100), {}, True))
+ self.assertIsNone(w.pending)
+
+ def test_silence_prompts_then_ends(self):
+ w = watch()
+ w.heard(at(5))
+ self.assertIsNone(w.tick(at(604), {}, True))
+ self.assertIsNone(w.pending)
+ self.assertIsNone(w.tick(at(605), {}, True))
+ self.assertEqual(Pending(Reason("silence"), at(665)), w.pending)
+ self.assertEqual(Reason("silence"), w.tick(at(665), {}, True))
+
+ def test_words_cancel_the_silence_prompt(self):
+ w = watch()
+ w.tick(at(600), {}, True)
+ self.assertEqual("silence", w.pending.reason.kind)
+ w.heard(at(620))
+ self.assertIsNone(w.pending)
+ self.assertIsNone(w.tick(at(700), {}, True))
+
+ def test_silence_end_mode_ends_at_once_and_off_never(self):
+ self.assertEqual(Reason("silence"), watch(END).tick(at(600), {}, True))
+ off = watch(OFF)
+ self.assertIsNone(off.tick(at(99_999), {}, True))
+ self.assertIsNone(off.pending)
+
+ def test_silence_does_not_count_during_a_call(self):
+ 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
+ self.assertIsNone(plain.tick(at(600), ZOOM, True))
+ self.assertEqual("silence", plain.pending.reason.kind)
+
+ def test_nothing_said_stops_quietly_after_the_silence(self):
+ w = watch()
+ self.assertIsNone(w.tick(at(599), {}, False))
+ self.assertEqual(Reason("nobody"), w.tick(at(600), {}, False))
+ self.assertIsNone(w.pending)
+ self.assertEqual(Reason("nobody"), watch(END).tick(at(600), {}, False))
+ self.assertIsNone(watch(OFF).tick(at(5_000), {}, False))
+ self.assertIsNone(watch().tick(at(5_000), ZOOM, False))
+
+ def test_nothing_said_keeps_listening(self):
+ w = watch()
+ 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
+ self.assertIsNone(w.tick(at(5_002), {}, True))
+ self.assertIsNone(w.pending)
+
+
+PACTL = """Source Output #109
+\tDriver: PipeWire
+\tSource: 101
+\tProperties:
+\t\tnode.name = "input.fakemic"
+\t\tstream.capture.sink = "true"
+\t\tmedia.class = "Stream/Input/Audio"
+Source Output #120
+\tDriver: PipeWire
+\tSource: 55
+\tProperties:
+\t\tapplication.name = "ZOOM VoiceEngine"
+\t\tapplication.process.id = "4321"
+\t\tapplication.process.binary = "zoom"
+\t\tmedia.class = "Stream/Input/Audio"
+Source Output #121
+\tProperties:
+\t\tapplication.name = "ZOOM VoiceEngine"
+\t\tapplication.process.binary = "zoom"
+Source Output #122
+\tProperties:
+\t\tapplication.name = "Firefox"
+\t\tapplication.process.binary = "firefox"
+Source Output #123
+\tProperties:
+\t\tapplication.name = "cicada"
+\t\tapplication.process.id = "777"
+\t\tapplication.process.binary = "python3"
+Source Output #124
+\tProperties:
+\t\tapplication.name = "wemeetapp"
+\t\tapplication.process.binary = "wemeetapp"
+"""
+
+
+class MicStreamTests(unittest.TestCase):
+ def test_only_meeting_apps_reading_a_mic_count(self):
+ self.assertEqual({"zoom": "Zoom", "wemeetapp": "腾讯会议"}, parse_source_outputs(PACTL, own_pid=777))
+
+ def test_nothing_recording(self):
+ self.assertEqual({}, parse_source_outputs(""))
+
+
+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 tempfile
+ from cicada.core.models import TranscriptLine
+ from cicada.core.session_store import SessionStore
+ from cicada.core.support import Paths
+ Paths.home_override = tempfile.mkdtemp()
+ Paths.log_override = os.path.join(Paths.home_override, "debug.log")
+ self.addCleanup(lambda: (setattr(Paths, "home_override", None), setattr(Paths, "log_override", None)))
+ store = SessionStore()
+ sid = store.begin().id
+ heard = []
+ store.on_words(heard.append)
+ store.append(sid, TranscriptLine(id="h1-1", t=0, src="so we will", dst="所以我们会", srcLang="en", dstLang="zh-CN"))
+ store.append(sid, TranscriptLine(id="m1", t=1, speaker="me", src="好的", dst="OK", srcLang="zh-CN", dstLang="en"))
+ store.replace(sid, TranscriptLine(id="h1-1", t=0, src="so we will", dst="所以我们将", srcLang="en", dstLang="zh-CN"))
+ self.assertEqual(2, len(heard), "a retranslation isn't speech")
+ store.replace(sid, TranscriptLine(id="h1-1", t=0, src="so we will ship", dst="所以我们会发布", srcLang="en", dstLang="zh-CN"))
+ self.assertEqual([sid] * 3, heard)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/linux/tests/voiceprint-ref.json b/linux/tests/voiceprint-ref.json
new file mode 100644
index 0000000..669600f
--- /dev/null
+++ b/linux/tests/voiceprint-ref.json
@@ -0,0 +1 @@
+{"clip": "windows/spike/clips/en.wav", "start": 3, "seconds": 4, "coreml": [-0.012143, -0.031368, -0.075807, -0.055855, 0.004361, -0.01287, 0.024247, 0.058096, -0.066418, -0.02478, -0.05108, -0.078528, 0.025887, -0.059856, 0.019392, -0.027981, 0.014737, -0.100881, 0.175727, 0.023966, -0.014191, -0.043558, 0.052121, -0.156095, 0.09944, -0.05044, 0.016738, -0.113737, -0.008776, -0.002911, 0.063217, -0.004311, 0.133689, -0.008062, -0.008402, -0.000681, 0.05004, -0.053614, 0.084449, -0.199414, 0.015097, 0.090851, -0.053561, -0.02334, -0.06151, 0.103815, 0.06023, 0.047159, -0.02554, -0.00161, 0.064231, 0.10947, -0.010663, 0.051481, 0.030355, -0.009609, -0.032595, 0.116191, 0.043452, -0.083969, -0.06087, -0.063751, 0.025607, -0.025794, 0.005918, 0.063004, -0.053881, 0.019259, 0.067165, -0.045426, 0.053214, 0.023153, -0.117258, -0.020632, 0.076927, 0.039664, 0.083062, 0.029448, 0.019525, -0.000566, -0.014417, 0.042678, -0.000739, -0.100454, -0.0261, 0.090264, -0.016871, -0.040838, 0.009996, -0.016231, 0.044359, 0.010369, -0.033022, 0.034303, 0.028994, 0.076821, -0.026794, 0.107176, 0.070899, -0.063857, 0.008229, 0.017965, 0.055375, -0.125261, -0.048733, -0.142332, -0.041638, -0.108136, -0.122913, 0.027768, 0.031262, -0.021286, 0.061083, 0.015471, 0.123127, 0.079595, 0.01059, 0.03625, 0.032595, 0.046706, -0.052441, -0.002141, 0.001729, -0.091918, 0.016685, 0.078048, -0.031155, -0.033769, 0.033582, 0.085783, 0.053454, -0.041718, -0.018232, 0.03569, -0.046893, -0.029768, 0.007635, -0.047826, -0.110537, 0.083169, 0.039451, 0.079702, -0.014471, 0.034383, -0.091065, 0.034516, -0.000408, 0.010843, 0.062257, 0.040091, -0.021112, 0.112884, -0.062844, 0.044785, 0.020179, 0.066951, -0.227902, 0.040091, -0.027087, 0.038971, 0.017178, -0.005171, -0.012237, 0.039504, -0.026567, -0.012297, 0.061137, 0.017071, 0.046786, -0.039104, 0.008062, 0.033396, 0.028461, -0.043718, -0.084183, -0.058416, 0.098693, -0.027954, -0.042331, -0.005785, -0.088344, -0.164738, 0.0506, -0.044679, -0.029048, -0.055215, -0.016004, 0.111283, -0.065671, -0.084556, -0.093785, 0.009609, 0.034836, -0.034063, 0.04892, 0.080022, 0.06151, -0.081302, -0.053294, -0.121099, -0.141692, 0.002262, 0.026687, 0.044572, 0.064124, 0.114911, 0.057189, -0.025327, 0.046252, 0.012957, -0.08669, -0.052201, -0.020899, 0.017405, -0.081515, -0.05991, -0.012763, 0.054948, 0.026941, -0.002204, 0.020552, -0.067965, -0.109576, 0.047213, -0.115978, 0.010256, 0.08637, -0.139558, 0.022099, -5e-06, 0.021539, 0.000398, 0.039371, -0.010389, -0.033822, -0.049373, -0.083489, 0.029821, 0.019792, 0.030141, 0.004898, 0.070366, -0.014177, 0.024713, -0.131769, 0.057936, -0.074047, 0.076021, 0.012163, -0.005808, -0.057189, 0.003168, 0.002626, 0.014911, 0.005668, 0.027087]}
\ No newline at end of file
diff --git a/linux/vm/click.py b/linux/vm/click.py
new file mode 100644
index 0000000..60d8745
--- /dev/null
+++ b/linux/vm/click.py
@@ -0,0 +1,51 @@
+#!/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 fcntl
+import os
+import struct
+import sys
+import time
+
+x, y = int(sys.argv[1]), int(sys.argv[2])
+to = (int(sys.argv[4]), int(sys.argv[5])) if len(sys.argv) > 5 and sys.argv[3] == "--to" else None
+w, h = 1600, 1000
+EV_SYN, EV_KEY, EV_ABS = 0, 1, 3
+ABS_X, ABS_Y, BTN_LEFT = 0, 1, 272
+UI_SET_EVBIT, UI_SET_KEYBIT, UI_SET_ABSBIT = 0x40045564, 0x40045565, 0x40045567
+UI_DEV_CREATE, UI_DEV_DESTROY = 0x5501, 0x5502
+
+fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK)
+for ev in (EV_KEY, EV_ABS):
+ fcntl.ioctl(fd, UI_SET_EVBIT, ev)
+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] * 64
+absmax[ABS_X], absmax[ABS_Y] = w - 1, h - 1
+dev = struct.pack("80sHHHHI", b"cicada-test-pointer", 3, 1, 1, 1, 0) + struct.pack("64i", *absmax) + struct.pack("64i", *([0] * 64)) * 3
+os.write(fd, dev)
+fcntl.ioctl(fd, UI_DEV_CREATE)
+time.sleep(1.0) # let libinput pick the new device up
+
+
+def emit(t, c, v):
+ os.write(fd, struct.pack("llHHi", 0, 0, t, c, v))
+
+
+def sync():
+ emit(EV_SYN, 0, 0)
+
+
+emit(EV_ABS, ABS_X, x); emit(EV_ABS, ABS_Y, y); sync(); time.sleep(0.2)
+emit(EV_KEY, BTN_LEFT, 1); sync(); time.sleep(0.1)
+if to:
+ for i in range(1, 21):
+ emit(EV_ABS, ABS_X, x + (to[0] - x) * i // 20); emit(EV_ABS, ABS_Y, y + (to[1] - y) * i // 20); sync(); time.sleep(0.03)
+emit(EV_KEY, BTN_LEFT, 0); sync(); time.sleep(0.3)
+fcntl.ioctl(fd, UI_DEV_DESTROY)
+os.close(fd)
diff --git a/linux/vm/focus_probe.py b/linux/vm/focus_probe.py
new file mode 100644
index 0000000..cca01b7
--- /dev/null
+++ b/linux/vm/focus_probe.py
@@ -0,0 +1,24 @@
+#!/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 os
+import time
+
+os.environ["GDK_BACKEND"] = "wayland"
+import gi # noqa: E402
+
+gi.require_version("Gtk", "3.0")
+from gi.repository import Gtk # noqa: E402
+
+log = open("/tmp/focus-probe.log", "a", buffering=1)
+w = Gtk.Window(title="Meeting app (focus probe)")
+entry = Gtk.Entry()
+entry.set_text("typing here")
+w.add(entry)
+w.connect("notify::is-active", lambda win, _p: log.write("%.3f active=%s\n" % (time.time(), win.is_active())))
+entry.connect("changed", lambda e: log.write("%.3f text=%s\n" % (time.time(), e.get_text())))
+w.connect("destroy", Gtk.main_quit)
+w.maximize()
+w.show_all()
+Gtk.main()
diff --git a/linux/vm/focus_test.sh b/linux/vm/focus_test.sh
new file mode 100755
index 0000000..7685ad4
--- /dev/null
+++ b/linux/vm/focus_test.sh
@@ -0,0 +1,29 @@
+#!/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 1
+rm -f /tmp/focus-probe.log
+python3 - <<'PY'
+import json, os
+p = os.path.expanduser("~/.config/cicada-dev/settings.json")
+s = json.load(open(p)) if os.path.exists(p) else {}
+s.update(onboarded=True, view="notes")
+open(p, "w").write(json.dumps(s))
+PY
+setsid -f python3 "$bin/focus_probe.py" >/dev/null 2>&1 </dev/null; sleep 2
+setsid -f "$bin/cicada" --dev >/tmp/cicada-app.out 2>&1 </dev/null; sleep 4
+"$bin/cicadactl" show notes; sleep 1
+geo="$("$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
+"$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 1
+before="$("$bin/cicadactl" windows | python3 -c 'import json,sys; n=json.load(sys.stdin)["notes"]; print(n["x"], n["y"])')"
+read -r x y <<<"$before"
+sudo python3 "$bin/click.py" $((x + 200)) $((y + 300)) --to $((x - 400)) $((y + 350)); sleep 1
+echo "drag: $before -> $("$bin/cicadactl" windows | python3 -c 'import json,sys; n=json.load(sys.stdin)["notes"]; print(n["x"], n["y"])')"
diff --git a/linux/vm/fullscreen_probe.py b/linux/vm/fullscreen_probe.py
new file mode 100644
index 0000000..384be3c
--- /dev/null
+++ b/linux/vm/fullscreen_probe.py
@@ -0,0 +1,17 @@
+#!/usr/bin/env python3
+"""A stand-in for a full-screen video player: a native-Wayland GTK window, full screen, black."""
+import os
+os.environ["GDK_BACKEND"] = "wayland"
+import gi # noqa: E402
+gi.require_version("Gtk", "3.0")
+gi.require_version("Gdk", "3.0")
+from gi.repository import Gdk, Gtk # noqa: E402
+w = Gtk.Window(title="Full-screen player (probe)")
+w.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0.05, 0.05, 0.08, 1))
+l = Gtk.Label(label="FULL SCREEN VIDEO")
+l.override_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(1, 1, 1, 1))
+w.add(l)
+w.connect("destroy", Gtk.main_quit)
+w.show_all()
+w.fullscreen()
+Gtk.main()
diff --git a/linux/vm/long_session.py b/linux/vm/long_session.py
new file mode 100644
index 0000000..ce7e5d8
--- /dev/null
+++ b/linux/vm/long_session.py
@@ -0,0 +1,16 @@
+#!/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, sys
+n = int(sys.argv[1]) if len(sys.argv) > 1 else 1500
+sid = "20261101-090000"
+lines = [{"id": "h%d-%d" % (i + 1, i + 1), "t": i * 4.2, "speaker": "them", "src": "Line %d: we went through the release plan and the open questions in some detail." % (i + 1),
+ "dst": "第 %d 句:我们详细过了一遍发布计划和未决问题。" % (i + 1), "srcLang": "en", "dstLang": "zh-CN"} for i in range(n)]
+notes = {"title": "长会议测试", "summary": "一场很长的会议。", "covered": n, "final": True, "conclusions": [], "todos": [], "terms": [],
+ "topics": [{"start": k * 600.0, "title": "话题 %d" % (k + 1), "summary": "", "points": ["要点 A", "要点 B"]} for k in range(8)]}
+s = {"id": sid, "title": "会议 11月1日 09:00", "startedAt": "2026-11-01T01:00:00Z", "endedAt": "2026-11-01T02:45:00Z",
+ "lines": lines, "hasAudio": False, "notes": notes}
+d = os.path.expanduser("~/.local/share/cicada-dev/Sessions/" + sid)
+os.makedirs(d, exist_ok=True)
+json.dump(s, open(d + "/session.json", "w"), ensure_ascii=False)
+print("wrote", n, "lines to", d)
diff --git a/linux/vm/push.sh b/linux/vm/push.sh
new file mode 100755
index 0000000..de87998
--- /dev/null
+++ b/linux/vm/push.sh
@@ -0,0 +1,14 @@
+#!/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 pipefail
+here="$(cd "$(dirname "$0")/.." && pwd)"
+VM="${VM:-$HOME/VMs/cicada-ubuntu}"
+o=(-q -i "$VM/vm_key" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ControlMaster=auto -o ControlPath="$VM/ssh.sock" -o ControlPersist=600)
+ssh "${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.sh
new file mode 100755
index 0000000..496f655
--- /dev/null
+++ b/linux/vm/run.sh
@@ -0,0 +1,34 @@
+#!/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 $VM
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+VM="${VM:-$HOME/VMs/cicada-ubuntu}"
+cd "$VM"
+share=/opt/homebrew/share/qemu
+
+if [ ! -f disk.qcow2 ]; then
+ qemu-img create -q -f qcow2 -F qcow2 -b noble-arm64.img disk.qcow2 40G
+ dd if=/dev/zero of=vars.fd bs=1m count=64 2>/dev/null
+ rm -rf seed && mkdir seed
+ sed "s|@KEY@|$(cat vm_key.pub)|" "$here/user-data" > seed/user-data
+ printf 'instance-id: cicada-ubuntu\nlocal-hostname: cicada-ubuntu\n' > seed/meta-data
+ rm -f seed.iso && hdiutil makehybrid -quiet -iso -joliet -default-volume-name cidata -o seed.iso seed
+fi
+
+# 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" \
+ -drive if=pflash,format=raw,file=vars.fd \
+ -drive file=disk.qcow2,if=virtio,discard=unmap \
+ -drive file=seed.iso,media=cdrom,if=virtio,readonly=on \
+ -device virtio-gpu-pci,xres=1600,yres=1000 -device virtio-keyboard-pci -device virtio-tablet-pci \
+ -audiodev none,id=snd,timer-period=20000 -device virtio-sound-pci,audiodev=snd \
+ -nic user,model=virtio-net-pci,hostfwd=tcp:127.0.0.1:2223-:22 \
+ -vnc 127.0.0.1:2 -monitor unix:"$VM/monitor.sock",server,nowait -daemonize -pidfile "$VM/qemu.pid" </dev/null >/dev/null 2>"$VM/qemu.log" || { cat "$VM/qemu.log" >&2; exit 1; }
+echo "started; ssh: linux/vm/vmctl.sh ssh"
diff --git a/linux/vm/set_scale.py b/linux/vm/set_scale.py
new file mode 100644
index 0000000..1c34fae
--- /dev/null
+++ b/linux/vm/set_scale.py
@@ -0,0 +1,18 @@
+#!/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 sys
+from gi.repository import Gio, GLib
+want = float(sys.argv[1])
+bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+def call(method, args=None):
+ return bus.call_sync("org.gnome.Mutter.DisplayConfig", "/org/gnome/Mutter/DisplayConfig", "org.gnome.Mutter.DisplayConfig",
+ method, args, None, Gio.DBusCallFlags.NONE, 5000, None).unpack()
+serial, monitors, logical, _props = call("GetCurrentState")
+(connector, *_), modes, _mprops = monitors[0]
+mode = next(m for m in modes if m[6].get("is-current"))
+scales = mode[5]
+scale = min(scales, key=lambda s: abs(s - want))
+print("connector", connector, "mode", mode[0], "scales", [round(s, 3) for s in scales], "->", scale)
+call("ApplyMonitorsConfig", GLib.Variant("(uua(iiduba(ssa{sv}))a{sv})",
+ (serial, 1, [(0, 0, scale, 0, True, [(connector, mode[0], {})])], {})))
diff --git a/linux/vm/user-data b/linux/vm/user-data
new file mode 100644
index 0000000..e41cb41
--- /dev/null
+++ b/linux/vm/user-data
@@ -0,0 +1,42 @@
+#cloud-config
+# The test VM: user "cicada", the host's key, a minimal GNOME desktop logged in automatically
+# (Wayland, Ubuntu's default). Apt goes through the host's proxy at 10.0.2.2:7890 when it's there.
+users:
+ - name: cicada
+ groups: [sudo, audio, video]
+ shell: /bin/bash
+ sudo: ALL=(ALL) NOPASSWD:ALL
+ lock_passwd: false
+ plain_text_passwd: cicada
+ ssh_authorized_keys: ["@KEY@"]
+ssh_pwauth: false
+bootcmd:
+ - "sh -c 'nc -z -w2 10.0.2.2 7890 && printf \"Acquire::http::Proxy \\\"http://10.0.2.2:7890\\\";\\nAcquire::https::Proxy \\\"http://10.0.2.2:7890\\\";\\n\" > /etc/apt/apt.conf.d/90proxy || true'"
+write_files:
+ # No screen lock or blanking: screenshots and tests run unattended.
+ - path: /etc/dconf/profile/user
+ content: |
+ user-db:user
+ system-db:local
+ - path: /etc/dconf/db/local.d/00-cicada-test
+ content: |
+ [org/gnome/desktop/session]
+ idle-delay=uint32 0
+ [org/gnome/desktop/screensaver]
+ lock-enabled=false
+ idle-activation-enabled=false
+ - path: /etc/gdm3/custom.conf
+ content: |
+ [daemon]
+ AutomaticLoginEnable=true
+ AutomaticLogin=cicada
+# The desktop is installed in runcmd rather than `packages:` so a slow mirror is retried and logged
+# (/var/log/cicada-provision.log), then GDM starts in place: no reboot, which hung under HVF.
+runcmd:
+ - "sh -c 'for i in 1 2 3; do DEBIAN_FRONTEND=noninteractive apt-get update -q && DEBIAN_FRONTEND=noninteractive apt-get install -y -q -o Dpkg::Options::=--force-confold ubuntu-desktop-minimal linux-modules-extra-$(uname -r) pulseaudio-utils xdotool x11-utils && break; sleep 10; done > /var/log/cicada-provision.log 2>&1'"
+ - dconf update
+ - systemctl set-default graphical.target
+ - sudo -u cicada mkdir -p /home/cicada/.config
+ - "sh -c 'echo yes > /home/cicada/.config/gnome-initial-setup-done'"
+ - "sh -c 'chown -R cicada:cicada /home/cicada/.config'"
+ - systemctl isolate graphical.target --no-block
diff --git a/linux/vm/vmctl.sh b/linux/vm/vmctl.sh
new file mode 100755
index 0000000..5e5f751
--- /dev/null
+++ b/linux/vm/vmctl.sh
@@ -0,0 +1,26 @@
+#!/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 stop
+set -euo pipefail
+VM="${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:-}" in
+ ssh) 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 1
+ sips -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 ;;
+esac