File size: 1,509 Bytes
d407cff |
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 |
from ninja import NinjaAPI, File
from ninja.files import UploadedFile
from django.http import HttpResponse
from .midi_utils import process_midi # Import from the same directory
api = NinjaAPI(
title="MIDI Processor API (Django Ninja)",
version="2.0.0",
description="A robust MIDI processing API built with Django Ninja."
)
@api.get("/")
def home(request):
"""
A simple welcome endpoint.
The interactive docs will be at /api/docs
"""
return {"message": "Welcome to the Django Ninja MIDI API!", "docs_url": "/api/docs"}
@api.post("/process-midi")
def process_midi_file(request, file: UploadedFile = File(...)):
"""
Receives a MIDI file, transposes it, and returns the processed file.
"""
try:
# Check filename
if not file.name.lower().endswith(('.mid', '.midi')):
return api.create_response(request, {"error": "Invalid file type"}, status=400)
# Read file bytes
midi_bytes = file.read()
# Process the midi data
processed_buffer = process_midi(midi_bytes)
# Create an HTTP response with the processed file
response = HttpResponse(
processed_buffer.getvalue(),
content_type='audio/midi'
)
response['Content-Disposition'] = f'attachment; filename="processed_{file.name}"'
return response
except Exception as e:
return api.create_response(request, {"error": str(e)}, status=500) |