File size: 15,909 Bytes
b1e967a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373ffd6
 
b1e967a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f75bf2
b1e967a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f733212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1e967a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416ec7b
 
b1e967a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416ec7b
b1e967a
 
 
 
 
 
 
 
 
a09966c
b1e967a
 
 
 
 
 
e7f4d41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1e967a
 
 
 
 
 
 
 
 
 
 
 
 
 
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# coding=utf-8
# 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.

""" Load norwegian NST dataset provided by National Library of Norway | Språkbanken.

Documentation with full description of the data: https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/no-16khz_reorganized_english.pdf

TODO:
* add multi channel option
* add train-validation-test split option
* add sample option
* add data preview

Suggested filtering:
* replace("<eeeh>", "")
* replace("<mmm>", "")
* replace("\\\\Punktum", "")
* replace("\\\\Komma", "")
"""

import json
import os

from tqdm import tqdm
import datasets


_DESCRIPTION = """\
This database was created by Nordic Language Technology for the development of automatic speech recognition and dictation in Norwegian.
In this version, the organization of the data have been altered to improve the usefulness of the database.
In the original version of the material, the files were organized in a specific folder structure where the folder names were meaningful.
However, the file names were not meaningful, and there were also cases of files with identical names in different folders.
This proved to be impractical, since users had to keep the original folder structure in order to use the data.
The files have been renamed, such that the file names are unique and meaningful regardless of the folder structure.
The original metadata files were in spl format. These have been converted to JSON format.
The converted metadata files are also anonymized and the text encoding has been converted from ANSI to UTF-8.
See the documentation file for a full description of the data and the changes made to the database."""

_HOMEPAGE = "https://www.nb.no/sprakbanken/en/resource-catalogue/oai-nb-no-sbr-54/"

_LICENSE = "CC0 1.0"

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLS = {
    "close_channel": [
        "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/lydfiler_16_1_a.tar.gz",
        "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/lydfiler_16_1_b.tar.gz",
        "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/lydfiler_16_1_c.tar.gz",
        "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/lydfiler_16_1_d.tar.gz",
    ],
    "distant_channel": [
        "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/lydfiler_16_2_a.tar.gz",
        "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/lydfiler_16_2_b.tar.gz",
        "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/lydfiler_16_2_c.tar.gz",
        "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/lydfiler_16_2_d.tar.gz",
    ]
    # TODO: add handling of multi channel
    # "multi_channel": "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/lydfiler_16_begge.tar.gz",
}

_ANNOTATIONS_URL = [
    "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/ADB_NOR_0463.tar.gz",
    "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/ADB_NOR_0464.tar.gz",
    "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/no_2020/ADB_OD_Nor.NOR.tar.gz"
]


