# app.py import os import tempfile import math import gradio as gr from TTS.api import TTS from pydub import AudioSegment # ----------------------- # Configuration # ----------------------- # Pick a Coqui TTS model. Change to a model you prefer. MODEL_NAME = os.environ.get("TTS_MODEL", "tts_models/en/ljspeech/tacotron2-DDC") # If you set an env var USE_GPU=1 in Space settings, this will enable GPU usage in TTS init. USE_GPU = os.environ.get("USE_GPU", "0") == "1" # Initialize TTS (downloads weights on first run) tts = TTS(MODEL_NAME, progress_bar=False, gpu=USE_GPU) def apply_speed_and_volume(wav_path: str, speed_factor: float = 1.0, volume_factor: float = 1.0) -> str: """ Load wav_path, change speed and volume using pydub, export a new temp wav file and return its path. speed_factor: 0.5 .. 2.0 (1.0 = original) volume_factor: 0.0 .. 2.0 (1.0 = original) """ audio = AudioSegment.from_file(wav_path, format="wav") # Speed: change frame_rate then resample to 44100 if speed_factor != 1.0: new_frame_rate = int(audio.frame_rate * float(speed_factor)) sped = audio._spawn(audio.raw_data, overrides={"frame_rate": new_frame_rate}) audio = sped.set_frame_rate(44100) # Volume: pydub uses dB. Convert linear multiplier to dB. if volume_factor != 1.0: # avoid math domain error for zero if float(volume_factor) <= 0: vol_db = -120.0 else: vol_db = 20.0 * math.log10(float(volume_factor)) audio = audio + vol_db fd, out_path = tempfile.mkstemp(suffix=".wav") os.close(fd) audio.export(out_path, format="wav") return out_path def synthesize(text: str, voice_choice: str, speed: float, volume: float): """ Returns a filepath string pointing to the processed WAV file (which Gradio will serve). voice_choice: currently unused for single-speaker models. If model supports speaker IDs, adapt this. """ if not text or not text.strip(): return None # Create a temp target for the TTS output fd, raw_out = tempfile.mkstemp(suffix=".wav") os.close(fd) # Generate the raw TTS wav try: # If model supports speaker or voice params, you can pass them here. tts.tts_to_file(text=text, file_path=raw_out) except Exception as e: # cleanup and surface error try: if os.path.exists(raw_out): os.remove(raw_out) except Exception: pass raise e # Post-process for speed/volume processed = apply_speed_and_volume(raw_out, speed_factor=float(speed), volume_factor=float(volume)) # remove raw output if different try: if os.path.exists(raw_out) and raw_out != processed: os.remove(raw_out) except Exception: pass # Return filepath (Gradio Audio uses type="filepath") return processed # A small voice list placeholder: if you use a multi-speaker model, populate with speaker IDs. VOICE_CHOICES = ["Default"] with gr.Blocks() as demo: gr.Markdown("# Advanced Coqui TTS (Gradio Space)") with gr.Row(): txt = gr.Textbox(lines=6, placeholder="Type text to synthesize...", label="Text") with gr.Column(): voice = gr.Dropdown(choices=VOICE_CHOICES, value=VOICE_CHOICES[0], label="Voice") speed = gr.Slider(minimum=0.5, maximum=2.0, step=0.05, value=1.0, label="Speed (0.5–2.0)") volume = gr.Slider(minimum=0.0, maximum=2.0, step=0.05, value=1.0, label="Volume (0.0–2.0)") btn = gr.Button("Synthesize") output_audio = gr.Audio(label="Output Audio", type="filepath") btn.click(fn=synthesize, inputs=[txt, voice, speed, volume], outputs=output_audio) if __name__ == "__main__": demo.launch()