知了 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
feat: the meeting transcript is re-heard on the Mac and comes out with far fewer misheard words
wquguru44dbce6df5d4
diff --git a/README.en.md b/README.en.mdindex 6a7d396..a7b9ab6 100644--- a/README.en.md+++ b/README.en.md@@ -52,7 +52,7 @@ While the meeting runs, the notes window organizes a summary, topics and key poi### Live subtitles and language detection-Cicada detects the spoken language on device within seconds and translates into your system language, and pressing `⌃⌥S` switches between the notes window, a compact subtitle bar, and hidden. The subtitle bar appears only when someone speaks and turns see-through under your pointer so you can click right through it.+Cicada detects the spoken language on device within seconds and translates into your system language, and pressing `⌃⌥S` switches between the notes window, a compact subtitle bar, and hidden. The subtitle bar appears only when someone speaks and turns see-through under your pointer so you can click right through it. On macOS 26 with Apple silicon, the Transcript also hears the meeting a second time on the Mac and refines each line 15–30 seconds after it is said: fewer misheard words and none lost where the subtitles cut a line, while subtitles stay as fast.### Meetings in the roomdiff --git a/README.ja.md b/README.ja.mdindex 074e3f6..e552443 100644--- a/README.ja.md+++ b/README.ja.md@@ -54,7 +54,7 @@ Cicada は、Zoom、Teams、Feishu の通話から、X スペース、Discord### リアルタイムの字幕と言語の検出-Cicada は、話されている言語を数秒以内にデバイス上で検出してシステムの言語に翻訳し、`⌃⌥S` を押すと、メモのウィンドウ、コンパクトな字幕バー、非表示を切り替えられます。字幕バーは誰かが話しているときにだけ表示され、ポインターを重ねると透けるので、その下をそのままクリックできます。+Cicada は、話されている言語を数秒以内にデバイス上で検出してシステムの言語に翻訳し、`⌃⌥S` を押すと、メモのウィンドウ、コンパクトな字幕バー、非表示を切り替えられます。字幕バーは誰かが話しているときにだけ表示され、ポインターを重ねると透けるので、その下をそのままクリックできます。Apple シリコン搭載の macOS 26 では、文字起こしがデバイス上で会議をもう一度聞き直し、各行を話してから 15〜30 秒後に補正します。誤認識が減り、字幕の区切りで言葉が抜けることもなく、字幕の速さはそのままです。### 会議室での会議diff --git a/README.ko.md b/README.ko.mdindex b00c3d5..2836685 100644--- a/README.ko.md+++ b/README.ko.md@@ -52,7 +52,7 @@ Zoom, Teams, Feishu 회의부터 X Spaces, Discord 스테이지, YouTube 라이### 실시간 자막 및 언어 감지-상대방이 말하기 시작하면 몇 초 안에 기기에서 언어를 감지해 시스템 언어로 번역합니다. `⌃⌥S`를 누르면 회의록 창, 자막 바, 숨김 상태를 오갈 수 있습니다. 자막 바는 누군가 말할 때만 나타나며, 마우스 포인터를 올리면 투명해져 아래에 있는 버튼을 그대로 클릭할 수 있습니다.+상대방이 말하기 시작하면 몇 초 안에 기기에서 언어를 감지해 시스템 언어로 번역합니다. `⌃⌥S`를 누르면 회의록 창, 자막 바, 숨김 상태를 오갈 수 있습니다. 자막 바는 누군가 말할 때만 나타나며, 마우스 포인터를 올리면 투명해져 아래에 있는 버튼을 그대로 클릭할 수 있습니다. Apple Silicon 탑재 macOS 26에서는 대화 기록이 기기에서 회의를 한 번 더 듣고, 각 줄을 말한 뒤 15~30초 후에 보정합니다. 잘못 들은 단어가 줄고 자막이 끊기는 곳에서 단어가 빠지지 않으며, 자막 속도는 그대로입니다.### 오프라인 회의diff --git a/README.md b/README.mdindex b79334e..4f32d09 100644--- a/README.md+++ b/README.md@@ -50,7 +50,7 @@### 实时字幕与语言识别-对方开口几秒钟就能在本地自动认出语言并翻成你的系统语言,按 `⌃⌥S` 可以在纪要窗口、字幕条和不显示之间切换。字幕条只在有人说话时出现,鼠标划过时自动变透明,不会挡住底下的按钮。+对方开口几秒钟就能在本地自动认出语言并翻成你的系统语言,按 `⌃⌥S` 可以在纪要窗口、字幕条和不显示之间切换。字幕条只在有人说话时出现,鼠标划过时自动变透明,不会挡住底下的按钮。在 Apple 芯片的 macOS 26 上,文字记录还会在本机把会议再听一遍,每句话说完 15 到 30 秒后校准好:错字更少,字幕断句的地方也不再丢字,字幕本身照样快。### 线下会议diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.stringsindex ffd1050..a2d0542 100644--- a/Resources/en.lproj/Localizable.strings+++ b/Resources/en.lproj/Localizable.strings@@ -472,8 +472,10 @@"依据较少,仅供参考" = "Little evidence; for reference only";"说话的内容会出现在这里" = "What's said will appear here";"%lld 句新内容" = "%lld new lines";+"校准中" = "Refining";"这段是谁说的" = "Who said this?";"这句是谁说的" = "Who said this?";+"文字稍后会再校准一次,字幕不受影响" = "Text will be refined in a moment. Subtitles aren’t affected.";"正在说" = "Speaking";"从这里开始听" = "Listening began";"原话" = "Original";diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.stringsindex 555e910..f3d14ef 100644--- a/Resources/ja.lproj/Localizable.strings+++ b/Resources/ja.lproj/Localizable.strings@@ -472,8 +472,10 @@"依据较少,仅供参考" = "根拠が少ないため参考情報です";"说话的内容会出现在这里" = "発言内容がここに表示されます";"%lld 句新内容" = "新着 %lld文";+"校准中" = "補正中";"这段是谁说的" = "この段落は誰の発言?";"这句是谁说的" = "この発言は誰?";+"文字稍后会再校准一次,字幕不受影响" = "文字はまもなく再補正されます(字幕には影響しません)";"正在说" = "発話中";"从这里开始听" = "ここから聞き始め";"原话" = "原文";diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.stringsindex 67bf59c..de642d2 100644--- a/Resources/ko.lproj/Localizable.strings+++ b/Resources/ko.lproj/Localizable.strings@@ -472,8 +472,10 @@"依据较少,仅供参考" = "근거가 적어 참고용입니다";"说话的内容会出现在这里" = "말한 내용이 여기에 표시됩니다";"%lld 句新内容" = "새 내용 %lld문장";+"校准中" = "보정 중";"这段是谁说的" = "이 단락은 누가 말했나요?";"这句是谁说的" = "이 문장은 누가 말했나요?";+"文字稍后会再校准一次,字幕不受影响" = "잠시 후 더 정확하게 보정됩니다. 자막에는 영향을 주지 않습니다.";"正在说" = "말하는 중";"从这里开始听" = "여기서부터 듣기 시작";"原话" = "원문";diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.stringsindex a497b46..82ec3e1 100644--- a/Resources/zh-Hans.lproj/Localizable.strings+++ b/Resources/zh-Hans.lproj/Localizable.strings@@ -472,8 +472,10 @@"依据较少,仅供参考" = "依据较少,仅供参考";"说话的内容会出现在这里" = "说话的内容会出现在这里";"%lld 句新内容" = "%lld 句新内容";+"校准中" = "校准中";"这段是谁说的" = "这段是谁说的";"这句是谁说的" = "这句是谁说的";+"文字稍后会再校准一次,字幕不受影响" = "文字稍后会再校准一次,字幕不受影响";"正在说" = "正在说";"从这里开始听" = "从这里开始听";"原话" = "原话";diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swiftindex 4b3374a..5cd4b37 100644--- a/Sources/Cicada/AppModel.swift+++ b/Sources/Cicada/AppModel.swift@@ -124,6 +124,8 @@ final class AppModel: ObservableObject {var listenReady: Bool { systemAudioOK && speechOK }@Published var micStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .audio)@Published var liveSource = ""+ /// Lines whose words the record's own recognizer hasn't settled yet (the notes window says 校准中).+ @Published private(set) var settling: Set<String> = []@Published var liveTranslation = ""@Published var onboardingStep = 1/// Step 3 is showing what skipping the key leaves out (debug: `onboarding:3,skip`).@@ -174,6 +176,15 @@ final class AppModel: ObservableObject {/// 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?)?+ /// Lines the record's own recognizer is still settling (`ListenEngine.onRefined`): each line's+ /// meeting and its segments in order (several after a join), each with the live recognizer's text.+ private var refining: [String: (session: String, segs: [(id: Int, text: String, settled: String?)])] = [:]+ private var refiningOrder: [String] = []+ private var lineOfSegment: [Int: String] = [:]+ /// Settled before its line was recorded (a line waiting for its voice, the language or an echo check).+ private var settledEarly: [Int: String] = [:]+ /// Lines with their record text: the live recognizer's translations no longer replace theirs.+ private var refinedLines: Set<String> = []init() {// A meeting or speaking holds the update notification until it ends (see stop()).@@ -219,6 +230,8 @@ final class AppModel: ObservableObject {}listen.onTranslated = { [weak self] segID, text in self?.translated(segID, text) }roomListen.onTranslated = { [weak self] segID, text in self?.translated(segID, text) }+ listen.onRefined = { [weak self] segID, text in self?.refined(segID, text) }+ roomListen.onRefined = { [weak self] segID, text in self?.refined(segID, text) }diagnostics.enabled = { [weak self] in self?.settings.diagnostics ?? false }diagnostics.folder = { [weak self] in@@ -651,6 +664,12 @@ final class AppModel: ObservableObject {lineForSegment = [:]lastHeard = nilheldJoin = nil+ refining = [:]+ settling = []+ refiningOrder = []+ lineOfSegment = [:]+ settledEarly = [:]+ refinedLines = []recentOnline = []heldRoom = []liveMain = ("", "", .distantPast)@@ -1390,10 +1409,57 @@ final class AppModel: ObservableObject {private func translated(_ segID: Int, _ text: String) {if heldJoin?.seg.id == segID { heldJoin?.translation = text }if let i = heldRoom.firstIndex(where: { $0.id == segID }) { heldRoom[i].seg.translation = text }- guard let line = lineForSegment[segID] else { return }+ guard let line = lineForSegment[segID], !refinedLines.contains(line) else { return }store.setTranslation(lineID: line, text)}+ /// A line starts settling with its first segment; a joined one adds its own.+ private func trackRefining(_ seg: Segment, line: String) {+ guard seg.refining, let session = store.liveID else { return }+ lineOfSegment[seg.id] = line+ if refining[line] == nil {+ refiningOrder.append(line)+ // Old lines no longer join or settle: keep the last few hundred.+ if refiningOrder.count > 300 {+ let old = refiningOrder.removeFirst()+ refining[old] = nil+ settling.remove(old)+ }+ }+ refining[line, default: (session, [])].segs.append((seg.id, seg.text, nil))+ settling.insert(line)+ if let early = settledEarly.removeValue(forKey: seg.id) { refined(seg.id, early) }+ }++ /// The record's recognizer settled segment `segID`. Once every segment of its line has, the line+ /// takes the record's words and is translated again; a segment it heard nothing in keeps its own.+ private func refined(_ segID: Int, _ text: String) {+ guard let line = lineOfSegment[segID], var entry = refining[line],+ let k = entry.segs.firstIndex(where: { $0.id == segID }) else {+ settledEarly[segID] = text+ if settledEarly.count > 60, let oldest = settledEarly.keys.min() { settledEarly[oldest] = nil }+ return+ }+ let heard = HeardText.clean(text)+ entry.segs[k].settled = heard.contains(where: \.isLetter) ? heard : entry.segs[k].text+ refining[line] = entry+ guard entry.segs.allSatisfy({ $0.settled != nil }) else { return }+ settling.remove(line)+ let parts = entry.segs.map { $0.settled! }+ let whole = parts.dropFirst().reduce(parts[0]) { HeardText.join($0, $1) }+ guard let rec = store.session(entry.session)?.lines.first(where: { $0.id == line }), whole != rec.src else { return }+ store.setSource(in: entry.session, lineID: line, whole)+ refinedLines.insert(line)+ contentLog("REFINE \(line): \(rec.src) => \(whole)")+ guard rec.dst != nil else { return }+ Task { [weak self] in+ guard let self, let out = await self.listen.translate(whole, source: rec.srcLang, target: rec.dstLang) else { return }+ // Joined again meanwhile: that line's own settling translates it.+ guard self.store.session(entry.session)?.lines.first(where: { $0.id == line })?.src == whole else { return }+ self.store.setTranslation(in: entry.session, lineID: line, out)+ }+ }+/// The line in progress: the engine that changed it last and still has words, so the room and the/// Mac take turns on the one caption.private func showLive(spoke src: String) {@@ -1460,6 +1526,7 @@ final class AppModel: ObservableObject {joined.cut = seg.cutlastHeard = (joined, prev.line)store.setSource(lineID: prev.line, text)+ trackRefining(seg, line: prev.line)listen.join(seg.id, into: prev.seg.id, text: text)contentLog("JOIN \(prev.line) += \(seg.text)")heardWords()@@ -1474,6 +1541,7 @@ final class AppModel: ObservableObject {// 会议室 alone too: a meeting switched to it from 电脑和会议室// would otherwise mark its later room lines 线上.via: seg.id >= ListenEngine.roomIDs || settings.listensToRoom ? "room" : nil))+ trackRefining(seg, line: id)var kept = segkept.voiceSamples = nillastHeard = (kept, id)@@ -1610,6 +1678,11 @@ final class AppModel: ObservableObject {listen.simulatedModels = arg == "off" ? nil : Set(p.first ?? [])listen.simulatedSystemLanguages = arg == "off" || p.count < 2 ? nil : p[1]Task { await listen.refreshInstalledLocales() }+ case "recordTrack":+ // recordTrack:off compares the meeting record without its own recognizer (next start).+ Recognition.recordTrackOff = arg == "off"+ debugLog("record track: \(Recognition.recordTrack ? "on" : "off")")+ case "recordState": debugLog("record track: \(Recognition.recordTrack ? "on" : "off") settling=\(settling.count) tracked=\(refining.count)")case "recognizer":// recognizer:legacy runs the macOS 14/15 recognizer (SFSpeechRecognizer) on 26; recognizer:cloud// hears as an Intel Mac does; recognizer:auto ends either. Takes effect from the next start.diff --git a/Sources/Cicada/ListenEngine.swift b/Sources/Cicada/ListenEngine.swiftindex abac400..3e1f3f3 100644--- a/Sources/Cicada/ListenEngine.swift+++ b/Sources/Cicada/ListenEngine.swift@@ -14,6 +14,8 @@ struct Segment {/// and whether Cicada ended it at a pause: what deciding a join needs (`HeardText.continues`).var start = 0.0, end = 0.0, clock = 0var cut = false+ /// The record's own recognizer heard it too and will settle its words (`onRefined`).+ var refining = false}/// System audio → language detection → on-device transcription → translation.@@ -34,6 +36,9 @@ final class ListenEngine {/// A finished sentence; `secondsAgo` ≈ how long ago it started.var onFinal: ((Segment, _ secondsAgo: Double) -> Void)?var onTranslated: ((_ segmentID: Int, _ translation: String) -> Void)?+ /// The record's own recognizer settled segment `id` (`RecordRefiner`): its text for the meeting+ /// record, "" when it heard nothing there.+ var onRefined: ((_ segmentID: Int, _ text: String) -> Void)?/// Diagnostics: how long a sentence took from its last new words to its translation on screen.var onTiming: ((SentenceTiming) -> Void)?/// The recognizer heard words (a draft or a line), whether or not they are shown.@@ -130,6 +135,11 @@ final class ListenEngine {private var startedAt = Date()private var recognizer: RecognitionStream?private var resultsTask: Task<Void, Never>?+ /// The record's recognizer for the current transcriber (`Recognition.recordTrack`). Its lines+ /// keep settling after `stop()`, so it has a generation of its own.+ private var refiner: RecordRefiner?+ private var refinerGen = 0+ private var recordTask: Task<Void, Never>?/// The room engine's clocks and segment ids start far above the main one's, so lines from the two/// never look like one recognizer's (joins, translations).private var generation: Int@@ -395,7 +405,13 @@ final class ListenEngine {router.reset()resultsTask?.cancel()resultsTask = nil- if let recognizer {+ if let tee = recognizer as? TeeStream {+ // The record's recognizer hears out what it has, and its last lines settle.+ Task {+ await tee.live.cancel()+ await tee.record.finish()+ }+ } else if let recognizer {Task { await recognizer.cancel() }}recognizer = nil@@ -700,9 +716,21 @@ final class ListenEngine {await stream.cancel()return}- router.attach(stream, replaySeconds: replaySeconds)+ var listening: RecognitionStream = stream+ if let record = try? await Recognition.startRecord(lang.locale, format: stream.format) {+ guard isRunning, gen == generation else {+ await stream.cancel()+ await record.cancel()+ return+ }+ listening = TeeStream(live: stream, record: record)+ startRefining(record)+ } else {+ refiner = nil+ }+ router.attach(listening, replaySeconds: replaySeconds)updateHold()- self.recognizer = stream+ self.recognizer = listeningresultsTask = Task { [weak self] indo {for try await piece in stream.results {@@ -773,6 +801,8 @@ final class ListenEngine {seg.clock = genseg.cut = cutAskedcutAsked = false+ seg.refining = refiner != nil+ if refiner != nil { settled(refiner!.emitted(id: seg.id, start: seg.start, end: seg.end, text: seg.text)) }if settings.speakerVoices {seg.voiceSamples = router.voiceSamples(from: result.start, to: result.end)}@@ -1376,6 +1406,33 @@ final class ListenEngine {renderSubtitles()}+ // MARK: The record's recognizer++ private func startRefining(_ record: RecordHearing) {+ recordTask?.cancel()+ refinerGen += 1+ let gen = refinerGen+ refiner = RecordRefiner()+ recordTask = Task { [weak self] in+ do {+ for try await sentence in record.sentences {+ guard let self, gen == self.refinerGen, self.refiner != nil else { return }+ contentLog("RECORD \(sentence.runs.map(\.text).joined())")+ self.settled(self.refiner!.heard(sentence.runs, through: sentence.through))+ }+ } catch {+ debugLog("record track: \(error)")+ }+ guard let self, gen == self.refinerGen, self.refiner != nil else { return }+ self.settled(self.refiner!.finish())+ self.refiner = nil+ }+ }++ private func settled(_ lines: [(id: Int, text: String)]) {+ for l in lines { onRefined?(l.id, l.text) }+ }+/// 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 fordiff --git a/Sources/Cicada/NotesViews.swift b/Sources/Cicada/NotesViews.swiftindex eaf7739..d094f51 100644--- a/Sources/Cicada/NotesViews.swift+++ b/Sources/Cicada/NotesViews.swift@@ -532,6 +532,8 @@ struct TranscriptListView<Partial: View>: View, Equatable {var marked: Int?/// 电脑和会议室 heard both: each paragraph says 现场 or 线上 (RecordList.heardBoth).var places = false+ /// Lines the meeting record's own recognizer is still settling: their words may change.+ var settling: Set<String> = []var onAssign: ((Set<String>, Int) -> Void)?@ViewBuilder var partial: Partial@@ -545,7 +547,7 @@ struct TranscriptListView<Partial: View>: View, Equatable {a.lines == b.lines && a.topics == b.topics && a.terms == b.terms && a.currentMatch == b.currentMatch&& a.bilingual == b.bilingual && a.live == b.live && a.partialShown == b.partialShown&& a.jumpTo == b.jumpTo && a.speakers == b.speakers && a.startedAt == b.startedAt && a.voices == b.voices && a.marked == b.marked- && a.identifying == b.identifying && a.places == b.places+ && a.identifying == b.identifying && a.places == b.places && a.settling == b.settling}private var searching: Bool { !terms.isEmpty }@@ -774,6 +776,11 @@ struct TranscriptListView<Partial: View>: View, Equatable {else if let n = speakers[l.id] { SpeakerTag(number: n) }else if !speakers.isEmpty { UnknownSpeakerTag() }if places, label, l.speaker != "me" { PlaceTag(line: l) }+ if live, ls.contains(where: { settling.contains($0.id) }) {+ Spacer(minLength: 4)+ Text("校准中").font(.system(size: 11)).foregroundStyle(Palette.tertiary)+ .help(L("文字稍后会再校准一次,字幕不受影响"))+ }}Text(highlighted(src, current: isMatch)).font(.system(size: 14)).lineSpacing(2).textSelection(.enabled)if bilingual, !dst.isEmpty {diff --git a/Sources/Cicada/NotesWindow.swift b/Sources/Cicada/NotesWindow.swiftindex a4e2cc5..8d07c79 100644--- a/Sources/Cicada/NotesWindow.swift+++ b/Sources/Cicada/NotesWindow.swift@@ -903,7 +903,7 @@ struct NotesWindowView: View {jumpTo: jumpTo, speakers: speakers, startedAt: store.liveStart,identifying: model.identifyingLanguage,voices: speakers.isEmpty ? [:] : SpeakerLabels.voiceNumbers(lines), marked: editingVoice,- places: RecordList.heardBoth(lines),+ places: RecordList.heardBoth(lines), settling: model.settling,onAssign: { ids, voice in if let s = session { model.assignLines(session: s.id, ids, to: voice) } }) {LivePartialRow(model: model, startedAt: store.liveStart)}diff --git a/Sources/Cicada/Recognition.swift b/Sources/Cicada/Recognition.swiftindex 7c63c76..e7f71ad 100644--- a/Sources/Cicada/Recognition.swift+++ b/Sources/Cicada/Recognition.swift@@ -78,6 +78,29 @@ enum Recognition {var translation: String? = nil}+ /// A few characters of a finished sentence and when they were said, from the meeting record's+ /// own recognizer (`RecordHearing`), so its text can be laid over the lines already recorded.+ struct Run: Sendable, Equatable {+ var text: String+ var start: Double+ var end: Double+ }++ /// Dev builds compare the record with and without its own recognizer: `lsctl recordTrack:off`.+ nonisolated(unsafe) static var recordTrackOff = DevBuild.isDev && ProcessInfo.processInfo.environment["CICADA_RECORD_TRACK"] == "off"++ /// The meeting record gets a second recognizer that is never hurried: no `.fastResults` and no+ /// lines cut short for the subtitles. Both cost Chinese about a third more wrong characters+ /// (meeting audio: 20% offline, 25–30% live). macOS 26's `SpeechTranscriber` only.+ static var recordTrack: Bool { host == nil && !cloudOnly && !legacy && !dictationModel && !recordTrackOff }++ /// The record's recognizer for `locale`, taking the same audio as the live one (`format`). Nil+ /// where there is none (`recordTrack`).+ static func startRecord(_ locale: String, format: AVAudioFormat) async throws -> RecordHearing? {+ guard recordTrack, #available(macOS 26, *) else { return nil }+ return try await RecordTrack.start(locale, format: format)+ }+enum ModelStatus { case installed, downloadable, unsupported }static var isAvailable: Bool {@@ -784,3 +807,115 @@ final class DeferredStream: RecognitionStream, @unchecked Sendable {await opening?.value?.cancel()}}++// MARK: - The meeting record's recognizer++/// Finished sentences only, each as runs with their times (`Recognition.Run`) and the end of the+/// audio it covers.+protocol RecordHearing: AnyObject, Sendable {+ var sentences: AsyncThrowingStream<(runs: [Recognition.Run], through: Double), Error> { get }+ func append(_ buffer: AVAudioPCMBuffer)+ /// No more audio: returns once every sentence has come back.+ func finish() async+ func cancel() async+}++@available(macOS 26, *)+final class RecordTrack: RecordHearing, @unchecked Sendable {+ let sentences: AsyncThrowingStream<(runs: [Recognition.Run], through: Double), Error>+ private let analyzer: SpeechAnalyzer+ private let input: AsyncStream<AnalyzerInput>.Continuation+ private let reader: Task<Void, Never>++ static func start(_ locale: String, format: AVAudioFormat) async throws -> RecordTrack {+ let t = SpeechTranscriber(locale: Locale(identifier: locale), transcriptionOptions: [],+ reportingOptions: [], attributeOptions: [.audioTimeRange])+ let analyzer = SpeechAnalyzer(modules: [t])+ try await analyzer.prepareToAnalyze(in: format)+ let (stream, input) = AsyncStream.makeStream(of: AnalyzerInput.self, bufferingPolicy: .unbounded)+ let me = RecordTrack(t, analyzer: analyzer, input: input)+ try await analyzer.start(inputSequence: stream)+ return me+ }++ private init(_ t: SpeechTranscriber, analyzer: SpeechAnalyzer, input: AsyncStream<AnalyzerInput>.Continuation) {+ self.analyzer = analyzer+ self.input = input+ let (sentences, out) = AsyncThrowingStream.makeStream(of: (runs: [Recognition.Run], through: Double).self)+ self.sentences = sentences+ reader = Task {+ do {+ for try await r in t.results where r.isFinal {+ let runs = Self.runs(r.text, r.range)+ if !runs.isEmpty { out.yield((runs, CMTimeGetSeconds(r.range.end))) }+ }+ out.finish()+ } catch {+ out.finish(throwing: error)+ }+ }+ }++ /// Punctuation comes without a time: it stays with the run before it.+ static func runs(_ text: AttributedString, _ range: CMTimeRange) -> [Recognition.Run] {+ var out: [Recognition.Run] = []+ for run in text.runs {+ let piece = String(text[run.range].characters)+ if let r = run.audioTimeRange {+ out.append(.init(text: piece, start: CMTimeGetSeconds(r.start), end: CMTimeGetSeconds(r.end)))+ } else if !out.isEmpty {+ out[out.count - 1].text += piece+ } else {+ let t = CMTimeGetSeconds(range.start)+ out.append(.init(text: piece, start: t, end: t))+ }+ }+ return out.filter { $0.start.isFinite && $0.end.isFinite }+ }++ func append(_ buffer: AVAudioPCMBuffer) { input.yield(AnalyzerInput(buffer: buffer)) }++ func finish() async {+ input.finish()+ do { try await analyzer.finalizeAndFinishThroughEndOfInput() } catch { debugLog("record track finish: \(error)") }+ await reader.value+ }++ func cancel() async {+ input.finish()+ await analyzer.cancelAndFinishNow()+ }+}++/// The live recognizer and the record's, fed the same audio from the same moment so their clocks+/// agree. Only the live one is cut short for the subtitles.+final class TeeStream: RecognitionStream, @unchecked Sendable {+ let live: RecognitionStream+ let record: RecordHearing+ var format: AVAudioFormat { live.format }+ var results: AsyncThrowingStream<Recognition.Piece, Error> { live.results }++ init(live: RecognitionStream, record: RecordHearing) {+ self.live = live+ self.record = record+ }++ func append(_ buffer: AVAudioPCMBuffer) {+ live.append(buffer)+ record.append(buffer)+ }++ func finalize(through seconds: Double) async throws { try await live.finalize(through: seconds) }++ func finish() async {+ async let a: Void = live.finish()+ async let b: Void = record.finish()+ _ = await (a, b)+ }++ func cancel() async {+ async let a: Void = live.cancel()+ async let b: Void = record.cancel()+ _ = await (a, b)+ }+}diff --git a/Sources/Cicada/RecordRefiner.swift b/Sources/Cicada/RecordRefiner.swiftnew file mode 100644index 0000000..fd7e420--- /dev/null+++ b/Sources/Cicada/RecordRefiner.swift@@ -0,0 +1,163 @@+import Foundation+import NaturalLanguage++/// Lays the record recognizer's sentences (`RecordHearing`) over the lines the live recognizer+/// already gave: each line keeps its id, speaker and timestamp and only its words change.+///+/// Time says when a line is covered; the text says where it ends. The live recognizer's line times+/// and the record recognizer's word times disagree by up to a second, so splitting by time moved+/// words between lines ("通 / 知"). The two texts mostly agree, so the record's text is aligned with+/// the lines' (edit distance) and cut where each line's text ends. A word the live recognizer split+/// at a cut goes whole to one side, and words it lost go to the line they were said in.+struct RecordRefiner {+ struct Line {+ let id: Int+ let start: Double+ let end: Double+ let text: String+ }++ /// Lines not settled yet, in order.+ private(set) var lines: [Line] = []+ /// The record's text not given to a line yet.+ private var pending = ""+ /// Where the record recognizer's last finished sentence ended.+ private var heardThrough = -Double.infinity++ /// A line whose next one hasn't come yet settles once this much has been heard after it: what+ /// follows could still be the start of the next line.+ static let wait = 2.0++ /// A line the live recognizer finished. Returns the lines that settled: id and text ("" when+ /// the record recognizer heard nothing for it).+ mutating func emitted(id: Int, start: Double, end: Double, text: String) -> [(id: Int, text: String)] {+ guard start.isFinite, end.isFinite else { return [] }+ lines.append(Line(id: id, start: start, end: max(start, end), text: text))+ return settle(final: false)+ }++ /// A sentence the record recognizer finished, through the end of the audio it covers (its+ /// last word, or the pause after it).+ mutating func heard(_ sentence: [Recognition.Run], through: Double? = nil) -> [(id: Int, text: String)] {+ guard let last = sentence.last else { return [] }+ pending += sentence.map(\.text).joined()+ heardThrough = max(heardThrough, through ?? last.end)+ return settle(final: false)+ }++ /// The record recognizer heard everything there was.+ mutating func finish() -> [(id: Int, text: String)] { settle(final: true) }++ private mutating func settle(final: Bool) -> [(id: Int, text: String)] {+ // The lines the record has heard all of, in order.+ var covered = 0+ while covered < lines.count {+ let l = lines[covered]+ let nextKnown = covered + 1 < lines.count+ guard final || heardThrough >= l.end - 0.05 && (nextKnown || heardThrough >= l.end + Self.wait) else { break }+ covered += 1+ }+ guard covered > 0 else { return [] }+ let settling = Array(lines[..<covered])+ lines.removeFirst(covered)+ let record = Array(pending)+ // The next line, when known, helps decide where the last settling one ends.+ let context = settling.map(\.text) + (lines.first.map { [$0.text] } ?? [])+ let ends = Self.split(record, at: context, freeTail: !final)+ var out: [(id: Int, text: String)] = []+ var from = 0+ for (i, l) in settling.enumerated() {+ // Finishing: whatever is left belongs to the last line.+ let to = final && i == settling.count - 1 ? record.count : ends[i]+ out.append((l.id, String(record[from..<max(from, to)])))+ from = max(from, to)+ }+ pending = String(record[from...])+ return out+ }++ /// Where in `record` each of `lines` ends: the record aligned with the lines' text joined, by+ /// edit distance. With `freeTail` the record may run on past the lines (a sentence that goes+ /// into a line not given yet).+ static func split(_ record: [Character], at lines: [String], freeTail: Bool) -> [Int] {+ let live = Array(lines.joined())+ let n = live.count, m = record.count+ var bounds: [Int] = []+ var acc = 0+ for t in lines { acc += t.count; bounds.append(acc) }+ guard n > 0, m > 0 else { return bounds.map { _ in 0 } }+ // d[i][j]: cost of live[..<i] against record[..<j].+ var d = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)+ for i in 0...n { d[i][0] = i }+ for j in 0...m { d[0][j] = j }+ for i in 1...n {+ for j in 1...m {+ let same = Self.same(live[i - 1], record[j - 1])+ d[i][j] = min(d[i - 1][j - 1] + (same ? 0 : 1), d[i - 1][j] + 1, d[i][j - 1] + 1)+ }+ }+ var j = m+ if freeTail { j = (0...m).min { d[n][$0] < d[n][$1] || d[n][$0] == d[n][$1] && $0 > $1 }! }+ // Walk back, noting the record position at each live position (the furthest one).+ var at = Array(repeating: 0, count: n + 1)+ var i = n+ at[n] = j+ while i > 0 || j > 0 {+ if i > 0, j > 0, d[i][j] == d[i - 1][j - 1] + (Self.same(live[i - 1], record[j - 1]) ? 0 : 1) {+ i -= 1; j -= 1+ } else if i > 0, d[i][j] == d[i - 1][j] + 1 {+ i -= 1+ } else {+ j -= 1+ continue+ }+ if at[i] == 0 { at[i] = j }+ }+ var ends = bounds.map { b in at[b] }+ // The live lines were often cut mid-sentence for the subtitles: a line ends at the record's+ // nearest punctuation when there is some a few characters away.+ // Otherwise it ends between words: Chinese comes one character per run, and "审 / 计" is no line end.+ let words = Self.wordStarts(record)+ for k in ends.indices {+ var e = Self.snap(ends[k], in: record)+ if e == ends[k], e > 0, e < m, !words.contains(e) {+ let after = (e...m).first { words.contains($0) || $0 == m } ?? m+ let before = (0...e).last { words.contains($0) } ?? 0+ e = after - e <= e - before ? after : before+ }+ ends[k] = max(e, k > 0 ? ends[k - 1] : 0)+ }+ return ends+ }++ /// Character offsets where a word starts (and the end).+ static func wordStarts(_ record: [Character]) -> Set<Int> {+ let text = String(record)+ let tokenizer = NLTokenizer(unit: .word)+ tokenizer.string = text+ var starts: Set<Int> = [0, record.count]+ tokenizer.enumerateTokens(in: text.startIndex..<text.endIndex) { range, _ in+ starts.insert(text.distance(from: text.startIndex, to: range.lowerBound))+ starts.insert(text.distance(from: text.startIndex, to: range.upperBound))+ return true+ }+ return starts+ }++ static let snapReach = 6++ /// `e`, or just after the closest sentence mark within `snapReach` characters.+ static func snap(_ e: Int, in record: [Character]) -> Int {+ func mark(_ c: Character) -> Bool { ",。?!;、,.?!;".contains(c) }+ guard e > 0, e < record.count, !mark(record[e - 1]) else { return e }+ for d in 0..<snapReach {+ if e + d < record.count, mark(record[e + d]) { return e + d + 1 }+ if e - 1 - d > 0, mark(record[e - 1 - d]) { return e - d }+ }+ return e+ }++ private static func same(_ a: Character, _ b: Character) -> Bool {+ a == b || a.lowercased() == b.lowercased()+ }+}diff --git a/Sources/Cicada/SessionStore.swift b/Sources/Cicada/SessionStore.swiftindex 4f4b9c2..bbd7948 100644--- a/Sources/Cicada/SessionStore.swift+++ b/Sources/Cicada/SessionStore.swift@@ -211,6 +211,14 @@ final class SessionStore: ObservableObject {scheduleSave(id)}+ /// The record's own recognizer's words for a line (`RecordRefiner`), which may land after the+ /// meeting ended.+ func setSource(in id: String, lineID: String, _ text: String) {+ guard 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 }diff --git a/Tests/CicadaTests/RecordRefinerTests.swift b/Tests/CicadaTests/RecordRefinerTests.swiftnew file mode 100644index 0000000..7e673a4--- /dev/null+++ b/Tests/CicadaTests/RecordRefinerTests.swift@@ -0,0 +1,97 @@+import Foundation+import Testing+@testable import Cicada++/// The record's recognizer laid over the live lines (issue #14: a Chinese product meeting).+@Suite struct RecordRefinerTests {+ private func run(_ text: String, _ start: Double, _ end: Double) -> Recognition.Run { .init(text: text, start: start, end: end) }++ @Test func lineTakesTheRecordsWords() {+ var r = RecordRefiner()+ #expect(r.emitted(id: 1, start: 0, end: 3, text: "今天周你过一下后才角色和权限。").isEmpty)+ #expect(r.emitted(id: 2, start: 3.2, end: 6, text: "就是这个功能").isEmpty)+ let out = r.heard([run("今天就要过一下后台角色和权限。", 0.1, 2.9)], through: 3.1)+ #expect(out.map(\.id) == [1])+ #expect(out.first?.text == "今天就要过一下后台角色和权限。")+ }++ /// Word times that run late still split where the text does: the sentence end stays with its line.+ @Test func textDecidesTheEnd() {+ var r = RecordRefiner()+ _ = r.emitted(id: 1, start: 0, end: 4, text: "每天凌晨跑一次回收完给管理员发一个通。")+ _ = r.emitted(id: 2, start: 4.2, end: 6, text: "好到今天就要下周二我们再约一次。")+ let out = r.heard([run("每天凌晨跑一次回收完给管理员发一个通知。好那今天就先这样下周二我们再约一下进度。", 0.1, 5.9)], through: 6.1)+ #expect(out.map(\.text) == ["每天凌晨跑一次回收完给管理员发一个通知。"])+ #expect(r.finish().map(\.text) == ["好那今天就先这样下周二我们再约一下进度。"])+ }++ /// A word the live recognizer split at a cut goes whole to one side.+ @Test func splitWordGoesWhole() {+ var r = RecordRefiner()+ _ = r.emitted(id: 1, start: 0, end: 2, text: "每天跑一次回")+ _ = r.emitted(id: 2, start: 2, end: 4, text: "收完发通知。")+ _ = r.emitted(id: 3, start: 4.5, end: 6, text: "好的。")+ let out = r.heard([run("每天跑一次回收完发通知。", 0.2, 3.9)], through: 4.2)+ #expect(out.count == 2)+ #expect(out.map(\.text).joined() == "每天跑一次回收完发通知。")+ }++ /// Words the live recognizer lost at a cut still reach the record.+ @Test func lostWordsAreKept() {+ var r = RecordRefiner()+ _ = r.emitted(id: 1, start: 0, end: 2, text: "那我说一下吧,")+ _ = r.emitted(id: 2, start: 3, end: 5, text: "才说的意思")+ _ = r.emitted(id: 3, start: 6, end: 8, text: "对。")+ let out = r.heard([run("那我说一下吧,我理解刚才说的意思", 0.1, 4.9)], through: 5.2)+ #expect(out.map(\.text).joined() == "那我说一下吧,我理解刚才说的意思")+ #expect(out.last?.text.hasSuffix("才说的意思") == true)+ }++ /// The last line waits: what follows could start the next line.+ @Test func lastLineWaits() {+ var r = RecordRefiner()+ _ = r.emitted(id: 1, start: 0, end: 2, text: "好的。")+ #expect(r.heard([run("好的。", 0.2, 1.9)], through: 2.1).isEmpty)+ #expect(r.heard([run("下周二", 4.5, 5.5)]).map(\.text) == ["好的。"])+ }++ /// A record sentence running into a line not given yet keeps that part for it.+ @Test func recordRunsAhead() {+ var r = RecordRefiner()+ _ = r.emitted(id: 1, start: 0, end: 2, text: "先接企业微信吧。")+ let out = r.heard([run("先接企业微信吧。飞书下个迭代再说。", 0.1, 6)], through: 6.2)+ #expect(out.map(\.text) == ["先接企业微信吧。"])+ _ = r.emitted(id: 2, start: 2.5, end: 6, text: "飞书下个节日再说。")+ #expect(r.finish().map(\.text) == ["飞书下个迭代再说。"])+ }++ /// A line the subtitles cut mid-sentence ends at the record's nearby comma instead.+ @Test func lineEndsAtNearbyPunctuation() {+ var r = RecordRefiner()+ _ = r.emitted(id: 1, start: 0, end: 3, text: "我理解刚才说的意思就是给用户赋予某个角色,然后这个")+ _ = r.emitted(id: 2, start: 3, end: 5, text: "角色带着一组权限。")+ _ = r.emitted(id: 3, start: 6, end: 7, text: "对。")+ let out = r.heard([run("我理解刚才说的意思就是给用户赋予某个角色,然后这个角色带着一组权限。", 0.1, 4.9)], through: 5.2)+ #expect(out.map(\.text) == ["我理解刚才说的意思就是给用户赋予某个角色,", "然后这个角色带着一组权限。"])+ }++ /// No punctuation near the cut: the line still ends between words.+ @Test func lineEndsBetweenWords() {+ var r = RecordRefiner()+ _ = r.emitted(id: 1, start: 0, end: 3, text: "他这个管理员可能就是因为他权限比较大了审")+ _ = r.emitted(id: 2, start: 3, end: 5, text: "计日志一定要记下来")+ _ = r.emitted(id: 3, start: 6, end: 7, text: "对")+ let out = r.heard([run("他这个管理员可能就是因为他权限比较大了审计日志一定要记下来", 0.1, 4.9)], through: 5.2)+ #expect(out.first?.text.hasSuffix("审") == false)+ #expect(out.map(\.text).joined() == "他这个管理员可能就是因为他权限比较大了审计日志一定要记下来")+ }++ @Test func finishSettlesTheRest() {+ var r = RecordRefiner()+ _ = r.emitted(id: 1, start: 0, end: 2, text: "好的。")+ _ = r.emitted(id: 2, start: 10, end: 12, text: "嗯。")+ let out = r.finish()+ #expect(out.map(\.id) == [1, 2])+ #expect(out.map(\.text) == ["", ""])+ }+}diff --git a/site/changelog.json b/site/changelog.jsonindex da03188..3d4808b 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -1,4 +1,21 @@[+ {+ "version": "1.4.0",+ "date": null,+ "title": "文字记录更准",+ "summary": "在 Apple 芯片的 macOS 26 上,文字记录会在本机再听一遍并校准:错字更少,字幕断句的地方不再丢字,字幕照样快。",+ "image": null,+ "items": [+ {+ "kind": "improved",+ "platforms": [+ "mac"+ ],+ "title": "在 Apple 芯片的 macOS 26 上,文字记录会在本机再听一遍并校准,错字更少,字幕断句的地方不再丢字。",+ "text": "字幕照样快;每句话说完 15–30 秒后校准好,期间纪要窗口里标着“校准中”。实测腾讯会议音质的中文会议,文字记录的错字从 25–30% 降到约 20%;英文从 11% 降到 2%。"+ }+ ]+ },{"version": "1.3.1","date": null,diff --git a/tools/README.md b/tools/README.mdindex bfdedbb..8b2b111 100644--- a/tools/README.md+++ b/tools/README.md@@ -16,7 +16,7 @@- 系统麦克风:`sysMic` 把状态、默认输入、要换回的麦克风和知了实际在录的麦克风写进日志,`sysMicSet:<设备名片段>` 假装别人改了系统麦克风,`sysMicRestore` 还原,`sysMicSwitch` 换成虚拟麦克风,`sysMicAuto:<on|off>`,`speakMic:<设备名片段>` 固定知了用的麦克风(留空 = 自动)。会改本机的系统麦克风:测完 `sysMicRestore` 或退出 App- 说话同传:`speakOn` / `speakOff` 开关,`speakAsk[:off]` 面板里第一次打开时的确认卡,`speakConfirmed:<on|off>` 是否已确认过,`speakFile:<音频>` 把文件按实时速度当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份,`speakOutput:<设备名片段>` 改输出设备(留空 = 虚拟麦克风),`speakVP:<on|off>` 按键说话时用不用带回声消除的麦克风(默认开;日志 `voice mic: ready`、`speak: mic with echo cancellation`),`talkDown` / `talkUp` 用真麦克风按住、松开说话键(日志 `speak: on-device heard … Ming …`、没人说话时 `nothing said in the press`)- 试一句:`speakTest:sample`(Mac 读一句示例)或 `speakTest:voice`(再发 `speakTestBegin` / `speakTestEnd` 当作按住、松开),结果以 `speak test:` 写进日志;`speakTestState`、`speakTestRender:<png>`、`speakTestClose`- - 识别引擎:`recognizer:legacy` 在 macOS 26 上改用 14 / 15 的识别(`SFSpeechRecognizer`,第一次会要“语音识别”权限),`recognizer:cloud` 像 Intel Mac 那样全部交给 Ling 听(没有 key 就听不了),`recognizer:auto` 换回;下一次开始听起生效(或启动时 `open --env CICADA_RECOGNIZER=legacy`),日志里 `transcriber started recognizer=…`+ - 识别引擎:`recognizer:legacy` 在 macOS 26 上改用 14 / 15 的识别(`SFSpeechRecognizer`,第一次会要“语音识别”权限),`recognizer:cloud` 像 Intel Mac 那样全部交给 Ling 听(没有 key 就听不了),`recognizer:auto` 换回;下一次开始听起生效(或启动时 `open --env CICADA_RECOGNIZER=legacy`),日志里 `transcriber started recognizer=…`;`recordTrack:off` 让会议记录不再另用一遍不切句的识别(下一次开始听起生效,对比准确度用;`open --env CICADA_RECORD_TRACK=off` 同理),`recordState` 把还在校准的句数写进日志,打开 `debug` 后日志里有 `RECORD` 和 `REFINE`- 多开:两边都设 `CICADA_DEBUG_CHANNEL=x`(`open -n --env CICADA_DEBUG_CHANNEL=x build/Cicada.app`),命令只发给这一份,日志在 `/tmp/livesubs-dev-debug-x.log`- 导出:`export:<目录>`- 导入录音或视频:`import:<路径>[,<路径>…]`(等于拖进会议记录窗口),`importState` 把进度写进日志,`importCancel` 停止转写,`importRetry:<会议 id>[=<locale>]` 重新转写(带 locale 等于在“这场会议只留下了录音”里选了这种语言),`importNotify` 把通知权限写进日志