from fastapi import FastAPI, UploadFile, File from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse, JSONResponse from midi_utils import process_midi # We no longer need os or ROOT_PATH here, keeping the code clean. # Uvicorn with --proxy-headers will handle the path prefix automatically. app = FastAPI( title="MIDI Processor API", description="A pure API backend to process MIDI files, running correctly behind a proxy.", version="1.0.2", # Version updated for the final fix ) # --- CORS Middleware (no change) --- origins = ["*"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # --- API Endpoints (no change) --- @app.get("/", tags=["General"]) def read_root(): # The /docs link will now work correctly without us manually building the path. return { "message": "Welcome to the MIDI Processor API!", "status": "ok", "documentation_url": "/docs" # FastAPI will resolve this correctly now } @app.post("/process-midi", tags=["MIDI Processing"]) async def process_midi_file(file: UploadFile = File(..., description="The MIDI file (.mid, .midi) to be processed.")): if not file.filename.lower().endswith(('.mid', '.midi')): return JSONResponse( status_code=400, content={"error": "Invalid file type. Please upload a .mid or .midi file."} ) try: print(f"Processing file: {file.filename}") midi_data = await file.read() processed_data_buffer = process_midi(midi_data) return StreamingResponse( processed_data_buffer, media_type="audio/midi", headers={"Content-Disposition": f"attachment; filename=processed_{file.filename}"} ) except Exception as e: print(f"An error occurred while processing the file: {e}") return JSONResponse( status_code=500, content={"error": "An internal server error occurred during MIDI processing.", "detail": str(e)} )