Spaces:
Sleeping
Sleeping
| 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 | |
| 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)) | |
| def root(): | |
| return RedirectResponse(url="/gradio") | |
| # Interfaz con Gradio (solo documentaci贸n) | |
| def gradio_ui(): | |
| description = """ | |
| # API de Generaci贸n de Texto | |
| Esta API utiliza `GPT-2` para generar texto basado en un prompt. | |
| ## Uso: | |
| 1. Visita [la documentaci贸n interactiva](https://<TU-HF-SPACE>.hf.space/docs) para probar la API. | |
| 2. Endpoint principal: `GET /generate?prompt=TuTexto` | |
| 3. Par谩metros: | |
| - `prompt` (str): Texto inicial. | |
| - `max_length` (int, opcional): Longitud m谩xima del texto generado. | |
| 馃搶 **Ejemplo de llamada en Python:** | |
| ```python | |
| import requests | |
| url = "https://<TU-HF-SPACE>.hf.space/generate?prompt=Hola" | |
| response = requests.get(url) | |
| print(response.json()) | |
| ``` | |
| """ | |
| return gr.Markdown(description) | |
| gr_app = gr.Blocks() | |
| with gr_app: | |
| gradio_ui() | |
| def gradio_launch(): | |
| """Lanza la interfaz de Gradio""" | |
| return gr_app.launch(server_name="0.0.0.0", server_port=7860, inline=False, share=False) | |
| # Para ejecutar en local | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=8000) |