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
| 2 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
import tempfile
|
| 6 |
+
import os
|
| 7 |
+
import uvicorn
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from threading import Thread
|
| 10 |
+
|
| 11 |
+
# Crear app FastAPI
|
| 12 |
+
app = FastAPI(title="Musical Instrument Detection API", version="1.0.0")
|
| 13 |
+
|
| 14 |
+
# Configurar CORS para permitir requests desde Android
|
| 15 |
+
app.add_middleware(
|
| 16 |
+
CORSMiddleware,
|
| 17 |
+
allow_origins=["*"],
|
| 18 |
+
allow_credentials=True,
|
| 19 |
+
allow_methods=["*"],
|
| 20 |
+
allow_headers=["*"],
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# Cargar modelo
|
| 24 |
+
try:
|
| 25 |
+
classifier = pipeline("audio-classification", model="Janiopi/detector_de_instrumentos_v1")
|
| 26 |
+
print("✅ Modelo cargado exitosamente")
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"❌ Error cargando modelo: {e}")
|
| 29 |
+
classifier = None
|
| 30 |
+
|
| 31 |
+
@app.get("/")
|
| 32 |
+
async def root():
|
| 33 |
+
return {
|
| 34 |
+
"message": "Musical Instrument Detection API",
|
| 35 |
+
"status": "online",
|
| 36 |
+
"model_loaded": classifier is not None,
|
| 37 |
+
"endpoints": {
|
| 38 |
+
"detect": "/detect (POST)",
|
| 39 |
+
"health": "/health (GET)"
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
@app.get("/health")
|
| 44 |
+
async def health_check():
|
| 45 |
+
return {
|
| 46 |
+
"status": "ok",
|
| 47 |
+
"model_loaded": classifier is not None,
|
| 48 |
+
"message": "API funcionando correctamente"
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
@app.post("/detect")
|
| 52 |
+
async def detect_instrument(audio: UploadFile = File(...)):
|
| 53 |
+
"""
|
| 54 |
+
Endpoint para detectar instrumentos musicales en audio
|
| 55 |
+
"""
|
| 56 |
+
try:
|
| 57 |
+
if classifier is None:
|
| 58 |
+
raise HTTPException(status_code=503, detail="Modelo no disponible")
|
| 59 |
+
|
| 60 |
+
# Verificar tipo de archivo
|
| 61 |
+
if not audio.content_type.startswith('audio/'):
|
| 62 |
+
raise HTTPException(status_code=400, detail="El archivo debe ser de audio")
|
| 63 |
+
|
| 64 |
+
# Guardar archivo temporalmente
|
| 65 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
|
| 66 |
+
content = await audio.read()
|
| 67 |
+
temp_file.write(content)
|
| 68 |
+
temp_path = temp_file.name
|
| 69 |
+
|
| 70 |
+
print(f"📁 Procesando archivo: {audio.filename}, tamaño: {len(content)} bytes")
|
| 71 |
+
|
| 72 |
+
# Procesar con el modelo
|
| 73 |
+
results = classifier(temp_path)
|
| 74 |
+
|
| 75 |
+
# Limpiar archivo temporal
|
| 76 |
+
os.unlink(temp_path)
|
| 77 |
+
|
| 78 |
+
# Formatear resultados
|
| 79 |
+
formatted_results = []
|
| 80 |
+
for result in results:
|
| 81 |
+
formatted_results.append({
|
| 82 |
+
"label": result["label"],
|
| 83 |
+
"score": round(result["score"], 4)
|
| 84 |
+
})
|
| 85 |
+
|
| 86 |
+
print(f"✅ Resultados: {formatted_results}")
|
| 87 |
+
|
| 88 |
+
return {
|
| 89 |
+
"success": True,
|
| 90 |
+
"results": formatted_results,
|
| 91 |
+
"filename": audio.filename
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"❌ Error: {e}")
|
| 96 |
+
raise HTTPException(status_code=500, detail=f"Error procesando audio: {str(e)}")
|
| 97 |
+
|
| 98 |
+
# Crear interfaz Gradio simple para visualización
|
| 99 |
+
def gradio_interface():
|
| 100 |
+
with gr.Blocks(title="Musical Instrument Detection API") as demo:
|
| 101 |
+
gr.Markdown("# 🎵 Musical Instrument Detection API")
|
| 102 |
+
gr.Markdown("## API Endpoints:")
|
| 103 |
+
gr.Markdown("""
|
| 104 |
+
- **GET** `/` - Información general
|
| 105 |
+
- **GET** `/health` - Estado del servicio
|
| 106 |
+
- **POST** `/detect` - Detectar instrumentos (enviar archivo audio)
|
| 107 |
+
|
| 108 |
+
### Uso desde Android:
|
| 109 |
+
```
|
| 110 |
+
POST https://tu-usuario-musical-detector-api.hf.space/detect
|
| 111 |
+
Content-Type: multipart/form-data
|
| 112 |
+
Body: audio file
|
| 113 |
+
```
|
| 114 |
+
""")
|
| 115 |
+
|
| 116 |
+
# Interfaz simple para probar
|
| 117 |
+
with gr.Row():
|
| 118 |
+
audio_input = gr.Audio(type="filepath", label="Probar detección")
|
| 119 |
+
output_text = gr.Textbox(label="Resultado")
|
| 120 |
+
|
| 121 |
+
def test_detection(audio_path):
|
| 122 |
+
if audio_path and classifier:
|
| 123 |
+
try:
|
| 124 |
+
results = classifier(audio_path)
|
| 125 |
+
output = "Instrumentos detectados:\n"
|
| 126 |
+
for result in results:
|
| 127 |
+
output += f"- {result['label']}: {result['score']:.4f}\n"
|
| 128 |
+
return output
|
| 129 |
+
except Exception as e:
|
| 130 |
+
return f"Error: {e}"
|
| 131 |
+
return "No se pudo procesar el audio"
|
| 132 |
+
|
| 133 |
+
audio_input.change(test_detection, inputs=[audio_input], outputs=[output_text])
|
| 134 |
+
|
| 135 |
+
return demo
|
| 136 |
+
|
| 137 |
+
# Función para ejecutar FastAPI
|
| 138 |
+
def run_fastapi():
|
| 139 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 140 |
+
|
| 141 |
+
# Función para ejecutar Gradio
|
| 142 |
+
def run_gradio():
|
| 143 |
+
demo = gradio_interface()
|
| 144 |
+
demo.launch(server_name="0.0.0.0", server_port=7861, share=False)
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
# Ejecutar FastAPI en thread separado
|
| 148 |
+
fastapi_thread = Thread(target=run_fastapi, daemon=True)
|
| 149 |
+
fastapi_thread.start()
|
| 150 |
+
|
| 151 |
+
print("🚀 FastAPI iniciado en puerto 7860")
|
| 152 |
+
print("🎨 Gradio iniciado en puerto 7861")
|
| 153 |
+
|
| 154 |
+
# Ejecutar Gradio en el hilo principal
|
| 155 |
+
run_gradio()
|