# coding=utf-8 # 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. """ Load swedish NST dataset provided by National Library of Norway | Språkbanken. Documentation with full description of the data: https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/se-16khz_reorganized.pdf NOTE: * The only split available is the train split, which includes the whole dataset. * The dataset is 33.5 GB compressed. If the download fails, you can try to download it manually: * From the logs, find the path to the local cache (e.g.: /Users/{user}/.cache/huggingface/datasets/marinone94___nst_sv/distant_channel/1.1.0/{hash}) * Most likely, {hash} directory does not exist yet, so $ cd /Users/{user}/.cache/huggingface/datasets/marinone94___nst_sv/distant_channel/1.1.0/ $ mkdir {hash} $ cd {hash} $ wget https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/se-16khz_reorganized.zip * Be patient, you need to download it only once... (if you don't delete the cache) TODO: * add multi channel option * add train-validation-test split option * add sample option * add data preview Suggested filtering: * replace("\\\\Punkt", "") * replace("\\\\Komma", "") """ import json import os from tqdm import tqdm import datasets _DESCRIPTION = """\ This database was created by Nordic Language Technology for the development of automatic speech recognition and dictation in Swedish. In this updated version, the organization of the data have been altered to improve the usefulness of the database. In the original version of the material, the files were organized in a specific folder structure where the folder names were meaningful. However, the file names were not meaningful, and there were also cases of files with identical names in different folders. This proved to be impractical, since users had to keep the original folder structure in order to use the data. The files have been renamed, such that the file names are unique and meaningful regardless of the folder structure. The original metadata files were in spl format. These have been converted to JSON format. The converted metadata files are also anonymized and the text encoding has been converted from ANSI to UTF-8. See the documentation file for a full description of the data and the changes made to the database.""" _HOMEPAGE = "https://www.nb.no/sprakbanken/en/resource-catalogue/oai-nb-no-sbr-56/" _LICENSE = "CC0 1.0" # 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) _URLS = { "close_channel": "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/lydfiler_16_1.tar.gz", # "distant_channel": "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/lydfiler_16_2.tar.gz", "distant_channel": "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/se-16khz_reorganized.pdf" # dummy # TODO: add handling of multi channel # "multi_channel": "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/lydfiler_16_begge.tar.gz", } _ANNOTATIONS_URL = "https://www.nb.no/sbfil/talegjenkjenning/16kHz_2020/se_2020/ADB_SWE_0467.tar.gz" class NstSV(datasets.GeneratorBasedBuilder): """Audio dataset for Swedish ASR provided by National Library of Norawy. Originally, recordings have been made on two channels: a close one and a distant one. Channels have been separated and can be loaded independently. TODO: enable and validate multi_channel Two configurations available: - close_channel - distant_channel Main data and metadata available: - audio file (bytes) - manually annotated transcription (str) - age (str) - gender (str) - region of birth (str) - region of youth (str) - recording session info (object) - recording system (object) - "type" of recording (see detailed documentatin) - common_voice-like structured information (info mentioned above with object structure like common voice dataset for ease of merging) """ VERSION = datasets.Version("1.1.0") # This is an example of a dataset with multiple configurations. # If you don't want/need to define several sub-sets in your dataset, # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes. # If you need to make complex sub-parts in the datasets with configurable options # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig # BUILDER_CONFIG_CLASS = MyBuilderConfig # You will be able to load one or the other configurations in the following list with # data = datasets.load_dataset('my_dataset', 'first_domain') # data = datasets.load_dataset('my_dataset', 'second_domain') BUILDER_CONFIGS = [ datasets.BuilderConfig(name="close_channel", version=VERSION, description="Close channel recordings"), datasets.BuilderConfig(name="distant_channel", version=VERSION, description="Distant channel recordings"), ] DEFAULT_CONFIG_NAME = "close_channel" # It's not mandatory to have a default configuration. Just use one if it make sense. def _info(self): features_dict = { "region_of_birth": datasets.Value("string"), "region_of_youth": datasets.Value("string"), "remarks": datasets.Value("string"), "pid": datasets.Value("string"), "directory": datasets.Value("string"), "imported_sheet_file": datasets.Value("string"), "mumber_of_recordings": datasets.Value("string"), "rec_date": datasets.Value("string"), "rec_time": datasets.Value("string"), "record_duration": datasets.Value("string"), "record_session": datasets.Value("string"), "sheet_number": datasets.Value("string"), "ansi_codepage": datasets.Value("string"), "board": datasets.Value("string"), "byte_format": datasets.Value("string"), "channels": datasets.Value("string"), "character_set": datasets.Value("string"), "coding": datasets.Value("string"), "dos_codepage": datasets.Value("string"), "delimiter": datasets.Value("string"), "frequency": datasets.Value("string"), "memo": datasets.Value("string"), "script": datasets.Value("string"), "version": datasets.Value("string"), "audio": datasets.features.Audio(sampling_rate=16000), 'client_id': datasets.Value("string"), 'path': datasets.Value("string"), 'sentence': datasets.Value("string"), 'up_votes': datasets.Value("int64"), 'down_votes': datasets.Value("int64"), 'age': datasets.Value("string"), 'sex': datasets.Value("string"), 'accent': datasets.Value("string"), 'locale': datasets.Value("string"), 'segment': datasets.Value("string"), 'channel': datasets.Value("string") } return datasets.DatasetInfo( # This is the description that will appear on the datasets page. description=_DESCRIPTION, # This defines the different columns of the dataset and their types features=datasets.Features(features_dict), # Here we define them above because they are different between the two configurations # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and # specify them. They'll be used if as_supervised=True in builder.as_dataset. # supervised_keys=("sentence", "label"), # Homepage of the dataset for documentation homepage=_HOMEPAGE, # License for the dataset if available license=_LICENSE, ) def _split_generators(self, dl_manager): # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files. # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive urls = _URLS[self.config.name] data_dir = dl_manager.download_and_extract(urls) annotations_dir = dl_manager.download_and_extract(_ANNOTATIONS_URL) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ "data_dir": data_dir, "annotations_dir": annotations_dir }, ), # TODO: add split handling # datasets.SplitGenerator( # name=datasets.Split.TRAIN, # # These kwargs will be passed to _generate_examples # gen_kwargs={ # "filepath": os.path.join(data_dir, "test.jsonl"), # "split": "test" # }, # ), # datasets.SplitGenerator( # name=datasets.Split.TEST, # # These kwargs will be passed to _generate_examples # gen_kwargs={ # "filepath": os.path.join(data_dir, "test.jsonl"), # "split": "test" # }, # ), # datasets.SplitGenerator( # name=datasets.Split.VALIDATION, # # These kwargs will be passed to _generate_examples # gen_kwargs={ # "filepath": os.path.join(data_dir, "dev.jsonl"), # "split": "dev", # }, # ), ] # method parameters are unpacked from `gen_kwargs` as given in `_split_generators` def _generate_examples(self, data_dir, annotations_dir): if self.config.name == "close_channel": channel_ext = "-1" else: channel_ext = "-2" annotations_files = os.listdir(annotations_dir) for annotation_filename in tqdm(annotations_files): annotations_filepath = os.path.join(annotations_dir, annotation_filename) with open(annotations_filepath, "r") as f: annotation = json.load(f) if "val_recordings" in annotation: val_recordings = annotation["val_recordings"] for recording in val_recordings: # channel_ext in can either be "-1" "-2" # so if file is "123456.wav" # close channel file is "123456-1.wav" # distant channel file is "123456-2.wav" rel_filepath = f'se/{annotation["pid"]}/{annotation["pid"]}_{recording["file"]}'.replace(".wav", f"{channel_ext}.wav") audio_filepath = f"{data_dir}/{rel_filepath}" if os.path.exists(audio_filepath): with open(audio_filepath, "rb") as f: audio_bytes = f.read() result = { "region_of_birth": annotation["info"]["Region_of_Birth"] or "", "region_of_youth": annotation["info"]["Region_of_Youth"] or "", "remarks": annotation["info"]["Remarks"] or "", "pid": annotation["pid"] or "", "directory": annotation["session"]["Directory"] or "", "imported_sheet_file": annotation["session"]["Imported_sheet_file"] or "", "mumber_of_recordings": annotation["session"]["Number_of_recordings"] or "", "rec_date": annotation["session"]["RecDate"] or "", "rec_time": annotation["session"]["RecTime"] or "", "record_duration": annotation["session"]["Record_duration"] or "", "record_session": annotation["session"]["Record_session"] or "", "sheet_number": annotation["session"]["Sheet_number"] or "", "ansi_codepage": annotation["system"]["ANSI_Codepage"] or "", "board": annotation["system"]["Board"] or "", "byte_format": annotation["system"]["ByteFormat"] or "", "channels": annotation["system"]["Channels"] or "", "character_set": annotation["system"]["CharacterSet"] or "", "coding": annotation["system"]["Coding"] or "", "dos_codepage": annotation["system"]["DOS_Codepage"] or "", "delimiter": annotation["system"]["Delimiter"] or "", "frequency": annotation["system"]["Frequency"] or "", "memo": annotation["system"]["Memo"] or "", "script": annotation["system"]["Script"] or "", "version": annotation["system"]["Version"] or "", "audio": {"path": rel_filepath, "bytes": audio_bytes}, 'client_id': annotation["info"]["Speaker_ID"] or "", 'path': rel_filepath, 'sentence': recording["text"], 'up_votes': 1, 'down_votes': 0, 'age': annotation["info"]["Age"] or "", 'sex': annotation["info"]["Sex"] or "", 'accent': "", 'locale': "sv", 'segment': "", 'channel': self.config.name or "" } yield rel_filepath, result