EN to MS Noisy HuggingFace#

This tutorial is available as an IPython notebook at Malaya/example/noisy-en-ms-translation-huggingface.

This module trained on standard language and augmented local language structures, proceed with caution.

[1]:
%%time

import malaya
import logging

logging.basicConfig(level=logging.INFO)
CPU times: user 3.9 s, sys: 3.52 s, total: 7.42 s
Wall time: 3.17 s

List available HuggingFace models#

[2]:
malaya.translation.en_ms.available_huggingface()
INFO:malaya.translation.en_ms:tested on FLORES200 EN-MS (eng_Latn-zsm_Latn) pair `dev` set, https://github.com/facebookresearch/flores/tree/main/flores200
INFO:malaya.translation.en_ms:for noisy, tested on noisy twitter google translation, https://huggingface.co/datasets/mesolitica/augmentation-test-set
[2]:
Size (MB) BLEU SacreBLEU Verbose SacreBLEU-chrF++-FLORES200 Suggested length
mesolitica/finetune-translation-t5-tiny-standard-bahasa-cased-v2 139 41.625536 73.4/50.1/35.7/25.7 (BP = 0.971 ratio = 0.972 ... 65.7 256
mesolitica/finetune-translation-t5-small-standard-bahasa-cased-v2 242 43.937298 74.9/52.2/37.9/27.7 (BP = 0.976 ratio = 0.977 ... 67.43 256
mesolitica/finetune-translation-t5-base-standard-bahasa-cased-v2 892 44.173559 74.7/52.3/38.0/28.0 (BP = 0.979 ratio = 0.979 ... 67.6 256
mesolitica/finetune-noisy-translation-t5-tiny-bahasa-cased-v3 139 60.000967 77.9/63.9/54.6/47.7 (BP = 1.000 ratio = 1.036 ... None 256
mesolitica/finetune-noisy-translation-t5-small-bahasa-cased-v3 242 64.062582 80.1/67.7/59.1/52.5 (BP = 1.000 ratio = 1.042 ... None 256
mesolitica/finetune-noisy-translation-t5-base-bahasa-cased-v2 892 64.583819 80.2/68.1/59.8/53.2 (BP = 1.000 ratio = 1.048 ... None 256

Load Transformer models#

def huggingface(
    model: str = 'mesolitica/finetune-translation-t5-small-standard-bahasa-cased',
    force_check: bool = True,
    **kwargs,
):
    """
    Load HuggingFace model to translate EN-to-MS.

    Parameters
    ----------
    model: str, optional (default='mesolitica/finetune-translation-t5-small-standard-bahasa-cased')
        Check available models at `malaya.translation.en_ms.available_huggingface()`.
    force_check: bool, optional (default=True)
        Force check model one of malaya model.
        Set to False if you have your own huggingface model.

    Returns
    -------
    result: malaya.torch_model.huggingface.Generator
    """
[3]:
transformer = malaya.translation.en_ms.huggingface()
[17]:
transformer_noisy = malaya.translation.en_ms.huggingface(model = 'mesolitica/finetune-noisy-translation-t5-small-bahasa-cased-v3')

Translate#

def generate(self, strings: List[str], **kwargs):
    """
    Generate texts from the input.

    Parameters
    ----------
    strings : List[str]
    **kwargs: vector arguments pass to huggingface `generate` method.

    Returns
    -------
    result: List[str]
    """

For better results, always split by end of sentences.

[5]:
from pprint import pprint
[6]:
# https://www.malaymail.com/news/malaysia/2020/07/01/dr-mahathir-again-claims-anwar-lacks-popularity-with-malays-to-be-pakatans/1880420

string_news1 = 'KUALA LUMPUR, July 1 - Datuk Seri Anwar Ibrahim is not suitable to as the prime minister candidate as he is allegedly not "popular" among the Malays, Tun Dr Mahathir Mohamad claimed. The former prime minister reportedly said the PKR president needs someone like himself in order to acquire support from the Malays and win the election.'
pprint(string_news1)
('KUALA LUMPUR, July 1 - Datuk Seri Anwar Ibrahim is not suitable to as the '
 'prime minister candidate as he is allegedly not "popular" among the Malays, '
 'Tun Dr Mahathir Mohamad claimed. The former prime minister reportedly said '
 'the PKR president needs someone like himself in order to acquire support '
 'from the Malays and win the election.')
[7]:
# https://edition.cnn.com/2020/07/06/politics/new-york-attorney-general-blm/index.html

string_news2 = '(CNN)New York Attorney General Letitia James on Monday ordered the Black Lives Matter Foundation -- which she said is not affiliated with the larger Black Lives Matter movement -- to stop collecting donations in New York. "I ordered the Black Lives Matter Foundation to stop illegally accepting donations that were intended for the #BlackLivesMatter movement. This foundation is not affiliated with the movement, yet it accepted countless donations and deceived goodwill," James tweeted.'
pprint(string_news2)
('(CNN)New York Attorney General Letitia James on Monday ordered the Black '
 'Lives Matter Foundation -- which she said is not affiliated with the larger '
 'Black Lives Matter movement -- to stop collecting donations in New York. "I '
 'ordered the Black Lives Matter Foundation to stop illegally accepting '
 'donations that were intended for the #BlackLivesMatter movement. This '
 'foundation is not affiliated with the movement, yet it accepted countless '
 'donations and deceived goodwill," James tweeted.')
[8]:
# https://www.thestar.com.my/business/business-news/2020/07/04/malaysia-worries-new-eu-food-rules-could-hurt-palm-oil-exports

string_news3 = 'Amongst the wide-ranging initiatives proposed are a sustainable food labelling framework, a reformulation of processed foods, and a sustainability chapter in all EU bilateral trade agreements. The EU also plans to publish a proposal for a legislative framework for sustainable food systems by 2023 to ensure all foods on the EU market become increasingly sustainable.'
pprint(string_news3)
('Amongst the wide-ranging initiatives proposed are a sustainable food '
 'labelling framework, a reformulation of processed foods, and a '
 'sustainability chapter in all EU bilateral trade agreements. The EU also '
 'plans to publish a proposal for a legislative framework for sustainable food '
 'systems by 2023 to ensure all foods on the EU market become increasingly '
 'sustainable.')
[9]:
# https://jamesclear.com/articles

string_article1 = 'This page shares my best articles to read on topics like health, happiness, creativity, productivity and more. The central question that drives my work is, “How can we live better?” To answer that question, I like to write about science-based ways to solve practical problems.'
pprint(string_article1)
('This page shares my best articles to read on topics like health, happiness, '
 'creativity, productivity and more. The central question that drives my work '
 'is, “How can we live better?” To answer that question, I like to write about '
 'science-based ways to solve practical problems.')
[10]:
%%time

pprint(transformer_noisy.generate([string_news1, string_news2, string_news3],
                                 max_length = 1000))
You're using a T5TokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.
['KUALA LUMPUR, 1 Julai - Datuk Seri Anwar Ibrahim tidak sesuai menjadi calon '
 'perdana menteri kerana didakwa tidak "popular" dalam kalangan orang Melayu, '
 'dakwa Tun Dr Mahathir Mohamad. Bekas perdana menteri itu dilaporkan berkata '
 'presiden PKR itu memerlukan seseorang seperti dirinya demi memperoleh '
 'sokongan daripada orang Melayu dan memenangi pilihan raya.',
 '(CNN) Peguam Negara New York Letitia James pada Isnin mengarahkan Yayasan '
 'Black Lives Matter -- yang menurutnya tidak bergabung dengan gerakan Black '
 'Lives Matter yang lebih besar -- untuk berhenti mengutip sumbangan di New '
 'York. "Saya mengarahkan Yayasan Black Lives Matter berhenti menerima '
 'sumbangan secara haram yang ditujukan untuk gerakan #BlackLivesMatter. '
 'Yayasan ini tidak bergabung dengan gerakan itu, namun ia menerima sumbangan '
 'yang tidak terkira dan muhibah yang tertipu," ciap James.',
 'Antara inisiatif yang meluas yang dicadangkan ialah rangka kerja pelabelan '
 'makanan yang mampan, pembaharuan makanan yang diproses, dan bab kelestarian '
 'dalam semua perjanjian perdagangan dua hala EU. EU juga merancang untuk '
 'menerbitkan cadangan rangka kerja perundangan bagi sistem makanan yang '
 'mampan menjelang 2023 bagi memastikan semua makanan di pasaran EU menjadi '
 'semakin mampan.']
CPU times: user 13.5 s, sys: 518 µs, total: 13.5 s
Wall time: 1.14 s

compare results using local language structure#

[11]:
strings = [
    'u ni, talk properly lah',
    "just attended my cousin's wedding. pelik jugak dia buat majlis biasa2 je sebab her lifestyle looks lavish. then i found out they're going on a 3 weeks honeymoon. smart decision 👍",
    'Me after seeing this video: mm dapnya burger benjo extra mayo',
    'Hi guys! I noticed semalam & harini dah ramai yang dapat cookies ni kan. So harini i nak share some post mortem of our first batch:',
]
[12]:
# do not forget to inject this initial prompt!

transformer_noisy._initial_text = 'terjemah pasar Melayu ke Melayu: '
[13]:
%%time

transformer_noisy.generate(strings, max_length = 1000)
CPU times: user 6.04 s, sys: 41 ms, total: 6.08 s
Wall time: 524 ms
[13]:
['ini awak, bercakap dengan betul',
 'baru menghadiri majlis perkahwinan sepupu saya. Pelik juga dia hanya mengadakan majlis biasa kerana gaya hidupnya kelihatan mewah. kemudian saya mendapat tahu mereka sedang berbulan madu selama 3 minggu. keputusan bijak ',
 'Saya selepas melihat video ini: memang ada burger benjo extra mayo',
 'Hai kawan-kawan! Saya perasan semalam & hari ini ramai yang dapat biskut ni kan? Jadi hari ini saya ingin berkongsi beberapa post mortem kumpulan pertama kami:']
[14]:
%%time

transformer.generate(strings, max_length = 1000)
You're using a T5TokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.
CPU times: user 5.99 s, sys: 5.1 ms, total: 5.99 s
Wall time: 502 ms
[14]:
['u ni, bercakap dengan betul',
 'baru sahaja menghadiri perkahwinan sepupu saya. pelik juga dia buat majlis biasa2 je sebab gaya hidupnya kelihatan mewah. kemudian saya dapati mereka akan berbulan madu selama 3 minggu. keputusan pintar ',
 'Saya selepas melihat video ini: benjo burger benjo extra mayo',
 'Hai kawan! Saya perasan semalam & harini ramai yang dapat biskut ni kan. Jadi harini saya nak kongsi beberapa post mortem daripada our first batch:']

compare with Google translate using googletrans#

Install it by,

pip3 install googletrans==4.0.0rc1
[15]:
from googletrans import Translator

translator = Translator()
[16]:
for t in strings:
    r = translator.translate(t, src='en', dest = 'ms')
    print(r.text)
u ni, bercakap betul lah
Baru sahaja menghadiri majlis perkahwinan sepupu saya.Pelik Jugak Dia Buat Majlis Biasa2 Je Sebab Gaya hidupnya kelihatan mewah.Kemudian saya dapati mereka akan berbulan madu selama 3 minggu.Keputusan Pintar 👍
Saya setelah melihat video ini: mm dapnya burger benjo tambahan mayo
Hai semua!Saya perhatikan Semalam & Harini Dah Ramai Yang Dapate Cookies Ni Kan.Jadi harini i nak berkongsi beberapa bedah siasat dari kumpulan pertama kami:
[ ]: