Waqas0327 commited on
Commit
68271ac
Β·
verified Β·
1 Parent(s): 6142fd8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -0
app.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # βœ… Step 1: Install required libraries
2
+ !pip install transformers gradio --quiet
3
+
4
+ # βœ… Step 2: Import required modules
5
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
6
+ import gradio as gr
7
+
8
+ # βœ… Step 3: Load model and tokenizer (Multilingual translation model)
9
+ model_name = "Helsinki-NLP/opus-mt-en-ur"
10
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
11
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
12
+
13
+ # βœ… Step 4: Translation pipeline
14
+ translator = pipeline("translation", model=model, tokenizer=tokenizer)
15
+
16
+ # βœ… Step 5: Translation function
17
+ def translate_text(text):
18
+ # Detect Urdu using Unicode range
19
+ contains_urdu = any('\u0600' <= ch <= '\u06FF' for ch in text)
20
+
21
+ if contains_urdu:
22
+ # Urdu to English
23
+ ur_to_en_model = "Helsinki-NLP/opus-mt-ur-en"
24
+ tokenizer_ur_en = AutoTokenizer.from_pretrained(ur_to_en_model)
25
+ model_ur_en = AutoModelForSeq2SeqLM.from_pretrained(ur_to_en_model)
26
+ ur_to_en_translator = pipeline("translation", model=model_ur_en, tokenizer=tokenizer_ur_en)
27
+ result = ur_to_en_translator(text, max_length=100)
28
+ direction = "Urdu β†’ English"
29
+ else:
30
+ # English to Urdu
31
+ result = translator(text, max_length=100)
32
+ direction = "English β†’ Urdu"
33
+
34
+ return f"πŸ” Translation ({direction}):\n\n" + result[0]['translation_text']
35
+
36
+ # βœ… Step 6: Gradio UI
37
+ with gr.Blocks() as demo:
38
+ gr.Markdown("## 🌐 English ↔ Urdu Translator\nUsing Hugging Face models")
39
+ input_text = gr.Textbox(label="Enter text (English or Urdu)", placeholder="Type something...")
40
+ output_text = gr.Textbox(label="Translated Text", interactive=False)
41
+ translate_btn = gr.Button("Translate")
42
+
43
+ translate_btn.click(fn=translate_text, inputs=input_text, outputs=output_text)
44
+
45
+ # βœ… Step 7: Launch in Colab
46
+ demo.launch(share=True)