Download code/tts_filter.py from phamhai/lifemate-data: direct link, hf CLI and curl.
- Browser
- Download file 2.05 kB
-
https://huggingface.co/datasets/phamhai/lifemate-data/resolve/main/code/tts_filter.py
- Command line
-
hf download hf://datasets/phamhai/lifemate-data/code/tts_filter.py
-
curl -L -o tts_filter.py https://huggingface.co/datasets/phamhai/lifemate-data/resolve/main/code/tts_filter.py
2.05 kB
| """Keep TTS clips the current ASR mostly agrees with (TTS sometimes skips/garbles words -> wrong labels). | |
| Number tokens are ignored (TTS reads '4' as 'bốn'). usage: python tts_filter.py --asr MODEL --inp tts_v1/extra.jsonl --out tts_v1/extra_ok.jsonl --max-wer 0.3""" | |
| import argparse, json, re, unicodedata | |
| import soundfile as sf, torch | |
| from transformers import WhisperForConditionalGeneration, WhisperProcessor | |
| NUM = set("không một mốt hai ba bốn tư năm lăm sáu bảy tám chín mười mươi trăm nghìn ngàn triệu tỷ linh lẻ rưỡi kg ký".split()) | |
| tok = lambda s: [w for w in re.findall(r"[^\W_]+", unicodedata.normalize("NFC", s.lower())) if not w.isdigit() and w not in NUM and not any(c.isdigit() for c in w)] | |
| def wer(r, h): | |
| d = list(range(len(h) + 1)) | |
| for i in range(1, len(r) + 1): | |
| q, d[0] = d[0], i | |
| for j in range(1, len(h) + 1): q, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, q + (r[i - 1] != h[j - 1])) | |
| return d[-1] / max(1, len(r)) | |
| ap = argparse.ArgumentParser(); ap.add_argument("--asr"); ap.add_argument("--inp"); ap.add_argument("--out"); ap.add_argument("--max-wer", type=float, default=0.3) | |
| a = ap.parse_args() | |
| p = WhisperProcessor.from_pretrained(a.asr); m = WhisperForConditionalGeneration.from_pretrained(a.asr, torch_dtype=torch.float16).cuda().eval() | |
| rows = [json.loads(l) for l in open(a.inp, encoding="utf-8")] | |
| keep, ws = [], [] | |
| for i in range(0, len(rows), 16): | |
| ch = rows[i:i + 16] | |
| f = p([sf.read(r["audio"], dtype="float32")[0] for r in ch], sampling_rate=16000, return_tensors="pt").input_features.cuda().half() | |
| with torch.no_grad(): hyp = p.batch_decode(m.generate(f, num_beams=1, max_new_tokens=200), skip_special_tokens=True) | |
| for r, h in zip(ch, hyp): | |
| w = wer(tok(r["text"]), tok(h)); ws.append(w) | |
| if w <= a.max_wer: keep.append(r) | |
| open(a.out, "w", encoding="utf-8").writelines(json.dumps(r, ensure_ascii=False) + "\n" for r in keep) | |
| print(f"kept {len(keep)}/{len(rows)} (max-wer {a.max_wer}); mean TTS->ASR WER {sum(ws) / len(ws):.1%}") | |