Aniket-Tathe-08 commited on
Commit
4551b02
·
verified ·
1 Parent(s): feb2898

Create common_voice_16_0.py

Browse files
Files changed (1) hide show
  1. common_voice_16_0.py +202 -0
common_voice_16_0.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
21
+
22
+ import datasets
23
+ from datasets.utils.py_utils import size_str
24
+ from tqdm import tqdm
25
+
26
+ from .languages import LANGUAGES
27
+ from .release_stats import STATS
28
+
29
+
30
+ _CITATION = """\
31
+ @inproceedings{commonvoice:2020,
32
+ author = {Ardila, R. and Branson, M. and Davis, K. and Henretty, M. and Kohler, M. and Meyer, J. and Morais, R. and Saunders, L. and Tyers, F. M. and Weber, G.},
33
+ title = {Common Voice: A Massively-Multilingual Speech Corpus},
34
+ booktitle = {Proceedings of the 12th Conference on Language Resources and Evaluation (LREC 2020)},
35
+ pages = {4211--4215},
36
+ year = 2020
37
+ }
38
+ """
39
+
40
+ _HOMEPAGE = "https://commonvoice.mozilla.org/en/datasets"
41
+
42
+ _LICENSE = "https://creativecommons.org/publicdomain/zero/1.0/"
43
+
44
+ _BASE_URL = "https://huggingface.co/datasets/Aniket-Tathe-08/Custom_common_voice_dataset_using_RVC/raw/main/"
45
+
46
+ _AUDIO_URL = _BASE_URL + "audio/{lang}/{split}/{lang}_{split}_{shard_idx}.tar"
47
+
48
+ _TRANSCRIPT_URL = _BASE_URL + "transcript/{lang}/{split}.tsv"
49
+
50
+ _N_SHARDS_URL = _BASE_URL + "n_shards.json"
51
+
52
+
53
+ class CommonVoiceConfig(datasets.BuilderConfig):
54
+ """BuilderConfig for CommonVoice."""
55
+
56
+ def __init__(self, name, version, **kwargs):
57
+ self.language = kwargs.pop("language", None)
58
+ self.release_date = kwargs.pop("release_date", None)
59
+ self.num_clips = kwargs.pop("num_clips", None)
60
+ self.num_speakers = kwargs.pop("num_speakers", None)
61
+ self.validated_hr = kwargs.pop("validated_hr", None)
62
+ self.total_hr = kwargs.pop("total_hr", None)
63
+ self.size_bytes = kwargs.pop("size_bytes", None)
64
+ self.size_human = size_str(self.size_bytes)
65
+ description = (
66
+ f"Common Voice speech to text dataset in {self.language} released on {self.release_date}. "
67
+ f"The dataset comprises {self.validated_hr} hours of validated transcribed speech data "
68
+ f"out of {self.total_hr} hours in total from {self.num_speakers} speakers. "
69
+ f"The dataset contains {self.num_clips} audio clips and has a size of {self.size_human}."
70
+ )
71
+ super(CommonVoiceConfig, self).__init__(
72
+ name=name,
73
+ version=datasets.Version(version),
74
+ description=description,
75
+ **kwargs,
76
+ )
77
+
78
+
79
+ class CommonVoice(datasets.GeneratorBasedBuilder):
80
+ DEFAULT_WRITER_BATCH_SIZE = 1000
81
+
82
+ BUILDER_CONFIGS = [
83
+ CommonVoiceConfig(
84
+ name=lang,
85
+ version=STATS["version"],
86
+ language=LANGUAGES[lang],
87
+ release_date=STATS["date"],
88
+ num_clips=lang_stats["clips"],
89
+ num_speakers=lang_stats["users"],
90
+ validated_hr=float(
91
+ lang_stats["validHrs"]) if lang_stats["validHrs"] else None,
92
+ total_hr=float(lang_stats["totalHrs"]
93
+ ) if lang_stats["totalHrs"] else None,
94
+ size_bytes=int(lang_stats["size"]) if lang_stats["size"] else None,
95
+ )
96
+ for lang, lang_stats in STATS["locales"].items()
97
+ ]
98
+
99
+ def _info(self):
100
+ total_languages = len(STATS["locales"])
101
+ total_valid_hours = STATS["totalValidHrs"]
102
+ description = (
103
+ "Common Voice is Mozilla's initiative to help teach machines how real people speak. "
104
+ f"The dataset currently consists of {total_valid_hours} validated hours of speech "
105
+ f" in {total_languages} languages, but more voices and languages are always added."
106
+ )
107
+ features = datasets.Features(
108
+ {
109
+ "client_id": datasets.Value("string"),
110
+ "path": datasets.Value("string"),
111
+ "audio": datasets.features.Audio(sampling_rate=48_000),
112
+ "sentence": datasets.Value("string"),
113
+ "up_votes": datasets.Value("int64"),
114
+ "down_votes": datasets.Value("int64"),
115
+ "age": datasets.Value("string"),
116
+ "gender": datasets.Value("string"),
117
+ "accent": datasets.Value("string"),
118
+ "locale": datasets.Value("string"),
119
+ "segment": datasets.Value("string"),
120
+ }
121
+ )
122
+
123
+ return datasets.DatasetInfo(
124
+ description=description,
125
+ features=features,
126
+ supervised_keys=None,
127
+ homepage=_HOMEPAGE,
128
+ license=_LICENSE,
129
+ citation=_CITATION,
130
+ version=self.config.version,
131
+ )
132
+
133
+ def _split_generators(self, dl_manager):
134
+ lang = self.config.name
135
+ n_shards_path = dl_manager.download_and_extract(_N_SHARDS_URL)
136
+ with open(n_shards_path, encoding="utf-8") as f:
137
+ n_shards = json.load(f)
138
+
139
+ audio_urls = {}
140
+ splits = ("train", "dev", "test", "other")
141
+ for split in splits:
142
+ audio_urls[split] = [
143
+ _AUDIO_URL.format(lang=lang, split=split, shard_idx=i) for i in range(n_shards[lang][split])
144
+ ]
145
+ print(audio_urls)
146
+ archive_paths = dl_manager.download(audio_urls)
147
+ local_extracted_archive_paths = dl_manager.extract(
148
+ archive_paths) if not dl_manager.is_streaming else {}
149
+
150
+ meta_urls = {split: _TRANSCRIPT_URL.format(
151
+ lang=lang, split=split) for split in splits}
152
+ meta_paths = dl_manager.download_and_extract(meta_urls)
153
+
154
+ split_generators = []
155
+ split_names = {
156
+ "train": datasets.Split.TRAIN,
157
+ "dev": datasets.Split.VALIDATION,
158
+ "test": datasets.Split.TEST,
159
+ }
160
+ for split in splits:
161
+ split_generators.append(
162
+ datasets.SplitGenerator(
163
+ name=split_names.get(split, split),
164
+ gen_kwargs={
165
+ "local_extracted_archive_paths": local_extracted_archive_paths.get(split),
166
+ "archives": [dl_manager.iter_archive(path) for path in archive_paths.get(split)],
167
+ "meta_path": meta_paths[split],
168
+ },
169
+ ),
170
+ )
171
+
172
+ return split_generators
173
+
174
+ def _generate_examples(self, local_extracted_archive_paths, archives, meta_path):
175
+ data_fields = list(self._info().features.keys())
176
+ metadata = {}
177
+ with open(meta_path, encoding="utf-8") as f:
178
+ reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
179
+ for row in tqdm(reader, desc="Reading metadata..."):
180
+ if not row["path"].endswith(".wav"):
181
+ row["path"] += ".wav"
182
+ # accent -> accents in CV 8.0
183
+ if "accents" in row:
184
+ row["accent"] = row["accents"]
185
+ del row["accents"]
186
+ # if data is incomplete, fill with empty values
187
+ for field in data_fields:
188
+ if field not in row:
189
+ row[field] = ""
190
+ metadata[row["path"]] = row
191
+
192
+ for i, audio_archive in enumerate(archives):
193
+ for path, file in audio_archive:
194
+ _, filename = os.path.split(path)
195
+ if filename in metadata:
196
+ result = dict(metadata[filename])
197
+ # set the audio feature and the path to the extracted file
198
+ path = os.path.join(
199
+ local_extracted_archive_paths[i], path) if local_extracted_archive_paths else path
200
+ result["audio"] = {"path": path, "bytes": file.read()}
201
+ result["path"] = path
202
+ yield path, result