|
import spaces |
|
import gradio as gr |
|
import edge_tts |
|
import asyncio |
|
import tempfile |
|
import os |
|
import re |
|
from pathlib import Path |
|
from pydub import AudioSegment |
|
|
|
def get_silence(duration_ms=1000): |
|
|
|
silent_audio = AudioSegment.silent( |
|
duration=duration_ms, |
|
frame_rate=24000 |
|
) |
|
|
|
|
|
silent_audio = silent_audio.set_channels(1) |
|
silent_audio = silent_audio.set_sample_width(4) |
|
|
|
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: |
|
|
|
silent_audio.export( |
|
tmp_file.name, |
|
format="mp3", |
|
bitrate="48k", |
|
parameters=[ |
|
"-ac", "1", |
|
"-ar", "24000", |
|
"-sample_fmt", "s32", |
|
"-codec:a", "libmp3lame" |
|
] |
|
) |
|
return tmp_file.name |
|
|
|
|
|
async def get_voices(): |
|
voices = await edge_tts.list_voices() |
|
return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices} |
|
|
|
def clean_text(text: str) -> str: |
|
""" |
|
Cleans a text string by: |
|
- Removing unwanted characters (except letters, digits, spaces, commas, periods) |
|
- Fixing broken words caused by dots and spaces |
|
- Normalizing spaces |
|
""" |
|
|
|
text = re.sub(r"[^a-zA-Z0-9\s,\.]", '', text) |
|
|
|
text = re.sub(r'(?<=\w)[\.\s]+(?=\w)', '', text) |
|
|
|
text = re.sub(r"\s+", ' ', text) |
|
|
|
text = text.strip() |
|
return text |
|
|
|
|
|
async def paragraph_to_speech(text, voice, rate, pitch): |
|
voice1 = "en-AU-WilliamNeural - en-AU (Male)" |
|
voice1F ="en-GB-SoniaNeural - en-GB (Female)" |
|
voice2 = "en-GB-RyanNeural - en-GB (Male)" |
|
voice2F = "en-US-JennyNeural - en-US (Female)" |
|
voice3 ="en-US-BrianMultilingualNeural - en-US (Male)" |
|
voice3F = "en-HK-YanNeural - en-HK (Female)" |
|
voice4 = "en-GB-ThomasNeural - en-GB (Male)" |
|
voice4F ="en-US-EmmaNeural - en-US (Female)" |
|
voice5 = "en-GB-RyanNeural - en-GB (Male)" |
|
voice6 = "en-GB-MaisieNeural - en-GB (Female)" |
|
|
|
if not text.strip(): |
|
return None, [] |
|
|
|
audio_segments = [] |
|
silence_durations = [] |
|
parts = re.split(r'(SS\d+\.?\d*)', text) |
|
for part in parts: |
|
if re.match(r'SS\d+\.?\d*', part): |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
silence_duration = float(part[2:]) * 1000 |
|
print(f"Silence.mp3 file NOT FOUND") |
|
silence_file_path = get_silence(silence_duration) |
|
audio_segments.append(silence_file_path) |
|
elif part.strip(): |
|
detect=0 |
|
processed_text = part |
|
current_voice = voice |
|
current_rate = rate |
|
current_pitch = pitch |
|
if part.startswith("1F"): |
|
detect=1 |
|
current_voice = voice1F.split(" - ")[0] |
|
current_pitch = 25 |
|
elif part.startswith("2F"): |
|
detect=1 |
|
current_voice = voice2F.split(" - ")[0] |
|
elif part.startswith("3F"): |
|
detect=1 |
|
current_voice = voice3F.split(" - ")[0] |
|
elif part.startswith("4F"): |
|
detect=1 |
|
current_voice = voice4F.split(" - ")[0] |
|
elif part.startswith("1M"): |
|
detect=1 |
|
current_voice = voice1.split(" - ")[0] |
|
elif part.startswith("2M"): |
|
detect=1 |
|
current_voice = voice2.split(" - ")[0] |
|
elif part.startswith("3M"): |
|
detect=1 |
|
current_voice = voice3.split(" - ")[0] |
|
elif part.startswith("4M"): |
|
detect=1 |
|
current_voice = voice4.split(" - ")[0] |
|
elif part.startswith("1O"): |
|
detect=1 |
|
current_voice = voice5.split(" - ")[0] |
|
current_pitch = -20 |
|
current_rate = -10 |
|
elif part.startswith("1C"): |
|
detect=1 |
|
current_voice = voice6.split(" - ")[0] |
|
else: |
|
|
|
|
|
current_voice = (voice or default_voice).split(" - ")[0] |
|
processed_text=part[:] |
|
|
|
|
|
match = re.search(r'[A-Za-z]+\-?\d+', part) |
|
if match: |
|
|
|
prefix = ''.join([ch for ch in match.group() if ch.isalpha()]) |
|
number = int(''.join([ch for ch in match.group() if ch.isdigit() or ch == '-'])) |
|
current_pitch = number |
|
|
|
new_text = re.sub(r'[A-Za-z]+\-?\d+', '', part, count=1).strip() |
|
|
|
processed_text = new_text[len(prefix):] |
|
else: |
|
if detect: |
|
processed_text = part[2:] |
|
rate_str = f"{current_rate:+d}%" |
|
|
|
|
|
|
|
pitch_str = f"{current_pitch:+d}Hz" |
|
texttosend = clean_text (processed_text) |
|
communicate = edge_tts.Communicate(texttosend, current_voice, rate=rate_str, pitch=pitch_str) |
|
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: |
|
tmp_path = tmp_file.name |
|
await communicate.save(tmp_path) |
|
audio_segments.append(tmp_path) |
|
else: |
|
audio_segments.append(None) |
|
|
|
return audio_segments, silence_durations |
|
|
|
|
|
async def text_to_speech(text, voice, rate, pitch): |
|
if not text.strip(): |
|
return None, gr.Warning("Please enter text to convert.") |
|
if not voice: |
|
return None, gr.Warning("Please select a voice.") |
|
|
|
|
|
|
|
paragraphs = [p.strip() for p in re.split(r'[โโ"]', text) if p.strip()] |
|
final_audio_segments = [] |
|
|
|
for paragraph in paragraphs: |
|
audio_paths, silence_times = await paragraph_to_speech(paragraph, voice, rate, pitch) |
|
if audio_paths: |
|
for i, path in enumerate(audio_paths): |
|
final_audio_segments.append(path) |
|
if i < len(silence_times): |
|
final_audio_segments.append(silence_times[i]) |
|
|
|
if not any(isinstance(item, str) for item in final_audio_segments): |
|
return None, None |
|
|
|
if all(not isinstance(item, str) for item in final_audio_segments): |
|
return None, "Only silence markers found." |
|
|
|
combined_audio_path = tempfile.mktemp(suffix=".mp3") |
|
with open(combined_audio_path, 'wb') as outfile: |
|
for segment in final_audio_segments: |
|
if isinstance(segment, str): |
|
try: |
|
with open(segment, 'rb') as infile: |
|
outfile.write(infile.read()) |
|
os.remove(segment) |
|
except FileNotFoundError: |
|
print(f"Warning: Audio file not found: {segment}") |
|
return combined_audio_path, None |
|
|
|
|
|
@spaces.GPU |
|
def tts_interface(text, voice, rate, pitch): |
|
audio, warning = asyncio.run(text_to_speech(text, voice, rate, pitch)) |
|
return audio, warning |
|
|
|
|
|
import gradio as gr |
|
|
|
async def create_demo(): |
|
voices = await get_voices() |
|
default_voice = "en-US-AndrewMultilingualNeural - en-US (Male)" |
|
description = """ |
|
Default = <b>"en-US-AndrewMultilingualNeural - en-US (Male), |
|
other voices 1F:en-GB-SoniaNeural, 2F:en-US-JennyNeural, 3F:en-HK-YanNeural, 4F:en-US-EmmaNeural |
|
1M:en-AU-WilliamNeural, 2M:en-GB-RyanNeural, 3M:en-US-BrianMultilingualNeural, 4M:en-GB-ThomasNeural |
|
1C: en-GB-MaisieNeural (Childvoice), 1O = en-GB-RyanNeural (OldMan)"</b> |
|
You can insert silence using the marker 'SS##' example "SS2.0" |
|
Enter your text, select a voice, and adjust the speech rate and pitch. Can also set like 1F-20 or 1M24. |
|
""" |
|
|
|
demo = gr.Interface( |
|
fn=tts_interface, |
|
inputs=[ |
|
gr.Textbox(label="Input Text", lines=5, placeholder="Separate paragraphs with two blank lines. Use 'SS[duration]' for silence."), |
|
gr.Dropdown(choices=[""] + list(voices.keys()), label="Select Voice", value=default_voice), |
|
gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Rate Adjustment (%)", step=1), |
|
gr.Slider(minimum=-50, maximum=50, value=0, label="Pitch Adjustment (Hz)", step=1) |
|
], |
|
outputs=[ |
|
gr.Audio(label="Generated Audio", type="filepath"), |
|
gr.Markdown(label="Warning", visible=False) |
|
], |
|
title="TTS using Edge Engine.. ENGLISH!", |
|
description=description, |
|
article="Process text paragraph by paragraph for smoother output and insert silence markers.", |
|
analytics_enabled=False, |
|
allow_flagging=False |
|
) |
|
return demo |
|
|
|
|
|
if __name__ == "__main__": |
|
demo = asyncio.run(create_demo()) |
|
demo.launch() |