File size: 10,859 Bytes
900248f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ef3490
900248f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d237cba
9ef3490
 
 
900248f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ef3490
900248f
 
 
 
 
 
 
9ef3490
900248f
 
 
9ef3490
900248f
 
 
 
 
 
 
 
 
 
 
 
9ef3490
 
 
 
 
900248f
 
 
 
 
 
 
 
 
 
9ef3490
 
 
900248f
 
 
 
 
 
 
 
 
 
 
 
ab94660
 
900248f
 
 
 
 
 
ab94660
 
900248f
 
 
 
 
 
 
 
ab94660
 
900248f
 
 
 
 
 
 
 
ab94660
 
900248f
 
 
 
 
 
ab94660
900248f
 
 
 
 
 
 
 
9ef3490
 
900248f
 
 
 
 
 
ab94660
900248f
9ef3490
ab94660
900248f
ab94660
900248f
ab94660
9ef3490
900248f
 
 
ab94660
900248f
 
 
 
 
 
 
9ef3490
900248f
 
 
 
 
9ef3490
900248f
ab94660
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2022 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.

"""
Multilingual Spoken Words Corpus is a large and growing audio dataset of spoken
words in 50 languages collectively spoken by over 5 billion people, for academic
research and commercial applications in keyword spotting and spoken term search,
licensed under CC-BY 4.0. The dataset contains more than 340,000 keywords,
totaling 23.4 million 1-second spoken examples (over 6,000 hours).
 """


import csv
import os.path
from functools import partial

import datasets


_CITATION = """\
@inproceedings{mazumder2021multilingual,
  title={Multilingual Spoken Words Corpus},
  author={Mazumder, Mark and Chitlangia, Sharad and Banbury, Colby and Kang, Yiping and Ciro, Juan Manuel and Achorn, Keith and Galvez, Daniel and Sabini, Mark and Mattson, Peter and Kanter, David and others},
  booktitle={Thirty-fifth Conference on Neural Information Processing Systems Datasets and Benchmarks Track (Round 2)},
  year={2021}
}
"""

_DESCRIPTION = """\
Multilingual Spoken Words Corpus is a large and growing audio dataset of spoken
words in 50 languages collectively spoken by over 5 billion people, for academic
research and commercial applications in keyword spotting and spoken term search,
licensed under CC-BY 4.0. The dataset contains more than 340,000 keywords,
totaling 23.4 million 1-second spoken examples (over 6,000 hours). The dataset
has many use cases, ranging from voice-enabled consumer devices to call center
automation. This dataset is generated by applying forced alignment on crowd-sourced sentence-level
audio to produce per-word timing estimates for extraction.
All alignments are included in the dataset.
"""

_HOMEPAGE = "https://mlcommons.org/en/multilingual-spoken-words/"

_LICENSE = "CC-BY 4.0."

_VERSION = datasets.Version("1.0.0")

_BASE_URL = "data/"
_AUDIO_URL = _BASE_URL + "{format}/{lang}/{split}/audio/{n}.tar.gz"
_N_FILES_URL = _BASE_URL + "{format}/{lang}/{split}/n_files.txt"
_SPLITS_URL = _BASE_URL + "splits/{lang}/splits.tar.gz"

_GENDERS = ["MALE", "FEMALE", "OTHER", "NAN"]

_LANGUAGES = [
    "ar",
    "as",
    "br",
    "ca",
    "cnh",
    "cs",
    "cv",
    "cy",
    "de",
    "dv",
    "el",
    "en",
    "eo",
    "es",
    "et",
    "eu",
    "fa",
    "fr",
    "fy-NL",
    "ga-IE",
    "gn",
    "ha",
    "ia",
    "id",
    "it",
    "ka",
    "ky",
    "lt",
    "lv",
    "mn",
    "mt",
    "nl",
    "or",
    "pl",
    "pt",
    "rm-sursilv",
    "rm-vallader",
    "ro",
    "ru",
    "rw",
    "sah",
    "sk",
    "sl",
    "sv-SE",
    "ta",
    "tr",
    "tt",
    "uk",
    "vi",
    "zh-CN",
]


class MlSpokenWordsConfig(datasets.BuilderConfig):
    """BuilderConfig for MlSpokenWords."""

    def __init__(self, *args, languages, format="wav", **kwargs):
        """BuilderConfig for MlSpokenWords.
        Args:
            languages (:obj:`Union[List[str], str]`): language or list of languages to load
            **kwargs: keyword arguments forwarded to super.
        """
        super().__init__(
            *args,
            name="+".join(languages) + "_" + format if isinstance(languages, list) else languages + "_" + format,
            **kwargs,
        )
        self.languages = languages if isinstance(languages, list) else [languages]
        self.format = format


