File size: 10,390 Bytes
b09dc83 a3b05c5 b09dc83 a3b05c5 b09dc83 a3b05c5 b09dc83 |
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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
import os
import csv
import random
import datasets
import numpy as np
from glob import glob
_NAMES = {
"chanyin": 0,
"dianyin": 6,
"shanghua": 2,
"xiahua": 3,
"huazhi": 4,
"guazou": 4,
"lianmo": 4,
"liantuo": 4,
"yaozhi": 5,
"boxian": 1,
}
_NAME = [
"chanyin", # Vibrato
"boxian", # Plucks
"shanghua", # Upward Portamento
"xiahua", # Downward Portamento
"huazhi/guazou/lianmo/liantuo", # Glissando
"yaozhi", # Tremolo
"dianyin", # Point Note
]
_HOMEPAGE = f"https://www.modelscope.cn/datasets/ccmusic-database/{os.path.basename(__file__)[:-3]}"
_DOMAIN = f"{_HOMEPAGE}/resolve/master/data"
_URLS = {
"audio": f"{_DOMAIN}/audio.zip",
"mel": f"{_DOMAIN}/mel.zip",
"label": f"{_DOMAIN}/label.zip",
}
_TIME_LENGTH = 3 # seconds
_SAMPLE_RATE = 44100
_HOP_LENGTH = 512 # SAMPLE_RATE * ZHEN_LENGTH // 1000
class Guzheng_Tech99(datasets.GeneratorBasedBuilder):
def _info(self):
return datasets.DatasetInfo(
features=(
datasets.Features(
{
"audio": datasets.Audio(sampling_rate=44100),
"mel": datasets.Image(),
"label": datasets.Sequence(
feature={
"onset_time": datasets.Value("float32"),
"offset_time": datasets.Value("float32"),
"IPT": datasets.ClassLabel(num_classes=7, names=_NAME),
"note": datasets.Value("int8"),
}
),
}
)
if self.config.name == "default"
else datasets.Features(
{
"data": datasets.features.Array3D(
dtype="float32", shape=(88, 258, 1)
),
"label": datasets.features.Array2D(
dtype="float32", shape=(7, 258)
),
}
)
),
homepage=_HOMEPAGE,
license="CC-BY-NC-ND",
version="1.2.0",
)
def _RoW_norm(self, data):
common_sum = 0
square_sum = 0
tfle = 0
for i in range(len(data)):
tfle += (data[i].sum(-1).sum(0) != 0).astype("int").sum()
common_sum += data[i].sum(-1).sum(-1)
square_sum += (data[i] ** 2).sum(-1).sum(-1)
common_avg = common_sum / tfle
square_avg = square_sum / tfle
std = np.sqrt(square_avg - common_avg**2)
return common_avg, std
def _norm(self, avg, std, data, size):
avg = np.tile(avg.reshape((1, -1, 1, 1)), (size[0], 1, size[2], size[3]))
std = np.tile(std.reshape((1, -1, 1, 1)), (size[0], 1, size[2], size[3]))
data = (data - avg) / std
return data
def _load(self, wav_dir, csv_dir, groups, avg=None, std=None):
# Return all [(audio address, corresponding to csv file address), ( , ), ...] list
if std is None:
std = np.array([None])
if avg is None:
avg = np.array([None])
def files(wav_dir, csv_dir, group):
flacs = sorted(glob(os.path.join(wav_dir, group, "*.flac")))
if len(flacs) == 0:
flacs = sorted(glob(os.path.join(wav_dir, group, "*.wav")))
csvs = sorted(glob(os.path.join(csv_dir, group, "*.csv")))
files = list(zip(flacs, csvs))
if len(files) == 0:
raise RuntimeError(f"Group {group} is empty")
result = []
for audio_path, csv_path in files:
result.append((audio_path, csv_path))
return result
# Returns the CQT of the input audio
def logCQT(file):
import librosa
sr = _SAMPLE_RATE
y, sr = librosa.load(file, sr=sr)
# 帧长为32ms (1000ms/(16000/512) = 32ms), D2的频率是73.418
cqt = librosa.cqt(
y,
sr=sr,
hop_length=_HOP_LENGTH,
fmin=27.5,
n_bins=88,
bins_per_octave=12,
)
return (
(1.0 / 80.0) * librosa.core.amplitude_to_db(np.abs(cqt), ref=np.max)
) + 1.0
def chunk_data(f):
s = int(_SAMPLE_RATE * _TIME_LENGTH / _HOP_LENGTH)
xdata = np.transpose(f)
x = []
length = int(np.ceil((int(len(xdata) / s) + 1) * s))
app = np.zeros((length - xdata.shape[0], xdata.shape[1]))
xdata = np.concatenate((xdata, app), 0)
for i in range(int(length / s)):
data = xdata[int(i * s) : int(i * s + s)]
x.append(np.transpose(data[:s, :]))
return np.array(x)
def load_all(audio_path, csv_path):
# Load audio features: The shape of cqt (88, 8520), 8520 is the number of frames on the time axis
cqt = logCQT(audio_path)
# Load the ground truth label
hop = _HOP_LENGTH
n_steps = cqt.shape[1]
n_IPTs = 7
technique = _NAMES
IPT_label = np.zeros([n_IPTs, n_steps], dtype=int)
with open(csv_path, "r") as f: # csv file for each audio
reader = csv.DictReader(f, delimiter=",")
for label in reader: # each note
onset = float(label["onset_time"])
offset = float(label["offset_time"])
IPT = int(technique[label["IPT"]])
left = int(round(onset * _SAMPLE_RATE / hop))
frame_right = int(round(offset * _SAMPLE_RATE / hop))
frame_right = min(n_steps, frame_right)
IPT_label[IPT, left:frame_right] = 1
return dict(
audiuo_path=audio_path, csv_path=csv_path, cqt=cqt, IPT_label=IPT_label
)
data = []
# print(f"Loading {len(groups)} group{'s' if len(groups) > 1 else ''} ")
for group in groups:
for input_files in files(wav_dir, csv_dir, group):
data.append(load_all(*input_files))
i = 0
for dic in data:
x = dic["cqt"]
x = chunk_data(x)
y_i = dic["IPT_label"]
y_i = chunk_data(y_i)
if i == 0:
Xtr = x
Ytr_i = y_i
i += 1
else:
Xtr = np.concatenate([Xtr, x], axis=0)
Ytr_i = np.concatenate([Ytr_i, y_i], axis=0)
# Transform the shape of the input
Xtr = np.expand_dims(Xtr, axis=3)
# Calculate the mean and variance of the input
if avg.all() == None and std.all() == None:
avg, std = self._RoW_norm(Xtr)
# Normalize
Xtr = self._norm(avg, std, Xtr, Xtr.shape)
return list(Xtr), list(Ytr_i)
def _parse_csv_label(self, csv_file):
label = []
with open(csv_file, mode="r", encoding="utf-8") as file:
for row in csv.DictReader(file):
label.append(
{
"onset_time": float(row["onset_time"]),
"offset_time": float(row["offset_time"]),
"IPT": _NAME[_NAMES[row["IPT"]]],
"note": int(row["note"]),
}
)
return label
def _split_generators(self, dl_manager):
audio_files = dl_manager.download_and_extract(_URLS["audio"])
csv_files = dl_manager.download_and_extract(_URLS["label"])
trainset, validset, testset = [], [], []
if self.config.name == "default":
files = {}
mel_files = dl_manager.download_and_extract(_URLS["mel"])
for path in dl_manager.iter_files([audio_files]):
fname: str = os.path.basename(path)
if fname.endswith(".flac"):
item_id = fname.split(".")[0]
files[item_id] = {"audio": path}
for path in dl_manager.iter_files([mel_files]):
fname = os.path.basename(path)
if fname.endswith(".jpg"):
item_id = fname.split(".")[0]
files[item_id]["mel"] = path
for path in dl_manager.iter_files([csv_files]):
fname = os.path.basename(path)
if fname.endswith(".csv"):
item_id = fname.split(".")[0]
files[item_id]["label"] = self._parse_csv_label(path)
for item in files.values():
if "train" in item["audio"]:
trainset.append(item)
elif "validation" in item["audio"]:
validset.append(item)
elif "test" in item["audio"]:
testset.append(item)
else:
audio_dir = audio_files + "\\audio"
csv_dir = csv_files + "\\label"
X_train, Y_train = self._load(audio_dir, csv_dir, ["train"])
X_valid, Y_valid = self._load(audio_dir, csv_dir, ["validation"])
X_test, Y_test = self._load(audio_dir, csv_dir, ["test"])
for i in range(len(X_train)):
trainset.append({"data": X_train[i], "label": Y_train[i]})
for i in range(len(X_valid)):
validset.append({"data": X_valid[i], "label": Y_valid[i]})
for i in range(len(X_test)):
testset.append({"data": X_test[i], "label": Y_test[i]})
random.shuffle(trainset)
random.shuffle(validset)
random.shuffle(testset)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN, gen_kwargs={"files": trainset}
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION, gen_kwargs={"files": validset}
),
datasets.SplitGenerator(
name=datasets.Split.TEST, gen_kwargs={"files": testset}
),
]
def _generate_examples(self, files):
for i, path in enumerate(files):
yield i, path
|