"""Map diarization labels to names seen in Teams call events.""" import difflib import json import re import unicodedata import db # Map each diarized 'Speaker N' label to a person from Teams events; unmatched labels get an empty name. def run(name): diar_path = db.out_dir(name) / "diar_segments.json" events = db.events(name, "active", "caption") if not diar_path.exists() or not events: return segments = json.loads(diar_path.read_text(encoding="utf-8")) intervals = [] # Intervals where a person was speaking or captioned: 'active' is a 0.5 s point, 'caption' is +/-2 s around its timestamp. for event in events: if not event["who"]: continue start, end = ( (event["t"], event["t"] + 0.5) if event["kind"] == "active" else (event["t"] - 2, event["t"] + 2) ) intervals.append((start, end, event["who"])) # Total overlap seconds per (label, person). totals = {} for segment in segments: label_totals = totals.setdefault(segment["label"], {}) for start, end, who in intervals: overlap = min(end, segment["end"]) - max(start, segment["start"]) if overlap > 0: label_totals[who] = label_totals.get(who, 0) + overlap # greedy one-to-one: strongest (label, person) overlap first, a person is never given to two labels pairs = sorted( ( (overlap, label, who) for label, label_totals in totals.items() for who, overlap in label_totals.items() ), reverse=True, ) assigned, used_people = {}, set() for overlap, label, who in pairs: if label in assigned or who in used_people: continue # Accept only if overlap >= 5 s and >= 40 % of the label's total. if overlap >= 5 and overlap / sum(totals[label].values()) >= 0.4: assigned[label] = (who, overlap) used_people.add(who) # Every label gets a row, even unmatched ones (who=''). for label in {segment["label"] for segment in segments}: 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")