class MlSpokenWords(datasets.GeneratorBasedBuilder):
    """
    Multilingual Spoken Words Corpus is a large and growing audio dataset of spoken
    words in 50 languages collectively spoken by over 5 billion people, for academic
    research and commercial applications in keyword spotting and spoken term search,
    licensed under CC-BY 4.0. The dataset contains more than 340,000 keywords,
    totaling 23.4 million 1-second spoken examples (over 6,000 hours).
    """

    VERSION = _VERSION
    BUILDER_CONFIGS = [
        MlSpokenWordsConfig(languages=[lang], format="wav", version=_VERSION) for lang in _LANGUAGES
    ] + [
        MlSpokenWordsConfig(languages=[lang], format="opus", version=_VERSION) for lang in _LANGUAGES
    ]
    BUILDER_CONFIG_CLASS = MlSpokenWordsConfig

    def _info(self):
        features = datasets.Features(
            {
                "file": datasets.Value("string"),
                "is_valid": datasets.Value("bool"),
                "language": datasets.ClassLabel(names=self.config.languages),
                "speaker_id": datasets.Value("string"),
                "gender": datasets.ClassLabel(names=_GENDERS),
                "keyword": datasets.Value("string"),  # 340k unique keywords
                "audio": datasets.Audio(sampling_rate=48_000) if self.config.format == "opus" \
                    else datasets.Audio(sampling_rate=16_000),
            }
        )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        splits_archive_path = [dl_manager.download(_SPLITS_URL.format(lang=lang)) for lang in self.config.languages]
        download_audio = partial(_download_audio_archives, dl_manager=dl_manager, format=self.config.format)
        download_extract_audio = partial(_download_extract_audio_archives, dl_manager=dl_manager, format=self.config.format)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "audio_archives": [download_audio(split="train", lang=lang) for lang in self.config.languages],
                    "local_audio_archives_paths": [download_extract_audio(split="train", lang=lang) for lang in
                                                   self.config.languages] if not dl_manager.is_streaming else None,
                    "splits_archives": [dl_manager.iter_archive(path) for path in splits_archive_path],
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "audio_archives": [download_audio(split="dev", lang=lang) for lang in self.config.languages],
                    "local_audio_archives_paths": [download_extract_audio(split="dev", lang=lang) for lang in
                                                   self.config.languages] if not dl_manager.is_streaming else None,
                    "splits_archives": [dl_manager.iter_archive(path) for path in splits_archive_path],
                    "split": "dev",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "audio_archives": [download_audio(split="test", lang=lang) for lang in self.config.languages],
                    "local_audio_archives_paths": [download_extract_audio(split="test", lang=lang) for lang in
                                                   self.config.languages] if not dl_manager.is_streaming else None,
                    "splits_archives": [dl_manager.iter_archive(path) for path in splits_archive_path],
                    "split": "test",
                },
            ),
        ]

    def _generate_examples(self, audio_archives, local_audio_archives_paths, splits_archives, split):
        metadata = dict()
        for lang_idx, lang in enumerate(self.config.languages):
            for split_filename, split_file in splits_archives[lang_idx]:
                if split_filename.split(".csv")[0] == split:
                    csv_reader = csv.reader([line.decode("utf-8") for line in split_file.readlines()], delimiter=",")
                    for i, (link, word, is_valid, speaker, gender) in enumerate(csv_reader):
                        if i == 0:
                            continue
                        audio_id, audio_ext = os.path.splitext("_".join(link.split("/")))
                        metadata[audio_id] = {
                            "keyword": word,
                            "is_valid": is_valid,
                            "speaker_id": speaker,
                            "gender": gender if gender and gender != "NA" else "NAN",  # some values are "NA"
                        }

            for archive_idx, audio_archive in enumerate(audio_archives[lang_idx]):
                for audio_filename, audio_file in audio_archive:
                    audio_id, audio_ext = os.path.splitext(audio_filename)
                    path = os.path.join(local_audio_archives_paths[lang_idx][archive_idx], audio_filename) if local_audio_archives_paths else audio_filename
                    yield audio_filename, {
                        "file": path if local_audio_archives_paths else None,
                        "language": lang,
                        "audio": {"path": path, "bytes": audio_file.read()},
                        **metadata[audio_id],
                    }


def _download_audio_archives_paths(dl_manager, lang, format, split):
    """
    All audio files are stored in several .tar.gz archives with names like 0.tar.gz, 1.tar.gz, ...
    Number of archives stored in a separate .txt file (n_files.txt)

    Prepare all the audio archives for iterating over them and their audio files.
    """

    n_files_url = _N_FILES_URL.format(lang=lang, format=format, split=split)
    n_files_path = dl_manager.download(n_files_url)

    with open(n_files_path, "r", encoding="utf-8") as file:
        n_files = int(file.read().strip())  # the file contains a number of archives

    archive_urls = [_AUDIO_URL.format(lang=lang, format=format, split=split, n=i) for i in range(n_files)]

    return dl_manager.download(archive_urls)


# for default, non-streaming case
def _download_extract_audio_archives(dl_manager, lang, format, split):
    archives_paths = _download_audio_archives_paths(dl_manager, lang, format, split)
    return [dl_manager.extract(archive_path) for archive_path in archives_paths]


# for streaming case
def _download_audio_archives(dl_manager, lang, format, split):
    archives_paths = _download_audio_archives_paths(dl_manager, lang, format, split)
    return [dl_manager.iter_archive(archive_path) for archive_path in archives_paths]