calicxy commited on
Commit
9f0db75
·
1 Parent(s): 575c769

added scripts for part3

Browse files
IMDA - National Speech Corpus/PART3/tmp_clip.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb5c677b03c843afe9c53bec71333239b070051adf913873385ceeb1ffd793d4
3
+ size 773270
clean_transcript.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ def cleanup_string(line):
4
+
5
+ words_to_remove = ['(ppo)','(ppc)', '(ppb)', '(ppl)', '<s/>','<c/>','<q/>', '<fil/>', '<sta/>', '<nps/>', '<spk/>', '<non/>', '<unk>', '<s>', '<z>', '<nen>']
6
+
7
+ formatted_line = re.sub(r'\s+', ' ', line).strip().lower()
8
+
9
+ #detect all word that matches words in the words_to_remove list
10
+ for word in words_to_remove:
11
+ if re.search(word,formatted_line):
12
+ # formatted_line = re.sub(word,'', formatted_line)
13
+ formatted_line = formatted_line.replace(word,'')
14
+ formatted_line = re.sub(r'\s+', ' ', formatted_line).strip().lower()
15
+ # print("*** removed words: " + formatted_line)
16
+
17
+ #detect '\[(.*?)\].' e.g. 'Okay [ah], why did I gamble?'
18
+ #remove [ ] and keep text within
19
+ if re.search('\[(.*?)\]', formatted_line):
20
+ formatted_line = re.sub('\[(.*?)\]', r'\1', formatted_line).strip()
21
+ #print("***: " + formatted_line)
22
+
23
+ #detect '\((.*?)\).' e.g. 'Okay (um), why did I gamble?'
24
+ #remove ( ) and keep text within
25
+ if re.search('\((.*?)\)', formatted_line):
26
+ formatted_line = re.sub('\((.*?)\)', r'\1', formatted_line).strip()
27
+ # print("***: " + formatted_line)
28
+
29
+ #detect '\'(.*?)\'' e.g. 'not 'hot' per se'
30
+ #remove ' ' and keep text within
31
+ if re.search('\'(.*?)\'', formatted_line):
32
+ formatted_line = re.sub('\'(.*?)\'', r'\1', formatted_line).strip()
33
+ #print("***: " + formatted_line)
34
+
35
+ #remove punctation '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
36
+ punctuation = '''!–;"\,./?@#$%^&*~'''
37
+ punctuation_list = str.maketrans("","",punctuation)
38
+ formatted_line = re.sub(r'-', ' ', formatted_line)
39
+ formatted_line = re.sub(r'_', ' ', formatted_line)
40
+ formatted_line = formatted_line.translate(punctuation_list)
41
+ formatted_line = re.sub(r'\s+', ' ', formatted_line).strip().lower()
42
+ #print("***: " + formatted_line)
43
+
44
+ return formatted_line
45
+
46
+
47
+ if __name__ == "__main__":
48
+ line = "<fil> you can go first (ppc) you guys are going to <fil> stand here <fil>"
49
+ print(cleanup_string(line))
imda-dataset.py CHANGED
@@ -1,54 +1,51 @@
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/PART1'
26
  # _PATH_TO_DATA = './PART1/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,25 +70,21 @@ 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
 
@@ -121,31 +114,75 @@ 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 1).XLSX"))
142
- speaker_df = pd.read_excel(path_to_speaker, dtype={'SCD/PART1': object})
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/PART1"])
148
- test_speaker_ids.extend(X_test["SCD/PART1"])
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 +191,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":["0001"],
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": ["0003"],
172
- "mics": mics,
173
- "dl_manager": dl_manager
174
  },
175
  ),
176
  ]
@@ -178,55 +207,78 @@ 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/PART1"]==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
+ # import pandas as pd
4
  from sklearn.model_selection import train_test_split
5
+ from textgrid import textgrid
6
+ import soundfile as sf
7
+ from clean_transcript import cleanup_string
8
 
9
  _DESCRIPTION = """\
10
+ The National Speech Corpus (NSC) is the first large-scale Singapore English corpus
11
+ spearheaded by the Info-communications and Media Development Authority (IMDA) of Singapore.
12
  """
13
 
14
  _CITATION = """\
15
  """
