import gradio as gr from fastapi import FastAPI, Request import json # ✅ Create FastAPI App app = FastAPI() # ✅ MIDI Processing Function in Python @app.post("/midi_input") async def process_midi(request: Request): try: midi_data = await request.json() note = midi_data["note"] velocity = midi_data["velocity"] print(f"🎹 Received MIDI Note: {note}, Velocity: {velocity}") # 🚀 Process MIDI data (example: Transpose + Generate New Notes) generated_note = (note + 5) % 128 # Transpose up by 3 semitones generated_velocity = min(velocity + 10, 127) # Increase velocity slightly # ✅ Send MIDI Response Back to Client return { "status": "success", "generated_note": generated_note, "generated_velocity": generated_velocity, "original_note": note } except Exception as e: print(f"🚨 Error processing MIDI: {str(e)}") return {"status": "error", "message": str(e)} @app.post("/midi_phrase") async def process_midi_phrase(request: Request): try: data = await request.json() phrase = data["phrase"] # List of MIDI notes print(f"🎹 Received MIDI Phrase ({len(phrase)} notes)") # 🚀 Process Phrase: Example - Transpose Each Note Up by 3 Semitones generated_phrase = [ { "note": (note["note"] + 3) % 128, "velocity": note["velocity"], "duration": note["duration"], # ✅ Keep original duration "inter_onset": note["inter_onset"] # ✅ Keep inter-onset time } for note in phrase ] return {"status": "success", "generated_phrase": generated_phrase} except Exception as e: print(f"🚨 Error processing MIDI phrase: {str(e)}") return {"status": "error", "message": str(e)} # ✅ JavaScript to Capture and Send MIDI Data midi_js = """
""" # ✅ Inject JavaScript and HTML with gr.Blocks() as demo: gr.HTML(midi_js) # ✅ Mount FastAPI with Gradio app = gr.mount_gradio_app(app, demo, path="/") if __name__ == "__main__": import uvicorn print("🚀 Starting FastAPI with Gradio...") uvicorn.run(app, host="0.0.0.0", port=7860)