asigalov61 commited on
Commit
3a735ad
·
verified ·
1 Parent(s): 90bf448

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -198
app.py CHANGED
@@ -30,8 +30,8 @@ def Text_to_Music(input_title, input_num_tokens, input_prompt_type):
30
 
31
  print('Loading model...')
32
 
33
- SEQ_LEN = 8192 # Models seq len
34
- PAD_IDX = 767 # Models pad index
35
  DEVICE = 'cuda' # 'cuda'
36
 
37
  # instantiate the model
@@ -39,7 +39,7 @@ def Text_to_Music(input_title, input_num_tokens, input_prompt_type):
39
  model = TransformerWrapper(
40
  num_tokens = PAD_IDX+1,
41
  max_seq_len = SEQ_LEN,
42
- attn_layers = Decoder(dim = 2048, depth = 4, heads = 16, attn_flash = True)
43
  )
44
 
45
  model = AutoregressiveWrapper(model, ignore_index = PAD_IDX)
@@ -50,7 +50,7 @@ def Text_to_Music(input_title, input_num_tokens, input_prompt_type):
50
  print('Loading model checkpoint...')
51
 
52
  model.load_state_dict(
53
- torch.load('Ultimate_Accompaniment_Transformer_Small_Improved_Trained_Model_13649_steps_0.3229_loss_0.898_acc.pth',
54
  map_location=DEVICE))
55
  print('=' * 70)
56
 
@@ -66,253 +66,186 @@ def Text_to_Music(input_title, input_num_tokens, input_prompt_type):
66
  print('Done!')
67
  print('=' * 70)
68
 
69
- fn = os.path.basename(input_midi.name)
70
- fn1 = fn.split('.')[0]
71
-
72
- input_num_tokens = max(4, min(128, input_num_tokens))
73
 
74
  print('-' * 70)
75
- print('Input file name:', fn)
76
  print('Req num toks:', input_num_tokens)
77
- print('Force acc:', input_acc_type)
78
  print('-' * 70)
79
 
80
  #===============================================================================
81
- raw_score = TMIDIX.midi2single_track_ms_score(input_midi.name)
82
-
83
- #===============================================================================
84
- # Enhanced score notes
85
-
86
- escore_notes = TMIDIX.advanced_score_processor(raw_score, return_enhanced_score_notes=True)[0]
87
-
88
- escore_notes = [e for e in escore_notes if e[3] != 9]
89
-
90
- if len(escore_notes) > 0:
91
-
92
- #=======================================================
93
- # PRE-PROCESSING
94
-
95
- #===============================================================================
96
- # Augmented enhanced score notes
97
-
98
- escore_notes = TMIDIX.augment_enhanced_score_notes(escore_notes, timings_divider=32)
99
-
100
- cscore = TMIDIX.chordify_score([1000, escore_notes])
101
-
102
- melody = TMIDIX.fix_monophonic_score_durations([sorted(e, key=lambda x: x[4], reverse=True)[0] for e in cscore])
103
-
104
- #=======================================================
105
- # FINAL PROCESSING
106
-
107
- melody_chords = []
108
-
109
- #=======================================================
110
- # MAIN PROCESSING CYCLE
111
- #=======================================================
112
-
113
- pe = cscore[0][0]
114
-
115
- mpe = melody[0]
116
-
117
- midx = 1
118
-
119
- for i, c in enumerate(cscore):
120
-
121
- c.sort(key=lambda x: (x[3], x[4]), reverse=True)
122
-
123
- # Next melody note
124
-
125
- if midx < len(melody):
126
-
127
- # Time
128
- mtime = melody[midx][1]-mpe[1]
129
-
130
- mdur = melody[midx][2]
131
-
132
- mdelta_time = max(0, min(127, mtime))
133
-
134
- # Durations
135
- mdur = max(0, min(127, mdur))
136
-
137
- # Pitch
138
- mptc = melody[midx][4]
139
-
140
- else:
141
- mtime = 127-mpe[1]
142
-
143
- mdur = mpe[2]
144
-
145
- mdelta_time = max(0, min(127, mtime))
146
-
147
- # Durations
148
- mdur = max(0, min(127, mdur))
149
-
150
- # Pitch
151
- mptc = mpe[4]
152
-
153
-
154
- e = melody[i]
155
-
156
- #=======================================================
157
- # Timings...
158
-
159
- time = e[1]-pe[1]
160
-
161
- dur = e[2]
162
-
163
- delta_time = max(0, min(127, time))
164
 
