File size: 10,320 Bytes
0041cfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#!/usr/bin/env python3
"""Score hypotheses from run_benchmark.py against the benchmark annotations.

    python score_benchmark.py --hyps runs/deepgram_nova3.jsonl

Reports span-level entity accuracy (the headline metric), a per-type and
per-subset breakdown, and WER. Writes a per-span hits CSV so two runs can be
diffed clip by clip instead of argued about as a single percentage.
"""

from __future__ import annotations

import argparse
import csv
import json
import os
import sys
from collections import defaultdict
from datetime import datetime, timezone

import common
import matcher_adapter


def parse_args(argv=None):
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--hyps", required=True, help="JSONL produced by run_benchmark.py")
    p.add_argument("--out-prefix", default=None, help="default: alongside --hyps")

    p.add_argument("--dataset", default=common.DEFAULT_DATASET)
    p.add_argument("--split", default=common.DEFAULT_SPLIT)
    p.add_argument("--revision", default=None)
    p.add_argument("--local-path", default=None)
    p.add_argument("--tier", default="A",
                   help="entity spans of this tier are scored ('A' is the published protocol; "
                        "'all' scores every span). WER always uses every scored clip.")

    p.add_argument("--matcher", default=None, help="module:callable override")
    p.add_argument("--matcher-path", default=None, help="path to matcher_v5.py")
    p.add_argument("--wer-normalizer", default="basic", choices=["basic", "whisper_english", "none"])
    p.add_argument("--no-wer", action="store_true")
    p.add_argument("--compare", default=None, help="another hits CSV to diff against")

    for field in common.CANDIDATES:
        p.add_argument(f"--{field.replace('_', '-')}-column", dest=f"{field}_column", default=None)
    return p.parse_args(argv)


def read_manifest(hyps_path: str) -> dict:
    path = os.path.splitext(hyps_path)[0] + ".manifest.json"
    if os.path.exists(path):
        with open(path) as fh:
            return json.load(fh)
    return {}


def read_hyps(path: str) -> tuple[dict[str, str], int]:
    table: dict[str, str] = {}
    failed = 0
    with open(path) as fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            record = json.loads(line)
            if record.get("hypothesis") is None:
                failed += 1
                continue
            table[record["clip_id"]] = record["hypothesis"]
    return table, failed


def percent(hits: int, total: int) -> str:
    return f"{100.0 * hits / total:.1f}%" if total else "n/a"


