gtzan-script / gtzan-script.py
yangwang825's picture
Rename gtzan.py to gtzan-script.py
9d79369 verified
# coding=utf-8
"""GTZAN music genres classification dataset."""
import os
import textwrap
import datasets
import itertools
import typing as tp
from pathlib import Path
from ._gtzan import FILTERED_TRAIN, FILTERED_VALID, FILTERED_TEST, GTZAN_GENRES
FOLDER_IN_ARCHIVE = "genres"
SAMPLE_RATE = 22_050
_COMPRESSED_FILENAME = 'archive.zip'
class GtzanConfig(datasets.BuilderConfig):
"""BuilderConfig for GTZAN."""
def __init__(self, features, **kwargs):
super(GtzanConfig, self).__init__(version=datasets.Version("0.0.1", ""), **kwargs)
self.features = features
class GTZAN(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
GtzanConfig(
features=datasets.Features(
{
"file": datasets.Value("string"),
"audio": datasets.Audio(sampling_rate=SAMPLE_RATE),
"genre": datasets.Value("string"),
"label": datasets.ClassLabel(names=GTZAN_GENRES),
}
),
name="gtzan",
description=textwrap.dedent(
"""\
Music Genres classifies each audio for its music genre as a multi-class
classification, where music are in the same pre-defined set for both training and testing.
The evaluation metric is accuracy (ACC).
"""
),
),
]
def _info(self):
return datasets.DatasetInfo(
description="",
features=self.config.features,
supervised_keys=None,
homepage="",
citation="",
task_templates=None,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
archive_path = dl_manager.extract(_COMPRESSED_FILENAME)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN, gen_kwargs={"archive_path": archive_path, "split": "train"}
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION, gen_kwargs={"archive_path": archive_path, "split": "validation"}
),
datasets.SplitGenerator(
name=datasets.Split.TEST, gen_kwargs={"archive_path": archive_path, "split": "test"}
),
]
def _generate_examples(self, archive_path, split=None):
extensions = ['.au']
_, _walker = fast_scandir(archive_path, extensions, recursive=True)
if split == 'train':
_walker = [fileid for fileid in _walker if Path(fileid).stem in FILTERED_TRAIN]
elif split == 'validation':
_walker = [fileid for fileid in _walker if Path(fileid).stem in FILTERED_VALID]
elif split == 'test':
_walker = [fileid for fileid in _walker if Path(fileid).stem in FILTERED_TEST]
for guid, audio_path in enumerate(_walker):
yield guid, {
"id": str(guid),
"file": audio_path,
"audio": audio_path,
"genre": Path(audio_path).parent.stem,
"label": Path(audio_path).parent.stem,
}
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