Translate_It / app.py
Jesus Carrasco
Create app.py
3d23272
raw
history blame
1.32 kB
import gradio as gr
from transformers import MarianMTModel, MarianTokenizer
# Define the translator function
def translate_text(text, target_language):
model_name = {
"Spanish": "Helsinki-NLP/opus-mt-en-es",
"French": "Helsinki-NLP/opus-mt-en-fr",
"Italian": "Helsinki-NLP/opus-mt-en-it",
"Ukrainian": "Helsinki-NLP/opus-mt-en-uk",
}
tokenizer = MarianTokenizer.from_pretrained(model_name[target_language])
model = MarianMTModel.from_pretrained(model_name[target_language])
# Tokenize the input text
input_tokens = tokenizer(text, return_tensors="pt")
# Generate translated tokens
translated_tokens = model.generate(**input_tokens)
# Decode the translated tokens
translated_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
return translated_text
# Define the Gradio interface
language_options = ["Spanish", "French", "Italian", "Ukrainian"]
inputs = [
gr.inputs.Textbox(lines=5, label="Enter text to translate:"),
gr.inputs.Dropdown(choices=language_options, label="Select target language:"),
]
outputs = gr.outputs.Textbox(label="Translated text:")
iface = gr.Interface(fn=translate_text, inputs=inputs, outputs=outputs, title="Language Translator")
# Launch the Hugging Face Spaces app
iface.launch()