File size: 11,049 Bytes
f40b165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77161bf
f40b165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77161bf
f40b165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77161bf
f40b165
 
 
77161bf
f40b165
 
 
 
77161bf
 
 
 
 
f40b165
 
 
 
 
 
 
 
77161bf
 
 
 
 
f40b165
 
 
 
 
77161bf
 
 
f40b165
 
 
 
 
 
 
 
 
77161bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dd05dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112ec03
f40b165
 
 
 
 
 
 
 
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
import csv
import os
import urllib


import datasets
from datasets.utils.py_utils import size_str


import datasets
import requests
from datasets.utils.py_utils import size_str
from huggingface_hub import HfApi, HfFolder

# from .languages import LANGUAGES
#Used to get tar.gz file from mozilla website
from .release_stats import STATS



#Hard Links

_HOMEPAGE = "https://commonvoice.mozilla.org/en/datasets"

_LICENSE = "https://creativecommons.org/publicdomain/zero/1.0/"

_API_URL = "https://commonvoice.mozilla.org/api/v1"





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

    def __init__(self, name, version, **kwargs):
        self.language = "bn"  # kwargs.pop("language", None)
        self.release_date = "2022-04-27"  # kwargs.pop("release_date", None)
        self.num_clips = 231120  # kwargs.pop("num_clips", None)
        self.num_speakers = 19863  # kwargs.pop("num_speakers", None)
        self.validated_hr = 56.61  # kwargs.pop("validated_hr", None)
        self.total_hr = 399.47  # kwargs.pop("total_hr", None)
        self.size_bytes = 8262390506  # kwargs.pop("size_bytes", None)
        self.size_human = size_str(self.size_bytes)
        description = (
            f"Common Voice speech to text dataset in {self.language} released on {self.release_date}. "
            f"The dataset comprises {self.validated_hr} hours of validated transcribed speech data "
            f"out of {self.total_hr} hours in total from {self.num_speakers} speakers. "
            f"The dataset contains {self.num_clips} audio clips and has a size of {self.size_human}."
        )
        super(CommonVoiceConfig, self).__init__(
            name=name,
            version=datasets.Version(version),
            description=description,
            **kwargs,
        )


