Spaces:
Running
Running
refactor + ui fix
Browse files- app.py +104 -388
- event_handlers.py +332 -0
- ui_layout.py +144 -0
app.py
CHANGED
|
@@ -1,439 +1,155 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
import asyncio
|
| 4 |
-
import tempfile
|
| 5 |
-
import shutil
|
| 6 |
-
import zipfile
|
| 7 |
-
import random
|
| 8 |
-
import json # Keep for other potential uses, though not primary for this config
|
| 9 |
-
import pandas as pd # Keep for now, in case other features might use it
|
| 10 |
from openai import AsyncOpenAI
|
| 11 |
-
from functools import partial # For
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
from
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 19 |
NSFW_API_URL_TEMPLATE = os.getenv("NSFW_API_URL_TEMPLATE")
|
| 20 |
-
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
if not OPENAI_API_KEY:
|
| 23 |
try:
|
|
|
|
| 24 |
from huggingface_hub import HfApi
|
| 25 |
api = HfApi()
|
| 26 |
-
space_id = os.getenv("SPACE_ID")
|
| 27 |
if space_id:
|
| 28 |
secrets = api.get_space_secrets(repo_id=space_id)
|
| 29 |
OPENAI_API_KEY = secrets.get("OPENAI_API_KEY")
|
| 30 |
NSFW_API_URL_TEMPLATE = secrets.get("NSFW_API_URL_TEMPLATE", NSFW_API_URL_TEMPLATE)
|
| 31 |
-
|
|
|
|
|
|
|
| 32 |
except Exception as e:
|
| 33 |
-
print(f"Could not retrieve secrets from Hugging Face Hub: {e}")
|
| 34 |
|
| 35 |
-
async_openai_client = None
|
| 36 |
if OPENAI_API_KEY:
|
| 37 |
async_openai_client = AsyncOpenAI(api_key=OPENAI_API_KEY)
|
| 38 |
else:
|
| 39 |
-
print("ERROR: OPENAI_API_KEY secret is not set. The application will not function properly.")
|
| 40 |
-
|
| 41 |
-
TTS_MODELS_AVAILABLE = ["tts-1", "tts-1-hd", "gpt-4o-mini-tts"]
|
| 42 |
-
if MODEL_DEFAULT not in TTS_MODELS_AVAILABLE:
|
| 43 |
-
MODEL_DEFAULT = "tts-1-hd"
|
| 44 |
-
|
| 45 |
-
SPEAKER_CONFIG_METHODS = [
|
| 46 |
-
"Single Voice (Global)",
|
| 47 |
-
"Random per Speaker",
|
| 48 |
-
"A/B Round Robin",
|
| 49 |
-
"Detailed Configuration (Per Speaker UI)"
|
| 50 |
-
]
|
| 51 |
-
DEFAULT_SPEAKER_CONFIG_METHOD = "Random per Speaker"
|
| 52 |
-
APP_AVAILABLE_VOICES = ALL_TTS_VOICES.copy() # Uses the extended list from openai_tts.py
|
| 53 |
-
|
| 54 |
-
PREDEFINED_VIBES = {
|
| 55 |
-
"None": "",
|
| 56 |
-
"Calm": "Speak in a calm, composed, and relaxed manner.",
|
| 57 |
-
"Excited": "Speak with an energetic, enthusiastic, and lively tone.",
|
| 58 |
-
"Happy": "Speak with a cheerful, bright, and joyful voice.",
|
| 59 |
-
"Sad": "Speak with a sorrowful, melancholic, and dejected tone.",
|
| 60 |
-
"Whisper": "Speak softly, as if whispering.",
|
| 61 |
-
"Angry": "Speak with a strong, firm, and possibly agitated voice.",
|
| 62 |
-
"Fearful": "Speak with a trembling, hesitant, and scared voice.",
|
| 63 |
-
"Formal": "Speak in a clear, precise, and professional tone, suitable for a formal address.",
|
| 64 |
-
"Authoritative": "Speak with a commanding, confident, and firm voice.",
|
| 65 |
-
"Friendly": "Speak in a warm, approachable, and amiable manner.",
|
| 66 |
-
"Custom...": "CUSTOM"
|
| 67 |
-
}
|
| 68 |
-
VIBE_CHOICES = list(PREDEFINED_VIBES.keys())
|
| 69 |
-
DEFAULT_VIBE = "None"
|
| 70 |
-
|
| 71 |
-
def get_speakers_from_script(script_text):
|
| 72 |
-
if not script_text.strip(): return []
|
| 73 |
-
try:
|
| 74 |
-
parsed_lines, _ = parse_dialogue_script(script_text)
|
| 75 |
-
# Return unique speakers in order of appearance (though order doesn't strictly matter for this use)
|
| 76 |
-
seen_speakers = set()
|
| 77 |
-
ordered_unique_speakers = []
|
| 78 |
-
for p in parsed_lines:
|
| 79 |
-
if p["speaker"] not in seen_speakers:
|
| 80 |
-
ordered_unique_speakers.append(p["speaker"])
|
| 81 |
-
seen_speakers.add(p["speaker"])
|
| 82 |
-
return ordered_unique_speakers
|
| 83 |
-
except ValueError: return []
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
def handle_dynamic_input_change(new_value, current_configs_state_dict, speaker_name, config_key, tts_model):
|
| 87 |
-
if speaker_name not in current_configs_state_dict:
|
| 88 |
-
current_configs_state_dict[speaker_name] = {}
|
| 89 |
-
|
| 90 |
-
current_configs_state_dict[speaker_name][config_key] = new_value
|
| 91 |
-
return current_configs_state_dict
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
def load_refresh_per_speaker_ui(script_text, current_configs_state_dict, tts_model):
|
| 95 |
-
unique_speakers = get_speakers_from_script(script_text)
|
| 96 |
-
new_ui_components = []
|
| 97 |
-
|
| 98 |
-
if current_configs_state_dict is None:
|
| 99 |
-
current_configs_state_dict = {}
|
| 100 |
-
|
| 101 |
-
for speaker_name in unique_speakers:
|
| 102 |
-
if speaker_name not in current_configs_state_dict:
|
| 103 |
-
current_configs_state_dict[speaker_name] = {
|
| 104 |
-
"voice": APP_AVAILABLE_VOICES[0],
|
| 105 |
-
"speed": 1.0,
|
| 106 |
-
"vibe": DEFAULT_VIBE,
|
| 107 |
-
"custom_instructions": ""
|
| 108 |
-
}
|
| 109 |
-
current_configs_state_dict[speaker_name].setdefault("voice", APP_AVAILABLE_VOICES[0])
|
| 110 |
-
current_configs_state_dict[speaker_name].setdefault("speed", 1.0)
|
| 111 |
-
current_configs_state_dict[speaker_name].setdefault("vibe", DEFAULT_VIBE)
|
| 112 |
-
current_configs_state_dict[speaker_name].setdefault("custom_instructions", "")
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
if not unique_speakers:
|
| 116 |
-
new_ui_components.append(gr.Markdown("No speakers detected in the script, or script is empty. Type a script and click 'Load/Refresh' again."))
|
| 117 |
-
return new_ui_components, current_configs_state_dict
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
for speaker_name in unique_speakers:
|
| 121 |
-
speaker_cfg = current_configs_state_dict[speaker_name]
|
| 122 |
-
|
| 123 |
-
speed_interactive = tts_model in ["tts-1", "tts-1-hd"]
|
| 124 |
-
instructions_relevant = tts_model == "gpt-4o-mini-tts"
|
| 125 |
-
|
| 126 |
-
with gr.Accordion(label=f"Settings for: {speaker_name}", open=False) as speaker_accordion:
|
| 127 |
-
voice_dd = gr.Dropdown(
|
| 128 |
-
label="Voice", choices=APP_AVAILABLE_VOICES, value=speaker_cfg["voice"], interactive=True
|
| 129 |
-
)
|
| 130 |
-
voice_dd.change(
|
| 131 |
-
fn=partial(handle_dynamic_input_change, speaker_name=speaker_name, config_key="voice", tts_model=tts_model),
|
| 132 |
-
inputs=[voice_dd, speaker_configs_state],
|
| 133 |
-
outputs=[speaker_configs_state]
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
speed_slider_label = "Speech Speed" + (" (Active for tts-1/hd)" if speed_interactive else " (N/A for this model)")
|
| 137 |
-
speed_slider = gr.Slider(
|
| 138 |
-
label=speed_slider_label, minimum=0.25, maximum=4.0, value=speaker_cfg["speed"],
|
| 139 |
-
step=0.05, interactive=speed_interactive
|
| 140 |
-
)
|
| 141 |
-
if speed_interactive:
|
| 142 |
-
speed_slider.release(
|
| 143 |
-
fn=partial(handle_dynamic_input_change, speaker_name=speaker_name, config_key="speed", tts_model=tts_model),
|
| 144 |
-
inputs=[speed_slider, speaker_configs_state],
|
| 145 |
-
outputs=[speaker_configs_state]
|
| 146 |
-
)
|
| 147 |
-
|
| 148 |
-
vibe_label = "Vibe/Emotion Preset" + (" (For gpt-4o-mini-tts)" if instructions_relevant else " (Less impact on other models)")
|
| 149 |
-
vibe_dd = gr.Dropdown(
|
| 150 |
-
label=vibe_label, choices=VIBE_CHOICES, value=speaker_cfg["vibe"], interactive=True
|
| 151 |
-
)
|
| 152 |
-
vibe_dd.change(
|
| 153 |
-
fn=partial(handle_dynamic_input_change, speaker_name=speaker_name, config_key="vibe", tts_model=tts_model),
|
| 154 |
-
inputs=[vibe_dd, speaker_configs_state],
|
| 155 |
-
outputs=[speaker_configs_state]
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
custom_instr_label = "Custom Instructions"
|
| 159 |
-
custom_instr_placeholder = "Only used if Vibe is 'Custom...'. Overrides Vibe."
|
| 160 |
-
custom_instr_tb = gr.Textbox(
|
| 161 |
-
label=custom_instr_label,
|
| 162 |
-
value=speaker_cfg["custom_instructions"],
|
| 163 |
-
placeholder=custom_instr_placeholder,
|
| 164 |
-
lines=2, interactive=True
|
| 165 |
-
)
|
| 166 |
-
custom_instr_tb.input(
|
| 167 |
-
fn=partial(handle_dynamic_input_change, speaker_name=speaker_name, config_key="custom_instructions", tts_model=tts_model),
|
| 168 |
-
inputs=[custom_instr_tb, speaker_configs_state],
|
| 169 |
-
outputs=[speaker_configs_state]
|
| 170 |
-
)
|
| 171 |
-
new_ui_components.append(speaker_accordion)
|
| 172 |
-
|
| 173 |
-
return new_ui_components, current_configs_state_dict
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
async def handle_script_processing(
|
| 177 |
-
dialogue_script: str, tts_model: str, pause_ms: int,
|
| 178 |
-
speaker_config_method: str, global_voice_selection: str,
|
| 179 |
-
speaker_configs_state_dict: dict,
|
| 180 |
-
global_speed: float,
|
| 181 |
-
global_instructions: str, progress=gr.Progress(track_tqdm=True)):
|
| 182 |
-
|
| 183 |
-
if not OPENAI_API_KEY or not async_openai_client: return None, None, "Error: OPENAI_API_KEY missing."
|
| 184 |
-
if not dialogue_script.strip(): return None, None, "Error: Script empty."
|
| 185 |
-
|
| 186 |
-
# Create a job-specific temporary directory and ensure it's clean
|
| 187 |
-
job_audio_path_prefix = os.path.join(tempfile.gettempdir(), f"dialogue_tts_job_{random.randint(10000, 99999)}")
|
| 188 |
-
if os.path.exists(job_audio_path_prefix): shutil.rmtree(job_audio_path_prefix)
|
| 189 |
-
os.makedirs(job_audio_path_prefix, exist_ok=True)
|
| 190 |
-
|
| 191 |
-
try:
|
| 192 |
-
parsed_lines, _ = parse_dialogue_script(dialogue_script)
|
| 193 |
-
if not parsed_lines:
|
| 194 |
-
shutil.rmtree(job_audio_path_prefix)
|
| 195 |
-
return None, None, "Error: No valid lines found in script."
|
| 196 |
-
except ValueError as e:
|
| 197 |
-
shutil.rmtree(job_audio_path_prefix)
|
| 198 |
-
return None, None, f"Script parsing error: {str(e)}"
|
| 199 |
-
|
| 200 |
-
if speaker_configs_state_dict is None: speaker_configs_state_dict = {}
|
| 201 |
-
|
| 202 |
-
# --- Voice assignment map for Random and A/B per Speaker ---
|
| 203 |
-
speaker_voice_map = {}
|
| 204 |
-
if speaker_config_method in ["Random per Speaker", "A/B Round Robin"]:
|
| 205 |
-
unique_script_speakers_for_map = get_speakers_from_script(dialogue_script)
|
| 206 |
-
if speaker_config_method == "Random per Speaker":
|
| 207 |
-
for spk_name in unique_script_speakers_for_map:
|
| 208 |
-
speaker_voice_map[spk_name] = random.choice(APP_AVAILABLE_VOICES)
|
| 209 |
-
elif speaker_config_method == "A/B Round Robin":
|
| 210 |
-
for i, spk_name in enumerate(unique_script_speakers_for_map):
|
| 211 |
-
# Ensure APP_AVAILABLE_VOICES is not empty to prevent modulo by zero
|
| 212 |
-
if APP_AVAILABLE_VOICES:
|
| 213 |
-
speaker_voice_map[spk_name] = APP_AVAILABLE_VOICES[i % len(APP_AVAILABLE_VOICES)]
|
| 214 |
-
else: # Fallback if voice list is somehow empty
|
| 215 |
-
speaker_voice_map[spk_name] = "alloy" # Default OpenAI voice
|
| 216 |
-
# --- End voice assignment map ---
|
| 217 |
-
|
| 218 |
-
tasks, line_audio_files = [], [None] * len(parsed_lines)
|
| 219 |
-
for i, line_data in enumerate(parsed_lines):
|
| 220 |
-
speaker_name = line_data["speaker"]
|
| 221 |
-
|
| 222 |
-
line_voice = global_voice_selection # Default for "Single Voice (Global)" or fallback
|
| 223 |
-
line_speed = global_speed
|
| 224 |
-
line_instructions = global_instructions if global_instructions and global_instructions.strip() else None
|
| 225 |
-
|
| 226 |
-
if speaker_config_method == "Detailed Configuration (Per Speaker UI)":
|
| 227 |
-
spk_cfg = speaker_configs_state_dict.get(speaker_name, {})
|
| 228 |
-
line_voice = spk_cfg.get("voice", global_voice_selection)
|
| 229 |
-
if tts_model in ["tts-1", "tts-1-hd"]:
|
| 230 |
-
line_speed = spk_cfg.get("speed", global_speed)
|
| 231 |
-
if tts_model == "gpt-4o-mini-tts":
|
| 232 |
-
vibe = spk_cfg.get("vibe", DEFAULT_VIBE)
|
| 233 |
-
custom_instr = spk_cfg.get("custom_instructions", "").strip()
|
| 234 |
-
if vibe == "Custom..." and custom_instr: line_instructions = custom_instr
|
| 235 |
-
elif vibe != "None" and vibe != "Custom...": line_instructions = PREDEFINED_VIBES.get(vibe, "")
|
| 236 |
-
if not line_instructions and global_instructions and global_instructions.strip(): line_instructions = global_instructions
|
| 237 |
-
elif not line_instructions : line_instructions = None
|
| 238 |
-
elif speaker_config_method == "Random per Speaker" or speaker_config_method == "A/B Round Robin":
|
| 239 |
-
line_voice = speaker_voice_map.get(speaker_name, global_voice_selection) # Use mapped voice
|
| 240 |
-
|
| 241 |
-
if tts_model not in ["tts-1", "tts-1-hd"]: line_speed = 1.0
|
| 242 |
-
|
| 243 |
-
out_fn = os.path.join(job_audio_path_prefix, f"line_{line_data['id']}.mp3")
|
| 244 |
-
progress(i / len(parsed_lines), desc=f"Synthesizing: Line {i+1}/{len(parsed_lines)} ({speaker_name})")
|
| 245 |
-
tasks.append(synthesize_speech_line(
|
| 246 |
-
client=async_openai_client, text=line_data["text"], voice=line_voice,
|
| 247 |
-
output_path=out_fn, model=tts_model, speed=line_speed,
|
| 248 |
-
instructions=line_instructions, nsfw_api_url_template=NSFW_API_URL_TEMPLATE,
|
| 249 |
-
line_index=line_data['id']))
|
| 250 |
-
|
| 251 |
-
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 252 |
-
for idx, res in enumerate(results):
|
| 253 |
-
if isinstance(res, Exception): print(f"Error synthesizing line {parsed_lines[idx]['id']}: {res}")
|
| 254 |
-
elif res is None: print(f"Skipped or failed synthesizing line {parsed_lines[idx]['id']}")
|
| 255 |
-
else: line_audio_files[parsed_lines[idx]['id']] = res # Store by original line ID if non-sequential
|
| 256 |
-
|
| 257 |
-
# Filter for valid, existing files, using the original parsed_lines order for merge
|
| 258 |
-
files_for_merge = []
|
| 259 |
-
for p_line in parsed_lines:
|
| 260 |
-
file_path = line_audio_files[p_line['id']]
|
| 261 |
-
if file_path and os.path.exists(file_path) and os.path.getsize(file_path) > 0:
|
| 262 |
-
files_for_merge.append(file_path)
|
| 263 |
-
else:
|
| 264 |
-
files_for_merge.append(None) # Keep placeholder for correct ordering if a line failed
|
| 265 |
-
|
| 266 |
-
valid_files_for_zip = [f for f in files_for_merge if f]
|
| 267 |
-
|
| 268 |
-
if not valid_files_for_zip:
|
| 269 |
-
shutil.rmtree(job_audio_path_prefix); return None, None, "Error: No audio was successfully synthesized."
|
| 270 |
-
|
| 271 |
-
zip_fn = os.path.join(job_audio_path_prefix, "dialogue_lines.zip")
|
| 272 |
-
with zipfile.ZipFile(zip_fn, 'w') as zf:
|
| 273 |
-
for f_path in valid_files_for_zip:
|
| 274 |
-
zf.write(f_path, os.path.basename(f_path))
|
| 275 |
-
|
| 276 |
-
merged_fn = os.path.join(job_audio_path_prefix, "merged_dialogue.mp3")
|
| 277 |
-
# Pass only existing files to merge_mp3_files, maintaining order
|
| 278 |
-
ordered_files_to_merge = [f for f in files_for_merge if f]
|
| 279 |
-
merged_path = merge_mp3_files(ordered_files_to_merge, merged_fn, pause_ms)
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
status = f"Successfully processed {len(valid_files_for_zip)} out of {len(parsed_lines)} lines. "
|
| 283 |
-
if len(valid_files_for_zip) < len(parsed_lines): status += "Some lines may have failed. "
|
| 284 |
-
if not merged_path and len(valid_files_for_zip) > 0: status += "Merging audio failed. "
|
| 285 |
-
elif not merged_path: status = "No audio to merge." # Overrides previous status if all failed before merge
|
| 286 |
-
else: status += "Merged audio generated."
|
| 287 |
-
|
| 288 |
-
# Note: job_audio_path_prefix (temp dir) is not explicitly deleted here.
|
| 289 |
-
# Gradio File/Audio components copy the file, so the temp dir can be cleaned
|
| 290 |
-
# by the OS or a cleanup routine if this Space were long-running.
|
| 291 |
-
# For HF Spaces, /tmp is ephemeral anyway. For robustness, could add shutil.rmtree(job_audio_path_prefix)
|
| 292 |
-
# after files are served, but need to ensure Gradio has finished with them.
|
| 293 |
-
# For now, rely on new unique dir per run and ephemeral /tmp.
|
| 294 |
-
|
| 295 |
-
return (zip_fn if os.path.exists(zip_fn) else None,
|
| 296 |
-
merged_path if merged_path and os.path.exists(merged_path) else None,
|
| 297 |
-
status)
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
def handle_calculate_cost(dialogue_script: str, tts_model: str):
|
| 301 |
-
if not dialogue_script.strip(): return "Cost: $0.00 (Script is empty)"
|
| 302 |
-
try:
|
| 303 |
-
parsed, chars = parse_dialogue_script(dialogue_script)
|
| 304 |
-
if not parsed: return "Cost: $0.00 (No valid lines in script)"
|
| 305 |
-
cost = calculate_cost(chars, len(parsed), tts_model)
|
| 306 |
-
# Using .6f for precision, especially for char-based cost
|
| 307 |
-
return f"Estimated Cost for {len(parsed)} lines ({chars} chars): ${cost:.6f}"
|
| 308 |
-
except ValueError as e: # Catch script length error from parser
|
| 309 |
-
return f"Cost calculation error: {str(e)}"
|
| 310 |
-
except Exception as e:
|
| 311 |
-
return f"An unexpected error occurred during cost calculation: {str(e)}"
|
| 312 |
|
| 313 |
|
|
|
|
| 314 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 315 |
-
gr.Markdown("# Dialogue Script to Speech (OpenAI TTS)")
|
| 316 |
if not OPENAI_API_KEY or not async_openai_client:
|
| 317 |
-
gr.Markdown("<h3 style='color:red;'>⚠️ Warning: OPENAI_API_KEY
|
| 318 |
|
| 319 |
-
|
|
|
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
with gr.Column(scale=1):
|
| 325 |
-
tts_model_dropdown = gr.Dropdown(TTS_MODELS_AVAILABLE, label="TTS Model", value=MODEL_DEFAULT)
|
| 326 |
-
pause_input = gr.Number(label="Pause Between Lines (ms)", value=500, minimum=0, maximum=5000, step=50)
|
| 327 |
-
global_speed_input = gr.Slider(minimum=0.25, maximum=4.0, value=1.0, step=0.05, label="Global Speed (for tts-1/hd)", visible=(MODEL_DEFAULT in ["tts-1", "tts-1-hd"]), interactive=True)
|
| 328 |
-
global_instructions_input = gr.Textbox(label="Global Instructions (for gpt-4o-mini-tts)", placeholder="e.g., Speak with a calm tone.", visible=(MODEL_DEFAULT == "gpt-4o-mini-tts"), interactive=True, lines=2)
|
| 329 |
-
|
| 330 |
-
gr.Markdown("### Speaker Voice & Style Configuration")
|
| 331 |
-
speaker_config_method_dropdown = gr.Dropdown(
|
| 332 |
-
SPEAKER_CONFIG_METHODS, label="Configuration Method", value=DEFAULT_SPEAKER_CONFIG_METHOD
|
| 333 |
-
)
|
| 334 |
-
|
| 335 |
-
with gr.Group(visible=(DEFAULT_SPEAKER_CONFIG_METHOD == "Single Voice (Global)")) as single_voice_group:
|
| 336 |
-
global_voice_dropdown = gr.Dropdown(
|
| 337 |
-
APP_AVAILABLE_VOICES, label="Global Voice", value=APP_AVAILABLE_VOICES[0] if APP_AVAILABLE_VOICES else "alloy", interactive=True
|
| 338 |
-
)
|
| 339 |
-
|
| 340 |
-
with gr.Column(visible=(DEFAULT_SPEAKER_CONFIG_METHOD == "Detailed Configuration (Per Speaker UI)")) as detailed_per_speaker_ui_group:
|
| 341 |
-
load_per_speaker_ui_button = gr.Button("Load/Refresh Per-Speaker Settings UI (from Script Above)")
|
| 342 |
-
gr.Markdown("<small>Click button above to populate settings for each speaker found in the script. Settings are applied per-speaker. If script changes, click again to refresh.</small>")
|
| 343 |
-
dynamic_speaker_ui_area = gr.Column(elem_id="dynamic_ui_area_for_speakers")
|
| 344 |
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
cost_output = gr.Textbox(label="Estimated Cost", interactive=False)
|
| 351 |
-
with gr.Row():
|
| 352 |
-
individual_lines_zip_output = gr.File(label="Download Individual Lines (ZIP)")
|
| 353 |
-
merged_dialogue_mp3_output = gr.Audio(label="Play/Download Merged Dialogue (MP3)", type="filepath")
|
| 354 |
-
status_output = gr.Textbox(label="Status", interactive=False, lines=2, max_lines=5)
|
| 355 |
|
| 356 |
-
|
| 357 |
-
new_dynamic_ui_components, updated_state = load_refresh_per_speaker_ui(script_text_for_refresh, current_speaker_configs_for_refresh, selected_model)
|
| 358 |
-
|
| 359 |
-
is_tts1_family = selected_model in ["tts-1", "tts-1-hd"]
|
| 360 |
-
is_gpt_mini_tts = selected_model == "gpt-4o-mini-tts"
|
| 361 |
-
|
| 362 |
-
# It's crucial that dynamic_speaker_ui_area receives the *list* of components.
|
| 363 |
-
# If it's wrapped in a gr.update, it might not render correctly unless gr.update(children=...)
|
| 364 |
-
# Direct assignment seems to be what Gradio expects when outputting to a Column/Row that acts as a container.
|
| 365 |
-
return {
|
| 366 |
-
global_speed_input: gr.update(visible=is_tts1_family, interactive=is_tts1_family),
|
| 367 |
-
global_instructions_input: gr.update(visible=is_gpt_mini_tts, interactive=is_gpt_mini_tts),
|
| 368 |
-
dynamic_speaker_ui_area: new_dynamic_ui_components,
|
| 369 |
-
speaker_configs_state: updated_state
|
| 370 |
-
}
|
| 371 |
|
|
|
|
| 372 |
tts_model_dropdown.change(
|
| 373 |
-
fn=update_model_controls_visibility,
|
| 374 |
-
inputs=[tts_model_dropdown, script_input, speaker_configs_state],
|
|
|
|
|
|
|
| 375 |
outputs=[global_speed_input, global_instructions_input, dynamic_speaker_ui_area, speaker_configs_state]
|
| 376 |
)
|
| 377 |
|
| 378 |
-
|
| 379 |
-
is_single = (method == "Single Voice (Global)")
|
| 380 |
-
is_detailed_per_speaker = (method == "Detailed Configuration (Per Speaker UI)")
|
| 381 |
-
return {
|
| 382 |
-
single_voice_group: gr.update(visible=is_single),
|
| 383 |
-
detailed_per_speaker_ui_group: gr.update(visible=is_detailed_per_speaker),
|
| 384 |
-
}
|
| 385 |
speaker_config_method_dropdown.change(
|
| 386 |
-
fn=update_speaker_config_method_visibility,
|
| 387 |
-
inputs=[speaker_config_method_dropdown],
|
|
|
|
| 388 |
outputs=[single_voice_group, detailed_per_speaker_ui_group]
|
| 389 |
)
|
| 390 |
|
|
|
|
| 391 |
load_per_speaker_ui_button.click(
|
| 392 |
fn=load_refresh_per_speaker_ui,
|
| 393 |
-
inputs=[script_input, speaker_configs_state, tts_model_dropdown],
|
| 394 |
-
outputs=[dynamic_speaker_ui_area, speaker_configs_state]
|
| 395 |
)
|
| 396 |
|
| 397 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
|
|
|
|
|
|
|
|
|
|
| 399 |
generate_button.click(
|
| 400 |
-
fn=handle_script_processing,
|
| 401 |
inputs=[
|
| 402 |
-
script_input, tts_model_dropdown, pause_input,
|
| 403 |
-
speaker_config_method_dropdown, global_voice_dropdown,
|
| 404 |
-
speaker_configs_state,
|
| 405 |
global_speed_input, global_instructions_input
|
| 406 |
],
|
| 407 |
-
outputs=[individual_lines_zip_output, merged_dialogue_mp3_output, status_output]
|
| 408 |
-
|
| 409 |
-
gr.Markdown("## Example Scripts")
|
| 410 |
-
example_script_1 = "[Alice] Hello Bob, this is a test using the detailed configuration method.\n[Bob] Hi Alice! I'm Bob, and I'll have my own voice settings.\n[Alice] Let's see how this sounds."
|
| 411 |
-
example_script_2 = "[Narrator] This is a short story.\n[CharacterA] Once upon a time...\n[Narrator] ...there was a Gradio app.\n[CharacterB] And it could talk!"
|
| 412 |
-
|
| 413 |
-
gr.Examples(
|
| 414 |
-
examples=[
|
| 415 |
-
[example_script_1, "tts-1-hd", 300, "Detailed Configuration (Per Speaker UI)", APP_AVAILABLE_VOICES[0] if APP_AVAILABLE_VOICES else "alloy", {}, 1.0, ""],
|
| 416 |
-
[example_script_2, "gpt-4o-mini-tts", 200, "Random per Speaker", APP_AVAILABLE_VOICES[0] if APP_AVAILABLE_VOICES else "alloy", {}, 1.0, "Speak with a gentle, storytelling voice for the narrator."],
|
| 417 |
-
["[Solo] Just one line, using global voice and speed.", "tts-1", 0, "Single Voice (Global)", "fable", {}, 1.2, ""],
|
| 418 |
-
],
|
| 419 |
-
# speaker_configs_state is passed as an empty dict {} for examples.
|
| 420 |
-
# For "Detailed Configuration", the user should click "Load/Refresh Per-Speaker UI" after an example loads to populate the UI.
|
| 421 |
-
inputs=[
|
| 422 |
-
script_input, tts_model_dropdown, pause_input,
|
| 423 |
-
speaker_config_method_dropdown, global_voice_dropdown,
|
| 424 |
-
speaker_configs_state,
|
| 425 |
-
global_speed_input, global_instructions_input
|
| 426 |
-
],
|
| 427 |
-
# Outputs for examples are not strictly necessary to pre-compute if cache_examples=False
|
| 428 |
-
# but defining them can help Gradio understand the flow.
|
| 429 |
-
# We can make the example click run the full processing.
|
| 430 |
-
outputs=[individual_lines_zip_output, merged_dialogue_mp3_output, status_output],
|
| 431 |
-
fn=handle_script_processing,
|
| 432 |
-
cache_examples=False # Set to True if pre-computation is desired and feasible
|
| 433 |
)
|
| 434 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
if __name__ == "__main__":
|
| 436 |
-
|
| 437 |
-
if os.name == 'nt':
|
| 438 |
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
| 439 |
-
demo.launch(debug=True) #
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
import asyncio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from openai import AsyncOpenAI
|
| 5 |
+
from functools import partial # For handle_script_processing
|
| 6 |
+
|
| 7 |
+
# Import UI creation functions and constants
|
| 8 |
+
from ui_layout import (
|
| 9 |
+
create_main_input_components, create_speaker_config_components,
|
| 10 |
+
create_action_and_output_components, create_examples_ui,
|
| 11 |
+
TTS_MODELS_AVAILABLE, MODEL_DEFAULT_ENV
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
# Import event handler functions
|
| 15 |
+
from event_handlers import (
|
| 16 |
+
handle_script_processing, handle_calculate_cost,
|
| 17 |
+
update_model_controls_visibility, update_speaker_config_method_visibility,
|
| 18 |
+
load_refresh_per_speaker_ui
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# --- Application Secrets and Global Client ---
|
| 22 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 23 |
NSFW_API_URL_TEMPLATE = os.getenv("NSFW_API_URL_TEMPLATE")
|
| 24 |
+
MODEL_DEFAULT_FROM_ENV = os.getenv("MODEL_DEFAULT", MODEL_DEFAULT_ENV)
|
| 25 |
|
| 26 |
+
# Validate MODEL_DEFAULT_FROM_ENV or use hardcoded default
|
| 27 |
+
EFFECTIVE_MODEL_DEFAULT = MODEL_DEFAULT_FROM_ENV if MODEL_DEFAULT_FROM_ENV in TTS_MODELS_AVAILABLE else MODEL_DEFAULT_ENV
|
| 28 |
+
|
| 29 |
+
async_openai_client = None
|
| 30 |
if not OPENAI_API_KEY:
|
| 31 |
try:
|
| 32 |
+
# Attempt to load from Hugging Face Hub secrets if not in env
|
| 33 |
from huggingface_hub import HfApi
|
| 34 |
api = HfApi()
|
| 35 |
+
space_id = os.getenv("SPACE_ID") # Provided by HF Spaces
|
| 36 |
if space_id:
|
| 37 |
secrets = api.get_space_secrets(repo_id=space_id)
|
| 38 |
OPENAI_API_KEY = secrets.get("OPENAI_API_KEY")
|
| 39 |
NSFW_API_URL_TEMPLATE = secrets.get("NSFW_API_URL_TEMPLATE", NSFW_API_URL_TEMPLATE)
|
| 40 |
+
MODEL_DEFAULT_FROM_HUB = secrets.get("MODEL_DEFAULT", EFFECTIVE_MODEL_DEFAULT)
|
| 41 |
+
EFFECTIVE_MODEL_DEFAULT = MODEL_DEFAULT_FROM_HUB if MODEL_DEFAULT_FROM_HUB in TTS_MODELS_AVAILABLE else EFFECTIVE_MODEL_DEFAULT
|
| 42 |
+
print("Loaded secrets from Hugging Face Hub.")
|
| 43 |
except Exception as e:
|
| 44 |
+
print(f"Could not retrieve secrets from Hugging Face Hub: {e}. OPENAI_API_KEY might be missing.")
|
| 45 |
|
|
|
|
| 46 |
if OPENAI_API_KEY:
|
| 47 |
async_openai_client = AsyncOpenAI(api_key=OPENAI_API_KEY)
|
| 48 |
else:
|
| 49 |
+
print("CRITICAL ERROR: OPENAI_API_KEY secret is not set. The application will not function properly.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
+
# --- Gradio Application UI and Logic ---
|
| 53 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 54 |
+
gr.Markdown("# Dialogue Script to Speech (OpenAI TTS) - Refactored")
|
| 55 |
if not OPENAI_API_KEY or not async_openai_client:
|
| 56 |
+
gr.Markdown("<h3 style='color:red;'>⚠️ Warning: OPENAI_API_KEY not set or invalid. Audio generation will fail. Please configure it in your Space settings.</h3>")
|
| 57 |
|
| 58 |
+
# Central state for detailed speaker configurations
|
| 59 |
+
speaker_configs_state = gr.State({}) # This is crucial for dynamic UI
|
| 60 |
|
| 61 |
+
# --- Define UI Components by calling layout functions ---
|
| 62 |
+
(script_input, tts_model_dropdown, pause_input,
|
| 63 |
+
global_speed_input, global_instructions_input) = create_main_input_components(EFFECTIVE_MODEL_DEFAULT)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
(speaker_config_method_dropdown, single_voice_group, global_voice_dropdown,
|
| 66 |
+
detailed_per_speaker_ui_group, load_per_speaker_ui_button,
|
| 67 |
+
dynamic_speaker_ui_area) = create_speaker_config_components()
|
| 68 |
|
| 69 |
+
(calculate_cost_button, generate_button, cost_output,
|
| 70 |
+
individual_lines_zip_output, merged_dialogue_mp3_output,
|
| 71 |
+
status_output) = create_action_and_output_components()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
# --- Event Wiring ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
# When TTS model changes, update visibility of global speed/instructions & refresh dynamic UI
|
| 76 |
tts_model_dropdown.change(
|
| 77 |
+
fn=update_model_controls_visibility,
|
| 78 |
+
inputs=[tts_model_dropdown, script_input, speaker_configs_state, speaker_configs_state], # Pass state component itself
|
| 79 |
+
# The outputs list names the components that will be updated by the dictionary keys
|
| 80 |
+
# returned by update_model_controls_visibility.
|
| 81 |
outputs=[global_speed_input, global_instructions_input, dynamic_speaker_ui_area, speaker_configs_state]
|
| 82 |
)
|
| 83 |
|
| 84 |
+
# When speaker config method changes, update visibility of relevant UI groups
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
speaker_config_method_dropdown.change(
|
| 86 |
+
fn=update_speaker_config_method_visibility,
|
| 87 |
+
inputs=[speaker_config_method_dropdown],
|
| 88 |
+
# The outputs list names the components that will be updated by the dictionary keys.
|
| 89 |
outputs=[single_voice_group, detailed_per_speaker_ui_group]
|
| 90 |
)
|
| 91 |
|
| 92 |
+
# Button to load/refresh the detailed per-speaker UI configurations
|
| 93 |
load_per_speaker_ui_button.click(
|
| 94 |
fn=load_refresh_per_speaker_ui,
|
| 95 |
+
inputs=[script_input, speaker_configs_state, tts_model_dropdown, speaker_configs_state], # Pass state comp
|
| 96 |
+
outputs=[dynamic_speaker_ui_area, speaker_configs_state]
|
| 97 |
)
|
| 98 |
|
| 99 |
+
# Calculate cost button
|
| 100 |
+
calculate_cost_button.click(
|
| 101 |
+
fn=handle_calculate_cost,
|
| 102 |
+
inputs=[script_input, tts_model_dropdown],
|
| 103 |
+
outputs=[cost_output]
|
| 104 |
+
)
|
| 105 |
|
| 106 |
+
# Generate audio button
|
| 107 |
+
# Use functools.partial to pass fixed arguments like API key and client to the handler
|
| 108 |
+
# Gradio inputs will be appended to these fixed arguments when the handler is called.
|
| 109 |
generate_button.click(
|
| 110 |
+
fn=partial(handle_script_processing, OPENAI_API_KEY, async_openai_client, NSFW_API_URL_TEMPLATE),
|
| 111 |
inputs=[
|
| 112 |
+
script_input, tts_model_dropdown, pause_input,
|
| 113 |
+
speaker_config_method_dropdown, global_voice_dropdown,
|
| 114 |
+
speaker_configs_state, # The gr.State object itself
|
| 115 |
global_speed_input, global_instructions_input
|
| 116 |
],
|
| 117 |
+
outputs=[individual_lines_zip_output, merged_dialogue_mp3_output, status_output]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
)
|
| 119 |
|
| 120 |
+
# --- Examples UI ---
|
| 121 |
+
# Define inputs for examples (must match the structure in ui_layout.create_examples_ui)
|
| 122 |
+
# This list should contain the Gradio component instances
|
| 123 |
+
example_inputs_list = [
|
| 124 |
+
script_input, tts_model_dropdown, pause_input,
|
| 125 |
+
speaker_config_method_dropdown, global_voice_dropdown,
|
| 126 |
+
speaker_configs_state, # This is a gr.State component, gr.Examples handles it
|
| 127 |
+
global_speed_input, global_instructions_input
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
# For examples to run the processing function, they need output components too.
|
| 131 |
+
example_outputs_list = [individual_lines_zip_output, merged_dialogue_mp3_output, status_output]
|
| 132 |
+
|
| 133 |
+
# Create examples UI - now passing the process_fn correctly
|
| 134 |
+
# We need a wrapper for the process_fn if it uses partial for fixed args like the main button.
|
| 135 |
+
# Or, examples can just load inputs, and user clicks "Generate".
|
| 136 |
+
# For now, let's make examples only load inputs to simplify.
|
| 137 |
+
# To make examples runnable:
|
| 138 |
+
# example_process_fn = partial(handle_script_processing, OPENAI_API_KEY, async_openai_client, NSFW_API_URL_TEMPLATE)
|
| 139 |
+
# Then use example_process_fn in create_examples_ui if it's set up to take `fn`.
|
| 140 |
+
# The current create_examples_ui doesn't use `fn` for simplicity of fixing display.
|
| 141 |
+
|
| 142 |
+
_ = create_examples_ui(inputs_for_examples=example_inputs_list, process_fn=None)
|
| 143 |
+
# If you want examples to be clickable to run the generation directly:
|
| 144 |
+
# 1. Modify `create_examples_ui` in `ui_layout.py` to accept and use `fn` and `outputs_for_examples`.
|
| 145 |
+
# Its gr.Examples call would be:
|
| 146 |
+
# `gr.Examples(..., fn=process_fn, outputs=outputs_for_examples, cache_examples=False)`
|
| 147 |
+
# 2. In this file, define `example_process_fn` and pass it:
|
| 148 |
+
# `example_process_fn = partial(handle_script_processing, OPENAI_API_KEY, async_openai_client, NSFW_API_URL_TEMPLATE)`
|
| 149 |
+
# `_ = create_examples_ui(inputs_for_examples=example_inputs_list, outputs_for_examples=example_outputs_list, process_fn=example_process_fn)`
|
| 150 |
+
|
| 151 |
+
# --- Launch ---
|
| 152 |
if __name__ == "__main__":
|
| 153 |
+
if os.name == 'nt':
|
|
|
|
| 154 |
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
| 155 |
+
demo.queue().launch(debug=True, share=False) # .queue() is good for async operations
|
event_handlers.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import asyncio
|
| 4 |
+
import tempfile
|
| 5 |
+
import shutil
|
| 6 |
+
import zipfile
|
| 7 |
+
import random
|
| 8 |
+
from functools import partial
|
| 9 |
+
|
| 10 |
+
from utils.script_parser import parse_dialogue_script, calculate_cost
|
| 11 |
+
from utils.openai_tts import synthesize_speech_line
|
| 12 |
+
from utils.merge_audio import merge_mp3_files
|
| 13 |
+
|
| 14 |
+
# Import constants from ui_layout to avoid circular dependencies if they were in app.py
|
| 15 |
+
from ui_layout import APP_AVAILABLE_VOICES, DEFAULT_VIBE, VIBE_CHOICES, PREDEFINED_VIBES
|
| 16 |
+
|
| 17 |
+
# Ensure a default voice if APP_AVAILABLE_VOICES is empty (shouldn't happen with new ui_layout)
|
| 18 |
+
DEFAULT_FALLBACK_VOICE = APP_AVAILABLE_VOICES[0] if APP_AVAILABLE_VOICES else "alloy"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_speakers_from_script(script_text: str):
|
| 22 |
+
if not script_text.strip():
|
| 23 |
+
return []
|
| 24 |
+
try:
|
| 25 |
+
parsed_lines, _ = parse_dialogue_script(script_text)
|
| 26 |
+
seen_speakers = set()
|
| 27 |
+
ordered_unique_speakers = []
|
| 28 |
+
for p in parsed_lines:
|
| 29 |
+
if p["speaker"] not in seen_speakers:
|
| 30 |
+
ordered_unique_speakers.append(p["speaker"])
|
| 31 |
+
seen_speakers.add(p["speaker"])
|
| 32 |
+
return ordered_unique_speakers
|
| 33 |
+
except ValueError:
|
| 34 |
+
return []
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def handle_dynamic_input_change(new_value, current_configs_state_dict: dict, speaker_name: str, config_key: str, tts_model: str):
|
| 38 |
+
"""Handles changes from dynamically generated UI elements for per-speaker settings."""
|
| 39 |
+
# print(f"Dynamic change for {speaker_name}, key {config_key}: {new_value}. State: {current_configs_state_dict}")
|
| 40 |
+
if current_configs_state_dict is None: # Should ideally be initialized by Gradio's gr.State
|
| 41 |
+
current_configs_state_dict = {}
|
| 42 |
+
if speaker_name not in current_configs_state_dict:
|
| 43 |
+
current_configs_state_dict[speaker_name] = {}
|
| 44 |
+
|
| 45 |
+
current_configs_state_dict[speaker_name][config_key] = new_value
|
| 46 |
+
return current_configs_state_dict
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def load_refresh_per_speaker_ui(script_text: str, current_configs_state_dict: dict, tts_model: str, speaker_configs_state_component: gr.State):
|
| 50 |
+
"""
|
| 51 |
+
Generates or refreshes the dynamic UI components (accordions) for each speaker.
|
| 52 |
+
Returns a list of Gradio components to populate the dynamic UI area and the updated state.
|
| 53 |
+
"""
|
| 54 |
+
print(f"Load/Refresh UI called. TTS Model: {tts_model}") # Debug
|
| 55 |
+
unique_speakers = get_speakers_from_script(script_text)
|
| 56 |
+
new_ui_components = []
|
| 57 |
+
|
| 58 |
+
if current_configs_state_dict is None:
|
| 59 |
+
current_configs_state_dict = {}
|
| 60 |
+
|
| 61 |
+
# Ensure a default voice for safety
|
| 62 |
+
safe_default_voice = APP_AVAILABLE_VOICES[0] if APP_AVAILABLE_VOICES else "alloy"
|
| 63 |
+
|
| 64 |
+
for speaker_name in unique_speakers:
|
| 65 |
+
if speaker_name not in current_configs_state_dict:
|
| 66 |
+
current_configs_state_dict[speaker_name] = {
|
| 67 |
+
"voice": safe_default_voice, "speed": 1.0,
|
| 68 |
+
"vibe": DEFAULT_VIBE, "custom_instructions": ""
|
| 69 |
+
}
|
| 70 |
+
# Ensure all keys exist with defaults
|
| 71 |
+
current_configs_state_dict[speaker_name].setdefault("voice", safe_default_voice)
|
| 72 |
+
current_configs_state_dict[speaker_name].setdefault("speed", 1.0)
|
| 73 |
+
current_configs_state_dict[speaker_name].setdefault("vibe", DEFAULT_VIBE)
|
| 74 |
+
current_configs_state_dict[speaker_name].setdefault("custom_instructions", "")
|
| 75 |
+
|
| 76 |
+
if not unique_speakers:
|
| 77 |
+
print("No unique speakers found, returning markdown.") # Debug
|
| 78 |
+
new_ui_components.append(gr.Markdown("No speakers detected in the script, or script is empty. Type a script and click 'Load/Refresh' again, or change the script content."))
|
| 79 |
+
return new_ui_components, current_configs_state_dict
|
| 80 |
+
|
| 81 |
+
print(f"Found speakers: {unique_speakers}. Building UI...") # Debug
|
| 82 |
+
for speaker_name in unique_speakers:
|
| 83 |
+
speaker_cfg = current_configs_state_dict[speaker_name]
|
| 84 |
+
|
| 85 |
+
speed_interactive = tts_model in ["tts-1", "tts-1-hd"]
|
| 86 |
+
instructions_relevant = tts_model == "gpt-4o-mini-tts"
|
| 87 |
+
|
| 88 |
+
# Use a unique elem_id for each accordion to help Gradio differentiate if needed
|
| 89 |
+
accordion_elem_id = f"accordion_speaker_{speaker_name.replace(' ', '_')}"
|
| 90 |
+
|
| 91 |
+
with gr.Accordion(label=f"Settings for: {speaker_name}", open=False, elem_id=accordion_elem_id) as speaker_accordion:
|
| 92 |
+
# Voice Dropdown
|
| 93 |
+
voice_dd = gr.Dropdown(
|
| 94 |
+
label="Voice", choices=APP_AVAILABLE_VOICES, value=speaker_cfg.get("voice", safe_default_voice), interactive=True
|
| 95 |
+
)
|
| 96 |
+
voice_dd.change(
|
| 97 |
+
fn=partial(handle_dynamic_input_change, speaker_name=speaker_name, config_key="voice", tts_model=tts_model),
|
| 98 |
+
inputs=[voice_dd, speaker_configs_state_component],
|
| 99 |
+
outputs=[speaker_configs_state_component]
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Speed Slider
|
| 103 |
+
speed_slider_label = "Speech Speed" + (" (Active for tts-1/hd)" if speed_interactive else " (N/A for this model)")
|
| 104 |
+
speed_slider = gr.Slider(
|
| 105 |
+
label=speed_slider_label, minimum=0.25, maximum=4.0, value=float(speaker_cfg.get("speed", 1.0)),
|
| 106 |
+
step=0.05, interactive=speed_interactive
|
| 107 |
+
)
|
| 108 |
+
if speed_interactive:
|
| 109 |
+
speed_slider.release(
|
| 110 |
+
fn=partial(handle_dynamic_input_change, speaker_name=speaker_name, config_key="speed", tts_model=tts_model),
|
| 111 |
+
inputs=[speed_slider, speaker_configs_state_component],
|
| 112 |
+
outputs=[speaker_configs_state_component]
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Vibe Dropdown
|
| 116 |
+
vibe_label = "Vibe/Emotion Preset" + (" (For gpt-4o-mini-tts)" if instructions_relevant else " (Less impact on other models)")
|
| 117 |
+
vibe_dd = gr.Dropdown(
|
| 118 |
+
label=vibe_label, choices=VIBE_CHOICES, value=speaker_cfg.get("vibe", DEFAULT_VIBE), interactive=True
|
| 119 |
+
)
|
| 120 |
+
vibe_dd.change(
|
| 121 |
+
fn=partial(handle_dynamic_input_change, speaker_name=speaker_name, config_key="vibe", tts_model=tts_model),
|
| 122 |
+
inputs=[vibe_dd, speaker_configs_state_component],
|
| 123 |
+
outputs=[speaker_configs_state_component]
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Custom Instructions Textbox
|
| 127 |
+
custom_instr_label = "Custom Instructions"
|
| 128 |
+
custom_instr_placeholder = "Used if Vibe is 'Custom...'. Overrides Vibe preset."
|
| 129 |
+
custom_instr_tb = gr.Textbox(
|
| 130 |
+
label=custom_instr_label,
|
| 131 |
+
value=speaker_cfg.get("custom_instructions", ""),
|
| 132 |
+
placeholder=custom_instr_placeholder,
|
| 133 |
+
lines=2, interactive=True
|
| 134 |
+
)
|
| 135 |
+
custom_instr_tb.input(
|
| 136 |
+
fn=partial(handle_dynamic_input_change, speaker_name=speaker_name, config_key="custom_instructions", tts_model=tts_model),
|
| 137 |
+
inputs=[custom_instr_tb, speaker_configs_state_component],
|
| 138 |
+
outputs=[speaker_configs_state_component]
|
| 139 |
+
)
|
| 140 |
+
new_ui_components.append(speaker_accordion)
|
| 141 |
+
|
| 142 |
+
print(f"Returning {len(new_ui_components)} UI components for dynamic area.") # Debug
|
| 143 |
+
return new_ui_components, current_configs_state_dict
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
async def handle_script_processing(
|
| 147 |
+
openai_api_key: str, async_openai_client, nsfw_api_url_template: str, # Passed from app.py
|
| 148 |
+
dialogue_script: str, tts_model: str, pause_ms: int,
|
| 149 |
+
speaker_config_method: str, global_voice_selection: str,
|
| 150 |
+
speaker_configs_state_dict: dict,
|
| 151 |
+
global_speed: float,
|
| 152 |
+
global_instructions: str,
|
| 153 |
+
progress=gr.Progress(track_tqdm=True)
|
| 154 |
+
):
|
| 155 |
+
if not openai_api_key or not async_openai_client:
|
| 156 |
+
return None, None, "Error: OpenAI API Key or client is not configured."
|
| 157 |
+
if not dialogue_script.strip():
|
| 158 |
+
return None, None, "Error: Script is empty."
|
| 159 |
+
|
| 160 |
+
job_audio_path_prefix = os.path.join(tempfile.gettempdir(), f"dialogue_tts_job_{random.randint(10000, 99999)}")
|
| 161 |
+
if os.path.exists(job_audio_path_prefix): shutil.rmtree(job_audio_path_prefix)
|
| 162 |
+
os.makedirs(job_audio_path_prefix, exist_ok=True)
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
parsed_lines, _ = parse_dialogue_script(dialogue_script)
|
| 166 |
+
if not parsed_lines:
|
| 167 |
+
shutil.rmtree(job_audio_path_prefix)
|
| 168 |
+
return None, None, "Error: No valid lines found in script."
|
| 169 |
+
except ValueError as e:
|
| 170 |
+
shutil.rmtree(job_audio_path_prefix)
|
| 171 |
+
return None, None, f"Script parsing error: {str(e)}"
|
| 172 |
+
|
| 173 |
+
if speaker_configs_state_dict is None: speaker_configs_state_dict = {}
|
| 174 |
+
|
| 175 |
+
# Ensure a default voice for safety
|
| 176 |
+
safe_default_global_voice = global_voice_selection if global_voice_selection in APP_AVAILABLE_VOICES else DEFAULT_FALLBACK_VOICE
|
| 177 |
+
|
| 178 |
+
speaker_voice_map = {}
|
| 179 |
+
if speaker_config_method in ["Random per Speaker", "A/B Round Robin"]:
|
| 180 |
+
unique_script_speakers_for_map = get_speakers_from_script(dialogue_script)
|
| 181 |
+
temp_voices_pool = APP_AVAILABLE_VOICES.copy()
|
| 182 |
+
if not temp_voices_pool: temp_voices_pool = [DEFAULT_FALLBACK_VOICE] # Ensure pool isn't empty
|
| 183 |
+
|
| 184 |
+
if speaker_config_method == "Random per Speaker":
|
| 185 |
+
for spk_name in unique_script_speakers_for_map:
|
| 186 |
+
speaker_voice_map[spk_name] = random.choice(temp_voices_pool)
|
| 187 |
+
elif speaker_config_method == "A/B Round Robin":
|
| 188 |
+
for i, spk_name in enumerate(unique_script_speakers_for_map):
|
| 189 |
+
speaker_voice_map[spk_name] = temp_voices_pool[i % len(temp_voices_pool)]
|
| 190 |
+
|
| 191 |
+
tasks = []
|
| 192 |
+
# line_audio_files map to store results by original line ID for correct ordering
|
| 193 |
+
line_audio_files_map = {}
|
| 194 |
+
|
| 195 |
+
for i, line_data in enumerate(parsed_lines):
|
| 196 |
+
speaker_name = line_data["speaker"]
|
| 197 |
+
line_voice = safe_default_global_voice
|
| 198 |
+
line_speed = global_speed
|
| 199 |
+
line_instructions = global_instructions if global_instructions and global_instructions.strip() else None
|
| 200 |
+
|
| 201 |
+
if speaker_config_method == "Detailed Configuration (Per Speaker UI)":
|
| 202 |
+
spk_cfg = speaker_configs_state_dict.get(speaker_name, {})
|
| 203 |
+
line_voice = spk_cfg.get("voice", safe_default_global_voice)
|
| 204 |
+
if tts_model in ["tts-1", "tts-1-hd"]:
|
| 205 |
+
line_speed = float(spk_cfg.get("speed", global_speed))
|
| 206 |
+
if tts_model == "gpt-4o-mini-tts":
|
| 207 |
+
vibe = spk_cfg.get("vibe", DEFAULT_VIBE)
|
| 208 |
+
custom_instr = spk_cfg.get("custom_instructions", "").strip()
|
| 209 |
+
if vibe == "Custom..." and custom_instr:
|
| 210 |
+
line_instructions = custom_instr
|
| 211 |
+
elif vibe != "None" and vibe != "Custom...":
|
| 212 |
+
line_instructions = PREDEFINED_VIBES.get(vibe, "")
|
| 213 |
+
if not line_instructions and global_instructions and global_instructions.strip():
|
| 214 |
+
line_instructions = global_instructions
|
| 215 |
+
elif not line_instructions:
|
| 216 |
+
line_instructions = None
|
| 217 |
+
elif speaker_config_method in ["Random per Speaker", "A/B Round Robin"]:
|
| 218 |
+
line_voice = speaker_voice_map.get(speaker_name, safe_default_global_voice)
|
| 219 |
+
|
| 220 |
+
if tts_model not in ["tts-1", "tts-1-hd"]:
|
| 221 |
+
line_speed = 1.0
|
| 222 |
+
|
| 223 |
+
out_fn = os.path.join(job_audio_path_prefix, f"line_{line_data['id']}_{speaker_name.replace(' ','_')}.mp3")
|
| 224 |
+
progress(i / len(parsed_lines), desc=f"Synthesizing: Line {i+1}/{len(parsed_lines)} ({speaker_name})")
|
| 225 |
+
|
| 226 |
+
tasks.append(synthesize_speech_line(
|
| 227 |
+
client=async_openai_client, text=line_data["text"], voice=line_voice,
|
| 228 |
+
output_path=out_fn, model=tts_model, speed=line_speed,
|
| 229 |
+
instructions=line_instructions, nsfw_api_url_template=nsfw_api_url_template,
|
| 230 |
+
line_index=line_data['id']
|
| 231 |
+
))
|
| 232 |
+
|
| 233 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 234 |
+
|
| 235 |
+
for idx, res_path_or_exc in enumerate(results):
|
| 236 |
+
original_line_id = parsed_lines[idx]['id'] # Get original ID from the parsed line
|
| 237 |
+
if isinstance(res_path_or_exc, Exception):
|
| 238 |
+
print(f"Error synthesizing line ID {original_line_id} ({parsed_lines[idx]['speaker']}): {res_path_or_exc}")
|
| 239 |
+
line_audio_files_map[original_line_id] = None
|
| 240 |
+
elif res_path_or_exc is None:
|
| 241 |
+
print(f"Skipped or failed synthesizing line ID {original_line_id} ({parsed_lines[idx]['speaker']})")
|
| 242 |
+
line_audio_files_map[original_line_id] = None
|
| 243 |
+
else:
|
| 244 |
+
line_audio_files_map[original_line_id] = res_path_or_exc
|
| 245 |
+
|
| 246 |
+
# Reconstruct ordered list of files for merging, using original line IDs
|
| 247 |
+
ordered_files_for_merge_and_zip = []
|
| 248 |
+
for p_line in parsed_lines:
|
| 249 |
+
file_path = line_audio_files_map.get(p_line['id'])
|
| 250 |
+
if file_path and os.path.exists(file_path) and os.path.getsize(file_path) > 0:
|
| 251 |
+
ordered_files_for_merge_and_zip.append(file_path)
|
| 252 |
+
else:
|
| 253 |
+
ordered_files_for_merge_and_zip.append(None) # Keep placeholder for failed lines for merge logic
|
| 254 |
+
|
| 255 |
+
valid_files_for_zip = [f for f in ordered_files_for_merge_and_zip if f]
|
| 256 |
+
|
| 257 |
+
if not valid_files_for_zip:
|
| 258 |
+
shutil.rmtree(job_audio_path_prefix)
|
| 259 |
+
return None, None, "Error: No audio was successfully synthesized."
|
| 260 |
+
|
| 261 |
+
zip_fn = os.path.join(job_audio_path_prefix, "dialogue_lines.zip")
|
| 262 |
+
with zipfile.ZipFile(zip_fn, 'w') as zf:
|
| 263 |
+
for f_path in valid_files_for_zip:
|
| 264 |
+
zf.write(f_path, os.path.basename(f_path))
|
| 265 |
+
|
| 266 |
+
merged_fn = os.path.join(job_audio_path_prefix, "merged_dialogue.mp3")
|
| 267 |
+
# For merge_mp3_files, pass only the list of existing files in order
|
| 268 |
+
files_to_actually_merge = [f for f in ordered_files_for_merge_and_zip if f]
|
| 269 |
+
merged_path = merge_mp3_files(files_to_actually_merge, merged_fn, pause_ms)
|
| 270 |
+
|
| 271 |
+
status = f"Successfully processed {len(valid_files_for_zip)} out of {len(parsed_lines)} lines. "
|
| 272 |
+
if len(valid_files_for_zip) < len(parsed_lines): status += "Some lines may have failed. "
|
| 273 |
+
if not merged_path and len(valid_files_for_zip) > 0: status += "Merging audio failed. "
|
| 274 |
+
elif not merged_path: status = "No audio to merge."
|
| 275 |
+
else: status += "Merged audio generated."
|
| 276 |
+
|
| 277 |
+
return (zip_fn if os.path.exists(zip_fn) else None,
|
| 278 |
+
merged_path if merged_path and os.path.exists(merged_path) else None,
|
| 279 |
+
status)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def handle_calculate_cost(dialogue_script: str, tts_model: str):
|
| 283 |
+
if not dialogue_script.strip(): return "Cost: $0.00 (Script is empty)"
|
| 284 |
+
try:
|
| 285 |
+
parsed, chars = parse_dialogue_script(dialogue_script)
|
| 286 |
+
if not parsed: return "Cost: $0.00 (No valid lines in script)"
|
| 287 |
+
cost = calculate_cost(chars, len(parsed), tts_model)
|
| 288 |
+
return f"Estimated Cost for {len(parsed)} lines ({chars} chars): ${cost:.6f}"
|
| 289 |
+
except ValueError as e:
|
| 290 |
+
return f"Cost calculation error: {str(e)}"
|
| 291 |
+
except Exception as e:
|
| 292 |
+
return f"An unexpected error occurred during cost calculation: {str(e)}"
|
| 293 |
+
|
| 294 |
+
def update_model_controls_visibility(selected_model: str, script_text_for_refresh: str, current_speaker_configs_for_refresh: dict, speaker_configs_state_comp: gr.State):
|
| 295 |
+
"""Updates visibility of global controls and refreshes per-speaker UI when TTS model changes."""
|
| 296 |
+
print(f"Model changed to: {selected_model}. Refreshing dynamic UI and controls.") # Debug
|
| 297 |
+
try:
|
| 298 |
+
# load_refresh_per_speaker_ui might return components or markdown
|
| 299 |
+
# It now takes speaker_configs_state_comp as an argument to wire up .change() correctly
|
| 300 |
+
dynamic_ui_output, updated_state = load_refresh_per_speaker_ui(
|
| 301 |
+
script_text_for_refresh, current_speaker_configs_for_refresh, selected_model, speaker_configs_state_comp
|
| 302 |
+
)
|
| 303 |
+
except Exception as e:
|
| 304 |
+
print(f"Error in load_refresh_per_speaker_ui called from model_controls_visibility: {e}")
|
| 305 |
+
# Fallback: clear dynamic UI and keep state as is, or return an error message component
|
| 306 |
+
dynamic_ui_output = [gr.Markdown(f"Error refreshing per-speaker UI: {e}")]
|
| 307 |
+
updated_state = current_speaker_configs_for_refresh # or {} to reset
|
| 308 |
+
|
| 309 |
+
is_tts1_family = selected_model in ["tts-1", "tts-1-hd"]
|
| 310 |
+
is_gpt_mini_tts = selected_model == "gpt-4o-mini-tts"
|
| 311 |
+
|
| 312 |
+
# The keys in this dictionary must match the Gradio components passed in the `outputs` list
|
| 313 |
+
# of the .change() event.
|
| 314 |
+
updates = {
|
| 315 |
+
"global_speed_input": gr.update(visible=is_tts1_family, interactive=is_tts1_family),
|
| 316 |
+
"global_instructions_input": gr.update(visible=is_gpt_mini_tts, interactive=is_gpt_mini_tts),
|
| 317 |
+
"dynamic_speaker_ui_area": dynamic_ui_output, # This directly provides the new children for the Column
|
| 318 |
+
"speaker_configs_state": updated_state
|
| 319 |
+
}
|
| 320 |
+
return updates["global_speed_input"], updates["global_instructions_input"], updates["dynamic_speaker_ui_area"], updates["speaker_configs_state"]
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def update_speaker_config_method_visibility(method: str):
|
| 324 |
+
"""Updates visibility of UI groups based on selected speaker configuration method."""
|
| 325 |
+
is_single = (method == "Single Voice (Global)")
|
| 326 |
+
is_detailed_per_speaker = (method == "Detailed Configuration (Per Speaker UI)")
|
| 327 |
+
|
| 328 |
+
# Keys here must match the Gradio components in the .change() event's `outputs` list.
|
| 329 |
+
return {
|
| 330 |
+
"single_voice_group": gr.update(visible=is_single),
|
| 331 |
+
"detailed_per_speaker_ui_group": gr.update(visible=is_detailed_per_speaker),
|
| 332 |
+
}
|
ui_layout.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from utils.openai_tts import OPENAI_VOICES as ALL_TTS_VOICES # Import directly for APP_AVAILABLE_VOICES
|
| 3 |
+
|
| 4 |
+
# --- UI Constants and Configuration ---
|
| 5 |
+
TTS_MODELS_AVAILABLE = ["tts-1", "tts-1-hd", "gpt-4o-mini-tts"]
|
| 6 |
+
MODEL_DEFAULT_ENV = "tts-1-hd" # Default if env var not set or invalid
|
| 7 |
+
|
| 8 |
+
SPEAKER_CONFIG_METHODS = [
|
| 9 |
+
"Single Voice (Global)",
|
| 10 |
+
"Random per Speaker",
|
| 11 |
+
"A/B Round Robin",
|
| 12 |
+
"Detailed Configuration (Per Speaker UI)"
|
| 13 |
+
]
|
| 14 |
+
DEFAULT_SPEAKER_CONFIG_METHOD = "Random per Speaker"
|
| 15 |
+
APP_AVAILABLE_VOICES = ALL_TTS_VOICES.copy()
|
| 16 |
+
# Ensure APP_AVAILABLE_VOICES is never empty for safety, though ALL_TTS_VOICES has defaults
|
| 17 |
+
if not APP_AVAILABLE_VOICES:
|
| 18 |
+
APP_AVAILABLE_VOICES = ["alloy"] # Absolute fallback
|
| 19 |
+
|
| 20 |
+
PREDEFINED_VIBES = {
|
| 21 |
+
"None": "",
|
| 22 |
+
"Calm": "Speak in a calm, composed, and relaxed manner.",
|
| 23 |
+
"Excited": "Speak with an energetic, enthusiastic, and lively tone.",
|
| 24 |
+
"Happy": "Speak with a cheerful, bright, and joyful voice.",
|
| 25 |
+
"Sad": "Speak with a sorrowful, melancholic, and dejected tone.",
|
| 26 |
+
"Whisper": "Speak softly, as if whispering.",
|
| 27 |
+
"Angry": "Speak with a strong, firm, and possibly agitated voice.",
|
| 28 |
+
"Fearful": "Speak with a trembling, hesitant, and scared voice.",
|
| 29 |
+
"Formal": "Speak in a clear, precise, and professional tone, suitable for a formal address.",
|
| 30 |
+
"Authoritative": "Speak with a commanding, confident, and firm voice.",
|
| 31 |
+
"Friendly": "Speak in a warm, approachable, and amiable manner.",
|
| 32 |
+
"Custom...": "CUSTOM"
|
| 33 |
+
}
|
| 34 |
+
VIBE_CHOICES = list(PREDEFINED_VIBES.keys())
|
| 35 |
+
DEFAULT_VIBE = "None"
|
| 36 |
+
DEFAULT_GLOBAL_VOICE = APP_AVAILABLE_VOICES[0] if APP_AVAILABLE_VOICES else "alloy"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# --- UI Element Creation Functions ---
|
| 40 |
+
|
| 41 |
+
def create_main_input_components(model_default_value):
|
| 42 |
+
"""Creates the main input components for script, model, pause, and global settings."""
|
| 43 |
+
with gr.Row():
|
| 44 |
+
with gr.Column(scale=2):
|
| 45 |
+
script_input = gr.TextArea(label="Dialogue Script", placeholder="[Speaker1] Hello world!\n[Speaker2] How are you today?", lines=10)
|
| 46 |
+
with gr.Column(scale=1):
|
| 47 |
+
tts_model_dropdown = gr.Dropdown(TTS_MODELS_AVAILABLE, label="TTS Model", value=model_default_value)
|
| 48 |
+
pause_input = gr.Number(label="Pause Between Lines (ms)", value=500, minimum=0, maximum=5000, step=50)
|
| 49 |
+
|
| 50 |
+
is_tts1_family_default = model_default_value in ["tts-1", "tts-1-hd"]
|
| 51 |
+
is_gpt_mini_tts_default = model_default_value == "gpt-4o-mini-tts"
|
| 52 |
+
|
| 53 |
+
global_speed_input = gr.Slider(
|
| 54 |
+
minimum=0.25, maximum=4.0, value=1.0, step=0.05,
|
| 55 |
+
label="Global Speed (for tts-1/hd)",
|
| 56 |
+
visible=is_tts1_family_default,
|
| 57 |
+
interactive=True
|
| 58 |
+
)
|
| 59 |
+
global_instructions_input = gr.Textbox(
|
| 60 |
+
label="Global Instructions (for gpt-4o-mini-tts)",
|
| 61 |
+
placeholder="e.g., Speak with a calm tone.",
|
| 62 |
+
visible=is_gpt_mini_tts_default,
|
| 63 |
+
interactive=True, lines=2
|
| 64 |
+
)
|
| 65 |
+
return script_input, tts_model_dropdown, pause_input, global_speed_input, global_instructions_input
|
| 66 |
+
|
| 67 |
+
def create_speaker_config_components():
|
| 68 |
+
"""Creates components for speaker configuration method and detailed settings UI."""
|
| 69 |
+
gr.Markdown("### Speaker Voice & Style Configuration")
|
| 70 |
+
speaker_config_method_dropdown = gr.Dropdown(
|
| 71 |
+
SPEAKER_CONFIG_METHODS, label="Configuration Method", value=DEFAULT_SPEAKER_CONFIG_METHOD
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Visibility is controlled by event handlers based on speaker_config_method_dropdown
|
| 75 |
+
with gr.Group(visible=(DEFAULT_SPEAKER_CONFIG_METHOD == "Single Voice (Global)")) as single_voice_group:
|
| 76 |
+
global_voice_dropdown = gr.Dropdown(
|
| 77 |
+
APP_AVAILABLE_VOICES, label="Global Voice", value=DEFAULT_GLOBAL_VOICE, interactive=True
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
with gr.Column(visible=(DEFAULT_SPEAKER_CONFIG_METHOD == "Detailed Configuration (Per Speaker UI)")) as detailed_per_speaker_ui_group:
|
| 81 |
+
load_per_speaker_ui_button = gr.Button("Load/Refresh Per-Speaker Settings UI (from Script Above)")
|
| 82 |
+
gr.Markdown("<small>Click button above to populate settings for each speaker found in the script. Settings are applied per-speaker. If script changes, click again to refresh.</small>")
|
| 83 |
+
dynamic_speaker_ui_area = gr.Column(elem_id="dynamic_ui_area_for_speakers")
|
| 84 |
+
|
| 85 |
+
return speaker_config_method_dropdown, single_voice_group, global_voice_dropdown, detailed_per_speaker_ui_group, load_per_speaker_ui_button, dynamic_speaker_ui_area
|
| 86 |
+
|
| 87 |
+
def create_action_and_output_components():
|
| 88 |
+
"""Creates buttons for actions (cost, generate) and output display areas."""
|
| 89 |
+
with gr.Row():
|
| 90 |
+
calculate_cost_button = gr.Button("Calculate Estimated Cost")
|
| 91 |
+
generate_button = gr.Button("Generate Audio", variant="primary")
|
| 92 |
+
|
| 93 |
+
cost_output = gr.Textbox(label="Estimated Cost", interactive=False)
|
| 94 |
+
with gr.Row():
|
| 95 |
+
individual_lines_zip_output = gr.File(label="Download Individual Lines (ZIP)")
|
| 96 |
+
merged_dialogue_mp3_output = gr.Audio(label="Play/Download Merged Dialogue (MP3)", type="filepath")
|
| 97 |
+
status_output = gr.Textbox(label="Status", interactive=False, lines=2, max_lines=5)
|
| 98 |
+
return calculate_cost_button, generate_button, cost_output, individual_lines_zip_output, merged_dialogue_mp3_output, status_output
|
| 99 |
+
|
| 100 |
+
def create_examples_ui(inputs_for_examples, process_fn):
|
| 101 |
+
"""Creates the examples section."""
|
| 102 |
+
gr.Markdown("## Example Scripts")
|
| 103 |
+
example_script_1 = "[Alice] Hello Bob, this is a test using the detailed configuration method.\n[Bob] Hi Alice! I'm Bob, and I'll have my own voice settings.\n[Alice] Let's see how this sounds."
|
| 104 |
+
example_script_2 = "[Narrator] This is a short story.\n[CharacterA] Once upon a time...\n[Narrator] ...there was a Gradio app.\n[CharacterB] And it could talk!"
|
| 105 |
+
|
| 106 |
+
# Ensure a valid default voice for examples if APP_AVAILABLE_VOICES is somehow empty
|
| 107 |
+
# This is already handled by DEFAULT_GLOBAL_VOICE at the top of this file.
|
| 108 |
+
|
| 109 |
+
examples_data = [
|
| 110 |
+
[example_script_1, "tts-1-hd", 300, "Detailed Configuration (Per Speaker UI)", DEFAULT_GLOBAL_VOICE, {}, 1.0, ""],
|
| 111 |
+
[example_script_2, "gpt-4o-mini-tts", 200, "Random per Speaker", DEFAULT_GLOBAL_VOICE, {}, 1.0, "Speak with a gentle, storytelling voice for the narrator."],
|
| 112 |
+
["[Solo] Just one line, using global voice and speed.", "tts-1", 0, "Single Voice (Global)", "fable", {}, 1.2, ""],
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
# Check if the number of items in each example matches the number of input components
|
| 116 |
+
num_inputs = len(inputs_for_examples)
|
| 117 |
+
valid_examples_data = []
|
| 118 |
+
for ex_data in examples_data:
|
| 119 |
+
if len(ex_data) == num_inputs:
|
| 120 |
+
valid_examples_data.append(ex_data)
|
| 121 |
+
else:
|
| 122 |
+
print(f"Warning: Example data mismatch. Expected {num_inputs} items, got {len(ex_data)}. Skipping example: {ex_data[0][:30]}...")
|
| 123 |
+
|
| 124 |
+
if not valid_examples_data:
|
| 125 |
+
gr.Markdown("<p style='color: orange;'>No valid examples could be loaded due to configuration mismatch.</p>")
|
| 126 |
+
return None # Or an empty Examples component if that's better
|
| 127 |
+
|
| 128 |
+
return gr.Examples(
|
| 129 |
+
examples=valid_examples_data,
|
| 130 |
+
inputs=inputs_for_examples, # This list must match the structure of example_data items
|
| 131 |
+
# Outputs for examples are not strictly necessary to pre-compute if cache_examples=False
|
| 132 |
+
# but defining them can help Gradio understand the flow.
|
| 133 |
+
# We can make the example click run the full processing.
|
| 134 |
+
# outputs=[individual_lines_zip_output, merged_dialogue_mp3_output, status_output], # these components are not passed here
|
| 135 |
+
# For examples to run the main function, the output components need to be part of the gr.Examples call.
|
| 136 |
+
# However, the prompt is to make the list appear. Let's simplify for now.
|
| 137 |
+
# If outputs are defined, they must be component instances.
|
| 138 |
+
# For now, let's remove fn and outputs from gr.Examples just to ensure the list shows.
|
| 139 |
+
# Later, we can wire them back if needed, ensuring the output components are correctly passed.
|
| 140 |
+
# fn=process_fn, # Removed for debugging example list display
|
| 141 |
+
# cache_examples=False
|
| 142 |
+
label="Example Scripts (Click to Load Inputs)",
|
| 143 |
+
samples_per_page=5 # Helps ensure it tries to render
|
| 144 |
+
)
|