16
  _CHANNEL_CONFIGS = sorted([
17
+ "Audio Same CloseMic", "Audio Separate IVR", "Audio Separate StandingMic"
18
  ])
19
 
20
+ _HOMEPAGE = "https://www.imda.gov.sg/how-we-can-help/national-speech-corpus"
21
 
22
+ _LICENSE = ""
23
 
24
+ _PATH_TO_DATA = './IMDA - National Speech Corpus/PART3'
 
 
 
 
25
  # _PATH_TO_DATA = './PART1/DATA'
26
 
27
+ INTERVAL_MAX_LENGTH = 25
28
+
29
  class Minds14Config(datasets.BuilderConfig):
30
  """BuilderConfig for xtreme-s"""
31
 
32
  def __init__(
33
+ self, channel, description, homepage, path_to_data
34
  ):
35
  super(Minds14Config, self).__init__(
36
+ name=channel,
37
  version=datasets.Version("1.0.0", ""),
38
  description=self.description,
39
  )
40
  self.channel = channel
 
 
41
  self.description = description
42
  self.homepage = homepage
43
  self.path_to_data = path_to_data
44
 
45
 
46
+ def _build_config(channel):
47
  return Minds14Config(
48
  channel=channel,
 
 
49
  description=_DESCRIPTION,
50
  homepage=_HOMEPAGE,
51
  path_to_data=_PATH_TO_DATA,
 
70
  # data = datasets.load_dataset('my_dataset', 'second_domain')
71
  BUILDER_CONFIGS = []
72
  for channel in _CHANNEL_CONFIGS + ["all"]:
73
+ BUILDER_CONFIGS.append(_build_config(channel))
 
 
74
  # BUILDER_CONFIGS = [_build_config(name) for name in _CHANNEL_CONFIGS + ["all"]]
75
 
76
+ DEFAULT_CONFIG_NAME = "all" # It's not mandatory to have a default configuration. Just use one if it make sense.
77
 
78
  def _info(self):
79
  # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
80
  task_templates = None
 
81
  features = datasets.Features(
82
  {
83
  "audio": datasets.features.Audio(sampling_rate=16000),
84
  "transcript": datasets.Value("string"),
85
  "mic": datasets.Value("string"),
86
  "audio_name": datasets.Value("string"),
87
+ "interval": datasets.Value("string")
 
88
  }
89
  )
90
 
 
114
  else [self.config.channel]
115
  )
116
 
117
+ train_audio_list = []
118
+ test_audio_list = []
119
+ for mic in mics:
120
+ audio_list = []
121
+ if mic == "Audio Same CloseMic":
122
+ for (root,dirs,files) in os.walk(os.path.join(self.config.path_to_data, mic), topdown=True):
123
+ if len(files) != 0:
124
+ for file in files:
125
+ # add only audio paths with -1 to the list
126
+ if file[-5] == "1":
127
+ audio_path = os.path.join(root, file)
128
+ audio_list.append(audio_path)
129
+ train, test = train_test_split(audio_list, test_size=0.3, random_state=42, shuffle=True)
130
+ for path in train:
131
+ train_audio_list.append(path)
132
+ s = list(path)
133
+ s[-5] = "2"
134
+ train_audio_list.append("".join(s))
135
+ for path in test:
136
+ test_audio_list.append(path)
137
+ s = list(path)
138
+ s[-5] = "2"
139
+ test_audio_list.append("".join(s))
140
+ elif mic == "Audio Separate IVR":
141
+ for (root,dirs,files) in os.walk(os.path.join(self.config.path_to_data, mic), topdown=True):
142
+ audio_list = dirs
143
+ break
144
+ train, test = train_test_split(audio_list, test_size=0.3, random_state=42, shuffle=True)
145
+ for folder in train:
146
+ for (root,dirs,files) in os.walk(os.path.join(self.config.path_to_data, mic, folder)):
147
+ if len(files) != 0:
148
+ for file in files:
149
+ audio_path = os.path.join(root, file)
150
+ train_audio_list.append(audio_path)
151
+ for folder in test:
152
+ for (root,dirs,files) in os.walk(os.path.join(self.config.path_to_data, mic, folder)):
153
+ if len(files) != 0:
154
+ for file in files:
155
+ audio_path = os.path.join(root, file)
156
+ test_audio_list.append(audio_path)
157
+ elif mic == "Audio Separate StandingMic":
158
+ complete_audio_list = []
159
+ prev_file = "placeholderplaceholder"
160
+ for (root,dirs,files) in os.walk(os.path.join(self.config.path_to_data, mic), topdown=True):
161
+ if len(files) != 0:
162
+ for file in files:
163
+ audio_path = os.path.join(root, file)
164
+ complete_audio_list.append(audio_path)
165
+ if file[:14] != prev_file[:14]:
166
+ audio_list.append(audio_path)
167
+ train, test = train_test_split(audio_list, test_size=0.3, random_state=42, shuffle=True)
168
+ for path in train:
169
+ train_audio_list.extend([x for x in complete_audio_list if x[-27:-13]==path[-27:-13]])
170
+ for path in test:
171
+ test_audio_list.extend([x for x in complete_audio_list if x[-27:-13]==path[-27:-13]])
172
+
173
 
