"""Pick the test utterances and write 16 kHz mono 16-bit WAVs + manifest.jsonl.

LibriSpeech test-clean: for each of the 40 speakers, the first 4 utterance IDs in sorted order (160 utterances).
EdAcc test, shard test-00000: per speaker, in file order, the first 8 utterances that last 3-30 s and have
at least 5 reference words.
"""
import io, json, os, subprocess, sys, collections
import pyarrow.parquet as pq, soundfile as sf

B = sys.argv[1]
out = os.path.join(B, 'data', 'wav'); os.makedirs(out, exist_ok=True)
manifest = []

def write_wav(raw, path):
    subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', 'pipe:0', '-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', path],
                   input=raw, check=True)

# LibriSpeech
t = pq.read_table(os.path.join(B, 'data/librispeech/test.clean.0000.parquet')).to_pylist()
by = collections.defaultdict(list)
for r in t: by[r['speaker_id']].append(r)
for spk in sorted(by):
    for r in sorted(by[spk], key=lambda r: r['id'])[:4]:
        p = os.path.join(out, f"ls_{r['id']}.wav"); write_wav(r['audio']['bytes'], p)
        manifest.append(dict(set='librispeech-test-clean', id=r['id'], path=p, duration=sf.info(p).duration,
                             ref=r['text'], speaker=str(spk), accent=''))

# EdAcc
t = pq.read_table(os.path.join(B, 'data/edacc/test-00000.parquet')).to_pylist()
taken = collections.Counter()
for r in t:
    d = sf.info(io.BytesIO(r['audio']['bytes'])).duration
    if not (3 <= d <= 30) or len(r['text'].split()) < 5 or taken[r['speaker']] >= 8: continue
    taken[r['speaker']] += 1
    uid = os.path.splitext(r['audio']['path'])[0]
    p = os.path.join(out, f"ed_{uid}.wav"); write_wav(r['audio']['bytes'], p)
    manifest.append(dict(set='edacc-test', id=uid, path=p, duration=sf.info(p).duration,
                         ref=r['text'], speaker=r['speaker'], accent=r['accent']))

with open(os.path.join(B, 'manifest.jsonl'), 'w') as f:
    for m in manifest: f.write(json.dumps(m) + '\n')
for s in ['librispeech-test-clean', 'edacc-test']:
    ms = [m for m in manifest if m['set'] == s]
    print(s, len(ms), 'utterances', round(sum(m['duration'] for m in ms) / 60, 2), 'min',
          len({m['speaker'] for m in ms}), 'speakers')
