"""Download the training/evaluation audio once and keep it as 16 kHz mono FLAC (data/audio//.flac). python -m tk.audio --sets fleurs-en-dev # resumable: finished ids are skipped python -m tk.audio --smoke # 30 clips per set into data/*-smoke Streaming code ported from ~/lvw-dictate/lvw_dictate/asr.py (same author), with LibriSpeech train-clean-100 added. """ from __future__ import annotations import argparse import io import json import random import shutil import subprocess import sys import tempfile import time from pathlib import Path import numpy as np import soundfile as sf from tk import paths SR = 16000 MIN_S, MAX_S = 0.5, 30.0 FLEURS = "datasets/google/fleurs" VOX = "datasets/facebook/voxpopuli" ESB = "datasets/hf-audio/esb-datasets-test-only-sorted" LS = "openslr/librispeech_asr" DIS = "amaai-lab/DisfluencySpeech" DIS_REV = "refs/convert/parquet" DIS_FILES = {"train": ["default/train/0000.parquet", "default/train/0001.parquet", "default/train/0002.parquet"], "validation": ["default/validation/0000.parquet"], "test": ["default/test/0000.parquet"]} TEXT_COLS = ("raw_transcription", "raw_text", "sentence", "text") FLEURS_CFG = {"es": "es_419", "fr": "fr_fr", "de": "de_de", "it": "it_it", "pt": "pt_br", "nl": "nl_nl", "pl": "pl_pl", "ru": "ru_ru", "uk": "uk_ua", "ro": "ro_ro", "cs": "cs_cz", "sk": "sk_sk", "bg": "bg_bg", "hr": "hr_hr", "sv": "sv_se", "da": "da_dk", "fi": "fi_fi", "et": "et_ee", "lv": "lv_lv", "lt": "lt_lt", "hu": "hu_hu", "sl": "sl_si", "mt": "mt_mt", "el": "el_gr"} MIN_FREE_GB = 25 _fs = None def fs(): global _fs if _fs is None: from huggingface_hub import HfFileSystem _fs = HfFileSystem() return _fs def free_gb() -> float: return shutil.disk_usage(paths.ROOT).free / 1e9 def decode(raw: bytes) -> np.ndarray: """bytes (wav/flac/mp3/ogg) -> float32 mono 16 kHz.""" try: w, sr = sf.read(io.BytesIO(raw), dtype="float32", always_2d=True) w = w.mean(axis=1) except Exception: p = subprocess.run(["ffmpeg", "-v", "quiet", "-i", "pipe:0", "-f", "f32le", "-ac", "1", "-ar", str(SR), "pipe:1"], input=raw, capture_output=True, check=True) return np.frombuffer(p.stdout, dtype=np.float32).copy() if sr != SR: p = subprocess.run(["ffmpeg", "-v", "quiet", "-f", "f32le", "-ar", str(sr), "-ac", "1", "-i", "pipe:0", "-f", "f32le", "-ac", "1", "-ar", str(SR), "pipe:1"], input=w.astype(np.float32).tobytes(), capture_output=True, check=True) return np.frombuffer(p.stdout, dtype=np.float32).copy() return w.astype(np.float32) def clean_ws(text: str) -> str: return " ".join((text or "").replace(" ", " ").split()) # ------------------------------------------------------------------ sources: yield (id, raw_bytes, ref, extra) def _parquet_rows(paths_: list[str], seed: int): import pyarrow.parquet as pq rng = random.Random(seed) paths_ = sorted(paths_) rng.shuffle(paths_) for p in paths_: with fs().open(p, "rb", block_size=4 << 20) as f: pf = pq.ParquetFile(f) names = pf.schema_arrow.names tcols = [c for c in TEXT_COLS + ("normalized_text",) if c in names] if not tcols or "audio" not in names: raise RuntimeError(f"{p}: no text/audio column in {names}") extra = [c for c in ("id", "audio_id", "is_gold_transcript") if c in names] groups = list(range(pf.num_row_groups)) rng.shuffle(groups) for g in groups: t = pf.read_row_group(g, columns=["audio", *tcols, *extra]).to_pylist() rng.shuffle(t) for r in t: if r.get("is_gold_transcript") is False: continue a = r["audio"] raw = a.get("bytes") if isinstance(a, dict) else None if not raw: continue rid = str(r.get("id") or r.get("audio_id") or (a.get("path") or "")).replace("/", "_") yield rid, raw, next((r[c] for c in tcols if (r[c] or "").strip()), ""), {} def fleurs_rows(cfg: str, split: str, seed: int): ps = fs().glob(f"{FLEURS}/parquet-data/{cfg}/{split}-*.parquet") if not ps: raise RuntimeError(f"fleurs {cfg}/{split}: no parquet") for rid, raw, ref, ex in _parquet_rows(ps, seed): yield f"{cfg}-{rid}", raw, ref, ex def _shard_rows(repo: str, files: list[str], cols: list[str], seed: int, per_shard: int): """Download whole parquet shards (row-group range reads crawl on big shards), yield rows, delete the shard.""" import pyarrow.parquet as pq from huggingface_hub import hf_hub_download rng = random.Random(seed) files = sorted(files) rng.shuffle(files) for fn in files: tmp = Path(tempfile.mkdtemp(prefix="tk-shard-", dir=paths.RUNS)) try: local = Path(hf_hub_download(repo, fn, repo_type="dataset", local_dir=tmp)) t = pq.read_table(local, columns=cols).to_pylist() rng.shuffle(t) for r in t[:per_shard]: yield r finally: shutil.rmtree(tmp, ignore_errors=True) def vox_rows(seed: int): files = [p.split("datasets/facebook/voxpopuli/", 1)[1] for p in fs().glob(f"{VOX}/en/train-*.parquet")] for r in _shard_rows("facebook/voxpopuli", files, ["audio", "raw_text", "audio_id"], seed, 2300): if (r["raw_text"] or "").strip() and r["audio"].get("bytes"): yield str(r["audio_id"]).replace("/", "_"), r["audio"]["bytes"], r["raw_text"], {} def ls_train_rows(seed: int): files = [f"clean/train.100/{i:04d}.parquet" for i in range(14)] for r in _shard_rows(LS, files, ["audio", "text", "id"], seed, 1000): yield "ls-" + str(r["id"]), r["audio"]["bytes"], r["text"], {} def esb_rows(cfg: str, prefix: str, seed: int, per_group: int = 16): """ESB files are sorted by length: visit row groups in a seeded random order and take a few rows of each.""" import pyarrow.parquet as pq ps = sorted(fs().glob(f"{ESB}/{cfg}/{prefix}-*.parquet")) if not ps: raise RuntimeError(f"{ESB}/{cfg}/{prefix}: no files") pairs = [] for p in ps: with fs().open(p, "rb", block_size=1 << 20) as f: pairs += [(p, g) for g in range(pq.ParquetFile(f).num_row_groups)] rng = random.Random(seed) rng.shuffle(pairs) for p, g in pairs: with fs().open(p, "rb", block_size=4 << 20) as f: t = pq.ParquetFile(f).read_row_group(g, columns=["audio", "text", "id"]).to_pylist() rng.shuffle(t) for r in t[:per_group]: a = r["audio"] raw = a.get("bytes") if isinstance(a, dict) else None if raw and (r.get("text") or "").strip(): yield str(r["id"]).replace("/", "_"), raw, r["text"], {} def dis_rows(split: str, seed: int): import pyarrow.parquet as pq from huggingface_hub import hf_hub_download for fn in DIS_FILES[split]: p = hf_hub_download(DIS, fn, repo_type="dataset", revision=DIS_REV) t = pq.read_table(p).to_pylist() part = fn.split("/")[-1].split(".")[0] for i, r in enumerate(t): ex = {k: r[k] for k in ("transcript_annotated", "transcript_a", "transcript_b", "transcript_c")} yield f"dis-{split}-{part}-{i:05d}", r["audio"]["bytes"], r["transcript_a"], ex def fleurs_multi_rows(seed: int, per_lang: int = 10): for code, cfg in FLEURS_CFG.items(): n = 0 for rid, raw, ref, ex in fleurs_rows(cfg, "test", seed): yield rid, raw, ref, {"lang": code} n += 1 if n >= per_lang: break # set name -> (factory(seed) -> rows, max clips, lang) SETS = { "fleurs-en-dev": (lambda s: fleurs_rows("en_us", "validation", s), 300, "en"), "dis-train": (lambda s: dis_rows("train", s), None, "en"), "dis-val": (lambda s: dis_rows("validation", s), None, "en"), "dis-test": (lambda s: dis_rows("test", s), None, "en"), "fleurs-en-train": (lambda s: fleurs_rows("en_us", "train", s), 2500, "en"), "fleurs-en-test": (lambda s: fleurs_rows("en_us", "test", s), None, "en"), "ls-clean-300": (lambda s: esb_rows("librispeech", "test.clean", s), 300, "en"), "fleurs-multi": (lambda s: fleurs_multi_rows(s), None, None), "vox-en-train": (vox_rows, 4500, "en"), "ls-train": (ls_train_rows, 12000, "en"), } def read_jsonl(path: Path) -> list[dict]: if not path.exists(): return [] return [json.loads(l) for l in path.read_text().splitlines() if l.strip()] def run_set(name: str, smoke: bool, limit: int | None, seed: int = 1234) -> None: factory, cap, lang = SETS[name] cap = min(x for x in (cap, limit) if x is not None) if (cap or limit) else None sfx = "-smoke" if smoke else "" out = paths.DATA / f"manifest{sfx}" / f"{name}.jsonl" adir = paths.DATA / f"audio{sfx}" / name out.parent.mkdir(parents=True, exist_ok=True) adir.mkdir(parents=True, exist_ok=True) done = {r["id"] for r in read_jsonl(out)} if cap is not None and len(done) >= cap: print(f"{name}: {len(done)} clips already, skipped") return n, skipped, t0 = len(done), 0, time.time() with out.open("a") as f: for rid, raw, ref, ex in factory(seed): if cap is not None and n >= cap: break if rid in done: continue w = decode(raw) dur = len(w) / SR if not (MIN_S <= dur <= MAX_S): skipped += 1 continue if n % 100 == 0 and free_gb() < MIN_FREE_GB: raise SystemExit(f"stop: only {free_gb():.1f} GB free (< {MIN_FREE_GB})") sf.write(adir / f"{rid}.flac", w, SR, subtype="PCM_16") row = {"id": rid, "set": name, "lang": ex.pop("lang", lang), "dur": round(dur, 2), "ref": clean_ws(ref), **ex} f.write(json.dumps(row, ensure_ascii=False) + "\n") f.flush() done.add(rid) n += 1 if n % 500 == 0: print(f" {name}: {n} clips, {time.time() - t0:.0f} s", flush=True) print(f"{name}: {n} clips ({skipped} skipped for length) in {time.time() - t0:.0f} s", flush=True) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--sets", nargs="+", default=list(SETS), choices=list(SETS)) ap.add_argument("--limit", type=int, default=None) ap.add_argument("--smoke", action="store_true") a = ap.parse_args() for s in a.sets: run_set(s, a.smoke, 30 if a.smoke else a.limit) if __name__ == "__main__": sys.exit(main())