"""Topic summaries (local llama-server) + report.md / report.html rendering.""" import base64 import difflib import json import re import unicodedata import urllib.request # db: SQLite meeting store; llama: client for the local llama-server. import db import 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(seconds): seconds = int(seconds) return f"{seconds // 60:02d}:{seconds % 60:02d}" # "mm:ss" (or leading digits) -> seconds; 0 if no match. def secs(text): match = re.match(r"(\d+):(\d+)", str(text)) return int(match[1]) * 60 + int(match[2]) if match 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(obj): """Small models sometimes append ' + a self-check' inside the last string value: cut it.""" if isinstance(obj, str): return re.split(r"[\]}]{2,}|[\u2705\u2714\u274c]", obj)[0].strip() if isinstance(obj, list): return [_strip_junk(item) for item in obj] if isinstance(obj, dict): return {key: _strip_junk(value) for key, value in obj.items()} return obj 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: response = llama.post(body, False, 1800) except urllib.error.HTTPError as error: # Only HTTP 400 is retried without response_format; other errors propagate. if error.code != 400: raise body.pop("response_format", None) response = llama.post(body, False, 1800) # Extract the assistant text from the response. text = llama.content(response, f"report ({max_tokens} max)") # Drop ... reasoning blocks emitted by thinking models. text = re.sub(r".*?", "", text, flags=re.S) # Parse the outermost {...} span (tolerates prose around the JSON), then strip junk. data = _strip_junk(json.loads(text[text.find("{") : text.rfind("}") + 1])) if isinstance(data, dict): return data 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(stamp), speaker, text) for stamp, speaker, text in db.connect().execute( "SELECT t, speaker, text FROM lines WHERE name=? ORDER BY rowid", (name,) ) ] # Read out// as JSON, or return default if the file is missing. def _load(name, filename, default): path = db.out_dir(name) / filename return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default # Presence-share spans from share_start/share_stop events; a share still open at the end runs to dur. def _shares(events, duration): out, open_ = [], {} for event in events: if event["kind"] == "share_start": open_[event["who"]] = event["t"] elif event["kind"] == "share_stop" and event["who"] in open_: out.append({"who": event["who"], "start": open_.pop(event["who"]), "end": event["t"]}) out += [{"who": who, "start": start, "end": duration} for who, start in open_.items()] return sorted(out, key=lambda span: span["start"]) # Replace "Speaker N" labels in a string with mapped names (unknown labels kept as-is). def _subst(text, names): return ( re.sub(r"\bSpeaker (\d+)\b", lambda match: names.get(match[0]) or match[0], text) if isinstance(text, str) else text ) # Apply f to every string leaf of a nested list/dict, returning a new structure. def _deep(obj, func): if isinstance(obj, str): return func(obj) if isinstance(obj, list): return [_deep(item, func) for item in obj] if isinstance(obj, dict): return {key: _deep(value, func) for key, value in obj.items()} return obj # Merge consecutive topics with equal titles (case-insensitive) into one. def _merge(topics): out = [] for topic in topics: if out and out[-1]["title"].lower() == topic["title"].lower(): merged = out[-1] for key in ("summary", "shown", "decisions", "actions", "open_questions"): merged[key] = merged[key] + topic[key] merged["end_s"] = topic["end_s"] else: out.append(topic) return out # Name normalization: strip accents, lowercase, collapse whitespace, sort words so word order does not matter. def _key(name): return " ".join( sorted( unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode().lower().split() ) ) # Similarity 0..1 of two names after _key normalization. def _sim(first, second): return difflib.SequenceMatcher(None, _key(first), _key(second)).ratio() def canon(counts, known, video=False, threshold=CLUSTER): """raw name -> canonical spelling (known list first, else most frequent of a similarity cluster); dropped names have no entry.""" out, clusters = {}, [] for raw, count in sorted(counts.items(), key=lambda item: -item[1]): if " " not in raw or len(raw) <= 4 or "..." in raw or "…" in raw: continue best = max(((_sim(raw, key), key) for key in known), default=(0, None)) if best[0] >= 0.75: out[raw] = best[1] continue cluster = next((item for item in clusters if _sim(raw, item[0]) >= threshold), None) if cluster: cluster[1] += count cluster[2].append(raw) else: clusters.append([raw, count, [raw]]) for representative, total, members in clusters: if video and total < 2: continue for member in members: out[member] = representative return out # Re-key attendee spans by canonical name; merged names keep the earliest first_t and latest last_t. def _canon_att(attendance, cmap): out = {} for attendee in attendance.values(): canonical = cmap.get(attendee["who"]) if not canonical: continue entry = out.setdefault( canonical, {"who": canonical, "first_t": attendee["first_t"], "last_t": attendee["last_t"]}, ) entry["first_t"], entry["last_t"] = ( min(entry["first_t"], attendee["first_t"]), max(entry["last_t"], attendee["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): pending = sorted( ({**share, "who": cmap[share["who"]]} for share in shares if share["who"] in cmap), key=lambda share: share["start"], ) while True: out = [] for share in pending: if out and out[-1]["who"] == share["who"] and share["start"] - out[-1]["end"] <= 60: out[-1]["end"] = max(out[-1]["end"], share["end"]) else: out.append(dict(share)) kept = [share for share in out if share["end"] - share["start"] >= 20] if len(kept) == len(pending): return kept pending = kept def _tidy(topics, duration, 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 topic: topic["start_s"]) prev = 0 for topic in topics: topic["start_s"] = max(topic["start_s"], prev) topic["end_s"] = max(topic["end_s"], topic["start_s"] + 1) prev = topic["end_s"] def topic_length(topic): return topic["end_s"] - topic["start_s"] # Repeatedly merge the first topic shorter than min_s into a neighbour. while len(topics) > 1: index = next( (index for index, topic in enumerate(topics) if topic_length(topic) < min_s), None ) if index is None: break # Neighbour: the previous topic, or the next one when the short topic is first. other = index - 1 if index else 1 first_index, last_index = min(index, other), max(index, other) earlier, later = topics[first_index], topics[last_index] merged = dict(earlier) # Merged topic keeps the title of the longer of the two. merged["title"] = (earlier if topic_length(earlier) >= topic_length(later) else later)[ "title" ] for key in ("summary", "shown", "decisions", "actions", "open_questions"): merged[key] = earlier[key] + later[key] # Drop filler and duplicates created by the merge. for key in ("decisions", "open_questions"): merged[key] = _clean(merged[key]) merged["start_s"], merged["end_s"] = ( min(earlier["start_s"], later["start_s"]), max(earlier["end_s"], later["end_s"]), ) topics[first_index : last_index + 1] = [merged] for topic in topics: # Keep shown facts whose mm:ss timestamp lies within the topic window, +/- 30 s. topic["shown"] = [ fact for fact in topic["shown"] if (match := re.search(r"(\d\d):(\d\d)", str(fact))) and topic["start_s"] - 30 <= int(match[1]) * 60 + int(match[2]) <= topic["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(items): """Drop model filler ("Nessuna domanda aperta emersa…") and duplicates; merged topics repeated them.""" out = [] for item in items: item = str(item).strip() if item and not FILLER.match(item) and item.lower() not in {kept.lower() for kept in out}: out.append(item) return out # Distinct lowercase words of 5+ letters: a cheap overlap signal for topic/doc matching. def _words(text): return {word for word in re.findall(r"\w+", text.lower()) if len(word) >= 5} def _pass_d(topic, 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. topic_words = _words( " ".join([topic["title"], *(item["text"] for item in topic["summary"]), *topic["shown"]]) ) # Rank docs by number of shared words; keep the top 3 that reach DOC_MIN. top = sorted( ((len(topic_words & _words(doc["title"] + " " + doc["body"])), doc) for doc in docs), key=lambda item: -item[0], ) top = [doc for number, doc in top[:3] if number >= DOC_MIN] if not top: return # Numbered doc extracts [1..n] appended to the topic. user = ( f"ARGOMENTO: {topic['title']}\nSINTESI:\n" + "\n".join(f"- {item['text']}" for item in topic["summary"]) + "\n\nDOCUMENTI:\n" + "\n\n".join( f"[{number}] {doc['title']} ({doc['source']})\n{doc['body'][:2500]}" for number, doc in enumerate(top, 1) ) ) reply = chat(SYS_D, user, 2500, think=True) or {} # Map 1-based prompt doc number -> docs item index "i"; None if invalid. def doc_index(number): return top[number - 1]["i"] if isinstance(number, int) and 1 <= number <= len(top) else None # Normalize LLM items to {text, doc}; drop empty ones. def normalize(entries): return [ {"text": str(item["text"]), "doc": doc_index(item.get("doc"))} for item in entries if isinstance(item, dict) and item.get("text") ] summary = normalize(reply.get("summary") or []) # Replace the summary only if the LLM returned something. if summary: topic["summary"] = summary # from_docs: max 3, and only entries that cite a valid doc. topic["from_docs"] = [ item for item in normalize(reply.get("from_docs") or [])[:3] if item["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. recording = ( db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() ) transcript = _transcript(name) # Duration from the recordings table, else last transcript timestamp + 5 s. duration = (recording and recording[0]) or (transcript[-1][0] + 5 if transcript else 0) shots = _load(name, "shots.json", []) glossary = _load(name, "glossary.json", []) crop_ok = any( (shot.get("view") or "").startswith("view_") for shot 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. def usable(shot): return shot["kind"] in CONTENT_KINDS and ( not crop_ok or (shot.get("view") or "").startswith("view_") ) # Meeting event stream: meta, presence, share, chat, raised hand. events = db.events(name, "meta", "present", "share_start", "share_stop", "chat", "hand") names = db.speaker_names(name) meta = [ json.loads(event["text"]) for event in events if event["kind"] == "meta" and event["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(events, duration) # att: attendee presence spans; src: sources that reported presence; counts: mentions per name (for canonicalization). attendance, sources, counts = {}, set(), {} for event in events: if event["kind"] != "present": continue for person in json.loads(event["text"] or "[]"): attendee = attendance.setdefault( person["who"], {"who": person["who"], "first_t": event["t"], "last_t": event["t"]} ) attendee["last_t"] = max(attendee["last_t"], event["t"]) sources.add("video" if event["who_key"] == "video" else "teams") counts[person["who"]] = counts.get(person["who"], 0) + 1 # "teams" if any Teams presence was seen, "video" if only video-frame names, else "none". attendees_source = "teams" if "teams" in sources else "video" if sources else "none" # Presenters read from shots count as mentions too. for shot in shots: if shot.get("presenter"): normalized = db.norm_name(shot["presenter"]) counts[normalized] = counts.get(normalized, 0) + 1 # Sharers count as mentions too. for share in shares: counts[share["who"]] = counts.get(share["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", []) + [ person["who"] for event in events if event["kind"] == "present" and event["who_key"] != "video" for person in json.loads(event["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. attendance, shares = _canon_att(attendance, cmap), _canon_shares(shares, cmap) # Chat messages for the report. chats = [ {"t": event["t"], "who": event["who"], "text": event["text"]} for event in events if event["kind"] == "chat" ] # timeline items: (t, line) items = [ ( stamp, f"[{mmss(stamp)}] " + (f"{names.get(speaker, speaker)}: " if speaker else "") + text, len(text.split()), ) for stamp, speaker, text in transcript ] prev_text = None for shot in filter(usable, shots): # Who was sharing at this frame's time, if anyone. sharer = next( (span["who"] for span in shares if span["start"] <= shot["t"] < span["end"]), None ) line = f"[{mmss(shot['t'])}] [SCHERMO {shot['kind']}{', condiviso da ' + sharer if sharer else ''}] {shot.get('title') or ''}: {shot.get('summary') or ''}" # Include OCR text only when it differs from the previous frame; cap at 600 chars. if shot.get("text") and shot["text"] != prev_text: line += "\n testo: " + shot["text"].replace("\n", " / ")[:600] prev_text = shot.get("text") items.append((shot["t"], line, len(line.split()))) items += [ (message["t"], f"[{mmss(message['t'])}] [CHAT] {message['who']}: {message['text']}", 0) for message in chats ] items += [ (event["t"], f"[{mmss(event['t'])}] [MANO ALZATA] {event['who']}", 0) for event in events if event["kind"] == "hand" ] items.sort(key=lambda item: item[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(word_count for _, _, word_count 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, buffer, words, wstart = [], [], 0, 0 # Send the buffered chunk to the LLM and append its topics. def flush(end): nonlocal buffer, words if not buffer: return reply = chat(system, "\n".join(buffer), 4000, think=True) _tick(f"argomenti: blocco {PROG[1] + 1} di {n_chunks} fatto") raw_topics = reply.get("topics") if reply else None if not raw_topics: # Placeholder topic when the LLM returns nothing, so the time range is not lost. raw_topics = [ { "title": f"Parte {mmss(wstart)}–{mmss(end)}", "start": mmss(wstart), "end": mmss(end), "summary": ["(riassunto non disponibile)"], } ] for topic in raw_topics: topic = { "title": str(topic.get("title") or "Argomento"), "summary": list(topic.get("summary") or []), "shown": list(topic.get("shown") or []), "decisions": _clean(topic.get("decisions") or []), "actions": [ action for action in (topic.get("actions") or []) if isinstance(action, dict) ], "open_questions": _clean(topic.get("open_questions") or []), "start_s": secs(topic.get("start")), "end_s": secs(topic.get("end")), } # Clamp end time into [start + 1 s, recording duration]. topic["end_s"] = min( max(topic["end_s"], topic["start_s"] + 1), max(duration, topic["start_s"] + 1) ) topics.append(topic) buffer, words = [], 0 # Group timeline items into chunks of ~window_words words, flushing at each boundary. for stamp, line, word_count in items: if not buffer: wstart = stamp buffer.append(line) words += word_count if words >= window_words: flush(stamp) # Flush the last chunk. flush(items[-1][0] if items else 0) # Sort/merge/clamp topics (see _tidy). topics = _tidy(topics, duration) for topic in topics: # Action owners labelled "Speaker N" without a known name are blanked. for action in topic["actions"]: if ( re.fullmatch(r"Speaker \d+", str(action.get("who", ""))) and action["who"] not in names ): action["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 topic in topics: # Summaries become {text, doc} dicts; doc is filled in by the docs pass. topic["summary"] = [{"text": str(shot), "doc": None} for shot in topic["summary"]] topic["from_docs"] = [] if docs: _pass_d(topic, docs) _tick(f"documentazione per «{topic['title'][:50]}»") # Overview pass: title and TL;DR from the topics. overview = ( chat( SYS_B, json.dumps( [ { "title": topic["title"], "summary": [text["text"] for text in topic["summary"]], "shown": topic["shown"], "decisions": topic["decisions"], "actions": topic["actions"], } for topic in topics ], ensure_ascii=False, ), 800, think=True, ) or {} ) _tick("fine") tldr = [str(text) for text in (overview.get("tldr") or [])][:5] # Manual title wins; otherwise the LLM title. title = title or str(overview.get("title") or "").strip() # Shots to attach: lead frames with usable content and at least 40 chars of OCR text. good = [ shot for shot in shots if shot.get("lead") and usable(shot) and len(shot.get("text") or "") >= 40 ] # Reset each topic's shot list. for topic in topics: topic["shots"] = [] for shot in good: if not topics: break # Topic containing the shot's time; else the topic with the nearest start. target_topic = next( (topic for topic in topics if topic["start_s"] <= shot["t"] <= topic["end_s"]), None ) or min(topics, key=lambda topic: abs(topic["start_s"] - shot["t"])) target_topic["shots"].append(shot) for topic in topics: # Keep the two shots with the most OCR text, then restore time order. best = sorted(topic["shots"], key=lambda shot: -len(shot.get("text") or ""))[:2] topic["shots"] = sorted(best, key=lambda shot: shot["t"]) # Entities from usable shots (urls/emails/numbers/systems) and ticket keys from speech. cshots = [shot for shot in shots if usable(shot)] refs = {"tickets": {}, "urls": {}, "systems": {}, "emails": {}, "numbers": {}} sysn = {} # Collect entities from each usable shot. for shot in cshots: entities = shot.get("entities") or {} for kind in ("urls", "emails", "numbers"): for value in entities.get(kind, []): refs[kind].setdefault(value, shot["t"]) # System names keyed by lowercase; remember which frames show them. for system_name in entities.get("systems", []): sysn.setdefault(system_name.lower(), (system_name, set()))[1].add(shot["file"]) # Lowercased transcript for substring checks. alltx = " ".join(text for _, _, text in transcript).lower() # Keep systems seen in >= 2 frames or mentioned in speech; first time wins; names under 3 chars dropped. for lowered, (system_name, files) in sysn.items(): if len(system_name) >= 3 and (len(files) >= 2 or lowered in alltx): refs["systems"][system_name] = min( shot["t"] for shot in cshots if shot["file"] in files ) # Ticket keys mentioned in speech, with first timestamp. for stamp, _, text in transcript: for key in TICKET.findall(text): refs["tickets"].setdefault(key, stamp) references = { "tickets": [{"key": key, "first_t": stamp} for key, stamp in refs["tickets"].items()], "urls": [{"url": key, "first_t": stamp} for key, stamp in refs["urls"].items()], "systems": [{"name": key, "first_t": stamp} for key, stamp in refs["systems"].items()], "emails": [{"email": key, "first_t": stamp} for key, stamp in refs["emails"].items()], "numbers": [{"value": key, "t": stamp} for key, stamp in refs["numbers"].items()], } # Screen timeline: usable lead frames; consecutive frames with the same title are merged. screen = [] for shot in shots: if not shot.get("lead") or not usable(shot): continue screen_row = {key: shot.get(key) for key in ("t", "t_end", "kind", "title", "summary")} if screen and (screen[-1]["title"] or "").lower() == (screen_row["title"] or "").lower(): screen[-1]["t_end"] = screen_row["t_end"] else: screen.append(screen_row) # Parse date/time from the recording name (teams_/meet_ YYYY-MM-DDTHH-MM-SS). date_match = re.match(r"(?:teams|meet)_(\d{4}-\d\d-\d\d)T(\d\d)-(\d\d)-\d\d", name) report = { "name": name, "date": f"{date_match[1]} {date_match[2]}:{date_match[3]}" if date_match else "", "duration_s": duration, "meeting_title": _manual_title(name) or title, "tldr": tldr, "attendees": list(attendance.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(report, 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.""" path = db.out_dir(name) / "report.json" report_data = json.loads(path.read_text(encoding="utf-8")) overview = ( chat( SYS_B, json.dumps( [ { "title": topic["title"], "summary": [item["text"] for item in topic["summary"]], "shown": topic["shown"], "decisions": topic["decisions"], "actions": topic["actions"], } for topic in report_data["topics"] ], ensure_ascii=False, ), 800, think=True, ) or {} ) title = str(overview.get("title") or "").strip() if not title: raise RuntimeError("title: nessun titolo generato") db.set_meta(name, title="") report_data["meeting_title"] = title path.write_text(json.dumps(report_data, ensure_ascii=False, indent=1), encoding="utf-8") # Topic heading "N. title (start–end)"; slugified for anchors in render(). def _head(index, topic): return f"{index}. {topic['title']} ({mmss(topic['start_s'])}–{mmss(topic['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, report_data): name_map = report_data.get("name_map", {}) names = { label: name_map.get(raw_name, raw_name) for label, raw_name in db.speaker_names(name).items() } return _deep( report_data, lambda text: re.sub(r"\bSpeaker \d+\b", "un partecipante", _subst(text, 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 folder = db.out_dir(name) report_data = json.loads((folder / "report.json").read_text(encoding="utf-8")) docs = _load(name, "docs.json", None) items = {item["i"]: item for item in (docs or {}).get("items", [])} report_data, names = named(name, report_data) # Diarization segments (label, start, end) for talk time. segs = _load(name, "diar_segments.json", []) # Turn ticket keys into Jira links. def link(raw): return TICKET.sub(lambda match: f"[{match[0]}]({JIRA_BROWSE}/{match[0]})", raw) # Strip brackets and quotes so text fits in Markdown link text/titles. def strip_marks(raw): return re.sub(r'[\[\]"]', "", raw or "") lines = [ f"# {report_data['meeting_title'] or 'Riunione'} — {report_data['date']}", "", f"**Durata:** {int(report_data['duration_s'] // 60)} min", "", "## In breve", "", ] lines += [f"- {item}" for item in report_data["tldr"]] + [""] # participants # Talk time per named speaker, summed from diarization segments. talk = {} for segment in segs: person = names.get(segment["label"]) if person: talk[person] = talk.get(person, 0) + segment["end"] - segment["start"] # Video-sourced attendance: names read from frames only, no presence times. video = report_data["attendees_source"] == "video" if video: people = sorted({attendee["who"] for attendee in report_data["attendees"]}) if talk or people: lines += ["## Partecipanti", ""] if talk: lines += ( ["| Partecipante | Parlato |", "|---|---|"] + [f"| {person} | {int(seconds // 60)} min |" for person, seconds in talk.items()] + [""] ) if people: lines += [ "*Nomi letti dai fotogrammi (ortografia verificata sulla documentazione): verificare.*" if report_data.get("known_spelling") else "*Nomi letti dai fotogrammi: verificare.*", "", ", ".join(people), "", ] else: rows = {person: [seconds, None] for person, seconds in talk.items()} # Teams-sourced: join talk time with presence windows by name (case-insensitive). for attendee in report_data["attendees"]: row_name = next( (person for person in rows if person.lower() == attendee["who"].lower()), attendee["who"], ) rows.setdefault(row_name, [0, None])[1] = ( f"{mmss(attendee['first_t'])}–{mmss(attendee['last_t'])}" ) if rows: lines += [ "## Partecipanti", "", "| Partecipante | Parlato | Presente |", "|---|---|---|", ] lines += [ f"| {person} | {f'{int(pair[0] // 60)} min' if pair[0] else '—'} | {pair[1] or '—'} |" for person, pair in rows.items() ] + [""] # Screen-share spans. if report_data["shares"]: lines += ( ["## Condivisioni schermo", ""] + [ f"- {mmss(share['start'])}–{mmss(share['end'])} {share['who']}" for share in report_data["shares"] ] + [""] ) heads = [] # Topic index with anchor links to the sections below. lines += ["## Argomenti", ""] for index, topic in enumerate(report_data["topics"], 1): heading = _head(index, topic) heads.append(heading) lines.append(f"{index}. [{topic['title']}](#{slugify(heading, '-')})") lines.append("") # Summary bullet; add a 📄 link when the cited doc is in items. def cite(entry): entry = entry if isinstance(entry, dict) else {"text": entry, "doc": None} citation = ( f' [📄]({items[entry["doc"]]["url"]} "{strip_marks(items[entry["doc"]]["title"])}")' if entry.get("doc") in items else "" ) return f"- {entry['text']}{citation}" for heading, topic in zip(heads, report_data["topics"], strict=False): lines += ( [f"## {heading}", "", "### Sintesi", ""] + [cite(entry) for entry in topic["summary"]] + [""] ) # Only doc facts whose doc is present in items. doc_facts = [fact for fact in topic.get("from_docs", []) if fact.get("doc") in items] if doc_facts: lines += ( ["### Dalla documentazione", ""] + [ f"- 📄 {fact['text']} — [{strip_marks(items[fact['doc']]['title'])}]({items[fact['doc']]['url']})" for fact in doc_facts ] + [""] ) # Previous-meeting references, linked to the GUI report anchors. previous_refs = topic.get("previous") or [] if previous_refs: lines += ( ["### Dalle riunioni precedenti", ""] + [ f"- **{previous_ref['status']}** — {previous_ref['text']} — [{strip_marks(previous_ref.get('meeting') or previous_ref['name'])} {previous_ref['date']}, {strip_marks(previous_ref['topic'])} {mmss(previous_ref['t'])}]({GUI}/report?name={previous_ref['name']}#{previous_ref['anchor']})" for previous_ref in previous_refs ] + [""] ) if topic["shown"]: lines += ( ["### Mostrato a schermo", ""] + [f"- {link(item)}" for item in topic["shown"]] + [""] ) if topic["decisions"]: lines += ["### Decisioni", ""] + [f"- {item}" for item in topic["decisions"]] + [""] if topic["open_questions"]: lines += ( ["### Domande aperte", ""] + [f"- {item}" for item in topic["open_questions"]] + [""] ) if topic["actions"]: lines += ["### Azioni", "", "| Chi | Cosa | Quando |", "|---|---|---|"] lines += [ f"| {action.get('who', '')} | {action.get('what', '')} | {action.get('when', '')} |" for action in topic["actions"] ] + [""] # Embed shots: crop view if present, else the full frame; caption has time, sharer, summary. for shot in topic["shots"]: alt_text = re.sub(r"[\[\]()]", "", shot.get("title") or "") sharer = next( ( item["who"] for item in report_data["shares"] if item["start"] <= shot["t"] < item["end"] ), None, ) caption = ( f"{mmss(shot['t'])} — " + (f"condiviso da {sharer} — " if sharer else "") + f"{shot.get('title') or ''} — {shot.get('summary') or ''}" ) lines += [ f"![{alt_text}](shots/{shot.get('view') or shot['file']})", "", f"*{caption}*", "", ] # Related docs section (items from docs.json). if items: lines += ["## Documentazione correlata", ""] for doc in items.values(): lines.append( ( f"- 🎫 [{strip_marks(doc['key'])} — {strip_marks(doc['title'])}]({doc['url']}) — {doc['status'] or ''}" if doc["source"] == "jira" else f"- 📄 [{strip_marks(doc['title'])}]({doc['url']}) — Confluence" ) + (" — citato in riunione" if doc.get("mentioned") else "") ) lines.append("") if report_data["chat"]: lines += ( ["## Chat", ""] + [ f"[{mmss(message['t'])}] **{message['who']}:** {message['text']} " for message in report_data["chat"] ] + [""] ) references = report_data["references"] # Tickets: from docs when docs.json exists (only those mentioned in the meeting), else transcript references. tickets = ( [ f"[{doc['key']}]({doc['url']}) — {strip_marks(doc['title'])}" for doc in items.values() if doc["source"] == "jira" and doc.get("mentioned") ] if docs is not None else [ f"[{ticket['key']}]({JIRA_BROWSE}/{ticket['key']}) — {mmss(ticket['first_t'])}" for ticket in references["tickets"] ] ) systems = [f"{system['name']} — {mmss(system['first_t'])}" for system in references["systems"]] if tickets or systems: lines += ["## Riferimenti", ""] for label, entries in (("Ticket", tickets), ("Sistemi", systems)): if entries: lines += [f"**{label}**", ""] + [f"- {item}" for item in entries] + [""] # Collapsible screen timeline; table cells escape "|" and newlines. if report_data["screen"]: lines += [ f'
Cronologia schermo ({len(report_data["screen"])} schermate)', "", "## Cronologia schermo", "", "| Da | A | Tipo | Titolo | Sintesi |", "|---|---|---|---|---|", ] def cell(value): return (value or "").replace("|", "/").replace("\n", " ") lines += [ f"| {mmss(frame['t'])} | {mmss(frame['t_end'] or 0)} | {frame['kind']} | {cell(frame['title'])} | {cell(frame['summary'])} |" for frame in report_data["screen"] ] lines += ["", "
", ""] text = "\n".join(lines) (folder / "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 match: ( 'src="data:image/jpeg;base64,' + base64.b64encode((folder / "shots" / match[1]).read_bytes()).decode() + '"' ), body, ) # Plain title from the first heading line. title_text = re.sub(r"[#]+ ", "", lines[0]) # Inline CSS: light theme; dark theme via prefers-color-scheme. style = """: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). (folder / "report.html").write_text( f'{title_text}\n{body}', encoding="utf-8", )