Datasets:
Formats:
csv
Size:
< 1K
Tags:
speech-recognition
code-switching
nigerian-languages
asr-benchmark
sahara-codeswitch-challenge
License:
Download scripts/score_wer.py from ukeje71/Dengevoice: direct link, hf CLI and curl.
- Browser
- Download file 6.38 kB
-
https://huggingface.co/datasets/ukeje71/Dengevoice/resolve/main/scripts/score_wer.py
- Command line
-
hf download hf://datasets/ukeje71/Dengevoice/scripts/score_wer.py
-
curl -L -o score_wer.py https://huggingface.co/datasets/ukeje71/Dengevoice/resolve/main/scripts/score_wer.py
6.38 kB
| """ | |
| score_wer.py — Step 5: score every engine's output against ground truth. | |
| Reads results/<engine>.csv for every engine present, joins each on clip_id | |
| against audio/ground_truth.csv, and computes: | |
| - WER (Word Error Rate) | |
| - CER (Character Error Rate) | |
| - Accuracy (1 - WER) | |
| - Insertion rate → proxy for hallucination (words added that weren't said) | |
| - Deletion rate → proxy for segment loss (words/chunks dropped) | |
| - Transcript loss → % of clips where the engine returned empty output | |
| Text is normalized identically for every engine before scoring (lowercased, | |
| punctuation stripped) so no engine is unfairly penalized for cosmetic | |
| formatting differences. | |
| NOTE on switch-point WER: this requires ground_truth.csv to mark WHERE in | |
| each sentence the language switches (e.g. word-level language tags). Our | |
| current ground_truth.csv doesn't have that annotation yet — this script | |
| computes whole-clip WER only. If switch-point accuracy is required for | |
| scoring, that needs a separate annotation pass on the ground truth first | |
| (flag this as a known limitation in the report, not a silent gap). | |
| Usage: | |
| !python scripts/score_wer.py --language igbo | |
| Needs: pip install jiwer pandas | |
| """ | |
| import argparse | |
| import os | |
| import re | |
| import pandas as pd | |
| from jiwer import process_words, process_characters | |
| from _common import AUDIO_DIR, RESULTS_DIR, GROUND_TRUTH_CSV | |
| ENGINES = ["sahara", "natlas", "mms"] | |
| def normalize(text): | |
| """Lowercase, strip punctuation, collapse whitespace. Applied identically | |
| to ground truth and every engine's output so scoring is apples-to-apples.""" | |
| text = str(text or "").lower() | |
| text = re.sub(r"[^\w\s]", " ", text) | |
| text = re.sub(r"\s+", " ", text).strip() | |
| return text | |
| def score_clip(reference, hypothesis): | |
| """Return a dict of metrics for one clip. Handles empty hypothesis | |
| (transcript loss) without crashing jiwer.""" | |
| ref_norm = normalize(reference) | |
| hyp_norm = normalize(hypothesis) | |
| if not hyp_norm: | |
| # Total failure — no output at all. WER is technically 1.0 (100% | |
| # deletions) but we track this separately as "transcript loss" too, | |
| # since it's a distinct failure mode from partial errors. | |
| word_count = len(ref_norm.split()) or 1 | |
| return { | |
| "wer": 1.0, | |
| "cer": 1.0, | |
| "insertions": 0, | |
| "deletions": word_count, | |
| "substitutions": 0, | |
| "transcript_lost": True, | |
| } | |
| word_result = process_words(ref_norm, hyp_norm) | |
| char_result = process_characters(ref_norm, hyp_norm) | |
| return { | |
| "wer": word_result.wer, | |
| "cer": char_result.cer, | |
| "insertions": word_result.insertions, | |
| "deletions": word_result.deletions, | |
| "substitutions": word_result.substitutions, | |
| "transcript_lost": False, | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--language", default="igbo") | |
| args = parser.parse_args() | |
| if not os.path.exists(GROUND_TRUTH_CSV): | |
| raise SystemExit(f"[STOP] {GROUND_TRUTH_CSV} not found. Run prepare_data.py first.") | |
| gt = pd.read_csv(GROUND_TRUTH_CSV) | |
| gt = gt[gt["language"] == args.language].set_index("clip_id") | |
| if gt.empty: | |
| raise SystemExit(f"[STOP] No ground truth rows for language '{args.language}'.") | |
| print(f"[info] Scoring against {len(gt)} ground-truth clips for '{args.language}'\n") | |
| per_clip_rows = [] | |
| summary_rows = [] | |
| for engine in ENGINES: | |
| path = os.path.join(RESULTS_DIR, f"{engine}.csv") | |
| if not os.path.exists(path): | |
| print(f"[warn] {engine}: results/{engine}.csv not found — skipping") | |
| continue | |
| df = pd.read_csv(path).set_index("clip_id") | |
| matched = 0 | |
| wers, cers = [], [] | |
| total_ins, total_del, total_sub = 0, 0, 0 | |
| lost = 0 | |
| for clip_id, gt_row in gt.iterrows(): | |
| if clip_id not in df.index: | |
| print(f"[warn] {engine}: missing clip '{clip_id}' — skipped") | |
| continue | |
| hyp = df.loc[clip_id, "transcript"] | |
| metrics = score_clip(gt_row["transcript"], hyp) | |
| per_clip_rows.append({ | |
| "clip_id": clip_id, | |
| "engine": engine, | |
| "wer": round(metrics["wer"], 4), | |
| "cer": round(metrics["cer"], 4), | |
| "insertions": metrics["insertions"], | |
| "deletions": metrics["deletions"], | |
| "substitutions": metrics["substitutions"], | |
| "transcript_lost": metrics["transcript_lost"], | |
| }) | |
| matched += 1 | |
| wers.append(metrics["wer"]) | |
| cers.append(metrics["cer"]) | |
| total_ins += metrics["insertions"] | |
| total_del += metrics["deletions"] | |
| total_sub += metrics["substitutions"] | |
| if metrics["transcript_lost"]: | |
| lost += 1 | |
| if matched == 0: | |
| continue | |
| mean_wer = sum(wers) / matched | |
| mean_cer = sum(cers) / matched | |
| summary_rows.append({ | |
| "engine": engine, | |
| "clips_scored": matched, | |
| "mean_wer": round(mean_wer, 4), | |
| "mean_cer": round(mean_cer, 4), | |
| "accuracy": round(1 - mean_wer, 4), | |
| "insertions_total": total_ins, | |
| "deletions_total": total_del, | |
| "substitutions_total": total_sub, | |
| "transcript_loss_rate": round(lost / matched, 4), | |
| }) | |
| print(f"[{engine}] {matched} clips scored — " | |
| f"WER {mean_wer:.2%} CER {mean_cer:.2%} " | |
| f"transcript loss {lost}/{matched}") | |
| per_clip_df = pd.DataFrame(per_clip_rows) | |
| summary_df = pd.DataFrame(summary_rows).sort_values("mean_wer") | |
| per_clip_path = os.path.join(RESULTS_DIR, "wer_scores.csv") | |
| summary_path = os.path.join(RESULTS_DIR, "wer_summary.csv") | |
| per_clip_df.to_csv(per_clip_path, index=False) | |
| summary_df.to_csv(summary_path, index=False) | |
| print(f"\n[done] Wrote per-clip scores to {per_clip_path}") | |
| print(f"[done] Wrote engine summary to {summary_path}\n") | |
| print(summary_df.to_string(index=False)) | |
| if __name__ == "__main__": | |
| main() |