Download eval/eval_wer.py from RightNowAI/duplex-v0: direct link, hf CLI and curl.
- Browser
- Download file 4.8 kB
-
https://huggingface.co/RightNowAI/duplex-v0/resolve/main/eval/eval_wer.py
- Command line
-
hf download hf://RightNowAI/duplex-v0/eval/eval_wer.py
-
curl -L -o eval_wer.py https://huggingface.co/RightNowAI/duplex-v0/resolve/main/eval/eval_wer.py
4.8 kB
| """Nobody has listened to the audio, so a speech recogniser does: Whisper large-v3 (Apache-2.0) | |
| transcribes it and the transcript is compared with the words the audio was meant to say. | |
| --pairs DIR ... folders of <name>.wav + <name>.txt (reply audio and the reply's own text, | |
| saved by serving/loadtest.py --save-audio) | |
| --tts-sample N N random clips of the training speech (data/out/tts) against the dialogue text | |
| Reported per group: word error rate (all errors / all reference words), and how often the | |
| first three words came out right (the first words are what a smaller first audio chunk | |
| could damage). Whisper makes errors of its own, so these are upper bounds on the audio's. | |
| CUDA_VISIBLE_DEVICES=7 python -m eval.eval_wer --pairs eval/results/loadtest_fc25/audio --tts-sample 300 --out eval/results/wer | |
| """ | |
| import argparse | |
| import json | |
| import random | |
| import re | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from scipy.signal import resample_poly | |
| from duplex.spec import SR, read_jsonl, read_wav, write_json | |
| UNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split() | |
| TENS = "twenty thirty forty fifty sixty seventy eighty ninety".split() | |
| def spell(m): | |
| n = int(m.group(0)) | |
| if n < 20: | |
| return UNITS[n] | |
| if n < 100: | |
| return TENS[n // 10 - 2] + ("" if n % 10 == 0 else " " + UNITS[n % 10]) | |
| return m.group(0) | |
| def words(text): | |
| text = re.sub(r"<[^>]+>", " ", text.split("</think>")[-1]).lower().replace("-", " ") | |
| text = re.sub(r"\d+", spell, text) | |
| return re.sub(r"[^a-z0-9' ]+", " ", text).replace("'", "").split() | |
| def errors(ref, hyp): | |
| """Word-level edit distance.""" | |
| d = list(range(len(hyp) + 1)) | |
| for i, r in enumerate(ref, 1): | |
| prev, d[0] = d[0], i | |
| for j, h in enumerate(hyp, 1): | |
| prev, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, prev + (r != h)) | |
| return d[-1] | |
| def score(rows): | |
| rows = [r for r in rows if r["ref"]] | |
| if not rows: | |
| return {"clips": 0} | |
| return { | |
| "clips": len(rows), "reference_words": sum(len(r["ref"]) for r in rows), | |
| "word_error_rate": sum(r["errors"] for r in rows) / sum(len(r["ref"]) for r in rows), | |
| "clips_with_no_error": sum(r["errors"] == 0 for r in rows), | |
| "first_three_words_right": sum(r["ref"][:3] == r["hyp"][:3] for r in rows) / len(rows), | |
| } | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--pairs", nargs="*", default=[]) | |
| ap.add_argument("--tts-sample", type=int, default=0) | |
| ap.add_argument("--tts", default="data/out/tts") | |
| ap.add_argument("--dialogues", default="data/out/dialogues.jsonl") | |
| ap.add_argument("--out", default="eval/results/wer") | |
| ap.add_argument("--seed", type=int, default=0) | |
| args = ap.parse_args() | |
| from transformers import pipeline | |
| asr = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", torch_dtype=torch.float16, device=0, chunk_length_s=30) | |
| def transcribe(x, sr): | |
| if sr != SR: | |
| x = resample_poly(x, SR, sr) | |
| return asr({"raw": np.asarray(x, dtype=np.float32), "sampling_rate": SR}, generate_kwargs={"language": "english", "task": "transcribe"})["text"] | |
| groups = {} | |
| for d in args.pairs: | |
| rows = [] | |
| for wav in sorted(Path(d).glob("*.wav")): | |
| x, sr = read_wav(wav) | |
| ref, hyp = words(wav.with_suffix(".txt").read_text(encoding="utf-8")), None | |
| hyp = words(transcribe(x[:, 0], sr)) | |
| rows.append({"clip": wav.name, "ref": ref, "hyp": hyp, "errors": errors(ref, hyp)}) | |
| groups[str(d)] = rows | |
| if args.tts_sample: | |
| rng = random.Random(args.seed) | |
| dialogues = read_jsonl(args.dialogues) | |
| rows = [] | |
| for d in rng.sample(dialogues, min(args.tts_sample, len(dialogues))): | |
| clips = np.load(Path(args.tts) / f"{d['id']}.npz") | |
| ti = rng.randrange(len(d["turns"])) | |
| parts = [p.strip() for p in d["turns"][ti]["text"].split("[pause]") if p.strip()] | |
| si = rng.randrange(len(parts)) | |
| ref = words(parts[si]) | |
| hyp = words(transcribe(clips[f"t{ti}_s{si}"].astype(np.float32) / 32768, SR)) | |
| rows.append({"clip": f"{d['id']} t{ti}_s{si}", "voice": d["caller_voice"] if d["turns"][ti]["spk"] == "caller" else d["agent_voice"], | |
| "ref": ref, "hyp": hyp, "errors": errors(ref, hyp)}) | |
| groups["training_speech"] = rows | |
| summary = {name: score(rows) for name, rows in groups.items()} | |
| out = Path(args.out) | |
| write_json(out / "clips.json", groups) | |
| write_json(out / "wer.json", summary) | |
| print(json.dumps(summary, indent=1)) | |
| if __name__ == "__main__": | |
| main() | |