asigalov61 commited on
Commit
35a52d1
1 Parent(s): 7976bb4

Upload 6 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2 filter=lfs diff=lfs merge=lfs -text
SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd41a4639c9e7a96413b4b22540d48e6741e24bcdabcb2eff22cd65929df3cfa
3
+ size 553961496
TMIDIX.py ADDED
The diff for this file is too large to render. See raw diff
 
app.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path
2
+
3
+ import time as reqtime
4
+ import datetime
5
+ from pytz import timezone
6
+
7
+ import torch
8
+
9
+ import spaces
10
+ import gradio as gr
11
+
12
+ from x_transformer_1_23_2 import *
13
+ import random
14
+ import tqdm
15
+
16
+ from midi_to_colab_audio import midi_to_colab_audio
17
+ import TMIDIX
18
+
19
+ import matplotlib.pyplot as plt
20
+
21
+ in_space = os.getenv("SYSTEM") == "spaces"
22
+
23
+ # =================================================================================================
24
+
25
+ @spaces.GPU
26
+ def InpaintPitches(input_midi, input_num_of_notes, input_patch_number):
27
+ print('=' * 70)
28
+ print('Req start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
29
+ start_time = reqtime.time()
30
+
31
+ print('Loading model...')
32
+
33
+ SEQ_LEN = 8192 # Models seq len
34
+ PAD_IDX = 19463 # Models pad index
35
+ DEVICE = 'cuda' # 'cuda'
36
+
37
+ # instantiate the model
38
+
39
+ model = TransformerWrapper(
40
+ num_tokens = PAD_IDX+1,
41
+ max_seq_len = SEQ_LEN,
42
+ attn_layers = Decoder(dim = 1024, depth = 32, heads = 32, attn_flash = True)
43
+ )
44
+
45
+ model = AutoregressiveWrapper(model, ignore_index = PAD_IDX)
46
+
47
+ model.to(DEVICE)
48
+ print('=' * 70)
49
+
50
+ print('Loading model checkpoint...')
51
+
52
+ model.load_state_dict(
53
+ torch.load('Giant_Music_Transformer_Large_Trained_Model_36074_steps_0.3067_loss_0.927_acc.pth',
54
+ map_location=DEVICE))
55
+ print('=' * 70)
56
+
57
+ model.eval()
58
+
59
+ if DEVICE == 'cpu':
60
+ dtype = torch.bfloat16
61
+ else:
62
+ dtype = torch.bfloat16
63
+
64
+ ctx = torch.amp.autocast(device_type=DEVICE, dtype=dtype)
65
+
66
+ print('Done!')
67
+ print('=' * 70)
68
+
69
+ fn = os.path.basename(input_midi.name)
70
+ fn1 = fn.split('.')[0]
71
+
72
+ input_num_of_notes = max(8, min(2048, input_num_of_notes))
73
+
74
+ print('-' * 70)
75
+ print('Input file name:', fn)
76
+ print('Req num of notes:', input_num_of_notes)
77
+ print('Req patch number:', input_patch_number)
78
+ print('-' * 70)
79
+
80
+ #===============================================================================
81
+ raw_score = TMIDIX.midi2single_track_ms_score(input_midi.name)
82
+
83
+ #===============================================================================
84
+ # Enhanced score notes
85
+
86
+ events_matrix1 = TMIDIX.advanced_score_processor(raw_score, return_enhanced_score_notes=True)[0]
87
+
88
+ #=======================================================
89
+ # PRE-PROCESSING
90
+
91
+ # checking number of instruments in a composition
92
+ instruments_list_without_drums = list(set([y[3] for y in events_matrix1 if y[3] != 9]))
93
+ instruments_list = list(set([y[3] for y in events_matrix1]))
94
+
95
+ if len(events_matrix1) > 0 and len(instruments_list_without_drums) > 0:
96
+
97
+ #======================================
98
+
99
+ events_matrix2 = []
100
+
101
+ # Recalculating timings
102
+ for e in events_matrix1:
103
+
104
+ # Original timings
105
+ e[1] = int(e[1] / 16)
106
+ e[2] = int(e[2] / 16)
107
+
108
+ #===================================
109
+ # ORIGINAL COMPOSITION
110
+ #===================================
111
+
112
+ # Sorting by patch, pitch, then by start-time
113
+
114
+ events_matrix1.sort(key=lambda x: x[6])
115
+ events_matrix1.sort(key=lambda x: x[4], reverse=True)
116
+ events_matrix1.sort(key=lambda x: x[1])
117
+
118
+ #=======================================================
119
+ # FINAL PROCESSING
120
+
121
+ melody_chords = []
122
+ melody_chords2 = []
123
+
124
+ # Break between compositions / Intro seq
125
+
126
+ if 9 in instruments_list:
127
+ drums_present = 19331 # Yes
128
+ else:
129
+ drums_present = 19330 # No
130
+
131
+ if events_matrix1[0][3] != 9:
132
+ pat = events_matrix1[0][6]
133
+ else:
134
+ pat = 128
135
+
136
+ melody_chords.extend([19461, drums_present, 19332+pat]) # Intro seq
137
+
138
+ #=======================================================
139
+ # MAIN PROCESSING CYCLE
140
+ #=======================================================
141
+
142
+ abs_time = 0
143
+
144
+ pbar_time = 0
145
+
146
+ pe = events_matrix1[0]
147
+
148
+ chords_counter = 1
149
+
150
+ comp_chords_len = len(list(set([y[1] for y in events_matrix1])))
151
+
152
+ for e in events_matrix1:
153
+
154
+ #=======================================================
155
+ # Timings...
156
+
157
+ # Cliping all values...
158
+ delta_time = max(0, min(255, e[1]-pe[1]))
159
+
160
+ # Durations and channels
161
+
162
+ dur = max(0, min(255, e[2]))
163
+ cha = max(0, min(15, e[3]))
164
+
165
+ # Patches
166
+ if cha == 9: # Drums patch will be == 128
167
+ pat = 128
168
+
169
+ else:
170
+ pat = e[6]
171
+
172
+ # Pitches
173
+
174
+ ptc = max(1, min(127, e[4]))
175
+
176
+ # Velocities
177
+
178
+ # Calculating octo-velocity
179
+ vel = max(8, min(127, e[5]))
180
+ velocity = round(vel / 15)-1
181
+
182
+ #=======================================================
183
+ # FINAL NOTE SEQ
184
+
185
+ # Writing final note asynchronously
186
+
187
+ dur_vel = (8 * dur) + velocity
188
+ pat_ptc = (129 * pat) + ptc
189
+
190
+ melody_chords.extend([delta_time, dur_vel+256, pat_ptc+2304])
191
+ melody_chords2.append([delta_time, dur_vel+256, pat_ptc+2304])
192
+
193
+ pe = e
194
+
195
+
196
+ #==================================================================
197
+
198
+ print('=' * 70)
199
+ print('Number of tokens:', len(melody_chords))
200
+ print('Number of notes:', len(melody_chords2))
201
+ print('Sample output events', melody_chords[:5])
202
+ print('=' * 70)
203
+ print('Generating...')
204
+
205
+ #@title Pitches/Instruments Inpainting
206
+
207
+ #@markdown You can stop the inpainting at any time to render partial results
208
+
209
+ #@markdown Inpainting settings
210
+
211
+ #@markdown Select MIDI patch present in the composition to inpaint
212
+
213
+ inpaint_MIDI_patch = input_patch_number
214
+
215
+ #@markdown Generation settings
216
+
217
+ number_of_prime_tokens = 90 # @param {type:"slider", min:3, max:8190, step:3}
218
+ number_of_memory_tokens = 1024 # @param {type:"slider", min:3, max:8190, step:3}
219
+ number_of_samples_per_inpainted_note = 1 #@param {type:"slider", min:1, max:16, step:1}
220
+ temperature = 0.85
221
+
222
+ print('=' * 70)
223
+ print('Giant Music Transformer Inpainting Model Generator')
224
+ print('=' * 70)
225
+
226
+ nidx = 0
227
+
228
+ for i, m in enumerate(melody_chords):
229
+
230
+ cpatch = (melody_chords[i]-2304) // 129
231
+
232
+ if 2304 <= melody_chords[i] < 18945 and (cpatch) == inpaint_MIDI_patch:
233
+ nidx += 1
234
+
235
+ if nidx == input_num_of_notes+(number_of_prime_tokens // 3):
236
+ break
237
+
238
+ nidx = i
239
+
240
+ out2 = []
241
+
242
+ for m in melody_chords[:number_of_prime_tokens]:
243
+ out2.append(m)
244
+
245
+ for i in range(number_of_prime_tokens, len(melody_chords[:nidx])):
246
+
247
+ cpatch = (melody_chords[i]-2304) // 129
248
+
249
+ if 2304 <= melody_chords[i] < 18945 and (cpatch) == inpaint_MIDI_patch:
250
+
251
+ samples = []
252
+
253
+ for j in range(number_of_samples_per_inpainted_note):
254
+
255
+ inp = torch.LongTensor(out2[-number_of_memory_tokens:]).cuda()
256
+
257
+ with ctx:
258
+ out1 = model.generate(inp,
259
+ 1,
260
+ temperature=temperature,
261
+ return_prime=True,
262
+ verbose=False)
263
+
264
+ with torch.no_grad():
265
+ test_loss, test_acc = model(out1)
266
+
267
+ samples.append([out1.tolist()[0][-1], test_acc.tolist()])
268
+
269
+ accs = [y[1] for y in samples]
270
+ max_acc = max(accs)
271
+ max_acc_sample = samples[accs.index(max_acc)][0]
272
+
273
+ cpitch = (max_acc_sample-2304) % 129
274
+
275
+ out2.extend([((cpatch * 129) + cpitch)+2304])
276
+
277
+ else:
278
+ out2.append(melody_chords[i])
279
+
280
+ print('=' * 70)
281
+ print('Done!')
282
+ print('=' * 70)
283
+
284
+ #===============================================================================
285
+ print('Rendering results...')
286
+
287
+ print('=' * 70)
288
+ print('Sample INTs', out2[:12])
289
+ print('=' * 70)
290
+
291
+ if len(out2) != 0:
292
+
293
+ song = out2
294
+ song_f = []
295
+
296
+ time = 0
297
+ dur = 0
298
+ vel = 90
299
+ pitch = 0
300
+ channel = 0
301
+
302
+ patches = [-1] * 16
303
+
304
+ channels = [0] * 16
305
+ channels[9] = 1
306
+
307
+ for ss in song:
308
+
309
+ if 0 <= ss < 256:
310
+
311
+ time += ss * 16
312
+
313
+ if 256 <= ss < 2304:
314
+
315
+ dur = ((ss-256) // 8) * 16
316
+ vel = (((ss-256) % 8)+1) * 15
317
+
318
+ if 2304 <= ss < 18945:
319
+
320
+ patch = (ss-2304) // 129
321
+
322
+ if patch < 128:
323
+
324
+ if patch not in patches:
325
+ if 0 in channels:
326
+ cha = channels.index(0)
327
+ channels[cha] = 1
328
+ else:
329
+ cha = 15
330
+
331
+ patches[cha] = patch
332
+ channel = patches.index(patch)
333
+ else:
334
+ channel = patches.index(patch)
335
+
336
+ if patch == 128:
337
+ channel = 9
338
+
339
+ pitch = (ss-2304) % 129
340
+
341
+ song_f.append(['note', time, dur, channel, pitch, vel, patch ])
342
+
343
+ patches = [0 if x==-1 else x for x in patches]
344
+
345
+ detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(song_f,
346
+ output_signature = 'Giant Music Transformer',
347
+ output_file_name = fn1,
348
+ track_name='Project Los Angeles',
349
+ list_of_MIDI_patches=patches
350
+ )
351
+
352
+ new_fn = fn1+'.mid'
353
+
354
+
355
+ audio = midi_to_colab_audio(new_fn,
356
+ soundfont_path=soundfont,
357
+ sample_rate=16000,
358
+ volume_scale=10,
359
+ output_for_gradio=True
360
+ )
361
+
362
+ print('Done!')
363
+ print('=' * 70)
364
+
365
+ #========================================================
366
+
367
+ output_midi_title = str(fn1)
368
+ output_midi_summary = str(song_f[:3])
369
+ output_midi = str(new_fn)
370
+ output_audio = (16000, audio)
371
+
372
+ output_plot = TMIDIX.plot_ms_SONG(song_f, plot_title=output_midi, return_plt=True)
373
+
374
+ print('Output MIDI file name:', output_midi)
375
+ print('Output MIDI title:', output_midi_title)
376
+ print('Output MIDI summary:', output_midi_summary)
377
+ print('=' * 70)
378
+
379
+
380
+ #========================================================
381
+
382
+ print('-' * 70)
383
+ print('Req end time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
384
+ print('-' * 70)
385
+ print('Req execution time:', (reqtime.time() - start_time), 'sec')
386
+
387
+ return output_midi_title, output_midi_summary, output_midi, output_audio, output_plot
388
+
389
+ # =================================================================================================
390
+
391
+ if __name__ == "__main__":
392
+
393
+ PDT = timezone('US/Pacific')
394
+
395
+ print('=' * 70)
396
+ print('App start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
397
+ print('=' * 70)
398
+
399
+ soundfont = "SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2"
400
+
401
+ app = gr.Blocks()
402
+ with app:
403
+ gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Inpaint Music Transformer</h1>")
404
+ gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Inpaint pitches in any MIDI</h1>")
405
+ gr.Markdown(
406
+ "![Visitors](https://api.visitorbadge.io/api/visitors?path=asigalov61.Inpaint-Music-Transformer&style=flat)\n\n"
407
+ "This is a demo of the Giant Music Transformer pitches inpainting feature\n\n"
408
+ "Check out [Giant Music Transformer](https://github.com/asigalov61/Giant-Music-Transformer) on GitHub!\n\n"
409
+ "[Open In Colab]"
410
+ "(https://colab.research.google.com/github/asigalov61/Giant-Music-Transformer/blob/main/Giant_Music_Transformer.ipynb)"
411
+ " for all features, faster execution and endless generation"
412
+ )
413
+ gr.Markdown("## Upload your MIDI or select a sample example MIDI")
414
+
415
+ input_midi = gr.File(label="Input MIDI", file_types=[".midi", ".mid", ".kar"])
416
+ input_num_of_notes = gr.Slider(8, 2048, value=128, step=8, label="Number of composition notes to inpaint")
417
+ input_patch_number = gr.Slider(0, 127, value=0, step=1, label="Composition MIDI patch to inpaint")
418
+
419
+ run_btn = gr.Button("generate", variant="primary")
420
+
421
+ gr.Markdown("## Generation results")
422
+
423
+ output_midi_title = gr.Textbox(label="Output MIDI title")
424
+ output_midi_summary = gr.Textbox(label="Output MIDI summary")
425
+ output_audio = gr.Audio(label="Output MIDI audio", format="wav", elem_id="midi_audio")
426
+ output_plot = gr.Plot(label="Output MIDI score plot")
427
+ output_midi = gr.File(label="Output MIDI file", file_types=[".mid"])
428
+
429
+
430
+ run_event = run_btn.click(InpaintPitches, [input_midi, input_num_of_notes, input_patch_number],
431
+ [output_midi_title, output_midi_summary, output_midi, output_audio, output_plot])
432
+
433
+ gr.Examples(
434
+ [["Giant-Music-Transformer-Piano-Seed-1.mid", 128, 0],
435
+ ["Giant-Music-Transformer-Piano-Seed-2.mid", 128, 0],
436
+ ["Giant-Music-Transformer-Piano-Seed-3.mid", 128, 0],
437
+ ["Giant-Music-Transformer-Piano-Seed-4.mid", 128, 0],
438
+ ["Giant-Music-Transformer-Piano-Seed-5.mid", 128, 0],
439
+ ["Giant-Music-Transformer-Piano-Seed-6.mid", 128, 0],
440
+ ["Giant-Music-Transformer-MI-Seed-1.mid", 128, 71],
441
+ ["Giant-Music-Transformer-MI-Seed-2.mid", 128, 40],
442
+ ["Giant-Music-Transformer-MI-Seed-3.mid", 128, 40],
443
+ ["Giant-Music-Transformer-MI-Seed-4.mid", 128, 40],
444
+ ["Giant-Music-Transformer-MI-Seed-5.mid", 128, 40],
445
+ ["Giant-Music-Transformer-MI-Seed-6.mid", 128, 0]
446
+ ],
447
+ [input_midi, input_num_of_notes, input_patch_number],
448
+ [output_midi_title, output_midi_summary, output_midi, output_audio, output_plot],
449
+ InpaintPitches,
450
+ cache_examples=True,
451
+ )
452
+
453
+ app.queue().launch()
midi_to_colab_audio.py ADDED
The diff for this file is too large to render. See raw diff
 
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ fluidsynth
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch
2
+ gradio
3
+ einops