Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182835 unmodified linesfrom TTS.api import TTSfrom pydub import AudioSegment# Choose a Coqui TTS model hosted or local; example: a lightweight ljspeech model# you can replace with "coqui/XTTS-v2" or other models listed on HF.MODEL_NAME = "tts_models/en/ljspeech/tacotron2-DDC" # example, change if you prefer# Initialize TTS (this downloads model weights on first run)tts = TTS(MODEL_NAME, progress_bar=False, gpu=os.getenv("USE_GPU", "0") == "1")def apply_speed_and_volume(wav_path, speed_factor=1.0, volume_factor=1.0):"""speed_factor: 0.5 (half speed) .. 2.0 (double speed)volume_factor: 0.0 .. 2.0 (1.0 is original)Returns path to processed wav file."""audio = AudioSegment.from_file(wav_path, format="wav")# change speed by altering frame_rate then resamplingif speed_factor != 1.0:new_frame_rate = int(audio.frame_rate * speed_factor)sped = audio._spawn(audio.raw_data, overrides={"frame_rate": new_frame_rate})# set frame rate back to 44100 (or keep original)audio = sped.set_frame_rate(44100)# change volume (pydub uses dB)if volume_factor != 1.0:# avoid log(0)vol_db = 20.0 * math.log10(volume_factor) if volume_factor > 0 else -120.0audio = audio + vol_db# export to temp fileout_fd, out_path = tempfile.mkstemp(suffix=".wav")os.close(out_fd)audio.export(out_path, format="wav")return out_pathdef synthesize(text, voice_choice, speed, volume):"""text: strvoice_choice: str (ignored for single-speaker model; used if model supports speaker ids)speed: float slider (0.5..2.0)volume: float slider (0.0..2.0)"""if not text or not text.strip():return None# Create a temp file to store raw TTS outputfd, out_file = tempfile.mkstemp(suffix=".wav")os.close(fd)# Generate TTS into out_file# Depending on model, you may be able to pass speaker/voices; this example is generictts.tts_to_file(text=text, file_path=out_file)# Post-process speed & volumeprocessed = apply_speed_and_volume(out_file, speed_factor=float(speed), volume_factor=float(volume))# return path to audio for gradio to servereturn processed# Simple list of voices (if model supports multiple speakers, map to speaker ids)VOICE_CHOICES = ["Default"]with gr.Blocks() as demo:gr.Markdown("# Advanced Coqui TTS demo (Hugging Face Space)")with gr.Row():txt = gr.Textbox(lines=6, placeholder="Type text here...", 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="file")btn.click(fn=synthesize, inputs=[txt, voice, speed, volume], outputs=output_audio)if __name__ == "__main__":5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001015 unmodified linesfrom TTS.api import TTSfrom 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 44100if 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 zeroif float(volume_factor) <= 0:vol_db = -120.0else:vol_db = 20.0 * math.log10(float(volume_factor))audio = audio + vol_dbfd, out_path = tempfile.mkstemp(suffix=".wav")os.close(fd)audio.export(out_path, format="wav")return out_pathdef 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 outputfd, raw_out = tempfile.mkstemp(suffix=".wav")os.close(fd)# Generate the raw TTS wavtry:# 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 errortry:if os.path.exists(raw_out):os.remove(raw_out)except Exception:passraise e# Post-process for speed/volumeprocessed = apply_speed_and_volume(raw_out, speed_factor=float(speed), volume_factor=float(volume))# remove raw output if differenttry: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__":
app.py+54-36