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): Interpreting can speak in your own voice: record 10–15 s in Settings and the room hears the translation in it

wquguruae02317c5144
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index 6d1fbf9..9a4c05b 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -27,7 +27,11 @@ per connection, one JSON line back. Never in release builds.
| copy all|link|password | revoke | close | state
export-folder <path>|off|on (存到文件夹: choose a folder as 存到这里 does, and its check) |
export-state (folder, problem, index, the records not written yet) | export-all (也存一份) | export-retry |
- export-choose (open 存到哪里, as 更改… does; answer it with the dialog itself)"""
+ export-choose (open 存到哪里, as 更改… does; answer it with the dialog itself)
+ voice <lang> | voice <lang>=<id> (the voice a language uses: "voice en=clone", "voice zh=灵小锋")
+ voice-clone <wav>|off|state (我自己的声音 from a 16 kHz WAV: Ming hears it, the Mac's checks, then kept; state
+ says the last result and the files' modes) | voice-preview [<lang>] (试听 in that language: what played)
+ voice-dialog open|feed <wav>|finish|play original|clone|save|close|state (the record sheet, a WAV as the mic)"""
from __future__ import annotations
import os
@@ -360,6 +364,8 @@ def command(app, line: str) -> dict:
app.toggle_speaking()
# echoCancelled: this press reads the talk key's echo canceller (else the plain mic, echo drop on)
return {"ok": True, "speaking": app.speak.active, "echoCancelled": app.speak.echo_cancelled}
+ if cmd.startswith("voice"):
+ return _voice(app, cmd, arg)
if cmd == "codecs":
from . import media
return {"ok": True, **media.codecs(), "recordAudio": app.settings.recordAudio, "recording": listen.recording}
@@ -743,6 +749,110 @@ def _fixes(app, cmd: str, arg: str) -> dict:
return {"ok": False, "error": "unknown command " + cmd}
+def _voice(app, cmd: str, arg: str) -> dict:
+ """我自己的声音 without a microphone: the network runs on a thread and `state` reads the result."""
+ from ..core import voice_reference as vref
+ from ..core import voices as voicemod
+ from ..core.audio import PcmAudioSource, RATE, Wav
+ sw = app.settings_window
+
+ def refresh():
+ if sw is not None and hasattr(sw, "_fill_voices"):
+ sw._fill_voices()
+ if cmd == "voice":
+ lang, _, vid = arg.partition("=")
+ if vid:
+ app.settings.speakVoices[voicemod.key(lang)] = vid
+ app.settings.save()
+ refresh()
+ Log.d("voice %s -> %s clone=%s" % (lang, app.speak.voice(lang), vref.exists()))
+ return {"ok": True, "lang": lang, "chosen": (app.settings.speakVoices or {}).get(voicemod.key(lang)),
+ "uses": app.speak.voice(lang), "options": [v for v, _n, _t in voicemod.voices(lang, app.ling.config())],
+ "clone": vref.exists(), "clones": voicemod.clones(app.ling.config())}
+ if cmd == "voice-clone":
+ if arg == "off":
+ if sw is not None:
+ sw.remove_voice()
+ else:
+ vref.remove()
+ return {"ok": True, "exists": vref.exists()}
+ if arg in ("", "state"):
+ out = {"ok": True, "exists": vref.exists(), "last": getattr(app, "voice_debug", None)}
+ if vref.exists():
+ out.update({"seconds": round(vref.duration(), 2), "textChars": len(vref.text() or ""), "slow": vref.saved_is_slow(),
+ "modes": [oct(os.stat(p).st_mode & 0o777) for p in (vref.folder(), vref.audio_path(), vref.text_path())]})
+ return out
+ app.voice_debug = {"running": True}
+
+ def run():
+ from .voice_clone import transcribe
+ samples = vref.trim(Wav.read_file(arg))
+ try:
+ text = transcribe(app, samples)
+ except Exception as e: # noqa: BLE001
+ app.voice_debug = {"running": False, "error": str(e)}
+ return
+ why = vref.check(samples, text)
+ p = vref.pace(text, samples)
+ if why is None:
+ vref.save(samples, text)
+ app.voice_debug = {"running": False, "seconds": round(len(samples) / RATE, 2), "textChars": len(text),
+ "pace": round(p, 2) if p else None, "why": why, "saved": why is None}
+ GLib.idle_add(lambda: refresh() or False)
+ threading.Thread(target=run, daemon=True).start()
+ return {"ok": True, "started": True}
+ if cmd == "voice-preview":
+ code = arg or app.speak.target
+ app.voice_debug = {"running": True}
+
+ def play():
+ from .room import Player
+ from .settings_window import PREVIEW
+ text = PREVIEW.get(code[:2], PREVIEW["en"])
+ uses = app.speak.voice(code)
+ start, n, first = time.monotonic(), 0, None
+ out = Player(None)
+ try:
+ for pcm in app.speak.speech(text, code):
+ if first is None:
+ first = time.monotonic() - start
+ n += len(pcm)
+ out.write(pcm)
+ out.drain()
+ app.voice_debug = {"running": False, "voice": uses, "seconds": round(n / 2 / 24000, 2),
+ "firstSound": round(first or 0, 2), "took": round(time.monotonic() - start, 2)}
+ except Exception as e: # noqa: BLE001
+ app.voice_debug = {"running": False, "voice": uses, "error": str(e)}
+ finally:
+ out.close()
+ threading.Thread(target=play, daemon=True).start()
+ return {"ok": True, "started": True}
+ if cmd == "voice-dialog":
+ what, _, rest = arg.partition(" ")
+ d = getattr(sw, "voice_dialog", None)
+ if what == "open":
+ app.show_settings()
+ app.settings_window.record_voice()
+ return {"ok": True}
+ if d is None or d.window is None:
+ return {"ok": False, "error": "no dialog"}
+ r = d.recorder
+ if what == "feed": # the WAV as the microphone, in real time; the recording stops when it ends
+ d.consent = True
+ r.start(PcmAudioSource(rest))
+ elif what == "finish":
+ r.finish()
+ elif what == "play":
+ d.play(rest)
+ elif what == "save":
+ d.save()
+ elif what == "close":
+ d.close(False)
+ return {"ok": True, "phase": r.phase, "why": r.why, "seconds": round(r.seconds, 1), "textChars": len(r.transcript),
+ "playing": d.playing, "consent": d.consent}
+ return {"ok": False, "error": "unknown command " + cmd}
+
+
def _ai(app) -> dict:
"""The AI service in use and what its last check found (never the key itself)."""
c, ling = app.ling.config(), app.ling
diff --git a/linux/cicada/app/room.py b/linux/cicada/app/room.py
index 7f9230b..3f65d4f 100644
--- a/linux/cicada/app/room.py
+++ b/linux/cicada/app/room.py
@@ -364,15 +364,15 @@ class EchoCanceller:
class Player:
- """Plays 24 kHz mono 16-bit PCM into a sink: 知了 麦克风's (the room) or, for 试听, the speakers."""
+ """Plays 24 kHz (or `rate`) mono 16-bit PCM into a sink: 知了 麦克风's (the room) or, for 试听, the speakers."""
- def __init__(self, device: str | None = SINK):
+ def __init__(self, device: str | None = SINK, rate: int = TTS_RATE):
lib = _pulse()
lib.pa_simple_write.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_int)]
lib.pa_simple_drain.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)]
self.lib = lib
- spec = _Spec(PA_SAMPLE_S16LE, TTS_RATE, 1)
- attr = _Attr(0xFFFFFFFF, TTS_RATE // 5 * 2, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) # ~200 ms buffered
+ spec = _Spec(PA_SAMPLE_S16LE, rate, 1)
+ attr = _Attr(0xFFFFFFFF, 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))
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index c0a28c8..3ef94c7 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -13,6 +13,8 @@ from gi.repository import Gdk, GLib, Gtk, Pango
from .. import VERSION
from ..core import ling as lingmod
+from ..core import voice_reference
+from ..core import voices as voicemod
from ..core.ling import AIKey
from ..core.strings import L, LF
from ..core.support import TARGETS, Paths, follow_system_target, my_language, system_languages
@@ -418,6 +420,13 @@ class SettingsWindow(Gtk.Window):
[(c, names.get(c, c)) for c in voicemod.ROOM_LANGUAGES], s.speakTo, set_to)
voice = Gtk.ComboBoxText()
voice.set_size_request(170, -1)
+ # 我自己的声音, under 声音: redrawn with the voices (a new recording, another service).
+ clone_slot = Gtk.EventBox()
+
+ def fill_clone():
+ ui.clear(clone_slot)
+ clone_slot.add(self._clone_row())
+ clone_slot.show_all()
def fill_voices():
code = app.speak.target
@@ -425,15 +434,19 @@ class SettingsWindow(Gtk.Window):
voice.remove_all()
for v, n, tags in voicemod.voices(code, app.ling.config()):
voice.append(v, "%s · %s" % (n, "、".join(L(t) for t in tags)))
+ if voice_reference.exists() and app.ling.usable and voicemod.clones(app.ling.config()):
+ voice.append(voicemod.CLONE, L("我自己的声音"))
voice.set_active_id(app.speak.voice(code) or "")
if getattr(voice, "_wired", False):
voice.handler_unblock_by_func(set_voice)
+ fill_clone()
def set_voice(w):
v = w.get_active_id()
if v:
s.speakVoices[voicemod.key(app.speak.target)] = v
s.save()
+ fill_clone()
fill_voices()
voice.connect("changed", set_voice)
voice._wired = True
@@ -450,8 +463,7 @@ class SettingsWindow(Gtk.Window):
p = Player(None) # the speakers, not the room
start, n = time.monotonic(), 0
try:
- for pcm in app.ling.speech(text, voice=app.speak.voice(code) or "US_Emma",
- language=voicemod.ming_language(code, app.ling.config())):
+ for pcm in app.speak.speech(text, code, voice=app.speak.voice(code) or "US_Emma"):
n += len(pcm)
p.write(pcm)
p.drain()
@@ -461,6 +473,7 @@ class SettingsWindow(Gtk.Window):
finally:
p.close()
threading.Thread(target=run, daemon=True).start()
+ self._preview_voice = preview
voice_box = ui.hbox(8, voice, ui.button(L("试听"), preview, "outline"))
self.voice_box = voice_box
combos.extend([mine, theirs, voice])
@@ -470,6 +483,8 @@ class SettingsWindow(Gtk.Window):
r = ui.prow(title, control, sub)
dependents.append(r)
rows.append(r)
+ dependents.append(clone_slot)
+ rows.append(clone_slot)
short = self._shortcut_row("speak")
dependents.append(short)
rows.append(short)
@@ -500,6 +515,46 @@ class SettingsWindow(Gtk.Window):
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 _clone_row(self) -> Gtk.Widget:
+ """我自己的声音 (VoicePicker.swift › cloneRow): 录制 until there is a recording, then how long
+ it is and how it will sound, with 重录 / 删除. Only Ling clones: elsewhere it says so."""
+ app, s = self.app, self.app.settings
+ code = app.speak.target
+ title = L("我自己的声音")
+ if not voicemod.clones(app.ling.config()):
+ return ui.prow(title, ui.soft_button(L("去换成 Ling"), lambda: app.show_settings(ai=True)), L("只有 Ling 能用你自己的声音"))
+ if not voice_reference.exists():
+ b = ui.soft_button(L("录制"), self.record_voice, dark=True)
+ b.set_sensitive(app.ling.usable)
+ return ui.prow(title, b, L("录 15 秒原声,对方听到你的音色,晚约 3 秒"))
+ if voice_reference.saved_is_slow():
+ note = L("读得偏慢")
+ else:
+ note = L("最像你") if voicemod.key(s.speak_from_code) == voicemod.key(code) else L("会带你的口音")
+ controls = ui.hbox(8, ui.soft_button(L("重录"), self.record_voice), ui.soft_button(L("删除"), self.remove_voice))
+ row = ui.prow(title, controls, LF("已录 %lld 秒 · %@", int(round(voice_reference.duration())), note))
+ if app.speak.voice(code) == voicemod.CLONE:
+ ui.classes(row, "voicewash")
+ return row
+
+ def record_voice(self) -> None:
+ from .voice_clone import VoiceCloneDialog
+ self.voice_dialog = VoiceCloneDialog(self.app, self, lambda saved: self._voice_done())
+
+ def _voice_done(self) -> None:
+ self.voice_dialog = None
+ if hasattr(self, "_fill_voices"):
+ self._fill_voices()
+
+ def remove_voice(self) -> None:
+ """The recording goes, and every language that used it is back on its default voice."""
+ s = self.app.settings
+ voice_reference.remove()
+ s.speakVoices = {k: v for k, v in (s.speakVoices or {}).items() if v != voicemod.CLONE}
+ s.save()
+ if hasattr(self, "_fill_voices"):
+ self._fill_voices()
+
def _room_group(self):
"""会议室: the microphone 打开麦克风 hears the room with (自动 picks as roommic.pick does). Whether
it hears the speakers is measured (roommic.EchoGate), not asked."""
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
index 318bc91..270fa4d 100644
--- a/linux/cicada/app/ui.py
+++ b/linux/cicada/app/ui.py
@@ -53,6 +53,8 @@ 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:disabled { background-color: #C9CCD3; }
+button.darkbtn:disabled label { color: #FFFFFF; }
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; }
@@ -405,6 +407,22 @@ entry.keyentry { border-radius: 10px; min-height: 34px; }
.stepbar.on { background-color: #15171C; }
.bigcard { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 18px; }
.raised { background-color: #F6F7F9; border-radius: 8px; }
+/* The own-voice row and sheet (VoicePicker.swift): an accent wash for the voice the room hears. */
+.voicewash { background-color: #FFFAF8; }
+.voicemeter { background-color: #FFFAF8; border-radius: 12px; }
+.voicefail { background-color: #FDECEA; border-radius: 12px; }
+.voicefail label { color: #B42318; }
+.voicerows { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 14px; }
+.voicepassage { background-color: #F6F7F9; border-radius: 14px; }
+button.voiceplay { background-image: none; background-color: #F2F3F5; border: none; box-shadow: none; border-radius: 16px; min-width: 32px; min-height: 32px; padding: 0; color: #15171C; }
+button.voiceplay.accent { background-color: #E8552B; color: #FFFFFF; }
+button.voiceplay.accent image { color: #FFFFFF; }
+button.voiceplay.accent spinner { color: #FFFFFF; }
+checkbutton.voicecheck check { background-image: none; background-color: #FFFFFF; border: 1px solid #B8BCC4; border-radius: 4px; min-width: 14px; min-height: 14px; box-shadow: none; color: transparent; }
+checkbutton.voicecheck check:checked { background-color: #15171C; border-color: #15171C; color: #FFFFFF; }
+checkbutton.voicecheck check:disabled { background-color: #F3F4F6; }
+checkbutton.voicecheck check:checked:disabled { background-color: #8A8E98; border-color: #8A8E98; }
+.voicetag { background-color: #E8552B; color: #FFFFFF; border-radius: 5px; padding: 1px 6px; }
.midcard { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 12px; }
.tipcard { background-color: #FFFFFF; border-radius: 14px; }
.hair { background-color: #E4E6EA; min-height: 1px; }
diff --git a/linux/cicada/app/voice_clone.py b/linux/cicada/app/voice_clone.py
new file mode 100644
index 0000000..e3f672a
--- /dev/null
+++ b/linux/cicada/app/voice_clone.py
@@ -0,0 +1,411 @@
+"""我自己的声音 (the Mac's VoiceCloneSheet and VoiceRecorder): read a passage for 10–15 s, Ming hears
+what it says, listen to the original and to the clone, then keep it (voice_reference). The
+recording stays in memory until 用这个声音; the network runs on worker threads."""
+from __future__ import annotations
+
+import threading
+from array import array
+
+from gi.repository import GLib, Gtk
+
+from ..core import voice_reference as ref
+from ..core import voices as voicemod
+from ..core.audio import RATE, Wav
+from ..core.ling import LingError
+from ..core.strings import L, LF
+from ..core.support import TARGETS, Log, clock
+from . import ui
+
+
+def own_and_other(app) -> tuple:
+ """My language, and one to interpret it into (the room's, else English or Chinese): Ming hears
+ the recording through the interpreting prompt, whose ORIGINAL line is what it says."""
+ mine = app.settings.speak_from_code
+ other = app.speak.target
+ if voicemod.key(other) == voicemod.key(mine):
+ other = "en" if voicemod.key(mine) != "en" else "zh-CN"
+ return mine, other
+
+
+def transcribe(app, samples: array) -> str:
+ """What the recording says, as Ming hears it; "" when it heard nothing usable."""
+ mine, other = own_and_other(app)
+ heard = app.translator.interpret(Wav.bytes(samples), mine, other)
+ return heard[0].strip() if heard else ""
+
+
+class Recorder:
+ """The microphone into memory, 16 kHz mono, stopping by itself at 15 s. Phases as on the Mac:
+ idle, recording, checking (Ming hears it), ready, failed (`why`). `on_change` comes on the main loop."""
+
+ def __init__(self, app, on_change):
+ self.app = app
+ self.on_change = on_change
+ self.phase = "idle"
+ self.why = ""
+ self.samples = array("h")
+ self.level = 0.0
+ self.transcript = ""
+ self._lock = threading.Lock()
+ self._source = None
+ self._tick = None
+ self._gen = 0
+
+ @property
+ def seconds(self) -> float:
+ return len(self.samples) / RATE
+
+ def start(self, source=None) -> None:
+ """`source`: an AudioSource (a WAV for tests); else the real microphone, not 知了 麦克风."""
+ from .capture import SystemAudio
+ self.cancel()
+ self._gen += 1
+ gen = self._gen
+ self.samples = array("h")
+ self.transcript = ""
+ self.why = ""
+ if source is None:
+ real = self.app.room.real_mic if self.app.room.on else None
+ source = SystemAudio(real or "@DEFAULT_SOURCE@", name=L("录制你的声音"))
+
+ def got(samples):
+ if gen != self._gen:
+ return
+ with self._lock:
+ self.samples.extend(samples)
+ if samples:
+ self.level = (sum(x * x for x in samples) / len(samples)) ** 0.5 / 32768.0 # RMS; ui.loudness shows it
+
+ def ended(why):
+ if gen != self._gen:
+ return
+ if why:
+ Log.d("voice clone: microphone ended %s" % why)
+ GLib.idle_add(lambda: self._fail(L("麦克风没收到声音,请检查麦克风权限")) or False)
+ else: # a file ran out
+ GLib.idle_add(lambda: self.finish() or False)
+ source.on_samples = got
+ source.on_ended = ended
+ self._source = source
+ self.phase = "recording"
+ source.start()
+ self._tick = GLib.timeout_add(100, self._tock)
+ self.on_change()
+
+ def _tock(self) -> bool:
+ if self.phase != "recording":
+ self._tick = None
+ return False
+ if self.seconds >= ref.MAX_SECONDS:
+ self._tick = None
+ self.finish()
+ return False
+ self.on_change()
+ return True
+
+ def _stop(self) -> None:
+ if self._source is not None:
+ self._source.stop()
+ self._source = None
+ if self._tick is not None:
+ GLib.source_remove(self._tick)
+ self._tick = None
+ self.level = 0.0
+
+ def _fail(self, why: str) -> None:
+ self._stop()
+ self.phase, self.why = "failed", why
+ self.on_change()
+
+ def finish(self) -> None:
+ """Stops and has Ming hear it; ready when it is long enough, understood and not too slow."""
+ if self.phase != "recording":
+ return
+ self._stop()
+ with self._lock:
+ samples = ref.trim(self.samples[:int(ref.MAX_SECONDS * RATE)])
+ self.samples = samples
+ if self.seconds < ref.MIN_SECONDS:
+ self._fail(LF("录音太短了,请至少朗读 %lld 秒", int(ref.MIN_SECONDS)))
+ return
+ self.phase = "checking"
+ self.on_change()
+ gen = self._gen
+
+ def run():
+ try:
+ text = transcribe(self.app, samples)
+ failed = None
+ except LingError as e:
+ text, failed = "", e
+ why = ref.check(samples, text)
+ Log.d("voice clone: %.1f s, %d chars, %s" % (len(samples) / RATE, len(text), failed or why or "ok"))
+
+ def done():
+ if gen != self._gen:
+ return False
+ self.transcript = text
+ if failed is not None and failed.kind in (LingError.NETWORK, LingError.TIMEOUT):
+ self._fail(L("连不上 Ling,检查网络或代理"))
+ elif why == "unclear" or failed is not None:
+ self._fail(L("没听清录音内容,请换个安静的地方再录一次"))
+ elif why == "slow":
+ self._fail(L("读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次"))
+ else:
+ self.phase = "ready"
+ self.on_change()
+ return False
+ GLib.idle_add(done)
+ threading.Thread(target=run, name="VoiceClone", daemon=True).start()
+
+ def cancel(self) -> None:
+ self._gen += 1
+ self._stop()
+ self.phase = "idle"
+
+
+class VoiceCloneDialog:
+ """The sheet: record, then review. `on_done(saved)` when it closes."""
+
+ def __init__(self, app, parent=None, on_done=None):
+ self.app = app
+ self.on_done = on_done
+ self.consent = False
+ self.playing = None # "original" or "clone" while one plays
+ self._play_gen = 0
+ self.recorder = Recorder(app, self.render)
+ d = Gtk.Dialog(transient_for=parent, modal=True)
+ d.set_decorated(False)
+ d.set_resizable(False)
+ ui.classes(d, "endask", "sharesheet")
+ d.connect("key-press-event", self._key)
+ d.connect("destroy", lambda *_: self._gone())
+ self.window = d
+ self.body = ui.vbox(16)
+ self.body.set_size_request(504, -1) # 560 with the padding, as on the Mac
+ d.get_content_area().pack_start(ui.pad(self.body, 28), True, True, 0)
+ self._last = None
+ self.render()
+ d.show_all()
+
+ @property
+ def target(self) -> str:
+ return self.app.speak.target
+
+ def _key(self, _w, ev) -> bool:
+ from gi.repository import Gdk
+ if ev.keyval == Gdk.KEY_Escape:
+ self.close(False)
+ return True
+ return False
+
+ def _gone(self) -> None:
+ self.recorder.cancel()
+ self._play_gen += 1
+ if self.window is not None:
+ self.window = None
+ if self.on_done:
+ self.on_done(False)
+ self.on_done = None
+
+ def close(self, saved: bool) -> None:
+ cb, self.on_done = self.on_done, None
+ w, self.window = self.window, None
+ self.recorder.cancel()
+ self._play_gen += 1
+ if w is not None:
+ w.destroy()
+ if cb:
+ cb(saved)
+
+ # Layout
+
+ def render(self) -> None:
+ if self.window is None:
+ return
+ r = self.recorder
+ # The meter ticks ten times a second: only its labels change then, not the whole sheet.
+ shape = (r.phase, r.why, self.consent, self.playing, self.app.ling.speaks)
+ if shape == self._last and r.phase == "recording" and hasattr(self, "_clock"):
+ ui.retext(self._clock, clock(r.seconds))
+ self._bar.set_fraction(min(1.0, r.seconds / ref.MAX_SECONDS))
+ self._level.set_value(ui.loudness(r.level))
+ return
+ self._last = shape
+ ui.clear(self.body)
+ (self._review if r.phase == "ready" else self._record)()
+ self.body.show_all()
+ GLib.idle_add(lambda: self.window is not None and self.window.resize(1, 1) and False)
+
+ def _heading(self, title: str, sub: str) -> None:
+ self.body.pack_start(ui.vbox(6, ui.text(title, 18, "ink", bold=True), ui.text(sub, 13, "secondary", width_chars=50)),
+ False, False, 0)
+
+ def _buttons(self, left, right) -> None:
+ row = ui.hbox(8)
+ row.pack_start(left, False, False, 0)
+ row.pack_end(right, False, False, 0)
+ self.body.pack_start(row, False, False, 0)
+
+ def _record(self) -> None:
+ r = self.recorder
+ self._heading(L("录制你的声音"), L("请用平时开会的自然语气朗读以下段落,约 15 秒,在安静环境下录制效果最佳。"))
+ passage = ui.text(ref.passage(self.app.settings.speak_from_code), 16, "ink", width_chars=44, selectable=True)
+ self.body.pack_start(ui.panel(ui.pad(passage, 16, 20), "voicepassage"), False, False, 0)
+ if r.phase == "recording":
+ meter = ui.hbox(14)
+ meter.pack_start(ui.breathing_dot(), False, False, 0)
+ self._clock = ui.text(clock(r.seconds), 14, "ink", bold=True, wrap=False)
+ meter.pack_start(self._clock, False, False, 0)
+ self._level = Gtk.LevelBar()
+ self._level.set_value(ui.loudness(r.level))
+ self._level.set_valign(Gtk.Align.CENTER)
+ meter.pack_start(self._level, True, True, 0)
+ meter.pack_end(ui.text(LF("%lld–%lld 秒", int(ref.MIN_SECONDS), int(ref.MAX_SECONDS)), 12, "tertiary", wrap=False), False, False, 0)
+ self._bar = Gtk.ProgressBar()
+ self._bar.set_fraction(min(1.0, r.seconds / ref.MAX_SECONDS))
+ self.body.pack_start(ui.panel(ui.pad(ui.vbox(10, meter, self._bar), 12, 16), "voicemeter"), False, False, 0)
+ elif r.phase == "failed":
+ self.body.pack_start(ui.panel(ui.pad(ui.text(r.why, 12, "", width_chars=50), 12), "voicefail"), False, False, 0)
+ check = Gtk.CheckButton()
+ ui.classes(check, "voicecheck")
+ check.add(ui.text(L("这是我自己的声音。只在我说话时用它替我翻译。"), 12, "secondary", width_chars=46))
+ check.set_active(self.consent)
+ check.set_sensitive(r.phase != "recording")
+
+ def toggled(w):
+ self.consent = w.get_active()
+ self.render()
+ check.connect("toggled", toggled)
+ self.body.pack_start(check, False, False, 0)
+ cancel = ui.soft_button(L("取消"), lambda: self.close(False))
+ if r.phase == "recording":
+ go = ui.soft_button(L("读完了"), r.finish, dark=True)
+ go.set_sensitive(r.seconds >= ref.MIN_SECONDS)
+ GLib.timeout_add(int(max(0.0, ref.MIN_SECONDS - r.seconds) * 1000) + 50,
+ lambda: self.window is not None and go.set_sensitive(True) and False)
+ elif r.phase == "checking":
+ go = ui.hbox(8, Gtk.Spinner(active=True), ui.text(L("正在听写…"), 12, "secondary", wrap=False))
+ else:
+ go = ui.soft_button(L("开始录") if r.phase == "idle" else L("再录一次"), lambda: r.start(), dark=True)
+ go.set_sensitive(self.consent)
+ self._buttons(cancel, go)
+
+ def _review(self) -> None:
+ r = self.recorder
+ self._heading(L("录好了,先听听像不像"), LF("%lld 秒 · 识别出的文字会与录音一起用于学习你的音色", int(round(r.seconds))))
+ names = {voicemod.key(c): n for n, c in TARGETS}
+ title = LF("用你的声音说%@", names.get(voicemod.key(self.target), self.target))
+ rows = ui.vbox(0, self._row("original", False, L("你的原声"), r.transcript),
+ self._row("clone", True, title, voicemod.sample(self.target), L("对方会听到这个")))
+ rows.get_children()[1].get_style_context().add_class("prow-top")
+ self.body.pack_start(ui.panel(rows, "voicerows"), False, False, 0)
+ if not self._clones():
+ self.body.pack_start(ui.text(L("需先在“AI 服务”中填入 Ling key,才能使用你自己的声音。"), 12, "warn", width_chars=50), False, False, 0)
+ self.body.pack_start(ui.text(L("听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。"), 12, "tertiary", width_chars=50),
+ False, False, 0)
+ use = ui.soft_button(L("用这个声音"), self.save, dark=True)
+ use.set_sensitive(self._clones())
+ self._buttons(ui.soft_button(L("重录"), self.rerecord), use)
+
+ def _clones(self) -> bool:
+ return self.app.ling.usable and voicemod.clones(self.app.ling.config())
+
+ def _row(self, which: str, accent: bool, title: str, detail: str, tag: str | None = None) -> Gtk.Widget:
+ row = ui.hbox(12)
+ b = Gtk.Button()
+ if self.playing == which and which == "clone":
+ b.add(Gtk.Spinner(active=True))
+ else:
+ b.add(ui.icon("media-playback-stop-symbolic" if self.playing == which else "media-playback-start-symbolic", 12))
+ ui.classes(b, "voiceplay", "accent" if accent else "")
+ b.set_valign(Gtk.Align.CENTER)
+ b.get_accessible().set_name(title)
+ b.connect("clicked", lambda *_: self.play(which))
+ b.set_sensitive(which == "original" or self._clones())
+ row.pack_start(b, False, False, 0)
+ words = ui.vbox(2, ui.text(title, 13, "ink", bold=True, wrap=False), ui.text(detail, 12, "tertiary", wrap=False))
+ for l in words.get_children():
+ l.set_max_width_chars(36) # one line each, cut short, so the sheet keeps the Mac's width
+ row.pack_start(words, True, True, 0)
+ if tag:
+ t = ui.text(tag, 11, "", wrap=False)
+ ui.classes(t, "voicetag")
+ t.set_valign(Gtk.Align.CENTER)
+ row.pack_end(t, False, False, 0)
+ return ui.panel(ui.pad(row, 12, 14), "voicewash" if accent else "")
+
+ # Actions
+
+ def rerecord(self) -> None:
+ self._play_gen += 1
+ self.playing = None
+ self.recorder.start()
+
+ def play(self, which: str) -> None:
+ """The original from memory, or the clone saying the sample line, on the speakers."""
+ from .room import Player
+ if self.playing == which:
+ self._play_gen += 1
+ self.playing = None
+ self.render()
+ return
+ self._play_gen += 1
+ gen = self._play_gen
+ self.playing = which
+ self.render()
+ r = self.recorder
+ samples, transcript, target = r.samples, r.transcript, self.target
+ ling = self.app.ling
+
+ def run():
+ out = None
+ n = 0
+ try:
+ if which == "original":
+ out = Player(None, rate=RATE)
+ data = samples.tobytes()
+ for i in range(0, len(data), RATE // 5 * 2):
+ if gen != self._play_gen:
+ break
+ out.write(data[i:i + RATE // 5 * 2])
+ n += 1
+ else:
+ clip = ("data:audio/wav;base64," + __import__("base64").b64encode(Wav.bytes(samples)).decode(), transcript)
+ lang = voicemod.ming_language(target, ling.config())
+ for pcm in ling.speech(voicemod.sample(target), voice=None, language=lang, reference=clip):
+ if gen != self._play_gen:
+ break
+ if out is None:
+ out = Player(None)
+ out.write(pcm)
+ n += 1
+ if out is not None and gen == self._play_gen:
+ out.drain()
+ Log.d("voice clone: played %s, %d chunks" % (which, n))
+ except Exception as e: # noqa: BLE001
+ Log.d("voice clone: play %s failed %s" % (which, e))
+ finally:
+ if out is not None:
+ out.close()
+
+ def done():
+ if gen == self._play_gen:
+ self.playing = None
+ self.render()
+ return False
+ GLib.idle_add(done)
+ threading.Thread(target=run, name="VoiceClonePlay", daemon=True).start()
+
+ def save(self) -> None:
+ r = self.recorder
+ try:
+ ref.save(r.samples, r.transcript)
+ except OSError as e:
+ Log.d("voice clone: save failed %s" % type(e).__name__)
+ return
+ Log.d("voice clone: saved %d s" % int(r.seconds))
+ s = self.app.settings
+ s.speakVoices[voicemod.key(self.target)] = voicemod.CLONE
+ s.save()
+ self.close(True)
diff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.py
index be36cf2..0438533 100644
--- a/linux/cicada/core/ling.py
+++ b/linux/cicada/core/ling.py
@@ -832,11 +832,12 @@ class LingClient:
Log.d("ling: %s 429, retry in %.1f s" % (name, wait))
attempt += 1
- def speech(self, text: str, voice: str | None = "UK_Charlotte", language: str | None = None, timeout: float = 20.0):
+ def speech(self, text: str, voice: str | None = "UK_Charlotte", language: str | None = None, timeout: float = 20.0,
+ reference: tuple | None = None):
"""_speech, remembering how it went (现在能用的 › 同传声音 says so). Cut short on purpose (stop,
a new press) is neither."""
try:
- yield from self._speech(text, voice, language, timeout)
+ yield from self._speech(text, voice, language, timeout, reference)
except GeneratorExit:
raise
except Exception:
@@ -844,9 +845,10 @@ class LingClient:
raise
self.last_voice = (True, time.time())
- def _speech(self, text: str, voice: str | None, language: str | None, timeout: float):
+ def _speech(self, text: str, voice: str | None, language: str | None, timeout: float, reference: tuple | None = None):
"""The service's voice for `text`, as raw 24 kHz mono 16-bit PCM chunks while they arrive (a
- generator). On Ling, `voice` is Ming's and `language` its language_id, needed for Japanese,
+ generator). On Ling, `voice` is Ming's, or a voice cloned from `reference` (a WAV data URI and
+ what it says, voice_reference.reference), and `language` its language_id, needed for Japanese,
Korean, German, French and Spanish (Ling.swift › speech); elsewhere the configured speech
model and `voice`. Replies come three ways and all are read: server-sent base64 chunks (Ling,
ZenMux), raw PCM (OpenRouter), or one JSON `{"audio": <WAV>}`."""
@@ -858,7 +860,13 @@ class LingClient:
raise LingError(LingError.NO_KEY)
body = {"model": c.voice_model, "input": text, "response_format": "pcm"}
if c.is_ling:
- body.update({"sample_rate": TTS_RATE, "stream": True, "stream_format": "sse", "voice": voice or "UK_Charlotte"})
+ body.update({"sample_rate": TTS_RATE, "stream": True, "stream_format": "sse"})
+ if reference:
+ # The clip goes with every sentence: Ming takes longer to start (Ling.swift waits 30 s).
+ body["references"] = [{"audio": reference[0], "text": reference[1]}]
+ timeout = max(timeout, 30.0)
+ else:
+ body["voice"] = voice or "UK_Charlotte"
if language:
body["language_id"] = language
else:
diff --git a/linux/cicada/core/speak.py b/linux/cicada/core/speak.py
index e1ad6fb..9291715 100644
--- a/linux/cicada/core/speak.py
+++ b/linux/cicada/core/speak.py
@@ -23,6 +23,7 @@ from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from . import strings
+from . import voice_reference
from . import voices as voicemod
from .audio import RATE, Wav
from .ling import LingError, TTS_RATE
@@ -115,10 +116,33 @@ class SpeakEngine:
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))
+ """The voice id for a language: a Ming voice (or the service's), or voicemod.CLONE."""
+ choice = (self.settings.speakVoices or {}).get(voicemod.key(code))
+ return voicemod.chosen(choice, code, self.ling.config(), voice_reference.exists())
+
+ def speech(self, text: str, code: str, voice: str | None = None):
+ """The voice for `text` in `code`'s language, as 24 kHz PCM chunks (a generator). The user's
+ own voice that fails before its first sound (Ming refused the clip, or took too long) says
+ the sentence in the language's default voice instead, as the Mac falls back to its own."""
config = self.ling.config()
- names = [v for v, _n, _t in voicemod.voices(code, config)]
- return chosen if chosen in names else voicemod.default_voice(code, config)
+ voice = voice or self.voice(code)
+ language = voicemod.ming_language(code, config)
+ if voice != voicemod.CLONE:
+ yield from self.ling.speech(text, voice=voice, language=language)
+ return
+ ref = voice_reference.reference()
+ started = False
+ if ref is not None:
+ try:
+ for pcm in self.ling.speech(text, voice=None, language=language, reference=ref):
+ started = True
+ yield pcm
+ return
+ except LingError as e:
+ if started:
+ raise
+ Log.d("speak: own voice failed %s, the default voice instead" % e)
+ yield from self.ling.speech(text, voice=voicemod.default_voice(code, config), language=language)
# Running
@@ -238,7 +262,7 @@ class SpeakEngine:
def run():
try:
- for pcm in self.ling.speech(text, voice=self.voice(target), language=voicemod.ming_language(target, self.ling.config())):
+ for pcm in self.speech(text, target):
chunks.put(pcm)
chunks.put(_END)
except LingError as e:
diff --git a/linux/cicada/core/voice_reference.py b/linux/cicada/core/voice_reference.py
new file mode 100644
index 0000000..9e1fb24
--- /dev/null
+++ b/linux/cicada/core/voice_reference.py
@@ -0,0 +1,221 @@
+"""The user's own voice (Voices.swift › VoiceReference): the recording Ming clones it from,
+`voice/reference.wav` (16 kHz mono, 10–15 s) and `voice/reference.txt` (what it says, as Ming
+heard it) in the config folder. The folder is 0700 and the files 0600, like the key; they never go
+into a record, an export or the log, and leave the computer only inside a speech request to Ling.
+UI-free: the settings window records, this keeps, checks and hands it to LingClient.speech."""
+from __future__ import annotations
+
+import base64
+import math
+import os
+import shutil
+from array import array
+
+from .audio import RATE, Wav
+from .support import Paths
+
+# The issue's advice (#32): the reference goes with every sentence, so a longer one makes each
+# sentence later. Under 10 s Ming has too little to go on; recording stops by itself at 15.
+MIN_SECONDS = 10.0
+MAX_SECONDS = 15.0
+
+# Ming copies the recording's pace into every sentence (Voices.swift › slowCharacters): below these
+# (characters a second for Chinese, Japanese and Korean, words otherwise) the clone is too slow for
+# a meeting; reading the passage at an ordinary pace gives 3.5–5 and 2.3–3.
+SLOW_CHARACTERS = 2.5
+SLOW_WORDS = 1.6
+
+CLONE = "clone"
+
+
+def folder() -> str:
+ return os.path.join(Paths.config(), "voice")
+
+
+def audio_path() -> str:
+ return os.path.join(folder(), "reference.wav")
+
+
+def text_path() -> str:
+ return os.path.join(folder(), "reference.txt")
+
+
+def text() -> str | None:
+ try:
+ with open(text_path(), encoding="utf-8") as f:
+ return f.read()
+ except OSError:
+ return None
+
+
+def exists() -> bool:
+ return os.path.isfile(audio_path()) and bool((text() or "").strip())
+
+
+def duration() -> float:
+ try:
+ return len(Wav.read_file(audio_path())) / RATE
+ except (OSError, ValueError):
+ return 0.0
+
+
+def reference() -> tuple[str, str] | None:
+ """What Ming needs: the clip as a data URI and its transcript."""
+ t = (text() or "").strip()
+ if not t:
+ return None
+ try:
+ with open(audio_path(), "rb") as f:
+ data = f.read()
+ except OSError:
+ return None
+ return "data:audio/wav;base64," + base64.b64encode(data).decode(), t
+
+
+def _private(path: str, mode: int, data: bytes) -> None:
+ """Written 0600 from the first byte, then swapped in, so a half-written clip is never used."""
+ tmp = path + ".tmp"
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
+ try:
+ os.write(fd, data)
+ finally:
+ os.close(fd)
+ os.chmod(tmp, mode)
+ os.replace(tmp, path)
+
+
+def save(samples: array, transcript: str) -> None:
+ """16 kHz mono samples and what they say."""
+ os.makedirs(folder(), mode=0o700, exist_ok=True)
+ os.chmod(folder(), 0o700)
+ _private(audio_path(), 0o600, Wav.bytes(trim(samples)))
+ _private(text_path(), 0o600, transcript.strip().encode("utf-8"))
+ global _saved_pace
+ _saved_pace = None
+
+
+def remove() -> None:
+ global _saved_pace
+ _saved_pace = None
+ shutil.rmtree(folder(), ignore_errors=True)
+
+
+# Pace
+
+def is_cjk(ch: str) -> bool:
+ o = ord(ch)
+ return 0x3040 <= o <= 0x30FF or 0x3400 <= o <= 0x4DBF or 0x4E00 <= o <= 0x9FFF or 0xAC00 <= o <= 0xD7AF or 0xF900 <= o <= 0xFAFF
+
+
+def tokens(s: str) -> list:
+ """Characters for Chinese, Japanese and Korean, words otherwise (SpeakTest.swift › tokens)."""
+ out, word = [], ""
+ for ch in s:
+ if is_cjk(ch):
+ if word:
+ out.append(word.lower())
+ word = ""
+ out.append(ch)
+ elif ch.isalnum() or ch in "'’":
+ word += "'" if ch == "’" else ch
+ elif word:
+ out.append(word.lower())
+ word = ""
+ if word:
+ out.append(word.lower())
+ return out
+
+
+def _speech_windows(samples, rate: int = RATE):
+ """(first, last, size): the 20 ms windows within 35 dB of the loudest one; None when silent."""
+ size = max(1, int(rate * 0.02))
+ levels = []
+ for i in range(0, len(samples), size):
+ part = samples[i:i + size]
+ levels.append(math.sqrt(sum((x / 32768.0) ** 2 for x in part) / len(part)))
+ if not levels or max(levels) <= 0.003:
+ return None
+ floor = max(levels) * 0.0178
+ loud = [i for i, l in enumerate(levels) if l >= floor]
+ return loud[0], loud[-1], size
+
+
+def speech_span(samples, rate: int = RATE) -> float | None:
+ """Seconds from the first to the last 20 ms window within 35 dB of the loudest one."""
+ w = _speech_windows(samples, rate)
+ return None if w is None else (w[1] - w[0] + 1) * w[2] / rate
+
+
+TRIM_PAD = 0.2
+
+
+def trim(samples, rate: int = RATE):
+ """The recording without the quiet before and after the reading, 0.2 s kept each side. Ming
+ copies the clip's ending: a second of silence after the last word (the pause before 读完了)
+ made every cloned sentence come back as 0.4 s of nothing (measured 2026-11 against Ling)."""
+ w = _speech_windows(samples, rate)
+ if w is None:
+ return samples
+ pad = int(TRIM_PAD * rate)
+ return samples[max(0, w[0] * w[2] - pad):min(len(samples), (w[1] + 1) * w[2] + pad)]
+
+
+def pace(transcript: str, samples, rate: int = RATE) -> float | None:
+ """Characters or words a second of speech; None when there is no speech to measure."""
+ units = len(tokens(transcript))
+ span = speech_span(samples, rate)
+ if units == 0 or span is None or span <= 0.5:
+ return None
+ return units / span
+
+
+def is_slow(transcript: str, p: float) -> bool:
+ t = tokens(transcript)
+ characters = sum(1 for x in t if any(is_cjk(c) for c in x))
+ return p < (SLOW_CHARACTERS if characters * 2 >= len(t) else SLOW_WORDS)
+
+
+_saved_pace = None # (mtime, slow)
+
+
+def saved_is_slow() -> bool:
+ """The saved recording is read too slowly (worked out once per recording)."""
+ global _saved_pace
+ try:
+ mtime = os.path.getmtime(audio_path())
+ except OSError:
+ return False
+ if _saved_pace and _saved_pace[0] == mtime:
+ return _saved_pace[1]
+ t = text() or ""
+ try:
+ p = pace(t, Wav.read_file(audio_path()))
+ except (OSError, ValueError):
+ p = None
+ slow = p is not None and is_slow(t, p)
+ _saved_pace = (mtime, slow)
+ return slow
+
+
+def passage(code: str) -> str:
+ """The passage to read, in the user's own language (Voices.swift › passage)."""
+ k = (code or "en").split("-")[0].lower()
+ if k == "zh":
+ return "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。请大家先看一下屏幕上的议程。"
+ if k == "ja":
+ return "皆さん、こんにちは。今日の会議では、新製品の発売計画について話し合います。スケジュール、テストの範囲、そしてマーケティングについて順番に確認しましょう。"
+ return ("Hello everyone, thanks for joining. Today we'll walk through the launch plan for the new product: the schedule, "
+ "what we still need to test, and how we'll tell people about it. Let's start with the agenda on the screen.")
+
+
+def check(samples, transcript: str) -> str | None:
+ """Why a recording can't be used ("short", "unclear", "slow"), or None; the Mac's order. Long
+ enough is measured on the reading itself (trim), not the quiet around it."""
+ if len(trim(samples)) / RATE < MIN_SECONDS:
+ return "short"
+ if len(transcript.strip()) < 6:
+ return "unclear"
+ p = pace(transcript, samples)
+ if p is not None and is_slow(transcript, p):
+ return "slow"
+ return None
diff --git a/linux/cicada/core/voices.py b/linux/cicada/core/voices.py
index 2daffd4..cbc6c7d 100644
--- a/linux/cicada/core/voices.py
+++ b/linux/cicada/core/voices.py
@@ -43,3 +43,34 @@ def voices(code: str, config=None) -> list:
def default_voice(code: str, config=None) -> str | None:
v = voices(code, config)
return v[0][0] if v else None
+
+
+CLONE = "clone" # the user's own voice (voice_reference), stored in speakVoices like a Ming voice
+
+
+def clones(config) -> bool:
+ """Only Ling clones the user's voice (providers.py)."""
+ return config is None or bool(getattr(config.provider, "clones", False))
+
+
+def chosen(choice: str | None, code: str, config=None, has_reference: bool = False) -> str | None:
+ """The voice a language uses: the choice while the service in use can speak it, else the default
+ (AppModel.voiceID). The user's own voice needs its recording and Ling; a Ming voice saved
+ before switching services isn't sent elsewhere. Either comes back with that service."""
+ if choice == CLONE:
+ return CLONE if has_reference and clones(config) else default_voice(code, config)
+ names = [v for v, _n, _t in voices(code, config)]
+ return choice if choice in names else default_voice(code, config)
+
+
+def sample(code: str) -> str:
+ """A short line to try a voice with, in the language it will speak (VoiceCatalog.sample)."""
+ return {
+ "zh": "谢谢大家。我们来看一下上线时间表,并确定谁负责麦克风测试。",
+ "ja": "皆さん、ありがとうございます。発売スケジュールを確認しましょう。",
+ "ko": "감사합니다. 출시 일정을 함께 확인해 보겠습니다.",
+ "es": "Gracias a todos. Revisemos el calendario de lanzamiento.",
+ "fr": "Merci à tous. Regardons ensemble le calendrier de lancement.",
+ "de": "Danke an alle. Schauen wir uns den Zeitplan für den Start an.",
+ "pt": "Obrigado a todos. Vamos ver o cronograma de lançamento.",
+ }.get(key(code), "Thanks everyone. Let's look at the launch timeline and decide who owns the microphone tests.")
diff --git a/linux/scripts/cicadactl b/linux/scripts/cicadactl
index cf0913c..42e8400 100755
--- a/linux/scripts/cicadactl
+++ b/linux/scripts/cicadactl
@@ -10,6 +10,8 @@
word-list [import <text>|edit <word>|heard <word>=<form>|delete <word>] (改正听错的词, debug.py › _fixes)
share <id>[,full][,pw] | unshare <id> | share-last | shareSheet <id>|"" | share-ui <action> (分享…, debug.py › _share)
export-folder <path>|off|on | export-state | export-all | export-retry | export-choose (存到文件夹, debug.py › _export)
+ voice <lang>[=<id>] | voice-clone <wav>|off|state | voice-preview [<lang>] | voice-dialog open|feed <wav>|finish|play original|clone|save|close
+ (我自己的声音, debug.py › _voice)
Run it inside the Linux session (linux/vm/vmctl.sh ssh does that for the test VM)."""
import os
import socket
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index 348362b..7662dc2 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -211,3 +211,6 @@
/* 在 Dock 中显示: the top bar, not a menu bar */
"关掉后只在顶栏,打开窗口时才出现" = "Off: top bar only, in the Dock just while a window is open";
"改一下这个文件夹的权限,或换个文件夹" = "Change this folder's permissions, or pick another folder";
+
+/* 我自己的声音 (voice_clone.py): the recording stays on this computer, not "this Mac". */
+"听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。" = "Doesn't sound like you, or noisy? Record again somewhere quiet. The recording stays on this computer and can be deleted anytime.";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index c3116b1..d83f6a5 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -211,3 +211,6 @@
/* 在 Dock 中显示 */
"关掉后只在顶栏,打开窗口时才出现" = "オフ:トップバーのみ。ウインドウを開いている間だけ Dock に表示";
"改一下这个文件夹的权限,或换个文件夹" = "このフォルダのアクセス権を変更するか、別のフォルダを選んでください";
+
+/* 我自己的声音 (voice_clone.py): the recording stays on this computer, not "this Mac". */
+"听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。" = "似ていない、またはノイズがありますか?静かな場所で録り直してください。録音はこのコンピュータにのみ保存され、いつでも削除できます。";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 1dc7318..1959f67 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -211,3 +211,6 @@
/* 在 Dock 中显示 */
"关掉后只在顶栏,打开窗口时才出现" = "끄면 상단 바에만 있고, 창을 열 때만 Dock에 나타납니다";
"改一下这个文件夹的权限,或换个文件夹" = "이 폴더의 권한을 바꾸거나 다른 폴더를 고르세요";
+
+/* 我自己的声音 (voice_clone.py): the recording stays on this computer, not "this Mac". */
+"听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。" = "내 목소리 같지 않거나 잡음이 있나요? 조용한 곳에서 다시 녹음해 보세요. 녹음은 이 컴퓨터에만 저장되며 언제든 삭제할 수 있습니다.";
diff --git a/linux/tests/test_voice_clone.py b/linux/tests/test_voice_clone.py
new file mode 100644
index 0000000..3052928
--- /dev/null
+++ b/linux/tests/test_voice_clone.py
@@ -0,0 +1,181 @@
+"""我自己的声音 (issue #32): the recording kept like the key, Ming's request with `references`, the
+voice a language falls back to, and the Mac's pace and length checks."""
+from __future__ import annotations
+
+import base64
+import os
+import stat
+import threading
+import time
+import unittest
+from types import SimpleNamespace
+
+from test_core import Base, Fake, Player, client, concat, reply, silence, sse, tone
+
+from cicada.core import jsonfmt
+from cicada.core import voice_reference as vref
+from cicada.core import voices as voicemod
+from cicada.core.audio import PcmAudioSource
+from cicada.core.ling import LingClient, StreamResponse
+from cicada.core.settings import AppSettings
+from cicada.core.speak import SpeakEngine
+from cicada.core.translator import Translator
+
+PASSAGE = "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。"
+
+
+class Storage(Base):
+ def test_kept_private_and_read_back_as_a_data_uri(self):
+ self.assertFalse(vref.exists())
+ vref.save(tone(12), PASSAGE)
+ self.assertTrue(vref.exists())
+ self.assertEqual(0o700, stat.S_IMODE(os.stat(vref.folder()).st_mode))
+ for p in (vref.audio_path(), vref.text_path()):
+ self.assertEqual(0o600, stat.S_IMODE(os.stat(p).st_mode), p)
+ self.assertAlmostEqual(12.0, vref.duration(), places=2)
+ audio, text = vref.reference()
+ self.assertTrue(audio.startswith("data:audio/wav;base64,"))
+ wav = base64.b64decode(audio.split(",", 1)[1])
+ self.assertEqual(b"RIFF", wav[:4])
+ self.assertEqual(16000, int.from_bytes(wav[24:28], "little"), "16 kHz")
+ self.assertEqual(1, int.from_bytes(wav[22:24], "little"), "mono")
+ self.assertEqual(PASSAGE, text)
+ vref.remove()
+ self.assertFalse(vref.exists())
+ self.assertIsNone(vref.reference())
+
+ def test_no_transcript_is_no_recording(self):
+ vref.save(tone(12), " ")
+ self.assertFalse(vref.exists())
+
+
+class Request(Base):
+ def test_clone_sends_the_reference_instead_of_a_voice(self):
+ timeouts = []
+ fake = Fake(lambda b: reply("ok"), speech=lambda b: sse(b"\x01\x00"))
+ stream = fake.stream
+ fake.stream = lambda url, body, headers, timeout: timeouts.append(timeout) or stream(url, body, headers, timeout)
+ pcm = list(client(fake).speech("Hello", voice=None, language="ja", reference=("data:audio/wav;base64,UklGRg==", "你好")))
+ self.assertEqual([b"\x01\x00"], pcm)
+ body = jsonfmt.parse(fake.spoken[0])
+ self.assertEqual([{"audio": "data:audio/wav;base64,UklGRg==", "text": "你好"}], body["references"])
+ self.assertNotIn("voice", body)
+ self.assertEqual("ja", body["language_id"])
+ self.assertGreaterEqual(timeouts[0], 30, "a cloned voice gets Ling.swift's 30 s")
+
+ def test_a_built_in_voice_sends_no_reference(self):
+ fake = Fake(lambda b: reply("ok"), speech=lambda b: sse(b"\x01\x00"))
+ list(client(fake).speech("Hello", voice="US_Emma"))
+ body = jsonfmt.parse(fake.spoken[0])
+ self.assertEqual("US_Emma", body["voice"])
+ self.assertNotIn("references", body)
+
+
+class Choice(unittest.TestCase):
+ OTHER = SimpleNamespace(is_ling=False, provider=SimpleNamespace(clones=False), voices=[SimpleNamespace(id="Kore", gender="女")])
+
+ def test_own_voice_needs_its_recording_and_ling(self):
+ self.assertEqual("clone", voicemod.chosen("clone", "en", None, has_reference=True))
+ self.assertEqual("US_Emma", voicemod.chosen("clone", "en", None, has_reference=False), "no recording: the default")
+ self.assertEqual("灵小雅", voicemod.chosen("clone", "zh-CN", None, has_reference=False))
+ self.assertEqual("Kore", voicemod.chosen("clone", "en", self.OTHER, has_reference=True), "only Ling clones")
+ self.assertFalse(voicemod.clones(self.OTHER))
+ self.assertEqual("UK_George", voicemod.chosen("UK_George", "en", None))
+ self.assertEqual("Kore", voicemod.chosen("UK_George", "en", self.OTHER), "a Ming voice isn't sent elsewhere")
+
+
+class Pace(unittest.TestCase):
+ def test_tokens_count_characters_and_words(self):
+ self.assertEqual(["大", "家", "好", "hello", "it's", "2"], vref.tokens("大家好, Hello it’s 2!"))
+
+ def test_too_slow_is_caught_like_the_mac(self):
+ # 54 characters over 12 s of speech: 4.5 a second, an ordinary pace.
+ self.assertIsNone(vref.check(concat(silence(0.5), tone(12), silence(0.5)), PASSAGE))
+ p = vref.pace(PASSAGE, concat(silence(1), tone(12), silence(2)))
+ self.assertAlmostEqual(len(vref.tokens(PASSAGE)) / 12, p, delta=0.05, msg="silence at both ends left out")
+ # The same over 14 s of a recital at a third of it.
+ self.assertEqual("slow", vref.check(tone(14), PASSAGE[:30]))
+ self.assertTrue(vref.is_slow("hello there everyone", 1.5))
+ self.assertFalse(vref.is_slow("hello there everyone", 2.0))
+
+ def test_the_quiet_around_the_reading_is_cut(self):
+ # A second of silence after the last word made Ming answer every sentence with 0.4 s of nothing.
+ cut = vref.trim(concat(silence(1.5), tone(11), silence(1.2)))
+ self.assertAlmostEqual(11 + 2 * vref.TRIM_PAD, len(cut) / 16000, delta=0.05)
+ self.assertEqual(16000 * 3, len(vref.trim(silence(3))), "nothing to cut by in silence")
+ self.assertEqual("short", vref.check(concat(tone(9), silence(3)), PASSAGE), "long enough is the reading itself")
+
+ def test_kept_without_its_silence(self):
+ home = __import__("tempfile").mkdtemp()
+ from cicada.core.support import Paths
+ Paths.home_override = home
+ try:
+ vref.save(concat(tone(11), silence(1)), PASSAGE)
+ self.assertAlmostEqual(11 + vref.TRIM_PAD, vref.duration(), delta=0.05)
+ finally:
+ Paths.home_override = None
+ __import__("shutil").rmtree(home, ignore_errors=True)
+
+ def test_too_short_or_not_understood(self):
+ self.assertEqual("short", vref.check(tone(9.5), PASSAGE))
+ self.assertEqual("unclear", vref.check(tone(12), "你好"))
+ self.assertEqual(10.0, vref.MIN_SECONDS)
+ self.assertEqual(15.0, vref.MAX_SECONDS)
+
+
+class Speaking(Base):
+ def _engine(self, speech, voices):
+ LingClient.spacing = 0.01
+ fake = Fake(lambda b: reply("ORIGINAL: 我们周五上线\nTRANSLATION: We launch on Friday"), speech=speech)
+ ling = client(fake)
+ player = Player()
+ settings = AppSettings(target="zh-CN", speakTo="en", speakVoices=voices)
+ return SpeakEngine(ling, Translator(ling), settings, player=lambda: player), fake, player
+
+ def _say(self, eng):
+ 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)
+ time.sleep(0.6)
+ eng.stop()
+
+ def test_speaks_in_my_own_voice(self):
+ vref.save(tone(12), PASSAGE)
+ eng, fake, player = self._engine(lambda b: sse(b"\x10\x00" * 100), {"en": "clone"})
+ self.assertEqual("clone", eng.voice("en"))
+ self._say(eng)
+ self.assertEqual(1, eng.spoken)
+ body = jsonfmt.parse(fake.spoken[0])
+ self.assertEqual(PASSAGE, body["references"][0]["text"])
+ self.assertNotIn("voice", body)
+ with open(os.path.join(self.home, "debug.log"), encoding="utf-8") as f:
+ self.assertNotIn("主持人", f.read(), "the transcript never goes into the log")
+
+ def test_without_the_recording_the_default_voice(self):
+ eng, fake, player = self._engine(lambda b: sse(b"\x10\x00" * 100), {"en": "clone"})
+ self.assertEqual("US_Emma", eng.voice("en"))
+ self._say(eng)
+ self.assertEqual("US_Emma", jsonfmt.parse(fake.spoken[0])["voice"])
+
+ def test_a_refused_clone_falls_back_to_the_default_voice(self):
+ vref.save(tone(12), PASSAGE)
+ eng, fake, player = self._engine(lambda b: sse(b"\x10\x00" * 100), {"en": "clone"})
+ stream = fake.stream
+
+ def refuse(url, body, headers, timeout):
+ if "references" in body:
+ fake.spoken.append(body)
+ return StreamResponse(400, iter([]))
+ return stream(url, body, headers, timeout)
+ fake.stream = refuse
+ self._say(eng)
+ self.assertEqual(1, eng.spoken, "still said, in the default voice")
+ self.assertEqual(b"\x10\x00" * 100, player.data)
+ self.assertIn("references", jsonfmt.parse(fake.spoken[0]))
+ self.assertEqual("US_Emma", jsonfmt.parse(fake.spoken[1])["voice"])
+
+
+if __name__ == "__main__":
+ unittest.main()