NPSC_orto / NPSC_orto.py
albertvillanova's picture
Remove deprecated tasks (#1)
b6537be verified
# 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_orto: Norwegian Parliament Speech Corpus"""
import io
import json
import tarfile
import datasets
_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.
This dataset builds on this corpus. In addition it adds two columns with machine generated orthographic text.
"""
_HOMEPAGE = "https://www.nb.no/sprakbanken/en/resource-catalogue/oai-nb-no-sbr-58/"
# Example: https://huggingface.co/datasets/NbAiLab/NPSC_orto/resolve/main/data/train/20170110_48K_mp3.tar.gz
_DATA_URL = "https://huggingface.co/datasets/NbAiLab/NPSC_orto/resolve/main/data/{split}/{shard}_{config}.tar.gz"
# Example: https://huggingface.co/datasets/NbAiLab/NPSC_orto/resolve/main/data/test/20170207.json
_METADATA_URL = "https://huggingface.co/datasets/NbAiLab/NPSC_orto/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 Npsc_ortoConfig(datasets.BuilderConfig):
"""BuilderConfig for NPSC_orto."""
def __init__(self, *args, **kwargs):
"""BuilderConfig for NPSC_orto.
Args:
**kwargs: keyword arguments forwarded to super.
"""
super(Npsc_ortoConfig, self).__init__(*args, **kwargs)
class Npsc_orto(datasets.GeneratorBasedBuilder):
"""NPSC_orto dataset."""
DEFAULT_WRITER_BATCH_SIZE = 1000
BUILDER_CONFIGS = [
Npsc_ortoConfig(
name="48K_mp3",
version=datasets.Version("1.0.0"),
description="NPSC_orto with samples in 48KHz stereo mp3)",
),
Npsc_ortoConfig(
name="16K_mp3",
version=datasets.Version("1.0.0"),
description="NPSC_orto with samples in 16KHz mono mp3)",
),
Npsc_ortoConfig(
name="48K_mp3_bokmaal",
version=datasets.Version("1.0.0"),
description="NPSCi_orto with Bokmål samples in 48KHz stereo mp3)",
),
Npsc_ortoConfig(
name="16K_mp3_bokmaal",
version=datasets.Version("1.0.0"),
description="NPSC_orto with Bokmål samples in 16KHz mono mp3)",
),
Npsc_ortoConfig(
name="48K_mp3_nynorsk",
version=datasets.Version("1.0.0"),
description="NPSCi_orto with Nynorsk samples in 48KHz stereo mp3)",
),
Npsc_ortoConfig(
name="16K_mp3_nynorsk",
version=datasets.Version("1.0.0"),
description="NPSC_orto 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(
{
"sentence_id": datasets.Value("int32"),
"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_nob": datasets.Value("string"),
"sentence_nno": 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,
)
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}