Download scripts/build_librispeech_dev_sets.py from anilkeshwani/speech-integration-eval-sets: direct link, hf CLI and curl.
- Browser
- Download file 5.58 kB
-
https://huggingface.co/datasets/anilkeshwani/speech-integration-eval-sets/resolve/main/scripts/build_librispeech_dev_sets.py
- Command line
-
hf download hf://datasets/anilkeshwani/speech-integration-eval-sets/scripts/build_librispeech_dev_sets.py
-
curl -L -o build_librispeech_dev_sets.py https://huggingface.co/datasets/anilkeshwani/speech-integration-eval-sets/resolve/main/scripts/build_librispeech_dev_sets.py
5.58 kB
| """Tokenize LibriSpeech dev-clean and dev-other (OpenSLR FLAC release) with the four DSU tokenizers. | |
| Analysis audio for the unit-representation analyses (plans/Plan - Ablations and Unit Embedding Analyses, section 3.0). | |
| Same pipeline and settings as build_dsu_asr_eval_sets.py (decode_16k, the tokenizer wrappers in dsu_tokenizers.py, | |
| fp32, one utterance at a time, no padding), but the audio comes from the extracted OpenSLR tarballs in | |
| downloads/librispeech_dev/LibriSpeech/<split>/ instead of HF parquet, and the device is the first visible GPU (the | |
| queue sets CUDA_VISIBLE_DEVICES) rather than the hard-wired GPU 3. | |
| One HF dataset per tokenizer at <out-root>/librispeech-<dev_clean|dev_other>/<tokenizer>/ with the eval-set columns | |
| ID (str), transcript (str, OpenSLR text unmodified), speech_tokens (list[int64]), duration (float, s) | |
| and identical row order (sorted by ID) across tokenizers. Word and phone alignments are joined separately by the | |
| speech-integration repo (scripts/data/build_analysis_alignments.py), so this script needs no repo code. | |
| CUDA_VISIBLE_DEVICES=0 HF_HUB_OFFLINE=1 .venv-tokenizers/bin/python -I \ | |
| scripts/build_librispeech_dev_sets.py --splits dev-clean dev-other | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import glob | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import torch | |
| from datasets import Dataset | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from build_dsu_asr_eval_sets import FEATURES, decode_16k # noqa: E402 | |
| from dsu_tokenizers import TOKENIZERS # noqa: E402 | |
| ROOT = "/home/anilkeshwani/scratch/speech-integration/eval_data" | |
| AUDIO_ROOT = os.path.join(ROOT, "downloads", "librispeech_dev", "LibriSpeech") | |
| SPLITS = {"dev-clean": "librispeech-dev_clean", "dev-other": "librispeech-dev_other"} | |
| OPENSLR_MD5 = {"dev-clean": "42e2234ba48799c1f50f24a7926300a1", "dev-other": "c8d0bcc9cca99d4f8b62fcc847357931"} | |
| def read_split(split: str) -> list[tuple[str, str, str]]: | |
| """(ID, transcript, flac path) for every utterance of an extracted OpenSLR split, sorted by ID.""" | |
| rows = [] | |
| for trans in sorted(glob.glob(os.path.join(AUDIO_ROOT, split, "*", "*", "*.trans.txt"))): | |
| with open(trans) as f: | |
| for line in f: | |
| uid, text = line.rstrip("\n").split(" ", 1) | |
| path = os.path.join(os.path.dirname(trans), f"{uid}.flac") | |
| if not os.path.isfile(path): | |
| raise FileNotFoundError(path) | |
| rows.append((uid, text, path)) | |
| if not rows: | |
| raise FileNotFoundError(f"No transcripts under {os.path.join(AUDIO_ROOT, split)}") | |
| rows.sort(key=lambda r: r[0]) | |
| if len({r[0] for r in rows}) != len(rows): | |
| raise ValueError(f"{split}: duplicate IDs") | |
| return rows | |
| def build(split: str, tokenizers: dict, out_root: str, limit: int | None) -> dict: | |
| name = SPLITS[split] | |
| rows = read_split(split)[:limit] | |
| ids, transcripts, durations = [], [], [] | |
| tokens = {t: [] for t in tokenizers} | |
| t0 = time.time() | |
| for i, (uid, text, path) in enumerate(rows): | |
| with open(path, "rb") as f: | |
| wav, dur = decode_16k(f.read()) | |
| ids.append(uid) | |
| transcripts.append(text) | |
| durations.append(float(dur)) | |
| for t, tok in tokenizers.items(): | |
| tokens[t].append(tok.encode(wav)) | |
| if (i + 1) % 500 == 0: | |
| print(f"[{name}] {i + 1} rows, {sum(durations) / 3600:.2f} h, {time.time() - t0:.0f} s", flush=True) | |
| for t in tokenizers: | |
| ds = Dataset.from_dict( | |
| {"ID": ids, "transcript": transcripts, "speech_tokens": tokens[t], "duration": durations}, | |
| features=FEATURES, | |
| ) | |
| out = os.path.join(out_root, name, t) | |
| ds.save_to_disk(out) | |
| print(f"[{name}] saved {len(ds)} rows to {out}", flush=True) | |
| meta = { | |
| "eval_set": name, | |
| "source": f"https://www.openslr.org/resources/12/{split}.tar.gz", | |
| "source_md5": OPENSLR_MD5[split], | |
| "transcript_field": "OpenSLR *.trans.txt", | |
| "row_order": "sorted by ID", | |
| "n_rows": len(ids), | |
| "total_hours": sum(durations) / 3600, | |
| "max_duration_s": max(durations), | |
| "limit": limit, | |
| "tokenizers": {t: {"n_tokens": int(sum(map(len, tokens[t])))} for t in tokenizers}, | |
| "elapsed_s": time.time() - t0, | |
| } | |
| with open(os.path.join(out_root, name, "build_info.json"), "w") as f: | |
| json.dump(meta, f, indent=2) | |
| return meta | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--splits", nargs="+", default=list(SPLITS), choices=list(SPLITS)) | |
| ap.add_argument("--tokenizers", nargs="+", default=list(TOKENIZERS), choices=list(TOKENIZERS)) | |
| ap.add_argument("--out-root", default=ROOT) | |
| ap.add_argument("--limit", type=int, default=None, help="Only the first N rows (smoke test)") | |
| ap.add_argument("--device", default=None, help="Default: cuda:0 (first visible GPU) if available, else cpu") | |
| args = ap.parse_args() | |
| device = torch.device(args.device or ("cuda:0" if torch.cuda.is_available() else "cpu")) | |
| print(f"device {device}, CUDA_VISIBLE_DEVICES={os.environ.get('CUDA_VISIBLE_DEVICES')!r}", flush=True) | |
| tokenizers = {t: TOKENIZERS[t](device) for t in args.tokenizers} | |
| for split in args.splits: | |
| meta = build(split, tokenizers, args.out_root, args.limit) | |
| print(json.dumps(meta), flush=True) | |
| if torch.cuda.is_available(): | |
| print(f"peak GPU memory {torch.cuda.max_memory_allocated() / 2**30:.2f} GiB", flush=True) | |
| if __name__ == "__main__": | |
| main() | |