cahya commited on
Commit
c45df4d
·
1 Parent(s): 3bc1bcd

added new files

Browse files
Files changed (4) hide show
  1. audio.tgz +3 -0
  2. languages.py +9 -0
  3. release_stats.py +6 -0
  4. test01.py +213 -0
audio.tgz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba58e91bc9a87c57cb226a75a81734811ad274d176d9210e6549184822c4ae76
3
+ size 23521945
languages.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ LANGUAGES = {
2
+ 'ace': 'Acehnese',
3
+ 'bal': 'Balinese',
4
+ 'bug': 'Bugisnese',
5
+ 'id': 'Indonesian',
6
+ 'min': 'Minangkabau',
7
+ 'jav': 'Javanese',
8
+ 'sun': 'Sundanese'
9
+ }
release_stats.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ STATS = {
2
+ "name": "",
3
+ "downloadUrl": "",
4
+ "version": "1.0",
5
+ "date": ""
6
+ }
test01.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Common Voice Dataset"""
16
+
17
+
18
+ import csv
19
+ import os
20
+ import urllib
21
+
22
+ import datasets
23
+ import requests
24
+ from datasets.utils.py_utils import size_str
25
+ from huggingface_hub import HfApi, HfFolder
26
+
27
+ from .languages import LANGUAGES
28
+ from .release_stats import STATS
29
+
30
+ _CITATION = """\
31
+ """
32
+
33
+ _HOMEPAGE = "https://commonvoice.mozilla.org/en/datasets"
34
+
35
+ _LICENSE = "https://creativecommons.org/publicdomain/zero/1.0/"
36
+
37
+
38
+ class Test01Config(datasets.BuilderConfig):
39
+ """BuilderConfig for Test01."""
40
+
41
+ def __init__(self, name, version, **kwargs):
42
+ self.language = kwargs.pop("language", None)
43
+ self.release_date = kwargs.pop("release_date", None)
44
+ self.num_clips = kwargs.pop("num_clips", None)
45
+ self.num_speakers = kwargs.pop("num_speakers", None)
46
+ self.validated_hr = kwargs.pop("validated_hr", None)
47
+ self.total_hr = kwargs.pop("total_hr", None)
48
+ self.size_bytes = kwargs.pop("size_bytes", None)
49
+ self.size_human = size_str(self.size_bytes)
50
+ description = (
51
+ f"Common Voice speech to text dataset in {self.language} released on {self.release_date}. "
52
+ f"The dataset comprises {self.validated_hr} hours of validated transcribed speech data "
53
+ f"out of {self.total_hr} hours in total from {self.num_speakers} speakers. "
54
+ f"The dataset contains {self.num_clips} audio clips and has a size of {self.size_human}."
55
+ )
56
+ super(Test01Config, self).__init__(
57
+ name=name,
58
+ version=datasets.Version(version),
59
+ description=description,
60
+ **kwargs,
61
+ )
62
+
63
+
64
+ class Test01(datasets.GeneratorBasedBuilder):
65
+ DEFAULT_CONFIG_NAME = "id"
66
+ DEFAULT_WRITER_BATCH_SIZE = 1000
67
+
68
+ BUILDER_CONFIGS = [
69
+ Test01Config(
70
+ name=lang,
71
+ version=STATS["version"],
72
+ language=LANGUAGES[lang],
73
+ release_date=STATS["date"],
74
+ num_clips=lang_stats["clips"],
75
+ num_speakers=lang_stats["users"],
76
+ validated_hr=float(lang_stats["validHrs"]) if lang_stats["validHrs"] else None,
77
+ total_hr=float(lang_stats["totalHrs"]) if lang_stats["totalHrs"] else None,
78
+ size_bytes=int(lang_stats["size"]) if lang_stats["size"] else None,
79
+ )
80
+ for lang, lang_stats in STATS["locales"].items()
81
+ ]
82
+
83
+ def _info(self):
84
+ total_languages = len(STATS["locales"])
85
+ total_valid_hours = STATS["totalValidHrs"]
86
+ description = (
87
+ "Common Voice is Mozilla's initiative to help teach machines how real people speak. "
88
+ f"The dataset currently consists of {total_valid_hours} validated hours of speech "
89
+ f" in {total_languages} languages, but more voices and languages are always added."
90
+ )
91
+ features = datasets.Features(
92
+ {
93
+ "client_id": datasets.Value("string"),
94
+ "path": datasets.Value("string"),
95
+ "audio": datasets.features.Audio(sampling_rate=48_000),
96
+ "sentence": datasets.Value("string"),
97
+ "up_votes": datasets.Value("int64"),
98
+ "down_votes": datasets.Value("int64"),
99
+ "age": datasets.Value("string"),
100
+ "gender": datasets.Value("string"),
101
+ "accent": datasets.Value("string"),
102
+ "locale": datasets.Value("string"),
103
+ "segment": datasets.Value("string"),
104
+ }
105
+ )
106
+
107
+ return datasets.DatasetInfo(
108
+ description=description,
109
+ features=features,
110
+ supervised_keys=None,
111
+ homepage=_HOMEPAGE,
112
+ license=_LICENSE,
113
+ citation=_CITATION,
114
+ version=self.config.version,
115
+ # task_templates=[
116
+ # AutomaticSpeechRecognition(audio_file_path_column="path", transcription_column="sentence")
117
+ # ],
118
+ )
119
+
120
+ def _get_bundle_url(self, locale, url_template):
121
+ # path = encodeURIComponent(path)
122
+ path = url_template.replace("{locale}", locale)
123
+ path = urllib.parse.quote(path.encode("utf-8"), safe="~()*!.'")
124
+ # use_cdn = self.config.size_bytes < 20 * 1024 * 1024 * 1024
125
+ # response = requests.get(f"{_API_URL}/bucket/dataset/{path}/{use_cdn}", timeout=10.0).json()
126
+ response = requests.get(f"{_API_URL}/bucket/dataset/{path}", timeout=10.0).json()
127
+ return response["url"]
128
+
129
+ def _log_download(self, locale, bundle_version, auth_token):
130
+ if isinstance(auth_token, bool):
131
+ auth_token = HfFolder().get_token()
132
+ whoami = HfApi().whoami(auth_token)
133
+ email = whoami["email"] if "email" in whoami else ""
134
+ payload = {"email": email, "locale": locale, "dataset": bundle_version}
135
+ requests.post(f"{_API_URL}/{locale}/downloaders", json=payload).json()
136
+
137
+ def _split_generators(self, dl_manager):
138
+ """Returns SplitGenerators."""
139
+ hf_auth_token = dl_manager.download_config.use_auth_token
140
+ if hf_auth_token is None:
141
+ raise ConnectionError(
142
+ "Please set use_auth_token=True or use_auth_token='<TOKEN>' to download this dataset"
143
+ )
144
+
145
+ bundle_url_template = STATS["bundleURLTemplate"]
146
+ bundle_version = bundle_url_template.split("/")[0]
147
+ dl_manager.download_config.ignore_url_params = True
148
+
149
+ self._log_download(self.config.name, bundle_version, hf_auth_token)
150
+ archive_path = dl_manager.download(self._get_bundle_url(self.config.name, bundle_url_template))
151
+ local_extracted_archive = dl_manager.extract(archive_path) if not dl_manager.is_streaming else None
152
+
153
+ if self.config.version < datasets.Version("5.0.0"):
154
+ path_to_data = ""
155
+ else:
156
+ path_to_data = "/".join([bundle_version, self.config.name])
157
+ path_to_clips = "/".join([path_to_data, "clips"]) if path_to_data else "clips"
158
+
159
+ return [
160
+ datasets.SplitGenerator(
161
+ name=datasets.Split.TRAIN,
162
+ gen_kwargs={
163
+ "local_extracted_archive": local_extracted_archive,
164
+ "archive_iterator": dl_manager.iter_archive(archive_path),
165
+ "metadata_filepath": "/".join([path_to_data, "train.tsv"]) if path_to_data else "train.tsv",
166
+ "path_to_clips": path_to_clips,
167
+ },
168
+ ),
169
+ ]
170
+
171
+ def _generate_examples(
172
+ self,
173
+ local_extracted_archive,
174
+ archive_iterator,
175
+ metadata_filepath,
176
+ path_to_clips,
177
+ ):
178
+ """Yields examples."""
179
+ data_fields = list(self._info().features.keys())
180
+ metadata = {}
181
+ metadata_found = False
182
+ for path, f in archive_iterator:
183
+ if path == metadata_filepath:
184
+ metadata_found = True
185
+ lines = (line.decode("utf-8") for line in f)
186
+ reader = csv.DictReader(lines, delimiter="\t", quoting=csv.QUOTE_NONE)
187
+ for row in reader:
188
+ # set absolute path for mp3 audio file
189
+ if not row["path"].endswith(".mp3"):
190
+ row["path"] += ".mp3"
191
+ row["path"] = os.path.join(path_to_clips, row["path"])
192
+ # accent -> accents in CV 8.0
193
+ if "accents" in row:
194
+ row["accent"] = row["accents"]
195
+ del row["accents"]
196
+ # if data is incomplete, fill with empty values
197
+ for field in data_fields:
198
+ if field not in row:
199
+ row[field] = ""
200
+ metadata[row["path"]] = row
201
+ elif path.startswith(path_to_clips):
202
+ assert metadata_found, "Found audio clips before the metadata TSV file."
203
+ if not metadata:
204
+ break
205
+ if path in metadata:
206
+ result = dict(metadata[path])
207
+ # set the audio feature and the path to the extracted file
208
+ path = os.path.join(local_extracted_archive, path) if local_extracted_archive else path
209
+ result["audio"] = {"path": path, "bytes": f.read()}
210
+ # set path to None if the audio file doesn't exist locally (i.e. in streaming mode)
211
+ result["path"] = path if local_extracted_archive else None
212
+
213
+ yield path, result