File size: 10,732 Bytes
2ce90a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720b05b
2ce90a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cce671
949d4d7
2ce90a9
1cce671
9b364ba
 
1cce671
2ce90a9
 
1cce671
2ce90a9
 
 
 
 
 
 
1cce671
2ce90a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
949d4d7
 
1cce671
949d4d7
1cce671
949d4d7
 
2ce90a9
1cce671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
949d4d7
 
 
9b364ba
949d4d7
 
 
 
 
 
3333d98
 
949d4d7
 
 
 
 
 
 
 
 
 
 
 
 
2ce90a9
3333d98
 
 
 
 
 
 
 
 
 
2ce90a9
 
 
 
949d4d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3333d98
949d4d7
 
2ce90a9
 
 
 
720b05b
2ce90a9
 
 
 
 
 
 
 
 
949d4d7
2ce90a9
 
 
 
 
 
720b05b
3333d98
2ce90a9
949d4d7
3333d98
 
720b05b
 
2ce90a9
 
720b05b
2ce90a9
 
 
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
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os

import datasets
from datasets.tasks import AutomaticSpeechRecognition
from tqdm.auto import tqdm


# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@article{DBLP:journals/corr/abs-2111-09344,
  author    = {Daniel Galvez and
               Greg Diamos and
               Juan Ciro and
               Juan Felipe Ceron and
               Keith Achorn and
               Anjali Gopi and
               David Kanter and
               Maximilian Lam and
               Mark Mazumder and
               Vijay Janapa Reddi},
  title     = {The People's Speech: A Large-Scale Diverse English Speech Recognition
               Dataset for Commercial Usage},
  journal   = {CoRR},
  volume    = {abs/2111.09344},
  year      = {2021},
  url       = {https://arxiv.org/abs/2111.09344},
  eprinttype = {arXiv},
  eprint    = {2111.09344},
  timestamp = {Mon, 22 Nov 2021 16:44:07 +0100},
  biburl    = {https://dblp.org/rec/journals/corr/abs-2111-09344.bib},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}
"""

# You can copy an official description
_DESCRIPTION = """\
The People's Speech is a free-to-download 30,000-hour and growing supervised 
conversational English speech recognition dataset licensed for academic and 
commercial usage under CC-BY-SA (with a CC-BY subset).
"""

_HOMEPAGE = "https://mlcommons.org/en/peoples-speech/"

_LICENSE = [
    "cc-by-2.0", "cc-by-2.5", "cc-by-3.0", "cc-by-4.0", "cc-by-sa-2.5",
    "cc-by-sa-3.0", "cc-by-sa-4.0"
]

_BASE_URL = "https://huggingface.co/datasets/MLCommons/peoples_speech/resolve/main/"

# relative path to data inside dataset's repo
_DATA_URL = _BASE_URL + "{split}/{config}/{config}_{archive_id:06d}.tar"

# relative path to file containing number of audio archives inside dataset's repo
_N_FILES_URL = _BASE_URL + "{split}/{config}/n_files.txt"

# relative path to metadata inside dataset's repo
_MANIFEST_URL = _BASE_URL + "{split}/{config}.json"


class PeoplesSpeech(datasets.GeneratorBasedBuilder):
    """The People's Speech dataset."""

    VERSION = datasets.Version("1.1.0")
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="microset", version=VERSION, description="Small subset of clean data for example pusposes."),
        datasets.BuilderConfig(name="clean", version=VERSION, description="Clean, CC-BY licensed subset."),
        datasets.BuilderConfig(name="dirty", version=VERSION, description="Dirty, CC-BY licensed subset."),
        datasets.BuilderConfig(name="clean_sa", version=VERSION, description="Clean, CC-BY-SA licensed subset."),
        datasets.BuilderConfig(name="dirty_sa", version=VERSION, description="Dirty, CC-BY-SA licensed subset."),
    ]
    DEFAULT_CONFIG_NAME = "clean"
    DEFAULT_WRITER_BATCH_SIZE = 1

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "audio": datasets.Audio(sampling_rate=16_000),
                    "duration_ms": datasets.Value("int32"),
                    "text": datasets.Value("string"),
                }
            ),
            task_templates=[AutomaticSpeechRecognition()],
            supervised_keys=("file", "text"),
            homepage=_HOMEPAGE,
            license="/".join(_LICENSE),  # license must be a string
            citation=_CITATION,
        )

    def _get_n_files(self, dl_manager, split, config):
        n_files_url = _N_FILES_URL.format(split=split, config=config)
        n_files_path = dl_manager.download_and_extract(n_files_url)

        with open(n_files_path, encoding="utf-8") as f:
            return int(f.read().strip())

    def _split_generators(self, dl_manager):

        if self.config.name == "microset":
            # take only first data archive for demo purposes
            url = [_DATA_URL.format(split="train", config="clean", archive_id=0)]
            archive_path = dl_manager.download(url)
            local_extracted_archive_path = dl_manager.extract(archive_path) if not dl_manager.is_streaming else [None]
            manifest_url = _MANIFEST_URL.format(split="train", config="clean_000000")  # train/clean_000000.json
            manifest_path = dl_manager.download_and_extract(manifest_url)

            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={
                        "local_extracted_archive_paths": local_extracted_archive_path,
                        # use iter_archive here to access the files in the TAR archives:
                        "archives": [dl_manager.iter_archive(path) for path in archive_path],
                        "manifest_path": manifest_path,
                    },
                ),
            ]

        n_files_train = self._get_n_files(dl_manager, split="train", config=self.config.name)
        n_files_dev = self._get_n_files(dl_manager, split="dev", config="dev")
        n_files_test = self._get_n_files(dl_manager, split="test", config="test")

        urls = {
            "train": [_DATA_URL.format(split="train", config=self.config.name, archive_id=i) for i in range(n_files_train)],
            "dev": [_DATA_URL.format(split="dev", config="dev", archive_id=i) for i in range(n_files_dev)],
            "test": [_DATA_URL.format(split="test", config="test", archive_id=i) for i in range(n_files_test)],
        }
        archive_paths = dl_manager.download(urls)

        # In non-streaming mode, we extract the archives to have the data locally:
        local_extracted_archive_paths = dl_manager.extract(archive_paths) if not dl_manager.is_streaming else \
            {
                "train": [None] * len(archive_paths),
                "dev": [None] * len(archive_paths),
                "test": [None] * len(archive_paths),
            }

        manifest_urls = {
            "train": _MANIFEST_URL.format(split="train", config=self.config.name),
            "dev": _MANIFEST_URL.format(split="dev", config="dev"),
            "test": _MANIFEST_URL.format(split="test", config="test"),
        }
        manifest_paths = dl_manager.download_and_extract(manifest_urls)

        # To access the audio data from the TAR archives using the download manager,
        # we have to use the dl_manager.iter_archive method
        #
        # This is because dl_manager.download_and_extract
        # doesn't work to stream TAR archives in streaming mode.
        # (we have to stream the files of a TAR archive one by one)
        #
        # The iter_archive method returns an iterable of (path_within_archive, file_obj) for every
        # file in a TAR archive.

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "local_extracted_archive_paths": local_extracted_archive_paths["train"],
                    # use iter_archive here to access the files in the TAR archives:
                    "archives": [dl_manager.iter_archive(path) for path in archive_paths["train"]],
                    "manifest_path": manifest_paths["train"],
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "local_extracted_archive_paths": local_extracted_archive_paths["dev"],
                    # use iter_archive here to access the files in the TAR archives:
                    "archives": [dl_manager.iter_archive(path) for path in archive_paths["dev"]],
                    "manifest_path": manifest_paths["dev"],
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "local_extracted_archive_paths": local_extracted_archive_paths["dev"],
                    # use iter_archive here to access the files in the TAR archives:
                    "archives": [dl_manager.iter_archive(path) for path in archive_paths["test"]],
                    "manifest_path": manifest_paths["test"],
                },
            ),
        ]

    def _generate_examples(self, local_extracted_archive_paths, archives, manifest_path):
        meta = dict()
        with open(manifest_path, "r", encoding="utf-8") as f:
            for line in tqdm(f, desc="reading metadata file"):
                sample_meta = json.loads(line)
                _id = sample_meta["audio_document_id"]
                texts = sample_meta["training_data"]["label"]
                audio_filenames = sample_meta["training_data"]["name"]
                durations = sample_meta["training_data"]["duration_ms"]
                for audio_filename, text, duration in zip(audio_filenames, texts, durations):
                    audio_filename = audio_filename.lstrip("./")
                    meta[audio_filename] = {
                        "audio_document_id": _id,
                        "text": text,
                        "duration_ms": duration
                    }

        for local_extracted_archive_path, archive in zip(local_extracted_archive_paths, archives):
            # Here we iterate over all the files within the TAR archive:
            for audio_filename, audio_file in archive:
                audio_filename = audio_filename.lstrip("./")
                # if an audio file exists locally (i.e. in default, non-streaming mode) set the full path to it
                # joining path to directory that the archive was extracted to and audio filename.
                path = os.path.join(local_extracted_archive_path, audio_filename) if local_extracted_archive_path \
                    else audio_filename
                yield audio_filename, {
                    "id": audio_filename,
                    "audio": {"path": path, "bytes": audio_file.read()},
                    "text": meta[audio_filename]["text"],
                    "duration_ms": meta[audio_filename]["duration_ms"]
                }