File size: 1,722 Bytes
637ccb3
68021a2
 
 
 
 
 
ce1f204
68021a2
 
 
 
 
 
 
ce1f204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
44
45
46
47
48
49
50
51
52
53
54

try:
    from transformers import MarianMTModel, MarianTokenizer
    print("Transformers imported successfully")
except ImportError as e:
    print(f"ImportError: {e}")

import streamlit as st

# Attempt to import the transformers package
try:
    from transformers import MarianMTModel, MarianTokenizer
except ImportError as e:
    st.error("Failed to import transformers. Please make sure it is installed.")
    st.stop()

# Initialize the model and tokenizer
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

# Function to translate text
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

# Streamlit app
st.title("Language Translator")

# Input text
input_text = st.text_area("Enter text to translate", "Hello, how are you?")

# Language selection
target_language = st.selectbox(
    "Select target language",
    ["fr", "de", "es", "it", "pt", "ru", "zh", "ja", "ar"]
)

# Load model and tokenizer based on selected language
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.")