165
- # Durations
 
166
 
167
- dur = max(0, min(127, dur))
 
 
168
 
169
- # Pitches
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
- ptc = max(1, min(127, e[4]))
 
 
 
172
 
173
- if ptc < 60:
174
- ptc = 60 + (ptc % 12)
175
 
176
- cha = e[3]
177
 
178
- #=======================================================
179
- # FINAL NOTE SEQ
180
 
181
- if midx < len(melody):
182
- melody_chords.append([delta_time, dur+128, ptc+384, mdelta_time+512, mptc+640])
183
- mpe = melody[midx]
184
- midx += 1
185
- else:
186
- melody_chords.append([delta_time, dur+128, ptc+384, mdelta_time+512, mptc+640])
187
 
188
- pe = e
189
-
190
- #===============================================================================
191
 
192
  print('=' * 70)
193
-
194
- print('Sample output events', melody_chords[:5])
195
  print('=' * 70)
196
- print('Generating...')
197
-
198
- output = []
199
 
200
- force_acc = input_acc_type
201
- num_toks_per_note = 32
202
- temperature=0.9
203
- max_drums_limit=4
204
- num_memory_tokens=4096
205
-
206
- output1 = []
207
- output2 = []
208
 
209
-
210
- for m in melody_chords[:input_num_tokens]:
211
-
212
- output1.extend(m)
213
-
214
- input_seq = output1
215
-
216
- if force_acc:
217
- x = torch.LongTensor([input_seq+[0]]).cuda()
218
- else:
219
- x = torch.LongTensor([input_seq]).cuda()
220
 
221
- time = input_seq[-2]-512
 
222
 
223
- cur_time = 0
 
 
224
 
225
- for _ in range(num_toks_per_note):
226
- with ctx:
227
- out = model.generate(x[-num_memory_tokens:],
228
- 1,
229
- temperature=temperature,
230
- return_prime=False,
231
- verbose=False)
232
 
233
- o = out.tolist()[0][0]
234
 
235
- if 0 <= o < 128:
236
- cur_time += o
237
 
238
- if cur_time < time and o < 384:
 
 
 
 
 
239
 
240
- out = torch.LongTensor([[o]]).cuda()
241
- x = torch.cat((x, out), 1)
242
- else:
243
- break
244
 
245
- outy = x.tolist()[0][len(input_seq):]
246
-
247
- output1.extend(outy)
248
- output2.append(outy)
249
-
250
  print('=' * 70)
251
  print('Done!')
252
  print('=' * 70)
253
 
254
  #===============================================================================
255
  print('Rendering results...')
256
-
257
- print('=' * 70)
258
- print('Sample INTs', output1[:12])
259
  print('=' * 70)
 
 
260
 
261
- out1 = output2
262
-
263
- accompaniment_MIDI_patch_number = 0
264
- melody_MIDI_patch_number = 40
265
 
266
- if len(out1) != 0:
267
 
268
- song = out1
269
- song_f = []
270
 
271
- time = 0
272
- ntime = 0
273
- ndur = 0
274
- vel = 90
275
- npitch = 0
276
- channel = 0
277
 
278
- patches = [0] * 16
279
- patches[0] = accompaniment_MIDI_patch_number
280
- patches[3] = melody_MIDI_patch_number
281
 
282
- for i, ss in enumerate(song):
 
 
 
 
283
 
284
- ntime += melody_chords[i][0] * 32
285
- ndur = (melody_chords[i][1]-128) * 32
286
- nchannel = 1
287
- npitch = (melody_chords[i][2]-256) % 128
288
- vel = max(40, npitch)+20
289
 
