diff --git a/app/diarize.py b/app/diarize.py index cefe437..48d33aa 100644 --- a/app/diarize.py +++ b/app/diarize.py @@ -10,7 +10,14 @@ M = Path(__file__).parent / "models" 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 src = db.out_dir(name) / "audio.opus" raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"], diff --git a/app/ext/teams.js b/app/ext/teams.js index d029ab4..11ef880 100644 --- a/app/ext/teams.js +++ b/app/ext/teams.js @@ -7,12 +7,12 @@ const SEL = { speaking: '[data-tid="voice-level-stream-outline"][data-is-speaking="true"]', self: '[data-tid="myself-video"]', 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 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 => { raw = (raw || "").trim(); @@ -28,7 +28,7 @@ const keyOf = tile => { const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent); 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 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 tiles = () => [...document.querySelectorAll(SEL.nametag)].map(tileOf).filter(Boolean); @@ -64,9 +64,12 @@ function share() { } function messages() { if (SEL.caption) for (const el of document.querySelectorAll(SEL.caption)) { - if (seenCap.has(el)) continue; seenCap.add(el); - const text = el.querySelector(SEL.captionText)?.textContent.trim(); - if (text) emit("caption", "", norm(el.querySelector(SEL.captionAuthor)?.textContent), text); + if (el.getAttribute("data-tid") === "author") { capAuthor = norm(el.textContent); continue; } + // caption text grows while spoken: emit once it was unchanged for a full tick + 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 (seenChat.has(el)) continue; seenChat.add(el); @@ -92,11 +95,12 @@ function stop() { } function start() { 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(); timers = [ setInterval(guard(() => { meta(); active(); }), 500), - setInterval(guard(() => { share(); messages(); }), 1000), + setInterval(guard(share), 1000), + setInterval(guard(messages), 1000), setInterval(guard(present), 30000), setInterval(guard(send), 5000), ]; diff --git a/app/flow.py b/app/flow.py index e0468e2..c2c9c01 100644 --- a/app/flow.py +++ b/app/flow.py @@ -82,7 +82,7 @@ def default_device(): @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() go = lambda s: STEPS.index(s) >= STEPS.index(start_from) L = Llama(name) @@ -143,7 +143,7 @@ if __name__ == "__main__": sys.stdout.reconfigure(encoding="utf-8") ap = argparse.ArgumentParser() 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") a = ap.parse_args() if a.bench_npu: bench(a.name) diff --git a/app/report.py b/app/report.py index aecf251..19e040b 100644 --- a/app/report.py +++ b/app/report.py @@ -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 +def _clean(o): + """Small models sometimes append ' + 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): """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) t = llama.content(json.load(r), f"report ({max_tokens} max)") t = re.sub(r".*?", "", 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 except (ValueError, KeyError): pass return None diff --git a/app/server.py b/app/server.py index 8e345e7..14ef551 100644 --- a/app/server.py +++ b/app/server.py @@ -63,7 +63,7 @@ def ask_once(q): 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.""" global BATCH with QLOCK: @@ -159,6 +159,34 @@ def cancel(name, reason="cancelled from web UI"): 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(): """Prefect cannot stop flows it did not launch: honour 'Cancel' from its UI and close runs whose process died.""" 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)} 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} -

Riunioni

+

Riunioni

Trascina qui un video o un audio di una riunione per elaborarlo.