import json, os, sys, time, httpx
URL = "https://space.ai-builders.com/backend/v1/audio/grok-transcription"
def run(path, language=None):
    data = {}
    if language: data["language"] = language
    t = time.time()
    try:
        with open(path, "rb") as f:
            r = httpx.post(URL, headers={"Authorization": f"Bearer {os.environ['AI_BUILDER_TOKEN']}"},
                           files={"audio_file": (os.path.basename(path), f)}, data=data, timeout=900)
        out = {"status": r.status_code, "secs": round(time.time()-t,1)}
        try:
            j = r.json(); out["text"] = j.get("text"); out["duration"] = j.get("duration_seconds")
            out["segments"] = [(s["start"], s["end"], s["text"]) for s in (j.get("segments") or [])]
            if r.status_code != 200: out["body"] = str(j)[:500]
        except Exception: out["body"] = r.text[:500]
    except Exception as e:
        out = {"error": repr(e)[:300], "secs": round(time.time()-t,1)}
    return out
res = {}
for spec in sys.argv[1:]:
    path, _, lang = spec.partition(":")
    res[spec] = run(path, lang or None)
    print(spec, json.dumps({k: v for k, v in res[spec].items() if k != "segments"}, ensure_ascii=False)[:1500], flush=True)
json.dump(res, open("asr_pilot_" + str(int(time.time())) + ".json", "w"), ensure_ascii=False, indent=1)
