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
 
 
 
 
 
 
 
2ed41e9
81cbc1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import os
import spaces
import gradio as gr #gr.load("models/NgalNgal/mT5-new").launch()
import torch
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
import sentencepiece as spm
import ctranslate2
import transformers
from nltk import sent_tokenize

# Load the source SentecePiece model
sp = spm.SentencePieceProcessor()


mbart_enmy_ct_model_path = "mbart25enmy_ct2/"
mbart_enmy_sp_model_path = "mbart25enmy_ct2/sentence.bpe.model"

mbart_myen_ct_model_path = "mbart25-myen_ct2/"
mbart_myen_sp_model_path = "mbart25-myen_ct2/sentence.bpe.model"

mt5_ct_model_path = "mt5-ct2/"
mt5_sp_model_path = "mt5-base/"


trans_sp_source_enmy_path = "enmy_ctranslate2/source.model"
trans_sp_target_enmy_path = "enmy_ctranslate2/target.model"

trans_sp_source_myen_path = "myen_ctranslate2/source.model"
trans_sp_target_myen_path = "myen_ctranslate2/target.model"

trans_enmy_ct_model_path = "enmy_ctranslate2/"
trans_myen_ct_model_path = "myen_ctranslate2/"

#translator = ctranslate2.Translator(ct_model_path)
#sp_model = spm.SentencePieceProcessor(sp_model_path)

#!/usr/bin/python

def segment_sentence(source):
    input_file = "input.txt"
    output_file = "output.txt"
    with open(input_file, "w", encoding="utf-8") as file:
        file.write(source)
    os.system("python myseg.py < input.txt > output.txt")



    #segmentation_command = f"python /content/drive/MyDrive/mbart-enmy/myseg.py {input_file} > {output_file}"
    #subprocess.run(segmentation_command, shell=True, check=True)

    with open(output_file, "r", encoding="utf-8") as file:
        segmented_content = file.read()

    #subprocess.run(f"rm /content/drive/MyDrive/input.txt /content/drive/MyDrive/output.txt", shell=True, check=True)
    #segmented_sentence = segmented_content.replace("|", " ")
    print(segmented_content)
    return segmented_content


def write_to_file_myanmar(source):
    input_file = "write-input.txt"
    output_file = "read-output.txt"
    with open(input_file, "w", encoding="utf-8") as file:
        file.write(source)
    
    os.system("python myseg.py < write-input.txt > read-output.txt")



    #segmentation_command = f"python /content/drive/MyDrive/mbart-enmy/myseg.py {input_file} > {output_file}"
    #subprocess.run(segmentation_command, shell=True, check=True)

    with open(output_file, "r", encoding="utf-8") as file:
        segmented_contents = file.read()
    
    #source_sents = [segmented_content.strip() for segmented_content in segmented_contents]
        
    return segmented_contents

def write_to_file_english(source):
    input_file = "write-input.txt"
    #output_file = "read-output.txt"
    with open(input_file, "w", encoding="utf-8") as file:
        file.write(source)
    
    #os.system("python /content/drive/MyDrive/mbart-enmy/myseg.py < /content/drive/MyDrive/write-input.txt > /content/drive/MyDrive/read-output.txt")



    #segmentation_command = f"python /content/drive/MyDrive/mbart-enmy/myseg.py {input_file} > {output_file}"
    #subprocess.run(segmentation_command, shell=True, check=True)

    with open(input_file, "r", encoding="utf-8") as file:
        segmented_contents = file.read()
    
    #source_sents = [segmented_content.strip() for segmented_content in segmented_contents]
        
    return segmented_contents


