|
|
|
try: |
|
from transformers import MarianMTModel, MarianTokenizer |
|
print("Transformers imported successfully") |
|
except ImportError as e: |
|
print(f"ImportError: {e}") |
|
|
|
import streamlit as st |
|
|
|
|
|
try: |
|
from transformers import MarianMTModel, MarianTokenizer |
|
except ImportError as e: |
|
st.error("Failed to import transformers. Please make sure it is installed.") |
|
st.stop() |
|
|
|
|
|
def load_model_and_tokenizer(target_lang): |
|
model_name = f'Helsinki-NLP/opus-mt-en-{target_lang}' |
|
model = MarianMTModel.from_pretrained(model_name) |
|
tokenizer = MarianTokenizer.from_pretrained(model_name) |
|
return model, tokenizer |
|
|
|
|
|
def translate_text(text, model, tokenizer): |
|
tokens = tokenizer(text, return_tensors="pt", padding=True) |
|
translated_tokens = model.generate(**tokens) |
|
translated_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True) |
|
return translated_text |
|
|
|
|
|
st.title("Language Translator") |
|
|
|
|
|
input_text = st.text_area("Enter text to translate", "Hello, how are you?") |
|
|
|
|
|
target_language = st.selectbox( |
|
"Select target language", |
|
["fr", "de", "es", "it", "pt", "ru", "zh", "ja", "ar"] |
|
) |
|
|
|
|
|
if target_language: |
|
model, tokenizer = load_model_and_tokenizer(target_language) |
|
|
|
if st.button("Translate"): |
|
if input_text: |
|
translated_text = translate_text(input_text, model, tokenizer) |
|
st.subheader("Translated text") |
|
st.write(translated_text) |
|
else: |
|
st.error("Please enter some text to translate.") |
|
|