File size: 10,487 Bytes
a9652e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae7d5d9
a9652e5
 
ae7d5d9
a9652e5
 
 
ae7d5d9
 
a9652e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5506cd
a9652e5
 
 
 
 
 
 
 
 
 
 
 
 
 
8e3b1c0
a9652e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae7d5d9
a9652e5
 
 
 
 
 
8e3b1c0
a9652e5
 
8e3b1c0
a9652e5
 
 
ae7d5d9
a9652e5
ae7d5d9
8e3b1c0
ae7d5d9
a9652e5
ae7d5d9
a9652e5
 
 
 
 
 
 
ae7d5d9
 
a9652e5
 
 
 
 
 
 
8e3b1c0
 
 
 
 
 
 
 
 
 
 
803fe81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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.

# Lint as: python3
"""NB Samtale: Norwegian conversation speech corpus"""


from collections import defaultdict
from email.mime import audio
from email.policy import default
from importlib import metadata
import io
import json
import os
from re import split
import tarfile
from typing import List

from huggingface_hub import hf_hub_url
import datasets

from datasets.packaged_modules.parquet.parquet import Parquet
from datasets.tasks import AutomaticSpeechRecognition
from datasets import ClassLabel

# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website


_DESCRIPTION = """\
NB Samtale is a speech corpus made by the Language Bank at the National Library of Norway.
The corpus contains orthographically transcribed speech from podcasts and recordings of live events at the National Library.
The corpus is intended as an open source dataset for Automatic Speech Recognition (ASR) development,
and is specifically aimed at improving ASR systems’ handle on conversational speech.
"""

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

_LICENSE = "CC-ZERO-license"

_CITATION = """\
"""

# 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)

# Source data: https://www.nb.no/sbfil/taledata/nb_samtale.zip
_DATA_URL= "https://huggingface.co/datasets/Sprakbanken/nb_samtale/resolve/main/data"

#_DATA_SPLITS = {
#    "train": ["train_bm_1.tar.gz", "train_nn_1.tar.gz"],
#    "dev": ["dev_bm_1.tar.gz", "dev_nn_1.tar.gz"],
#    "test": ["test_bm_1.tar.gz", "test_nn_1.tar.gz"],
#}

class NBSamtaleConfig(datasets.BuilderConfig):
    """BuilderConfig for NBSamtale"""

    def __init__(self, **kwargs):
        # Version history:
        # 1.0.0: Initial version.
        super(NBSamtaleConfig, self).__init__(version=datasets.Version("1.0.0"), **kwargs)


class NBSamtale(datasets.GeneratorBasedBuilder):
    """Norwegian conversational speech audio dataset with a total of 24 hours transcribed speech from 69 speakers. """
    BUILDER_CONFIG_CLASS = NBSamtaleConfig

    BUILDER_CONFIGS = [
        NBSamtaleConfig(name="annotations", description="Transcriptions contain original annotations, including hesitations, laughter, interruptions etc. See https://www.nb.no/sbfil/taledata/NB_Samtale_About_the_corpus.pdf section 'Transcriptions' for more information."),
        NBSamtaleConfig(name="orthographic",  description="Transcriptions have been normalized and word forms that comply with the orthographic standard are chosen, even for dialect specific words, e.g. 'korsen'/'kossen' is replaced with 'hvordan' in bokmål, or 'korleis' in nynorsk."),
        NBSamtaleConfig(name="verbatim", description="Transcriptions are closer to the spoken words, dialectal word forms have been chosen instead of the standard orthographic word form. E.g. 'korsen' or 'kossen' would be kept, instead of the orthographic bokmål 'hvordan', or nynorsk 'korleis'."),
        #NBSamtaleConfig(name="bm", language="bokmål", description="Normalized bokmål transcriptions. Word forms that comply with the orthographic standard are chosen, e.g. 'korsen' is replaced with 'hvordan'."),
        #NBSamtaleConfig(name="nn", language="nynorsk", description="Normalized nynorsk transcriptions. Word forms that comply with the orthographic standard are chosen, e.g. 'kossen' is replaced with 'korleis'."),
    ]

    DEFAULT_CONFIG_NAME = "annotations"

    def _info(self):
        """This method specifies the datasets.DatasetInfo object
        which contains informations and typings for the dataset.
        """

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    'source_file_id': datasets.Value(dtype='string'),
                    'segment_id': datasets.Value(dtype='string'),
                    'segment_order': datasets.Value(dtype='int64'),
                    'duration': datasets.Value(dtype='float64'),
                    'overlap_previous': datasets.Value(dtype='bool'),
                    'overlap_next': datasets.Value(dtype='bool'),
                    'speaker_id': datasets.Value(dtype='string'),
                    'gender': ClassLabel(names=['f', 'm']),
                    'dialect': ClassLabel(names=['e', 'n', 'sw', 't', 'w']),
                    'orthography': ClassLabel(names=['bm', 'nn']),
                    'source_type': ClassLabel(names=['live-event', 'podcast']),
                    'file_name': datasets.Value(dtype='string'),
                    'transcription': datasets.Value(dtype='string'),
                    'audio': datasets.Audio(sampling_rate=16000, mono=True, decode=True),
                }
            ),
            supervised_keys=None,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )


    def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
        """Download data and extract to datasets.Splits"""
        dl_manager.download_config.ignore_url_params = True
        audio_path = {}
        split_type = {
            "train": datasets.Split.TRAIN,
            "test": datasets.Split.TEST,
            "validation": datasets.Split.VALIDATION,
            }
        for split in split_type:
            audio_path[split] = dl_manager.download([f"data/{split}_{lang}_1.tar.gz" for lang in ["bm", "nn"]])

        return [
            datasets.SplitGenerator(
            name=split_type[split],
            gen_kwargs={
                "local_extracted_archive": dl_manager.extract(audio_path[split]) if not dl_manager.is_streaming else None,
                "audio_files":[dl_manager.iter_archive(archive) for archive in audio_path[split]],  #dl_manager.iter_archive(audio_path[split]),
                "metadata": dl_manager.download_and_extract(f"data/{split}_metadata.jsonl"),
                }
            ) for split in split_type
        ]

    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, local_extracted_archive, audio_files, metadata):
        """Loads the data files and extract the features."""
        meta = {}
        with open(metadata, encoding="utf-8") as mf:
            datalines = mf.read().splitlines()
            for row in datalines:
                data = json.loads(row)
                audio_path = data["file_name"]
                data["transcription"] = normalize_transcription(data["transcription"], config=self.config.name)
                meta[audio_path] = data

        id_ = 0

        for archive in audio_files:
            for path, audio_file in archive:
                if not path in meta:
                    print(f"{path} not in metadata")
                else:
                    result = dict(meta[path])
                    # set the audio feature and the path to the extracted file
                    path = os.path.join(local_extracted_archive, path) if local_extracted_archive else path
                    result["audio"] = {"path": path, "bytes": audio_file.read()}
                    yield id_, result
                    id_ += 1


