File size: 9,521 Bytes
a71e4b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1102f82
86a1eaa
a71e4b6
 
1c1db08
9a86ac4
b799535
 
 
9a86ac4
a71e4b6
 
 
9fe2df1
 
a71e4b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2109ac9
a71e4b6
 
 
 
 
 
 
 
 
 
 
86a1eaa
 
 
 
 
a71e4b6
 
 
 
 
 
 
4bf433a
 
018c60b
9a86ac4
a71e4b6
 
 
 
 
 
 
 
9d7b476
a71e4b6
 
 
 
 
 
cde998c
a88a8b1
6e6b986
a71e4b6
 
 
 
 
9a86ac4
 
a71e4b6
 
 
 
 
 
9a86ac4
 
29cd8e8
 
 
 
 
 
9fe2df1
9a86ac4
a71e4b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a86ac4
a71e4b6
 
 
 
 
9a86ac4
 
1102f82
 
86a1eaa
1102f82
527f680
1102f82
 
86a1eaa
 
 
 
 
 
 
 
1102f82
 
 
527f680
1102f82
9a86ac4
0f67128
 
9a86ac4
 
0f67128
9a86ac4
 
 
86a1eaa
 
 
 
0f67128
 
9a86ac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2021 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Common Voice Dataset"""


import datasets
from datasets.tasks import AutomaticSpeechRecognition
import pandas as pd
import re


_DATA_URL = "https://dutudn-my.sharepoint.com/:u:/g/personal/122180028_sv1_dut_udn_vn/EYsBHQzK4JVFhmN50e5vRFMBizbGJGXe_HlxV9uRlLaTyg?e=s1czWW?download=1"
_PROMPTS_URLS = {
    "train": "https://drive.google.com/uc?export=download&id=13sANpjVoF9FIXj_rGGNvVNuK0GscPVsW",
    "test": "https://drive.google.com/uc?export=download&id=173oUWFMbeFUBnfoVke4dH2fiHdgOu9xb",
    "validation": "https://drive.google.com/uc?export=download&id=1J1zTG0IMPIRWnnw3dyr2UTyiq-KvlcX5"
}

_DESCRIPTION = """\
Common Voice is Mozilla's initiative to help teach machines how real people speak.
The dataset currently consists of 7,335 validated hours of speech in 60 languages, but we’re always adding more voices
 and languages.
