tts-avatar / app2.py
fadzwan's picture
Rename app.py to app2.py
39de4c3 verified
import gradio as gr
import edge_tts
import asyncio
import tempfile
import os
import requests
from bs4 import BeautifulSoup
# Global voice cache
_voice_cache = None
async def get_cached_voices():
global _voice_cache
if _voice_cache is None:
_voice_cache = await edge_tts.list_voices()
return _voice_cache
async def get_voices():
voices = await get_cached_voices()
return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}
def fetch_html_text_from_url(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
# Extract meaningful readable text from HTML (e.g., from <p> tags)
paragraphs = soup.find_all('p')
text = "\n\n".join(p.get_text(strip=True) for p in paragraphs if p.get_text(strip=True))
if not text.strip():
return "No readable content found on the page."
return text
except Exception as e:
return f"Error fetching or parsing URL: {str(e)}"
async def text_to_speech(text, voice, rate, pitch):
if not text.strip():
return None, None, "Please enter text to convert."
if not voice:
return None, None, "Please select a voice."
voice_short_name = voice.split(" - ")[0]
rate_str = f"{rate:+d}%"
pitch_str = f"{pitch:+d}Hz"
communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
tmp_path = tmp_file.name
try:
await communicate.save(tmp_path)
except Exception as e:
return None, None, f"Error generating speech: {str(e)}"
return tmp_path, tmp_path, None
async def tts_interface(text, voice, rate, pitch):
audio_path, file_path, warning = await text_to_speech(text, voice, rate, pitch)
if warning:
return None, None, gr.update(visible=True, value=warning)
return audio_path, file_path, gr.update(visible=False)
async def create_demo():
voices = await get_voices()
with gr.Blocks(analytics_enabled=False) as demo:
gr.Markdown("# 🎙️ Edge TTS Text-to-Speech")
with gr.Row():
with gr.Column():
url_input = gr.Textbox(label="Optional: Enter URL to extract text (e.g., arXiv)", placeholder="https://arxiv.org/html/...")
fetch_button = gr.Button("Fetch Text from URL")
text_input = gr.Textbox(label="Input Text", lines=10)
fetch_button.click(fn=fetch_html_text_from_url, inputs=url_input, outputs=text_input)
example_btn = gr.Button("Use Example Text")
example_btn.click(fn=lambda: "Hello, this is a sample sentence using Edge TTS.", outputs=text_input)
voice_dropdown = gr.Dropdown(
choices=[""] + list(voices.keys()),
label="Select Voice",
value="en-US-GuyNeural - en-US (Male)"
)
rate_slider = gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Rate Adjustment (%)", step=1)
pitch_slider = gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch Adjustment (Hz)", step=1)
generate_btn = gr.Button("Generate Speech", variant="primary")
audio_output = gr.Audio(label="Generated Audio", type="filepath", autoplay=True)
file_download = gr.File(label="Download MP3", visible=False)
warning_md = gr.Markdown("Warning Message", visible=False)
generate_btn.click(
fn=tts_interface,
inputs=[text_input, voice_dropdown, rate_slider, pitch_slider],
outputs=[audio_output, file_download, warning_md]
)
return demo
async def main():
demo = await create_demo()
demo.queue()
demo.launch(show_api=False)
if __name__ == "__main__":
asyncio.run(main())