| from __future__ import annotations |
| import argparse |
| import ast |
| import csv |
| import json |
| from pathlib import Path |
| from sklearn.metrics import f1_score, precision_score, recall_score |
|
|
|
|
| def read_rows(path): |
| with open(path, encoding="utf-8", newline="") as f: |
| return list(csv.DictReader(f)) |
|
|
|
|
| def parse_boundary_prediction(value, word): |
| value = value.strip() |
| if value.startswith("["): |
| parsed = json.loads(value) |
| return [int(x) for x in parsed] |
| if "-" in value: |
| syllables = value.split("-") |
| if "".join(syllables) != word: |
| raise ValueError(f"Segmentation does not reconstruct word {word!r}: {value!r}") |
| labels = [0] * (len(word) - 1) |
| cursor = 0 |
| for syllable in syllables[:-1]: |
| cursor += len(syllable) |
| labels[cursor - 1] = 1 |
| return labels |
| try: |
| parsed = ast.literal_eval(value) |
| return [int(x) for x in parsed] |
| except Exception as exc: |
| raise ValueError(f"Invalid boundary prediction for {word!r}: {value!r}") from exc |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--gold", required=True) |
| parser.add_argument("--predictions", required=True) |
| parser.add_argument("--output") |
| args = parser.parse_args() |
| gold_rows = read_rows(args.gold) |
| pred_rows = read_rows(args.predictions) |
| if not pred_rows or not {"id", "prediction"}.issubset(pred_rows[0]): |
| raise ValueError("Prediction CSV must contain columns: id,prediction") |
| preds = {row["id"]: row["prediction"] for row in pred_rows} |
| y_true, y_pred = [], [] |
| exact = 0 |
| for row in gold_rows: |
| if row["id"] not in preds: |
| raise ValueError(f"Missing prediction for {row['id']}") |
| gold = [int(x) for x in json.loads(row["boundary_labels"])] |
| pred = parse_boundary_prediction(preds[row["id"]], row["word"]) |
| if len(pred) != len(gold): |
| raise ValueError(f"Boundary length mismatch for {row['id']}: {len(pred)} != {len(gold)}") |
| y_true.extend(gold) |
| y_pred.extend(pred) |
| exact += int(gold == pred) |
| metrics = { |
| "n_examples": len(gold_rows), |
| "boundary_precision": precision_score(y_true, y_pred, zero_division=0), |
| "boundary_recall": recall_score(y_true, y_pred, zero_division=0), |
| "boundary_f1": f1_score(y_true, y_pred, zero_division=0), |
| "exact_match": exact / len(gold_rows), |
| } |
| text = json.dumps(metrics, ensure_ascii=False, indent=2) |
| print(text) |
| if args.output: |
| Path(args.output).write_text(text + "\n", encoding="utf-8") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|