Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
2 |
+
import gradio as gr
|
3 |
+
|
4 |
+
# Load English to Urdu model
|
5 |
+
en_ur_model_name = "Helsinki-NLP/opus-mt-en-ur"
|
6 |
+
en_ur_tokenizer = AutoTokenizer.from_pretrained(en_ur_model_name)
|
7 |
+
en_ur_model = AutoModelForSeq2SeqLM.from_pretrained(en_ur_model_name)
|
8 |
+
|
9 |
+
# Load Urdu to English model
|
10 |
+
ur_en_model_name = "Helsinki-NLP/opus-mt-ur-en"
|
11 |
+
ur_en_tokenizer = AutoTokenizer.from_pretrained(ur_en_model_name)
|
12 |
+
ur_en_model = AutoModelForSeq2SeqLM.from_pretrained(ur_en_model_name)
|
13 |
+
|
14 |
+
# Translation function
|
15 |
+
def translate(text, direction):
|
16 |
+
if not text.strip():
|
17 |
+
return "Please enter some text."
|
18 |
+
|
19 |
+
if direction == "English to Urdu":
|
20 |
+
inputs = en_ur_tokenizer.encode(text, return_tensors="pt")
|
21 |
+
outputs = en_ur_model.generate(inputs, max_length=512, num_beams=4, early_stopping=True)
|
22 |
+
result = en_ur_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
23 |
+
else: # Urdu to English
|
24 |
+
inputs = ur_en_tokenizer.encode(text, return_tensors="pt")
|
25 |
+
outputs = ur_en_model.generate(inputs, max_length=512, num_beams=4, early_stopping=True)
|
26 |
+
result = ur_en_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
27 |
+
|
28 |
+
return result
|
29 |
+
|
30 |
+
# Gradio Interface
|
31 |
+
interface = gr.Interface(
|
32 |
+
fn=translate,
|
33 |
+
inputs=[
|
34 |
+
gr.Textbox(label="Enter text", lines=3),
|
35 |
+
gr.Radio(["English to Urdu", "Urdu to English"], label="Translation Direction")
|
36 |
+
],
|
37 |
+
outputs=gr.Textbox(label="Translated text"),
|
38 |
+
title="English ↔ Urdu Translator",
|
39 |
+
description="Translate between English and Urdu using Helsinki-NLP models"
|
40 |
+
)
|
41 |
+
|
42 |
+
interface.launch()
|