Files
teams-whisper/app/diarize.py
T
pinokioandClaude Opus 5.5 a64d3fb275 Hardware-aware install, per-step LLM profiles, tuned llama.cpp for 4 GB VRAM
Benchmarked on RTX 500 Ada 4 GB (~3.2 GB usable on Windows) + Core Ultra 7 155H.

- install.js: log GPU/VRAM/RAM, abort without NVIDIA >= 4 GB VRAM; always
  install Qwen3.5-4B Q4_K_S, Qwen3.6-35B-A3B only with >= 48 GB RAM.
- llama.py: model registry with vision (shots) and text (report/ask)
  profiles; KV q8, image tokens 1024-1536.
  - 35B: vision encoder on GPU, -ngl 30 (shot 142 -> ~50 s); text: -ub 2048.
  - 4B: vision encoder on GPU, FFN of layers 19-31 in RAM (shot 36 -> 22 s);
    text fully on GPU (~30 tok/s, report 4.5 min).
  - Per-step choice in out/llm.txt: default 4B for shots, biggest for report.
- flow.py: restart llama in text profile after shots (no mmproj for report).
- shots.py: prompt v3 (inline template + defined fields, Italian summary
  rules) and bounded json_schema; stops 4B loops, title 1/38 -> 36/38.
- server.py: shots/report model selects, POST /cancel + stop button, reaper
  thread that honours Prefect "Cancel" and closes runs whose process died.
- diarize.py: cut same-speaker paragraphs every 60 s (one 11-min paragraph
  truncated every report at 28:52); 8 threads; CUDA provider with CPU
  fallback via sherpa-onnx cuda12.cudnn9 wheel (CUDA path not yet verified).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:20:19 +01:00

58 lines
3.5 KiB
Python

"""Label who speaks (sherpa-onnx, CUDA with CPU fallback): run(name) -> out/<name>.spk.txt, diar_segments.json, DB lines."""
import json, re, subprocess, time
from pathlib import Path
import numpy as np
import common, db # common: puts the pip nvidia-* CUDA DLLs on PATH
M = Path(__file__).parent / "models"
THREADS = 8 # CPU fallback; sherpa-onnx default is 1 thread: a 40-min call took >10 min
def run(name, speakers=5, threshold=0.85):
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", "-"],
capture_output=True, check=True).stdout
audio = np.frombuffer(raw, np.float32)
def diarizer(provider):
return sherpa_onnx.OfflineSpeakerDiarization(sherpa_onnx.OfflineSpeakerDiarizationConfig(
segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig(
pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(model=str(M / "sherpa-onnx-pyannote-segmentation-3-0/model.onnx")),
num_threads=THREADS, provider=provider),
embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(M / "emb.onnx"), num_threads=THREADS, provider=provider),
clustering=sherpa_onnx.FastClusteringConfig(num_clusters=speakers, threshold=threshold),
min_duration_on=0.3, min_duration_off=0.5))
t0 = time.time()
try: sd, used = diarizer("cuda"), "cuda" # CUDA build: sherpa-onnx==...+cuda12.cudnn9 (flow.py deps)
except Exception as e: print("diarize: CUDA unavailable, using CPU:", e, flush=True); sd, used = diarizer("cpu"), "cpu"
segs = [(s.start, s.end, s.speaker) for s in sd.process(audio).sort_by_start_time()]
print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({used}, {time.time() - t0:.0f} s)", flush=True)
lines = []
for l in (db.OUT / f"{name}.txt").read_text(encoding="utf-8").splitlines():
m = re.match(r"\[(\d+):(\d+)\] (.*)", l)
if m: lines.append((int(m[1]) * 60 + int(m[2]), m[3]))
out, order = [], {}
for i, (t, text) in enumerate(lines):
t1 = lines[i + 1][0] if i + 1 < len(lines) else t + 5
ov = {}
for s, e, sp in segs:
o = min(e, t1) - max(s, t)
if o > 0: ov[sp] = ov.get(sp, 0) + o
sp = max(ov, key=ov.get) if ov else None
if sp is not None: order.setdefault(sp, len(order) + 1)
# same speaker continues: one paragraph, but cut every 60 s so the timestamps stay usable (one 11-min paragraph
# stamped 28:52 made every model end the report there)
if out and out[-1][1] == sp and t - out[-1][0] < 60: out[-1][2] += " " + text
else: out.append([t, sp, text])
# labels by first appearance in the text; clusters never seen in text get the following numbers
for s in sorted(segs):
order.setdefault(s[2], len(order) + 1)
(db.OUT / f"{name}.spk.txt").write_text("\n".join(
f"[{t//60:02d}:{t%60:02d}] " + (f"Speaker {order[sp]}: " if sp is not None else "") + text for t, sp, text in out), encoding="utf-8")
(db.out_dir(name) / "diar_segments.json").write_text(json.dumps(
[{"start": s, "end": e, "label": f"Speaker {order[sp]}"} for s, e, sp in segs]), encoding="utf-8")
db.replace_lines(name, [(t, f"Speaker {order[sp]}" if sp is not None else None, text) for t, sp, text in out])
db.upsert_recording(name, speakers=len({sp for _, sp, _ in out if sp is not None}))
print("saved", db.OUT / f"{name}.spk.txt")