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.27 s, sys: 3.58 s, total: 6.85 s
Wall time: 2.26 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-super-super-tiny-standard-bahasa-cased 23.3 36.290743 71.2/46.0/30.9/21.0 (BP = 0.950 ratio = 0.951 ... 61.89 256
mesolitica/finetune-translation-t5-super-tiny-standard-bahasa-cased 50.7 39.188342 72.6/48.3/33.5/23.6 (BP = 0.960 ratio = 0.961 ... 64.03 256
mesolitica/finetune-translation-t5-tiny-standard-bahasa-cased 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 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 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 139 41.036414 72.9/49.2/34.8/25.0 (BP = 0.977 ratio = 0.977 ... 65.58 256
mesolitica/finetune-noisy-translation-t5-small-bahasa-cased 242 41.15794 72.2/48.8/34.5/24.8 (BP = 0.988 ratio = 0.988 ... 65.51 256
mesolitica/finetune-noisy-translation-t5-base-bahasa-cased 892 41.827831 73.4/50.1/35.7/25.8 (BP = 0.982 ratio = 0.982 ... 66.51 256
mesolitica/finetune-noisy-translation-t5-tiny-bahasa-cased-v2 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-v4 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()
[4]:
transformer_noisy = malaya.translation.en_ms.huggingface(model = 'mesolitica/finetune-noisy-translation-t5-small-bahasa-cased-v4')

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 sebagai calon '
 'perdana menteri kerana kononnya tidak "popular" di kalangan orang Melayu, '
 'Tun Dr Mahathir Mohamad mendakwa. Bekas perdana menteri dilaporkan berkata '
 'presiden PKR memerlukan seseorang seperti dirinya demi memperoleh sokongan '
 'daripada orang Melayu dan memenangi pilihan raya.',
 '(CNN) Peguam Negara New York Letitia James pada hari Isnin mengarahkan '
 'Yayasan Black Lives Matter -- yang katanya tidak bergabung dengan gerakan '
 'Black Lives Matter yang lebih besar -- untuk berhenti mengutip sumbangan di '
 'New York. "Saya mengarahkan Yayasan Black Lives Matter untuk berhenti secara '
 'haram menerima sumbangan yang ditujukan untuk gerakan #BlackLivesMatter. '
 'Yayasan ini tidak bergabung dengan gerakan tersebut, namun menerima '
 'sumbangan yang tidak terkira dan tertipu muhibah," James tweet.',
 'Antara inisiatif yang luas dicadang adalah rangka label makanan lestari, '
 'reformasi makanan yang diproses, dan bab kelestarian dalam semua perjanjian '
 'perdagangan dua hala EU. EU juga bercadang untuk menerbitkan cadangan rangka '
 'perundangan bagi sistem makanan lestari menjelang 2023 bagi memastikan semua '
 'makanan di pasaran EU menjadi semakin mampan.']
CPU times: user 15.9 s, sys: 2.17 ms, total: 15.9 s
Wall time: 1.35 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:',
]
[13]:
# do not forget to inject this initial prompt!

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

transformer_noisy.generate(strings, max_length = 1000)
CPU times: user 5.92 s, sys: 820 ยตs, total: 5.92 s
Wall time: 499 ms
[14]:
['ini awak, bercakap dengan betul',
 'baru menghadiri majlis perkahwinan sepupu saya. Peliknya dia buat majlis biasa-biasa saja sebab gaya hidup dia nampak mewah. kemudian saya mendapat tahu mereka sedang berbulan madu selama 3 minggu. keputusan yang bijak ',
 'Selepas menonton video ini: burger bejo tambahan mayo memang sedap',
 'Hai kawan-kawan! Saya perasan semalam & hari ini ramai yang dapat biskut kan? Jadi hari ini saya ingin berkongsi beberapa post mortem batch pertama kami:']
[15]:
%%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 7.32 s, sys: 4.04 ms, total: 7.32 s
Wall time: 616 ms
[15]:
['u ni, bercakap dengan betul',
 'baru sahaja menghadiri majlis perkahwinan sepupu saya. pelik jugak dia buat majlis biasa2 je kerana gaya hidupnya kelihatan mewah. maka saya mendapat tahu bahawa mereka akan berbulan madu selama 3 minggu. keputusan pintar ',
 'Saya selepas melihat video ini: mm dapnya burger benjo extra mayo',
 'Hai kawan-kawan! Saya perhatikan semalam & harini dah banyak yang dapat kuki ni kan. Jadi harini saya ingin berkongsi beberapa post mortem kumpulan pertama kami:']

compare with Google translate using googletrans#

Install it by,

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

translator = Translator()
[19]:
for t in strings:
    r = translator.translate(t, src='en', dest = 'ms')
    print(r.text)
u ni, bercakap dengan 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 kumpulan pertama kami: