Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,34 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import MarianMTModel, MarianTokenizer
|
| 3 |
|
| 4 |
-
# Define model names
|
| 5 |
model_names = {
|
| 6 |
"English to Urdu": "Helsinki-NLP/opus-mt-en-ur",
|
| 7 |
"Urdu to English": "Helsinki-NLP/opus-mt-ur-en"
|
| 8 |
}
|
| 9 |
|
| 10 |
-
# Load models only once
|
| 11 |
models = {}
|
| 12 |
|
| 13 |
def load_model(direction):
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
models[direction] = (tokenizer, model)
|
| 19 |
-
return models[direction]
|
| 20 |
|
| 21 |
def translate(text, direction):
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
|
| 30 |
iface = gr.Interface(
|
| 31 |
fn=translate,
|
| 32 |
inputs=[
|
| 33 |
-
gr.Textbox(label="Enter Text", lines=4
|
| 34 |
gr.Radio(["English to Urdu", "Urdu to English"], label="Select Direction")
|
| 35 |
],
|
| 36 |
outputs=gr.Textbox(label="Translated Text"),
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import MarianMTModel, MarianTokenizer
|
| 3 |
|
|
|
|
| 4 |
model_names = {
|
| 5 |
"English to Urdu": "Helsinki-NLP/opus-mt-en-ur",
|
| 6 |
"Urdu to English": "Helsinki-NLP/opus-mt-ur-en"
|
| 7 |
}
|
| 8 |
|
|
|
|
| 9 |
models = {}
|
| 10 |
|
| 11 |
def load_model(direction):
|
| 12 |
+
model_name = model_names[direction]
|
| 13 |
+
tokenizer = MarianTokenizer.from_pretrained(model_name)
|
| 14 |
+
model = MarianMTModel.from_pretrained(model_name)
|
| 15 |
+
return tokenizer, model
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def translate(text, direction):
|
| 18 |
+
try:
|
| 19 |
+
if not text.strip():
|
| 20 |
+
return "Please enter text to translate."
|
| 21 |
+
tokenizer, model = load_model(direction)
|
| 22 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
| 23 |
+
output = model.generate(**inputs)
|
| 24 |
+
return tokenizer.decode(output[0], skip_special_tokens=True)
|
| 25 |
+
except Exception as e:
|
| 26 |
+
return f"Error: {str(e)}"
|
| 27 |
|
| 28 |
iface = gr.Interface(
|
| 29 |
fn=translate,
|
| 30 |
inputs=[
|
| 31 |
+
gr.Textbox(label="Enter Text", lines=4),
|
| 32 |
gr.Radio(["English to Urdu", "Urdu to English"], label="Select Direction")
|
| 33 |
],
|
| 34 |
outputs=gr.Textbox(label="Translated Text"),
|