def call_model_transformer(source, direction_trans):
    if direction_trans == "English to Myanmar":
        ct_model_path = "enmy_ctranslate2/"
        sp_source_model_path = "enmy_ctranslate2/source.model"
        sp_target_model_path = "enmy_ctranslate2/target.model"
        if source == "" :
            gr.Warning("Please Enter English Text")
        else:
            #Set file paths
            source_file_path = "write-input.txt"
            target_file_path = "read-output.txt"
            
            # Load the source SentecePiece model
            sp = spm.SentencePieceProcessor()
            sp.load(sp_source_model_path)

            # write source to file
            with open(source_file_path, "w", encoding="utf-8") as file:
                file.write(source)

            # Open the source file
            with open(source_file_path, "r") as source:
                  lines = source.readlines()

            source_sents = [line.strip() for line in lines]

            # Subword the source sentences
            source_sents_subworded = sp.encode_as_pieces(source_sents)

            # Translate the source sentences
            translator = ctranslate2.Translator(ct_model_path, device="cpu")  # or "cuda" for GPU
            translations = translator.translate_batch(source_sents_subworded, batch_type="tokens", max_batch_size=4096)
            translations = [translation.hypotheses[0] for translation in translations]

            # Load the target SentecePiece model
            sp.load(sp_target_model_path)

            # Desubword the target sentences
            translations_desubword = sp.decode(translations)


            # Save the translations to the a file
            with open(target_file_path, "w+", encoding="utf-8") as target:
                for line in translations_desubword:
                    target.write(line.strip() + "\n")

            #print("Done")
            
            with open(target_file_path, "r", encoding="utf-8") as file:
                segmented_contents = file.read()

     
    elif direction_trans == "Myanmar to English":
        ct_model_path = "myen_ctranslate2/"
        sp_source_model_path = "myen_ctranslate2/source.model"
        sp_target_model_path = "myen_ctranslate2/target.model"
        if sources == "" :
            gr.Warning("Please Enter Myanmar Text")
        else:
            #Set file paths
            source_file_path = "write-input.txt"
            target_file_path = "read-output.txt"
            
            # Load the source SentecePiece model
            sp = spm.SentencePieceProcessor()
            sp.load(sp_source_model_path)

            # write source to file
            with open(source_file_path, "w", encoding="utf-8") as file:
                file.write(source)

            # Open the source file
            with open(source_file_path, "r") as source:
                  lines = source.readlines()

            source_sents = [line.strip() for line in lines]

            # Subword the source sentences
            source_sents_subworded = sp.encode_as_pieces(source_sents)

            # Translate the source sentences
            translator = ctranslate2.Translator(ct_model_path, device="cpu")  # or "cuda" for GPU
            translations = translator.translate_batch(source_sents_subworded, batch_type="tokens", max_batch_size=4096)
            translations = [translation.hypotheses[0] for translation in translations]

            # Load the target SentecePiece model
            sp.load(sp_target_model_path)

            # Desubword the target sentences
            translations_desubword = sp.decode(translations)


            # Save the translations to the a file
            with open(target_file_path, "w+", encoding="utf-8") as target:
                for line in translations_desubword:
                    target.write(line.strip() + "\n")

            #print("Done")
            
            with open(target_file_path, "r", encoding="utf-8") as file:
                segmented_contents = file.read()


    else: gr.Warning("Please Select Language Direction")
  
  
    return segmented_contents


def translate_trans_myen(source, translator, sp_source_model, sp_target_model):
    """Use CTranslate model to translate a sentence
    Args:
        source (str): Source sentences to translate
        translator (object): Object of Translator, with the CTranslate2 model
        tokenizer (object): Object of SentencePieceProcessor, with the SentencePiece source model
    Returns:
        Translation of the source text
    """
    source = segment_sentence(source)
    source_sentences = sent_tokenize(source)  # split sentences
    source_tokenized = sp_source_model.encode(source_sentences, out_type=str)
    translations = translator.translate_batch(source_tokenized, replace_unknowns=True)
    translations = [translation[0]["tokens"] for translation in translations]
    translations = sp_target_model.decode(translations)

    return translations

