File size: 11,556 Bytes
fd4c083
0d7d207
 
 
 
 
 
 
 
75f75a1
0d7d207
 
 
 
6fce636
0d7d207
 
 
 
 
 
 
75f75a1
0d7d207
 
356c43a
75f75a1
356c43a
0d7d207
 
 
50f85db
 
98ef25e
0d7d207
 
 
 
 
 
50f85db
0d7d207
 
 
 
 
 
 
 
 
 
50f85db
0d7d207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2389791
356c43a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e762b3
356c43a
 
 
 
2e762b3
2389791
 
356c43a
 
 
 
 
 
 
 
 
 
1904770
356c43a
 
 
 
bf1555a
 
 
 
356c43a
 
 
 
0d7d207
 
6c4cb55
 
 
 
 
0d7d207
 
6c4cb55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b324ee1
6c4cb55
 
 
0d7d207
 
 
6c4cb55
9a50d02
 
7da6719
0d7d207
6c4cb55
0d7d207
b324ee1
6c4cb55
 
7da6719
9a50d02
7da6719
 
 
 
 
356c43a
1904770
0d7d207
6c4cb55
6fce636
0d7d207
6c4cb55
 
0d7d207
6c4cb55
 
 
 
7da6719
 
 
cf071b9
7da6719
 
0d7d207
6c4cb55
 
0d7d207
6c4cb55
446db64
 
7da6719
 
 
6c4cb55
 
 
 
 
 
 
7c1609a
 
 
e8f5afe
6c4cb55
 
1904770
6c4cb55
 
b40ab34
d7ec460
f166bfe
 
d7ec460
0d7d207
4d53e66
6c4cb55
0d7d207
 
7c1609a
 
0d7d207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7da6719
0d7d207
 
 
4d53e66
0d7d207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d8b6d
ab6bc31
7c1609a
0d7d207
88d8b6d
 
ab6bc31
88d8b6d
 
0d7d207
 
6d01d0c
 
0d7d207
9a50d02
aba2db8
 
9a50d02
 
6d01d0c
0d7d207
ab6bc31
0d7d207
6d01d0c
0d7d207
ace20a5
9a50d02
ace20a5
 
 
0d7d207
6d01d0c
0d7d207
 
 
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# https://huggingface.co/spaces/asigalov61/Advanced-MIDI-Classifier

import os
import time as reqtime
import datetime
from pytz import timezone

import torch

# import spaces
import gradio as gr

from x_transformer_1_23_2 import *
import random
from statistics import mode
import tqdm

from midi_to_colab_audio import midi_to_colab_audio
import TMIDIX

import matplotlib.pyplot as plt

# in_space = os.getenv("SYSTEM") == "spaces"
         
# =================================================================================================

# @spaces.GPU
def classify_GPU(input_data):

    print('Loading model...')

    SEQ_LEN = 1024
    PAD_IDX = 14627
    DEVICE = 'cpu' # 'cuda'

    # instantiate the model

    model = TransformerWrapper(
        num_tokens = PAD_IDX+1,
        max_seq_len = SEQ_LEN,
        attn_layers = Decoder(dim = 1024, depth = 12, heads = 16, attn_flash = True)
        )
    
    model = AutoregressiveWrapper(model, ignore_index = PAD_IDX)

    model.to(DEVICE)
    print('=' * 70)

    print('Loading model checkpoint...')

    model.load_state_dict(
        torch.load('Annotated_MIDI_Dataset_Classifier_Trained_Model_21269_steps_0.4335_loss_0.8716_acc.pth',
                   map_location=DEVICE))
    print('=' * 70)

    model.eval()

    if DEVICE == 'cpu':
        dtype = torch.bfloat16
    else:
        dtype = torch.bfloat16

    ctx = torch.amp.autocast(device_type=DEVICE, dtype=dtype)

    print('Done!')
    print('=' * 70)

    #==================================================================

    number_of_batches = 1 # @param {type:"slider", min:1, max:100, step:1}
    
    # @markdown NOTE: You can increase the number of batches on high-ram GPUs for better classification
    
    print('=' * 70)
    print('Annotated MIDI Dataset Classifier')
    print('=' * 70)
    print('Classifying...')
    
    torch.cuda.empty_cache()
    
    model.eval()
    
    results = []
    
    for input in input_data:
    
        x = torch.tensor([input[:1022]] * number_of_batches, dtype=torch.long, device=DEVICE)
    
        with ctx:
          out = model.generate(x,
                              1,
                              temperature=0.9,
                              filter_logits_fn=top_k,
                              filter_kwargs={'k': 1},
                              return_prime=False,
                              verbose=False)
    
        y = out.tolist()
    
        output = [l[0] for l in y]
        result = mode(output)
    
        results.append(result)

    return output, results
                       
