|
import streamlit as st |
|
from transformers import MarianMTModel, MarianTokenizer |
|
|
|
|
|
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", |
|
|
|
} |
|
|
|
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.") |
|
|
|
|
|
target_language = st.selectbox("Select target language", list(LANGUAGE_MODELS.keys())) |
|
|
|
|
|
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: |
|
|
|
tokenizer, model = load_model(target_language) |
|
if tokenizer and model: |
|
|
|
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 |
|
|