amauricunha commited on
Commit
5d57748
·
verified ·
1 Parent(s): b98cbb9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -0
app.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)