File size: 11,583 Bytes
a239d5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e594a17
 
 
9c93bb1
7c0e406
a239d5a
 
 
4411402
a239d5a
 
 
 
 
4411402
a239d5a
 
 
 
 
 
 
 
 
 
4411402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75fceb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a239d5a
 
 
 
1eecf83
a239d5a
4411402
 
 
 
 
a239d5a
4411402
a239d5a
 
 
 
 
 
 
4411402
75fceb6
 
 
 
4411402
75fceb6
4411402
 
 
 
 
 
 
 
 
75fceb6
 
 
4411402
 
75fceb6
 
 
4411402
75fceb6
4411402
 
 
 
75fceb6
a239d5a
 
 
75fceb6
0b720c8
a239d5a
 
 
 
 
 
 
48be34f
a239d5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75fceb6
4411402
a239d5a
 
 
 
 
1042eff
931cf65
 
 
 
 
 
7dd0ea4
4411402
 
 
 
a239d5a
 
1042eff
 
 
4411402
 
 
9d61f37
 
4411402
a239d5a
 
 
 
 
 
 
 
472576b
a239d5a
31583b5
 
 
 
 
 
 
 
 
 
 
a239d5a
 
 
 
 
 
 
 
27520da
a239d5a
 
 
 
4411402
 
75fceb6
 
 
 
a239d5a
 
9c93bb1
 
75fceb6
 
a239d5a
 
 
 
 
48be34f
a239d5a
 
 
 
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
# coding=utf-8
# Copyright 2023 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.
""" AfriSpeech-200 Dataset"""

# Adapted from
# https://huggingface.co/datasets/vivos/blob/main/vivos.py
# https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0/blob/main/common_voice_11_0.py
# https://huggingface.co/datasets/PolyAI/minds14/blob/main/minds14.py
# https://huggingface.co/docs/datasets/share#clone-the-repository

import csv
import os
import json

import datasets
from datasets.utils.py_utils import size_str
from tqdm import tqdm

from .accent_stats import ACCENT_STATS

_CITATION = """ TBD """

_DESCRIPTION = """\
AFRISPEECH-200 is a 200hr Pan-African speech corpus for clinical and general domain English accented ASR; 
a dataset with 120 African accents from 13 countries and 2,463 unique African speakers. 
Our goal is to raise awareness for and advance Pan-African English ASR research, 
especially for the clinical domain. 
"""

ACCENT_MAPPER = {
    'akan (fante)': 'akan-fante',
    'igbo and yoruba': 'igbo-and-yoruba',
    'ijaw(nembe)': 'ijaw-nembe',
    'luganda and kiswahili': 'luganda-and-kiswahili',
    'luo, swahili': 'luo-swahili',
    'nasarawa eggon': 'nasarawa-eggon',
    'south african english': 'south-african-english',
    'southern sotho': 'southern-sotho', 
    'swahili ,luganda ,arabic': 'swahili-luganda-arabic',
    'venda and xitsonga': 'venda-and-xitsonga',
    'yala mbembe': 'yala-mbembe',
    'yoruba, hausa': 'yoruba-hausa'
}
ACCENT_MAPPER_REVERSED = {v:k for k,v in ACCENT_MAPPER.items()}

