File size: 6,783 Bytes
195efb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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