File size: 2,170 Bytes
9804e6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)}
        )