Spelling Correction using probability LM#

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

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

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)
[3]:
import malaya
/home/husein/dev/malaya/malaya/tokenizer.py:202: FutureWarning: Possible nested set at position 3361
  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))
/home/husein/dev/malaya/malaya/tokenizer.py:202: FutureWarning: Possible nested set at position 3879
  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))
[4]:
# 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 object with `score` method.
    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`.
    """
[5]:
lm = malaya.language_model.kenlm()
lm
[5]:
<Model from b'79a00bc9ce79bd29dea1bfa15b66524db7b6731f040a71c653f02c2132d955a3.a63730b02158debc1b0102385e131830c93721224b1f932896486da18e3ec1bb'>
[6]:
model = malaya.spelling_correction.probability.load(language_model = lm)
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]:
['sembang',
 'sambung',
 'sambong',
 'sembung',
 'sembong',
 'sombong',
 'sembing',
 'sambang',
 'sumbang',
 'simbang',
 'sumbing']

To correct a word#

def correct(
    self,
    word: str,
    string: List[str],
    index: int = -1,
    lookback: int = 3,
    lookforward: int = 3,
):
    """
    Correct a word within a text, returning the corrected word.

    Parameters
    ----------
    word: str
    string: str
        Entire string, `word` must a word inside `string`.
    index: int, optional (default=-1)
        index of word in the string, if -1, will try to use `string.index(word)`.
    lookback: int, optional (default=3)
        N left hand side words.
    lookforward: int, optional (default=3)
        N right hand side words.

    Returns
    -------
    result: str
    """
[9]:
splitted = string1.split()
model.correct('kpd', splitted)
[9]:
'kepada'
[10]:
model.correct('krajaan', splitted)
[10]:
'kerajaan'
[11]:
%%time

model.correct('skt', splitted, )
CPU times: user 802 µs, sys: 0 ns, total: 802 µs
Wall time: 811 µs
[11]:
'sikit'
[12]:
%%time

model.correct('skt', splitted, lookback = -1)
CPU times: user 640 µs, sys: 0 ns, total: 640 µs
Wall time: 641 µs
[12]:
'sikit'

To correct a sentence#

def correct_text(
    self,
    text: str,
    lookback: int = 3,
    lookforward: int = 3,
):
    """
    Correct all the words within a text, returning the corrected text.

    Parameters
    ----------
    text: str
    lookback: int, optional (default=3)
        N words on the left hand side.
        if put -1, will take all words on the left hand side.
        longer left hand side will take longer to compute.
    lookforward: int, optional (default=3)
        N words on the right hand side.
        if put -1, will take all words on the right hand side.
        longer right hand side will take longer to compute.

    Returns
    -------
    result: str
    """
[13]:
model.correct_text(string1)
[13]:
'kerajaan patut bagi pencen awal sikit kepada warga emas supaya emosi'
[14]:
tokenizer = malaya.tokenizer.Tokenizer()
[15]:
tokenized = tokenizer.tokenize(string2)
model.correct_text(' '.join(tokenized))
[15]:
'Husin suka makan ayam dekat kampung Jawa'
[16]:
tokenized = tokenizer.tokenize(string3)
model.correct_text(' '.join(tokenized))
[16]:
'Melayu malas ini narration dia sama sahaja macam men are trash . True to some , false to some .'
[17]:
tokenized = tokenizer.tokenize(string4)
model.correct_text(' '.join(tokenized))
[17]:
'Tapi tak fikir ke bahaya perpetuate myths macam itu . Nanti kalau ada hiring discrimination despite your good qualifications because of your race tahu pula marah . Your kids will be victims of that too .'
[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]:
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 🤣🤣🤣'
[22]:
tokenized = tokenizer.tokenize(s)
model.correct_text(' '.join(tokenized))
[22]:
'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 🤣 🤣 🤣'

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').

[23]:
stemmer = malaya.stem.deep_model(model = 'noisy')
INFO:malaya_boilerplate.frozen_graph:running home/husein/.cache/huggingface/hub using device /device:CPU:0
2022-09-13 14:22:37.882374: 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 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-09-13 14:22:37.886864: 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-13 14:22:37.886885: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: husein-MS-7D31
2022-09-13 14:22:37.886888: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: husein-MS-7D31
2022-09-13 14:22:37.886930: 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-13 14:22:37.886948: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:204] kernel reported version is: 470.141.3
[24]:
model_stemmer = malaya.spelling_correction.probability.load(language_model = lm, stemmer = stemmer)
INFO:malaya_boilerplate.huggingface:downloading frozen huseinzol05/v27-preprocessing/bm_1grams.json
[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 🤣 🤣 🤣'