Tobius commited on
Commit
7d8b9ab
1 Parent(s): 93cfdcd

Upload runyankore_data.py

Browse files
Files changed (1) hide show
  1. runyankore_data.py +187 -0
runyankore_data.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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{tericvoices:2024,
32
+ author = {Bateesa, T. and Wairagala, EP. },
33
+ title = {Teric Lab: A Massively-Multilingual Speech Corpus},
34
+ }
35
+ """
36
+
37
+ _HOMEPAGE = "https://commonvoice.mozilla.org/en/datasets"
38
+
39
+ _LICENSE = "https://creativecommons.org/publicdomain/zero/1.0/"
40
+
41
+ # TODO: change "streaming" to "main" after merge!
42
+ _BASE_URL = "https://huggingface.co/datasets/Tobius/tericvoices_v2/resolve/main/"
43
+
44
+ _AUDIO_URL = _BASE_URL + "audio/{lang}/{split}/{lang}_{split}_{shard_idx}.tar"
45
+
46
+ _TRANSCRIPT_URL = _BASE_URL + "transcript/{lang}/{split}.tsv"
47
+
48
+ _N_SHARDS_URL = _BASE_URL + "n_shards.json"
49
+
50
+
51
+ class CommonVoiceConfig(datasets.BuilderConfig):
52
+ """BuilderConfig for CommonVoice."""
53
+
54
+ def __init__(self, name, version, **kwargs):
55
+ self.language = kwargs.pop("language", None)
56
+ self.release_date = kwargs.pop("release_date", None)
57
+ self.num_clips = kwargs.pop("num_clips", None)
58
+ self.num_speakers = kwargs.pop("num_speakers", None)
59
+ self.validated_hr = kwargs.pop("validated_hr", None)
60
+ self.total_hr = kwargs.pop("total_hr", None)
61
+ self.size_bytes = kwargs.pop("size_bytes", None)
62
+ self.size_human = size_str(self.size_bytes)
63
+ description = (
64
+ f"Common Voice speech to text dataset in {self.language} released on {self.release_date}. "
65
+ f"The dataset comprises {self.validated_hr} hours of validated transcribed speech data "
66
+ f"out of {self.total_hr} hours in total from {self.num_speakers} speakers. "
67
+ f"The dataset contains {self.num_clips} audio clips and has a size of {self.size_human}."
68
+ )
69
+ super(CommonVoiceConfig, self).__init__(
70
+ name=name,
71
+ version=datasets.Version(version),
72
+ description=description,
73
+ **kwargs,
74
+ )
75
+
76
+
77
+ class CommonVoice(datasets.GeneratorBasedBuilder):
78
+ DEFAULT_WRITER_BATCH_SIZE = 1000
79
+
80
+ BUILDER_CONFIGS = [
81
+ CommonVoiceConfig(
82
+ name=lang,
83
+ version=STATS["version"],
84
+ language=LANGUAGES[lang],
85
+ release_date=STATS["date"],
86
+ num_clips=lang_stats["clips"],
87
+ num_speakers=lang_stats["users"],
88
+ validated_hr=float(lang_stats["validHrs"]) if lang_stats["validHrs"] else None,
89
+ total_hr=float(lang_stats["totalHrs"]) if lang_stats["totalHrs"] else None,
90
+ size_bytes=int(lang_stats["size"]) if lang_stats["size"] else None,
91
+ )
92
+ for lang, lang_stats in STATS["locales"].items()
93
+ ]
94
+
95
+ def _info(self):
96
+ total_languages = len(STATS["locales"])
97
+ total_valid_hours = STATS["totalValidHrs"]
98
+ description = (
99
+ "Teric Lab is an East African AI startup levereaging AI to ease communication in local African local langauges"
100
+ f"The dataset currently consists of {total_valid_hours} validated hours of speech "
101
+ f" in {total_languages} languages, but more voices and languages are always added."
102
+ )
103
+ features = datasets.Features(
104
+ {
105
+ "path": datasets.Value("string"),
106
+ "audio": datasets.features.Audio(sampling_rate=16_000),
107
+ "transcription": datasets.Value("string"),
108
+ "sample_rate": datasets.Value("int64"),
109
+ "speaker_id": datasets.Value("string"),
110
+ }
111
+ )
112
+
113
+ return datasets.DatasetInfo(
114
+ description=description,
115
+ features=features,
116
+ supervised_keys=None,
117
+ homepage=_HOMEPAGE,
118
+ license=_LICENSE,
119
+ citation=_CITATION,
120
+ version=self.config.version,
121
+ )
122
+
123
+ def _split_generators(self, dl_manager):
124
+ lang = self.config.name
125
+ n_shards_path = dl_manager.download_and_extract(_N_SHARDS_URL)
126
+ with open(n_shards_path, encoding="utf-8") as f:
127
+ n_shards = json.load(f)
128
+
129
+ audio_urls = {}
130
+ splits = ("train","test")
131
+ for split in splits:
132
+ audio_urls[split] = [
133
+ _AUDIO_URL.format(lang=lang, split=split, shard_idx=i) for i in range(n_shards[lang][split])
134
+ ]
135
+ archive_paths = dl_manager.download(audio_urls)
136
+ local_extracted_archive_paths = dl_manager.extract(archive_paths) if not dl_manager.is_streaming else {}
137
+
138
+ meta_urls = {split: _TRANSCRIPT_URL.format(lang=lang, split=split) for split in splits}
139
+ meta_paths = dl_manager.download_and_extract(meta_urls)
140
+
141
+ split_generators = []
142
+ split_names = {
143
+ "train": datasets.Split.TRAIN,
144
+ "test": datasets.Split.TEST,
145
+ }
146
+ for split in splits:
147
+ split_generators.append(
148
+ datasets.SplitGenerator(
149
+ name=split_names.get(split, split),
150
+ gen_kwargs={
151
+ "local_extracted_archive_paths": local_extracted_archive_paths.get(split),
152
+ "archives": [dl_manager.iter_archive(path) for path in archive_paths.get(split)],
153
+ "meta_path": meta_paths[split],
154
+ },
155
+ ),
156
+ )
157
+
158
+ return split_generators
159
+
160
+ def _generate_examples(self, local_extracted_archive_paths, archives, meta_path):
161
+ data_fields = list(self._info().features.keys())
162
+ metadata = {}
163
+ with open(meta_path, encoding="utf-8") as f:
164
+ reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
165
+ for row in tqdm(reader, desc="Reading metadata..."):
166
+ if not row["path"].endswith(".wav"):
167
+ row["path"] += ".wav"
168
+ # accent -> accents in CV 8.0
169
+ # if "accents" in row:
170
+ # row["accent"] = row["accents"]
171
+ # del row["accents"]
172
+ # if data is incomplete, fill with empty values
173
+ for field in data_fields:
174
+ if field not in row:
175
+ row[field] = ""
176
+ metadata[row["path"]] = row
177
+
178
+ for i, audio_archive in enumerate(archives):
179
+ for path, file in audio_archive:
180
+ _, filename = os.path.split(path)
181
+ if filename in metadata:
182
+ result = dict(metadata[filename])
183
+ # set the audio feature and the path to the extracted file
184
+ path = os.path.join(local_extracted_archive_paths[i], path) if local_extracted_archive_paths else path
185
+ result["audio"] = {"path": path, "bytes": file.read()}
186
+ result["path"] = path
187
+ yield path, result