"""Prepare the official LibriSpeech test-clean split with its 2,620 references.""" import hashlib import json import tarfile import urllib.request from pathlib import Path from .sources import ROOT ARCHIVE_URL = "https://openslr.trmal.net/resources/12/test-clean.tar.gz" ARCHIVE_MD5 = "32fa31d27d2e1cad72775fee3f4849a9" def verify_archive(archive): digest = hashlib.md5() with archive.open("rb") as source: for chunk in iter(lambda: source.read(1 << 22), b""): digest.update(chunk) if digest.hexdigest() != ARCHIVE_MD5: raise ValueError("LibriSpeech archive checksum differs from OpenSLR") def prepare(destination): destination.mkdir(parents=True, exist_ok=True) archive = destination / "test-clean.tar.gz" if not archive.is_file(): temporary = archive.with_suffix(".gz.tmp") with urllib.request.urlopen(ARCHIVE_URL, timeout=120) as response, temporary.open("wb") as out: while chunk := response.read(1 << 22): out.write(chunk) verify_archive(temporary) temporary.replace(archive) else: verify_archive(archive) audio = destination / "audio" audio.mkdir(exist_ok=True) refs, recordings = {}, {} with tarfile.open(archive, "r:gz") as tar: for member in tar: name = Path(member.name).name if not member.isfile(): continue if name.endswith(".trans.txt"): for line in tar.extractfile(member).read().decode("ascii").splitlines(): identifier, reference = line.split(" ", maxsplit=1) refs[identifier] = reference elif name.endswith(".flac"): data = tar.extractfile(member).read() (audio / name).write_bytes(data) recordings[Path(name).stem] = { "audio": f"audio/{name}", "audio_sha256": hashlib.sha256(data).hexdigest(), } if len(refs) != 2620 or refs.keys() != recordings.keys(): raise ValueError("Expected all 2,620 LibriSpeech clean test utterances") manifest = destination / "test.jsonl" with manifest.open("w") as out: for identifier, reference in sorted(refs.items()): row = {"id": identifier, "reference": reference, **recordings[identifier]} out.write(json.dumps(row) + "\n") return manifest if __name__ == "__main__": print(prepare(ROOT / "data/bench/librispeech"))