amasood commited on
Commit
4578245
·
verified ·
1 Parent(s): 4e78f32

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -0
app.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import MarianMTModel, MarianTokenizer
3
+
4
+ # Load the pre-trained model and tokenizer for English-to-Urdu translation
5
+ model_name = 'Helsinki-NLP/opus-mt-en-ur'
6
+ model = MarianMTModel.from_pretrained(model_name)
7
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
8
+
9
+ # Function to translate English text to Urdu
10
+ def translate_to_urdu(text, chunk_size=500):
11
+ # Split the text into chunks to handle long sentences
12
+ words = text.split()
13
+ chunks = [' '.join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size)]
14
+
15
+ translated_text = []
16
+
17
+ for chunk in chunks:
18
+ # Tokenize the chunk and translate it
19
+ translated = tokenizer.encode(chunk, return_tensors="pt", padding=True, truncation=True, max_length=512)
20
+ chunk_translation = model.generate(translated, max_length=512, num_beams=4, early_stopping=True)
21
+
22
+ # Decode and add the translated chunk to the result
23
+ translated_chunk = tokenizer.decode(chunk_translation[0], skip_special_tokens=True)
24
+ translated_text.append(translated_chunk)
25
+
26
+ # Join all translated chunks into one complete translation
27
+ return ' '.join(translated_text)
28
+
29
+ # Gradio interface
30
+ def gradio_interface(english_text):
31
+ return translate_to_urdu(english_text)
32
+
33
+ # Create the Gradio interface with input and output textboxes
34
+ iface = gr.Interface(
35
+ fn=gradio_interface, # Function that handles translation
36
+ inputs=gr.Textbox(label="English Text", placeholder="Type English text here..."),
37
+ outputs=gr.Textbox(label="Urdu Translation", placeholder="Translated Urdu text will appear here...", interactive=False),
38
+ title="English to Urdu Translation",
39
+ description="Enter English text and get the translation in Urdu. Long texts will be split into chunks for translation.",
40
+ )
41
+
42
+ # Launch the app
43
+ iface.launch()