Spaces:
Sleeping
Sleeping
Next
commited on
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import mido
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from pydub import AudioSegment
|
| 5 |
+
from pydub.playback import play
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
def visualize_midi(midi_file):
|
| 9 |
+
# Load MIDI file
|
| 10 |
+
mid = mido.MidiFile(midi_file.name)
|
| 11 |
+
|
| 12 |
+
# Prepare to plot
|
| 13 |
+
plt.figure(figsize=(10, 4))
|
| 14 |
+
ticks = []
|
| 15 |
+
notes = []
|
| 16 |
+
|
| 17 |
+
# Extract note and tick data
|
| 18 |
+
for i, track in enumerate(mid.tracks):
|
| 19 |
+
time = 0
|
| 20 |
+
for msg in track:
|
| 21 |
+
time += msg.time
|
| 22 |
+
if not msg.is_meta and msg.type == 'note_on':
|
| 23 |
+
ticks.append(time)
|
| 24 |
+
notes.append(msg.note)
|
| 25 |
+
|
| 26 |
+
plt.scatter(ticks, notes, c='blue', marker='o')
|
| 27 |
+
plt.xlabel('Ticks')
|
| 28 |
+
plt.ylabel('Note')
|
| 29 |
+
plt.title('MIDI Visualization')
|
| 30 |
+
plt.grid(True)
|
| 31 |
+
|
| 32 |
+
# Save plot to a buffer
|
| 33 |
+
buf = io.BytesIO()
|
| 34 |
+
plt.savefig(buf, format='png')
|
| 35 |
+
buf.seek(0)
|
| 36 |
+
plt.close()
|
| 37 |
+
|
| 38 |
+
return buf
|
| 39 |
+
|
| 40 |
+
def play_midi(midi_file):
|
| 41 |
+
# Convert MIDI to audio using pydub
|
| 42 |
+
audio = AudioSegment.from_file(midi_file.name, format='mid')
|
| 43 |
+
play(audio)
|
| 44 |
+
return "Playing MIDI..."
|
| 45 |
+
|
| 46 |
+
# Create Gradio blocks interface
|
| 47 |
+
with gr.Blocks() as demo:
|
| 48 |
+
midi_input = gr.File(label="Upload MIDI File")
|
| 49 |
+
midi_visual = gr.Image(type="plot", label="MIDI Visualization")
|
| 50 |
+
play_button = gr.Button("Play MIDI")
|
| 51 |
+
|
| 52 |
+
midi_input.change(visualize_midi, inputs=midi_input, outputs=midi_visual)
|
| 53 |
+
play_button.click(play_midi, inputs=midi_input, outputs=None)
|
| 54 |
+
|
| 55 |
+
demo.launch()
|