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"
template_response_ori = gr.routes.templates.TemplateResponse
def template_response(*args, **kwargs):
res = template_response_ori(*args, **kwargs)
res.body = res.body.replace(
b'', f'{javascript}'.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):
events = process_midi(file)
script = f"""
"""
return script
# Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("""
# MIDI Visualizer
Upload a MIDI file to visualize the notes.
""")
midi_file = gr.File(label="Upload MIDI File", file_types=[".mid", ".midi"])
play_button = gr.Button("Play MIDI")
output = gr.HTML()
play_button.click(play_midi, inputs=midi_file, outputs=output)
demo.launch()