File size: 11,251 Bytes
0a5f8f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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 swedish 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/se_2020/se-16khz_reorganized.pdf

TODO:
* add multi channel option
* add train-validation-test split option
"""

import csv
import json
import os

import datasets


_DESCRIPTION = """\
This database was created by Nordic Language Technology for the development 
of automatic speech recognition and dictation in Swedish. 
In this updated 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-56/"

_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/se_2020/lydfiler_16_1.tar.gz",
    "distant_channel": "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/lydfiler_16_2.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/se_2020/ADB_SWE_0467.tar.gz"


class NstSV(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 = {
            "info": dict,
            "metadata": dict,
            "pid": datasets.Value("string"),
            "session": dict,
            "system": dict,
            "val_recordings": list,
            "audio": datasets.features.Audio(sampling_rate=16000),
            'client_id': datasets.Value("string"),
            'path': datasets.Value("string"),
            'sentence': datasets.Value("string"),
            'up_votes': datasets.Value("int32"),
            'down_votes': datasets.Value("int32"),
            'age': datasets.Value("string"),
            'gender': 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_dir = dl_manager.download_and_extract(urls)
        annotations_dir = dl_manager.download_and_extract(_ANNOTATIONS_URL)
        
        return [
            datasets.SplitGenerator(
                name="all",
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "data_dir": data_dir,
                    "annotations_dir": annotations_dir
                },
            ),
            # 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_dir, annotations_dir):
        # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
        # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.

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

        for annotation_filename in os.listdir(annotations_dir):

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

            for recording in annotation["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'se/{annotation["pid"]}/{annotation["pid"]}_{recording["file"]}'.replace(".wav", f"{channel_ext}.wav")
                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 = {
                        "info": annotation["info"],
                        "metadata": annotation["metadata"],
                        "pid": annotation["pid"],
                        "session": annotation["session"],
                        "system": annotation["system"],
                        "val_recordings": annotation["val_recordings"],
                        "client_id": annotation["info"]["Speaker_ID"],
                        'path': rel_filepath,
                        'audio': {"path": rel_filepath, "bytes": audio_bytes},
                        'sentence': recording["text"],
                        'up_votes': 0,
                        'down_votes': 0,
                        'age': annotation["info"]["Age"],
                        'gender': annotation["info"]["Sex"],
                        'accent': "",
                        'locale': "sv",
                        'segment': ""
                    }

                    yield rel_filepath, result