知了 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: name speakers only from their own lines, join sentences cut by a pause, tidy stray punctuation
wquguru1fa79e7c02a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 87c4230..fb8c46c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,10 @@ the release workflow publishes it as the release notes.## Unreleased+- Fixed: with 说话人识别 on, Ling no longer names a voice from a line someone else said. A name now counts only when its line was said by that voice or within two lines of it ("Okay, Amos, thank you" right after Amos spoke), so "I'm Christina…" from an advert break no longer names the anchor; names guessed this way before are checked again and dropped. Well-known people's names are spelt as the news spells them ("Amos Hochstein", not "Hockstein"), in the names and in the notes.+- Fixed: a sentence cut in two by a short pause is joined back into one line and translated again as a whole, instead of two lines with half translations ("…at this" → "在这个"). Lines join when the second follows within 1.5 s, from the same voice, and the first doesn't end a sentence; the subtitle shows the joined sentence too.+- Fixed: lines no longer start with stray punctuation or carry runs of dots from hesitations (", , that", "in..........", ". , that is"): leading marks go, dots become one "…", repeated commas one comma.+- Fixed: a recognised "line" that is only punctuation (a "." from a breath or a click) is dropped. It used to be kept in the record and sent to Ling, which answered with a note that there was nothing to translate.- Fixed: a meeting where nobody ever spoke no longer listens forever. After the 结束会议 silence time (10 minutes by default) with nothing recognized, and no meeting app in a call, Cicada stops listening quietly, without a countdown since there is nothing to keep, and the switch goes back to 开始听. 一直记录 still keeps it listening.- Changed: the live notes window and Settings › 诊断 no longer look blank before anyone speaks. 纪要 shows one line (有人开口后,约半分钟出第一版) above the notes' own outline, shimmering where the summary and topics will appear, with what will be pulled out (结论, 待办, 人名和术语, 鱼骨图). 文字记录 shows when listening began, two rows in the bilingual shape lines will take, and 此刻 waiting with a blinking caret; a stray "." from background noise no longer replaces it. 诊断 shows the path of a sentence with what each stage measures, the translation routes with their colours, Ling 本场还没调用 and a faded example sentence in place of dashes, an empty bar and zeros; 复制诊断信息 waits until there is something to copy.- New (experimental): 说话人识别, in Settings › 通用 › 实验功能 and off by default, labels the other side's lines 说话人 1, 2… by voice, on this Mac. A voice is named once it has five lines and only when at least two are heard, so a one-to-one call still reads 对方; unsure lines stay 对方. The notes window shows who is speaking with an 实验 tag and a 不准?关掉 link, and the records window, Markdown and Word exports and the notes use the same names. With a Ling key, the names fill themselves in: Ling reads how people address each other ("Thanks, George") once two voices are named, every 20 lines after that and again when the meeting ends, and the voice shows as George. Click a person above the transcript (in the records window; from the notes window it opens there) to see the line the name came from, correct it, turn it down (不是 TA) or merge two voices that are the same person; your name always wins over Ling's. Names show everywhere the numbers did, once per change of speaker as in a chat; lines whose voice isn't one of them say 未识别 rather than 对方, and to-dos in the notes name their owner (George) instead of 对方. The people above the transcript wrap onto a second line in a narrow window instead of shrinking to one letter. Turning it off hides the names again. It uses the WeSpeaker ResNet34-LM voiceprint model (VoxCeleb, CC BY 4.0), bundled with the app.diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex 2bc9031..9eb47b1 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -99,6 +99,11 @@ final class AppModel: ObservableObject {private var lineForSegment: [Int: String] = [:]private var lineCounter = 0+ /// The other side's last recorded line, which the next one may carry on (`HeardText.continues`).+ private var lastHeard: (seg: Segment, line: String)?+ /// A line that may carry on `lastHeard`, waiting to hear whose voice it is; its translation if+ /// that comes first.+ private var heldJoin: (seg: Segment, t: Double, translation: String?)?init() {listen.onSubtitle = { [weak self] src, dst in@@ -126,7 +131,9 @@ final class AppModel: ObservableObject {self?.listen.router.setVoiceCapture(on)}listen.onTranslated = { [weak self] segID, text in- guard let self, let line = self.lineForSegment[segID] else { return }+ guard let self else { return }+ if self.heldJoin?.seg.id == segID { self.heldJoin?.translation = text }+ guard let line = self.lineForSegment[segID] else { return }self.store.setTranslation(lineID: line, text)}@@ -374,6 +381,8 @@ final class AppModel: ObservableObject {diagnostics.begin()speakers.reset()lineForSegment = [:]+ lastHeard = nil+ heldJoin = nilspeechHeard = falsemeetingSubtitles = nilautoEnded = false@@ -402,6 +411,10 @@ final class AppModel: ObservableObject {listen.stop()listen.router.setRecording(nil)speak.setRecording(nil)+ if let held = heldJoin {+ heldJoin = nil+ appendHeard(held.seg, t: held.t, translation: held.translation)+ }// Read the whole meeting for names once more (the id outlives store.end).let ended = store.liveIDstore.end(at: endedAt)@@ -848,14 +861,69 @@ final class AppModel: ObservableObject {private func recordHeard(_ seg: Segment, duration: Double) {guard let start = store.liveStart else { return }+ let t = max(0, Date().timeIntervalSince(start) - duration)+ // A line still waiting for its voice is overtaken: it stands on its own.+ if let held = heldJoin {+ heldJoin = nil+ appendHeard(held.seg, t: held.t, translation: held.translation)+ }+ guard let prev = lastHeard, store.session(store.liveID ?? "")?.lines.last?.id == prev.line,+ prev.seg.clock == seg.clock, prev.seg.sourceCode == seg.sourceCode,+ HeardText.continues(prev.seg.text, seg.text, gap: seg.start - prev.seg.end, cut: prev.seg.cut) else {+ appendHeard(seg, t: t, tag: true)+ return+ }+ // Two voices never share a line: hear whose this is first (a few hundredths of a second).+ if settings.speakerVoices, let samples = seg.voiceSamples, seg.text.filter(\.isLetter).count >= 2 {+ heldJoin = (seg, t, nil)+ speakers.voice(of: samples) { [weak self] voice in self?.heardVoice(seg, voice) }+ return+ }+ join(seg, onto: prev)+ }++ private func heardVoice(_ seg: Segment, _ voice: Int?) {+ guard let held = heldJoin, held.seg.id == seg.id else {+ // Already recorded on its own (another line came first).+ if let voice, let line = lineForSegment[seg.id] { speakers.onVoice?(line, voice) }+ return+ }+ heldJoin = nil+ let lines = store.session(store.liveID ?? "")?.lines ?? []+ if let prev = lastHeard, let last = lines.last, last.id == prev.line,+ voice == nil || last.voice == nil || voice == last.voice {+ join(seg, onto: prev) // the earlier line's voice stays+ } else {+ appendHeard(seg, t: held.t, translation: held.translation)+ if let voice, let line = lineForSegment[seg.id] { speakers.onVoice?(line, voice) }+ }+ }++ /// One sentence a pause cut in two: the earlier line takes the rest and is translated again whole.+ private func join(_ seg: Segment, onto prev: (seg: Segment, line: String)) {+ let text = HeardText.join(prev.seg.text, seg.text)+ var joined = prev.seg+ joined.text = text+ joined.end = seg.end+ joined.cut = seg.cut+ lastHeard = (joined, prev.line)+ store.setSource(lineID: prev.line, text)+ listen.join(seg.id, into: prev.seg.id, text: text)+ contentLog("JOIN \(prev.line) += \(seg.text)")+ heardWords()+ }++ private func appendHeard(_ seg: Segment, t: Double, translation: String? = nil, tag: Bool = false) {lineCounter += 1let id = "h\(lineCounter)-\(seg.id)"lineForSegment[seg.id] = id- let t = max(0, Date().timeIntervalSince(start) - duration)- store.append(TranscriptLine(id: id, t: t, speaker: "them", src: seg.text, dst: seg.translation,+ store.append(TranscriptLine(id: id, t: t, speaker: "them", src: seg.text, dst: translation ?? seg.translation,srcLang: seg.sourceCode, dstLang: listen.resolvedTarget))+ var kept = seg+ kept.voiceSamples = nil+ lastHeard = (kept, id)// A line with hardly a letter ("." from a breath or a click) gets no voiceprint.- if settings.speakerVoices, let samples = seg.voiceSamples, seg.text.filter(\.isLetter).count >= 2 {+ if tag, settings.speakerVoices, let samples = seg.voiceSamples, seg.text.filter(\.isLetter).count >= 2 {speakers.tag(lineID: id, samples: samples)}heardWords()diff --git a/Sources/LiveSubs/HeardText.swift b/Sources/LiveSubs/HeardText.swiftnew file mode 100644index 0000000..7860e23--- /dev/null+++ b/Sources/LiveSubs/HeardText.swift@@ -0,0 +1,55 @@+import Foundation++/// The other side's finished lines before they are recorded and translated: tidied, and joined to the+/// line before when a pause cut one sentence in two.+enum HeardText {+ /// Speech recognition leaves stray marks where it hears breaths and hesitations: "in..........",+ /// ", , that", ". , that is". They start lines, and a translator turns them into ",……" or worse.+ static func clean(_ text: String) -> String {+ var s = text+ // Two dots or more, with or without spaces or commas between: one ellipsis.+ s = s.replacingOccurrences(of: #"\s*[.。]{2,}|\s*…+"#, with: "…", options: .regularExpression)+ s = s.replacingOccurrences(of: #"…(?:[\s,,]*…)+"#, with: "…", options: .regularExpression)+ // ", ," and ",," are one comma; a comma against an ellipsis adds nothing.+ s = s.replacingOccurrences(of: #"([,,])(?:\s*[,,])+"#, with: "$1", options: .regularExpression)+ s = s.replacingOccurrences(of: #"[,,]\s*…|…\s*[,,]"#, with: "…", options: .regularExpression)+ // "UALE ," → "UALE,".+ s = s.replacingOccurrences(of: #"\s+([,,.。…??!!;;::])"#, with: "$1", options: .regularExpression)+ s = s.replacingOccurrences(of: #"\s{2,}"#, with: " ", options: .regularExpression)+ // A line starts with a word, not with what was left of the last one.+ let lead: Set<Character> = [".", ",", ";", ":", "!", "?", "…", "、", ",", "。", ";", ":", "!", "?", "-", "–", "—"]+ s = String(s.drop(while: { lead.contains($0) || $0.isWhitespace }))+ return s.trimmingCharacters(in: .whitespacesAndNewlines)+ }++ /// The longest pause, in seconds, that still joins two pieces of one sentence.+ static let joinGap = 1.5+ /// A line this long takes nothing more: past it a translation is slow and the line hard to read.+ /// The piece that finishes a shorter line always joins it, so a sentence is never left half.+ static let joinWords = 40++ /// Whether `next` carries on `previous`, from the same voice, rather than starting a sentence.+ /// `gap`: seconds of audio between them. `cut`: Cicada ended `previous` at a pause (ListenEngine's+ /// `maybeCutSentence`), so its closing "." is the recognizer's guess, not the speaker's: it is+ /// ignored when `next` starts in lower case (scripts without case keep it).+ static func continues(_ previous: String, _ next: String, gap: Double, cut: Bool) -> Bool {+ guard gap >= -0.5, gap <= joinGap, let last = previous.last, let first = next.first else { return false }+ let cjk = previous.unicodeScalars.contains { $0.properties.isIdeographic }+ let size = cjk ? previous.count / 2 : previous.split(separator: " ").count+ guard size < joinWords else { return false }+ switch last {+ case "?", "!", "?", "!": return false+ case ".", "。": return cut && first.isLowercase+ default: return true+ }+ }++ static func join(_ previous: String, _ next: String) -> String {+ let cjk = previous.unicodeScalars.contains { $0.properties.isIdeographic }+ // A cut's guessed "." goes: "are going to be." + "in the…" reads as one sentence.+ var head = previous+ if head.hasSuffix(".") && !head.hasSuffix("…") { head.removeLast() }+ if head.hasSuffix("。") { head.removeLast() }+ return cjk ? head + next : head + " " + next+ }+}diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swiftindex b13b5f7..00c4159 100644--- a/Sources/LiveSubs/ListenEngine.swift+++ b/Sources/LiveSubs/ListenEngine.swift@@ -5,11 +5,15 @@ import Speechstruct Segment {let id: Int- let text: String+ var text: Stringlet sourceCode: Stringvar translation: String?/// The sentence's audio, 16 kHz mono, when telling voices apart is on.var voiceSamples: [Float]? = nil+ /// Where it sits in the recognizer's audio (seconds; `clock` changes with each new recognizer),+ /// and whether Cicada ended it at a pause: what deciding a join needs (`HeardText.continues`).+ var start = 0.0, end = 0.0, clock = 0+ var cut = false}/// System audio → language detection → on-device transcription → translation.@@ -68,6 +72,8 @@ final class ListenEngine {private var cutting = falseprivate var lastCut = ""private var lastCutThrough = 0.0+ /// A cut was asked for: the next final line ends at Cicada's pause, not the speaker's.+ private var cutAsked = false/// Final transcript time and how long after the last word it came, per segment, until its translation lands.private var finalTiming: [Int: (at: Date, recognize: Double?)] = [:]@@ -259,6 +265,7 @@ final class ListenEngine {volatileTranslation = ""lastVolatileSent = ""volatileEpoch += 1+ cutAsked = falseonStateChange?()let transcriber = SpeechTranscriber(locale: Locale(identifier: lang.locale),@@ -315,11 +322,14 @@ final class ListenEngine {private func handle(_ result: SpeechTranscriber.Result, generation gen: Int) {guard gen == generation, isRunning else { return }failureStreak = 0- let text = String(result.text.characters).trimmingCharacters(in: .whitespacesAndNewlines)+ var text = String(result.text.characters).trimmingCharacters(in: .whitespacesAndNewlines)if result.isFinal {+ text = HeardText.clean(text)volatileText = ""volatileEpoch += 1- guard !text.isEmpty else { renderSubtitles(); return }+ // A "." or "…" from a breath or a click is no sentence: Ling would answer it with a note that+ // there was nothing to translate, and it would sit in the record as a line.+ guard text.contains(where: \.isLetter) else { renderSubtitles(); return }var weighted = 0.0, chars = 0for run in result.text.runs {guard let c = run.transcriptionConfidence else { continue }@@ -330,6 +340,11 @@ final class ListenEngine {let conf = chars > 0 ? weighted / Double(chars) : 1let provisional = volatileTranslation.isEmpty ? nil : volatileTranslationvar seg = Segment(id: nextSegmentID, text: text, sourceCode: activeLang?.code ?? "auto", translation: provisional)+ seg.start = CMTimeGetSeconds(result.range.start)+ seg.end = CMTimeGetSeconds(result.range.end)+ seg.clock = gen+ seg.cut = cutAsked+ cutAsked = falseif settings.speakerVoices {seg.voiceSamples = router.voiceSamples(from: CMTimeGetSeconds(result.range.start), to: CMTimeGetSeconds(result.range.end))}@@ -513,6 +528,8 @@ final class ListenEngine {}guard let out = result else { return }guard self.isRunning else { return }+ // The line was joined with the next one meanwhile: only the whole sentence's translation counts.+ if let now = self.segments.first(where: { $0.id == id }), now.text != seg.text { return }if let idx = self.segments.firstIndex(where: { $0.id == id }) {self.segments[idx].translation = out}@@ -522,6 +539,21 @@ final class ListenEngine {}}+ /// The app joined segment `id` onto `into` (one sentence cut by a pause): the bar shows them as+ /// one, and the whole sentence is translated again. The old translation stays until then.+ func join(_ id: Int, into: Int, text: String) {+ let piece = segments.firstIndex(where: { $0.id == id }).map { segments.remove(at: $0) }+ if let i = segments.firstIndex(where: { $0.id == into }) {+ segments[i].text = text+ } else {+ // The bar was cleared in between: show the joined sentence on its own.+ segments.append(Segment(id: into, text: text, sourceCode: piece?.sourceCode ?? activeLang?.code ?? "auto", translation: nil))+ }+ finalTiming[id] = nil+ translateSegment(id: into)+ renderSubtitles()+ }+/// SpeechTranscriber ends a sentence only at a clear pause; in a quick conversation that can/// take 15–20 s, and the subtitle stays a draft that long (the notes wait for it too). A long/// line in progress is ended at the next small pause: a dip in the sound, or no new words for@@ -547,6 +579,7 @@ final class ListenEngine {return}cutting = true+ cutAsked = truelastCut = volatileTextlastCutThrough = throughlet chars = volatileText.count@@ -556,6 +589,7 @@ final class ListenEngine {debugLog(String(format: "cut: line of %d chars ended after %.1f s (%@)", chars, held, why))} catch {debugLog("cut: finalize failed \(error)")+ self?.cutAsked = false}self?.cutting = false}diff --git a/Sources/LiveSubs/Notes.swift b/Sources/LiveSubs/Notes.swiftindex 427d10f..61e1063 100644--- a/Sources/LiveSubs/Notes.swift+++ b/Sources/LiveSubs/Notes.swift@@ -336,7 +336,7 @@ final class NotesEngine: ObservableObject {if context < from {p += "Already covered (context only):\n" + (context..<from).map(line).joined(separator: "\n") + "\n\n"}- p += "\(final ? "Transcript" : "New lines") (id, mm:ss, speaker 对方=the other side / 你=me / a name or 说话人N=one person on the other side, told apart by voice and possibly wrong / 未识别=someone on the other side not identified, text). Speech recognition makes mistakes, often in names: correct them from context.\n"+ p += "\(final ? "Transcript" : "New lines") (id, mm:ss, speaker 对方=the other side / 你=me / a name or 说话人N=one person on the other side, told apart by voice and possibly wrong / 未识别=someone on the other side not identified, text). Speech recognition makes mistakes, often in names: correct them from context, and write a public figure's name as the news spells it.\n"p += (from..<lines.count).map(line).joined(separator: "\n")// The model splits too eagerly when only told how long a topic should be: say plainly// whether this update may start one.diff --git a/Sources/LiveSubs/SessionStore.swift b/Sources/LiveSubs/SessionStore.swiftindex 74d59a9..c2073fc 100644--- a/Sources/LiveSubs/SessionStore.swift+++ b/Sources/LiveSubs/SessionStore.swift@@ -159,6 +159,14 @@ final class SessionStore: ObservableObject {scheduleSave(id)}+ /// A line joined with the one after it (`HeardText.join`).+ func setSource(lineID: String, _ text: String) {+ guard let id = liveID, let i = index(id),+ let j = sessions[i].lines.firstIndex(where: { $0.id == lineID }) else { return }+ sessions[i].lines[j].src = text+ scheduleSave(id)+ }+func setVoice(lineID: String, _ voice: Int) {guard let id = liveID, let i = index(id),let j = sessions[i].lines.firstIndex(where: { $0.id == lineID }) else { return }@@ -175,13 +183,15 @@ final class SessionStore: ObservableObject {saveNow(id)}- /// Ling's latest guesses; earlier ones stay for voices it no longer mentions.- func setVoiceGuesses(_ id: String, _ guesses: [Int: VoiceGuess]) {- guard let i = index(id), !guesses.isEmpty else { return }+ /// Ling's latest guesses; earlier ones stay for voices it no longer mentions, unless it now named+ /// them without evidence (`refuted`, voice → name): then that earlier name goes too.+ func setVoiceGuesses(_ id: String, _ guesses: [Int: VoiceGuess], refuted: [Int: String] = [:]) {+ guard let i = index(id), !guesses.isEmpty || !refuted.isEmpty else { return }var all = sessions[i].voiceGuesses ?? [:]+ for (v, name) in refuted where guesses[v] == nil && all[String(v)]?.name == name { all[String(v)] = nil }for (v, g) in guesses { all[String(v)] = g }guard all != sessions[i].voiceGuesses else { return }- sessions[i].voiceGuesses = all+ sessions[i].voiceGuesses = all.isEmpty ? nil : allsaveNow(id)}diff --git a/Sources/LiveSubs/SpeakerID.swift b/Sources/LiveSubs/SpeakerID.swiftindex 0fcc0cd..aaa44b6 100644--- a/Sources/LiveSubs/SpeakerID.swift+++ b/Sources/LiveSubs/SpeakerID.swift@@ -283,6 +283,13 @@ final class SpeakerTagger {func merge(_ from: Int, into: Int) { queue.async { [self] in clusterer.merge(from, into: into) } }func tag(lineID: String, samples: [Float]) {+ voice(of: samples) { [weak self] voice in+ if let voice { self?.onVoice?(lineID, voice) }+ }+ }++ /// The voice of a line not recorded yet; nil when unsure. Like `tag`, it counts towards that voice.+ func voice(of samples: [Float], _ done: @escaping @MainActor (Int?) -> Void) {let seconds = Double(samples.count) / 16000queue.async { [self] inif model == nil, !loadFailed {@@ -291,10 +298,8 @@ final class SpeakerTagger {debugLog("voiceprint model failed to load: \(error)")}}- guard let model, let v = model.embed(samples), let voice = clusterer.label(v, seconds: seconds) else { return }- DispatchQueue.main.async { [weak self] in- MainActor.assumeIsolated { self?.onVoice?(lineID, voice) }- }+ let voice = model.flatMap { $0.embed(samples) }.flatMap { clusterer.label($0, seconds: seconds) }+ DispatchQueue.main.async { MainActor.assumeIsolated { done(voice) } }}}}@@ -318,38 +323,69 @@ enum SpeakerNameGuess {}static let instruction = """- Who are the people labelled 说话人N? Name one only when the transcript makes it clear: they introduce \- themselves, or someone addresses them by name and they answer next, or others name them as they speak. \- Use the name as written. Leave out anyone you are unsure of. Reply as JSON: \- {"speakers": [{"speaker": 2, "name": "George", "evidence": "L12"}]}, with an empty list if none.+ Who are the people labelled 说话人N? Name one only when the transcript makes it clear: they \+ introduce themselves on a line labelled with their own 说话人N; someone addresses them by name just \+ before or after they speak ("Thanks, George" right after 说话人1's answer: 说话人1 is George); \+ or others name them as they speak. A name on a 对方 line, or far from any line of 说话人N (an advert, \+ a clip, people introducing themselves on another show), is not theirs. Speech recognition writes \+ names by ear and often misspells them: for a public figure (an official, an executive, a presenter) \+ recognisable from the name and what is said, write the name as the news spells it ("Jensen Hwang" \+ → "Jensen Huang"); otherwise as written. Leave out anyone \+ you are unsure of. Reply as JSON: {"speakers": [{"speaker": 2, "name": "George", "evidence": "L12"}]}, \+ the evidence being the line with the name; an empty list if none. Check each name's spelling before replying."""/// Voice id → guess, with the evidence line quoted ("03:21 “Thanks, George”"). A name Ling gives/// two voices goes to the one with more lines: two people rarely share a name in one meeting.- static func parse(_ reply: String, _ s: Session) -> [Int: VoiceGuess] {+ static func parse(_ reply: String, _ s: Session) -> [Int: VoiceGuess] { read(reply, s).found }++ /// How far from the evidence line the named voice may speak: "Okay, Amos, thank you" comes+ /// right after Amos's last words.+ static let evidenceReach = 2++ /// `refuted`: voices Ling named on a line they neither said nor spoke next to ("I'm Christina"+ /// in an advert, given to the anchor); such a name is dropped, and an earlier copy of it too.+ static func read(_ reply: String, _ s: Session) -> (found: [Int: VoiceGuess], refuted: [Int: String]) {guard let data = reply.data(using: .utf8),let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let list = obj["speakers"] as? [[String: Any]] else { return [:] }+ let list = obj["speakers"] as? [[String: Any]] else { return ([:], [:]) }let voiceOf = Dictionary(uniqueKeysWithValues: SpeakerLabels.voiceNumbers(s.lines).map { ($1, $0) })let lines = Array(s.lines.suffix(400))func count(_ v: Int) -> Int { s.lines.filter { $0.voice == v }.count }- var out: [Int: VoiceGuess] = [:]+ var out: [Int: VoiceGuess] = [:], refuted: [Int: String] = [:]for item in list {guard let n = (item["speaker"] as? Int) ?? Int("\(item["speaker"] ?? "")"), let v = voiceOf[n],let name = (item["name"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines),!name.isEmpty, name.count <= 40 else { continue }+ // "L52" or "L52, L53": the first line named.+ let e = (item["evidence"] as? String) ?? "\(item["evidence"] ?? "")"+ guard let i = Int(String(e.drop(while: { !$0.isNumber }).prefix(while: \.isNumber))).map({ $0 - 1 }),+ lines.indices.contains(i),+ lines[max(0, i - evidenceReach)...min(lines.count - 1, i + evidenceReach)]+ .contains(where: { $0.speaker == "them" && $0.voice == v }) else {+ refuted[v] = name+ continue+ }if let other = out.first(where: { $0.value.name == name })?.key {if count(other) >= count(v) { continue }out[other] = nil}- var evidence = ""- if let e = item["evidence"] as? String, let i = Int(e.drop(while: { !$0.isNumber })), lines.indices.contains(i - 1) {- let l = lines[i - 1]- evidence = "\(TranscriptExport.clock(l.t)) “\(l.src.count > 60 ? String(l.src.prefix(60)) + "…" : l.src)”"- }+ let l = lines[i]+ let evidence = "\(TranscriptExport.clock(l.t)) “\(l.src.count > 60 ? String(l.src.prefix(60)) + "…" : l.src)”"out[v] = VoiceGuess(name: name, evidence: evidence)}- return out+ return (out, refuted)+ }++ /// Whether a stored guess still stands by the same rule (guesses from before it was checked): its+ /// evidence ("04:41 “I'm Christina…”") is found again and the voice speaks there. Kept when not found.+ static func holds(_ g: VoiceGuess, voice v: Int, in s: Session) -> Bool {+ guard let open = g.evidence.firstIndex(of: "“") else { return true }+ let clock = g.evidence[..<open].trimmingCharacters(in: .whitespaces)+ let quote = String(g.evidence[g.evidence.index(after: open)...].dropLast().prefix(while: { $0 != "…" }))+ guard let i = s.lines.firstIndex(where: { TranscriptExport.clock($0.t) == clock && $0.src.hasPrefix(quote) }) else { return true }+ return s.lines[max(0, i - evidenceReach)...min(s.lines.count - 1, i + evidenceReach)]+ .contains { $0.speaker == "them" && $0.voice == v }}}@@ -389,9 +425,14 @@ final class SpeakerNamer: ObservableObject {do {let reply = try await ling.chat(content: content, instruction: SpeakerNameGuess.instruction,priority: .notes, json: true, maxTokens: 300)- let found = SpeakerNameGuess.parse(reply, s)- store.setVoiceGuesses(id, found)- debugLog("speaker names: \(found.count) found for \(id)")+ let (found, read) = SpeakerNameGuess.read(reply, s)+ var refuted = read+ for (key, g) in s.voiceGuesses ?? [:] {+ if let v = Int(key), found[v] == nil, !SpeakerNameGuess.holds(g, voice: v, in: s) { refuted[v] = g.name }+ }+ store.setVoiceGuesses(id, found, refuted: refuted)+ debugLog("speaker names: \(found.count) found, \(refuted.count) without evidence for \(id)")+ contentLog("speaker names reply: \(reply)")} catch {debugLog("speaker names: ling failed \(error)")}diff --git a/Tests/LiveSubsTests/HeardTextTests.swift b/Tests/LiveSubsTests/HeardTextTests.swiftnew file mode 100644index 0000000..7fb17d6--- /dev/null+++ b/Tests/LiveSubsTests/HeardTextTests.swift@@ -0,0 +1,92 @@+import Foundation+import Testing+@testable import LiveSubs++/// Lines from a recorded Bloomberg interview (session 20261103-000911).+@Suite struct HeardTextTests {+ @Test func cleanStrayMarks() {+ #expect(HeardText.clean("in..........") == "in…")+ #expect(HeardText.clean(", , that") == "that")+ #expect(HeardText.clean(",...... has translated at its end into infrastructure...") == "has translated at its end into infrastructure…")+ #expect(HeardText.clean(". , that is causing a product twice.") == "that is causing a product twice.")+ #expect(HeardText.clean("that.......... in increased production") == "that… in increased production")+ #expect(HeardText.clean("would.. would be oversupplied.") == "would… would be oversupplied.")+ #expect(HeardText.clean(", and......... in alternative infrastructure routes that let's.................") ==+ "and… in alternative infrastructure routes that let's…")+ #expect(HeardText.clean("whether it's in the UALE, , Saudi Arab, or the wider.") == "whether it's in the UALE, Saudi Arab, or the wider.")+ #expect(HeardText.clean(",, and there should be more diversified.") == "and there should be more diversified.")+ #expect(HeardText.clean(", you... lucrative") == "you… lucrative")+ #expect(HeardText.clean("of people..") == "of people…")+ // What is fine stays as it is.+ #expect(HeardText.clean("to over 1.4 million a day.") == "to over 1.4 million a day.")+ #expect(HeardText.clean("The U.S. said no.") == "The U.S. said no.")+ #expect(HeardText.clean(",,我们周四上线。。。") == "我们周四上线…")+ #expect(HeardText.clean("........") == "")+ }++ @Test func joinOnlyWhatCarriesOn() {+ // Cut mid-sentence by a pause, carried on at once.+ #expect(HeardText.continues("that… in increased production that you would have expected at this",+ "because I think as soon as this crisis is over,", gap: 0.2, cut: true))+ #expect(HeardText.continues("in, diesel and gasoline crisis in Russia that is combined with the Middle",+ "that is causing a product twice.", gap: 0.1, cut: false))+ // The recognizer put a "." where Cicada cut; the next piece starts in lower case.+ #expect(HeardText.continues("So, I think the long term headwinds for global energy markets are going to be.",+ "in the, and in the getting the tanker market back", gap: 0.3, cut: true))+ // A real full stop, a question, or too long a pause: a new line.+ #expect(!HeardText.continues("It's not just rhetoric.", "it costs a lot more to transport.", gap: 0.2, cut: false))+ #expect(!HeardText.continues("are going to be.", "So the tanker market", gap: 0.2, cut: true))+ #expect(!HeardText.continues("Is it the headlines that are moving markets?", "or is it more", gap: 0.1, cut: true))+ #expect(!HeardText.continues("at this", "because I think", gap: 2.4, cut: true))+ #expect(!HeardText.continues(String(repeating: "word ", count: 40), "and more", gap: 0.1, cut: true))+ #expect(HeardText.continues(String(repeating: "word ", count: 39), "and five or six more words", gap: 0.1, cut: true))+ #expect(HeardText.continues("我们下周", "再看这个方案", gap: 0.3, cut: true))+ #expect(!HeardText.continues("我们下周再看。", "这个方案", gap: 0.3, cut: true))+ }++ @Test func joinedText() {+ #expect(HeardText.join("are going to be.", "in the tanker market") == "are going to be in the tanker market")+ #expect(HeardText.join("at this", "because I think") == "at this because I think")+ #expect(HeardText.join("between…", "loading a ship.") == "between… loading a ship.")+ #expect(HeardText.join("我们下周", "再看") == "我们下周再看")+ }++ /// `CICADA_REPLAY=<session.json>[:<debug log>]`: prints that meeting's lines through clean-up and+ /// joining, before and after. A line counts as cut when the log has a "cut:" between its start and+ /// the next line's (no log: none); the session keeps no audio times, so a cut line's gap is taken as 0.+ @Test func replay() throws {+ guard let arg = ProcessInfo.processInfo.environment["CICADA_REPLAY"] else { return }+ let parts = arg.split(separator: ":", maxSplits: 1).map(String.init)+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601+ let s = try decoder.decode(Session.self, from: Data(contentsOf: URL(fileURLWithPath: parts[0])))+ var cuts: [Double] = []+ if parts.count > 1, let log = try? String(contentsOfFile: parts[1], encoding: .utf8) {+ let f = DateFormatter()+ f.dateFormat = "yyyy-MM-dd HH:mm:ss Z"+ for l in log.split(separator: "\n") where l.contains(" cut: line") {+ if let d = f.date(from: String(l.prefix(25))) { cuts.append(d.timeIntervalSince(s.startedAt)) }+ }+ }+ var out: [(t: Double, voice: Int?, src: String, from: [String])] = []+ for l in s.lines where l.speaker == "them" {+ let text = HeardText.clean(l.src)+ guard text.contains(where: \.isLetter) else { print("DROP \(l.src)"); continue }+ if let prev = out.last, let pi = s.lines.firstIndex(where: { $0.t == prev.t }) {+ let cut = cuts.contains { $0 >= s.lines[pi].t && $0 < l.t + 1 }+ if (prev.voice == nil || l.voice == nil || prev.voice == l.voice),+ HeardText.continues(prev.src, text, gap: cut ? 0 : .infinity, cut: cut) {+ out[out.count - 1].src = HeardText.join(prev.src, text)+ out[out.count - 1].from.append(l.src)+ continue+ }+ }+ out.append((l.t, l.voice, text, [l.src]))+ }+ for o in out where o.from.count > 1 || o.from[0] != o.src {+ print("BEFORE " + o.from.map { "«\($0)»" }.joined(separator: " + "))+ print("AFTER [\(TranscriptExport.clock(o.t)) v\(o.voice.map(String.init) ?? "-")] \(o.src)\n")+ }+ print("lines: \(s.lines.count) → \(out.count)")+ }+}diff --git a/Tests/LiveSubsTests/SpeakerTests.swift b/Tests/LiveSubsTests/SpeakerTests.swiftindex 6cb93c9..93e8391 100644--- a/Tests/LiveSubsTests/SpeakerTests.swift+++ b/Tests/LiveSubsTests/SpeakerTests.swift@@ -103,13 +103,58 @@ import Testing// One name for two voices: the one with more lines keeps it.var more = smore.lines += (11..<14).map { line($0, 4) }- #expect(SpeakerNameGuess.parse(#"{"speakers": [{"speaker": 1, "name": "Ann"}, {"speaker": 2, "name": "Ann"}]}"#, more).keys.sorted() == [4])+ #expect(SpeakerNameGuess.parse(#"{"speakers": [{"speaker": 1, "name": "Ann", "evidence": "L1"}, {"speaker": 2, "name": "Ann", "evidence": "L6"}]}"#, more).keys.sorted() == [4])#expect(SpeakerNameGuess.parse("not json", s).isEmpty)// One voice on show: nothing to ask.#expect(SpeakerNameGuess.content(Session(id: "s", title: "t", startedAt: Date(), endedAt: nil,lines: (0..<6).map { line($0, 1) }, hasAudio: false, notes: nil, renamed: nil)) == nil)}+ /// The end of session 20261103-000911 (Bloomberg TV): voice 0 is the guest, voice 1 the anchor,+ /// then an advert break with other voices.+ private var bloomberg: Session {+ let rows: [(Int?, String)] = [+ (0, "We have to invest in alternative routes to the Strait of Hormuz."), (0, "That is something that financial markets are not used to doing."),+ (1, "Let's talk about financing a little bit."), (1, "I was watching you speak yesterday as well in an interview."),+ (1, "It is still important, and you see the need to still come here."), (1, "lucrative investment opportunities, whether it's in the UAE."),+ (0, "Yes, I think that what we're going to see is a big investment in infrastructure."), (0, "We need to invest in these infrastructure routes to harden them."),+ (0, "And I think the question will be, how do we invest in them?"), (0, "We saw that in the '70s."), (0, "I think we're going to see it again."),+ (1, "Okay, Amos, thank you so much for your time this morning, Amos Hockstein, managing partner."),+ (nil, ".."), (1, "And now, coming up, we will be discussing the outlook for oil markets."), (1, "That is next live from Adipec here in Abu Dhabi."),+ (nil, "This is Bloomberg."), (2, "It's a multi trillion dollar industry."), (3, "Welcome to Bloomer this weekend."),+ (nil, "I'm David Brewer."), (nil, "I'm Lisa Mattay."), (nil, "I'm Christina Raffini."),+ (4, "We're tracking breaking news today from Wall Street to Washington."),+ ]+ let lines = rows.enumerated().map { i, r in+ TranscriptLine(id: "l\(i)", t: Double(i), speaker: "them", src: r.1, dst: nil, srcLang: "en", dstLang: "zh-CN", voice: r.0)+ }+ return Session(id: "s", title: "t", startedAt: Date(), endedAt: nil, lines: lines, hasAudio: false, notes: nil, renamed: nil)+ }++ @Test func aNameNeedsItsSpeakerNearTheEvidence() {+ let s = bloomberg+ #expect(SpeakerLabels.voiceNumbers(s.lines) == [0: 1, 1: 2])+ // Amos (voice 0, 说话人1) is thanked on L12, right after his own L10 and L11: kept.+ // "I'm Christina Raffini." (L21) is an advert, voice 1 last spoke on L15: dropped.+ let reply = #"{"speakers": [{"speaker": 1, "name": "Amos Hochstein", "evidence": "L12"}, {"speaker": 2, "name": "Christina Raffini", "evidence": "L21"}]}"#+ let r = SpeakerNameGuess.read(reply, s)+ #expect(r.found.keys.sorted() == [0] && r.found[0]?.name == "Amos Hochstein")+ #expect(r.found[0]?.evidence.hasPrefix("00:11 “Okay, Amos") == true)+ #expect(r.refuted == [1: "Christina Raffini"])+ // Said by the speaker themselves; "L12, L13" reads as L12; no evidence, or one out of range, is no name.+ #expect(SpeakerNameGuess.parse(#"{"speakers": [{"speaker": 2, "name": "Anchor", "evidence": "L12, L14"}]}"#, s)[1]?.name == "Anchor")+ #expect(SpeakerNameGuess.parse(#"{"speakers": [{"speaker": 2, "name": "Anchor"}]}"#, s).isEmpty)+ #expect(SpeakerNameGuess.parse(#"{"speakers": [{"speaker": 2, "name": "Anchor", "evidence": "L99"}]}"#, s).isEmpty)+ // Two lines away still counts; three doesn't.+ #expect(SpeakerNameGuess.parse(#"{"speakers": [{"speaker": 1, "name": "Amos", "evidence": "L13"}]}"#, s)[0] != nil)+ #expect(SpeakerNameGuess.parse(#"{"speakers": [{"speaker": 1, "name": "Amos", "evidence": "L14"}]}"#, s).isEmpty)+ #expect(SpeakerNameGuess.instruction.contains("misspells"))+ // A guess stored before the check is tested again from its quoted line.+ #expect(!SpeakerNameGuess.holds(VoiceGuess(name: "Christina Raffini", evidence: "00:20 “I'm Christina Raffini.”"), voice: 1, in: s))+ #expect(SpeakerNameGuess.holds(VoiceGuess(name: "Amos", evidence: "00:11 “Okay, Amos, thank you so much for your time this morning, Amos…”"), voice: 0, in: s))+ #expect(SpeakerNameGuess.holds(VoiceGuess(name: "Ann", evidence: "09:59 “Not in this meeting”"), voice: 1, in: s))+ }+@Test func guessesShowUntilTheUserSaysOtherwise() {var s = named(nil)s.voiceGuesses = ["9": VoiceGuess(name: "Emma", evidence: ""), "4": VoiceGuess(name: "George", evidence: "")]diff --git a/site/changelog.json b/site/changelog.jsonindex 1a1dd0c..2447e5b 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -6,6 +6,26 @@"summary": "打开同声传译时,系统麦克风自动换成虚拟麦克风,Chrome 里的会议网页不用再手动设置;关掉或退出时自动换回。","image": null,"items": [+ {+ "kind": "fixed",+ "title": "Ling 不再用别人说的话给说话人起名。",+ "text": "名字只在那句话是这个人说的、或就在这个人说话的前后两句时才算(比如他刚答完,主持人说“Okay, Amos, thank you”);广告里的“I'm Christina…”不会再落到主持人头上,以前这样猜出的名字会重新核对并去掉。知名人物的名字按新闻里的写法拼(Amos Hochstein,不是 Hockstein),纪要里也一样。"+ },+ {+ "kind": "fixed",+ "title": "被停顿切断的一句话会接回来,重新翻译。",+ "text": "以前一句话被短停顿切成两行,各自翻译,前半句只剩“在这个”。现在后半句在 1.5 秒内接上、同一个人说、前半句没说完时,两行合成一行,整句再译一次;字幕上也是整句。"+ },+ {+ "kind": "fixed",+ "title": "句首不再有零碎标点。",+ "text": "识别留下的“, , that”“in..........”“. , that is”会先清理:句首的标点去掉,一串点变成一个“…”,重复的逗号只留一个。"+ },+ {+ "kind": "fixed",+ "title": "只有标点的“句子”不再出现。",+ "text": "呼吸声或杂音被识别成一个“.”时,现在直接丢掉;以前会留在记录里,还被发给 Ling 翻译,回来一句“没有需要翻译的内容”。"+ },{"kind": "fixed","title": "一直没人说话的会议不再一直听下去。",