知了 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(ios): misheard names and terms are fixed as the meeting goes, from the word list and the AI service, with new names held for a yes
wqugurub83721eafcea
diff --git a/Sources/Cicada/LiveFixes.swift b/Sources/Cicada/LiveFixes.swiftindex e9d4885..3ce8c55 100644--- a/Sources/Cicada/LiveFixes.swift+++ b/Sources/Cicada/LiveFixes.swift@@ -1,5 +1,14 @@import Foundation+/// The two switches 改正听错的词 reads: the Mac's `AppSettings`, the iOS app's own preferences.+@MainActor+protocol FixSwitches: AnyObject {+ /// 会中改正听错的词.+ var fixMisheard: Bool { get }+ /// 没见过的名字和专称先问我.+ var askNames: Bool { get }+}+/// 改正听错的词, between the translation chain and the records: which fixes a line takes, which wait/// for the user (待确认), and what the user's answers and edits teach the word list. Who wins: the/// user's own decisions, then the word list, then the recheck, then the first live guess. UI-free;@@ -8,7 +17,7 @@ import Foundationfinal class LiveFixes: ObservableObject {let store: SessionStorelet vocabulary: Vocabulary- let settings: AppSettings+ let settings: FixSwitches/// The line changed: the app refreshes the subtitle bar if it is still showing it.var onLineFixed: ((_ session: String, _ line: TranscriptLine) -> Void)?var onChange: (() -> Void)?@@ -31,7 +40,7 @@ final class LiveFixes: ObservableObject {/// The card asks about at most this many names in a row; the rest wait for after the meeting.static let askAtOnce = 3- init(store: SessionStore, vocabulary: Vocabulary, settings: AppSettings) {+ init(store: SessionStore, vocabulary: Vocabulary, settings: FixSwitches) {self.store = storeself.vocabulary = vocabularyself.settings = settingsdiff --git a/Sources/Cicada/Settings.swift b/Sources/Cicada/Settings.swiftindex b5fe293..998bd92 100644--- a/Sources/Cicada/Settings.swift+++ b/Sources/Cicada/Settings.swift@@ -369,3 +369,5 @@ func debugLog(_ message: String) {func contentLog(_ message: @autoclosure () -> String) {if UserDefaults.standard.bool(forKey: "debug") { debugLog(message()) }}++extension AppSettings: FixSwitches {}diff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swiftindex a36e025..b75c7e7 100644--- a/ios/Sources/Cicada/CicadaApp.swift+++ b/ios/Sources/Cicada/CicadaApp.swift@@ -31,6 +31,9 @@ enum Pref {static let voices = "speakerVoices"/// 纪要语言: "mine" (the language meetings are translated into) or "source" (the meeting's own).static let notesLanguage = "notesLanguage"+ /// 会中改正听错的词, and 没见过的名字和专称先问我.+ static let fixMisheard = "fixMisheard"+ static let askNames = "askNames"/// 对方说 on iOS: one language the user picks (detecting it comes later); the Mac's "auto" reads as English.static var sourceLang: Lang {@@ -57,6 +60,13 @@ enum Pref {}}+/// 改正听错的词's two switches, by the Mac's names (AppSettings).+@MainActor+final class FixPrefs: FixSwitches {+ var fixMisheard: Bool { UserDefaults.standard.bool(forKey: Pref.fixMisheard) }+ var askNames: Bool { UserDefaults.standard.bool(forKey: Pref.askNames) }+}+/// Wires the shared engines to the screens, like the Mac's AppModel. M1: the records, the key and/// their notes.@MainActor@@ -72,6 +82,9 @@ final class AppModel: ObservableObject {return r}()let liveActivity = LiveActivityController()+ /// 词表 and 改正听错的词, the Mac's own engines.+ let vocabulary = Vocabulary(url: Vocabulary.defaultURL)+ lazy var fixes = makeFixes()/// 正在听's 字幕 / 纪要 switch, so a debug command can flip it.@Published var livePage: LivePage = .subtitles/// The record page's picked speaker (scheme A: only they are drawn in ink).@@ -95,7 +108,8 @@ final class AppModel: ObservableObject {@Published var devWindow: CGSize?init() {- UserDefaults.standard.register(defaults: [Pref.source: "en-US", Pref.voices: true, Pref.model: LingClient.models[0], Pref.notesLanguage: "mine"])+ UserDefaults.standard.register(defaults: [Pref.source: "en-US", Pref.voices: true, Pref.model: LingClient.models[0], Pref.notesLanguage: "mine",+ Pref.fixMisheard: true, Pref.askNames: true])TranscriptExport.voices = UserDefaults.standard.bool(forKey: Pref.voices)// Ling only for now: the Mac's other services (AIProvider) come to iOS with their settings.ling.config = {@@ -103,6 +117,7 @@ final class AppModel: ObservableObject {textModel: UserDefaults.standard.string(forKey: Pref.model) ?? LingClient.models[0])}wireNotes()+ wireFixes()#if targetEnvironment(simulator)HostRecognizer.install()#endif@@ -118,13 +133,14 @@ final class AppModel: ObservableObject {selection = nilsearchPath = []tab = .records+ fixes.meetingStarted()room.start(source: Pref.sourceLang.locale, target: Pref.targetCode, voices: UserDefaults.standard.bool(forKey: Pref.voices))}func stopListening() { room.stop() }/// The Live Activity shows the line as fixed (改正听错的词), like the 字幕 page.- private func showOnLockScreen(_ line: RoomListen.Line) {+ func showOnLockScreen(_ line: RoomListen.Line) {var shown = lineif let rec = store.session(room.sessionID)?.lines.first(where: { $0.id == line.id }) { shown.src = rec.shown }liveActivity.update(line: shown)@@ -146,6 +162,26 @@ final class AppModel: ObservableObject {notes.generate(for: id)}+ /// Each finished sentence's translation also asks which words were misheard (Ling only); the+ /// word list's known forms are fixed as soon as a line is written. As the Mac's AppModel.+ func wireFixes() {+ translator.fixContext = { [weak self] text in self?.fixes.context(for: text) }+ translator.onFixes = { [weak self] text, edits in self?.fixes.received(text, edits) }+ room.onHeard = { [weak self] session, line in self?.fixes.applyKnown(lineID: line, in: session) }+ }++ func makeFixes() -> LiveFixes {+ let f = LiveFixes(store: store, vocabulary: vocabulary, settings: FixPrefs())+ f.onChange = { [weak self] in self?.objectWillChange.send() }+ // The lock screen follows a fix on the line it shows.+ f.onLineFixed = { [weak self] session, line in+ guard let self, session == self.room.sessionID, let last = self.room.lines.last, last.id == line.id else { return }+ self.showOnLockScreen(last)+ }+ vocabulary.onChange = { [weak self] in self?.objectWillChange.send() }+ return f+ }+func wireNotes() {notes.language = { [weak self] id in TranslationService.englishName(self?.notesLanguageCode(id) ?? Pref.targetCode) }}diff --git a/ios/Sources/Cicada/Debug.swift b/ios/Sources/Cicada/Debug.swiftindex f98cd0e..d02b3f2 100644--- a/ios/Sources/Cicada/Debug.swift+++ b/ios/Sources/Cicada/Debug.swift@@ -30,6 +30,9 @@ enum DebugChannel {}extension AppModel {+ /// The meeting a fix command means: the live one, else the open one, else the newest.+ private var fixSession: String { store.liveID ?? selection ?? store.sessions.first?.id ?? "" }+func debugCommand(_ cmd: String) {debugLog("debug command: \(cmd)")let (name, arg) = cmd.split(separator: ":", maxSplits: 1).map(String.init).splitPair@@ -94,6 +97,7 @@ extension AppModel {store = SessionStore()notes = NotesEngine(ling: ling, store: store)wireNotes()+ fixes = makeFixes()case "generateNotes":// generateNotes:<id>, as the record page's 生成纪要 (needs a key).generateNotes(arg.isEmpty ? (selection ?? store.sessions.first?.id ?? "") : arg)@@ -122,6 +126,78 @@ extension AppModel {namingSpeaker = Int(arg)case "undoSpeaker":undoSpeakerEdit()+ // 改正听错的词, by the Mac's names: switches, the word list, and the fixes of a meeting+ // (the live one, or `<id>`, else the open one or the newest).+ case "fixes": UserDefaults.standard.set(arg != "off", forKey: Pref.fixMisheard)+ case "askNames": UserDefaults.standard.set(arg != "off", forKey: Pref.askNames)+ case "silentListen":+ // A meeting without the microphone or the recognizer, fed lines by `heard:`.+ RoomListen.silent = arg != "off"+ case "heard": room.debugHeard(arg)+ case "vocabAdd": // vocabAdd:Morpho=莫拉、莫法 (several lines with "|")+ let r = vocabulary.importText(arg.replacingOccurrences(of: "|", with: "\n"))+ debugLog("vocab: added=\(r.added) updated=\(r.updated) skipped=\(r.skipped)")+ case "vocabRemove": vocabulary.remove(arg)+ case "vocabState":+ debugLog("vocab: \(vocabulary.terms.count) terms")+ for t in vocabulary.terms { contentLog("VOCAB \(t.word) heard=\(t.heard) source=\(t.source) fixes=\(t.fixes)") }+ case "fixState":+ let id = arg.isEmpty ? fixSession : arg+ let lines = store.session(id)?.lines ?? []+ let all = lines.flatMap { $0.fixes ?? [] }+ debugLog("fix state \(id): lines=\(lines.filter { $0.fixes != nil }.count) applied=\(all.filter(\.applied).count) "+ + "asked=\(all.filter { $0.ask == true }.count) off=\(all.filter { $0.off == true }.count) on=\(FixPrefs().fixMisheard)")+ for l in lines where l.fixes != nil {+ contentLog("FIXED \(l.id) \(l.fixes!.map { "\($0.from)→\($0.to)\($0.ask == true ? "?" : $0.off == true ? "✗" : "")" }) | \(l.shown)")+ }+ // What the AI service would propose for a live line, without asking it (no key needed):+ // proposeFix:<line id>=<from>><to>@<confidence>[|…]+ case "proposeFix":+ let p = arg.split(separator: "=", maxSplits: 1).map(String.init)+ guard p.count == 2, let id = store.liveID, let l = store.session(id)?.lines.first(where: { $0.id == p[0] }) else { break }+ let edits = p[1].split(separator: "|").compactMap { e -> Correction.Edit? in+ let ft = e.split(separator: ">", maxSplits: 1).map(String.init)+ guard ft.count == 2 else { return nil }+ let tc = ft[1].split(separator: "@").map(String.init)+ return Correction.Edit(from: ft[0], to: tc[0], confidence: tc.count > 1 ? Double(tc[1]) ?? 0.9 : 0.9)+ }+ fixes.received(l.src, edits)+ case "fixAnswer": // fixAnswer:yes|no[,<id>]+ let parts = arg.split(separator: ",", maxSplits: 1).map(String.init)+ let id = parts.count > 1 ? parts[1] : fixSession+ if let first = fixes.asking(in: id) ?? fixes.pending(in: id).first.map({ ($0.line, $0.fix, 1, 1) }) {+ fixes.answer(first.fix, yes: parts.first == "yes", in: id)+ }+ // The recheck without audio: line `<id>` settles as `<text>` and is translated (and fixed) again.+ case "resettle": // resettle:<line id>=<text>+ let p = arg.split(separator: "=", maxSplits: 1).map(String.init)+ guard p.count == 2, let id = store.liveID, let rec = store.session(id)?.lines.first(where: { $0.id == p[0] }) else { break }+ store.setSource(in: id, lineID: rec.id, p[1])+ fixes.applyKnown(lineID: rec.id, in: id)+ Task { [weak self] in+ guard let self, let out = await self.translator.translate(p[1], source: rec.srcLang, target: rec.dstLang, kind: .sentence) else { return }+ self.store.setTranslation(in: id, lineID: rec.id, out)+ }+ case "fixLater":+ let id = arg.isEmpty ? store.liveID ?? "" : arg+ if let a = fixes.asking(in: id) { fixes.later(a.fix, in: id) }+ case "fixUndo": fixes.undo()+ case "fixEdit": // fixEdit:<line id>=<new text>[|one|keep0][,<session id>]+ let (head, sid) = { () -> (String, String) in+ if let c = arg.lastIndex(of: ","), !arg[arg.index(after: c)...].contains("=") { return (String(arg[..<c]), String(arg[arg.index(after: c)...])) }+ return (arg, fixSession)+ }()+ let p = head.split(separator: "=", maxSplits: 1).map(String.init)+ guard p.count == 2 else { break }+ let opts = p[1].split(separator: "|").map(String.init)+ let n = fixes.edit(lineID: p[0], in: sid, to: opts[0], everywhere: !opts.contains("one"), remember: !opts.contains("keep0"))+ debugLog("fix edit changed \(n) lines")+ case "fixRevert": // fixRevert:<line id>[,<session id>]: the line's first applied fix+ let parts = arg.split(separator: ",", maxSplits: 1).map(String.init)+ let id = parts.count > 1 ? parts[1] : fixSession+ if let l = store.session(id)?.lines.first(where: { $0.id == parts.first }), let f = l.fixes?.first(where: \.applied) {+ fixes.revert(f, lineID: l.id, in: id)+ }case "state":debugLog("room running=\(room.isRunning) lines=\(room.lines.count) draft=\(room.draft.count) level=\(room.level) status=\(room.status) session=\(room.sessionID ?? "-")")debugLog("state tab=\(tab.rawValue) selection=\(selection ?? "-") page=\(recordPage) sessions=\(store.sessions.count) query=\(query) notesLang=\(notesLanguageCode(selection ?? store.sessions.first?.id ?? "")) undo=\(speakerUndo?.text ?? "-")")diff --git a/ios/Sources/Cicada/RoomListen.swift b/ios/Sources/Cicada/RoomListen.swiftindex 6938d6d..825bd27 100644--- a/ios/Sources/Cicada/RoomListen.swift+++ b/ios/Sources/Cicada/RoomListen.swift@@ -29,6 +29,12 @@ final class RoomListen: ObservableObject {/// Every finished line, for the Live Activity.var onLine: ((Line) -> Void)?+ /// A line was written or its words changed (a joined sentence): the word list's known+ /// misheard forms are fixed at once (`LiveFixes.applyKnown`).+ var onHeard: ((_ session: String, _ lineID: String) -> Void)?+ /// Debug (`silentListen`): a meeting with no microphone and no recognizer, fed by `heard:`.+ static var silent = false+ private var silentClock = 0.0var onStateChange: (() -> Void)?private let store: SessionStore@@ -88,6 +94,17 @@ final class RoomListen: ObservableObject {last = nilcounter = 0speakers.reset()+ if Self.silent {+ let s = store.begin()+ store.markLiveInRoom()+ sessionID = s.id+ startedAt = s.startedAt+ notes.begin(s.id)+ status = ""+ debugLog("room: listening silent (debug), no audio, session=\(s.id)")+ onStateChange?()+ return+ }guard await AVAudioApplication.requestRecordPermission() else {fail(L("请在设置里允许知了使用麦克风"))return@@ -141,7 +158,7 @@ final class RoomListen: ObservableObject {func stop() {guard isRunning else { return }isRunning = false- audio.stop()+ if !Self.silent { audio.stop() }let stream = self.stream, reader = self.readerself.stream = nilself.reader = nil@@ -182,6 +199,7 @@ final class RoomListen: ObservableObject {last = (prev.id, joined, piece.end)store.setSource(lineID: prev.id, joined)if let i = lines.firstIndex(where: { $0.id == prev.id }) { lines[i].src = joined }+ if let sid = sessionID { onHeard?(sid, prev.id) }translate(prev.id, joined)return}@@ -192,6 +210,7 @@ final class RoomListen: ObservableObject {store.append(TranscriptLine(id: id, t: t, speaker: "them", src: final, dst: nil,srcLang: lang.code, dstLang: target))lines.append(Line(id: id, src: final, dst: nil, voice: nil, t: t))+ if let sid = sessionID { onHeard?(sid, id) }if lines.count > 60 { lines.removeFirst(lines.count - 60) }last = (id, final, piece.end)if let samples = audio.voiceSamples(from: piece.start, to: piece.end) {@@ -200,6 +219,16 @@ final class RoomListen: ObservableObject {translate(id, final)}+ /// Debug (`heard:<text>`): a finished sentence as if the recognizer gave it, in a silent meeting.+ /// The record, its translation and fixes, and the 字幕 page all follow.+ func debugHeard(_ text: String) {+ guard isRunning, Self.silent, sessionID != nil else { return }+ // Half a minute apart, so two lines are never joined as one sentence a pause cut.+ silentClock += 30+ let at = silentClock+ handle(Recognition.Piece(text: text, isFinal: true, start: at, end: at + 2, confidence: nil))+ }+/// `retry`: every provider failed before (Ling busy while Google answers 429): asked again a/// little later, twice at most, as the Mac does.private func translate(_ id: String, _ text: String, retry: Int = 0) {diff --git a/ios/shared-sources.txt b/ios/shared-sources.txtindex 3a14eb5..5f34cba 100644--- a/ios/shared-sources.txt+++ b/ios/shared-sources.txt@@ -11,6 +11,8 @@ Sources/Cicada/Localization.swiftSources/Cicada/Voices.swiftSources/Cicada/SessionStore.swiftSources/Cicada/Correction.swift+Sources/Cicada/Vocabulary.swift+Sources/Cicada/LiveFixes.swiftSources/Cicada/SpeakerID.swiftSources/Cicada/AudioFiles.swiftSources/Cicada/Translator.swift