sanchit-gandhi HF staff commited on
Commit
e3615e7
1 Parent(s): 8b016b1

Upload tedlium.py

Browse files
Files changed (1) hide show
  1. tedlium.py +272 -0
tedlium.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import numpy as np
20
+
21
+
22
+ import datasets
23
+ from datasets.tasks import AutomaticSpeechRecognition
24
+
25
+ from pydub import AudioSegment
26
+
27
+ _LICENSE = "licensed under Creative Commons BY-NC-ND 3.0 (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en)"
28
+
29
+ class TedliumReleaseConfig(datasets.BuilderConfig):
30
+ """BuilderConfig for a release of the TED-LIUM dataset."""
31
+
32
+ def __init__(self, *, url, download_url, split_paths, citation, **kwargs):
33
+ super(TedliumReleaseConfig, self).__init__(
34
+ version=datasets.Version("1.0.1"), **kwargs)
35
+ self.url = url
36
+ self.download_url = download_url
37
+ # List of split, path pairs containing the relative path within the
38
+ # extracted tarball to the data for each split.
39
+ self.split_paths = split_paths
40
+ self.citation = citation
41
+
42
+
43
+ def _make_builder_configs():
44
+ """Creates builder configs for all supported Tedlium dataset releases."""
45
+ release1 = TedliumReleaseConfig(
46
+ name="release1",
47
+ description="""\
48
+ The TED-LIUM corpus is English-language TED talks, with transcriptions,
49
+ sampled at 16kHz. It contains about 118 hours of speech.
50
+
51
+ This is the TED-LIUM corpus release 1,
52
+ licensed under Creative Commons BY-NC-ND 3.0
53
+ (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en).
54
+ """,
55
+ citation="""\
56
+ @inproceedings{rousseau2012tedlium,
57
+ title={TED-LIUM: an Automatic Speech Recognition dedicated corpus},
58
+ author={Rousseau, Anthony and Del{\\'e}glise, Paul and Est{\\`e}ve, Yannick},
59
+ booktitle={Conference on Language Resources and Evaluation (LREC)},
60
+ pages={125--129},
61
+ year={2012}
62
+ }
63
+ """,
64
+ url="https://www.openslr.org/7/",
65
+ download_url="http://www.openslr.org/resources/7/TEDLIUM_release1.tar.gz",
66
+ split_paths=[(datasets.Split.TRAIN, os.path.join("TEDLIUM_release1",
67
+ "train")),
68
+ (datasets.Split.VALIDATION,
69
+ os.path.join("TEDLIUM_release1", "dev")),
70
+ (datasets.Split.TEST, os.path.join("TEDLIUM_release1", "test"))])
71
+
72
+ release2 = TedliumReleaseConfig(
73
+ name="release2",
74
+ description="""\
75
+ This is the TED-LIUM corpus release 2,
76
+ licensed under Creative Commons BY-NC-ND 3.0
77
+ (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en).
78
+
79
+ All talks and text are property of TED Conferences LLC.
80
+
81
+ The TED-LIUM corpus was made from audio talks and their transcriptions
82
+ available on the TED website. We have prepared and filtered these data
83
+ in order to train acoustic models to participate to the International
84
+ Workshop on Spoken Language Translation 2011 (the LIUM English/French
85
+ SLT system reached the first rank in the SLT task).
86
+
87
+ Contains 1495 talks and transcripts.
88
+ """,
89
+ citation="""\
90
+ @inproceedings{rousseau2014tedlium2,
91
+ title={Enhancing the {TED-LIUM} Corpus with Selected Data for Language Modeling and More {TED} Talks},
92
+ author={Rousseau, Anthony and Del{\\'e}glise, Paul and Est{\\`e}ve, Yannick},
93
+ booktitle={Conference on Language Resources and Evaluation (LREC)},
94
+ year={2014}
95
+ }
96
+ """,
97
+ url="https://www.openslr.org/19/",
98
+ download_url="http://www.openslr.org/resources/19/TEDLIUM_release2.tar.gz",
99
+ split_paths=[(datasets.Split.TRAIN, os.path.join("TEDLIUM_release2",
100
+ "train")),
101
+ (datasets.Split.VALIDATION,
102
+ os.path.join("TEDLIUM_release2", "dev")),
103
+ (datasets.Split.TEST, os.path.join("TEDLIUM_release2", "test"))])
104
+
105
+ release3 = TedliumReleaseConfig(
106
+ name="release3",
107
+ description="""\
108
+ This is the TED-LIUM corpus release 3, licensed under Creative Commons
109
+ BY-NC-ND 3.0.
110
+
111
+ All talks and text are property of TED Conferences LLC.
112
+
113
+ This new TED-LIUM release was made through a collaboration between the
114
+ Ubiqus company and the LIUM (University of Le Mans, France)
115
+
116
+ Contents:
117
+
118
+ - 2351 audio talks in NIST sphere format (SPH), including talks from
119
+ TED-LIUM 2: be careful, same talks but not same audio files (only
120
+ these audio file must be used with the TED-LIUM 3 STM files)
121
+ - 452 hours of audio
122
+ - 2351 aligned automatic transcripts in STM format
123
+ - TEDLIUM 2 dev and test data: 19 TED talks in SPH format with
124
+ corresponding manual transcriptions (cf. 'legacy' distribution below).
125
+ - Dictionary with pronunciations (159848 entries), same file as the one
126
+ included in TED-LIUM 2
127
+ - Selected monolingual data for language modeling from WMT12 publicly
128
+ available corpora: these files come from the TED-LIUM 2 release, but
129
+ have been modified to get a tokenization more relevant for English
130
+ language
131
+
132
+ Two corpus distributions:
133
+ - the legacy one, on which the dev and test datasets are the same as in
134
+ TED-LIUM 2 (and TED-LIUM 1).
135
+ - the 'speaker adaptation' one, especially designed for experiments on
136
+ speaker adaptation.
137
+ """,
138
+ citation="""\
139
+ @inproceedings{hernandez2018tedlium3,
140
+ title={TED-LIUM 3: twice as much data and corpus repartition for experiments on speaker adaptation},
141
+ author={Hernandez, Fran{\\c{c}}ois and Nguyen, Vincent and Ghannay, Sahar and Tomashenko, Natalia and Est{\\`e}ve, Yannick},
142
+ booktitle={International Conference on Speech and Computer},
143
+ pages={198--208},
144
+ year={2018},
145
+ organization={Springer}
146
+ }
147
+ """,
148
+ url="https://www.openslr.org/51/",
149
+ download_url="http://www.openslr.org/resources/51/TEDLIUM_release-3.tgz",
150
+ split_paths=[
151
+ (datasets.Split.VALIDATION,
152
+ os.path.join("TEDLIUM_release-3", "legacy", "dev")),
153
+ (datasets.Split.TEST, os.path.join("TEDLIUM_release-3", "legacy",
154
+ "test")),
155
+ # The legacy/train directory contains symlinks to "data",
156
+ # which are skipped by extraction (see above).
157
+ # Work around this by manually dereferencing the links here.
158
+ (datasets.Split.TRAIN, os.path.join("TEDLIUM_release-3", "data"))
159
+ ])
160
+
161
+ return [release1, release2, release3]
162
+
163
+
164
+ class TedLium(datasets.GeneratorBasedBuilder):
165
+ """ The TED-LIUM corpus is English-language TED talks, with transcriptions, sampled at 16kHz. It contains about 118 hours of speech."""
166
+
167
+ VERSION = datasets.Version("1.1.0")
168
+
169
+ BUILDER_CONFIGS = _make_builder_configs()
170
+
171
+ def _info(self):
172
+ features = datasets.Features({
173
+ "audio":
174
+ datasets.features.Audio(sampling_rate=16_000),
175
+ "text":
176
+ datasets.Value('string'),
177
+ "speaker_id":
178
+ datasets.Value('string'),
179
+ "gender":
180
+ datasets.features.ClassLabel(names=["unknown", "female", "male"]),
181
+ "file": datasets.Value('string'),
182
+ "id":
183
+ datasets.Value('string'),
184
+ })
185
+ return datasets.DatasetInfo(
186
+ description=self.config.description,
187
+ features=features,
188
+ supervised_keys=("audio", "text"),
189
+ homepage=self.config.url,
190
+ license=_LICENSE,
191
+ citation=self.config.citation,
192
+ task_templates=[AutomaticSpeechRecognition(audio_column="audio", transcription_column="text")],
193
+ )
194
+
195
+ def _split_generators(self, dl_manager):
196
+ data_dir = dl_manager.download_and_extract(
197
+ self.config.download_url)
198
+ splits = []
199
+ for split, path in self.config.split_paths:
200
+ kwargs = {"filepath": os.path.join(data_dir, path)}
201
+ splits.append(datasets.SplitGenerator(name=split, gen_kwargs=kwargs))
202
+ return splits
203
+
204
+ def _generate_examples(self, filepath):
205
+ """Generate examples from a TED-LIUM stm file."""
206
+ # The stm directory houses the speaker and transcription information in .stm format
207
+ stm_dir = os.path.join(filepath, "stm")
208
+ # The sph directory houses the audio files in .sph format
209
+ sph_dir = os.path.join(filepath, "sph")
210
+ stm_files = [os.path.join(stm_dir, f) for f in os.listdir(stm_dir) if f.endswith('.stm')]
211
+ for file in stm_files:
212
+ with open(file) as f:
213
+ for line in f:
214
+ line = line.strip()
215
+ fn, channel, speaker, start, end, label, transcript = line.split(" ", 6)
216
+ transcript = _maybe_trim_suffix(transcript)
217
+
218
+ audio_file = "%s.sph" % fn
219
+ samples = _extract_audio_segment(
220
+ os.path.join(sph_dir, audio_file), int(channel), float(start),
221
+ float(end))
222
+
223
+ key = "-".join([speaker, start, end, label])
224
+ example = {
225
+ "audio": {"path": file, "bytes": samples},
226
+ "text": transcript,
227
+ "speaker_id": speaker,
228
+ "gender": _parse_gender(label),
229
+ "file": file,
230
+ "id": key,
231
+ }
232
+ yield key, example
233
+
234
+ def _maybe_trim_suffix(transcript):
235
+ # stm files for the TEDLIUM release 1 train split contain a key (enclosed in
236
+ # parens) at the end.
237
+ splits = transcript.rsplit(" ", 1)
238
+ transcript = splits[0]
239
+ if len(splits) > 1:
240
+ suffix = splits[-1]
241
+ if not suffix.startswith("("):
242
+ transcript += " " + suffix
243
+ return transcript
244
+
245
+
246
+ def _parse_gender(label_str):
247
+ """Parse gender string from STM "<label>" field."""
248
+ gender = re.split(",|_", label_str)[-1][:-1]
249
+ # Fix inconsistencies in the data.
250
+ if not gender:
251
+ gender = -1 # Missing label.
252
+ elif gender == "<NA": # In TEDLIUM release 3 training data.
253
+ gender = -1 # Missing label.
254
+ elif gender == "F":
255
+ gender = "female"
256
+ elif gender == "M":
257
+ gender = "male"
258
+ return gender
259
+
260
+
261
+ def _extract_audio_segment(sph_path, channel, start_sec, end_sec):
262
+ """Extracts segment of audio samples (as an ndarray) from the given path."""
263
+ with open(sph_path, "rb") as f:
264
+ segment = AudioSegment.from_file(f, format="nistsphere")
265
+ # The dataset only contains mono audio.
266
+ assert segment.channels == 1
267
+ assert channel == 1
268
+ start_ms = int(start_sec * 1000)
269
+ end_ms = int(end_sec * 1000)
270
+ segment = segment[start_ms:end_ms]
271
+ samples = np.array(segment.get_array_of_samples())
272
+ return samples