# =================================================================================================

def ClassifyMIDI(input_midi):

    SEQ_LEN = 1024
    PAD_IDX = 14627
    
    print('=' * 70)
    print('Req start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
    start_time = reqtime.time()

    print('=' * 70)

    fn = os.path.basename(input_midi.name)
    fn1 = fn.split('.')[0]

    print('-' * 70)
    print('Input file name:', fn)

    print('=' * 70)
    print('Loading MIDI file...')
    
    midi_name = fn
    
    raw_score = TMIDIX.midi2single_track_ms_score(open(input_midi.name, 'rb').read())
    
    escore_notes = TMIDIX.advanced_score_processor(raw_score, return_enhanced_score_notes=True)[0]
    
    escore = [e for e in TMIDIX.augment_enhanced_score_notes(escore_notes, timings_divider=32) if e[6] < 80]
    
    cscore = TMIDIX.chordify_score([1000, escore])
    
    #=======================================================
    # MAIN PROCESSING CYCLE
    #=======================================================
    
    melody_chords = []
    
    pe = cscore[0][0]
    
    for c in cscore:
    
        pitches = []
    
        for e in c:
    
          if e[4] not in pitches:
    
            dtime = max(0, min(127, e[1]-pe[1]))
    
            dur = max(1, min(127, e[2]))
            ptc = max(1, min(127, e[4]))
    
            melody_chords.append([dtime, dur, ptc])
    
            pitches.append(ptc)
    
            pe = e
    
    #==============================================================
    
    seq = []
    input_data = []
    
    notes_counter = 0
    
    for mm in melody_chords:
    
        time = mm[0]
        dur = mm[1]
        ptc = mm[2]
    
        seq.extend([time, dur+128, ptc+256])
        notes_counter += 1
    
    for i in range(0, len(seq)-SEQ_LEN-4, (SEQ_LEN-4) // 4):
      schunk = seq[i:i+SEQ_LEN-4]
      input_data.append([14624] + schunk + [14625])
    
    print('Done!')
    print('=' * 70)
    
    #==============================================================

    classification_summary_string = '=' * 70
    classification_summary_string += '\n'
    
    print('Composition has', notes_counter, 'notes')
    print('=' * 70)
    print('Composition was split into' , len(input_data), 'chunks of 340 notes each with 255 notes overlap')
    print('Number of notes in all composition chunks:', len(input_data) * 340)

    classification_summary_string += 'Composition has ' + str(notes_counter) + ' notes\n'
    classification_summary_string += '=' * 70
    classification_summary_string += '\n'
    classification_summary_string += 'Composition was split into ' + str(len(input_data)) + ' chunks of 340 notes each with 170 notes overlap\n'
    classification_summary_string += 'Number of notes in all composition chunks: ' + str(len(input_data) * 340) + '\n'
    classification_summary_string += '=' * 70
    classification_summary_string += '\n'

    output, results = classify_GPU(input_data)
    
    all_results_labels = [classifier_labels[0][r-384] for r in results]
    final_result = mode(results)
    
    print('Done!')
    print('=' * 70)
    
    print('Most common classification label:', classifier_labels[0][final_result-384])
    print('Most common classification label ratio:' , results.count(final_result) / len(results))
    print('Most common classification label index', final_result)
    print('=' * 70)

    classification_summary_string += 'Most common classification label: ' + str(classifier_labels[0][final_result-384]) + '\n'
    classification_summary_string += 'Most common classification label ratio: ' + str(results.count(final_result) / len(results)) + '\n'
    classification_summary_string += 'Most common classification label index '+ str(final_result) + '\n'
    classification_summary_string += '=' * 70
    classification_summary_string += '\n'
    
    print('All classification labels summary:')
    print('=' * 70)
    
    for i, a in enumerate(all_results_labels):
        print('Notes', i*85, '-', (i*85)+340, '===', a)
        classification_summary_string += 'Notes ' + str(i*85) + ' - ' + str((i*85)+340) + ' === ' + str(a) + '\n'
    
    classification_summary_string += '=' * 70
    classification_summary_string += '\n'
    
    print('=' * 70)
    print('Done!')
    print('=' * 70)
    
    #===============================================================================
    print('Rendering results...')

    score_idx = processed_scores_labels.index(classifier_labels[0][final_result-384])

    output_score = processed_scores[score_idx][1][:6000]
    
    print('=' * 70)
    print('Sample INTs', results[:15])
    print('=' * 70)
    
    fn1 = processed_scores[score_idx][0]

    output_score = TMIDIX.recalculate_score_timings(output_score)

    output_score, patches, overflow_patches = TMIDIX.patch_enhanced_score_notes(output_score)
    
    detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(output_score,
                                                              output_signature = 'Advanced MIDI Classifier',
                                                              output_file_name = fn1,
                                                              track_name='Project Los Angeles',
                                                              list_of_MIDI_patches=patches,
                                                              timings_multiplier=16
                                                              )
    
    new_fn = fn1+'.mid'
            
    
    audio = midi_to_colab_audio(new_fn, 
                        soundfont_path=soundfont,
                        sample_rate=16000,
                        volume_scale=10,
                        output_for_gradio=True
                        )
    
    print('Done!')
    print('=' * 70)

    #========================================================

    output_midi_title = str(fn1)
    output_midi_summary = classification_summary_string
    output_midi = str(new_fn)
    output_audio = (16000, audio)
    
    output_plot = TMIDIX.plot_ms_SONG(output_score, plot_title=output_midi, return_plt=True, timings_multiplier=16)

    print('Output MIDI file name:', output_midi)
    print('Output MIDI title:', output_midi_title)
    print('=' * 70) 
    

    #========================================================
    
    print('-' * 70)
    print('Req end time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
    print('-' * 70)
    print('Req execution time:', (reqtime.time() - start_time), 'sec')

    return output_midi_title, output_midi_summary, output_midi, output_audio, output_plot

# =================================================================================================

if __name__ == "__main__":
    
    PDT = timezone('US/Pacific')
    
    print('=' * 70)
    print('App start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
    print('=' * 70)

    soundfont = "SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2"

    print('Loading Annotated MIDI Dataset processed scores...')
    processed_scores = TMIDIX.Tegridy_Any_Pickle_File_Reader('processed_scores')
    processed_scores_labels = [l[0] for l in processed_scores]
    print('=' * 70)

    print('Loading Annotated MIDI Dataset Classifier Songs Artists Labels...')
    classifier_labels = TMIDIX.Tegridy_Any_Pickle_File_Reader('Annotated_MIDI_Dataset_Classifier_Songs_Artists_Labels')
    print('=' * 70)

    app = gr.Blocks()
    with app:
        gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Advanced MIDI Classifier</h1>")
        gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Detailed MIDI classification with transformers</h1>")
        gr.Markdown(
            "![Visitors](https://api.visitorbadge.io/api/visitors?path=asigalov61.Advanced-MIDI-Classifier&style=flat)\n\n"
            "This is a demo for Annotated MIDI Dataset\n\n"
            "Check out [Annotated MIDI Dataset](https://huggingface.co/datasets/asigalov61/Annotated-MIDI-Dataset) on Hugging Face!\n\n"
        )

        input_midi = gr.File(label="Input MIDI", file_types=[".midi", ".mid", ".kar"])

        run_btn = gr.Button("classify", variant="primary")

        gr.Markdown("## Classification results")

        output_midi_title = gr.Textbox(label="Best classification match MIDI title")
        output_midi_summary = gr.Textbox(label="MIDI classification summary")
        output_audio = gr.Audio(label="Best classification match MIDI audio", format="wav", elem_id="midi_audio")
        output_plot = gr.Plot(label="Best classification match MIDI score plot")
        output_midi = gr.File(label="Best classification match MIDI file", file_types=[".mid"])

        run_event = run_btn.click(ClassifyMIDI, [input_midi],
                                  [output_midi_title, output_midi_summary, output_midi, output_audio, output_plot])

        app.queue().launch()