tiny-voca-da / recipe /scripts /intelligibility.py
inlanger's picture
tiny-voca-da v0.1: frontend v4 + sm9 vocoder (ONNX fp32/int8, PyTorch, frontend, recipe, samples)
adabee1 verified
Raw History Blame Contribute Delete
4.73 kB
"""Intelligibility of rendered Danish speech: CER/WER of Whisper large-v3 (Apache-2.0; language
forced to Danish, greedy) against the input text. Lower is better; compare systems on the same
texts. (Røst v3 wav2vec2 was used until 2026-11-25 and dropped for its licence; see
docker/Dockerfile.asr. Its numbers are not comparable with these.)
Usage (inside the `asr` service, data root mounted at /work):
python scripts/intelligibility.py --out checks/asr/<name>.json \
--group "recordings=data/coral_da/validation.jsonl" \
--group "v2 30k=out/val-v2-s30000-voc50k/render.json:vocoded"
A group is MANIFEST[:SUBDIR]:
* a dataset .jsonl (rows with id, audio, text[, split_text]); audio is relative to its folder;
* a render.json from scripts/render_pair.py; audio is <its folder>/<SUBDIR>/<id>.wav.
--ids restricts every group to the ids listed in a .jsonl (e.g. the rendered set), so all
groups are scored on the same texts. The reference is `split_text` (numbers spelled out, as
the frontend reads them) when the dataset row has it, else `text`.
"""
import argparse
import json
import os
import re
from pathlib import Path
import jiwer
import librosa
import torch
from transformers import WhisperForConditionalGeneration, WhisperProcessor
SR = 16000
def normalize(text):
text = re.sub(r"[^\w\s]", " ", text.lower().replace('-', ' '))
return re.sub(r"\s+", " ", text).strip()
def load_group(spec, references):
manifest, _, subdir = spec.partition(':')
manifest = Path(manifest)
if manifest.suffix == '.json':
clips = json.loads(manifest.read_text(encoding='utf-8'))['clips']
return [(c['id'], manifest.parent / subdir / f"{c['id']}.wav", references.get(c['id'], c['text'])) for c in clips]
rows = [json.loads(line) for line in manifest.read_text(encoding='utf-8').splitlines() if line.strip()]
return [(r['id'], manifest.parent / r['audio'], references.get(r['id'], r.get('split_text') or r['text'])) for r in rows]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--group', action='append', required=True, help='"name=MANIFEST[:SUBDIR]"')
parser.add_argument('--ids', type=Path, help='jsonl whose ids (and split_text/text) define the scored set')
parser.add_argument('--out', type=Path, required=True)
parser.add_argument('--batch', type=int, default=8)
args = parser.parse_args()
references, keep = {}, None
if args.ids:
rows = [json.loads(l) for l in args.ids.read_text(encoding='utf-8').splitlines() if l.strip()]
references = {r['id']: r.get('split_text') or r['text'] for r in rows}
keep = set(references)
name, revision = os.environ['ASR_MODEL'], os.environ['ASR_REVISION']
processor = WhisperProcessor.from_pretrained(name, revision=revision)
model = WhisperForConditionalGeneration.from_pretrained(name, revision=revision).eval()
report = {'asr': f'{name}@{revision} language=da task=transcribe greedy', 'normalization': 'lowercase, punctuation -> space',
'groups': {}}
for spec in args.group:
label, source = spec.split('=', 1)
items = [x for x in load_group(source, references) if keep is None or x[0] in keep]
if not items:
raise SystemExit(f'no clips for {label}: {source}')
rows = []
for start in range(0, len(items), args.batch):
chunk = items[start:start + args.batch]
audio = [librosa.load(path, sr=SR, mono=True)[0] for _, path, _ in chunk]
inputs = processor(audio, sampling_rate=SR, return_tensors='pt')
with torch.inference_mode():
ids = model.generate(inputs.input_features, language='da', task='transcribe', num_beams=1, max_new_tokens=200)
for (clip_id, _, reference), hypothesis in zip(chunk, processor.batch_decode(ids, skip_special_tokens=True)):
ref, hyp = normalize(reference), normalize(hypothesis)
rows.append({'id': clip_id, 'reference': ref, 'hypothesis': hyp,
'cer': jiwer.cer(ref, hyp), 'wer': jiwer.wer(ref, hyp)})
refs, hyps = [r['reference'] for r in rows], [r['hypothesis'] for r in rows]
summary = {'clips': len(rows), 'cer': jiwer.cer(refs, hyps), 'wer': jiwer.wer(refs, hyps)}
report['groups'][label] = {**summary, 'rows': rows}
print(f"{label:34s} n={len(rows):3d} CER {100 * summary['cer']:5.2f}% WER {100 * summary['wer']:5.2f}%", flush=True)
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_text(json.dumps(report, indent=2, ensure_ascii=False))
if __name__ == '__main__':
main()