Files
teams-whisper/app/speakers.py
T

37 lines
1.7 KiB
Python

"""Map diarization labels to names seen in Teams call events."""
import json
import db
# Map each diarized 'Speaker N' label to a person from Teams events; unmatched labels get an empty name.
def run(name):
p = db.out_dir(name) / "diar_segments.json"
ev = db.events(name, "active", "caption")
if not p.exists() or not ev: return
segs = json.loads(p.read_text(encoding="utf-8"))
iv = []
# Intervals where a person was speaking or captioned: 'active' is a 0.5 s point, 'caption' is +/-2 s around its timestamp.
for e in ev:
if not e["who"]: continue
a, b = (e["t"], e["t"] + 0.5) if e["kind"] == "active" else (e["t"] - 2, e["t"] + 2)
iv.append((a, b, e["who"]))
# Total overlap seconds per (label, person).
tot = {}
for s in segs:
d = tot.setdefault(s["label"], {})
for a, b, who in iv:
o = min(b, s["end"]) - max(a, s["start"])
if o > 0: d[who] = d.get(who, 0) + o
# greedy one-to-one: strongest (label, person) overlap first, a person is never given to two labels
pairs = sorted(((ov, label, who) for label, d in tot.items() for who, ov in d.items()), reverse=True)
got, used = {}, set()
for ov, label, who in pairs:
if label in got or who in used: continue
# Accept only if overlap >= 5 s and >= 40 % of the label's total.
if ov >= 5 and ov / sum(tot[label].values()) >= 0.4: got[label] = (who, ov); used.add(who)
# Every label gets a row, even unmatched ones (who='').
for label in {s["label"] for s in segs}:
who, ov = got.get(label, ("", sum(tot.get(label, {}).values())))
# Store the mapping (source 'auto', with overlap seconds).
db.set_speaker_map(name, label, who, "auto", ov)