File size: 1,536 Bytes
eab46ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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()