File size: 15,100 Bytes
a3ef88a
a5da942
4d440f4
a3ef88a
16dca97
36ecd1e
16dca97
a3ef88a
36ecd1e
a3ef88a
 
cee38fa
d0604a0
7dd2cd1
 
 
 
a3ef88a
36ecd1e
a3ef88a
 
 
 
 
b2f373f
a3ef88a
 
 
 
 
 
 
b9ced4c
 
a3ef88a
b8ca4b2
a3ef88a
 
 
 
 
 
 
987c189
 
a3ef88a
36ecd1e
a3ef88a
 
 
 
4154701
a3ef88a
 
 
 
 
 
 
 
 
 
3a23894
7dd057d
465603c
053cdcc
a3ef88a
b8e4da9
da6ee62
a3ef88a
 
47be7bd
7dd057d
47be7bd
 
 
 
 
 
 
7dd057d
 
 
 
 
 
 
 
 
 
 
 
47be7bd
 
7dd057d
47be7bd
 
 
 
7dd057d
47be7bd
7dd057d
47be7bd
7dd057d
47be7bd
 
 
 
 
 
e02c3f7
0792426
 
7dd057d
 
a3ef88a
7dd057d
 
a3ef88a
7dd057d
 
6b6f593
7dd057d
 
6b6f593
7dd057d
 
 
 
 
 
 
 
 
 
2cb6a42
7dd057d
2cb6a42
7dd057d
 
a3ef88a
7dd057d
 
 
 
 
 
 
 
 
 
 
a3ef88a
 
 
d0604a0
 
 
 
 
9cd9938
d0604a0
 
 
 
 
 
4154701
0403a1b
773571c
 
d0604a0
a3ef88a
98cb603
cee38fa
e084a2b
 
 
 
 
 
cee38fa
 
 
 
 
1ad380e
cee38fa
 
 
e084a2b
cee38fa
 
 
 
 
 
 
 
74b9db5
 
 
 
 
 
 
 
cee38fa
 
 
 
 
 
 
 
 
e084a2b
 
 
cee38fa
 
 
 
98cb603
 
 
 
 
a3ef88a
98cb603
 
b8ca4b2
 
06f05a8
773571c
98cb603
bc6831a
98cb603
 
 
bc6831a
98cb603
9cd9938
 
0403a1b
 
 
 
 
98cb603
eb9280b
 
778a081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cd9938
 
 
b8e4da9
151dbdb
 
 
b81318c
9cd9938
 
 
 
 
 
 
 
 
 
 
 
 
ea6350b
89b00b1
527be6f
 
 
 
9cd9938
 
da6ee62
9cd9938
 
 
eb9280b
 
 
 
89b00b1
 
773571c
 
 
 
a5db927
 
92b3ee4
98cb603
 
 
a3ef88a
98cb603
a3ef88a
98cb603
a3ef88a
bc6831a
98cb603
 
a3ef88a
98cb603
da6ee62
a3ef88a
98cb603
a3ef88a
98cb603
 
 
20a4294
98cb603
 
20a4294
 
 
 
da6ee62
 
20a4294
 
 
 
 
ea6350b
20a4294
 
 
 
 
 
 
 
 
 
 
98cb603
da6ee62
7dd2cd1
ea6350b
 
 
a81680a
 
 
ea6350b
36ecd1e
98cb603
 
36ecd1e
98cb603
 
20a4294
98cb603
bc6831a
98cb603
 
 
 
96ba707
98cb603
 
 
 
 
 
930090d
 
98cb603
dd9d99a
98cb603
 
89b00b1
a3ef88a
da6ee62
98cb603
 
 
a3ef88a
98cb603
 
 
bc6831a
98cb603
bc6831a
a3ef88a
89b00b1
98cb603
a3ef88a
 
8edbfbe
 
 
 
 
 
5c91d9e
 
a3ef88a
205c7b8
5c91d9e
 
a5da942
 
9748eb8
 
36ecd1e
aeee50c
14b9312
 
 
 
 
5c91d9e
2c6a087
8586ed2
7dd057d
a3ef88a
b8e4da9
a3ef88a
601785e
a3ef88a
 