290
- song_f.append(['note', ntime, ndur, 3, npitch, vel, melody_MIDI_patch_number ])
291
 
292
- time = ntime
293
 
294
- for s in ss:
295
 
296
- if 0 <= s < 128:
297
 
298
- time += s * 32
299
 
300
- if 128 <= s < 256:
301
 
302
- dur = (s-128) * 32
 
 
 
 
 
 
 
303
 
304
- if 256 <= s < 384:
305
 
306
- pitch = (s-256)
307
 
308
- vel = max(40, pitch)
309
 
310
- song_f.append(['note', time, dur, 0, pitch, vel, accompaniment_MIDI_patch_number])
311
 
312
- fn1 = "Ultimate-Accompaniment-Transformer-Composition"
313
 
314
  detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(song_f,
315
- output_signature = 'Ultimate Accompaniment Transformer',
316
  output_file_name = fn1,
317
  track_name='Project Los Angeles',
318
  list_of_MIDI_patches=patches
@@ -333,7 +266,7 @@ def Text_to_Music(input_title, input_num_tokens, input_prompt_type):
333
 
334
  #========================================================
335
 
336
- output_midi_title = str(fn1)
337
  output_midi_summary = str(song_f[:3])
338
  output_midi = str(new_fn)
339
  output_audio = (16000, audio)
@@ -342,7 +275,7 @@ def Text_to_Music(input_title, input_num_tokens, input_prompt_type):
342
 
343
  print('Output MIDI file name:', output_midi)
344
  print('Output MIDI title:', output_midi_title)
345
- print('Output MIDI summary:', '')
346
  print('=' * 70)
347
 
348
 
@@ -390,7 +323,7 @@ if __name__ == "__main__":
390
 
391
  gr.Markdown("## Generation results")
392
 
393
- output_midi_title = gr.Textbox(label="Output MIDI title")
394
  output_midi_summary = gr.Textbox(label="Output MIDI summary")
395
  output_audio = gr.Audio(label="Output MIDI audio", format="wav", elem_id="midi_audio")
396
  output_plot = gr.Plot(label="Output MIDI score plot")
 
30
 
31
  print('Loading model...')
32
 
33
+ SEQ_LEN = 4096 # Models seq len
34
+ PAD_IDX = 2571 # Models pad index
35
  DEVICE = 'cuda' # 'cuda'
36
 
37
  # instantiate the model
 
39
  model = TransformerWrapper(
40
  num_tokens = PAD_IDX+1,
41
  max_seq_len = SEQ_LEN,
42
+ attn_layers = Decoder(dim = 2048, depth = 8, heads = 16, attn_flash = True)
43
  )
44
 
45
  model = AutoregressiveWrapper(model, ignore_index = PAD_IDX)
 
50
  print('Loading model checkpoint...')
51
 
52
  model.load_state_dict(
53
+ torch.load('Text_to_Music_Transformer_Medium_Trained_Model_33934_steps_0.6093_loss_0.813_acc.pth',
54
  map_location=DEVICE))
55
  print('=' * 70)
56
 
 
66
  print('Done!')
67
  print('=' * 70)
68
 
69
+ input_num_tokens = max(8, min(2048, input_num_tokens))
 
 
 
70
 
71
  print('-' * 70)
72
+ print('Input title:', input_title)
73
  print('Req num toks:', input_num_tokens)
74
+ print('Open-ended prompt:', input_prompt_type)
75
  print('-' * 70)
76
 
77
  #===============================================================================
78
+
79
+ print('Setting up model patches and loading helper functions...')
80
+
81
+ # @title Setup and load model channels MIDI patches
82
+
83
+ model_channel_0_piano_family = "Acoustic Grand" # @param ["Acoustic Grand", "Bright Acoustic", "Electric Grand", "Honky-Tonk", "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clav"]
84
+ model_channel_1_chromatic_percussion_family = "Music Box" # @param ["Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer"]
85
+ model_channel_2_organ_family = "Church Organ" # @param ["Drawbar Organ", "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica", "Tango Accordion"]
86
+ model_channel_3_guitar_family = "Acoustic Guitar(nylon)" # @param ["Acoustic Guitar(nylon)", "Acoustic Guitar(steel)", "Electric Guitar(jazz)", "Electric Guitar(clean)", "Electric Guitar(muted)", "Overdriven Guitar", "Distortion Guitar", "Guitar Harmonics"]
87
+ model_channel_4_bass_family = "Fretless Bass" # @param ["Acoustic Bass", "Electric Bass(finger)", "Electric Bass(pick)", "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2"]
88
+ model_channel_5_strings_family = "Violin" # @param ["Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp", "Timpani"]
89
+ model_channel_6_ensemble_family = "Choir Aahs" # @param ["String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2", "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit"]
90
+ model_channel_7_brass_family = "Trumpet" # @param ["Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2"]
91
+ model_channel_8_reed_family = "Alto Sax" # @param ["Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet"]
92
+ model_channel_9_pipe_family = "Flute" # @param ["Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Skakuhachi", "Whistle", "Ocarina"]
93
+ model_channel_10_synth_lead_family = "Lead 8 (bass+lead)" # @param ["Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)", "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)"]
94
+ model_channel_11_synth_pad_family = "Pad 2 (warm)" # @param ["Pad 1 (new age)", "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)", "Pad 7 (halo)", "Pad 8 (sweep)"]
95
+ model_channel_12_synth_effects_family = "FX 3 (crystal)" # @param ["FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)"]
96
+ model_channel_13_ethnic_family = "Banjo" # @param ["Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bagpipe", "Fiddle", "Shanai"]
97
+ model_channel_14_percussive_family = "Melodic Tom" # @param ["Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal"]
98
+ model_channel_15_sound_effects_family = "Bird Tweet" # @param ["Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter", "Applause", "Gunshot"]
99
+ model_channel_16_drums_family = "Drums" # @param ["Drums"]
100
+
101
+ print('=' * 70)
102
+ print('Loading helper functions...')
103
+
104
+ def txt2tokens(txt):
105
+ return [ord(char)+2440 if 0 < ord(char) < 128 else 0+2440 for char in txt.lower()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
+ def tokens2txt(tokens):
108
+ return [chr(tok-2440) for tok in tokens if 0+2440 < tok < 128+2440 ]
109
 
110
+ print('=' * 70)
111
+ print('Setting up patches...')
112
+ print('=' * 70)
113
 
114
+ instruments = [v[1] for v in TMIDIX.Number2patch.items()]
115
+
116
+ patches = [instruments.index(model_channel_0_piano_family),
117
+ instruments.index(model_channel_1_chromatic_percussion_family),
118
+ instruments.index(model_channel_2_organ_family),
119
+ instruments.index(model_channel_3_guitar_family),
120
+ instruments.index(model_channel_4_bass_family),
121
+ instruments.index(model_channel_5_strings_family),
122
+ instruments.index(model_channel_6_ensemble_family),
123
+ instruments.index(model_channel_7_brass_family),
124
+ instruments.index(model_channel_8_reed_family),
125
+ 9, # Drums patch
126
+ instruments.index(model_channel_9_pipe_family),
127
+ instruments.index(model_channel_10_synth_lead_family),
128
+ instruments.index(model_channel_11_synth_pad_family),
129
+ instruments.index(model_channel_12_synth_effects_family),
130
+ instruments.index(model_channel_13_ethnic_family),
131
+ instruments.index(model_channel_15_sound_effects_family)
132
+ ]
133
 
134
+ print('Done!')
135
+ print('=' * 70)
136
+
137
+ print('Generating...')
138
 
139
+ #@title Standard Text-to-Music Generator
 
140
 
141
+ #@markdown Prompt settings
142
 
143
+ song_title_prompt = input_title
144
+ open_ended_prompt = input_prompt_type
145
 
146
+ #@markdown Generation settings
 
 
 
 
 
147
 
148
+ number_of_tokens_to_generate = input_num_tokens
149
+ number_of_batches_to_generate = 1 #@param {type:"slider", min:1, max:16, step:1}
150
+ temperature = 0.9 # @param {type:"slider", min:0.1, max:1, step:0.05}
151
 
152
  print('=' * 70)
153
+ print('Text-to-Music Model Generator')
 
154
  print('=' * 70)
 
 
 
155
 
156
+ if song_title_prompt == '':
157
+ outy = [2569]
 
 
 
 
 
 
158
 
159
+ else:
160
+ if open_ended_prompt:
161
+ outy = [2569] + txt2tokens(song_title_prompt)
 
 
 
 
 
 
 
 
162
 
163
+ else:
164
+ outy = [2569] + txt2tokens(song_title_prompt) + [2570]
165
 
166
+ print('Selected prompt sequence:')
167
+ print(outy[:12])
168
+ print('=' * 70)
169
 
170
+ torch.cuda.empty_cache()
 
 
 
 
 
 
171
 
172
+ inp = [outy] * number_of_batches_to_generate
173
 
174
+ inp = torch.LongTensor(inp).cuda()
 
175
 
176
+ with ctx:
177
+ out = model.generate(inp,
178
+ number_of_tokens_to_generate,
179
+ temperature=temperature,
180
+ return_prime=True,
181
+ verbose=False)
182
 
183
+ out0 = out.tolist()
 
 
 
184
 
 
 
 
 
 
185
  print('=' * 70)
186
  print('Done!')
187
  print('=' * 70)
188
 
189
  #===============================================================================
190
  print('Rendering results...')
 
 
 
191
  print('=' * 70)
192
+
193
+ out1 = out0[i]
194
 
195
+ print('Sample INTs', out1[:12])
196
+ print('=' * 70)
 
 
197
 
198
+ generated_song_title = ''.join(tokens2txt(out1)).title()
199
 
200
+ print('Generated song title:', generated_song_title)
201
+ print('=' * 70)
202
 
203
+ if len(out1) != 0:
 
 
 
 
 
204
 
205
+ song = out1
206
+ song_f = []
 
207
 
208
+ time = 0
209
+ dur = 0
210
+ vel = 90
211
+ pitch = 0
212
+ channel = 0
213
 
214
+ for ss in song:
 
 
 
 
215
 
216
+ if 0 <= ss < 128:
217
 
218
+ time += ss * 32
219
 
220
+ if 128 <= ss < 256:
221
 
222
+ dur = (ss-128) * 32
223
 
224
+ if 256 <= ss < 2432:
225
 
226
+ chan = (ss-256) // 128
227
 
228
+ if chan < 9:
229
+ channel = chan
230
+ elif 9 < chan < 15:
231
+ channel = chan+1
232
+ elif chan == 15:
233
+ channel = 15
234
+ elif chan == 16:
235
+ channel = 9
236
 
237
+ pitch = (ss-256) % 128
238
 
239
+ if 2432 <= ss < 2440:
240
 
241
+ vel = (((ss-2432)+1) * 15)-1
242
 
243
+ song_f.append(['note', time, dur, channel, pitch, vel, chan*8 ])
244
 
245
+ fn1 = "Text-to-Music-Transformer-Composition"
246
 
247
  detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(song_f,
248
+ output_signature = 'Text-to-Music Transformer',
249
  output_file_name = fn1,
250
  track_name='Project Los Angeles',
251
  list_of_MIDI_patches=patches
 
266
 
267
  #========================================================
268
 
269
+ output_midi_title = generated_song_title
270
  output_midi_summary = str(song_f[:3])
271
  output_midi = str(new_fn)
272
  output_audio = (16000, audio)
 
275
 
276
  print('Output MIDI file name:', output_midi)
277
  print('Output MIDI title:', output_midi_title)
278
+ print('Output MIDI summary:', output_midi_summary)
279
  print('=' * 70)
280
 
281
 
 
323
 
324
  gr.Markdown("## Generation results")
325
 
326
+ output_midi_title = gr.Textbox(label="Generated MIDI title")
327
  output_midi_summary = gr.Textbox(label="Output MIDI summary")
328
  output_audio = gr.Audio(label="Output MIDI audio", format="wav", elem_id="midi_audio")
329
  output_plot = gr.Plot(label="Output MIDI score plot")