#!/usr/bin/env python3 """Rebuild asr-ja-bench from the upstream corpora. asr-ja-bench ships no audio and no transcripts, only which upstream samples it uses and how their transcripts were corrected. This script reads each upstream corpus, takes the listed samples in order, applies the corrections, checks every transcript against its published hash, and writes the benchmark: /.jsonl {"id", "audio", "text", "duration"} per sample /audio//.flac 16 kHz mono, 16-bit PCM Inputs (see the dataset card for where to get each): --jsut jsut_ver1.1.zip, or the directory it extracts to --jvnv jvnv_ver1.zip, or the directory it extracts to --tedxjp10k the TEDxJP-10K v1.1 directory written by Laboro.AI's compose_tedxjp10k.py (text, segments, wav/) FLEURS and SpeechBSD are read from the Hugging Face Hub at pinned revisions (SpeechBSD is gated: accept its terms on the Hub and log in first). python rebuild.py --jsut jsut_ver1.1.zip --jvnv jvnv_ver1.zip \\ --tedxjp10k TEDxJP-10K_v1.1 --out asr-ja-bench-v1.1 python rebuild.py ... --subset fleurs --text-only # transcripts only Requires: numpy, soundfile, pyarrow, huggingface_hub, and the ffmpeg command (JSUT and JVNV are 48 kHz; resampling them with ffmpeg's default resampler reproduces the benchmark audio bit for bit, tested with ffmpeg 7.1). Exits non-zero if any transcript fails its hash or a listed sample is missing. """ from __future__ import annotations import argparse import csv import hashlib import io import json import shutil import subprocess import sys import tarfile import zipfile from dataclasses import dataclass from pathlib import Path from typing import Callable, Iterator import numpy as np import soundfile as sf SUBSETS = ("jsut", "jvnv", "tedxjp10k", "fleurs", "speech-bsd") SAMPLE_RATE = 16000 FLEURS = {"repo": "google/fleurs", "revision": "70bb2e84b976b7e960aa89f1c648e09c59f894dd", "config": "ja_jp"} SPEECH_BSD = {"repo": "ku-nlp/speech-bsd-hf", "revision": "c925805c8607193b3a89fc705a61bd3647cd31f2"} @dataclass class Upstream: """One upstream sample: its transcript and a loader for its 16 kHz mono audio.""" text: str audio: Callable[[], np.ndarray] # --------------------------------------------------------------------------- # transcripts: hash and patch # --------------------------------------------------------------------------- def text_sha256(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() def apply_patch(text: str, patch: list | None) -> str: """Apply [[start, end, replacement], ...] (code-point offsets into the upstream text, non-overlapping, ascending) from the right.""" for start, end, replacement in reversed(patch or []): text = text[:start] + replacement + text[end:] return text def make_patch(source: str, target: str) -> list | None: """The patch apply_patch(source, patch) == target. Carries only the replacement characters, never the source text.""" import difflib if source == target: return None ops = [[i1, i2, target[j1:j2]] for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, source, target, autojunk=False).get_opcodes() if tag != "equal"] if sum(len(r) for _, _, r in ops) > len(target) / 2: ops = [[0, len(source), target]] # mostly rewritten: one replacement reads better assert apply_patch(source, ops) == target return ops # --------------------------------------------------------------------------- # upstream readers: {upstream_id: Upstream} # --------------------------------------------------------------------------- class Archive: """A corpus zip or the directory it extracts to, read the same way.""" def __init__(self, path: Path): self.path = path self.zip = zipfile.ZipFile(path) if path.is_file() else None def read(self, name: str) -> bytes: if self.zip: return self.zip.read(name) return (self.path / name).read_bytes() def names(self) -> set[str]: if self.zip: return set(self.zip.namelist()) return {str(p.relative_to(self.path)) for p in self.path.rglob("*")} def _decode(data: bytes) -> np.ndarray: """16 kHz mono float32. Other rates and multi-channel audio go through ffmpeg, which is how the benchmark audio was made.""" info = sf.info(io.BytesIO(data)) if info.samplerate == SAMPLE_RATE and info.channels == 1: return sf.read(io.BytesIO(data), dtype="float32")[0] if shutil.which("ffmpeg") is None: raise SystemExit("ffmpeg not found on PATH (needed to resample to 16 kHz)") out = subprocess.run(["ffmpeg", "-v", "error", "-i", "-", "-ar", str(SAMPLE_RATE), "-ac", "1", "-f", "f32le", "-"], input=data, capture_output=True, check=True).stdout return np.frombuffer(out, dtype="float32") def read_jsut(path: Path) -> dict[str, Upstream]: a = Archive(path) root = "jsut_ver1.1/" if a.zip else "" out = {} for line in a.read(f"{root}basic5000/transcript_utf8.txt").decode("utf-8").splitlines(): if line.strip(): uid, text = line.split(":", 1) out[uid] = Upstream(text, lambda u=uid: _decode(a.read(f"{root}basic5000/wav/{u}.wav"))) return out def read_jvnv(path: Path) -> dict[str, Upstream]: # transcription.csv rows are `__||`, # shared by the four speakers; the transcript is the full text. a = Archive(path) root = "jvnv_v1/" if a.zip else "" scripts = {} for line in a.read(f"{root}transcription.csv").decode("utf-8").splitlines(): if line.strip(): key, _nonverbal, text = line.split("|") scripts[key] = text.strip() names = a.names() out = {} for spk in ("F1", "F2", "M1", "M2"): for key, text in scripts.items(): emotion, session, _n = key.split("_") uid = f"{spk}_{key}" name = f"{root}{spk}/{emotion}/{session}/{uid}.wav" if name in names: # not every speaker recorded every script line out[uid] = Upstream(text, lambda n=name: _decode(a.read(n))) return out def read_tedxjp10k(path: Path) -> dict[str, Upstream]: texts = {} for line in (path / "text").read_text(encoding="utf-8").splitlines(): parts = line.split(maxsplit=1) if len(parts) == 2: texts[parts[0]] = parts[1] cache: dict[str, np.ndarray] = {} def cut(video: str, start: float, end: float) -> np.ndarray: if video not in cache: cache.clear() # one video at a time; samples come in video order cache[video] = sf.read(path / "wav" / f"{video}.16k.wav", dtype="int16")[0] x = cache[video] a, b = int(start * SAMPLE_RATE), min(int(end * SAMPLE_RATE), len(x)) return x[a:b].astype("float32") / 32768 out = {} for line in (path / "segments").read_text(encoding="utf-8").splitlines(): uid, video, start, end = line.split() if uid in texts: out[uid] = Upstream(texts[uid], lambda v=video, s=float(start), e=float(end): cut(v, s, e)) return out def _hub(repo: str, filename: str, revision: str) -> str: from huggingface_hub import hf_hub_download return hf_hub_download(repo, filename, repo_type="dataset", revision=revision) def read_fleurs() -> dict[str, Upstream]: rev, cfg = FLEURS["revision"], FLEURS["config"] texts = {} with open(_hub(FLEURS["repo"], f"data/{cfg}/test.tsv", rev), encoding="utf-8") as f: for row in csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE): texts[row[1].removesuffix(".wav")] = row[3] # file name -> transcription audio = {} with tarfile.open(_hub(FLEURS["repo"], f"data/{cfg}/audio/test.tar.gz", rev)) as tf: for m in tf: if m.isfile() and m.name.endswith(".wav"): audio[m.name.rsplit("/", 1)[-1].removesuffix(".wav")] = tf.extractfile(m).read() return {uid: Upstream(text, lambda d=audio[uid]: _decode(d)) for uid, text in texts.items() if uid in audio} def read_speech_bsd() -> dict[str, Upstream]: import pyarrow.parquet as pq from huggingface_hub import HfApi rev = SPEECH_BSD["revision"] files = sorted(f for f in HfApi().list_repo_files(SPEECH_BSD["repo"], repo_type="dataset", revision=rev) if f.startswith("data/test-")) out = {} for f in files: table = pq.read_table(_hub(SPEECH_BSD["repo"], f, rev), columns=["ja_wav", "ja_sentence", "audio"]) for row in table.to_pylist(): if row["ja_wav"]: uid = Path(row["ja_wav"]).stem out[uid] = Upstream(row["ja_sentence"], lambda d=row["audio"]["bytes"]: _decode(d)) return out def read_upstream(subset: str, args) -> dict[str, Upstream]: if subset in ("jsut", "jvnv", "tedxjp10k"): path = getattr(args, subset) if path is None: raise SystemExit(f"{subset}: pass --{subset} (see the dataset card for where to get it)") return {"jsut": read_jsut, "jvnv": read_jvnv, "tedxjp10k": read_tedxjp10k}[subset](path) return read_fleurs() if subset == "fleurs" else read_speech_bsd() # --------------------------------------------------------------------------- # rebuild # --------------------------------------------------------------------------- def rebuild_subset(subset: str, samples: list[dict], upstream: dict[str, Upstream], out: Path | None) -> tuple[list[dict], list[str]]: rows, problems = [], [] for s in samples: u = upstream.get(s["id"]) if u is None: problems.append(f"{s['id']}: not found upstream") continue if text_sha256(u.text) != s["upstream_sha256"]: problems.append(f"{s['id']}: upstream transcript differs from the one this " f"benchmark was built from") continue text = apply_patch(u.text, s.get("patch")) if text_sha256(text) != s["text_sha256"]: problems.append(f"{s['id']}: corrected transcript fails its hash") continue row = {"id": s["id"], "text": text, "duration": s["duration"]} if out is not None: x = u.audio() rel = f"audio/{subset}/{s['id']}.flac" sf.write(out / rel, x, SAMPLE_RATE, format="FLAC", subtype="PCM_16") row = {"id": s["id"], "audio": rel, "text": text, "duration": round(len(x) / SAMPLE_RATE, 4)} rows.append(row) return rows, problems def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--data", type=Path, default=Path(__file__).resolve().parent / "data", help="this dataset's data/ directory (default: next to this script)") ap.add_argument("--out", type=Path, help="output directory (required unless --text-only)") ap.add_argument("--subset", action="append", choices=SUBSETS, help="repeatable; default: all") ap.add_argument("--text-only", action="store_true", help="check transcripts, write no audio") ap.add_argument("--jsut", type=Path) ap.add_argument("--jvnv", type=Path) ap.add_argument("--tedxjp10k", type=Path) args = ap.parse_args(argv) if args.out is None and not args.text_only: ap.error("--out is required unless --text-only") failed = 0 for subset in args.subset or SUBSETS: with open(args.data / subset / "samples.jsonl", encoding="utf-8") as f: samples = [json.loads(line) for line in f if line.strip()] print(f"[{subset}] reading upstream ...", flush=True) upstream = read_upstream(subset, args) audio_out = None if args.text_only else args.out if audio_out is not None: (audio_out / "audio" / subset).mkdir(parents=True, exist_ok=True) rows, problems = rebuild_subset(subset, samples, upstream, audio_out) if args.out is not None: args.out.mkdir(parents=True, exist_ok=True) with open(args.out / f"{subset}.jsonl", "w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(r, ensure_ascii=False) + "\n") for p in problems[:10]: print(f"[{subset}] {p}", file=sys.stderr) print(f"[{subset}] {len(rows)}/{len(samples)} samples rebuilt" + (f", {len(problems)} problems" if problems else ", all transcripts verified"), flush=True) failed += bool(problems) return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())