File size: 16,377 Bytes
c1fc4e4
1ae6f31
c1fc4e4
0d7d207
 
 
 
 
 
 
 
c1fc4e4
 
 
0d7d207
c1fc4e4
ecd66de
6b75c99
0d7d207
 
1ae6f31
c1fc4e4
 
0d7d207
356c43a
1e4e336
ecd66de
115a10b
7594447
115a10b
 
 
 
bf1555a
356c43a
 
 
 
0d7d207
19b530f
1e4e336
ecd66de
19b530f
74d6d93
19b530f
 
 
ea63137
 
df2f0e4
 
 
19b530f
6c4cb55
19b530f
09fc820
 
 
 
 
0d7d207
09fc820
f8c0b9d
09fc820
f8c0b9d
09fc820
f8c0b9d
 
 
 
 
 
ecd66de
f8c0b9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecd66de
 
f8c0b9d
 
 
 
 
 
 
 
 
 
 
 
 
 
ecd66de
 
 
 
 
09fc820
 
 
 
 
 
 
 
6c4cb55
09fc820
6c4cb55
 
 
f63089f
 
09fc820
f63089f
 
c3563d1
 
 
 
 
b4ffaa9
c3563d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f63089f
c3563d1
 
 
 
 
 
b4ffaa9
c3563d1
 
 
 
 
b7bd104
 
 
 
7594447
74d6d93
7594447
92e004d
7594447
c3563d1
 
 
 
 
 
f63089f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3563d1
b4ffaa9
 
 
 
c3563d1
 
b4ffaa9
 
 
c3563d1
 
f63089f
51e919f
 
 
 
 
 
 
 
b4ffaa9
 
 
51e919f
 
fb790c1
 
 
51e919f
 
fb790c1
 
 
51e919f
 
c292aa6
bc9a4ca
 
1b74287
51e919f
1b74287
bc9a4ca
 
 
51e919f
bc9a4ca
 
 
 
51e919f
 
1b74287
bc9a4ca
 
 
1b74287
 
bc9a4ca
 
 
1b74287
51e919f
1b74287
bc9a4ca
1b74287
bc9a4ca
1b74287
bc9a4ca
 
0d7d207
 
 
 
 
 
 
c3563d1
0d7d207
 
 
 
 
 
 
 
 
 
 
f3a0ea5
 
19b530f
 
48bf7f7
7fd51d1
48bf7f7
f3a0ea5
 
 
 
 
d1f9189
 
f3a0ea5
 
 
 
 
 
 
 
 
 
0d7d207
 
c1fc4e4
 
0d7d207
c1fc4e4
 
 
1f738c2
c1fc4e4
 
9a50d02
 
c1fc4e4
 
1e4e336
d894956
115a10b
7d3e6c3
115a10b
 
 
0d7d207
115a10b
0d7d207
c1fc4e4
510fa10
2b29c59
510fa10
 
0d7d207
115a10b
 
 
1e4e336
ecd66de
115a10b
7594447
115a10b
 
 
510fa10
115a10b
c1fc4e4
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
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
# =================================================================================================
# https://huggingface.co/spaces/asigalov61/Chords-Progressions-Generator
# =================================================================================================

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

import gradio as gr

import numpy as np

import os
import random
from collections import Counter
import math
from tqdm import tqdm

import TMIDIX

from midi_to_colab_audio import midi_to_colab_audio

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

