admin commited on
Commit
284b9fd
Β·
1 Parent(s): b82980a
Files changed (8) hide show
  1. .gitignore +10 -0
  2. app.py +552 -0
  3. conda.txt +5 -0
  4. convert.py +91 -0
  5. model.py +350 -0
  6. requirements.txt +8 -0
  7. utils.py +62 -0
  8. xml2abc.py +0 -0
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ *__pycache__*
2
+ output/*
3
+ rename.sh
4
+ test.py
5
+ gpt2-abcmusic/*
6
+ *.pth
7
+ flagged/*
8
+ mscore3/*
9
+ key.txt
10
+ feedbacks/*
app.py ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+ import json
4
+ import time
5
+ import torch
6
+ import random
7
+ import shutil
8
+ import argparse
9
+ import warnings
10
+ import gradio as gr
11
+ import soundfile as sf
12
+ from transformers import GPT2Config
13
+ from model import Patchilizer, TunesFormer
14
+ from convert import abc2xml, xml2img, xml2, transpose_octaves_abc
15
+ from utils import (
16
+ PATCH_NUM_LAYERS,
17
+ PATCH_LENGTH,
18
+ CHAR_NUM_LAYERS,
19
+ PATCH_SIZE,
20
+ SHARE_WEIGHTS,
21
+ TEMP_DIR,
22
+ WEIGHTS_DIR,
23
+ DEVICE,
24
+ )
25
+
26
+
27
+ def get_args(parser: argparse.ArgumentParser):
28
+ parser.add_argument(
29
+ "-num_tunes",
30
+ type=int,
31
+ default=1,
32
+ help="the number of independently computed returned tunes",
33
+ )
34
+ parser.add_argument(
35
+ "-max_patch",
36
+ type=int,
37
+ default=128,
38
+ help="integer to define the maximum length in tokens of each tune",
39
+ )
40
+ parser.add_argument(
41
+ "-top_p",
42
+ type=float,
43
+ default=0.8,
44
+ help="float to define the tokens that are within the sample operation of text generation",
45
+ )
46
+ parser.add_argument(
47
+ "-top_k",
48
+ type=int,
49
+ default=8,
50
+ help="integer to define the tokens that are within the sample operation of text generation",
51
+ )
52
+ parser.add_argument(
53
+ "-temperature",
54
+ type=float,
55
+ default=1.2,
56
+ help="the temperature of the sampling operation",
57
+ )
58
+ parser.add_argument("-seed", type=int, default=None, help="seed for randomstate")
59
+ parser.add_argument(
60
+ "-show_control_code",
61
+ type=bool,
62
+ default=False,
63
+ help="whether to show control code",
64
+ )
65
+ return parser.parse_args()
66
+
67
+
68
+ def get_abc_key_val(text: str, key="K"):
69
+ pattern = re.escape(key) + r":(.*?)\n"
70
+ match = re.search(pattern, text)
71
+ if match:
72
+ return match.group(1).strip()
73
+ else:
74
+ return None
75
+
76
+
77
+ def adjust_volume(in_audio: str, dB_change: int):
78
+ y, sr = sf.read(in_audio)
79
+ sf.write(in_audio, y * 10 ** (dB_change / 20), sr)
80
+
81
+
82
+ def generate_music(
83
+ args,
84
+ emo: str,
85
+ weights: str,
86
+ outdir=TEMP_DIR,
87
+ fix_tempo=None,
88
+ fix_pitch=None,
89
+ fix_volume=None,
90
+ ):
91
+ patchilizer = Patchilizer()
92
+ patch_config = GPT2Config(
93
+ num_hidden_layers=PATCH_NUM_LAYERS,
94
+ max_length=PATCH_LENGTH,
95
+ max_position_embeddings=PATCH_LENGTH,
96
+ vocab_size=1,
97
+ )
98
+ char_config = GPT2Config(
99
+ num_hidden_layers=CHAR_NUM_LAYERS,
100
+ max_length=PATCH_SIZE,
101
+ max_position_embeddings=PATCH_SIZE,
102
+ vocab_size=128,
103
+ )
104
+ model = TunesFormer(patch_config, char_config, share_weights=SHARE_WEIGHTS)
105
+ checkpoint = torch.load(weights)
106
+ model.load_state_dict(checkpoint["model"])
107
+ model = model.to(DEVICE)
108
+ model.eval()
109
+ prompt = f"A:{emo}\n"
110
+ tunes = ""
111
+ num_tunes = args.num_tunes
112
+ max_patch = args.max_patch
113
+ top_p = args.top_p
114
+ top_k = args.top_k
115
+ temperature = args.temperature
116
+ seed = args.seed
117
+ show_control_code = args.show_control_code
118
+ print(" Hyper parms ".center(60, "#"), "\n")
119
+ args_dict: dict = vars(args)
120
+ for arg in args_dict.keys():
121
+ print(f"{arg}: {str(args_dict[arg])}")
122
+
123
+ print("\n", " Output tunes ".center(60, "#"))
124
+ start_time = time.time()
125
+ for i in range(num_tunes):
126
+ title = f"T:{emo} Fragment\n"
127
+ artist = f"C:Generated by AI\n"
128
+ tune = f"X:{str(i + 1)}\n{title}{artist}{prompt}"
129
+ lines = re.split(r"(\n)", tune)
130
+ tune = ""
131
+ skip = False
132
+ for line in lines:
133
+ if show_control_code or line[:2] not in ["S:", "B:", "E:"]:
134
+ if not skip:
135
+ print(line, end="")
136
+ tune += line
137
+
138
+ skip = False
139
+
140
+ else:
141
+ skip = True
142
+
143
+ input_patches = torch.tensor(
144
+ [patchilizer.encode(prompt, add_special_patches=True)[:-1]],
145
+ device=DEVICE,
146
+ )
147
+ if tune == "":
148
+ tokens = None
149
+
150
+ else:
151
+ prefix = patchilizer.decode(input_patches[0])
152
+ remaining_tokens = prompt[len(prefix) :]
153
+ tokens = torch.tensor(
154
+ [patchilizer.bos_token_id] + [ord(c) for c in remaining_tokens],
155
+ device=DEVICE,
156
+ )
157
+
158
+ while input_patches.shape[1] < max_patch:
159
+ predicted_patch, seed = model.generate(
160
+ input_patches,
161
+ tokens,
162
+ top_p=top_p,
163
+ top_k=top_k,
164
+ temperature=temperature,
165
+ seed=seed,
166
+ )
167
+ tokens = None
168
+ if predicted_patch[0] != patchilizer.eos_token_id:
169
+ next_bar = patchilizer.decode([predicted_patch])
170
+ if show_control_code or next_bar[:2] not in ["S:", "B:", "E:"]:
171
+ print(next_bar, end="")
172
+ tune += next_bar
173
+
174
+ if next_bar == "":
175
+ break
176
+
177
+ next_bar = remaining_tokens + next_bar
178
+ remaining_tokens = ""
179
+ predicted_patch = torch.tensor(
180
+ patchilizer.bar2patch(next_bar),
181
+ device=DEVICE,
182
+ ).unsqueeze(0)
183
+ input_patches = torch.cat(
184
+ [input_patches, predicted_patch.unsqueeze(0)],
185
+ dim=1,
186
+ )
187
+
188
+ else:
189
+ break
190
+
191
+ tunes += f"{tune}\n\n"
192
+ print("\n")
193
+
194
+ # fix tempo
195
+ if fix_tempo != None:
196
+ tempo = f"Q:{fix_tempo}\n"
197
+
198
+ else:
199
+ tempo = f"Q:{random.randint(88, 132)}\n"
200
+ if emo == "Q1":
201
+ tempo = f"Q:{random.randint(160, 184)}\n"
202
+ elif emo == "Q2":
203
+ tempo = f"Q:{random.randint(184, 228)}\n"
204
+ elif emo == "Q3":
205
+ tempo = f"Q:{random.randint(40, 69)}\n"
206
+ elif emo == "Q4":
207
+ tempo = f"Q:{random.randint(40, 69)}\n"
208
+
209
+ Q_val = get_abc_key_val(tunes, "Q")
210
+ if Q_val:
211
+ tunes = tunes.replace(f"Q:{Q_val}\n", "")
212
+
213
+ tunes = tunes.replace(f"A:{emo}\n", tempo)
214
+ # fix mode:major/minor
215
+ mode = "major" if emo == "Q1" or emo == "Q4" else "minor"
216
+ K_val = get_abc_key_val(tunes)
217
+ if mode == "major" and K_val and "m" in K_val:
218
+ tunes = tunes.replace(f"\nK:{K_val}\n", f"\nK:{K_val.split('m')[0]}\n")
219
+
220
+ elif mode == "minor" and K_val and not "m" in K_val:
221
+ tunes = tunes.replace(f"\nK:{K_val}\n", f"\nK:{K_val.lower()}min\n")
222
+
223
+ print("Generation time: {:.2f} seconds".format(time.time() - start_time))
224
+ timestamp = time.strftime("%a_%d_%b_%Y_%H_%M_%S", time.localtime())
225
+ try:
226
+ # fix avg_pitch (octave)
227
+ if fix_pitch != None:
228
+ if fix_pitch:
229
+ tunes, xml = transpose_octaves_abc(
230
+ tunes,
231
+ f"{outdir}/{timestamp}.musicxml",
232
+ fix_pitch,
233
+ )
234
+ tunes = tunes.replace(title + title, title)
235
+ os.rename(xml, f"{outdir}/[{emo}]{timestamp}.musicxml")
236
+ xml = f"{outdir}/[{emo}]{timestamp}.musicxml"
237
+
238
+ else:
239
+ if mode == "minor":
240
+ offset = -12
241
+ if emo == "Q2":
242
+ offset -= 12
243
+
244
+ tunes, xml = transpose_octaves_abc(
245
+ tunes,
246
+ f"{outdir}/{timestamp}.musicxml",
247
+ offset,
248
+ )
249
+ tunes = tunes.replace(title + title, title)
250
+ os.rename(xml, f"{outdir}/[{emo}]{timestamp}.musicxml")
251
+ xml = f"{outdir}/[{emo}]{timestamp}.musicxml"
252
+
253
+ else:
254
+ xml = abc2xml(tunes, f"{outdir}/[{emo}]{timestamp}.musicxml")
255
+
256
+ audio = xml2(xml, "wav")
257
+ if fix_volume != None:
258
+ if fix_volume:
259
+ adjust_volume(audio, fix_volume)
260
+
261
+ elif os.path.exists(audio):
262
+ if emo == "Q1":
263
+ adjust_volume(audio, 5)
264
+
265
+ elif emo == "Q2":
266
+ adjust_volume(audio, 10)
267
+
268
+ mxl = xml2(xml, "mxl")
269
+ midi = xml2(xml, "mid")
270
+ pdf, jpg = xml2img(xml)
271
+ return audio, midi, pdf, xml, mxl, tunes, jpg
272
+
273
+ except Exception as e:
274
+ print(f"{e}")
275
+ return generate_music(args, emo, weights)
276
+
277
+
278
+ def inference(dataset: str, v: str, a: str, add_chord: bool):
279
+ if os.path.exists(TEMP_DIR):
280
+ shutil.rmtree(TEMP_DIR)
281
+
282
+ os.makedirs(TEMP_DIR, exist_ok=True)
283
+ emotion = "Q1"
284
+ if v == "Low" and a == "High":
285
+ emotion = "Q2"
286
+
287
+ elif v == "Low" and a == "Low":
288
+ emotion = "Q3"
289
+
290
+ elif v == "High" and a == "Low":
291
+ emotion = "Q4"
292
+
293
+ parser = argparse.ArgumentParser()
294
+ args = get_args(parser)
295
+ return generate_music(
296
+ args,
297
+ emo=emotion,
298
+ weights=f"{WEIGHTS_DIR}/{dataset.lower()}/weights.pth",
299
+ )
300
+
301
+
302
+ def infer(
303
+ dataset: str,
304
+ pitch_std: str,
305
+ mode: str,
306
+ tempo: int,
307
+ octave: int,
308
+ rms: int,
309
+ add_chord: bool,
310
+ ):
311
+ if os.path.exists(TEMP_DIR):
312
+ shutil.rmtree(TEMP_DIR)
313
+
314
+ os.makedirs(TEMP_DIR, exist_ok=True)
315
+ emotion = "Q1"
316
+ if mode == "Minor" and pitch_std == "High":
317
+ emotion = "Q2"
318
+
319
+ elif mode == "Minor" and pitch_std == "Low":
320
+ emotion = "Q3"
321
+
322
+ elif mode == "Major" and pitch_std == "Low":
323
+ emotion = "Q4"
324
+
325
+ parser = argparse.ArgumentParser()
326
+ args = get_args(parser)
327
+ return generate_music(
328
+ args,
329
+ emo=emotion,
330
+ weights=f"{WEIGHTS_DIR}/{dataset.lower()}/weights.pth",
331
+ fix_tempo=tempo,
332
+ fix_pitch=octave,
333
+ fix_volume=rms,
334
+ )
335
+
336
+
337
+ def feedback(fixed_emo: str, source_dir="./flagged", target_dir="./feedbacks"):
338
+ if not fixed_emo:
339
+ return "Please select feedback before submitting! "
340
+
341
+ os.makedirs(target_dir, exist_ok=True)
342
+ for root, _, files in os.walk(source_dir):
343
+ for file in files:
344
+ if file.endswith(".mxl"):
345
+ prompt_emo = file.split("]")[0][1:]
346
+ if prompt_emo != fixed_emo:
347
+ file_path = os.path.join(root, file)
348
+ target_path = os.path.join(
349
+ target_dir, file.replace(".mxl", f"_{fixed_emo}.mxl")
350
+ )
351
+ shutil.copy(file_path, target_path)
352
+ return f"Copied {file_path} to {target_path}"
353
+
354
+ else:
355
+ return "Thanks for your feedback!"
356
+
357
+ return "No .mxl files found in the source directory."
358
+
359
+
360
+ def save_template(
361
+ label: str,
362
+ pitch_std: str,
363
+ mode: str,
364
+ tempo: int,
365
+ octave: int,
366
+ rms: int,
367
+ ):
368
+ if (
369
+ label
370
+ and pitch_std
371
+ and mode
372
+ and tempo != None
373
+ and octave != None
374
+ and rms != None
375
+ ):
376
+ json_str = json.dumps(
377
+ {
378
+ "label": label,
379
+ "pitch_std": pitch_std == "High",
380
+ "mode": mode == "Major",
381
+ "tempo": tempo,
382
+ "octave": octave,
383
+ "volume": rms,
384
+ }
385
+ )
386
+
387
+ with open("./feedbacks/templates.jsonl", "a", encoding="utf-8") as file:
388
+ file.write(json_str + "\n")
389
+
390
+
391
+ if __name__ == "__main__":
392
+ warnings.filterwarnings("ignore")
393
+ if os.path.exists("./flagged"):
394
+ shutil.rmtree("./flagged")
395
+
396
+ with gr.Blocks() as demo:
397
+ with gr.Row():
398
+ with gr.Column():
399
+ dataset_option = gr.Dropdown(
400
+ ["VGMIDI", "EMOPIA", "Rough4Q"],
401
+ label="Dataset",
402
+ value="Rough4Q",
403
+ )
404
+ gr.Markdown(
405
+ "# Generate by emotion condition<br><img width='100%' src='https://www.modelscope.cn/studio/monetjoe/EMusicGen/resolve/master/4q.jpg'>"
406
+ )
407
+ valence_radio = gr.Radio(
408
+ ["Low", "High"],
409
+ label="Valence (reflects negative-positive levels of emotion)",
410
+ value="High",
411
+ )
412
+ arousal_radio = gr.Radio(
413
+ ["Low", "High"],
414
+ label="Arousal (reflects the calmness-intensity of the emotion)",
415
+ value="High",
416
+ )
417
+ chord_check = gr.Checkbox(
418
+ label="Generate chords",
419
+ value=False,
420
+ )
421
+ gen_btn = gr.Button("Generate")
422
+ gr.Markdown("# Generate by feature control")
423
+ std_option = gr.Radio(
424
+ ["Low", "High"],
425
+ label="Pitch SD",
426
+ value="High",
427
+ )
428
+ mode_option = gr.Radio(
429
+ ["Minor", "Major"],
430
+ label="Mode",
431
+ value="Major",
432
+ )
433
+ tempo_option = gr.Slider(
434
+ minimum=40,
435
+ maximum=228,
436
+ step=1,
437
+ value=120,
438
+ label="Tempo (BPM)",
439
+ )
440
+ octave_option = gr.Slider(
441
+ minimum=-24,
442
+ maximum=24,
443
+ step=12,
444
+ value=0,
445
+ label="Octave (Β±12)",
446
+ )
447
+ volume_option = gr.Slider(
448
+ minimum=-5,
449
+ maximum=10,
450
+ step=5,
451
+ value=0,
452
+ label="Volume (dB)",
453
+ )
454
+ chord_check_2 = gr.Checkbox(
455
+ label="Generate chords",
456
+ value=False,
457
+ )
458
+ gen_btn_2 = gr.Button("Generate")
459
+ template_radio = gr.Radio(
460
+ ["Q1", "Q2", "Q3", "Q4"],
461
+ label="The emotion to which the current template belongs",
462
+ )
463
+ save_btn = gr.Button("Save template")
464
+ gr.Markdown(
465
+ """
466
+ ## Cite
467
+ ```bibtex
468
+ @article{Zhou2024EMusicGen,
469
+ title = {EMusicGen: Emotion-Conditioned Melody Generation in ABC Notation},
470
+ author = {Monan Zhou, Xiaobing Li, Feng Yu and Wei Li},
471
+ month = {Sep},
472
+ year = {2024},
473
+ publisher = {GitHub},
474
+ version = {0.1},
475
+ url = {https://github.com/monetjoe/EMusicGen}
476
+ }
477
+ ```
478
+ """
479
+ )
480
+
481
+ with gr.Column():
482
+ wav_audio = gr.Audio(label="Audio", type="filepath")
483
+ midi_file = gr.File(label="Download MIDI")
484
+ pdf_file = gr.File(label="Download PDF score")
485
+ xml_file = gr.File(label="Download MusicXML")
486
+ mxl_file = gr.File(label="Download MXL")
487
+ abc_textbox = gr.Textbox(
488
+ label="ABC notation",
489
+ show_copy_button=True,
490
+ )
491
+ staff_img = gr.Image(label="Staff", type="filepath")
492
+
493
+ with gr.Row():
494
+ gr.Interface(
495
+ fn=feedback,
496
+ inputs=gr.Radio(
497
+ ["Q1", "Q2", "Q3", "Q4"],
498
+ label="Feedback: the emotion you believe the generated result should belong to",
499
+ ),
500
+ outputs=gr.Textbox(show_copy_button=False, show_label=False),
501
+ allow_flagging="never",
502
+ )
503
+
504
+ gen_btn.click(
505
+ fn=inference,
506
+ inputs=[dataset_option, valence_radio, arousal_radio, chord_check],
507
+ outputs=[
508
+ wav_audio,
509
+ midi_file,
510
+ pdf_file,
511
+ xml_file,
512
+ mxl_file,
513
+ abc_textbox,
514
+ staff_img,
515
+ ],
516
+ )
517
+
518
+ gen_btn_2.click(
519
+ fn=infer,
520
+ inputs=[
521
+ dataset_option,
522
+ std_option,
523
+ mode_option,
524
+ tempo_option,
525
+ octave_option,
526
+ volume_option,
527
+ chord_check,
528
+ ],
529
+ outputs=[
530
+ wav_audio,
531
+ midi_file,
532
+ pdf_file,
533
+ xml_file,
534
+ mxl_file,
535
+ abc_textbox,
536
+ staff_img,
537
+ ],
538
+ )
539
+
540
+ save_btn.click(
541
+ fn=save_template,
542
+ inputs=[
543
+ template_radio,
544
+ std_option,
545
+ mode_option,
546
+ tempo_option,
547
+ octave_option,
548
+ volume_option,
549
+ ],
550
+ )
551
+
552
+ demo.launch()
conda.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ python=3.10
2
+ pytorch=1.12.1
3
+ torchvision=0.13.1
4
+ torchaudio=0.12.1
5
+ cudatoolkit=11.3.1
convert.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import fitz
3
+ import subprocess
4
+ from PIL import Image
5
+ from music21 import converter, interval, clef, stream
6
+ from utils import MSCORE
7
+
8
+
9
+ def abc2xml(abc_content, output_xml_path):
10
+ score = converter.parse(abc_content, format="abc")
11
+ score.write("musicxml", fp=output_xml_path, encoding="utf-8")
12
+ return output_xml_path
13
+
14
+
15
+ def xml2(xml_path: str, target_fmt: str):
16
+ src_fmt = os.path.basename(xml_path).split(".")[-1]
17
+ if not "." in target_fmt:
18
+ target_fmt = "." + target_fmt
19
+
20
+ target_file = xml_path.replace(f".{src_fmt}", target_fmt)
21
+ print(subprocess.run([MSCORE, "-o", target_file, xml_path]))
22
+ return target_file
23
+
24
+
25
+ def pdf2img(pdf_path: str):
26
+ output_path = pdf_path.replace(".pdf", ".jpg")
27
+ doc = fitz.open(pdf_path)
28
+ # εˆ›ε»ΊδΈ€δΈͺε›Ύεƒεˆ—θ‘¨
29
+ images = []
30
+ for page_number in range(doc.page_count):
31
+ page = doc[page_number]
32
+ # ε°†ι‘΅ι’ζΈ²ζŸ“δΈΊε›Ύεƒ
33
+ image = page.get_pixmap()
34
+ # ε°†ε›Ύεƒζ·»εŠ εˆ°εˆ—θ‘¨
35
+ images.append(
36
+ Image.frombytes("RGB", [image.width, image.height], image.samples)
37
+ )
38
+ # η«–ε‘εˆεΉΆε›Ύεƒ
39
+ merged_image = Image.new(
40
+ "RGB", (images[0].width, sum(image.height for image in images))
41
+ )
42
+ y_offset = 0
43
+ for image in images:
44
+ merged_image.paste(image, (0, y_offset))
45
+ y_offset += image.height
46
+ # δΏε­˜εˆεΉΆεŽηš„ε›ΎεƒδΈΊJPG
47
+ merged_image.save(output_path, "JPEG")
48
+ # ε…³ι—­PDFζ–‡ζ‘£
49
+ doc.close()
50
+ return output_path
51
+
52
+
53
+ def xml2img(xml_file: str):
54
+ ext = os.path.basename(xml_file).split(".")[-1]
55
+ pdf_score = xml_file.replace(f".{ext}", ".pdf")
56
+ command = [MSCORE, "-o", pdf_score, xml_file]
57
+ result = subprocess.run(command)
58
+ print(result)
59
+ return pdf_score, pdf2img(pdf_score)
60
+
61
+
62
+ # xml to abc
63
+ def xml2abc(input_xml_file: str):
64
+ result = subprocess.run(
65
+ ["python", "-Xfrozen_modules=off", "./xml2abc.py", input_xml_file],
66
+ stdout=subprocess.PIPE,
67
+ text=True,
68
+ )
69
+
70
+ if result.returncode == 0:
71
+ return str(result.stdout).strip()
72
+
73
+ return ""
74
+
75
+
76
+ def transpose_octaves_abc(abc_notation: str, out_xml_file: str, offset=-12):
77
+ score = converter.parse(abc_notation)
78
+ if offset < 0:
79
+ for part in score.parts:
80
+ for measure in part.getElementsByClass(stream.Measure):
81
+ # ζ£€ζŸ₯ε½“ε‰ε°θŠ‚ηš„θ°±ε·
82
+ if measure.clef:
83
+ measure.clef = clef.BassClef()
84
+
85
+ octaves_interval = interval.Interval(offset)
86
+ # ιεŽ†ζ―δΈͺιŸ³η¬¦οΌŒε°†ε…ΆδΈŠδΈ‹η§»ε…«εΊ¦
87
+ for note in score.recurse().notes:
88
+ note.transpose(octaves_interval, inPlace=True)
89
+
90
+ score.write("musicxml", fp=out_xml_file)
91
+ return xml2abc(out_xml_file), out_xml_file
model.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import torch
3
+ import random
4
+ from tqdm import tqdm
5
+ from unidecode import unidecode
6
+ from torch.utils.data import Dataset
7
+ from transformers import GPT2Model, GPT2LMHeadModel, PreTrainedModel
8
+ from samplings import top_p_sampling, top_k_sampling, temperature_sampling
9
+ from utils import PATCH_SIZE, PATCH_LENGTH, PATCH_SAMPLING_BATCH_SIZE
10
+
11
+
12
+ class Patchilizer:
13
+ """
14
+ A class for converting music bars to patches and vice versa.
15
+ """
16
+
17
+ def __init__(self):
18
+ self.delimiters = ["|:", "::", ":|", "[|", "||", "|]", "|"]
19
+ self.regexPattern = f"({'|'.join(map(re.escape, self.delimiters))})"
20
+ self.pad_token_id = 0
21
+ self.bos_token_id = 1
22
+ self.eos_token_id = 2
23
+
24
+ def split_bars(self, body):
25
+ """
26
+ Split a body of music into individual bars.
27
+ """
28
+ bars = re.split(self.regexPattern, "".join(body))
29
+ bars = list(filter(None, bars))
30
+ # remove empty strings
31
+ if bars[0] in self.delimiters:
32
+ bars[1] = bars[0] + bars[1]
33
+ bars = bars[1:]
34
+
35
+ bars = [bars[i * 2] + bars[i * 2 + 1] for i in range(len(bars) // 2)]
36
+ return bars
37
+
38
+ def bar2patch(self, bar, patch_size=PATCH_SIZE):
39
+ """
40
+ Convert a bar into a patch of specified length.
41
+ """
42
+ patch = [self.bos_token_id] + [ord(c) for c in bar] + [self.eos_token_id]
43
+ patch = patch[:patch_size]
44
+ patch += [self.pad_token_id] * (patch_size - len(patch))
45
+ return patch
46
+
47
+ def patch2bar(self, patch):
48
+ """
49
+ Convert a patch into a bar.
50
+ """
51
+ return "".join(
52
+ chr(idx) if idx > self.eos_token_id else ""
53
+ for idx in patch
54
+ if idx != self.eos_token_id
55
+ )
56
+
57
+ def encode(
58
+ self,
59
+ abc_code,
60
+ patch_length=PATCH_LENGTH,
61
+ patch_size=PATCH_SIZE,
62
+ add_special_patches=False,
63
+ ):
64
+ """
65
+ Encode music into patches of specified length.
66
+ """
67
+ lines = unidecode(abc_code).split("\n")
68
+ lines = list(filter(None, lines)) # remove empty lines
69
+
70
+ body = ""
71
+ patches = []
72
+
73
+ for line in lines:
74
+ if len(line) > 1 and (
75
+ (line[0].isalpha() and line[1] == ":") or line.startswith("%%score")
76
+ ):
77
+ if body:
78
+ bars = self.split_bars(body)
79
+ patches.extend(
80
+ self.bar2patch(
81
+ bar + "\n" if idx == len(bars) - 1 else bar, patch_size
82
+ )
83
+ for idx, bar in enumerate(bars)
84
+ )
85
+ body = ""
86
+
87
+ patches.append(self.bar2patch(line + "\n", patch_size))
88
+
89
+ else:
90
+ body += line + "\n"
91
+
92
+ if body:
93
+ patches.extend(
94
+ self.bar2patch(bar, patch_size) for bar in self.split_bars(body)
95
+ )
96
+
97
+ if add_special_patches:
98
+ bos_patch = [self.bos_token_id] * (patch_size - 1) + [self.eos_token_id]
99
+ eos_patch = [self.bos_token_id] + [self.eos_token_id] * (patch_size - 1)
100
+ patches = [bos_patch] + patches + [eos_patch]
101
+
102
+ return patches[:patch_length]
103
+
104
+ def decode(self, patches):
105
+ """
106
+ Decode patches into music.
107
+ """
108
+ return "".join(self.patch2bar(patch) for patch in patches)
109
+
110
+
111
+ class PatchLevelDecoder(PreTrainedModel):
112
+ """
113
+ An Patch-level Decoder model for generating patch features in an auto-regressive manner.
114
+ It inherits PreTrainedModel from transformers.
115
+ """
116
+
117
+ def __init__(self, config):
118
+ super().__init__(config)
119
+ self.patch_embedding = torch.nn.Linear(PATCH_SIZE * 128, config.n_embd)
120
+ torch.nn.init.normal_(self.patch_embedding.weight, std=0.02)
121
+ self.base = GPT2Model(config)
122
+
123
+ def forward(self, patches: torch.Tensor) -> torch.Tensor:
124
+ """
125
+ The forward pass of the patch-level decoder model.
126
+ :param patches: the patches to be encoded
127
+ :return: the encoded patches
128
+ """
129
+ patches = torch.nn.functional.one_hot(patches, num_classes=128).float()
130
+ patches = patches.reshape(len(patches), -1, PATCH_SIZE * 128)
131
+ patches = self.patch_embedding(patches.to(self.device))
132
+
133
+ return self.base(inputs_embeds=patches)
134
+
135
+
136
+ class CharLevelDecoder(PreTrainedModel):
137
+ """
138
+ A Char-level Decoder model for generating the characters within each bar patch sequentially.
139
+ It inherits PreTrainedModel from transformers.
140
+ """
141
+
142
+ def __init__(self, config):
143
+ super().__init__(config)
144
+ self.pad_token_id = 0
145
+ self.bos_token_id = 1
146
+ self.eos_token_id = 2
147
+ self.base = GPT2LMHeadModel(config)
148
+
149
+ def forward(
150
+ self,
151
+ encoded_patches: torch.Tensor,
152
+ target_patches: torch.Tensor,
153
+ patch_sampling_batch_size: int,
154
+ ):
155
+ """
156
+ The forward pass of the char-level decoder model.
157
+ :param encoded_patches: the encoded patches
158
+ :param target_patches: the target patches
159
+ :return: the decoded patches
160
+ """
161
+ # preparing the labels for model training
162
+ target_masks = target_patches == self.pad_token_id
163
+ labels = target_patches.clone().masked_fill_(target_masks, -100)
164
+
165
+ # masking the labels for model training
166
+ target_masks = torch.ones_like(labels)
167
+ target_masks = target_masks.masked_fill_(labels == -100, 0)
168
+
169
+ # select patches
170
+ if (
171
+ patch_sampling_batch_size != 0
172
+ and patch_sampling_batch_size < target_patches.shape[0]
173
+ ):
174
+ indices = list(range(len(target_patches)))
175
+ random.shuffle(indices)
176
+ selected_indices = sorted(indices[:patch_sampling_batch_size])
177
+
178
+ target_patches = target_patches[selected_indices, :]
179
+ target_masks = target_masks[selected_indices, :]
180
+ encoded_patches = encoded_patches[selected_indices, :]
181
+ labels = labels[selected_indices, :]
182
+
183
+ # get input embeddings
184
+ inputs_embeds = torch.nn.functional.embedding(
185
+ target_patches, self.base.transformer.wte.weight
186
+ )
187
+
188
+ # concatenate the encoded patches with the input embeddings
189
+ inputs_embeds = torch.cat(
190
+ (encoded_patches.unsqueeze(1), inputs_embeds[:, 1:, :]), dim=1
191
+ )
192
+
193
+ return self.base(
194
+ inputs_embeds=inputs_embeds, attention_mask=target_masks, labels=labels
195
+ )
196
+
197
+ def generate(self, encoded_patch: torch.Tensor, tokens: torch.Tensor):
198
+ """
199
+ The generate function for generating a patch based on the encoded patch and already generated tokens.
200
+ :param encoded_patch: the encoded patch
201
+ :param tokens: already generated tokens in the patch
202
+ :return: the probability distribution of next token
203
+ """
204
+ encoded_patch = encoded_patch.reshape(1, 1, -1)
205
+ tokens = tokens.reshape(1, -1)
206
+
207
+ # Get input embeddings
208
+ tokens = torch.nn.functional.embedding(tokens, self.base.transformer.wte.weight)
209
+
210
+ # Concatenate the encoded patch with the input embeddings
211
+ tokens = torch.cat((encoded_patch, tokens[:, 1:, :]), dim=1)
212
+
213
+ # Get output from model
214
+ outputs = self.base(inputs_embeds=tokens)
215
+
216
+ # Get probabilities of next token
217
+ probs = torch.nn.functional.softmax(outputs.logits.squeeze(0)[-1], dim=-1)
218
+
219
+ return probs
220
+
221
+
222
+ class TunesFormer(PreTrainedModel):
223
+ """
224
+ TunesFormer is a hierarchical music generation model based on bar patching.
225
+ It includes a patch-level decoder and a character-level decoder.
226
+ It inherits PreTrainedModel from transformers.
227
+ """
228
+
229
+ def __init__(self, encoder_config, decoder_config, share_weights=False):
230
+ super().__init__(encoder_config)
231
+ self.pad_token_id = 0
232
+ self.bos_token_id = 1
233
+ self.eos_token_id = 2
234
+ if share_weights:
235
+ max_layers = max(
236
+ encoder_config.num_hidden_layers, decoder_config.num_hidden_layers
237
+ )
238
+
239
+ max_context_size = max(encoder_config.max_length, decoder_config.max_length)
240
+
241
+ max_position_embeddings = max(
242
+ encoder_config.max_position_embeddings,
243
+ decoder_config.max_position_embeddings,
244
+ )
245
+
246
+ encoder_config.num_hidden_layers = max_layers
247
+ encoder_config.max_length = max_context_size
248
+ encoder_config.max_position_embeddings = max_position_embeddings
249
+ decoder_config.num_hidden_layers = max_layers
250
+ decoder_config.max_length = max_context_size
251
+ decoder_config.max_position_embeddings = max_position_embeddings
252
+
253
+ self.patch_level_decoder = PatchLevelDecoder(encoder_config)
254
+ self.char_level_decoder = CharLevelDecoder(decoder_config)
255
+
256
+ if share_weights:
257
+ self.patch_level_decoder.base = self.char_level_decoder.base.transformer
258
+
259
+ def forward(
260
+ self,
261
+ patches: torch.Tensor,
262
+ patch_sampling_batch_size: int = PATCH_SAMPLING_BATCH_SIZE,
263
+ ):
264
+ """
265
+ The forward pass of the TunesFormer model.
266
+ :param patches: the patches to be both encoded and decoded
267
+ :return: the decoded patches
268
+ """
269
+ patches = patches.reshape(len(patches), -1, PATCH_SIZE)
270
+ encoded_patches = self.patch_level_decoder(patches)["last_hidden_state"]
271
+
272
+ return self.char_level_decoder(
273
+ encoded_patches.squeeze(0)[:-1, :],
274
+ patches.squeeze(0)[1:, :],
275
+ patch_sampling_batch_size,
276
+ )
277
+
278
+ def generate(
279
+ self,
280
+ patches: torch.Tensor,
281
+ tokens: torch.Tensor,
282
+ top_p: float = 1,
283
+ top_k: int = 0,
284
+ temperature: float = 1,
285
+ seed: int = None,
286
+ ):
287
+ """
288
+ The generate function for generating patches based on patches.
289
+ :param patches: the patches to be encoded
290
+ :return: the generated patches
291
+ """
292
+ patches = patches.reshape(len(patches), -1, PATCH_SIZE)
293
+ encoded_patches = self.patch_level_decoder(patches)["last_hidden_state"]
294
+
295
+ if tokens == None:
296
+ tokens = torch.tensor([self.bos_token_id], device=self.device)
297
+
298
+ generated_patch = []
299
+ random.seed(seed)
300
+
301
+ while True:
302
+ if seed != None:
303
+ n_seed = random.randint(0, 1000000)
304
+ random.seed(n_seed)
305
+
306
+ else:
307
+ n_seed = None
308
+
309
+ prob = (
310
+ self.char_level_decoder.generate(encoded_patches[0][-1], tokens)
311
+ .cpu()
312
+ .detach()
313
+ .numpy()
314
+ )
315
+
316
+ prob = top_p_sampling(prob, top_p=top_p, return_probs=True)
317
+ prob = top_k_sampling(prob, top_k=top_k, return_probs=True)
318
+
319
+ token = temperature_sampling(prob, temperature=temperature, seed=n_seed)
320
+
321
+ generated_patch.append(token)
322
+ if token == self.eos_token_id or len(tokens) >= PATCH_SIZE - 1:
323
+ break
324
+
325
+ else:
326
+ tokens = torch.cat(
327
+ (tokens, torch.tensor([token], device=self.device)), dim=0
328
+ )
329
+
330
+ return generated_patch, n_seed
331
+
332
+
333
+ class PatchilizedData(Dataset):
334
+ def __init__(self, items, patchilizer):
335
+ self.texts = []
336
+
337
+ for item in tqdm(items):
338
+ text = item["control code"] + "\n".join(
339
+ item["abc notation"].split("\n")[1:]
340
+ )
341
+ input_patch = patchilizer.encode(text, add_special_patches=True)
342
+ input_patch = torch.tensor(input_patch)
343
+ if torch.sum(input_patch) != 0:
344
+ self.texts.append(input_patch)
345
+
346
+ def __len__(self):
347
+ return len(self.texts)
348
+
349
+ def __getitem__(self, idx):
350
+ return self.texts[idx]
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ music21
2
+ pymupdf
3
+ autopep8
4
+ unidecode
5
+ pillow==9.4.0
6
+ samplings==0.1.7
7
+ modelscope==1.15
8
+ transformers==4.18.0
utils.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import time
4
+ import torch
5
+ import requests
6
+ import subprocess
7
+ from tqdm import tqdm
8
+ from modelscope.hub.api import HubApi
9
+ from modelscope import snapshot_download
10
+
11
+ HubApi().login(os.getenv("ms_app_key"))
12
+ TEMP_DIR = "./flagged"
13
+ WEIGHTS_DIR = snapshot_download("monetjoe/EMusicGen", cache_dir="./__pycache__")
14
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+ PATCH_LENGTH = 128 # Patch Length
16
+ PATCH_SIZE = 32 # Patch Size
17
+ PATCH_NUM_LAYERS = 9 # Number of layers in the encoder
18
+ CHAR_NUM_LAYERS = 3 # Number of layers in the decoder
19
+ PATCH_SAMPLING_BATCH_SIZE = 0 # Batch size for training patch, 0 for full context
20
+ LOAD_FROM_CHECKPOINT = True # Whether to load weights from a checkpoint
21
+ SHARE_WEIGHTS = False # Whether to share weights between the encoder and decoder
22
+
23
+
24
+ def download(filename: str, url: str):
25
+ try:
26
+ response = requests.get(url, stream=True)
27
+ total_size = int(response.headers.get("content-length", 0))
28
+ chunk_size = 1024
29
+
30
+ with open(filename, "wb") as file, tqdm(
31
+ desc=f"Downloading {filename} from {url}...",
32
+ total=total_size,
33
+ unit="B",
34
+ unit_scale=True,
35
+ unit_divisor=1024,
36
+ ) as bar:
37
+ for data in response.iter_content(chunk_size=chunk_size):
38
+ size = file.write(data)
39
+ bar.update(size)
40
+
41
+ except Exception as e:
42
+ print(f"Error: {e}")
43
+ time.sleep(10)
44
+ download(filename, url)
45
+
46
+
47
+ if sys.platform.startswith("linux"):
48
+ apkname = "MuseScore.AppImage"
49
+ extra_dir = "squashfs-root"
50
+ download(
51
+ filename=apkname,
52
+ url="https://www.modelscope.cn/studio/MuGeminorum/piano_transcription/resolve/master/MuseScore.AppImage",
53
+ )
54
+ if not os.path.exists(extra_dir):
55
+ subprocess.run(["chmod", "+x", f"./{apkname}"])
56
+ subprocess.run([f"./{apkname}", "--appimage-extract"])
57
+
58
+ MSCORE = f"./{extra_dir}/AppRun"
59
+ os.environ["QT_QPA_PLATFORM"] = "offscreen"
60
+
61
+ else:
62
+ MSCORE = os.getenv("mscore")
xml2abc.py ADDED
The diff for this file is too large to render. See raw diff