File size: 3,884 Bytes
b982e77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Aggregation, the printed table, and the files a scoring run leaves behind."""

from __future__ import annotations

import csv
import json
import statistics
from collections import OrderedDict
from pathlib import Path

import numpy as np

from .scorers import POLICIES

_AGG_KEYS = ("wer", "wer_strict", "wer_norm", "wer_robust", "ssim", "utmos",
             "excess_silence")


def aggregate(rows: list[dict]) -> dict:
    out: dict = {"n": len(rows)}
    for key in _AGG_KEYS:
        vals = [r[key] for r in rows
                if r.get(key) is not None
                and not (isinstance(r[key], float) and np.isnan(r[key]))]
        out[f"{key}_mean"] = float(statistics.mean(vals)) if vals else float("nan")
        out[f"{key}_median"] = float(statistics.median(vals)) if vals else float("nan")
    return out


def _group_by(rows: list[dict], key: str) -> "OrderedDict[str, dict]":
    buckets: "OrderedDict[str, list[dict]]" = OrderedDict()
    for r in rows:
        buckets.setdefault(str(r.get(key, "")), []).append(r)
    return OrderedDict((k, aggregate(v)) for k, v in sorted(buckets.items()))


def format_report(title: str, groups: "dict[str, dict]") -> str:
    """Fixed-width table; one row per group, all three WER policies side by side."""
    w = 118
    lines = ["=" * w, title, "=" * w,
             f"{'group':<22}{'n':>5}{'WER strict':>15}{'WER norm':>15}"
             f"{'WER robust':>15}{'SSIM':>15}{'UTMOS':>15}{'EXCESS-SIL s':>15}",
             f"{'':<22}{'':>5}" + "".join(f"{'mean/median':>15}" for _ in range(6))]
    for name, s in groups.items():
        lines.append(
            f"{name:<22}{s['n']:>5}"
            + "".join(f"{s[f'wer_{p}_mean']:>7.4f}/{s[f'wer_{p}_median']:<7.4f}"
                      for p in POLICIES)
            + f"{s['ssim_mean']:>7.4f}/{s['ssim_median']:<7.4f}"
              f"{s['utmos_mean']:>7.4f}/{s['utmos_median']:<7.4f}"
              f"{s['excess_silence_mean']:>7.4f}/{s['excess_silence_median']:<7.4f}")
    lines.append("=" * w)
    return "\n".join(lines)


def group_report(name: str, rows: list[dict]) -> str:
    return "\n".join([
        format_report(f"ZeroBench-TTS — {name}",
                      {**_group_by(rows, "subset"), "── overall ──": aggregate(rows)}),
        format_report("by length bucket", _group_by(rows, "length_bucket")),
        format_report("by voice source", _group_by(rows, "voice_source")),
    ])


def write_outputs(out_dir: Path, name: str, results: list[dict],
                  all_rows: list[dict], args) -> dict:
    """per_sample.csv + summary.json + report.txt. Returns the summary."""
    out_dir.mkdir(parents=True, exist_ok=True)

    with (out_dir / "per_sample.csv").open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(results[0].keys()))
        writer.writeheader()
        writer.writerows(results)

    summary = {
        "system": name,
        "benchmark": "zeroweight-ai/ZeroBench-TTS",
        "n_items": len(all_rows),
        "n_scored": len(results),
        "complete": len(results) == len(all_rows),
        "asr_models": list(getattr(args, "asr", None) or
                           ("openai/whisper-large-v3", "vinai/PhoWhisper-large")),
        "wer_policies": list(POLICIES),
        "headline_wer_policy": "robust",
        "utmos_scored": not getattr(args, "skip_utmos", False),
        "overall": aggregate(results),
        "by_subset": _group_by(results, "subset"),
        "by_length_bucket": _group_by(results, "length_bucket"),
        "by_voice_source": _group_by(results, "voice_source"),
    }
    (out_dir / "summary.json").write_text(
        json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
    (out_dir / "report.txt").write_text(group_report(name, results) + "\n",
                                        encoding="utf-8")
    return summary