Datasets:
LIUM
/

sanchit-gandhi HF staff commited on
Commit
4ed3116
1 Parent(s): 4efcd6e

read .sph file only once per .stm file

Browse files
Files changed (1) hide show
  1. tedlium.py +99 -91
tedlium.py CHANGED
@@ -16,35 +16,36 @@
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
 
@@ -52,7 +53,7 @@ def _make_builder_configs():
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},
@@ -61,17 +62,18 @@ def _make_builder_configs():
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).
@@ -86,7 +88,7 @@ def _make_builder_configs():
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},
@@ -94,17 +96,18 @@ def _make_builder_configs():
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
 
@@ -135,7 +138,7 @@ def _make_builder_configs():
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},
@@ -145,43 +148,39 @@ def _make_builder_configs():
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,
@@ -193,8 +192,7 @@ class TedLium(datasets.GeneratorBasedBuilder):
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)}
@@ -207,18 +205,22 @@ class TedLium(datasets.GeneratorBasedBuilder):
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 = {
@@ -231,6 +233,15 @@ class TedLium(datasets.GeneratorBasedBuilder):
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.
@@ -243,6 +254,17 @@ def _maybe_trim_suffix(transcript):
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]
@@ -256,17 +278,3 @@ def _parse_gender(label_str):
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
 
16
 
17
  import os
18
  import re
19
+ from pathlib import Path
20
 
21
+ import numpy as np
22
+ from pydub import AudioSegment
23
 
24
  import datasets
25
  from datasets.tasks import AutomaticSpeechRecognition
26
 
 
27
 
28
  _LICENSE = "licensed under Creative Commons BY-NC-ND 3.0 (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en)"
29
 
30
+
31
  class TedliumReleaseConfig(datasets.BuilderConfig):
32
+ """BuilderConfig for a release of the TED-LIUM dataset."""
33
 
34
+ def __init__(self, *, url, download_url, split_paths, citation, **kwargs):
35
+ super(TedliumReleaseConfig, self).__init__(version=datasets.Version("1.0.1"), **kwargs)
36
+ self.url = url
37
+ self.download_url = download_url
38
+ # List of split, path pairs containing the relative path within the
39
+ # extracted tarball to the data for each split.
40
+ self.split_paths = split_paths
41
+ self.citation = citation
 
42
 
43
 
44
  def _make_builder_configs():
45
+ """Creates builder configs for all supported Tedlium dataset releases."""
46
+ release1 = TedliumReleaseConfig(
47
+ name="release1",
48
+ description="""\
49
  The TED-LIUM corpus is English-language TED talks, with transcriptions,
50
  sampled at 16kHz. It contains about 118 hours of speech.
51
 
 
53
  licensed under Creative Commons BY-NC-ND 3.0
54
  (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en).
55
  """,
56
+ citation="""\
57
  @inproceedings{rousseau2012tedlium,
58
  title={TED-LIUM: an Automatic Speech Recognition dedicated corpus},
59
  author={Rousseau, Anthony and Del{\\'e}glise, Paul and Est{\\`e}ve, Yannick},
 
62
  year={2012}
63
  }
64
  """,
65
+ url="https://www.openslr.org/7/",
66
+ download_url="http://www.openslr.org/resources/7/TEDLIUM_release1.tar.gz",
67
+ split_paths=[
68
+ (datasets.Split.TRAIN, os.path.join("TEDLIUM_release1", "train")),
69
+ (datasets.Split.VALIDATION, os.path.join("TEDLIUM_release1", "dev")),
70
+ (datasets.Split.TEST, os.path.join("TEDLIUM_release1", "test")),
71
+ ],
72
+ )
73
+
74
+ release2 = TedliumReleaseConfig(
75
+ name="release2",
76
+ description="""\
77
  This is the TED-LIUM corpus release 2,
78
  licensed under Creative Commons BY-NC-ND 3.0
79
  (http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en).
 
88
 
89
  Contains 1495 talks and transcripts.
90
  """,
91
+ citation="""\
92
  @inproceedings{rousseau2014tedlium2,
93
  title={Enhancing the {TED-LIUM} Corpus with Selected Data for Language Modeling and More {TED} Talks},
94
  author={Rousseau, Anthony and Del{\\'e}glise, Paul and Est{\\`e}ve, Yannick},
 
96
  year={2014}
97
  }
98
  """,
99
+ url="https://www.openslr.org/19/",
100
+ download_url="http://www.openslr.org/resources/19/TEDLIUM_release2.tar.gz",
101
+ split_paths=[
102
+ (datasets.Split.TRAIN, os.path.join("TEDLIUM_release2", "train")),
103
+ (datasets.Split.VALIDATION, os.path.join("TEDLIUM_release2", "dev")),
104
+ (datasets.Split.TEST, os.path.join("TEDLIUM_release2", "test")),
105
+ ],
106
+ )
107
+
108
+ release3 = TedliumReleaseConfig(
109
+ name="release3",
110
+ description="""\
111
  This is the TED-LIUM corpus release 3, licensed under Creative Commons
112
  BY-NC-ND 3.0.
113
 
 
138
  - the 'speaker adaptation' one, especially designed for experiments on
139
  speaker adaptation.
140
  """,
141
+ citation="""\
142
  @inproceedings{hernandez2018tedlium3,
143
  title={TED-LIUM 3: twice as much data and corpus repartition for experiments on speaker adaptation},
144
  author={Hernandez, Fran{\\c{c}}ois and Nguyen, Vincent and Ghannay, Sahar and Tomashenko, Natalia and Est{\\`e}ve, Yannick},
 
148
  organization={Springer}
149
  }
150
  """,
151
+ url="https://www.openslr.org/51/",
152
+ download_url="http://www.openslr.org/resources/51/TEDLIUM_release-3.tgz",
153
+ split_paths=[
154
+ (datasets.Split.VALIDATION, os.path.join("TEDLIUM_release-3", "legacy", "dev")),
155
+ (datasets.Split.TEST, os.path.join("TEDLIUM_release-3", "legacy", "test")),
156
+ # The legacy/train directory contains symlinks to "data",
157
+ # which are skipped by extraction (see above).
158
+ # Work around this by manually dereferencing the links here.
159
+ (datasets.Split.TRAIN, os.path.join("TEDLIUM_release-3", "data")),
160
+ ],
161
+ )
162
+
163
+ return [release1, release2, release3]
 