174
+
175
+ for (root,dirs,files) in os.walk(os.path.join(self.config.path_to_data, mic), topdown=True):
176
+ if len(files) != 0:
177
+ for file in files:
178
+ # get audio path
179
+ audio_path = os.path.join(root, file)
180
+ audio_list.append(audio_path)
181
+ train, test = train_test_split(audio_list, test_size=0.3, random_state=42, shuffle=True)
182
+ train_audio_list.extend(train)
183
+ test_audio_list.extend(test)
184
+ print(f"train_audio_list: { train_audio_list}")
185
+ print(f"test_audio_list: { test_audio_list}")
 
186
 
187
  # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
188
  # 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.
 
191
  datasets.SplitGenerator(
192
  name=datasets.Split.TRAIN,
193
  gen_kwargs={
194
+ # "path_to_data": os.path.join(self.config.path_to_data, "Audio Same CloseMic"),
195
+ "audio_list":audio_list,
 
 
 
 
196
  },
197
  ),
198
  datasets.SplitGenerator(
199
  name=datasets.Split.TEST,
200
  gen_kwargs={
201
+ # "path_to_data": os.path.join(self.config.path_to_data, "Audio Same CloseMic"),
202
+ "audio_list": audio_list,
 
 
 
 
203
  },
204
  ),
205
  ]
 
207
  # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
208
  def _generate_examples(
209
  self,
210
+ audio_list,
 
 
 
 
211
  ):
212
  id_ = 0