151dbdb
a3ef88a
 
 
601785e
a3ef88a
601785e
 
89b00b1
7df01ae
 
d0604a0
7dd057d
773571c
 
a3ef88a
92b3ee4
7e1768b
89b00b1
 
7e1768b
a3ef88a
98cb603
8edbfbe
 
b506373
8edbfbe
 
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#==================================================================================
# https://huggingface.co/spaces/asigalov61/Karaoke-Transformer
#==================================================================================

print('=' * 70)
print('Karaoke Transformer Gradio App')

print('=' * 70)
print('Loading core Karaoke Transformer modules...')

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

print('=' * 70)
print('Loading main Karaoke Transformer modules...')

os.environ['USE_FLASH_ATTENTION'] = '1'

import torch

torch.set_float32_matmul_precision('medium')
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
torch.backends.cuda.enable_mem_efficient_sdp(True)
torch.backends.cuda.enable_math_sdp(True)
torch.backends.cuda.enable_flash_sdp(True)
torch.backends.cuda.enable_cudnn_sdp(True)

from huggingface_hub import hf_hub_download

import TMIDIX
import SyllablesSearch

from midi_to_colab_audio import midi_to_colab_audio

from x_transformer_1_23_2 import *

import random

import tqdm

print('=' * 70)
print('Loading aux Karaoke Transformer modules...')

import matplotlib.pyplot as plt

import gradio as gr
import spaces

print('=' * 70)
print('PyTorch version:', torch.__version__)
print('=' * 70)
print('Done!')
print('Enjoy! :)')
print('=' * 70)

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

KAR_MODEL_CHECKPOINT = 'Karaoke_Transformer_Lyr2Mel_Trained_Model_3910_steps_0.186_loss_0.9456_acc.pth'
ACC_MODEL_CHECKPOINT = 'Guided_Accompaniment_Transformer_Trained_Model_36457_steps_0.5384_loss_0.8417_acc.pth'

SOUDFONT_PATH = 'SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2'

MAX_NUM_GEN_WORDS = 56

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

print('=' * 70)
print('Instantiating karaoke model...')

device_type = 'cuda'
dtype = 'bfloat16'

