import os import random import hashlib import datasets import pandas as pd from datasets.tasks import AudioClassification _SYSTEM_TONIC = [ "C", "#C/bD", "D", "#D/bE", "E", "F", "#F/bG", "G", "#G/bA", "A", "#A/bB", "B", ] _PATTERN = [ "Gong", "Shang", "Jue", "Zhi", "Yu", ] _TYPE = [ "Pentatonic", "Hexatonic_Qingjue", "Hexatonic_Biangong", "Heptatonic_Yayue", "Heptatonic_Qingyue", "Heptatonic_Yanyue", ] _DBNAME = os.path.basename(__file__).split(".")[0] _DOMAIN = f"https://www.modelscope.cn/api/v1/datasets/ccmusic-database/{_DBNAME}/repo?Revision=master&FilePath=data" _HOMEPAGE = f"https://www.modelscope.cn/datasets/ccmusic-database/{_DBNAME}" _CITATION = """\ @dataset{zhaorui_liu_2021_5676893, author = {Monan Zhou, Shenyang Xu, Zhaorui Liu, Zhaowen Wang, Feng Yu, Wei Li and Baoqiang Han}, title = {CCMusic: an Open and Diverse Database for Chinese and General Music Information Retrieval Research}, month = {mar}, year = {2024}, publisher = {HuggingFace}, version = {1.2}, url = {https://huggingface.co/ccmusic-database} } """ _DESCRIPTION = """\ Musical pieces collected are mostly composed in pentatonic (five-note) scales, with some of them being hexatonic (six-note) and heptatonic (seven-note) scales. The total recording number is 287 with the average duration being 179.5 s. The expanded dataset is integrated into our database, and each data entry consists of seven columns: the first column denotes the audio recording in .wav format, sampled at 44,100 Hz. The second and third presents the name of the piece and artist. The subsequent columns represent the system, tonic, pattern, and type of the musical piece, respectively. The eighth column contains an additional Chinese name of the mode, while the final column indicates the duration of the audio in seconds. This dataset is applicable for tasks related to Chinese traditional pentatonic mode or computational ethnomusicology research related to Chinese music mode. """ _URLS = { "audio": f"{_DOMAIN}/audio.zip", "mel": f"{_DOMAIN}/mel.zip", "label": f"{_DOMAIN}/label.csv", } class CNPM(datasets.GeneratorBasedBuilder): def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { "audio": datasets.Audio(sampling_rate=22050), "mel": datasets.Image(), "title": datasets.Value("string"), "artist": datasets.Value("string"), "system": datasets.features.ClassLabel(names=_SYSTEM_TONIC), "tonic": datasets.features.ClassLabel(names=_SYSTEM_TONIC), "pattern": datasets.features.ClassLabel(names=_PATTERN), "type": datasets.features.ClassLabel(names=_TYPE), "mode_name": datasets.Value("string"), "length": datasets.Value("string"), } ), supervised_keys=("audio", "type"), homepage=_HOMEPAGE, license="CC-BY-NC-ND", version="1.2.0", citation=_CITATION, task_templates=[ AudioClassification( task="audio-classification", audio_column="audio", label_column="type", ) ], ) def _str2md5(self, original_string: str): md5_obj = hashlib.md5() md5_obj.update(original_string.encode("utf-8")) return md5_obj.hexdigest() def _val_of_key(self, labels: pd.DataFrame, key: str, col: str): try: return labels.loc[key][col] except KeyError: return "" def _split_generators(self, dl_manager): audio_files = dl_manager.download_and_extract(_URLS["audio"]) mel_files = dl_manager.download_and_extract(_URLS["mel"]) label_file = dl_manager.download(_URLS["label"]) labels = pd.read_csv(label_file, index_col="文件名/File Name", encoding="gbk") files = {} for fpath in dl_manager.iter_files([audio_files]): fname: str = os.path.basename(fpath) if fname.endswith(".wav") or fname.endswith(".mp3"): song_id = self._str2md5(fname.split(".")[0]) files[song_id] = {"audio": fpath} for fpath in dl_manager.iter_files([mel_files]): fname = os.path.basename(fpath) if fname.endswith(".jpg"): song_id = self._str2md5(fname.split(".")[0]) files[song_id]["mel"] = fpath dataset = [] for path in files.values(): fname = os.path.basename(path["audio"]) dataset.append( { "audio": path["audio"], "mel": path["mel"], "title": self._val_of_key(labels, fname, "曲名/Title"), "artist": self._val_of_key(labels, fname, "演奏者/Artist"), "system": _SYSTEM_TONIC[ int(self._val_of_key(labels, fname, "同宫系统/System")) ], "tonic": _SYSTEM_TONIC[ int(self._val_of_key(labels, fname, "主音音名/Tonic")) ], "pattern": _PATTERN[ int(self._val_of_key(labels, fname, "样式/Pattern")) ], "type": _TYPE[int(self._val_of_key(labels, fname, "种类/Type"))], "mode_name": self._val_of_key(labels, fname, "调式全称/Mode Name"), "length": self._val_of_key(labels, fname, "时长/Length"), } ) random.shuffle(dataset) data_count = len(dataset) p80 = int(data_count * 0.8) p90 = int(data_count * 0.9) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"files": dataset[:p80]}, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={"files": dataset[p80:p90]}, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"files": dataset[p90:]}, ), ] def _generate_examples(self, files): for i, path in enumerate(files): yield i, path