NPSC / NPSC.py
versae's picture
Adding data and docs
d0eabf1
raw
history blame
8.25 kB
# 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
from datasets.utils.streaming_download_manager import xopen
_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 = {
"validation": ["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 mp3)",
),
]
def _info(self):
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=48000),
}
),
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 = {}
metadata_urls = {}
config_name = self.config.name
for split in ["train", "validation", "test"]:
metadata_urls[split] = []
data_urls[split] = []
for shard in _SHARDS[split]:
metadata_urls[split] += [
_METADATA_URL.format(split=split, shard=shard)
]
data_urls[split] += [
_DATA_URL.format(split=split, shard=shard, config=config_name)
]
train_downloaded_metadata = dl_manager.download(metadata_urls["train"])
validation_downloaded_metadata = dl_manager.download(metadata_urls["validation"])
test_downloaded_metadata = dl_manager.download(metadata_urls["test"])
train_downloaded_archives = dl_manager.download(data_urls["train"])
validation_downloaded_archives = dl_manager.download(data_urls["validation"])
test_downloaded_archives = dl_manager.download(data_urls["test"])
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN, gen_kwargs={
"archives": train_downloaded_archives,
"metadata_paths": train_downloaded_metadata,
}
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION, gen_kwargs={
"archives": validation_downloaded_archives,
"metadata_paths": validation_downloaded_metadata,
}
),
datasets.SplitGenerator(
name=datasets.Split.TEST, gen_kwargs={
"archives": test_downloaded_archives,
"metadata_paths": test_downloaded_metadata,
}
),
]
def _generate_examples(self, archives, metadata_paths):
"""Yields examples."""
data_fields = list(self._info().features.keys())
data_fields.remove("audio")
for archive_path, metadata_path in zip(*[archives, metadata_paths]):
metadata = {}
with xopen(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 xopen(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}
yield metadata_key, {"audio": audio_dict, **fields}