知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix: drop Ling's remarks about a garbled line instead of showing them as the translation
wquguru9641ae437194
diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swiftindex 00c4159..d50f92f 100644--- a/Sources/LiveSubs/ListenEngine.swift+++ b/Sources/LiveSubs/ListenEngine.swift@@ -517,9 +517,11 @@ final class ListenEngine {guard !translationOff(), let seg = segments.first(where: { $0.id == id }) else { return }let trace = TranslateTrace()let asked = Date()+ // The target follows the detected language; log the one this call used, not the one after.+ let target = resolvedTargetTask { [weak self] inguard let self else { return }- let result = await self.translate(seg.text, source: seg.sourceCode, trace: trace)+ let result = await self.translate(seg.text, source: seg.sourceCode, target: target, trace: trace)if let timing = self.finalTiming.removeValue(forKey: id), !trace.attempts.isEmpty {self.onTiming?(SentenceTiming(at: timing.at, side: "them", chars: seg.text.count, recognize: timing.recognize,queue: trace.lingQueue, translate: Date().timeIntervalSince(asked), voice: nil,@@ -533,7 +535,7 @@ final class ListenEngine {if let idx = self.segments.firstIndex(where: { $0.id == id }) {self.segments[idx].translation = out}- contentLog("TRANSLATE [\(seg.sourceCode)→\(self.resolvedTarget)] \(seg.text) => \(out)")+ contentLog("TRANSLATE [\(seg.sourceCode)→\(target)] \(seg.text) => \(out)")self.onTranslated?(id, out)self.renderSubtitles()}diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swiftindex af0948c..d32dd6f 100644--- a/Sources/LiveSubs/Translator.swift+++ b/Sources/LiveSubs/Translator.swift@@ -118,7 +118,12 @@ final class TranslationService {let out = try await ling.chat(content: prompt, instruction: "Translate.", priority: kind == .speak ? .speak : .translate,maxTokens: 400, timeout: kind == .speak ? 10 : 6,onQueued: { [weak trace] in trace?.lingQueue += $0 })- return (out.isEmpty ? nil : out, "empty")+ if out.isEmpty { return (nil, "empty") }+ guard let clean = Self.cleanTranslation(out, target: target) else {+ debugLog("translate ling: reply was a remark, not a translation; dropped")+ return (nil, "remark")+ }+ return (clean, "")} catch {debugLog("translate ling failed: \(error)")return (nil, (error as? LingClient.Failure).map(LingClient.name) ?? "error")@@ -180,6 +185,38 @@ final class TranslationService {return (o, t)}+ /// Ling sometimes comments on a garbled subtitle ("The subtitle appears to be… Here is the+ /// best-effort translation:") instead of translating it, and that would land in the subtitles and+ /// the record. Remark lines are dropped, a "Translation:" label is stripped, and what is left must+ /// be in the target's script; nil means the next provider translates it.+ nonisolated static func cleanTranslation(_ reply: String, target: String) -> String? {+ // A line is a remark only when it opens or ends like one and talks about the job itself,+ // so a subtitle that happens to start with "The text…" is kept.+ let opener = ["here is", "here's", "the subtitle", "this subtitle", "the text", "this text", "the original",+ "note", "(note", "i'm sorry", "i am sorry", "sorry", "it seems", "it appears", "this appears"]+ let about = ["translat", "subtitle", "garbled", "transcri", "asr", "speech recognition", "best-effort"]+ var kept: [String] = []+ for raw in reply.components(separatedBy: .newlines) {+ var line = raw.trimmingCharacters(in: .whitespaces)+ if line.isEmpty { continue }+ let lower = line.lowercased()+ if lower.hasPrefix("translation:") {+ line = String(line.dropFirst("translation:".count)).trimmingCharacters(in: .whitespaces)+ } else if opener.contains(where: { lower.hasPrefix($0) }) || line.hasSuffix(":") || line.hasSuffix(":"),+ about.contains(where: { lower.contains($0) }) {+ continue+ }+ if !line.isEmpty { kept.append(line) }+ }+ let out = kept.joined(separator: " ").trimmingCharacters(in: CharacterSet(charactersIn: "\"“”「」 "))+ guard !out.isEmpty else { return nil }+ let letters = out.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 !letters.isEmpty, wantsCJK ? cjk == 0 : cjk * 2 > letters.count { return nil }+ return out+ }+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/Tests/LiveSubsTests/TranslatorTests.swift b/Tests/LiveSubsTests/TranslatorTests.swiftnew file mode 100644index 0000000..3d7851f--- /dev/null+++ b/Tests/LiveSubsTests/TranslatorTests.swift@@ -0,0 +1,31 @@+import Testing+@testable import LiveSubs++@Suite struct TranslatorTests {+ @Test func remarkInsteadOfTranslationIsDropped() {+ // Issue #2: Ling commented on a garbled line and the remark became the subtitle.+ let reply = "The subtitle appears to be a mix of Chinese and heavily garbled English (likely from poor audio or ASR errors). Here is the best-effort translation:"+ #expect(TranslationService.cleanTranslation(reply, target: "en-US") == nil)+ #expect(TranslationService.cleanTranslation(reply, target: "zh-CN") == nil)+ }++ @Test func remarkLinesAroundATranslationAreStripped() {+ let reply = "Here is the best-effort translation:\n我们周五前把落地页文案定下来。"+ #expect(TranslationService.cleanTranslation(reply, target: "zh-CN") == "我们周五前把落地页文案定下来。")+ #expect(TranslationService.cleanTranslation("Translation: We ship on Friday.", target: "en-US") == "We ship on Friday.")+ #expect(TranslationService.cleanTranslation("“我们周五发布。”", target: "zh-CN") == "我们周五发布。")+ }++ @Test func ordinaryTranslationsAreKept() {+ #expect(TranslationService.cleanTranslation("The text is due on Friday.", target: "en-US") == "The text is due on Friday.")+ #expect(TranslationService.cleanTranslation("There are three points:", target: "en-US") == "There are three points:")+ #expect(TranslationService.cleanTranslation("Note the deadline is Tuesday.", target: "en-US") == "Note the deadline is Tuesday.")+ #expect(TranslationService.cleanTranslation("2026", target: "zh-CN") == "2026")+ #expect(TranslationService.cleanTranslation("我们用 API 和 SDK。", target: "zh-CN") == "我们用 API 和 SDK。")+ }++ @Test func translationInTheWrongScriptIsDropped() {+ #expect(TranslationService.cleanTranslation("We ship on Friday.", target: "zh-CN") == nil)+ #expect(TranslationService.cleanTranslation("我们周五发布。", target: "en-US") == nil)+ }+}