WasabiDrop commited on
Commit
9cd83cd
·
verified ·
1 Parent(s): a0a4728

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -77
app.py CHANGED
@@ -2,7 +2,7 @@ import gradio as gr
2
  import requests
3
  import os
4
  import time
5
- import json # Added for JSON loading
6
  from dotenv import load_dotenv
7
 
8
  # --- Configuration & Constants ---
@@ -17,32 +17,29 @@ else:
17
 
18
  MODEL_ENDPOINT = "https://api.replicate.com/v1/models/minimax/speech-02-hd/predictions"
19
 
20
- # --- Load Voice IDs from JSON ---
21
  VOICE_ID_MAP = {}
22
  try:
23
  with open("voices.json", "r", encoding="utf-8") as f:
24
  VOICE_ID_MAP = json.load(f)
25
  if not VOICE_ID_MAP:
26
- print("WARNING: voices.json is empty or could not be loaded. Voice ID dropdown will be empty.")
27
  VOICE_ID_PRETTY_NAMES = list(VOICE_ID_MAP.keys())
28
  DEFAULT_VOICE_PRETTY_NAME = "Friendly Person" if "Friendly Person" in VOICE_ID_PRETTY_NAMES else (VOICE_ID_PRETTY_NAMES[0] if VOICE_ID_PRETTY_NAMES else None)
29
  except FileNotFoundError:
30
- print("ERROR: voices.json not found. Please create it. Voice ID dropdown will be empty.")
31
  VOICE_ID_PRETTY_NAMES = []
32
  DEFAULT_VOICE_PRETTY_NAME = None
33
  except json.JSONDecodeError:
34
- print("ERROR: voices.json is not valid JSON. Please check its format. Voice ID dropdown will be empty.")
35
  VOICE_ID_PRETTY_NAMES = []
36
  DEFAULT_VOICE_PRETTY_NAME = None
37
 
38
-
39
  EMOTIONS = ["auto", "neutral", "happy", "sad", "angry", "fearful", "disgusted", "surprised"]
40
  SAMPLE_RATES = [8000, 16000, 22050, 24000, 32000, 44100]
41
  BITRATES = [32000, 64000, 128000, 256000]
42
  CHANNELS = ["mono", "stereo"]
43
  LANGUAGE_BOOST_OPTIONS = ["None", "English", "Chinese", "Japanese", "Korean"]
44
 
45
- # --- API Key Management ---
46
  current_key_index = 0
47
  MAX_POLLING_ATTEMPTS = 60
48
  POLL_INTERVAL = 3
@@ -55,20 +52,22 @@ def get_next_api_key():
55
  current_key_index = (current_key_index + 1) % len(REPLICATE_API_KEYS)
56
  return key
57
 
58
- # --- Core TTS Function ---
59
  def generate_speech(
60
  text, pitch, speed, volume, bitrate, channel, emotion,
61
- voice_id_pretty_name, custom_voice_id, sample_rate, # Changed voice_id_dropdown to voice_id_pretty_name
62
  language_boost, english_normalization
63
  ):
64
  if not text.strip():
65
- return None, "Error: Text input cannot be empty."
 
66
 
67
  if not REPLICATE_API_KEYS:
68
- return None, "Error: No Replicate API Tokens configured. Please set REPLICATE_API_TOKENS."
 
69
 
70
  if not VOICE_ID_MAP and not custom_voice_id.strip():
71
- return None, "Error: Voice ID configuration is missing or voices.json is empty/invalid, and no custom voice ID provided."
 
72
 
73
  actual_voice_id_to_use = ""
74
  if custom_voice_id.strip():
