import streamlit as st from transformers import pipeline from gtts import gTTS import tempfile import os # Set up the translator using a Hugging Face model @st.cache_resource def load_model(model_name): return pipeline("translation", model=model_name) # Title of the app st.title("Language Translator App") # Add input fields for text and target language selection st.subheader("Enter the text you want to translate:") input_text = st.text_area("Text to translate", height=150) # Dropdown for language selection language_options = { "French": "Helsinki-NLP/opus-mt-en-fr", "German": "Helsinki-NLP/opus-mt-en-de", "Romanian": "Helsinki-NLP/opus-mt-en-ro", "Spanish": "Helsinki-NLP/opus-mt-en-es", "Italian": "Helsinki-NLP/opus-mt-en-it" } st.subheader("Select the target language:") target_language = st.selectbox("Target Language", list(language_options.keys())) # Translate button if st.button("Translate"): # Load the chosen model based on the selected language selected_model = language_options[target_language] translator = load_model(selected_model) # Perform translation if input_text: translation = translator(input_text) translated_text = translation[0]['translation_text'] # Display the translated text st.subheader(f"Translated Text in {target_language}:") st.write(translated_text) # Convert the translated text to speech tts = gTTS(text=translated_text, lang=target_language[:2].lower()) # Use the first two letters of the language for the TTS language code with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_file: temp_file_path = temp_file.name tts.save(temp_file_path) # Play the converted speech st.audio(temp_file_path, format="audio/mp3") # Clean up temporary file os.remove(temp_file_path) else: st.write("Please enter some text to translate.")