Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import tempfile
|
| 3 |
+
import os
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
from basic_pitch.inference import predict
|
| 7 |
+
from basic_pitch import ICASSP_2022_MODEL_PATH
|
| 8 |
+
import pretty_midi
|
| 9 |
+
|
| 10 |
+
def audio_to_midi(audio_url: str, instrument: str):
|
| 11 |
+
try:
|
| 12 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 13 |
+
audio_path = os.path.join(tmp, "input.wav")
|
| 14 |
+
|
| 15 |
+
# Download audio
|
| 16 |
+
r = requests.get(audio_url, timeout=30)
|
| 17 |
+
r.raise_for_status()
|
| 18 |
+
with open(audio_path, "wb") as f:
|
| 19 |
+
f.write(r.content)
|
| 20 |
+
|
| 21 |
+
# Run Basic Pitch
|
| 22 |
+
_, midi_data, _ = predict(
|
| 23 |
+
audio_path,
|
| 24 |
+
model_path=ICASSP_2022_MODEL_PATH
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
notes = []
|
| 28 |
+
for inst in midi_data.instruments:
|
| 29 |
+
for n in inst.notes:
|
| 30 |
+
notes.append({
|
| 31 |
+
"pitch": int(n.pitch),
|
| 32 |
+
"startTime": round(n.start, 4),
|
| 33 |
+
"duration": round(n.end - n.start, 4),
|
| 34 |
+
"velocity": int(n.velocity)
|
| 35 |
+
})
|
| 36 |
+
|
| 37 |
+
return {
|
| 38 |
+
"instrument": instrument,
|
| 39 |
+
"notes": notes
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return {
|
| 44 |
+
"error": str(e),
|
| 45 |
+
"notes": []
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
with gr.Blocks() as demo:
|
| 49 |
+
gr.Markdown("## Audio → MIDI API")
|
| 50 |
+
audio_input = gr.Textbox(label="Audio URL")
|
| 51 |
+
instr_input = gr.Textbox(label="Instrument")
|
| 52 |
+
output = gr.JSON()
|
| 53 |
+
|
| 54 |
+
btn = gr.Button("Convert")
|
| 55 |
+
btn.click(fn=audio_to_midi, inputs=[audio_input, instr_input], outputs=output)
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
demo.launch(
|
| 59 |
+
ssr_mode=False,
|
| 60 |
+
theme=gr.themes.Soft(
|
| 61 |
+
primary_hue="indigo",
|
| 62 |
+
secondary_hue="blue",
|
| 63 |
+
),
|
| 64 |
+
)
|