Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,23 +5,32 @@ import tempfile
|
|
| 5 |
import os
|
| 6 |
import warnings
|
| 7 |
from contextlib import contextmanager
|
| 8 |
-
import numpy as np
|
| 9 |
|
| 10 |
warnings.filterwarnings("ignore")
|
| 11 |
|
| 12 |
# CRITICAL: Coqui Terms of Service
|
| 13 |
os.environ["COQUI_TOS_AGREED"] = "1"
|
| 14 |
|
| 15 |
-
print("π Starting Voice Cloning Studio...")
|
| 16 |
|
| 17 |
-
# PyTorch 2.6 Compatibility
|
| 18 |
@contextmanager
|
| 19 |
-
def
|
| 20 |
-
"""
|
| 21 |
original_load = torch.load
|
|
|
|
| 22 |
def patched_load(f, *args, **kwargs):
|
| 23 |
kwargs['weights_only'] = False
|
| 24 |
return original_load(f, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
torch.load = patched_load
|
| 26 |
try:
|
| 27 |
yield
|
|
@@ -35,402 +44,201 @@ print(f"π Using device: {DEVICE}")
|
|
| 35 |
# Global variables
|
| 36 |
TTS_MODEL = None
|
| 37 |
WHISPER_MODEL = None
|
| 38 |
-
MODEL_STATUS = "Not Loaded"
|
| 39 |
|
| 40 |
def load_models():
|
| 41 |
-
"""Load models with
|
| 42 |
-
global TTS_MODEL, WHISPER_MODEL
|
| 43 |
|
| 44 |
-
print("π Loading models...")
|
| 45 |
-
|
| 46 |
-
# Load XTTS-v2
|
| 47 |
if TTS_MODEL is None:
|
| 48 |
try:
|
| 49 |
-
with
|
|
|
|
| 50 |
from TTS.api import TTS
|
| 51 |
-
print("π¦ Loading XTTS-v2...")
|
| 52 |
|
| 53 |
TTS_MODEL = TTS(
|
| 54 |
model_name="tts_models/multilingual/multi-dataset/xtts_v2",
|
| 55 |
progress_bar=True,
|
| 56 |
gpu=(DEVICE == "cuda")
|
| 57 |
)
|
| 58 |
-
|
| 59 |
-
MODEL_STATUS = "XTTS-v2 Ready"
|
| 60 |
-
print("β
XTTS-v2 loaded successfully!")
|
| 61 |
-
|
| 62 |
-
# CRITICAL: Verify the model has the correct methods
|
| 63 |
-
if hasattr(TTS_MODEL, 'tts') and hasattr(TTS_MODEL, 'tts_to_file'):
|
| 64 |
-
print("β
Verified: TTS model has correct API methods")
|
| 65 |
-
else:
|
| 66 |
-
print("β Warning: TTS model missing expected methods")
|
| 67 |
|
| 68 |
except Exception as e:
|
| 69 |
-
print(f"β
|
| 70 |
-
MODEL_STATUS = f"XTTS Load Failed: {str(e)}"
|
| 71 |
return False
|
| 72 |
|
| 73 |
-
# Load Whisper
|
| 74 |
if WHISPER_MODEL is None:
|
| 75 |
try:
|
| 76 |
-
print("π¦ Loading Whisper...")
|
| 77 |
import whisper
|
| 78 |
WHISPER_MODEL = whisper.load_model("base")
|
| 79 |
-
print("β
Whisper loaded
|
| 80 |
except Exception as e:
|
| 81 |
-
print(f"β Whisper
|
| 82 |
|
| 83 |
return TTS_MODEL is not None
|
| 84 |
|
| 85 |
-
def
|
| 86 |
-
"""
|
| 87 |
-
CORRECTED: Uses tts() method instead of generate()
|
| 88 |
-
"""
|
| 89 |
try:
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
return None, "β Please upload reference audio!"
|
| 93 |
-
|
| 94 |
-
if not input_audio:
|
| 95 |
-
return None, "β Please upload input audio!"
|
| 96 |
|
| 97 |
-
print("π€ Starting Voice-to-Voice Cloning...")
|
| 98 |
-
|
| 99 |
-
# Load models
|
| 100 |
if not load_models():
|
| 101 |
-
return None,
|
| 102 |
-
|
| 103 |
-
# Extract text from input audio
|
| 104 |
-
extracted_text = "Voice cloning demonstration using uploaded audio content."
|
| 105 |
|
|
|
|
|
|
|
| 106 |
if WHISPER_MODEL:
|
| 107 |
try:
|
| 108 |
-
print("π Transcribing input audio...")
|
| 109 |
result = WHISPER_MODEL.transcribe(input_audio)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
print(f"β
Extracted: '{extracted_text[:100]}...'")
|
| 116 |
-
|
| 117 |
except Exception as e:
|
| 118 |
-
print(f"β οΈ Whisper
|
| 119 |
-
|
| 120 |
-
#
|
| 121 |
-
print("π Generating speech with
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
with
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
sample_rate = getattr(TTS_MODEL, 'synthesizer', {}).get('output_sample_rate', 24000) or 24000
|
| 148 |
-
torchaudio.save(output_path, wav_tensor, sample_rate)
|
| 149 |
-
|
| 150 |
-
# Verify output
|
| 151 |
-
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
|
| 152 |
-
return output_path, f"β
Voice-to-Voice Complete!\n\nπ€ Content: '{extracted_text[:150]}...'\nπ Applied reference voice\nπ Language: {language}\nπ€ Model: {MODEL_STATUS}\nπ§ Used: tts() method (CORRECT API)"
|
| 153 |
-
else:
|
| 154 |
-
return None, "β Generated audio file is empty!"
|
| 155 |
-
|
| 156 |
-
except Exception as gen_error:
|
| 157 |
-
# Fallback: Try tts_to_file method
|
| 158 |
-
try:
|
| 159 |
-
print("π Trying fallback method: tts_to_file()...")
|
| 160 |
-
|
| 161 |
-
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
|
| 162 |
-
output_path = tmp_file.name
|
| 163 |
-
|
| 164 |
-
with patch_torch_load():
|
| 165 |
-
TTS_MODEL.tts_to_file(
|
| 166 |
-
text=extracted_text,
|
| 167 |
-
speaker_wav=reference_audio,
|
| 168 |
-
language=language,
|
| 169 |
-
file_path=output_path
|
| 170 |
-
)
|
| 171 |
-
|
| 172 |
-
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
|
| 173 |
-
return output_path, f"β
Voice-to-Voice Complete (Fallback)!\n\nπ€ Content: '{extracted_text[:150]}...'\nπ Applied reference voice\nπ Language: {language}\nπ€ Model: {MODEL_STATUS}\nπ§ Used: tts_to_file() method"
|
| 174 |
-
else:
|
| 175 |
-
return None, "β Generated audio file is empty!"
|
| 176 |
-
|
| 177 |
-
except Exception as fallback_error:
|
| 178 |
-
return None, f"β Generation failed:\nPrimary error: {str(gen_error)}\nFallback error: {str(fallback_error)}\n\nTip: The model doesn't have a 'generate()' method. Use 'tts()' or 'tts_to_file()' instead."
|
| 179 |
|
| 180 |
except Exception as e:
|
| 181 |
-
return None, f"β
|
| 182 |
|
| 183 |
-
def
|
| 184 |
-
"""
|
| 185 |
-
CORRECTED: Uses tts() method instead of generate()
|
| 186 |
-
"""
|
| 187 |
try:
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
return None, "β Please upload reference audio!"
|
| 191 |
|
| 192 |
-
if not
|
| 193 |
-
return None, "β
|
| 194 |
|
| 195 |
-
print("
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
-
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
# Convert numpy array to tensor and save
|
| 215 |
-
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
|
| 216 |
-
output_path = tmp_file.name
|
| 217 |
-
|
| 218 |
-
# Convert to tensor and save
|
| 219 |
-
if isinstance(wav_array, np.ndarray):
|
| 220 |
-
wav_tensor = torch.tensor(wav_array, dtype=torch.float32).unsqueeze(0)
|
| 221 |
-
else:
|
| 222 |
-
wav_tensor = torch.tensor(wav_array, dtype=torch.float32)
|
| 223 |
-
if wav_tensor.dim() == 1:
|
| 224 |
-
wav_tensor = wav_tensor.unsqueeze(0)
|
| 225 |
-
|
| 226 |
-
# Save with correct sample rate
|
| 227 |
-
sample_rate = getattr(TTS_MODEL, 'synthesizer', {}).get('output_sample_rate', 24000) or 24000
|
| 228 |
-
torchaudio.save(output_path, wav_tensor, sample_rate)
|
| 229 |
-
|
| 230 |
-
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
|
| 231 |
-
return output_path, f"β
Text-to-Voice Complete!\n\nπ Generated: '{input_text[:150]}...'\nπ Using reference voice\nπ Language: {language}\nπ€ Model: {MODEL_STATUS}\nπ§ Used: tts() method (CORRECT API)"
|
| 232 |
-
else:
|
| 233 |
-
return None, "β Generated audio file is empty!"
|
| 234 |
-
|
| 235 |
-
except Exception as gen_error:
|
| 236 |
-
# Fallback: Try tts_to_file method
|
| 237 |
-
try:
|
| 238 |
-
print("π Trying fallback method: tts_to_file()...")
|
| 239 |
-
|
| 240 |
-
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
|
| 241 |
-
output_path = tmp_file.name
|
| 242 |
-
|
| 243 |
-
with patch_torch_load():
|
| 244 |
-
TTS_MODEL.tts_to_file(
|
| 245 |
-
text=input_text,
|
| 246 |
-
speaker_wav=reference_audio,
|
| 247 |
-
language=language,
|
| 248 |
-
file_path=output_path
|
| 249 |
-
)
|
| 250 |
-
|
| 251 |
-
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
|
| 252 |
-
return output_path, f"β
Text-to-Voice Complete (Fallback)!\n\nπ Generated: '{input_text[:150]}...'\nπ Using reference voice\nπ Language: {language}\nπ€ Model: {MODEL_STATUS}\nπ§ Used: tts_to_file() method"
|
| 253 |
-
else:
|
| 254 |
-
return None, "β Generated audio file is empty!"
|
| 255 |
-
|
| 256 |
-
except Exception as fallback_error:
|
| 257 |
-
return None, f"β Generation failed:\nPrimary error: {str(gen_error)}\nFallback error: {str(fallback_error)}\n\nTip: The model doesn't have a 'generate()' method. Use 'tts()' or 'tts_to_file()' instead."
|
| 258 |
|
| 259 |
except Exception as e:
|
| 260 |
-
return None, f"β
|
| 261 |
-
|
| 262 |
-
# Initialize at startup
|
| 263 |
-
print("π Initializing models at startup...")
|
| 264 |
-
try:
|
| 265 |
-
startup_success = load_models()
|
| 266 |
-
if startup_success:
|
| 267 |
-
startup_msg = f"β
{MODEL_STATUS}!"
|
| 268 |
-
startup_color = "#d4edda"
|
| 269 |
-
else:
|
| 270 |
-
startup_msg = f"β οΈ Models will load on first use - {MODEL_STATUS}"
|
| 271 |
-
startup_color = "#fff3cd"
|
| 272 |
-
except Exception as e:
|
| 273 |
-
startup_success = False
|
| 274 |
-
startup_msg = f"β οΈ Startup warning: {str(e)}"
|
| 275 |
-
startup_color = "#f8d7da"
|
| 276 |
-
|
| 277 |
-
print(f"Startup status: {startup_msg}")
|
| 278 |
|
| 279 |
# Create Gradio Interface
|
| 280 |
-
with gr.Blocks(
|
| 281 |
-
title="π Voice Cloning Studio - API Fixed",
|
| 282 |
-
theme=gr.themes.Soft(primary_hue="blue", secondary_hue="green")
|
| 283 |
-
) as demo:
|
| 284 |
|
| 285 |
gr.HTML("""
|
| 286 |
<div style="text-align: center; padding: 20px;">
|
| 287 |
-
<h1
|
| 288 |
-
<p style="color: #
|
| 289 |
-
<p style="color: #
|
| 290 |
</div>
|
| 291 |
""")
|
| 292 |
|
| 293 |
-
#
|
| 294 |
-
gr.HTML(
|
| 295 |
-
<div style="
|
| 296 |
-
<
|
|
|
|
|
|
|
|
|
|
| 297 |
</div>
|
| 298 |
""")
|
| 299 |
|
| 300 |
-
# Reference
|
| 301 |
-
gr.HTML("<h3 style='color: #2E86AB; text-align: center;'>π€ Reference Voice (Voice to Clone)</h3>")
|
| 302 |
reference_audio = gr.Audio(
|
| 303 |
-
label="
|
| 304 |
type="filepath",
|
| 305 |
sources=["upload", "microphone"]
|
| 306 |
)
|
| 307 |
|
| 308 |
-
# Main tabs
|
| 309 |
with gr.Tabs():
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
<li>β
Uses <code>model.tts()</code> method (correct)</li>
|
| 317 |
-
<li>β No longer tries <code>model.generate()</code> (doesn't exist)</li>
|
| 318 |
-
<li>π Fallback to <code>model.tts_to_file()</code> if needed</li>
|
| 319 |
-
</ul>
|
| 320 |
-
</div>
|
| 321 |
-
""")
|
| 322 |
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
label="Text to Convert",
|
| 362 |
-
placeholder="Enter text to speak in the cloned voice...",
|
| 363 |
-
lines=5
|
| 364 |
-
)
|
| 365 |
-
|
| 366 |
-
text_language = gr.Dropdown(
|
| 367 |
-
choices=[
|
| 368 |
-
("πΊπΈ English", "en"),
|
| 369 |
-
("πͺπΈ Spanish", "es"),
|
| 370 |
-
("π«π· French", "fr"),
|
| 371 |
-
("π©πͺ German", "de")
|
| 372 |
-
],
|
| 373 |
-
value="en",
|
| 374 |
-
label="Language"
|
| 375 |
-
)
|
| 376 |
-
|
| 377 |
-
text_btn = gr.Button(
|
| 378 |
-
"π Generate Speech (API Fixed)",
|
| 379 |
-
variant="secondary",
|
| 380 |
-
size="lg"
|
| 381 |
-
)
|
| 382 |
-
|
| 383 |
-
with gr.Column():
|
| 384 |
-
text_output = gr.Audio(label="Generated Speech")
|
| 385 |
-
text_status = gr.Textbox(
|
| 386 |
-
label="Status",
|
| 387 |
-
lines=8,
|
| 388 |
-
interactive=False
|
| 389 |
-
)
|
| 390 |
-
|
| 391 |
-
# Help section
|
| 392 |
-
with gr.Accordion("π§ API Fix Explanation", open=False):
|
| 393 |
-
gr.Markdown("""
|
| 394 |
-
### β
What Was Fixed
|
| 395 |
-
**The Problem:** Your code was trying to call `model.generate()` which doesn't exist on XTTS models.
|
| 396 |
-
|
| 397 |
-
**The Solution:**
|
| 398 |
-
- **Primary Method:** `model.tts()` - Returns numpy array that we convert and save
|
| 399 |
-
- **Fallback Method:** `model.tts_to_file()` - Saves directly to file
|
| 400 |
-
- **Removed:** All calls to `model.generate()` (doesn't exist)
|
| 401 |
-
|
| 402 |
-
### π XTTS API Reference
|
| 403 |
-
```
|
| 404 |
-
# β
CORRECT - What we now use:
|
| 405 |
-
wav = model.tts(text=text, speaker_wav=reference_audio, language=language)
|
| 406 |
-
|
| 407 |
-
# β
ALTERNATIVE - Also works:
|
| 408 |
-
model.tts_to_file(text=text, speaker_wav=reference_audio, language=language, file_path=output)
|
| 409 |
-
|
| 410 |
-
# β WRONG - What was causing the error:
|
| 411 |
-
model.generate() # This method doesn't exist!
|
| 412 |
-
```
|
| 413 |
-
|
| 414 |
-
### π Expected Results
|
| 415 |
-
- **No More API Errors:** `'GPT2InferenceModel' object has no attribute 'generate'` is fixed
|
| 416 |
-
- **Working Voice Cloning:** Real audio transformation using correct XTTS methods
|
| 417 |
-
- **Robust Fallbacks:** If primary method fails, tries alternative approach
|
| 418 |
-
""")
|
| 419 |
-
|
| 420 |
-
# Event handlers
|
| 421 |
-
voice_btn.click(
|
| 422 |
-
fn=voice_to_voice_clone,
|
| 423 |
-
inputs=[reference_audio, input_audio, voice_language],
|
| 424 |
-
outputs=[voice_output, voice_status],
|
| 425 |
-
show_progress=True
|
| 426 |
-
)
|
| 427 |
-
|
| 428 |
-
text_btn.click(
|
| 429 |
-
fn=text_to_voice_clone,
|
| 430 |
-
inputs=[reference_audio, text_input, text_language],
|
| 431 |
-
outputs=[text_output, text_status],
|
| 432 |
-
show_progress=True
|
| 433 |
-
)
|
| 434 |
|
| 435 |
if __name__ == "__main__":
|
| 436 |
demo.launch()
|
|
|
|
| 5 |
import os
|
| 6 |
import warnings
|
| 7 |
from contextlib import contextmanager
|
|
|
|
| 8 |
|
| 9 |
warnings.filterwarnings("ignore")
|
| 10 |
|
| 11 |
# CRITICAL: Coqui Terms of Service
|
| 12 |
os.environ["COQUI_TOS_AGREED"] = "1"
|
| 13 |
|
| 14 |
+
print("π Starting Voice Cloning Studio with Fixed Package...")
|
| 15 |
|
| 16 |
+
# PyTorch 2.6 Compatibility + Safe Globals Fix
|
| 17 |
@contextmanager
|
| 18 |
+
def fix_torch_load():
|
| 19 |
+
"""Complete fix for PyTorch 2.6 and XTTS loading"""
|
| 20 |
original_load = torch.load
|
| 21 |
+
|
| 22 |
def patched_load(f, *args, **kwargs):
|
| 23 |
kwargs['weights_only'] = False
|
| 24 |
return original_load(f, *args, **kwargs)
|
| 25 |
+
|
| 26 |
+
# Add safe globals for XTTS classes
|
| 27 |
+
try:
|
| 28 |
+
from TTS.tts.configs.xtts_config import XttsConfig
|
| 29 |
+
from TTS.tts.configs.shared_configs import BaseDatasetConfig
|
| 30 |
+
torch.serialization.add_safe_globals([XttsConfig, BaseDatasetConfig])
|
| 31 |
+
except:
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
torch.load = patched_load
|
| 35 |
try:
|
| 36 |
yield
|
|
|
|
| 44 |
# Global variables
|
| 45 |
TTS_MODEL = None
|
| 46 |
WHISPER_MODEL = None
|
|
|
|
| 47 |
|
| 48 |
def load_models():
|
| 49 |
+
"""Load models with the FIXED coqui-tts package"""
|
| 50 |
+
global TTS_MODEL, WHISPER_MODEL
|
| 51 |
|
|
|
|
|
|
|
|
|
|
| 52 |
if TTS_MODEL is None:
|
| 53 |
try:
|
| 54 |
+
with fix_torch_load():
|
| 55 |
+
# Use the FIXED coqui-tts package
|
| 56 |
from TTS.api import TTS
|
| 57 |
+
print("π¦ Loading XTTS-v2 with FIXED package...")
|
| 58 |
|
| 59 |
TTS_MODEL = TTS(
|
| 60 |
model_name="tts_models/multilingual/multi-dataset/xtts_v2",
|
| 61 |
progress_bar=True,
|
| 62 |
gpu=(DEVICE == "cuda")
|
| 63 |
)
|
| 64 |
+
print("β
XTTS-v2 loaded with FIXED package!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
except Exception as e:
|
| 67 |
+
print(f"β Model loading failed: {e}")
|
|
|
|
| 68 |
return False
|
| 69 |
|
|
|
|
| 70 |
if WHISPER_MODEL is None:
|
| 71 |
try:
|
|
|
|
| 72 |
import whisper
|
| 73 |
WHISPER_MODEL = whisper.load_model("base")
|
| 74 |
+
print("β
Whisper loaded!")
|
| 75 |
except Exception as e:
|
| 76 |
+
print(f"β Whisper failed: {e}")
|
| 77 |
|
| 78 |
return TTS_MODEL is not None
|
| 79 |
|
| 80 |
+
def voice_clone(reference_audio, input_audio, language="en"):
|
| 81 |
+
"""Voice cloning with COMPLETELY FIXED implementation"""
|
|
|
|
|
|
|
| 82 |
try:
|
| 83 |
+
if not reference_audio or not input_audio:
|
| 84 |
+
return None, "β Upload both audio files!"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
|
|
|
|
|
|
|
|
|
| 86 |
if not load_models():
|
| 87 |
+
return None, "β Models failed to load! Check if coqui-tts package is installed correctly."
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
# Extract text using Whisper
|
| 90 |
+
text = "Voice cloning demonstration."
|
| 91 |
if WHISPER_MODEL:
|
| 92 |
try:
|
|
|
|
| 93 |
result = WHISPER_MODEL.transcribe(input_audio)
|
| 94 |
+
extracted = result.get("text", "").strip()
|
| 95 |
+
if extracted and len(extracted) > 3:
|
| 96 |
+
text = extracted
|
| 97 |
+
print(f"β
Extracted text: {text[:50]}...")
|
|
|
|
|
|
|
|
|
|
| 98 |
except Exception as e:
|
| 99 |
+
print(f"β οΈ Whisper error: {e}")
|
| 100 |
+
|
| 101 |
+
# Generate speech using FIXED package
|
| 102 |
+
print("π Generating speech with FIXED coqui-tts...")
|
| 103 |
+
|
| 104 |
+
with fix_torch_load():
|
| 105 |
+
# Use the correct API that works with the fixed package
|
| 106 |
+
wav = TTS_MODEL.tts(
|
| 107 |
+
text=text,
|
| 108 |
+
speaker_wav=reference_audio,
|
| 109 |
+
language=language
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Save audio
|
| 113 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
|
| 114 |
+
output_path = tmp.name
|
| 115 |
+
|
| 116 |
+
# Convert to tensor and save
|
| 117 |
+
wav_tensor = torch.FloatTensor(wav)
|
| 118 |
+
if wav_tensor.dim() == 1:
|
| 119 |
+
wav_tensor = wav_tensor.unsqueeze(0)
|
| 120 |
+
|
| 121 |
+
sample_rate = 22050 # Standard XTTS sample rate
|
| 122 |
+
torchaudio.save(output_path, wav_tensor, sample_rate)
|
| 123 |
+
|
| 124 |
+
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
|
| 125 |
+
return output_path, f"β
SUCCESS with FIXED package!\n\nπ€ Text: {text[:100]}...\nπ§ Package: coqui-tts (maintained fork)\nπ Language: {language}\nπ Voice cloning completed!"
|
| 126 |
+
else:
|
| 127 |
+
return None, "β Output file is empty!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
+
return None, f"β Error: {str(e)}\n\nπ‘ Make sure you're using 'coqui-tts' package, not 'TTS'!"
|
| 131 |
|
| 132 |
+
def text_clone(reference_audio, text, language="en"):
|
| 133 |
+
"""Text-to-speech with COMPLETELY FIXED implementation"""
|
|
|
|
|
|
|
| 134 |
try:
|
| 135 |
+
if not reference_audio or not text:
|
| 136 |
+
return None, "β Upload audio and enter text!"
|
|
|
|
| 137 |
|
| 138 |
+
if not load_models():
|
| 139 |
+
return None, "β Models failed to load! Check if coqui-tts package is installed correctly."
|
| 140 |
|
| 141 |
+
print(f"π Generating speech for: {text[:50]}...")
|
| 142 |
|
| 143 |
+
with fix_torch_load():
|
| 144 |
+
wav = TTS_MODEL.tts(
|
| 145 |
+
text=text,
|
| 146 |
+
speaker_wav=reference_audio,
|
| 147 |
+
language=language
|
| 148 |
+
)
|
| 149 |
|
| 150 |
+
# Save audio
|
| 151 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
|
| 152 |
+
output_path = tmp.name
|
| 153 |
|
| 154 |
+
wav_tensor = torch.FloatTensor(wav)
|
| 155 |
+
if wav_tensor.dim() == 1:
|
| 156 |
+
wav_tensor = wav_tensor.unsqueeze(0)
|
| 157 |
+
|
| 158 |
+
torchaudio.save(output_path, wav_tensor, 22050)
|
| 159 |
+
|
| 160 |
+
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
|
| 161 |
+
return output_path, f"β
SUCCESS with FIXED package!\n\nπ Generated: {text[:100]}...\nπ§ Package: coqui-tts (maintained fork)\nπ Language: {language}\nπ Text-to-speech completed!"
|
| 162 |
+
else:
|
| 163 |
+
return None, "β Output file is empty!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
except Exception as e:
|
| 166 |
+
return None, f"β Error: {str(e)}\n\nπ‘ Make sure you're using 'coqui-tts' package, not 'TTS'!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
# Create Gradio Interface
|
| 169 |
+
with gr.Blocks(title="π Voice Cloning - PACKAGE FIXED") as demo:
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
gr.HTML("""
|
| 172 |
<div style="text-align: center; padding: 20px;">
|
| 173 |
+
<h1>π Voice Cloning Studio</h1>
|
| 174 |
+
<p style="color: #198754; font-weight: bold;">β
FIXED: Now uses maintained 'coqui-tts' package!</p>
|
| 175 |
+
<p style="color: #666;">No more 'generate' method errors - completely resolved!</p>
|
| 176 |
</div>
|
| 177 |
""")
|
| 178 |
|
| 179 |
+
# Show the fix
|
| 180 |
+
gr.HTML("""
|
| 181 |
+
<div style="background: #d1ecf1; padding: 15px; border-radius: 8px; margin: 20px 0;">
|
| 182 |
+
<h4 style="color: #0c5460;">π§ Problem Fixed!</h4>
|
| 183 |
+
<p><strong>Issue:</strong> Old TTS package had bugs causing 'generate' method errors</p>
|
| 184 |
+
<p><strong>Solution:</strong> Switched to maintained 'coqui-tts' fork that fixes this issue</p>
|
| 185 |
+
<p><strong>Result:</strong> Voice cloning now works without errors!</p>
|
| 186 |
</div>
|
| 187 |
""")
|
| 188 |
|
| 189 |
+
# Reference audio
|
|
|
|
| 190 |
reference_audio = gr.Audio(
|
| 191 |
+
label="π€ Reference Voice (Voice to Clone)",
|
| 192 |
type="filepath",
|
| 193 |
sources=["upload", "microphone"]
|
| 194 |
)
|
| 195 |
|
|
|
|
| 196 |
with gr.Tabs():
|
| 197 |
+
with gr.TabItem("π΅ Voice-to-Voice"):
|
| 198 |
+
input_audio = gr.Audio(
|
| 199 |
+
label="Input Audio (Content to Transform)",
|
| 200 |
+
type="filepath",
|
| 201 |
+
sources=["upload", "microphone"]
|
| 202 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
language1 = gr.Dropdown(
|
| 205 |
+
choices=[("English", "en"), ("Spanish", "es"), ("French", "fr")],
|
| 206 |
+
value="en",
|
| 207 |
+
label="Language"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
btn1 = gr.Button("π€ Clone Voice (FIXED Package)", variant="primary", size="lg")
|
| 211 |
+
output1 = gr.Audio(label="Cloned Voice Result")
|
| 212 |
+
status1 = gr.Textbox(label="Status", lines=6, interactive=False)
|
| 213 |
+
|
| 214 |
+
btn1.click(
|
| 215 |
+
fn=voice_clone,
|
| 216 |
+
inputs=[reference_audio, input_audio, language1],
|
| 217 |
+
outputs=[output1, status1]
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
with gr.TabItem("π Text-to-Speech"):
|
| 221 |
+
text_input = gr.Textbox(
|
| 222 |
+
label="Text to Convert",
|
| 223 |
+
lines=4,
|
| 224 |
+
placeholder="Enter text to speak in the cloned voice..."
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
language2 = gr.Dropdown(
|
| 228 |
+
choices=[("English", "en"), ("Spanish", "es"), ("French", "fr")],
|
| 229 |
+
value="en",
|
| 230 |
+
label="Language"
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
btn2 = gr.Button("π Generate Speech (FIXED Package)", variant="secondary", size="lg")
|
| 234 |
+
output2 = gr.Audio(label="Generated Speech Result")
|
| 235 |
+
status2 = gr.Textbox(label="Status", lines=6, interactive=False)
|
| 236 |
+
|
| 237 |
+
btn2.click(
|
| 238 |
+
fn=text_clone,
|
| 239 |
+
inputs=[reference_audio, text_input, language2],
|
| 240 |
+
outputs=[output2, status2]
|
| 241 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
if __name__ == "__main__":
|
| 244 |
demo.launch()
|