File size: 1,429 Bytes
56b97c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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.")