AamerAkhter commited on
Commit
8ad5381
·
verified ·
1 Parent(s): 1b23a07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -8
app.py CHANGED
@@ -1,13 +1,13 @@
1
  import gradio as gr
2
  from transformers import MarianMTModel, MarianTokenizer
3
 
4
- # Define model names for each direction
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
- # Cache loaded models
11
  models = {}
12
 
13
  def load_model(direction):
@@ -20,21 +20,22 @@ def load_model(direction):
20
 
21
  def translate(text, direction):
22
  if not text.strip():
23
- return ""
24
  tokenizer, model = load_model(direction)
25
  inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
26
- translated = model.generate(**inputs)
27
- return tokenizer.decode(translated[0], skip_special_tokens=True)
 
28
 
29
  iface = gr.Interface(
30
  fn=translate,
31
  inputs=[
32
- gr.Textbox(label="Enter Text", lines=4),
33
- gr.Radio(["English to Urdu", "Urdu to English"], label="Translation Direction")
34
  ],
35
  outputs=gr.Textbox(label="Translated Text"),
36
  title="English ↔ Urdu Translator",
37
- description="Translate between English and Urdu using pretrained Hugging Face models.",
38
  allow_flagging="never"
39
  )
40
 
 
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):
 
20
 
21
  def translate(text, direction):
22
  if not text.strip():
23
+ return "Please enter some text to translate."
24
  tokenizer, model = load_model(direction)
25
  inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
26
+ outputs = model.generate(**inputs)
27
+ translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
28
+ return translated_text
29
 
30
  iface = gr.Interface(
31
  fn=translate,
32
  inputs=[
33
+ gr.Textbox(label="Enter Text", lines=4, placeholder="Type here..."),
34
+ gr.Radio(["English to Urdu", "Urdu to English"], label="Select Direction")
35
  ],
36
  outputs=gr.Textbox(label="Translated Text"),
37
  title="English ↔ Urdu Translator",
38
+ description="Use this app to translate between English and Urdu using Hugging Face MarianMT models.",
39
  allow_flagging="never"
40
  )
41