qasimgill's picture
Create app.py
eab46ad verified
# app.py
from transformers import MarianMTModel, MarianTokenizer
import gradio as gr
# Load the pre-trained model and tokenizer
model_name = "Helsinki-NLP/opus-mt-en-ur"
tokenizer = MarianTokenizer.from_pretrained(model_name)
model = MarianMTModel.from_pretrained(model_name)
# Define the translation function
def translate_english_to_urdu(text):
# Tokenize the input text
tokenized_text = tokenizer.prepare_seq2seq_batch([text], return_tensors="pt")
# Perform the translation
translated_tokens = model.generate(**tokenized_text)
# Decode the translated tokens to a string
translated_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
return translated_text
# Create a Gradio interface
def gradio_translator(input_text):
# Translate the input text
translated_text = translate_english_to_urdu(input_text)
return translated_text
# Define the Gradio interface
interface = gr.Interface(
fn=gradio_translator, # Function to call
inputs=gr.Textbox(lines=2, placeholder="Enter English text here..."), # Input component
outputs=gr.Textbox(lines=2, placeholder="Urdu translation will appear here..."), # Output component
title="English to Urdu Translator", # Title of the interface
description="Translate English text to Urdu using the Helsinki-NLP/opus-mt-en-ur model.",
examples=[
["Hello, how are you?"],
["What is your name?"],
["I love programming."]
]
)
# Launch the Gradio interface
interface.launch()