esc50 / esc50.py
yangwang825's picture
Create esc50.py
20e025e
raw
history blame
2.55 kB
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(
{
# "filepath": datasets.Value("string"),
"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, {
# 'filepath': fileid,
'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):
# 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