Spelling Correction using probability#

This tutorial is available as an IPython notebook at Malaya/example/spelling-correction-probability.

This spelling correction extends the functionality of the Peter Norvig’s spell-corrector in http://norvig.com/spell-correct.html

And improve it using some algorithms from Normalization of noisy texts in Malaysian online reviews, https://www.researchgate.net/publication/287050449_Normalization_of_noisy_texts_in_Malaysian_online_reviews

Also added custom vowels augmentation.

[1]:
import os

os.environ['CUDA_VISIBLE_DEVICES'] = ''
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
[2]:
import logging

logging.basicConfig(level=logging.INFO)
[4]:
import malaya
/home/ubuntu/dev/malaya/malaya/tokenizer.py:202: FutureWarning: Possible nested set at position 3361
  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))
/home/ubuntu/dev/malaya/malaya/tokenizer.py:202: FutureWarning: Possible nested set at position 3879
  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))
[5]:
# some text examples copied from Twitter

string1 = 'krajaan patut bagi pencen awal skt kpd warga emas supaya emosi'
string2 = 'Husein ska mkn aym dkat kampng Jawa'
string3 = 'Melayu malas ni narration dia sama je macam men are trash. True to some, false to some.'
string4 = 'Tapi tak pikir ke bahaya perpetuate myths camtu. Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah. Your kids will be victims of that too.'
string5 = 'DrM cerita Melayu malas semenjak saya kat University (early 1980s) and now as i am edging towards retirement in 4-5 years time after a career of being an Engineer, Project Manager, General Manager'
string6 = 'blh bntg dlm kls nlp sy, nnti intch'
string7 = 'mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik'

Load probability model#

def load(
    language_model=None,
    sentence_piece: bool = False,
    stemmer=None,
    **kwargs,
):
    """
    Load a Probability Spell Corrector.

    Parameters
    ----------
    language_model: Callable, optional (default=None)
        If not None, must an instance of kenlm.Model.
    sentence_piece: bool, optional (default=False)
        if True, reduce possible augmentation states using sentence piece.
    stemmer: Callable, optional (default=None)
        a Callable object, must have `stem_word` method.

    Returns
    -------
    result: model
        List of model classes:

        * if passed `language_model` will return `malaya.spelling_correction.probability.ProbabilityLM`.
        * else will return `malaya.spelling_correction.probability.Probability`.
    """
[6]:
model = malaya.spelling_correction.probability.load()
INFO:malaya_boilerplate.huggingface:downloading frozen huseinzol05/v27-preprocessing/bm_1grams.json

List possible generated pool of words#

def edit_candidates(self, word):
    """
    Generate candidates given a word.

    Parameters
    ----------
    word: str

    Returns
    -------
    result: List[str]
    """
[7]:
model.edit_candidates('mhthir')
[7]:
['mahathir']
[8]:
model.edit_candidates('smbng')
[8]:
['sembung',
 'sumbang',
 'sambong',
 'sambung',
 'sambang',
 'sembong',
 'sumbing',
 'sembing',
 'simbang',
 'sembang',
 'sombong']

Now you can see, edit_candidates suggested quite a lot candidates and some of candidates not an actual word like sambang, to reduce that, we can use sentencepiece to check a candidate a legit word for malaysia context or not.

[9]:
model_sp = malaya.spelling_correction.probability.load(sentence_piece = True)
model_sp.edit_candidates('smbng')
INFO:malaya_boilerplate.huggingface:downloading frozen huseinzol05/v27-preprocessing/sp10m.cased.v4.vocab
INFO:malaya_boilerplate.huggingface:downloading frozen huseinzol05/v27-preprocessing/sp10m.cased.v4.model
INFO:malaya_boilerplate.huggingface:downloading frozen huseinzol05/v27-preprocessing/bm_1grams.json
[9]:
['sembung',
 'sumbang',
 'sambong',
 'sambung',
 'sembong',
 'sumbing',
 'sembing',
 'sembang',
 'sombong']

So how does the model knows which words need to pick? highest counts from the corpus!

To correct a word#

def correct(self, word: str, **kwargs):
    """
    Most probable spelling correction for word.

    Parameters
    ----------
    word: str

    Returns
    -------
    result: str
    """
