midi_visualizer / app.py
Next
Update app.py
614a1b3 verified
import gradio as gr
import mido
import glob
def load_javascript(dir="javascript"):
scripts_list = glob.glob(f"{dir}/*.js")
javascript = ""
for path in scripts_list:
with open(path, "r", encoding="utf8") as jsfile:
javascript += f"\n<!-- {path} --><script>{jsfile.read()}</script>"
template_response_ori = gr.routes.templates.TemplateResponse
def template_response(*args, **kwargs):
res = template_response_ori(*args, **kwargs)
res.body = res.body.replace(
b'</head>', f'{javascript}</head>'.encode("utf8"))
res.init_headers()
return res
gr.routes.templates.TemplateResponse = template_response
load_javascript()
def process_midi(file):
midi = mido.MidiFile(file.name)
events = []
for i, track in enumerate(midi.tracks):
absolute_time = 0
for msg in track:
absolute_time += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
events.append(['note', absolute_time, i, msg.time, msg.channel, msg.note, msg.velocity])
return events
def play_midi(file):
load_javascript()
events = process_midi(file)
script = f"""
<script>
const midiVisualizer = document.querySelector('midi-visualizer');
if (midiVisualizer) {{
midiVisualizer.clearMidiEvents();
{''.join([f'midiVisualizer.appendMidiEvent({event});' for event in events])}
midiVisualizer.finishAppendMidiEvent();
midiVisualizer.play();
}}
</script>
"""
return script
# Gradio Interface
load_javascript()
with gr.Blocks() as demo:
gr.Markdown("""
# MIDI Visualizer test
""")
midi_file = gr.File(label="Upload MIDI File", file_types=[".mid", ".midi", ".smf"])
play_button = gr.Button("Play MIDI")
output = gr.HTML(elem_id="midi_visualizer_container")
play_button.click(play_midi, inputs=[midi_file], outputs=[output])
demo.launch()