def main(argv=None) -> int:
    args = parse_args(argv)
    manifest = read_manifest(args.hyps)

    tier = args.tier or "A"
    revision = args.revision or manifest.get("revision")
    dataset = args.dataset
    local_path = args.local_path
    if not local_path and str(manifest.get("dataset", "")).startswith("local:"):
        local_path = manifest["dataset"].split("local:", 1)[1]
    elif manifest.get("dataset") and args.dataset == common.DEFAULT_DATASET:
        dataset = manifest["dataset"]

    matcher, matcher_desc = matcher_adapter.load_matcher(args.matcher, args.matcher_path)
    common.eprint(f"Matcher: {matcher_desc}")
    passed, total_tests = matcher_adapter.self_test(args.matcher_path)
    if total_tests:
        common.eprint(f"Matcher self-test: {passed}/{total_tests}")
        if passed != total_tests:
            common.eprint("! self-test failing -- numbers from this run are not comparable")
            return 2

    hyps, failed = read_hyps(args.hyps)
    common.eprint(f"Hypotheses: {len(hyps)} usable, {failed} failed")

    ds = common.load_bench(dataset, args.split, revision, local_path)
    overrides = {f: getattr(args, f"{f}_column") for f in common.CANDIDATES}
    schema = common.resolve_schema(ds.column_names, overrides)
    ds = common.undecode_audio(ds, schema)  # ids only; never decode audio to score
    want_tier = None if not tier or tier.lower() == "all" else tier.strip().upper()

    rows: list[dict] = []
    by_type: dict[str, list[int]] = defaultdict(lambda: [0, 0])
    by_subset: dict[str, list[int]] = defaultdict(lambda: [0, 0])
    hits = spans = 0
    missing_clips = 0
    refs: list[str] = []
    preds: list[str] = []

    for index, row in enumerate(ds):
        clip = common.row_id(row, schema, index)
        if clip not in hyps:
            missing_clips += 1
            continue
        hypothesis = hyps[clip]
        entities = common.parse_list_field(row[schema.entities])
        types = common.parse_list_field(row[schema.entity_types]) if schema.entity_types else []
        subset = str(row[schema.subset]) if schema.subset else ""

        if schema.reference and not args.no_wer:
            refs.append(str(row[schema.reference]))
            preds.append(hypothesis)

        tiers = common.span_tiers(row, schema, len(entities))
        for position, entity in enumerate(entities):
            if want_tier is not None and tiers[position] != want_tier:
                continue
            etype = types[position] if position < len(types) else "UNKNOWN"
            hit = bool(matcher(entity, hypothesis))
            spans += 1
            hits += hit
            by_type[etype][0] += hit
            by_type[etype][1] += 1
            if subset:
                by_subset[subset][0] += hit
                by_subset[subset][1] += 1
            rows.append({
                "clip_id": clip,
                "entity": entity,
                "entity_type": etype,
                "subset": subset,
                "tier": tiers[position],
                "hit": int(hit),
                "hypothesis": hypothesis,
            })

    if missing_clips:
        common.eprint(f"! {missing_clips} clips in the tier had no hypothesis -- run is incomplete")

    wer = None
    if refs and not args.no_wer:
        import jiwer

        normalize = common.get_normalizer(args.wer_normalizer)
        pairs = [(normalize(r), normalize(p)) for r, p in zip(refs, preds)]
        pairs = [(r, p) for r, p in pairs if r]
        if pairs:
            wer = jiwer.wer([r for r, _ in pairs], [p for _, p in pairs])

    prefix = args.out_prefix or os.path.splitext(args.hyps)[0]
    hits_csv = f"{prefix}.hits.csv"
    with open(hits_csv, "w", newline="") as fh:
        writer = csv.DictWriter(
            fh, fieldnames=["clip_id", "entity", "entity_type", "subset", "tier", "hit", "hypothesis"])
        writer.writeheader()
        writer.writerows(rows)

    summary = {
        "scored_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "dataset": dataset if not local_path else f"local:{local_path}",
        "revision": revision,
        "tier": tier,
        "wer_scope": "all clips with a hypothesis (tier filter applies to entity spans only)",
        "system_name": manifest.get("system_name") or manifest.get("provider"),
        "provider": manifest.get("provider"),
        "provider_opts": manifest.get("provider_opts"),
        "matcher": matcher_desc,
        "matcher_self_test": f"{passed}/{total_tests}" if total_tests else "not exposed",
        "wer_normalizer": None if args.no_wer else args.wer_normalizer,
        "clips_scored": len({r["clip_id"] for r in rows}),
        "clips_with_hypothesis": len(hyps),
        "clips_missing": missing_clips,
        "clips_failed": failed,
        "entity_spans": spans,
        "entity_hits": hits,
        "entity_accuracy": round(hits / spans, 4) if spans else None,
        "wer": round(wer, 4) if wer is not None else None,
        "by_type": {k: {"hits": v[0], "spans": v[1], "accuracy": round(v[0] / v[1], 4)} for k, v in sorted(by_type.items())},
        "by_subset": {k: {"hits": v[0], "spans": v[1], "accuracy": round(v[0] / v[1], 4)} for k, v in sorted(by_subset.items())},
    }
    summary_path = f"{prefix}.summary.json"
    with open(summary_path, "w") as fh:
        json.dump(summary, fh, indent=2)

    print()
    print(f"Entity Transcription Benchmark -- entity spans: tier {tier}")
    print(f"  system          {summary['system_name'] or '?'}")
    print(f"  transport       {manifest.get('provider', '?')} {manifest.get('provider_opts', '')}")
    print(f"  clips w/ spans  {summary['clips_scored']} of {len(hyps)} transcribed")
    print(f"  entity accuracy {percent(hits, spans)}  ({hits}/{spans} spans)")
    if wer is not None:
        print(f"  WER             {100 * wer:.2f}%  (normalizer: {args.wer_normalizer})")
    print()
    print(f"  {'type':<16}{'acc':>8}{'spans':>9}")
    for etype, (h, t) in sorted(by_type.items(), key=lambda kv: -kv[1][1]):
        print(f"  {etype:<16}{percent(h, t):>8}{t:>9}")
    if by_subset:
        print()
        print(f"  {'subset':<16}{'acc':>8}{'spans':>9}")
        for name, (h, t) in sorted(by_subset.items(), key=lambda kv: -kv[1][1]):
            print(f"  {name:<16}{percent(h, t):>8}{t:>9}")

    if args.compare:
        diff_path = f"{prefix}.diff.csv"
        compare(rows, args.compare, diff_path)

    print()
    print(f"Per-span hits: {hits_csv}")
    print(f"Summary:       {summary_path}")
    return 0


def compare(rows: list[dict], other_path: str, out_path: str) -> None:
    key = lambda r: (r["clip_id"], r["entity"])  # noqa: E731
    mine = {key(r): int(r["hit"]) for r in rows}
    with open(other_path) as fh:
        theirs = {key(r): int(r["hit"]) for r in csv.DictReader(fh)}

    shared = sorted(set(mine) & set(theirs))
    disagree = [k for k in shared if mine[k] != theirs[k]]
    with open(out_path, "w", newline="") as fh:
        writer = csv.writer(fh)
        writer.writerow(["clip_id", "entity", "this_run", "reference_run"])
        for k in disagree:
            writer.writerow([k[0], k[1], mine[k], theirs[k]])

    print()
    print(f"  compared against {os.path.basename(other_path)}")
    print(f"    shared spans   {len(shared)}")
    print(f"    disagreements  {len(disagree)} ({percent(len(disagree), len(shared))})")
    print(f"    only here      {len(set(mine) - set(theirs))}")
    print(f"    only reference {len(set(theirs) - set(mine))}")
    print(f"  diff: {out_path}")


if __name__ == "__main__":
    sys.exit(main())