File size: 14,142 Bytes
6ea4d69
 
04228fb
6ea4d69
04228fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ea4d69
 
04228fb
 
6ea4d69
 
 
 
 
04228fb
6ea4d69
 
04228fb
6ea4d69
04228fb
6ea4d69
04228fb
cfdff6c
9f0db75
04228fb
 
6ea4d69
 
 
 
04228fb
6ea4d69
 
04228fb
6ea4d69
 
 
 
 
 
 
 
 
04228fb
6ea4d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04228fb
6ea4d69
 
04228fb
6ea4d69
 
 
 
 
 
 
 
 
 
04228fb
6ea4d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04228fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ea4d69
 
 
 
 
 
 
 
04228fb
 
6ea4d69
 
 
 
 
04228fb
 
6ea4d69
 
 
 
 
 
 
04228fb
6ea4d69
 
04228fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import os
import datasets
# import pandas as pd
from sklearn.model_selection import train_test_split
from textgrid import textgrid
import soundfile as sf
import re
import json

def cleanup_string(line):

    words_to_remove = ['(ppo)','(ppc)', '(ppb)', '(ppl)', '<s/>','<c/>','<q/>', '<fil/>', '<sta/>', '<nps/>', '<spk/>', '<non/>', '<unk>', '<s>', '<z>', '<nen>']

    formatted_line = re.sub(r'\s+', ' ', line).strip().lower()

    #detect all word that matches words in the words_to_remove list
    for word in words_to_remove:
        if re.search(word,formatted_line):
            # formatted_line = re.sub(word,'', formatted_line)
            formatted_line = formatted_line.replace(word,'')
            formatted_line = re.sub(r'\s+', ' ', formatted_line).strip().lower()
            # print("*** removed words: " + formatted_line)

    #detect '\[(.*?)\].' e.g. 'Okay [ah], why did I gamble?'
    #remove [ ] and keep text within
    if re.search('\[(.*?)\]', formatted_line):
        formatted_line = re.sub('\[(.*?)\]', r'\1', formatted_line).strip()
        #print("***: " + formatted_line)

    #detect '\((.*?)\).' e.g. 'Okay (um), why did I gamble?'
    #remove ( ) and keep text within
    if re.search('\((.*?)\)', formatted_line):
        formatted_line = re.sub('\((.*?)\)', r'\1', formatted_line).strip()
        # print("***: " + formatted_line)

    #detect '\'(.*?)\'' e.g. 'not 'hot' per se'
    #remove ' ' and keep text within
    if re.search('\'(.*?)\'', formatted_line):
        formatted_line = re.sub('\'(.*?)\'', r'\1', formatted_line).strip()
        #print("***: " + formatted_line)

    #remove punctation '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
    punctuation = '''!–;"\,./?@#$%^&*~''' 
    punctuation_list = str.maketrans("","",punctuation)
    formatted_line = re.sub(r'-', ' ', formatted_line)
    formatted_line = re.sub(r'_', ' ', formatted_line)
    formatted_line = formatted_line.translate(punctuation_list)
    formatted_line = re.sub(r'\s+', ' ', formatted_line).strip().lower()
    #print("***: " + formatted_line)

    return formatted_line



_DESCRIPTION = """\
The National Speech Corpus (NSC) is the first large-scale Singapore English corpus 
spearheaded by the Info-communications and Media Development Authority (IMDA) of Singapore.
"""

_CITATION = """\
"""
_CHANNEL_CONFIGS = sorted([
    "Audio Same CloseMic", "Audio Separate IVR", "Audio Separate StandingMic"
])

_HOMEPAGE = "https://www.imda.gov.sg/how-we-can-help/national-speech-corpus"

_LICENSE = ""

_PATH_TO_DATA = './IMDA - National Speech Corpus/PART3'
# _PATH_TO_DATA = './PART1/DATA'

INTERVAL_MAX_LENGTH = 25

class Minds14Config(datasets.BuilderConfig):
    """BuilderConfig for xtreme-s"""

    def __init__(
        self, channel, description, homepage, path_to_data
    ):
        super(Minds14Config, self).__init__(
            name=channel,
            version=datasets.Version("1.0.0", ""),
            description=self.description,
        )
        self.channel = channel
        self.description = description
        self.homepage = homepage
        self.path_to_data = path_to_data