### Normalization functions ###

from sprakbanken_normalizer.inverse_text_normalizer import inv_normalize
import re


def filter_backslash(text, left=True):
    """Substitute backslash notation with the word to the left or right of it."""
    regx = re.compile(r"\b([\w_-]+)\\([\w_-]+)\b")
    if left:
        return regx.sub(r"\1", text)
    else:
        return regx.sub(r"\2", text)

def remove_repeats(text):
    """Remove repeated words."""
    return re.sub(r"\b(\w+\s+)(\1){1,10}", "\1", text)

def bracket_metatags(text):
    """Enclose unintelligible, foreign, overlapping and unknown words in angle brackets."""
    regx = re.compile(r"%(unint|foreign|unk|overlapping)")
    return regx.sub(r"<\1>", text)

def remove_metatags(text):
    """Remove metatags for hesitations, laughter, paralinguistic sounds etc."""
    return re.sub(r"%\w{3}\s", "", text)

def remove_percentage_sign(text):
    """Remove percentage sign."""
    return re.sub(r"%", "", text)

def remove_false_starts(text):
    """Remove annotations of false starts and interruptions."""
    return re.sub(r"\s\w+£", "", text)

def remove_pound_sign(text):
    """Remove pound sign."""
    return re.sub(r"£", "", text)

def replace_underscore(text):
    """Replace underscore with a single whitespace."""
    return re.sub(r"_", " ", text)

def remove_punctuation(text):
    """Remove punctuation."""
    return re.sub(r"[,\.\!\'-]", "", text)

def normalize_number_words(text):
    """Normalize number words to integers."""
    # TODO: convert hyphenated year-words to integers
    # TODO: deal with punctuation at the end
    inv_norm = inv_normalize(text)
    return inv_norm



def normalize_transcription(transcription: str, config="annotations"):
    """Normalize transcriptions according to orthographic standards, or verbatim."""
    t = transcription
    if config == "annotations":
        # Nothing do, return as is
        return t
    if config == "orthographic":
        t = remove_metatags(t)
        t = remove_false_starts(t)
        t = re.sub(r"CO-to", "CO2", t)
        t = filter_backslash(t, left=False)
        t = normalize_number_words(t)
    elif config == "verbatim":
        t = bracket_metatags(t)
        t = remove_percentage_sign(t)
        t = remove_pound_sign(t)
        t = re.sub(r"C_O-to", "C O to", t)
        t = filter_backslash(t, left=True)
        t = remove_punctuation(t)
    # For both, at the end:
    t = replace_underscore(t)
    return t