import os import torch import gradio as gr # 设置缓存路径,避免 /.cache 权限问题 os.environ["COQUI_TOS_AGREED"] = "1" os.environ["XDG_CACHE_HOME"] = "/tmp/tts_cache" # 加载模型(XTTS v2) from TTS.api import TTS tts = TTS(model_name="tts_models/multilingual/multi-dataset/xtts_v2", progress_bar=False, gpu=torch.cuda.is_available()) # 合成函数 def generate_tts(input_text, speaker_wav, language): if speaker_wav is None or input_text.strip() == "": return "Please provide both voice sample and text.", None # 合成语音 output_path = "/tmp/output.wav" tts.tts_to_file( text=input_text, speaker_wav=speaker_wav, language=language, file_path=output_path ) return "✅ Generation complete", output_path # Gradio 界面 gr.Interface( fn=generate_tts, inputs=[ gr.Textbox(label="Input Text"), gr.Audio(type="filepath", label="Upload your voice (.wav)", format="wav"), gr.Dropdown( label="Target Language", choices=["en", "zh", "es", "fr", "de", "ja", "ko"], value="en" ) ], outputs=[ gr.Textbox(label="Status"), gr.Audio(label="Synthesized Audio") ], title="XTTS v2 - Voice Cloning TTS", description="Upload a short voice clip (2-10 seconds), enter text, and XTTS will clone the voice to speak it.", allow_flagging="never" ).launch()