def translate_trans_enmy(source, translator, sp_source_model, sp_target_model):
    """Use CTranslate model to translate a sentence
    Args:
        source (str): Source sentences to translate
        translator (object): Object of Translator, with the CTranslate2 model
        tokenizer (object): Object of SentencePieceProcessor, with the SentencePiece source model
    Returns:
        Translation of the source text
    """
    source_sentences = sent_tokenize(source)  # split sentences
    source_tokenized = sp_source_model.encode(source_sentences, out_type=str)
    translations = translator.translate_batch(source_tokenized, replace_unknowns=True)
    translations = [translation[0]["tokens"] for translation in translations]
    translations_detokenized = sp_target_model.decode(translations)

    return translations_detokenized
def translate_mt5_myen(source, translator, tokenizer):
    """Use CTranslate model to translate a sentence
    Args:
        source (str): Source sentences to translate
        translator (object): Object of Translator, with the CTranslate2 model
        tokenizer (object): Object of SentencePieceProcessor, with the SentencePiece source model
    Returns:
        Translation of the source text
    """
    source = segment_sentence(source)
    input_tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(source))
    results = translator.translate_batch([input_tokens])
    output_tokens = results[0].hypotheses[0]
    translations = tokenizer.decode(tokenizer.convert_tokens_to_ids(output_tokens))
    return translations

def call_model_mt5(source, direction_mt5):
    if direction_mt5 == "English to Myanmar":
        translator = ctranslate2.Translator(mt5_ct_model_path)
        tokenizer = transformers.AutoTokenizer.from_pretrained(mt5_sp_model_path)
        if source == "" :
            gr.Warning("Please Enter English Text")
        else:
            translation = translate_mt5_enmy(source, translator, tokenizer)
    elif direction_mt5 == "Myanmar to English":
        translator = ctranslate2.Translator(mt5_ct_model_path)
        tokenizer = transformers.AutoTokenizer.from_pretrained(mt5_sp_model_path)
        if source == "" :
            gr.Warning("Please Enter Myanmar Text")
        else:
            translation = translate_mt5_myen(source, translator, tokenizer)
    else: gr.Warning("Please Select Language Direction")
    return translation

def translate_mt5_enmy(source, translator, tokenizer):
    """Use CTranslate model to translate a sentence
    Args:
        source (str): Source sentences to translate
        translator (object): Object of Translator, with the CTranslate2 model
        tokenizer (object): Object of SentencePieceProcessor, with the SentencePiece source model
    Returns:
        Translation of the source text
    """
    input_tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(source))
    results = translator.translate_batch([input_tokens])
    output_tokens = results[0].hypotheses[0]
    translations = tokenizer.decode(tokenizer.convert_tokens_to_ids(output_tokens))
    return translations

def translate_mbart_myen(source, translator, sp_model):
    """Use CTranslate model to translate a sentence
    Args:
        source (str): Source sentences to translate
        translator (object): Object of Translator, with the CTranslate2 model
        sp_model (object): Object of SentencePieceProcessor, with the SentencePiece source model
    Returns:
        Translation of the source text
    """
    source = segment_sentence(source)
#    source_sentences = sent_tokenize(source)
    source_tokenized = sp_model.encode(source, out_type=str)
#    print("print 1" , source_tokenized)
    source_tokenized = ["[my_MM]"] + source_tokenized
#    print("print " + source_tokenized)
    target_prefix = ["[en_XX]"]
    translations = translator.translate_batch([source_tokenized],target_prefix= [target_prefix])
#    translations = [translation[0]["tokens"] for translation in translations]
    translations = sp_model.decode(translations[0].hypotheses[0][1:])
#    translation = " ".join(translations_detokenized)

    return translations

def translate_mbart_enmy(source, translator, sp_model):
    """Use CTranslate model to translate a sentence
    Args:
        source (str): Source sentences to translate
        translator (object): Object of Translator, with the CTranslate2 model
        sp_model (object): Object of SentencePieceProcessor, with the SentencePiece source model
    Returns:
        Translation of the source text
    """

