File size: 5,279 Bytes
abafa99
d9324d8
abafa99
 
 
 
ce1dcb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36996c5
 
 
 
ce1dcb7
 
 
 
 
 
 
36996c5
ce1dcb7
 
 
 
 
abafa99
36996c5
d9324d8
36996c5
abafa99
 
 
36ba2bb
ce1dcb7
 
 
abafa99
 
 
 
 
 
 
 
901bfee
abafa99
 
d9324d8
abafa99
 
 
 
 
ce1dcb7
84b0e54
 
ce1dcb7
 
 
abafa99
 
ce1dcb7
abafa99
 
 
 
 
 
 
ce1dcb7
 
abafa99
 
 
 
6244213
 
 
 
36996c5
6244213
901bfee
6244213
abafa99
6244213
84b0e54
 
 
 
4bbafbb
84b0e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abafa99
6860b71
1bf45da
6860b71
1bf45da
b925a79
1bf45da
 
b925a79
1bf45da
6860b71
d0813bd
7d231ae
 
6860b71
47b3773
6860b71
36996c5
6860b71
84b0e54
dd8113e
480b3e4
84b0e54
 
 
 
 
 
480b3e4
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
import os
import socket
import random
import datasets
from datasets.tasks import ImageClassification

_NAMES_1 = {
    1: "Classic",
    2: "Non_classic"
}

_NAMES_2 = {
    3: "Symphony",
    4: "Opera",
    5: "Solo",
    6: "Chamber",
    7: "Pop",
    8: "Dance_and_house",
    9: "Indie",
    10: "Soul_or_r_and_b",
    11: "Rock"
}

_NAMES_3 = {
    3: "Symphony",
    4: "Opera",
    5: "Solo",
    6: "Chamber",
    12: "Pop_vocal_ballad",
    13: "Adult_contemporary",
    14: "Teen_pop",
    15: "Contemporary_dance_pop",
    16: "Dance_pop",
    17: "Classic_indie_pop",
    18: "Chamber_cabaret_and_art_pop",
    10: "Soul_or_r_and_b",
    19: "Adult_alternative_rock",
    20: "Uplifting_anthemic_rock",
    21: "Soft_rock",
    22: "Acoustic_pop"
}

_DBNAME = os.path.basename(__file__).split('.')[0]

_HOMEPAGE = f"https://huggingface.co/datasets/ccmusic-database/{_DBNAME}"

_CITATION = """\
@dataset{zhaorui_liu_2021_5676893,
  author       = {Zhaorui Liu, Monan Zhou, Shenyang Xu, Yuan Wang, Zhaowen Wang, Wei Li and Zijin Li},
  title        = {CCMUSIC DATABASE: A Music Data Sharing Platform for Computational Musicology Research},
  month        = {nov},
  year         = {2021},
  publisher    = {Zenodo},
  version      = {1.1},
  doi          = {10.5281/zenodo.5676893},
  url          = {https://doi.org/10.5281/zenodo.5676893}
}
"""

_DESCRIPTION = """\
This database contains about 1700 musical pieces (.mp3 format) with lengths of 270-300s that are divided into 17 genres in total. 
"""


class music_genre(datasets.GeneratorBasedBuilder):
    def _info(self):
        return datasets.DatasetInfo(
            features=datasets.Features(
                {
                    "mel": datasets.Image(),
                    "cqt": datasets.Image(),
                    "chroma": datasets.Image(),
                    "fst_level_label": datasets.features.ClassLabel(names=list(_NAMES_1.values())),
                    "sec_level_label": datasets.features.ClassLabel(names=list(_NAMES_2.values())),
                    "thr_level_label": datasets.features.ClassLabel(names=list(_NAMES_3.values()))
                }
            ),
            supervised_keys=("mel", "sec_level_label"),
            homepage=_HOMEPAGE,
            license="mit",
            citation=_CITATION,
            description=_DESCRIPTION,
            task_templates=[
                ImageClassification(
                    task="image-classification",
                    image_column="mel",
                    label_column="sec_level_label",
                )
            ]
        )

    def _cdn_url(self, ip='127.0.0.1', port=80):
        try:
            # easy for local test
            with socket.create_connection((ip, port), timeout=5):
                return f'http://{ip}/{_DBNAME}/data/genre_data.zip'
        except (socket.timeout, socket.error):
            return f"{_HOMEPAGE}/resolve/main/data/genre_data.zip"

    def _split_generators(self, dl_manager):
        data_files = dl_manager.download_and_extract(self._cdn_url())
        files = dl_manager.iter_files([data_files])

        dataset = []
        for path in files:
            if os.path.basename(path).endswith(".jpg") and 'mel' in path:
                dataset.append({
                    'mel': path,
                    'cqt': path.replace('\\mel\\', '\\cqt\\').replace('/mel/', '/cqt/'),
                    'chroma': path.replace('\\mel\\', '\\chroma\\').replace('/mel/', '/chroma/')
                })

        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 _calc_label(self, path, depth, substr='/mel/'):
        spect = substr
        dirpath = os.path.dirname(path)
        substr_index = dirpath.find(spect)
        if substr_index < 0:
            spect = spect.replace('/', '\\')
            substr_index = dirpath.find(spect)

        labstr = dirpath[substr_index + len(spect):]
        labs = labstr.split('/')
        if len(labs) < 2:
            labs = labstr.split('\\')

        if depth <= len(labs):
            return int(labs[depth - 1].split('_')[0])
        else:
            return int(labs[-1].split('_')[0])

    def _generate_examples(self, files):
        for i, path in enumerate(files):
            yield i, {
                "mel": path['mel'],
                "cqt": path['cqt'],
                "chroma": path['chroma'],
                "fst_level_label": _NAMES_1[self._calc_label(path['mel'], 1)],
                "sec_level_label": _NAMES_2[self._calc_label(path['mel'], 2)],
                "thr_level_label": _NAMES_3[self._calc_label(path['mel'], 3)]
            }