|
import os |
|
import datasets |
|
import typing as tp |
|
from pathlib import Path |
|
|
|
SAMPLE_RATE = 44_100 |
|
EXTENSION = '.wav' |
|
|
|
|
|
class ESC50(datasets.GeneratorBasedBuilder): |
|
""" |
|
The ESC50 dataset |
|
""" |
|
def _info(self): |
|
return datasets.DatasetInfo( |
|
description='Environmental sound classification dataset', |
|
features=datasets.Features( |
|
{ |
|
|
|
"audio": datasets.Audio(sampling_rate=SAMPLE_RATE), |
|
"label": datasets.ClassLabel(names=GENRES), |
|
} |
|
), |
|
) |
|
|
|
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' |
|
}, |
|
), |
|
] |
|
|
|
def _generate_examples(self, data_dir, split): |
|
_, _walker = fast_scandir(data_dir, [EXTENSION], recursive=True) |
|
|
|
for idx, fileid in enumerate(_walker): |
|
yield idx, { |
|
|
|
'audio': fileid, |
|
'fold': default_find_fold(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): |
|
|
|
|
|
subfolders, files = [], [] |
|
|
|
try: |
|
for f in os.scandir(path): |
|
try: |
|
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) |
|
|
|
return subfolders, files |