#    source_sentences = sent_tokenize(source)
    source_tokenized = sp_model.encode(source, out_type=str)
#    print("print 1" , source_tokenized)
    source_tokenized = ["[en_XX]"] + source_tokenized
#    print("print " + source_tokenized)
    target_prefix = ["[my_MM]"]
    translations = translator.translate_batch([source_tokenized],target_prefix= [target_prefix])
#    translations = [translation[0]["tokens"] for translation in translations]
    translations = sp_model.decode(translations[0].hypotheses[0][1:])
#    translation = " ".join(translations_detokenized)

    return translations

def call_model(source, direction):
  if direction == "English to Myanmar":
    translator = ctranslate2.Translator(mbart_enmy_ct_model_path)
    sp_model = spm.SentencePieceProcessor(mbart_enmy_sp_model_path)
    if source == "" :
      gr.Warning("Please Enter English Text")
    else:
      translation = translate_mbart_enmy(source, translator, sp_model)
  elif direction == "Myanmar to English":
    translator = ctranslate2.Translator(mbart_myen_ct_model_path)
    sp_model = spm.SentencePieceProcessor(mbart_myen_sp_model_path)
    if source == "" :
      gr.Warning("Please Enter Myanmar Text")
    else:
      translation = translate_mbart_myen(source, translator, sp_model)
  else: gr.Warning("Please Select Language Direction")
  return translation

css = """
#warning {background-color: #FFCCCB}
.feedback textarea {font-size: 24px !important}
#text_button1 {background: gray;}
.translate {font-size: 5px !important;}
.translate {width: 150px !important;}
#img .img {width: 30px; height: 400px;}
#img1
input, textarea, select {font-weight: bold; color:blue !important;}
.tab button.selected{
    font-size: 36px !important;
    font-weight: bold;
    color:blue !important;
}
"""
def clear_mbart():
    return "", ""

def clear_mm_to_wa():
    return "", "", "", ""
import base64

theme = 'gstaff/whiteboard'

demo = gr.Blocks(css=css, theme=gr.themes.Soft(), title="Machine Translation between Myanmar and English Translator")

with open("logo.png", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read()).decode()
width, height = 80, 80

html_content = f'<img src="data:image/x-icon;base64,{encoded_string}" alt="NLP Logo" align="left" width="{width}" height="{height}"/>'

with demo:

    with gr.Row(equal_height=True):
        with gr.Column(scale=1, min_width=150):
            gr.HTML(html_content)
        with gr.Column(scale=25, min_width=150):
            gr.Markdown("<div style='text-align: center;font-weight: bold;font-size: 32px; color:blue'>Transformer-based Neural Machine Traslation between Myanmar and English Languages Translator</div>")
        with gr.Column(scale=1, min_width=150):
            gr.HTML("<img src='https://www.ucsy.edu.mm/img/ucsylogo.png' alt='UCSY Logo' width='100' height='100' align='right'/>")

####################
    with gr.Tabs(elem_classes=["tab"]): #elem_classes=["tab"]

        with gr.TabItem("Proposed Transformer"):
            with gr.Row():
              direction_trans = gr.Dropdown(["English to Myanmar", "Myanmar to English"] ,label="Select Direction")

            with gr.Row():
              with gr.Column():
                input_to_translate_trans = gr.Textbox("", label="Enter Input Text", lines=5)

                #english = gr.Textbox(label="English text")

                translate_btn = gr.Button(value="Translate")

              with gr.Column():
                translated_text_trans = gr.Textbox(value="", label="Translated Text", lines=5)
                gr.ClearButton([input_to_translate_trans,translated_text_trans])
                #clear_button2 = gr.Button(value="Clear")
                #myanmar = gr.Textbox(label="Myanmar Text")
              #with gr.Row():
                #clear_button2 = gr.Button(value="Clear", elem_id="clear_button2", elem_classes="translate")
            examples = gr.Examples(examples=["I went to the supermarket yesterday.", "α€…α€¬α€žα€„α€Ία€α€”α€Ία€Έα€‘α€²α€™α€Ύα€¬α€€α€½α€”α€Ία€•α€»α€°α€α€¬α€‘α€žα€…α€Ία€α€…α€Ία€œα€―α€Άα€Έα€›α€Ύα€­α€α€šα€Ία‹"],
                           inputs=[input_to_translate_trans])
    translate_btn.click(call_model_transformer, inputs=[input_to_translate_trans,direction_trans], outputs=translated_text_trans, api_name="English-to-Myanmar")
