File size: 11,049 Bytes
7f772ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310c3fd
7f772ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685aaee
7f772ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c129621
 
 
 
 
7f772ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b563d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f772ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# 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.
"""
Aishell dataset.
"""

import os
import datasets
from huggingface_hub import list_repo_files
import gzip
import json

repo_id = "yuekai/aishell"

_DESCRIPTION = """\
aishell
"""
_HOMEPAGE = "https://github.com/SpeechColab/Aishell"

_SUBSETS = ("train", "dev", "test")

_BASE_DATA_URL = f"https://huggingface.co/datasets/{repo_id}/resolve/main/"

_AUDIO_ARCHIVE_URL = _BASE_DATA_URL + "data/aishell_cuts_{subset}.{archive_id:08}.tar.gz"

_META_URL = _BASE_DATA_URL + "data/aishell_cuts_{subset}.{archive_id:08}.jsonl.gz"

FILES = list_repo_files(repo_id, repo_type="dataset")

logger = datasets.utils.logging.get_logger(__name__)


class CustomAudioConfig(datasets.BuilderConfig):
    """BuilderConfig for the dataset."""

    def __init__(self, name, *args, **kwargs):
        """BuilderConfig for the dataset.
        """
        super().__init__(name=name, *args, **kwargs)
        assert name in _SUBSETS, f"Unknown subset {name}"
        self.subsets_to_download = (name,)