[10]:
model.correct('suke')
[10]:
'suka'
[11]:
model.correct('kpd')
[11]:
'kepada'
[12]:
model.correct('krajaan')
[12]:
'kerajaan'

To correct a sentence#

def correct_text(self, text: str):
    """
    Correct all the words within a text, returning the corrected text.

    Parameters
    ----------
    text: str

    Returns
    -------
    result: str
    """
[13]:
model.correct_text(string1)
[13]:
'kerajaan patut bagi pencen awal sakit kepada warga emas supaya emosi'
[14]:
tokenizer = malaya.tokenizer.Tokenizer()
[15]:
string2
[15]:
'Husein ska mkn aym dkat kampng Jawa'
[16]:
tokenized = tokenizer.tokenize(string2)
model.correct_text(' '.join(tokenized))
[16]:
'Hussein suka makan ayam dekat kampung Jawa'
[17]:
tokenized = tokenizer.tokenize(string3)
model.correct_text(' '.join(tokenized))
[17]:
'Melayu malas ini narration dia sama sahaja macam men are trash . True to some , false to some .'
[18]:
tokenized = tokenizer.tokenize(string5)
model.correct_text(' '.join(tokenized))
[18]:
'DrM cerita Melayu malas semenjak saya kat University ( early 1980s ) and now as i am edging towards retirement in 4 - 5 years time after a career of being an Engineer , Project Manager , General Manager'
[19]:
tokenized = tokenizer.tokenize(string6)
model.correct_text(' '.join(tokenized))
[19]:
'boleh bintang dalam kelas nlp saya , nanti intch'
[20]:
tokenized = tokenizer.tokenize(string7)
model.correct_text(' '.join(tokenized))
[20]:
'mulakan salah orang boleh , bila geng itu kena salahkan juga xboleh terima . . pelik'
[21]:
model.edit_candidates('slhkn')
[21]:
['suluhkan', 'silahkan', 'salahakan', 'salahkan']

Load stemmer for probability model#

By default kata imbuhan captured using naive regex pattern without understand the word structure, and problem with that, there are so many rules need to hardcode, so we can use better stemmer model like malaya.stem.deep_model(model = 'noisy').

[22]:
stemmer = malaya.stem.deep_model(model = 'noisy')
INFO:malaya_boilerplate.frozen_graph:running home/ubuntu/.cache/huggingface/hub using device /device:CPU:0
2022-09-01 21:46:11.257398: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-09-01 21:46:11.261443: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected
2022-09-01 21:46:11.261459: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: huseincomel-desktop
2022-09-01 21:46:11.261462: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: huseincomel-desktop
2022-09-01 21:46:11.261512: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:200] libcuda reported version is: Not found: was unable to find libcuda.so DSO loaded into this program
2022-09-01 21:46:11.261529: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:204] kernel reported version is: 470.141.3
[23]:
model_stemmer = malaya.spelling_correction.probability.load(stemmer = stemmer)
INFO:malaya_boilerplate.huggingface:downloading frozen huseinzol05/v27-preprocessing/bm_1grams.json
[24]:
model_stemmer.edit_candidates('slhkn')
[24]:
['suluhkan', 'silahkan', 'salahakan', 'salahkan']
[25]:
tokenized = tokenizer.tokenize(string7)
model_stemmer.correct_text(' '.join(tokenized))
[25]:
'mulakan salah orang boleh , bila geng itu kena salahkan juga xboleh terima . . pelik'
[26]:
s = 'mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik , dia slhkn org bole hri2 crta sakau then bila kna bls balik xdpt jwb ,kata mcm biasa slh (parti sampah) 🤣🤣🤣 jgn mulakn dlu slhkn org kalau xboleh trima bila kna bls balik 🤣🤣🤣'
[27]:
tokenized = tokenizer.tokenize(s)
model_stemmer.correct_text(' '.join(tokenized))
[27]:
'mulakan salah orang boleh , bila geng itu kena salahkan juga xboleh terima . . pelik , dia salahkan orang bole hari2 cerita sakau then bila kena balas balik xdpt jawab , kata macam biasa salah ( parti sampah ) 🤣 🤣 🤣 jangan mulakan dahulu salahkan orang kalau xboleh terima bila kena balas balik 🤣 🤣 🤣'