Spaces:
Sleeping
Sleeping
File size: 1,953 Bytes
7715eaa 8b57ddb |
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 |
import streamlit as st
from transformers import MarianMTModel, MarianTokenizer
# Function to load model and tokenizer
@st.cache_resource
def load_model_and_tokenizer(model_name):
tokenizer = MarianTokenizer.from_pretrained(model_name)
model = MarianMTModel.from_pretrained(model_name)
return tokenizer, model
# Function to perform translation
def translate_text(text, tokenizer, model):
tokenized_text = tokenizer.prepare_seq2seq_batch([text], return_tensors="pt", padding=True)
translated_tokens = model.generate(**tokenized_text)
translated_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
return translated_text
# Available language pairs (from Helsinki-NLP models)
language_pairs = {
"English to French": "Helsinki-NLP/opus-mt-en-fr",
"French to English": "Helsinki-NLP/opus-mt-fr-en",
"English to German": "Helsinki-NLP/opus-mt-en-de",
"German to English": "Helsinki-NLP/opus-mt-de-en",
"English to Spanish": "Helsinki-NLP/opus-mt-en-es",
"Spanish to English": "Helsinki-NLP/opus-mt-es-en",
# Add more pairs as needed
}
# Streamlit App
st.title("Language Translation App")
st.write("Translate text between multiple languages using open-source models.")
# User selects language pair
language_pair = st.selectbox("Select Language Pair:", list(language_pairs.keys()))
model_name = language_pairs[language_pair]
# Load model and tokenizer
with st.spinner("Loading translation model..."):
tokenizer, model = load_model_and_tokenizer(model_name)
# Input text
input_text = st.text_area("Enter text to translate:")
if st.button("Translate"):
if input_text.strip():
with st.spinner("Translating..."):
translated_text = translate_text(input_text, tokenizer, model)
st.success("Translation complete!")
st.text_area("Translated Text:", translated_text, height=200)
else:
st.warning("Please enter text to translate.")
|