#!/usr/bin/env python3
"""Transcribe all 6 MP3 files with word-level timestamps via Whisper."""
import os, json, subprocess, sys
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor

KEY = os.environ['OPENAI_API_KEY']
AUDIO_DIR = Path('/opt/mia/workspace/clientes/px3lab/video_2_0/audio')
OUT_DIR = Path('/opt/mia/workspace/clientes/px3lab/video_2_0/v2/karaoke')
OUT_DIR.mkdir(parents=True, exist_ok=True)

FILES = ['01_hook', '02_dor', '03_virada', '04_diferenciais', '05_autoridade', '06_cta']

def transcribe(name):
    src = AUDIO_DIR / f'{name}.mp3'
    dst = OUT_DIR / f'{name}.json'
    if dst.exists():
        print(f'{name}: cached')
        return
    r = subprocess.run(['curl', '-s', '-X', 'POST',
        'https://api.openai.com/v1/audio/transcriptions',
        '-H', f'Authorization: Bearer {KEY}',
        '-F', f'file=@{src}',
        '-F', 'model=whisper-1',
        '-F', 'language=pt',
        '-F', 'response_format=verbose_json',
        '-F', 'timestamp_granularities[]=word',
    ], capture_output=True, text=True)
    data = json.loads(r.stdout)
    dst.write_text(json.dumps(data, ensure_ascii=False, indent=2))
    print(f'{name}: {len(data.get("words",[]))} words, {data.get("duration")}s')

with ThreadPoolExecutor(max_workers=6) as ex:
    list(ex.map(transcribe, FILES))
print('done')