@@ -76,22 +75,14 @@ def generate_speech(
76
  elif voice_id_pretty_name and voice_id_pretty_name in VOICE_ID_MAP:
77
  actual_voice_id_to_use = VOICE_ID_MAP[voice_id_pretty_name]
78
  else:
79
- # Fallback if pretty name somehow isn't in map (shouldn't happen with Gradio dropdown)
80
- # or if voice_id_pretty_name is None (e.g. if VOICE_ID_MAP was empty)
81
- return None, f"Error: Selected voice '{voice_id_pretty_name}' not found in mappings and no custom ID provided."
82
-
83
 
84
  payload = {
85
  "input": {
86
- "text": text,
87
- "pitch": int(pitch),
88
- "speed": float(speed),
89
- "volume": int(volume),
90
- "bitrate": int(bitrate),
91
- "channel": channel,
92
- "emotion": emotion,
93
- "voice_id": actual_voice_id_to_use, # Use the mapped or custom voice ID
94
- "sample_rate": int(sample_rate),
95
  "english_normalization": bool(english_normalization)
96
  }
97
  }
@@ -99,18 +90,18 @@ def generate_speech(
99
  payload["input"]["language_boost"] = language_boost
100
 
101
  num_keys_to_try = len(REPLICATE_API_KEYS)
 
102
 
103
  for i in range(num_keys_to_try):
104
  api_key = get_next_api_key()
105
- if not api_key:
106
- return None, "Error: No API keys available."
 
107
 
108
  headers_post = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
109
  headers_get = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
110
 
111
- print(f"Attempting API call with key ending: ...{api_key[-4:]}")
112
- print(f"Using Voice ID: {actual_voice_id_to_use}")
113
- # print(f"Payload: {payload}") # Optionally print full payload for debugging
114
 
115
  try:
116
  response = requests.post(MODEL_ENDPOINT, json=payload, headers=headers_post, timeout=30)
@@ -125,98 +116,96 @@ def generate_speech(
125
  polling_attempts = 0
126
  while current_status in ["starting", "processing"] and prediction_url:
127
  if polling_attempts >= MAX_POLLING_ATTEMPTS:
128
- print(f"Max polling attempts reached for key ...{api_key[-4:]}.")
129
- result["error"] = "Polling timed out."
 
130
  current_status = "failed_polling_timeout"
131
  break
132
-
133
  polling_attempts += 1
134
- # print(f"Polling {prediction_url} (Attempt {polling_attempts}, Key ...{api_key[-4:]})") # Verbose
135
  time.sleep(POLL_INTERVAL)
136
-
137
  poll_response = requests.get(prediction_url, headers=headers_get, timeout=30)
138
  poll_response.raise_for_status()
139
  result = poll_response.json()
140
  current_status = result.get("status")
141
- # print(f"Poll response (Key ...{api_key[-4:]}): Status '{current_status}'") # Verbose
142
 
143
  if current_status == "succeeded":
144
  audio_url = result.get("output")
145
  if audio_url:
146
  success_logs = result.get('logs', logs_from_initial_call if logs_from_initial_call else 'N/A')
147
- return audio_url, f"Success! (Key ...{api_key[-4:]}). Logs: {success_logs}"
 
 
148
  else:
149
- print(f"API status succeeded (Key ...{api_key[-4:]}) but no output URL. Resp: {result}")
150
- continue
 
151
  else: # Covers "failed", "failed_polling_timeout", or other unexpected states
152
  error_detail = result.get("error", f"Unknown error or unexpected status '{current_status}'")
153
- print(f"Prediction failed or timed out for key ...{api_key[-4:]}. Status: {current_status}. Error: {error_detail}")
154
- continue
 
155
 
156
  except requests.exceptions.HTTPError as e:
157
  error_text = "Unknown HTTP Error"
158
- try:
159
- error_text = e.response.text
160
- except AttributeError:
161
- pass # Keep default
162
- print(f"HTTP error for key ...{api_key[-4:]}: {e.response.status_code} - {error_text}")
163
- continue
164
  except requests.exceptions.RequestException as e:
165
- print(f"Request exception for key ...{api_key[-4:]}: {e}")
166
- continue
 
167
 
168
- return None, "Error: All API keys failed or an unrecoverable error occurred. Check logs and API key validity/limits."
 
 
 
 
 
169
 
170
 
171
  # --- Gradio UI ---
172
  with gr.Blocks(theme=gr.themes.Soft()) as app:
173
- gr.Markdown("# Text-To-Speech with Minimax Speech-02-HD (via Replicate)")
174
- gr.Markdown(
175
- "Enter text and adjust parameters to generate speech. "
176
- "API keys are cycled on failures. If all keys fail for a request, an error is shown."
177
- )
178
 
179
  with gr.Row():
180
  with gr.Column(scale=2):
181
  text_input = gr.Textbox(
182
  label="Text to Synthesize",
183
  lines=5,
184
- placeholder="Enter your text here...\n\nEach character represents 1 token on Replicate."
185
  )
186
  with gr.Accordion("Voice Selection", open=True):
187
- voice_id_dropdown = gr.Dropdown( # This variable name is what Gradio uses internally
188
  label="Choose a Voice ID",
189
- choices=VOICE_ID_PRETTY_NAMES, # Use pretty names for display
190
- value=DEFAULT_VOICE_PRETTY_NAME # Set a default pretty name
191
  )
192
  custom_voice_id_input = gr.Textbox(
193
  label="Custom Voice ID (Optional)",
194
  placeholder="e.g., my_cloned_voice_v2",
195
- info="If filled, this will override the dropdown selection."
196
- )
197
- gr.Markdown(
198
- "For more voice options or to explore voice cloning, visit "
199
- "[Minimax Voices](https://www.minimax.io/audio/voices)."
200
  )
 
201
 
202
  with gr.Accordion("Advanced Speech Parameters", open=False):
203
  speed_slider = gr.Slider(label="Speed", minimum=0.5, maximum=2, step=0.1, value=1.0)
204
  volume_slider = gr.Slider(label="Volume", minimum=0, maximum=10, step=1, value=1)
205
- pitch_slider = gr.Slider(label="Pitch (semitones)", minimum=-12, maximum=12, step=1, value=0)
206
- english_norm_checkbox = gr.Checkbox(label="Enable English Normalization", value=False,
207
- info="Improves number reading in English, may slightly increase latency.")
208
 
209
  with gr.Accordion("Audio Format & Emotion", open=False):
210
  emotion_dropdown = gr.Dropdown(label="Emotion", choices=EMOTIONS, value="auto")
211
  sample_rate_dropdown = gr.Dropdown(label="Sample Rate (Hz)", choices=SAMPLE_RATES, value=32000, type="value")
212
  bitrate_dropdown = gr.Dropdown(label="Bitrate (bps)", choices=BITRATES, value=128000, type="value")
213
- channel_dropdown = gr.Dropdown(label="Audio Channels", choices=CHANNELS, value="mono")
214
- language_boost_dropdown = gr.Dropdown(label="Language Boost", choices=LANGUAGE_BOOST_OPTIONS, value="None",
215
- info="Boosts recognition for the selected language. 'None' for general use.")
216
 
217
  with gr.Column(scale=1):
218
  generate_button = gr.Button("Generate Speech", variant="primary")
219
- status_message = gr.Textbox(label="Status", interactive=False, lines=3)
220
  audio_output = gr.Audio(label="Generated Speech", type="filepath")
221
 
222
  generate_button.click(
@@ -224,17 +213,15 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
224
  inputs=[
225
  text_input, pitch_slider, speed_slider, volume_slider,
226
  bitrate_dropdown, channel_dropdown, emotion_dropdown,
227
- voice_id_dropdown, custom_voice_id_input, sample_rate_dropdown, # Pass the dropdown component itself
228
  language_boost_dropdown, english_norm_checkbox
229
  ],
230
- outputs=[audio_output, status_message]
231
  )
232
 
233
- # REMOVED gr.Examples block
234
-
235
  if __name__ == "__main__":
236
  if not REPLICATE_API_KEYS:
237
- print("FATAL: REPLICATE_API_TOKENS are not set. App will not be able to make API calls.")
238
  if not VOICE_ID_MAP:
239
- print("WARNING: Voice ID map is empty. This might be due to issues with voices.json.")
240
  app.launch(debug=True)
 
2
  import requests
3
  import os
4
  import time
5
+ import json
6
  from dotenv import load_dotenv
7
 
8
  # --- Configuration & Constants ---
 
17
 
18
  MODEL_ENDPOINT = "https://api.replicate.com/v1/models/minimax/speech-02-hd/predictions"
19
 
 
20
  VOICE_ID_MAP = {}
21
  try:
22
  with open("voices.json", "r", encoding="utf-8") as f:
23
  VOICE_ID_MAP = json.load(f)
24
  if not VOICE_ID_MAP:
25
+ print("WARNING: voices.json is empty or could not be loaded.")
26
  VOICE_ID_PRETTY_NAMES = list(VOICE_ID_MAP.keys())
27
  DEFAULT_VOICE_PRETTY_NAME = "Friendly Person" if "Friendly Person" in VOICE_ID_PRETTY_NAMES else (VOICE_ID_PRETTY_NAMES[0] if VOICE_ID_PRETTY_NAMES else None)
28
  except FileNotFoundError:
29
+ print("ERROR: voices.json not found. Please create it.")
30
  VOICE_ID_PRETTY_NAMES = []
31
  DEFAULT_VOICE_PRETTY_NAME = None
32
  except json.JSONDecodeError:
33
+ print("ERROR: voices.json is not valid JSON.")
34
  VOICE_ID_PRETTY_NAMES = []
35
  DEFAULT_VOICE_PRETTY_NAME = None
36
 
 
37
  EMOTIONS = ["auto", "neutral", "happy", "sad", "angry", "fearful", "disgusted", "surprised"]
38
  SAMPLE_RATES = [8000, 16000, 22050, 24000, 32000, 44100]
39
  BITRATES = [32000, 64000, 128000, 256000]
40
  CHANNELS = ["mono", "stereo"]
41
  LANGUAGE_BOOST_OPTIONS = ["None", "English", "Chinese", "Japanese", "Korean"]
42
 
 
43
  current_key_index = 0
44
  MAX_POLLING_ATTEMPTS = 60
45
  POLL_INTERVAL = 3
 
52
  current_key_index = (current_key_index + 1) % len(REPLICATE_API_KEYS)
53
  return key
54
 
 
55
  def generate_speech(
56
  text, pitch, speed, volume, bitrate, channel, emotion,
57
+ voice_id_pretty_name, custom_voice_id, sample_rate,
58
  language_boost, english_normalization
59
  ):
60
  if not text.strip():
61
+ gr.Warning("Text input cannot be empty.")
62
+ return None # Must return a value for the audio output
63
 
64
  if not REPLICATE_API_KEYS:
65
+ gr.Error("No Replicate API Tokens configured. Please set REPLICATE_API_TOKENS in secrets.")
66
+ return None
67
 
68
  if not VOICE_ID_MAP and not custom_voice_id.strip():
69
+ gr.Error("Voice ID configuration is missing (voices.json empty/invalid) and no custom voice ID provided.")
70
+ return None
71
 
72
  actual_voice_id_to_use = ""
73
  if custom_voice_id.strip():
 
75
  elif voice_id_pretty_name and voice_id_pretty_name in VOICE_ID_MAP:
76
  actual_voice_id_to_use = VOICE_ID_MAP[voice_id_pretty_name]
77
  else:
78
+ gr.Error(f"Selected voice '{voice_id_pretty_name}' not found in mappings and no custom ID provided.")
79
+ return None
 
 
80
 
81
  payload = {
82
  "input": {
83
+ "text": text, "pitch": int(pitch), "speed": float(speed), "volume": int(volume),
84
+ "bitrate": int(bitrate), "channel": channel, "emotion": emotion,
85
+ "voice_id": actual_voice_id_to_use, "sample_rate": int(sample_rate),
 
 
 
 
 
 
86
  "english_normalization": bool(english_normalization)
87
  }
88
  }
 
90
  payload["input"]["language_boost"] = language_boost
91
 
92
  num_keys_to_try = len(REPLICATE_API_KEYS)
93
+ last_error_message_for_key = ""
94
 
95
  for i in range(num_keys_to_try):
96
  api_key = get_next_api_key()
97
+ if not api_key: # Should not happen if REPLICATE_API_KEYS is populated
98
+ gr.Error("Internal error: No API keys available in the cycling pool.")
99
+ return None
100
 
101
  headers_post = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
102
  headers_get = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
103
 
104
+ print(f"Attempting API call with key ending: ...{api_key[-4:]}. Voice ID: {actual_voice_id_to_use}")
 
 
105
 
106
  try:
107
  response = requests.post(MODEL_ENDPOINT, json=payload, headers=headers_post, timeout=30)
 
116
  polling_attempts = 0
117
  while current_status in ["starting", "processing"] and prediction_url:
118
  if polling_attempts >= MAX_POLLING_ATTEMPTS:
119
+ last_error_message_for_key = f"Polling timed out for key ...{api_key[-4:]}."
120
+ print(last_error_message_for_key)
121
+ result["error"] = "Polling timed out." # For local log
122
  current_status = "failed_polling_timeout"
123
  break
 
124
  polling_attempts += 1
 
125
  time.sleep(POLL_INTERVAL)
 
126
  poll_response = requests.get(prediction_url, headers=headers_get, timeout=30)
127
  poll_response.raise_for_status()
128
  result = poll_response.json()
129
  current_status = result.get("status")
 
130
 
131
  if current_status == "succeeded":
132
  audio_url = result.get("output")
133
  if audio_url:
134
  success_logs = result.get('logs', logs_from_initial_call if logs_from_initial_call else 'N/A')
135
+ print(f"Success with key ...{api_key[-4:]}. Logs: {success_logs}")
136
+ gr.Info("Success! Audio generated.")
137
+ return audio_url
138
  else:
139
+ last_error_message_for_key = f"API succeeded (Key ...{api_key[-4:]}) but no output URL. Resp: {result}"
140
+ print(last_error_message_for_key)
141
+ continue # Try next key
142
  else: # Covers "failed", "failed_polling_timeout", or other unexpected states
143
  error_detail = result.get("error", f"Unknown error or unexpected status '{current_status}'")
144
+ last_error_message_for_key = f"Prediction failed/timed out for key ...{api_key[-4:]}. Status: {current_status}. Error: {error_detail}"
145
+ print(last_error_message_for_key)
146
+ continue # Try next key
147
 
148
  except requests.exceptions.HTTPError as e:
149
  error_text = "Unknown HTTP Error"
150
+ try: error_text = e.response.text
151
+ except AttributeError: pass
152
+ last_error_message_for_key = f"HTTP error for key ...{api_key[-4:]}: {e.response.status_code} - {error_text}"
153
+ print(last_error_message_for_key)
154
+ continue # Try next key
 
155
  except requests.exceptions.RequestException as e:
156
+ last_error_message_for_key = f"Request exception for key ...{api_key[-4:]}: {e}"
157
+ print(last_error_message_for_key)
158
+ continue # Try next key
159
 
160
+ # If all keys failed
161
+ final_error_message = "All API keys failed or an unrecoverable error occurred."
162
+ if last_error_message_for_key: # Provide a bit more context from the last attempt if available
163
+ final_error_message += f" Last attempt error: {last_error_message_for_key}"
164
+ gr.Error(final_error_message)
165
+ return None
166
 
167
 
168
  # --- Gradio UI ---
169
  with gr.Blocks(theme=gr.themes.Soft()) as app:
170
+ gr.Markdown("# Glue Up Academy Narrator")
171
+ gr.Markdown("Enter text and adjust parameters to generate speech.")
 
 
 
172
 
173
  with gr.Row():
174
  with gr.Column(scale=2):
175
  text_input = gr.Textbox(
176
  label="Text to Synthesize",
177
  lines=5,
178
+ placeholder="Enter your text here...\n💡Insert '<#0.5#>' to add a 0.5s pause. Adjust duration."
179
  )
180
  with gr.Accordion("Voice Selection", open=True):
181
+ voice_id_dropdown = gr.Dropdown(
182
  label="Choose a Voice ID",
183
+ choices=VOICE_ID_PRETTY_NAMES,
184
+ value=DEFAULT_VOICE_PRETTY_NAME
185
  )
186
  custom_voice_id_input = gr.Textbox(
187
  label="Custom Voice ID (Optional)",
188
  placeholder="e.g., my_cloned_voice_v2",
189
+ info="If filled, this will override dropdown."
 
 
 
 
190
  )
191
+ gr.Markdown("[Minimax Voices](https://www.minimax.io/audio/voices) for more options.")
192
 
193
  with gr.Accordion("Advanced Speech Parameters", open=False):
194
  speed_slider = gr.Slider(label="Speed", minimum=0.5, maximum=2, step=0.1, value=1.0)
195
  volume_slider = gr.Slider(label="Volume", minimum=0, maximum=10, step=1, value=1)
196
+ pitch_slider = gr.Slider(label="Pitch", minimum=-12, maximum=12, step=1, value=0)
197
+ english_norm_checkbox = gr.Checkbox(label="English Normalization", value=False, info="Improves number reading.")
 
198
 
199
  with gr.Accordion("Audio Format & Emotion", open=False):
200
  emotion_dropdown = gr.Dropdown(label="Emotion", choices=EMOTIONS, value="auto")
201
  sample_rate_dropdown = gr.Dropdown(label="Sample Rate (Hz)", choices=SAMPLE_RATES, value=32000, type="value")
202
  bitrate_dropdown = gr.Dropdown(label="Bitrate (bps)", choices=BITRATES, value=128000, type="value")
203
+ channel_dropdown = gr.Dropdown(label="Channels", choices=CHANNELS, value="mono")
204
+ language_boost_dropdown = gr.Dropdown(label="Language Boost", choices=LANGUAGE_BOOST_OPTIONS, value="None")
 
205
 
206
  with gr.Column(scale=1):
207
  generate_button = gr.Button("Generate Speech", variant="primary")
208
+ # REMOVED status_message Textbox
209
  audio_output = gr.Audio(label="Generated Speech", type="filepath")
210
 
211
  generate_button.click(
 
213
  inputs=[
214
  text_input, pitch_slider, speed_slider, volume_slider,
215
  bitrate_dropdown, channel_dropdown, emotion_dropdown,
216
+ voice_id_dropdown, custom_voice_id_input, sample_rate_dropdown,
217
  language_boost_dropdown, english_norm_checkbox
218
  ],
219
+ outputs=[audio_output] # REMOVED status_message from outputs
220
  )
221
 
 
 
222
  if __name__ == "__main__":
223
  if not REPLICATE_API_KEYS:
224
+ print("FATAL: REPLICATE_API_TOKENS are not set.")
225
  if not VOICE_ID_MAP:
226
+ print("WARNING: Voice ID map is empty (voices.json issue?).")
227
  app.launch(debug=True)