"""One-command API evaluation campaign: prepare items, run every model of a plan, merge top-effort fallbacks, report. # 1. items: clips for cropped views, export, Gemini copy with re-encoded recordings (HTTP 413 limit) python3 tools/evaluation/campaign.py prepare --out runs/eval- \\ --questions /vout/*/groups.jsonl --videos --scripts /segs \\ [--sample-per-version N --seed S | --items-from ] # 2. models (keys from the environment, e.g. `source eval-keys.sh`); safe to re-run, every run resumes python3 tools/evaluation/campaign.py run --dir runs/eval- [--plan campaigns/api-final.json] [--only a,b] # 3. report.md: overall, choice/fill x single/multi, per version, two-stage packets (G0/G1) python3 tools/evaluation/campaign.py report --dir runs/eval- A plan (``campaigns/*.json``, schema eval-campaign/1) lists models with an endpoint name, a settings preset, workers, the item variant (``frames`` default or ``gemini``) and optionally a ``fallback`` endpoint: such a model runs its top effort and the fallback effort side by side, and the merged run keeps the top-effort answer unless the gateway cut it (HTTP 504 / timed out after its retries), where the fallback answer is used (``effort_used``/``fallback_from`` per record, counts in merge.json). Other top-effort errors stay errors. The merged run is scored under the model's name. Models carry a ``batch`` number: batches run one after another, the passes of one batch side by side (11-11: aigw banned the account when nine models ran at once at 24 workers each). Every pass stops after 5 answers refused with HTTP 401/403 (banned key or account) instead of sending the rest; a batch with such a pass aborts the campaign (exit 3, later batches not started, nothing merged or scored). Top-effort passes keep their gateway cuts on resume (they already used their tries). ``run --batch N`` runs one batch; re-running resumes. Layout of the campaign dir: items/ (np_export: items.jsonl, truth.jsonl), clips-src/, gemini-items/, plan.json (copy of the plan used), runs/[.top|.fallback]/ (runner dirs), runs// (scored final run), driver.log, report.md. """ import argparse import collections import concurrent.futures import hashlib import json import os import random import re import shutil import subprocess import sys import time from pathlib import Path HERE = Path(__file__).resolve().parent PY = sys.executable FFMPEG = '/usr/bin/ffmpeg' if Path('/usr/bin/ffmpeg').exists() else 'ffmpeg' GEMINI_ARGS = ['-an', '-c:v', 'libx264', '-preset', 'medium', '-crf', '30', '-maxrate', '600k', '-bufsize', '1200k', '-pix_fmt', 'yuv420p', '-r', '20', '-color_range', 'tv', '-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'iec61966-2-1', '-movflags', '+faststart', '-threads', '2'] def jl(path): return [json.loads(l) for l in open(path, encoding='utf-8') if l.strip()] def log(cdir, msg): line = f'{time.strftime("%m-%d %H:%M:%S")} {msg}' print(line, flush=True) with open(Path(cdir) / 'driver.log', 'a', encoding='utf-8') as fh: fh.write(line + '\n') # ---------------------------------------------------------------- prepare def sample_args(a): if a.sample_per_version: return ['--sample-per-version', str(a.sample_per_version), '--seed', str(a.seed)] if a.items_from: return ['--items-from', str(a.items_from)] return [] def frames_of(path): sys.path.insert(0, str(HERE)) import media info = media.probe(path) return info['frame_count'] if info['frame_count'] is not None else round(info['duration_s'] * info['fps']) def gemini_copy(items_dir, out, jobs): """Copy of items/ whose recordings are re-encoded (same frames, CRF 30, maxrate 600k): aigw refuses Gemini requests with large inline video (HTTP 413 above ~40-60 MB per item).""" items = jl(items_dir / 'items.jsonl') paths = sorted({v['path'] for it in items for v in it['videos']}) if not paths: return None def target(p): p = Path(p) return out / 'media' / hashlib.sha1(str(p.resolve()).encode()).hexdigest()[:10] / p.name def encode(p): src = (items_dir / p).resolve() dst = target(p) want = frames_of(src) if dst.exists() and frames_of(dst) == want: return p, dst dst.parent.mkdir(parents=True, exist_ok=True) tmp = dst.with_name(dst.name + '.part.mp4') subprocess.run([FFMPEG, '-nostdin', '-v', 'error', '-y', '-i', str(src), *GEMINI_ARGS, str(tmp)], check=True, capture_output=True) if frames_of(tmp) != want: tmp.unlink() raise RuntimeError(f'{src}: re-encode changed the frame count') tmp.replace(dst) return p, dst with concurrent.futures.ThreadPoolExecutor(jobs) as ex: done = dict(ex.map(encode, paths)) out.mkdir(parents=True, exist_ok=True) with open(out / 'items.jsonl', 'w', encoding='utf-8') as fh: for it in items: for v in it['videos']: v['path'] = str(done[v['path']]) for im in it.get('images') or []: im['path'] = str((items_dir / im['path']).resolve()) fh.write(json.dumps(it, ensure_ascii=False) + '\n') size = sorted(sum(Path(v['path']).stat().st_size for v in it['videos']) for it in jl(out / 'items.jsonl')) meta = {'source': str(items_dir), 'ffmpeg_args': GEMINI_ARGS, 'videos': len(done), 'item_mb_max': round(size[-1] / 1e6, 1), 'item_mb_median': round(size[len(size) // 2] / 1e6, 1)} (out / 'reencode.json').write_text(json.dumps(meta, indent=1)) return meta def prepare(a): cdir = Path(a.out) cdir.mkdir(parents=True, exist_ok=True) items = cdir / 'items' if (items / 'items.jsonl').exists(): raise SystemExit(f'{items} already exported; use a new --out for a new item set') common = ['--questions', *a.questions, *sample_args(a)] if a.videos: log(cdir, 'cut clips for cropped recording views') subprocess.run([PY, '-B', str(HERE / 'cut_clips.py'), *common, '--videos', a.videos, '--out', str(cdir / 'clips-src'), '--jobs', str(a.jobs)], check=True) log(cdir, 'export items') cmd = [PY, '-B', str(HERE / 'np_export.py'), *common, '--out', str(items)] if a.videos: cmd += ['--videos', a.videos, '--clips', str(cdir / 'clips-src' / 'clips' / 'index.json')] if a.scripts: cmd += ['--scripts', a.scripts] subprocess.run(cmd, check=True) if a.videos and not a.no_gemini: log(cdir, 'Gemini copy with re-encoded recordings') meta = gemini_copy(items, cdir / 'gemini-items', a.jobs) log(cdir, f'gemini-items: {json.dumps(meta)}') exp = json.loads((items / 'export.json').read_text()) log(cdir, f"prepared {exp.get('items')} items, {exp.get('without_video', 0)} without video") # ---------------------------------------------------------------- run def load_plan(path): plan = json.loads(Path(path).read_text(encoding='utf-8')) if plan.get('schema') != 'eval-campaign/1': raise SystemExit(f'{path}: not an eval-campaign/1 plan') ep = Path(plan['endpoints']) plan['endpoints'] = str(ep if ep.is_absolute() else (Path(path).parent / ep).resolve()) return plan def check_keys(plan, models): table = json.loads(Path(plan['endpoints']).read_text())['endpoints'] missing = set() for m in models: for name in [m['endpoint']] + ([m['fallback']['endpoint']] if m.get('fallback') else []): if name not in table: raise SystemExit(f'endpoint {name} not in {plan["endpoints"]}') env = table[name].get('api_key_env') for e in ([env] if isinstance(env, str) else env or []): if not os.environ.get(e): missing.add(e) if missing: raise SystemExit(f'API keys not in the environment: {", ".join(sorted(missing))} (source your keys file)') STOP_AFTER_DENIED = 5 # a banned key/account answers 401/403: stop that pass instead of burning every item CUT = r'HTTP 504|timed out|Gateway Time-out' # gateway cuts; a top-effort pass does not retry them on resume def runner(cdir, out, endpoint, settings, items, workers, plan, keep_errors=None): """One runner pass (resumes: items already OK in out/responses.jsonl are skipped). Returns (rc, last line); rc 3 = stopped because answers were refused with HTTP 401/403.""" out.parent.mkdir(parents=True, exist_ok=True) logf = out.parent / (out.name + '.log') # not with_suffix: model names hold dots (gpt-6.1-sol) cmd = [PY, '-B', str(HERE / 'runner.py'), 'run', '--items', str(items), '--endpoint', plan['endpoints'], '--name', endpoint, '--settings', json.dumps(settings), '--out', str(out), '--workers', str(workers), '--stop-after-denied', str(STOP_AFTER_DENIED)] if keep_errors: cmd += ['--keep-errors', keep_errors] with open(logf, 'a', encoding='utf-8') as fh: rc = subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT).returncode tail = logf.read_text(encoding='utf-8').strip().splitlines()[-1:] return rc, (tail[0] if tail else '') def latest(path): rows = {} for r in jl(path): if r['item_id'] not in rows or r['status'] == 'OK' or rows[r['item_id']]['status'] != 'OK': rows[r['item_id']] = r return rows def cut(r): e = r.get('error') or '' return r['status'] != 'OK' and ('HTTP 504' in e or 'timed out' in e or 'Gateway Time-out' in e) def merge(top, low, out, top_effort, low_effort): """Final run = top-effort answers; items the gateway cut take the fallback-effort answer.""" T, L = latest(top / 'responses.jsonl'), latest(low / 'responses.jsonl') if out.exists(): shutil.rmtree(out) out.mkdir(parents=True) meta = json.loads((top / 'run.json').read_text()) meta['merge'] = {'top': str(top), 'fallback': str(low), 'top_effort': top_effort, 'fallback_effort': low_effort, 'rule': 'top effort; if the gateway cut it (504/timeout) after its retries, the fallback answer'} (out / 'run.json').write_text(json.dumps(meta, ensure_ascii=False, indent=2)) counts = dict(items=len(T), top_ok=0, fell_back=0, fallback_ok=0, other_errors=0) with open(out / 'responses.jsonl', 'w', encoding='utf-8') as fh: for iid, r in T.items(): if r['status'] == 'OK': rec = dict(r, effort_used=top_effort); counts['top_ok'] += 1 elif cut(r) and iid in L: rec = dict(L[iid], effort_used=low_effort, fallback_from=(r.get('error') or '')[:200]) counts['fell_back'] += 1; counts['fallback_ok'] += rec['status'] == 'OK' else: rec = dict(r, effort_used=top_effort); counts['other_errors'] += 1 fh.write(json.dumps(rec, ensure_ascii=False) + '\n') (out / 'merge.json').write_text(json.dumps(counts, indent=1)) return counts def score(run, truth): subprocess.run([PY, '-B', str(HERE / 'runner.py'), 'score', '--run', str(run), '--truth', str(truth)], check=True, capture_output=True) return json.loads((run / 'summary.json').read_text())['overall'] def run(a): cdir = Path(a.dir).resolve() plan_path = Path(a.plan) if a.plan else (cdir / 'plan.json' if (cdir / 'plan.json').exists() else HERE / 'campaigns' / 'api-final.json') plan = load_plan(plan_path) models = [m for m in plan['models'] if not a.only or m['name'] in a.only.split(',')] if a.only and len(models) != len(a.only.split(',')): raise SystemExit(f'--only names not in the plan: {set(a.only.split(",")) - {m["name"] for m in models}}') check_keys(plan, models) p = json.loads(Path(plan_path).read_text(encoding='utf-8')); p['endpoints'] = plan['endpoints'] (cdir / 'plan.json').write_text(json.dumps(p, ensure_ascii=False, indent=1)) # the plan this run used truth = cdir / 'items' / 'truth.jsonl' variants = {'frames': cdir / 'items' / 'items.jsonl', 'gemini': cdir / 'gemini-items' / 'items.jsonl'} runs = cdir / 'runs' def passes(m): items = variants[m.get('items', 'frames')] if not items.exists(): raise SystemExit(f'{m["name"]}: {items} missing (run prepare with --videos for the gemini variant)') settings = plan['settings'][m['settings']] if not m.get('fallback'): return [(m['name'], runs / m['name'], m['endpoint'], settings, items, m['workers'], None)] return [(m['name'] + '.top', runs / f"{m['name']}.top", m['endpoint'], settings, items, m['workers'], CUT), (m['name'] + '.fallback', runs / f"{m['name']}.fallback", m['fallback']['endpoint'], settings, items, m['workers'], None)] batches = sorted({m.get('batch', 1) for m in models}) if a.batch is not None: if a.batch not in batches: raise SystemExit(f'--batch {a.batch}: plan batches are {batches}') batches = [a.batch] rcs, done_models = {}, [] def one(job): name, out, endpoint, settings, items, workers, keep = job log(cdir, f'{name}: start ({endpoint}, {workers} workers)') rc, tail = runner(cdir, out, endpoint, settings, items, workers, plan, keep) log(cdir, f'{name}: rc={rc} {tail}') return name, rc for b in batches: group = [m for m in models if m.get('batch', 1) == b] jobs = [p for m in group for p in passes(m)] log(cdir, f'batch {b}: {len(group)} models / {len(jobs)} passes: {", ".join(j[0] for j in jobs)}') with concurrent.futures.ThreadPoolExecutor(len(jobs)) as ex: got = dict(ex.map(one, jobs)) rcs.update(got) if any(rc == 3 for rc in got.values()): denied = [n for n, rc in got.items() if rc == 3] log(cdir, f'ABORTED after batch {b}: answers refused with HTTP 401/403 ({", ".join(denied)}); ' 'later batches not started, nothing merged or scored. Check the keys/account, then re-run (resumes).') raise SystemExit(3) done_models += group for m in done_models: final = runs / m['name'] if m.get('fallback'): counts = merge(runs / f"{m['name']}.top", runs / f"{m['name']}.fallback", final, m.get('effort', 'top'), m['fallback'].get('effort', 'fallback')) log(cdir, f"{m['name']}: merged {json.dumps(counts)}") o = score(final, truth) log(cdir, f"{m['name']}: scored {o['passed']}/{o['items']} pass {o['pass_rate']:.3f}, errors {o['errors']}") bad = [n for n, rc in rcs.items() if rc] log(cdir, 'ALL DONE' + (f' (non-zero runner exit: {", ".join(bad)})' if bad else '')) # ---------------------------------------------------------------- report CHOICE = {'sector', 'map_point', 'options', 'boolean', 'map', 'order'} def pct(h, n): return '—' if not n else f'{100 * h / n:.0f}%' def table(head, rows): return ['| ' + ' | '.join(head) + ' |', '|' + '---|' * len(head)] + \ ['| ' + ' | '.join(str(c) for c in r) + ' |' for r in rows] def boot(vals, n=2000): rng = random.Random(0) m = sorted(sum(vals[rng.randrange(len(vals))] for _ in vals) / len(vals) for _ in range(n)) return m[int(0.025 * n)], m[int(0.975 * n)] def report(a): cdir = Path(a.dir).resolve() plan = json.loads((cdir / 'plan.json').read_text()) items = {d['item_id']: d for d in jl(cdir / 'items' / 'items.jsonl')} ids = list(items) runs = [] for m in plan['models']: p = cdir / 'runs' / m['name'] / 'scores.jsonl' if p.exists(): runs.append((m, {d['item_id']: d for d in jl(p)})) if not runs: raise SystemExit('no scored runs yet') ok = lambda s, i: bool(s.get(i, {}).get('passed')) rate = lambda s, g: (sum(ok(s, i) for i in g), len(g)) runs.sort(key=lambda t: -rate(t[1], ids)[0]) tag = lambda i, k: items[i]['tags'].get(k) ch = lambda i: tag(i, 'answer_kind') in CHOICE sv = lambda i: tag(i, 'views') == 'single_ego' out = [f'# 评测结果:{cdir.name}', '', f'{len(ids)} 道题(`items/items.jsonl`),{len(runs)} 个模型;失败(出错、未解析、截断)记 0 分。' ' 带回退的模型是“顶档 + 网关截断回退低一档”的合并结果,回退数见总表。由 `tools/evaluation/campaign.py report` 生成。', '', '## 总表', ''] rows = [] for m, s in runs: lo, hi = boot([ok(s, i) for i in ids]) st = collections.Counter(s[i]['status'] for i in ids if i in s) mj = cdir / 'runs' / m['name'] / 'merge.json' fb = json.loads(mj.read_text()) if mj.exists() else None ans = [i for i in ids if s.get(i, {}).get('status') == 'SCORED'] rows.append([m['name'], m['endpoint'] + (f" → {m['fallback']['endpoint']}" if m.get('fallback') else ''), f'{pct(*rate(s, ids))} [{100 * lo:.0f}, {100 * hi:.0f}]', pct(*rate(s, ans)), pct(*rate(s, [i for i in ids if ch(i)])), pct(*rate(s, [i for i in ids if not ch(i)])), pct(*rate(s, [i for i in ids if sv(i)])), pct(*rate(s, [i for i in ids if not sv(i)])), f"{st['UNPARSED']} / {st['TRUNCATED']} / {st['ERROR'] + len(ids) - len(s)}", f"{fb['fell_back']}({pct(fb['fell_back'], fb['items'])})" if fb else '—']) out += table(['模型', '端点', '通过率 [95%]', '作答题通过率', '选择题', '填空题', '单路', '多路', '未解析 / 截断 / 出错', '回退题数'], rows) + [''] names = [m['name'] for m, _ in runs] grp = [('全部', ids), ('选择题', [i for i in ids if ch(i)]), ('填空题', [i for i in ids if not ch(i)]), ('单路·选择', [i for i in ids if sv(i) and ch(i)]), ('单路·填空', [i for i in ids if sv(i) and not ch(i)]), ('多路·选择', [i for i in ids if not sv(i) and ch(i)]), ('多路·填空', [i for i in ids if not sv(i) and not ch(i)])] common = [i for i in ids if all(s.get(i, {}).get('status') == 'SCORED' for _, s in runs)] out += ['## 分组(全部题 / 所有模型都作答的题)', ''] + table( ['分组', '题数'] + names, [[g, len(x)] + [pct(*rate(s, x)) for _, s in runs] for g, x in grp if x]) + [''] + \ [f'所有模型都作答的 {len(common)} 道:', ''] + table( ['分组', '题数'] + names, [[g, len(x)] + [pct(*rate(s, x)) for _, s in runs] for g, x in [(g, [i for i in x if i in set(common)]) for g, x in grp] if x]) + [''] by_v = collections.defaultdict(list) for i in ids: by_v[items[i]['version_id']].append(i) out += ['## 按版式', ''] + table(['版式', '题数'] + names, [[f'`{v}`', len(x)] + [pct(*rate(s, x)) for _, s in runs] for v, x in sorted(by_v.items())]) + [''] # two-stage packets: