oicui commited on
Commit
c22869a
·
verified ·
1 Parent(s): 73147ac

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -228
app.py DELETED
@@ -1,228 +0,0 @@
1
- import random
2
- import re
3
- import numpy as np
4
- import torch
5
- import torchaudio
6
- from src.chatterbox.mtl_tts import ChatterboxMultilingualTTS, SUPPORTED_LANGUAGES
7
- import gradio as gr
8
- import spaces
9
-
10
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
11
- print(f"🚀 Running on device: {DEVICE}")
12
-
13
- MODEL = None
14
-
15
- LANGUAGE_CONFIG = {
16
- "ar": {"audio": "https://storage.googleapis.com/chatterbox-demo-samples/mtl_prompts/ar_f/ar_prompts2.flac",
17
- "text": "في الشهر الماضي، وصلنا إلى معلم جديد بمليارين من المشاهدات على قناتنا على يوتيوب."},
18
- "en": {"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
- "fr": {"audio": "https://storage.googleapis.com/chatterbox-demo-samples/mtl_prompts/fr_f1.flac",
21
- "text": "Le mois dernier, nous avons atteint un nouveau jalon avec deux milliards de vues sur notre chaîne YouTube."},
22
- "hi": {"audio": "https://storage.googleapis.com/chatterbox-demo-samples/mtl_prompts/hi_f1.flac",
23
- "text": "पिछले महीने हमने एक नया मील का पत्थर छुआ: हमारे YouTube चैनल पर दो अरब व्यूज़।"},
24
- "tr": {"audio": "https://storage.googleapis.com/chatterbox-demo-samples/mtl_prompts/tr_m.flac",
25
- "text": "Geçen ay YouTube kanalımızda iki milyar görüntüleme ile yeni bir dönüm noktasına ulaştık."},
26
- "zh": {"audio": "https://storage.googleapis.com/chatterbox-demo-samples/mtl_prompts/zh_f2.flac",
27
- "text": "上个月,我们达到了一个新的里程碑。 我们的YouTube频道观看次数达到了二十亿次,这绝对令人难以置信。"},
28
- }
29
-
30
- def default_audio_for_ui(lang: str) -> str | None:
31
- return LANGUAGE_CONFIG.get(lang, {}).get("audio")
32
-
33
- def default_text_for_ui(lang: str) -> str:
34
- return LANGUAGE_CONFIG.get(lang, {}).get("text", "")
35
-
36
- def get_supported_languages_display() -> str:
37
- items = [f"**{name}** (`{code}`)" for code, name in sorted(SUPPORTED_LANGUAGES.items())]
38
- mid = len(items)//2
39
- return f"### 🌍 Supported Languages ({len(SUPPORTED_LANGUAGES)} total)\n" \
40
- f"{' • '.join(items[:mid])}\n\n{' • '.join(items[mid:])}"
41
-
42
- def get_or_load_model():
43
- global MODEL
44
- if MODEL is None:
45
- print("Model not loaded, initializing...")
46
- MODEL = ChatterboxMultilingualTTS.from_pretrained(DEVICE)
47
- if hasattr(MODEL, "to"):
48
- MODEL.to(DEVICE)
49
- print(f"✅ Model loaded successfully on {DEVICE}")
50
- return MODEL
51
-
52
- try:
53
- get_or_load_model()
54
- except Exception as e:
55
- print(f"CRITICAL: Failed to load model. Error: {e}")
56
-
57
- def set_seed(seed: int):
58
- torch.manual_seed(seed)
59
- if DEVICE == "cuda":
60
- torch.cuda.manual_seed(seed)
61
- torch.cuda.manual_seed_all(seed)
62
- random.seed(seed)
63
- np.random.seed(seed)
64
-
65
- def resolve_audio_prompt(language_id: str, provided_path: str | None) -> str | None:
66
- if provided_path and str(provided_path).strip():
67
- return provided_path
68
- return LANGUAGE_CONFIG.get(language_id, {}).get("audio")
69
-
70
-
71
- # ======================================================
72
- # ⭐⭐ HÀM THÊM NGẮT NGHỈ TỰ NHIÊN (THÊM MỚI)
73
- # ======================================================
74
- def enhance_prosody(text: str) -> str:
75
- text = re.sub(r"\s+", " ", text.strip())
76
-
77
- # Pause theo dấu câu
78
- text = re.sub(r"\.", ". …", text)
79
- text = re.sub(r",", ", –", text)
80
- text = re.sub(r";", "; …", text)
81
- text = re.sub(r":", ": …", text)
82
- text = re.sub(r"([!?])", r"\1 …", text)
83
-
84
- # Từ chuyển ý
85
- transition_words = [
86
- "tuy nhiên", "nhưng", "vì vậy", "do đó",
87
- "mặt khác", "bên cạnh đó", "ngoài ra", "tóm lại"
88
- ]
89
- for w in transition_words:
90
- text = re.sub(fr"\b{w}\b", f"… {w}", text, flags=re.IGNORECASE)
91
-
92
- return text
93
-
94
-
95
-
96
- # ======================================================
97
- # TEXT SPLITTER
98
- # ======================================================
99
- def split_text_into_chunks(text: str, max_chars: int = 500) -> list[str]:
100
- text = re.sub(r"\s+", " ", text.strip())
101
- if len(text) <= max_chars:
102
- return [text]
103
-
104
- sentences = re.split(r'(?<=[.!?۔،])\s+', text)
105
- chunks, current_chunk = [], ""
106
-
107
- for sent in sentences:
108
- if len(current_chunk) + len(sent) < max_chars:
109
- current_chunk += " " + sent
110
- else:
111
- chunks.append(current_chunk.strip())
112
- current_chunk = sent
113
- if current_chunk:
114
- chunks.append(current_chunk.strip())
115
-
116
- return [c for c in chunks if c]
117
-
118
-
119
- # ======================================================
120
- # GENERATE AUDIO
121
- # ======================================================
122
- @spaces.GPU
123
- def generate_tts_audio(
124
- text_input: str,
125
- language_id: str,
126
- audio_prompt_path_input: str = None,
127
- exaggeration_input: float = 0.5,
128
- temperature_input: float = 0.8,
129
- seed_num_input: int = 0,
130
- cfgw_input: float = 0.5
131
- ):
132
-
133
- current_model = get_or_load_model()
134
- if current_model is None:
135
- raise RuntimeError("TTS model not loaded.")
136
-
137
- if seed_num_input == 0:
138
- seed_num_input = random.randint(1, 2**32 - 1)
139
- print(f"🌱 Random seed generated: {seed_num_input}")
140
- else:
141
- print(f"🌱 Using provided seed: {seed_num_input}")
142
-
143
- set_seed(int(seed_num_input))
144
-
145
- chosen_prompt = audio_prompt_path_input or default_audio_for_ui(language_id)
146
- generate_kwargs = {
147
- "exaggeration": exaggeration_input,
148
- "temperature": temperature_input,
149
- "cfg_weight": cfgw_input,
150
- }
151
- if chosen_prompt:
152
- generate_kwargs["audio_prompt_path"] = chosen_prompt
153
-
154
- # ⭐⭐ ÁP DỤNG NGẮT NGHỈ TỰ NHIÊN TRƯỚC KHI GENERATE ⭐⭐
155
- text_input = enhance_prosody(text_input)
156
-
157
- chunks = split_text_into_chunks(text_input)
158
-
159
- all_audio = []
160
- for chunk in chunks:
161
- wav = current_model.generate(chunk, language_id=language_id, **generate_kwargs)
162
- all_audio.append(wav.squeeze(0).cpu())
163
-
164
- final_audio = torch.cat(all_audio, dim=-1)
165
- return (current_model.sr, final_audio.numpy()), str(seed_num_input)
166
-
167
-
168
-
169
- # ======================================================
170
- # GRADIO UI
171
- # ======================================================
172
- with gr.Blocks() as demo:
173
- gr.Markdown("""
174
- # 🎙️ Multi Language Realistic Voice Cloner
175
- Generate long-form multilingual speech with reference audio styling and auto-chunking.
176
- """)
177
-
178
- gr.Markdown(get_supported_languages_display())
179
-
180
- with gr.Row():
181
- with gr.Column():
182
- initial_lang = "en"
183
- text = gr.Textbox(
184
- value=default_text_for_ui(initial_lang),
185
- label="Text to synthesize",
186
- lines=8
187
- )
188
- language_id = gr.Dropdown(
189
- choices=list(ChatterboxMultilingualTTS.get_supported_languages().keys()),
190
- value=initial_lang,
191
- label="Language"
192
- )
193
- ref_wav = gr.Audio(
194
- sources=["upload", "microphone"],
195
- type="filepath",
196
- label="Reference Audio (Optional)",
197
- value=default_audio_for_ui(initial_lang)
198
- )
199
- exaggeration = gr.Slider(0.25, 2, step=.05, label="Exaggeration", value=.5)
200
- cfg_weight = gr.Slider(0.2, 1, step=.05, label="CFG Weight", value=0.5)
201
-
202
- with gr.Accordion("Advanced", open=False):
203
- seed_num = gr.Number(value=0, label="Random Seed (0=random)")
204
- temp = gr.Slider(0.05, 5, step=.05, label="Temperature", value=.8)
205
-
206
- run_btn = gr.Button("Generate", variant="primary")
207
-
208
- with gr.Column():
209
- audio_output = gr.Audio(label="Output Audio")
210
- seed_output = gr.Textbox(label="Seed Used", interactive=False)
211
-
212
- def on_lang_change(lang, current_ref, current_text):
213
- return default_audio_for_ui(lang), default_text_for_ui(lang)
214
-
215
- language_id.change(
216
- fn=on_lang_change,
217
- inputs=[language_id, ref_wav, text],
218
- outputs=[ref_wav, text],
219
- show_progress=False
220
- )
221
-
222
- run_btn.click(
223
- fn=generate_tts_audio,
224
- inputs=[text, language_id, ref_wav, exaggeration, temp, seed_num, cfg_weight],
225
- outputs=[audio_output, seed_output],
226
- )
227
-
228
- demo.launch(mcp_server=True, share=True)