Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import MarianMTModel, MarianTokenizer
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# Model names
|
| 6 |
+
en_ur_model_name = "Helsinki-NLP/opus-mt-en-ur"
|
| 7 |
+
ur_en_model_name = "Helsinki-NLP/opus-mt-ur-en"
|
| 8 |
+
|
| 9 |
+
# Load English to Urdu model
|
| 10 |
+
en_ur_tokenizer = MarianTokenizer.from_pretrained(en_ur_model_name)
|
| 11 |
+
en_ur_model = MarianMTModel.from_pretrained(en_ur_model_name)
|
| 12 |
+
|
| 13 |
+
# Load Urdu to English model
|
| 14 |
+
ur_en_tokenizer = MarianTokenizer.from_pretrained(ur_en_model_name)
|
| 15 |
+
ur_en_model = MarianMTModel.from_pretrained(ur_en_model_name)
|
| 16 |
+
|
| 17 |
+
# Translation Function
|
| 18 |
+
def translate(text, direction):
|
| 19 |
+
if not text.strip():
|
| 20 |
+
return "Please enter some text."
|
| 21 |
+
|
| 22 |
+
if direction == "English to Urdu":
|
| 23 |
+
tokenizer, model = en_ur_tokenizer, en_ur_model
|
| 24 |
+
else:
|
| 25 |
+
tokenizer, model = ur_en_tokenizer, ur_en_model
|
| 26 |
+
|
| 27 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
| 28 |
+
with torch.no_grad():
|
| 29 |
+
translated = model.generate(**inputs)
|
| 30 |
+
output = tokenizer.decode(translated[0], skip_special_tokens=True)
|
| 31 |
+
return output
|
| 32 |
+
|
| 33 |
+
# Gradio Interface
|
| 34 |
+
iface = gr.Interface(
|
| 35 |
+
fn=translate,
|
| 36 |
+
inputs=[
|
| 37 |
+
gr.Textbox(label="Enter Text", lines=4, placeholder="Type your sentence here..."),
|
| 38 |
+
gr.Radio(["English to Urdu", "Urdu to English"], label="Select Translation Direction")
|
| 39 |
+
],
|
| 40 |
+
outputs=gr.Textbox(label="Translated Text"),
|
| 41 |
+
title="English ↔ Urdu Translator",
|
| 42 |
+
description="Translate text between English and Urdu using Hugging Face MarianMT models."
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
iface.launch(share=True) # Use share=True for Colab public link
|