magnatagatune / magnatagatune.py
yangwang825's picture
Update magnatagatune.py
6941c43 verified
raw
history blame
12.3 kB
# coding=utf-8
"""MagnaTagATune dataset."""
import os
import json
import gzip
import shutil
import pathlib
import logging
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
logger = logging.getLogger(__name__)
logger.addHandler(RichHandler())
logger.setLevel(logging.INFO)
SAMPLE_RATE = 16_000
# 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))
TOP_50_CLASSES = [
'ambient', 'beat', 'beats', 'cello', 'choir', 'choral', 'classic', 'classical', 'country', 'dance',
'drums', 'electronic', 'fast', 'female', 'female vocal', 'female voice', 'flute', 'guitar', 'harp', 'harpsichord',
'indian', 'loud', 'male', 'male vocal', 'male voice', 'man', 'metal', 'new age', 'no vocal', 'no vocals',
'no voice', 'opera', 'piano', 'pop', 'quiet', 'rock', 'singing', 'sitar', 'slow', 'soft',
'solo', 'strings', 'synth', 'techno', 'violin', 'vocal', 'vocals', 'voice', 'weird', 'woman'
]
CLASS2INDEX = {cls:idx for idx, cls in enumerate(TOP_50_CLASSES)}
INDEX2CLASS = {idx:cls for idx, cls in enumerate(TOP_50_CLASSES)}
class MagnaTagATuneConfig(datasets.BuilderConfig):
"""BuilderConfig for MagnaTagATune."""
def __init__(self, features, **kwargs):
super(MagnaTagATuneConfig, self).__init__(version=datasets.Version(VERSION, ""), **kwargs)
self.features = features
class MagnaTagATune(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
MagnaTagATuneConfig(
features=datasets.Features(
{
"file": datasets.Value("string"),
"audio": datasets.Audio(sampling_rate=SAMPLE_RATE),
"tags": datasets.Sequence(datasets.Value("string")),
"label": datasets.Sequence(datasets.features.ClassLabel(names=TOP_50_CLASSES)),
}
),
name="top50",
description="",
),
]
DEFAULT_CONFIG_NAME = "top50"
def _info(self):
return datasets.DatasetInfo(
description="",
features=self.config.features,
supervised_keys=None,
homepage="",
citation="",
task_templates=None,
)
def _load_metadata(self):
# Read metadata
df = pd.read_csv("https://mirg.city.ac.uk/datasets/magnatagatune/annotations_final.csv", sep="\t")
df = df[df[TOP_50_CLASSES].sum(axis=1) > 0]
df = df[TOP_50_CLASSES + ["mp3_path", "clip_id"]]
train_ids_df = pd.read_csv(
'https://raw.githubusercontent.com/jordipons/musicnn-training/master/data/index/mtt/train_gt_mtt.tsv',
sep='\t', header=None
)
train_ids = train_ids_df[0].tolist()
train_df = df[df["clip_id"].isin(train_ids)]
validation_ids_df = pd.read_csv(
"https://raw.githubusercontent.com/jordipons/musicnn-training/master/data/index/mtt/val_gt_mtt.tsv",
sep="\t", header=None
)
validation_ids = validation_ids_df[0].tolist()
validation_df = df[df["clip_id"].isin(validation_ids)]
test_ids_df = pd.read_csv(
"https://raw.githubusercontent.com/jordipons/musicnn-training/master/data/index/mtt/test_gt_mtt.tsv",
sep="\t", header=None
)
test_ids = test_ids_df[0].tolist()
test_df = df[df["clip_id"].isin(test_ids)]
label_names = df.columns
label_names = label_names.drop(["mp3_path", "clip_id"])
return train_df, validation_df, test_df, label_names
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
if self.config.name == 'top50':
mp3_zip_files = [
'https://mirg.city.ac.uk/datasets/magnatagatune/mp3.zip.001',
'https://mirg.city.ac.uk/datasets/magnatagatune/mp3.zip.002',
'https://mirg.city.ac.uk/datasets/magnatagatune/mp3.zip.003',
]
for zip_file_url in mp3_zip_files:
_filename = zip_file_url.split('/')[-1]
_save_path = os.path.join(
HF_DATASETS_CACHE, 'confit___magnatagatune/top50', VERSION, _filename
)
download_file(zip_file_url, _save_path)
logger.info(f"`{_filename}` is downloaded to {_save_path}")
main_zip_filename = 'mp3.zip'
_save_dir = os.path.join(HF_DATASETS_CACHE, 'confit___magnatagatune/top50', VERSION)
_output_file = os.path.join(_save_dir, main_zip_filename)
if not os.path.exists(_output_file):
logger.info(f"Concatenate zip files to {main_zip_filename}")
os.system(f"cat {os.path.join(_save_dir, 'mp3.zip.*')} > {_output_file}")
archive_path = dl_manager.extract(_output_file)
logger.info(f"`{main_zip_filename}` is now extracted to {archive_path}")
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, metadata_df=None):
train_df, validation_df, test_df, label_names = self._load_metadata()
extensions = ['.mp3']
_, _walker = fast_scandir(archive_path, extensions, recursive=True)
class2index = {cls:idx for idx, cls in enumerate(label_names)}
index2class = {idx:cls for idx, cls in enumerate(label_names)}
if split == 'train':
fileid2class = {}
for idx, row in train_df.iterrows():
fileid = row['mp3_path']
class_ = row[label_names].tolist()
if sum(class_) == 0:
continue
class_ = [idx for idx, val in enumerate(class_) if val != 0]
class_ = [index2class.get(idx) for idx in class_]
fileid2class[fileid] = class_
elif split == 'validation':
fileid2class = {}
for idx, row in validation_df.iterrows():
fileid = row['mp3_path']
class_ = row[label_names].tolist()
if sum(class_) == 0:
continue
class_ = [idx for idx, val in enumerate(class_) if val != 0]
class_ = [index2class.get(idx) for idx in class_]
fileid2class[fileid] = class_
elif split == 'test':
fileid2class = {}
for idx, row in test_df.iterrows():
fileid = row['mp3_path']
class_ = row[label_names].tolist()
if sum(class_) == 0:
continue
class_ = [idx for idx, val in enumerate(class_) if val != 0]
class_ = [index2class.get(idx) for idx in class_]
fileid2class[fileid] = class_
for guid, audio_path in enumerate(_walker):
parent = Path(audio_path).parent.stem
filename = Path(audio_path).name
fileid = f"{parent}/{filename}"
if fileid not in fileid2class:
continue
tags = fileid2class.get(fileid)
yield guid, {
"id": str(guid),
"file": audio_path,
"audio": audio_path,
"tags": tags,
"label": tags,
}
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
):
print(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:
print(f"{dest} exists. Skipping download")
# Unpack if necessary
if unpack:
if dest_unpack is None:
dest_unpack = os.path.dirname(dest)
print(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 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)