amauricunha commited on
Commit
6b6af6b
·
verified ·
1 Parent(s): 7645a35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -58
app.py CHANGED
@@ -1,86 +1,59 @@
1
  import os
2
  import json
3
  import base64
4
- from flask import Flask, request, jsonify
 
 
 
5
 
6
- # Gradio/Flask setup
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
- # Ensure the API Key is set as a Secret in Hugging Face Space Settings
11
- # Variable name must be GEMINI_API_KEY for security
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
- Handles the request from the frontend, securely calls the Gemini TTS API,
20
- and returns the base64 audio data.
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 = data.get('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
- # Use requests library or similar to call the API from the backend
46
- # We use standard library fetch if running in a compliant environment,
47
- # but for simplicity and common deployment, we simulate the internal call structure.
48
 
49
- # Since we cannot use an external 'requests' dependency easily here,
50
- # we assume this file will be executed by an environment (like a Gradio wrapper)
51
- # that handles external API calls or we rely on the internal execution context
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
- # *** Critical Section: Calling the Gemini API from the Backend ***
56
- import requests
 
 
57
 
58
- api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key={GEMINI_API_KEY}"
59
-
60
- response = requests.post(
61
- api_url,
62
- headers={'Content-Type': 'application/json'},
63
- data=json.dumps(payload)
 
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"General error in TTS proxy: {e}")
77
- return jsonify({"error": "Internal server error during audio generation."}), 500
78
 
79
  @app.route('/')
80
- def index():
81
  return app.send_static_file('index.html')
82
 
83
  if __name__ == '__main__':
84
- # When deployed on HF Spaces, the port is usually managed by the environment
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)