File size: 1,515 Bytes
aa46d6f
16d3fb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc6ab81
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
# Install necessary libraries (run this once)!pip install transformers gradio

# Now import them
from transformers import MarianMTModel, MarianTokenizer
import gradio as gr

# Define the models
models = {
    "English to Urdu": {
        "model_name": "Helsinki-NLP/opus-mt-en-ur"
    },
    "Urdu to English": {
        "model_name": "Helsinki-NLP/opus-mt-ur-en"
    }
}

# Load models and tokenizers
loaded_models = {}
for direction, info in models.items():
    tokenizer = MarianTokenizer.from_pretrained(info["model_name"])
    model = MarianMTModel.from_pretrained(info["model_name"])
    loaded_models[direction] = (tokenizer, model)

# Define the translation function
def translate_text(text, direction):
    tokenizer, model = loaded_models[direction]
    inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
    translated = model.generate(**inputs, max_length=512)
    output = tokenizer.decode(translated[0], skip_special_tokens=True)
    return output

# Create Gradio Interface
iface = gr.Interface(
    fn=translate_text,
    inputs=[
        gr.Textbox(label="Enter text here", placeholder="Type your English or Urdu text..."),
        gr.Radio(["English to Urdu", "Urdu to English"], label="Select translation direction")
    ],
    outputs=gr.Textbox(label="Translated Text"),
    title="🌍 English ↔ Urdu Translator",
    description="Translate text between English and Urdu using Hugging Face pretrained models.",
    theme="default"
)

# Launch the app
iface.launch()