# coding=utf-8 """FSDKaggle2019 sound classification dataset.""" import os import gzip import shutil import pathlib import textwrap import datasets import itertools import urllib.request import pandas as pd import typing as tp from pathlib import Path from copy import deepcopy from tqdm.auto import tqdm from ._fsd2019 import CLASSES VERSION = "0.0.1" SAMPLE_RATE = 44_100 _TRAIN_CURATED_URL = "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_train_curated.zip" _TRAIN_NOISY_URLS = [ "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_train_noisy.z01", "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_train_noisy.z02", "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_train_noisy.z03", "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_train_noisy.z04", "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_train_noisy.z05", "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_train_noisy.z06", "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_train_noisy.zip" ] _TEST_URL = "https://zenodo.org/records/3612637/files/FSDKaggle2019.audio_test.zip" _METADATA_URL = "https://zenodo.org/records/3612637/files/FSDKaggle2019.meta.zip" # Cache location DEFAULT_XDG_CACHE_HOME = "~/.cache" XDG_CACHE_HOME = os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME) DEFAULT_HF_CACHE_HOME = os.path.join(XDG_CACHE_HOME, "huggingface") HF_CACHE_HOME = os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME)) DEFAULT_HF_DATASETS_CACHE = os.path.join(HF_CACHE_HOME, "datasets") HF_DATASETS_CACHE = Path(os.getenv("HF_DATASETS_CACHE", DEFAULT_HF_DATASETS_CACHE)) class FSDKaggle2019Config(datasets.BuilderConfig): """BuilderConfig for FSDKaggle2019.""" def __init__(self, features, **kwargs): super(FSDKaggle2019Config, self).__init__(version=datasets.Version(VERSION, ""), **kwargs) self.features = features class FSDKaggle2019(datasets.GeneratorBasedBuilder): BUILDER_CONFIGS = [ FSDKaggle2019Config( features=datasets.Features( { "file": datasets.Value("string"), "audio": datasets.Audio(sampling_rate=SAMPLE_RATE), "sound": datasets.Sequence(datasets.Value("string")), "label": datasets.Sequence(datasets.features.ClassLabel(names=CLASSES)), } ), name="curated", description="", ), FSDKaggle2019Config( features=datasets.Features( { "file": datasets.Value("string"), "audio": datasets.Audio(sampling_rate=SAMPLE_RATE), "sound": datasets.Sequence(datasets.Value("string")), "label": datasets.Sequence(datasets.features.ClassLabel(names=CLASSES)), } ), name="noisy", description="", ), ] def _info(self): return datasets.DatasetInfo( description="Database can be downloaded from https://zenodo.org/records/3612637", features=self.config.features, supervised_keys=None, homepage="", citation="", task_templates=None, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" if self.config.name == 'curated': train_archive_path = dl_manager.download_and_extract(_TRAIN_CURATED_URL) elif self.config.name == 'noisy': for zip_file_url in _TRAIN_NOISY_URLS: name = zip_file_url.split("/")[-1] download_file( zip_file_url, os.path.join(HF_DATASETS_CACHE, 'confit___fsdkaggle2019/noisy', VERSION, name) ) _input_file = os.path.join(HF_DATASETS_CACHE, 'confit___fsdkaggle2019/noisy', VERSION, 'FSDKaggle2019.audio_train_noisy.zip') _output_file = os.path.join(HF_DATASETS_CACHE, 'confit___fsdkaggle2019/noisy', VERSION, 'FSDKaggle2019.audio_train_noisy.combine.zip') if not os.path.exists(_output_file): os.system(f"zip -q -F {_input_file} --out {_output_file}") train_archive_path = dl_manager.extract(_output_file) test_archive_path = dl_manager.download_and_extract(_TEST_URL) metadata_archive_path = dl_manager.download_and_extract(_METADATA_URL) extensions = ['.wav'] _, train_walker = fast_scandir(train_archive_path, extensions, recursive=True) _, test_walker = fast_scandir(test_archive_path, extensions, recursive=True) if self.config.name == 'curated': train_df = pd.read_csv(os.path.join(metadata_archive_path, "FSDKaggle2019.meta", "train_curated_post_competition.csv")) elif self.config.name == 'noisy': train_df = pd.read_csv(os.path.join(metadata_archive_path, "FSDKaggle2019.meta", "train_noisy_post_competition.csv")) test_df = pd.read_csv(os.path.join(metadata_archive_path, "FSDKaggle2019.meta", "test_post_competition.csv")) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"audio_paths": train_walker, "split": "train", "metadata": train_df} ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"audio_paths": test_walker, "split": "test", "metadata": test_df} ), ] def _generate_examples(self, audio_paths, split=None, metadata=None): metadata_df = deepcopy(metadata) def default_find_classes(audio_path): fileid = Path(audio_path).name ids = metadata_df.query(f'fname=="{fileid}"')['labels'].values.tolist() ids = str(ids[0]).split(',') # assert False, f"{ids}" return ids for guid, audio_path in enumerate(audio_paths): yield guid, { "id": str(guid), "file": audio_path, "audio": audio_path, "sound": default_find_classes(audio_path), "label": default_find_classes(audio_path), } def fast_scandir(path: str, exts: tp.List[str], recursive: bool = False): # Scan files recursively faster than glob # From github.com/drscotthawley/aeiou/blob/main/aeiou/core.py subfolders, files = [], [] try: # hope to avoid 'permission denied' by this try for f in os.scandir(path): try: # 'hope to avoid too many levels of symbolic links' error if f.is_dir(): subfolders.append(f.path) elif f.is_file(): if os.path.splitext(f.name)[1].lower() in exts: files.append(f.path) except Exception: pass except Exception: pass if recursive: for path in list(subfolders): sf, f = fast_scandir(path, exts, recursive=recursive) subfolders.extend(sf) files.extend(f) # type: ignore return subfolders, files def download_file( source, dest, unpack=False, dest_unpack=None, replace_existing=False, write_permissions=False, ): """Downloads the file from the given source and saves it in the given destination path. Arguments --------- source : path or url Path of the source file. If the source is an URL, it downloads it from the web. dest : path Destination path. unpack : bool If True, it unpacks the data in the dest folder. dest_unpack: path Path where to store the unpacked dataset replace_existing : bool If True, replaces the existing files. write_permissions: bool When set to True, all the files in the dest_unpack directory will be granted write permissions. This option is active only when unpack=True. """ class DownloadProgressBar(tqdm): """DownloadProgressBar class.""" def update_to(self, b=1, bsize=1, tsize=None): """Needed to support multigpu training.""" if tsize is not None: self.total = tsize self.update(b * bsize - self.n) # Create the destination directory if it doesn't exist dest_dir = pathlib.Path(dest).resolve().parent dest_dir.mkdir(parents=True, exist_ok=True) if "http" not in source: shutil.copyfile(source, dest) elif not os.path.isfile(dest) or ( os.path.isfile(dest) and replace_existing ): print(f"Downloading {source} to {dest}") with DownloadProgressBar( unit="B", unit_scale=True, miniters=1, desc=source.split("/")[-1], ) as t: urllib.request.urlretrieve( source, filename=dest, reporthook=t.update_to ) else: print(f"{dest} exists. Skipping download") # Unpack if necessary if unpack: if dest_unpack is None: dest_unpack = os.path.dirname(dest) print(f"Extracting {dest} to {dest_unpack}") # shutil unpack_archive does not work with tar.gz files if ( source.endswith(".tar.gz") or source.endswith(".tgz") or source.endswith(".gz") ): out = dest.replace(".gz", "") with gzip.open(dest, "rb") as f_in: with open(out, "wb") as f_out: shutil.copyfileobj(f_in, f_out) else: shutil.unpack_archive(dest, dest_unpack) if write_permissions: set_writing_permissions(dest_unpack) def set_writing_permissions(folder_path): """ This function sets user writing permissions to all the files in the given folder. Arguments --------- folder_path : folder Folder whose files will be granted write permissions. """ for root, dirs, files in os.walk(folder_path): for file_name in files: file_path = os.path.join(root, file_name) # Set writing permissions (mode 0o666) to the file os.chmod(file_path, 0o666)