class CommonVoice(datasets.GeneratorBasedBuilder):
    #DEFAULT_CONFIG_NAME = "en"
    DEFAULT_CONFIG_NAME = "bn"
    DEFAULT_WRITER_BATCH_SIZE = 1000

    BUILDER_CONFIGS = [
        CommonVoiceConfig(
            name="bn"#lang,
            version= '9.0.0' #STATS["version"],
            language= "Bengali" #LANGUAGES[lang],
            release_date= "2022-04-27" #STATS["date"],
            num_clips= 231120 #lang_stats["clips"],
            num_speakers= 19863 #lang_stats["users"],
            validated_hr= float(56.61) #float(lang_stats["validHrs"]),
            total_hr= float(399.47) #float(lang_stats["totalHrs"]),
            size_bytes= int(8262390506) #int(lang_stats["size"]),
        )
        #for lang, lang_stats in STATS["locales"].items()
    ]

    def _info(self):
        # total_languages = len(STATS["locales"])
        # total_valid_hours = STATS["totalValidHrs"]
        total_languages = 1 #len(STATS["locales"])
        total_valid_hours = float(399.47) #STATS["totalValidHrs"]
        description = (
            "Common Voice Bangla is bengali AI's initiative to help teach machines how real people speak in Bangla. "
            f"The dataset is for initial training of a general speech recognition model for Bangla."
        )
        features = datasets.Features(
            {
                "client_id": datasets.Value("string"),
                "path": datasets.Value("string"),
                "audio": datasets.features.Audio(sampling_rate=48_000),
                "sentence": datasets.Value("string"),
                "up_votes": datasets.Value("int64"),
                "down_votes": datasets.Value("int64"),
                "age": datasets.Value("string"),
                "gender": datasets.Value("string"),
                "accent": datasets.Value("string"),
                "locale": datasets.Value("string"),
                "segment": datasets.Value("string"),
            }
        )

        return datasets.DatasetInfo(
            description=description,
            features=features,
            supervised_keys=None,
            # homepage=_HOMEPAGE,
            license=_LICENSE,
            # citation=_CITATION,
            version=self.config.version,            
            #task_templates=[
            #    AutomaticSpeechRecognition(audio_file_path_column="path", transcription_column="sentence")
            #],
        )


    def _get_bundle_url(self, locale, url_template):
        # path = encodeURIComponent(path)
        path = url_template.replace("{locale}", locale)
        path = urllib.parse.quote(path.encode("utf-8"), safe="~()*!.'")
        # use_cdn = self.config.size_bytes < 20 * 1024 * 1024 * 1024
        # response = requests.get(f"{_API_URL}/bucket/dataset/{path}/{use_cdn}", timeout=10.0).json()
        response = requests.get(
            f"{_API_URL}/bucket/dataset/{path}", timeout=10.0
        ).json()
        return response["url"]

    def _log_download(self, locale, bundle_version, auth_token):
        if isinstance(auth_token, bool):
            auth_token = HfFolder().get_token()
        whoami = HfApi().whoami(auth_token)
        email = whoami["email"] if "email" in whoami else ""
        payload = {"email": email, "locale": locale, "dataset": bundle_version}
        requests.post(f"{_API_URL}/{locale}/downloaders", json=payload).json()

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        hf_auth_token = dl_manager.download_config.use_auth_token
        if hf_auth_token is None:
            raise ConnectionError(
                "Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset"
            )

        bundle_url_template = STATS["bundleURLTemplate"]
        bundle_version = bundle_url_template.split("/")[0]
        dl_manager.download_config.ignore_url_params = True

        self._log_download(self.config.name, bundle_version, hf_auth_token)
        archive_path = dl_manager.download(
            self._get_bundle_url(self.config.name, bundle_url_template)
        )
        local_extracted_archive = (
            dl_manager.extract(archive_path) if not dl_manager.is_streaming else None
        )

        if self.config.version < datasets.Version("5.0.0"):
            path_to_data = ""
        else:
            path_to_data = "/".join([bundle_version, self.config.name])
        path_to_clips = "/".join([path_to_data, "clips"]) if path_to_data else "clips"

        #we provide our custom csvs with the huggingface repo so,
        path_to_tsvs = "/" + "bengali_ai_tsv" + "/"

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "local_extracted_archive": local_extracted_archive,
                    "archive_iterator": dl_manager.iter_archive(archive_path),
                    #"metadata_filepath": "/".join([path_to_data, "train.tsv"])
                    # if path_to_data
                    # else "train.tsv",
                    #custom train.tsv
                    "metadata_filepath": "/".join([path_to_tsvs, "train.tsv"]),
                    "path_to_clips": path_to_clips,
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "local_extracted_archive": local_extracted_archive,
                    "archive_iterator": dl_manager.iter_archive(archive_path),
                    #"metadata_filepath": "/".join([path_to_data, "test.tsv"])
                    # if path_to_data
                    # else "test.tsv",
                    #custom test.tsv
                    "metadata_filepath": "/".join([path_to_tsvs, "test.tsv"]),
                    "path_to_clips": path_to_clips,
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "local_extracted_archive": local_extracted_archive,
                    "archive_iterator": dl_manager.iter_archive(archive_path),
                    # "metadata_filepath": "/".join([path_to_data, "dev.tsv"])
                    # if path_to_data
                    # else "dev.tsv",
                    #custom test.tsv
                    "metadata_filepath": "/".join([path_to_tsvs, "dev.tsv"]),
                    "path_to_clips": path_to_clips,
                },
            ),
        ]



    def _generate_examples(
        self,
        local_extracted_archive,
        archive_iterator,
        metadata_filepath,
        path_to_clips,
    ):
        """Yields examples."""
        data_fields = list(self._info().features.keys())
        metadata = {}
        metadata_found = False
        for path, f in archive_iterator:
            if path == metadata_filepath:
                metadata_found = True
                lines = (line.decode("utf-8") for line in f)
                reader = csv.DictReader(lines, delimiter="\t", quoting=csv.QUOTE_NONE)
                for row in reader:
                    # set absolute path for mp3 audio file
                    if not row["path"].endswith(".mp3"):
                        row["path"] += ".mp3"
                    row["path"] = os.path.join(path_to_clips, row["path"])
                    # accent -> accents in CV 8.0
                    if "accents" in row:
                        row["accent"] = row["accents"]
                        del row["accents"]
                    # if data is incomplete, fill with empty values
                    for field in data_fields:
                        if field not in row:
                            row[field] = ""
                    metadata[row["path"]] = row
            elif path.startswith(path_to_clips):
                assert metadata_found, "Found audio clips before the metadata TSV file."
                if not metadata:
                    break
                if path in metadata:
                    result = metadata[path]
                    # set the audio feature and the path to the extracted file
                    path = (
                        os.path.join(local_extracted_archive, path)
                        if local_extracted_archive
                        else path
                    )
                    result["audio"] = {"path": path, "bytes": f.read()}
                    # set path to None if the audio file doesn't exist locally (i.e. in streaming mode)
                    result["path"] = path if local_extracted_archive else None

                    yield path, result



# 'bn': {'duration': 1438112808, 'reportedSentences': 693, 'buckets': {'dev': 7748, 'invalidated': 5844, 'other': 192522,
# 'reported': 717, 'test': 7748, 'train': 14503, 'validated': 32754}, 'clips': 231120, 'splits': {'accent': {'': 1},
# 'age': {'thirties': 0.02, 'twenties': 0.22, '': 0.72, 'teens': 0.04, 'fourties': 0},
#  'gender': {'male': 0.24, '': 0.72, 'female': 0.04, 'other': 0}}, 'users': 19863, 'size': 8262390506,
#  'checksum': '599a5f7c9e55a297928da390345a19180b279a1f013081e7255a657fc99f98d5', 'avgDurationSecs': 6.222,
#   'validDurationSecs': 203807.316, 'totalHrs': 399.47, 'validHrs': 56.61},