Files
teams-whisper/app/report.py
T

575 lines
36 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Topic summaries (local llama-server) + report.md / report.html rendering."""
import base64, difflib, json, re, unicodedata, urllib.request
# db: SQLite meeting store; llama: client for the local llama-server.
import db, llama
# Screen-capture kinds that count as shared content.
from shots import CONTENT_KINDS
# Base URL for Jira ticket links.
JIRA_BROWSE = "https://italdesign.atlassian.net/browse"
# Jira key, e.g. ABC-123: uppercase project of 2-10 chars, then 1-6 digits.
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
# Prompt pass 1: split the transcript/screen timeline into topics, answer as JSON.
SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"topics":[{"title":str,"start":"mm:ss","end":"mm:ss","summary":[str],"shown":[str],"decisions":[str],"actions":[{"who":str,"what":str,"when":str}],"open_questions":[str]}]}. '
'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. '
'In "shown" metti i fatti concreti visti a schermo e rilevanti per l\'argomento (valori, nomi di sistemi, ticket, errori, URL), ognuno iniziando con il timestamp "mm:ss" della riga [SCHERMO] da cui proviene. '
'Se parlato e schermo divergono, riportalo nel summary. Usa solo fatti presenti nel testo. '
'Usa i nomi dei partecipanti solo se compaiono nel testo come nomi propri; non citare mai le etichette "Speaker N": usa forme impersonali ("si conferma", "viene proposto"). Ogni argomento copre almeno 3 minuti di discussione: non creare un argomento per ogni schermata. '
'Nel summary riporta ciò che è stato detto, spiegato e deciso, non la navigazione tra le schermate (es. «si apre la console»): al massimo 6 punti per argomento. '
'Non scrivere voci vuote come «nessuna domanda aperta»: lascia la lista vuota. Scrivi tutto in italiano. Se non sei sicuro, ometti. '
'Glossario dei termini corretti letti dallo schermo (la trascrizione può storpiarli, usa la grafia del glossario): ')
# Prompt pass 3: meeting title + up to 5 TL;DR points from the topic list.
SYS_B = 'Dato l\'elenco degli argomenti, rispondi SOLO JSON: {"title":str,"tldr":[str]}. title: titolo breve della riunione (max 8 parole). Massimo 5 punti in tldr, in italiano, forma impersonale, senza etichette "Speaker N". Usa solo fatti presenti.'
# Prompt pass 2 (per topic): complete the summary with numbered doc extracts; from_docs = extra doc facts.
SYS_D = ('Hai un argomento di una riunione e alcuni estratti di documentazione aziendale numerati. Rispondi SOLO JSON: {"summary":[{"text":str,"doc":int|null}],"from_docs":[{"text":str,"doc":int}]}. '
'"summary": riscrivi i punti della sintesi mantenendo tutti i fatti della riunione; puoi completarli o correggerli con la documentazione indicando in "doc" il numero dell\'estratto usato (null se il punto viene solo dalla riunione). '
'Se riunione e documentazione divergono, riporta entrambe ("in riunione …; secondo la documentazione …"). "from_docs": massimo 3 fatti della documentazione pertinenti all\'argomento e non detti in riunione. Non citare etichette "Speaker N". Non inventare. Scrivi in italiano.')
# Tuning: CLUSTER = name similarity to merge spellings; TIDY_MIN = seconds below which a topic is merged into a neighbour; DOC_MIN = shared long words needed to attach a doc.
CLUSTER, TIDY_MIN, DOC_MIN = 0.82, 120, 3
# Local GUI server, used for links to previous meetings.
GUI = "http://127.0.0.1:18765"
# Seconds -> "mm:ss".
def mmss(s): s = int(s); return f"{s // 60:02d}:{s % 60:02d}"
# "mm:ss" (or leading digits) -> seconds; 0 if no match.
def secs(s):
m = re.match(r"(\d+):(\d+)", str(s))
return int(m[1]) * 60 + int(m[2]) if m else 0
PROG = None # [name, calls done, calls expected] while report.run() is active
# Progress note: print (goes to the Prefect log) and, while run() is active, advance the DB progress counter.
def _tick(note):
print(f"report: {note}", flush=True) # flow(log_prints=True) -> Prefect log
if PROG: PROG[1] += 1; db.tick(PROG[0], PROG[1], max(PROG[2], PROG[1] + 1) if note != "fine" else PROG[1], note)
# Title typed manually in the meeting metadata (wins over the LLM title).
def _manual_title(name):
return db.meta(name).get("title", "")
THINK = 1024 # reasoning budget per report call (server: --reasoning-budget); added to max_tokens so the answer keeps its room
def _strip_junk(o):
"""Small models sometimes append '<closing braces> + a self-check' inside the last string value: cut it."""
if isinstance(o, str): return re.split(r"[\]}]{2,}|[\u2705\u2714\u274c]", o)[0].strip()
if isinstance(o, list): return [_strip_junk(x) for x in o]
if isinstance(o, dict): return {k: _strip_junk(v) for k, v in o.items()}
return o
def chat(system, user, max_tokens, retries=2, think=False):
"""think=True only for the report passes (topics, docs merge, overview); docs queries and memory stay fast."""
# response_format requests JSON; enable_thinking toggles reasoning. THINK tokens are added only when thinking is on.
body = {"temperature": 0.2, "max_tokens": max_tokens + (THINK if think else 0),
"chat_template_kwargs": {"enable_thinking": think}, "response_format": {"type": "json_object"},
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
# Retry on unparseable output or a non-dict result.
for _ in range(retries):
try:
try:
r = llama.post(body, False, 1800)
except urllib.error.HTTPError as e:
# Only HTTP 400 is retried without response_format; other errors propagate.
if e.code != 400: raise
body.pop("response_format", None)
r = llama.post(body, False, 1800)
# Extract the assistant text from the response.
t = llama.content(r, f"report ({max_tokens} max)")
# Drop <think>...</think> reasoning blocks emitted by thinking models.
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
# Parse the outermost {...} span (tolerates prose around the JSON), then strip junk.
d = _strip_junk(json.loads(t[t.find("{"):t.rfind("}") + 1]))
if isinstance(d, dict): return d
except (ValueError, KeyError): pass
return None
def _transcript(name):
"""[(sec, "Speaker N" | None, text)] from the lines table: diarize stores the speaker-labelled paragraphs there, names are applied at render time."""
return [(int(t), sp, x) for t, sp, x in db.connect().execute("SELECT t, speaker, text FROM lines WHERE name=? ORDER BY rowid", (name,))]
# Read out/<name>/<f> as JSON, or return default if the file is missing.
def _load(name, f, default):
p = db.out_dir(name) / f
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else default
# Presence-share spans from share_start/share_stop events; a share still open at the end runs to dur.
def _shares(evs, dur):
out, open_ = [], {}
for e in evs:
if e["kind"] == "share_start": open_[e["who"]] = e["t"]
elif e["kind"] == "share_stop" and e["who"] in open_: out.append({"who": e["who"], "start": open_.pop(e["who"]), "end": e["t"]})
out += [{"who": w, "start": s, "end": dur} for w, s in open_.items()]
return sorted(out, key=lambda x: x["start"])
# Replace "Speaker N" labels in a string with mapped names (unknown labels kept as-is).
def _subst(s, names):
return re.sub(r"\bSpeaker (\d+)\b", lambda m: names.get(m[0]) or m[0], s) if isinstance(s, str) else s
# Apply f to every string leaf of a nested list/dict, returning a new structure.
def _deep(o, f):
if isinstance(o, str): return f(o)
if isinstance(o, list): return [_deep(x, f) for x in o]
if isinstance(o, dict): return {k: _deep(v, f) for k, v in o.items()}
return o
# Merge consecutive topics with equal titles (case-insensitive) into one.
def _merge(topics):
out = []
for t in topics:
if out and out[-1]["title"].lower() == t["title"].lower():
p = out[-1]
for k in ("summary", "shown", "decisions", "actions", "open_questions"): p[k] = p[k] + t[k]
p["end_s"] = t["end_s"]
else: out.append(t)
return out
# Name normalization: strip accents, lowercase, collapse whitespace, sort words so word order does not matter.
def _key(n): return " ".join(sorted(unicodedata.normalize("NFKD", n).encode("ascii", "ignore").decode().lower().split()))
# Similarity 0..1 of two names after _key normalization.
def _sim(a, b): return difflib.SequenceMatcher(None, _key(a), _key(b)).ratio()
def canon(counts, known, video=False, thr=CLUSTER):
"""raw name -> canonical spelling (known list first, else most frequent of a similarity cluster); dropped names have no entry."""
out, clusters = {}, []
for raw, c in sorted(counts.items(), key=lambda x: -x[1]):
if " " not in raw or len(raw) <= 4 or "..." in raw or "…" in raw: continue
best = max(((_sim(raw, k), k) for k in known), default=(0, None))
if best[0] >= .75: out[raw] = best[1]; continue
cl = next((x for x in clusters if _sim(raw, x[0]) >= thr), None)
if cl: cl[1] += c; cl[2].append(raw)
else: clusters.append([raw, c, [raw]])
for rep, tot, mem in clusters:
if video and tot < 2: continue
for m in mem: out[m] = rep
return out
# Re-key attendee spans by canonical name; merged names keep the earliest first_t and latest last_t.
def _canon_att(att, cmap):
out = {}
for a in att.values():
c = cmap.get(a["who"])
if not c: continue
x = out.setdefault(c, {"who": c, "first_t": a["first_t"], "last_t": a["last_t"]})
x["first_t"], x["last_t"] = min(x["first_t"], a["first_t"]), max(x["last_t"], a["last_t"])
return out
# Rename share presenters to canonical names (drop unknown ones), merge same-presenter shares with gaps <= 60 s, drop spans < 20 s; repeat until stable.
def _canon_shares(shares, cmap):
ss = sorted(({**s, "who": cmap[s["who"]]} for s in shares if s["who"] in cmap), key=lambda s: s["start"])
while True:
out = []
for s in ss:
if out and out[-1]["who"] == s["who"] and s["start"] - out[-1]["end"] <= 60: out[-1]["end"] = max(out[-1]["end"], s["end"])
else: out.append(dict(s))
kept = [s for s in out if s["end"] - s["start"] >= 20]
if len(kept) == len(ss): return kept
ss = kept
def _tidy(topics, dur, min_s=TIDY_MIN):
"""Sort, de-overlap, merge topics shorter than min_s into a neighbour, keep only screen facts timed inside the topic."""
# Sort, then push each topic to start no earlier than the previous one ends (no overlap); min length 1 s.
topics.sort(key=lambda t: t["start_s"])
prev = 0
for t in topics: t["start_s"] = max(t["start_s"], prev); t["end_s"] = max(t["end_s"], t["start_s"] + 1); prev = t["end_s"]
ln = lambda t: t["end_s"] - t["start_s"]
# Repeatedly merge the first topic shorter than min_s into a neighbour.
while len(topics) > 1:
i = next((i for i, t in enumerate(topics) if ln(t) < min_s), None)
if i is None: break
# Neighbour: the previous topic, or the next one when the short topic is first.
j = i - 1 if i else 1
lo, hi = min(i, j), max(i, j)
a, b = topics[lo], topics[hi]
m = dict(a)
# Merged topic keeps the title of the longer of the two.
m["title"] = (a if ln(a) >= ln(b) else b)["title"]
for k in ("summary", "shown", "decisions", "actions", "open_questions"): m[k] = a[k] + b[k]
# Drop filler and duplicates created by the merge.
for k in ("decisions", "open_questions"): m[k] = _clean(m[k])
m["start_s"], m["end_s"] = min(a["start_s"], b["start_s"]), max(a["end_s"], b["end_s"])
topics[lo:hi + 1] = [m]
for t in topics:
# Keep shown facts whose mm:ss timestamp lies within the topic window, +/- 30 s.
t["shown"] = [x for x in t["shown"] if (m := re.search(r"(\d\d):(\d\d)", str(x))) and t["start_s"] - 30 <= int(m[1]) * 60 + int(m[2]) <= t["end_s"] + 30]
return topics
# Model filler to discard: "nessuno/a", "non sono/è emers/stat...", "n/a", or lines of dashes.
FILLER = re.compile(r"(?i)^\s*(nessun[aoe]?|non (sono|è) (emers|stat)|n/?a\b|-+$)")
def _clean(xs):
"""Drop model filler ("Nessuna domanda aperta emersa…") and duplicates; merged topics repeated them."""
out = []
for x in xs:
x = str(x).strip()
if x and not FILLER.match(x) and x.lower() not in {o.lower() for o in out}: out.append(x)
return out
# Distinct lowercase words of 5+ letters: a cheap overlap signal for topic/doc matching.
def _words(s): return {w for w in re.findall(r"\w+", s.lower()) if len(w) >= 5}
def _pass_d(t, docs):
"""Complete/correct a topic's summary with the best-matching docs; sets t['summary'] and t['from_docs'] as {text, doc} dicts."""
# Words of the topic (title, summary, shown) to match against docs.
w = _words(" ".join([t["title"], *(x["text"] for x in t["summary"]), *t["shown"]]))
# Rank docs by number of shared words; keep the top 3 that reach DOC_MIN.
top = sorted(((len(w & _words(d["title"] + " " + d["body"])), d) for d in docs), key=lambda x: -x[0])
top = [d for n, d in top[:3] if n >= DOC_MIN]
if not top: return
# Numbered doc extracts [1..n] appended to the topic.
user = f"ARGOMENTO: {t['title']}\nSINTESI:\n" + "\n".join(f"- {x['text']}" for x in t["summary"]) + "\n\nDOCUMENTI:\n" + "\n\n".join(
f"[{n}] {d['title']} ({d['source']})\n{d['body'][:2500]}" for n, d in enumerate(top, 1))
r = chat(SYS_D, user, 2500, think=True) or {}
# Map 1-based prompt doc number -> docs item index "i"; None if invalid.
ref = lambda n: top[n - 1]["i"] if isinstance(n, int) and 1 <= n <= len(top) else None
# Normalize LLM items to {text, doc}; drop empty ones.
fix = lambda l: [{"text": str(x["text"]), "doc": ref(x.get("doc"))} for x in l if isinstance(x, dict) and x.get("text")]
s = fix(r.get("summary") or [])
# Replace the summary only if the LLM returned something.
if s: t["summary"] = s
# from_docs: max 3, and only entries that cite a valid doc.
t["from_docs"] = [x for x in fix(r.get("from_docs") or [])[:3] if x["doc"] is not None]
def run(name, window_words=3000):
# Pipeline: (1) gather inputs, (2) build a timeline, (3) LLM topic extraction per chunk,
# (4) tidy topics, (5) docs pass + overview, (6) attach shots, (7) references, (8) write report.json and topics.
rec = db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
tx = _transcript(name)
# Duration from the recordings table, else last transcript timestamp + 5 s.
dur = (rec and rec[0]) or (tx[-1][0] + 5 if tx else 0)
shots = _load(name, "shots.json", []); glossary = _load(name, "glossary.json", [])
crop_ok = any((s.get("view") or "").startswith("view_") for s in shots) # when crops exist, frames without one show no shared content
# A shot is usable if its kind is a content kind and, when crops exist, it has a view_* crop.
usable = lambda s: s["kind"] in CONTENT_KINDS and (not crop_ok or (s.get("view") or "").startswith("view_"))
# Meeting event stream: meta, presence, share, chat, raised hand.
evs = db.events(name, "meta", "present", "share_start", "share_stop", "chat", "hand")
names = db.speaker_names(name)
meta = [json.loads(e["text"]) for e in evs if e["kind"] == "meta" and e["who_key"] != "video"] # Teams topic only; else LLM title from transcript
title = (meta[-1].get("title") or "") if meta else ""
# Share spans per presenter.
shares = _shares(evs, dur)
# att: attendee presence spans; src: sources that reported presence; counts: mentions per name (for canonicalization).
att, src, counts = {}, set(), {}
for e in evs:
if e["kind"] != "present": continue
for p in json.loads(e["text"] or "[]"):
a = att.setdefault(p["who"], {"who": p["who"], "first_t": e["t"], "last_t": e["t"]})
a["last_t"] = max(a["last_t"], e["t"])
src.add("video" if e["who_key"] == "video" else "teams")
counts[p["who"]] = counts.get(p["who"], 0) + 1
# "teams" if any Teams presence was seen, "video" if only video-frame names, else "none".
attendees_source = "teams" if "teams" in src else "video" if src else "none"
# Presenters read from shots count as mentions too.
for s in shots:
if s.get("presenter"): n = db.norm_name(s["presenter"]); counts[n] = counts.get(n, 0) + 1
# Sharers count as mentions too.
for s in shares: counts[s["who"]] = counts.get(s["who"], 0) + 1
# Known spellings: people from earlier docs.json plus Teams presence names.
known = list(dict.fromkeys(_load(name, "docs.json", {"people": []}).get("people", []) +
[p["who"] for e in evs if e["kind"] == "present" and e["who_key"] != "video" for p in json.loads(e["text"] or "[]")]))
# Canonical spelling per raw name; video-sourced names need at least 2 mentions.
cmap = canon(counts, known, video=attendees_source == "video")
# Apply the canonical map to attendees and shares.
att, shares = _canon_att(att, cmap), _canon_shares(shares, cmap)
# Chat messages for the report.
chats = [{"t": e["t"], "who": e["who"], "text": e["text"]} for e in evs if e["kind"] == "chat"]
# timeline items: (t, line)
items = [(t, f"[{mmss(t)}] " + (f"{names.get(sp, sp)}: " if sp else "") + x, len(x.split())) for t, sp, x in tx]
prev_text = None
for s in filter(usable, shots):
# Who was sharing at this frame's time, if anyone.
sh = next((x["who"] for x in shares if x["start"] <= s["t"] < x["end"]), None)
l = f"[{mmss(s['t'])}] [SCHERMO {s['kind']}{', condiviso da ' + sh if sh else ''}] {s.get('title') or ''}: {s.get('summary') or ''}"
# Include OCR text only when it differs from the previous frame; cap at 600 chars.
if s.get("text") and s["text"] != prev_text: l += "\n testo: " + s["text"].replace("\n", " / ")[:600]
prev_text = s.get("text"); items.append((s["t"], l, len(l.split())))
items += [(c["t"], f"[{mmss(c['t'])}] [CHAT] {c['who']}: {c['text']}", 0) for c in chats]
items += [(e["t"], f"[{mmss(e['t'])}] [MANO ALZATA] {e['who']}", 0) for e in evs if e["kind"] == "hand"]
items.sort(key=lambda x: x[0])
# Progress counter shared with _tick: [name, done, expected].
global PROG
# Split the timeline into chunks of about window_words words.
n_chunks = max(1, -(-sum(w for _, _, w in items) // window_words))
PROG = [name, 0, n_chunks + 3 * n_chunks + 1] # chunks + ~3 topics per chunk (docs pass) + overview
db.tick(name, 0, PROG[2], f"argomenti: blocco 1 di {n_chunks}")
# System prompt + glossary (or "nessuno").
system = SYS_A + (", ".join(glossary) or "nessuno")
topics, buf, words, wstart = [], [], 0, 0
# Send the buffered chunk to the LLM and append its topics.
def flush(end):
nonlocal buf, words
if not buf: return
d = chat(system, "\n".join(buf), 4000, think=True); _tick(f"argomenti: blocco {PROG[1] + 1} di {n_chunks} fatto")
ts = d.get("topics") if d else None
if not ts:
# Placeholder topic when the LLM returns nothing, so the time range is not lost.
ts = [{"title": f"Parte {mmss(wstart)}–{mmss(end)}", "start": mmss(wstart), "end": mmss(end), "summary": ["(riassunto non disponibile)"]}]
for t in ts:
t = {"title": str(t.get("title") or "Argomento"), "summary": list(t.get("summary") or []), "shown": list(t.get("shown") or []),
"decisions": _clean(t.get("decisions") or []), "actions": [a for a in (t.get("actions") or []) if isinstance(a, dict)],
"open_questions": _clean(t.get("open_questions") or []),
"start_s": secs(t.get("start")), "end_s": secs(t.get("end"))}
# Clamp end time into [start + 1 s, recording duration].
t["end_s"] = min(max(t["end_s"], t["start_s"] + 1), max(dur, t["start_s"] + 1))
topics.append(t)
buf, words = [], 0
# Group timeline items into chunks of ~window_words words, flushing at each boundary.
for t, l, w in items:
if not buf: wstart = t
buf.append(l); words += w
if words >= window_words: flush(t)
# Flush the last chunk.
flush(items[-1][0] if items else 0)
# Sort/merge/clamp topics (see _tidy).
topics = _tidy(topics, dur)
for t in topics:
# Action owners labelled "Speaker N" without a known name are blanked.
for a in t["actions"]:
if re.fullmatch(r"Speaker \d+", str(a.get("who", ""))) and a["who"] not in names: a["who"] = ""
# Candidate docs from docs.json (empty if no docs pass ran).
docs = _load(name, "docs.json", {"items": [], "people": []})["items"]
# Expected progress: the docs pass costs one tick per topic (when docs exist), plus the overview.
PROG[2] = PROG[1] + (len(topics) if docs else 0) + 1
for t in topics:
# Summaries become {text, doc} dicts; doc is filled in by the docs pass.
t["summary"] = [{"text": str(s), "doc": None} for s in t["summary"]]
t["from_docs"] = []
if docs: _pass_d(t, docs); _tick(f"documentazione per «{t['title'][:50]}»")
# Overview pass: title and TL;DR from the topics.
ov = chat(SYS_B, json.dumps([{"title": t["title"], "summary": [x["text"] for x in t["summary"]], "shown": t["shown"], "decisions": t["decisions"], "actions": t["actions"]} for t in topics], ensure_ascii=False), 800, think=True) or {}; _tick("fine")
tldr = [str(x) for x in (ov.get("tldr") or [])][:5]
# Manual title wins; otherwise the LLM title.
title = title or str(ov.get("title") or "").strip()
# Shots to attach: lead frames with usable content and at least 40 chars of OCR text.
good = [s for s in shots if s.get("lead") and usable(s) and len(s.get("text") or "") >= 40]
# Reset each topic's shot list.
for t in topics: t["shots"] = []
for s in good:
if not topics: break
# Topic containing the shot's time; else the topic with the nearest start.
tp = next((t for t in topics if t["start_s"] <= s["t"] <= t["end_s"]), None) or min(topics, key=lambda t: abs(t["start_s"] - s["t"]))
tp["shots"].append(s)
for t in topics:
# Keep the two shots with the most OCR text, then restore time order.
best = sorted(t["shots"], key=lambda s: -len(s.get("text") or ""))[:2]
t["shots"] = sorted(best, key=lambda s: s["t"])
# Entities from usable shots (urls/emails/numbers/systems) and ticket keys from speech.
cshots = [s for s in shots if usable(s)]
refs = {"tickets": {}, "urls": {}, "systems": {}, "emails": {}, "numbers": {}}
sysn = {}
# Collect entities from each usable shot.
for s in cshots:
e = s.get("entities") or {}
for k in ("urls", "emails", "numbers"):
for v in e.get(k, []): refs[k].setdefault(v, s["t"])
# System names keyed by lowercase; remember which frames show them.
for v in e.get("systems", []): sysn.setdefault(v.lower(), (v, set()))[1].add(s["file"])
# Lowercased transcript for substring checks.
alltx = " ".join(x for _, _, x in tx).lower()
# Keep systems seen in >= 2 frames or mentioned in speech; first time wins; names under 3 chars dropped.
for low, (v, files) in sysn.items():
if len(v) >= 3 and (len(files) >= 2 or low in alltx):
refs["systems"][v] = min(s["t"] for s in cshots if s["file"] in files)
# Ticket keys mentioned in speech, with first timestamp.
for t, _, x in tx:
for k in TICKET.findall(x): refs["tickets"].setdefault(k, t)
references = {"tickets": [{"key": k, "first_t": t} for k, t in refs["tickets"].items()],
"urls": [{"url": k, "first_t": t} for k, t in refs["urls"].items()],
"systems": [{"name": k, "first_t": t} for k, t in refs["systems"].items()],
"emails": [{"email": k, "first_t": t} for k, t in refs["emails"].items()],
"numbers": [{"value": k, "t": t} for k, t in refs["numbers"].items()]}
# Screen timeline: usable lead frames; consecutive frames with the same title are merged.
screen = []
for s in shots:
if not s.get("lead") or not usable(s): continue
r = {k: s.get(k) for k in ("t", "t_end", "kind", "title", "summary")}
if screen and (screen[-1]["title"] or "").lower() == (r["title"] or "").lower(): screen[-1]["t_end"] = r["t_end"]
else: screen.append(r)
# Parse date/time from the recording name (teams_/meet_ YYYY-MM-DDTHH-MM-SS).
m = re.match(r"(?:teams|meet)_(\d{4}-\d\d-\d\d)T(\d\d)-(\d\d)-\d\d", name)
rep = {"name": name, "date": f"{m[1]} {m[2]}:{m[3]}" if m else "", "duration_s": dur, "meeting_title": _manual_title(name) or title,
"tldr": tldr, "attendees": list(att.values()), "attendees_source": attendees_source, "known_spelling": bool(known),
"name_map": cmap, "shares": shares, "chat": chats, "references": references, "screen": screen, "topics": topics}
# report.json is what render() reads; topics also go to the DB table.
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
db.replace_topics(name, topics)
def retitle(name):
"""Regenerate the meeting title from the saved topics (LLM overview pass); drops the manual title. Render is done by the caller."""
p = db.out_dir(name) / "report.json"
rep = json.loads(p.read_text(encoding="utf-8"))
ov = chat(SYS_B, json.dumps([{"title": t["title"], "summary": [x["text"] for x in t["summary"]], "shown": t["shown"], "decisions": t["decisions"], "actions": t["actions"]} for t in rep["topics"]], ensure_ascii=False), 800, think=True) or {}
t = str(ov.get("title") or "").strip()
if not t: raise RuntimeError("title: nessun titolo generato")
db.set_meta(name, title="")
rep["meeting_title"] = t
p.write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
# Topic heading "N. title (start–end)"; slugified for anchors in render().
def _head(i, t): return f"{i}. {t['title']} ({mmss(t['start_s'])}–{mmss(t['end_s'])})"
# Apply the speaker-name map to every string in the report; unmapped "Speaker N" becomes "un partecipante".
# Returns (report, label -> name map).
def named(name, rep):
nm = rep.get("name_map", {})
names = {l: nm.get(p, p) for l, p in db.speaker_names(name).items()}
return _deep(rep, lambda s: re.sub(r"\bSpeaker \d+\b", "un partecipante", _subst(s, names))), names
# Render report.md and report.html from report.json (plus docs.json and diarization segments).
def render(name):
import markdown
from markdown.extensions.toc import slugify
d = db.out_dir(name)
rep = json.loads((d / "report.json").read_text(encoding="utf-8"))
docs = _load(name, "docs.json", None)
items = {x["i"]: x for x in (docs or {}).get("items", [])}
rep, names = named(name, rep)
# Diarization segments (label, start, end) for talk time.
segs = _load(name, "diar_segments.json", [])
# Turn ticket keys into Jira links.
link = lambda s: TICKET.sub(lambda m: f"[{m[0]}]({JIRA_BROWSE}/{m[0]})", s)
# Strip brackets and quotes so text fits in Markdown link text/titles.
q = lambda s: re.sub(r'[\[\]"]', "", s or "")
md = [f"# {rep['meeting_title'] or 'Riunione'} — {rep['date']}", "", f"**Durata:** {int(rep['duration_s'] // 60)} min", "", "## In breve", ""]
md += [f"- {x}" for x in rep["tldr"]] + [""]
# participants
# Talk time per named speaker, summed from diarization segments.
talk = {}
for s in segs:
p = names.get(s["label"])
if p: talk[p] = talk.get(p, 0) + s["end"] - s["start"]
# Video-sourced attendance: names read from frames only, no presence times.
video = rep["attendees_source"] == "video"
if video:
people = sorted({a["who"] for a in rep["attendees"]})
if talk or people: md += ["## Partecipanti", ""]
if talk: md += ["| Partecipante | Parlato |", "|---|---|"] + [f"| {p} | {int(v // 60)} min |" for p, v in talk.items()] + [""]
if people:
md += ["*Nomi letti dai fotogrammi (ortografia verificata sulla documentazione): verificare.*" if rep.get("known_spelling") else "*Nomi letti dai fotogrammi: verificare.*", "", ", ".join(people), ""]
else:
rows = {p: [v, None] for p, v in talk.items()}
# Teams-sourced: join talk time with presence windows by name (case-insensitive).
for a in rep["attendees"]:
k = next((p for p in rows if p.lower() == a["who"].lower()), a["who"])
rows.setdefault(k, [0, None])[1] = f"{mmss(a['first_t'])}–{mmss(a['last_t'])}"
if rows:
md += ["## Partecipanti", "", "| Partecipante | Parlato | Presente |", "|---|---|---|"]
md += [f"| {p} | {f'{int(v[0] // 60)} min' if v[0] else '—'} | {v[1] or '—'} |" for p, v in rows.items()] + [""]
# Screen-share spans.
if rep["shares"]:
md += ["## Condivisioni schermo", ""] + [f"- {mmss(s['start'])}–{mmss(s['end'])} {s['who']}" for s in rep["shares"]] + [""]
heads = []
# Topic index with anchor links to the sections below.
md += ["## Argomenti", ""]
for i, t in enumerate(rep["topics"], 1):
h = _head(i, t)
heads.append(h)
md.append(f"{i}. [{t['title']}](#{slugify(h, '-')})")
md.append("")
# Summary bullet; add a 📄 link when the cited doc is in items.
def cite(x):
x = x if isinstance(x, dict) else {"text": x, "doc": None}
c = f' [📄]({items[x["doc"]]["url"]} "{q(items[x["doc"]]["title"])}")' if x.get("doc") in items else ""
return f"- {x['text']}{c}"
for h, t in zip(heads, rep["topics"]):
md += [f"## {h}", "", "### Sintesi", ""] + [cite(x) for x in t["summary"]] + [""]
# Only doc facts whose doc is present in items.
fd = [x for x in t.get("from_docs", []) if x.get("doc") in items]
if fd: md += ["### Dalla documentazione", ""] + [f"- 📄 {x['text']} — [{q(items[x['doc']]['title'])}]({items[x['doc']]['url']})" for x in fd] + [""]
# Previous-meeting references, linked to the GUI report anchors.
pv = t.get("previous") or []
if pv: md += ["### Dalle riunioni precedenti", ""] + [f"- **{x['status']}** — {x['text']} — [{q(x.get('meeting') or x['name'])} {x['date']}, {q(x['topic'])} {mmss(x['t'])}]({GUI}/report?name={x['name']}#{x['anchor']})" for x in pv] + [""]
if t["shown"]: md += ["### Mostrato a schermo", ""] + [f"- {link(x)}" for x in t["shown"]] + [""]
if t["decisions"]: md += ["### Decisioni", ""] + [f"- {x}" for x in t["decisions"]] + [""]
if t["open_questions"]: md += ["### Domande aperte", ""] + [f"- {x}" for x in t["open_questions"]] + [""]
if t["actions"]:
md += ["### Azioni", "", "| Chi | Cosa | Quando |", "|---|---|---|"]
md += [f"| {a.get('who', '')} | {a.get('what', '')} | {a.get('when', '')} |" for a in t["actions"]] + [""]
# Embed shots: crop view if present, else the full frame; caption has time, sharer, summary.
for s in t["shots"]:
alt = re.sub(r"[\[\]()]", "", s.get("title") or "")
sh = next((x["who"] for x in rep["shares"] if x["start"] <= s["t"] < x["end"]), None)
cap = f"{mmss(s['t'])} — " + (f"condiviso da {sh} — " if sh else "") + f"{s.get('title') or ''} — {s.get('summary') or ''}"
md += [f"![{alt}](shots/{s.get('view') or s['file']})", "", f"*{cap}*", ""]
# Related docs section (items from docs.json).
if items:
md += ["## Documentazione correlata", ""]
for x in items.values():
md.append((f"- 🎫 [{q(x['key'])} — {q(x['title'])}]({x['url']}) — {x['status'] or ''}" if x["source"] == "jira" else f"- 📄 [{q(x['title'])}]({x['url']}) — Confluence")
+ (" — citato in riunione" if x.get("mentioned") else ""))
md.append("")
if rep["chat"]:
md += ["## Chat", ""] + [f"[{mmss(c['t'])}] **{c['who']}:** {c['text']} " for c in rep["chat"]] + [""]
r = rep["references"]
# Tickets: from docs when docs.json exists (only those mentioned in the meeting), else transcript references.
tk = ([f"[{x['key']}]({x['url']}) — {q(x['title'])}" for x in items.values() if x["source"] == "jira" and x.get("mentioned")] if docs is not None
else [f"[{x['key']}]({JIRA_BROWSE}/{x['key']}) — {mmss(x['first_t'])}" for x in r["tickets"]])
sy = [f"{x['name']} — {mmss(x['first_t'])}" for x in r["systems"]]
if tk or sy:
md += ["## Riferimenti", ""]
for k, v in (("Ticket", tk), ("Sistemi", sy)):
if v: md += [f"**{k}**", ""] + [f"- {x}" for x in v] + [""]
# Collapsible screen timeline; table cells escape "|" and newlines.
if rep["screen"]:
md += [f'<details markdown="1"><summary>Cronologia schermo ({len(rep["screen"])} schermate)</summary>', "",
"## Cronologia schermo", "", "| Da | A | Tipo | Titolo | Sintesi |", "|---|---|---|---|---|"]
cell = lambda x: (x or "").replace("|", "/").replace("\n", " ")
md += [f"| {mmss(s['t'])} | {mmss(s['t_end'] or 0)} | {s['kind']} | {cell(s['title'])} | {cell(s['summary'])} |" for s in rep["screen"]]
md += ["", "</details>", ""]
text = "\n".join(md)
(d / "report.md").write_text(text, encoding="utf-8")
# Markdown -> HTML (tables, toc, raw HTML blocks).
body = markdown.markdown(text, extensions=["tables", "toc", "md_in_html"])
# Inline shot images as base64 so the HTML is self-contained.
body = re.sub(r'src="shots/([^"]+)"', lambda m: 'src="data:image/jpeg;base64,' + base64.b64encode((d / "shots" / m[1]).read_bytes()).decode() + '"', body)
# Plain title from the first heading line.
h1 = re.sub(r"[#]+ ", "", md[0])
# Inline CSS: light theme; dark theme via prefers-color-scheme.
css = """:root{--bg:#faf9f5;--card:#fff;--soft:#f0eee6;--line:#e8e6dc;--fg:#141413;--mut:#6b6a64;--acc:#c96442}
@media screen and (prefers-color-scheme:dark){:root{--bg:#262624;--card:#30302e;--soft:#1f1e1d;--line:#3e3e38;--fg:#f5f4ed;--mut:#a3a29a;--acc:#d97757}}
*{box-sizing:border-box}body{max-width:860px;margin:auto;padding:56px 24px 96px;background:var(--bg);color:var(--fg);font:16px/1.65 system-ui,-apple-system,"Segoe UI",sans-serif}
h1,h2{font-family:ui-serif,Georgia,"Times New Roman",serif;font-weight:500;line-height:1.25;letter-spacing:-.01em}
h1{font-size:2.2em;margin:0 0 .2em}h1+p{color:var(--mut);margin-top:0}
h2{font-size:1.5em;margin:2em 0 .6em;padding-top:1em;border-top:1px solid var(--line)}
h3{font-size:.78em;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--mut);margin:1.8em 0 .4em}
a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline}
ul,ol{padding-left:1.4em}li{margin:.3em 0}li::marker{color:var(--acc)}
#in-breve{border-top:0}#in-breve+ul{background:var(--soft);border-left:3px solid var(--acc);border-radius:10px;padding:16px 20px 16px 2.4em}
table{border-collapse:separate;border-spacing:0;width:100%;background:var(--card);border:1px solid var(--line);border-radius:12px;overflow:hidden;font-size:.92em}
td,th{padding:9px 14px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}tr:last-child td{border-bottom:0}th{background:var(--soft);font-weight:600}
img{width:100%;border:1px solid var(--line);border-radius:12px;margin-top:.8em}p>em{color:var(--mut);font-size:.88em}
details{margin-top:2.4em;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 18px}summary{cursor:pointer;color:var(--acc);font-weight:500}
code{background:var(--soft);border-radius:5px;padding:.1em .35em;font-size:.9em}"""
# Write a single self-contained HTML document (CSS inline, images base64).
(d / "report.html").write_text(f'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{h1}</title><style>{css}</style>\n{body}', encoding="utf-8")