File size: 3,301 Bytes
df7317f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Helpers of scripts/add_system.sh (standard library only; counts and rates are printed, no item text).

  add_system_helpers.py summary   VERDICTS.summary.json
  add_system_helpers.py published RESULTS_DIR OUT_DIR KEY REFERENCE      (prints the `nanori-eval score` arguments)
  add_system_helpers.py check     PUBLISHED_LEADERBOARD NEW_LEADERBOARD KEY
"""
import json
import os
import sys


def summary(path):
    s = json.load(open(path))
    print('add_system: combine', s['rows'], 'rows;', json.dumps(s['sets'], sort_keys=True), '; missing judge rows',
          json.dumps(s['missing_judge_rows'], sort_keys=True))


def as_combined(r):
    """A published per-item row as a combined verdict row (rule R2 with the G, KW and CTC verdicts beside it)."""
    return {'set': r['subset'], 'item_id': r['id'], 'k': 0, 'rule': 'R2', 'verdict': r['verdict_R2'],
            'decided_by': r['decided_by_R2'], 'gemini': {'verdict': r['verdict_gemini']},
            'kw': {'verdict': r['verdict_kana_whisper']}, 'ctc': {'verdict': r['verdict_kana_ctc']}}


def published(res, out, key, ref):
    lb = json.load(open(os.path.join(res, 'leaderboard.json')))
    if ref not in lb['systems']:
        raise SystemExit(f'add_system: --reference {ref} is not a published system')
    os.makedirs(out, exist_ok=True)
    args = []
    # a system re-added under the same key is scored from the new run only
    for sy in [s for s in lb['systems'] if s != key]:
        p = os.path.join(out, f'{sy}.verdicts.jsonl')
        with open(os.path.join(res, 'per_item', f'{sy}.jsonl'), encoding='utf-8') as f:
            rows = [as_combined(json.loads(l)) for l in f if l.strip()]
        with open(p, 'w', encoding='utf-8') as g:
            g.writelines(json.dumps(r) + '\n' for r in rows)
        args += ['--system', f'{sy}:{lb["system_labels"][sy]}={p}']
    pairs = [p.replace(' - ', ':') for p in lb['pairs'] if key not in p.split(' - ')] + [f'{key}:{ref}']
    print('\n'.join(args + ['--pairs', ','.join(pairs)]))


def check(pub_path, new_path, key):
    pub, new = json.load(open(pub_path)), json.load(open(new_path))
    n = bad = 0
    for s, S in pub['subsets'].items():
        for cid, Cc in S['cells'].items():
            for j, J in Cc['judges'].items():
                N = new['subsets'][s]['cells'][cid]['judges'][j]
                same = [N['systems'][sy] == b for sy, b in J['systems'].items() if sy != key]
                same += [N['pairs'][p] == b for p, b in J['pairs'].items() if key not in p.split(' - ')]
                n, bad = n + len(same), bad + same.count(False)
    print(f'add_system: published blocks compared {n}, differing {bad}')
    if bad:
        raise SystemExit('add_system: the published numbers changed: check --dataset-dir and the per-item files')
    for s, S in new['subsets'].items():
        for cid in ('headline_weighted', 'main_unweighted', 'D-E', 'D-N', 'all_150', 'hard'):
            if cid in S['cells']:
                b = S['cells'][cid]['judges']['R2']['systems'][key]
                print(f'add_system: {key} {s} {cid} R2 {b["rate"]} (scored {b["n_scored"]} of {b["n_items"]})')


if __name__ == '__main__':
    cmd, rest = sys.argv[1], sys.argv[2:]
    {'summary': summary, 'published': published, 'check': check}[cmd](*rest)