File size: 9,354 Bytes
49afe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45f5cc8
49afe74
bb41293
 
49afe74
 
 
 
 
 
c98fdcf
 
49afe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb41293
49afe74
 
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
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.

# Lint as: python3
"""NST_hesitate_hesitate: Nordic Language Technology"""

import io
import json
import tarfile
import datasets
from datasets.tasks import AutomaticSpeechRecognition


_CITATION = """\
@inproceedings{,
  title={},
  author={},
  booktitle={},
  year={2022},
  url={https://arxiv.org/abs/}
}
"""

_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.

The acoustic databases described below were developed by the firm Nordisk språkteknologi holding AS (NST_hesitate), which went bankrupt in 2003. In 2006, a consortium consisting of the University of Oslo, the University of Bergen, the Norwegian University of Science and Technology, the Norwegian Language Council and IBM bought the bankruptcy estate of NST_hesitate, in order to ensure that the language resources developed by NST_hesitate were preserved. In 2009, the Norwegian Ministry of Culture charged the National Library of Norway with the task of creating a Norwegian language bank, which they initiated in 2010. The resources from NST_hesitate were transferred to the National Library in May 2011, and are now made available in Språkbanken, for the time being without any further modification. Språkbanken is open for feedback from users about how the resources can be improved, and we are also interested in improved versions of the databases that users wish to share with other users. Please send response and feedback to sprakbanken@nb.no.
"""

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

# Example: https://huggingface.co/datasets/NbAiLab/NST_hesitate/resolve/main/data/train/NST_hesitate_no-0001-of-0001.tar.gz
_DATA_URL = "https://huggingface.co/datasets/NbAiLab/NST_hesitate/resolve/main/data/{split}/NST_hesitate_{lang_code}-{shard_idx:04d}-of-{shard_total:04d}.tar.gz"
# Example: https://huggingface.co/datasets/NbAiLab/NST_hesitate/resolve/main/data/test/NST_hesitate_no-0001-of-0001.json
_METADATA_URL = "https://huggingface.co/datasets/NbAiLab/NST_hesitate/resolve/main/data/{split}/NST_hesitate_{lang_code}-{shard_idx:04d}-of-{shard_total:04d}.json"

_SHARDS = {
    "no": {
        "test":1,
        "train": 1,
    },
}

_METADATA_MAPPING = {
  "id": "Id",
  "speakerId": "SpeakerId",
  "speakerName": "SpeakerName",
  "speakerAge": "SpeakerAge",
  "sex": "Sex",
  "speakerBirthPlace": "SpeakerBirthPlace",
  "speakerYouth": "SpeakerYouth",
  "speakerSheet": "SpeakerSheet",
  "script": "Script",
  "version": "Version",
  "board": "Board",
  "coding": "Coding",
  "frequency": "Frequency",
  "channels": "Channels",
  "byteFormat": "Byteformat",
  "delimiter": "Delimiter",
  "characterSet": "CharacterSet",
  "ansi_codepage": "Ansi_codepage",
  "dos_codepage": "Dos_codepage",
  "normalizedText": "normalizedText",
  "text": "text",
  "file": "file",

}


class NST_hesitateConfig(datasets.BuilderConfig):
    """BuilderConfig for NST_hesitate."""

    def __init__(self, *args, **kwargs):
        """BuilderConfig for NST_hesitate.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(NST_hesitateConfig, self).__init__(*args, **kwargs)


class NST_hesitate(datasets.GeneratorBasedBuilder):
    """NST_hesitate dataset."""

    DEFAULT_WRITER_BATCH_SIZE = 1000
    BUILDER_CONFIGS = [
        NST_hesitateConfig(
            name="no",
            version=datasets.Version("1.0.1"),
            description="NST_hesitate Norwegian",
        ),

    ]

    def _info(self):
        sampling_rate = 16000
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features({
                "id": datasets.Value("string"),
                "audio": datasets.features.Audio(sampling_rate=sampling_rate),
                "speakerId": datasets.Value("string"),
                "speakerName": datasets.Value("string"),
                "speakerAge": datasets.Value("string"),
                "sex": datasets.Value("string"),
                "speakerBirthPlace": datasets.Value("string"),
                "speakerYouth": datasets.Value("string"),
                "speakerSheet": datasets.Value("string"),
                "script": datasets.Value("string"),
                "version": datasets.Value("string"),
                "board": datasets.Value("string"),
                "coding": datasets.Value("string"),
                "frequency": datasets.Value("string"),
                "channels": datasets.Value("string"),
                "byteFormat": datasets.Value("string"),
                "delimiter": datasets.Value("string"),
                "characterSet": datasets.Value("string"),
                "ansi_codepage": datasets.Value("string"),
                "dos_codepage": datasets.Value("string"),
                "normalizedText": datasets.Value("string"),
                "text": datasets.Value("string"),
                "file": datasets.Value("string"),

            }),
            supervised_keys=None,
            homepage=_HOMEPAGE,
            citation=_CITATION,
            task_templates=[
                AutomaticSpeechRecognition(
                    audio_column="audio",
                    transcription_column="text"
                )
            ],
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        data_urls = {}


        for split in ["train", "test"]:
            data_urls[split] = []

            shard_total = _SHARDS["no"][split]
            for shard_idx in range(1, shard_total + 1):

                # .../data/{split}/NST_hesitate_{lang_code}_{split}_{mic}-{shard_idx}-of-{shard_total}
                string_formatting = dict(
                    split=split,
                    lang_code="no",
                    shard_idx=shard_idx,
                    shard_total=shard_total
                )
                data_urls[split] += [(
                    _METADATA_URL.format(**string_formatting),
                    _DATA_URL.format(**string_formatting)
                )]
        train_downloaded_data = dl_manager.download(data_urls["train"])
        test_downloaded_data = dl_manager.download(data_urls["test"])
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN, gen_kwargs={
                    "filepaths": train_downloaded_data,
                }
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST, gen_kwargs={
                    "filepaths": test_downloaded_data,
                }
            ),
        ]

    def _generate_examples(self, filepaths):
        """Yields examples."""
        #lang_code, _ = self.config.name.split("-")
        data_fields = list(self._info().features.keys())
        data_fields.remove("id")
        data_fields.remove("audio")
        for metadata_path, archive_path in filepaths:
            metadata = {}
            with open(metadata_path) as metadata_file:
                for line in metadata_file.read().split("\n"):
                    if line:
                        metadata_object = json.loads(line)
                        metadata_key = metadata_object["id"]
                        #metadata_key = f'{metadata_object["id"]}_{metadata_object["file"].replace(".wav", "")}'
                        metadata[metadata_key] = metadata_object
            with open(archive_path, "rb") as archive_fs:
                archive_bytes = io.BytesIO(archive_fs.read())
                with tarfile.open(fileobj=archive_bytes, mode="r") as tar:
                    for audio_file in tar.getmembers():
                        if audio_file.isfile() and audio_file.name.endswith(".mp3"):
                            metadata_key = f'{audio_file.name.replace(".mp3", "")}'
                            audio_bytes = tar.extractfile(audio_file).read()
                            audio_dict = {"bytes": audio_bytes, "path": audio_file.name}
                            fields = {key: metadata[metadata_key].get(_METADATA_MAPPING[key], "") for key in data_fields}
                            fields["channels"] = 1
                            fields["file"] = fields["file"].replace(".wav", ".mp3")
                            fields["frequency"] = 16000
                            # Fixing some errors in the metadata

                            yield metadata_key, {
                                "id": metadata_key,
                                "audio": audio_dict,
                                **fields
                            }