"""Batch-transcribe the first N utterances (sorted by utterance ID) of LibriSpeech test-clean with Whisper on CPU.""" import sys, glob, os, json, time, platform, torch, soundfile as sf from transformers import WhisperProcessor, WhisperForConditionalGeneration MODEL, N, OUT = sys.argv[1], int(sys.argv[2]), sys.argv[3] torch.set_num_threads(8) refs = {} for f in glob.glob("LibriSpeech/test-clean/*/*/*.trans.txt"): for line in open(f): uid, txt = line.strip().split(" ", 1); refs[uid] = txt ids = sorted(refs)[:N] proc = WhisperProcessor.from_pretrained(MODEL) model = WhisperForConditionalGeneration.from_pretrained(MODEL).eval() def path(uid): s, c, _ = uid.split("-"); return f"LibriSpeech/test-clean/{s}/{c}/{uid}.flac" rows, failed, retried, BS = [], [], 0, 8 t0 = time.time() done = set() if os.path.exists(OUT + ".partial.jsonl"): for l in open(OUT + ".partial.jsonl"): r = json.loads(l); rows.append(r); done.add(r["id"]) todo = [u for u in ids if u not in done] pf = open(OUT + ".partial.jsonl", "a") def run(batch): audio = [sf.read(path(u))[0] for u in batch] feats = proc(audio, sampling_rate=16000, return_tensors="pt") with torch.no_grad(): g = model.generate(feats.input_features, max_new_tokens=200) return audio, proc.batch_decode(g, skip_special_tokens=True) for i in range(0, len(todo), BS): batch = todo[i:i+BS] for attempt in range(2): try: audio, hyps = run(batch); break except Exception as e: print("batch error", batch[0], e, flush=True) if attempt == 0: retried += 1 else: failed += batch; audio = None if audio is None: continue for u, a, h in zip(batch, audio, hyps): r = {"id": u, "speaker_id": u.split("-")[0], "chapter_id": u.split("-")[1], "duration_s": round(len(a)/16000, 3), "reference": refs[u], "transcript": h.strip()} rows.append(r); pf.write(json.dumps(r) + "\n") pf.flush(); print(f"{len(rows)}/{len(ids)} {time.time()-t0:.0f}s", flush=True) wall = time.time() - t0 json.dump({"model": MODEL, "n_requested": N, "n_processed": len(rows), "failed": failed, "retried_batches": retried, "audio_seconds": round(sum(r["duration_s"] for r in rows), 1), "transcribe_wall_seconds_this_run": round(wall, 1), "batch_size": BS, "threads": 8, "cpu": "8-core Intel Xeon VM, 15 GB RAM, no GPU"}, open(OUT + ".stats.json", "w"), indent=1) json.dump(rows, open(OUT + ".rows.json", "w"))