File size: 6,001 Bytes
7814ee2
 
 
 
 
 
 
56998f6
7814ee2
 
149c25a
 
7814ee2
149c25a
7814ee2
 
149c25a
7814ee2
149c25a
 
7814ee2
 
 
 
 
 
149c25a
 
 
 
7814ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56998f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383458e
 
56998f6
 
383458e
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
@app.get("/status")
def status():
    return {"status": "API running", "version": "1.0"}

@app.post("/generate-sound/")
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))

@app.post("/generate-music/")
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)
@app.get("/", response_class=HTMLResponse)
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
@app.get("/docs", response_class=RedirectResponse, status_code=302)
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)