##################



###########################################################
    with gr.Tabs(elem_classes=["tab"]): #elem_classes=["tab"]

        with gr.TabItem("Fine-Tuned MBART"):
            with gr.Row():
              direction = gr.Dropdown(["English to Myanmar", "Myanmar to English"] ,label="Select Direction")

            with gr.Row():
              with gr.Column():
                input_to_translate = gr.Textbox("", label="Enter Input Text", lines=5)

                #english = gr.Textbox(label="English text")

                translate_btn = gr.Button(value="Translate")

              with gr.Column():
                translated_text = gr.Textbox(value="", label="Translated Text", lines=5)
                gr.ClearButton([input_to_translate,translated_text])
                #clear_button2 = gr.Button(value="Clear")
                #myanmar = gr.Textbox(label="Myanmar Text")
              #with gr.Row():
                #clear_button2 = gr.Button(value="Clear", elem_id="clear_button2", elem_classes="translate")
            examples = gr.Examples(examples=["I went to the supermarket yesterday.", "α€…α€¬α€žα€„α€Ία€α€”α€Ία€Έα€‘α€²α€™α€Ύα€¬α€€α€½α€”α€Ία€•α€»α€°α€α€¬α€‘α€žα€…α€Ία€α€…α€Ία€œα€―α€Άα€Έα€›α€Ύα€­α€α€šα€Ία‹"],
                           inputs=[input_to_translate])
    translate_btn.click(call_model, inputs=[input_to_translate,direction], outputs=translated_text, api_name="English-to-Myanmar")

    #text_button2.click(translate_interface, inputs=[input_to_translate, model_choice], outputs=[segmented_text, translated_text_pivot, translated_text_combined])

    #clear_button2.click(outputs=[input_to_translate,translated_text])
##########################
####################
    with gr.Tabs(elem_classes=["tab"]): #elem_classes=["tab"]

        with gr.TabItem("Fine-Tuned MT5"):
            with gr.Row():
              direction_mt5 = gr.Dropdown(["English to Myanmar", "Myanmar to English"] ,label="Select Direction")

            with gr.Row():
              with gr.Column():
                input_to_translate_mt5 = gr.Textbox("", label="Enter Input Text", lines=5)

                #english = gr.Textbox(label="English text")

                translate_btn = gr.Button(value="Translate")

              with gr.Column():
                translated_text_mt5 = gr.Textbox(value="", label="Translated Text", lines=5)
                gr.ClearButton([input_to_translate_mt5,translated_text_mt5])
                #clear_button2 = gr.Button(value="Clear")
                #myanmar = gr.Textbox(label="Myanmar Text")
              #with gr.Row():
                #clear_button2 = gr.Button(value="Clear", elem_id="clear_button2", elem_classes="translate")
            examples = gr.Examples(examples=["I went to the supermarket yesterday.", "α€…α€¬α€žα€„α€Ία€α€”α€Ία€Έα€‘α€²α€™α€Ύα€¬α€€α€½α€”α€Ία€•α€»α€°α€α€¬α€‘α€žα€…α€Ία€α€…α€Ία€œα€―α€Άα€Έα€›α€Ύα€­α€α€šα€Ία‹"],
                           inputs=[input_to_translate_mt5])
    translate_btn.click(call_model_mt5, inputs=[input_to_translate_mt5, direction_mt5], outputs=translated_text_mt5, api_name="English-to-Myanmar")
##################
demo.launch()