calicxy commited on
Commit
6928828
·
1 Parent(s): 195e483

updating loading script

Browse files
IMDA - National Speech Corpus/PART3/tmp_clip.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bee5844aab3b7fc7f612fd752dc4f7ca8ce49b30a5cc8c3b8f116beb9f45c761
3
- size 787404
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57cbf6bf547727f71d6d0208756677ceea272749468e7877db11f8a918b053a6
3
+ size 530898
imda-dataset-p1.py CHANGED
@@ -5,7 +5,9 @@ import pandas as pd
5
  from sklearn.model_selection import train_test_split
6
 
7
  _DESCRIPTION = """\
8
- This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
 
 
9
  """
10
 
11
  _CITATION = """\
 
5
  from sklearn.model_selection import train_test_split
6
 
7
  _DESCRIPTION = """\
8
+ Part 1 of the National Speech Corpus. The National Speech Corpus (NSC)
9
+ is the first large-scale Singapore English corpus spearheaded by the
10
+ Info-communications and Media Development Authority (IMDA) of Singapore.
11
  """
12
 
13
  _CITATION = """\
imda-dataset.py CHANGED
@@ -1,54 +1,97 @@
1
  import os
2
- import glob
3
  import datasets
4
- import pandas as pd
5
  from sklearn.model_selection import train_test_split
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  _DESCRIPTION = """\
8
- This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
 
9
  """
10
 
11
  _CITATION = """\
12
  """
13
  _CHANNEL_CONFIGS = sorted([
14
- "CHANNEL0", "CHANNEL1", "CHANNEL2"
15
  ])
16
 
17
- _GENDER_CONFIGS = sorted(["F", "M"])
18
-
19
- _RACE_CONFIGS = sorted(["CHINESE", "MALAY", "INDIAN", "OTHERS"])
20
 
21
- _HOMEPAGE = "https://huggingface.co/indonesian-nlp/librivox-indonesia"
22
 
23
- _LICENSE = "https://creativecommons.org/publicdomain/zero/1.0/"
24
 
25
- _PATH_TO_DATA = './IMDA - National Speech Corpus/PART2'
26
- # _PATH_TO_DATA = './PART2/DATA'
27
 
28
  class Minds14Config(datasets.BuilderConfig):
29
  """BuilderConfig for xtreme-s"""
30
 
31
  def __init__(
32
- self, channel, gender, race, description, homepage, path_to_data
33
  ):
34
  super(Minds14Config, self).__init__(
35
- name=channel+gender+race,
36
  version=datasets.Version("1.0.0", ""),
37
  description=self.description,
38
  )
39
  self.channel = channel
40
- self.gender = gender
41
- self.race = race
42
  self.description = description
43
  self.homepage = homepage
44
  self.path_to_data = path_to_data
45
 
46
 
