#!/usr/bin/env python3
"""Fetches a fixed, documented benchmark set.

1. LibriSpeech test-clean (CC BY 4.0, openslr.org/12): 40 utterances — 10 consecutive rows
   at each of offsets 0, 650, 1300, 1950 of HF dataset `openslr/librispeech_asr` (clean/test).
2. Dictation-style prompts synthesized with macOS `say` (synthetic speech; used to test
   cleanup/formatting behavior and latency, NOT to claim real-world accuracy).
Writes samples/manifest.json with reference texts.
"""
import json, os, subprocess, time, urllib.request, urllib.error

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "samples")
manifest = []

def get(url):
    for attempt in range(8):
        try:
            return urllib.request.urlopen(url, timeout=60)
        except urllib.error.HTTPError as e:
            if e.code != 429: raise
            time.sleep(5 * (attempt + 1))
    raise RuntimeError("rate limited")

rows = []
for offset in (0, 650, 1300, 1950):
    url = f"https://datasets-server.huggingface.co/rows?dataset=openslr/librispeech_asr&config=clean&split=test&offset={offset}&length=10"
    rows += [r["row"] for r in json.load(get(url))["rows"]]
    time.sleep(2)
for row in rows:
    path = os.path.join(OUT, "librispeech", f"{row['id']}.flac")
    if not os.path.exists(path):
        open(path, "wb").write(get(row["audio"][0]["src"]).read())
    manifest.append({"id": row["id"], "set": "librispeech-test-clean", "file": os.path.relpath(path, HERE), "reference": row["text"].lower()})

DICTATION = [
    ("email", "Samantha", "um hi sam, uh the draft is ready for review. new paragraph. can you look at it before friday? thanks, alex",
     "hi sam the draft is ready for review can you look at it before friday thanks alex"),
    ("message", "Daniel", "running about ten minutes late, uh, start without me",
     "running about ten minutes late start without me"),
    ("note", "Samantha", "remind me to call the printer about the invoice tomorrow morning",
     "remind me to call the printer about the invoice tomorrow morning"),
    ("prompt", "Daniel", "write a python function that removes duplicate rows from a list of dictionaries and keeps the first occurrence",
     "write a python function that removes duplicate rows from a list of dictionaries and keeps the first occurrence"),
    ("vocab", "Samantha", "please push the fix to github and tag it in the sayburst repo",
     "please push the fix to github and tag it in the sayburst repo"),
    ("numbers", "Daniel", "the meeting moved to three thirty on october twelfth in room four oh two",
     "the meeting moved to three thirty on october twelfth in room four oh two"),
    ("long", "Samantha", "I've been thinking about the onboarding flow and I think we should cut the second screen entirely because most people skip it anyway, and then we can move the permission request to right before the first dictation so it actually makes sense in context",
     "i've been thinking about the onboarding flow and i think we should cut the second screen entirely because most people skip it anyway and then we can move the permission request to right before the first dictation so it actually makes sense in context"),
    ("short", "Daniel", "sounds good", "sounds good"),
]
for name, voice, spoken, ref in DICTATION:
    path = os.path.join(OUT, "dictation", f"{name}.wav")
    if not os.path.exists(path):
        subprocess.run(["say", "-v", voice, "-o", path, "--data-format=LEI16@16000", spoken], check=True)
    manifest.append({"id": f"say-{name}", "set": "synthetic-dictation", "voice": voice, "file": os.path.relpath(path, HERE), "spoken": spoken, "reference": ref})

json.dump(manifest, open(os.path.join(OUT, "manifest.json"), "w"), indent=2)
print(f"{len(manifest)} samples")
