- 8 threads (sherpa-onnx default is 1): 40-min call >10 min -> ~6 min. - CUDA provider measured slower (>7 min, GPU ~5 W): tiny models and one embedding per segment (3474 here), so transfer/launch overhead dominates. Reverted the cuda12.cudnn9 wheel and extra nvidia-* deps. - Progress callback prints every 10 % (segmentation, then embeddings). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
61 lines
3.5 KiB
Python
61 lines
3.5 KiB
Python
"""Label who speaks (sherpa-onnx, CPU): 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 db
|
|
|
|
M = Path(__file__).parent / "models"
|
|
# sherpa-onnx default is 1 thread (>10 min for a 40-min call); 8 threads: ~6 min. CUDA measured slower (>7 min, GPU ~5 W):
|
|
# tiny models + one embedding per segment -> transfer/launch overhead dominates.
|
|
THREADS = 8
|
|
|
|
|
|
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)
|
|
sd = 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),
|
|
embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(M / "emb.onnx"), num_threads=THREADS),
|
|
clustering=sherpa_onnx.FastClusteringConfig(num_clusters=speakers, threshold=threshold),
|
|
min_duration_on=0.3, min_duration_off=0.5))
|
|
t0, last = time.time(), [-1]
|
|
def progress(done, total): # sherpa calls this per processed chunk; print every 10 %
|
|
pct = done * 100 // max(total, 1)
|
|
if pct // 10 > last[0]: last[0] = pct // 10; print(f"diarize {pct}% ({done}/{total}, {time.time() - t0:.0f} s)", flush=True)
|
|
return 0
|
|
segs = [(s.start, s.end, s.speaker) for s in sd.process(audio, callback=progress).sort_by_start_time()]
|
|
print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({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")
|