_ALL_CONFIGS = [
       'yoruba', 'igbo', 'swahili', 'ijaw', 'xhosa', 'twi', 'luhya',
       'igala', 'urhobo', 'hausa', 'kiswahili', 'zulu', 'isizulu',
       'venda and xitsonga', 'borana', 'afrikaans', 'setswana', 'idoma',
       'izon', 'chichewa', 'ebira', 'tshivenda', 'isixhosa',
       'kinyarwanda', 'tswana', 'luganda', 'luo', 'venda', 'dholuo',
       'akan (fante)', 'sepedi', 'kikuyu', 'isindebele',
       'luganda and kiswahili', 'akan', 'sotho', 'south african english',
       'sesotho', 'swahili ,luganda ,arabic', 'shona', 'damara',
       'southern sotho', 'luo, swahili', 'ateso', 'meru', 'siswati',
       'portuguese', 'esan', 'nasarawa eggon', 'ibibio', 'isoko',
       'pidgin', 'alago', 'nembe', 'ngas', 'kagoma', 'ikwere', 'fulani',
       'bette', 'efik', 'edo', 'hausa/fulani', 'bekwarra', 'epie',
       'afemai', 'benin', 'nupe', 'tiv', 'okrika', 'etsako', 'ogoni',
       'kubi', 'gbagyi', 'brass', 'oklo', 'ekene', 'ika', 'berom', 'jaba',
       'itsekiri', 'ukwuani', 'yala mbembe', 'afo', 'english', 'ebiobo',
       'igbo and yoruba', 'okirika', 'kalabari', 'ijaw(nembe)', 'anaang',
       'eggon', 'bini', 'yoruba, hausa', 'ekpeye', 'bajju', 'kanuri',
       'delta', 'khana', 'ogbia', 'mada', 'mwaghavul', 'angas', 'ikulu',
       'eleme', 'igarra', 'etche', 'agatu', 'bassa', 'jukun', 'urobo',
       'ibani', 'obolo', 'idah', 'eket', 'nyandang', 'estako', 'ishan',
       'bassa-nge/nupe', 'bagi', 'gerawa'
    ]

_HOMEPAGE = "https://github.com/intron-innovation/AfriSpeech-Dataset-Paper"

_LICENSE = "http://creativecommons.org/licenses/by-nc-sa/4.0/"

# _BASE_URL = "https://huggingface.co/datasets/tobiolatunji/afrispeech-200/main/"

_AUDIO_URL = "audio/{accent}/{split}/{split}_{accent}_{shard_idx}.tar.gz"
_AUDIO_URL_ALL = "audio/{split}/{split}_{shard_idx}.tar.gz"

_TRANSCRIPT_URL = "transcripts/{accent}/{split}.csv"
_TRANSCRIPT_URL_ALL = "transcripts/{split}.csv"

_N_SHARDS_URL = "accents.json"

_SHARDS = {
    'train': 35,
    'dev': 2,
    'test': 4
}

    
class AfriSpeechConfig(datasets.BuilderConfig):
    """BuilderConfig for afrispeech"""

    def __init__(
        self, accent, **kwargs
    ):
        self.name = accent
        self.homepage = _HOMEPAGE
        self.num_clips = kwargs.pop("num_clips", None)
        self.num_speakers = kwargs.pop("num_speakers", None)
        self.duration_secs = kwargs.pop("duration", None)
        description = (
            f"AfriSpeech dataset in {accent} accent(s) with {self.num_clips} clips "
            f"{self.num_speakers} speakers and {self.duration_secs} seconds"  
        )
        super(AfriSpeechConfig, self).__init__(
            name=self.name,
            version=datasets.Version("1.0.0", ""),
            description=description,
            **kwargs,
        )


def _build_config(accent):
    return AfriSpeechConfig(
        accent=accent,
        num_clips=ACCENT_STATS[accent]["num_clips"] if ACCENT_STATS[accent]["num_clips"] else None,
        num_speakers=ACCENT_STATS[accent]["num_speakers"] if ACCENT_STATS[accent]["num_speakers"] else None,
        duration=round(ACCENT_STATS[accent]["duration"], 2) if ACCENT_STATS[accent]["duration"] else None,
    )

