Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,86 +1,59 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import base64
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
# This simple setup avoids full Gradio UI and focuses on serving static files and the API endpoint
|
| 8 |
app = Flask(__name__, static_folder=".")
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 13 |
-
if not GEMINI_API_KEY:
|
| 14 |
-
print("Warning: GEMINI_API_KEY environment variable not set. TTS generation will fail.")
|
| 15 |
|
| 16 |
@app.route('/tts-proxy', methods=['POST'])
|
| 17 |
def tts_proxy():
|
| 18 |
"""
|
| 19 |
-
|
| 20 |
-
|
| 21 |
"""
|
| 22 |
-
if not GEMINI_API_KEY:
|
| 23 |
-
return jsonify({"error": "API Key is missing or not configured."}), 500
|
| 24 |
-
|
| 25 |
try:
|
| 26 |
data = request.json
|
| 27 |
prompt = data.get('prompt')
|
| 28 |
-
voice
|
| 29 |
-
|
| 30 |
-
if not prompt or not voice:
|
| 31 |
-
return jsonify({"error": "Missing 'prompt' or 'voice' parameter."}), 400
|
| 32 |
-
|
| 33 |
-
# Prepare the payload for the Gemini TTS API
|
| 34 |
-
payload = {
|
| 35 |
-
"contents": [{"parts": [{"text": prompt}]}],
|
| 36 |
-
"generationConfig": {
|
| 37 |
-
"responseModalities": ["AUDIO"],
|
| 38 |
-
"speechConfig": {
|
| 39 |
-
"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": voice}}
|
| 40 |
-
}
|
| 41 |
-
},
|
| 42 |
-
"model": "gemini-2.5-flash-preview-tts"
|
| 43 |
-
}
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# but for simplicity and common deployment, we simulate the internal call structure.
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
#
|
| 51 |
-
|
| 52 |
-
# in a standard Hugging Face Docker/SDK setup.
|
| 53 |
-
# For a true Gradio Space deployment, this part is usually written slightly differently.
|
| 54 |
|
| 55 |
-
#
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
| 64 |
)
|
| 65 |
-
response.raise_for_status() # Raise exception for bad status codes (4xx or 5xx)
|
| 66 |
-
|
| 67 |
-
result = response.json()
|
| 68 |
-
audio_data = result.get('candidates')[0].get('content').get('parts')[0].get('inlineData').get('data')
|
| 69 |
-
|
| 70 |
-
return jsonify({"audioData": audio_data}), 200
|
| 71 |
|
| 72 |
-
except requests.exceptions.HTTPError as e:
|
| 73 |
-
print(f"HTTP Error calling Gemini API: {e}")
|
| 74 |
-
return jsonify({"error": f"API call failed: {e.response.text}"}), 500
|
| 75 |
except Exception as e:
|
| 76 |
-
print(f"
|
| 77 |
-
return jsonify({"error": "
|
| 78 |
|
| 79 |
@app.route('/')
|
| 80 |
-
def
|
| 81 |
return app.send_static_file('index.html')
|
| 82 |
|
| 83 |
if __name__ == '__main__':
|
| 84 |
-
#
|
| 85 |
port = int(os.environ.get('PORT', 7860))
|
| 86 |
app.run(host='0.0.0.0', port=port)
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import base64
|
| 4 |
+
import io
|
| 5 |
+
from gtts import gTTS
|
| 6 |
+
from flask import Flask, request, jsonify, send_file
|
| 7 |
+
import tempfile
|
| 8 |
|
| 9 |
+
# Flask setup
|
|
|
|
| 10 |
app = Flask(__name__, static_folder=".")
|
| 11 |
|
| 12 |
+
# The language code 'en' for English
|
| 13 |
+
TTS_LANG = 'en'
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
@app.route('/tts-proxy', methods=['POST'])
|
| 16 |
def tts_proxy():
|
| 17 |
"""
|
| 18 |
+
Recebe o texto do frontend e usa gTTS para gerar áudio MP3.
|
| 19 |
+
O áudio é retornado como um arquivo para o cliente.
|
| 20 |
"""
|
|
|
|
|
|
|
|
|
|
| 21 |
try:
|
| 22 |
data = request.json
|
| 23 |
prompt = data.get('prompt')
|
| 24 |
+
# gTTS does not support changing voice/accent like Gemini, so we ignore it.
|
| 25 |
+
# It defaults to a neutral female voice.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
if not prompt:
|
| 28 |
+
return jsonify({"error": "Parâmetro 'prompt' ausente. Cole o texto para gerar o áudio."}), 400
|
|
|
|
| 29 |
|
| 30 |
+
# 1. Geração do áudio usando gTTS (requer internet)
|
| 31 |
+
# Usamos tld='us' para um sotaque americano padrão (US English).
|
| 32 |
+
tts = gTTS(text=prompt, lang=TTS_LANG, slow=False, tld='us')
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# 2. Salva o áudio em um buffer de memória
|
| 35 |
+
mp3_fp = io.BytesIO()
|
| 36 |
+
tts.write_to_fp(mp3_fp)
|
| 37 |
+
mp3_fp.seek(0)
|
| 38 |
|
| 39 |
+
# 3. Retorna o arquivo MP3 diretamente como uma resposta do Flask
|
| 40 |
+
# O navegador tratará isso como um arquivo de áudio.
|
| 41 |
+
return send_file(
|
| 42 |
+
mp3_fp,
|
| 43 |
+
mimetype='audio/mp3',
|
| 44 |
+
as_attachment=False,
|
| 45 |
+
download_name='generated_audio.mp3'
|
| 46 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
|
|
|
|
|
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
+
print(f"Erro geral no proxy TTS: {e}")
|
| 50 |
+
return jsonify({"error": f"Erro interno durante a geração de áudio: {e}"}), 500
|
| 51 |
|
| 52 |
@app.route('/')
|
| 53 |
+
def index_route():
|
| 54 |
return app.send_static_file('index.html')
|
| 55 |
|
| 56 |
if __name__ == '__main__':
|
| 57 |
+
# Quando implantado no HF Spaces, a porta é gerenciada pelo ambiente
|
| 58 |
port = int(os.environ.get('PORT', 7860))
|
| 59 |
app.run(host='0.0.0.0', port=port)
|