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.

fix(linux): 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

wquguru0ec26288efc5
diff --git a/linux/cicada/core/notes.py b/linux/cicada/core/notes.py
index 8205b03..882fcfd 100644
--- a/linux/cicada/core/notes.py
+++ b/linux/cicada/core/notes.py
@@ -1,14 +1,17 @@
"""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.
+current notes plus the new lines and gets the notes back as JSON, rewriting only the last topics; a
+final pass rewrites them over the whole transcript when the meeting ends (a long meeting in parts,
+merged). A failed or odd reply never replaces good notes.
The prompt and parsing are the Mac's (Notes.swift, via the Windows and Android ports), so every
platform writes the same notes."""
from __future__ import annotations
+import math
import re
import threading
import time
from concurrent.futures import ThreadPoolExecutor
+from dataclasses import replace
from . import jsonfmt, speakers
from .jsonfmt import arr, num, obj
@@ -158,13 +161,21 @@ class NotesEngine:
lines = self.store.lines(sid)
frm = 0 if final else min(base.covered, len(lines))
lang = self.language(sid)
- shown = speakers.names(session) if self.voices() else {}
- p = prompt(base, lines, frm, lang, final, shown, self.voices())
- nxt = None
+ voices = self.voices()
+ shown = speakers.names(session) if voices else {}
+ started_at = lines[0].t if lines else 0.0
+ # 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.
+ frozen = 0 if final or fresh else max(0, len(base.topics) - EDITABLE_TOPICS)
+ p = prompt(base, lines, frm, lang, final, shown, voices, frozen)
+ nxt = self._long_final(lines, shown, voices, lang, started_at) if final else None
for attempt in range(1, 3 if final else 2):
+ if nxt is not None:
+ break
raw = self.ling.chat(p, "Update the notes. Write them in %s." % lang, NOTES, json=True, max_tokens=6000, timeout=90.0,
patient=final)
- parsed = parse(raw, [l.t for l in lines], lines[0].t if lines else 0.0)
+ parsed = parse(raw, [l.t for l in lines], started_at)
if parsed is None:
break
if written(parsed, lang):
@@ -175,6 +186,8 @@ class NotesEngine:
Log.d("notes: no usable reply, kept the previous notes")
self.status = FAILED
return
+ if not final and not fresh:
+ nxt.topics = merge(base.topics, frozen, nxt.topics)
carry_times(base, nxt)
nxt.title = nxt.title or base.title or (session.notes.title if session.notes else None)
nxt.covered = len(lines)
@@ -206,11 +219,126 @@ class NotesEngine:
elif again is not None:
self._update(again, final=False, fresh=True)
+ def _long_final(self, lines: list, names: dict, voices: bool, lang: str, started_at: float) -> MeetingNotes | None:
+ """A long meeting's final pass: each part noted on its own, all at once, then merged into one.
+ None when a step fails: the caller then makes one pass over the whole transcript, as before."""
+ ranges = parts(lines)
+ if len(ranges) <= 1:
+ return None
+ started = time.time()
+ times = [l.t for l in lines]
+
+ def ask(i):
+ r = ranges[i]
+ p = prompt(MeetingNotes(), lines[:r.stop], r.start, lang, True, names, voices, part=(i + 1, len(ranges)))
+ try:
+ return self.ling.chat(p, "Write the notes for this part. Write them in %s." % lang, NOTES, json=True,
+ max_tokens=6000, timeout=90.0)
+ except Exception: # noqa: BLE001
+ return None
+ with ThreadPoolExecutor(max_workers=len(ranges), thread_name_prefix="NotesPart") as pool:
+ replies = list(pool.map(ask, range(len(ranges))))
+ notes, topics = [], []
+ for i, raw in enumerate(replies):
+ parsed = parse(raw, times, started_at) if raw else None
+ root = jsonfmt.parse_object(raw[raw.find("{"):raw.rfind("}") + 1]) if parsed is not None and parsed.topics else None
+ if root is None:
+ Log.d("notes: final part %d/%d failed, one pass instead" % (i + 1, len(ranges)))
+ return None
+ # Without its topics: given them, the merge wrote them all back out and was cut off.
+ root.pop("topics", None)
+ notes.append(jsonfmt.write(root, pretty=False))
+ topics += spread(parsed.topics, part_topics(len(ranges)))
+ p = merge_prompt(notes, lines, lang, voices and bool(speakers.numbers(lines)))
+ for attempt in (1, 2):
+ try:
+ raw = self.ling.chat(p, "Merge the notes. Write them in %s." % lang, NOTES, json=True, max_tokens=6000, timeout=90.0)
+ except Exception: # noqa: BLE001
+ break
+ merged = parse(raw, times, started_at)
+ if merged is None:
+ break
+ merged.topics = topics
+ if written(merged, lang):
+ Log.d("notes: final in %d parts -> %d topics in %d s" % (len(ranges), len(topics), time.time() - started))
+ return merged
+ Log.d("notes: merged reply not in %s (attempt %d), dropped" % (lang, attempt))
+ Log.d("notes: merging %d parts failed, one pass instead" % len(ranges))
+ return None
+
def _min(a, b):
return b if a is None else a if b is None else min(a, b)
+# The most topics the final notes have (the prompt says so too; the model doesn't always listen).
+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.
+LIVE_MAX_TOPICS = 12
+# How many of the last topics a live update may rewrite; earlier ones stay as they are.
+EDITABLE_TOPICS = 2
+# A topic summary longer than this is a log the model kept appending to, not one sentence.
+TOPIC_SUMMARY_LIMIT = 160
+
+
+def shortened(summary: str) -> str:
+ """A runaway topic summary cut back to its first sentence (or to the limit, with "…")."""
+ if len(summary) <= TOPIC_SUMMARY_LIMIT:
+ return summary
+ head = summary[:TOPIC_SUMMARY_LIMIT]
+ m = re.search(r"[。!?;.!?;]", head[10:])
+ return head[:10 + m.end()] if m else head.rstrip() + "…"
+
+
+def merge(old: list, frozen: int, returned: list) -> list:
+ """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."""
+ kept = list(old[:frozen])
+ fixed = {t.title for t in kept}
+ own = [t for t in returned if t.title not in fixed]
+ tail = own if not kept else own[-(len(old) - len(kept) + 1):]
+ if not tail:
+ return old
+ tail = [replace(t, summary=shortened(t.summary)) for t in tail]
+ tail = capped(tail, LIVE_MAX_TOPICS - min(len(kept), 1))
+ while len(kept) + len(tail) > LIVE_MAX_TOPICS and len(kept) >= 2:
+ # The pair spanning the least time, its end being the next topic's start.
+ ends = [t.start for t in kept[1:]] + [tail[0].start]
+ i = min(range(len(kept) - 1), key=lambda j: ends[j + 1] - kept[j].start)
+ kept[i] = joined(kept[i], kept[i + 1])
+ del kept[i + 1]
+ return capped(kept + tail, LIVE_MAX_TOPICS)
+
+
+def joined(a: NoteTopic, b: NoteTopic) -> NoteTopic:
+ """Two neighbouring topics as one: both titles and summaries, and up to the 4 points the prompt
+ allows, taken evenly from each."""
+ from_a = min(len(a.points), max(2, 4 - len(b.points)))
+ from_b = min(len(b.points), 4 - from_a)
+ times = [a.point_time(i) for i in range(from_a)] + [b.point_time(i) for i in range(from_b)]
+ gap = "" if not a.summary or a.summary[-1] in "。!?;" else " "
+ return NoteTopic(start=a.start, title="%s / %s" % (a.title, b.title), summary=a.summary + gap + b.summary,
+ points=a.points[:from_a] + b.points[:from_b], fishbone=a.fishbone or b.fishbone,
+ pointTimes=times if any(x is not None for x in times) else None)
+
+
+def capped(topics: list, count: int) -> list:
+ """At most `count` topics (at least one): the points of any after that go into the last kept."""
+ topics = list(topics)
+ while len(topics) > max(1, count):
+ extra = topics.pop()
+ last = topics.pop()
+ times = [last.point_time(i) for i in range(len(last.points))] + [extra.point_time(i) for i in range(len(extra.points))]
+ topics.append(replace(last, points=last.points + extra.points,
+ pointTimes=times if any(x is not None for x in times) else None))
+ return topics
+
+
def carry_times(old: MeetingNotes, nxt: MeetingNotes) -> None:
"""The model echoes points it already had without evidence: keep the times they had, and a point
keeps the time it was first heard."""
@@ -238,7 +366,9 @@ def written(notes: MeetingNotes, language: str) -> bool:
# Prompt (Notes.swift › prompt, word for word)
def prompt(notes: MeetingNotes, lines: list, frm: int, language: str, final: bool, names: dict | None = None,
- voices: bool = False) -> str:
+ voices: bool = False, frozen: int = 0, part: tuple | None = None) -> str:
+ """`frozen`: the first topics, settled, sent as a list and not returned. `part`: in a long
+ meeting's final pass, which part `frm:len(lines)` is (1-based index, count)."""
nums = speakers.numbers(lines) if voices else {}
names = names or {}
@@ -248,63 +378,138 @@ def prompt(notes: MeetingNotes, lines: list, frm: int, language: str, final: boo
who = "你" if l.speaker == "me" else (
(names.get(nums[l.id]) or "说话人%d" % nums[l.id]) if l.id in nums else ("对方" if not nums else "未识别"))
return "[L%d %s %s] %s" % (i + 1, clock(l.t), who, l.src)
- current = "{}" if notes.is_empty else _compact_json(notes)
+ current = "{}" if notes.is_empty else _compact_json(notes, frozen)
context = max(0, frm - 2)
- p = ("You keep notes for a meeting %s.\n" % ("that has just ended. Rewrite them from the whole transcript" if final
- else "that is still going on. Update them with the new lines") +
- "Write the notes in %s. Return JSON only.\n" % language)
+ if part is not None:
+ task = ("that has just ended. It was long, so it is noted in parts: write the notes for part %d of %d only, from the lines below"
+ % part)
+ else:
+ task = "that has just ended. Rewrite them from the whole transcript" if final else "that is still going on. Update them with the new lines"
+ p = "You keep notes for a meeting %s.\nWrite the notes in %s. Return JSON only.\n" % (task, language)
if not final:
- p += "Current notes (JSON):\n%s\n\n" % current
+ if frozen > 0:
+ p += ("Earlier topics (settled: kept as they are, do not return them):\n" +
+ "\n".join("- %s %s: %s" % (clock(t.start), t.title, t.summary) for t in notes.topics[:frozen]) + "\n\n")
+ p += "Current notes (JSON%s):\n%s\n\n" % (", latest topics only" if frozen > 0 else "", current)
if context < frm:
p += "Already covered (context only):\n" + "\n".join(line(i) for i in range(context, frm)) + "\n\n"
p += ("%s (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"
% ("Transcript" if final else "New lines"))
p += "\n".join(line(i) for i in range(frm, len(lines)))
- if final and lines:
- span = lines[-1].t - lines[0].t
- most = max(1, min(8, int(span / 180) + 1))
- p += "\n\nThis meeting ran %s: use at most %d topic%s." % (clock(span), most, "" if most == 1 else "s")
+ # The model splits too eagerly when only told how long a topic should be: say plainly whether
+ # this update may start one.
+ if final and frm < len(lines):
+ span = lines[-1].t - lines[frm].t
+ most = max(1, min(part_topics(part[1]) if part else MAX_TOPICS, int(span / 180) + 1))
+ p += "\n\nThis %s ran %s: use at most %d topic%s." % ("meeting" if part is None else "part", clock(span), most, "" if most == 1 else "s")
elif not final and notes.topics and lines and lines[-1].t - notes.topics[-1].start < 120:
topic = notes.topics[-1]
p += ("\n\nThe current topic \"%s\" started at %s, under 2 minutes ago: do not start a new topic in this update; add the new lines to it."
% (topic.title, clock(topic.start)))
elif not final and not notes.topics:
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"
- "{\"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"
- " \"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\": %s, \"evidence\": [\"L9\"]}],\n"
- " \"terms\": [{\"name\": \"correct spelling\", \"note\": \"who or what, a few words\", \"heard\": [\"how it was misrecognised\"]}]}\n"
- "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%s. 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"
- "- 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"
- "- Every topic, point, branch, conclusion and to-do needs evidence: the ids of the lines that say it. Never state anything the transcript does not say.\n"
- "- terms: at most 10 in total, replacing less useful ones rather than adding: first names the transcript misspells (heard), then the people, places and jargon a reader would not know. Leave out what everyone knows (a famous company, index or politician) unless it was misheard. 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.\n"
- "- Write the meeting title and every summary, title, point, branch, conclusion and to-do in %s, 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."
- % ('"对方" or "你" or null' if not nums else
- 'the person\'s label from the transcript (a name like "George", or "说话人2"), "你", or null when unclear',
- "" if final else "; add at most one new topic per update", language))
- return p
-
-
-def _compact_json(n: MeetingNotes) -> str:
- """The current notes as sent back to the model (no bookkeeping fields). Insertion order, like the
- Kotlin LinkedHashMap; jsonfmt sorts keys, which the model doesn't mind."""
+ return p + "\n\n" + _format(language, bool(nums), final, frozen)
+
+
+def _format(language: str, voices: bool, final: bool, frozen: int) -> str:
+ """The reply's JSON shape and the rules for its contents."""
+ return ("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 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\": %s, \"evidence\": [\"L9\"]}],\n"
+ " \"terms\": [{\"name\": \"correct spelling\", \"note\": \"who or what, a few words\", \"heard\": [\"how it was misrecognised\"]}]}\n"
+ "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, %s. 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%s. 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"
+ "- Every topic, point, branch, conclusion and to-do needs evidence: the ids of the lines that say it. Never state anything the transcript does not say.\n"
+ "- terms: at most 10 in total, replacing less useful ones rather than adding: first names the transcript misspells (heard), then the people, places and jargon a reader would not know. Leave out what everyone knows (a famous company, index or politician) unless it was misheard. 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.\n"
+ "- Write the meeting title and every summary, title, point, branch, conclusion and to-do in %s, 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."
+ % ('"对方" or "你" or null' if not voices else
+ 'the person\'s label from the transcript (a name like "George", or "说话人2"), "你", or null when unclear',
+ "returning only the topics in the current notes and at most one new one after them" if frozen > 0
+ else "at most %d in total" % MAX_TOPICS,
+ "" if final else "; add at most one new topic per update", language))
+
+
+# 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.
+SPLIT_MINUTES = 100.0
+PART_MINUTES = 60.0
+
+
+def parts(lines: list) -> list:
+ """The final pass's parts as ranges of line indices."""
+ if not lines:
+ return []
+ first, last = lines[0].t, lines[-1].t
+ minutes = (last - first) / 60
+ if minutes <= SPLIT_MINUTES:
+ return [range(0, len(lines))]
+ count = math.ceil(minutes / PART_MINUTES)
+ length = (last - first) / count
+ bounds = [0]
+ for k in range(1, count):
+ at = first + length * k
+ i = next((j for j, l in enumerate(lines) if l.t >= at), None)
+ if i is not None and i > bounds[-1]:
+ bounds.append(i)
+ bounds.append(len(lines))
+ return [range(a, b) for a, b in zip(bounds, bounds[1:])]
+
+
+def part_topics(n: int) -> int:
+ """Each part's share of the topics: the merge keeps them as they are, so every part has some."""
+ return max(2, MAX_TOPICS // max(1, n))
+
+
+def spread(topics: list, count: int) -> list:
+ """`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."""
+ if len(topics) <= count or count <= 0:
+ return topics
+ if count == 1:
+ return [topics[0]]
+ # Rounded half up, as Swift's rounded() does for these non-negative positions.
+ return [topics[int(k * (len(topics) - 1) / (count - 1) + 0.5)] for k in range(count)]
+
+
+def merge_prompt(parts: list, lines: list, language: str, voices: bool) -> str:
+ """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."""
+ 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 %s. Return JSON only.\n\n" % language)
+ for i, part in enumerate(parts):
+ p += "Part %d of %d:\n%s\n\n" % (i + 1, len(parts), part)
+ if lines:
+ p += ("This meeting ran %s. 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"
+ % clock(lines[-1].t - lines[0].t))
+ return p + _format(language, voices, True, 0)
+
+
+def _compact_json(n: MeetingNotes, frm: int = 0) -> str:
+ """The current notes as sent back to the model (no bookkeeping fields), topics from `frm` (earlier
+ ones go as a list of titles). Insertion order, like the Kotlin LinkedHashMap; jsonfmt sorts keys,
+ which the model doesn't mind."""
o = {}
if n.title is not None:
o["title"] = n.title
o["summary"] = n.summary
o["topics"] = [{"start": t.start, "title": t.title, "summary": t.summary, "points": list(t.points),
- "fishbone": t.fishbone.to_json() if t.fishbone else None} for t in n.topics]
+ "fishbone": t.fishbone.to_json() if t.fishbone else None} for t in n.topics[frm:]]
o["conclusions"] = [c.text for c in n.conclusions]
o["todos"] = [t.text for t in n.todos]
o["terms"] = [t.to_json() for t in n.terms]
@@ -366,7 +571,10 @@ def parse(raw: str, times: list, started_at: float) -> MeetingNotes | None:
continue
points.append(text)
point_times.append(time_of(po.get("evidence")) if po is not None else None)
- start = num(t.get("start"))
+ # 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).
+ said = [x for x in [time_of(t.get("evidence"))] + point_times if x is not None]
+ start = min(said) if said else num(t.get("start"))
n.topics.append(NoteTopic(start=started_at if start is None else start, title=topic_title, summary=s(t.get("summary")),
points=points, pointTimes=point_times if any(x is not None for x in point_times) else None,
fishbone=fish))
diff --git a/linux/tests/test_core.py b/linux/tests/test_core.py
index 3852e6c..f08f8c9 100644
--- a/linux/tests/test_core.py
+++ b/linux/tests/test_core.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import math
import os
+import re
import shutil
import stat
import sys
@@ -574,9 +575,147 @@ class Notes(Base):
self.assertTrue(p.endswith("No markdown, no text outside the JSON."))
f = notesmod.prompt(MeetingNotes(), lines, 0, "English", final=True)
self.assertIn("This meeting ran 01:04: use at most 1 topic.", f)
+ self.assertIn("at most 8 in total", p, "nothing frozen yet: the Mac's wording")
+ self.assertIn("at most 8 in total", f)
+ self.assertIn("never append to it", p, "topic summaries stay one sentence")
+ log = "对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。" + "最新对方又补充了一些内容," * 20
+ self.assertEqual("对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。", notesmod.shortened(log))
+ self.assertEqual(notesmod.TOPIC_SUMMARY_LIMIT + 1, len(notesmod.shortened("长" * 200)))
self.assertTrue(notesmod.written(MeetingNotes(summary="讨论发布 Stripe"), "Simplified Chinese"))
self.assertFalse(notesmod.written(MeetingNotes(summary="We talked"), "Simplified Chinese"))
+ # Live notes rewrite only their last topics, so a long meeting's reply stays small (NotesTests.swift).
+
+ @staticmethod
+ def _topic(start, title, points=("p",), times=None):
+ return NoteTopic(start=float(start), title=title, summary="s", points=list(points), pointTimes=times)
+
+ @staticmethod
+ def _lines(n):
+ return [TranscriptLine(id="l%d" % i, t=float(i * 10), src="line %d" % i, srcLang="zh-CN", dstLang="en") for i in range(n)]
+
+ def test_keeps_frozen_topics_and_takes_the_replys_tail(self):
+ old = [self._topic(i * 100, "t%d" % i) for i in range(5)]
+ # The model echoed everything, renamed the current topic and added one.
+ reply = [self._topic(0, "t0"), self._topic(100, "t1 改"), self._topic(300, "t3"), self._topic(400, "t4 改"), self._topic(500, "t5")]
+ self.assertEqual(["t0", "t1", "t2", "t3", "t4 改", "t5"], [t.title for t in notesmod.merge(old, 3, reply)])
+
+ def test_nothing_frozen_keeps_every_topic(self):
+ # The first update over many lines: nothing to echo, so every topic is the model's own.
+ reply = [self._topic(i * 100, "t%d" % i) for i in range(5)]
+ self.assertEqual(reply, notesmod.merge([], 0, reply))
+ self.assertEqual(reply, notesmod.merge([self._topic(0, "t0")], 0, reply))
+
+ def test_empty_reply_keeps_the_topics(self):
+ old = [self._topic(0, "a"), self._topic(100, "b"), self._topic(200, "c")]
+ self.assertEqual(old, notesmod.merge(old, 1, []))
+ self.assertEqual(old, notesmod.merge(old, 1, [self._topic(0, "a")]))
+
+ def test_full_live_notes_join_the_shortest_settled_pair(self):
+ # Twelve topics, t3 and t4 the shortest neighbours (t3 to t5 is 100 s): a new topic still
+ # starts, and those two become one.
+ starts = [0, 100, 200, 300, 330, 400, 600, 700, 800, 900, 1000, 1100]
+ old = [self._topic(x, "t%d" % i, ["a%d" % i, "b%d" % i, "c%d" % i]) for i, x in enumerate(starts)]
+ reply = [self._topic(1000, "t10"), self._topic(1100, "t11"), self._topic(1200, "t12")]
+ merged = notesmod.merge(old, 10, reply)
+ self.assertEqual(notesmod.LIVE_MAX_TOPICS, len(merged))
+ self.assertEqual("t12", merged[-1].title)
+ self.assertEqual("t3 / t4", merged[3].title)
+ self.assertEqual(300, merged[3].start)
+ self.assertEqual(["a3", "b3", "a4", "b4"], merged[3].points)
+ self.assertEqual("s s", merged[3].summary)
+
+ def test_runaway_topic_summary_is_cut_to_its_first_sentence(self):
+ t = self._topic(0, "t0")
+ t.summary = "对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。" + "最新对方又补充了一些内容," * 20
+ self.assertEqual("对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。", notesmod.merge([], 0, [t])[0].summary)
+ self.assertEqual("short", notesmod.shortened("short"))
+
+ def test_live_prompt_sends_only_the_latest_topics(self):
+ notes = MeetingNotes(summary="summary", covered=20,
+ topics=[self._topic(0, "最早的话题"), self._topic(100, "第二个话题"), self._topic(200, "当前话题")])
+ p = notesmod.prompt(notes, self._lines(24), 20, "Simplified Chinese", False, frozen=1)
+ json = p.split("Current notes")[1].split("\n\n")[0]
+ self.assertIn("Earlier topics", p)
+ self.assertIn("- 00:00 最早的话题: s", p)
+ self.assertNotIn("最早的话题", json)
+ self.assertTrue("第二个话题" in json and "当前话题" in json)
+ self.assertIn("returning only the topics in the current notes and at most one new one after them", p)
+ self.assertNotIn("in total. A topic", p)
+ # A full rewrite has nothing frozen.
+ self.assertNotIn("Earlier topics", notesmod.prompt(notes, self._lines(24), 20, "Simplified Chinese", False))
+
+ def test_live_prompt_asks_for_one_sentence_summaries(self):
+ notes = MeetingNotes(summary="summary", covered=20, topics=[self._topic(i * 10, "t%d" % i) for i in range(8)])
+ p = notesmod.prompt(notes, self._lines(24), 20, "English", False, frozen=6)
+ self.assertNotIn("do not start a new topic", p)
+ self.assertIn("never append to it", p)
+
+ def test_long_meetings_split_by_time(self):
+ # A line every 10 s: 90 min stays whole, 4 h becomes four parts of an hour.
+ self.assertEqual([range(0, 540)], notesmod.parts(self._lines(540)))
+ four = notesmod.parts(self._lines(1440))
+ self.assertEqual(4, len(four))
+ self.assertEqual((0, 1440), (four[0].start, four[-1].stop))
+ self.assertTrue(all(a.stop == b.start for a, b in zip(four, four[1:])))
+ self.assertEqual([], notesmod.parts([]))
+
+ def test_part_prompt_keeps_line_numbers(self):
+ every = self._lines(720)
+ p = notesmod.prompt(MeetingNotes(), every[:480], 240, "English", True, part=(2, 3))
+ self.assertIn("part 2 of 3", p)
+ self.assertIn("[L241 40:00 对方] line 240", p)
+ self.assertNotIn("[L238 ", p)
+ self.assertIn("This part ran 39:50", p)
+ merge = notesmod.merge_prompt(['{"summary":"a"}', '{"summary":"b"}'], every, "English", False)
+ self.assertIn('Part 2 of 2:\n{"summary":"b"}', merge)
+ self.assertIn("Return the full notes as one JSON object", merge)
+ self.assertIn('"topics": []', merge)
+ # Each of three parts gets two of the eight topics.
+ self.assertIn("use at most 2 topics", p)
+
+ def test_topic_starts_when_its_lines_were_said(self):
+ times = [float(i * 60) for i in range(100)]
+ 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"]}]}"""
+ self.assertEqual([51 * 60, 300], [t.start for t in notesmod.parse(raw, times, 0.0).topics])
+
+ def test_part_topics_spread_over_the_part(self):
+ ten = [self._topic(i * 300, "t%d" % i) for i in range(10)]
+ self.assertEqual(["t0", "t3", "t6", "t9"], [t.title for t in notesmod.spread(ten, 4)])
+ self.assertEqual(["t0"], [t.title for t in notesmod.spread(ten, 1)])
+ self.assertEqual(3, len(notesmod.spread(ten[:3], 4)))
+
+ def test_long_final_in_parts_then_merged(self):
+ # Four hours: four part calls at once, then one merge; topics come from the parts.
+ store = SessionStore()
+ s = store.begin()
+ for l in self._lines(1440):
+ store.append(s.id, l)
+ asked = []
+
+ def respond(body):
+ sys_msg = content(body, 0)
+ asked.append(sys_msg)
+ if "noted in parts" in sys_msg:
+ k = int(re.search(r"part (\d) of 4", sys_msg).group(1))
+ first = (k - 1) * 360 + 1
+ return reply(jsonfmt.write({"summary": "第%d部分" % k, "topics": [
+ {"title": "话题%d-%d" % (k, j), "summary": "s", "evidence": ["L%d" % (first + j * 100)]} for j in range(3)]}, pretty=False))
+ return reply(jsonfmt.write({"title": "长会", "summary": "全程讨论", "topics": [{"title": "丢掉", "summary": "x"}]}, pretty=False))
+ LingClient.spacing = 0
+ notes = NotesEngine(client(Fake(respond)), store)
+ notes.generate(s.id)
+ notes._work.shutdown(wait=True)
+ n = store.get(s.id).notes
+ self.assertEqual(5, len(asked))
+ self.assertIn("Part 4 of 4:", asked[-1])
+ self.assertNotIn("话题1-0", asked[-1], "the parts go to the merge without their topics")
+ self.assertEqual("全程讨论", n.summary)
+ self.assertEqual(["话题%d-%d" % (k, j) for k in range(1, 5) for j in (0, 2)], [t.title for t in n.topics])
+ self.assertTrue(n.final)
+
def test_notes_prompt_matches_the_android_port(self):
"""The same prompt text as android/core Notes.kt, checked against its source so a change
on one side shows up here."""
@@ -587,6 +726,8 @@ class Notes(Base):
kt = f.read()
p = notesmod.prompt(MeetingNotes(), [TranscriptLine(t=1.0, src="x")], 0, "English", final=True)
for rule in [l for l in p.split("\n") if l.startswith("- ")]:
+ # The topic limit is filled in (live and final differ): check the rule from after it.
+ rule = rule.split("in total. ", 1)[-1] if rule.startswith("- Topics in time order") else rule
probe = rule.replace('"', '\\"')[:60]
self.assertIn(probe, kt, rule)