class Aishell(datasets.GeneratorBasedBuilder):
    """
    Aishell is an evolving, multi-domain English speech recognition corpus with 10,000 hours of high quality
    labeled audio suitable for supervised training, and 40,000 hours of total audio suitable for semi-supervised
    and unsupervised training (this implementation contains only labelled data for now).
    Around 40,000 hours of transcribed audio is first collected from audiobooks, podcasts
    and YouTube, covering both read and spontaneous speaking styles, and a variety of topics, such as arts, science,
    sports, etc. A new forced alignment and segmentation pipeline is proposed to create sentence segments suitable
    for speech recognition training, and to filter out segments with low-quality transcription. For system training,
    Aishell provides five subsets of different sizes, 10h, 250h, 1000h, 2500h, and 10000h.
    For our 10,000-hour XL training subset, we cap the word error rate at 4% during the filtering/validation stage,
    and for all our other smaller training subsets, we cap it at 0%. The DEV and TEST evaluation sets, on the other hand,
    are re-processed by professional human transcribers to ensure high transcription quality.
    """

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [CustomAudioConfig(name=subset) for subset in _SUBSETS]

    DEFAULT_WRITER_BATCH_SIZE = 128

    def _info(self):
        features = datasets.Features(
            {
                "segment_id": datasets.Value("string"),
                "speaker": datasets.Value("string"),
                "text": datasets.Value("string"),
                "audio": datasets.Audio(sampling_rate=16_000),
                "original_full_path": datasets.Value("string"),  # relative path to full audio in original data dirs
            }
        )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
        )

    @property
    def _splits_to_subsets(self):
        return {
            "train": ['train'],
            "dev": ["dev"],
            "test": ["test"]
        }

    def _split_generators(self, dl_manager):
        splits_to_subsets = self._splits_to_subsets
        splits = (self.config.name,)
        # if self.config.name in {"dev", "test"}:
        #     splits = (self.config.name,)
        # else:
        #     splits = ("train", "dev", "test")

        split_to_n_archives = {
            split: int(len([file for file in FILES if f"cuts_{splits_to_subsets[split][0]}" in file]) / 2)
            for split in splits
        }

        # 2. prepare sharded archives with audio files
        audio_archives_urls = {
            split: 
                [
                    _AUDIO_ARCHIVE_URL.format(subset=splits_to_subsets[split][0], 
                                              archive_id=i)
                    for i in range(split_to_n_archives[split])
                ]
            for split in splits
        }

        audio_archives_paths = dl_manager.download(audio_archives_urls)

        local_audio_archives_paths = dl_manager.extract(audio_archives_paths) if not dl_manager.is_streaming \
            else None

        # 3. prepare sharded metadata csv files
        meta_urls = {
            split: [
                    _META_URL.format(subset=splits_to_subsets[split][0], archive_id=i)
                    for i in range(split_to_n_archives[split])
                ]
            for split in splits
        }

        # meta_paths = dl_manager.download_and_extract(meta_urls)
        meta_paths = dl_manager.download(meta_urls)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "audio_archives_iterators": [
                        dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths[self.config.name]
                    ],
                    "local_audio_archives_paths": local_audio_archives_paths[
                        self.config.name] if local_audio_archives_paths else None,
                    "meta_paths": meta_paths[self.config.name]
                },
            ),
        ]
        # if self.config.name not in {"dev", "test"}:
        #     result = [
        #         datasets.SplitGenerator(
        #             name=datasets.Split.TRAIN,
        #             gen_kwargs={
        #                 "audio_archives_iterators": [
        #                     dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["train"]
        #                 ],
        #                 "local_audio_archives_paths": local_audio_archives_paths[
        #                     "train"] if local_audio_archives_paths else None,
        #                 "meta_paths": meta_paths["train"]
        #             },
        #         )
        #     ]
        #     if 'dev' in audio_archives_paths:
        #         result.append(datasets.SplitGenerator(
        #             name=datasets.Split.VALIDATION,
        #             gen_kwargs={
        #                 "audio_archives_iterators": [
        #                     dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["dev"]
        #                 ],
        #                 "local_audio_archives_paths": local_audio_archives_paths[
        #                     "dev"] if local_audio_archives_paths else None,
        #                 "meta_paths": meta_paths["dev"]
        #             },
        #         ))
        #     if 'test' in audio_archives_paths:
        #         result.append(datasets.SplitGenerator(
        #             name=datasets.Split.TEST,
        #             gen_kwargs={
        #                 "audio_archives_iterators": [
        #                     dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["test"]
        #                 ],
        #                 "local_audio_archives_paths": local_audio_archives_paths[
        #                     "test"] if local_audio_archives_paths else None,
        #                 "meta_paths": meta_paths["test"]
        #             },
        #         ))
        #     return result

        # if self.config.name == "dev":
        #     return [
        #         datasets.SplitGenerator(
        #             name=datasets.Split.VALIDATION,
        #             gen_kwargs={
        #                 "audio_archives_iterators": [
        #                     dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["dev"]
        #                 ],
        #                 "local_audio_archives_paths": local_audio_archives_paths[
        #                     "dev"] if local_audio_archives_paths else None,
        #                 "meta_paths": meta_paths["dev"]
        #             },
        #         ),
        #     ]

        # if self.config.name == "test":

        #     return [
        #         datasets.SplitGenerator(
        #             name=datasets.Split.TEST,
        #             gen_kwargs={
        #                 "audio_archives_iterators": [
        #                     dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["test"]
        #                 ],
        #                 "local_audio_archives_paths": local_audio_archives_paths[
        #                     "test"] if local_audio_archives_paths else None,
        #                 "meta_paths": meta_paths["test"]
        #             },
        #         ),
        #     ]

    def _generate_examples(self, audio_archives_iterators, local_audio_archives_paths, meta_paths):

        def load_meta(file_path):
            data = {}

            with gzip.open(file_path, 'rt', encoding='utf-8') as f:
                for line in f:
                    item = json.loads(line)
                    data[item["id"]] = item
            return data

        assert len(audio_archives_iterators) == len(meta_paths)
        if local_audio_archives_paths:
            assert len(audio_archives_iterators) == len(local_audio_archives_paths)

        for i, (meta_path, audio_archive_iterator) in enumerate(zip(meta_paths, audio_archives_iterators)):
            meta_dict = load_meta(meta_path)

            for audio_path_in_archive, audio_file in audio_archive_iterator:
                # `audio_path_in_archive` is like "data/aishell_cuts_test.00000000/BAC/BAC009S0764W0393-359.wav"
                audio_filename = os.path.split(audio_path_in_archive)[-1]

                audio_id = audio_filename.split(".wav")[0]
                audio_meta = meta_dict[audio_id]

                audio_meta["segment_id"] = audio_id
                audio_meta["original_full_path"] = audio_meta["recording"]["sources"][0]["source"]
                audio_meta["text"] = audio_meta['supervisions'][0]['text']
                audio_meta["speaker"] = audio_meta['supervisions'][0]['speaker']

                path = os.path.join(local_audio_archives_paths[i], audio_path_in_archive) if local_audio_archives_paths \
                    else audio_path_in_archive

                yield audio_id, {
                    "audio": {"path": path , "bytes": audio_file.read()},
                    **{feature: value for feature, value in audio_meta.items() if feature in self.info.features}
                }