File size: 1,988 Bytes
cdafe9e
08f1390
 
cdafe9e
 
08f1390
 
cdafe9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08f1390
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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):
    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
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()