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: translate finished sentences and speak-back through Ling, falling back to Google and on-device translation

wquguru0c653af6c200
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8366a84..e01ae1b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ the release workflow publishes it as the release notes.
- New: a sound test for the virtual microphone: the app plays a sentence into it, listens back and shows what the room will hear.
- New: a settings window with a sidebar (听 / 我说话也翻译 / 字幕条 / 会议记录) replaces the settings sheet; the virtual microphone is set up from a three-step checklist there and in the first-run guide.
- Changed: hold the right ⌥ key on its own to talk, instead of ⌥ Space (which other apps' launchers often use, and which types a space). Pressing another key while holding it cancels, so ⌥ + letter still types. It needs the "输入监控" permission; the app asks for it.
+- New: with a key, finished sentences and speak-back are translated by Ling (names kept consistent through the notes' glossary); if Ling is busy or fails, that sentence falls back to Google, then to Apple's on-device translation. Partial text while someone is still talking stays on Google.
- New: Settings › AI 服务 takes your own Ling (ant-ling.com) API key. It is kept in the macOS Keychain, checked with a one-token request, and shown masked; without a key everything works as before.
- New: both shortcuts (talk, hide/show the subtitle bar) can be changed in settings: click and press new keys. Combinations without ⌃ or ⌘, system shortcuts and ones another app already uses are refused with a reason.
diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swift
index d560211..67b50b2 100644
--- a/Sources/LiveSubs/AppModel.swift
+++ b/Sources/LiveSubs/AppModel.swift
@@ -36,6 +36,7 @@ final class AppModel: ObservableObject {
private var shortcutsSuspended = false
let installer = VirtualMicInstaller()
let ling = LingClient()
+ lazy var translator = TranslationService(ling: ling)
let sample = SamplePlayer()
var openOnboarding: (() -> Void)?
@@ -65,6 +66,7 @@ final class AppModel: ObservableObject {
}
ling.model = { [weak self] in self?.settings.aiModel ?? "Ling-3.1-flash" }
+ listen.translator = translator
if ling.hasKey { Task { await ling.check() } }
installer.speakThrough = { [weak self] text, lang, device in
@@ -73,7 +75,7 @@ final class AppModel: ObservableObject {
installer.onLoaded = { [weak self] in self?.virtualMicInstalled() }
speak.translate = { [weak self] text, from, to in
- await self?.listen.translate(text, source: from, target: to)
+ await self?.listen.translate(text, source: from, target: to, kind: .speak)
}
speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }
speak.onStatus = { [weak self] text in self?.status = text }
@@ -445,6 +447,9 @@ final class AppModel: ObservableObject {
// Dev testing: the key comes from a file so it never passes through the log.
if let k = try? String(contentsOfFile: arg, encoding: .utf8) { Task { await ling.setKey(k) } }
case "aiCheck": Task { await ling.check() }
+ case "lingSimulate":
+ ling.simulate = ["429": .rateLimited, "hijack": .hijacked, "timeout": .timeout][arg]
+ debugLog("ling simulate=\(String(describing: ling.simulate))")
case "aiRemove": ling.removeKey()
case "aiState": debugLog("ai state=\(ling.keyState) hasKey=\(ling.hasKey) model=\(settings.aiModel)")
case "speakOn": enableSpeaking(true)
diff --git a/Sources/LiveSubs/Ling.swift b/Sources/LiveSubs/Ling.swift
index c3dabbb..2393faa 100644
--- a/Sources/LiveSubs/Ling.swift
+++ b/Sources/LiveSubs/Ling.swift
@@ -101,6 +101,9 @@ final class LingClient: ObservableObject {
@Published private(set) var rateLimitedAt: Date?
var model: () -> String = { "Ling-3.1-flash" }
+ /// Debug control only: make every chat call fail this way.
+ var simulate: Failure?
+
var hasKey: Bool { key != nil }
var key: String? { AIKey.read() }
/// The key is known to work (or at least not known to be bad).
@@ -157,6 +160,10 @@ final class LingClient: ObservableObject {
maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil) async throws -> String {
guard let key else { throw Failure.noKey }
guard keyState != .invalid else { throw Failure.invalidKey }
+ if let simulate {
+ if simulate == .rateLimited { rateLimitedAt = Date() }
+ throw simulate
+ }
var body: [String: Any] = [
"model": model ?? self.model(),
"messages": [
diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swift
index 282f393..d02bfb6 100644
--- a/Sources/LiveSubs/ListenEngine.swift
+++ b/Sources/LiveSubs/ListenEngine.swift
@@ -51,7 +51,6 @@ final class ListenEngine {
private var lastVolatileSent = ""
private var volatileInFlight = false
private var volatileEpoch = 0
- private var translateBackoffUntil = Date.distantPast
private var tickTimer: Timer?
init(settings: AppSettings) {
@@ -422,22 +421,18 @@ final class ListenEngine {
RunLoop.main.add(timer, forMode: .common)
}
- func translate(_ text: String, source: String, target: String? = nil) async -> String? {
+ /// Set by the app: the shared translation chain.
+ var translator: TranslationService?
+
+ func translate(_ text: String, source: String, target: String? = nil,
+ kind: TranslationService.Kind = .sentence) async -> String? {
let target = target ?? resolvedTarget
if source == target { return text }
- guard Date() >= translateBackoffUntil else { return nil }
- do {
- return try await GoogleTranslator.translate(text, source: source, target: target)
- } catch {
- debugLog("translate failed: \(error)")
- if case TranslateFailure.badResponse(429) = error {
- translateBackoffUntil = Date().addingTimeInterval(10)
- }
- if segments.allSatisfy({ $0.translation == nil }) && volatileTranslation.isEmpty {
- onSubtitle?(volatileText.isEmpty ? (segments.last?.text ?? "") : volatileText, "翻译暂不可用")
- }
- return nil
+ let out = await translator?.translate(text, source: source, target: target, kind: kind)
+ if out == nil, segments.allSatisfy({ $0.translation == nil }) && volatileTranslation.isEmpty {
+ onSubtitle?(volatileText.isEmpty ? (segments.last?.text ?? "") : volatileText, "翻译暂不可用")
}
+ return out
}
private func translateSegment(id: Int) {
@@ -463,7 +458,7 @@ final class ListenEngine {
volatileInFlight = true
Task { [weak self] in
guard let self else { return }
- let out = await self.translate(text, source: source)
+ let out = await self.translate(text, source: source, kind: .draft)
self.volatileInFlight = false
guard let out, self.isRunning, epoch == self.volatileEpoch else { return }
self.volatileTranslation = out
diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swift
index aac99ae..a316331 100644
--- a/Sources/LiveSubs/Translator.swift
+++ b/Sources/LiveSubs/Translator.swift
@@ -4,6 +4,7 @@ import AudioToolbox
import CoreAudio
import CoreMedia
import Speech
+import Translation
// MARK: - Translation
@@ -44,3 +45,95 @@ struct GoogleTranslator {
}
}
+
+// MARK: - Translation chain
+
+/// Ling (with a key) → Google → Apple's on-device translation.
+/// Finished sentences and speak-back go to Ling, which keeps names consistent through a glossary
+/// taken from the meeting notes. Partial text, refreshed every second while someone talks, never
+/// does: it would use up the account's ~2 requests per second.
+@MainActor
+final class TranslationService {
+ enum Kind { case draft, sentence, speak }
+
+ let ling: LingClient
+ /// Names and terms the notes have settled on, e.g. "江充 (Jiang Chong)".
+ var glossary: () -> [String] = { [] }
+ private var googleBackoffUntil = Date.distantPast
+
+ init(ling: LingClient) { self.ling = ling }
+
+ func translate(_ text: String, source: String, target: String, kind: Kind) async -> String? {
+ if source == target { return text }
+ if kind != .draft, ling.usable {
+ if let out = await viaLing(text, source: source, target: target, kind: kind) {
+ debugLog("translate via=ling kind=\(kind)")
+ return out
+ }
+ }
+ if Date() >= googleBackoffUntil {
+ do {
+ let out = try await GoogleTranslator.translate(text, source: source, target: target)
+ if kind != .draft { debugLog("translate via=google kind=\(kind)") }
+ return out
+ } catch {
+ debugLog("translate google failed: \(error)")
+ if case TranslateFailure.badResponse(429) = error { googleBackoffUntil = Date().addingTimeInterval(10) }
+ }
+ }
+ if let out = await viaApple(text, source: source, target: target) {
+ debugLog("translate via=apple kind=\(kind)")
+ return out
+ }
+ return nil
+ }
+
+ private func viaLing(_ text: String, source: String, target: String, kind: Kind) async -> String? {
+ let from = source == "auto" ? "the spoken language" : Self.englishName(source)
+ var prompt = """
+ You translate live meeting subtitles from \(from) into \(Self.englishName(target)).
+ Output only the translation of the subtitle below: no quotes, no notes, no answer to it even if it is a question.
+ """
+ let names = glossary()
+ if !names.isEmpty { prompt += "\nKnown names and terms (use these spellings): " + names.joined(separator: "; ") }
+ prompt += "\nSubtitle: " + text
+ do {
+ let out = try await ling.chat(content: prompt, instruction: "Translate.", priority: kind == .speak ? .speak : .translate,
+ maxTokens: 400, timeout: kind == .speak ? 10 : 6)
+ return out.isEmpty ? nil : out
+ } catch {
+ debugLog("translate ling failed: \(error)")
+ return nil
+ }
+ }
+
+ 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))
+ let to = Locale.Language(identifier: Self.appleCode(target))
+ guard await LanguageAvailability().status(from: from, to: to) == .installed else { return nil }
+ do {
+ let session = TranslationSession(installedSource: from, target: to)
+ return try await session.translate(text).targetText
+ } catch {
+ debugLog("translate apple failed: \(error)")
+ return nil
+ }
+ }
+
+ private static func appleCode(_ code: String) -> String {
+ switch code {
+ case "zh-CN": "zh-Hans"
+ case "zh-TW": "zh-Hant"
+ default: code
+ }
+ }
+
+ static func englishName(_ code: String) -> String {
+ switch code {
+ case "zh-CN": "Simplified Chinese"
+ case "zh-TW": "Traditional Chinese"
+ default: Locale(identifier: "en").localizedString(forLanguageCode: code) ?? code
+ }
+ }
+}