| import argparse |
| import csv |
| from collections import defaultdict |
| from pathlib import Path |
|
|
| import jiwer |
| from tabulate import tabulate |
|
|
|
|
| DEFAULT_GOLD = Path("data/gold.tsv") |
| DEFAULT_PREDICTIONS = Path("data/predictions.tsv") |
| PHONEME_CHARS = set("abdefhijklmnopstuvwzɡʁʃʒʔˈχ") |
| PHONEME_TRANSLATION = str.maketrans({"x": "χ", "r": "ʁ", "g": "ɡ"}) |
|
|
|
|
| def normalize_phonemes(text): |
| text = text.translate(PHONEME_TRANSLATION) |
| return "".join(char for char in text if char in PHONEME_CHARS) |
|
|
|
|
| def read_tsv(path): |
| if not path.exists() or path.stat().st_size == 0: |
| return [] |
| with path.open("r", encoding="utf-8-sig", newline="") as f: |
| return list(csv.DictReader(f, delimiter="\t")) |
|
|
|
|
| def read_predictions(path): |
| if not path.exists() or path.stat().st_size == 0: |
| return [] |
| with path.open("r", encoding="utf-8-sig", newline="") as f: |
| return list(csv.DictReader(f, delimiter="\t")) |
|
|
|
|
| def read_predictions_header(path): |
| if not path.exists() or path.stat().st_size == 0: |
| return [] |
| with path.open("r", encoding="utf-8-sig", newline="") as f: |
| return next(csv.reader(f, delimiter="\t"), []) |
|
|
|
|
| def parse_label(label): |
| """Parse labels like: 1=ʔelˈajiχ 4=kibˈalt.""" |
| targets = {} |
| for part in label.split(): |
| if "=" not in part: |
| continue |
| index, ipa = part.split("=", 1) |
| targets[int(index)] = normalize_phonemes(ipa) |
| return targets |
|
|
|
|
| def prediction_targets(prediction): |
| """Allow either full token output or target-only index=IPA predictions.""" |
| if all("=" in part for part in prediction.split() if part): |
| return parse_label(prediction) |
| return None |
|
|
|
|
| def get_prediction_rows(gold_rows, pred_rows): |
| if not pred_rows: |
| raise ValueError("Predictions file is empty. Run a plan script first.") |
|
|
| if len(pred_rows) != len(gold_rows): |
| raise ValueError( |
| "Predictions must have the same number of rows " |
| f"as gold: got {len(pred_rows)}, expected {len(gold_rows)}." |
| ) |
| return pred_rows |
|
|
|
|
| def target_prediction(row, pred_text): |
| targets = parse_label(row["Label"]) |
| indexed_pred = prediction_targets(pred_text) |
|
|
| if indexed_pred is not None: |
| return " ".join(indexed_pred.get(i, "") for i in targets) |
|
|
| pred_tokens = pred_text.split() |
| return " ".join(normalize_phonemes(pred_tokens[i]) if i < len(pred_tokens) else "" for i in targets) |
|
|
|
|
| def score_rows(gold_rows, pred_rows, pred_col): |
| by_category = defaultdict(lambda: {"refs": [], "hyps": [], "exact": []}) |
| all_refs = [] |
| all_hyps = [] |
| all_exact = [] |
|
|
| for gold, pred in zip(gold_rows, get_prediction_rows(gold_rows, pred_rows)): |
| ref = " ".join(parse_label(gold["Label"]).values()) |
| hyp = target_prediction(gold, pred.get(pred_col, "")) |
| exact = int(ref == hyp) |
|
|
| all_refs.append(ref) |
| all_hyps.append(hyp) |
| all_exact.append(exact) |
|
|
| bucket = by_category[gold["Category"]] |
| bucket["refs"].append(ref) |
| bucket["hyps"].append(hyp) |
| bucket["exact"].append(exact) |
|
|
| return all_refs, all_hyps, all_exact, by_category |
|
|
|
|
| def summarize(name, refs, hyps, exact): |
| return { |
| "Category": name, |
| "Items": len(refs), |
| "WER": jiwer.wer(refs, hyps), |
| "CER": jiwer.cer(refs, hyps), |
| "Exact": sum(exact) / len(exact) if exact else 0.0, |
| } |
|
|
|
|
| def prediction_columns(predictions_path, requested): |
| if requested: |
| return requested |
|
|
| header = read_predictions_header(predictions_path) |
| columns = header |
| if not columns: |
| raise ValueError( |
| "No prediction columns found. Expected data/predictions.tsv with " |
| "one or more G2P columns." |
| ) |
| return columns |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Evaluate MILIM-Bench G2P predictions.") |
| parser.add_argument("predictions", type=Path, nargs="?", default=DEFAULT_PREDICTIONS) |
| parser.add_argument("--gold", type=Path, default=DEFAULT_GOLD) |
| parser.add_argument( |
| "--prediction-column", |
| action="append", |
| help="Prediction column to evaluate. May be passed more than once. Defaults to all non-Text columns.", |
| ) |
| args = parser.parse_args() |
|
|
| gold_rows = read_tsv(args.gold) |
| pred_rows = read_predictions(args.predictions) |
| columns = prediction_columns(args.predictions, args.prediction_column) |
| table = [] |
|
|
| for column in columns: |
| refs, hyps, exact, by_category = score_rows(gold_rows, pred_rows, column) |
| model_summary = [summarize("ALL", refs, hyps, exact)] |
| model_summary.extend( |
| summarize(category, data["refs"], data["hyps"], data["exact"]) |
| for category, data in sorted(by_category.items()) |
| ) |
|
|
| for row in model_summary: |
| table.append( |
| [ |
| column, |
| row["Category"], |
| row["Items"], |
| f"{1 - row['WER']:.4f}", |
| f"{1 - row['CER']:.4f}", |
| f"{row['Exact']:.4f}", |
| ] |
| ) |
|
|
| print(tabulate(table, headers=["model", "category", "items", "WER ↑", "CER ↑", "Exact ↑"])) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|