import os import datasets import typing as tp from pathlib import Path SAMPLE_RATE = 44_100 EXTENSION = '.wav' ESC50_LABELS = [ "airplane", "breathing", "brushing_teeth", "can_opening", "car_horn", "cat", "chainsaw", "chirping_birds", "church_bells", "clapping", "clock_alarm", "clock_tick", "coughing", "cow", "crackling_fire", "crickets", "crow", "crying_baby", "dog", "door_wood_creaks", "door_wood_knock", "drinking_sipping", "engine", "fireworks", "footsteps", "frog", "glass_breaking", "hand_saw", "helicopter", "hen", "insects", "keyboard_typing", "laughing", "mouse_click", "pig", "pouring_water", "rain", "rooster", "sea_waves", "sheep", "siren", "sneezing", "snoring", "thunderstorm", "toilet_flush", "train", "vacuum_cleaner", "washing_machine", "water_drops", "wind", ] ESC50_LABEL2ID = { "dog": 0, "rooster": 1, "pig": 2, "cow": 3, "frog": 4, "cat": 5, "hen": 6, "insects": 7, "sheep": 8, "crow": 9, "rain": 10, "sea_waves": 11, "crackling_fire": 12, "crickets": 13, "chirping_birds": 14, "water_drops": 15, "wind": 16, "pouring_water": 17, "toilet_flush": 18, "thunderstorm": 19, "crying_baby": 20, "sneezing": 21, "clapping": 22, "breathing": 23, "coughing": 24, "footsteps": 25, "laughing": 26, "brushing_teeth": 27, "snoring": 28, "drinking_sipping": 29, "door_wood_knock": 30, "mouse_click": 31, "keyboard_typing": 32, "door_wood_creaks": 33, "can_opening": 34, "washing_machine": 35, "vacuum_cleaner": 36, "clock_alarm": 37, "clock_tick": 38, "glass_breaking": 39, "helicopter": 40, "chainsaw": 41, "siren": 42, "car_horn": 43, "engine": 44, "train": 45, "church_bells": 46, "airplane": 47, "fireworks": 48, "hand_saw": 49 } ESC50_ID2LABEL = {v:k for k, v in ESC50_LABEL2ID.items()} class Esc50Config(datasets.BuilderConfig): """BuilderConfig for ESC50.""" def __init__(self, features, **kwargs): super(Esc50Config, self).__init__(version=datasets.Version("0.0.1", ""), **kwargs) self.features = features class ESC50(datasets.GeneratorBasedBuilder): """ The ESC50 dataset """ BUILDER_CONFIGS = [ Esc50Config( features=datasets.Features( { "file": datasets.Value("string"), "audio": datasets.Audio(sampling_rate=SAMPLE_RATE), "sound": datasets.Value("string"), "label": datasets.ClassLabel(names=ESC50_LABELS), } ), name=f"fold{f}", description='', ) for f in range(1, 6) ] def _info(self): return datasets.DatasetInfo( description='Environmental sound classification dataset', features=self.config.features, ) def _split_generators(self, dl_manager): data_dir = dl_manager.download_and_extract("ESC-50-master.zip") return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "data_dir": data_dir, "split": 'train' }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "data_dir": data_dir, "split": 'test' }, ), ] def _generate_examples(self, data_dir, split): _, _walker = fast_scandir(data_dir, [EXTENSION], recursive=True) for idx, fileid in enumerate(_walker): fold = default_find_fold(fileid) test_fold = self.config.name train_fold = [f'fold{f}' for f in range(1, 11)] train_fold.remove(test_fold) if split == 'train' and f'fold{fold}' in train_fold: yield idx, { 'file': fileid, 'audio': fileid, 'sound': default_find_classes(fileid), 'label': default_find_classes(fileid) } elif split == 'test' and f'fold{fold}' in test_fold: yield idx, { 'file': fileid, 'audio': fileid, 'sound': default_find_classes(fileid), 'label': default_find_classes(fileid) } def default_find_classes(audio_path): id_ = Path(audio_path).stem.split('-')[-1] return ESC50_ID2LABEL.get(int(id_)) def default_find_fold(audio_path): fold = Path(audio_path).stem.split('-')[0] return int(fold) 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