知了 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: generate live meeting notes with Ling and keep them with the session
wquguruf62f15011c54
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e01ae1b..26ff99e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ the release workflow publishes it as the release notes.- New: a sound test for the virtual microphone: the app plays a sentence into it, listens back and shows what the room will hear.- New: a settings window with a sidebar (听 / 我说话也翻译 / 字幕条 / 会议记录) replaces the settings sheet; the virtual microphone is set up from a three-step checklist there and in the first-run guide.- Changed: hold the right ⌥ key on its own to talk, instead of ⌥ Space (which other apps' launchers often use, and which types a space). Pressing another key while holding it cancels, so ⌥ + letter still types. It needs the "输入监控" permission; the app asks for it.+- New: live meeting notes. With a key, Ling updates the notes about every 45 s while the meeting runs (summary, topics with key points, a fishbone diagram where causes are discussed, conclusions and to-dos with how many lines back them, names and terms with their misrecognised forms) and rewrites them once over the whole transcript when it ends. Notes are saved with the meeting.- New: with a key, finished sentences and speak-back are translated by Ling (names kept consistent through the notes' glossary); if Ling is busy or fails, that sentence falls back to Google, then to Apple's on-device translation. Partial text while someone is still talking stays on Google.- New: Settings › AI 服务 takes your own Ling (ant-ling.com) API key. It is kept in the macOS Keychain, checked with a one-token request, and shown masked; without a key everything works as before.- New: both shortcuts (talk, hide/show the subtitle bar) can be changed in settings: click and press new keys. Combinations without ⌃ or ⌘, system shortcuts and ones another app already uses are refused with a reason.diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex 67b50b2..f84f84e 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -37,6 +37,7 @@ final class AppModel: ObservableObject {let installer = VirtualMicInstaller()let ling = LingClient()lazy var translator = TranslationService(ling: ling)+ lazy var notes = NotesEngine(ling: ling, store: store)let sample = SamplePlayer()var openOnboarding: (() -> Void)?@@ -67,6 +68,13 @@ final class AppModel: ObservableObject {ling.model = { [weak self] in self?.settings.aiModel ?? "Ling-3.1-flash" }listen.translator = translator+ translator.glossary = { [weak self] in self?.notes.glossary ?? [] }+ notes.language = {+ // The app speaks Chinese, so notes do too when Chinese is among the system languages.+ let prefs = Locale.preferredLanguages+ let pick = prefs.first(where: { $0.hasPrefix("zh") }) ?? prefs.first ?? "zh-Hans"+ return TranslationService.englishName(translationCode(forSystemLanguage: pick))+ }if ling.hasKey { Task { await ling.check() } }installer.speakThrough = { [weak self] text, lang, device in@@ -210,6 +218,7 @@ final class AppModel: ObservableObject {speak.setRecording(store.micAudioURL(session.id))}listen.start()+ notes.begin(session.id)if listen.isRunning {overlay.show()} else {@@ -223,6 +232,7 @@ final class AppModel: ObservableObject {listen.router.setRecording(nil)speak.setRecording(nil)store.end()+ notes.finish()overlay.hide()refresh()}@@ -447,6 +457,9 @@ final class AppModel: ObservableObject {// Dev testing: the key comes from a file so it never passes through the log.if let k = try? String(contentsOfFile: arg, encoding: .utf8) { Task { await ling.setKey(k) } }case "aiCheck": Task { await ling.check() }+ case "notesNow": notes.updateNow()+ case "notesReplay": Task { await notes.replay(arg) }+ case "notesState": debugLog("notes state=\(notes.state) topics=\(notes.notes.topics.count) covered=\(notes.notes.covered) glossary=\(notes.glossary.count)")case "lingSimulate":ling.simulate = ["429": .rateLimited, "hijack": .hijacked, "timeout": .timeout][arg]debugLog("ling simulate=\(String(describing: ling.simulate))")diff --git a/Sources/LiveSubs/Notes.swift b/Sources/LiveSubs/Notes.swiftnew file mode 100644index 0000000..9dd4cad--- /dev/null+++ b/Sources/LiveSubs/Notes.swift@@ -0,0 +1,329 @@+import Foundation++// MARK: - Model++/// Meeting notes kept with the session (`session.json` › `notes`). Written by Ling while the+/// meeting runs ("速记版") and rewritten once over the whole transcript when it ends ("完整版").+struct MeetingNotes: Codable, Equatable {+ var summary = ""+ var topics: [NoteTopic] = []+ var conclusions: [NoteItem] = []+ var todos: [NoteItem] = []+ var terms: [NoteTerm] = []+ /// How many transcript lines these notes cover.+ var covered = 0+ var updatedAt: Date?+ var final = false++ var isEmpty: Bool { summary.isEmpty && topics.isEmpty }+}++struct NoteTopic: Codable, Equatable, Identifiable {+ var start: Double+ var title: String+ var summary: String+ var points: [String]+ var fishbone: Fishbone?+ var id: String { "\(Int(start))-\(title)" }+}++/// A cause-and-effect diagram for a topic that discusses why something happened.+struct Fishbone: Codable, Equatable {+ var question: String+ var branches: [FishboneBranch]+}++struct FishboneBranch: Codable, Equatable, Identifiable {+ var label: String+ var detail: String+ var t: Double?+ /// How many transcript lines back this branch; 0–1 is shown as weak.+ var support: Int+ var id: String { label + detail }+}++struct NoteItem: Codable, Equatable, Identifiable {+ var text: String+ var owner: String?+ var support: Int+ var id: String { text }+}++/// A name or term as the notes settled on it, and how speech recognition heard it.+struct NoteTerm: Codable, Equatable, Identifiable {+ var name: String+ var note: String+ var heard: [String]+ var id: String { name }+}++// MARK: - Engine++/// Keeps the live session's notes up to date: every ~45 s with new speech, one Ling call sends+/// the current notes plus the new lines and gets the whole updated notes back as JSON. A failed or+/// odd reply never replaces good notes. UI-free; the notes window observes it.+@MainActor+final class NotesEngine: ObservableObject {+ enum State: Equatable {+ case idle+ case updating+ case noKey+ case invalidKey+ case rateLimited+ case failed+ }++ @Published private(set) var notes = MeetingNotes()+ @Published private(set) var state: State = .idle+ /// Points and topics that appeared in the last update ("新").+ @Published private(set) var fresh: Set<String> = []+ @Published private(set) var summaryChangedAt: Date?++ let ling: LingClient+ let store: SessionStore+ /// The language the reader wants notes in (their own system language).+ var language: () -> String = { "Simplified Chinese" }++ private var sessionID: String?+ /// The session whose notes `notes` shows (stays set after the meeting ends).+ private(set) var shownID: String?+ private var timer: Timer?+ private var inFlight = false+ private var lastAttempt = Date.distantPast+ static let interval: TimeInterval = 45++ init(ling: LingClient, store: SessionStore) {+ self.ling = ling+ self.store = store+ }++ /// Names for the translation glossary: "江充 (heard as 江松, 江冲)".+ var glossary: [String] {+ notes.terms.prefix(30).map { t in+ t.heard.isEmpty ? "\(t.name) (\(t.note))" : "\(t.name) (\(t.note); misheard as \(t.heard.joined(separator: ", ")))"+ }+ }++ func begin(_ id: String) {+ sessionID = id+ shownID = id+ notes = store.session(id)?.notes ?? MeetingNotes()+ fresh = []+ state = ling.hasKey ? .idle : .noKey+ lastAttempt = Date()+ timer?.invalidate()+ let t = Timer(timeInterval: 5, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.tick() }+ }+ timer = t+ RunLoop.main.add(t, forMode: .common)+ }++ /// The meeting ended: one last pass over the whole transcript.+ func finish() {+ timer?.invalidate()+ timer = nil+ guard let id = sessionID else { return }+ sessionID = nil+ Task { await update(id, final: true) }+ }++ func updateNow() {+ guard let id = sessionID else { return }+ Task { await update(id, final: false) }+ }++ /// Notes for a finished meeting that has none (e.g. recorded before a key was set).+ func generate(for id: String) {+ Task { await update(id, final: true) }+ }++ /// Debug control: rebuild a stored meeting's notes the way a live meeting would, a few lines+ /// at a time, then the final pass.+ func replay(_ id: String, step: Int = 4) async {+ guard let count = store.session(id)?.lines.count else { return }+ shownID = id+ notes = MeetingNotes()+ for upto in stride(from: min(step, count), through: count, by: step) {+ await update(id, final: false, upto: upto)+ }+ if count % step != 0 { await update(id, final: false, upto: count) }+ await update(id, final: true)+ }++ private func tick() {+ guard let id = sessionID, !inFlight else { return }+ guard let s = store.session(id), s.lines.count > notes.covered else { return }+ // First notes as soon as there is something to say, then every 45 s.+ let due = notes.isEmpty ? (s.lines.count >= 3 || Date().timeIntervalSince(lastAttempt) > 20)+ : Date().timeIntervalSince(lastAttempt) >= Self.interval+ if due { Task { await update(id, final: false) } }+ }++ private func update(_ id: String, final: Bool, upto: Int? = nil) async {+ guard !inFlight, let session = store.session(id), !session.lines.isEmpty else { return }+ guard ling.hasKey else { state = .noKey; return }+ inFlight = true+ lastAttempt = Date()+ state = .updating+ defer { inFlight = false }++ let lines = Array(session.lines.prefix(upto ?? session.lines.count))+ let base = final ? MeetingNotes() : (id == shownID ? notes : session.notes ?? MeetingNotes())+ let from = final ? 0 : min(base.covered, lines.count)+ let prompt = Self.prompt(notes: base, lines: lines, from: from, language: language(), final: final)+ let started = Date()+ do {+ let raw = try await ling.chat(content: prompt, instruction: "Update the notes.", priority: .notes,+ json: true, maxTokens: 6000, timeout: 90)+ guard var next = Self.parse(raw, lineCount: lines.count, startedAt: session.lines.first?.t ?? 0) else {+ debugLog("notes: reply was not usable JSON, kept the previous notes")+ state = .failed+ return+ }+ next.covered = lines.count+ next.updatedAt = Date()+ next.final = final+ if id == shownID {+ markFresh(old: notes, new: next)+ if next.summary != notes.summary { summaryChangedAt = Date() }+ notes = next+ }+ store.setNotes(id, next)+ state = .idle+ debugLog("notes: \(final ? "final" : "live") update \(lines.count - from) new lines → \(next.topics.count) topics, \(next.terms.count) terms in \(Int(Date().timeIntervalSince(started))) s")+ } catch LingClient.Failure.invalidKey {+ state = .invalidKey+ } catch LingClient.Failure.rateLimited {+ state = .rateLimited+ } catch LingClient.Failure.noKey {+ state = .noKey+ } catch {+ debugLog("notes: update failed \(error)")+ state = .failed+ }+ }++ private func markFresh(old: MeetingNotes, new: MeetingNotes) {+ guard !old.isEmpty else { fresh = []; return }+ let before = Set(old.topics.flatMap { [$0.title] + $0.points })+ fresh = Set(new.topics.flatMap { [$0.title] + $0.points }).subtracting(before)+ }++ // MARK: Prompt++ static func clock(_ t: Double) -> String { String(format: "%02d:%02d", Int(t) / 60, Int(t) % 60) }++ static func prompt(notes: MeetingNotes, lines: [TranscriptLine], from: Int, language: String, final: Bool) -> String {+ func line(_ i: Int) -> String {+ let l = lines[i]+ return "[L\(i + 1) \(clock(l.t)) \(l.speaker == "me" ? "你" : "对方")] \(l.src)"+ }+ var current = "{}"+ if !notes.isEmpty, let data = try? JSONEncoder().encode(Compact(notes)), let s = String(data: data, encoding: .utf8) {+ current = s+ }+ let context = max(0, from - 2)+ var p = """+ You keep notes for a meeting \(final ? "that has just ended. Rewrite them from the whole transcript" : "that is still going on. Update them with the new lines").+ Write the notes in \(language). Return JSON only.++ """+ if !final {+ p += "Current notes (JSON):\n\(current)\n\n"+ }+ if context < from {+ p += "Already covered (context only):\n" + (context..<from).map(line).joined(separator: "\n") + "\n\n"+ }+ p += "\(final ? "Transcript" : "New lines") (id, mm:ss, speaker 对方=the other side / 你=me, text). Speech recognition makes mistakes, often in names: correct them from context.\n"+ p += (from..<lines.count).map(line).joined(separator: "\n")+ p += """+++ Return the full notes as one JSON object with exactly these keys:+ {"summary": "2-3 sentences on the whole meeting so far",+ "topics": [{"start": seconds, "title": "short title", "summary": "one sentence", "points": ["key point"], "evidence": ["L3"],+ "fishbone": null or {"question": "the problem or question", "branches": [{"label": "2-6 words", "detail": "one short line", "t": seconds, "evidence": ["L5"]}]}}],+ "conclusions": [{"text": "...", "evidence": ["L7", "L8"]}],+ "todos": [{"text": "...", "owner": "对方" or "你" or null, "evidence": ["L9"]}],+ "terms": [{"name": "correct spelling", "note": "who or what, a few words", "heard": ["how it was misrecognised"]}]}+ Rules (be brief: these notes are read at a glance during the meeting):+ - summary: at most 3 short sentences.+ - Topics in time order, at most 8 in total. Start a new topic only when the subject clearly changes (usually every few minutes); otherwise add to the current one, and merge small neighbouring topics. Keep earlier topics as they are unless new lines correct them. The last topic is the one being discussed now.+ - At most 4 points per topic, each one short phrase. Merge rather than repeat.+ - At most 5 conclusions and only real to-dos (often none).+ - Add a fishbone only to a topic that discusses causes, reasons or factors (3-5 branches); otherwise null.+ - Every topic, point source, branch, conclusion and to-do needs evidence: the ids of the lines that say it. Never state anything the transcript does not say.+ - terms: at most 10 people, places or jargon words that matter. name is the correct spelling in the transcript's language (no translation in brackets); heard lists only the wrong forms the transcript used; note is a few words.+ - Use empty arrays when there is nothing. No markdown, no text outside the JSON.+ """+ return p+ }++ /// The current notes as sent back to the model (no bookkeeping fields).+ private struct Compact: Encodable {+ let summary: String+ let topics: [NoteTopic]+ let conclusions: [String]+ let todos: [String]+ let terms: [NoteTerm]+ init(_ n: MeetingNotes) {+ summary = n.summary+ topics = n.topics+ conclusions = n.conclusions.map(\.text)+ todos = n.todos.map(\.text)+ terms = n.terms+ }+ }++ // MARK: Parse++ /// Lenient: missing keys become empty, evidence ids are checked against the transcript.+ static func parse(_ raw: String, lineCount: Int, startedAt: Double) -> MeetingNotes? {+ var text = raw+ if let a = text.firstIndex(of: "{"), let b = text.lastIndex(of: "}") { text = String(text[a...b]) }+ guard let data = text.data(using: .utf8),+ let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }+ func str(_ v: Any?) -> String { (v as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" }+ func num(_ v: Any?) -> Double? { (v as? NSNumber)?.doubleValue ?? (v as? String).flatMap(Double.init) }+ func support(_ v: Any?) -> Int {+ let ids = (v as? [Any])?.compactMap { $0 as? String } ?? []+ return Set(ids.compactMap { id -> Int? in+ guard let n = Int(id.drop(while: { !$0.isNumber })), n >= 1, n <= lineCount else { return nil }+ return n+ }).count+ }+ var n = MeetingNotes()+ n.summary = str(root["summary"])+ n.topics = (root["topics"] as? [[String: Any]] ?? []).compactMap { t in+ let title = str(t["title"])+ guard !title.isEmpty else { return nil }+ var fish: Fishbone?+ if let f = t["fishbone"] as? [String: Any] {+ let branches = (f["branches"] as? [[String: Any]] ?? []).compactMap { b -> FishboneBranch? in+ let label = str(b["label"])+ return label.isEmpty ? nil : FishboneBranch(label: label, detail: str(b["detail"]), t: num(b["t"]),+ support: support(b["evidence"]))+ }+ if branches.count >= 2 { fish = Fishbone(question: str(f["question"]), branches: branches) }+ }+ return NoteTopic(start: num(t["start"]) ?? startedAt, title: title, summary: str(t["summary"]),+ points: (t["points"] as? [Any] ?? []).map(str).filter { !$0.isEmpty }, fishbone: fish)+ }+ func items(_ key: String) -> [NoteItem] {+ (root[key] as? [[String: Any]] ?? []).compactMap { i in+ let text = str(i["text"])+ let owner = str(i["owner"])+ return text.isEmpty ? nil : NoteItem(text: text, owner: owner.isEmpty ? nil : owner, support: support(i["evidence"]))+ }+ }+ n.conclusions = items("conclusions")+ n.todos = items("todos")+ n.terms = (root["terms"] as? [[String: Any]] ?? []).compactMap { t in+ let name = str(t["name"])+ let heard = (t["heard"] as? [Any] ?? []).map(str).filter { !$0.isEmpty && $0 != name }+ return name.isEmpty ? nil : NoteTerm(name: name, note: str(t["note"]), heard: heard)+ }+ return n.isEmpty ? nil : n+ }+}diff --git a/Sources/LiveSubs/SessionStore.swift b/Sources/LiveSubs/SessionStore.swiftindex 13822c4..db1c13d 100644--- a/Sources/LiveSubs/SessionStore.swift+++ b/Sources/LiveSubs/SessionStore.swift@@ -20,6 +20,8 @@ struct Session: Codable, Identifiable, Equatable {var endedAt: Date?var lines: [TranscriptLine]var hasAudio: Bool+ /// AI notes (absent in older sessions and without an API key).+ var notes: MeetingNotes?var duration: TimeInterval { (endedAt ?? Date()).timeIntervalSince(startedAt) }}@@ -108,6 +110,12 @@ final class SessionStore: ObservableObject {scheduleSave(id)}+ func setNotes(_ id: String, _ notes: MeetingNotes) {+ guard let i = index(id) else { return }+ sessions[i].notes = notes+ id == liveID ? scheduleSave(id) : saveNow(id)+ }+// MARK: Editingfunc rename(_ id: String, to title: String) {