File size: 9,149 Bytes
f19ff8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0eabf1
 
 
 
f19ff8a
 
0e12b46
f19ff8a
5b01d58
f19ff8a
 
5b01d58
f19ff8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69bf15
 
 
 
 
 
f19ff8a
2c1585e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f19ff8a
 
 
2c1585e
f19ff8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddb68e8
f19ff8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c1585e
 
0e12b46
f19ff8a
 
f0aa293
 
f19ff8a
f0aa293
 
 
 
f19ff8a
 
 
 
f0aa293
f19ff8a
 
 
 
f0aa293
f19ff8a
 
 
 
f0aa293
f19ff8a
 
 
 
f0aa293
f19ff8a
 
 
2c1585e
 
 
 
 
f0aa293
f19ff8a
f0aa293
f19ff8a
 
 
 
 
 
f0aa293
f19ff8a
 
 
 
 
 
 
 
2c1585e
 
 
 
 
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
# 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
"""NPSC: Norwegian Parliament Speech Corpus"""

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


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

_DESCRIPTION = """\
The Norwegian Parliament Speech Corpus (NPSC) is a corpus for training a Norwegian ASR (Automatic Speech Recognition) models. The corpus is created by Språkbanken at the National Library in Norway.

NPSC is based on sound recording from meeting in the Norwegian Parliament. These talks are orthographically transcribed to either Norwegian Bokmål or Norwegian Nynorsk. In addition to the data actually included in this dataset, there is a significant amount of metadata that is included in the original corpus. Through the speaker id there is additional information about the speaker, like gender, age, and place of birth (ie dialect). Through the proceedings id the corpus can be linked to the official proceedings from the meetings.

The corpus is in total sound recordings from 40 entire days of meetings. This amounts to 140 hours of speech, 65,000 sentences or 1.2 million words.
"""

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

# Example: https://huggingface.co/datasets/NbAiLab/NPSC/resolve/main/data/train/20170110_48K_mp3.tar.gz
_DATA_URL = "https://huggingface.co/datasets/NbAiLab/NPSC/resolve/main/data/{split}/{shard}_{config}.tar.gz"
# Example: https://huggingface.co/datasets/NbAiLab/NPSC/resolve/main/data/test/20170207.json
_METADATA_URL = "https://huggingface.co/datasets/NbAiLab/NPSC/resolve/main/data/{split}/{shard}.json"

_SHARDS = {
    "eval": ["20170209", "20180109", "20180201", "20180307", "20180611"],
    "test": ["20170207", "20171122", "20171219", "20180530"],
    "train": ["20170110", "20170208", "20170215", "20170216", "20170222", "20170314", "20170322", "20170323", "20170403", "20170405", "20170419", "20170426", "20170503", "20170510", "20170516", "20170613", "20170615", "20171007", "20171012", "20171018", "20171024", "20171208", "20171211", "20171213", "20180316", "20180321", "20180404", "20180410", "20180411", "20180601", "20180613", "20180615"],
}


class NpscConfig(datasets.BuilderConfig):
    """BuilderConfig for NPSC."""

    def __init__(self, *args, **kwargs):
        """BuilderConfig for NPSC.

        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(NpscConfig, self).__init__(*args, **kwargs)


class Npsc(datasets.GeneratorBasedBuilder):
    """NPSC dataset."""

    DEFAULT_WRITER_BATCH_SIZE = 1000
    BUILDER_CONFIGS = [
        NpscConfig(
            name="48K_mp3",
            version=datasets.Version("1.0.0"),
            description="NPSC with samples in 48KHz stereo mp3)",
        ),
        NpscConfig(
            name="16K_mp3",
            version=datasets.Version("1.0.0"),
            description="NPSC with samples in 16KHz mono mp3)",
        ),
        NpscConfig(
            name="48K_mp3_bokmaal",
            version=datasets.Version("1.0.0"),
            description="NPSC with Bokmål samples in 48KHz stereo mp3)",
        ),
        NpscConfig(
            name="16K_mp3_bokmaal",
            version=datasets.Version("1.0.0"),
            description="NPSC with Bokmål samples in 16KHz mono mp3)",
        ),
        NpscConfig(
            name="48K_mp3_nynorsk",
            version=datasets.Version("1.0.0"),
            description="NPSC with Nynorsk samples in 48KHz stereo mp3)",
        ),
        NpscConfig(
            name="16K_mp3_nynorsk",
            version=datasets.Version("1.0.0"),
            description="NPSC with Nynorsk samples in 16KHz mono mp3)",
        ),
    ]

    def _info(self):
        sampling_rate = 16_000 if self.config.name.startswith("16K") else 48_000
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "meeting_date": datasets.Value("string"),
                    "sentence_order":  datasets.Value("int32"),
                    "speaker_id" : datasets.Value("int32"),
                    "speaker_name": datasets.Value("string"),
                    "sentence_text": datasets.Value("string"),
                    "sentence_language_code": datasets.Value("string"),
                    "text": datasets.Value("string"),
                    "start_time": datasets.Value("int32"),
                    "end_time": datasets.Value("int32"),
                    "normsentence_text": datasets.Value("string"),
                    "transsentence_text": datasets.Value("string"),
                    "translated": datasets.Value("int32"),
                    "audio": datasets.features.Audio(sampling_rate=sampling_rate),

                }
            ),
            supervised_keys=None,
            homepage=_HOMEPAGE,
            citation=_CITATION,
            task_templates=[
                AutomaticSpeechRecognition(
                    audio_file_path_column="path",
                    transcription_column="sentence_text"
                )
            ],
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        data_urls = {}
        config_name = self.config.name
        if config_name.endswith("bokmaal") or config_name.endswith("nynorsk"):
            config_name, *_ = config_name.rsplit("_", 1)
        for split in ["train", "eval", "test"]:
            data_urls[split] = []
            for shard in _SHARDS[split]:
                data_urls[split] += [(
                    _METADATA_URL.format(split=split, shard=shard),
                    _DATA_URL.format(split=split, shard=shard, config=config_name)
                )]
        train_downloaded_data = dl_manager.download(data_urls["train"])
        validation_downloaded_data = dl_manager.download(data_urls["eval"])
        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.VALIDATION, gen_kwargs={
                    "filepaths": validation_downloaded_data,
                }
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST, gen_kwargs={
                    "filepaths": test_downloaded_data,
                }
            ),
        ]

    def _generate_examples(self, filepaths):
        """Yields examples."""
        data_fields = list(self._info().features.keys())
        data_fields.remove("audio")
        lang_code = None
        if self.config.name.endswith("bokmaal"):
            lang_code = "nb-no"
        elif self.config.name.endswith("nynorsk"):
           lang_code = "nn-no"
        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)
                        if "path" in metadata_object:
                            metadata_key = metadata_object["path"].split("/", 1)[-1]
                            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():
                            metadata_key = audio_file.name.split(".mp3", 1)[0].split("/", 1)[-1]
                            audio_bytes = tar.extractfile(audio_file).read()
                            audio_dict = {"bytes": audio_bytes, "path": audio_file.name}
                            fields = {key: metadata[metadata_key][key] for key in data_fields}
                            if lang_code:
                                if lang_code == fields.get("sentence_language_code", "").lower():
                                    yield metadata_key, {"audio": audio_dict, **fields}
                            else:
                                yield metadata_key, {"audio": audio_dict, **fields}