| |
| """Run the Entity Transcription Benchmark against any STT endpoint. |
| |
| export DEEPGRAM_API_KEY=... |
| python run_benchmark.py --provider deepgram --provider-opt model=nova-3 \ |
| --out runs/deepgram_nova3.jsonl |
| |
| export MY_KEY=... |
| python run_benchmark.py --provider http --endpoint https://api.example.com/v1/stt \ |
| --api-key-env MY_KEY --response-path result.transcript --out runs/mine.jsonl |
| |
| Output is a resumable JSONL of hypotheses plus a manifest recording exactly how |
| the run was configured. Scoring is a separate step: score_benchmark.py. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| import sys |
| import time |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from datetime import datetime, timezone |
|
|
| import common |
| import providers |
|
|
|
|
| def parse_args(argv=None): |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| p.add_argument("--provider", default="http", choices=sorted(providers.PROVIDERS), |
| help="'http' (default) works with any endpoint that takes audio and " |
| "returns JSON. The named adapters are conveniences, not requirements.") |
| p.add_argument("--system-name", default=None, |
| help="label for the system under test, recorded in the manifest and " |
| "summary (e.g. 'acme-stt-v2'). Defaults to the provider name.") |
| p.add_argument("--endpoint", help="for --provider http, or to override a vendor base URL") |
| p.add_argument("--api-key-env", default=None, |
| help="env var holding the API key (default: <PROVIDER>_API_KEY)") |
| p.add_argument("--provider-opt", action="append", default=[], metavar="K=V", |
| help="repeatable; passed to the adapter (e.g. model=nova-3 smart_format=true)") |
| p.add_argument("--response-path", help="shorthand for --provider-opt response_path=...") |
|
|
| p.add_argument("--dataset", default=common.DEFAULT_DATASET) |
| p.add_argument("--split", default=common.DEFAULT_SPLIT) |
| p.add_argument("--revision", default=None, help="pin a dataset commit SHA -- recommended") |
| p.add_argument("--local-path", default=None, help="load_from_disk path instead of the Hub") |
| p.add_argument("--tier", default="all", |
| help="skip clips with no span of this tier. Default 'all' -- transcribe " |
| "every clip, since WER is reported over the full split and the tier " |
| "filter is applied per span at scoring time.") |
| p.add_argument("--limit", type=int, default=0, help="first N clips; smoke tests only") |
|
|
| p.add_argument("--out", required=True, help="hypotheses JSONL") |
| p.add_argument("--workers", type=int, default=4) |
| p.add_argument("--timeout", type=int, default=providers.DEFAULT_TIMEOUT) |
| p.add_argument("--retries", type=int, default=3) |
| p.add_argument("--overwrite", action="store_true", help="ignore existing output and start over") |
|
|
| for field in common.CANDIDATES: |
| p.add_argument(f"--{field.replace('_', '-')}-column", dest=f"{field}_column", default=None) |
| return p.parse_args(argv) |
|
|
|
|
| def build_cfg(args) -> dict: |
| opts: dict = {} |
| for item in args.provider_opt: |
| key, _, value = item.partition("=") |
| opts[key.strip()] = value.strip() |
| if args.endpoint: |
| opts["endpoint"] = args.endpoint |
| if args.response_path: |
| opts["response_path"] = args.response_path |
| key_env = args.api_key_env or f"{args.provider.upper()}_API_KEY" |
| return { |
| "provider": args.provider, |
| "system_name": args.system_name or args.provider, |
| "api_key_env": key_env, |
| "opts": opts, |
| "timeout": args.timeout, |
| } |
|
|
|
|
| def load_done(path: str) -> dict[str, dict]: |
| if not os.path.exists(path): |
| return {} |
| done = {} |
| with open(path) as fh: |
| for line in fh: |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| record = json.loads(line) |
| except json.JSONDecodeError: |
| continue |
| if record.get("hypothesis") is not None and not record.get("error"): |
| done[record["clip_id"]] = record |
| return done |
|
|
|
|
| def main(argv=None) -> int: |
| args = parse_args(argv) |
| cfg = build_cfg(args) |
|
|
| anonymous_ok = args.provider in ("mock", "http") and not args.api_key_env |
| if not anonymous_ok and not os.environ.get(cfg["api_key_env"]): |
| common.eprint( |
| f"! {cfg['api_key_env']} is not set. Export your key, or pass --api-key-env " |
| f"to name a different variable." |
| ) |
| return 2 |
| if args.provider == "http" and not args.endpoint: |
| common.eprint("! --provider http needs --endpoint") |
| return 2 |
|
|
| ds = common.load_bench(args.dataset, args.split, args.revision, args.local_path) |
| overrides = {f: getattr(args, f"{f}_column") for f in common.CANDIDATES} |
| schema = common.resolve_schema(ds.column_names, overrides) |
| common.eprint("Resolved columns:\n" + schema.pretty()) |
|
|
| if args.tier and args.tier.lower() != "all": |
| ds = ds.filter(lambda row: common.row_has_tier(row, schema, args.tier)) |
| ds = common.undecode_audio(ds, schema) |
| if args.limit: |
| ds = ds.select(range(min(args.limit, len(ds)))) |
| common.eprint(f"Clips to transcribe: {len(ds)} (tier={args.tier})") |
|
|
| os.makedirs(os.path.dirname(os.path.abspath(args.out)) or ".", exist_ok=True) |
| if args.overwrite and os.path.exists(args.out): |
| os.remove(args.out) |
| done = load_done(args.out) |
| if done: |
| common.eprint(f"Resuming: {len(done)} clips already transcribed") |
|
|
| manifest = { |
| "harness_version": "1.0.0", |
| "started_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), |
| "dataset": args.dataset if not args.local_path else f"local:{args.local_path}", |
| "split": args.split, |
| "revision": args.revision, |
| "tier": args.tier, |
| "system_name": cfg["system_name"], |
| "provider": args.provider, |
| "provider_opts": cfg["opts"], |
| "api_key_env": cfg["api_key_env"], |
| "clips": len(ds), |
| } |
| manifest_path = os.path.splitext(args.out)[0] + ".manifest.json" |
| with open(manifest_path, "w") as fh: |
| json.dump(manifest, fh, indent=2) |
|
|
| pending = [] |
| for index, row in enumerate(ds): |
| clip = common.row_id(row, schema, index) |
| if clip in done: |
| continue |
| pending.append((index, clip, row)) |
|
|
| if not pending: |
| common.eprint("Nothing to do -- all clips already present.") |
| return 0 |
|
|
| started = time.time() |
| errors = 0 |
| sink = open(args.out, "a", buffering=1) |
|
|
| def work(item): |
| index, clip, row = item |
| try: |
| audio, sample_rate = common.audio_to_wav_bytes(row[schema.audio]) |
| call_cfg = dict(cfg) |
| call_cfg["clip_id"] = clip |
| hypothesis = providers.transcribe(audio, call_cfg, retries=args.retries) |
| return { |
| "clip_id": clip, |
| "index": index, |
| "hypothesis": hypothesis, |
| "sampling_rate": sample_rate, |
| } |
| except Exception as exc: |
| return {"clip_id": clip, "index": index, "hypothesis": None, "error": str(exc)} |
|
|
| try: |
| with ThreadPoolExecutor(max_workers=args.workers) as pool: |
| futures = {pool.submit(work, item): item for item in pending} |
| for completed, future in enumerate(as_completed(futures), 1): |
| record = future.result() |
| if record.get("error"): |
| errors += 1 |
| if errors <= 5: |
| common.eprint(f" ! {record['clip_id']}: {record['error'][:160]}") |
| if errors == 6: |
| common.eprint(" ! (further errors suppressed; see the JSONL)") |
| sink.write(json.dumps(record, ensure_ascii=False) + "\n") |
| if completed % 25 == 0 or completed == len(pending): |
| rate = completed / max(time.time() - started, 1e-6) |
| common.eprint( |
| f" {completed}/{len(pending)} {rate:.1f} clips/s errors={errors}" |
| ) |
| except KeyboardInterrupt: |
| common.eprint("\nInterrupted -- rerun the same command to resume.") |
| return 130 |
| finally: |
| sink.close() |
|
|
| if errors: |
| common.eprint( |
| f"\nDone with {errors} failed clips. Rerun the same command to retry only those." |
| ) |
| common.eprint(f"\nHypotheses: {args.out}\nManifest: {manifest_path}") |
| common.eprint(f"Next: python score_benchmark.py --hyps {args.out}") |
| return 1 if errors else 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|