ptdtype = {'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
ctx = torch.amp.autocast(device_type=device_type, dtype=ptdtype)

SEQ_LEN = 3072
PAD_IDX = 20387

kar_model = TransformerWrapper(
            num_tokens = PAD_IDX+1,
            max_seq_len = SEQ_LEN,
            attn_layers = Decoder(dim = 1024,
                                  depth = 4,
                                  heads = 32,
                                  rotary_pos_emb = True,
                                  attn_flash = True
                                  )
)

kar_model = AutoregressiveWrapper(kar_model, ignore_index=PAD_IDX, pad_value=PAD_IDX)

print('=' * 70)
print('Loading model checkpoint...')      

kar_model_checkpoint = hf_hub_download(repo_id='asigalov61/Karaoke-Transformer', filename=KAR_MODEL_CHECKPOINT)

kar_model.load_state_dict(torch.load(kar_model_checkpoint, map_location='cpu', weights_only=True))

kar_model = torch.compile(kar_model, mode='max-autotune')

print('=' * 70)
print('Done!')
print('=' * 70)
print('Model will use', dtype, 'precision...')
print('=' * 70)

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

print('=' * 70)
print('Instantiating accompaniment model...')

device_type = 'cuda'
dtype = 'bfloat16'

ptdtype = {'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
ctx = torch.amp.autocast(device_type=device_type, dtype=ptdtype)

SEQ_LEN = 4096
PAD_IDX = 1794

acc_model = TransformerWrapper(
            num_tokens = PAD_IDX+1,
            max_seq_len = SEQ_LEN,
            attn_layers = Decoder(dim = 2048,
                                  depth = 4,
                                  heads = 32,
                                  rotary_pos_emb = True,
                                  attn_flash = True
                                  )
)

acc_model = AutoregressiveWrapper(acc_model, ignore_index=PAD_IDX, pad_value=PAD_IDX)

print('=' * 70)
print('Loading model checkpoint...')      

acc_model_checkpoint = hf_hub_download(repo_id='asigalov61/Guided-Accompaniment-Transformer', filename=ACC_MODEL_CHECKPOINT)

acc_model.load_state_dict(torch.load(acc_model_checkpoint, map_location='cpu', weights_only=True))

acc_model = torch.compile(acc_model, mode='max-autotune')

print('=' * 70)
print('Done!')
print('=' * 70)
print('Model will use', dtype, 'precision...')
print('=' * 70)

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

print('Loading karaoke words list and dict...')

kar_words_list_dict_pickle = hf_hub_download(repo_id='asigalov61/Karaoke-Transformer', filename='all_words_list_dict.pickle')

with open(kar_words_list_dict_pickle, 'rb') as f:
    all_words_list, all_words_dict = pickle.load(f)

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

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

@spaces.GPU
def Generate_Karaoke(input_lyrics,
                     model_temperature,
                     model_sampling_top_k
                    ):

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

    def generate_full_seq(input_seq, 
                          max_toks=3072, 
                          temperature=0.9, 
                          top_k_value=15, 
                          verbose=True
                         ):
    
        seq_abs_run_time = sum([t for t in input_seq if t < 128])
    
        cur_time = 0
    
        full_seq = copy.deepcopy(input_seq)
    
        toks_counter = 0
    
        while cur_time <= seq_abs_run_time+32:
    
            if verbose:
                if toks_counter % 128 == 0:
                    print('Generated', toks_counter, 'tokens')
    
            x = torch.LongTensor(full_seq).cuda()
    
            with ctx:
                out = acc_model.generate(x,
                                         1,
                                         filter_logits_fn=top_k,
                                         filter_kwargs={'k': top_k_value},
                                         temperature=temperature,
                                         return_prime=False,
                                         verbose=False
                                        )
            
            y = out.tolist()[0][0]
    
            if y < 128:
                cur_time += y
    
            full_seq.append(y)
    
            toks_counter += 1

            if toks_counter == max_toks:
                return full_seq
    
        return full_seq

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

    print('Requested settings:')
    print('=' * 70)
    print('Input lyrics:', input_lyrics)
    print('=' * 70)
    print('Model temperature:', model_temperature)
    print('Model top k:', model_sampling_top_k)
    print('=' * 70)

    #==================================================================
    
    print('=' * 70)
    print('Generating...')

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

    kar_model.to(device_type)
    kar_model.eval()

    acc_model.to(device_type)
    acc_model.eval()

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

    lyric_toks = [20384]

    if input_lyrics != '':

        lyrics_clean = TMIDIX.clean_string(input_lyrics.replace('\n', ' '), regex='[^a-zA-Z ]').lower().strip()
        syl_toks = [s for s in SyllablesSearch.split_words(lyrics_clean.split(' ')) if s != ' ']
    
        for l in syl_toks:
            if l in all_words_list:
                lyric_toks.append(all_words_dict[tuple(l)]+384)
        
        lyric_toks.append(20385)
    
    #==================================================================

    x = torch.LongTensor(lyric_toks).cuda()
    
    with ctx:
        out = kar_model.generate(x,
                                 768,
                                 temperature=model_temperature,
                                 filter_logits_fn=top_k,
                                 filter_kwargs={'k': model_sampling_top_k},
                                 return_prime=False,
                                 eos_token=20386,
                                 verbose=True)
    
    y = out.tolist()

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

    decoded_lyrics = []

    for tok in y[0]:
        if 383 < tok < 20384:
            decoded_lyrics.append(all_words_list[tok-384])

    decoded_lyrics = decoded_lyrics[:MAX_NUM_GEN_WORDS]

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

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

    score = [t for t in y[0] if t < 384][:MAX_NUM_GEN_WORDS*3]

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

    start_score_seq = [1792] + score + [1793]

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

    print('Generating accompaniment...')

    input_seq = generate_full_seq(start_score_seq, 
                                  temperature=model_temperature, 
                                  top_k_value=model_sampling_top_k
                                 )

    final_song = input_seq[len(start_score_seq):]
   
    print('=' * 70)
    print('Done!')
    print('=' * 70)
    
    #===============================================================================
    
    print('Rendering results...')
    
    print('=' * 70)
    print('Sample INTs', final_song[:15])
    print('=' * 70)

    song_f = []
    psong_f = []
    
    if len(final_song) != 0:
    
        time = 0
        dur = 0
        vel = 90
        pitch = 0
        channel = 0
        patch = 0
    
        channels_map = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 9, 12, 13, 14, 15]
        patches_map = [40, 0, 10, 19, 24, 35, 40, 52, 56, 9, 65, 73, 0, 0, 0, 0]
        velocities_map = [125, 80, 100, 80, 90, 100, 100, 80, 110, 110, 110, 110, 80, 80, 80, 80]

        widx = 0
    
        for m in final_song:
    
            if 0 <= m < 128:
                time += m * 32
                
            elif 128 < m < 256:
                dur = (m-128) * 32
    
            elif 256 < m < 1792:
                cha = (m-256) // 128
                pitch = (m-256) % 128
    
                channel = channels_map[cha]
                patch = patches_map[channel]
                vel = velocities_map[channel]
    
                song_f.append(['note', time, dur, channel, pitch, vel, patch])
                psong_f.append(['note', time, dur, channel, pitch, vel, patch])

                if cha == 0:
                    song_f.append(['lyric', time, decoded_lyrics[widx]])
                    widx += 1

                    if widx == len(decoded_lyrics):
                        break
                
    fn1 = "Karaoke-Transformer-Composition"
    
    detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(song_f,
                                                              output_signature = 'Karaoke Transformer',
                                                              output_file_name = fn1,
                                                              track_name='Project Los Angeles',
                                                              list_of_MIDI_patches=patches_map
                                                              )
    
    new_fn = fn1+'.mid'
            
    
    audio = midi_to_colab_audio(new_fn, 
                        soundfont_path=SOUDFONT_PATH,
                        sample_rate=16000,
                        volume_scale=10,
                        output_for_gradio=True
                        )
    
    print('Done!')
    print('=' * 70)

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

    output_midi = str(new_fn)
    output_audio = (16000, audio)
    output_lyrics = ' '.join(decoded_lyrics)
    
    output_plot = TMIDIX.plot_ms_SONG(psong_f, plot_title=output_midi, return_plt=True)

    print('Output MIDI file name:', output_midi)
    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_audio, output_plot, output_midi, output_lyrics
    
#==================================================================================

PDT = timezone('US/Pacific')

print('=' * 70)
print('App start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
print('=' * 70)

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

with gr.Blocks() as demo:

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

    gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Karaoke Transformer</h1>")
    gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Generate Karaoke MIDI composition from any lyrics</h1>")
    gr.HTML("""            
            <p> 
                <a href="https://huggingface.co/spaces/asigalov61/Karaoke-Transformer?duplicate=true">
                    <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-md.svg" alt="Duplicate in Hugging Face">
                </a>
            </p>
            
            for faster execution and endless generation!
            """)
    
    #==================================================================================
    
    gr.Markdown("## Enter desired lyrics below")
    
    input_lyrics = gr.Textbox(label="Input lyrics", value="So close no matter how far\nCould not be much more from the heart\nForever trusting who we are\nAnd nothing else matters")
    
    gr.Markdown("## Generation options")
    
    model_temperature = gr.Slider(0.1, 1, value=0.9, step=0.01, label="Model temperature")
    model_sampling_top_k = gr.Slider(1, 100, value=5, step=1, label="Model sampling top k value")
    
    generate_btn = gr.Button("Generate", variant="primary")

    gr.Markdown("## Generation results")
    
    output_audio = gr.Audio(label="MIDI audio", format="wav", elem_id="midi_audio")
    output_plot = gr.Plot(label="MIDI score plot")
    output_lyrics = gr.Textbox(label="MIDI lyrics")
    output_midi = gr.File(label="MIDI file", file_types=[".mid"])
    
    generate_btn.click(Generate_Karaoke, 
                       [input_lyrics, 
                        model_temperature,
                        model_sampling_top_k
                       ], 
                       [output_audio,
                        output_plot,
                        output_midi,
                        output_lyrics
                       ]
                      )
        
#==================================================================================

demo.launch()

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