File size: 5,284 Bytes
a5bbc9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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()