streamlit run app.py import streamlit as st from transformers import MarianMTModel, MarianTokenizer # Define a dictionary of available languages and their corresponding Hugging Face models LANGUAGE_MODELS = { "French": "Helsinki-NLP/opus-mt-en-fr", "German": "Helsinki-NLP/opus-mt-en-de", "Spanish": "Helsinki-NLP/opus-mt-en-es", "Italian": "Helsinki-NLP/opus-mt-en-it", "Portuguese": "Helsinki-NLP/opus-mt-en-pt", # Add more languages and their models here } def load_model(language): model_name = LANGUAGE_MODELS.get(language) if model_name is None: st.error("Selected language not supported.") return None, None tokenizer = MarianTokenizer.from_pretrained(model_name) model = MarianMTModel.from_pretrained(model_name) return tokenizer, model def translate_text(text, tokenizer, model): inputs = tokenizer(text, return_tensors="pt", padding=True) translated = model.generate(**inputs) translation = tokenizer.decode(translated[0], skip_special_tokens=True) return translation def main(): st.title("Language Translator") st.write("This app translates English text into selected languages using Hugging Face models.") # Select target language target_language = st.selectbox("Select target language", list(LANGUAGE_MODELS.keys())) # Input text input_text = st.text_area("Enter text in English") if st.button("Translate"): if not input_text: st.error("Please enter text to translate.") else: # Load the model and tokenizer for the selected language tokenizer, model = load_model(target_language) if tokenizer and model: # Translate the text translated_text = translate_text(input_text, tokenizer, model) st.subheader("Translated Text") st.write(translated_text) if __name__ == "__main__": main()