"""Verify the model and prediction files and recompute corpus-level WER.""" from collections import Counter from hashlib import file_digest import json from pathlib import Path from zipfile import ZipFile from transformers.models.whisper.english_normalizer import EnglishTextNormalizer ROOT = Path(__file__).resolve().parent def sha256(path): with path.open("rb") as stream: return file_digest(stream, "sha256").hexdigest() def word_edits(reference, hypothesis): previous = list(range(len(hypothesis) + 1)) for index, word in enumerate(reference, 1): current = [index] for column, predicted in enumerate(hypothesis, 1): current.append(min(previous[column] + 1, current[-1] + 1, previous[column - 1] + (word != predicted))) previous = current return previous[-1] def main(): metrics = json.loads((ROOT / "metrics.json").read_text()) archive = ROOT.parent / metrics["model"]["filename"] if archive.stat().st_size != metrics["model"]["bytes"] or sha256(archive) != metrics["model"]["sha256"]: raise ValueError("Model archive differs from the scored release") with ZipFile(archive) as package: if package.testzip() is not None: raise ValueError("Model archive failed its ZIP integrity check") normalize = EnglishTextNormalizer({}) for result in metrics["results"]: predictions = ROOT / result["predictions"] if sha256(predictions) != result["predictions_sha256"]: raise ValueError(f"Prediction digest mismatch for {predictions.name}") ids, words, errors = set(), 0, Counter() with predictions.open(encoding="utf-8") as stream: for line in stream: row = json.loads(line) if row["id"] in ids: raise ValueError(f"Duplicate utterance ID {row['id']}") ids.add(row["id"]) reference = normalize(row["reference"]).split() words += len(reference) for name, prediction in row["pred"].items(): errors[name] += word_edits(reference, normalize(prediction).split()) if (len(ids), words, dict(errors)) != (result["clips"], result["words"], result["edits"]): raise ValueError(f"Counts differ from the report for {predictions.name}") print(f"{result['name']} | {len(ids):,} clips | {errors['lattice']:,}/{words:,} edits | " f"{100 * errors['lattice'] / words:.6f}% WER") if __name__ == "__main__": main()