def Generate_Chords_Progression(minimum_song_length_in_chords_chunks,
                                chords_chunks_memory_ratio,
                                chord_time_step,
                                merge_chords_notes,
                                melody_MIDI_patch_number,
                                chords_progression_MIDI_patch_number,
                                base_MIDI_patch_number
                               ):

    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('Minimum song length in chords chunks:', minimum_song_length_in_chords_chunks)
    print('Chords chunks memory ratio:', chords_chunks_memory_ratio)
    print('Chord time step:', chord_time_step)
    print('Merge chords notes max time:', merge_chords_notes)
    print('Melody MIDI patch number:', melody_MIDI_patch_number)
    print('Chords progression MIDI patch number:', chords_progression_MIDI_patch_number)
    print('Base MIDI patch number:', base_MIDI_patch_number)
    print('=' * 70)
    
    #==================================================================

    print('=' * 70)
    print('Pitches Chords Progressions Generator')
    print('=' * 70)

    print('=' * 70)
    print('Chunk-by-chunk generation')
    print('=' * 70)
    print('Generating...')
    print('=' * 70)
    
    matching_long_chords_chunks = []
    
    ridx = random.randint(0, len(all_long_chords_tokens_chunks)-1)
    
    matching_long_chords_chunks.append(ridx)
    
    max_song_len = 0
    
    tries = 0
    
    while len(matching_long_chords_chunks) < minimum_song_length_in_chords_chunks:

        matching_long_chords_chunks = []
    
        ridx = random.randint(0, len(all_long_chords_tokens_chunks)-1)
    
        matching_long_chords_chunks.append(ridx)
        seen = [ridx]
        gseen = [ridx]
    
        for a in range(minimum_song_length_in_chords_chunks * 10):
    
          if not matching_long_chords_chunks:
            break
    
          if len(matching_long_chords_chunks) > minimum_song_length_in_chords_chunks:
            break
    
          schunk = all_long_chords_tokens_chunks[matching_long_chords_chunks[-1]]
          trg_long_chunk = np.array(schunk[-chunk_size:])
          idxs = np.where((src_long_chunks == trg_long_chunk).all(axis=1))[0].tolist()
    
          if len(idxs) > 1:
    
            random.shuffle(idxs)
    
            eidxs = [i for i in idxs if i not in seen]
    
            if eidxs:
              eidx = eidxs[0]
              matching_long_chords_chunks.append(eidx)
              seen.append(eidx)
              gseen.append(eidx)
    
              if 0 < chords_chunks_memory_ratio < 1:
                seen = random.choices(gseen, k=math.ceil(len(gseen) * chords_chunks_memory_ratio))
              elif chords_chunks_memory_ratio == 0:
                seen = []
    
            else:
                gseen.pop()
                matching_long_chords_chunks.pop()
    
          else:
            gseen.pop()
            matching_long_chords_chunks.pop()
    
    
        if len(matching_long_chords_chunks) > max_song_len:
          print('Current song length:', len(matching_long_chords_chunks), 'chords chunks')
          print('=' * 70)
          final_song = matching_long_chords_chunks
    
        max_song_len = max(max_song_len, len(matching_long_chords_chunks))
    
        tries += 1
    
        if tries % 500 == 0:
          print('Number of passed tries:', tries)
          print('=' * 70)

    if len(matching_long_chords_chunks) > max_song_len:
      print('Current song length:', len(matching_long_chords_chunks), 'chords chunks')
      print('=' * 70)
      final_song = matching_long_chords_chunks
    
    f_song = []
    
    for mat in final_song:
      f_song.extend(all_long_good_chords_chunks[mat][:-chunk_size])
    f_song.extend(all_long_good_chords_chunks[mat][-chunk_size:])
    
    print('Generated final song after', tries, 'tries with', len(final_song), 'chords chunks and', len(f_song), 'chords')
    print('=' * 70)

    print('Done!')
    print('=' * 70)
    
    #===============================================================================
    
    print('Rendering results...')
    print('=' * 70)

    output_score = []
    
    time = 0
    
    patches = [0] * 16
    patches[0] = chords_progression_MIDI_patch_number
    
    if base_MIDI_patch_number > -1:
      patches[2] = base_MIDI_patch_number
    
    if melody_MIDI_patch_number > -1:
      patches[3] = melody_MIDI_patch_number
    
    chords_labels = []
    
    for i, s in enumerate(f_song):
    
      time += chord_time_step
    
      dur = chord_time_step
    
      chord_str = str(i+1)
    
      for t in sorted(set([t % 12 for t in s])):
        chord_str += '-' + str(t)
    
      chords_labels.append(['text_event', time, chord_str])
    
      for p in s:
        output_score.append(['note', time, dur, 0, p, max(40, p), chords_progression_MIDI_patch_number])
                    
      if base_MIDI_patch_number > -1:
        output_score.append(['note', time, dur, 2, (s[-1] %  12)+24, 120-(s[-1] %  12), base_MIDI_patch_number])
    
    if melody_MIDI_patch_number > -1:
      output_score = TMIDIX.add_melody_to_enhanced_score_notes(output_score, 
                                                               melody_patch=melody_MIDI_patch_number,
                                                               melody_notes_max_duration=max(merge_chords_notes, chord_time_step)
                                                              )

    if merge_chords_notes > 0:
        escore_matrix = TMIDIX.escore_notes_to_escore_matrix(output_score)
        output_score = TMIDIX.escore_matrix_to_merged_escore_notes(escore_matrix, max_note_duration=merge_chords_notes)
        
    midi_score = sorted(chords_labels + output_score, key=lambda x: x[1])

    fn1 = "Pitches-Chords-Progression-Composition"
    
    detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(midi_score,
                                                              output_signature = 'Pitches Chords Progression',
                                                              output_file_name = fn1,
                                                              track_name='Project Los Angeles',
                                                              list_of_MIDI_patches=patches
                                                              )
    
    new_fn = fn1+'.mid'
            
    
    audio = midi_to_colab_audio(new_fn, 
                        soundfont_path=soundfont,
                        sample_rate=16000,
                        volume_scale=10,
                        output_for_gradio=True
                        )
    
    #========================================================

    output_midi_title = str(fn1)
    output_midi = str(new_fn)
    output_audio = (16000, audio)
    
    output_plot = TMIDIX.plot_ms_SONG(output_score, plot_title=output_midi, return_plt=True)
    
    print('Done!')
    print('=' * 70)
    
    #========================================================

    print('Generated chords progression info and stats:')
    print('=' * 70)

    chords_progression_summary_string = '=' * 70
    chords_progression_summary_string += '\n'

    all_song_chords = []
    
    for pc in f_song:
      tones_chord = tuple(sorted(set([p % 12 for p in pc])))
      all_song_chords.append([pc, tones_chord])
    
    print('=' * 70)
    print('Total number of chords:', len(all_song_chords))
    chords_progression_summary_string += 'Total number of chords: ' + str(len(all_song_chords)) + '\n'
    chords_progression_summary_string += '=' * 70
    chords_progression_summary_string += '\n'
    print('=' * 70)
    print('Most common pitches chord:', list(Counter(tuple([a[0] for a in all_song_chords])).most_common(1)[0][0]), '===', Counter(tuple([a[0] for a in all_song_chords])).most_common(1)[0][1], 'count')
    chords_progression_summary_string += 'Most common pitches chord: ' + str(list(Counter(tuple([a[0] for a in all_song_chords])).most_common(1)[0][0])) + ' === ' + str(Counter(tuple([a[0] for a in all_song_chords])).most_common(1)[0][1]) + ' count' + '\n'
    chords_progression_summary_string += '=' * 70
    chords_progression_summary_string += '\n'
    print('=' * 70)
    print('Most common tones chord:', list(Counter(tuple([a[1] for a in all_song_chords])).most_common(1)[0][0]), '===', Counter(tuple([a[1] for a in all_song_chords])).most_common(1)[0][1], 'count')
    chords_progression_summary_string += 'Most common tones chord: ' + str(list(Counter(tuple([a[1] for a in all_song_chords])).most_common(1)[0][0])) + ' === ' + str(Counter(tuple([a[1] for a in all_song_chords])).most_common(1)[0][1]) + ' count' + '\n'
    chords_progression_summary_string += '=' * 70
    chords_progression_summary_string += '\n'    
    print('=' * 70)
    print('Sorted unique songs chords set:', len(sorted(set(tuple([a[1] for a in all_song_chords])))), 'count')
    chords_progression_summary_string += 'Sorted unique songs chords set: ' + str(len(sorted(set(tuple([a[1] for a in all_song_chords]))))) +  ' count' + '\n'
    chords_progression_summary_string += '=' * 70
    chords_progression_summary_string += '\n'
    #print('=' * 70)
    for c in sorted(set(tuple([a[1] for a in all_song_chords]))):
        #print(list(c))
        chords_progression_summary_string += str(list(c)) + '\n'
    chords_progression_summary_string += '=' * 70
    chords_progression_summary_string += '\n'
    print('=' * 70)
    print('Grouped songs chords set:', len(TMIDIX.grouped_set(tuple([a[1] for a in all_song_chords]))), 'count')
    chords_progression_summary_string += 'Grouped songs chords set: ' + str(len(TMIDIX.grouped_set(tuple([a[1] for a in all_song_chords])))) + ' count' + '\n'
    chords_progression_summary_string += '=' * 70
    chords_progression_summary_string += '\n'
    print('=' * 70)
    for c in TMIDIX.grouped_set(tuple([a[1] for a in all_song_chords])):
        #print(list(c))
        chords_progression_summary_string += str(list(c)) + '\n'
    chords_progression_summary_string += '=' * 70
    chords_progression_summary_string += '\n'
    #print('=' * 70)
    #print('All songs chords')
    chords_progression_summary_string += 'All songs chords' + '\n'
    chords_progression_summary_string += '=' * 70
    chords_progression_summary_string += '\n'
    #print('=' * 70)
    for i, pc_tc in enumerate(all_song_chords):
        #print('Song chord #', i)
        chords_progression_summary_string += 'Song chord # ' + str(i) + '\n'
        #print(list(pc_tc[0]), '===', list(pc_tc[1]))
        chords_progression_summary_string += str(list(pc_tc[0])) + ' === ' + str(list(pc_tc[1])) + '\n'
        #print('=' * 70)
        chords_progression_summary_string += '=' * 70
        chords_progression_summary_string += '\n'
    #========================================================
    
    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, chords_progression_summary_string

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

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 processed Pitches Chords Progressions dataset data...')
    print('=' * 70)
    long_tones_chords_dict, all_long_chords_tokens_chunks, all_long_good_chords_chunks = TMIDIX.Tegridy_Any_Pickle_File_Reader('processed_chords_progressions_chunks_data')
    
    print('=' * 70)
    print('Resulting chords dictionary size:', len(long_tones_chords_dict))
    print('=' * 70)
    print('Loading chords chunks...')

    chunk_size = 4
    
    src_long_chunks = np.array([a[:chunk_size] for a in all_long_chords_tokens_chunks])
    
    print('Done!')
    print('=' * 70)
    print('Total chords chunks count:', len(all_long_good_chords_chunks))
    print('=' * 70)
    
    #===============================================================================
    
    app = gr.Blocks()
    with app:
        gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Chords Progressions Generator</h1>")
        gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Generate unique chords progressions</h1>")
        gr.Markdown(
            "![Visitors](https://api.visitorbadge.io/api/visitors?path=asigalov61.Chords-Progressions-Generator&style=flat)\n\n"
            "This is a demo for Tegridy MIDI Dataset\n\n"
            "Check out [Tegridy MIDI Dataset](https://github.com/asigalov61/Tegridy-MIDI-Dataset) on GitHub!\n\n"
            "[Open In Colab]"
            "(https://colab.research.google.com/github/asigalov61/Tegridy-MIDI-Dataset/blob/master/Chords-Progressions/Pitches_Chords_Progressions_Generator.ipynb)"
            " for all options, faster execution and endless generation"
        )

        gr.Markdown("## Select generation options")

        minimum_song_length_in_chords_chunks = gr.Slider(4, 60, value=30, step=1, label="Minimum song length in chords chunks")
        chords_chunks_memory_ratio = gr.Slider(0, 1, value=1, step=0.1, label="Chords chunks memory ratio")
        chord_time_step = gr.Slider(100, 1000, value=500, step=50, label="Chord time step")
        merge_chords_notes = gr.Slider(0, 4000, value=1000, step=100, label="Merged chords notes max time")
        melody_MIDI_patch_number = gr.Slider(0, 127, value=40, step=1, label="Melody MIDI patch number")
        chords_progression_MIDI_patch_number = gr.Slider(0, 127, value=0, step=1, label="Chords progression MIDI patch number")
        base_MIDI_patch_number = gr.Slider(0, 127, value=35, step=1, label="Base MIDI patch number")

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

        gr.Markdown("## Generation results")
        
        output_audio = gr.Audio(label="Output MIDI audio", format="mp3", elem_id="midi_audio")
        output_plot = gr.Plot(label="Output MIDI score plot")
        output_midi = gr.File(label="Output MIDI file", file_types=[".mid"])

        output_cp_summary = gr.Textbox(label="Generated chords progression info and stats")

        run_event = run_btn.click(Generate_Chords_Progression, 
                                                              [minimum_song_length_in_chords_chunks,
                                                                chords_chunks_memory_ratio,
                                                                chord_time_step,
                                                                merge_chords_notes,
                                                                melody_MIDI_patch_number,
                                                                chords_progression_MIDI_patch_number,
                                                                base_MIDI_patch_number],                                                                                                                       
                                                               [output_audio, output_plot, output_midi, output_cp_summary]
                                 )
   
        app.queue().launch()