Cotton code
133 lines · 5.8 KB · PythonRaw
#!/usr/bin/env python3"""Measure a speaker-separation pair (segmentation + embedding) on recordings with RTTM truth.    measure_speakers.py <segmentation-model.onnx> <embedding-model.onnx> <folder> [--threshold 0.5] [--threads 4]<folder> holds <name>.wav and <name>.rttm pairs (AMI's test meetings, say). For eachpair it runs sherpa-onnx's offline speaker diarization (pyannote segmentation, theembedding model, fast clustering with the number of speakers unknown) and scores thediarization error rate: missed speech, false alarm and speaker confusion over thereference speech, on 10 ms frames, no forgiveness collar, overlap counted, speakersmapped one to one to minimise the error. Also the real-time factor and CPU time.Nothing touches the network."""import argparseimport jsonimport osimport resourceimport sysimport timefrom pathlib import PathFRAME = 0.01def rttm(path: Path):    out = []    for line in path.read_text().splitlines():        f = line.split()        if f and f[0] == "SPEAKER":            out.append((float(f[3]), float(f[3]) + float(f[4]), f[7]))    return outdef frames(segs, n):    import numpy as np    labels = sorted({s for _, _, s in segs})    m = np.zeros((len(labels), n), dtype=bool)    for a, b, s in segs:        m[labels.index(s), int(a / FRAME):min(n, int(b / FRAME))] = True    return mdef der(ref, hyp, dur):    import numpy as np    from scipy.optimize import linear_sum_assignment    n = int(dur / FRAME) + 1    R, H = frames(ref, n), frames(hyp, n)    nr, nh = R.sum(0), H.sum(0) if len(H) else np.zeros(n, dtype=int)    total = nr.sum()    miss = np.maximum(nr - nh, 0).sum()    fa = np.maximum(nh - nr, 0).sum()    if len(H) and len(R):        overlap = R.astype(np.int32) @ H.T.astype(np.int32)        r, c = linear_sum_assignment(-overlap)        correct = overlap[r, c].sum()    else:        correct = 0    confusion = np.minimum(nr, nh).sum() - correct    return {"der": (miss + fa + confusion) / total, "miss": miss / total, "false_alarm": fa / total,            "confusion": confusion / total, "speakers_ref": len(R), "speakers_hyp": len(H)}def main() -> None:    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)    ap.add_argument("segmentation")    ap.add_argument("embedding")    ap.add_argument("folder", type=Path)    ap.add_argument("--threshold", type=float, default=0.5)    ap.add_argument("--threads", type=int, default=4)    ap.add_argument("--limit-s", type=float, default=0, help="score only the first N seconds of each recording")    a = ap.parse_args()    if hasattr(os, "sched_setaffinity") and os.environ.get("VOICE_CPUS"):        lo, hi = os.environ["VOICE_CPUS"].split("-")        os.sched_setaffinity(0, set(range(int(lo), int(hi) + 1)))    import numpy as np    import sherpa_onnx as so    import soundfile as sf    import soxr    cfg = so.OfflineSpeakerDiarizationConfig(        segmentation=so.OfflineSpeakerSegmentationModelConfig(            pyannote=so.OfflineSpeakerSegmentationPyannoteModelConfig(model=a.segmentation), num_threads=a.threads),        embedding=so.SpeakerEmbeddingExtractorConfig(model=a.embedding, num_threads=a.threads),        clustering=so.FastClusteringConfig(num_clusters=-1, threshold=a.threshold),        min_duration_on=0.3, min_duration_off=0.5)    if not cfg.validate():        sys.exit("bad diarization config")    sd = so.OfflineSpeakerDiarization(cfg)    rows = []    tot = {"audio": 0.0, "wall": 0.0, "cpu": 0.0}    for wav in sorted(a.folder.glob("*.wav")):        truth = wav.with_suffix(".rttm")        if not truth.exists():            continue        data, sr = sf.read(str(wav), dtype="float32", always_2d=True)        x = data.mean(axis=1)        if sr != sd.sample_rate:            x = soxr.resample(x, sr, sd.sample_rate)        if a.limit_s:            x = x[: int(a.limit_s * sd.sample_rate)]        dur = len(x) / sd.sample_rate        r0 = resource.getrusage(resource.RUSAGE_SELF)        t0 = time.perf_counter()        result = sd.process(np.ascontiguousarray(x)).sort_by_start_time()        wall = time.perf_counter() - t0        r1 = resource.getrusage(resource.RUSAGE_SELF)        cpu = (r1.ru_utime + r1.ru_stime) - (r0.ru_utime + r0.ru_stime)        hyp = [(s.start, s.end, str(s.speaker)) for s in result]        ref = [(s, min(e, dur), k) for s, e, k in rttm(truth) if s < dur]        score = der(ref, hyp, dur)        score.update(file=wav.stem, seconds=round(dur), rtf=round(wall / dur, 4), rtf_cpu=round(cpu / dur / a.threads, 4))        rows.append(score)        tot["audio"] += dur        tot["wall"] += wall        tot["cpu"] += cpu        print(f"{wav.stem:<10} DER {score['der'] * 100:5.1f}%  miss {score['miss'] * 100:4.1f}  fa {score['false_alarm'] * 100:4.1f}  "              f"conf {score['confusion'] * 100:4.1f}  speakers {score['speakers_hyp']}/{score['speakers_ref']}  rtf {score['rtf']}", flush=True)    weights = [r["seconds"] for r in rows]    summary = {        "segmentation": Path(a.segmentation).name, "embedding": Path(a.embedding).name, "threshold": a.threshold,        "der": round(sum(r["der"] * w for r, w in zip(rows, weights)) / sum(weights), 4),        "confusion": round(sum(r["confusion"] * w for r, w in zip(rows, weights)) / sum(weights), 4),        "rtf": round(tot["wall"] / tot["audio"], 4), "rtf_cpu": round(tot["cpu"] / tot["audio"] / a.threads, 4),        "bytes": os.path.getsize(a.segmentation) + os.path.getsize(a.embedding), "files": rows,    }    print(json.dumps({k: v for k, v in summary.items() if k != "files"}))    out = Path(os.environ.get("VOICE_OUT", Path.home() / ".cache" / "cotton-voice" / "runs")) / "speakers"    out.mkdir(parents=True, exist_ok=True)    (out / f"{Path(a.segmentation).stem}-{Path(a.embedding).stem}-{a.threshold}.json").write_text(json.dumps(summary, indent=2))if __name__ == "__main__":    main()