213
+ for audio_path in audio_list:
214
+ file = os.path.split(audio_path)[-1]
215
+ folder = os.path.split(os.path.split(audio_path)[0])[-1]
216
+
217
+ # get script_path
218
+ if folder.split("_")[0] == "conf":
219
+ # mic == "Audio Separate IVR"
220
+ script_path = os.path.join(self.config.path_to_data, "Scripts Separate", folder+"_"+file[:-4]+".TextGrid")
221
+ elif folder.split()[1] == "Same":
222
+ # mic == "Audio Same CloseMic IVR"
223
+ script_path = os.path.join(self.config.path_to_data, "Scripts Same", file[:-4]+".TextGrid")
224
+ elif folder.split()[1] == "Separate":
225
+ # mic == "Audio Separate StandingMic":
226
+ script_path = os.path.join(self.config.path_to_data, "Scripts Separate", file[:-4]+".TextGrid")
227
+
228
+
229
+ # LOAD TRANSCRIPT
230
+ # script_path = os.path.join(self.config.path_to_data, 'Scripts Same', '3000-1.TextGrid')
231
+ # check that the textgrid file can be read
232
+ try:
233
+ tg = textgrid.TextGrid.fromFile(script_path)
234
+ except:
235
+ print(f"error reading textgrid file")
236
+ continue
237
+ # LOAD AUDIO
238
+ # archive_path = os.path.join(path_to_data, '3000-1.wav')
239
+ # check that archive path exists, else will not open the archive
240
+ if os.path.exists(audio_path):
241
+ # read into a numpy array using soundfile
242
+ data, sr = sf.read(audio_path)
243
+ result = {}
244
+ i = 0
245
+ intervalLength = 0
246
+ intervalStart = 0
247
+ transcript_list = []
248
+ filepath = os.path.join(self.config.path_to_data, 'tmp_clip.wav')
249
+ while i < (len(tg[0])-1):
250
+ transcript = cleanup_string(tg[0][i].mark)
251
+ if intervalLength == 0 and len(transcript) == 0:
252
+ intervalStart = tg[0][i].maxTime
253
+ i+=1
254
+ continue
255
+ intervalLength += tg[0][i].maxTime-tg[0][i].minTime
256
+ if intervalLength > INTERVAL_MAX_LENGTH:
257
+ print(f"INTERVAL LONGER THAN {intervalLength}")
258
+ result["transcript"] = transcript
259
+ result["interval"] = "start:"+str(tg[0][i].minTime)+", end:"+str(tg[0][i].maxTime)
260
+ result["audio"] = {"path": audio_path, "bytes": data[int(tg[0][i].minTime*sr):int(tg[0][i].maxTime*sr)], "sampling_rate":sr}
261
+ yield id_, result
262
+ id_+= 1
263
+ intervalLength = 0
264
+ else:
265
+ if (intervalLength + tg[0][i+1].maxTime-tg[0][i+1].minTime) < INTERVAL_MAX_LENGTH:
266
+ if len(transcript) != 0:
267
+ transcript_list.append(transcript)
268
+ i+=1
269
+ continue
270
+ if len(transcript) == 0:
271
+ spliced_audio = data[int(intervalStart*sr):int(tg[0][i].minTime*sr)]
272
+ else:
273
+ transcript_list.append(transcript)
274
+ spliced_audio = data[int(intervalStart*sr):int(tg[0][i].maxTime*sr)]
275
+ sf.write(filepath, spliced_audio, sr)
276
+ result["interval"] = "start:"+str(intervalStart)+", end:"+str(tg[0][i].maxTime)
277
+ result["audio"] = {"path": filepath, "bytes": spliced_audio, "sampling_rate":sr}
278
+ result["transcript"] = ' '.join(transcript_list)
279
+ yield id_, result
280
+ id_+= 1
281
+ intervalLength=0
282
+ intervalStart=tg[0][i].maxTime
283
+ transcript_list = []
284
+ i+=1
loadingScript_HF_Part1.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/PART1'
26
+ # _PATH_TO_DATA = './PART1/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,
55
+ )
56
+
57
+ # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
58
+ class NewDataset(datasets.GeneratorBasedBuilder):
59
+ """TODO: Short description of my dataset."""
60
+
61
+ VERSION = datasets.Version("1.1.0")
62
+
63
+ # This is an example of a dataset with multiple configurations.
64
+ # If you don't want/need to define several sub-sets in your dataset,
65
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
66
+
67
+ # If you need to make complex sub-parts in the datasets with configurable options
68
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
69
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
70
+
71
+ # You will be able to load one or the other configurations in the following list with
72
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
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,
101
+ # This defines the different columns of the dataset and their types
102
+ features=features, # Here we define them above because they are different between the two configurations
103
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
104
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
105
+ supervised_keys=("audio", "transcript"),
106
+ # Homepage of the dataset for documentation
107
+ homepage=_HOMEPAGE,
108
+ # License for the dataset if available
109
+ license=_LICENSE,
110
+ # Citation for the dataset
111
+ citation=_CITATION,
112
+ task_templates=task_templates,
113
+ )
114
+
115
+ def _split_generators(self, dl_manager):
116
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
117
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
118
+ mics = (
119
+ _CHANNEL_CONFIGS
120
+ if self.config.channel == "all"
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 1).XLSX"))
142
+ speaker_df = pd.read_excel(path_to_speaker, dtype={'SCD/PART1': object})
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/PART1"])
148
+ test_speaker_ids.extend(X_test["SCD/PART1"])
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.
152
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
153
+ return [
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":["0001"],
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": ["0003"],
172
+ "mics": mics,
173
+ "dl_manager": dl_manager
174
+ },
175
+ ),
176
+ ]
177
+
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/PART1"]==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
+
textgrid ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit 19d3ea2f765a435bb22a529602532752361167c9