File size: 10,581 Bytes
349c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d73d6d
349c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357d879
0d750c4
349c94d
 
 
0d750c4
349c94d
 
 
357d879
349c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fc640e
 
349c94d
 
 
eb258ba
9f80114
70c57c1
 
 
 
 
349c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357d879
 
349c94d
357d879
 
349c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70c57c1
7d200c7
 
349c94d
 
 
 
501d4a0
 
 
 
 
 
 
 
 
70c57c1
349c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb258ba
 
349c94d
d83bc5f
 
 
70c57c1
 
 
 
 
 
 
 
 
 
 
 
349c94d
 
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
# 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.
# TODO: Address all TODOs and remove all explanatory comments
"""Build script for Polish ASR-BIGOS dataset"""


import csv
import json
import os

import datasets

print("Running script")

# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@inproceedings{FedCSIS20231609,
	author={Michał Junczyk},
	pages={585–590},
	title={BIGOS - Benchmark Intended Grouping of Open Speech Corpora for Polish Automatic Speech Recognition},
	booktitle={Proceedings of the 18th Conference on Computer Science and Intelligence Systems},
	year={2023},
	editor={Maria Ganzha and Leszek Maciaszek and Marcin Paprzycki and Dominik Ślęzak},
	publisher={IEEE},
	doi={10.15439/2023F1609},
	url={http://dx.doi.org/10.15439/2023F1609},
	volume={35},
	series={Annals of Computer Science and Information Systems}
}
"""

_DESCRIPTION = """\
BIGOS (Benchmark Intended Grouping of Open Speech) dataset goal is to simplify access to the openly available Polish speech corpora and
enable systematic benchmarking of open and commercial Polish ASR systems.
"""

_HOMEPAGE = "https://huggingface.co/datasets/amu-cai/pl-asr-bigos-v2"

_LICENSE = "CC-BY-SA-4.0"

_BIGOS_SUBSETS = ["pjatk-clarin_mobile-15", "pjatk-clarin_studio-15", "fair-mls-20", "mailabs-corpus_librivox-19", "mozilla-common_voice_15-23", "pwr-azon_read-20", "pwr-azon_spont-20", "pwr-maleset-unk", "pwr-shortwords-unk", "pwr-viu-unk", "google-fleurs-22", "polyai-minds14-21"]
_ALL_CONFIGS = []

for subset in _BIGOS_SUBSETS:
    _ALL_CONFIGS.append(subset)

_ALL_CONFIGS.append("all")

_BASE_PATH = "data/{subset}/"
_DATA_URL = _BASE_PATH + "{split}.tar.gz"
_META_URL = _BASE_PATH + "{split}.tsv"

_SPLITS=["train","validation","test"]

class BigosConfig(datasets.BuilderConfig):

    def __init__(
        self, name, description, citation, homepage,
    ):
        super(BigosConfig, self).__init__(
            name=self.name,
            version=datasets.Version("2.1.0", ""),
            description=self.description,
        )
        self.name = name
        self.description = description
        self.citation = citation
        self.homepage = homepage


def _build_config(name):
    return BigosConfig(
        name=name,
        description=_DESCRIPTION,
        citation=_CITATION,
        homepage=_HOMEPAGE,
    )

class Bigos(datasets.GeneratorBasedBuilder):

    DEFAULT_WRITER_BATCH_SIZE = 2
    #in case the issue persits, investigatae the following:
    #https://github.com/huggingface/datasets/issues/4057
    BUILDER_CONFIGS = [_build_config(name) for name in _ALL_CONFIGS]

    def _info(self):
        task_templates = None
        features = datasets.Features(
            {
                "audioname": datasets.Value("string"),
                "split": datasets.Value("string"),
                "dataset": datasets.Value("string"),
                "speaker_id": datasets.Value("string"),
                "ref_orig": datasets.Value("string"),
                "audio": datasets.Audio(sampling_rate=16_000),
                "audio_duration_samples": datasets.Value("int32"),
                "audio_duration_seconds": datasets.Value("float32"),
                "samplingrate_orig": datasets.Value("int32"),
                "sampling_rate": datasets.Value("int32"),
                "audiopath_bigos": datasets.Value("string"),
                "audiopath_local": datasets.Value("string"),
                "speaker_age": datasets.Value("string"),
                "speaker_gender": datasets.Value("string"),
                "utt_length_words": datasets.Value("int32"),
                "utt_length_chars": datasets.Value("int32"),
                "speech_rate_words": datasets.Value("float32"),
                "speech_rate_chars": datasets.Value("float32")
            }
        )

        return datasets.DatasetInfo(
            description=self.config.description + "\n" + _DESCRIPTION,
            features=features,
            supervised_keys=("audio", "ref_orig"),
            homepage=self.config.homepage,
            citation=self.config.citation + "\n" + _CITATION,
            task_templates=task_templates,
        )

    def _split_generators(self, dl_manager):

        if self.config.name == "all":
            data_urls = {split: [_DATA_URL.format(subset=subset,split=split) for subset in _BIGOS_SUBSETS] for split in _SPLITS}
            meta_urls = {split: [_META_URL.format(subset=subset,split=split) for subset in _BIGOS_SUBSETS] for split in _SPLITS}
        else:
            data_urls = {split: [_DATA_URL.format(subset=self.config.name, split=split)] for split in _SPLITS}
            meta_urls = {split: [_META_URL.format(subset=self.config.name, split=split)] for split in _SPLITS}

        archive_paths = dl_manager.download(data_urls)
        local_extracted_archives = dl_manager.extract(archive_paths) if not dl_manager.is_streaming else {}
        archive_iters = {split: [dl_manager.iter_archive(path) for path in paths] for split, paths in archive_paths.items()}

        meta_paths = dl_manager.download(meta_urls)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "local_extracted_archives": local_extracted_archives.get("test", [None] * len(meta_paths.get("test"))),
                    "archive_iters": archive_iters.get("test"),
                    "text_paths": meta_paths.get("test")
                },
            ),
    
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "local_extracted_archives": local_extracted_archives.get("train", [None] * len(meta_paths.get("train"))),
                    "archive_iters": archive_iters.get("train"),
                    "text_paths": meta_paths.get("train")
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "local_extracted_archives": local_extracted_archives.get("validation", [None] * len(meta_paths.get("validation"))),
                    "archive_iters": archive_iters.get("validation"),
                    "text_paths": meta_paths.get("validation")
                },
            ),
        ]

    def _get_data(self, lines, subset_id):
        data = {}
        for line in lines:
            # parse TSV
            if isinstance(line, bytes):
                line = line.decode("utf-8")
            (
                _id,
                split,
                dataset,
                speaker_id,
                sampling_rate_orig,
                sampling_rate,
                ref_orig,
                audio_path_bigos,
                gender,
                age

            ) = line.strip().split("\t")


            data[audio_path_bigos] = {
                "audioname": str.strip(_id),
                "split": str.strip(split),
                "dataset": str.strip(dataset),
                "speaker_id": str.strip(speaker_id),
                "samplingrate_orig": str.strip(sampling_rate_orig),
                "sampling_rate": str.strip(sampling_rate),
                "ref_orig": str.strip(ref_orig),
                "audiopath_bigos": str.strip(audio_path_bigos),
                "speaker_age": str.strip(age),
                "speaker_gender": str.strip(gender)
            }

        return data

    def _generate_examples(self, local_extracted_archives, archive_iters, text_paths):
        assert len(local_extracted_archives) == len(archive_iters) == len(text_paths)
        key = 0

        print("Generating  examples")
        if self.config.name == "all":
            subsets = _BIGOS_SUBSETS
        else:
            subsets = [self.config.name]

        for archive, text_path, local_extracted_path, subset_id in zip(archive_iters, text_paths, local_extracted_archives, subsets):
            with open(text_path, encoding="utf-8") as f:
                lines = f.readlines()
                data = self._get_data(lines, subset_id)

            for audio_path, audio_file in archive:
                #print("audio_path: ", audio_path)

                audio_filename = audio_path.split("/")[-1]
                #if audio_filename not in data.keys():
                #    continue
                
                #print("audio_filename: ", audio_filename)
                result = data[audio_filename]
                extracted_audio_path = (
                    os.path.join(local_extracted_path, audio_filename)
                    if local_extracted_path is not None
                    else None
                )
                #print("extracted_audio_path: ", extracted_audio_path)
                result["audiopath_local"] = extracted_audio_path
                result["audio"] = {"path": audio_path, "bytes": audio_file.read()}
                # dividing the byte length by 2 because the audio is 16-bit PCM. Removing the header
                result["audio_duration_samples"] = len(result["audio"]["bytes"]) // 2 - 22 
                result["audio_duration_seconds"] = round(int(result["audio_duration_samples"]) / int(result["sampling_rate"]), 2)

                if result["ref_orig"] == "":
                    result["utt_length_words"] = None
                    result["utt_length_chars"] = None
                    result["speech_rate_words"] = None
                    result["speech_rate_chars"] = None
                else:
                    result["utt_length_words"] = len(result["ref_orig"].split())
                    result["utt_length_chars"] = len(result["ref_orig"])
                    result["speech_rate_words"] = round(result["utt_length_words"] / result["audio_duration_seconds"], 2)
                    result["speech_rate_chars"] = round(result["utt_length_chars"] / result["audio_duration_seconds"], 2)

                yield key, result
                key += 1