From 3f020cd246de2d0e3d16fd23ce810360f5e6658b Mon Sep 17 00:00:00 2001 From: Stefano Zini Date: Tue, 10 Nov 2026 14:23:59 +0100 Subject: [PATCH] report: less repetition, cleaner shots, correct speakers - docs/memory passes get the facts already reported, so topics stop repeating them - regroup pass merges consecutive topics on the same subject - shots: settle 1.5s after a scene change, yuvj444p, no duplicate screen per topic, click-to-zoom in report.html, OCR identifier misreads fixed by majority vote - speakers: split diarized paragraphs where Teams captions change speaker - talk time from those paragraphs, counting only detected speech --- README.md | 2 +- app/memory.py | 16 ++- app/report.py | 253 +++++++++++++++++++++++++++++++++++------------- app/shots.py | 97 +++++++++++++++++-- app/speakers.py | 119 +++++++++++++++++++++++ 5 files changed, 408 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index f186406..e78c37c 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ out//source. the only video/audio source (removed by "elimina vide report.json (+ .md .html .pdf renders) meta.json (manual title, upload filename) progress.json logs/ ``` -The speaker-labelled transcript is the `lines` table (names are applied when the report renders); there is no `.spk.txt`. A meeting without `source.` cannot be re-run at all (`/run` returns 409, the GUI hides the run controls). +The speaker-labelled transcript is the `lines` table (names are applied when the report renders); there is no `.spk.txt`. The `speakers` step maps diarization labels to people from Teams events, then re-splits each paragraph where the Teams captions change speaker (diarization merges similar voices, so one paragraph often holds two speakers); talk time in the report comes from those paragraphs. A meeting without `source.` cannot be re-run at all (`/run` returns 409, the GUI hides the run controls). Other CLI tools (from `app/`): diff --git a/app/memory.py b/app/memory.py index 198f9e8..bad5d77 100644 --- a/app/memory.py +++ b/app/memory.py @@ -25,7 +25,9 @@ _open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # Italian prompt: link current-meeting topics to earlier excerpts; JSON output. SYS_M = ( 'Hai un argomento della riunione attuale ed estratti numerati di riunioni precedenti. Rispondi SOLO JSON: {"links":[{"text":str,"ref":int,"status":"confermato"|"cambiato"|"aperto"|"contesto"}]}. ' - '"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che la riunione attuale non ha chiuso; "contesto": informazione precedente pertinente non ripresa oggi. ' + '"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che questo argomento non chiude; "contesto": informazione precedente utile a capire l\'argomento. ' + "Una sola voce per ciascun fatto precedente. Non ripetere, neanche riformulate, le voci in GIÀ COLLEGATI: sono già nel report sotto altri argomenti. " + 'Non scrivere che qualcosa "non è stato ripreso oggi": vedi solo questo argomento, non tutta la riunione. ' 'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.' ) # Prompt for ask(): answer from numbered excerpts only, cite as [n]. @@ -173,6 +175,7 @@ def _link(name): # Clear old links so re-running the step does not accumulate them. for topic in report_json["topics"]: topic["previous"] = [] + reported = [] # (text, source anchor) of links already given to earlier topics of this meeting if rows: # Query vectors: each current topic as title + content. query_vectors = embed([_topic_text(topic) for topic in named_report["topics"]]) @@ -193,11 +196,12 @@ def _link(name): " — ".join(str(action[key]) for key in ("who", "what", "when") if action.get(key)) for action in named_topic.get("actions", []) ) - # Prompt: current topic, then numbered earlier excerpts the model may cite as [n]. + # Prompt: current topic, numbered earlier excerpts the model may cite as [n], then links already reported. user = ( f"ARGOMENTO: {named_topic['title']}\nSINTESI: {' '.join(_summary_text(item) for item in named_topic.get('summary', []))}\nDECISIONI: {'; '.join(named_topic.get('decisions', []))}\n" f"AZIONI: {actions}\nDOMANDE APERTE: {'; '.join(named_topic.get('open_questions', []))}\n\nPRECEDENTI:\n" + "\n".join(_prev_line(number, rows[index]) for number, index in enumerate(top, 1)) + + ("\n\nGIÀ COLLEGATI:\n" + "\n".join(f"- {text}" for text, _ in reported[-20:]) if reported else "") ) # report.chat returns parsed JSON or None; None -> no links. response = report.chat(SYS_M, user, 1500) or {} @@ -210,6 +214,14 @@ def _link(name): continue if 1 <= ref <= len(top) and status in STATUSES and text: previous = rows[top[ref - 1]] + source = f"{previous['name']}#{previous['anchor']}" + # Same earlier excerpt, same content (word overlap >= 0.45): a repeat the model let through. + if any( + seen_source == source and report._jaccard(text, seen_text) >= 0.45 + for seen_text, seen_source in reported + ): + continue + reported.append((text, source)) topic["previous"].append( { "text": text, diff --git a/app/report.py b/app/report.py index e1bd937..b55ae5d 100644 --- a/app/report.py +++ b/app/report.py @@ -12,7 +12,7 @@ import db import llama # Screen-capture kinds that count as shared content. -from shots import CONTENT_KINDS +from shots import CONTENT_KINDS, _fix_spelling # Base URL for Jira ticket links. JIRA_BROWSE = "https://italdesign.atlassian.net/browse" @@ -26,7 +26,8 @@ SYS_A = ( "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. " + "Non scrivere voci vuote come «nessuna domanda aperta»: lascia la lista vuota. Scrivi tutto in italiano, titoli compresi (non «Next step»). Se non sei sicuro, ometti. " + 'Nelle azioni "who" è chi si impegna a svolgere il compito o a cui viene assegnato (chi lo chiede non è il responsabile); stringa vuota se non è chiaro. ' "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. @@ -34,9 +35,19 @@ SYS_B = 'Dato l\'elenco degli argomenti, rispondi SOLO JSON: {"title":str,"tldr" # 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.' + '"summary": riscrivi i punti della sintesi mantenendo tutti i fatti della riunione; usa la documentazione solo per correggere un punto o completarlo con un dettaglio essenziale, 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; lista vuota se non ce ne sono. ' + "Non ripetere, neanche riformulati, i fatti elencati in GIÀ RIPORTATI: sono già nel report. Non citare etichette \"Speaker N\". Non inventare. Scrivi in italiano." ) +# Prompt: merge runs of consecutive topics on the same subject (chunked extraction splits and repeats them). +SYS_G = ( + 'Ricevi gli argomenti di una riunione in ordine di tempo. Rispondi SOLO JSON: {"groups":[{"first":int,"last":int,"title":str}]}. ' + "Elenca solo i gruppi di argomenti CONSECUTIVI che riprendono la stessa discussione (la stessa domanda o lo stesso punto, spezzato o ripetuto). " + "Argomenti diversi sulla stessa tecnologia restano separati: requisiti, costi e health check di uno stesso prodotto sono tre argomenti. Ogni gruppo copre al massimo 10 minuti. Nel dubbio non unire. " + "title: titolo in italiano del gruppo, massimo 12 parole. Lista vuota se nessun argomento va unito." +) +# Longest topic a regroup may produce, in seconds. +REGROUP_MAX = 12 * 60 # 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. @@ -49,6 +60,11 @@ def mmss(seconds): return f"{seconds // 60:02d}:{seconds % 60:02d}" +# Talk time cell: "—" when silent, "<1 min" under a minute. +def _mins(seconds): + return "—" if not seconds else f"{int(seconds // 60)} min" if seconds >= 60 else "<1 min" + + # "mm:ss" (or leading digits) -> seconds; 0 if no match. def secs(text): match = re.match(r"(\d+):(\d+)", str(text)) @@ -285,19 +301,10 @@ def _tidy(topics, duration, min_s=TIDY_MIN): 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"]), + merged = _join( + earlier, + later, + (earlier if topic_length(earlier) >= topic_length(later) else later)["title"], ) topics[first_index : last_index + 1] = [merged] for topic in topics: @@ -325,13 +332,71 @@ def _clean(items): return out +# Two adjacent topics as one spanning both; decisions/questions de-duplicated. +def _join(earlier, later, title): + merged = dict(earlier, title=title) + for key in ("summary", "shown", "decisions", "actions", "open_questions"): + merged[key] = earlier[key] + later[key] + for key in ("decisions", "open_questions"): + merged[key] = _clean(merged[key]) + merged["start_s"] = min(earlier["start_s"], later["start_s"]) + merged["end_s"] = max(earlier["end_s"], later["end_s"]) + return merged + + +def _regroup(topics): + """One LLM pass: merge runs of consecutive topics on the same subject, each run at most REGROUP_MAX long.""" + if len(topics) < 2: + return topics + listing = "\n".join( + f"{number}. [{mmss(topic['start_s'])}–{mmss(topic['end_s'])}] {topic['title']}: " + + " ".join(str(item) for item in topic["summary"][:3]) + for number, topic in enumerate(topics, 1) + ) + reply = chat(SYS_G, listing, 1500, think=True) or {} + groups = [] + for group in reply.get("groups") or []: + try: + first, last = int(group["first"]), int(group["last"]) + except (KeyError, TypeError, ValueError): + continue + groups.append((first, last, str(group.get("title") or "").strip())) + valid = [] + for first, last, title in sorted(groups): + if ( + 1 <= first < last <= len(topics) + and (not valid or first > valid[-1][1]) + and topics[last - 1]["end_s"] - topics[first - 1]["start_s"] <= REGROUP_MAX + ): + valid.append((first, last, title)) + # Apply from the end so earlier indices stay valid. + for first, last, title in reversed(valid): + merged = topics[first - 1] + for later in topics[first:last]: + merged = _join(merged, later, title or merged["title"]) + topics[first - 1 : last] = [merged] + return topics + + +# Word overlap (Jaccard over words of 3+ chars) of two texts: cheap "same content" signal. +def _jaccard(text_a, text_b): + words_a, words_b = (set(re.findall(r"\w{3,}", text.lower())) for text in (text_a, text_b)) + return len(words_a & words_b) / max(1, len(words_a | words_b)) + + +# Presenter sharing at second t; 2 s slack because frame times and share events come from different clocks. +def _sharer(shares, t): + return next((span["who"] for span in shares if span["start"] - 2 <= t < span["end"]), None) + + # 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.""" +def _pass_d(topic, docs, seen): + """Complete/correct a topic's summary with the best-matching docs; sets t['summary'] and t['from_docs'] as {text, doc} dicts. + seen: doc facts already reported by earlier topics; shown to the model and filtered out of from_docs.""" # 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"]]) @@ -353,6 +418,7 @@ def _pass_d(topic, docs): f"[{number}] {doc['title']} ({doc['source']})\n{doc['body'][:2500]}" for number, doc in enumerate(top, 1) ) + + ("\n\nGIÀ RIPORTATI:\n" + "\n".join(f"- {text[:250]}" for text in seen[-30:]) if seen else "") ) reply = chat(SYS_D, user, 2500, think=True) or {} @@ -372,12 +438,26 @@ def _pass_d(topic, docs): # 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. + # from_docs: max 3, only entries that cite a valid doc and do not repeat an earlier topic's fact. topic["from_docs"] = [ - item for item in normalize(reply.get("from_docs") or [])[:3] if item["doc"] is not None + item + for item in normalize(reply.get("from_docs") or [])[:3] + if item["doc"] is not None and all(_jaccard(item["text"], text) < 0.55 for text in seen) ] +# Same screen captured twice: OCR word overlap (Jaccard) >= 0.8, or near-identical titles with overlap >= 0.5. +# ponytail: thresholds measured on one meeting (same slide 0.51-1.0, different 'Option A/B' diagrams <= 0.66); retune if real dupes slip through. +def _same_screen(a, b): + overlap = _jaccard(*(f"{shot.get('title') or ''} {shot.get('text') or ''}" for shot in (a, b))) + title_a, title_b = ((shot.get("title") or "").strip().lower() for shot in (a, b)) + return overlap >= 0.8 or ( + bool(title_a and title_b) + and overlap >= 0.5 + and difflib.SequenceMatcher(None, title_a, title_b).ratio() >= 0.9 + ) + + 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. @@ -388,6 +468,7 @@ def run(name, window_words=3000): # 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", []) + _fix_spelling(shots) # also applied in shots.run; idempotent, so a re-render fixes meetings read before it existed glossary = _load(name, "glossary.json", []) crop_ok = any( (shot.get("view") or "").startswith("view_") for shot in shots @@ -467,9 +548,7 @@ def run(name, window_words=3000): 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 - ) + sharer = _sharer(shares, shot["t"]) 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: @@ -552,23 +631,36 @@ def run(name, window_words=3000): # 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"]: + # Action owners labelled "Speaker N" without a known name are blanked. if ( re.fullmatch(r"Speaker \d+", str(action.get("who", ""))) and action["who"] not in names ): action["who"] = "" + # Short form of one attendee's name ("Aurelio Paolillo") -> the full attendee name. + who_words = set(_key(str(action.get("who") or "")).split()) + full = [person for person in attendance if who_words and who_words < set(_key(person).split())] + if len(full) == 1: + action["who"] = full[0] + topics = _regroup(topics) + _tick("argomenti accorpati") # 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 + seen = [] # doc facts already reported by earlier topics 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) + _pass_d(topic, docs, seen) + seen += [ + item["text"] + for item in topic["summary"] + topic["from_docs"] + if item["doc"] is not None + ] _tick(f"documentazione per «{topic['title'][:50]}»") # Overview pass: title and TL;DR from the topics. @@ -616,8 +708,11 @@ def run(name, window_words=3000): ) 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] + # Up to two distinct screens, most OCR text first (re-shows of the same slide skipped), then time order. + best = [] + for shot in sorted(topic["shots"], key=lambda shot: -len(shot.get("text") or "")): + if len(best) < 2 and not any(_same_screen(shot, kept) for kept in best): + best.append(shot) topic["shots"] = sorted(best, key=lambda shot: shot["t"]) # Entities from usable shots (urls/emails/numbers/systems) and ticket keys from speech. @@ -641,6 +736,20 @@ def run(name, window_words=3000): refs["systems"][system_name] = min( shot["t"] for shot in cshots if shot["file"] in files ) + # Collapse spelling variants ("AWS Lambda"/"Lambda", "AWS IoT Greengrass v2"/"Greengrass"): + # equal after dropping vendor prefix and version, or the longer name ends with the shorter one. Longest name kept. + systems = {} + for system_name in sorted(refs["systems"], key=len, reverse=True): + base = re.sub(r"^(aws|amazon)\s+|\s+v\d+$", "", system_name.lower()) + kept = next( + (kept for kept, kept_base in systems.items() if f" {kept_base}".endswith(f" {base}")), + None, + ) + if kept: + refs["systems"][kept] = min(refs["systems"][kept], refs["systems"].pop(system_name)) + else: + systems[system_name] = base + refs["systems"] = dict(sorted(refs["systems"].items(), key=lambda item: item[1])) # Ticket keys mentioned in speech, with first timestamp. for stamp, _, text in transcript: for key in TICKET.findall(text): @@ -652,16 +761,21 @@ def run(name, window_words=3000): "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 = [] + # Screen timeline: usable lead frames; consecutive frames with the same title or the same screen are merged. + screen, prev_shot = [], None 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(): + if screen and ( + (screen[-1]["title"] or "").lower() == (screen_row["title"] or "").lower() + or _same_screen(shot, prev_shot) + ): screen[-1]["t_end"] = screen_row["t_end"] + screen[-1]["title"] = screen[-1]["title"] or screen_row["title"] else: screen.append(screen_row) + prev_shot = shot # 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 = { @@ -748,8 +862,9 @@ def render(name): 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", []) + # Speaker-labelled paragraphs (caption-split) and diarized speech spans, for talk time. + paragraphs = _transcript(name) + speech = sorted((segment["start"], segment["end"]) for segment in _load(name, "diar_segments.json", [])) # Turn ticket keys into Jira links. def link(raw): @@ -770,12 +885,15 @@ def render(name): lines += [f"- {item}" for item in report_data["tldr"]] + [""] # participants - # Talk time per named speaker, summed from diarization segments. + # Talk time per named speaker: speech detected inside each paragraph's window (silence and pauses excluded). talk = {} - for segment in segs: - person = names.get(segment["label"]) + for index, (stamp, label, _) in enumerate(paragraphs): + person = names.get(label) if person: - talk[person] = talk.get(person, 0) + segment["end"] - segment["start"] + end = paragraphs[index + 1][0] if index + 1 < len(paragraphs) else stamp + 30 + talk[person] = talk.get(person, 0) + sum( + max(0, min(end, speech_end) - max(stamp, speech_start)) for speech_start, speech_end in speech + ) # Video-sourced attendance: names read from frames only, no presence times. video = report_data["attendees_source"] == "video" if video: @@ -785,7 +903,7 @@ def render(name): if talk: lines += ( ["| Partecipante | Parlato |", "|---|---|"] - + [f"| {person} | {int(seconds // 60)} min |" for person, seconds in talk.items()] + + [f"| {person} | {_mins(seconds)} |" for person, seconds in talk.items()] + [""] ) if people: @@ -816,7 +934,7 @@ def render(name): "|---|---|---|", ] lines += [ - f"| {person} | {f'{int(pair[0] // 60)} min' if pair[0] else '—'} | {pair[1] or '—'} |" + f"| {person} | {_mins(pair[0])} | {pair[1] or '—'} |" for person, pair in rows.items() ] + [""] # Screen-share spans. @@ -876,12 +994,30 @@ def render(name): ] + [""] ) - if topic["shown"]: - lines += ( - ["### Mostrato a schermo", ""] - + [f"- {link(item)}" for item in topic["shown"]] - + [""] + # Shots go right under the screen facts: crop view if present, else the full frame; caption has time, sharer, title, summary. + if topic["shown"] or topic["shots"]: + lines += ["### Mostrato a schermo", ""] + if topic["shown"]: + lines += [f"- {link(item)}" for item in topic["shown"]] + [""] + for shot in topic["shots"]: + alt_text = re.sub(r"[\[\]()]", "", shot.get("title") or "") + sharer = _sharer(report_data["shares"], shot["t"]) + caption = " — ".join( + part + for part in ( + mmss(shot["t"]), + f"condiviso da {sharer}" if sharer else "", + shot.get("title") or "", + shot.get("summary") or "", + ) + if part ) + lines += [ + f"![{alt_text}](shots/{shot.get('view') or shot['file']})", + "", + f"*{caption}*", + "", + ] if topic["decisions"]: lines += ["### Decisioni", ""] + [f"- {item}" for item in topic["decisions"]] + [""] if topic["open_questions"]: @@ -893,31 +1029,9 @@ def render(name): if topic["actions"]: lines += ["### Azioni", "", "| Chi | Cosa | Quando |", "|---|---|---|"] lines += [ - f"| {action.get('who', '')} | {action.get('what', '')} | {action.get('when', '')} |" + f"| {action.get('who') or '—'} | {action.get('what', '')} | {action.get('when') or '—'} |" 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", ""] @@ -1008,11 +1122,12 @@ 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} +img{width:100%;border:1px solid var(--line);border-radius:12px;margin-top:.8em;cursor:zoom-in}p>em{color:var(--mut);font-size:.88em} +img.zoom{position:fixed;inset:0;width:100vw;height:100vh;margin:0;object-fit:contain;background:#000d;border:0;border-radius:0;cursor:zoom-out;z-index:9} 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}', + f'{title_text}\n{body}', encoding="utf-8", ) diff --git a/app/shots.py b/app/shots.py index 9d63d9f..20d6d44 100644 --- a/app/shots.py +++ b/app/shots.py @@ -38,6 +38,9 @@ CONTENT_KINDS = { } # Crop frames to the model-reported shared-content box (see _view). CROP_BOX = True +# Seconds after a scene change before grabbing the frame: slide/tab swipe animations and Teams' share re-sharpening are over by then. +# A candidate followed by another change within SETTLE s is mid-transition and skipped. +SETTLE = 1.5 # Allowed values for 'kind'; also the grammar enum in SCHEMA. KINDS = [ "slide", @@ -108,11 +111,11 @@ PROMPT = ( + "|".join(KINDS) + '","title":str|null,"app":str|null,"summary":str,"text":str,' '"entities":{"systems":[str],"tickets":[str],"urls":[str],"numbers":[str],"terms":[str]},"people":[str],"presenter":str|null,"meeting_title":str|null,"content_box":[x1,y1,x2,y2]|null}\n' - "Look ONLY at the shared screen content: ignore the browser bookmarks bar, OS taskbar, Teams toolbar, video tiles and captions, except for people/presenter/meeting_title.\n" + "Look ONLY at the shared screen content: ignore the browser bookmarks bar, OS taskbar, Teams toolbar, video tiles, captions and notification pop-ups/toasts (chat messages, meeting reminders), except for people/presenter/meeting_title.\n" "- kind: type of the shared content; video_tiles ONLY if no screen is shared (just participant videos), chat for a chat panel.\n" - '- title: the visible heading of the shared content: slide title, page/document title, active browser tab title or window title (e.g. "Sprint Review Q3 - Backlog"). null only if no title is readable.\n' + '- title: the heading written inside the shared content: slide title, diagram or document heading, page title (e.g. "Sprint Review Q3 - Backlog"). Use the active browser tab or window title only when the content has no heading. null only if no title is readable.\n' '- app: application or website shown (e.g. "Confluence", "Grafana", "Excel").\n' - "- summary: in italiano, massimo 40 parole: cosa si vede (nomi concreti: progetti, ambienti, servizi, valori) e perché conta. Inizia direttamente con il contenuto.\n" + "- summary: in italiano, massimo 40 parole: cosa si vede (nomi concreti: progetti, ambienti, servizi, valori). Inizia direttamente con il contenuto; niente frasi finali di commento (es. «utile per…», «serve a…»).\n" "- text: important visible text copied verbatim (headings, bullets, table rows with values, code lines, errors, form values), max 1500 characters, keep line breaks.\n" "- entities.systems: every product/tool/service/platform name visible (e.g. GitLab, Grafana, Azure, PostgreSQL); tickets: issue keys like ABC-123; urls; numbers: business figures with their label; terms: technical words useful for a glossary.\n" '- people: full names (first and last) on video tiles/name tags, never initials. presenter: name in a "Contenuto condiviso da"/"Content shared by" label. meeting_title: the Teams meeting name (Teams window title bar or meeting header, never the title of the shared content); null if not visible.\n' @@ -280,7 +283,7 @@ def _view(path, content_box): return path.name crop_path = path.with_name(f"view_{path.stem}.jpg") image.crop((int(left), int(top), int(right), int(bottom))).convert("RGB").save( - crop_path, quality=90 + crop_path, quality=95, subsampling=0 ) return crop_path.name @@ -306,6 +309,65 @@ def _times(video, scene, bars=None): return [float(match) for match in re.findall(r"pts_time:([\d.]+)", result.stderr)] +# Fix rare OCR misreads inside identifiers by majority vote on their parts: 'sap-infra-iac'/'sep-env-dev' lose to 'scp-' seen on more frames. +# ponytail: hyphenated identifiers only (plain words like componente/components are real variants); one letter differs, never a digit or case. +def _fix_spelling(rows, fields=("title", "summary", "text")): + def strings(row): + return [row.get(field) or "" for field in fields] + [ + item for items in (row.get("entities") or {}).values() for item in items if isinstance(item, str) + ] + + def identifiers(text): + return [token for token in re.findall(r"\w+(?:-\w+)+", text) if len(token) >= 6] + + # Frames each identifier part ('scp', 'infra', 'iac') appears on. + counts = collections.Counter( + part + for row in rows + for part in { + part + for text in strings(row) + for token in identifiers(text) + for part in token.split("-") + if len(part) >= 3 + } + ) + fixes = {} + for rare, rare_count in counts.items(): + for common, common_count in counts.most_common(): + if common_count < max(3, 2 * rare_count): + break + diff = [(a, b) for a, b in zip(rare, common) if a != b] + if ( + len(rare) == len(common) + and len(diff) == 1 + and diff[0][0].isalpha() + and diff[0][1].isalpha() + and diff[0][0].lower() != diff[0][1].lower() + ): + fixes[rare] = common + break + if not fixes: + return + + def fix(text): + return re.sub( + r"\w+(?:-\w+)+", + lambda match: "-".join(fixes.get(part, part) for part in match[0].split("-")) + if len(match[0]) >= 6 + else match[0], + text, + ) + + for row in rows: + for field in fields: + if row.get(field): + row[field] = fix(row[field]) + for key, items in (row.get("entities") or {}).items(): + row["entities"][key] = [fix(item) if isinstance(item, str) else item for item in items] + print("shots: spelling fixes", fixes, flush=True) + + # Extract scene-change keyframes, dedupe, read each with the VLM, write shots.json and glossary, derive share/presence events. def run(name, max_frames=60, scene=0.05): import imagehash @@ -338,7 +400,10 @@ def run(name, max_frames=60, scene=0.05): )[0] or 0, ) - for timestamp in _times(video, scene, bars): + times = _times(video, scene, bars) + for timestamp, next_change in zip(times, [*times[1:], float("inf")]): + if next_change - timestamp <= SETTLE: + continue # transitional: the next change follows within SETTLE s frame_path = shots_dir / f"shot_{int(timestamp) // 60:02d}m{int(timestamp) % 60:02d}s.jpg" if any(kept_frame[1] == frame_path for kept_frame in kept): continue # same second as a kept frame @@ -349,14 +414,16 @@ def run(name, max_frames=60, scene=0.05): "-v", "error", "-ss", - str(timestamp), + str(timestamp + SETTLE), "-i", str(video), "-frames:v", "1", *(["-vf", bars] if bars else []), "-q:v", - "3", + "2", + "-pix_fmt", + "yuvj444p", str(frame_path), ], check=True, @@ -408,6 +475,7 @@ def run(name, max_frames=60, scene=0.05): )[0] if duration is None: duration = rows[-1]["t"] + 60 if rows else 0 + _fix_spelling(rows) prev = None # lead=False when a row repeats the previous kind+title (continuation of the same topic). for index, row in enumerate(rows): @@ -482,3 +550,18 @@ def run(name, max_frames=60, scene=0.05): if last: events.append((duration, "share_stop", "video", last, "")) db.add_events(name, events) + + +if __name__ == "__main__": + # Self-check: a one-letter OCR misread loses to the spelling seen on more frames, unrelated identifiers survive. + shots = [ + {"title": "scp-infra-iac", "summary": "", "text": "", "entities": {"systems": ["scp-env-dev"]}}, + {"title": "scp-infra-iac", "summary": "pipeline scp-env-dev", "text": "", "entities": {}}, + {"title": "scp-infra-iac", "summary": "", "text": "stage1-deploy", "entities": {}}, + {"title": "sap-infra-iac", "summary": "", "text": "stage2-deploy", "entities": {"systems": ["sep-env-dev"]}}, + ] + _fix_spelling(shots) + assert shots[3]["title"] == "scp-infra-iac", shots[3] + assert shots[3]["entities"]["systems"] == ["scp-env-dev"], shots[3] + assert shots[2]["text"] == "stage1-deploy" and shots[3]["text"] == "stage2-deploy" # digits never voted away + print("ok") diff --git a/app/speakers.py b/app/speakers.py index e3429b0..9363566 100644 --- a/app/speakers.py +++ b/app/speakers.py @@ -1,6 +1,9 @@ """Map diarization labels to names seen in Teams call events.""" +import difflib import json +import re +import unicodedata import db @@ -53,3 +56,119 @@ def run(name): who, overlap = assigned.get(label, ("", sum(totals.get(label, {}).values()))) # Store the mapping (source 'auto', with overlap seconds). db.set_speaker_map(name, label, who, "auto", overlap) + _caption_split(name, [event for event in events if event["kind"] == "caption" and event["who"]]) + + +# Lowercase, accent-free, punctuation-stripped word for caption/transcript alignment. +def _norm(word): + return ( + unicodedata.normalize("NFKD", word).encode("ascii", "ignore").decode().lower().strip(".,;:?!'\"()«»") + ) + + +def _caption_split(name, captions): + """Diarization clusters merge similar voices (a whole speaker vanished into another label), and a paragraph gets one label. + Teams captions carry the real speaker: align each paragraph's words with nearby caption words and split at speaker changes.""" + if not captions: + return + names = db.speaker_names(name) + label_by_person = {person: label for label, person in names.items()} + labels = [row[0] for row in db.connect().execute("SELECT label FROM speaker_map WHERE name=?", (name,))] + next_number = max([int(n) for label in labels for n in re.findall(r"\d+", label)] + [0]) + 1 + + def label_of(person): + nonlocal next_number + if person not in label_by_person: + # Captioned person with no diarization cluster: give them their own label. + label_by_person[person] = f"Speaker {next_number}" + db.set_speaker_map(name, label_by_person[person], person, "auto", 0) + next_number += 1 + return label_by_person[person] + + lines = [ + (int(stamp), speaker, text) + for stamp, speaker, text in db.connect().execute( + "SELECT t, speaker, text FROM lines WHERE name=? ORDER BY CAST(t AS INTEGER)", (name,) + ) + ] + out = _split_lines( + lines, [(caption["t"], caption["who"], caption["text"]) for caption in captions], label_of + ) + db.replace_lines(name, out) + print("speakers: speaker split", len(lines), "->", len(out), "paragraphs", flush=True) + + +# Split speaker-labelled paragraphs where the captions change speaker; label_of(person) -> "Speaker N". +def _split_lines(lines, captions, label_of): + out = [] + for index, (start, label, text) in enumerate(lines): + end = lines[index + 1][0] if index + 1 < len(lines) else start + 60 + words = text.split() + # Caption t is when the caption settles (end of the utterance), so look up to 20 s past the paragraph. + window = [ + (_norm(word), who) + for stamp, who, caption_text in captions + if start - 2 <= stamp <= end + 20 + for word in caption_text.split() + ] + who = [None] * len(words) + matcher = difflib.SequenceMatcher( + None, [_norm(word) for word in words], [word for word, _ in window], autojunk=False + ) + for word_index, window_index, size in matcher.get_matching_blocks(): + if size >= 2: # single-word matches ("ok", "sì") are noise + for offset in range(size): + who[word_index + offset] = window[window_index + offset][1] + # 'active speaker' events were tried here as a fallback without captions: 0.5 s points plus interpolated word + # times split mid-sentence and moved whole turns to the wrong person, so paragraphs without captions stay as diarized. + # Unmatched words take the previous matched speaker, leading ones the next. + for order in (range(len(words)), reversed(range(len(words)))): + last = None + for word_index in order: + last = who[word_index] = who[word_index] or last + runs = [] + for word_index, word in enumerate(words): + run_label = label_of(who[word_index]) if who[word_index] else label + if runs and runs[-1][1] == run_label: + runs[-1][2].append(word) + else: + runs.append([word_index, run_label, [word]]) + # Runs under 4 words are alignment noise: fold them into the run before (or after, at the start). + merged = [] + for run in runs: + if merged and (len(run[2]) < 4 or merged[-1][1] == run[1]): + merged[-1][2] += run[2] + else: + merged.append(run) + if len(merged) > 1 and len(merged[0][2]) < 4: + merged[1][2][:0], merged[1][0] = merged[0][2], 0 + merged.pop(0) + for word_index, run_label, run_words in merged: + stamp = start + (end - start) * word_index // len(words) # ponytail: time interpolated by word position + # Same speaker continues: one paragraph, cut every 60 s like diarize. + if out and out[-1][1] == run_label and stamp - out[-1][0] < 60: + out[-1][2] += " " + " ".join(run_words) + else: + out.append([stamp, run_label, " ".join(run_words)]) + return [tuple(row) for row in out] + + +if __name__ == "__main__": + # Self-check: one diarized paragraph holding two speakers is split where the captions change speaker. + rows = _split_lines( + [ + ( + 100, + "Speaker 1", + "come next step possiamo iniziare a deployare questi pezzetti nel momento in cui fate il deploy coinvolgete anche Mattia", + ) + ], + [ + (104, "Adriano", "Come next step possiamo iniziare a deployare questi pezzetti."), + (118, "Edoardo", "Nel momento in cui fate il deploy coinvolgete anche Mattia."), + ], + lambda person: {"Adriano": "Speaker 4", "Edoardo": "Speaker 8"}[person], + ) + assert [row[1] for row in rows] == ["Speaker 4", "Speaker 8"], rows + assert rows[0][2].endswith("pezzetti") and rows[1][2].startswith("nel momento"), rows + print("ok")