def _build_config(channel):
    return Minds14Config(
        channel=channel,
        description=_DESCRIPTION,
        homepage=_HOMEPAGE,
        path_to_data=_PATH_TO_DATA,
    )

# TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
class NewDataset(datasets.GeneratorBasedBuilder):
    """TODO: Short description of my dataset."""

    VERSION = datasets.Version("1.1.0")

    # This is an example of a dataset with multiple configurations.
    # If you don't want/need to define several sub-sets in your dataset,
    # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

    # If you need to make complex sub-parts in the datasets with configurable options
    # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
    # BUILDER_CONFIG_CLASS = MyBuilderConfig

    # You will be able to load one or the other configurations in the following list with
    # data = datasets.load_dataset('my_dataset', 'first_domain')
    # data = datasets.load_dataset('my_dataset', 'second_domain')
    BUILDER_CONFIGS = []
    for channel in _CHANNEL_CONFIGS + ["all"]:
        BUILDER_CONFIGS.append(_build_config(channel))
    # BUILDER_CONFIGS = [_build_config(name) for name in _CHANNEL_CONFIGS + ["all"]]

    DEFAULT_CONFIG_NAME = "all"  # It's not mandatory to have a default configuration. Just use one if it make sense.

    def _info(self):
        # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
        task_templates = None
        features = datasets.Features(
            {
                "audio": datasets.features.Audio(sampling_rate=16000),
                "transcript": datasets.Value("string"),
                "mic": datasets.Value("string"),
                "audio_name": datasets.Value("string"),
                "interval": datasets.Value("string")
            }
        )
        
        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
            # specify them. They'll be used if as_supervised=True in builder.as_dataset.
            supervised_keys=("audio", "transcript"),
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
            task_templates=task_templates,
        )

    def _split_generators(self, dl_manager):
        # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
        # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
        mics = (
            _CHANNEL_CONFIGS
            if self.config.channel == "all"
            else [self.config.channel]
        )

        with (os.path.join(self.config.path_to_data, "directory_list.json"), "r") as f:
            directory_dict = json.load(f)
        
        train_audio_list = []
        test_audio_list = []
        for mic in mics:
            audio_list = []
            if mic == "Audio Same CloseMic":
                audio_list = [x for x in directory_dict[mic] if (x[-5] == 1) ]
                train, test = train_test_split(audio_list, test_size=0.3, random_state=42, shuffle=True)
                for path in train:
                    train_audio_list.append(os.path.join(self.config.path_to_data, mic, path))
                    s = list(path)
                    s[-5] = "2"
                    train_audio_list.append(os.path.join(self.config.path_to_data, mic, "".join(s)))
                for path in test:
                    test_audio_list.append(os.path.join(self.config.path_to_data, mic, path))
                    s = list(path)
                    s[-5] = "2"
                    test_audio_list.append(os.path.join(self.config.path_to_data, mic, "".join(s)))
            elif mic == "Audio Separate IVR":
                audio_list = [x.split("\\")[0] for x in directory_dict[mic]]
                train, test = train_test_split(audio_list, test_size=0.3, random_state=42, shuffle=True)
                for folder in train:
                    audios = [os.path.join(self.config.path_to_data, mic, x) for x in directory_dict[mic] if (x.split("\\")[0]==folder)]
                    train_audio_list.extend(audios)
                for folder in test:
                    audios = [os.path.join(self.config.path_to_data, mic, x) for x in directory_dict[mic] if (x.split("\\")[0]==folder)]
                    test_audio_list.extend(audios)
            elif mic == "Audio Separate StandingMic":
                audio_list = [x[:14] for x in directory_dict[mic]]
                audio_list = list(set(audio_list))
                train, test = train_test_split(audio_list, test_size=0.3, random_state=42, shuffle=True)
                for folder in train:
                    audios = [os.path.join(self.config.path_to_data, mic, x) for x in directory_dict[mic] if (x[:14]==folder)]
                    train_audio_list.extend(audios)
                for folder in test:
                    audios = [os.path.join(self.config.path_to_data, mic, x) for x in directory_dict[mic] if (x[:14]==folder)]
                    test_audio_list.extend(audios)
                            
        print(f"train_audio_list: { train_audio_list}")
        print(f"test_audio_list: { test_audio_list}")

        # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
        # 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.
        # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
        return [
            datasets.SplitGenerator(
            name=datasets.Split.TRAIN,
            gen_kwargs={
                # "path_to_data": os.path.join(self.config.path_to_data, "Audio Same CloseMic"),
                "audio_list": train_audio_list,
              },
          ),
          datasets.SplitGenerator(
            name=datasets.Split.TEST,
            gen_kwargs={
                # "path_to_data": os.path.join(self.config.path_to_data, "Audio Same CloseMic"),
                "audio_list": test_audio_list,
            },
        ),
        ]

    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(
            self,
            audio_list,
        ):
        id_ = 0
        for audio_path in audio_list:
            file = os.path.split(audio_path)[-1]
            folder = os.path.split(os.path.split(audio_path)[0])[-1]

            # get script_path
            if folder.split("_")[0] == "conf":
                # mic == "Audio Separate IVR"
                script_path = os.path.join(self.config.path_to_data, "Scripts Separate", folder+"_"+file[:-4]+".TextGrid")
            elif folder.split()[1] == "Same":
                # mic == "Audio Same CloseMic IVR"
                script_path = os.path.join(self.config.path_to_data, "Scripts Same", file[:-4]+".TextGrid")
            elif folder.split()[1] == "Separate":
                # mic == "Audio Separate StandingMic":
                script_path = os.path.join(self.config.path_to_data, "Scripts Separate", file[:-4]+".TextGrid")
            

            # LOAD TRANSCRIPT
            # script_path = os.path.join(self.config.path_to_data, 'Scripts Same', '3000-1.TextGrid')
            # check that the textgrid file can be read
            try:
                tg = textgrid.TextGrid.fromFile(script_path)
            except:
                print(f"error reading textgrid file")
                continue
            # LOAD AUDIO
            # archive_path = os.path.join(path_to_data, '3000-1.wav')
            # check that archive path exists, else will not open the archive
            if os.path.exists(audio_path):
                # read into a numpy array using soundfile
                data, sr = sf.read(audio_path)
                result = {}
                i = 0
                intervalLength = 0
                intervalStart = 0
                transcript_list = []
                filepath = os.path.join(self.config.path_to_data, 'tmp_clip.wav')
                while i < (len(tg[0])-1):
                    transcript = cleanup_string(tg[0][i].mark)
                    if intervalLength == 0 and len(transcript) == 0:
                        intervalStart = tg[0][i].maxTime
                        i+=1
                        continue
                    intervalLength += tg[0][i].maxTime-tg[0][i].minTime
                    if intervalLength > INTERVAL_MAX_LENGTH:
                        print(f"INTERVAL LONGER THAN {intervalLength}")
                        result["transcript"] = transcript
                        result["interval"] = "start:"+str(tg[0][i].minTime)+", end:"+str(tg[0][i].maxTime)
                        result["audio"] = {"path": audio_path, "bytes": data[int(tg[0][i].minTime*sr):int(tg[0][i].maxTime*sr)], "sampling_rate":sr}
                        yield id_, result
                        id_+= 1
                        intervalLength = 0
                    else:
                        if (intervalLength + tg[0][i+1].maxTime-tg[0][i+1].minTime) < INTERVAL_MAX_LENGTH:
                            if len(transcript) != 0:
                                transcript_list.append(transcript)
                            i+=1
                            continue
                        if len(transcript) == 0:
                            spliced_audio = data[int(intervalStart*sr):int(tg[0][i].minTime*sr)]
                        else:
                            transcript_list.append(transcript)
                            spliced_audio = data[int(intervalStart*sr):int(tg[0][i].maxTime*sr)]
                        sf.write(filepath, spliced_audio, sr)
                        result["interval"] = "start:"+str(intervalStart)+", end:"+str(tg[0][i].maxTime)
                        result["audio"] = {"path": filepath, "bytes": spliced_audio, "sampling_rate":sr}
                        result["transcript"] = ' '.join(transcript_list)
                        yield id_, result
                        id_+= 1
                        intervalLength=0
                        intervalStart=tg[0][i].maxTime
                        transcript_list = []
                    i+=1