Auto speaker count from roster, one-to-one speaker map, clean LLM junk, merge recordings, Teams caption scraping

This commit is contained in:
Stefano Zini
2026-11-03 14:28:58 +01:00
parent 9763b4ffab
commit 0a66ae0c05
6 changed files with 74 additions and 22 deletions
+8 -1
View File
@@ -10,7 +10,14 @@ M = Path(__file__).parent / "models"
THREADS = 8 THREADS = 8
def run(name, speakers=5, threshold=0.85): def roster_size(name, default=5):
"""Distinct people seen in the Teams roster events -> cluster count (a fixed 5 merged 8 people into 4 labels)."""
who = {p["who"] for e in db.events(name, "present") if e["who_key"] != "video" for p in json.loads(e["text"] or "[]") if p.get("who")}
return min(max(len(who), 2), 12) if who else default
def run(name, speakers=0, threshold=0.85):
speakers = speakers or roster_size(name)
import sherpa_onnx import sherpa_onnx
src = db.out_dir(name) / "audio.opus" src = db.out_dir(name) / "audio.opus"
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"], raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
+12 -8
View File
@@ -7,12 +7,12 @@ const SEL = {
speaking: '[data-tid="voice-level-stream-outline"][data-is-speaking="true"]', speaking: '[data-tid="voice-level-stream-outline"][data-is-speaking="true"]',
self: '[data-tid="myself-video"]', self: '[data-tid="myself-video"]',
shareAria: /^(Contenuto condiviso da|Content shared by) (.+)$/, shareAria: /^(Contenuto condiviso da|Content shared by) (.+)$/,
caption: null, captionAuthor: null, captionText: null, // discovery step (see plan 3b) caption: '[data-tid="author"],[data-tid="closed-caption-text"]', // DOM order; author only on first row of a speaker's run
chatMsg: null, chatAuthor: null, chatText: null, // discovery step chatMsg: null, chatAuthor: null, chatText: null, // discovery step
hand: null, // discovery step hand: null, // discovery step
}; };
let buf = [], timers = [], seenCap = new WeakSet(), seenChat = new WeakSet(), lastShare = "", raised = new Set(), lastTitle = null; let buf = [], timers = [], seenCap = new WeakMap(), capAuthor = "", seenChat = new WeakSet(), lastShare = "", raised = new Set(), lastTitle = null;
const norm = raw => { const norm = raw => {
raw = (raw || "").trim(); raw = (raw || "").trim();
@@ -28,7 +28,7 @@ const keyOf = tile => {
const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent); const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent);
const selfName = () => { const s = document.querySelector(SEL.self); return s ? nameOf(s) : ""; }; const selfName = () => { const s = document.querySelector(SEL.self); return s ? nameOf(s) : ""; };
const emit = (kind, who_key = "", who = "", text = "") => buf.push({ ts: Date.now(), kind, who_key, who, text }); const emit = (kind, who_key = "", who = "", text = "") => buf.push({ ts: Date.now(), kind, who_key, who, text });
const guard = f => () => { try { f(); } catch { } }; const guard = f => () => { try { f(); } catch (e) { console.error("[teams-whisper]", e); } };
const send = () => { if (buf.length) chrome.runtime.sendMessage({ to: "off", cmd: "events", events: buf.splice(0) }).catch(() => { }); }; const send = () => { if (buf.length) chrome.runtime.sendMessage({ to: "off", cmd: "events", events: buf.splice(0) }).catch(() => { }); };
const tiles = () => [...document.querySelectorAll(SEL.nametag)].map(tileOf).filter(Boolean); const tiles = () => [...document.querySelectorAll(SEL.nametag)].map(tileOf).filter(Boolean);
@@ -64,9 +64,12 @@ function share() {
} }
function messages() { function messages() {
if (SEL.caption) for (const el of document.querySelectorAll(SEL.caption)) { if (SEL.caption) for (const el of document.querySelectorAll(SEL.caption)) {
if (seenCap.has(el)) continue; seenCap.add(el); if (el.getAttribute("data-tid") === "author") { capAuthor = norm(el.textContent); continue; }
const text = el.querySelector(SEL.captionText)?.textContent.trim(); // caption text grows while spoken: emit once it was unchanged for a full tick
if (text) emit("caption", "", norm(el.querySelector(SEL.captionAuthor)?.textContent), text); const text = el.textContent.trim(), s = seenCap.get(el) || {};
if (s.done) continue;
if (text && s.text === text) { s.done = true; emit("caption", "", capAuthor, text); }
s.text = text; seenCap.set(el, s);
} }
if (SEL.chatMsg) for (const el of document.querySelectorAll(SEL.chatMsg)) { if (SEL.chatMsg) for (const el of document.querySelectorAll(SEL.chatMsg)) {
if (seenChat.has(el)) continue; seenChat.add(el); if (seenChat.has(el)) continue; seenChat.add(el);
@@ -92,11 +95,12 @@ function stop() {
} }
function start() { function start() {
stop(); stop();
buf = []; seenCap = new WeakSet(); seenChat = new WeakSet(); raised = new Set(); lastTitle = null; lastShare = ""; buf = []; seenCap = new WeakMap(); capAuthor = ""; seenChat = new WeakSet(); raised = new Set(); lastTitle = null; lastShare = "";
meta(); present(); meta(); present();
timers = [ timers = [
setInterval(guard(() => { meta(); active(); }), 500), setInterval(guard(() => { meta(); active(); }), 500),
setInterval(guard(() => { share(); messages(); }), 1000), setInterval(guard(share), 1000),
setInterval(guard(messages), 1000),
setInterval(guard(present), 30000), setInterval(guard(present), 30000),
setInterval(guard(send), 5000), setInterval(guard(send), 5000),
]; ];
+2 -2
View File
@@ -82,7 +82,7 @@ def default_device():
@flow(name="meeting", log_prints=True, task_runner=ThreadPoolTaskRunner(max_workers=3)) @flow(name="meeting", log_prints=True, task_runner=ThreadPoolTaskRunner(max_workers=3))
def meeting(name: str, start_from: str = "audio", speakers: int = 5, model: str = "large-v3-turbo", device: str | None = None): def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str = "large-v3-turbo", device: str | None = None):
device = device or default_device() device = device or default_device()
go = lambda s: STEPS.index(s) >= STEPS.index(start_from) go = lambda s: STEPS.index(s) >= STEPS.index(start_from)
L = Llama(name) L = Llama(name)
@@ -143,7 +143,7 @@ if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8") sys.stdout.reconfigure(encoding="utf-8")
ap = argparse.ArgumentParser() ap = argparse.ArgumentParser()
ap.add_argument("name"); ap.add_argument("--from", dest="start", default="audio", choices=STEPS) ap.add_argument("name"); ap.add_argument("--from", dest="start", default="audio", choices=STEPS)
ap.add_argument("--speakers", type=int, default=5); ap.add_argument("--device", choices=["cuda", "npu"]) ap.add_argument("--speakers", type=int, default=0, help="0 = auto from Teams roster"); ap.add_argument("--device", choices=["cuda", "npu"])
ap.add_argument("--bench-npu", action="store_true") ap.add_argument("--bench-npu", action="store_true")
a = ap.parse_args() a = ap.parse_args()
if a.bench_npu: bench(a.name) if a.bench_npu: bench(a.name)
+8 -1
View File
@@ -40,6 +40,13 @@ def _tick(note):
THINK = 1024 # reasoning budget per report call (server: --reasoning-budget); added to max_tokens so the answer keeps its room THINK = 1024 # reasoning budget per report call (server: --reasoning-budget); added to max_tokens so the answer keeps its room
def _clean(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 [_clean(x) for x in o]
if isinstance(o, dict): return {k: _clean(v) for k, v in o.items()}
return o
def chat(system, user, max_tokens, retries=2, think=False): 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.""" """think=True only for the report passes (topics, docs merge, overview); docs queries and memory stay fast."""
@@ -56,7 +63,7 @@ def chat(system, user, max_tokens, retries=2, think=False):
r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800) r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800)
t = llama.content(json.load(r), f"report ({max_tokens} max)") t = llama.content(json.load(r), f"report ({max_tokens} max)")
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S) t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
d = json.loads(t[t.find("{"):t.rfind("}") + 1]) d = _clean(json.loads(t[t.find("{"):t.rfind("}") + 1]))
if isinstance(d, dict): return d if isinstance(d, dict): return d
except (ValueError, KeyError): pass except (ValueError, KeyError): pass
return None return None
+36 -4
View File
@@ -63,7 +63,7 @@ def ask_once(q):
def now(): return time.strftime("%Y-%m-%d %H:%M:%S") def now(): return time.strftime("%Y-%m-%d %H:%M:%S")
def launch(name, start_from, speakers=5): def launch(name, start_from, speakers=0):
"""Queue a flow run. One flow at a time (one GPU): the rest wait. False if `name` is already running or queued.""" """Queue a flow run. One flow at a time (one GPU): the rest wait. False if `name` is already running or queued."""
global BATCH global BATCH
with QLOCK: with QLOCK:
@@ -159,6 +159,34 @@ def cancel(name, reason="cancelled from web UI"):
return bool(pids) return bool(pids)
def merge(names):
"""Join webm parts of one call (restarted recording): stream copy in start order, events shifted by the cumulative length.
Returns (merged_name, None) or (None, error). Originals stay; delete them from the GUI once the merged report is fine."""
c = db.connect()
rows = [c.execute("SELECT name, started_at, ended_at, chunks, bytes, status FROM recordings WHERE name=?", (n,)).fetchone() for n in names]
if len(names) < 2 or None in rows: return None, "servono almeno 2 registrazioni esistenti"
if any(r["status"] == "recording" or r["name"] in R or r["name"] in JOBS and JOBS[r["name"]].poll() is None for r in rows): return None, "ferma prima le registrazioni in corso"
rows.sort(key=lambda r: r["started_at"] or "")
files = [out / f"{r['name']}.webm" for r in rows]
if not all(f.exists() for f in files): return None, "solo registrazioni .webm"
merged = rows[0]["name"] + "_merged"
if c.execute("SELECT 1 FROM recordings WHERE name=?", (merged,)).fetchone(): return None, "unione già esistente"
lst = out / f"{merged}.concat.txt"
lst.write_text("".join(f"file '{f.name}'\n" for f in files), encoding="utf-8")
dst = out / f"{merged}.webm"
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(dst)], capture_output=True, text=True)
lst.unlink(missing_ok=True)
if r.returncode: return None, r.stderr[-300:]
offs, o = [], 0.0
for f in files: offs.append(o); o += db.duration(f)
db.upsert_recording(merged, source="ext", started_at=rows[0]["started_at"], ended_at=rows[-1]["ended_at"], chunks=sum(r["chunks"] or 0 for r in rows),
bytes=dst.stat().st_size, duration_s=o, status="queued")
for r, off in zip(rows, offs):
c.execute("INSERT INTO call_events(name,t,kind,who_key,who,text) SELECT ?,t+?,kind,who_key,who,text FROM call_events WHERE name=?", (merged, off, r["name"]))
launch(merged, "audio")
return merged, None
def reaper(): def reaper():
"""Prefect cannot stop flows it did not launch: honour 'Cancel' from its UI and close runs whose process died.""" """Prefect cannot stop flows it did not launch: honour 'Cancel' from its UI and close runs whose process died."""
while True: while True:
@@ -351,7 +379,7 @@ body.drag main{outline:3px dashed var(--acc);outline-offset:8px;border-radius:14
button.del{color:var(--redf)}button.del:hover{background:var(--red);border-color:var(--redf)} button.del{color:var(--redf)}button.del:hover{background:var(--red);border-color:var(--redf)}
dialog{border:1px solid var(--line);border-radius:14px;background:var(--card);color:var(--fg);padding:16px;width:min(960px,94vw)}dialog::backdrop{background:rgba(0,0,0,.5)} dialog{border:1px solid var(--line);border-radius:14px;background:var(--card);color:var(--fg);padding:16px;width:min(960px,94vw)}dialog::backdrop{background:rgba(0,0,0,.5)}
dialog video{width:100%;max-height:68vh;background:#000;border-radius:8px}dialog input.tm{width:90px}#cmsg{color:var(--mut);font-size:13px}</style> dialog video{width:100%;max-height:68vh;background:#000;border-radius:8px}dialog input.tm{width:90px}#cmsg{color:var(--mut);font-size:13px}</style>
<main><header><h1>Riunioni</h1><div class=row><span id=qs></span><select id=llm title="modello per le schermate (shots)" onchange=setLlm()></select><select id=llmr title="modello per il report" onchange=setLlm()></select><button class=pri onclick=pick() title="mp4, mkv, mov, webm, wav, m4a, mp3">⬆ Carica video</button> <main><header><h1>Riunioni</h1><div class=row><span id=qs></span><select id=llm title="modello per le schermate (shots)" onchange=setLlm()></select><select id=llmr title="modello per il report" onchange=setLlm()></select><button onclick=mergeSel() title="unisce in un solo video le registrazioni spuntate (stessa chiamata riavviata)">Unisci spuntati</button><button class=pri onclick=pick() title="mp4, mkv, mov, webm, wav, m4a, mp3">⬆ Carica video</button>
<input type=file id=up accept="video/*,audio/*,.mkv" hidden></div></header> <input type=file id=up accept="video/*,audio/*,.mkv" hidden></div></header>
<div id=hint>Trascina qui un video o un audio di una riunione per elaborarlo.</div> <div id=hint>Trascina qui un video o un audio di una riunione per elaborarlo.</div>
<div class="card" id=ub hidden><div class=pg style="margin:0;border:0;padding:0;background:none"><div class=pgh><span><span class=big id=ubig>0%</span> &nbsp;<b id=utitle></b></span><button id=ucancel>annulla</button></div> <div class="card" id=ub hidden><div class=pg style="margin:0;border:0;padding:0;background:none"><div class=pgh><span><span class=big id=ubig>0%</span> &nbsp;<b id=utitle></b></span><button id=ucancel>annulla</button></div>
@@ -377,6 +405,7 @@ j.sources.map(s=>`<div><small>[${s.n}] ${E(s.date)} ${E(s.meeting)} — ${E(s.to
async function srch(){if(!q.value){sr.innerHTML="";return}const j=await (await fetch("/search?q="+encodeURIComponent(q.value))).json(); async function srch(){if(!q.value){sr.innerHTML="";return}const j=await (await fetch("/search?q="+encodeURIComponent(q.value))).json();
sr.innerHTML=j.speech.map(r=>`<div>${E(r[0])} ${fmt(r[1])} ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")+j.screen.map(r=>`<div>🖥 <a href="/shot?name=${r[0]}&file=shots/${r[4]}" target=_blank>${E(r[0])} ${fmt(r[1])}</a> ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")} sr.innerHTML=j.speech.map(r=>`<div>${E(r[0])} ${fmt(r[1])} ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")+j.screen.map(r=>`<div>🖥 <a href="/shot?name=${r[0]}&file=shots/${r[4]}" target=_blank>${E(r[0])} ${fmt(r[1])}</a> ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")}
async function run(n){const f=document.getElementById("f-"+n).value;const r=await fetch(`/run?name=${n}&from=${f}`,{method:"POST"});if(r.status==409)alert("già in esecuzione");tick()} async function run(n){const f=document.getElementById("f-"+n).value;const r=await fetch(`/run?name=${n}&from=${f}`,{method:"POST"});if(r.status==409)alert("già in esecuzione");tick()}
async function mergeSel(){const n=[...document.querySelectorAll(".mg:checked")].map(x=>x.value);if(n.length<2)return alert("spunta almeno 2 registrazioni");const r=await fetch("/merge?names="+n.join(","),{method:"POST"});if(!r.ok)alert(await r.text());tick()}
const open_=new Set(); const open_=new Set();
async function spk(n){open_.has(n)?open_.delete(n):open_.add(n);tick()} async function spk(n){open_.has(n)?open_.delete(n):open_.add(n);tick()}
async function panel(n){const j=await (await fetch("/speakers?name="+n)).json(); async function panel(n){const j=await (await fetch("/speakers?name="+n)).json();
@@ -450,7 +479,7 @@ document.querySelectorAll("select[id^=f-]").forEach(s=>sel[s.id]=s.value);
let h="<tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr>"; let h="<tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr>";
for(const r of j.recs){const st=r.running&&r.status=="done"?"running":r.status; for(const r of j.recs){const st=r.running&&r.status=="done"?"running":r.status;
const nm=r.title||r.upload; const nm=r.title||r.upload;
h+=`<tr><td>${nm?`<b>${E(nm)}</b><br><small>${r.name}</small>`:r.name}<td><span class="b ${r.status}" title="${E(r.error)}">${r.status}</span>${r.receiving_age_s!=null&&r.status=="recording"?` <small>${r.receiving_age_s}s ago</small>`:""}${r.error?`<br><small>${E(r.error)}</small>`:""}<td>${r.duration_s?fmt(r.duration_s):""}<td>${r.speakers??""}<td>${r.mb} h+=`<tr><td><input type=checkbox class=mg value="${r.name}">${nm?`<b>${E(nm)}</b><br><small>${r.name}</small>`:r.name}<td><span class="b ${r.status}" title="${E(r.error)}">${r.status}</span>${r.receiving_age_s!=null&&r.status=="recording"?` <small>${r.receiving_age_s}s ago</small>`:""}${r.error?`<br><small>${E(r.error)}</small>`:""}<td>${r.duration_s?fmt(r.duration_s):""}<td>${r.speakers??""}<td>${r.mb}
<td>${r.files.includes("report.html")?`<a href="/report?name=${r.name}" target=_blank>report</a><a href="/pdf?name=${r.name}" target=_blank>pdf</a>`:""}${r.flow_run_id?`<a href="http://127.0.0.1:4200/runs/flow-run/${r.flow_run_id}" target=_blank>prefect</a>`:""} <td>${r.files.includes("report.html")?`<a href="/report?name=${r.name}" target=_blank>report</a><a href="/pdf?name=${r.name}" target=_blank>pdf</a>`:""}${r.flow_run_id?`<a href="http://127.0.0.1:4200/runs/flow-run/${r.flow_run_id}" target=_blank>prefect</a>`:""}
<td><select id="f-${r.name}">${["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].map(s=>`<option>${s}`).join("")}</select><button onclick="run('${r.name}')">run</button><button onclick="spk('${r.name}')">speakers</button>${r.mb?`<button title="anteprima e ritaglio" onclick="play('${r.name}',${r.duration_s||0},'${E(nm||r.name).replace(/'/g,"")}')">▶ video</button>`:""}${r.running?`<button onclick="stopRun('${r.name}')">stop</button>`:`<button class=del title="elimina la riunione" onclick="del_('${r.name}','${E(nm||r.name).replace(/'/g,"")}')">🗑</button>`}`; <td><select id="f-${r.name}">${["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].map(s=>`<option>${s}`).join("")}</select><button onclick="run('${r.name}')">run</button><button onclick="spk('${r.name}')">speakers</button>${r.mb?`<button title="anteprima e ritaglio" onclick="play('${r.name}',${r.duration_s||0},'${E(nm||r.name).replace(/'/g,"")}')">▶ video</button>`:""}${r.running?`<button onclick="stopRun('${r.name}')">stop</button>`:`<button class=del title="elimina la riunione" onclick="del_('${r.name}','${E(nm||r.name).replace(/'/g,"")}')">🗑</button>`}`;
h+=progPanel(r); h+=progPanel(r);
@@ -523,8 +552,11 @@ class H(BaseHTTPRequestHandler):
elif u.path == "/crop": self.crop(name, q) elif u.path == "/crop": self.crop(name, q)
elif u.path == "/cancel": elif u.path == "/cancel":
self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200) self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200)
elif u.path == "/merge":
m, err = merge([n for n in q.get("names", "").split(",") if n])
self._send(m.encode() if m else err.encode(), 200 if m else 400)
elif u.path == "/run": elif u.path == "/run":
ok = launch(name, q.get("from", "audio"), int(q.get("speakers") or 5)) ok = launch(name, q.get("from", "audio"), int(q.get("speakers") or 0))
self._send(b"" if ok else "già in coda o in esecuzione".encode(), 200 if ok else 409) self._send(b"" if ok else "già in coda o in esecuzione".encode(), 200 if ok else 409)
elif u.path == "/run_all": elif u.path == "/run_all":
f = q.get("from", "audio") f = q.get("from", "audio")
+8 -6
View File
@@ -19,10 +19,12 @@ def run(name):
for a, b, who in iv: for a, b, who in iv:
o = min(b, s["end"]) - max(a, s["start"]) o = min(b, s["end"]) - max(a, s["start"])
if o > 0: d[who] = d.get(who, 0) + o 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
if ov >= 5 and ov / sum(tot[label].values()) >= 0.4: got[label] = (who, ov); used.add(who)
for label in {s["label"] for s in segs}: for label in {s["label"] for s in segs}:
d = tot.get(label, {}) who, ov = got.get(label, ("", sum(tot.get(label, {}).values())))
if not d: db.set_speaker_map(name, label, who, "auto", ov)
db.set_speaker_map(name, label, "", "auto", 0); continue
person = max(d, key=d.get); ov = d[person]
ok = ov >= 5 and ov / sum(d.values()) >= 0.4
db.set_speaker_map(name, label, person if ok else "", "auto", ov)