Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Install necessary libraries (run this once)
|
2 |
+
!pip install transformers gradio
|
3 |
+
|
4 |
+
# Now import them
|
5 |
+
from transformers import MarianMTModel, MarianTokenizer
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
# Define the models
|
9 |
+
models = {
|
10 |
+
"English to Urdu": {
|
11 |
+
"model_name": "Helsinki-NLP/opus-mt-en-ur"
|
12 |
+
},
|
13 |
+
"Urdu to English": {
|
14 |
+
"model_name": "Helsinki-NLP/opus-mt-ur-en"
|
15 |
+
}
|
16 |
+
}
|
17 |
+
|
18 |
+
# Load models and tokenizers
|
19 |
+
loaded_models = {}
|
20 |
+
for direction, info in models.items():
|
21 |
+
tokenizer = MarianTokenizer.from_pretrained(info["model_name"])
|
22 |
+
model = MarianMTModel.from_pretrained(info["model_name"])
|
23 |
+
loaded_models[direction] = (tokenizer, model)
|
24 |
+
|
25 |
+
# Define the translation function
|
26 |
+
def translate_text(text, direction):
|
27 |
+
tokenizer, model = loaded_models[direction]
|
28 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
29 |
+
translated = model.generate(**inputs, max_length=512)
|
30 |
+
output = tokenizer.decode(translated[0], skip_special_tokens=True)
|
31 |
+
return output
|
32 |
+
|
33 |
+
# Create Gradio Interface
|
34 |
+
iface = gr.Interface(
|
35 |
+
fn=translate_text,
|
36 |
+
inputs=[
|
37 |
+
gr.Textbox(label="Enter text here", placeholder="Type your English or Urdu text..."),
|
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 pretrained models.",
|
43 |
+
theme="default"
|
44 |
+
)
|
45 |
+
|
46 |
+
# Launch the app
|
47 |
+
iface.launch()
|