ingerid commited on
Commit
a9652e5
1 Parent(s): fc68fbb

add loading script

Browse files
Files changed (1) hide show
  1. nb_samtale.py +202 -0
nb_samtale.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # Lint as: python3
16
+ """NB Samtale: Norwegian conversation speech corpus"""
17
+
18
+
19
+ from collections import defaultdict
20
+ from email.policy import default
21
+ from importlib import metadata
22
+ import json
23
+ import os
24
+ from re import split
25
+
26
+ from huggingface_hub import hf_hub_url
27
+ import datasets
28
+
29
+ from datasets.packaged_modules.parquet.parquet import Parquet
30
+ from datasets.tasks import AutomaticSpeechRecognition
31
+ from datasets import ClassLabel
32
+
33
+ # TODO: Add BibTeX citation
34
+ # Find for instance the citation on arxiv or on the dataset repo/website
35
+
36
+
37
+ _DESCRIPTION = """\
38
+ NB Samtale is a speech corpus made by the Language Bank at the National Library of Norway.
39
+ The corpus contains orthographically transcribed speech from podcasts and recordings of live events at the National Library.
40
+ The corpus is intended as an open source dataset for Automatic Speech Recognition (ASR) development,
41
+ and is specifically aimed at improving ASR systems’ handle on conversational speech.
42
+ """
43
+
44
+ _HOMEPAGE = "https://www.nb.no/sprakbanken/en/resource-catalogue/oai-nb-no-sbr-85/"
45
+
46
+ _LICENSE = "CC-ZERO-license"
47
+
48
+ _CITATION = """\
49
+ """
50
+
51
+ # TODO: Add link to the official dataset URLs here
52
+ # The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
53
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
54
+
55
+ # Source data: https://www.nb.no/sbfil/taledata/nb_samtale.zip
56
+ _DATA_URL= "https://huggingface.co/datasets/Sprakbanken/nb_samtale/resolve/main/data"
57
+
58
+ #_DATA_SPLITS = {
59
+ # "train": ["train_bm_1.tar.gz", "train_nn_1.tar.gz"],
60
+ # "dev": ["dev_bm_1.tar.gz", "dev_nn_1.tar.gz"],
61
+ # "test": ["test_bm_1.tar.gz", "test_nn_1.tar.gz"],
62
+ #}
63
+
64
+ class NBSamtaleConfig(datasets.BuilderConfig):
65
+ """BuilderConfig for NBSamtale"""
66
+
67
+ def __init__(self, **kwargs):
68
+ # Version history:
69
+ # 1.0.0: Initial version.
70
+ super().__init__(version=datasets.Version("1.0.0"), **kwargs)
71
+ #self.language = language
72
+
73
+
74
+ class NBSamtale(datasets.GeneratorBasedBuilder):
75
+ """Norwegian conversational speech audio dataset with a total of 24 hours transcribed speech from 69 speakers. """
76
+
77
+ # This is an example of a dataset with multiple configurations.
78
+ # If you don't want/need to define several sub-sets in your dataset,
79
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
80
+
81
+ # If you need to make complex sub-parts in the datasets with configurable options
82
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
83
+ BUILDER_CONFIG_CLASS = NBSamtaleConfig
84
+
85
+ # You will be able to load one or the other configurations in the following list with
86
+ # data = datasets.load_dataset('Sprakbanken/nb_samtale', 'normalized')
87
+ # data = datasets.load_dataset('Sprakbanken/nb_samtale', 'verbatim')
88
+ BUILDER_CONFIGS = [
89
+ 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."),
90
+ 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."),
91
+ 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'."),
92
+ #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'."),
93
+ #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'."),
94
+ ]
95
+
96
+ DEFAULT_CONFIG_NAME = "annotations" # It's not mandatory to have a default configuration. Just use one if it make sense.
97
+
98
+ def _info(self):
99
+ """This method specifies the datasets.DatasetInfo object
100
+ which contains informations and typings for the dataset.
101
+ """
102
+
103
+ return datasets.DatasetInfo(
104
+ # This is the description that will appear on the datasets page.
105
+ description=_DESCRIPTION,
106
+ # This defines the different columns of the dataset and their types
107
+ features=datasets.Features(
108
+ {
109
+ 'source_file_id': datasets.Value(dtype='string'),
110
+ 'segment_id': datasets.Value(dtype='string'),
111
+ 'segment_order': datasets.Value(dtype='int64'),
112
+ 'duration': datasets.Value(dtype='float64'),
113
+ 'overlap_previous': datasets.Value(dtype='bool'),
114
+ 'overlap_next': datasets.Value(dtype='bool'),
115
+ 'speaker_id': datasets.Value(dtype='string'),
116
+ 'gender': ClassLabel(names=['f', 'm']),
117
+ 'dialect': ClassLabel(names=['e', 'n', 'sw', 't', 'w']),
118
+ 'orthography': ClassLabel(names=['bm', 'nn']),
119
+ 'source_type': ClassLabel(names=['live-event', 'podcast']),
120
+ 'file_name': datasets.Value(dtype='string'),
121
+ 'transcription': datasets.Value(dtype='string'),
122
+ 'audio': datasets.Audio(sampling_rate=16000, mono=True, decode=True),
123
+ }
124
+ ),
125
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
126
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
127
+ supervised_keys=None,
128
+ # Homepage of the dataset for documentation
129
+ homepage=_HOMEPAGE,
130
+ # License for the dataset if available
131
+ license=_LICENSE,
132
+ # Citation for the dataset
133
+ citation=_CITATION,
134
+ )
135
+
136
+
137
+ def _split_generator(self, dl_manager) -> datasets.SplitGenerator:
138
+ """Download data and extract to datasets.Splits"""
139
+ dl_manager.download_config.ignore_url_params = True
140
+ audio_path = {}
141
+ local_extracted_archive = {}
142
+ metadata_path = {}
143
+ split_type = {
144
+ "train": datasets.Split.TRAIN,
145
+ "test": datasets.Split.TEST,
146
+ "dev": datasets.Split.VALIDATION
147
+ }
148
+ for split in split_type:
149
+ audio_path[split] = dl_manager.download([f"{_DATA_URL}/{split}_{lang}_1.tar.gz" for lang in ["bm", "nn"]])
150
+ local_extracted_archive[split] = dl_manager.extract(audio_path[split]) if not dl_manager.is_streaming else None
151
+ metadata_path[split] = dl_manager.download_and_extract(f"{_DATA_URL}/{split}_metadata.jsonl")
152
+
153
+ return [
154
+ datasets.SplitGenerator(
155
+ name=dsplit,
156
+ gen_kwargs={
157
+ "local_extracted_archive": local_extracted_archive[split],
158
+ "audio_files": dl_manager.iter_archive(audio_path[split]),
159
+ "metadata": metadata_path[split],
160
+ }
161
+ ) for split, dsplit in split_type.items()
162
+ ]
163
+
164
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
165
+ def _generate_examples(self, local_extracted_archive, audio_files, metadata):
166
+ """Loads the data files and extract the features."""
167
+ data_fields = list(self._info().features.keys())
168
+ # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
169
+ # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
170
+ meta = {}
171
+ with open(metadata, encoding="utf-8") as mf:
172
+ for row in mf.read().splitlines():
173
+ data = json.loads(row)
174
+ audio_path = data["file_name"]
175
+ # if data is incomplete, fill with empty values
176
+ data["transcription"] = normalize_transcription(data["transcription"], config=self.config.name)
177
+ for field in data_fields:
178
+ if field not in data:
179
+ data[field] = ""
180
+
181
+ meta[audio_path] = data
182
+
183
+ id_ = 0
184
+ for path, audiofile in audio_files:
185
+ if path in meta:
186
+ result = dict(meta[path])
187
+ # set the audio feature and the path to the extracted file
188
+ path = os.path.join(local_extracted_archive, path) if local_extracted_archive else path
189
+ result["audio"] = {"path": path, "bytes": audiofile.read()}
190
+ result["path"] = path
191
+ yield id_, result
192
+ id_ += 1
193
+
194
+
195
+ def normalize_transcription(transcription: str, config="annotations"):
196
+ """Normalize transcriptions according to orthographic standards, or verbatim."""
197
+ # TODO: Implement normalization
198
+ if config == "orthographic":
199
+ return transcription
200
+ elif config == "verbatim":
201
+ return transcription
202
+ return transcription