ilyakam commited on
Commit
3f8a4d0
·
1 Parent(s): dcaa3e9

chore(*): initial commit

Browse files

Explain the purpose of this repo by updating the `README`.
Add `.editorconfig` to keep a consistent style.
Add `process.py` to actually convert the dataset.
Include instructions on how to actually create this dataset.

Files changed (4) hide show
  1. .editorconfig +15 -0
  2. README.md +87 -3
  3. process.py +330 -0
  4. requirements.txt +4 -0
.editorconfig ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = space
5
+ indent_size = 2
6
+ end_of_line = lf
7
+ charset = utf-8
8
+ trim_trailing_whitespace = true
9
+ insert_final_newline = true
10
+
11
+ [*md]
12
+ trim_trailing_whitespace = false
13
+
14
+ [*py]
15
+ indent_size = 4
README.md CHANGED
@@ -1,3 +1,87 @@
1
- ---
2
- license: cc-by-4.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ ---
4
+
5
+ # LibriSpeech-Long
6
+
7
+ LibriSpeech-Long is a benchmark dataset for long-form speech generation and processing. Released as part of "Long-Form Speech Generation with Spoken Language Models" (arXiv 2024).
8
+
9
+ ## Prerequisites
10
+
11
+ 1. [uv](https://docs.astral.sh/uv/)
12
+
13
+ ## Development
14
+
15
+ 1. Clone the repo
16
+ ```sh
17
+ git clone git@hf.co:datasets/ilyakam/librispeech-long && cd librispeech-long
18
+ ```
19
+
20
+ 1. Activate the virtual environment:
21
+ ```sh
22
+ source .venv/bin/activate
23
+ ```
24
+
25
+ 1. Install dependencies:
26
+ ```sh
27
+ uv pip install -r requirements.txt
28
+ ```
29
+
30
+ 1. Process the dataset:
31
+ ```sh
32
+ python process.py [SOURCE_ROOT] . --limit-speakers
33
+ ```
34
+
35
+ Notes:
36
+ - The `SOURCE_ROOT` is a folder where you've extracted the dataset containing the splits `dev-clean`, `dev-other`, `test-clean`, and `test-other`.
37
+ - The optional `--limit-speakers` flag will only process the first speaker directory in each split for quick testing.
38
+
39
+ 1. Copy the metadata to the top of this `README.md` file.
40
+
41
+ 1. Commit and push the generated `*.parquet` files and the updated `README.md` file.
42
+
43
+
44
+ ## Purpose
45
+
46
+ To migrate the [google-deepmind/librispeech-long](https://github.com/google-deepmind/librispeech-long) dataset to Hugging Face datasets.
47
+
48
+ ## Original
49
+
50
+ **[Download audio, ground-truth transcripts, and per-file durations for all splits (3GB).](https://storage.googleapis.com/librispeech_long/v0_1.tar.gz)**
51
+
52
+ This is a benchmark dataset for evaluating long-form variants of speech processing tasks such as speech continuation, speech recognition, and text-to-speech synthesis. It is derived from the [LibriSpeech](https://www.openslr.org/12) dev and test sets, whose utterances are reprocessed into contiguous examples of up to 4 minutes in length (in the manner of [LibriLight's `cut_by_vad.py` script](https://github.com/facebookresearch/libri-light/blob/main/data_preparation/cut_by_vad.py)).
53
+
54
+ **For more details:** see "Long-Form Speech Generation with Spoken Language Models" ([paper](https://arxiv.org/abs/2412.18603), [website](https://google.github.io/tacotron/publications/speechssm/)).
55
+
56
+ *This is part of a preprint that is work-in-progress; dataset may be subject to change.*
57
+
58
+ ## Citation
59
+
60
+ When using this dataset, please cite the associated [paper](https://arxiv.org/abs/2412.18603):
61
+
62
+ ```
63
+ @article{park2024long,
64
+ author = {Se Jin Park and
65
+ Julian Salazar and
66
+ Aren Jansen and
67
+ Keisuke Kinoshita and
68
+ Yong Man Ro and
69
+ R. J. Skerry{-}Ryan},
70
+ title = {Long-Form Speech Generation with Spoken Language Models},
71
+ journal = {CoRR},
72
+ volume = {abs/2412.18603},
73
+ year = {2024}
74
+ }
75
+ ```
76
+
77
+ ## License and disclaimer
78
+
79
+ Copyright 2024 DeepMind Technologies Limited
80
+
81
+ The software and materials, except for the underlying LibriSpeech data, are licensed under the Creative Commons Attribution 4.0 International License (CC-BY). You may obtain a copy of the CC-BY license at: https://creativecommons.org/licenses/by/4.0/legalcode, or in the LICENSE file.
82
+
83
+ The materials contain adapted material from the LibriSpeech dataset. LibriSpeech is also licensed under the Creative Commons Attribution 4.0 International License (CC-BY). You may obtain a copy of the CC-BY license at: https://creativecommons.org/licenses/by/4.0/legalcode, or in the LICENSE file. LibriSpeech is available at https://www.openslr.org/12 and created by Vassil Panayotov, Guoguo Chen, Daniel Povey and Sanjeev Khudanpur, pursuant to the paper “LibriSpeech: an ASR corpus based on public domain audio books", ICASSP 2015 (https://ieeexplore.ieee.org/document/7178964).
84
+
85
+ Unless required by applicable law or agreed to in writing, all software and materials distributed here under the CC-BY licenses are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the licenses for the specific language governing permissions and limitations under those licenses.
86
+
87
+ This is not an official Google product.
process.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Processes the DeepMind LibriSpeech-Long dataset into Parquet files
4
+ for Hugging Face Hub compatibility.
5
+
6
+ This script converts FLAC audio files to WAV format in-memory,
7
+ gathers metadata, and saves the data into Parquet files, one for each split.
8
+ It also generates the necessary YAML front-matter for the README.md file
9
+ on the Hugging Face Hub, ensuring the dataset is correctly displayed,
10
+ especially in the Data Studio.
11
+
12
+ Example Usage:
13
+ python process.py \
14
+ /path/to/source/librispeech-long \
15
+ /path/to/your/cloned-hf-repo
16
+
17
+ To process only a small subset for testing:
18
+ python process.py \
19
+ /path/to/source/librispeech-long \
20
+ /path/to/your/cloned-hf-repo \
21
+ --limit-speakers
22
+ """
23
+ import argparse
24
+ import re
25
+ import shutil
26
+ import subprocess
27
+ from dataclasses import dataclass
28
+ from pathlib import Path
29
+ from typing import Dict, List, Optional, Tuple
30
+
31
+ from datasets import Audio, Dataset, Features, Value
32
+ from tqdm import tqdm
33
+
34
+ # --- Configuration ---
35
+
36
+ # Config name on the Hub.
37
+ CONFIG_NAME = "librispeech_long"
38
+
39
+ # Parquet files will be written under this subfolder in the repo.
40
+ OUTPUT_SUBDIR = CONFIG_NAME
41
+
42
+ # Map source split directory names to the desired Hugging Face Hub split names.
43
+ # Using underscores instead of dots is safer for the Hub's Data Studio.
44
+ SPLIT_MAP: Dict[str, str] = {
45
+ "dev-clean": "dev_clean",
46
+ "dev-other": "dev_other",
47
+ "test-clean": "test_clean",
48
+ "test-other": "test_other",
49
+ }
50
+
51
+ # Dataset string stored in the "dataset" column of the Parquet file.
52
+ DATASET_NAME = "librispeech-long"
53
+
54
+ # Parquet filename template.
55
+ FILENAME_TEMPLATE = "{split}-00000-of-00001.parquet"
56
+
57
+ # Audio conversion settings.
58
+ TARGET_SR = 16000
59
+ TARGET_CHANNELS = 1
60
+ TARGET_CODEC = "pcm_s16le"
61
+
62
+ # --- Data Structures ---
63
+
64
+ @dataclass
65
+ class Row:
66
+ """Represents a single row in the dataset."""
67
+ audio_bytes: bytes
68
+ dataset: str
69
+ text: str
70
+ id: str
71
+ audio_length_s: float
72
+
73
+ # --- Helper Functions ---
74
+
75
+ def check_ffmpeg() -> None:
76
+ """Checks if ffmpeg and ffprobe are installed and available on PATH."""
77
+ for bin_name in ("ffmpeg", "ffprobe"):
78
+ try:
79
+ subprocess.run(
80
+ [bin_name, "-version"],
81
+ check=True,
82
+ stdout=subprocess.DEVNULL,
83
+ stderr=subprocess.DEVNULL,
84
+ )
85
+ except FileNotFoundError:
86
+ raise RuntimeError(
87
+ f"'{bin_name}' not found on PATH. Please install FFmpeg and retry."
88
+ )
89
+
90
+ def cleanup_outputs(target_dir: Path, clean: bool) -> None:
91
+ """Removes old Parquet files and temporary directories."""
92
+ if not clean:
93
+ return
94
+
95
+ output_path = target_dir / OUTPUT_SUBDIR
96
+ if output_path.exists():
97
+ print(f"[INFO] Cleaning up old output directory: {output_path}")
98
+ shutil.rmtree(output_path)
99
+
100
+ # Clean up any old temporary directories from previous runs
101
+ for p in target_dir.glob(".tmp_write_*"):
102
+ try:
103
+ shutil.rmtree(p, ignore_errors=True)
104
+ except Exception:
105
+ pass
106
+
107
+ def find_first_speaker_dir(split_dir: Path) -> Optional[Path]:
108
+ """Finds the first speaker directory within a split directory."""
109
+ if not split_dir.is_dir():
110
+ return None
111
+ speakers = sorted(p for p in split_dir.iterdir() if p.is_dir())
112
+ return speakers[0] if speakers else None
113
+
114
+ def collect_flac_pairs(root: Path) -> List[Tuple[Path, Path]]:
115
+ """Collects pairs of FLAC audio files and their corresponding text files."""
116
+ pairs: List[Tuple[Path, Path]] = []
117
+ for flac in sorted(root.rglob("*.flac")):
118
+ txt = flac.with_suffix(".txt")
119
+ if txt.exists():
120
+ pairs.append((flac, txt))
121
+ return pairs
122
+
123
+ def ffmpeg_flac_to_wav_bytes(flac_path: Path) -> bytes:
124
+ """Converts a FLAC file to WAV format bytes using ffmpeg."""
125
+ cmd = [
126
+ "ffmpeg", "-v", "error", "-i", str(flac_path),
127
+ "-ac", str(TARGET_CHANNELS), "-ar", str(TARGET_SR),
128
+ "-f", "wav", "-acodec", TARGET_CODEC, "pipe:1",
129
+ ]
130
+ proc = subprocess.run(cmd, check=True, capture_output=True)
131
+ return proc.stdout
132
+
133
+ def ffprobe_duration_seconds(audio_path: Path) -> float:
134
+ """Gets the duration of an audio file in seconds using ffprobe."""
135
+ cmd = [
136
+ "ffprobe", "-v", "error", "-show_entries", "format=duration",
137
+ "-of", "default=noprint_wrappers=1:nokey=1", str(audio_path),
138
+ ]
139
+ proc = subprocess.run(cmd, check=True, capture_output=True, text=True)
140
+ try:
141
+ return float(proc.stdout.strip())
142
+ except (ValueError, TypeError):
143
+ return 0.0
144
+
145
+ def make_id_from_path(flac_path: Path, split_dir: Path) -> str:
146
+ """Creates a unique ID from the file path, e.g., '1272-128104-0000'."""
147
+ rel_path = flac_path.relative_to(split_dir)
148
+ parts = rel_path.parts
149
+ if len(parts) < 3:
150
+ return flac_path.stem.replace("_", "-")
151
+
152
+ speaker, session, stem_with_ext = parts[0], parts[1], parts[-1]
153
+ stem = Path(stem_with_ext).stem
154
+
155
+ match = re.match(r"^\d+_(\d+)$", stem)
156
+ utt_id = match.group(1) if match else stem.replace('_', '-')
157
+ return f"{speaker}-{session}-{utt_id}"
158
+
159
+ def read_text(txt_path: Path) -> str:
160
+ """Reads the text from a transcript file."""
161
+ return txt_path.read_text(encoding="utf-8").strip()
162
+
163
+ def rows_for_split(source_split_path: Path, limit_speakers: bool) -> List[Row]:
164
+ """Generates a list of Row objects for a given data split."""
165
+ if not source_split_path.exists():
166
+ print(f"[WARN] Source split directory not found: {source_split_path}")
167
+ return []
168
+
169
+ if limit_speakers:
170
+ spk_dir = find_first_speaker_dir(source_split_path)
171
+ if spk_dir is None:
172
+ print(f"[WARN] No speaker directories in {source_split_path}")
173
+ return []
174
+ roots_to_process = [spk_dir]
175
+ print(f"[INFO] Using speaker subset for {source_split_path.name}: {spk_dir.name}")
176
+ else:
177
+ roots_to_process = [p for p in source_split_path.iterdir() if p.is_dir()]
178
+
179
+ file_pairs = []
180
+ for root in roots_to_process:
181
+ file_pairs.extend(collect_flac_pairs(root))
182
+
183
+ rows: List[Row] = []
184
+ for flac_path, txt_path in tqdm(file_pairs, desc=f"{source_split_path.name}: converting", unit="file"):
185
+ rows.append(Row(
186
+ audio_bytes=ffmpeg_flac_to_wav_bytes(flac_path),
187
+ dataset=DATASET_NAME,
188
+ text=read_text(txt_path),
189
+ id=make_id_from_path(flac_path, source_split_path),
190
+ audio_length_s=ffprobe_duration_seconds(flac_path),
191
+ ))
192
+
193
+ rows.sort(key=lambda r: r.id)
194
+ return rows
195
+
196
+ def build_parquet_dataset(rows: List[Row]) -> Dataset:
197
+ """
198
+ Builds a Hugging Face Dataset with the correct Audio feature type.
199
+ This ensures the Parquet file has the right schema (a STRUCT for audio)
200
+ for the Hugging Face Data Studio to interpret it correctly.
201
+ """
202
+ features = Features({
203
+ "audio": Audio(sampling_rate=TARGET_SR, decode=False),
204
+ "dataset": Value("string"),
205
+ "text": Value("string"),
206
+ "id": Value("string"),
207
+ "audio_length_s": Value("float64"),
208
+ })
209
+
210
+ data_list = [
211
+ {
212
+ "audio": {"bytes": r.audio_bytes, "path": None},
213
+ "dataset": r.dataset,
214
+ "text": r.text,
215
+ "id": r.id,
216
+ "audio_length_s": r.audio_length_s,
217
+ }
218
+ for r in rows
219
+ ]
220
+ return Dataset.from_list(data_list, features=features)
221
+
222
+
223
+ def write_split(ds: Dataset, out_path: Path) -> Tuple[int, int]:
224
+ """Writes a Dataset split to a Parquet file."""
225
+ out_path.parent.mkdir(parents=True, exist_ok=True)
226
+ if out_path.exists():
227
+ out_path.unlink()
228
+ ds.to_parquet(str(out_path))
229
+ return ds.num_rows, out_path.stat().st_size
230
+
231
+ def format_yaml_block(stats: Dict[str, Dict[str, float]]) -> str:
232
+ """Generates the YAML front-matter for the README.md file."""
233
+ download_size = sum(int(v["num_bytes"]) for v in stats.values())
234
+
235
+ lines = [
236
+ "---",
237
+ "license: cc-by-4.0",
238
+ "dataset_info:",
239
+ f"- config_name: {CONFIG_NAME}",
240
+ " features:",
241
+ " - name: audio",
242
+ " dtype:",
243
+ " audio:",
244
+ f" sampling_rate: {TARGET_SR}",
245
+ " - name: dataset",
246
+ " dtype: string",
247
+ " - name: text",
248
+ " dtype: string",
249
+ " - name: id",
250
+ " dtype: string",
251
+ " - name: audio_length_s",
252
+ " dtype: float64",
253
+ " splits:",
254
+ ]
255
+
256
+ for hub_split, vals in sorted(stats.items()):
257
+ lines.append(f" - name: {hub_split}")
258
+ lines.append(f" num_bytes: {float(vals['num_bytes'])}")
259
+ lines.append(f" num_examples: {int(vals['num_examples'])}")
260
+
261
+ lines.extend([
262
+ f" download_size: {download_size}",
263
+ f" dataset_size: {download_size}",
264
+ "configs:",
265
+ f"- config_name: {CONFIG_NAME}",
266
+ " data_files:",
267
+ ])
268
+
269
+ for hub_split in sorted(stats.keys()):
270
+ path_pattern = f"{OUTPUT_SUBDIR}/{hub_split}-*"
271
+ lines.append(f" - split: {hub_split}")
272
+ lines.append(f" path: {path_pattern}")
273
+
274
+ lines.append("---")
275
+ return "\n".join(lines)
276
+
277
+ def main() -> None:
278
+ """Main function to run the data processing pipeline."""
279
+ parser = argparse.ArgumentParser(
280
+ description="Process LibriSpeech-Long dataset for Hugging Face Hub."
281
+ )
282
+ parser.add_argument(
283
+ "source_root", type=Path, help="Path to the source data directory (e.g., '.../librispeech-long')."
284
+ )
285
+ parser.add_argument(
286
+ "target_repo_root", type=Path, help="Path to your cloned Hugging Face dataset repository."
287
+ )
288
+ parser.add_argument(
289
+ "--limit-speakers", action="store_true", help="Only process the first speaker per split for quick testing."
290
+ )
291
+ parser.add_argument(
292
+ "--no-clean", dest="clean", action="store_false", help="Do not clean up old output files before running."
293
+ )
294
+ args = parser.parse_args()
295
+
296
+ check_ffmpeg()
297
+ cleanup_outputs(args.target_repo_root, args.clean)
298
+
299
+ out_dir = args.target_repo_root / OUTPUT_SUBDIR
300
+ out_dir.mkdir(parents=True, exist_ok=True)
301
+
302
+ all_stats: Dict[str, Dict[str, float]] = {}
303
+
304
+ for src_split, hub_split in SPLIT_MAP.items():
305
+ source_split_path = args.source_root / src_split
306
+ rows = rows_for_split(source_split_path, args.limit_speakers)
307
+ if not rows:
308
+ print(f"[WARN] No rows found for split '{src_split}', skipping.")
309
+ continue
310
+
311
+ ds = build_parquet_dataset(rows)
312
+ out_name = FILENAME_TEMPLATE.format(split=hub_split)
313
+ out_path = out_dir / out_name
314
+
315
+ print(f"[INFO] Writing {hub_split} -> {out_path}")
316
+ num_examples, num_bytes = write_split(ds, out_path)
317
+ all_stats[hub_split] = {
318
+ "num_examples": num_examples,
319
+ "num_bytes": num_bytes,
320
+ }
321
+ print(f"[INFO] {hub_split}: examples={num_examples}, bytes={num_bytes}")
322
+
323
+ print("\n" + "="*60)
324
+ print("=== Paste this YAML at the top of your README.md ===")
325
+ print("="*60)
326
+ print(format_yaml_block(all_stats))
327
+ print("="*60)
328
+
329
+ if __name__ == "__main__":
330
+ main()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ datasets
2
+ pyarrow
3
+ soundfile
4
+ tqdm