# 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. """ Aishell dataset. """ import os import datasets from huggingface_hub import list_repo_files import gzip import json repo_id = "yuekai/aishell" _DESCRIPTION = """\ aishell """ _HOMEPAGE = "https://github.com/SpeechColab/Aishell" _SUBSETS = ("train", "dev", "test") _BASE_DATA_URL = f"https://huggingface.co/datasets/{repo_id}/resolve/main/" _AUDIO_ARCHIVE_URL = _BASE_DATA_URL + "data/aishell_cuts_{subset}.{archive_id:08}.tar.gz" _META_URL = _BASE_DATA_URL + "data/aishell_cuts_{subset}.{archive_id:08}.jsonl.gz" FILES = list_repo_files(repo_id, repo_type="dataset") logger = datasets.utils.logging.get_logger(__name__) class CustomAudioConfig(datasets.BuilderConfig): """BuilderConfig for the dataset.""" def __init__(self, name, *args, **kwargs): """BuilderConfig for the dataset. """ super().__init__(name=name, *args, **kwargs) assert name in _SUBSETS, f"Unknown subset {name}" self.subsets_to_download = (name,) class Aishell(datasets.GeneratorBasedBuilder): """ Aishell is an evolving, multi-domain English speech recognition corpus with 10,000 hours of high quality labeled audio suitable for supervised training, and 40,000 hours of total audio suitable for semi-supervised and unsupervised training (this implementation contains only labelled data for now). Around 40,000 hours of transcribed audio is first collected from audiobooks, podcasts and YouTube, covering both read and spontaneous speaking styles, and a variety of topics, such as arts, science, sports, etc. A new forced alignment and segmentation pipeline is proposed to create sentence segments suitable for speech recognition training, and to filter out segments with low-quality transcription. For system training, Aishell provides five subsets of different sizes, 10h, 250h, 1000h, 2500h, and 10000h. For our 10,000-hour XL training subset, we cap the word error rate at 4% during the filtering/validation stage, and for all our other smaller training subsets, we cap it at 0%. The DEV and TEST evaluation sets, on the other hand, are re-processed by professional human transcribers to ensure high transcription quality. """ VERSION = datasets.Version("1.0.0") BUILDER_CONFIGS = [CustomAudioConfig(name=subset) for subset in _SUBSETS] DEFAULT_WRITER_BATCH_SIZE = 128 def _info(self): features = datasets.Features( { "segment_id": datasets.Value("string"), "speaker": datasets.Value("string"), "text": datasets.Value("string"), "audio": datasets.Audio(sampling_rate=16_000), "original_full_path": datasets.Value("string"), # relative path to full audio in original data dirs } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, homepage=_HOMEPAGE, ) @property def _splits_to_subsets(self): return { "train": ['train'], "dev": ["dev"], "test": ["test"] } def _split_generators(self, dl_manager): splits_to_subsets = self._splits_to_subsets splits = (self.config.name,) # if self.config.name in {"dev", "test"}: # splits = (self.config.name,) # else: # splits = ("train", "dev", "test") split_to_n_archives = { split: int(len([file for file in FILES if f"cuts_{splits_to_subsets[split][0]}" in file]) / 2) for split in splits } # 2. prepare sharded archives with audio files audio_archives_urls = { split: [ _AUDIO_ARCHIVE_URL.format(subset=splits_to_subsets[split][0], archive_id=i) for i in range(split_to_n_archives[split]) ] for split in splits } audio_archives_paths = dl_manager.download(audio_archives_urls) local_audio_archives_paths = dl_manager.extract(audio_archives_paths) if not dl_manager.is_streaming \ else None # 3. prepare sharded metadata csv files meta_urls = { split: [ _META_URL.format(subset=splits_to_subsets[split][0], archive_id=i) for i in range(split_to_n_archives[split]) ] for split in splits } # meta_paths = dl_manager.download_and_extract(meta_urls) meta_paths = dl_manager.download(meta_urls) return [ datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "audio_archives_iterators": [ dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths[self.config.name] ], "local_audio_archives_paths": local_audio_archives_paths[ self.config.name] if local_audio_archives_paths else None, "meta_paths": meta_paths[self.config.name] }, ), ] # if self.config.name not in {"dev", "test"}: # result = [ # datasets.SplitGenerator( # name=datasets.Split.TRAIN, # gen_kwargs={ # "audio_archives_iterators": [ # dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["train"] # ], # "local_audio_archives_paths": local_audio_archives_paths[ # "train"] if local_audio_archives_paths else None, # "meta_paths": meta_paths["train"] # }, # ) # ] # if 'dev' in audio_archives_paths: # result.append(datasets.SplitGenerator( # name=datasets.Split.VALIDATION, # gen_kwargs={ # "audio_archives_iterators": [ # dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["dev"] # ], # "local_audio_archives_paths": local_audio_archives_paths[ # "dev"] if local_audio_archives_paths else None, # "meta_paths": meta_paths["dev"] # }, # )) # if 'test' in audio_archives_paths: # result.append(datasets.SplitGenerator( # name=datasets.Split.TEST, # gen_kwargs={ # "audio_archives_iterators": [ # dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["test"] # ], # "local_audio_archives_paths": local_audio_archives_paths[ # "test"] if local_audio_archives_paths else None, # "meta_paths": meta_paths["test"] # }, # )) # return result # if self.config.name == "dev": # return [ # datasets.SplitGenerator( # name=datasets.Split.VALIDATION, # gen_kwargs={ # "audio_archives_iterators": [ # dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["dev"] # ], # "local_audio_archives_paths": local_audio_archives_paths[ # "dev"] if local_audio_archives_paths else None, # "meta_paths": meta_paths["dev"] # }, # ), # ] # if self.config.name == "test": # return [ # datasets.SplitGenerator( # name=datasets.Split.TEST, # gen_kwargs={ # "audio_archives_iterators": [ # dl_manager.iter_archive(archive_path) for archive_path in audio_archives_paths["test"] # ], # "local_audio_archives_paths": local_audio_archives_paths[ # "test"] if local_audio_archives_paths else None, # "meta_paths": meta_paths["test"] # }, # ), # ] def _generate_examples(self, audio_archives_iterators, local_audio_archives_paths, meta_paths): def load_meta(file_path): data = {} with gzip.open(file_path, 'rt', encoding='utf-8') as f: for line in f: item = json.loads(line) data[item["id"]] = item return data assert len(audio_archives_iterators) == len(meta_paths) if local_audio_archives_paths: assert len(audio_archives_iterators) == len(local_audio_archives_paths) for i, (meta_path, audio_archive_iterator) in enumerate(zip(meta_paths, audio_archives_iterators)): meta_dict = load_meta(meta_path) for audio_path_in_archive, audio_file in audio_archive_iterator: # `audio_path_in_archive` is like "data/aishell_cuts_test.00000000/BAC/BAC009S0764W0393-359.wav" audio_filename = os.path.split(audio_path_in_archive)[-1] audio_id = audio_filename.split(".wav")[0] audio_meta = meta_dict[audio_id] audio_meta["segment_id"] = audio_id audio_meta["original_full_path"] = audio_meta["recording"]["sources"][0]["source"] audio_meta["text"] = audio_meta['supervisions'][0]['text'] audio_meta["speaker"] = audio_meta['supervisions'][0]['speaker'] path = os.path.join(local_audio_archives_paths[i], audio_path_in_archive) if local_audio_archives_paths \ else audio_path_in_archive yield audio_id, { "audio": {"path": path , "bytes": audio_file.read()}, **{feature: value for feature, value in audio_meta.items() if feature in self.info.features} }