tz18609292528@163.com commited on
Commit
65bf5ad
1 Parent(s): 3e34a19
Files changed (1) hide show
  1. Cylonix_ASR_dataset.py +200 -0
Cylonix_ASR_dataset.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ Common Voice Dataset"""
17
+
18
+
19
+ import csv
20
+ import os
21
+ import json
22
+
23
+ import datasets
24
+ from datasets.utils.py_utils import size_str
25
+ from tqdm import tqdm
26
+
27
+ from .languages import LANGUAGES
28
+ from .release_stats import STATS
29
+
30
+
31
+ _CITATION = """\
32
+ @inproceedings{commonvoice:2020,
33
+ 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.},
34
+ title = {Common Voice: A Massively-Multilingual Speech Corpus},
35
+ booktitle = {Proceedings of the 12th Conference on Language Resources and Evaluation (LREC 2020)},
36
+ pages = {4211--4215},
37
+ year = 2020
38
+ }
39
+ """
40
+
41
+ _HOMEPAGE = "https://commonvoice.mozilla.org/en/datasets"
42
+
43
+ _LICENSE = "https://creativecommons.org/publicdomain/zero/1.0/"
44
+
45
+ # TODO: change "streaming" to "main" after merge!
46
+ _BASE_URL = "https://huggingface.co/datasets/KoddaDuck/Cylonix_ASR_dataset/blob/main/"
47
+
48
+ _AUDIO_URL = _BASE_URL + "audio/{lang}/{split}/{lang}_{split}_{shard_idx}.tar"
49
+
50
+ _TRANSCRIPT_URL = _BASE_URL + "transcript/{lang}/{split}.tsv"
51
+
52
+ _N_SHARDS_URL = _BASE_URL + "n_shards.json"
53
+
54
+
55
+ class CommonVoiceConfig(datasets.BuilderConfig):
56
+ """BuilderConfig for CommonVoice."""
57
+
58
+ def __init__(self, name, version, **kwargs):
59
+ self.language = kwargs.pop("language", None)
60
+ self.release_date = kwargs.pop("release_date", None)
61
+ self.num_clips = kwargs.pop("num_clips", None)
62
+ self.num_speakers = kwargs.pop("num_speakers", None)
63
+ self.validated_hr = kwargs.pop("validated_hr", None)
64
+ self.total_hr = kwargs.pop("total_hr", None)
65
+ self.size_bytes = kwargs.pop("size_bytes", None)
66
+ self.size_human = size_str(self.size_bytes)
67
+ description = (
68
+ f"Common Voice speech to text dataset in {self.language} released on {self.release_date}. "
69
+ f"The dataset comprises {self.validated_hr} hours of validated transcribed speech data "
70
+ f"out of {self.total_hr} hours in total from {self.num_speakers} speakers. "
71
+ f"The dataset contains {self.num_clips} audio clips and has a size of {self.size_human}."
72
+ )
73
+ super(CommonVoiceConfig, self).__init__(
74
+ name=name,
75
+ version=datasets.Version(version),
76
+ description=description,
77
+ **kwargs,
78
+ )
79
+
80
+
81
+ class CommonVoice(datasets.GeneratorBasedBuilder):
82
+ DEFAULT_WRITER_BATCH_SIZE = 1000
83
+
84
+ BUILDER_CONFIGS = [
85
+ CommonVoiceConfig(
86
+ name=lang,
87
+ version=STATS["version"],
88
+ language=LANGUAGES[lang],
89
+ release_date=STATS["date"],
90
+ num_clips=lang_stats["clips"],
91
+ num_speakers=lang_stats["users"],
92
+ validated_hr=float(lang_stats["validHrs"]) if lang_stats["validHrs"] else None,
93
+ total_hr=float(lang_stats["totalHrs"]) 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", "test")
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
+ archive_paths = dl_manager.download(audio_urls)
146
+ local_extracted_archive_paths = dl_manager.extract(archive_paths) if not dl_manager.is_streaming else {}
147
+
148
+ meta_urls = {split: _TRANSCRIPT_URL.format(lang=lang, split=split) for split in splits}
149
+ meta_paths = dl_manager.download_and_extract(meta_urls)
150
+
151
+ split_generators = []
152
+ split_names = {
153
+ "train": datasets.Split.TRAIN,
154
+ "test": datasets.Split.TEST,
155
+ }
156
+ for split in splits:
157
+ split_generators.append(
158
+ datasets.SplitGenerator(
159
+ name=split_names.get(split, split),
160
+ gen_kwargs={
161
+ "local_extracted_archive_paths": local_extracted_archive_paths.get(split),
162
+ "archives": [dl_manager.iter_archive(path) for path in archive_paths.get(split)],
163
+ "meta_path": meta_paths[split],
164
+ },
165
+ ),
166
+ )
167
+
168
+ return split_generators
169
+
170
+ def _generate_examples(self, local_extracted_archive_paths, archives, meta_path):
171
+ data_fields = list(self._info().features.keys())
172
+ metadata = {}
173
+ with open(meta_path, encoding="utf-8") as f:
174
+ reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
175
+ for row in tqdm(reader, desc="Reading metadata..."):
176
+ if not row["path"].endswith(".wav"):
177
+ row["path"] += ".wav"
178
+ # accent -> accents in CV 8.0
179
+ if "accents" in row:
180
+ row["accent"] = row["accents"]
181
+ del row["accents"]
182
+ # if data is incomplete, fill with empty values
183
+ for field in data_fields:
184
+ if field not in row:
185
+ row[field] = ""
186
+ metadata[row["path"]] = row
187
+
188
+ for i, audio_archive in enumerate(archives):
189
+ for filename, file in audio_archive:
190
+ _, filename = os.path.split(filename)
191
+ if filename in metadata:
192
+ result = dict(metadata[filename])
193
+ # set the audio feature and the path to the extracted file
194
+ path = os.path.join(local_extracted_archive_paths[i], filename) if local_extracted_archive_paths else filename
195
+ result["audio"] = {"path": path, "bytes": file.read()}
196
+ # set path to None if the audio file doesn't exist locally (i.e. in streaming mode)
197
+ result["path"] = path if local_extracted_archive_paths else filename
198
+
199
+ yield path, result
200
+