Spaces:
Running
Running
Create app.py
Browse files
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)
|