Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import osimport jsonimport base64from flask import Flask, request, jsonify# Gradio/Flask setup# This simple setup avoids full Gradio UI and focuses on serving static files and the API endpointapp = Flask(__name__, static_folder=".")# Ensure the API Key is set as a Secret in Hugging Face Space Settings# Variable name must be GEMINI_API_KEY for securityGEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")if not GEMINI_API_KEY:print("Warning: GEMINI_API_KEY environment variable not set. TTS generation will fail.")@app.route('/tts-proxy', methods=['POST'])def tts_proxy():"""Handles the request from the frontend, securely calls the Gemini TTS API,and returns the base64 audio data."""if not GEMINI_API_KEY:return jsonify({"error": "API Key is missing or not configured."}), 500try:data = request.jsonprompt = data.get('prompt')voice = data.get('voice')if not prompt or not voice:return jsonify({"error": "Missing 'prompt' or 'voice' parameter."}), 400# Prepare the payload for the Gemini TTS APIpayload = {"contents": [{"parts": [{"text": prompt}]}],"generationConfig": {"responseModalities": ["AUDIO"],"speechConfig": {"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": voice}}}},"model": "gemini-2.5-flash-preview-tts"}# Use requests library or similar to call the API from the backend# We use standard library fetch if running in a compliant environment,# but for simplicity and common deployment, we simulate the internal call structure.# Since we cannot use an external 'requests' dependency easily here,# we assume this file will be executed by an environment (like a Gradio wrapper)# that handles external API calls or we rely on the internal execution context# in a standard Hugging Face Docker/SDK setup.# For a true Gradio Space deployment, this part is usually written slightly differently.# *** Critical Section: Calling the Gemini API from the Backend ***import requestsapi_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key={GEMINI_API_KEY}"response = requests.post(api_url,headers={'Content-Type': 'application/json'},data=json.dumps(payload))response.raise_for_status() # Raise exception for bad status codes (4xx or 5xx)result = response.json()audio_data = result.get('candidates')[0].get('content').get('parts')[0].get('inlineData').get('data')return jsonify({"audioData": audio_data}), 200except requests.exceptions.HTTPError as e:print(f"HTTP Error calling Gemini API: {e}")return jsonify({"error": f"API call failed: {e.response.text}"}), 500except Exception as e:print(f"General error in TTS proxy: {e}")return jsonify({"error": "Internal server error during audio generation."}), 500@app.route('/')def index():return app.send_static_file('index.html')if __name__ == '__main__':# When deployed on HF Spaces, the port is usually managed by the environmentport = int(os.environ.get('PORT', 7860))app.run(host='0.0.0.0', port=port)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import osimport jsonimport base64import iofrom gtts import gTTSfrom flask import Flask, request, jsonify, send_fileimport tempfile# Flask setupapp = Flask(__name__, static_folder=".")# The language code 'en' for EnglishTTS_LANG = 'en'@app.route('/tts-proxy', methods=['POST'])def tts_proxy():"""Recebe o texto do frontend e usa gTTS para gerar áudio MP3.O áudio é retornado como um arquivo para o cliente."""try:data = request.jsonprompt = data.get('prompt')# gTTS does not support changing voice/accent like Gemini, so we ignore it.# It defaults to a neutral female voice.if not prompt:return jsonify({"error": "Parâmetro 'prompt' ausente. Cole o texto para gerar o áudio."}), 400# 1. Geração do áudio usando gTTS (requer internet)# Usamos tld='us' para um sotaque americano padrão (US English).tts = gTTS(text=prompt, lang=TTS_LANG, slow=False, tld='us')# 2. Salva o áudio em um buffer de memóriamp3_fp = io.BytesIO()tts.write_to_fp(mp3_fp)mp3_fp.seek(0)# 3. Retorna o arquivo MP3 diretamente como uma resposta do Flask# O navegador tratará isso como um arquivo de áudio.return send_file(mp3_fp,mimetype='audio/mp3',as_attachment=False,download_name='generated_audio.mp3')except Exception as e:print(f"Erro geral no proxy TTS: {e}")return jsonify({"error": f"Erro interno durante a geração de áudio: {e}"}), 500@app.route('/')def index_route():return app.send_static_file('index.html')if __name__ == '__main__':# Quando implantado no HF Spaces, a porta é gerenciada pelo ambienteport = int(os.environ.get('PORT', 7860))app.run(host='0.0.0.0', port=port)
app.py+31-58