File size: 1,959 Bytes
b3fa491
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bced140
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
55
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()
pip install streamlit transformers torch