47
- def _build_config(channel, gender, race):
48
  return Minds14Config(
49
  channel=channel,
50
- gender=gender,
51
- race=race,
52
  description=_DESCRIPTION,
53
  homepage=_HOMEPAGE,
54
  path_to_data=_PATH_TO_DATA,
@@ -73,28 +116,24 @@ class NewDataset(datasets.GeneratorBasedBuilder):
73
  # data = datasets.load_dataset('my_dataset', 'second_domain')
74
  BUILDER_CONFIGS = []
75
  for channel in _CHANNEL_CONFIGS + ["all"]:
76
- for gender in _GENDER_CONFIGS + ["all"]:
77
- for race in _RACE_CONFIGS + ["all"]:
78
- BUILDER_CONFIGS.append(_build_config(channel, gender, race))
79
  # BUILDER_CONFIGS = [_build_config(name) for name in _CHANNEL_CONFIGS + ["all"]]
80
 
81
- DEFAULT_CONFIG_NAME = "allallall" # It's not mandatory to have a default configuration. Just use one if it make sense.
82
 
83
  def _info(self):
84
  # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
85
  task_templates = None
86
- # mics = _CHANNEL_CONFIGS
87
  features = datasets.Features(
88
  {
89
- "audio": datasets.features.Audio(sampling_rate=16000),
90
  "transcript": datasets.Value("string"),
91
  "mic": datasets.Value("string"),
92
  "audio_name": datasets.Value("string"),
93
- "gender": datasets.Value("string"),
94
- "race": datasets.Value("string"),
95
  }
96
  )
97
-
98
  return datasets.DatasetInfo(
99
  # This is the description that will appear on the datasets page.
100
  description=_DESCRIPTION,
@@ -121,31 +160,55 @@ class NewDataset(datasets.GeneratorBasedBuilder):
121
  else [self.config.channel]
122
  )
123
 
124
- gender = (
125
- _GENDER_CONFIGS
126
- if self.config.gender == "all"
127
- else [self.config.gender]
128
- )
129
 
130
- race = (
131
- _RACE_CONFIGS
132
- if self.config.race == "all"
133
- else [self.config.race]
134
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- # augment speaker ids directly here
137
- # read the speaker information
138
- train_speaker_ids = []
139
- test_speaker_ids = []
140
- # path_to_speaker = os.path.join(self.config.path_to_data, "DOC", "Speaker Information (Part 1).XLSX")
141
- path_to_speaker = dl_manager.download(os.path.join(self.config.path_to_data, "DOC", "Speaker Information (Part 2).XLSX"))
142
- speaker_df = pd.read_excel(path_to_speaker, dtype={'SCD/PART2': 'str'})
143
- for g in gender:
144
- for r in race:
145
- X = speaker_df[(speaker_df["ACC"]==r) & (speaker_df["SEX"]==g)]
146
- X_train, X_test = train_test_split(X, test_size=0.3, random_state=42, shuffle=True)
147
- train_speaker_ids.extend(X_train["SCD/PART2"])
148
- test_speaker_ids.extend(X_test["SCD/PART2"])
149
 
150
  # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
151
  # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
@@ -154,23 +217,15 @@ class NewDataset(datasets.GeneratorBasedBuilder):
154
  datasets.SplitGenerator(
155
  name=datasets.Split.TRAIN,
156
  gen_kwargs={
157
- "path_to_data": self.config.path_to_data,
158
- "speaker_metadata":speaker_df,
159
- # "speaker_ids": train_speaker_ids,
160
- "speaker_ids":["2001"],
161
- "mics": mics,
162
- "dl_manager": dl_manager
163
  },
164
  ),
165
  datasets.SplitGenerator(
166
  name=datasets.Split.TEST,
167
  gen_kwargs={
168
- "path_to_data": self.config.path_to_data,
169
- "speaker_metadata":speaker_df,
170
- # "speaker_ids": test_speaker_ids,
171
- "speaker_ids": ["2003"],
172
- "mics": mics,
173
- "dl_manager": dl_manager
174
  },
175
  ),
176
  ]
@@ -178,55 +233,135 @@ class NewDataset(datasets.GeneratorBasedBuilder):
178
  # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
179
  def _generate_examples(
180
  self,
181
- path_to_data,
182
- speaker_metadata,
183
- speaker_ids,
184
- mics,
185
- dl_manager
186
  ):
187
  id_ = 0
188
- for mic in mics:
189
- for speaker in speaker_ids:
190
- # TRANSCRIPT: in the case of error, if no file found then dictionary will b empty
191
- d = {}
192
- counter = 0
193
- while counter < 10:
194
- data = dl_manager.download(os.path.join(path_to_data, "DATA", mic, "SCRIPT", mic[-1]+speaker+str(counter)+'.TXT'))
195
- try:
196
- line_num = 0
197
- with open(data, encoding='utf-8-sig') as f:
198
- for line in f:
199
- if line_num == 0:
200
- key = line.split("\t")[0]
201
- line_num += 1
202
- elif line_num == 1:
203
- d[key] = line.strip()
204
- line_num -= 1
205
- except:
206
- print(f"{counter}")
207
- break
208
- counter+=1
209
- # AUDIO: in the case of error it will skip the speaker
210
- # archive_path = os.path.join(path_to_data, "DATA", mic, "WAVE", "SPEAKER"+speaker+'.zip')
211
- archive_path = dl_manager.download(os.path.join(path_to_data, "DATA", mic, "WAVE", "SPEAKER"+speaker+'.zip'))
212
- # check that archive path exists, else will not open the archive
213
- if os.path.exists(archive_path):
214
- audio_files = dl_manager.iter_archive(archive_path)
215
- for path, f in audio_files:
216
- # bug catching if any error?
217
- result = {}
218
- full_path = os.path.join(archive_path, path) if archive_path else path # bug catching here
219
- result["audio"] = {"path": full_path, "bytes": f.read()}
220
- result["audio_name"] = path
221
- result["mic"] = mic
222
- metadata_row = speaker_metadata.loc[speaker_metadata["SCD/PART2"]==speaker].iloc[0]
223
- result["gender"]=metadata_row["SEX"]
224
- result["race"]=metadata_row["ACC"]
225
- try:
226
- result["transcript"] = d[f.name[-13:-4]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  yield id_, result
228
- id_ += 1
229
- except:
230
- print(f"unable to find transcript")
231
-
232
-
 
 
 
1
  import os
 
2
  import datasets
 
3
  from sklearn.model_selection import train_test_split
4
+ import textgrids
5
+ import soundfile as sf
6
+ import re
7
+ import json
8
+ import tempfile
9
+ import random
10
+
11
+ def cleanup_string(line):
12
+
13
+ words_to_remove = ['(ppo)','(ppc)', '(ppb)', '(ppl)', '<s/>','<c/>','<q/>', '<fil/>', '<sta/>', '<nps/>', '<spk/>', '<non/>', '<unk>', '<s>', '<z>', '<nen>']
14
+
15
+ formatted_line = re.sub(r'\s+', ' ', line).strip().lower()
16
+
17
+ #detect all word that matches words in the words_to_remove list
18
+ for word in words_to_remove:
19
+ if re.search(word,formatted_line):
20
+ # formatted_line = re.sub(word,'', formatted_line)
21
+ formatted_line = formatted_line.replace(word,'')
22
+ formatted_line = re.sub(r'\s+', ' ', formatted_line).strip().lower()
23
+ # print("*** removed words: " + formatted_line)
24
+
25
+ #detect '\[(.*?)\].' e.g. 'Okay [ah], why did I gamble?'
26
+ #remove [ ] and keep text within
27
+ if re.search('\[(.*?)\]', formatted_line):
28
+ formatted_line = re.sub('\[(.*?)\]', r'\1', formatted_line).strip()
29
+ #print("***: " + formatted_line)
30
+
31
+ #detect '\((.*?)\).' e.g. 'Okay (um), why did I gamble?'
32
+ #remove ( ) and keep text within
33
+ if re.search('\((.*?)\)', formatted_line):
34
+ formatted_line = re.sub('\((.*?)\)', r'\1', formatted_line).strip()
35
+ # print("***: " + formatted_line)
36
+
37
+ #detect '\'(.*?)\'' e.g. 'not 'hot' per se'
38
+ #remove ' ' and keep text within
39
+ if re.search('\'(.*?)\'', formatted_line):
40
+ formatted_line = re.sub('\'(.*?)\'', r'\1', formatted_line).strip()
41
+ #print("***: " + formatted_line)
42
+
43
+ #remove punctation '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
44
+ punctuation = '''!–;"\,./?@#$%^&*~'''
45
+ punctuation_list = str.maketrans("","",punctuation)
46
+ formatted_line = re.sub(r'-', ' ', formatted_line)
47
+ formatted_line = re.sub(r'_', ' ', formatted_line)
48
+ formatted_line = formatted_line.translate(punctuation_list)
49
+ formatted_line = re.sub(r'\s+', ' ', formatted_line).strip().lower()
50
+ #print("***: " + formatted_line)
51
+
52
+ return formatted_line
53
+
54
+
55
 
56
  _DESCRIPTION = """\
57
+ The National Speech Corpus (NSC) is the first large-scale Singapore English corpus
58
+ spearheaded by the Info-communications and Media Development Authority (IMDA) of Singapore.
59
  """
60
 
61
  _CITATION = """\
62
  """
63
  _CHANNEL_CONFIGS = sorted([
64
+ "Audio Same CloseMic", "Audio Separate StandingMic"
65
  ])
66
 
67
+ _HOMEPAGE = "https://www.imda.gov.sg/how-we-can-help/national-speech-corpus"
 
 
68
 
69
+ _LICENSE = ""
70
 
71
+ _PATH_TO_DATA = './IMDA - National Speech Corpus/PART3'
72
 
73
+ INTERVAL_MAX_LENGTH = 25
 
74
 
75
  class Minds14Config(datasets.BuilderConfig):
76
  """BuilderConfig for xtreme-s"""
77
 
78
  def __init__(
79
+ self, channel, description, homepage, path_to_data
80
  ):
81
  super(Minds14Config, self).__init__(
82
+ name=channel,
83
  version=datasets.Version("1.0.0", ""),
84
  description=self.description,
85
  )
86
  self.channel = channel
 
 
87
  self.description = description
88
  self.homepage = homepage
89
  self.path_to_data = path_to_data
90
 
91
 
92
+ def _build_config(channel):
93
  return Minds14Config(
94
  channel=channel,
 
 
95
  description=_DESCRIPTION,
96
  homepage=_HOMEPAGE,
97
  path_to_data=_PATH_TO_DATA,
 
116
  # data = datasets.load_dataset('my_dataset', 'second_domain')
117
  BUILDER_CONFIGS = []
118
  for channel in _CHANNEL_CONFIGS + ["all"]:
119
+ BUILDER_CONFIGS.append(_build_config(channel))
 
 
120
  # BUILDER_CONFIGS = [_build_config(name) for name in _CHANNEL_CONFIGS + ["all"]]
121
 
122
+ DEFAULT_CONFIG_NAME = "all" # It's not mandatory to have a default configuration. Just use one if it make sense.
123
 
124
  def _info(self):
125
  # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
126
  task_templates = None
 
127
  features = datasets.Features(
128
  {
129
+ "audio": datasets.features.Audio(),
130
  "transcript": datasets.Value("string"),
131
  "mic": datasets.Value("string"),
132
  "audio_name": datasets.Value("string"),
133
+ "interval": datasets.Value("string")
 
134
  }
135
  )
136
+
137
  return datasets.DatasetInfo(
138
  # This is the description that will appear on the datasets page.
139
  description=_DESCRIPTION,
 
160
  else [self.config.channel]
161
  )
162
 
163
+ json_path = dl_manager.download(os.path.join(self.config.path_to_data, "directory_list.json"))
164
+ # print(f"json_path: {json_path}")
165
+ with open(json_path, "r") as f:
166
+ directory_dict = json.load(f)
167
+ # print(f"directory_dict: {directory_dict}")
168
 
169
+ train_audio_list = []
170
+ test_audio_list = []
171
+ for mic in mics:
172
+ audio_list = []
173
+ if mic == "Audio Same CloseMic":
174
+ audio_list = [x for x in directory_dict[mic] if (x[-5] == "1") ]
175
+ # train test split speaker 1, append speaker 2 depending on in train or test dataset
176
+ train, test = train_test_split(audio_list, test_size=0.005, random_state=42, shuffle=True)
177
+ for path in train:
178
+ train_audio_list.append(os.path.join(self.config.path_to_data, mic, path))
179
+ s = list(path)
180
+ s[-5] = "2"
181
+ train_audio_list.append(os.path.join(self.config.path_to_data, mic, "".join(s)))
182
+ for path in test:
183
+ test_audio_list.append(os.path.join(self.config.path_to_data, mic, path))
184
+ s = list(path)
185
+ s[-5] = "2"
186
+ test_audio_list.append(os.path.join(self.config.path_to_data, mic, "".join(s)))
187
+ elif mic == "Audio Separate IVR":
188
+ audio_list = [x.split("\\")[0] for x in directory_dict[mic]]
189
+ print('AUDIO LIST',audio_list)
190
+ train, test = train_test_split(audio_list, test_size=0.005, random_state=42, shuffle=True)
191
+ for folder in train:
192
+ audios = [os.path.join(self.config.path_to_data, mic, x) for x in directory_dict[mic] if (x.split("\\")[0]==folder)]
193
+ train_audio_list.extend(audios)
194
+ for folder in test:
195
+ audios = [os.path.join(self.config.path_to_data, mic, x) for x in directory_dict[mic] if (x.split("\\")[0]==folder)]
196
+ test_audio_list.extend(audios)
197
+ elif mic == "Audio Separate StandingMic":
198
+ audio_list = [x[:14] for x in directory_dict[mic]]
199
+ audio_list = list(set(audio_list))
200
+ train, test = train_test_split(audio_list, test_size=0.005, random_state=42, shuffle=True)
201
+ for folder in train:
202
+ audios = [os.path.join(self.config.path_to_data, mic, x) for x in directory_dict[mic] if (x[:14]==folder)]
203
+ train_audio_list.extend(audios)
204
+ for folder in test:
205
+ audios = [os.path.join(self.config.path_to_data, mic, x) for x in directory_dict[mic] if (x[:14]==folder)]
206
+ test_audio_list.extend(audios)
207
 
208
+ random.shuffle(train_audio_list)
209
+ random.shuffle(test_audio_list)
210
+ print(f"train_audio_list: { train_audio_list}")
211
+ print(f"test_audio_list: { test_audio_list}")
 
 
 
 
 
 
 
 
 
212
 
213
  # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
214
  # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
 
217
  datasets.SplitGenerator(
218
  name=datasets.Split.TRAIN,
219
  gen_kwargs={
220
+ "audio_list": train_audio_list,
221
+ "dl_manager":dl_manager,
 
 
 
 
222
  },
223
  ),
224
  datasets.SplitGenerator(
225
  name=datasets.Split.TEST,
226
  gen_kwargs={
227
+ "audio_list": test_audio_list,
228
+ "dl_manager":dl_manager,
 
 
 
 
229
  },
230
  ),
231
  ]
 
233
  # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
234
  def _generate_examples(
235
  self,
236
+ audio_list,
237
+ dl_manager,
 
 
 
238
  ):
239
  id_ = 0
240
+ for audio_path in audio_list:
241
+ try:
242
+ file = os.path.split(audio_path)[-1]
243
+ folder = os.path.split(os.path.split(audio_path)[0])[-1]
244
+ # get script_path
245
+ if folder.split("_")[0] == "conf":
246
+ # mic == "Audio Separate IVR"
247
+ file_name = folder+'_'+file
248
+ script_path = os.path.join(self.config.path_to_data, "Scripts Separate", file_name[:-4]+".TextGrid")
249
+ elif folder.split()[1] == "Same":
250
+ # mic == "Audio Same CloseMic IVR"
251
+ script_path = os.path.join(self.config.path_to_data, "Scripts Same", file[:-4]+".TextGrid")
252
+ elif folder.split()[1] == "Separate":
253
+ # mic == "Audio Separate StandingMic":
254
+ script_path = os.path.join(self.config.path_to_data, "Scripts Separate", file[:-4]+".TextGrid")
255
+ script_path = dl_manager.download(script_path)
256
+ except Exception as e:
257
+ print(f"error getting script path, {str(e)}")
258
+ continue
259
+
260
+ # LOAD TRANSCRIPT
261
+ # check that the textgrid file can be read
262
+
263
+ try:
264
+ # tg = textgrid.TextGrid.fromFile(script_path)
265
+ with open(script_path, "rb") as f:
266
+ tg = f.read()
267
+ tg_dict = textgrids.TextGrid()
268
+ tg_dict.parse(tg)
269
+ for key in tg_dict.keys():
270
+ tg = tg_dict[key]
271
+ except UnicodeDecodeError:
272
+ try:
273
+ with open(script_path, "rb") as f:
274
+ tg = f.read()
275
+ decoded = tg.decode('utf-16')
276
+ encoded = decoded.encode('utf-8')
277
+ tg_dict = textgrids.TextGrid()
278
+ tg_dict.parse(encoded)
279
+ for key in tg_dict.keys():
280
+ tg = tg_dict[key]
281
+ except Exception as e:
282
+ print(f"error reading textgrid file, {script_path}, {str(e)}")
283
+ continue
284
+ except TypeError:
285
+ try:
286
+ with open(script_path, "rb") as f:
287
+ tg = f.read()
288
+ decoded = tg.decode('utf-8-sig')
289
+ encoded = decoded.encode('utf-8')
290
+ tg_dict = textgrids.TextGrid()
291
+ tg_dict.parse(encoded)
292
+ for key in tg_dict.keys():
293
+ tg = tg_dict[key]
294
+ except Exception as e:
295
+ print(f"error reading textgrid file, {script_path}, {str(e)}")
296
+ continue
297
+ except Exception as e:
298
+ print(f"error reading textgrid file, {script_path}, {str(e)}")
299
+ continue
300
+ # LOAD AUDIO
301
+ # check that archive path exists, else will not open the archive
302
+ audio_path = dl_manager.download(audio_path)
303
+ if os.path.exists(audio_path):
304
+ try:
305
+ with open(audio_path, 'rb') as f:
306
+ data, sr = sf.read(f)
307
+ if sr != 16000:
308
+ print(f'sample rate: {sr}')
309
+ continue
310
+ # data, sr = sf.read(audio_path)
311
+ result = {}
312
+ i = 0
313
+ intervalLength = 0
314
+ intervalStart = 0
315
+ transcript_list = []
316
+ # filepath = os.path.join(self.config.path_to_data, f'tmp_clip{id_}.wav')
317
+ # filepath = dl_manager.download(filepath)
318
+ tempWavFile = tempfile.mktemp('.wav')
319
+ while i < (len(tg)-1):
320
+ transcript = cleanup_string(tg[i].text)
321
+ if intervalLength == 0 and len(transcript) == 0:
322
+ intervalStart = tg[i+1].xmin
323
+ i+=1
324
+ continue
325
+ intervalLength += tg[i].xmax-tg[i].xmin
326
+ if (tg[i].xmax-tg[i].xmin) > INTERVAL_MAX_LENGTH:
327
+ print(f"Interval is too long: {tg[i].xmax-tg[i].xmin}")
328
+ intervalLength = 0
329
+ intervalStart = tg[i+1].xmin
330
+ transcript_list = []
331
+ i+=1
332
+ continue
333
+ # spliced_audio = data[int(tg[i].xmin*sr):int(tg[i].xmax*sr)]
334
+ # sf.write(tempWavFile, spliced_audio, sr)
335
+ # result["transcript"] = transcript
336
+ # result["interval"] = "start:"+str(tg[i].xmin)+", end:"+str(tg[i].xmax)
337
+ # result["audio"] = {"path": tempWavFile, "bytes": spliced_audio, "sampling_rate":sr}
338
+ # result["audio_name"] = audio_path
339
+ # yield id_, result
340
+ # id_+= 1
341
+ # intervalLength = 0
342
+ else:
343
+ if (intervalLength + tg[i+1].xmax-tg[i+1].xmin) < INTERVAL_MAX_LENGTH:
344
+ if len(transcript) != 0:
345
+ transcript_list.append(transcript)
346
+ i+=1
347
+ continue
348
+ if len(transcript) == 0:
349
+ spliced_audio = data[int(intervalStart*sr):int(tg[i].xmax*sr)]
350
+ else:
351
+ transcript_list.append(transcript)
352
+ spliced_audio = data[int(intervalStart*sr):int(tg[i].xmax*sr)]
353
+
354
+ sf.write(tempWavFile,spliced_audio, sr )
355
+ # sf.write(filepath, spliced_audio, sr)
356
+ result["interval"] = "start:"+str(intervalStart)+", end:"+str(tg[i].xmax)
357
+ result["audio"] = {"path": tempWavFile, "bytes": spliced_audio, "sampling_rate":sr}
358
+ result["transcript"] = ' '.join(transcript_list)
359
+ result["audio_name"] = audio_path
360
  yield id_, result
361
+ id_+= 1
362
+ intervalLength=0
363
+ intervalStart=tg[i+1].xmin
364
+ transcript_list = []
365
+ i+=1
366
+ except:
367
+ continue
imda_nsc_part2.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import datasets
4
+ import pandas as pd
5
+ from sklearn.model_selection import train_test_split
6
+
7
+ _DESCRIPTION = """\
8
+ Part 2 of the National Speech Corpus. The National Speech Corpus (NSC)
9
+ is the first large-scale Singapore English corpus spearheaded by the
10
+ Info-communications and Media Development Authority (IMDA) of Singapore.
11
+ """
12
+
13
+ _CITATION = """\
14
+ """
15
+ _CHANNEL_CONFIGS = sorted([
16
+ "CHANNEL0", "CHANNEL1", "CHANNEL2"
17
+ ])
18
+
19
+ _GENDER_CONFIGS = sorted(["F", "M"])
20
+
21
+ _RACE_CONFIGS = sorted(["CHINESE", "MALAY", "INDIAN", "OTHERS"])
22
+
23
+ _HOMEPAGE = "https://www.imda.gov.sg/how-we-can-help/national-speech-corpus"
24
+
25
+ _LICENSE = "https://creativecommons.org/publicdomain/zero/1.0/"
26
+
27
+ # _PATH_TO_DATA = './IMDA - National Speech Corpus/PART2'
28
+ _PATH_TO_DATA = './PART2'
29
+
30
+ class Minds14Config(datasets.BuilderConfig):
31
+ """BuilderConfig for xtreme-s"""
32
+
33
+ def __init__(
34
+ self, channel, gender, race, description, homepage, path_to_data
35
+ ):
36
+ super(Minds14Config, self).__init__(
37
+ name=channel+gender+race,
38
+ version=datasets.Version("1.0.0", ""),
39
+ description=self.description,
40
+ )
41
+ self.channel = channel
42
+ self.gender = gender
43
+ self.race = race
44
+ self.description = description
45
+ self.homepage = homepage
46
+ self.path_to_data = path_to_data
47
+
48
+
49
+ def _build_config(channel, gender, race):
50
+ return Minds14Config(
51
+ channel=channel,
52
+ gender=gender,
53
+ race=race,
54
+ description=_DESCRIPTION,
55
+ homepage=_HOMEPAGE,
56
+ path_to_data=_PATH_TO_DATA,
57
+ )
58
+
59
+ # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
60
+ class NewDataset(datasets.GeneratorBasedBuilder):
61
+ """TODO: Short description of my dataset."""
62
+
63
+ VERSION = datasets.Version("1.1.0")
64
+
65
+ # This is an example of a dataset with multiple configurations.
66
+ # If you don't want/need to define several sub-sets in your dataset,
67
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
68
+
69
+ # If you need to make complex sub-parts in the datasets with configurable options
70
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
71
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
72
+
73
+ # You will be able to load one or the other configurations in the following list with
74
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
75
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
76
+ BUILDER_CONFIGS = []
77
+ for channel in _CHANNEL_CONFIGS + ["all"]:
78
+ for gender in _GENDER_CONFIGS + ["all"]:
79
+ for race in _RACE_CONFIGS + ["all"]:
80
+ BUILDER_CONFIGS.append(_build_config(channel, gender, race))
81
+ # BUILDER_CONFIGS = [_build_config(name) for name in _CHANNEL_CONFIGS + ["all"]]
82
+
83
+ DEFAULT_CONFIG_NAME = "allallall" # It's not mandatory to have a default configuration. Just use one if it make sense.
84
+
85
+ def _info(self):
86
+ # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
87
+ task_templates = None
88
+ # mics = _CHANNEL_CONFIGS
89
+ features = datasets.Features(
90
+ {
91
+ "audio": datasets.features.Audio(sampling_rate=16000),
92
+ "transcript": datasets.Value("string"),
93
+ "mic": datasets.Value("string"),
94
+ "audio_name": datasets.Value("string"),
95
+ "gender": datasets.Value("string"),
96
+ "race": datasets.Value("string"),
97
+ }
98
+ )
99
+
100
+ return datasets.DatasetInfo(
101
+ # This is the description that will appear on the datasets page.
102
+ description=_DESCRIPTION,
103
+ # This defines the different columns of the dataset and their types
104
+ features=features, # Here we define them above because they are different between the two configurations
105
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
106
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
107
+ supervised_keys=("audio", "transcript"),
108
+ # Homepage of the dataset for documentation
109
+ homepage=_HOMEPAGE,
110
+ # License for the dataset if available
111
+ license=_LICENSE,
112
+ # Citation for the dataset
113
+ citation=_CITATION,
114
+ task_templates=task_templates,
115
+ )
116
+
117
+ def _split_generators(self, dl_manager):
118
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
119
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
120
+ mics = (
121
+ _CHANNEL_CONFIGS
122
+ if self.config.channel == "all"
123
+ else [self.config.channel]
124
+ )
125
+
126
+ gender = (
127
+ _GENDER_CONFIGS
128
+ if self.config.gender == "all"
129
+ else [self.config.gender]
130
+ )
131
+
132
+ race = (
133
+ _RACE_CONFIGS
134
+ if self.config.race == "all"
135
+ else [self.config.race]
136
+ )
137
+
138
+ # augment speaker ids directly here
139
+ # read the speaker information
140
+ train_speaker_ids = []
141
+ test_speaker_ids = []
142
+ # path_to_speaker = os.path.join(self.config.path_to_data, "DOC", "Speaker Information (Part 1).XLSX")
143
+ path_to_speaker = dl_manager.download(os.path.join(self.config.path_to_data, "DOC", "Speaker Information (Part 2).XLSX"))
144
+ speaker_df = pd.read_excel(path_to_speaker, dtype={'SCD/PART2': 'str'})
145
+ for g in gender:
146
+ for r in race:
147
+ X = speaker_df[(speaker_df["ACC"]==r) & (speaker_df["SEX"]==g)]
148
+ X_train, X_test = train_test_split(X, test_size=0.3, random_state=42, shuffle=True)
149
+ train_speaker_ids.extend(X_train["SCD/PART2"])
150
+ test_speaker_ids.extend(X_test["SCD/PART2"])
151
+
152
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
153
+ # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
154
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
155
+ return [
156
+ datasets.SplitGenerator(
157
+ name=datasets.Split.TRAIN,
158
+ gen_kwargs={
159
+ "path_to_data": self.config.path_to_data,
160
+ "speaker_metadata":speaker_df,
161
+ "speaker_ids": train_speaker_ids,
162
+ # "speaker_ids":["2001"],
163
+ "mics": mics,
164
+ "dl_manager": dl_manager
165
+ },
166
+ ),
167
+ datasets.SplitGenerator(
168
+ name=datasets.Split.TEST,
169
+ gen_kwargs={
170
+ "path_to_data": self.config.path_to_data,
171
+ "speaker_metadata":speaker_df,
172
+ "speaker_ids": test_speaker_ids,
173
+ # "speaker_ids": ["2003"],
174
+ "mics": mics,
175
+ "dl_manager": dl_manager
176
+ },
177
+ ),
178
+ ]
179
+
180
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
181
+ def _generate_examples(
182
+ self,
183
+ path_to_data,
184
+ speaker_metadata,
185
+ speaker_ids,
186
+ mics,
187
+ dl_manager
188
+ ):
189
+ id_ = 0
190
+ for mic in mics:
191
+ for speaker in speaker_ids:
192
+ # TRANSCRIPT: in the case of error, if no file found then dictionary will b empty
193
+ d = {}
194
+ counter = 0
195
+ while counter < 10:
196
+ data = dl_manager.download(os.path.join(path_to_data, "DATA", mic, "SCRIPT", mic[-1]+speaker+str(counter)+'.TXT'))
197
+ try:
198
+ line_num = 0
199
+ with open(data, encoding='utf-8-sig') as f:
200
+ for line in f:
201
+ if line_num == 0:
202
+ key = line.split("\t")[0]
203
+ line_num += 1
204
+ elif line_num == 1:
205
+ d[key] = line.strip()
206
+ line_num -= 1
207
+ except:
208
+ print(f"{counter}")
209
+ break
210
+ counter+=1
211
+ # AUDIO: in the case of error it will skip the speaker
212
+ # archive_path = os.path.join(path_to_data, "DATA", mic, "WAVE", "SPEAKER"+speaker+'.zip')
213
+ archive_path = dl_manager.download(os.path.join(path_to_data, "DATA", mic, "WAVE", "SPEAKER"+speaker+'.zip'))
214
+ # check that archive path exists, else will not open the archive
215
+ if os.path.exists(archive_path):
216
+ audio_files = dl_manager.iter_archive(archive_path)
217
+ for path, f in audio_files:
218
+ # bug catching if any error?
219
+ result = {}
220
+ full_path = os.path.join(archive_path, path) if archive_path else path # bug catching here
221
+ result["audio"] = {"path": full_path, "bytes": f.read()}
222
+ result["audio_name"] = path
223
+ result["mic"] = mic
224
+ metadata_row = speaker_metadata.loc[speaker_metadata["SCD/PART2"]==speaker].iloc[0]
225
+ result["gender"]=metadata_row["SEX"]
226
+ result["race"]=metadata_row["ACC"]
227
+ try:
228
+ result["transcript"] = d[f.name[-13:-4]]
229
+ yield id_, result
230
+ id_ += 1
231
+ except:
232
+ print(f"unable to find transcript")
233
+
234
+