知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix(android): live notes keep updating through hours-long meetings without one topic swallowing the rest, and a long meeting's full notes cover all of it
wquguru80dd2c57c275
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.ktindex de9cf0b..4c89a14 100644--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt@@ -60,6 +60,11 @@ object Tests {"parsesNotes" to ::parsesNotes,"keepsEarliestTimes" to ::keepsEarliestTimes,"notesPromptIsTheMacs" to ::notesPromptIsTheMacs,+ "keepsFrozenTopicsAndTakesTheRepliesTail" to ::keepsFrozenTopicsAndTakesTheRepliesTail,+ "fullLiveNotesJoinTheShortestSettledPair" to ::fullLiveNotesJoinTheShortestSettledPair,+ "livePromptSendsOnlyTheLatestTopics" to ::livePromptSendsOnlyTheLatestTopics,+ "longMeetingsAreNotedInPartsByTime" to ::longMeetingsAreNotedInPartsByTime,+ "topicStartsWhenItsLinesWereSaid" to ::topicStartsWhenItsLinesWereSaid,"loadsTheMacsTranslations" to ::loadsTheMacsTranslations,"keyFileIsPrivate" to ::keyFileIsPrivate,"onboardingKeepsAWorkingSavedKey" to ::onboardingKeepsAWorkingSavedKey,@@ -520,10 +525,107 @@ object Tests {check(p.endsWith("No markdown, no text outside the JSON."), "ending")val f = NotesEngine.prompt(MeetingNotes(), lines, 0, "English", final = true)check(f.contains("This meeting ran 01:04: use at most 1 topic."), "final topic limit")+ check(p.contains("at most 8 in total") && f.contains("at most 8 in total"), "with nothing frozen, the Mac's limit")+ check(p.contains("never append to it"), "topic summaries stay one sentence")check(NotesEngine.written(MeetingNotes(summary = "讨论发布 Stripe"), "Simplified Chinese"), "Chinese notes")check(!NotesEngine.written(MeetingNotes(summary = "We talked"), "Simplified Chinese"), "English isn't Chinese")}+ private fun topic(start: Double, title: String, points: List<String> = listOf("p")) =+ NoteTopic(start = start, title = title, summary = "s", points = points.toMutableList())++ private fun notesLines(n: Int) = (0 until n).map { TranscriptLine(id = "l$it", t = it * 10.0, speaker = "them", src = "line $it") }++ fun keepsFrozenTopicsAndTakesTheRepliesTail() {+ val old = (0 until 5).map { topic(it * 100.0, "t$it") }+ // The model echoed everything, renamed the current topic and added one.+ val reply = listOf(topic(0.0, "t0"), topic(100.0, "t1 改"), topic(300.0, "t3"), topic(400.0, "t4 改"), topic(500.0, "t5"))+ equal("t0,t1,t2,t3,t4 改,t5", NotesEngine.merge(old, 3, reply).joinToString(",") { it.title }, "frozen kept, the reply's tail after them")+ // The first update over many lines: nothing to echo, so every topic is the model's own.+ val five = (0 until 5).map { topic(it * 100.0, "t$it") }+ equal("t0,t1,t2,t3,t4", NotesEngine.merge(emptyList(), 0, five).joinToString(",") { it.title }, "nothing frozen")+ equal("t0,t1,t2,t3,t4", NotesEngine.merge(listOf(topic(0.0, "t0")), 0, five).joinToString(",") { it.title }, "nothing frozen keeps every topic")+ val abc = listOf(topic(0.0, "a"), topic(100.0, "b"), topic(200.0, "c"))+ equal("a,b,c", NotesEngine.merge(abc, 1, emptyList()).joinToString(",") { it.title }, "an empty reply keeps the topics")+ equal("a,b,c", NotesEngine.merge(abc, 1, listOf(topic(0.0, "a"))).joinToString(",") { it.title }, "only an echo keeps them too")+ // A runaway summary is cut to its first sentence.+ val runaway = topic(0.0, "t0").apply { summary = "对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。" + "最新对方又补充了一些内容,".repeat(20) }+ equal("对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。", NotesEngine.merge(emptyList(), 0, listOf(runaway))[0].summary, "a runaway summary")+ equal(NotesEngine.TOPIC_SUMMARY_LIMIT + 1, NotesEngine.shortened("长".repeat(200)).length, "or cut to the limit")+ equal("short", NotesEngine.shortened("short"), "a short one stays")+ }++ fun fullLiveNotesJoinTheShortestSettledPair() {+ // Twelve topics, t3 and t4 the shortest neighbours (t3 to t5 is 100 s): a new topic+ // still starts, and those two become one.+ val starts = listOf(0, 100, 200, 300, 330, 400, 600, 700, 800, 900, 1000, 1100)+ val old = starts.mapIndexed { i, s -> topic(s.toDouble(), "t$i", listOf("a$i", "b$i", "c$i")) }+ val reply = listOf(topic(1000.0, "t10"), topic(1100.0, "t11"), topic(1200.0, "t12"))+ val merged = NotesEngine.merge(old, 10, reply)+ equal(NotesEngine.LIVE_MAX_TOPICS, merged.size, "no more than the live limit")+ equal("t12", merged.last().title, "the new topic starts")+ equal("t3 / t4", merged[3].title, "the shortest pair joined")+ equal(300.0, merged[3].start, "from the first one's start")+ equal("a3,b3,a4,b4", merged[3].points.joinToString(","), "points taken evenly")+ equal("s s", merged[3].summary, "both summaries")+ }++ fun livePromptSendsOnlyTheLatestTopics() {+ val notes = MeetingNotes(summary = "summary", covered = 20,+ topics = mutableListOf(topic(0.0, "最早的话题"), topic(100.0, "第二个话题"), topic(200.0, "当前话题")))+ val p = NotesEngine.prompt(notes, notesLines(24), 20, "Simplified Chinese", final = false, frozen = 1)+ val json = p.split("Current notes")[1].split("\n\n")[0]+ check(p.contains("Earlier topics"), "settled topics listed")+ check(p.contains("- 00:00 最早的话题: s"), "as a line each")+ check(!json.contains("最早的话题"), "not in the JSON")+ check(json.contains("第二个话题") && json.contains("当前话题"), "the latest are")+ check(p.contains("returning only the topics in the current notes and at most one new one after them"), "the topics rule")+ check(!NotesEngine.prompt(notes, notesLines(24), 20, "Simplified Chinese", final = false).contains("Earlier topics"), "nothing frozen")+ val eight = MeetingNotes(summary = "summary", covered = 20, topics = (0 until 8).map { topic(it * 10.0, "t$it") }.toMutableList())+ val q = NotesEngine.prompt(eight, notesLines(24), 20, "English", final = false, frozen = 6)+ check(!q.contains("do not start a new topic"), "an old topic may be followed")+ check(q.contains("never append to it"), "one-sentence summaries")+ }++ fun longMeetingsAreNotedInPartsByTime() {+ // A line every 10 s: 90 min stays whole, 4 h becomes four parts of an hour.+ equal(listOf(0 until 540), NotesEngine.parts(notesLines(540)), "90 minutes in one")+ val four = NotesEngine.parts(notesLines(1440))+ equal(4, four.size, "4 hours in four")+ check(four.first().first == 0 && four.last().last == 1439, "every line")+ check(four.zipWithNext().all { (a, b) -> a.last + 1 == b.first }, "no gaps or overlaps")+ equal(0, NotesEngine.parts(emptyList()).size, "nothing")++ val all = notesLines(720)+ val p = NotesEngine.prompt(MeetingNotes(), all.take(480), 240, "English", final = true, part = 2 to 3)+ check(p.contains("part 2 of 3"), "which part")+ check(p.contains("[L241 40:00 对方] line 240"), "original line numbers")+ check(!p.contains("[L238 "), "no earlier lines")+ check(p.contains("This part ran 39:50"), "the part's length")+ // Each of three parts gets two of the eight topics.+ check(p.contains("use at most 2 topics"), "the part's share of topics")+ val merge = NotesEngine.mergePrompt(listOf("{\"summary\":\"a\"}", "{\"summary\":\"b\"}"), all, "English")+ check(merge.contains("Part 2 of 2:\n{\"summary\":\"b\"}"), "the parts' notes")+ check(merge.contains("Return the full notes as one JSON object"), "the usual format")+ check(merge.contains("\"topics\": []"), "no topics back")++ val ten = (0 until 10).map { topic(it * 300.0, "t$it") }+ equal("t0,t3,t6,t9", NotesEngine.spread(ten, 4).joinToString(",") { it.title }, "topics spread over the part")+ equal("t0", NotesEngine.spread(ten, 1).joinToString(",") { it.title }, "one")+ equal(3, NotesEngine.spread(ten.take(3), 4).size, "fewer stay")+ }++ fun topicStartsWhenItsLinesWereSaid() {+ val times = (0 until 100).map { it * 60.0 }+ val raw = """+ {"summary": "s", "topics": [+ {"start": 1380, "title": "late", "summary": "s", "points": [{"text": "a", "evidence": ["L86"]}, {"text": "b", "evidence": ["L52"]}], "evidence": ["L60"]},+ {"start": 300, "title": "no evidence", "summary": "s", "points": ["c"]}]}+ """+ val n = NotesEngine.parse(raw, times, 0.0)!!+ equal(listOf(51 * 60.0, 300.0), n.topics.map { it.start }, "the earliest line, else the model's start")+ }+// MARK: Stringsfun loadsTheMacsTranslations() {diff --git a/android/core/src/main/kotlin/cicada/Notes.kt b/android/core/src/main/kotlin/cicada/Notes.ktindex b25cbff..29e9cef 100644--- a/android/core/src/main/kotlin/cicada/Notes.kt+++ b/android/core/src/main/kotlin/cicada/Notes.kt@@ -1,15 +1,16 @@package cicadaimport java.time.Instant+import java.util.concurrent.Callableimport java.util.concurrent.Executorsimport java.util.concurrent.ScheduledFutureimport java.util.concurrent.TimeUnit/// Keeps the live meeting'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 notes back as JSON; a final pass rewrites-/// them over the whole transcript when the meeting ends. A failed or odd reply never replaces good-/// notes. The prompt and parsing are the Mac's (Notes.swift, via the Windows port), so all write-/// the same notes.+/// current notes plus the new lines and gets the last topics back as JSON; a final pass rewrites+/// them over the whole transcript (a long one in parts) when the meeting ends. A failed or odd+/// reply never replaces good notes. The prompt and parsing are the Mac's (Notes.swift, via the+/// Windows port), so all write the same notes.class NotesEngine(private val ling: LingClient, private val store: SessionStore) {enum class State { Idle, Updating, NoKey, InvalidKey, RateLimited, Failed }@@ -113,11 +114,17 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)val lines = store.lines(id)val from = if (final) 0 else minOf(base.covered, lines.size)val lang = language()- val prompt = prompt(base, lines, from, lang, final)- var next: MeetingNotes? = null+ // A live update returns only the last topics: when it rewrote them all, its reply grew with+ // the meeting until, about an hour in, it was cut off at max_tokens or fell into a loop and+ // the notes stopped updating. The final pass still rewrites everything once.+ val frozen = if (final) 0 else maxOf(0, base.topics.size - EDITABLE_TOPICS)+ val prompt = prompt(base, lines, from, lang, final, frozen = frozen)+ val startedAt = lines.firstOrNull()?.t ?: 0.0+ var next: MeetingNotes? = if (final) longFinal(lines, lang, startedAt) else nullfor (attempt in 1..(if (final) 2 else 1)) {+ if (next != null) breakval raw = ling.chat(prompt, "Update the notes. Write them in $lang.", Priority.Notes, json = true, maxTokens = 6000, timeout = 90.0, patient = final)- val parsed = parse(raw, lines.map { it.t }, lines.firstOrNull()?.t ?: 0.0) ?: break+ val parsed = parse(raw, lines.map { it.t }, startedAt) ?: breakif (written(parsed, lang)) { next = parsed; break }Log.d("notes: ${if (final) "final" else "live"} reply not in $lang (attempt $attempt), dropped")}@@ -126,6 +133,7 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)status = State.Failedreturn}+ if (!final) next.topics = merge(base.topics, frozen, next.topics).toMutableList()carryTimes(base, next)next.title = next.title ?: base.title ?: session.notes?.titlenext.covered = lines.size@@ -153,8 +161,126 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)}}+ /// A long meeting's final pass: each part noted on its own, all at once, then merged into one.+ /// null when a step fails: the caller then makes one pass over the whole transcript, as before.+ private fun longFinal(lines: List<TranscriptLine>, lang: String, startedAt: Double): MeetingNotes? {+ val parts = parts(lines)+ if (parts.size <= 1) return null+ val started = System.currentTimeMillis()+ val times = lines.map { it.t }+ // The engine's own executor is single-threaded: the parts get a pool of their own, for this+ // pass only. Each call still goes through LingClient's gate.+ val pool = Executors.newFixedThreadPool(parts.size) { r -> Thread(r, "NotesPart").apply { isDaemon = true } }+ val replies = try {+ pool.invokeAll(parts.mapIndexed { i, range ->+ val prompt = prompt(MeetingNotes(), lines.subList(0, range.last + 1), range.first, lang, final = true, part = i + 1 to parts.size)+ Callable {+ try {+ ling.chat(prompt, "Write the notes for this part. Write them in $lang.", Priority.Notes, json = true, maxTokens = 6000, timeout = 90.0)+ } catch (e: Exception) { null }+ }+ }).map { it.get() }+ } finally { pool.shutdown() }+ val notes = mutableListOf<String>()+ val topics = mutableListOf<NoteTopic>()+ for ((i, raw) in replies.withIndex()) {+ val parsed = raw?.let { parse(it, times, startedAt) }+ val a = raw?.indexOf('{') ?: -1; val b = raw?.lastIndexOf('}') ?: -1+ val part = if (parsed != null && parsed.topics.isNotEmpty() && a >= 0 && b > a) Json.parseObject(raw!!.substring(a, b + 1)) else null+ if (part == null) {+ Log.d("notes: final part ${i + 1}/${parts.size} failed, one pass instead")+ return null+ }+ // Without its topics: given them, the merge wrote them all back out and was cut off.+ notes.add(Json.write(part - "topics", pretty = false))+ topics += spread(parsed!!.topics, partTopics(parts.size))+ }+ val prompt = mergePrompt(notes, lines, lang)+ for (attempt in 1..2) {+ val raw = try {+ ling.chat(prompt, "Merge the notes. Write them in $lang.", Priority.Notes, json = true, maxTokens = 6000, timeout = 90.0)+ } catch (e: Exception) { break }+ val merged = parse(raw, times, startedAt) ?: break+ merged.topics = topics+ if (written(merged, lang)) {+ Log.d("notes: final in ${parts.size} parts -> ${merged.topics.size} topics in ${(System.currentTimeMillis() - started) / 1000} s")+ return merged+ }+ Log.d("notes: merged reply not in $lang (attempt $attempt), dropped")+ }+ Log.d("notes: merging ${parts.size} parts failed, one pass instead")+ return null+ }+companion object {const val INTERVAL = 45.0+ /// The most topics the final notes have (the prompt says so too; the model doesn't always listen).+ const val MAX_TOPICS = 8+ /// Live notes once stopped at 8 topics and poured the rest of the meeting into the last one,+ /// whose summary grew into a wall of "最新…又…补充…"; past this, the two shortest neighbouring+ /// settled topics are joined instead, so the newest can start.+ const val LIVE_MAX_TOPICS = 12+ /// A topic summary longer than this is a log the model kept appending to, not one sentence.+ const val TOPIC_SUMMARY_LIMIT = 160+ /// How many of the last topics a live update may rewrite; earlier ones stay as they are.+ const val EDITABLE_TOPICS = 2++ /// A live reply's topics after the `frozen` ones it was told to leave alone: with some frozen,+ /// at most the editable ones plus one new, from the end (the model sometimes echoes the whole+ /// list), never a copy of a frozen one, each summary kept to one sentence; and no more than+ /// LIVE_MAX_TOPICS in all (past that, settled neighbours are joined). A reply with no topics of+ /// its own keeps the ones it had.+ fun merge(old: List<NoteTopic>, frozen: Int, returned: List<NoteTopic>): List<NoteTopic> {+ val kept = old.take(frozen).toMutableList()+ val fixed = kept.map { it.title }.toSet()+ val own = returned.filter { it.title !in fixed }+ var tail = if (kept.isEmpty()) own else own.takeLast(old.size - kept.size + 1)+ if (tail.isEmpty()) return old+ tail.forEach { it.summary = shortened(it.summary) }+ tail = capped(tail, LIVE_MAX_TOPICS - minOf(kept.size, 1))+ while (kept.size + tail.size > LIVE_MAX_TOPICS && kept.size >= 2) {+ // The pair spanning the least time, its end being the next topic's start.+ val ends = kept.drop(1).map { it.start } + tail[0].start+ val i = (0 until kept.size - 1).minBy { ends[it + 1] - kept[it].start }+ kept[i] = joined(kept[i], kept[i + 1])+ kept.removeAt(i + 1)+ }+ return capped(kept + tail, LIVE_MAX_TOPICS)+ }++ /// Two neighbouring topics as one: both titles and summaries, and up to the 4 points the+ /// prompt allows, taken evenly from each.+ fun joined(a: NoteTopic, b: NoteTopic): NoteTopic {+ val fromA = minOf(a.points.size, maxOf(2, 4 - b.points.size))+ val fromB = minOf(b.points.size, 4 - fromA)+ val times = (0 until fromA).map { a.pointTime(it) } + (0 until fromB).map { b.pointTime(it) }+ val gap = if (a.summary.isEmpty() || a.summary.last() in "。!?;") "" else " "+ return NoteTopic(start = a.start, title = "${a.title} / ${b.title}", summary = a.summary + gap + b.summary,+ points = (a.points.take(fromA) + b.points.take(fromB)).toMutableList(),+ pointTimes = if (times.any { it != null }) times.toMutableList() else null, fishbone = a.fishbone ?: b.fishbone)+ }++ /// At most `count` topics (at least one): the points of any after that go into the last kept.+ /// Copies the topic it adds to: the earlier ones may be the notes on screen.+ fun capped(topics: List<NoteTopic>, count: Int): List<NoteTopic> {+ val out = topics.toMutableList()+ while (out.size > maxOf(1, count)) {+ val extra = out.removeAt(out.size - 1)+ val last = out.removeAt(out.size - 1)+ val times = last.points.indices.map { last.pointTime(it) } + extra.points.indices.map { extra.pointTime(it) }+ out.add(NoteTopic(start = last.start, title = last.title, summary = last.summary, points = (last.points + extra.points).toMutableList(),+ pointTimes = if (times.any { it != null }) times.toMutableList() else null, fishbone = last.fishbone))+ }+ return out+ }++ /// A runaway topic summary cut back to its first sentence (or to the limit, with "…").+ fun shortened(summary: String): String {+ if (summary.length <= TOPIC_SUMMARY_LIMIT) return summary+ val head = summary.take(TOPIC_SUMMARY_LIMIT)+ val end = head.indexOfAny("。!?;.!?;".toCharArray(), 10)+ return if (end >= 0) head.take(end + 1) else head.trimEnd() + "…"+ }/// The model echoes points it already had without evidence: keep the times they had, and a/// point keeps the time it was first heard.@@ -177,34 +303,50 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)// MARK: Prompt (Notes.swift › prompt, word for word)- fun prompt(notes: MeetingNotes, lines: List<TranscriptLine>, from: Int, language: String, final: Boolean): String {+ /// `frozen`: how many first topics a live update leaves alone (sent as a list, not returned).+ /// `part`: in a long meeting's final pass, which part `from until lines.size` is (1-based, of).+ fun prompt(notes: MeetingNotes, lines: List<TranscriptLine>, from: Int, language: String, final: Boolean,+ frozen: Int = 0, part: Pair<Int, Int>? = null): String {fun line(i: Int): String {val l = lines[i]val who = if (l.speaker == "me") "你" else "对方"return "[L${i + 1} ${Languages.clock(l.t)} $who] ${l.src}"}- val current = if (notes.isEmpty) "{}" else compactJson(notes)+ val current = if (notes.isEmpty) "{}" else compactJson(notes, frozen)val context = maxOf(0, from - 2)- var p = "You keep notes for a meeting ${if (final) "that has just ended. Rewrite them from the whole transcript" else "that is still going on. Update them with the new lines"}.\n" ++ val task = part?.let { "that has just ended. It was long, so it is noted in parts: write the notes for part ${it.first} of ${it.second} only, from the lines below" }+ ?: if (final) "that has just ended. Rewrite them from the whole transcript" else "that is still going on. Update them with the new lines"+ var p = "You keep notes for a meeting $task.\n" +"Write the notes in $language. Return JSON only.\n"- if (!final) p += "Current notes (JSON):\n$current\n\n"+ if (!final) {+ if (frozen > 0) {+ p += "Earlier topics (settled: kept as they are, do not return them):\n" ++ notes.topics.take(frozen).joinToString("\n") { "- ${Languages.clock(it.start)} ${it.title}: ${it.summary}" } + "\n\n"+ }+ p += "Current notes (JSON${if (frozen > 0) ", latest topics only" else ""}):\n$current\n\n"+ }if (context < from) p += "Already covered (context only):\n" + (context until from).joinToString("\n") { line(it) } + "\n\n"p += "${if (final) "Transcript" else "New lines"} (id, mm:ss, speaker 对方=the other side / 你=me / a name or 说话人N=one person on the other side, told apart by voice and possibly wrong / 未识别=someone on the other side not identified, text). Speech recognition makes mistakes, often in names: correct them from context, and write a public figure's name as the news spells it.\n"p += (from until lines.size).joinToString("\n") { line(it) }- if (final && lines.isNotEmpty()) {- val span = lines.last().t - lines.first().t- val most = maxOf(1, minOf(8, (span / 180).toInt() + 1))- p += "\n\nThis meeting ran ${Languages.clock(span)}: use at most $most topic${if (most == 1) "" else "s"}."+ if (final && from < lines.size) {+ val span = lines.last().t - lines[from].t+ val most = maxOf(1, minOf(part?.let { partTopics(it.second) } ?: MAX_TOPICS, (span / 180).toInt() + 1))+ p += "\n\nThis ${if (part == null) "meeting" else "part"} ran ${Languages.clock(span)}: use at most $most topic${if (most == 1) "" else "s"}."} else if (!final && notes.topics.isNotEmpty() && lines.isNotEmpty() && lines.last().t - notes.topics.last().start < 120) {val topic = notes.topics.last()p += "\n\nThe current topic \"${topic.title}\" started at ${Languages.clock(topic.start)}, under 2 minutes ago: do not start a new topic in this update; add the new lines to it."} else if (!final && notes.topics.isEmpty()) {p += "\n\nThese are the first lines: make one topic."}- p += "\n\nReturn the full notes as one JSON object with exactly these keys:\n" ++ return p + "\n\n" + format(language, final, frozen)+ }++ /// The reply's JSON shape and the rules for its contents.+ private fun format(language: String, final: Boolean, frozen: Int): String =+ "Return the full notes as one JSON object with exactly these keys:\n" +"{\"title\": \"the meeting's name: what it is about, a few words\",\n" +" \"summary\": \"2-3 sentences on the whole meeting so far\",\n" +- " \"topics\": [{\"start\": seconds, \"title\": \"short title\", \"summary\": \"one sentence\", \"points\": [{\"text\": \"key point\", \"evidence\": [\"L4\"]}], \"evidence\": [\"L3\"],\n" ++ " \"topics\": [{\"start\": seconds, \"title\": \"short title\", \"summary\": \"one sentence on the whole topic\", \"points\": [{\"text\": \"key point\", \"evidence\": [\"L4\"]}], \"evidence\": [\"L3\"],\n" +" \"fishbone\": null or {\"question\": \"the problem or question\", \"branches\": [{\"label\": \"2-6 words\", \"detail\": \"one short line\", \"t\": seconds, \"evidence\": [\"L5\"]}]}}],\n" +" \"conclusions\": [{\"text\": \"...\", \"evidence\": [\"L7\", \"L8\"]}],\n" +" \"todos\": [{\"text\": \"...\", \"owner\": \"对方\" or \"你\" or null, \"evidence\": [\"L9\"]}],\n" +@@ -212,7 +354,8 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)"Rules (be brief: these notes are read at a glance during the meeting):\n" +"- title: a name for the whole meeting, like a calendar entry (at most 12 Chinese characters or 6 words; no date, no quotes, not \"会议\" alone). Keep the current title unless the meeting's subject has clearly changed.\n" +"- summary: at most 3 short sentences.\n" +- "- Topics in time order, at most 8 in total. A topic is a stretch of the meeting, usually 3-10 minutes, not a single remark: start a new one only when the subject clearly changes and the current topic started at least 2 minutes before the newest line${if (final) "" else "; add at most one new topic per update"}. 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.\n" ++ "- Topics in time order, ${if (frozen > 0) "returning only the topics in the current notes and at most one new one after them" else "at most $MAX_TOPICS in total"}. A topic is a stretch of the meeting, usually 3-10 minutes, not a single remark: start a new one only when the subject clearly changes and the current topic started at least 2 minutes before the newest line${if (final) "" else "; add at most one new topic per update"}. 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.\n" ++ "- A topic's summary is one sentence on the whole topic, at most 40 Chinese characters or 25 words: as the topic grows, rewrite it; never append to it or narrate what came next (\"最新\", \"又\", \"补充\", \"then\", \"later\").\n" +"- At most 4 points per topic, each one short phrase. Merge rather than repeat.\n" +"- At most 5 conclusions and only real to-dos (often none).\n" +"- Add a fishbone only to a topic that discusses causes, reasons or factors (3-5 branches); otherwise null.\n" +@@ -221,15 +364,62 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)"- Write the meeting title and every summary, title, point, branch, conclusion and to-do in $language, even when the transcript is in another language. Only term names keep the transcript's spelling.\n" +"- Write about what was said, never about the transcript or recognition quality.\n" +"- Use empty arrays when there is nothing. No markdown, no text outside the JSON."- return p++ // MARK: Long meetings++ /// How a long meeting's final pass is split: over SPLIT_MINUTES, into equal parts by time of at+ /// most PART_MINUTES. One pass covered a 91-minute meeting but only the first hour of a 4-hour one.+ const val SPLIT_MINUTES = 100.0+ const val PART_MINUTES = 60.0+ fun parts(lines: List<TranscriptLine>): List<IntRange> {+ if (lines.isEmpty()) return emptyList()+ val first = lines.first().t; val last = lines.last().t+ val minutes = (last - first) / 60+ if (minutes <= SPLIT_MINUTES) return listOf(lines.indices)+ val count = Math.ceil(minutes / PART_MINUTES).toInt()+ val length = (last - first) / count+ val bounds = mutableListOf(0)+ for (k in 1 until count) {+ val at = first + length * k+ val i = lines.indexOfFirst { it.t >= at }+ if (i > bounds.last()) bounds.add(i)+ }+ bounds.add(lines.size)+ return bounds.zipWithNext { a, b -> a until b }+ }++ /// Each part's share of the topics: the merge keeps them as they are, so every part has some.+ fun partTopics(parts: Int) = maxOf(2, MAX_TOPICS / maxOf(1, parts))++ /// `count` of `topics`, spread evenly from the first to the last: a part's reply often has+ /// more topics than asked, and keeping the first ones (or folding the rest into the last) lost+ /// the end of each part.+ fun spread(topics: List<NoteTopic>, count: Int): List<NoteTopic> {+ if (topics.size <= count || count <= 0) return topics+ if (count == 1) return listOf(topics[0])+ return (0 until count).map { topics[Math.round(it.toDouble() * (topics.size - 1) / (count - 1)).toInt()] }+ }++ /// The whole meeting's title, summary, conclusions, to-dos and terms from its parts' notes (the+ /// replies as they came, with their evidence line ids). Asked to merge topics too, the model+ /// kept the first parts' and dropped the rest, so topics are joined in code.+ fun mergePrompt(parts: List<String>, lines: List<TranscriptLine>, language: String): String {+ var p = "You keep notes for a meeting that has just ended. It was long, so each part was noted on its own; below are those notes, in time order (JSON; evidence ids are transcript lines, L1 the first). Merge them into the notes for the whole meeting.\n" ++ "Write the notes in $language. Return JSON only.\n\n"+ for ((i, part) in parts.withIndex()) p += "Part ${i + 1} of ${parts.size}:\n$part\n\n"+ if (lines.isNotEmpty()) {+ p += "This meeting ran ${Languages.clock(lines.last().t - lines.first().t)}. Return \"topics\": []: the parts' topics are kept as they are. Name and summarise the whole meeting, every part of it; keep each conclusion, to-do and term once, with the evidence ids it had (joined when you merge two).\n\n"+ }+ return p + format(language, final = true, frozen = 0)}- /// The current notes as sent back to the model (no bookkeeping fields).- private fun compactJson(n: MeetingNotes): String {+ /// The current notes as sent back to the model (no bookkeeping fields). `from`: the first topic+ /// sent (earlier ones go as a list of titles).+ private fun compactJson(n: MeetingNotes, from: Int = 0): String {val o = linkedMapOf<String, Any?>()if (n.title != null) o["title"] = n.titleo["summary"] = n.summary- o["topics"] = n.topics.map {+ o["topics"] = n.topics.drop(from).map {mapOf("start" to it.start, "title" to it.title, "summary" to it.summary, "points" to it.points, "fishbone" to it.fishbone?.toJson())}o["conclusions"] = n.conclusions.map { it.text }@@ -276,7 +466,10 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)points.add(text)pointTimes.add(po?.let { time(it["evidence"]) })}- n.topics.add(NoteTopic(start = t["start"].num() ?: startedAt, title = topicTitle, summary = s(t["summary"]), points = points,+ // When it was first said, from its lines: the model's own `start` drifts by tens of+ // minutes in a long meeting (a topic said at 51-85 min came back as starting at 23).+ val said = (listOf(time(t["evidence"])) + pointTimes).filterNotNull().minOrNull()+ n.topics.add(NoteTopic(start = said ?: t["start"].num() ?: startedAt, title = topicTitle, summary = s(t["summary"]), points = points,pointTimes = if (pointTimes.any { it != null }) pointTimes else null, fishbone = fish))}fun items(key: String) = objects(root[key]).map { i ->