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: hear and translate speak-back in one step with Ming's audio model

wquguru0539b6c68864
diff --git a/AGENTS.md b/AGENTS.md
index e89e660..801c3ee 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,7 +9,7 @@ Cicada (知了, formerly Live Subs) is a macOS menu bar app that turns whatever
- Language detection compares confidence: the same 3–6 s clip after a pause is transcribed by every installed model; a winner needs confidence ≥ 0.6 and a 0.08 lead; the first detection or a 0.30 lead switches at once, otherwise two agreeing detections. After a switch the last 8 s are replayed into the new model.
- "Follow system" translates into the first system language that differs from the source language.
- Subtitle bar: shows only while someone talks (auto) or always; tucks into a dot after 2/4/8 s of quiet; fades to 15% and stays click-through while the pointer passes over it; editable after the pointer rests 0.6 s (drag to move, drag the corner to scale, double-click resets); ⌃⌥S (changeable) cycles the display mode (notes → bar → none). Position, width and size are remembered per display.
-- Speaking: hold the right ⌥ key alone (a listen-only event tap, needs Input Monitoring; any other key while held cancels the press as a chord) or a user-chosen combination (Carbon hotkey, no permission) → microphone → one `SpeechAnalyzer` per press, finished with `finalizeAndFinishThroughEndOfInput` → translate into the room's language → system voice → the chosen output device (a virtual microphone). The virtual microphone is BlackHole 2ch, installed from the app: download the official notarized package, check its pinned SHA-256, run `installer` and restart `coreaudiod` in one standard administrator prompt (the package only copies the driver and asks for a reboot; Core Audio loads a new HAL plug-in only when it restarts). Then a loopback sound test: speak a fixed English phrase into the device, record its input side, transcribe it (`LoopbackTest`). The checklist UI (`MicSetupCard`) is shared by onboarding step 3 and settings. We never bundle the GPL driver.
+- Speaking: hold the right ⌥ key alone (a listen-only event tap, needs Input Monitoring; any other key while held cancels the press as a chord) or a user-chosen combination (Carbon hotkey, no permission) → microphone → with a usable Ling key the press (16 kHz WAV, ≤ 60 s) goes to `Ming-3.0-audio-flash` in one `.speak` request that returns `ORIGINAL:` / `TRANSLATION:` lines (`TranslationService.interpret`; anything else is dropped, since the model sometimes answers a question instead of interpreting it; ~2 s, names right). One `SpeechAnalyzer` per press always runs too, finished with `finalizeAndFinishThroughEndOfInput`: it shows the words while held and is the fallback transcript, translated into the room's language by the usual chain → voice → the chosen output device (a virtual microphone). The virtual microphone is BlackHole 2ch, installed from the app: download the official notarized package, check its pinned SHA-256, run `installer` and restart `coreaudiod` in one standard administrator prompt (the package only copies the driver and asks for a reboot; Core Audio loads a new HAL plug-in only when it restarts). Then a loopback sound test: speak a fixed English phrase into the device, record its input side, transcribe it (`LoopbackTest`). The checklist UI (`MicSetupCard`) is shared by onboarding step 3 and settings. We never bundle the GPL driver.
- AI (Ling, ant-ling.com, OpenAI-compatible): one user key for the whole app, for now in a 0600 file `ling-api-key` in the app's Application Support folder, excluded from backups (`AIKey`; never in UserDefaults, logs or exports; ad-hoc signing makes the Keychain ask for the password after every rebuild or update, so it moves back to the Keychain once builds have a Developer ID; a key in the old Keychain item, service = bundle id + `.ai`, is moved over once), checked with a one-token `Ling-3.0-tiny` call. `LingClient` is the single gate for every call: request *starts* ≥ 0.6 s apart (the account allows ~2 requests/s across all models), waiting requests ordered speak-back > translation > notes; notes retry 429 with 1/2/4/8 s backoff, translation and speak-back fail fast to the next translator; 401 marks the key invalid. Every call sends `thinking: disabled`, puts the content in the **system** message and a fixed instruction in the user message (otherwise question-like text gets a search-grounded essay instead), and drops replies with no `finish_reason` or starting 根据现有检索证据.
- Live notes (`NotesEngine`, UI-free): about every 45 s with new lines, one JSON call sends the current notes + new lines (`[L12 02:03 对方] …`) and gets the whole notes back (summary, ≤ 8 topics with points and an optional fishbone, conclusions/to-dos with evidence line ids → support counts, terms with misrecognised forms); a bad reply never replaces good notes. A final pass over the whole transcript runs when the meeting ends ("完整版"). Notes are written in Chinese when Chinese is among the system languages. Stored as `notes` in `session.json`; finished meetings without notes can generate them from the main window. Speak-back voices (`Voices.swift`, settings UI `VoicePicker.swift` on the 同声传译 page): one choice per room language (`speakVoices`, "en" → `ming:US_Emma` / `system:<AVSpeechSynthesisVoice id>` / `clone`). Offered: hand-picked Ming voices (English Emma/George/Charlotte; Chinese 小雅/小棠/小锋/卓然; ja/ko/de/fr/es via Emma/George with `language_id`) and the Mac's best female and male voice; default is Ming's first with a key, else the Mac's. `clone` is the user's own voice: a 8–30 s recording read from a passage in their language (16 kHz WAV + its on-device transcript in `voice/` under Application Support, 0600, out of backups), sent to Ming as `references` with every sentence (~600 KB, first audio ~3 s, ~8 s on a cold call; a foreign language keeps the speaker's accent). Ming's voices fall back to the Mac's voice without a usable key or when the stream fails; previews play on the default output, not the room.0-tts-0.5B`, SSE PCM 24 kHz) through the same key, falling back to the system voice.
- Live notes window (`NotesWindow`): a floating `NSPanel`, `sharingType = .none` (invisible to screen sharing and screenshots), on all Spaces, frame autosaved; < 360 px a card that offers what the notes added since it was collapsed ("收起后新增 …", only when there is something), tabs 纪要 / 文字记录 in between, both side by side from 760 px; banners for no key (inline key entry) / invalid key / rate limited. While writing: sound bars before anyone speaks, a spinner with "已听到 N 句" and shimmering placeholders for the first version, an "正在更新" pill and a warm shimmer under the current topic for later updates (`TimelineView`, since the window redraws every second). Transcript: oldest first, follows the newest line plus the sentence still being spoken; scrolling up pauses following and gathers new lines into a "↓ N 句新内容" button; search highlights in place (query plus the notes' misheard forms of a name). Notes carry times: points and conclusions get the time of their first evidence line (`pointTimes`, `NoteItem.t`; carried over when the model echoes a point without evidence), topics show ranges.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f9d2b61..a59bfc5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ the release workflow publishes it as the release notes.
## Unreleased
+- Changed: with a Ling key, what you say while holding the talk key is heard and translated in one step by Ming's audio model, which gets names right far more often than the on-device recognizer (江充 instead of 将冲) and needs one request instead of two. The translation is ready about 2 s after you let go (about 1 s before); if Ming is slow, busy or replies oddly, it falls back to on-device recognition and the usual translation. 诊断 shows which one answered.
- Changed: Live Subs is now 知了 (Cicada in English): new name, new logo, new app id (`com.wquguru.cicada`). macOS treats it as a new app, so it asks again for system audio, microphone and Input Monitoring, and settings and the AI key start fresh; meeting records are kept. Delete the old Live Subs from Applications.
- New: choose the voice the room hears for each language (Settings › 同声传译 › 对方听到的声音): natural Ming voices, two women and two men where available (Emma, George, Charlotte in English; 小雅, 小棠, 小锋, 卓然 in Chinese; Japanese, Korean, German, French and Spanish too), the Mac's own voices, each with a play button. Or record 15 s of your own voice and the room hears you, in any language (with your accent, about 1.5 s later than the built-in voices). The recording stays on your Mac and is sent to Ling only with what you say.
- Changed: clearer wording throughout the Chinese interface.
diff --git a/README.md b/README.md
index 89e0a2b..e6f6831 100644
--- a/README.md
+++ b/README.md
@@ -36,9 +36,9 @@ Cicada (知了, “cicada” in Chinese, formerly Live Subs) listens to what you
- **Translates into your language** — follows your system languages by default (English audio on an English Mac goes to your next language), or pick one.
- **Stays out of the way** — the subtitle bar appears only while someone talks, tucks into a small dot when it's quiet, and turns see-through when your pointer passes over it, so you can still click what's underneath. Rest the pointer on it to drag or resize; ⌃⌥S hides it.
- **Live meeting notes** — with your own [Ling](https://chat.ant-ling.com/open) API key (Settings › AI 服务, kept only on your Mac in a file only your account can read), a floating notes window fills in while the meeting runs: a summary, topics with key points, a fishbone diagram where causes are discussed, conclusions and to-dos, and names spelled consistently. Drag it anywhere, shrink it to a card (it tells you when something new was said since) or widen it to read notes beside the transcript; it never shows up when you share your screen. While it is open the app's menus are in the top left (stop recording ⌘R, what was added since collapsing ⌘J, search ⌘F, sizes ⌘1–⌘3). A full version is written when the meeting ends. The same key makes translation more accurate and lets the room hear a natural Ming voice, or your own voice cloned from a 15 s recording (Settings › 同声传译); without a key everything else works as before.
-- **Speak back** — hold the right ⌥ key and talk; the room hears your words translated, through a virtual microphone you install from the app.
+- **Speak back** — hold the right ⌥ key and talk; the room hears your words translated, through a virtual microphone you install from the app. With a Ling key, Ming's audio model hears and translates what you said in one step, so names come out right.
- **Meeting records** — every session is saved as a bilingual transcript (with the audio, on your Mac only) and exports to Markdown, Word or SRT.
-- **Private by design** — audio capture, language detection and speech recognition all run on-device.
+- **Private by design** — audio capture, language detection and speech recognition all run on-device. The only audio that leaves your Mac is what you say while holding the talk key, and only with a Ling key.
<p align="center">
<img src="docs/panel.png" width="300" alt="The menu bar panel">
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 5860802..51a14b4 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -40,9 +40,9 @@
- 鼠标停住不动,就可以拖动、缩放字幕条;
- ⌃⌥S 随时隐藏或显示。
- **实时纪要**:在 设置 › AI 服务 填上自己的 [Ling](https://chat.ant-ling.com/open) API key(只存在你的 Mac 上,只有你的账户能读),开会时一个悬浮窗口会边听边整理:总结、议题和要点、讨论原因时的鱼骨图、结论和待办、统一写法的人名。窗口可以拖到任何地方、收成小卡(收起后有新内容时会提示)或拉宽和文字记录并排;共享屏幕时别人看不到它。它开着时,左上角有知了的菜单(停止记录 ⌘R、收起后的新内容 ⌘J、搜索 ⌘F、窗口大小 ⌘1–⌘3)。会议结束后再整理一遍完整版。同一个 key 还让翻译更准;同声传译时对方可以听到自然的 Ming 声音,或者录 15 秒、用你自己的声音(设置 › 同声传译);没有 key 时其他功能照常。
-- **说话也能翻译**:按住右边的 ⌥ 键说话,会议里的人听到的是翻译后的语音。这需要一个虚拟麦克风,在 App 里一键安装。
+- **说话也能翻译**:按住右边的 ⌥ 键说话,会议里的人听到的是翻译后的语音。这需要一个虚拟麦克风,在 App 里一键安装。填了 Ling key 时,由 Ming 语音模型一步听懂并翻译,人名更准。
- **会议记录**:每场会议都自动存成双语稿子(录音只存在本机),可以导出 Markdown、Word 或 SRT。
-- **隐私**:声音采集、语言识别、语音识别都在本机完成。
+- **隐私**:声音采集、语言识别、语音识别都在本机完成。唯一会离开 Mac 的声音,是填了 Ling key 时你按住说话键说的那几句。
<p align="center">
<img src="docs/panel.png" width="300" alt="菜单栏面板">
@@ -75,7 +75,7 @@
1. 播放任何有声音的内容,实时纪要窗口里会出现文字记录和字幕行。想要原来的字幕条,在面板里选“字幕条”;⌃⌥S 在实时纪要、字幕条、不显示之间切换。
2. 点菜单栏图标,可以改“听到”的语言(默认自动识别)、“翻译成”的语言,以及显示方式。
-3. 想要纪要:在 设置 › AI 服务(或直接在纪要窗口里)填上 Ling 的 API key。按目前价格一小时会议约 ¥0.15–1;发出去的只有文字,语音识别留在本机。
+3. 想要纪要:在 设置 › AI 服务(或直接在纪要窗口里)填上 Ling 的 API key。按目前价格一小时会议约 ¥0.15–1;纪要发出去的只有文字,听对方说话的识别留在本机。
4. 想让对方听到你的翻译:
- 打开 **同声传译**;
- 在会议软件里把麦克风选成 **BlackHole 2ch**;
diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swift
index 04a0a5e..46693c4 100644
--- a/Sources/LiveSubs/AppModel.swift
+++ b/Sources/LiveSubs/AppModel.swift
@@ -102,6 +102,9 @@ final class AppModel: ObservableObject {
}
speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }
applyVoice()
+ speak.interpret = { [weak self] wav, from, to, trace in
+ await self?.translator.interpret(wav: wav, source: from, target: to, trace: trace)
+ }
speak.onStatus = { [weak self] text in self?.status = text }
speak.onLive = { [weak self] phase, src, dst in
guard let self else { return }
diff --git a/Sources/LiveSubs/Diagnostics.swift b/Sources/LiveSubs/Diagnostics.swift
index 08c9e5b..ca9ee5a 100644
--- a/Sources/LiveSubs/Diagnostics.swift
+++ b/Sources/LiveSubs/Diagnostics.swift
@@ -225,6 +225,7 @@ struct DiagnosticsView: View {
switch via {
case "ling": Palette.ink
case "google": Palette.accent
+ case "ming": Palette.accentInk
default: Color(red: 0.72, green: 0.74, blue: 0.78)
}
}
@@ -234,18 +235,20 @@ struct DiagnosticsView: View {
case "ling": "Ling"
case "google": "Google"
case "apple": "本机"
+ case "ming": "Ming 语音"
default: "没译出"
}
}
private static func reason(_ key: String) -> String {
let parts = key.split(separator: ":").map(String.init)
- let who = parts.first.map { $0 == "ling" ? "Ling" : $0 == "google" ? "Google" : $0 == "notes" ? "纪要" : "本机" } ?? ""
+ let who = parts.first.map { $0 == "ling" ? "Ling" : $0 == "google" ? "Google" : $0 == "notes" ? "纪要" : $0 == "ming" ? "Ming 语音" : "本机" } ?? ""
let why: String
switch parts.last ?? "" {
case "hijacked": why = "被搜索劫持"
case "rateLimited", "429": why = "限流"
case "timeout": why = "超时"
+ case "unparsed": why = "回复格式不对"
case "network": why = "网络错误"
case "unavailable": why = "未安装语言包"
default: why = parts.last ?? ""
diff --git a/Sources/LiveSubs/Ling.swift b/Sources/LiveSubs/Ling.swift
index 22419c1..cec35b9 100644
--- a/Sources/LiveSubs/Ling.swift
+++ b/Sources/LiveSubs/Ling.swift
@@ -199,9 +199,10 @@ final class LingClient: ObservableObject {
/// One chat completion. `content` goes in the system message, `instruction` is the fixed user
/// message. Notes retry 429s with backoff; translation and speak-back fail fast so the caller
- /// can fall back to another translator.
+ /// can fall back to another translator. `audio` (a WAV) goes in the user message before the
+ /// instruction, for Ming's audio model.
func chat(content: String, instruction: String, priority: Priority, json: Bool = false,
- maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil,
+ maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil, audio: Data? = nil,
onQueued: ((Double) -> Void)? = nil) async throws -> String {
guard let key else { throw Failure.noKey }
guard keyState != .invalid else { throw Failure.invalidKey }
@@ -213,7 +214,10 @@ final class LingClient: ObservableObject {
"model": model ?? self.model(),
"messages": [
["role": "system", "content": content],
- ["role": "user", "content": instruction],
+ ["role": "user", "content": audio.map { wav -> Any in
+ [["type": "audio_url", "audio_url": ["url": "data:audio/wav;base64," + wav.base64EncodedString()]],
+ ["type": "text", "text": instruction]]
+ } ?? instruction],
],
"max_tokens": maxTokens,
"temperature": 0.2,
diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swift
index c3a6392..f54bfa8 100644
--- a/Sources/LiveSubs/SpeakEngine.swift
+++ b/Sources/LiveSubs/SpeakEngine.swift
@@ -62,8 +62,10 @@ enum AudioDevices {
// MARK: - Speak engine
-/// Hold to talk: microphone → on-device transcription → translation →
-/// system voice → chosen output device (a virtual microphone for the call).
+/// Hold to talk: microphone → Ming's audio model (what was said + its translation in one call),
+/// or on-device transcription → translation when that fails → voice → chosen output device
+/// (a virtual microphone for the call). The on-device transcriber always runs: it shows the words
+/// while the key is held and is the fallback transcript.
@MainActor
final class SpeakEngine {
enum Phase { case idle, listening, translating, speaking }
@@ -74,6 +76,8 @@ final class SpeakEngine {
var onStatus: ((String) -> Void)?
/// Translator shared with the listening side.
var translate: ((_ text: String, _ from: String, _ to: String, _ trace: TranslateTrace) async -> String?)?
+ /// The press as a WAV → (what was said, translation); nil when Ming is unavailable or its reply is unusable.
+ var interpret: ((_ wav: Data, _ from: String, _ to: String, _ trace: TranslateTrace) async -> (original: String, translation: String)?)?
/// Diagnostics: key released → transcript → translation → voice finished.
var onTiming: ((SentenceTiming) -> Void)?
private var releasedAt: Date?
@@ -94,6 +98,12 @@ final class SpeakEngine {
private var pressStarted = Date()
private nonisolated(unsafe) var micRecorder: AVAudioFile?
private nonisolated(unsafe) var micRecordURL: URL?
+ /// This press's audio as 16 kHz mono 16-bit samples for Ming; only touched on `micQueue`.
+ private nonisolated(unsafe) var pressSamples: [Int16] = []
+ private nonisolated(unsafe) var pressConverter = PCMConverter()
+ private nonisolated static let pressFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: false)!
+ /// Ming takes at most this much of a press (the talk key is meant for a sentence or two).
+ private nonisolated static let pressLimit = 16_000 * 60
private let synth = AVSpeechSynthesizer()
private let out = AVAudioEngine()
@@ -166,6 +176,7 @@ final class SpeakEngine {
let (stream, cont) = AsyncStream.makeStream(of: AnalyzerInput.self)
finals = []
volatile = ""
+ micQueue.sync { pressSamples = []; pressConverter = PCMConverter() }
let task = Task { [weak self] () -> String in
let collector = Task { [weak self] in
do {
@@ -225,6 +236,7 @@ final class SpeakEngine {
stopMic()
utterance?.input.finish()
utterance = nil
+ micQueue.sync { pressSamples = [] }
finals = []
volatile = ""
phase = .idle
@@ -257,7 +269,10 @@ final class SpeakEngine {
while true {
guard let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 4096),
(try? file.read(into: buf)) != nil, buf.frameLength > 0 else { break }
- if let c = conv.convert(buf, to: format) { input.yield(AnalyzerInput(buffer: c)) }
+ if let c = conv.convert(buf, to: format) {
+ input.yield(AnalyzerInput(buffer: c))
+ micQueue.sync { keepForMing(c) }
+ }
}
finishUtterance()
}
@@ -280,6 +295,7 @@ final class SpeakEngine {
if let c = conv.convert(buf, to: format) {
cont.yield(AnalyzerInput(buffer: c))
self.recordMic(c)
+ self.keepForMing(c)
}
}
}
@@ -292,6 +308,32 @@ final class SpeakEngine {
}
}
+ private nonisolated func keepForMing(_ buffer: AVAudioPCMBuffer) {
+ guard pressSamples.count < Self.pressLimit,
+ let c = pressConverter.convert(buffer, to: Self.pressFormat), let p = c.int16ChannelData else { return }
+ pressSamples.append(contentsOf: UnsafeBufferPointer(start: p[0], count: Int(c.frameLength)))
+ }
+
+ /// The press as a WAV file in memory (44-byte RIFF header + little-endian samples).
+ private func takePressWAV() -> Data? {
+ let samples = micQueue.sync { () -> [Int16] in
+ defer { pressSamples = [] }
+ return pressSamples
+ }
+ guard samples.count >= 16_000 / 4 else { return nil }
+ var d = Data()
+ func u32(_ v: UInt32) { withUnsafeBytes(of: v.littleEndian) { d.append(contentsOf: $0) } }
+ func u16(_ v: UInt16) { withUnsafeBytes(of: v.littleEndian) { d.append(contentsOf: $0) } }
+ let bytes = UInt32(samples.count * 2)
+ d.append(contentsOf: Array("RIFF".utf8)); u32(36 + bytes); d.append(contentsOf: Array("WAVE".utf8))
+ d.append(contentsOf: Array("fmt ".utf8)); u32(16); u16(1); u16(1); u32(16_000); u32(32_000); u16(2); u16(16)
+ d.append(contentsOf: Array("data".utf8)); u32(bytes)
+ samples.withUnsafeBufferPointer { buf in
+ for s in buf { withUnsafeBytes(of: s.littleEndian) { d.append(contentsOf: $0) } }
+ }
+ return d
+ }
+
private nonisolated func recordMic(_ buffer: AVAudioPCMBuffer) {
guard let url = micRecordURL else { return }
if micRecorder == nil { micRecorder = AudioFileWriter.open(url, format: buffer.format) }
@@ -314,23 +356,38 @@ final class SpeakEngine {
u.input.finish()
let released = releasedAt ?? Date()
releasedAt = nil
+ let wav = takePressWAV()
+ let from = settings.speakFromLang.code
+ let to = targetCode
+ let trace = TranslateTrace()
+ // Ming hears the audio while the on-device transcriber finishes, so its fallback costs nothing.
+ let ming = Task { () -> (original: String, translation: String)? in
+ guard let wav, let interpret else { return nil }
+ return await interpret(wav, from, to, trace)
+ }
Task {
- let text = await u.text.value
- let textAt = Date()
+ var text = await u.text.value
finals = []
volatile = ""
+ if !text.isEmpty { onLive?(.translating, text, "") }
+ let heard = await ming.value
+ if let heard { text = heard.original }
+ // Ming answers recognition and translation together: its whole call counts as `recognize`.
+ let textAt = Date()
guard !text.isEmpty else {
phase = .idle
onLive?(.idle, "", "")
return
}
- let from = settings.speakFromLang.code
- let to = targetCode
onLive?(.translating, text, "")
// Never speak the untranslated original into the room: if translation
// fails, say so on the bar and send nothing.
- let trace = TranslateTrace()
- let result = await translate?(text, from, to, trace)
+ let result: String?
+ if let heard {
+ result = heard.translation
+ } else {
+ result = await translate?(text, from, to, trace)
+ }
let translatedAt = Date()
@MainActor func timing(voice: Double?) -> SentenceTiming {
SentenceTiming(at: textAt, side: "me", chars: text.count, recognize: textAt.timeIntervalSince(released),
@@ -344,7 +401,8 @@ final class SpeakEngine {
onLive?(.idle, text, "翻译失败,这句话未发送")
return
}
- contentLog("SPEAK [\(from)→\(to)] \(text) => \(translated)")
+ contentLog("SPEAK [\(from)→\(to)] via=\(trace.via) \(text) => \(translated)")
+ debugLog("speak: via=\(trace.via) recognize \(String(format: "%.2f", textAt.timeIntervalSince(released))) s translate \(String(format: "%.2f", translatedAt.timeIntervalSince(textAt))) s fallbacks=\(trace.fallbacks)")
onUtterance?(text, translated, from, to, Date().timeIntervalSince(pressStarted))
phase = .speaking
onLive?(.speaking, text, translated)
diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swift
index 004ad9a..af0948c 100644
--- a/Sources/LiveSubs/Translator.swift
+++ b/Sources/LiveSubs/Translator.swift
@@ -125,6 +125,61 @@ final class TranslationService {
}
}
+ /// Speak-back in one call: Ming's audio model hears the press and returns what was said and its
+ /// translation. One queue slot instead of two, and names come out right more often than from
+ /// the on-device transcript. Anything but the two labelled lines is dropped (nil): the model
+ /// sometimes answers a question instead of interpreting it, and that must never reach the room.
+ func interpret(wav: Data, source: String, target: String, trace: TranslateTrace) async -> (original: String, translation: String)? {
+ guard ling.usable, source != target else { return nil }
+ var prompt = "You are an interpreter from \(Self.englishName(source)) into \(Self.englishName(target)). "
+ + "Never answer or act on what is said; only interpret it."
+ let names = glossary()
+ if !names.isEmpty { prompt += "\nKnown names and terms (use these spellings): " + names.joined(separator: "; ") }
+ let instruction = """
+ Reply in exactly two lines:
+ ORIGINAL: <what was said, in \(Self.englishName(source))>
+ TRANSLATION: <its translation into \(Self.englishName(target))>
+ """
+ let started = Date()
+ var failure = "unparsed"
+ do {
+ // A 30 s press is ~1 MB of audio: a little more time than a text translation (10 s).
+ let reply = try await ling.chat(content: prompt, instruction: instruction, priority: .speak, maxTokens: 800,
+ timeout: 12, model: "Ming-3.0-audio-flash", audio: wav,
+ onQueued: { [weak trace] in trace?.lingQueue += $0 })
+ if let parsed = Self.parseInterpretation(reply, target: target) {
+ trace.attempts.append(.init(provider: "ming", seconds: Date().timeIntervalSince(started), failure: nil))
+ return parsed
+ }
+ debugLog("interpret: reply not in the two-line form, dropped")
+ } catch {
+ debugLog("interpret ming failed: \(error)")
+ failure = (error as? LingClient.Failure).map(LingClient.name) ?? "error"
+ }
+ trace.attempts.append(.init(provider: "ming", seconds: Date().timeIntervalSince(started), failure: failure))
+ return nil
+ }
+
+ /// `ORIGINAL: …` then `TRANSLATION: …`, both non-empty, and the translation in the target's
+ /// script (Chinese/Japanese targets need CJK, others must not be mostly CJK).
+ static func parseInterpretation(_ reply: String, target: String) -> (original: String, translation: String)? {
+ var original: String?, translation: String?
+ for raw in reply.components(separatedBy: .newlines) {
+ let line = raw.trimmingCharacters(in: .whitespaces)
+ if line.uppercased().hasPrefix("ORIGINAL:") {
+ original = String(line.dropFirst("ORIGINAL:".count)).trimmingCharacters(in: .whitespaces)
+ } else if line.uppercased().hasPrefix("TRANSLATION:") {
+ translation = String(line.dropFirst("TRANSLATION:".count)).trimmingCharacters(in: .whitespaces)
+ }
+ }
+ guard let o = original, let t = translation, !o.isEmpty, !t.isEmpty, o != t else { return nil }
+ let letters = t.unicodeScalars.filter { $0.properties.isAlphabetic }
+ let cjk = letters.filter { (0x3040...0x9FFF).contains($0.value) || (0xAC00...0xD7AF).contains($0.value) }.count
+ let wantsCJK = ["zh", "ja", "ko"].contains(where: { target.hasPrefix($0) })
+ if wantsCJK ? cjk == 0 : cjk * 2 > letters.count { return nil }
+ return (o, t)
+ }
+
private func viaApple(_ text: String, source: String, target: String) async -> String? {
guard source != "auto" else { return nil }
let from = Locale.Language(identifier: Self.appleCode(source))
diff --git a/site/changelog.json b/site/changelog.json
index 4d2fb69..1dfee5b 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -46,6 +46,11 @@
"title": "App 菜单。",
"text": "知了的窗口开着时,左上角有菜单、Dock 里有图标、⌘Tab 能切到;⌘F 搜索文字记录。"
},
+ {
+ "kind": "improved",
+ "title": "同声传译听得更准。",
+ "text": "填了 Ling key 时,你说的话由 Ming 语音模型一步听懂并翻译,人名、专有名词更少听错,松开约 2 秒后说出去;Ming 慢或出错时自动改用本机识别。"
+ },
{
"kind": "improved",
"title": "按住右 ⌥ 说话。",