File size: 13,751 Bytes
c1fc4e4 06f7611 c1fc4e4 0d7d207 c1fc4e4 0d7d207 6b75c99 0d7d207 33d78dd 1ae6f31 c1fc4e4 0d7d207 356c43a 547144f c171914 bf1555a 356c43a 547144f 356c43a 547144f 0d7d207 19b530f c171914 19b530f c171914 19b530f ea63137 df2f0e4 c171914 547144f c171914 38c5961 c171914 6c4cb55 19b530f c171914 09fc820 38c5961 c171914 09fc820 38c5961 09fc820 ecd66de 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 21779fc f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 f8c0b9d 38c5961 4f225bc 38c5961 f8c0b9d 09fc820 38c5961 09fc820 38c5961 09fc820 38c5961 09fc820 6c4cb55 f63089f 09fc820 f63089f c3563d1 38c5961 c3563d1 38c5961 c3563d1 38c5961 f63089f 38c5961 c3563d1 38c5961 c3563d1 2946b4a c3563d1 38c5961 f63089f c3563d1 b4ffaa9 c3563d1 38c5961 b4ffaa9 464df0b 38c5961 51e919f 464df0b 38c5961 51e919f 0d7d207 38c5961 0d7d207 f3a0ea5 19b530f 33d78dd 7fd51d1 33d78dd f3a0ea5 33d78dd f3a0ea5 33d78dd d1f9189 33d78dd f3a0ea5 33d78dd f3a0ea5 33d78dd f3a0ea5 0d7d207 06f7611 0d7d207 06f7611 e1624a5 9a50d02 547144f 464df0b 547144f c171914 c1fc4e4 174c4ab 4f225bc c171914 174c4ab 0d7d207 710f8d3 4f225bc 710f8d3 0d7d207 464df0b 174c4ab 510fa10 2b29c59 510fa10 0d7d207 c171914 547144f c171914 115a10b bb21aac d11a767 bb21aac 547144f bb21aac 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 |
# =================================================================================================
# https://huggingface.co/spaces/asigalov61/Monophonic-MIDI-Melody-Harmonizer
# =================================================================================================
import os
import time as reqtime
import datetime
from pytz import timezone
import gradio as gr
import os
import random
from tqdm import tqdm
import TMIDIX
import HaystackSearch
from midi_to_colab_audio import midi_to_colab_audio
# =================================================================================================
def Harmonize_Melody(input_src_midi,
source_melody_transpose_value,
harmonizer_melody_chunk_size,
harmonizer_max_matches_count,
melody_MIDI_patch_number,
harmonized_accompaniment_MIDI_patch_number,
base_MIDI_patch_number
):
print('=' * 70)
print('Req start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
print('=' * 70)
start_time = reqtime.time()
sfn = os.path.basename(input_src_midi.name)
sfn1 = sfn.split('.')[0]
print('Input src MIDI name:', sfn)
print('=' * 70)
print('Requested settings:')
print('Source melody transpose value:', source_melody_transpose_value)
print('Harmonizer melody chunk size:', harmonizer_melody_chunk_size)
print('Harmonizer max matrches count:', harmonizer_max_matches_count)
print('Melody MIDI patch number:', melody_MIDI_patch_number)
print('Harmonized accompaniment MIDI patch number:', harmonized_accompaniment_MIDI_patch_number)
print('Base MIDI patch number:', base_MIDI_patch_number)
print('=' * 70)
#==================================================================
print('=' * 70)
print('Loading seed melody...')
#===============================================================================
# Raw single-track ms score
raw_score = TMIDIX.midi2single_track_ms_score(input_src_midi.name)
#===============================================================================
# Enhanced score notes
escore_notes = TMIDIX.advanced_score_processor(raw_score, return_enhanced_score_notes=True)[0]
#===============================================================================
# Augmented enhanced score notes
escore_notes = TMIDIX.augment_enhanced_score_notes(escore_notes, timings_divider=16)
cscore = [c[0] for c in TMIDIX.chordify_score([1000, escore_notes])]
mel_score = TMIDIX.fix_monophonic_score_durations(TMIDIX.recalculate_score_timings(cscore))
mel_score = TMIDIX.transpose_escore_notes(mel_score, source_melody_transpose_value)
print('=' * 70)
print('Done!')
print('=' * 70)
mel_pitches = [p[4] % 12 for p in mel_score]
print('Melody has', len(mel_pitches), 'notes')
print('=' * 70)
#==================================================================
print('=' * 70)
print('Melody Harmonizer')
print('=' * 70)
print('=' * 70)
print('Harmonizing...')
print('=' * 70)
#===============================================================================
song = []
csize = harmonizer_melody_chunk_size
matches_mem_size = harmonizer_max_matches_count
i = 0
dev = 0
dchunk = []
#===============================================================================
def find_best_match(matches):
mlens = []
for sidx in matches:
mlen = len(TMIDIX.flatten(long_chords_chunks_mult[sidx[0]][sidx[1]:sidx[1]+(csize // 2)]))
mlens.append(mlen)
max_len = max(mlens)
max_len_idx = mlens.index(max_len)
return matches[max_len_idx]
#===============================================================================
while i < len(mel_pitches):
matches = []
for midx, mel in enumerate(long_mels_chunks_mult):
if len(mel) >= csize:
schunk = mel_pitches[i:i+csize]
idx = HaystackSearch.HaystackSearch(schunk, mel)
if idx != -1:
matches.append([midx, idx])
if matches_mem_size > -1:
if len(matches) > matches_mem_size:
break
if matches:
sidx = find_best_match(matches)
fchunk = long_chords_chunks_mult[sidx[0]][sidx[1]:sidx[1]+csize]
song.extend(fchunk[:(csize // 2)])
i += (csize // 2)
dchunk = fchunk
dev = 0
print('step', i)
else:
if dchunk:
song.append(dchunk[(csize // 2)+dev])
dev += 1
i += 1
print('dead chord', i, dev)
else:
print('DEAD END!!!')
song.append([mel_pitches[0]+48])
break
if dev == csize // 2:
print('DEAD END!!!')
break
song = song[:len(mel_pitches)]
print('Harmonized', len(song), 'out of', len(mel_pitches), 'notes')
print('Done!')
print('=' * 70)
#===============================================================================
print('Rendering results...')
print('=' * 70)
output_score = []
time = 0
patches = [0] * 16
patches[0] = harmonized_accompaniment_MIDI_patch_number
if base_MIDI_patch_number > -1:
patches[2] = base_MIDI_patch_number
patches[3] = melody_MIDI_patch_number
for i, s in enumerate(song):
time = mel_score[i][1] * 16
dur = mel_score[i][2] * 16
output_score.append(['note', time, dur, 3, mel_score[i][4], 115+(mel_score[i][4] % 12), 40])
for p in s:
output_score.append(['note', time, dur, 0, p, max(40, p), harmonized_accompaniment_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])
fn1 = "Monophonic-MIDI-Melody-Harmonizer-Composition"
detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(output_score,
output_signature = 'Monophonic MIDI Melody Harmonizer',
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!')
#========================================================
harmonization_summary_string = '=' * 70
harmonization_summary_string += '\n'
harmonization_summary_string += 'Source melody has ' + str(len(mel_pitches)) + ' monophonic pitches' + '\n'
harmonization_summary_string += '=' * 70
harmonization_summary_string += '\n'
harmonization_summary_string += 'Harmonized ' + str(len(song)) + ' out of ' + str(len(mel_pitches)) + ' source melody pitches' + '\n'
harmonization_summary_string += '=' * 70
harmonization_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, harmonization_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 Monster Harmonized Melodies MIDI Dataset...')
print('=' * 70)
all_chords_chunks = TMIDIX.Tegridy_Any_Pickle_File_Reader('Monster_Harmonized_Melodies_MIDI_Dataset')
print('=' * 70)
print('Total number of harmonized melodies:', len(all_chords_chunks))
print('=' * 70)
print('Loading melodies...')
long_mels_chunks_mult = []
long_chords_chunks_mult = []
for c in tqdm(all_chords_chunks):
long_mels_chunks_mult.append([p % 12 for p in c[0]])
long_chords_chunks_mult.append(c[1])
print('Done!')
print('=' * 70)
print('Total loaded melodies count:', len(long_mels_chunks_mult))
print('=' * 70)
#===============================================================================
app = gr.Blocks()
with app:
gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Monophonic MIDI Melody Harmonizer</h1>")
gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Retrieval augmented harmonization of any MIDI melody</h1>")
gr.Markdown(
"![Visitors](https://api.visitorbadge.io/api/visitors?path=asigalov61.Monophonic-MIDI-Melody-Harmonizer&style=flat)\n\n"
"This is a demo for Monster MIDI Dataset\n\n"
"Check out [Monster MIDI Dataset](https://github.com/asigalov61/Monster-MIDI-Dataset) on GitHub!\n\n"
)
gr.Markdown("## Upload your MIDI or select a sample example below")
gr.Markdown("### For best results upload only monophonic melody MIDIs")
input_src_midi = gr.File(label="Source MIDI", file_types=[".midi", ".mid", ".kar"])
gr.Markdown("## Select harmonization options")
source_melody_transpose_value = gr.Slider(-6, 6, value=0, step=1, label="Source melody transpose value", info="You can transpose source melody by specified number of semitones if the original melody key does not harmonize well")
harmonizer_melody_chunk_size = gr.Slider(4, 16, value=8, step=2, label="Hamonizer melody chunk size", info="Larger chunk sizes result in better harmonization at the cost of speed and harminzation length")
harmonizer_max_matches_count = gr.Slider(-1, 20, value=0, step=1, label="Harmonizer max matches count", info="Maximum number of harmonized chords per melody note to collect and to select from")
melody_MIDI_patch_number = gr.Slider(0, 127, value=40, step=1, label="Source melody MIDI patch number")
harmonized_accompaniment_MIDI_patch_number = gr.Slider(0, 127, value=0, step=1, label="Harmonized accompaniment MIDI patch number")
base_MIDI_patch_number = gr.Slider(-1, 127, value=35, step=1, label="Base MIDI patch number")
gr.Markdown("## PLEASE NOTE:")
gr.Markdown("### 1) Harmonization may take a long time which is dependent on the melody length and selected harmonization settings")
gr.Markdown("### 2) If harmonization fails, reduce harmonized melody chunk size value in settings above")
run_btn = gr.Button("Harmonize Melody", variant="primary")
gr.Markdown("## Harmonization results")
output_summary = gr.Textbox(label="Melody harmonization summary")
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"])
run_event = run_btn.click(Harmonize_Melody,
[input_src_midi,
source_melody_transpose_value,
harmonizer_melody_chunk_size,
harmonizer_max_matches_count,
melody_MIDI_patch_number,
harmonized_accompaniment_MIDI_patch_number,
base_MIDI_patch_number],
[output_audio, output_plot, output_midi, output_summary]
)
gr.Examples(
[
["USSR Anthem Seed Melody.mid", 0, 12, -1, 40, 0, 35],
],
[input_src_midi,
source_melody_transpose_value,
harmonizer_melody_chunk_size,
harmonizer_max_matches_count,
melody_MIDI_patch_number,
harmonized_accompaniment_MIDI_patch_number,
base_MIDI_patch_number],
[output_audio, output_plot, output_midi, output_summary],
Harmonize_Melody,
cache_examples=True,
)
app.queue().launch() |