Datasets:

Languages:
English
License:
sanchit-gandhi HF staff commited on
Commit
575441a
1 Parent(s): 22808fd

from tedlium

Browse files
Files changed (1) hide show
  1. tedlium.py +385 -0
tedlium.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Datasets Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """TED-LIUM speech recognition dataset."""
16
+
17
+ import os
18
+ import re
19
+ from collections import defaultdict
20
+ from io import BytesIO
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+ import soundfile as sf
25
+
26
+ import datasets
27
+ from datasets.tasks import AutomaticSpeechRecognition
28
+
29
+
30
+ _DL_URL = "https://huggingface.co/datasets/LIUM/tedlium/resolve/main/"
31
+
32
+ _LICENSE = "licensed under Creative Commons BY-NC-ND 3.0 (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en)"
33
+
34
+
35
+ class TedliumReleaseConfig(datasets.BuilderConfig):
36
+ """BuilderConfig for a release of the TED-LIUM dataset."""
37
+
38
+ def __init__(self, *, url, download_urls, split_paths, citation, **kwargs):
39
+ super(TedliumReleaseConfig, self).__init__(version=datasets.Version("1.0.1"), **kwargs)
40
+ self.url = url
41
+ self.download_urls = download_urls
42
+ # List of split, path pairs containing the relative path within the
43
+ # extracted tarball to the data for each split.
44
+ self.split_paths = split_paths
45
+ self.citation = citation
46
+
47
+
48
+ def _make_builder_configs():
49
+ """Creates builder configs for all supported Tedlium dataset releases."""
50
+ release1 = TedliumReleaseConfig(
51
+ name="release1",
52
+ description="""\
53
+ The TED-LIUM corpus is English-language TED talks, with transcriptions,
54
+ sampled at 16kHz. It contains about 118 hours of speech.
55
+
56
+ This is the TED-LIUM corpus release 1,
57
+ licensed under Creative Commons BY-NC-ND 3.0
58
+ (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en).
59
+ """,
60
+ citation="""\
61
+ @inproceedings{rousseau2012tedlium,
62
+ title={TED-LIUM: an Automatic Speech Recognition dedicated corpus},
63
+ author={Rousseau, Anthony and Del{\\'e}glise, Paul and Est{\\`e}ve, Yannick},
64
+ booktitle={Conference on Language Resources and Evaluation (LREC)},
65
+ pages={125--129},
66
+ year={2012}
67
+ }
68
+ """,
69
+ url="https://www.openslr.org/7/",
70
+ download_urls={
71
+ "train": [_DL_URL + os.path.join("TEDLIUM_release1", "train.tar.gz")],
72
+ "validation": [_DL_URL + os.path.join("TEDLIUM_release1", "dev.tar.gz")],
73
+ "test": [_DL_URL + os.path.join("TEDLIUM_release1", "test.tar.gz")],
74
+ },
75
+ split_paths=[
76
+ (datasets.Split.TRAIN, "train"),
77
+ (datasets.Split.VALIDATION, "dev"),
78
+ (datasets.Split.TEST, "test"),
79
+ ],
80
+ )
81
+
82
+ release2 = TedliumReleaseConfig(
83
+ name="release2",
84
+ description="""\
85
+ This is the TED-LIUM corpus release 2,
86
+ licensed under Creative Commons BY-NC-ND 3.0
87
+ (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en).
88
+
89
+ All talks and text are property of TED Conferences LLC.
90
+
91
+ The TED-LIUM corpus was made from audio talks and their transcriptions
92
+ available on the TED website. We have prepared and filtered these data
93
+ in order to train acoustic models to participate to the International
94
+ Workshop on Spoken Language Translation 2011 (the LIUM English/French
95
+ SLT system reached the first rank in the SLT task).
96
+
97
+ Contains 1495 talks and transcripts.
98
+ """,
99
+ citation="""\
100
+ @inproceedings{rousseau2014tedlium2,
101
+ title={Enhancing the {TED-LIUM} Corpus with Selected Data for Language Modeling and More {TED} Talks},
102
+ author={Rousseau, Anthony and Del{\\'e}glise, Paul and Est{\\`e}ve, Yannick},
103
+ booktitle={Conference on Language Resources and Evaluation (LREC)},
104
+ year={2014}
105
+ }
106
+ """,
107
+ url="https://www.openslr.org/19/",
108
+ download_urls={
109
+ "train": [
110
+ _DL_URL + os.path.join("TEDLIUM_release2", "train_1.tar.gz"),
111
+ _DL_URL + os.path.join("TEDLIUM_release2", "train_2.tar.gz"),
112
+ ],
113
+ "validation": [_DL_URL + os.path.join("TEDLIUM_release2", "dev.tar.gz")],
114
+ "test": [_DL_URL + os.path.join("TEDLIUM_release2", "test.tar.gz")],
115
+ },
116
+ split_paths=[
117
+ (datasets.Split.TRAIN, "train"),
118
+ (datasets.Split.VALIDATION, "dev"),
119
+ (datasets.Split.TEST, "test"),
120
+ ],
121
+ )
122
+
123
+ release3 = TedliumReleaseConfig(
124
+ name="release3",
125
+ description="""\
126
+ This is the TED-LIUM corpus release 3, licensed under Creative Commons
127
+ BY-NC-ND 3.0. This is the 'legacy' version of the corpus, in which the dev and test datasets are the same as in
128
+ TED-LIUM 2 (and TED-LIUM 1).
129
+
130
+ All talks and text are property of TED Conferences LLC.
131
+
132
+ This new TED-LIUM release was made through a collaboration between the
133
+ Ubiqus company and the LIUM (University of Le Mans, France)
134
+
135
+ Contents:
136
+
137
+ - 2351 audio talks in NIST sphere format (SPH), including talks from
138
+ TED-LIUM 2: be careful, same talks but not same audio files (only
139
+ these audio file must be used with the TED-LIUM 3 STM files)
140
+ - 452 hours of audio
141
+ - 2351 aligned automatic transcripts in STM format
142
+ - TEDLIUM 2 dev and test data: 19 TED talks in SPH format with
143
+ corresponding manual transcriptions.
144
+ - Dictionary with pronunciations (159848 entries), same file as the one
145
+ included in TED-LIUM 2
146
+ - Selected monolingual data for language modeling from WMT12 publicly
147
+ available corpora: these files come from the TED-LIUM 2 release, but
148
+ have been modified to get a tokenization more relevant for English
149
+ language
150
+
151
+ """,
152
+ citation="""\
153
+ @inproceedings{hernandez2018tedlium3,
154
+ title={TED-LIUM 3: twice as much data and corpus repartition for experiments on speaker adaptation},
155
+ author={Hernandez, Fran{\\c{c}}ois and Nguyen, Vincent and Ghannay, Sahar and Tomashenko, Natalia and Est{\\`e}ve, Yannick},
156
+ booktitle={International Conference on Speech and Computer},
157
+ pages={198--208},
158
+ year={2018},
159
+ organization={Springer}
160
+ }
161
+ """,
162
+ url="https://www.openslr.org/51/",
163
+ download_urls={
164
+ "train": [
165
+ _DL_URL + os.path.join("TEDLIUM_release3", "legacy", "train_1.tar.gz"),
166
+ _DL_URL + os.path.join("TEDLIUM_release3", "legacy", "train_2.tar.gz"),
167
+ ],
168
+ "validation": [_DL_URL + os.path.join("TEDLIUM_release3", "legacy", "dev.tar.gz")],
169
+ "test": [_DL_URL + os.path.join("TEDLIUM_release3", "legacy", "test.tar.gz")],
170
+ },
171
+ split_paths=[
172
+ (datasets.Split.TRAIN, "train"),
173
+ (datasets.Split.VALIDATION, "dev"),
174
+ (datasets.Split.TEST, "test"),
175
+ ],
176
+ )
177
+
178
+ release3_speaker_adaptation = TedliumReleaseConfig(
179
+ name="release3-speaker-adaptation",
180
+ description="""\
181
+ This is the TED-LIUM corpus release 3, licensed under Creative Commons
182
+ BY-NC-ND 3.0. This is the 'speaker adaptation' version of the corpus, specially designed for experiments on
183
+ speaker adaptation.
184
+
185
+ All talks and text are property of TED Conferences LLC.
186
+
187
+ This new TED-LIUM release was made through a collaboration between the
188
+ Ubiqus company and the LIUM (University of Le Mans, France)
189
+ """,
190
+ citation="""\
191
+ @inproceedings{hernandez2018tedlium3,
192
+ title={TED-LIUM 3: twice as much data and corpus repartition for experiments on speaker adaptation},
193
+ author={Hernandez, Fran{\\c{c}}ois and Nguyen, Vincent and Ghannay, Sahar and Tomashenko, Natalia and Est{\\`e}ve, Yannick},
194
+ booktitle={International Conference on Speech and Computer},
195
+ pages={198--208},
196
+ year={2018},
197
+ organization={Springer}
198
+ }
199
+ """,
200
+ url="https://www.openslr.org/51/",
201
+ download_urls={
202
+ "train": [
203
+ _DL_URL + os.path.join("TEDLIUM_release3", "speaker-adaptation", "train_1.tar.gz"),
204
+ _DL_URL + os.path.join("TEDLIUM_release3", "speaker-adaptation", "train_2.tar.gz"),
205
+ ],
206
+ "validation": [_DL_URL + os.path.join("TEDLIUM_release3", "speaker-adaptation", "dev.tar.gz")],
207
+ "test": [_DL_URL + os.path.join("TEDLIUM_release3", "speaker-adaptation", "test.tar.gz")],
208
+ },
209
+ split_paths=[
210
+ (datasets.Split.TRAIN, "train"),
211
+ (datasets.Split.VALIDATION, "dev"),
212
+ (datasets.Split.TEST, "test"),
213
+ ],
214
+ )
215
+
216
+ return [release1, release2, release3, release3_speaker_adaptation]
217
+
218
+
219
+ class TedLium(datasets.GeneratorBasedBuilder):
220
+ """The TED-LIUM corpus is English-language TED talks, with transcriptions, sampled at 16kHz. It contains about 118 hours of speech."""
221
+
222
+ VERSION = datasets.Version("1.1.0")
223
+
224
+ BUILDER_CONFIGS = _make_builder_configs()
225
+
226
+ def _info(self):
227
+ features = datasets.Features(
228
+ {
229
+ "audio": datasets.features.Audio(sampling_rate=16_000),
230
+ "text": datasets.Value("string"),
231
+ "speaker_id": datasets.Value("string"),
232
+ "gender": datasets.features.ClassLabel(names=["unknown", "female", "male"]),
233
+ "file": datasets.Value("string"),
234
+ "id": datasets.Value("string"),
235
+ }
236
+ )
237
+ return datasets.DatasetInfo(
238
+ description=self.config.description,
239
+ features=features,
240
+ supervised_keys=("audio", "text"),
241
+ homepage=self.config.url,
242
+ license=_LICENSE,
243
+ citation=self.config.citation,
244
+ task_templates=[AutomaticSpeechRecognition(audio_column="audio", transcription_column="text")],
245
+ )
246
+
247
+ def _split_generators(self, dl_manager):
248
+ archive_path = dl_manager.download(self.config.download_urls)
249
+ # (Optional) In non-streaming mode, we can extract the archive locally to have actual local audio files:
250
+ local_extracted_archive = dl_manager.extract(archive_path) if not dl_manager.is_streaming else {}
251
+ splits = []
252
+ for split, path in self.config.split_paths:
253
+ kwargs = {
254
+ "filepath": [dl_manager.iter_archive(sharded_path) for sharded_path in archive_path[split]],
255
+ "local_extracted_archive": local_extracted_archive.get(split),
256
+ "split_path": path,
257
+ }
258
+ splits.append(datasets.SplitGenerator(name=split, gen_kwargs=kwargs))
259
+ return splits
260
+
261
+ def _generate_examples(self, filepath, local_extracted_archive, split_path):
262
+ """Generate examples from a TED-LIUM stm file."""
263
+ if local_extracted_archive:
264
+ for local_archive in local_extracted_archive:
265
+ # The stm directory houses the speaker and transcription information in .stm format
266
+ split_dir = os.path.join(local_archive, split_path)
267
+ stm_files = [os.path.join(split_dir, f) for f in os.listdir(split_dir) if f.endswith(".stm")]
268
+ for file in stm_files:
269
+ # the .sph speaker file almost always has the same file name as the .stm file
270
+ speaker_file = Path(file).stem
271
+ audio_file = os.path.join(split_dir, speaker_file + ".sph")
272
+ segment, sampling_rate = sf.read(audio_file, dtype=np.int16)
273
+ with open(file) as f:
274
+ for line in f:
275
+ line = line.strip()
276
+ fn, channel, speaker, start, end, label, transcript = line.split(" ", 6)
277
+ transcript = _maybe_trim_suffix(transcript)
278
+ if speaker_file != fn:
279
+ # handle the case where the stm file does not have the same file name as the transcript
280
+ speaker_file = fn
281
+ audio_file = os.path.join(split_dir, speaker_file + ".sph")
282
+ segment, sampling_rate = sf.read(audio_file, dtype=np.int16)
283
+ samples = _extract_audio_segment(segment, sampling_rate, float(start), float(end))
284
+ key = "-".join([speaker, start, end, label])
285
+ example = {
286
+ "audio": {"path": audio_file, "array": samples, "sampling_rate": sampling_rate},
287
+ "text": transcript,
288
+ "speaker_id": speaker,
289
+ "gender": _parse_gender(label),
290
+ "file": audio_file,
291
+ "id": key,
292
+ }
293
+ yield key, example
294
+
295
+ else:
296
+ audio_data = {}
297
+ transcripts = defaultdict(list)
298
+ for file in filepath:
299
+ for path, f in file:
300
+ if path.endswith(".sph"):
301
+ # get the speaker id
302
+ fn = path.split("/")[-1].strip(".sph")
303
+ # read the audio data from raw byte form and add key-value pair to dict
304
+ audio_data[fn] = sf.read(BytesIO(f.read()), dtype=np.int16)
305
+ elif path.endswith(".stm"):
306
+ for line in f:
307
+ if line:
308
+ line = line.decode("utf-8").strip()
309
+ fn, channel, speaker, start, end, label, transcript = line.split(" ", 6)
310
+ transcript = _maybe_trim_suffix(transcript)
311
+ audio_file = path.replace("stm", "sph")
312
+ key = "-".join([speaker, start, end, label])
313
+ # append metadata information to the dict of transcripts for the associated speaker
314
+ transcripts[fn].append(
315
+ {
316
+ "text": transcript,
317
+ "speaker_id": speaker,
318
+ "gender": _parse_gender(label),
319
+ "file": audio_file,
320
+ "id": key,
321
+ "start": start,
322
+ "end": end,
323
+ "channel": channel,
324
+ "fn": fn,
325
+ }
326
+ )
327
+
328
+ if audio_data and audio_data.keys() == transcripts.keys():
329
+ for fn, speaker in transcripts.items():
330
+ for transcript in speaker:
331
+ segment, sampling_rate = audio_data[transcript["fn"]]
332
+ samples = _extract_audio_segment(
333
+ segment,
334
+ sampling_rate,
335
+ float(transcript["start"]),
336
+ float(transcript["end"]),
337
+ )
338
+ audio = {"path": transcript["file"], "array": samples, "sampling_rate": sampling_rate}
339
+ key = transcript["id"]
340
+ yield key, {
341
+ "audio": audio,
342
+ "text": transcript["text"],
343
+ "speaker_id": transcript["speaker_id"],
344
+ "gender": transcript["gender"],
345
+ "file": transcript["file"],
346
+ "id": transcript["id"],
347
+ }
348
+ audio_data = {}
349
+ transcripts = defaultdict(list)
350
+
351
+
352
+ def _maybe_trim_suffix(transcript):
353
+ # stm files for the TEDLIUM release 1 train split contain a key (enclosed in
354
+ # parens) at the end.
355
+ splits = transcript.rsplit(" ", 1)
356
+ transcript = splits[0]
357
+ if len(splits) > 1:
358
+ suffix = splits[-1]
359
+ if not suffix.startswith("("):
360
+ transcript += " " + suffix
361
+ return transcript
362
+
363
+
364
+ def _extract_audio_segment(segment, sampling_rate, start_sec, end_sec):
365
+ """Extracts segment of audio samples (as an ndarray) from the given segment."""
366
+ # The dataset only contains mono audio.
367
+ start_sample = int(start_sec * sampling_rate)
368
+ end_sample = min(int(end_sec * sampling_rate), segment.shape[0])
369
+ samples = segment[start_sample:end_sample]
370
+ return samples
371
+
372
+
373
+ def _parse_gender(label_str):
374
+ """Parse gender string from STM "<label>" field."""
375
+ gender = re.split(",|_", label_str)[-1][:-1]
376
+ # Fix inconsistencies in the data.
377
+ if not gender:
378
+ gender = -1 # Missing label.
379
+ elif gender == "<NA": # In TEDLIUM release 3 training data.
380
+ gender = -1 # Missing label.
381
+ elif gender == "F":
382
+ gender = "female"
383
+ elif gender == "M":
384
+ gender = "male"
385
+ return gender