Spaces:
Sleeping
Sleeping
Next
commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,10 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
| 2 |
import glob
|
| 3 |
|
| 4 |
-
def load_javascript():
|
| 5 |
-
scripts_list = glob.glob("
|
| 6 |
javascript = ""
|
| 7 |
for path in scripts_list:
|
| 8 |
with open(path, "r", encoding="utf8") as jsfile:
|
|
@@ -19,3 +21,47 @@ def load_javascript():
|
|
| 19 |
gr.routes.templates.TemplateResponse = template_response
|
| 20 |
|
| 21 |
load_javascript()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import mido
|
| 3 |
+
|
| 4 |
import glob
|
| 5 |
|
| 6 |
+
def load_javascript(dir="javascript"):
|
| 7 |
+
scripts_list = glob.glob(f"{dir}/*.js")
|
| 8 |
javascript = ""
|
| 9 |
for path in scripts_list:
|
| 10 |
with open(path, "r", encoding="utf8") as jsfile:
|
|
|
|
| 21 |
gr.routes.templates.TemplateResponse = template_response
|
| 22 |
|
| 23 |
load_javascript()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def process_midi(file):
|
| 28 |
+
midi = mido.MidiFile(file.name)
|
| 29 |
+
events = []
|
| 30 |
+
|
| 31 |
+
for i, track in enumerate(midi.tracks):
|
| 32 |
+
absolute_time = 0
|
| 33 |
+
for msg in track:
|
| 34 |
+
absolute_time += msg.time
|
| 35 |
+
if msg.type == 'note_on' and msg.velocity > 0:
|
| 36 |
+
events.append(['note', absolute_time, i, msg.time, msg.channel, msg.note, msg.velocity])
|
| 37 |
+
|
| 38 |
+
return events
|
| 39 |
+
|
| 40 |
+
def play_midi(file):
|
| 41 |
+
events = process_midi(file)
|
| 42 |
+
script = f"""
|
| 43 |
+
<script>
|
| 44 |
+
const midiVisualizer = document.querySelector('midi-visualizer');
|
| 45 |
+
if (midiVisualizer) {{
|
| 46 |
+
midiVisualizer.clearMidiEvents();
|
| 47 |
+
{''.join([f'midiVisualizer.appendMidiEvent({event});' for event in events])}
|
| 48 |
+
midiVisualizer.finishAppendMidiEvent();
|
| 49 |
+
midiVisualizer.play();
|
| 50 |
+
}}
|
| 51 |
+
</script>
|
| 52 |
+
"""
|
| 53 |
+
return script
|
| 54 |
+
|
| 55 |
+
# Gradio Interface
|
| 56 |
+
with gr.Blocks() as demo:
|
| 57 |
+
gr.Markdown("""
|
| 58 |
+
# MIDI Visualizer
|
| 59 |
+
Upload a MIDI file to visualize the notes.
|
| 60 |
+
""")
|
| 61 |
+
midi_file = gr.File(label="Upload MIDI File", file_types=[".mid", ".midi"])
|
| 62 |
+
play_button = gr.Button("Play MIDI")
|
| 63 |
+
output = gr.HTML()
|
| 64 |
+
|
| 65 |
+
play_button.click(play_midi, inputs=midi_file, outputs=output)
|
| 66 |
+
|
| 67 |
+
demo.launch()
|