"""Transcribe every synthetic memo (English) with AI Builder Space.
Outputs transcripts_<variant>.json: {memo_id: text}. Variants:
  grok        /audio/grok-transcription, language=en, no terms
  grok_terms  same, with `terms` = the 9 names + the jargon list (minus "terminal", which is never spoken: it is the
              author's written form for "shell" in 2.6, and putting it in the ASR vocabulary could bias that test)
  compat      the OpenAI-compatible /audio/transcriptions route (whisper-1), language=en
Existing output files are skipped; delete one to redo it. Usage:
  op run --env-file experiments/aib.env -- .venv/bin/python experiments_en/corpus/transcribe.py"""
import json, pathlib, sys, wave
from concurrent.futures import ThreadPoolExecutor
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from common import transcribe, log_cost, ASR_PRICE_PER_HOUR

HERE = pathlib.Path(__file__).resolve().parent
d = json.load(open(HERE / 'memos.json', encoding='utf-8'))
terms = list(d['people']) + [t for t in d['terms'] if t != 'terminal']
variants = {'grok': dict(engine='grok'), 'grok_terms': dict(engine='grok', terms=terms), 'compat': dict(engine='compat')}
hours = sum(wave.open(str(HERE / 'audio' / f"{m['id']}.wav")).getnframes() / wave.open(str(HERE / 'audio' / f"{m['id']}.wav")).getframerate()
            for m in d['memos']) / 3600
usd, ran = 0.0, []
for name, kw in variants.items():
    out = HERE / f'transcripts_{name}.json'
    if out.exists():
        continue
    def one(m):
        err = ''
        for attempt in range(3):
            try:
                return m['id'], transcribe(HERE / 'audio' / f"{m['id']}.wav", language='en', **kw)
            except Exception as e:
                err = str(e)
        return m['id'], f'ERROR: {err[:200]}'
    with ThreadPoolExecutor(6) as ex:
        res = dict(ex.map(one, d['memos']))
    out.write_text(json.dumps(res, ensure_ascii=False, indent=1), encoding='utf-8')
    print(name, sum(v.startswith('ERROR') for v in res.values()), 'errors')
    usd += hours * ASR_PRICE_PER_HOUR[kw['engine']]; ran.append(name)
if ran:
    log_cost('corpus/transcribe.py ' + ' '.join(ran), extra_usd=usd, note=f'ASR only, {hours * 60:.1f} audio min per variant')
