Spaces:
Running
Running
import os | |
import gradio as gr | |
import uvicorn | |
from sound_generator import generate_sound, generate_music | |
from fastapi import FastAPI, HTTPException | |
from fastapi.middleware.cors import CORSMiddleware | |
from fastapi.responses import FileResponse, RedirectResponse, HTMLResponse | |
from pydantic import BaseModel | |
# Create the FastAPI app with custom docs URL | |
app = FastAPI(docs_url="/api/docs") | |
# Configuración de CORS | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=["*"], | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
# Define a Pydantic model to handle the input prompt | |
class AudioRequest(BaseModel): | |
prompt: str | |
# Prueba para verificar si la API funciona - la dejamos por ahora para debugging | |
def status(): | |
return {"status": "API running", "version": "1.0"} | |
async def generate_sound_endpoint(request: AudioRequest): | |
try: | |
# Llamada a la función para generar el sonido | |
audio_file_path = generate_sound(request.prompt) | |
# Verifica si el archivo se ha generado correctamente | |
if not os.path.exists(audio_file_path): | |
raise HTTPException( | |
status_code=404, detail="Archivo de audio no encontrado." | |
) | |
# Regresar el archivo generado como una respuesta de descarga | |
return FileResponse( | |
audio_file_path, media_type="audio/wav", filename="generated_audio.wav" | |
) | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=str(e)) | |
async def generate_music_endpoint(request: AudioRequest): | |
try: | |
# Call the synchronous generate_music function | |
audio_file_path = generate_music(request.prompt) | |
# Verifies if the file has been generated correctly | |
if not os.path.exists(audio_file_path): | |
raise HTTPException( | |
status_code=404, detail="Archivo de audio no encontrado." | |
) | |
# Return the generated file as a download response | |
return FileResponse( | |
audio_file_path, media_type="audio/wav", filename="generated_audio.wav" | |
) | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=str(e)) | |
# Página principal simplificada (HTML puro) | |
async def home(): | |
html_content = """ | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>API de Sonidos Generativos</title> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<style> | |
body { | |
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; | |
line-height: 1.6; | |
max-width: 800px; | |
margin: 0 auto; | |
padding: 20px; | |
color: #333; | |
} | |
.container { | |
background-color: #f9f9f9; | |
border-radius: 8px; | |
padding: 20px; | |
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); | |
} | |
h1 { | |
color: #2563eb; | |
margin-top: 0; | |
} | |
.button { | |
display: inline-block; | |
background-color: #2563eb; | |
color: white; | |
padding: 10px 20px; | |
text-decoration: none; | |
border-radius: 4px; | |
font-weight: 500; | |
margin-right: 10px; | |
margin-top: 10px; | |
} | |
.button:hover { | |
background-color: #1d4ed8; | |
} | |
pre { | |
background-color: #f1f1f1; | |
padding: 10px; | |
border-radius: 4px; | |
overflow-x: auto; | |
} | |
code { | |
font-family: monospace; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="container"> | |
<h1>API de Sonidos Generativos</h1> | |
<p>Bienvenido al servicio de generación de sonidos y música mediante IA.</p> | |
<h2>Documentación</h2> | |
<p>La API completa está documentada y disponible en los siguientes enlaces:</p> | |
<a href="/api/docs" class="button">Swagger UI</a> | |
<a href="/api/redoc" class="button">ReDoc</a> | |
<h2>Endpoints disponibles</h2> | |
<ul> | |
<li><strong>GET /api/health</strong> - Verificar estado del servicio</li> | |
<li><strong>POST /api/generate-sound/</strong> - Generar sonido a partir de descripción</li> | |
<li><strong>POST /api/generate-music/</strong> - Generar música a partir de descripción</li> | |
</ul> | |
<h2>Ejemplos de uso</h2> | |
<h3>Generar sonido</h3> | |
<pre><code>curl -X POST "http://localhost:7860/api/generate-sound/" \\ | |
-H "Content-Type: application/json" \\ | |
-d '{"prompt": "Un trueno distante", "duration": 15, "pitch": 0.9}'</code></pre> | |
<h3>Generar música</h3> | |
<pre><code>curl -X POST "http://localhost:7860/api/generate-music/" \\ | |
-H "Content-Type: application/json" \\ | |
-d '{"prompt": "Melodía relajante", "genre": "ambient", "duration": 60, "bpm": 100}'</code></pre> | |
</div> | |
</body> | |
</html> | |
""" | |
return html_content | |
# También puedes ofrecer una redirección directa a la documentación si lo prefieres | |
async def redirect_to_docs(): | |
return "/api/docs" | |
# Confirmar inicialización | |
print("✅ Servidor inicializado correctamente !!!!") | |
print("🌐 Página principal disponible en la ruta '/'") | |
print("📝 Endpoints de la API disponibles en '/api/*'") | |
print("📄 Documentación disponible en '/api/docs'") | |
# Iniciar el servidor | |
if __name__ == "__main__": | |
uvicorn.run(app, host="0.0.0.0", port=7860) |