Spaces:
Sleeping
Sleeping
File size: 10,480 Bytes
3888ab7 4543735 660b28d 800d0d0 660b28d 3888ab7 2278710 3888ab7 a2c6cfa 29090fa 6df655f 06d58f4 6df655f 3888ab7 6df655f 6ccde9d 4543735 8d39a27 660b28d 4543735 2a2c4ee 4543735 660b28d 6df655f 4543735 f025921 57440b4 f7f27b0 91a38ff 57440b4 6df655f 4543735 281d949 4543735 6df655f 4543735 cf7d19c 8d39a27 f025921 6df655f f025921 980027a f025921 f626247 99fabfd b9703ed 99fabfd 79a1a3f ddf16bf de3057c 91a38ff 6ccde9d 8d39a27 91a38ff 2ec1a72 8d39a27 2a2c4ee 6df655f 37f1de7 183a2a9 37f1de7 fe65f7b 980027a 37f1de7 8d39a27 2a2c4ee 29bd92e 2a2c4ee 57440b4 f7f27b0 2a2c4ee 57440b4 f7f27b0 2a2c4ee fd58682 2a2c4ee 8d39a27 6df655f 91d5e8a fd58682 f7f27b0 99fabfd fd58682 8d39a27 fd58682 660b28d 8d39a27 fd58682 6df655f 3888ab7 800d0d0 3888ab7 eec4853 3888ab7 eec4853 a04859d 3888ab7 a04859d e30e402 a04859d 99fabfd a04859d 99fabfd d0f533f 008d8d4 d0f533f 99fabfd f025921 ddf16bf 66cd8ce 99fabfd f7f27b0 91a38ff 86dfaf8 3adc64e d0f533f 660b28d a04859d 4cdbeb8 a04859d c04453c 6ccde9d fd58682 d85cb0d 7dd6e93 |
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 |
import argparse
import glob
import os.path
import hashlib
import time
import datetime
from pytz import timezone
import gradio as gr
import pickle
import tqdm
import json
import TMIDIX
from midi_to_colab_audio import midi_to_colab_audio
import copy
from collections import Counter
import random
import statistics
import matplotlib.pyplot as plt
#==========================================================================================================
in_space = os.getenv("SYSTEM") == "spaces"
#==========================================================================================================
def render_midi(input_midi, render_type, soundfont_bank, render_sample_rate, custom_render_patch):
print('*' * 70)
print('Req start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
start_time = time.time()
print('=' * 70)
print('Loading MIDI...')
fn = os.path.basename(input_midi)
fn1 = fn.split('.')[0]
fdata = open(input_midi, 'rb').read()
input_midi_md5hash = hashlib.md5(fdata).hexdigest()
print('=' * 70)
print('Input MIDI file name:', fn)
print('Input MIDI md5 hash', input_midi_md5hash)
print('Render type:', render_type)
print('Soudnfont bank', soundfont_bank)
print('Audio render sample rate', render_sample_rate)
print('Custom MIDI render patch', custom_render_patch)
print('Melody patch', melody_patch)
print('=' * 70)
print('Processing MIDI...Please wait...')
#=======================================================
# START PROCESSING
raw_score = TMIDIX.midi2single_track_ms_score(fdata, recalculate_channels=False)
escore = TMIDIX.advanced_score_processor(raw_score, return_score_analysis=False, return_enhanced_score_notes=True)[0]
first_note_index = raw_score[1].index(escore[0][:6])
for e in escore:
e[1] = int(e[1] / 16)
e[2] = int(e[2] / 16)
# Sorting by patch, pitch, then by start-time
escore.sort(key=lambda x: x[6])
escore.sort(key=lambda x: x[4], reverse=True)
escore.sort(key=lambda x: x[1])
cscore = TMIDIX.chordify_score([1000, escore])
meta_data = raw_score[1][:first_note_index] + [escore[0]] + [escore[-1]] + [raw_score[1][-1]]
print('Done!')
print('=' * 70)
print('Input MIDI metadata:', meta_data)
print('=' * 70)
print('Processing...Please wait...')
if render_type == "Render as-is" or not render_type:
output_score = copy.deepcopy(escore)
elif render_type == "Extract melody":
output_score = copy.deepcopy([c[0] for c in cscore if c[0][3] != 9])
for e in output_score:
e[3] = 0
if e[4] < 60:
e[4] = (e[4] % 12) + 60
fixed_score = []
for i in range(len(output_score)-1):
note = output_score[i]
nmt = output_score[i+1][1]
if note[1]+note[2] >= nmt:
note_dur = nmt-note[1]-1
else:
note_dur = note[2]
fixed_score.append([note[0], note[1], note_dur, note[3], note[4], note[5], note[6]])
fixed_score.append(output_score[-1])
output_score = copy.deepcopy(fixed_score)
elif render_type == "Transform":
output_score = copy.deepcopy(escore)
for e in output_score:
if e[3] != 9:
e[4] = (127 - e[4]) - 10
elif render_type == 'Repair':
output_score = []
for c in cscore:
tones_chord = sorted(set([t[4] % 12 for t in c if t[3] != 9]))
drums_events = [t for t in c if t[3] == 9]
if tones_chord:
new_tones_chord = TMIDIX.check_and_fix_tones_chord(tones_chord)
if len(c) > 1:
output_score.extend([c[0]])
for cc in c[1:]:
if cc[3] != 9:
if (cc[4] % 12) in new_tones_chord:
output_score.extend([cc])
output_score.extend(drums_events)
else:
output_score.extend([c[0]])
else:
output_score.extend(c)
output_score.sort(key= lambda x: x[1])
print('Done processing!')
print('=' * 70)
print('Recalculating timings...')
print('=' * 70)
for e in output_score:
e[1] = e[1] * 16
e[2] = e[2] * 16
if -1 < custom_render_patch < 128:
if e[3] != 9:
e[6] = custom_render_patch
print('Done recalculating timings!')
print('=' * 70)
print('Sample output events', output_score[:5])
print('=' * 70)
print('Final processing...')
new_fn = fn1+'.mid'
patches = [-1] * 16
patches[9] = 9
for e in output_score:
if e[3] != 9:
if patches[e[3]] == -1:
patches[e[3]] = e[6]
else:
if patches[e[3]] != e[6]:
if -1 in patches:
patches[patches.index(-1)] = e[6]
else:
patches[-1] = e[6]
patches = [p if p != -1 else 0 for p in patches]
detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(output_score,
output_signature = 'Advanced MIDI Renderer',
output_file_name = fn1,
track_name='Project Los Angeles',
list_of_MIDI_patches=patches
)
if soundfont_bank in ["General MIDI", "Nice strings plus orchestra", "Real choir"]:
sf2bank = ["General MIDI", "Nice strings plus orchestra", "Real choir"].index(soundfont_bank)
else:
sf2bank = 0
if render_sample_rate in ["16000", "32000", "44100"]:
srate = int(render_sample_rate)
else:
srate = 16000
audio = midi_to_colab_audio(new_fn,
soundfont_path=soundfonts[sf2bank],
sample_rate=srate,
volume_scale=10,
output_for_gradio=True
)
new_md5_hash = hashlib.md5(open(new_fn,'rb').read()).hexdigest()
print('Done!')
print('=' * 70)
#========================================================
output_midi_md5 = str(new_md5_hash)
output_midi_title = str(fn1)
output_midi_summary = str(meta_data)
output_midi = str(new_fn)
output_audio = (srate, audio)
output_plot = TMIDIX.plot_ms_SONG(output_score, plot_title=output_midi)
print('Output MIDI file name:', output_midi)
print('Output MIDI title:', output_midi_title)
print('Output MIDI hash:', output_midi_md5)
print('Output MIDI summary:', output_midi_summary)
print('=' * 70)
#========================================================
print('Req end time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT)))
print('-' * 70)
print('Req execution time:', (time.time() - start_time), 'sec')
print('*' * 70)
#========================================================
yield output_midi_md5, 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)
parser = argparse.ArgumentParser()
parser.add_argument("--share", action="store_true", default=False, help="share gradio app")
parser.add_argument("--port", type=int, default=7860, help="gradio server port")
opt = parser.parse_args()
soundfonts = ["SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2", "Nice-Strings-PlusOrchestra-v1.6.sf2", "KBH-Real-Choir-V2.5.sf2"]
app = gr.Blocks()
with app:
gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Advanced MIDI Renderer</h1>")
gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Transform and render any MIDI</h1>")
gr.Markdown("![Visitors](https://api.visitorbadge.io/api/visitors?path=asigalov61.Advanced-MIDI-Renderer&style=flat)\n\n"
"This is a demo for tegridy-tools\n\n"
"Please see [tegridy-tools](https://github.com/asigalov61/tegridy-tools) GitHub repo for more information\n\n"
)
gr.Markdown("## Upload your MIDI")
input_midi = gr.File(label="Input MIDI", file_types=[".midi", ".mid", ".kar"], type="filepath")
gr.Markdown("## Select desired render type")
render_type = gr.Radio(["Render as-is", "Extract melody", "Transform", "Repair"], label="Render type", value="Render as-is")
gr.Markdown("## Select desired render options")
soundfont_bank = gr.Radio(["General MIDI", "Nice strings plus orchestra", "Real choir"], label="SoundFont bank", value="General MIDI")
render_sample_rate = gr.Radio(["16000", "32000", "44100"], label="MIDI audio render sample rate", value="16000")
custom_render_patch = gr.Slider(-1, 127, value=-1, label="Custom MIDI render patch")
submit = gr.Button()
gr.Markdown("## Render results")
output_midi_md5 = gr.Textbox(label="Output MIDI md5 hash")
output_midi_title = gr.Textbox(label="Output MIDI title")
output_midi_summary = gr.Textbox(label="Output MIDI summary")
output_audio = gr.Audio(label="Output MIDI audio", format="wav", 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 = submit.click(render_midi, [input_midi, render_type, soundfont_bank, render_sample_rate, custom_render_patch],
[output_midi_md5, output_midi_title, output_midi_summary, output_midi, output_audio, output_plot])
app.queue(1).launch(server_port=opt.port, share=opt.share, inbrowser=True) |