164
 
165
 
166
  class TedLium(datasets.GeneratorBasedBuilder):
167
+ """The TED-LIUM corpus is English-language TED talks, with transcriptions, sampled at 16kHz. It contains about 118 hours of speech."""
168
 
169
  VERSION = datasets.Version("1.1.0")
170
 
171
  BUILDER_CONFIGS = _make_builder_configs()
172
 
173
  def _info(self):
174
+ features = datasets.Features(
175
+ {
176
+ "audio": datasets.features.Audio(sampling_rate=16_000),
177
+ "text": datasets.Value("string"),
178
+ "speaker_id": datasets.Value("string"),
179
+ "gender": datasets.features.ClassLabel(names=["unknown", "female", "male"]),
180
+ "file": datasets.Value("string"),
181
+ "id": datasets.Value("string"),
182
+ }
183
+ )
 
 
 
184
  return datasets.DatasetInfo(
185
  description=self.config.description,
186
  features=features,
 
192
  )
193
 
194
  def _split_generators(self, dl_manager):
195
+ data_dir = dl_manager.download_and_extract(self.config.download_url)
 
196
  splits = []
197
  for split, path in self.config.split_paths:
198
  kwargs = {"filepath": os.path.join(data_dir, path)}
 
205
  stm_dir = os.path.join(filepath, "stm")
206
  # The sph directory houses the audio files in .sph format
207
  sph_dir = os.path.join(filepath, "sph")
208
+ stm_files = [os.path.join(stm_dir, f) for f in os.listdir(stm_dir) if f.endswith(".stm")]
209
  for file in stm_files:
210
+ # the .sph speaker file almost always has the same file name as the .stm file
211
+ speaker_file = Path(file).stem
212
+ audio_file = os.path.join(sph_dir, speaker_file + ".sph")
213
+ segment = _read_audio_segment(os.path.join(sph_dir, audio_file))
214
  with open(file) as f:
215
  for line in f:
216
  line = line.strip()
217
  fn, channel, speaker, start, end, label, transcript = line.split(" ", 6)
218
  transcript = _maybe_trim_suffix(transcript)
219
+ if speaker_file != fn:
220
+ # handle the case where the stm file does not have the same file name as the transcript
221
+ speaker_file = fn
222
+ segment = _read_audio_segment(os.path.join(sph_dir, speaker_file + ".sph"))
223
+ samples = _extract_audio_segment(segment, int(channel), float(start), float(end))
224
 
225
  key = "-".join([speaker, start, end, label])
226
  example = {
 
233
  }
234
  yield key, example
235
 
236
+
237
+ def _read_audio_segment(sph_path):
238
+ """Reads segment of audio samples from given sph file path"""
239
+ with open(sph_path, "rb") as f:
240
+ segment = AudioSegment.from_file(f, format="nistsphere")
241
+ assert segment.channels == 1
242
+ return segment
243
+
244
+
245
  def _maybe_trim_suffix(transcript):
246
  # stm files for the TEDLIUM release 1 train split contain a key (enclosed in
247
  # parens) at the end.
 
254
  return transcript
255
 
256
 
257
+ def _extract_audio_segment(segment, channel, start_sec, end_sec):
258
+ """Extracts segment of audio samples (as an ndarray) from the given segment."""
259
+ # The dataset only contains mono audio.
260
+ assert channel == 1
261
+ start_ms = int(start_sec * 1000)
262
+ end_ms = int(end_sec * 1000)
263
+ segment = segment[start_ms:end_ms]
264
+ samples = np.array(segment.get_array_of_samples())
265
+ return samples
266
+
267
+
268
  def _parse_gender(label_str):
269
  """Parse gender string from STM "<label>" field."""
270
  gender = re.split(",|_", label_str)[-1][:-1]
 
278
  elif gender == "M":
279
  gender = "male"
280
  return gender