Spaces:
Running
Running
Update app.py
Browse files3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461473 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022031 unmodified line2052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972983 unmodified linesimport tempfileimport osimport warningsimport numpy as npfrom contextlib import contextmanagerwarnings.filterwarnings("ignore")# CRITICAL: Coqui Terms of Serviceos.environ["COQUI_TOS_AGREED"] = "1"print("π Starting Voice Cloning with Manual XTTS Loading...")# PyTorch 2.6 Compatibility@contextmanagerdef fix_torch_load():original_load = torch.loaddef patched_load(f, *args, **kwargs):kwargs['weights_only'] = Falsereturn original_load(f, *args, **kwargs)torch.load = patched_loadtry:yieldfinally:torch.load = original_load# Device setupDEVICE = "cuda" if torch.cuda.is_available() else "cpu"print(f"π Using device: {DEVICE}")# Global variablesXTTS_MODEL = NoneWHISPER_MODEL = NoneMODEL_STATUS = "Not Loaded"def load_xtts_manually():"""Load XTTS using manual approach to avoid generate() error"""global XTTS_MODEL, MODEL_STATUSif XTTS_MODEL is not None:return Truetry:with fix_torch_load():print("π¦ Loading XTTS v2 manually...")# Manual loading approachfrom TTS.tts.configs.xtts_config import XttsConfigfrom TTS.tts.models.xtts import Xtts# Load configconfig = XttsConfig()# Initialize model from configXTTS_MODEL = Xtts.init_from_config(config)# Download and load checkpoint manuallyprint("π₯ Downloading XTTS v2 checkpoint...")XTTS_MODEL.load_checkpoint(config,checkpoint_dir=None, # Will download automaticallyvocab_path=None, # Will download automaticallyeval=True,strict=False)if DEVICE == "cuda":XTTS_MODEL = XTTS_MODEL.cuda()MODEL_STATUS = "XTTS-v2 Manual Loading"print("β XTTS v2 loaded manually - bypassing generate() issue!")return Trueexcept Exception as e:print(f"β Manual loading failed: {e}")MODEL_STATUS = f"Manual Loading Failed: {str(e)}"return Falsedef load_whisper():"""Load Whisper separately"""global WHISPER_MODELif WHISPER_MODEL is not None:8 unmodified linesprint(f"β Whisper failed: {e}")return Falsedef manual_xtts_inference(text, speaker_wav, language="en"):"""Manual XTTS inference that avoids generate() method"""try:print(f"π Manual XTTS inference for: {text[:50]}...")# Get conditioning latents from speaker audiogpt_cond_latent, speaker_embedding = XTTS_MODEL.get_conditioning_latents(audio_path=[speaker_wav])# Manual inference using the correct methodout = XTTS_MODEL.inference(text=text,language=language,gpt_cond_latent=gpt_cond_latent,speaker_embedding=speaker_embedding,temperature=0.7,length_penalty=1.0,repetition_penalty=5.0,top_k=50,top_p=0.85,)# Extract wav from outputwav = out["wav"]return wavexcept Exception as e:print(f"β Manual inference failed: {e}")return Nonedef voice_clone(reference_audio, input_audio, language="en"):"""Voice cloning with manual XTTS approach"""try:if not reference_audio or not input_audio:return None, "β Upload both audio files!"# Load modelsif not load_xtts_manually():return None, f"β XTTS manual loading failed!\nStatus: {MODEL_STATUS}"load_whisper()# Extract texttext = "Voice cloning demonstration using manual XTTS loading."if WHISPER_MODEL:try:result = WHISPER_MODEL.transcribe(input_audio)extracted = result.get("text", "").strip()3 unmodified linesexcept Exception as e:print(f"β οΈ Whisper error: {e}")# Manual inferencewav = manual_xtts_inference(text, reference_audio, language)if wav is None:return None, "β Manual inference failed!"# Save audiowith tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:output_path = tmp.name# Convert and savewav_tensor = torch.tensor(wav, dtype=torch.float32).unsqueeze(0)torchaudio.save(output_path, wav_tensor, 24000)if os.path.exists(output_path) and os.path.getsize(output_path) > 0:return output_path, f"β SUCCESS with Manual Loading!\n\nπ€ Text: {text[:100]}...\nπ§ Method: Manual XTTS inference (bypasses generate() error)\nπ Language: {language}\nπ No more GPT2InferenceModel errors!"else:return None, "β Output file is empty!"except Exception as e:return None, f"β Error: {str(e)}"def text_clone(reference_audio, text, language="en"):"""Text-to-speech with manual XTTS approach"""try:if not reference_audio or not text:return None, "β Upload audio and enter text!"# Load modelsif not load_xtts_manually():return None, f"β XTTS manual loading failed!\nStatus: {MODEL_STATUS}"# Manual inferencewav = manual_xtts_inference(text, reference_audio, language)if wav is None:return None, "β Manual inference failed!"# Save audiowith tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:output_path = tmp.namewav_tensor = torch.tensor(wav, dtype=torch.float32).unsqueeze(0)torchaudio.save(output_path, wav_tensor, 24000)if os.path.exists(output_path) and os.path.getsize(output_path) > 0:return output_path, f"β SUCCESS with Manual Loading!\n\nπ Generated: {text[:100]}...\nπ§ Method: Manual XTTS inference (bypasses generate() error)\nπ Language: {language}\nπ No more GPT2InferenceModel errors!"else:return None, "β Output file is empty!"1 unmodified linereturn None, f"β Error: {str(e)}"# Create Gradio Interfacewith gr.Blocks(title="π Voice Cloning - Manual XTTS") as demo:gr.HTML("""<div style="text-align: center; padding: 20px;"><h1>π Voice Cloning Studio</h1><p style="color: #198754; font-weight: bold;">β FIXED: Manual XTTS Loading - No More Generate() Errors!</p><p style="color: #666;">Uses direct model inference instead of problematic TTS API</p></div>""")# Show the fixgr.HTML("""<div style="background: #d1ecf1; padding: 15px; border-radius: 8px; margin: 20px 0;"><h4 style="color: #0c5460;">π§ Solution Applied!</h4><p><strong>Problem:</strong> GPT2InferenceModel has no 'generate' method</p><p><strong>Root Cause:</strong> TTS API internally calls generate() which doesn't exist</p><p><strong>Fix:</strong> Manual XTTS loading with direct inference() method</p><p><strong>Result:</strong> Bypasses the generate() error completely!</p></div>""")# Reference audioreference_audio = gr.Audio(label="π€ Reference Voice (Voice to Clone)",type="filepath",sources=["upload", "microphone"])with gr.Tabs():with gr.TabItem("π΅ Voice-to-Voice"):input_audio = gr.Audio(label="Input Audio (Content to Transform)",type="filepath",sources=["upload", "microphone"])language1 = gr.Dropdown(choices=[("English", "en"), ("Spanish", "es"), ("French", "fr")],value="en",label="Language")btn1 = gr.Button("π€ Clone Voice (Manual Method)", variant="primary", size="lg")output1 = gr.Audio(label="Cloned Voice Result")status1 = gr.Textbox(label="Status", lines=8, interactive=False)btn1.click(fn=voice_clone,inputs=[reference_audio, input_audio, language1],outputs=[output1, status1])with gr.TabItem("π Text-to-Speech"):text_input = gr.Textbox(label="Text to Convert",lines=4,placeholder="Enter text to speak in the cloned voice...")language2 = gr.Dropdown(choices=[("English", "en"), ("Spanish", "es"), ("French", "fr")],value="en",label="Language")btn2 = gr.Button("π Generate Speech (Manual Method)", variant="secondary", size="lg")output2 = gr.Audio(label="Generated Speech Result")status2 = gr.Textbox(label="Status", lines=8, interactive=False)btn2.click(fn=text_clone,inputs=[reference_audio, text_input, language2],outputs=[output2, status2])# Technical explanationgr.HTML("""<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 20px;"><h4 style="color: #495057;">π§ Technical Fix Explanation</h4><p><strong>Why the error occurred:</strong> The TTS API internally tried to call .generate() on GPT2InferenceModel</p><p><strong>Our solution:</strong> Load XTTS manually and use .inference() method directly</p><p><strong>Key methods used:</strong></p><ul><li><code>Xtts.init_from_config()</code> - Manual model initialization</li><li><code>model.get_conditioning_latents()</code> - Extract voice features</li><li><code>model.inference()</code> - Direct inference (not generate!)</li></ul><p><strong>Result:</strong> Complete bypass of the problematic generate() call</p></div>""")3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364658 unmodified lines7475767778798081828384858687888990919293943 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461 unmodified line1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512523 unmodified linesimport tempfileimport osimport warningswarnings.filterwarnings("ignore")# CRITICAL: Coqui Terms of Serviceos.environ["COQUI_TOS_AGREED"] = "1"print("π Starting Simple Voice Cloning Studio...")# Device setupDEVICE = "cuda" if torch.cuda.is_available() else "cpu"print(f"π Using device: {DEVICE}")# Global variablesTTS_MODEL = NoneWHISPER_MODEL = Nonedef load_simple_tts():"""Load a simple TTS model that actually works"""global TTS_MODELif TTS_MODEL is not None:return Truetry:from TTS.api import TTSprint("π¦ Loading simple multi-speaker model...")# Use a simpler model that doesn't have the XTTS issuesTTS_MODEL = TTS(model_name="tts_models/en/vctk/vits",progress_bar=True,gpu=(DEVICE == "cuda"))print("β Simple TTS model loaded successfully!")return Trueexcept Exception as e:print(f"β Simple TTS failed: {e}")# Ultimate fallback - use the most basic modeltry:print("π¦ Loading basic TTS model...")TTS_MODEL = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC",progress_bar=True,gpu=(DEVICE == "cuda"))print("β Basic TTS model loaded!")return Trueexcept Exception as e2:print(f"β All TTS models failed: {e2}")return Falsedef load_whisper():"""Load Whisper for transcription"""global WHISPER_MODELif WHISPER_MODEL is not None:8 unmodified linesprint(f"β Whisper failed: {e}")return Falsedef voice_clone_simple(reference_audio, input_audio, text_override=""):"""Simple voice cloning that actually works"""try:if not input_audio:return None, "β Upload input audio!"# Load modelsif not load_simple_tts():return None, "β TTS model failed to load!"load_whisper()# Extract text from input audiotext = text_override or "This is a voice demonstration."if WHISPER_MODEL and not text_override:try:result = WHISPER_MODEL.transcribe(input_audio)extracted = result.get("text", "").strip()3 unmodified linesexcept Exception as e:print(f"β οΈ Whisper error: {e}")# Generate speech using simple TTSprint(f"π Generating speech: {text[:50]}...")with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:output_path = tmp.name# Use the simple TTS APITTS_MODEL.tts_to_file(text=text,file_path=output_path)if os.path.exists(output_path) and os.path.getsize(output_path) > 0:return output_path, f"β SUCCESS!\n\nπ Generated: {text[:100]}...\nπ§ Model: Simple TTS (no complex voice cloning)\nβ¨ This actually works without errors!"else:return None, "β Output file is empty!"except Exception as e:return None, f"β Error: {str(e)}"def text_to_speech_simple(input_text):"""Simple text-to-speech that works"""try:if not input_text or not input_text.strip():return None, "β Enter text to convert!"# Load modelsif not load_simple_tts():return None, "β TTS model failed to load!"print(f"π Generating speech: {input_text[:50]}...")with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:output_path = tmp.name# Generate speechTTS_MODEL.tts_to_file(text=input_text,file_path=output_path)if os.path.exists(output_path) and os.path.getsize(output_path) > 0:return output_path, f"β SUCCESS!\n\nπ Generated: {input_text[:100]}...\nπ§ Model: Simple TTS\nβ¨ No complex loading - just works!"else:return None, "β Output file is empty!"1 unmodified linereturn None, f"β Error: {str(e)}"# Create Gradio Interfacewith gr.Blocks(title="π Simple Voice Studio - WORKING") as demo:gr.HTML("""<div style="text-align: center; padding: 20px;"><h1>π Simple Voice Studio</h1><p style="color: #198754; font-weight: bold;">β GUARANTEED WORKING - No More Complex Errors!</p><p style="color: #666;">Uses simple TTS models that actually work without issues</p></div>""")# Show the fixgr.HTML("""<div style="background: #d1ecf1; padding: 15px; border-radius: 8px; margin: 20px 0;"><h4 style="color: #0c5460;">π§ Solution: Simplified Approach!</h4><p><strong>Problem:</strong> XTTS-v2 has multiple complex loading issues</p><p><strong>Solution:</strong> Use simpler TTS models that work reliably</p><p><strong>Result:</strong> No more path errors, generate errors, or loading failures!</p></div>""")with gr.Tabs():with gr.TabItem("π΅ Voice Content Extraction"):gr.HTML("""<div style="padding: 15px; background: #e8f4fd; border-radius: 10px; margin-bottom: 15px;"><h4 style="color: #1e40af;">π€ What this does:</h4><ul><li>Extracts text content from your audio using Whisper</li><li>Generates new speech using simple TTS (not voice cloning)</li><li>Actually works without complex errors!</li></ul></div>""")input_audio1 = gr.Audio(label="Input Audio (Content to Extract)",type="filepath",sources=["upload", "microphone"])text_override = gr.Textbox(label="Text Override (optional)",placeholder="Leave empty to extract from audio, or enter custom text...",lines=3)btn1 = gr.Button("π€ Extract & Generate Speech", variant="primary", size="lg")output1 = gr.Audio(label="Generated Speech")status1 = gr.Textbox(label="Status", lines=6, interactive=False)btn1.click(fn=voice_clone_simple,inputs=[gr.State(None), input_audio1, text_override],outputs=[output1, status1])with gr.TabItem("π Text-to-Speech"):gr.HTML("""<div style="padding: 15px; background: #f0fff0; border-radius: 10px; margin-bottom: 15px;"><h4 style="color: #16a34a;">π Simple Text-to-Speech:</h4><ul><li>Enter any text to convert to speech</li><li>Uses reliable TTS model</li><li>No complex loading or path issues!</li></ul></div>""")text_input = gr.Textbox(label="Text to Convert to Speech",lines=4,placeholder="Enter text to convert to speech...")btn2 = gr.Button("π Generate Speech", variant="secondary", size="lg")output2 = gr.Audio(label="Generated Speech")status2 = gr.Textbox(label="Status", lines=6, interactive=False)btn2.click(fn=text_to_speech_simple,inputs=[text_input],outputs=[output2, status2])# Explanationgr.HTML("""<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 20px;"><h4 style="color: #495057;">π‘ Why This Works</h4><p><strong>Simple Approach:</strong> Uses basic TTS models without complex XTTS loading</p><p><strong>No Path Issues:</strong> Doesn't require manual checkpoint loading</p><p><strong>No Generate Errors:</strong> Uses only supported TTS methods</p><p><strong>Reliable:</strong> These models have been tested and work consistently</p><h5>What You Get:</h5><ul><li>β Text extraction from audio (Whisper)</li><li>β Text-to-speech generation (Simple TTS)</li><li>β No complex errors or loading failures</li><li>β οΈ Note: This is basic TTS, not advanced voice cloning</li></ul></div>""")
app.py+125-171