"""

_LANGUAGES = {
    "vi": {
        "Language": "Vietnamese",
        "Date": "2020-12-11",
        "Size": "50 MB",
        "Version": "vi_1h_2020-12-11",
        "Validated_Hr_Total": 0.74,
        "Overall_Hr_Total": 1,
        "Number_Of_Voice": 62,
    },
}


class CustomCommonVoiceConfig(datasets.BuilderConfig):
    """BuilderConfig for CommonVoice."""

    def __init__(self, name, sub_version, **kwargs):
        """
        Args:
          data_dir: `string`, the path to the folder containing the files in the
            downloaded .tar
          citation: `string`, citation for the data set
          url: `string`, url for information about the data set
          **kwargs: keyword arguments forwarded to super.
        """
        self.sub_version = sub_version
        self.language = kwargs.pop("language", None)
        self.date_of_snapshot = kwargs.pop("date", None)
        self.size = kwargs.pop("size", None)
        self.validated_hr_total = kwargs.pop("val_hrs", None)
        self.total_hr_total = kwargs.pop("total_hrs", None)
        self.num_of_voice = kwargs.pop("num_of_voice", None)
        description = f"Common Voice speech to text dataset in {self.language} version " \
                      f"{self.sub_version} of {self.date_of_snapshot}. " \
                      f"The dataset comprises {self.validated_hr_total} of validated transcribed speech data from " \
                      f"{self.num_of_voice} speakers. The dataset has a size of {self.size} "
        super(CustomCommonVoiceConfig, self).__init__(
            name=name, version=datasets.Version("0.1.0", ""), description=description, **kwargs
        )


class CustomCommonVoice(datasets.GeneratorBasedBuilder):

    DEFAULT_WRITER_BATCH_SIZE = 1000
    BUILDER_CONFIGS = [
        CustomCommonVoiceConfig(
            name=lang_id,
            language=_LANGUAGES[lang_id]["Language"],
            sub_version=_LANGUAGES[lang_id]["Version"],
            # date=_LANGUAGES[lang_id]["Date"],
            # size=_LANGUAGES[lang_id]["Size"],
            # val_hrs=_LANGUAGES[lang_id]["Validated_Hr_Total"],
            # total_hrs=_LANGUAGES[lang_id]["Overall_Hr_Total"],
            # num_of_voice=_LANGUAGES[lang_id]["Number_Of_Voice"],
        )
        for lang_id in _LANGUAGES.keys()
    ]

    def _info(self):
        features = datasets.Features(
            {
                "file_path": datasets.Value("string"),
                "script": datasets.Value("string"),
                "duration": datasets.Value("float32"),
                "audio": datasets.Audio(sampling_rate=16_000),
            }
        )

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            supervised_keys=None,
            task_templates=[
                AutomaticSpeechRecognition(audio_file_path_column="file_path", transcription_column="script")
            ],
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        archive = dl_manager.download(_DATA_URL)
        tsv_files = dl_manager.download(_PROMPTS_URLS)
        path_to_data = "content/data_2/"
        path_to_clips = path_to_data + "audio"

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "tsv_files": tsv_files["train"],
                    "audio_files": dl_manager.iter_archive(archive),
                    "path_to_clips": path_to_clips,
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "tsv_files": tsv_files["test"],
                    "audio_files": dl_manager.iter_archive(archive),
                    "path_to_clips": path_to_clips,
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "tsv_files": tsv_files["validation"],
                    "audio_files": dl_manager.iter_archive(archive),
                    "path_to_clips": path_to_clips,
                },
            ),
            # datasets.SplitGenerator(
            #     name="other",
            #     gen_kwargs={
            #         "files": dl_manager.iter_archive(archive),
            #         "filepath": "/".join([path_to_data, "other.tsv"]),
            #         "path_to_clips": path_to_clips,
            #     },
            # ),
            # datasets.SplitGenerator(
            #     name="invalidated",
            #     gen_kwargs={
            #         "files": dl_manager.iter_archive(archive),
            #         "filepath": "/".join([path_to_data, "invalidated.tsv"]),
            #         "path_to_clips": path_to_clips,
            #     },
            # ),
        ]

    def _generate_examples(self, tsv_files, audio_files, path_to_clips):
        """Yields examples."""
        data_fields = list(self._info().features.keys())

        # audio is not a header of the csv files
        data_fields.remove("audio")
        examples = {}

        df = pd.read_csv(tsv_files, sep="\t", header=0)
        df = df.dropna()
        chars_to_ignore_regex = r'[,?.!\-;:"“%\'�]'

        for file_path, script, duration in zip(df["file_path"], df["script"], df["duration"]):
            # set full path for mp3 audio file
            audio_path = path_to_clips + "/" + file_path

            # Preprocessing script
            if ":" in script:
                two_dot_index = script.index(":")
                script = script[two_dot_index + 1:]
            script = script.replace("\n", " ")
            script = re.sub(chars_to_ignore_regex, '', script).lower()

            examples[audio_path] = {
                "file_path": audio_path,
                "script": script,
                "duration": duration
            }

        # inside_clips_dir = False

        for path, f in audio_files:
            if path.startswith(path_to_clips):
                # inside_clips_dir = True
                if path in examples:
                    audio = {"path": path, "bytes": f.read()}
                    yield path, {**examples[path], "audio": audio}
            # elif "custom_common_voice.tsv" in path:
            #     continue
            # elif ".txt" in path:
            #     continue
            # elif inside_clips_dir:
            #     break

        # for path, f in tsv_files:
        #     if path == filepath:
        #         metadata_found = True
        #         lines = f.readlines()
        #         headline = lines[0]
        #         column_names = headline.strip().split("\t")
        #         assert (
        #             column_names == data_fields
        #         ), f"The file should have {data_fields} as column names, but has {column_names}"
        #         for line in lines[1:]:
        #             field_values = line.strip().split("\t")
        #             # set full path for mp3 audio file
        #             audio_path = path_to_clips + "/" + field_values[path_idx]
        #             all_field_values[audio_path] = field_values
        #     elif path.startswith(path_to_clips):
        #         assert metadata_found, "Found audio clips before the metadata TSV file."
        #         if not all_field_values:
        #             break
        #         if path in all_field_values:
        #             field_values = all_field_values[path]
        #
        #             # if data is incomplete, fill with empty values
        #             if len(field_values) < len(data_fields):
        #                 field_values += (len(data_fields) - len(field_values)) * ["''"]
        #
        #             result = {key: value for key, value in zip(data_fields, field_values)}
        #
        #             # set audio feature
        #             result["audio"] = {"path": path, "bytes": f.read()}
        #
        #             yield path, result