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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from chatterbox.mtl_tts import ChatterboxMultilingualTTS
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 8 |
+
print(f"๐ Running on device: {DEVICE}")
|
| 9 |
+
|
| 10 |
+
MODEL = None
|
| 11 |
+
|
| 12 |
+
LANGUAGE_CONFIG = {
|
| 13 |
+
"ar": {
|
| 14 |
+
"audio": "https://storage.googleapis.com/chatterbox-demo-samples/mtl_prompts/ar_f/ar_prompts2.flac",
|
| 15 |
+
"text": "ูู ุงูุดูุฑ ุงูู
ุงุถูุ ูุตููุง ุฅูู ู
ุนูู
ุฌุฏูุฏ ุจู
ููุงุฑูู ู
ู ุงูู
ุดุงูุฏุงุช ุนูู ููุงุชูุง ุนูู ููุชููุจ."
|
| 16 |
+
},
|
| 17 |
+
"en": {
|
| 18 |
+
"audio": "https://storage.googleapis.com/chatterbox-demo-samples/mtl_prompts/en_f1.flac",
|
| 19 |
+
"text": "Last month, we reached a new milestone with two billion views on our YouTube channel."
|
| 20 |
+
},
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
def default_audio_for_ui(lang: str) -> str | None:
|
| 24 |
+
return LANGUAGE_CONFIG.get(lang, {}).get("audio")
|
| 25 |
+
|
| 26 |
+
def default_text_for_ui(lang: str) -> str:
|
| 27 |
+
return LANGUAGE_CONFIG.get(lang, {}).get("text", "")
|
| 28 |
+
|
| 29 |
+
def get_supported_languages_display() -> str:
|
| 30 |
+
return """
|
| 31 |
+
### ๐ Supported Languages (2 total)
|
| 32 |
+
**Arabic** (`ar`) โข **English** (`en`)
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def get_or_load_model():
|
| 36 |
+
global MODEL
|
| 37 |
+
if MODEL is None:
|
| 38 |
+
print("Model not loaded, initializing...")
|
| 39 |
+
try:
|
| 40 |
+
MODEL = ChatterboxMultilingualTTS.from_pretrained(DEVICE)
|
| 41 |
+
if hasattr(MODEL, 'to') and str(MODEL.device) != DEVICE:
|
| 42 |
+
MODEL.to(DEVICE)
|
| 43 |
+
print(f"Model loaded successfully. Internal device: {getattr(MODEL, 'device', 'N/A')}")
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error loading model: {e}")
|
| 46 |
+
raise
|
| 47 |
+
return MODEL
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
get_or_load_model()
|
| 51 |
+
except Exception as e:
|
| 52 |
+
print(f"CRITICAL: Failed to load model on startup. Application may not function. Error: {e}")
|
| 53 |
+
|
| 54 |
+
def set_seed(seed: int):
|
| 55 |
+
torch.manual_seed(seed)
|
| 56 |
+
if DEVICE == "cuda":
|
| 57 |
+
torch.cuda.manual_seed(seed)
|
| 58 |
+
torch.cuda.manual_seed_all(seed)
|
| 59 |
+
random.seed(seed)
|
| 60 |
+
np.random.seed(seed)
|
| 61 |
+
|
| 62 |
+
def generate_tts_audio(
|
| 63 |
+
text_input: str,
|
| 64 |
+
language_id: str,
|
| 65 |
+
audio_prompt_path_input: str = None,
|
| 66 |
+
exaggeration_input: float = 0.5,
|
| 67 |
+
temperature_input: float = 0.8,
|
| 68 |
+
seed_num_input: int = 0,
|
| 69 |
+
cfgw_input: float = 0.5,
|
| 70 |
+
speed_input: float = 1.0
|
| 71 |
+
) -> tuple[int, np.ndarray]:
|
| 72 |
+
current_model = get_or_load_model()
|
| 73 |
+
|
| 74 |
+
if current_model is None:
|
| 75 |
+
raise RuntimeError("TTS model is not loaded.")
|
| 76 |
+
|
| 77 |
+
if seed_num_input != 0:
|
| 78 |
+
set_seed(int(seed_num_input))
|
| 79 |
+
|
| 80 |
+
print(f"Generating audio for text: '{text_input[:50]}...'")
|
| 81 |
+
|
| 82 |
+
chosen_prompt = audio_prompt_path_input or default_audio_for_ui(language_id)
|
| 83 |
+
|
| 84 |
+
generate_kwargs = {
|
| 85 |
+
"exaggeration": exaggeration_input,
|
| 86 |
+
"temperature": temperature_input,
|
| 87 |
+
"cfg_weight": cfgw_input,
|
| 88 |
+
"speed": speed_input,
|
| 89 |
+
}
|
| 90 |
+
if chosen_prompt:
|
| 91 |
+
generate_kwargs["audio_prompt_path"] = chosen_prompt
|
| 92 |
+
print(f"Using audio prompt: {chosen_prompt}")
|
| 93 |
+
else:
|
| 94 |
+
print("No audio prompt provided; using default voice.")
|
| 95 |
+
|
| 96 |
+
wav = current_model.generate(
|
| 97 |
+
text_input[:300],
|
| 98 |
+
language_id=language_id,
|
| 99 |
+
**generate_kwargs
|
| 100 |
+
)
|
| 101 |
+
print("Audio generation complete.")
|
| 102 |
+
return (current_model.sr, wav.squeeze(0).numpy())
|
| 103 |
+
|
| 104 |
+
with gr.Blocks() as demo:
|
| 105 |
+
gr.Markdown(
|
| 106 |
+
"""
|
| 107 |
+
# Chatterbox Multilingual TTS - Arabic & English
|
| 108 |
+
Generate high-quality speech from text with reference audio styling for Arabic and English languages.
|
| 109 |
+
"""
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
gr.Markdown(get_supported_languages_display())
|
| 113 |
+
with gr.Row():
|
| 114 |
+
with gr.Column():
|
| 115 |
+
initial_lang = "ar"
|
| 116 |
+
text = gr.Textbox(
|
| 117 |
+
value=default_text_for_ui(initial_lang),
|
| 118 |
+
label="Text to synthesize (max chars 300)",
|
| 119 |
+
max_lines=5
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
language_id = gr.Dropdown(
|
| 123 |
+
choices=["ar", "en"],
|
| 124 |
+
value=initial_lang,
|
| 125 |
+
label="Language",
|
| 126 |
+
info="Select the language for text-to-speech synthesis"
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
ref_wav = gr.Audio(
|
| 130 |
+
sources=["upload", "microphone"],
|
| 131 |
+
type="filepath",
|
| 132 |
+
label="Reference Audio File (Optional)",
|
| 133 |
+
value=default_audio_for_ui(initial_lang)
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
gr.Markdown(
|
| 137 |
+
"๐ก **Note**: Ensure that the reference clip matches the specified language tag. Otherwise, language transfer outputs may inherit the accent of the reference clip's language. To mitigate this, set the CFG weight to 0.",
|
| 138 |
+
elem_classes=["audio-note"]
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
exaggeration = gr.Slider(
|
| 142 |
+
0.25, 2, step=.05, label="Exaggeration (Neutral = 0.5, extreme values can be unstable)", value=.5
|
| 143 |
+
)
|
| 144 |
+
cfg_weight = gr.Slider(
|
| 145 |
+
0.2, 1, step=.05, label="CFG/Pace", value=0.5
|
| 146 |
+
)
|
| 147 |
+
speed = gr.Slider(
|
| 148 |
+
0.5, 2.0, step=0.1, label="Speed", value=1.0
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
with gr.Accordion("More options", open=False):
|
| 152 |
+
seed_num = gr.Number(value=0, label="Random seed (0 for random)")
|
| 153 |
+
temp = gr.Slider(0.05, 5, step=.05, label="Temperature", value=.8)
|
| 154 |
+
|
| 155 |
+
run_btn = gr.Button("Generate", variant="primary")
|
| 156 |
+
|
| 157 |
+
with gr.Column():
|
| 158 |
+
audio_output = gr.Audio(label="Output Audio")
|
| 159 |
+
|
| 160 |
+
def on_language_change(lang, current_ref, current_text):
|
| 161 |
+
return default_audio_for_ui(lang), default_text_for_ui(lang)
|
| 162 |
+
|
| 163 |
+
language_id.change(
|
| 164 |
+
fn=on_language_change,
|
| 165 |
+
inputs=[language_id, ref_wav, text],
|
| 166 |
+
outputs=[ref_wav, text],
|
| 167 |
+
show_progress=False
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
run_btn.click(
|
| 171 |
+
fn=generate_tts_audio,
|
| 172 |
+
inputs=[
|
| 173 |
+
text,
|
| 174 |
+
language_id,
|
| 175 |
+
ref_wav,
|
| 176 |
+
exaggeration,
|
| 177 |
+
temp,
|
| 178 |
+
seed_num,
|
| 179 |
+
cfg_weight,
|
| 180 |
+
speed,
|
| 181 |
+
],
|
| 182 |
+
outputs=[audio_output],
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
demo.launch()
|