Text-to-Speech / app.py
mjawad17's picture
Update app.py
eb03aa3 verified
import streamlit as st
from gtts import gTTS
from io import BytesIO
import time
# Dictionary to map language codes to full names
LANGUAGES = {
"ar": "Arabic",
"bn": "Bengali",
"zh": "Chinese",
"nl": "Dutch",
"en": "English",
"fa": "Persian",
"fr": "French",
"de": "German",
"el": "Greek",
"he": "Hebrew",
"hi": "Hindi",
"it": "Italian",
"ja": "Japanese",
"ko": "Korean",
"ms": "Malay",
"no": "Norwegian",
"pl": "Polish",
"pt": "Portuguese",
"ru": "Russian",
"es": "Spanish",
"sv": "Swedish",
"th": "Thai",
"tr": "Turkish",
"ur": "Urdu",
"vi": "Vietnamese",
}
# Function to convert text to speech
def text_to_speech(text, lang='en'):
tts = gTTS(text=text, lang=lang, slow=False)
mp3_fp = BytesIO()
tts.write_to_fp(mp3_fp)
mp3_fp.seek(0)
return mp3_fp
# Custom CSS for gradient background
st.markdown(
"""
<style>
.stApp {
background: linear-gradient(to bottom right, #6a11cb, #2575fc);
}
</style>
""",
unsafe_allow_html=True
)
# Streamlit app layout
st.title("Text-to-Speech App")
# Sidebar for language selection and other options
st.sidebar.header("Options")
# Language selection
lang_code = st.sidebar.selectbox(
"Choose language",
options=list(LANGUAGES.keys()),
format_func=lambda x: LANGUAGES[x] # Display full name
)
# Instruction for using the app
st.markdown("### Instructions For Using App")
st.markdown(
"""
1. Enter the text you want to convert to speech in the text box below.
2. Select the language from the sidebar.
3. Click the 'Convert to Speech' button to generate the audio file.
4. Click the 'Download' button to download the audio file.
"""
)
st.caption("---")
# Text input
user_text = st.text_area("Enter your text:", "Hello, world!")
# Initialize file variable
audio_file = None
# Convert text to speech and provide download button
if st.button("Convert to Speech"):
if user_text:
with st.spinner("Generating audio..."):
time.sleep(2) # 2-second loading simulation
audio_file = text_to_speech(user_text, lang_code)
st.audio(audio_file, format='audio/mp3')
# Make the audio file downloadable
st.download_button(
label="Download Audio",
data=audio_file,
file_name="output.mp3",
mime="audio/mp3"
)
else:
st.error("Please enter some text!")
st.markdown("Developed by Muhammad Jawad.")