class AfriSpeech(datasets.GeneratorBasedBuilder):
    DEFAULT_WRITER_BATCH_SIZE = 1000
    VERSION = datasets.Version("1.0.0")
    BUILDER_CONFIGS = [_build_config(name) for name in ACCENT_STATS.keys()]

    def _info(self):
        description = _DESCRIPTION
        features = datasets.Features(
            {
                "speaker_id": datasets.Value("string"),
                "path": datasets.Value("string"),
                "audio_id": datasets.Value("string"),
                "audio": datasets.features.Audio(sampling_rate=44_100),
                "transcript": datasets.Value("string"),
                "age_group": datasets.Value("string"),
                "gender": datasets.Value("string"),
                "accent": datasets.Value("string"),
                "domain": datasets.Value("string"),
                "country": datasets.Value("string"),
                "duration": datasets.Value("float"),
            }
        )

        return datasets.DatasetInfo(
            description=description,
            features=features,
            supervised_keys=None,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
            version=self.VERSION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        # If several configurations are possible (listed in BUILDER_CONFIGS),
        # the configuration selected by the user is in self.config.name

        # 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
        
        accent = self.config.name
        n_shards = _SHARDS

        audio_urls = {}
        splits = ("train", "dev")  # , "test"
        for split in splits:
            if self.config.name == 'all':
                audio_urls[split] = []
                for accent in ACCENT_STATS:
                    if accent == "all" or split not in ACCENT_STATS[accent]:
                        continue
                    for i in range(ACCENT_STATS[accent][split]['shards']):
                        audio_urls[split].append(_AUDIO_URL.format(accent=accent, split=split, shard_idx=i))
            elif split in ACCENT_STATS[accent]:
                audio_urls[split] = [
                    _AUDIO_URL.format(accent=accent, split=split, 
                                      shard_idx=i) for i in range(ACCENT_STATS[accent][split]['shards'])
                ]
        archive_paths = dl_manager.download(audio_urls)
        local_extracted_archive_paths = dl_manager.extract(archive_paths) if not dl_manager.is_streaming else {}
        
        accent = self.config.name
        
        if accent == 'all':
            meta_urls = {split: _TRANSCRIPT_URL_ALL.format(split=split) for split in splits}
        else:
            meta_urls = {split: _TRANSCRIPT_URL.format(accent=accent, split=split) 
                         for split in splits if split in ACCENT_STATS[accent]}
        
        meta_paths = dl_manager.download_and_extract(meta_urls)

        split_generators = []
        split_names = {
            "train": datasets.Split.TRAIN,
            "dev": datasets.Split.VALIDATION,
            # "test": datasets.Split.TEST,
        }

        for split in splits:
            if split in ACCENT_STATS[self.config.name]:
                split_generators.append(
                    datasets.SplitGenerator(
                        name=split_names.get(split, split),
                        gen_kwargs={
                            "local_extracted_archive_paths": local_extracted_archive_paths.get(split),
                            "archives": [dl_manager.iter_archive(path) for path in archive_paths.get(split)],
                            "meta_path": meta_paths[split],
                        },
                    ),
                )

        return split_generators

    def _generate_examples(self, local_extracted_archive_paths, archives, meta_path):
        """Yields examples as (key, example) tuples."""
        # This method handles input defined in _split_generators to yield (key, example) tuples
        # from the dataset.
        # The `key` is here for legacy reason (tfds) and is not important in itself.
        data_fields = [key for key in self._info().features.keys() if key not in ["audio", "path"]]
        metadata = {}
        with open(meta_path, "r", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            for row in tqdm(reader, desc="Reading metadata..."):
                accent = ACCENT_MAPPER_REVERSED.get(self.config.name, self.config.name)
                if (row['accent'] == accent) or (accent == 'all'):
                    row["speaker_id"] = row["user_ids"]
                    audio_id = "/".join(row["audio_paths"].split("/")[-2:])
                    # if data is incomplete, fill with empty values
                    metadata[audio_id] = {field: row.get(field, "") for field in data_fields}

        for i, audio_archive in enumerate(archives):
            #for filename, file in tqdm(audio_archive, desc=f"Searching and Extracting audios for config {self.config.name}..."):
            for filename, file in audio_archive:
                # _, filename = os.path.split(filename)
                filename = "/".join(filename.split("/")[-2:])
                if filename in metadata:
                    result = dict(metadata[filename])
                    # set the audio feature and the path to the extracted file
                    path = os.path.join(local_extracted_archive_paths[i], filename) if local_extracted_archive_paths else filename
                    result["audio"] = {"path": path, "bytes": file.read()}
                    result["audio_id"] = filename.replace(".wav", "")
                    # set path to None if the audio file doesn't exist locally (i.e. in streaming mode)
                    result["path"] = path if local_extracted_archive_paths else filename

                    yield path, result