import streamlit as st from transformers import MarianMTModel, MarianTokenizer # Define language options LANGUAGES = { "Spanish": "es", "French": "fr", "German": "de", "Italian": "it", "Portuguese": "pt", } # Load translation model and tokenizer model_name = "Helsinki-NLP/opus-mt-en-ROMANCE" tokenizer = MarianTokenizer.from_pretrained(model_name) model = MarianMTModel.from_pretrained(model_name) def translate_text(text, target_language): # Prepare the text for the model translated = tokenizer(text, return_tensors="pt", padding=True, truncation=True) # Perform the translation translated = model.generate(**translated, forced_bos_token_id=tokenizer.lang_code_to_id[target_language]) # Decode and return the translation translated_text = tokenizer.decode(translated[0], skip_special_tokens=True) return translated_text # Streamlit app st.title("Language Translator") # User input text_to_translate = st.text_area("Enter text in English:", "") selected_language = st.selectbox("Select target language:", list(LANGUAGES.keys())) if st.button("Translate"): if text_to_translate: target_language = LANGUAGES[selected_language] translated_text = translate_text(text_to_translate, target_language) st.write(f"Translated text ({selected_language}):") st.write(translated_text) else: st.warning("Please enter text to translate.")