import os import random import hashlib import datasets from datasets.tasks import AudioClassification _HOMEPAGE = f"https://www.modelscope.cn/datasets/ccmusic-database/{os.path.basename(__file__)[:-3]}" _DOMAIN = f"{_HOMEPAGE}/resolve/master/data" _NAMES = { "vibrato": ["颤音", "chan4_yin1"], "upward_portamento": ["上滑音", "shang4_hua2_yin1"], "downward_portamento": ["下滑音", "xia4_hua2_yin1"], "returning_portamento": ["回滑音", "hui2_hua2_yin1"], "glissando": ["刮奏, 花指", "gua1_zou4/hua1_zhi3"], "tremolo": ["摇指", "yao2_zhi3"], "harmonics": ["泛音", "fan4_yin1"], "plucks": ["勾, 打, 抹, 托, ...", "gou1/da3/mo3/tuo1/etc"], } _URLS = { "audio": f"{_DOMAIN}/audio.zip", "mel": f"{_DOMAIN}/mel.zip", } class GZ_IsoTech(datasets.GeneratorBasedBuilder): def _info(self): return datasets.DatasetInfo( features=datasets.Features( { "audio": datasets.Audio(sampling_rate=44100), "mel": datasets.Image(), "label": datasets.features.ClassLabel(names=list(_NAMES.keys())), "cname": datasets.Value("string"), "pinyin": datasets.Value("string"), } ), supervised_keys=("audio", "label"), homepage=_HOMEPAGE, license="CC-BY-NC-ND", version="1.2.0", task_templates=[ AudioClassification( task="audio-classification", audio_column="audio", label_column="label", ) ], ) def _str2md5(self, original_string: str): md5_obj = hashlib.md5() md5_obj.update(original_string.encode("utf-8")) return md5_obj.hexdigest() def _split_generators(self, dl_manager): audio_files = dl_manager.download_and_extract(_URLS["audio"]) mel_files = dl_manager.download_and_extract(_URLS["mel"]) train_files, test_files = {}, {} for path in dl_manager.iter_files([audio_files]): fname: str = os.path.basename(path) dirname = os.path.dirname(path) splt = os.path.basename(os.path.dirname(dirname)) if fname.endswith(".wav"): cls = f"{splt}/{os.path.basename(dirname)}/" item_id = self._str2md5(cls + fname.split(".wa")[0]) if splt == "train": train_files[item_id] = {"audio": path} else: test_files[item_id] = {"audio": path} for path in dl_manager.iter_files([mel_files]): fname = os.path.basename(path) dirname = os.path.dirname(path) splt = os.path.basename(os.path.dirname(dirname)) if fname.endswith(".jpg"): cls = f"{splt}/{os.path.basename(dirname)}/" item_id = self._str2md5(cls + fname.split(".jp")[0]) if splt == "train": train_files[item_id]["mel"] = path else: test_files[item_id]["mel"] = path trainset = list(train_files.values()) testset = list(test_files.values()) random.shuffle(trainset) random.shuffle(testset) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"files": trainset}, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"files": testset}, ), ] def _generate_examples(self, files): for i, path in enumerate(files): pt = os.path.basename(os.path.dirname(path["audio"])) yield i, { "audio": path["audio"], "mel": path["mel"], "label": pt, "cname": _NAMES[pt][0], "pinyin": _NAMES[pt][1], }