Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat: misheard names and terms are fixed in subtitles and live notes as the meeting goes, with new names asked about once

wqugurubf9a680258c0
diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.strings
index bd5aff2..2ebe17d 100644
--- a/Resources/en.lproj/Localizable.strings
+++ b/Resources/en.lproj/Localizable.strings
@@ -1254,3 +1254,11 @@
"在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。" = "On the Ling platform, click “Create token” and copy the string that starts with sk-.";
"打开 Ling 开放平台 ↗" = "Open the Ling platform ↗";
"Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个" = "Ling says this token is invalid. Check that you copied all of it, or create a new one";
+
+/* NotesViews: 改正听错的词 */
+"听成" = "Heard as";
+"改回" = "Revert";
+"这样改对吗?" = "Is this fix right?";
+"确认后整场一起改,以后也照此改" = "Fixes the whole meeting, and future ones";
+"对" = "Yes";
+"不对" = "No";
diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.strings
index 9df5349..5a5e0b4 100644
--- a/Resources/ja.lproj/Localizable.strings
+++ b/Resources/ja.lproj/Localizable.strings
@@ -1254,3 +1254,11 @@
"在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。" = "Ling のプラットフォームで「トークンを作成」をクリックし、sk- で始まる文字列をコピーします。";
"打开 Ling 开放平台 ↗" = "Ling プラットフォームを開く ↗";
"Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个" = "Ling がこのトークンは無効だと通知しました。全体をコピーできているか確認するか、新しく作成してください";
+
+/* NotesViews: 改正听错的词 */
+"听成" = "認識";
+"改回" = "元に戻す";
+"这样改对吗?" = "この修正で合っていますか?";
+"确认后整场一起改,以后也照此改" = "会議全体に反映し、次回からも同じく直します";
+"对" = "はい";
+"不对" = "いいえ";
diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.strings
index 23d9314..52b6d28 100644
--- a/Resources/ko.lproj/Localizable.strings
+++ b/Resources/ko.lproj/Localizable.strings
@@ -1254,3 +1254,11 @@
"在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。" = "Ling 개발자 플랫폼에서 “토큰 만들기”를 클릭하고 sk-로 시작하는 문자열을 복사하세요.";
"打开 Ling 开放平台 ↗" = "Ling 개발자 플랫폼 열기 ↗";
"Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个" = "Ling에서 이 토큰이 유효하지 않다고 합니다. 전체를 복사했는지 확인하거나 새로 만드세요";
+
+/* NotesViews: 改正听错的词 */
+"听成" = "인식";
+"改回" = "되돌리기";
+"这样改对吗?" = "이렇게 고치는 게 맞나요?";
+"确认后整场一起改,以后也照此改" = "회의 전체에 적용하고 다음부터도 이렇게 고칩니다";
+"对" = "네";
+"不对" = "아니요";
diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.strings
index a7cc983..18cd77b 100644
--- a/Resources/zh-Hans.lproj/Localizable.strings
+++ b/Resources/zh-Hans.lproj/Localizable.strings
@@ -1254,3 +1254,11 @@
"在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。" = "在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。";
"打开 Ling 开放平台 ↗" = "打开 Ling 开放平台 ↗";
"Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个" = "Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个";
+
+/* NotesViews: 改正听错的词 */
+"听成" = "听成";
+"改回" = "改回";
+"这样改对吗?" = "这样改对吗?";
+"确认后整场一起改,以后也照此改" = "确认后整场一起改,以后也照此改";
+"对" = "对";
+"不对" = "不对";
diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swift
index 36dd63c..b45466c 100644
--- a/Sources/Cicada/AppModel.swift
+++ b/Sources/Cicada/AppModel.swift
@@ -155,6 +155,8 @@ final class AppModel: ObservableObject {
lazy var notes = NotesEngine(ling: ling, store: store)
lazy var notesWindow = NotesWindowController(model: self)
lazy var importer = FileImporter(store: store, settings: settings, translator: translator)
+ let vocabulary = Vocabulary(url: Vocabulary.defaultURL)
+ lazy var fixes = LiveFixes(store: store, vocabulary: vocabulary, settings: settings)
let sample = SamplePlayer()
let speakers = SpeakerTagger()
lazy var speakerNamer = SpeakerNamer(ling: ling, store: store)
@@ -271,6 +273,10 @@ final class AppModel: ObservableObject {
}
}
translator.glossary = { [weak self] in self?.notes.glossary ?? [] }
+ translator.fixContext = { [weak self] text in self?.fixes.context(for: text) }
+ translator.onFixes = { [weak self] text, edits in self?.fixes.received(text, edits) }
+ fixes.onLineFixed = { [weak self] id, line in self?.lineFixed(id, line) }
+ fixes.onChange = { [weak self] in self?.objectWillChange.send() }
// An Intel Mac's imports: heard at a lower priority than the live meeting.
Recognition.cloudHear = { [weak self] wav, seconds, locale in
guard let self else { return nil }
@@ -670,6 +676,7 @@ final class AppModel: ObservableObject {
lineOfSegment = [:]
settledEarly = [:]
refinedLines = []
+ fixes.meetingStarted()
recentOnline = []
heldRoom = []
liveMain = ("", "", .distantPast)
@@ -1422,6 +1429,13 @@ final class AppModel: ObservableObject {
recordHeard(h.seg, duration: h.duration + waited)
}
+ /// A live line's words were fixed (or a fix undone): the subtitle bar follows if it still shows it.
+ private func lineFixed(_ session: String, _ line: TranscriptLine) {
+ guard session == store.liveID, let seg = lineForSegment.first(where: { $0.value == line.id })?.key else { return }
+ let engine = line.via == "room" && roomListen.isRunning ? roomListen : listen
+ engine.showFixed(seg, text: line.shown)
+ }
+
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 }
@@ -1763,6 +1777,39 @@ final class AppModel: ObservableObject {
case "step": onboardingStep = Int(arg) ?? 1
case "samplePlay": ensureListening(); sample.play()
case "speakers": settings.speakerVoices = arg == "on"
+ // 改正听错的词: switches, the word list, and the fixes of a meeting (live, or `<id>`).
+ case "fixes": settings.fixMisheard = arg != "off"
+ // A meeting without audio (no tap, no recognizer), fed lines by `heard:`.
+ case "silentListen": ListenEngine.silentLocale = arg.isEmpty || arg == "off" ? nil : arg
+ case "heard": listen.debugHeard(arg)
+ case "askNames": settings.askNames = arg != "off"
+ 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 ? store.liveID ?? store.sessions.first?.id ?? "" : 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=\(settings.fixMisheard)")
+ contentLog("BAR \(liveMain.src) | \(liveMain.dst)")
+ 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)")
+ }
+ case "fixAnswer": // fixAnswer:yes|no[,<id>]
+ let parts = arg.split(separator: ",", maxSplits: 1).map(String.init)
+ let id = parts.count > 1 ? parts[1] : store.liveID ?? store.sessions.first?.id ?? ""
+ if let first = fixes.pending(in: id).first { fixes.answer(first.fix, yes: parts.first == "yes", in: id) }
+ 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] : store.liveID ?? store.sessions.first?.id ?? ""
+ 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 "speakerGuess": speakerNamer.guess(arg, force: true)
case "speakersRender":
// speakersRender:<session id>=<png>[@width]: the people strip and the first lines with their labels.
@@ -1900,6 +1947,31 @@ final class AppModel: ObservableObject {
}
}
w?.performClose(nil)
+ case "transcriptRender": // transcriptRender:<png>,<session id>,<first line>,<count>: the notes window's 原话
+ let p = arg.split(separator: ",").map(String.init)
+ guard p.count == 4, let s = store.session(p[1]), let first = Int(p[2]), let count = Int(p[3]) else { break }
+ let ls = Array(s.lines.dropFirst(max(0, first - 1)).prefix(count))
+ let waiting = fixes.pending(in: s.id)
+ // The row's own parts (the list itself is lazy and draws nothing off screen).
+ let view = VStack(alignment: .leading, spacing: 14) {
+ ForEach(ls) { l in
+ VStack(alignment: .leading, spacing: 4) {
+ Text(TranscriptParagraphs.joinFixed([l])).font(.system(size: 14)).lineSpacing(2)
+ if let d = l.dst { Text(d).font(.system(size: 13)).foregroundStyle(Palette.secondary) }
+ let fixed = (l.fixes ?? []).filter(\.applied).map { (l.id, $0) }
+ if !fixed.isEmpty { FixedWords(fixes: fixed) { _, _ in } }
+ }
+ }
+ Spacer(minLength: 0)
+ if let w = waiting.first { FixConfirmCard(line: w.line, fix: w.fix, count: waiting.count) { _ in } }
+ }
+ .padding(16).frame(width: 460, height: 900).background(Color.white)
+ let r = ImageRenderer(content: view)
+ r.scale = 2
+ if let img = r.nsImage, let tiff = img.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff),
+ let png = rep.representation(using: .png, properties: [:]) {
+ try? png.write(to: URL(fileURLWithPath: p[0]))
+ }
case "notesRender":
// The whole notes column as a PNG, for checking what is below the fold.
let view = NotesContentView(notes: notes.notes, fresh: notes.fresh, live: store.liveID != nil,
diff --git a/Sources/Cicada/Correction.swift b/Sources/Cicada/Correction.swift
new file mode 100644
index 0000000..7afd86a
--- /dev/null
+++ b/Sources/Cicada/Correction.swift
@@ -0,0 +1,188 @@
+import Foundation
+
+/// A word the AI service said speech recognition got wrong in a finished line ("莫拉" → "Morpho").
+/// The line keeps what was heard (`src`) and carries its fixes, so a port that doesn't know them
+/// still shows the heard text, and a line the record recognizer refines later keeps the fixes
+/// whose words are still in it.
+struct LineFix: Codable, Equatable, Hashable {
+ var from: String
+ var to: String
+ /// Waiting for the user (a name the Mac can't check by sound): not applied until confirmed.
+ var ask: Bool? = nil
+ /// The user said no (改回 or 不对): kept so the same line isn't fixed that way again.
+ var off: Bool? = nil
+
+ var applied: Bool { ask != true && off != true }
+}
+
+/// Deciding which of the service's proposed fixes to take, without asking it again. Its own
+/// confidence isn't enough: in a 21-minute test it rated "快销 → 区块" and "苍蝇 → 方向" above 0.85.
+/// So a Chinese word may only be swapped for one that sounds alike (pinyin from the system's own
+/// transform), a Latin word only for a near spelling, and a new name only once the user says so.
+enum Correction {
+ struct Edit: Equatable {
+ var from: String
+ var to: String
+ var confidence: Double
+ }
+
+ enum Verdict: Equatable { case apply, ask, drop }
+
+ static let applyAt = 0.6
+ static let spellingAt = 0.8
+ static let askAt = 0.8
+
+ /// The part an edit changes, as a word: "解除质压" → "解除质押" is "质压" → "质押" (at least two
+ /// characters, so one refusal doesn't block every 压 → 押), and a Latin word stays whole
+ /// ("Un450P三" → "Uniswap V3", not "450P三" → "iswap V3").
+ static func core(_ from: String, _ to: String) -> (from: String, to: String) {
+ let a = Array(from), b = Array(to)
+ var i = 0
+ while i < min(a.count, b.count), a[i] == b[i] { i += 1 }
+ var j = 0
+ while j < min(a.count, b.count) - i, a[a.count - 1 - j] == b[b.count - 1 - j] { j += 1 }
+ let word: (Character) -> Bool = { $0.isASCII && ($0.isLetter || $0.isNumber) }
+ // Only a change that starts or ends inside a Latin word takes the rest of the word.
+ let fromEdge = { (k: Int) -> Bool in (k < a.count && word(a[k])) || (k < b.count && word(b[k])) }
+ if fromEdge(i) { while i > 0, word(a[i - 1]) { i -= 1 } }
+ if (a.count - j - 1 >= 0 && word(a[a.count - j - 1])) || (b.count - j - 1 >= 0 && word(b[b.count - j - 1])) {
+ while j > 0, word(a[a.count - j]) { j -= 1 }
+ }
+ // Two characters at least, taken from the Chinese side: "FFT制押" → "FFT质押" is "制押" → "质押".
+ while a.count - j - i < 2 || b.count - j - i < 2 {
+ if j > 0, !word(a[a.count - j]) { j -= 1 } else if i > 0, !word(a[i - 1]) { i -= 1 } else { break }
+ }
+ return (String(a[i..<(a.count - j)]), String(b[i..<(b.count - j)]))
+ }
+
+ /// `known`: the user confirmed this heard form for this word (the word list). `rejected`: they
+ /// said no to it in this meeting.
+ static func decide(_ e: Edit, known: (String, String) -> Bool, rejected: (String, String) -> Bool) -> Verdict {
+ let c = core(e.from, e.to)
+ guard !c.from.isEmpty, !c.to.isEmpty, c.from.lowercased() != c.to.lowercased(),
+ !rejected(e.from, e.to), !rejected(c.from, c.to) else { return .drop }
+ if known(e.from, e.to) || known(c.from, c.to) { return .apply }
+ guard e.confidence >= applyAt else { return .drop }
+ let latinFrom = c.from.contains(where: \.isASCIILetter), latinTo = c.to.contains(where: \.isASCIILetter)
+ if !latinFrom, !latinTo, han(c.from), han(c.to), soundsAlike(c.from, c.to) { return .apply }
+ if latinFrom, latinTo, c.from.allSatisfy(\.isASCII), c.to.allSatisfy(\.isASCII), e.confidence >= spellingAt,
+ c.from.lowercased() != c.to.lowercased(), distance(c.from.lowercased(), c.to.lowercased()) <= 2 {
+ return .apply
+ }
+ // A new name (Chinese heard as a Latin name, or a respelled one): sound can't check it.
+ if latinTo, e.confidence >= askAt { return .ask }
+ return .drop
+ }
+
+ /// Toneless pinyin, one syllable per character, from the system's Mandarin transform.
+ static func pinyin(_ s: String) -> [String] {
+ s.map { ch in
+ let m = NSMutableString(string: String(ch))
+ CFStringTransform(m, nil, kCFStringTransformMandarinLatin, false)
+ CFStringTransform(m, nil, kCFStringTransformStripDiacritics, false)
+ return (m as String).lowercased().trimmingCharacters(in: .whitespaces)
+ }
+ }
+
+ private static let initials = ["zh", "ch", "sh", "b", "p", "m", "f", "d", "t", "n", "l", "g", "k", "h", "j", "q",
+ "x", "r", "z", "c", "s", "y", "w"]
+
+ private static func split(_ syllable: String) -> (String, String) {
+ for i in initials where syllable.hasPrefix(i) { return (i, String(syllable.dropFirst(i.count))) }
+ return ("", syllable)
+ }
+
+ /// Same number of syllables, and on average three quarters alike: a syllable counts whole when
+ /// equal, half when its initial or its final matches (质/追, 销/照). 苍蝇/方向 is a quarter.
+ static func soundsAlike(_ a: String, _ b: String) -> Bool {
+ let x = pinyin(a), y = pinyin(b)
+ guard x.count == y.count, !x.isEmpty else { return false }
+ var score = 0.0
+ for (p, q) in zip(x, y) {
+ if p == q { score += 1; continue }
+ let (i1, f1) = split(p), (i2, f2) = split(q)
+ if i1 == i2 || f1 == f2 || f1.replacingOccurrences(of: "ng", with: "n") == f2.replacingOccurrences(of: "ng", with: "n") {
+ score += 0.5
+ }
+ }
+ return score / Double(x.count) >= 0.75
+ }
+
+ static func han(_ s: String) -> Bool {
+ s.unicodeScalars.allSatisfy { $0.properties.isIdeographic }
+ }
+
+ static func distance(_ a: String, _ b: String) -> Int {
+ let a = Array(a), b = Array(b)
+ var row = Array(0...b.count)
+ for (i, ca) in a.enumerated() {
+ var prev = row[0]
+ row[0] = i + 1
+ for (j, cb) in b.enumerated() {
+ let cur = row[j + 1]
+ row[j + 1] = min(row[j + 1] + 1, row[j] + 1, prev + (ca == cb ? 0 : 1))
+ prev = cur
+ }
+ }
+ return row[b.count]
+ }
+
+ /// The line as shown: each applied fix replaces its words where they still are. The ranges are
+ /// the replaced words, for the dotted underline.
+ static func apply(_ fixes: [LineFix], to src: String) -> (text: String, marks: [Range<String.Index>]) {
+ var text = src
+ var spans: [(String, Int)] = [] // replacement and its character offset, kept valid as text changes
+ for f in fixes where f.applied && !f.from.isEmpty {
+ guard let r = text.range(of: f.from) else { continue }
+ let start = text.distance(from: text.startIndex, to: r.lowerBound)
+ let delta = f.to.count - f.from.count
+ spans = spans.map { $0.1 > start ? ($0.0, $0.1 + delta) : $0 }
+ text.replaceSubrange(r, with: f.to)
+ spans.append((f.to, start))
+ }
+ let marks = spans.compactMap { word, offset -> Range<String.Index>? in
+ guard offset + word.count <= text.count else { return nil }
+ let lo = text.index(text.startIndex, offsetBy: offset)
+ return lo..<text.index(lo, offsetBy: word.count)
+ }
+ return (text, marks.sorted { $0.lowerBound < $1.lowerBound })
+ }
+
+ /// The service's reply to a sentence sent with fixes asked for:
+ /// {"translation": "…", "fixes": [{"from", "to", "confidence"}]}. nil when it isn't that shape,
+ /// and the caller treats the reply as a plain translation. Fixes whose words aren't in the
+ /// subtitle are dropped: the service sometimes quotes them rephrased.
+ static func parse(_ reply: String, subtitle: String) -> (translation: String, edits: [Edit])? {
+ // Asked for JSON in the prompt only: take the outermost {…}, fenced or not.
+ guard let open = reply.firstIndex(of: "{"), let close = reply.lastIndex(of: "}"), open < close,
+ let data = String(reply[open...close]).data(using: .utf8),
+ let o = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let translation = o["translation"] as? String else { return nil }
+ let raw = o["fixes"] as? [[String: Any]] ?? []
+ var edits: [Edit] = []
+ for f in raw {
+ guard let from = f["from"] as? String, let to = f["to"] as? String, !from.isEmpty, from != to,
+ subtitle.contains(from) else { continue }
+ let c = (f["confidence"] as? Double) ?? (f["confidence"] as? NSNumber)?.doubleValue ?? 0
+ edits.append(Edit(from: from, to: to, confidence: c))
+ }
+ return (translation.trimmingCharacters(in: .whitespacesAndNewlines), edits)
+ }
+
+ /// What the lines' fixes become after the service answered for this text again (a joined or
+ /// refined line): its new fixes, plus every one the user already turned down.
+ static func merge(_ old: [LineFix], _ new: [LineFix]) -> [LineFix] {
+ let refused = old.filter { $0.off == true }
+ let fresh = new.filter { n in !refused.contains { $0.from == n.from && $0.to == n.to } }
+ return refused + fresh
+ }
+}
+
+extension TranscriptLine {
+ /// What the line says once its fixes are in: shown, exported and read by the notes.
+ var shown: String { fixes.map { Correction.apply($0, to: src).text } ?? src }
+}
+
+private extension Character {
+ var isASCIILetter: Bool { isASCII && isLetter }
+}
diff --git a/Sources/Cicada/ListenEngine.swift b/Sources/Cicada/ListenEngine.swift
index 5b91fa6..7ce6bba 100644
--- a/Sources/Cicada/ListenEngine.swift
+++ b/Sources/Cicada/ListenEngine.swift
@@ -364,6 +364,16 @@ final class ListenEngine {
updateHold()
debugLog("listen start mode=\(settings.sourceMode) target=\(resolvedTarget)")
+ // Debug (`silentListen:<locale>`): a meeting with no audio at all, its lines given by
+ // `heard:` — to try what follows a finished sentence while another app is recording.
+ if let locale = Self.silentLocale {
+ activeLang = sourceLanguages.first { $0.locale == locale } ?? sourceLanguages[0]
+ languageConfirmed = true
+ isRunning = true
+ debugLog("listen start: silent (debug), no audio, \(activeLang!.code)")
+ return
+ }
+
guard startTap() else { return }
router.setVoiceCapture(settings.speakerVoices)
isRunning = true
@@ -856,10 +866,23 @@ final class ListenEngine {
renderSubtitles()
}
+ /// 改正听错的词: a finished line as shown once its fixes are in. Kept apart from the segment's own
+ /// text, which deciding a join and the record's settling compare with what was heard.
+ private var fixedText: [Int: String] = [:]
+
+ /// The app fixed segment `id`'s words: the bar shows them if the line is still on it.
+ func showFixed(_ id: Int, text: String) {
+ guard let seg = segments.first(where: { $0.id == id }) else { return }
+ fixedText[id] = text == seg.text ? nil : text
+ if fixedText.count > 50, let oldest = fixedText.keys.min() { fixedText[oldest] = nil }
+ if segments.last?.id == id { renderSubtitles() }
+ }
+
private func renderSubtitles() {
guard !(segments.isEmpty && volatileText.isEmpty) else { return }
let srcJoin = joiner(for: activeLang?.code ?? "en")
- let source = [segments.last?.text ?? "", volatileText].filter { !$0.isEmpty }
+ let last = segments.last.map { fixedText[$0.id] ?? $0.text } ?? ""
+ let source = [last, volatileText].filter { !$0.isEmpty }
.joined(separator: srcJoin.isEmpty ? " " : srcJoin)
if settings.sourceMode == .auto, !recordable {
onSubtitle?(source, asksLanguage ? L("听不出是哪种语言,到菜单栏里选一下") : L("正在识别语言…"))
@@ -1361,6 +1384,23 @@ final class ListenEngine {
/// `retry` counts the earlier tries of a line every provider failed (Ling rate-limited while
/// Google answers 429, and no on-device model): it is asked again a little later, as the copy
/// `again`, since it may have scrolled off the bar meanwhile; the record still takes it.
+ /// Debug: listen without any audio (`silentListen`), the locale its lines are in.
+ static var silentLocale: String?
+
+ /// Debug (`heard:<text>`): a finished sentence as if the recognizer gave it, in a silent meeting.
+ /// The record, its translation and fixes, the bar and the notes window all follow.
+ func debugHeard(_ text: String) {
+ guard isRunning, Self.silentLocale != nil, let lang = activeLang else { return }
+ let seg = Segment(id: nextSegmentID, text: text, sourceCode: lang.code, translation: nil)
+ nextSegmentID += 1
+ segments.append(seg)
+ if segments.count > 8 { segments.removeFirst(segments.count - 8) }
+ finalTiming[seg.id] = (Date(), 0.5)
+ onFinal?(seg, 2)
+ translateSegment(id: seg.id)
+ renderSubtitles()
+ }
+
private func translateSegment(id: Int, retry: Int = 0, again: Segment? = nil) {
guard !translationOff(), let seg = again ?? segments.first(where: { $0.id == id }) else { return }
let trace = TranslateTrace()
diff --git a/Sources/Cicada/LiveFixes.swift b/Sources/Cicada/LiveFixes.swift
new file mode 100644
index 0000000..40cca0e
--- /dev/null
+++ b/Sources/Cicada/LiveFixes.swift
@@ -0,0 +1,123 @@
+import Foundation
+
+/// 改正听错的词, between the translation chain and the records: which fixes a line takes, which wait
+/// for the user (待确认), and what the user's answers teach the word list. UI-free; the app shows
+/// `pending` and passes taps back.
+@MainActor
+final class LiveFixes {
+ let store: SessionStore
+ let vocabulary: Vocabulary
+ let settings: AppSettings
+ /// 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)?
+
+ /// Fixes said no to in this meeting ("from→to"), and how often each heard form was turned down
+ /// overall this run: twice and it leaves the word list.
+ private var refused: Set<String> = []
+ private var refusals: [String: Int] = [:]
+
+ init(store: SessionStore, vocabulary: Vocabulary, settings: AppSettings) {
+ self.store = store
+ self.vocabulary = vocabulary
+ self.settings = settings
+ }
+
+ func meetingStarted() { refused = [] }
+
+ private static func pair(_ a: String, _ b: String) -> String { a + "\u{1F}" + b }
+
+ /// What a finished sentence's request carries; nil while fixing is off.
+ func context(for text: String) -> TranslationService.FixContext? {
+ guard settings.fixMisheard else { return nil }
+ var topic: String?
+ var recent: [String] = []
+ if let (id, line) = store.lineHeard(as: text), let s = store.session(id) {
+ topic = s.notes?.title ?? (s.renamed == true ? s.title : nil)
+ if let i = s.lines.firstIndex(where: { $0.id == line.id }) {
+ recent = s.lines[max(0, i - 3)..<i].map(\.shown)
+ }
+ }
+ return .init(topic: topic, words: vocabulary.promptLines(), recent: recent)
+ }
+
+ /// The service's proposals for a line heard as `text`.
+ func received(_ text: String, _ edits: [Correction.Edit]) {
+ guard settings.fixMisheard, let (id, line) = store.lineHeard(as: text) else { return }
+ var fresh: [LineFix] = []
+ for e in edits {
+ let verdict = Correction.decide(e, known: { self.vocabulary.knows(heard: $0, word: $1) },
+ rejected: { self.refused.contains(Self.pair($0, $1)) })
+ debugLog("fix \(verdict) c=\(String(format: "%.2f", e.confidence)) line=\(line.id)")
+ contentLog("FIX \(verdict) \(e.from) → \(e.to)")
+ switch verdict {
+ case .apply:
+ fresh.append(LineFix(from: e.from, to: e.to))
+ // A listed word counts as used whichever way the fix was found (a sound-alike too).
+ vocabulary.used(Correction.core(e.from, e.to).to)
+ case .ask where settings.askNames:
+ fresh.append(LineFix(from: e.from, to: e.to, ask: true))
+ default: break
+ }
+ }
+ let fixes = Correction.merge(line.fixes ?? [], fresh)
+ guard fixes != line.fixes ?? [] else { return }
+ store.setFixes(in: id, lineID: line.id, fixes)
+ if let now = store.session(id)?.lines.first(where: { $0.id == line.id }) { onLineFixed?(id, now) }
+ onChange?()
+ }
+
+ /// 待确认 in a meeting: each (from → to) once, oldest first.
+ func pending(in id: String) -> [(line: TranscriptLine, fix: LineFix)] {
+ var seen: Set<String> = []
+ var out: [(TranscriptLine, LineFix)] = []
+ for l in store.session(id)?.lines ?? [] {
+ for f in l.fixes ?? [] where f.ask == true {
+ let c = Correction.core(f.from, f.to)
+ if seen.insert(Self.pair(c.from, c.to)).inserted { out.append((l, f)) }
+ }
+ }
+ return out
+ }
+
+ /// 对 / 不对 on a waiting fix: every line in the meeting waiting on the same change follows,
+ /// and a yes goes into the word list so the next meeting fixes it without asking.
+ func answer(_ fix: LineFix, yes: Bool, in id: String) {
+ let c = Correction.core(fix.from, fix.to)
+ guard let s = store.session(id) else { return }
+ for l in s.lines {
+ guard var fixes = l.fixes else { continue }
+ var changed = false
+ for k in fixes.indices where fixes[k].ask == true && Correction.core(fixes[k].from, fixes[k].to) == c {
+ fixes[k].ask = nil
+ if !yes { fixes[k].off = true }
+ changed = true
+ }
+ if changed {
+ store.setFixes(in: id, lineID: l.id, fixes)
+ if let now = store.session(id)?.lines.first(where: { $0.id == l.id }) { onLineFixed?(id, now) }
+ }
+ }
+ if yes { vocabulary.confirm(heard: c.from, word: c.to) } else { refused.insert(Self.pair(c.from, c.to)) }
+ debugLog("fix answered \(yes ? "yes" : "no")")
+ onChange?()
+ }
+
+ /// 改回: this line goes back to what was heard, and the meeting stops making this change.
+ func revert(_ fix: LineFix, lineID: String, in id: String) {
+ guard let l = store.session(id)?.lines.first(where: { $0.id == lineID }), var fixes = l.fixes,
+ let k = fixes.firstIndex(where: { $0.from == fix.from && $0.to == fix.to }) else { return }
+ fixes[k].off = true
+ fixes[k].ask = nil
+ store.setFixes(in: id, lineID: lineID, fixes)
+ let c = Correction.core(fix.from, fix.to)
+ refused.insert(Self.pair(c.from, c.to))
+ refused.insert(Self.pair(fix.from, fix.to))
+ let key = Self.pair(c.from, c.to)
+ refusals[key, default: 0] += 1
+ if refusals[key]! >= 2 { vocabulary.forget(heard: c.from, word: c.to) }
+ if let now = store.session(id)?.lines.first(where: { $0.id == lineID }) { onLineFixed?(id, now) }
+ debugLog("fix reverted line=\(lineID)")
+ onChange?()
+ }
+}
diff --git a/Sources/Cicada/Notes.swift b/Sources/Cicada/Notes.swift
index 3c0ccb8..d9a7bca 100644
--- a/Sources/Cicada/Notes.swift
+++ b/Sources/Cicada/Notes.swift
@@ -476,7 +476,7 @@ final class NotesEngine: ObservableObject {
let l = lines[i]
// A named voice goes as its name: notes then say "George" rather than "说话人2".
let who = l.speaker == "me" ? "你" : numbers[l.id].map { names[$0] ?? "说话人\($0)" } ?? (numbers.isEmpty ? "对方" : "未识别")
- return "[L\(i + 1) \(clock(l.t)) \(who)] \(l.src)"
+ return "[L\(i + 1) \(clock(l.t)) \(who)] \(l.shown)"
}
var current = "{}"
if !notes.isEmpty, let data = try? JSONEncoder().encode(Compact(notes, from: frozen)), let s = String(data: data, encoding: .utf8) {
diff --git a/Sources/Cicada/NotesViews.swift b/Sources/Cicada/NotesViews.swift
index 659ebc3..f9dcac7 100644
--- a/Sources/Cicada/NotesViews.swift
+++ b/Sources/Cicada/NotesViews.swift
@@ -535,9 +535,14 @@ struct TranscriptListView<Partial: View>: View, Equatable {
/// Lines the meeting record's own recognizer is still settling: their words may change.
var settling: Set<String> = []
var onAssign: ((Set<String>, Int) -> Void)?
+ /// 改回 on a fixed word: the line goes back to what was heard.
+ var onRevert: ((String, LineFix) -> Void)?
+ /// Debug renders: every fixed paragraph shows its words as if pointed at.
+ var revealFixes = false
@ViewBuilder var partial: Partial
@State private var assigning: String?
+ @State private var hovered: String?
@State private var following = true
@State private var seenCount = 0
@@ -712,7 +717,7 @@ struct TranscriptListView<Partial: View>: View, Equatable {
Image(systemName: "arrow.down").font(.system(size: 12, weight: .bold))
Text("\(lines.count - seenCount) 句新内容").font(.system(size: 13, weight: .semibold))
if let last = lines.last {
- Text(last.src).font(.system(size: 13)).foregroundStyle(Color(white: 0.74)).lineLimit(1)
+ Text(last.shown).font(.system(size: 13)).foregroundStyle(Color(white: 0.74)).lineLimit(1)
}
}
.foregroundStyle(.white)
@@ -730,11 +735,15 @@ struct TranscriptListView<Partial: View>: View, Equatable {
}
private func matches(_ l: TranscriptLine) -> Bool {
- terms.contains { l.src.localizedCaseInsensitiveContains($0) || (l.dst ?? "").localizedCaseInsensitiveContains($0) }
+ terms.contains { l.shown.localizedCaseInsensitiveContains($0) || (l.dst ?? "").localizedCaseInsensitiveContains($0) }
}
private func highlighted(_ text: String, current: Bool) -> AttributedString {
- var a = AttributedString(text)
+ highlighted(AttributedString(text), current: current)
+ }
+
+ private func highlighted(_ base: AttributedString, current: Bool) -> AttributedString {
+ var a = base
for term in terms where !term.isEmpty {
var from = a.startIndex
while from < a.endIndex, let r = a[from...].range(of: term, options: .caseInsensitive) {
@@ -751,8 +760,9 @@ struct TranscriptListView<Partial: View>: View, Equatable {
let isMatch = ls.contains { $0.id == currentMatch }
let latest = live && ls.last?.id == lines.last?.id
let dim = searching && !ls.contains(where: matches)
- let src = TranscriptParagraphs.join(ls.map(\.src))
- let dst = TranscriptParagraphs.join(ls.compactMap { $0.dst != $0.src ? $0.dst : nil })
+ let src = TranscriptParagraphs.joinFixed(ls)
+ let dst = TranscriptParagraphs.join(ls.compactMap { $0.dst != $0.src && $0.dst != $0.shown ? $0.dst : nil })
+ let fixed = ls.flatMap { l in (l.fixes ?? []).filter(\.applied).map { (l.id, $0) } }
return HStack(alignment: .top, spacing: 12) {
Text(NotesEngine.clock(l.t)).font(.system(size: 12, weight: isMatch ? .semibold : .regular).monospacedDigit())
.foregroundStyle(latest || isMatch ? Palette.accentInk : Palette.tertiary)
@@ -787,6 +797,12 @@ struct TranscriptListView<Partial: View>: View, Equatable {
Text(highlighted(dst, current: isMatch)).font(.system(size: 13)).foregroundStyle(Palette.secondary)
.lineSpacing(2).textSelection(.enabled)
}
+ // 改正听错的词: pointing at the paragraph shows what each fixed word was heard as.
+ // The line being said is shown open too: hover in the notes panel, which never takes
+ // focus, is not to be counted on.
+ if hovered == l.id || revealFixes || latest, !fixed.isEmpty, let onRevert {
+ FixedWords(fixes: fixed, onRevert: onRevert).padding(.top, 2)
+ }
if assigning == l.id, let onAssign {
LineSpeakerPicker(voices: voices, current: l.voice.flatMap { voices[$0] != nil ? $0 : nil },
nearby: nearby(ls), several: ls.count > 1) { v in
@@ -805,6 +821,9 @@ struct TranscriptListView<Partial: View>: View, Equatable {
: marked != nil && ls.contains(where: { $0.voice == marked }) ? SpeakerColor.ink(voices[marked!] ?? 1).opacity(0.07)
: Color.clear))
.opacity(dim ? 0.5 : 1)
+ .onHover { inside in
+ if inside { hovered = l.id } else if hovered == l.id { hovered = nil }
+ }
}
}
@@ -849,6 +868,29 @@ enum TranscriptParagraphs {
return out
}
+ /// The lines as shown, each fixed word with a dotted underline.
+ static func joinFixed(_ lines: [TranscriptLine]) -> AttributedString {
+ var out = AttributedString()
+ var plain = ""
+ for l in lines {
+ let (text, marks) = Correction.apply(l.fixes ?? [], to: l.src)
+ let p = text.trimmingCharacters(in: .whitespaces)
+ guard !p.isEmpty else { continue }
+ if let last = plain.unicodeScalars.last, !(last.properties.isIdeographic || "。!?,、;:”)".unicodeScalars.contains(last)) {
+ out += AttributedString(" ")
+ plain += " "
+ }
+ var a = AttributedString(text)
+ for m in marks {
+ guard let lo = AttributedString.Index(m.lowerBound, within: a), let hi = AttributedString.Index(m.upperBound, within: a) else { continue }
+ a[lo..<hi].underlineStyle = Text.LineStyle(pattern: .dot, color: Palette.tertiary)
+ }
+ out += a
+ plain += text
+ }
+ return out
+ }
+
/// Sentences side by side: a space between words, none after Chinese or Japanese.
static func join(_ parts: [String]) -> String {
var out = ""
@@ -1364,3 +1406,66 @@ struct MeetingEndingStrip: View {
.onReceive(tick) { now = $0 }
}
}
+
+
+/// Under a paragraph being pointed at: each fixed word, what it was heard as, and 改回.
+struct FixedWords: View {
+ let fixes: [(line: String, fix: LineFix)]
+ let onRevert: (String, LineFix) -> Void
+
+ var body: some View {
+ FlowLayout(spacing: 6) {
+ ForEach(Array(fixes.enumerated()), id: \.offset) { _, item in
+ let c = Correction.core(item.fix.from, item.fix.to)
+ HStack(spacing: 6) {
+ (Text("听成").foregroundStyle(Palette.tertiary) + Text(" " + c.from) + Text(" → ").foregroundStyle(Palette.tertiary) + Text(c.to))
+ .font(.system(size: 11))
+ Button(L("改回")) { onRevert(item.line, item.fix) }
+ .buttonStyle(.plain).font(.system(size: 11, weight: .medium)).foregroundStyle(Palette.link)
+ }
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .background(RoundedRectangle(cornerRadius: 6).fill(Palette.fill))
+ }
+ }
+ }
+}
+
+/// 这样改对吗?: a name the Mac couldn't check by sound, asked about once. Clicks only: the notes
+/// window never takes focus. 对 fixes every line waiting on it and adds it to the word list.
+struct FixConfirmCard: View {
+ let line: TranscriptLine
+ let fix: LineFix
+ let count: Int
+ let onAnswer: (Bool) -> Void
+
+ var body: some View {
+ let c = Correction.core(fix.from, fix.to)
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text("这样改对吗?").font(.system(size: 13, weight: .semibold))
+ Text("确认后整场一起改,以后也照此改").font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineLimit(1)
+ Spacer(minLength: 4)
+ if count > 1 { Text("1 / \(count)").font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.tertiary) }
+ }
+ HStack(spacing: 8) {
+ VStack(alignment: .leading, spacing: 2) {
+ (Text(c.from) + Text(" → ").foregroundStyle(Palette.tertiary) + Text(c.to).bold()).font(.system(size: 14))
+ Text("\(NotesEngine.clock(line.t)) · \(line.src)").font(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(1)
+ }
+ Spacer(minLength: 4)
+ Button { onAnswer(true) } label: {
+ Text("对").font(.system(size: 13, weight: .medium)).foregroundStyle(.white)
+ .padding(.horizontal, 14).frame(height: 28).background(RoundedRectangle(cornerRadius: 7).fill(Palette.ink))
+ }.buttonStyle(.plain)
+ Button { onAnswer(false) } label: {
+ Text("不对").font(.system(size: 13)).foregroundStyle(Palette.secondary)
+ .padding(.horizontal, 14).frame(height: 28).background(RoundedRectangle(cornerRadius: 7).fill(Palette.fill))
+ }.buttonStyle(.plain)
+ }
+ }
+ .padding(.horizontal, 12).padding(.vertical, 10)
+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.black.opacity(0.08), lineWidth: 1))
+ .shadow(color: .black.opacity(0.08), radius: 10, y: 4)
+ }
+}
diff --git a/Sources/Cicada/NotesWindow.swift b/Sources/Cicada/NotesWindow.swift
index 8d07c79..b6970a5 100644
--- a/Sources/Cicada/NotesWindow.swift
+++ b/Sources/Cicada/NotesWindow.swift
@@ -267,6 +267,9 @@ struct NotesWindowView: View {
meetingBar.padding(.horizontal, 24).padding(.bottom, 4)
banner.padding(.horizontal, 24).padding(.bottom, 4)
if live { liveAsks.padding(.horizontal, 24).padding(.bottom, 4) }
+ // 这样改对吗? above both tabs: the window opens on 纪要, where a card in the
+ // transcript would never be seen.
+ fixAsk.padding(.horizontal, 24).padding(.bottom, 4)
if live { LanguageNotice(model: model).padding(.horizontal, 24).padding(.bottom, 8) }
// Where the scrolling starts: a hairline, and each column fades in under it (`topFade`).
Rectangle().fill(MainWindowView.hairline).frame(height: 1)
@@ -480,7 +483,7 @@ struct NotesWindowView: View {
let terms = searchTerms
guard !terms.isEmpty else { return [] }
return (session?.lines ?? []).filter { l in
- terms.contains { l.src.localizedCaseInsensitiveContains($0) || (l.dst ?? "").localizedCaseInsensitiveContains($0) }
+ terms.contains { l.shown.localizedCaseInsensitiveContains($0) || (l.dst ?? "").localizedCaseInsensitiveContains($0) }
}.map(\.id)
}
@@ -889,6 +892,17 @@ struct NotesWindowView: View {
if animated { withAnimation(.easeInOut(duration: 0.4)) { proxy.scrollTo(id, anchor: .top) } } else { proxy.scrollTo(id, anchor: .top) }
}
+ @ViewBuilder private var fixAsk: some View {
+ if let s = session {
+ let waiting = model.fixes.pending(in: s.id)
+ if let first = waiting.first {
+ FixConfirmCard(line: first.line, fix: first.fix, count: waiting.count) { yes in
+ model.fixes.answer(first.fix, yes: yes, in: s.id)
+ }
+ }
+ }
+ }
+
private var transcript: some View {
let ms = matches
let lines = session?.lines ?? []
@@ -904,7 +918,8 @@ struct NotesWindowView: View {
identifying: model.identifyingLanguage,
voices: speakers.isEmpty ? [:] : SpeakerLabels.voiceNumbers(lines), marked: editingVoice,
places: RecordList.heardBoth(lines), settling: model.settling,
- onAssign: { ids, voice in if let s = session { model.assignLines(session: s.id, ids, to: voice) } }) {
+ onAssign: { ids, voice in if let s = session { model.assignLines(session: s.id, ids, to: voice) } },
+ onRevert: { lineID, fix in if let s = session { model.fixes.revert(fix, lineID: lineID, in: s.id) } }) {
LivePartialRow(model: model, startedAt: store.liveStart)
}
.equatable()
diff --git a/Sources/Cicada/SessionStore.swift b/Sources/Cicada/SessionStore.swift
index 2f9d0e1..76bad1e 100644
--- a/Sources/Cicada/SessionStore.swift
+++ b/Sources/Cicada/SessionStore.swift
@@ -17,6 +17,8 @@ struct TranscriptLine: Codable, Identifiable, Equatable {
var voice: Int? = nil
/// 电脑和会议室: "room" when the room mic heard it; absent for the Mac's audio (or older records).
var via: String? = nil
+ /// Words the AI service fixed (`Correction`); `src` stays what was heard. Absent when none.
+ var fixes: [LineFix]? = nil
}
/// A name Ling found for a voice, and the line it is based on ("00:06 “Sure, Emma…”").
@@ -337,6 +339,24 @@ final class SessionStore: ObservableObject {
scheduleSave(id)
}
+ /// A line's fixes (`Correction`): what the AI service proposed and the user decided.
+ func setFixes(in id: String, lineID: String, _ fixes: [LineFix]) {
+ guard let i = index(id), let j = sessions[i].lines.firstIndex(where: { $0.id == lineID }) else { return }
+ guard sessions[i].lines[j].fixes ?? [] != fixes else { return }
+ sessions[i].lines[j].fixes = fixes.isEmpty ? nil : fixes
+ scheduleSave(id)
+ }
+
+ /// The line a reply was for, by its text as heard: the newest such line in the live meeting,
+ /// else in a file being imported. Older meetings never: "好的。" is in all of them.
+ func lineHeard(as text: String) -> (session: String, line: TranscriptLine)? {
+ let ids = ([liveID].compactMap { $0 }) + sessions.filter { $0.importing == true }.map(\.id)
+ for id in ids {
+ if let s = session(id), let l = s.lines.last(where: { $0.src == text }) { return (id, l) }
+ }
+ return nil
+ }
+
func setTranslation(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].dst = text
@@ -458,8 +478,8 @@ enum TranscriptExport {
for l in s.lines {
// An imported file has no "other side" to name.
let who = s.sourceFile == nil ? " \(speakerName(l, numbers, names))" : ""
- out += "**[\(clock(l.t))]\(who)** \n\(l.src)\n"
- if let d = l.dst, d != l.src { out += "> \(d)\n" }
+ out += "**[\(clock(l.t))]\(who)** \n\(l.shown)\n"
+ if let d = l.dst, d != l.shown { out += "> \(d)\n" }
out += "\n"
}
return out
@@ -476,8 +496,8 @@ enum TranscriptExport {
let end = max(l.t + 1, min(next, l.t + 8))
// Your own lines (the talk key) say so, as the record does.
let tag = l.speaker == "me" ? "[\(L("同传"))] " : ""
- out += "\(i + 1)\n\(ts(l.t)) --> \(ts(end))\n\(tag)\(l.src)\n"
- if let d = l.dst, d != l.src { out += "\(d)\n" }
+ out += "\(i + 1)\n\(ts(l.t)) --> \(ts(end))\n\(tag)\(l.shown)\n"
+ if let d = l.dst, d != l.shown { out += "\(d)\n" }
out += "\n"
}
return out
@@ -524,8 +544,8 @@ 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(l.src, size: 11, after: 2)
- if let d = l.dst, d != l.src { add(d, size: 11, color: NSColor(calibratedWhite: 0.3, alpha: 1), after: 10) }
+ 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) }
}
return try doc.data(from: NSRange(location: 0, length: doc.length),
documentAttributes: [.documentType: NSAttributedString.DocumentType.officeOpenXML])
diff --git a/Sources/Cicada/Settings.swift b/Sources/Cicada/Settings.swift
index 224c122..b5fe293 100644
--- a/Sources/Cicada/Settings.swift
+++ b/Sources/Cicada/Settings.swift
@@ -194,6 +194,17 @@ final class AppSettings: ObservableObject {
didSet { save() }
}
+ /// 会中改正听错的词: finished sentences carry the word list to the AI service, which points out
+ /// misheard words (`Correction`). On by default; does nothing without an AI service.
+ @Published var fixMisheard: Bool {
+ didSet { save() }
+ }
+
+ /// 没见过的名字先问我: a new name is asked about once instead of left as heard.
+ @Published var askNames: Bool {
+ didSet { save() }
+ }
+
/// Record per-sentence timings (never text) and show the 诊断 tab. On by default in dev builds.
/// 听哪里: "system" (what the Mac plays), "room" (a real microphone, for a meeting in the room) or
/// "both" (电脑和会议室: people online and in the room, each heard on its own).
@@ -258,6 +269,8 @@ final class AppSettings: ObservableObject {
listenSource = ["room", "both"].contains(defaults.string(forKey: "listenSource")) ? defaults.string(forKey: "listenSource")! : "system"
diagnostics = defaults.object(forKey: "diagnostics") as? Bool ?? DevBuild.isDev
notesCapturable = defaults.bool(forKey: "notesCapturable")
+ fixMisheard = defaults.object(forKey: "fixMisheard") as? Bool ?? true
+ askNames = defaults.object(forKey: "askNames") as? Bool ?? true
// Off by default while it was an experiment, and save() stores every key, so a stored false
// mostly means "never touched": turn it on once for everyone when it became a regular feature.
if defaults.bool(forKey: "speakerVoicesRegular") {
@@ -312,6 +325,8 @@ final class AppSettings: ObservableObject {
defaults.set(diagnostics, forKey: "diagnostics")
defaults.set(notesCapturable, forKey: "notesCapturable")
defaults.set(speakerVoices, forKey: "speakerVoices")
+ defaults.set(fixMisheard, forKey: "fixMisheard")
+ defaults.set(askNames, forKey: "askNames")
}
/// Target language. "Follow system" translates into my language, or into the next system
diff --git a/Sources/Cicada/SpeakerID.swift b/Sources/Cicada/SpeakerID.swift
index 92f5a79..96b7d72 100644
--- a/Sources/Cicada/SpeakerID.swift
+++ b/Sources/Cicada/SpeakerID.swift
@@ -336,7 +336,7 @@ enum SpeakerNameGuess {
var out = "Meeting transcript. Speakers: 你 = the user; 说话人N = one person on the other side, told apart by voice; 对方 = someone on the other side, not identified.\n"
for (i, l) in lines.enumerated() {
let who = l.speaker == "me" ? "你" : numbers[l.id].map { "说话人\($0)" } ?? "对方"
- out += "[L\(i + 1) \(TranscriptExport.clock(l.t)) \(who)] \(l.src)\n"
+ out += "[L\(i + 1) \(TranscriptExport.clock(l.t)) \(who)] \(l.shown)\n"
}
return out
}
@@ -393,7 +393,7 @@ enum SpeakerNameGuess {
out[other] = nil
}
let l = lines[i]
- let evidence = "\(TranscriptExport.clock(l.t)) “\(l.src.count > 60 ? String(l.src.prefix(60)) + "…" : l.src)”"
+ let evidence = "\(TranscriptExport.clock(l.t)) “\(l.shown.count > 60 ? String(l.shown.prefix(60)) + "…" : l.shown)”"
out[v] = VoiceGuess(name: name, evidence: evidence)
}
return (out, refuted)
@@ -405,7 +405,7 @@ enum SpeakerNameGuess {
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 }
+ guard let i = s.lines.firstIndex(where: { TranscriptExport.clock($0.t) == clock && $0.shown.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 }
}
diff --git a/Sources/Cicada/SpeakerViews.swift b/Sources/Cicada/SpeakerViews.swift
index 68af518..804558a 100644
--- a/Sources/Cicada/SpeakerViews.swift
+++ b/Sources/Cicada/SpeakerViews.swift
@@ -347,7 +347,7 @@ struct SpeakerPreview: View {
} else if l.speaker == "me" { MeTag() }
else if let n = numbers[l.id] { SpeakerTag(number: n) }
else if !numbers.isEmpty { UnknownSpeakerTag() }
- Text(l.src).font(.system(size: 13)).foregroundStyle(Palette.ink)
+ Text(l.shown).font(.system(size: 13)).foregroundStyle(Palette.ink)
}
}
}
diff --git a/Sources/Cicada/Translator.swift b/Sources/Cicada/Translator.swift
index 5a4aff1..2539b7d 100644
--- a/Sources/Cicada/Translator.swift
+++ b/Sources/Cicada/Translator.swift
@@ -94,6 +94,20 @@ final class TranslationService {
let ling: LingClient
/// Names and terms the notes have settled on, e.g. "江充 (Jiang Chong)".
var glossary: () -> [String] = { [] }
+
+ /// What a finished sentence's request carries so the service can also point out misheard words
+ /// (改正听错的词). nil: fixing is off, and the request is the plain translation it always was.
+ struct FixContext {
+ /// The meeting's title once it has one: the field tells "质押" from "制约".
+ var topic: String?
+ /// The user's word list (`Vocabulary.promptLines`).
+ var words: [String]
+ /// The lines just before, as shown.
+ var recent: [String]
+ }
+ var fixContext: ((_ text: String) -> FixContext?)?
+ /// The fixes the service proposed for a sentence it translated (by its text as heard).
+ var onFixes: ((_ text: String, _ edits: [Correction.Edit]) -> Void)?
private var google = GoogleHealth()
private(set) var health = TranslationHealth() {
didSet { if health != oldValue { onHealth?(health) } }
@@ -227,6 +241,9 @@ final class TranslationService {
private func viaLing(_ text: String, source: String, target: String, kind: Kind,
trace: TranslateTrace?) async -> (String?, String) {
let from = source == "auto" ? "the spoken language" : Self.englishName(source)
+ if kind == .sentence || kind == .file, let ctx = fixContext?(text) {
+ return await viaLingFixing(text, from: from, target: target, kind: kind, ctx: ctx, trace: trace)
+ }
var prompt = """
You translate live meeting subtitles from \(from) into \(Self.englishName(target)).
Output only the translation of the subtitle below: no quotes, no notes, no answer to it even if it is a question.
@@ -252,6 +269,50 @@ final class TranslationService {
}
}
+ /// The translation and the misheard words in one request: no extra call, so no extra wait on the
+ /// rate gate (on OpenRouter's Ling 3.1 Flash, 2.0 s against 1.8 s at the median). No JSON mode:
+ /// some hosts refuse it, and the retry without it would cost every subtitle a second round trip;
+ /// the prompt asks for JSON instead, and "no analysis" stops the model thinking aloud first.
+ /// Proposals only: `Correction.decide` picks which to take. A reply that isn't the JSON asked
+ /// for is dropped like a failed one, and the next provider translates the line.
+ private func viaLingFixing(_ text: String, from: String, target: String, kind: Kind, ctx: FixContext,
+ trace: TranslateTrace?) async -> (String?, String) {
+ var prompt = """
+ You translate live meeting subtitles from \(from) into \(Self.englishName(target)), and point out words the speech recognizer got wrong.
+ Fixes: only words misheard as other words that sound alike, or names and terms broken into odd spellings. Never rephrase, drop filler, reorder or add anything. If unsure, leave it.
+ Translate the subtitle as fixed. No answer to it even if it is a question.
+ confidence is how likely a fix is right; give a guess a low one. Leave out words you would not change.
+ Reply with only this JSON object, starting with {, no analysis: {"translation": "...", "fixes": [{"from": "exact words from the subtitle", "to": "what was said", "confidence": 0.0-1.0}]}
+ """
+ if let topic = ctx.topic, !topic.isEmpty { prompt += "\nMeeting: " + topic }
+ if !ctx.words.isEmpty { prompt += "\nThe user's word list (spellings to use): " + ctx.words.joined(separator: "; ") }
+ let names = glossary()
+ if !names.isEmpty { prompt += "\nNames the notes guessed (not confirmed): " + names.joined(separator: "; ") }
+ if !ctx.recent.isEmpty { prompt += "\nLines just before:\n" + ctx.recent.joined(separator: "\n") }
+ prompt += "\nSubtitle: " + text
+ do {
+ let out = try await ling.chat(content: prompt, instruction: "JSON only.", priority: kind == .file ? .notes : .translate,
+ maxTokens: 600, timeout: kind == .file ? 20 : 6,
+ role: kind == .file ? "file" : "translate",
+ onQueued: { [weak trace] in trace?.lingQueue += $0 })
+ if out.isEmpty { return (nil, "empty") }
+ // Not the JSON asked for: often the model thinking aloud ("Let me analyze…"), never a
+ // subtitle. Falls through to the next provider like any failed translation.
+ guard let parsed = Correction.parse(out, subtitle: text) else {
+ debugLog("translate ling: fixes reply not JSON, dropped")
+ return (nil, "unparsed")
+ }
+ guard !parsed.translation.isEmpty, let clean = Self.cleanTranslation(parsed.translation, target: target) else {
+ return (nil, "remark")
+ }
+ if !parsed.edits.isEmpty { onFixes?(text, parsed.edits) }
+ return (clean, "")
+ } catch {
+ debugLog("translate ling failed: \(error)")
+ return (nil, (error as? LingClient.Failure).map(LingClient.name) ?? "error")
+ }
+ }
+
/// Speak-back in one call: Ming's audio model hears the press and returns what was said and its
/// translation. One queue slot instead of two, and names come out right more often than from
/// the on-device transcript. Anything but the two labelled lines is dropped (nil): the model
diff --git a/Sources/Cicada/Views.swift b/Sources/Cicada/Views.swift
index fc42103..a5c8168 100644
--- a/Sources/Cicada/Views.swift
+++ b/Sources/Cicada/Views.swift
@@ -806,7 +806,7 @@ struct MainWindowView: View {
guard !query.isEmpty else { return store.sessions }
return store.sessions.filter { s in
s.displayTitle.localizedCaseInsensitiveContains(query)
- || s.lines.contains { $0.src.localizedCaseInsensitiveContains(query) || ($0.dst ?? "").localizedCaseInsensitiveContains(query) }
+ || s.lines.contains { $0.shown.localizedCaseInsensitiveContains(query) || ($0.dst ?? "").localizedCaseInsensitiveContains(query) }
}
}
@@ -1285,7 +1285,7 @@ struct MainWindowView: View {
} else if let speaker { SpeakerTag(number: speaker).padding(.bottom, 2) }
else if voices, l.speaker != "me" { UnknownSpeakerTag().padding(.bottom, 2) }
else if l.speaker == "me" { MeTag().padding(.bottom, 2) }
- Text(l.src).font(.system(size: 12)).foregroundStyle(Palette.secondary).lineSpacing(1)
+ Text(l.shown).font(.system(size: 12)).foregroundStyle(Palette.secondary).lineSpacing(1)
.textSelection(.enabled)
Text(l.dst ?? L("翻译中…")).font(.system(size: 14)).lineSpacing(2)
.foregroundStyle(l.dst == nil ? Palette.secondary : Palette.ink)
@@ -1391,7 +1391,7 @@ struct MainWindowView: View {
if place, label, !me { PlaceTag(line: l) }
}
if view != "dst" {
- Text(l.src)
+ Text(l.shown)
.font(.system(size: view == "src" ? 15 : 13))
.foregroundStyle(view == "src" ? Palette.ink : Palette.tertiary)
.lineSpacing(2)
diff --git a/Sources/Cicada/Vocabulary.swift b/Sources/Cicada/Vocabulary.swift
new file mode 100644
index 0000000..5a63752
--- /dev/null
+++ b/Sources/Cicada/Vocabulary.swift
@@ -0,0 +1,148 @@
+import Foundation
+
+/// 词表: the spellings the user stands behind, and how speech recognition has misheard each. Only
+/// these let a new name be fixed without asking: names the notes guess are often wrong (in a test
+/// meeting 6 of 10, e.g. 巡检 → "audit"), so they stay suggestions until the user confirms one.
+/// One JSON file beside the records; not a secret, so not one of the 0600 key files.
+@MainActor
+final class Vocabulary: ObservableObject {
+ struct Term: Codable, Equatable {
+ var word: String
+ /// Wrong forms the recognizer produced, as confirmed or typed by the user.
+ var heard: [String] = []
+ /// "user" (added or imported), "live" (confirmed during a meeting).
+ var source: String
+ var fixes: Int = 0
+ var used: Date? = nil
+ }
+
+ /// More would make every sentence's request long, and more terms means more wrong swaps.
+ static let limit = 300
+
+ @Published private(set) var terms: [Term] = []
+ private let url: URL?
+ var onChange: (() -> Void)?
+
+ init(url: URL?) {
+ self.url = url
+ if let url, let data = try? Data(contentsOf: url),
+ let saved = try? JSONDecoder.vocabulary.decode([Term].self, from: data) {
+ terms = saved
+ }
+ }
+
+ static var defaultURL: URL {
+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent(DevBuild.supportFolder).appendingPathComponent("vocabulary.json")
+ }
+
+ /// Same word whatever its width, case or spacing ("AAVE" is "aave").
+ nonisolated static func key(_ s: String) -> String {
+ s.precomposedStringWithCompatibilityMapping.lowercased()
+ .split(whereSeparator: \.isWhitespace).joined(separator: " ")
+ }
+
+ func knows(heard: String, word: String) -> Bool {
+ let h = Self.key(heard), w = Self.key(word)
+ return terms.contains { Self.key($0.word) == w && $0.heard.contains { Self.key($0) == h } }
+ }
+
+ /// The user said yes to a fix (or added it): the word, and the form it was heard as.
+ func confirm(heard: String, word: String, source: String = "live") {
+ let w = Self.key(word)
+ if let i = terms.firstIndex(where: { Self.key($0.word) == w }) {
+ if !heard.isEmpty, !terms[i].heard.contains(where: { Self.key($0) == Self.key(heard) }) { terms[i].heard.append(heard) }
+ } else {
+ terms.append(Term(word: word, heard: heard.isEmpty ? [] : [heard], source: source))
+ }
+ save()
+ }
+
+ /// A heard form the user turned down twice stops being one.
+ func forget(heard: String, word: String) {
+ let w = Self.key(word), h = Self.key(heard)
+ guard let i = terms.firstIndex(where: { Self.key($0.word) == w }) else { return }
+ terms[i].heard.removeAll { Self.key($0) == h }
+ save()
+ }
+
+ func remove(_ word: String) {
+ terms.removeAll { Self.key($0.word) == Self.key(word) }
+ save()
+ }
+
+ func used(_ word: String, at date: Date = Date()) {
+ guard let i = terms.firstIndex(where: { Self.key($0.word) == Self.key(word) }) else { return }
+ terms[i].fixes += 1
+ terms[i].used = date
+ save()
+ }
+
+ /// For the request: the most recently useful first, "Morpho (heard as 莫拉, 莫法)".
+ func promptLines() -> [String] {
+ terms.sorted { ($0.used ?? .distantPast) > ($1.used ?? .distantPast) }.prefix(Self.limit).map {
+ $0.heard.isEmpty ? $0.word : "\($0.word) (heard as \($0.heard.joined(separator: ", ")))"
+ }
+ }
+
+ /// 粘贴导入: one per line, heard forms after "=" ("Morpho = 莫拉、莫法"). Lines too long or empty
+ /// are reported by number; a word already there gains the new heard forms.
+ struct ImportResult: Equatable { var added = 0; var updated = 0; var skipped: [Int] = [] }
+
+ nonisolated static func parse(_ text: String) -> [(line: Int, word: String, heard: [String])?] {
+ text.components(separatedBy: .newlines).enumerated().compactMap { i, raw in
+ let line = raw.trimmingCharacters(in: .whitespaces)
+ if line.isEmpty { return nil }
+ let parts = line.split(separator: "=", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }
+ let word = parts[0]
+ let heard = parts.count > 1
+ ? parts[1].split(whereSeparator: { "、,,;;".contains($0) }).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
+ : []
+ guard !word.isEmpty, word.count <= 40, !word.contains(where: { $0.isNewline || $0.unicodeScalars.contains { $0.properties.generalCategory == .control } }) else {
+ return (i + 1, "", [])
+ }
+ return (i + 1, word, heard)
+ }
+ }
+
+ func importText(_ text: String) -> ImportResult {
+ var r = ImportResult()
+ for case let entry? in Self.parse(text) {
+ if entry.word.isEmpty { r.skipped.append(entry.line); continue }
+ let w = Self.key(entry.word)
+ if let i = terms.firstIndex(where: { Self.key($0.word) == w }) {
+ for h in entry.heard where !terms[i].heard.contains(where: { Self.key($0) == Self.key(h) }) { terms[i].heard.append(h) }
+ r.updated += 1
+ } else {
+ terms.append(Term(word: entry.word, heard: entry.heard, source: "user"))
+ r.added += 1
+ }
+ }
+ save()
+ return r
+ }
+
+ private func save() {
+ onChange?()
+ guard let url else { return }
+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ if let data = try? JSONEncoder.vocabulary.encode(terms) { try? data.write(to: url, options: .atomic) }
+ }
+}
+
+private extension JSONEncoder {
+ static var vocabulary: JSONEncoder {
+ let e = JSONEncoder()
+ e.dateEncodingStrategy = .iso8601
+ e.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
+ return e
+ }
+}
+
+private extension JSONDecoder {
+ static var vocabulary: JSONDecoder {
+ let d = JSONDecoder()
+ d.dateDecodingStrategy = .iso8601
+ return d
+ }
+}
diff --git a/Tests/CicadaTests/CorrectionTests.swift b/Tests/CicadaTests/CorrectionTests.swift
new file mode 100644
index 0000000..0b220a4
--- /dev/null
+++ b/Tests/CicadaTests/CorrectionTests.swift
@@ -0,0 +1,116 @@
+import Foundation
+import Testing
+@testable import Cicada
+
+/// Cases from a 21-minute meeting recording (a DeFi team's weekly), labelled by reading the context.
+@Suite struct CorrectionTests {
+ private func verdict(_ from: String, _ to: String, _ c: Double, known: [(String, String)] = [],
+ rejected: [(String, String)] = []) -> Correction.Verdict {
+ Correction.decide(.init(from: from, to: to, confidence: c),
+ known: { a, b in known.contains { $0 == (a, b) } },
+ rejected: { a, b in rejected.contains { $0 == (a, b) } })
+ }
+
+ @Test func soundAlikeChineseIsApplied() {
+ #expect(verdict("解除质压", "解除质押", 0.9) == .apply)
+ #expect(verdict("跳便是", "跳变", 0.9) != .apply) // a word dropped: not a sound fix
+ #expect(verdict("两个代笔", "两个代币", 0.9) == .apply)
+ #expect(verdict("管理房", "管理方", 0.9) == .apply)
+ #expect(verdict("追压", "质押", 0.85) == .apply)
+ // Only the changed part is compared: 花/概 share nothing, though the phrase around them does.
+ #expect(verdict("花了大花", "花了大概", 0.85) == .drop)
+ #expect(verdict("FFT制押", "FFT质押", 0.9) == .apply)
+ }
+
+ @Test func confidentButUnlikeSoundIsDropped() {
+ #expect(verdict("快销", "区块", 0.85) == .drop)
+ #expect(verdict("苍蝇", "方向", 0.85) == .drop)
+ #expect(verdict("机录", "机会", 0.8) == .drop)
+ }
+
+ @Test func lowConfidenceIsDropped() {
+ #expect(verdict("质压", "质押", 0.5) == .drop)
+ }
+
+ @Test func spellingFixNeedsHighConfidence() {
+ #expect(verdict("cransfer", "transfer", 0.85) == .apply)
+ #expect(verdict("cransfer", "transfer", 0.7) == .drop)
+ #expect(verdict("bos", "BOS", 0.9) == .drop) // case only
+ }
+
+ @Test func newNamesAreAsked() {
+ #expect(verdict("莫拉", "Morpho", 0.85) == .ask)
+ #expect(verdict("开布特", "Curve", 0.8) == .ask)
+ #expect(verdict("Ero", "Euler", 0.85) == .ask)
+ #expect(verdict("莫纳", "Morpho", 0.7) == .drop)
+ }
+
+ @Test func confirmedHeardFormIsApplied() {
+ #expect(verdict("莫拉", "Morpho", 0.5, known: [("莫拉", "Morpho")]) == .apply)
+ #expect(verdict("解释这个莫拉的", "解释这个Morpho的", 0.5, known: [("莫拉", "Morpho")]) == .apply)
+ }
+
+ @Test func rejectedIsDropped() {
+ #expect(verdict("质压", "质押", 0.95, rejected: [("质压", "质押")]) == .drop)
+ #expect(verdict("莫拉", "Morpho", 0.95, known: [("莫拉", "Morpho")], rejected: [("莫拉", "Morpho")]) == .drop)
+ }
+
+ @Test func coreDropsSharedEnds() {
+ #expect(Correction.core("解除质压", "解除质押") == ("质压", "质押"))
+ #expect(Correction.core("Un450P三", "Uniswap V3") == ("Un450P三", "Uniswap V3"))
+ #expect(Correction.core("解释这个莫拉的", "解释这个Morpho的") == ("莫拉", "Morpho"))
+ #expect(Correction.core("找了cransfer记录", "找了transfer记录") == ("cransfer", "transfer"))
+ // A Chinese change next to a Latin word leaves the word out.
+ #expect(Correction.core("FFT制押", "FFT质押") == ("制押", "质押"))
+ #expect(Correction.core("Un450P三", "Uniswap V3") == ("Un450P三", "Uniswap V3"))
+ }
+
+ @Test func applyReplacesAndMarks() {
+ let fixes = [LineFix(from: "莫拉", to: "Morpho"), LineFix(from: "质压", to: "质押"),
+ LineFix(from: "开布特", to: "Curve", ask: true), LineFix(from: "ropax", to: "RoPax", off: true)]
+ let (text, marks) = Correction.apply(fixes, to: "解释这个莫拉的,质压和开布特,ropax")
+ #expect(text == "解释这个Morpho的,质押和开布特,ropax")
+ #expect(marks.map { String(text[$0]) } == ["Morpho", "质押"])
+ }
+
+ @Test func applyKeepsEarlierMarksWhenLaterFixesShift() {
+ let (text, marks) = Correction.apply([LineFix(from: "质压", to: "质押"), LineFix(from: "莫拉", to: "Morpho")],
+ to: "莫拉说质压")
+ #expect(text == "Morpho说质押")
+ #expect(marks.map { String(text[$0]) } == ["Morpho", "质押"])
+ }
+
+ @Test func fixWhoseWordsWentAwayIsSkipped() {
+ // The record recognizer rewrote the line: the fix no longer applies, nothing breaks.
+ #expect(Correction.apply([LineFix(from: "莫拉", to: "Morpho")], to: "解释这个摩托的").text == "解释这个摩托的")
+ }
+
+ @Test func parseReply() {
+ let reply = """
+ {"translation": "I explained Morpho.", "fixes": [{"from": "莫拉", "to": "Morpho", "confidence": 0.85},
+ {"from": "不在原文", "to": "x", "confidence": 0.9}]}
+ """
+ let p = Correction.parse(reply, subtitle: "解释这个莫拉的。")
+ #expect(p?.translation == "I explained Morpho.")
+ #expect(p?.edits == [.init(from: "莫拉", to: "Morpho", confidence: 0.85)])
+ #expect(Correction.parse("I explained Mora.", subtitle: "x") == nil)
+ #expect(Correction.parse("```json\n{\"translation\": \"Hi\"}\n```", subtitle: "x")?.translation == "Hi")
+ }
+
+ @Test func mergeKeepsRefusals() {
+ let old = [LineFix(from: "莫拉", to: "Morpho", off: true), LineFix(from: "质压", to: "质押")]
+ let new = [LineFix(from: "莫拉", to: "Morpho"), LineFix(from: "寻检", to: "巡检")]
+ #expect(Correction.merge(old, new) == [LineFix(from: "莫拉", to: "Morpho", off: true), LineFix(from: "寻检", to: "巡检")])
+ }
+
+ @Test func recordFormatUnchangedWithoutFixes() throws {
+ let line = TranscriptLine(id: "1", t: 0, speaker: "them", src: "a", dst: nil, srcLang: "zh", dstLang: "en")
+ let json = String(data: try JSONEncoder().encode(line), encoding: .utf8)!
+ #expect(!json.contains("fixes"))
+ var fixed = line
+ fixed.fixes = [LineFix(from: "a", to: "b")]
+ let back = try JSONDecoder().decode(TranscriptLine.self, from: JSONEncoder().encode(fixed))
+ #expect(back.shown == "b")
+ #expect(back.src == "a")
+ }
+}
diff --git a/Tests/CicadaTests/VocabularyTests.swift b/Tests/CicadaTests/VocabularyTests.swift
new file mode 100644
index 0000000..53d3501
--- /dev/null
+++ b/Tests/CicadaTests/VocabularyTests.swift
@@ -0,0 +1,45 @@
+import Foundation
+import Testing
+@testable import Cicada
+
+@MainActor @Suite struct VocabularyTests {
+ @Test func importLinesWithHeardForms() {
+ let v = Vocabulary(url: nil)
+ let r = v.importText("Uniswap V3\nMorpho = 莫拉、莫法\n\n" + String(repeating: "长", count: 41) + "\n巡检=寻检,巡练")
+ #expect(r == .init(added: 3, updated: 0, skipped: [4]))
+ #expect(v.knows(heard: "莫法", word: "morpho"))
+ #expect(v.terms.first { $0.word == "巡检" }?.heard == ["寻检", "巡练"])
+ }
+
+ @Test func sameWordWhateverWidthOrCase() {
+ let v = Vocabulary(url: nil)
+ _ = v.importText("Aave")
+ let r = v.importText("AAVE = 阿韦")
+ #expect(r.updated == 1 && r.added == 0)
+ #expect(v.terms.count == 1)
+ #expect(v.knows(heard: "阿韦", word: "Aave"))
+ }
+
+ @Test func confirmAndForget() {
+ let v = Vocabulary(url: nil)
+ v.confirm(heard: "开布特", word: "Curve")
+ #expect(v.terms == [.init(word: "Curve", heard: ["开布特"], source: "live")])
+ v.forget(heard: "开布特", word: "Curve")
+ #expect(!v.knows(heard: "开布特", word: "Curve"))
+ }
+
+ @Test func promptPutsRecentFirst() {
+ let v = Vocabulary(url: nil)
+ _ = v.importText("A\nB = b")
+ v.used("B", at: Date(timeIntervalSince1970: 100))
+ #expect(v.promptLines() == ["B (heard as b)", "A"])
+ }
+
+ @Test func savesAndLoads() throws {
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("vocab-\(UUID().uuidString).json")
+ defer { try? FileManager.default.removeItem(at: url) }
+ let v = Vocabulary(url: url)
+ _ = v.importText("Morpho = 莫拉")
+ #expect(Vocabulary(url: url).knows(heard: "莫拉", word: "Morpho"))
+ }
+}
diff --git a/ios/shared-sources.txt b/ios/shared-sources.txt
index fc31dc9..3a14eb5 100644
--- a/ios/shared-sources.txt
+++ b/ios/shared-sources.txt
@@ -10,6 +10,7 @@ Sources/Cicada/MeetingEnd.swift
Sources/Cicada/Localization.swift
Sources/Cicada/Voices.swift
Sources/Cicada/SessionStore.swift
+Sources/Cicada/Correction.swift
Sources/Cicada/SpeakerID.swift
Sources/Cicada/AudioFiles.swift
Sources/Cicada/Translator.swift
diff --git a/site/changelog.json b/site/changelog.json
index 15f1bc0..2455789 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -13,6 +13,14 @@
],
"title": "会议刚开始时,文字记录不再把几个人说的话挤成一段。",
"text": "说话人编号要等两个声音各说够 5 句才出现,在那之前所有的话都算同一个人,半分钟内的问答会并成一大段。现在只要听出前后两句是不同的声音,就分成两段;编号出来后照旧标上说话人。"
+ },
+ {
+ "kind": "new",
+ "platforms": [
+ "mac"
+ ],
+ "title": "开会时听错的人名和术语,字幕和纪要里当场就改对(需要 AI 服务)。",
+ "text": "每句话说完,翻译时顺带找出听错的词:读音相近的错字(质压 → 质押)直接改,没见过的名字(莫拉 → Morpho)先在纪要窗口问一次“这样改对吗?”,答“对”以后就自动改。改过的词带虚线,指着这段话能看到原来听成什么,点“改回”就恢复。导出和纪要用改后的文字,记录里仍留着原来听到的。"
}
]
},