知了 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: imported recordings and videos, and re-transcribed meetings, now tell speakers apart too
wquguru3a97dab90430
diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swiftindex 6454d92..48a49cf 100644--- a/Sources/Cicada/AppModel.swift+++ b/Sources/Cicada/AppModel.swift@@ -1691,6 +1691,8 @@ final class AppModel: ObservableObject {private func importFinished(_ id: String) {guard let s = store.session(id) else { return }+ // The voices are known now: Ling's guess at who 说话人 1, 2… are, as at the end of a meeting.+ if settings.speakerVoices { speakerNamer.guess(id, force: true) }let notesToo = settings.importNotes && ling.hasKey && !s.lines.isEmptyif notesToo { notes.generate(for: id) }let content = UNMutableNotificationContent()diff --git a/Sources/Cicada/FileImport.swift b/Sources/Cicada/FileImport.swiftindex bf56a8b..da46526 100644--- a/Sources/Cicada/FileImport.swift+++ b/Sources/Cicada/FileImport.swift@@ -179,12 +179,16 @@ final class FileImporter: ObservableObject {phase = .transcribingvar n = 0var translations: [Task<Void, Never>] = []- let add = { (sentences: [(text: String, t: Double)], heard: String?, translation: String?) in+ // 说话人识别, as when listening: each line's stretch of the file gets a voiceprint.+ let voices = settings.speakerVoices ? ImportVoices(pcm: pcm, store: store, session: job.id) : nil+ defer { voices?.stop() }+ // `end`: when the recognized stretch ends, so its last line's sound ends there.+ let add = { (sentences: [(text: String, t: Double)], end: Double, heard: String?, translation: String?) inlet src = heard.flatMap { code in sourceLanguages.first { $0.code == code }?.code } ?? lang.codelet to = heard == nil ? target : self.settings.resolvedTarget(source: src)// The service's translation covers the whole stretch: kept when the stretch is one line.let given = sentences.count == 1 && to == heardTarget ? translation : nil- for sentence in sentences {+ for (k, sentence) in sentences.enumerated() {let text = HeardText.clean(sentence.text)guard text.contains(where: \.isLetter) else { continue }n += 1@@ -192,6 +196,7 @@ final class FileImporter: ObservableObject {src: text, dst: src == to ? text : given, srcLang: src, dstLang: to)self.store.append(line, to: job.id)if line.dst == nil { translations.append(self.translate(line, session: job.id)) }+ voices?.tag(line.id, from: line.t, to: k + 1 < sentences.count ? sentences[k + 1].t : end)}}if !Recognition.legacy, !Recognition.cloudOnly, #available(macOS 26, *) {@@ -206,13 +211,13 @@ final class FileImporter: ObservableObject {let pieces = result.text.runs.map { run in(String(result.text[run.range].characters), run.audioTimeRange.map { CMTimeGetSeconds($0.start) })}- add(Self.sentences(pieces, start: CMTimeGetSeconds(result.range.start)), nil, nil)+ add(Self.sentences(pieces, start: CMTimeGetSeconds(result.range.start)), CMTimeGetSeconds(result.range.end), nil, nil)}_ = analyzer} else {let hint = Recognition.cloudOnly ? named?.locale : lang.localetry await transcribeLegacy(pcm, locale: hint, session: job.id) { piece in- add(Self.sentences(Self.words(piece), start: piece.start), piece.language, piece.translation)+ add(Self.sentences(Self.words(piece), start: piece.start), piece.end, piece.language, piece.translation)}}guard !Task.isCancelled, store.session(job.id) != nil else { return }@@ -223,6 +228,7 @@ final class FileImporter: ObservableObject {heard = durationphase = .translatingfor t in translations { await t.value }+ await voices?.finish()store.finishImport(job.id)debugLog(String(format: "import: %@ done, %d lines from %.0f s of audio in %.0f s", job.id, n, duration, Date().timeIntervalSince(started)))onFinished?(job.id)@@ -419,3 +425,55 @@ final class FileImporter: ObservableObject {return Double(frames) / 16_000}}++/// 说话人识别 for an imported file: each line's stretch of the decoded audio goes through a tagger+/// of the file's own, so a meeting listened to meanwhile keeps its voices apart from the file's.+@MainActor+final class ImportVoices {+ private let tagger = SpeakerTagger()+ private let file: AVAudioFile?+ /// Off once the file is stopped: a voiceprint still queued then must not land on the lines of+ /// a 重新转写 that reuses the line ids.+ private var on = true++ init(pcm: URL, store: SessionStore, session id: String) {+ file = try? AVAudioFile(forReading: pcm)+ tagger.onVoice = { [weak self, weak store] line, voice in+ guard self?.on == true else { return }+ store?.setVoice(in: id, lineID: line, voice)+ }+ }++ func tag(_ lineID: String, from start: Double, to end: Double) {+ // The model looks at 20 s at most: no need to hold more of a long line in memory.+ guard let file, let samples = Self.read(file, from: start, to: min(end, start + Voiceprints.maxSeconds)) else { return }+ tagger.tag(lineID: lineID, samples: samples)+ }++ /// Returns once every line handed in so far has its voice, or is known to have none.+ func finish() async {+ await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in+ tagger.voice(of: []) { _ in c.resume() } // too short to embed: just a place in the queue+ }+ }++ func stop() { on = false }++ /// 16 kHz mono floats from `start` to `end` seconds of the file.+ nonisolated static func read(_ file: AVAudioFile, from start: Double, to end: Double) -> [Float]? {+ let rate = file.processingFormat.sampleRate+ let first = AVAudioFramePosition(max(0, start) * rate)+ let last = min(file.length, AVAudioFramePosition(max(0, end) * rate))+ guard last > first, let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(last - first)) else { return nil }+ file.framePosition = first+ // A read after a seek can stop short of what was asked (a packet boundary): read on to the end.+ var out: [Float] = []+ out.reserveCapacity(Int(last - first))+ while file.framePosition < last {+ guard (try? file.read(into: buf, frameCount: AVAudioFrameCount(last - file.framePosition))) != nil,+ buf.frameLength > 0, let d = buf.floatChannelData else { break }+ out.append(contentsOf: UnsafeBufferPointer(start: d[0], count: Int(buf.frameLength)))+ }+ return out.isEmpty ? nil : out+ }+}diff --git a/Sources/Cicada/SessionStore.swift b/Sources/Cicada/SessionStore.swiftindex 8fe15ac..f6f7db4 100644--- a/Sources/Cicada/SessionStore.swift+++ b/Sources/Cicada/SessionStore.swift@@ -241,7 +241,13 @@ final class SessionStore: ObservableObject {}func setVoice(lineID: String, _ voice: Int) {- guard let id = liveID, let i = index(id),+ guard let id = liveID else { return }+ setVoice(in: id, lineID: lineID, voice)+ }++ /// An imported file's line got its voice (`ImportVoices`).+ func setVoice(in id: String, lineID: String, _ voice: Int) {+ guard let i = index(id),let j = sessions[i].lines.firstIndex(where: { $0.id == lineID }) else { return }sessions[i].lines[j].voice = voicescheduleSave(id)@@ -348,6 +354,9 @@ final class SessionStore: ObservableObject {guard let i = index(id) else { return }sessions[i].lines = []sessions[i].notes = nil+ // Voices are numbered afresh: names given to the old ones would land on other people.+ sessions[i].voiceNames = nil+ sessions[i].voiceGuesses = nilsessions[i].importing = truesaveNow(id)}@@ -460,6 +469,10 @@ enum TranscriptExport {static func speakerNumbers(_ s: Session) -> [String: Int] { voices ? SpeakerLabels.numbers(s.lines) : [:] }+ /// Whether lines say who spoke. An imported file has no "other side" to call 对方: its lines+ /// are named only once its voices are told apart.+ static func saysWho(_ s: Session, _ numbers: [String: Int]) -> Bool { s.sourceFile == nil || !numbers.isEmpty }+static func header(_ s: Session) -> String {let mins = Int(s.duration / 60)return "\(dateText(s.startedAt, "yMMMdHHmm")) · " + (mins < 1 ? L("不到 1 分钟") : L("\(mins) 分钟"))@@ -495,8 +508,7 @@ enum TranscriptExport {if !notes.isEmpty { out += notes + "## \(L("文字记录"))\n\n" }let numbers = speakerNumbers(s), names = SpeakerLabels.names(s)for l in s.lines {- // An imported file has no "other side" to name.- let who = s.sourceFile == nil ? " \(speakerName(l, numbers, names))" : ""+ let who = saysWho(s, numbers) ? " \(speakerName(l, numbers, names))" : ""out += "**[\(clock(l.t))]\(who)** \n\(l.shown)\n"if let d = l.dst, d != l.shown { out += "> \(d)\n" }out += "\n"@@ -562,7 +574,7 @@ enum TranscriptExport {}let numbers = speakerNumbers(s), names = SpeakerLabels.names(s)for l in s.lines {- add("[\(clock(l.t))]" + (s.sourceFile == nil ? " \(speakerName(l, numbers, names))" : ""), size: 9, weight: .semibold, color: .darkGray, after: 2)+ add("[\(clock(l.t))]" + (saysWho(s, numbers) ? " \(speakerName(l, numbers, names))" : ""), size: 9, weight: .semibold, color: .darkGray, after: 2)add(l.shown, size: 11, after: 2)if let d = l.dst, d != l.shown { add(d, size: 11, color: NSColor(calibratedWhite: 0.3, alpha: 1), after: 10) }}diff --git a/Tests/CicadaTests/ImportTests.swift b/Tests/CicadaTests/ImportTests.swiftindex b8b0cc3..c4523f1 100644--- a/Tests/CicadaTests/ImportTests.swift+++ b/Tests/CicadaTests/ImportTests.swift@@ -84,6 +84,39 @@ import Testing#expect(abs((s.last?.t ?? 0) - 14.4) < 0.01)}+ /// 说话人识别 on an import: a line's voiceprint is cut from the decoded file by its times,+ /// clipped to the file's end.+ @Test func lineSoundIsCutFromTheFile() throws {+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-voices-\(UUID().uuidString).caf")+ defer { try? FileManager.default.removeItem(at: url) }+ let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false)!+ do {+ let file = try AVAudioFile(forWriting: url, settings: format.settings, commonFormat: .pcmFormatFloat32, interleaved: false)+ let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 48_000)!+ buf.frameLength = 48_000+ for i in 0..<48_000 { buf.floatChannelData![0][i] = Float(i / 16_000) } // second n holds n+ try file.write(from: buf)+ }+ let file = try AVAudioFile(forReading: url)+ let middle = try #require(ImportVoices.read(file, from: 1, to: 2))+ #expect(middle.count == 16_000, "\(middle.count)")+ #expect(middle.first == 1 && middle.last == 1, "\(middle.prefix(3)) … \(middle.suffix(3))")+ #expect(ImportVoices.read(file, from: 2.5, to: 9)?.count == 8_000)+ #expect(ImportVoices.read(file, from: 4, to: 5) == nil)+ }++ /// 重新转写 numbers the voices afresh: names given to the old ones go.+ @Test @MainActor func retranscribingForgetsVoiceNames() {+ let store = SessionStore(root: FileManager.default.temporaryDirectory.appendingPathComponent("cicada-retry-\(UUID().uuidString)"))+ let s = store.beginImport(file: URL(fileURLWithPath: "/tmp/a.m4a"), recordedAt: Date(), duration: 60)+ store.append(TranscriptLine(id: "f1", t: 0, speaker: "them", src: "Hello there everyone", dst: nil, srcLang: "en", dstLang: "zh"), to: s.id)+ store.setVoice(in: s.id, lineID: "f1", 0)+ #expect(store.session(s.id)?.lines.first?.voice == 0)+ store.setVoiceName(s.id, voice: 0, "Daniel")+ store.restartImport(s.id)+ #expect(store.session(s.id)?.voiceNames == nil && store.session(s.id)?.lines.isEmpty == true)+ }+@Test func missingTimesFallBack() {let s = FileImporter.sentences([("Hello there, everyone.", nil), (" How are you?", nil)], start: 7)#expect(s.map(\.t) == [7, 7])diff --git a/Tests/CicadaTests/SpeakerTests.swift b/Tests/CicadaTests/SpeakerTests.swiftindex 19f64c2..dc0ecf1 100644--- a/Tests/CicadaTests/SpeakerTests.swift+++ b/Tests/CicadaTests/SpeakerTests.swift@@ -76,6 +76,16 @@ import Testing#expect(TranscriptExport.speakerName(line(4, nil, me: true), ["l4": 1]) == L("你 · 同传"))}+ /// An imported file names nobody ("对方" means nothing there) until its voices are told apart.+ @Test func importedFilesNameSpeakersOnceTold() {+ var s = Session(id: "i", title: "t", startedAt: Date(), endedAt: nil, lines: [line(0, 1)], hasAudio: false)+ s.sourceFile = "call.m4a"+ #expect(!TranscriptExport.saysWho(s, [:]))+ #expect(TranscriptExport.saysWho(s, ["l0": 1]))+ s.sourceFile = nil+ #expect(TranscriptExport.saysWho(s, [:]))+ }+private func named(_ voiceNames: [String: String]?) -> Session {let lines = (0..<5).map { line($0, 9) } + (5..<10).map { line($0, 4) } + [line(10, nil, me: true)]return Session(id: "s", title: "t", startedAt: Date(), endedAt: nil, lines: lines, hasAudio: false,diff --git a/site/changelog.json b/site/changelog.jsonindex eda7c46..c2ab101 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -131,6 +131,15 @@],"title": "打开同声传译后,Teams 等其他应用又能用内置麦克风了。","text": "以前打开同声传译,知了会提前备好回声消除,哪怕没按发言键,其他应用从内置麦克风也几乎收不到声音,退出知了才恢复。现在只在按住发言键、到这句译文说完为止才占用;代价是按下后要等 1 到 2 秒才开始收音。"+ },+ {+ "kind": "fixed",+ "platforms": [+ "mac",+ "android"+ ],+ "title": "导入的录音和视频、重新转写的会议,也会区分说话人。",+ "text": "以前只有现场听的会议会按声音标出说话人 1、2,导入的文件看不出是谁说的。现在导入和重新转写也会认声音,同样可以改名、合并,导出的文字记录和纪要里也能分清是谁说的。"}]},