Spaces:
Running
Running
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950513 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021033 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611 unmodified line1631641651661671681694 unmodified lines17417517617717817918018118218318414 unmodified lines1992002012022032042052062079 unmodified lines2172182192202212222231 unmodified line22522622722822923023123223323423523623723823924024124223 unmodified lines2662672682692702712722732742752762772782792802812822832842852 unmodified linesimport torchaudioimport tempfileimport os# Device detectionDEVICE = "cuda" if torch.cuda.is_available() else "cpu"print(f"๐ Using device: {DEVICE}")# Global modelsTTS_MODEL = NoneWHISPER_MODEL = Nonedef load_models():"""Load TTS models with proper error handling"""global TTS_MODEL, WHISPER_MODELprint("๐ Loading models...")# Load XTTS-v2 (most reliable for voice cloning)if TTS_MODEL is None:try:from TTS.api import TTSos.environ["COQUI_TOS_AGREED"] = "1"print("๐ฆ Loading XTTS-v2...")TTS_MODEL = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(DEVICE)print("โ XTTS-v2 loaded successfully!")except Exception as e:print(f"โ XTTS-v2 failed: {e}")return False# Load Whisper for voice-to-voiceif WHISPER_MODEL is None:try:import whisperprint("๐ฆ Loading Whisper...")WHISPER_MODEL = whisper.load_model("base")print("โ Whisper loaded successfully!")except Exception as e:print(f"โ Whisper failed: {e}")return TTS_MODEL is not Nonedef voice_to_voice_clone(reference_audio, input_audio, language="en"):"""๐ค VOICE-TO-VOICE CLONING - Real ImplementationTransform input audio content using reference voice characteristics"""try:if not reference_audio:3 unmodified linesreturn None, "โ Please upload input audio (content to transform)!"# Load modelsif not load_models():return None, "โ XTTS-v2 model failed to load!"print("๐ค Starting Voice-to-Voice Cloning...")# Step 1: Extract text from input audio using Whisperif WHISPER_MODEL:print("๐ Transcribing input audio...")result = WHISPER_MODEL.transcribe(input_audio)extracted_text = result["text"]print(f"โ Extracted: {extracted_text[:100]}...")else:extracted_text = "Voice cloning demonstration using uploaded audio content."print("โ ๏ธ Using fallback text")# Step 2: Generate new audio with reference voice using XTTS-v2print("๐ญ Generating speech with cloned voice...")with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:output_path = tmp_file.name# Use XTTS-v2 for voice cloningTTS_MODEL.tts_to_file(text=extracted_text,speaker_wav=reference_audio,language=language,file_path=output_path)# Verify outputif os.path.exists(output_path) and os.path.getsize(output_path) > 0:return output_path, f"โ Voice-to-Voice Cloning Complete!\n๐ค Original content: '{extracted_text[:100]}...'\n๐ญ Applied reference voice characteristics\n๐ Language: {language}\n๐ค Model: XTTS-v2"else:return None, "โ Generated audio file is empty!"except Exception as e:error_msg = f"โ Voice-to-Voice Error: {str(e)}"print(error_msg)return None, error_msgdef text_to_voice_clone(reference_audio, input_text, language="en"):"""๐ TEXT-TO-VOICE CLONING - Real Implementation"""try:if not reference_audio:3 unmodified linesreturn None, "โ Please enter text to convert!"# Load modelsif not load_models():return None, "โ XTTS-v2 model failed to load!"print("๐ Starting Text-to-Voice Cloning...")with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:output_path = tmp_file.name# Generate speech using XTTS-v2TTS_MODEL.tts_to_file(text=input_text,speaker_wav=reference_audio,language=language,file_path=output_path)# Verify outputif os.path.exists(output_path) and os.path.getsize(output_path) > 0:return output_path, f"โ Text-to-Voice Complete!\n๐ Generated: '{input_text[:100]}...'\n๐ญ Using reference voice characteristics\n๐ Language: {language}\n๐ค Model: XTTS-v2"else:return None, "โ Generated audio file is empty!"except Exception as e:error_msg = f"โ Text-to-Voice Error: {str(e)}"print(error_msg)return None, error_msg# Try loading models at startupstartup_success = load_models()startup_msg = "โ XTTS-v2 Ready for Voice Cloning!" if startup_success else "โ ๏ธ Models will load on first use"# Create Gradio interface with BOTH functionalitieswith gr.Blocks(title="๐ญ Voice Cloning Studio - XTTS-v2",theme=gr.themes.Soft(primary_hue="blue", secondary_hue="green")) as demo:gr.HTML("""<div style="text-align: center; padding: 20px;"><h1 style="color: #2E86AB;">๐ญ Voice Cloning Studio</h1><p style="color: #666; font-size: 18px;">Real Voice-to-Voice & Text-to-Speech Cloning</p><p style="color: #888; font-size: 14px;">Powered by XTTS-v2 - Production Ready Open Source Model</p></div>""")# Statusstatus_color = "#d4edda" if startup_success else "#fff3cd"gr.HTML(f"""<div style="text-align: center; padding: 15px; background: {status_color}; border-radius: 10px; margin-bottom: 20px;"><strong>๐ค Model Status:</strong> {startup_msg}</div>""")1 unmodified line# Reference Voice (shared)gr.HTML("<h3 style='color: #2E86AB; text-align: center;'>๐ค Reference Voice (Voice to Clone)</h3>")reference_audio = gr.Audio(label="Upload Reference Audio (6+ seconds recommended)",type="filepath",sources=["upload", "microphone"])4 unmodified lineswith gr.TabItem("๐ต Voice-to-Voice Cloning"):gr.HTML("""<div style="padding: 15px; background: #e8f4fd; border-radius: 10px; margin-bottom: 15px;"><h4>๐ค Voice-to-Voice Process:</h4><p><strong>1.</strong> Upload reference voice (person to clone)<br><strong>2.</strong> Upload input audio (speech content to transform)<br><strong>3.</strong> AI extracts text from input audio using Whisper<br><strong>4.</strong> XTTS-v2 generates new audio with reference voice + extracted content</p></div>""")14 unmodified lines("๐ฎ๐น Italian", "it"),("๐ง๐ท Portuguese", "pt"),("๐จ๐ณ Chinese", "zh"),("๐ฏ๐ต Japanese", "ja"),("๐ฐ๐ท Korean", "ko"),("๐ท๐บ Russian", "ru")],value="en",label="Language"9 unmodified linesvoice_output = gr.Audio(label="Voice-to-Voice Result")voice_status = gr.Textbox(label="Voice-to-Voice Status",lines=6,interactive=False)1 unmodified linewith gr.TabItem("๐ Text-to-Speech Cloning"):gr.HTML("""<div style="padding: 15px; background: #f0fff0; border-radius: 10px; margin-bottom: 15px;"><h4>๐ Text-to-Speech Process:</h4><p><strong>1.</strong> Upload reference voice (person to clone)<br><strong>2.</strong> Enter text to convert to speech<br><strong>3.</strong> XTTS-v2 generates speech directly in the cloned voice<br><strong>4.</strong> Download high-quality result</p></div>""")with gr.Row():with gr.Column():text_input = gr.Textbox(label="Text to Convert",placeholder="Enter text to speak in the cloned voice...",lines=5)23 unmodified linestext_output = gr.Audio(label="Text-to-Speech Result")text_status = gr.Textbox(label="Text-to-Speech Status",lines=6,interactive=False)# Exampleswith gr.Accordion("๐ก Example Texts", open=False):examples = ["Hello, this is a demonstration of AI voice cloning using XTTS-v2.","The weather today is absolutely beautiful, perfect for a walk in the park.","Artificial intelligence continues to revolutionize how we create and share content."]gr.Examples(examples=examples, inputs=text_input)# Connect both functions - VOICE-TO-VOICE AND TEXT-TO-SPEECHvoice_btn.click(fn=voice_to_voice_clone,inputs=[reference_audio, input_audio, voice_lang],2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051063 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801813 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582591 unmodified line2612622632642652662674 unmodified lines27227327427527627727827928028128214 unmodified lines2972982993003013023039 unmodified lines3133143153163173183191 unmodified line32132232332432532632732832933033133233333433533633733823 unmodified lines3623633643653663673683693703713723733743753763773783793803813823833843853863872 unmodified linesimport torchaudioimport tempfileimport osimport sysimport traceback# Fix COQUI Terms of Service issueos.environ["COQUI_TOS_AGREED"] = "1"os.environ["COQUI_TOS"] = "1"# Device detection with fallbacksdef get_device():if torch.cuda.is_available():return "cuda"elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():return "cpu" # Force CPU for MPS compatibility issueselse:return "cpu"DEVICE = get_device()print(f"๐ Using device: {DEVICE}")# Global modelsTTS_MODEL = NoneWHISPER_MODEL = NoneMODEL_TYPE = Nonedef load_tts_models():"""Load TTS models with comprehensive error handling and multiple fallbacks"""global TTS_MODEL, WHISPER_MODEL, MODEL_TYPEprint("๐ Starting model loading process...")# Method 1: Try XTTS-v2 (Primary)if TTS_MODEL is None:try:print("๐ฆ Attempting XTTS-v2 (Method 1: Direct API)...")from TTS.api import TTS# Force download and loadTTS_MODEL = TTS(model_name="tts_models/multilingual/multi-dataset/xtts_v2",progress_bar=True,gpu=False if DEVICE == "cpu" else True).to(DEVICE)MODEL_TYPE = "XTTS-v2"print("โ XTTS-v2 loaded successfully!")except Exception as e1:print(f"โ XTTS-v2 Method 1 failed: {e1}")# Method 2: Try manual XTTS loadingtry:print("๐ฆ Attempting XTTS-v2 (Method 2: Manual loading)...")from TTS.tts.configs.xtts_config import XttsConfigfrom TTS.tts.models.xtts import Xttsconfig = XttsConfig()config.load_json("https://huggingface.co/coqui/XTTS-v2/resolve/main/config.json")TTS_MODEL = Xtts.init_from_config(config)TTS_MODEL.load_checkpoint(config,checkpoint_path="https://huggingface.co/coqui/XTTS-v2/resolve/main/model.pth",eval=True)TTS_MODEL.to(DEVICE)MODEL_TYPE = "XTTS-v2-Manual"print("โ XTTS-v2 manual loading successful!")except Exception as e2:print(f"โ XTTS-v2 Method 2 failed: {e2}")# Method 3: Try fallback TTS modeltry:print("๐ฆ Attempting fallback TTS model...")from TTS.api import TTSTTS_MODEL = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC", progress_bar=True).to(DEVICE)MODEL_TYPE = "Tacotron2-Fallback"print("โ Fallback TTS model loaded!")except Exception as e3:print(f"โ All TTS methods failed: {e3}")return False# Load Whisper for voice-to-voiceif WHISPER_MODEL is None:try:print("๐ฆ Loading Whisper for voice-to-voice...")import whisperWHISPER_MODEL = whisper.load_model("base")print("โ Whisper loaded successfully!")except Exception as e:print(f"โ ๏ธ Whisper failed: {e}")print("๐ Voice-to-voice will use fallback text")return TTS_MODEL is not Nonedef voice_to_voice_clone(reference_audio, input_audio, language="en"):"""๐ค VOICE-TO-VOICE CLONING with robust error handling"""try:if not reference_audio:3 unmodified linesreturn None, "โ Please upload input audio (content to transform)!"# Load modelsif not load_tts_models():return None, "โ All TTS models failed to load! Check your internet connection and try again."print("๐ค Starting Voice-to-Voice Cloning...")# Step 1: Extract text from input audioextracted_text = ""if WHISPER_MODEL:try:print("๐ Transcribing input audio with Whisper...")result = WHISPER_MODEL.transcribe(input_audio)extracted_text = result["text"].strip()print(f"โ Extracted: {extracted_text[:100]}...")except Exception as e:print(f"โ ๏ธ Whisper transcription failed: {e}")extracted_text = "Voice cloning demonstration using uploaded audio content."else:extracted_text = "Voice cloning demonstration using uploaded audio content."print("โ ๏ธ Using fallback text (Whisper not available)")if not extracted_text:extracted_text = "Hello, this is a voice cloning demonstration."# Step 2: Generate speech with reference voiceprint(f"๐ญ Generating speech with {MODEL_TYPE}...")with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:output_path = tmp_file.name# Use appropriate TTS method based on model typeif MODEL_TYPE == "XTTS-v2":TTS_MODEL.tts_to_file(text=extracted_text,speaker_wav=reference_audio,language=language,file_path=output_path)elif MODEL_TYPE == "XTTS-v2-Manual":# Manual XTTS inferencegpt_cond_latent, speaker_embedding = TTS_MODEL.get_conditioning_latents(audio_path=[reference_audio])out = TTS_MODEL.inference(extracted_text,language,gpt_cond_latent,speaker_embedding,temperature=0.7)torchaudio.save(output_path, torch.tensor(out["wav"]).unsqueeze(0), 24000)else:# Fallback model (limited voice cloning)TTS_MODEL.tts_to_file(text=extracted_text, file_path=output_path)# Verify outputif os.path.exists(output_path) and os.path.getsize(output_path) > 0:return output_path, f"โ Voice-to-Voice Cloning Complete!\n๐ค Original: '{extracted_text[:100]}...'\n๐ญ Model: {MODEL_TYPE}\n๐ Language: {language}\n๐ Voice characteristics applied from reference audio"else:return None, "โ Generated audio file is empty!"except Exception as e:error_msg = f"โ Voice-to-Voice Error: {str(e)}\n๐ Model: {MODEL_TYPE}\n๐ Traceback:\n{traceback.format_exc()}"print(error_msg)return None, error_msgdef text_to_voice_clone(reference_audio, input_text, language="en"):"""๐ TEXT-TO-VOICE CLONING with robust error handling"""try:if not reference_audio:3 unmodified linesreturn None, "โ Please enter text to convert!"# Load modelsif not load_tts_models():return None, "โ All TTS models failed to load! Check your internet connection and try again."print("๐ Starting Text-to-Voice Cloning...")with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:output_path = tmp_file.name# Generate speech using appropriate methodif MODEL_TYPE == "XTTS-v2":TTS_MODEL.tts_to_file(text=input_text,speaker_wav=reference_audio,language=language,file_path=output_path)elif MODEL_TYPE == "XTTS-v2-Manual":# Manual XTTS inferencegpt_cond_latent, speaker_embedding = TTS_MODEL.get_conditioning_latents(audio_path=[reference_audio])out = TTS_MODEL.inference(input_text,language,gpt_cond_latent,speaker_embedding,temperature=0.7)torchaudio.save(output_path, torch.tensor(out["wav"]).unsqueeze(0), 24000)else:# Fallback modelTTS_MODEL.tts_to_file(text=input_text, file_path=output_path)# Verify outputif os.path.exists(output_path) and os.path.getsize(output_path) > 0:return output_path, f"โ Text-to-Voice Complete!\n๐ Generated: '{input_text[:100]}...'\n๐ญ Model: {MODEL_TYPE}\n๐ Language: {language}\n๐ Voice characteristics applied from reference audio"else:return None, "โ Generated audio file is empty!"except Exception as e:error_msg = f"โ Text-to-Voice Error: {str(e)}\n๐ Model: {MODEL_TYPE}\n๐ Traceback:\n{traceback.format_exc()}"print(error_msg)return None, error_msg# Try loading models at startupprint("๐ Initializing models at startup...")startup_success = load_tts_models()if startup_success:startup_msg = f"โ {MODEL_TYPE} Ready for Voice Cloning!"startup_color = "#d4edda"else:startup_msg = "โ ๏ธ Models will load on first use (may take 2-3 minutes)"startup_color = "#fff3cd"# Create Gradio interfacewith gr.Blocks(title="๐ญ Voice Cloning Studio - Production Ready",theme=gr.themes.Soft(primary_hue="blue", secondary_hue="green")) as demo:gr.HTML("""<div style="text-align: center; padding: 20px;"><h1 style="color: #2E86AB;">๐ญ Voice Cloning Studio</h1><p style="color: #666; font-size: 18px;">Professional Voice-to-Voice & Text-to-Speech Cloning</p><p style="color: #888; font-size: 14px;">Multi-Model Support: XTTS-v2 + Fallbacks | Production Ready</p></div>""")# Dynamic statusgr.HTML(f"""<div style="text-align: center; padding: 15px; background: {startup_color}; border-radius: 10px; margin-bottom: 20px;"><strong>๐ค Model Status:</strong> {startup_msg}</div>""")1 unmodified line# Reference Voice (shared)gr.HTML("<h3 style='color: #2E86AB; text-align: center;'>๐ค Reference Voice (Voice to Clone)</h3>")reference_audio = gr.Audio(label="Upload Reference Audio (6+ seconds of clear speech)",type="filepath",sources=["upload", "microphone"])4 unmodified lineswith gr.TabItem("๐ต Voice-to-Voice Cloning"):gr.HTML("""<div style="padding: 15px; background: #e8f4fd; border-radius: 10px; margin-bottom: 15px;"><h4 style="color: #1e40af;">๐ค Voice-to-Voice Process:</h4><p><strong>Step 1:</strong> Upload reference voice (person to clone)<br><strong>Step 2:</strong> Upload input audio (speech content to transform)<br><strong>Step 3:</strong> AI extracts text from input using Whisper<br><strong>Step 4:</strong> Generate new audio with reference voice + extracted content</p></div>""")14 unmodified lines("๐ฎ๐น Italian", "it"),("๐ง๐ท Portuguese", "pt"),("๐จ๐ณ Chinese", "zh"),("๐ฏ๐ต Japanese", "ja")],value="en",label="Language"9 unmodified linesvoice_output = gr.Audio(label="Voice-to-Voice Result")voice_status = gr.Textbox(label="Voice-to-Voice Status",lines=8,interactive=False)1 unmodified linewith gr.TabItem("๐ Text-to-Speech Cloning"):gr.HTML("""<div style="padding: 15px; background: #f0fff0; border-radius: 10px; margin-bottom: 15px;"><h4 style="color: #16a34a;">๐ Text-to-Speech Process:</h4><p><strong>Step 1:</strong> Upload reference voice (person to clone)<br><strong>Step 2:</strong> Enter text to convert to speech<br><strong>Step 3:</strong> AI generates speech in the cloned voice<br><strong>Step 4:</strong> Download high-quality result</p></div>""")with gr.Row():with gr.Column():text_input = gr.Textbox(label="Text to Convert to Speech",placeholder="Enter text to speak in the cloned voice...",lines=5)23 unmodified linestext_output = gr.Audio(label="Text-to-Speech Result")text_status = gr.Textbox(label="Text-to-Speech Status",lines=8,interactive=False)# Examples and Helpwith gr.Accordion("๐ก Example Texts & Troubleshooting", open=False):gr.Markdown("""### Example Texts- "Hello, this is a demonstration of AI voice cloning using advanced models."- "The weather today is absolutely beautiful, perfect for a walk in the park."- "Artificial intelligence continues to revolutionize how we create content."### Troubleshooting- **Model Loading Issues**: Wait 2-3 minutes on first use for model download- **Voice Quality**: Use clear, 6+ second reference audio with minimal background noise- **Language Support**: XTTS-v2 supports 16+ languages with cross-lingual cloning- **Processing Time**: Voice cloning takes 10-60 seconds depending on text length""")# Event handlers - BOTH FUNCTIONALITIES CONNECTEDvoice_btn.click(fn=voice_to_voice_clone,inputs=[reference_audio, input_audio, voice_lang],
app.py+185-83