Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,138 +1,55 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from flask_cors import CORS
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
|
|
|
|
| 7 |
app = Flask(__name__)
|
| 8 |
-
CORS(app)
|
| 9 |
-
|
| 10 |
-
# Obtener la API key de las variables de entorno de Hugging Face
|
| 11 |
-
# Aseg煤rate de que el secret/variable en Hugging Face se llama GEMINI_API_KEY
|
| 12 |
-
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 13 |
-
|
| 14 |
-
if not GEMINI_API_KEY:
|
| 15 |
-
print("WARNING: GEMINI_API_KEY environment variable is NOT configured. Google API calls will fail.", file=sys.stderr, flush=True)
|
| 16 |
-
else:
|
| 17 |
-
print("INFO: GEMINI_API_KEY successfully loaded from environment.", flush=True)
|
| 18 |
-
|
| 19 |
-
@app.route('/')
|
| 20 |
-
def home():
|
| 21 |
-
"""Serves the main page (index.html)."""
|
| 22 |
-
# In a Hugging Face Space, index.html is usually served automatically
|
| 23 |
-
print("INFO: Received request for root path. Serving placeholder text.", flush=True)
|
| 24 |
-
return "Flask backend is running. Access /index.html if it does not load automatically."
|
| 25 |
-
|
| 26 |
-
@app.route('/generate_image', methods=['POST'])
|
| 27 |
-
def generate_image():
|
| 28 |
-
"""Endpoint para generar im谩genes usando Google Imagen."""
|
| 29 |
-
print("INFO: Received /generate_image POST request.", flush=True)
|
| 30 |
-
data = request.get_json()
|
| 31 |
-
prompt = data.get('prompt')
|
| 32 |
-
|
| 33 |
-
if not prompt:
|
| 34 |
-
print("ERROR: No prompt provided for image generation.", file=sys.stderr, flush=True)
|
| 35 |
-
return jsonify({"error": "No se proporcion贸 un prompt para la imagen."}), 400
|
| 36 |
-
|
| 37 |
-
if not GEMINI_API_KEY:
|
| 38 |
-
print("ERROR: API Key is not configured for image generation.", file=sys.stderr, flush=True)
|
| 39 |
-
return jsonify({"error": "La clave API no est谩 configurada en el backend."}), 500
|
| 40 |
-
|
| 41 |
-
url = f"https://generativelanguage.googleapis.com/v1beta/models/imagen-3.0-generate-002:predict?key={GEMINI_API_KEY}"
|
| 42 |
-
headers = {'Content-Type': 'application/json'}
|
| 43 |
-
payload = {
|
| 44 |
-
"instances": {"prompt": prompt},
|
| 45 |
-
"parameters": {"sampleCount": 1}
|
| 46 |
-
}
|
| 47 |
-
|
| 48 |
-
try:
|
| 49 |
-
print(f"INFO: Calling Imagen API with prompt: '{prompt[:50]}...'", flush=True)
|
| 50 |
-
response = requests.post(url, headers=headers, json=payload, timeout=60) # Added timeout
|
| 51 |
-
response.raise_for_status() # Raise an exception for HTTP 4xx or 5xx errors
|
| 52 |
-
result = response.json()
|
| 53 |
-
print("INFO: Successfully received response from Imagen API.", flush=True)
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
image_url = f"data:image/png;base64,{image_base64}"
|
| 58 |
-
print("INFO: Image base64 extracted successfully.", flush=True)
|
| 59 |
-
return jsonify({"imageUrl": image_url})
|
| 60 |
-
else:
|
| 61 |
-
print(f"ERROR: No valid image data found in Imagen API response: {result}", file=sys.stderr, flush=True)
|
| 62 |
-
return jsonify({"error": "No se recibi贸 una imagen v谩lida de la API de Google Imagen."}), 500
|
| 63 |
-
|
| 64 |
-
except requests.exceptions.HTTPError as http_err:
|
| 65 |
-
print(f"ERROR: HTTP error from Imagen API: {http_err.response.status_code} - {http_err.response.text}", file=sys.stderr, flush=True)
|
| 66 |
-
return jsonify({"error": f"Error de la API de Imagen ({http_err.response.status_code}): {http_err.response.text}"}), 500
|
| 67 |
-
except requests.exceptions.ConnectionError as conn_err:
|
| 68 |
-
print(f"ERROR: Connection error to Imagen API: {conn_err}", file=sys.stderr, flush=True)
|
| 69 |
-
return jsonify({"error": f"Error de conexi贸n con la API de Imagen: {conn_err}"}), 500
|
| 70 |
-
except requests.exceptions.Timeout as timeout_err:
|
| 71 |
-
print(f"ERROR: Timeout error with Imagen API: {timeout_err}", file=sys.stderr, flush=True)
|
| 72 |
-
return jsonify({"error": f"La solicitud a la API de Imagen tard贸 demasiado (timeout): {timeout_err}"}), 500
|
| 73 |
-
except requests.exceptions.RequestException as req_err:
|
| 74 |
-
print(f"ERROR: General request error with Imagen API: {req_err}", file=sys.stderr, flush=True)
|
| 75 |
-
return jsonify({"error": f"Error al comunicarse con la API de generaci贸n de im谩genes: {req_err}"}), 500
|
| 76 |
-
except Exception as e:
|
| 77 |
-
print(f"CRITICAL ERROR: Unexpected error generating image: {e}", file=sys.stderr, exc_info=True, flush=True) # exc_info for traceback
|
| 78 |
-
return jsonify({"error": f"Error inesperado al generar imagen: {e}"}), 500
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
@app.route('/generate_text', methods=['POST'])
|
| 82 |
-
def generate_text():
|
| 83 |
-
"""Endpoint para generar texto usando Google Gemini-Flash."""
|
| 84 |
-
print("INFO: Received /generate_text POST request.", flush=True)
|
| 85 |
-
data = request.get_json()
|
| 86 |
-
prompt = data.get('prompt')
|
| 87 |
-
|
| 88 |
-
if not prompt:
|
| 89 |
-
print("ERROR: No prompt provided for text generation.", file=sys.stderr, flush=True)
|
| 90 |
-
return jsonify({"error": "No se proporcion贸 un prompt para el texto."}), 400
|
| 91 |
-
|
| 92 |
-
if not GEMINI_API_KEY:
|
| 93 |
-
print("ERROR: API Key is not configured for text generation.", file=sys.stderr, flush=True)
|
| 94 |
-
return jsonify({"error": "La clave API no est谩 configurada en el backend."}), 500
|
| 95 |
-
|
| 96 |
-
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={GEMINI_API_KEY}"
|
| 97 |
-
headers = {'Content-Type': 'application/json'}
|
| 98 |
-
payload = {
|
| 99 |
-
"contents": [{"role": "user", "parts": [{"text": prompt}]}]
|
| 100 |
-
}
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
try:
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
except requests.exceptions.HTTPError as http_err:
|
| 120 |
-
print(f"ERROR: HTTP error from Gemini API: {http_err.response.status_code} - {http_err.response.text}", file=sys.stderr, flush=True)
|
| 121 |
-
return jsonify({"error": f"Error de la API de Gemini ({http_err.response.status_code}): {http_err.response.text}"}), 500
|
| 122 |
-
except requests.exceptions.ConnectionError as conn_err:
|
| 123 |
-
print(f"ERROR: Connection error to Gemini API: {conn_err}", file=sys.stderr, flush=True)
|
| 124 |
-
return jsonify({"error": f"Error de conexi贸n con la API de Gemini: {conn_err}"}), 500
|
| 125 |
-
except requests.exceptions.Timeout as timeout_err:
|
| 126 |
-
print(f"ERROR: Timeout error with Gemini API: {timeout_err}", file=sys.stderr, flush=True)
|
| 127 |
-
return jsonify({"error": f"La solicitud a la API de Gemini tard贸 demasiado (timeout): {timeout_err}"}), 500
|
| 128 |
-
except requests.exceptions.RequestException as req_err:
|
| 129 |
-
print(f"ERROR: General request error with Gemini API: {req_err}", file=sys.stderr, flush=True)
|
| 130 |
-
return jsonify({"error": f"Error al comunicarse con la API de generaci贸n de texto: {req_err}"}), 500
|
| 131 |
except Exception as e:
|
| 132 |
-
print(f"
|
| 133 |
-
return jsonify({"error":
|
| 134 |
|
| 135 |
if __name__ == '__main__':
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
app.run(host='0.0.0.0', port=port, debug=False)
|
|
|
|
| 1 |
+
# gtts_server.py
|
| 2 |
+
#
|
| 3 |
+
# Requisitos:
|
| 4 |
+
# pip install Flask gTTS Flask-Cors
|
| 5 |
+
#
|
| 6 |
+
# C贸mo ejecutar:
|
| 7 |
+
# python gtts_server.py
|
| 8 |
+
#
|
| 9 |
+
# El servidor se ejecutar谩 en http://localhost:5000
|
| 10 |
+
|
| 11 |
+
from flask import Flask, request, jsonify, send_file
|
| 12 |
from flask_cors import CORS
|
| 13 |
+
from gtts import gTTS
|
| 14 |
+
from io import BytesIO
|
| 15 |
|
| 16 |
+
# Inicializar la aplicaci贸n Flask
|
| 17 |
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# Habilitar CORS para permitir peticiones desde el navegador (frontend)
|
| 20 |
+
CORS(app)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
@app.route('/api/tts', methods=['POST'])
|
| 23 |
+
def text_to_speech():
|
| 24 |
+
"""
|
| 25 |
+
Endpoint para convertir texto a voz.
|
| 26 |
+
Recibe un JSON con la clave "text" y devuelve un archivo de audio MP3.
|
| 27 |
+
"""
|
| 28 |
try:
|
| 29 |
+
data = request.get_json()
|
| 30 |
+
text_to_speak = data.get('text')
|
| 31 |
+
|
| 32 |
+
if not text_to_speak:
|
| 33 |
+
return jsonify({"error": "No se proporcion贸 texto (clave 'text')."}), 400
|
| 34 |
+
|
| 35 |
+
# Generar el audio con acento de M茅xico
|
| 36 |
+
tts = gTTS(text=text_to_speak, lang='es', tld='com.mx', slow=False)
|
| 37 |
+
|
| 38 |
+
mp3_fp = BytesIO()
|
| 39 |
+
tts.write_to_fp(mp3_fp)
|
| 40 |
+
mp3_fp.seek(0)
|
| 41 |
+
|
| 42 |
+
return send_file(
|
| 43 |
+
mp3_fp,
|
| 44 |
+
mimetype='audio/mpeg',
|
| 45 |
+
as_attachment=False,
|
| 46 |
+
download_name='narration.mp3'
|
| 47 |
+
)
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
except Exception as e:
|
| 50 |
+
print(f"Ha ocurrido un error: {e}")
|
| 51 |
+
return jsonify({"error": str(e)}), 500
|
| 52 |
|
| 53 |
if __name__ == '__main__':
|
| 54 |
+
print("Iniciando servidor de gTTS en http://localhost:5000")
|
| 55 |
+
app.run(host='0.0.0.0', port=5000, debug=True)
|
|
|