class NstNO(datasets.GeneratorBasedBuilder):
    """Audio dataset for Swedish ASR provided by National Library of Norawy.

    Originally, recordings have been made on two channels: a close one and a distant one.
    Channels have been separated and can be loaded independently.

    TODO: enable and validate multi_channel
    Two configurations available:
    - close_channel
    - distant_channel

    Main data and metadata available:
    - audio file (bytes)
    - manually annotated transcription (str)
    - age (str)
    - gender (str)
    - region of birth (str)
    - region of youth (str)
    - recording session info (object)
    - recording system (object)
    - "type" of recording (see detailed documentatin)
    - common_voice-like structured information
      (info mentioned above with object structure like common voice dataset for ease of merging)

    """

    VERSION = datasets.Version("1.1.0")

    # This is an example of a dataset with multiple configurations.
    # If you don't want/need to define several sub-sets in your dataset,
    # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

    # If you need to make complex sub-parts in the datasets with configurable options
    # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
    # BUILDER_CONFIG_CLASS = MyBuilderConfig

    # You will be able to load one or the other configurations in the following list with
    # data = datasets.load_dataset('my_dataset', 'first_domain')
    # data = datasets.load_dataset('my_dataset', 'second_domain')
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="close_channel", version=VERSION, description="Close channel recordings"),
        datasets.BuilderConfig(name="distant_channel", version=VERSION, description="Distant channel recordings"),
    ]

    DEFAULT_CONFIG_NAME = "close_channel"  # It's not mandatory to have a default configuration. Just use one if it make sense.

    def _info(self):
        features_dict = {
            # "region_of_birth": datasets.Value("string"),
            # "region_of_youth": datasets.Value("string"),
            # "remarks": datasets.Value("string"),
            # "pid": datasets.Value("string"),
            # "directory": datasets.Value("string"),
            # "imported_sheet_file": datasets.Value("string"),
            # "mumber_of_recordings": datasets.Value("string"),
            # "rec_date": datasets.Value("string"),
            # "rec_time": datasets.Value("string"),
            # "record_duration": datasets.Value("string"),
            # "record_session": datasets.Value("string"),
            # "sheet_number": datasets.Value("string"),
            # "ansi_codepage": datasets.Value("string"),
            # "board": datasets.Value("string"),
            # "byte_format": datasets.Value("string"),
            # "channels": datasets.Value("string"),
            # "character_set": datasets.Value("string"),
            # "coding": datasets.Value("string"),
            # "dos_codepage": datasets.Value("string"),
            # "delimiter": datasets.Value("string"),
            # "frequency": datasets.Value("string"),
            # "memo": datasets.Value("string"),
            # "script": datasets.Value("string"),
            # "version": datasets.Value("string"),
            # real sampling rate is 16000
            # it is set to 48000 to allow concatenation
            # with common voice dataset using
            # datasets.concatenate_datasets([dataset_a, dataset_b])
            "audio": datasets.features.Audio(sampling_rate=48000),
            'client_id': datasets.Value("string"),
            'path': datasets.Value("string"),
            'sentence': datasets.Value("string"),
            'up_votes': datasets.Value("int64"),
            'down_votes': datasets.Value("int64"),
            'age': datasets.Value("string"),
            'sex': datasets.Value("string"),
            'accent': datasets.Value("string"),
            'locale': datasets.Value("string"),
            'segment': datasets.Value("string"),
            'channel': datasets.Value("string")
        }
        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=datasets.Features(features_dict),
            # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
            # specify them. They'll be used if as_supervised=True in builder.as_dataset.
            # supervised_keys=("sentence", "label"),
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
        )

    def _split_generators(self, dl_manager):
        # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
        # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

        # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
        # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
        # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
        urls = _URLS[self.config.name]
        data_dirs = dl_manager.download_and_extract(urls)
        annotations_dirs = dl_manager.download_and_extract(_ANNOTATIONS_URL)
        print(f"data dirs: {data_dirs}")
        print(f"annotation dirs: {annotations_dirs}")
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "data_dirs": data_dirs,
                    "annotations_dirs": annotations_dirs
                },
            ),
            # TODO: add split handling
            # datasets.SplitGenerator(
            #     name=datasets.Split.TRAIN,
            #     # These kwargs will be passed to _generate_examples
            #     gen_kwargs={
            #         "filepath": os.path.join(data_dir, "test.jsonl"),
            #         "split": "test"
            #     },
            # ),
            # datasets.SplitGenerator(
            #     name=datasets.Split.TEST,
            #     # These kwargs will be passed to _generate_examples
            #     gen_kwargs={
            #         "filepath": os.path.join(data_dir, "test.jsonl"),
            #         "split": "test"
            #     },
            # ),
            # datasets.SplitGenerator(
            #     name=datasets.Split.VALIDATION,
            #     # These kwargs will be passed to _generate_examples
            #     gen_kwargs={
            #         "filepath": os.path.join(data_dir, "dev.jsonl"),
            #         "split": "dev",
            #     },
            # ),
        ]

    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, data_dirs, annotations_dirs):

        if self.config.name == "close_channel":
            channel_ext = "-1"
        else:
            channel_ext = "-2"

        for annotations_dir in annotations_dirs:
            annotations_files = os.listdir(annotations_dir)
            for annotation_filename in tqdm(annotations_files):

                annotations_filepath = os.path.join(annotations_dir, annotation_filename)
                with open(annotations_filepath, "r") as f:
                    annotation = json.load(f)

                if "val_recordings" in annotation:
                    val_recordings = annotation["val_recordings"]
                    for recording in val_recordings:
                        # channel_ext in can either be "-1" "-2"
                        # so if file is "123456.wav"
                        # close channel file is "123456-1.wav"
                        # distant channel file is "123456-2.wav"
                        rel_filepath = f'no/{annotation["pid"]}/{annotation["pid"]}_{recording["file"]}'.replace(".wav", f"{channel_ext}.wav")
                        for data_dir in data_dirs:
                            audio_filepath = f"{data_dir}/{rel_filepath}"
                            if os.path.exists(audio_filepath):
                                with open(audio_filepath, "rb") as f:
                                    audio_bytes = f.read()
                                result = {
                                    # "region_of_birth": annotation["info"]["Region_of_Birth"] or "",
                                    # "region_of_youth": annotation["info"]["Region_of_Youth"] or "",
                                    # "remarks": annotation["info"]["Remarks"] or "",
                                    # "pid": annotation["pid"] or "",
                                    # "directory": annotation["session"]["Directory"] or "",
                                    # "imported_sheet_file": annotation["session"]["Imported_sheet_file"] or "",
                                    # "mumber_of_recordings": annotation["session"]["Number_of_recordings"] or "",
                                    # "rec_date": annotation["session"]["RecDate"] or "",
                                    # "rec_time": annotation["session"]["RecTime"] or "",
                                    # "record_duration": annotation["session"]["Record_duration"] or "",
                                    # "record_session": annotation["session"]["Record_session"] or "",
                                    # "sheet_number": annotation["session"]["Sheet_number"] or "",
                                    # "ansi_codepage": annotation["system"]["ANSI_Codepage"] or "",
                                    # "board": annotation["system"]["Board"] or "",
                                    # "byte_format": annotation["system"]["ByteFormat"] or "",
                                    # "channels": annotation["system"]["Channels"] or "",
                                    # "character_set": annotation["system"]["CharacterSet"] or "",
                                    # "coding": annotation["system"]["Coding"] or "",
                                    # "dos_codepage": annotation["system"]["DOS_Codepage"] or "",
                                    # "delimiter": annotation["system"]["Delimiter"] or "",
                                    # "frequency": annotation["system"]["Frequency"] or "",
                                    # "memo": annotation["system"]["Memo"] or "",
                                    # "script": annotation["system"]["Script"] or "",
                                    # "version": annotation["system"]["Version"] or "", 
                                    "audio": {"path": rel_filepath, "bytes": audio_bytes},
                                    'client_id': annotation["info"]["Speaker_ID"] or "",
                                    'path': rel_filepath,
                                    'sentence': recording["text"],
                                    'up_votes': 1,
                                    'down_votes': 0,
                                    'age': annotation["info"]["Age"] or "",
                                    'sex': annotation["info"]["Sex"] or "",
                                    'accent': "",
                                    'locale': "sv",
                                    'segment': "",
                                    'channel': self.config.name or ""
                                }
                                yield rel_filepath, result