# coding=utf-8 """AudioSet sound event classification dataset.""" import os import json import gzip import joblib import shutil import pathlib import logging import zipfile import textwrap import datasets import itertools import typing as tp import pandas as pd import urllib.request from pathlib import Path from copy import deepcopy from tqdm.auto import tqdm from rich.logging import RichHandler from huggingface_hub import hf_hub_download from ._audioset import ID2LABEL logger = logging.getLogger(__name__) logger.addHandler(RichHandler()) logger.setLevel(logging.INFO) SAMPLE_RATE = 32_000 _HOMEPAGE = "https://huggingface.co/datasets/confit/audioset" _BALANCED_TRAIN_FILENAME = 'balanced/balanced_train_segments.zip' _EVAL_FILENAME = 'eval/eval_segments.zip' # ID2LABEL = json.load( # open(hf_hub_download("huggingface/label-files", "audioset-id2label.json", repo_type="dataset"), "r") # ) LABEL2ID = {v:k for k, v in ID2LABEL.items()} CLASSES = list(ID2LABEL.values()) # Cache location VERSION = "0.0.1" 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 AudioSetConfig(datasets.BuilderConfig): """BuilderConfig for AudioSet.""" def __init__(self, features, **kwargs): super(AudioSetConfig, self).__init__(version=datasets.Version("0.0.1", ""), **kwargs) self.features = features class AudioSet(datasets.GeneratorBasedBuilder): BUILDER_CONFIGS = [ AudioSetConfig( 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="balanced", description="", ), ] + [ AudioSetConfig( 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=f"unbalanced-part{i:02d}", description="", ) for i in range(40+1) ] DEFAULT_CONFIG_NAME = "balanced" def _info(self): return datasets.DatasetInfo( description="", features=self.config.features, supervised_keys=None, homepage="", citation="", task_templates=None, ) def _preprocess_metadata_csv(self, csv_file): df = pd.read_csv(csv_file, skiprows=2, sep=', ', engine='python') df.rename(columns={'positive_labels': 'ids'}, inplace=True) df['ids'] = [label.strip('\"').split(',') for label in df['ids']] df['filename'] = ( 'Y' + df['# YTID'] + '.wav' ) return df[['filename', 'ids']] def _split_generators(self, dl_manager): """Returns SplitGenerators.""" if self.config.name == 'balanced': train_archive_path = dl_manager.download_and_extract( f'https://huggingface.co/datasets/confit/audioset/resolve/main/{_BALANCED_TRAIN_FILENAME}' ) logger.info(f"`{_BALANCED_TRAIN_FILENAME}` is downloaded to {train_archive_path}") elif str(self.config.name).startswith('unbalanced-part'): partxx = str(self.config.name).split('-')[-1] main_zip_filename = f'unbalanced_train_segments_{partxx}_partial.zip' concat_zip_filename = f'unbalanced_train_segments_{partxx}_full.zip' _input_file = os.path.join(HF_DATASETS_CACHE, 'confit___audioset/unbalanced', VERSION, main_zip_filename) _output_file = os.path.join(HF_DATASETS_CACHE, 'confit___audioset/unbalanced', VERSION, concat_zip_filename) if not os.path.exists(_output_file): def _download(zip_type): _UNBALANCED_TRAIN_FILENAME = f'unbalanced_train_segments_{partxx}_partial.{zip_type}' zip_file_url = f'https://huggingface.co/datasets/confit/audioset/resolve/main/unbalanced/{_UNBALANCED_TRAIN_FILENAME}' _save_path = os.path.join( HF_DATASETS_CACHE, 'confit___audioset/unbalanced', VERSION ) download_file( source=zip_file_url, dest=os.path.join(_save_path, _UNBALANCED_TRAIN_FILENAME) ) logger.info(f"`{_UNBALANCED_TRAIN_FILENAME}` is downloaded to {_save_path}") joblib.Parallel(n_jobs=4, verbose=10)( joblib.delayed(_download)( zip_type=zip_type ) for zip_type in ['zip', 'z01', 'z02'] ) logger.info(f"Reassembling {_output_file}") os.system(f"zip -q -F {_input_file} --out {_output_file}") part_zip_files = os.path.join( HF_DATASETS_CACHE, 'confit___audioset/unbalanced', VERSION, f'unbalanced_train_segments_{partxx}_partial.*' ) os.system(f"rm -rf {part_zip_files}") train_archive_path = os.path.join( HF_DATASETS_CACHE, 'confit___audioset/unbalanced', VERSION, 'extracted' ) unzip_file(zip_path=_output_file, extract_to=train_archive_path) logger.info(f"`{concat_zip_filename}` is extracted to {train_archive_path}") zip_file_url = f'https://huggingface.co/datasets/confit/audioset/resolve/main/{_EVAL_FILENAME}' _eval_save_path = os.path.join( HF_DATASETS_CACHE, 'confit___audioset/eval', VERSION ) download_file( source=zip_file_url, dest=os.path.join(_eval_save_path, _EVAL_FILENAME), unpack=True, dest_unpack=os.path.join(_eval_save_path, 'extracted', 'eval'), ) test_archive_path = os.path.join(_eval_save_path, 'extracted', 'eval') logger.info(f"`eval_segments.zip` is extracted to {test_archive_path}") return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"archive_path": train_archive_path, "split": "train"} ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"archive_path": test_archive_path, "split": "test"} ), ] def _generate_examples(self, archive_path, split=None): extensions = ['.wav'] if split == 'train': if self.config.name == 'balanced': train_metadata_csv = f"{_HOMEPAGE}/resolve/main/metadata/balanced_train_segments.csv" elif str(self.config.name).startswith('unbalanced-part'): train_metadata_csv = f"{_HOMEPAGE}/resolve/main/metadata/unbalanced_train_segments.csv" metadata_df = self._preprocess_metadata_csv(train_metadata_csv) # ['filename', 'ids'] elif split == 'test': test_metadata_csv = f"{_HOMEPAGE}/resolve/main/metadata/eval_segments.csv" metadata_df = self._preprocess_metadata_csv(test_metadata_csv) # ['filename', 'ids'] class_labels_indices_df = pd.read_csv( f"{_HOMEPAGE}/resolve/main/metadata/class_labels_indices.csv" ) # ['index', 'mid', 'display_name'] mid2label = { row['mid']:row['display_name'] for idx, row in class_labels_indices_df.iterrows() } def default_find_classes(audio_path): fileid = Path(audio_path).name ids = metadata_df.query(f'filename=="{fileid}"')['ids'].values.tolist() ids = [ mid2label.get(mid, None) for mid in flatten(ids) ] return ids _, _walker = fast_scandir(archive_path, extensions, recursive=True) bad_zip_files = [ 'YZu5HOzXcX7k.wav', 'YmW3S0u8bj58.wav' ] for guid, audio_path in enumerate(_walker): if Path(audio_path).name in bad_zip_files: continue try: yield guid, { "id": str(guid), "file": audio_path, "audio": audio_path, "sound": default_find_classes(audio_path), "label": default_find_classes(audio_path), } except: continue def flatten(list2d): return list(itertools.chain.from_iterable(list2d)) 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 ): logger.info(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: logger.info(f"{dest} exists. Skipping download") # Unpack if necessary if unpack: if dest_unpack is None: dest_unpack = os.path.dirname(dest) if os.path.exists(dest_unpack): logger.info(f"{dest_unpack} already exists. Skipping extraction") else: logger.info(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 unzip_file(zip_path, extract_to): """ Unzips a given zip file to a specified directory. Parameters: zip_path (str): The path to the zip file. extract_to (str): The directory to extract the files to. """ if os.path.exists(extract_to): logger.info(f"{extract_to} already exists. Skipping extraction") if not os.path.exists(zip_path): raise FileNotFoundError(f"The file {zip_path} does not exist.") if not os.path.exists(extract_to): os.makedirs(extract_to) with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(extract_to) logger.info(f"Extracted {zip_path} to {extract_to}") 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)