Spaces:
Runtime error
Runtime error
File size: 25,407 Bytes
44db343 |
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 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 |
import string
from nltk.tokenize import word_tokenize
import numpy as np
import re
import unidecode
import nltk
import json
import os
real_file_path = "/".join(os.path.realpath(__file__).split("/")[:-1])
nltk.download('punkt')
from dataset.vocab import Vocab
from ast import literal_eval
class SynthesizeData(object):
"""
Uitils class to create artificial miss-spelled words
Args:
vocab_path: path to vocab file. Vocab file is expected to be a set of words, separate by ' ', no newline charactor.
"""
def __init__(self, vocab: Vocab):
self.vocab = vocab
self.tokenizer = word_tokenize
self.vn_alphabet = ['a', 'ă', 'â', 'b', 'c', 'd', 'đ', 'e', 'ê', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'ô',
'ơ', 'p', 'q', 'r', 's', 't', 'u', 'ư', 'v', 'x', 'y']
self.alphabet_len = len(self.vn_alphabet)
self.word_couples = [pair.strip("\n").split(" ") for pair in open(os.path.join(real_file_path, "noising_resources/kieu_go_dau_cu_moi.txt"), "r", encoding='utf-8').readlines()]
self.homowords = literal_eval(open( os.path.join(real_file_path, "noising_resources/confusion_set.json"), "r", encoding='utf-8').read())
self.homo_leters_dict = literal_eval(open( os.path.join(real_file_path, "noising_resources/homo_leter.json"), "r", encoding='utf-8').read())
self.teencode_dict = {'mình': ['mk', 'mik', 'mjk'], 'vô': ['zô', 'zo', 'vo'], 'vậy': ['zậy', 'z', 'zay', 'za'],
'phải': ['fải', 'fai', ], 'biết': ['bit', 'biet'],
'rồi': ['rùi', 'ròi', 'r'], 'bây': ['bi', 'bay'], 'giờ': ['h', ],
'không': ['k', 'ko', 'khong', 'hk', 'hong', 'hông', '0', 'kg', 'kh', ],
'đi': ['di', 'dj', ], 'gì': ['j', ], 'em': ['e', ], 'được': ['dc', 'đc', ], 'tao': ['t'],
'tôi': ['t'], 'chồng': ['ck'], 'vợ': ['vk']
}
self.typo = json.load( open(os.path.join(real_file_path,"noising_resources/typo.json"), "r", encoding='utf-8'))
self.all_char_candidates = self.get_all_char_candidates()
self.all_word_candidates = self.get_all_word_candidates()
def replace_teencode(self, word):
candidates = self.teencode_dict.get(word, None)
if candidates is not None:
chosen_one = 0
if len(candidates) > 1:
chosen_one = np.random.randint(0, len(candidates))
return candidates[chosen_one]
def replace_char_candidate(self, char):
"""
return a homophone char/subword of the input char.
"""
return np.random.choice(self.homo_leters_dict[char])
def replace_word_candidate(self, word):
"""
Return a new typo word of the input word for example òa oà
"""
capital_flag = word[0].isupper()
word = word.lower()
if capital_flag and word in self.teencode_dict:
return self.replace_teencode(word).capitalize()
elif word in self.teencode_dict:
return self.replace_teencode(word)
for couple in self.word_couples:
for i in range(2):
if couple[i] == word:
if i == 0:
if capital_flag:
return couple[1].capitalize()
else:
return couple[1]
else:
if capital_flag:
return couple[0].capitalize()
else:
return couple[0]
def replace_homo_candidate(self, word):
"""
Return a homo word of the input word
"""
capital_flag = word[0].isupper()
word = word.lower()
def random_capitalize(word):
index = np.random.randint(0, len(word))
return word[0:index] + word[index].upper() + word[index+1:]
candidate_type = np.random.choice(["phu_am_dau", "phu_am_cuoi", "nguyen_am"]\
, p = [0.1, 0.3, 0.6])
if candidate_type == "nguyen_am":
coin = np.random.choice([0, 1], p = [0.7, 0.3])
candidates = list(self.homowords[word][candidate_type][coin])
else:
candidates = list(self.homowords[word][candidate_type])
if len(candidates) == 0:
if capital_flag:
return word
return random_capitalize(word)
candidate = np.random.choice(candidates)
if capital_flag:
return candidate.capitalize()
return candidate
def replace_char_candidate_typo(self, char):
"""
return a homophone char/subword of the input char.
"""
candidates = self.typo[char]
num_lower_priority = len(candidates) - 1
round_flag = 10 * num_lower_priority
return np.random.choice(candidates, p = [0.7, *[3 / round_flag for i in range(num_lower_priority)]])
def get_all_char_candidates(self):
return list(self.homo_leters_dict.keys())
def get_all_word_candidates(self):
all_word_candidates = []
for couple in self.word_couples:
all_word_candidates.extend(couple)
return all_word_candidates
def remove_diacritics(self, text, onehot_label):
"""
Replace word which has diacritics with the same word without diacritics
Args:
text: a list of word tokens
onehot_label: onehot array indicate position of word that has already modify, so this
function only choose the word that do not has onehot label == 1.
return: a list of word tokens has one word that its diacritics was removed,
a list of onehot label indicate the position of words that has been modified.
"""
if len(text) == len(' '.join(text).split()):
its_me = True
else:
its_me = False
idx = np.random.randint(0, len(onehot_label))
prevent_loop = 0
noised_token = unidecode.unidecode(text[idx])
while onehot_label[idx] != 0 or not self.vocab.exist(text[idx]) or text[idx] in string.punctuation or text[idx] == noised_token:
idx = np.random.randint(0, len(onehot_label))
noised_token = unidecode.unidecode(text[idx])
prevent_loop += 1
if prevent_loop > 10:
return False, text, onehot_label
onehot_label[idx] = 1
token = text[idx]
text[idx] = unidecode.unidecode(text[idx])
if (len(text) != len(' '.join(text).split())) and its_me:
print("ERROR:")
print("text: ", text)
print("replaced token: ", text[idx])
print("org token: ", token)
return True, text, onehot_label
def replace_with_random_letter(self, text, onehot_label):
"""
Replace, add (or remove) a random letter in a random chosen word with a random letter
Args:
text: a list of word tokens
onehot_label: onehot array indicate position of word that has already modify, so this
function only choose the word that do not has onehot label == 1.
return: a list of word tokens has one word that has been modified,
a list of onehot label indicate the position of words that has been modified.
"""
if len(text) == len(' '.join(text).split()):
its_me = True
else:
its_me = False
idx = np.random.randint(0, len(onehot_label))
prevent_loop = 0
while onehot_label[idx] != 0 or not self.vocab.exist(text[idx]) or len(text[idx]) < 3:
idx = np.random.randint(0, len(onehot_label))
prevent_loop += 1
if prevent_loop > 10:
return False, text, onehot_label
# replace, add or remove? 0 is replace, 1 is add, 2 is remove
# 0.8 1 edits, 0.2 2 edits
num_edit = np.random.choice([1,2], p = [0.8, 0.2])
coin = np.random.choice([0, 1, 2])
for i in range(num_edit):
token = list(text[idx])
if coin == 0:
chosen_idx = np.random.randint(0, len(token))
replace_candidate = self.vn_alphabet[np.random.randint(
0, self.alphabet_len)]
token[chosen_idx] = replace_candidate
text[idx] = "".join(token)
elif coin == 1:
chosen_idx = np.random.randint(0, len(token) + 1)
if chosen_idx == len(token):
added_chars = self.vn_alphabet[np.random.randint(0, self.alphabet_len)] + \
token[0]
chosen_idx = 0
else:
added_chars = token[chosen_idx] + \
self.vn_alphabet[np.random.randint(0, self.alphabet_len)]
token[chosen_idx] = added_chars
text[idx] = "".join(token)
else:
chosen_idx = np.random.randint(0, len(token))
token[chosen_idx] = ""
text[idx] = "".join(token)
onehot_label[idx] = 1
if (len(text) != len(' '.join(text).split())) and its_me:
print("ERROR:")
print("text: ", text)
print("replaced token: ", text[idx])
print("org token: ", token)
print("coin: ", coin)
return False, text, onehot_label
return True, text, onehot_label
def replace_with_new_typo_word(self, text, onehot_label):
"""
Replace a candidate word (if exist in the word_couple) with its homophone. if successful, return True, else False
Args:
text: a list of word tokens
onehot_label: onehot array indicate position of word that has already modify, so this
function only choose the word that do not has onehot label == 1.
return: True, text, onehot_label if successful replace, else False, text, onehot_label
"""
# account for the case that the word in the text is upper case but its lowercase match the candidates list
if len(text) == len(' '.join(text).split()):
its_me = True
else:
its_me = False
candidates = []
for i in range(len(text)):
if text[i].lower() in self.all_word_candidates or text[i].lower() in self.teencode_dict.keys():
candidates.append((i, text[i]))
if len(candidates) == 0:
return False, text, onehot_label
idx = np.random.randint(0, len(candidates))
prevent_loop = 0
while onehot_label[candidates[idx][0]] != 0 or not self.vocab.exist(candidates[idx][1]):
idx = np.random.choice(np.arange(0, len(candidates)))
prevent_loop += 1
if prevent_loop > 10:
return False, text, onehot_label
text[candidates[idx][0]] = self.replace_word_candidate(
candidates[idx][1])
if (len(text) != len(' '.join(text).split())) and its_me:
print("ERROR:")
print("text: ", text)
print("replaced token: ", text[candidates[idx][0]])
print("org token: ", candidates[idx][1])
onehot_label[candidates[idx][0]] = 1
return True, text, onehot_label
def replace_with_homophone_word(self, text, onehot_label):
"""
Replace a candidate word (if exist in the word_couple) with its homophone. if successful, return True, else False
Args:
text: a list of word tokens
onehot_label: onehot array indicate position of word that has already modify, so this
function only choose the word that do not has onehot label == 1.
return: True, text, onehot_label if successful replace, else False, text, onehot_label
"""
# account for the case that the word in the text is upper case but its lowercase match the candidates list
if len(text) == len(' '.join(text).split()):
its_me = True
else:
its_me = False
candidates = []
for i in range(len(text)):
if text[i].lower() in self.homowords:
candidates.append((i, text[i]))
if len(candidates) == 0:
return False, text, onehot_label
idx = np.random.randint(0, len(candidates))
prevent_loop = 0
while onehot_label[candidates[idx][0]] != 0 or not self.vocab.exist(candidates[idx][1]):
idx = np.random.choice(np.arange(0, len(candidates)))
prevent_loop += 1
if prevent_loop > 10:
return False, text, onehot_label
text[candidates[idx][0]] = self.replace_homo_candidate(
candidates[idx][1])
if (len(text) != len(' '.join(text).split())) and its_me:
print("ERROR:")
print("text: ", text)
print("replaced token: ", text[candidates[idx][0]])
print("org token: ", candidates[idx][1])
return False, text, onehot_label
onehot_label[candidates[idx][0]] = 1
return True, text, onehot_label
def replace_with_homophone_letter(self, text, onehot_label):
"""
Replace a subword/letter with its homophones
Args:
text: a list of word tokens
onehot_label: onehot array indicate position of word that has already modify, so this
function only choose the word that do not has onehot label == 1.
return: True, text, onehot_label if successful replace, else False, None, None
"""
if len(text) == len(' '.join(text).split()):
its_me = True
else:
its_me = False
candidates = []
for i in range(len(text)):
for char in self.all_char_candidates:
if re.search("^" + char, text[i]) is not None:
candidates.append((i, char, "^" + char ))
if re.search(char + "$", text[i]) is not None:
candidates.append((i, char, char + "$"))
if len(candidates) == 0:
return False, text, onehot_label
else:
idx = np.random.randint(0, len(candidates))
prevent_loop = 0
while onehot_label[candidates[idx][0]] != 0 or not self.vocab.exist(text[candidates[idx][0]]) or len(text[candidates[idx][0]]) < 2:
idx = np.random.randint(0, len(candidates))
prevent_loop += 1
if prevent_loop > 10:
return False, text, onehot_label
replaced = self.replace_char_candidate(candidates[idx][1])
## 0.15% remove the candidate. cát -> cá
coin = np.random.choice([0, 1], p = [0.8, 0.2])
text_to_replace = text[candidates[idx][0]]
result = re.sub(candidates[idx][2], replaced if coin == 0 else "",
text_to_replace)
if result == "":
result = re.sub(candidates[idx][2], replaced,
text_to_replace)
text[candidates[idx][0]] = result
if (len(text) != len(' '.join(text).split())) and its_me:
print("ERROR:")
print("text: ", text)
print("replaced token: ", text[candidates[idx][0]])
print("letter: ", candidates[idx][1])
print("replaced letter: ", replaced)
onehot_label[candidates[idx][0]] = 1
return True, text, onehot_label
def replace_with_typo_letter(self, text, onehot_label):
"""
Replace a subword/letter with its homophones
Args:
text: a list of word tokens
onehot_label: onehot array indicate position of word that has already modify, so this
function only choose the word that do not has onehot label == 1.
return: True, text, onehot_label if successful replace, else False, None, None
"""
if len(text) == len(' '.join(text).split()):
its_me = True
else:
its_me = False
# find index noise
idx = np.random.randint(0, len(onehot_label))
prevent_loop = 0
while onehot_label[idx] != 0 or not self.vocab.exist(text[idx]):
idx = np.random.randint(0, len(onehot_label))
prevent_loop += 1
if prevent_loop > 10:
return False, text, onehot_label
index_noise = idx
onehot_label[index_noise] = 1
org_word = text[index_noise]
word_noise = text[index_noise]
pattern = "(" + "|".join(self.typo.keys()) + "){1}"
candidates = re.findall(pattern, word_noise)
if len(candidates) == 0:
return False, text, onehot_label
accent_pattern = "(s|f|r|x|j|1|2|3|4|5){1}"
for candidate in candidates:
replaced = self.replace_char_candidate_typo(candidate)
# Move accent to the end of text
result = re.findall(accent_pattern, replaced)
if len(result) != 0:
word_noise = re.sub(candidate, replaced[0:-1], word_noise)
word_noise += replaced[-1]
else:
word_noise = re.sub(candidate, replaced, word_noise)
text[index_noise] = word_noise
if len(word_noise) < 3:
return True, text, onehot_label
### Introduce one or two edit on text
num_edits = np.random.choice([0, 1, 2], p = [0.5, 0.35, 0.15])
for i in range(num_edits):
coin = np.random.choice([0, 1, 2, 3])
word_noise = list(text[index_noise])
start_char = word_noise.pop(0)
if coin == 0:
chosen_idx = np.random.randint(0, len(word_noise))
word_noise[chosen_idx] = self.vn_alphabet[np.random.randint(0, self.alphabet_len)]
text[index_noise] = start_char + "".join(word_noise)
elif coin == 1:
chosen_idx = np.random.randint(0, len(word_noise))
word_noise[chosen_idx] += self.vn_alphabet[np.random.randint(0, self.alphabet_len)]
text[index_noise] = start_char + "".join(word_noise)
elif coin == 2:
if len(word_noise) < 2:
continue
chosen_idxs = np.random.choice(range(len(word_noise)), size = 2)
word_noise[chosen_idxs[0]], word_noise[chosen_idxs[1]] = \
word_noise[chosen_idxs[1]], word_noise[chosen_idxs[0]]
text[index_noise] = start_char + "".join(word_noise)
else:
chosen_idx = np.random.randint(0, len(word_noise))
word_noise[chosen_idx] = ""
text[index_noise] = start_char + "".join(word_noise)
return True, text, onehot_label
def split_word(self, text, onehot_label):
# find index noise
idx = np.random.randint(0, len(onehot_label))
prevent_loop = 0
while onehot_label[idx] not in [0, 1] or len(text[idx]) < 3 or text[idx] in r'''!"#$%&'()*+,-./:;<=>?@[]^_`{|}~''' :
idx = np.random.randint(0, len(onehot_label))
prevent_loop += 1
if prevent_loop > 10:
return False, text, onehot_label
org_word = text[idx]
new_text = text[:idx]
new_onehot = onehot_label[:idx]
index_split = np.random.randint(1, len(org_word))
new_text.extend([org_word[:index_split], org_word[index_split:]])
new_onehot.extend([2, 2])
if idx < len(text) - 1:
new_text.extend(text[idx+1:])
new_onehot.extend(onehot_label[idx+1:])
return True, new_text, new_onehot
def merge_word(self, text, onehot_label):
length = len(onehot_label)
if length < 2:
return False, text, onehot_label
def validate_len(idx, size):
while idx + size > length:
if idx > 0:
idx -= 1
else:
size -= 1
return idx, size
def validate_value(idx, size):
for i in range(idx, idx+size):
if onehot_label[i] not in [0, 1] or text[i] in r'''!"#$%&'()*+,-./:;<=>?@[]^_`{|}~''':
return False
return True
# find index noise
min_words = 2
max_words = 3 if length > 3 else length
num_words = np.random.randint(min_words, max_words + 1)
idx = np.random.randint(0, length)
prevent_loop = 0
idx, num_words = validate_len(idx, num_words)
while not validate_value(idx, num_words) :
prevent_loop += 1
if prevent_loop > 10:
return False, text, onehot_label
idx = np.random.randint(0, length)
num_words = np.random.randint(min_words, max_words + 1)
idx, num_words = validate_len(idx, num_words)
new_text = text[:idx]
new_onehot = onehot_label[:idx]
new_text.append(''.join(text[idx:idx+num_words]))
new_onehot.append(-num_words+1)
if idx + num_words < length:
new_text.extend(text[idx+num_words:])
new_onehot.extend(onehot_label[idx+num_words:])
return True, new_text, new_onehot
def add_normal_noise(self, sentence, percent_err=0.2, num_type_err=4):
tokens = sentence.split()
if len(tokens) <= 0:
print(f"SOMETHING WROONG - sent: {sentence}")
onehot_label = [0] * len(tokens)
num_wrong = int(np.ceil(percent_err * len(tokens)))
num_wrong = np.random.randint(1, num_wrong + 1)
if np.random.rand() < 0.05:
num_wrong = 0
prevent_loop = 0
for i in range(0, num_wrong):
err = np.random.choice(range(num_type_err + 1)\
, p = [0.15, 0.15, 0.1, 0.2, 0.4])
if err == 0:
_, tokens, onehot_label = self.remove_diacritics(
tokens, onehot_label)
elif err == 1:
_, tokens, onehot_label = self.replace_with_typo_letter(
tokens, onehot_label)
elif err == 2:
_, tokens, onehot_label = self.replace_with_random_letter(
tokens, onehot_label)
elif err == 3:
_, tokens, onehot_label = self.replace_with_homophone_letter(
tokens, onehot_label)
else:
_, tokens, onehot_label = self.replace_with_homophone_word(
tokens, onehot_label)
prevent_loop += 1
if prevent_loop > 10:
return ' '.join(tokens), ' '.join([str(i) for i in onehot_label])
# print(tokens)
self.verify(tokens, sentence)
return ' '.join(tokens), ' '.join([str(i) for i in onehot_label])
def add_split_merge_noise(self, sentence, percent_err=0.15, num_type_err=2, percent_normal_err = 0.15):
def count_zero_one(onehot_label):
return sum([1 if onehot in [0, 1] else 0 for onehot in onehot_label])
## Introduce normal noise before split merge
normal_noise, normal_onehot = self.add_normal_noise(
sentence, percent_err=percent_normal_err)
tokens = normal_noise.split()
length = len(tokens)
onehot_label = [int(x) for x in normal_onehot.split(" ")]
num_wrong = int(np.ceil(percent_err * length))
num_wrong = np.random.randint(1, num_wrong + 1)
if np.random.rand() < 0.05:
num_wrong = 0
min_zeroes = length - num_wrong
zero_one_num = length
prevent_loop = 0
while zero_one_num > min_zeroes:
err = np.random.randint(0, num_type_err)
if err == 0:
_, tokens, onehot_label = self.split_word(
tokens, onehot_label)
else:
_, tokens, onehot_label = self.merge_word(
tokens, onehot_label)
prevent_loop += 1
if prevent_loop > 10:
return ' '.join(tokens), ' '.join([str(i) for i in onehot_label])
zero_one_num = count_zero_one(onehot_label)
return ' '.join(tokens), ' '.join([str(i) for i in onehot_label])
def verify(self, noised_tokens, sentence):
if len(noised_tokens) != len(' '.join(noised_tokens).split()):
print("ERROR:")
print("TEXT : ", sentence)
print("TOKENS: ", ' '.join(noised_tokens))
exit()
return True
if __name__ == "__main__":
text = "Ô kìa ai như cô thắm , con bác năm ở xa mới về , nghiêng nghiêng"
dict_pickle_path = '../data/vi/datasets/vi_wiki/vi_wiki.vocab.test.pkl'
vocab = Vocab()
vocab.load_vocab_dict(dict_pickle_path)
noiser = SynthesizeData(vocab)
noised_text, onehot_label = noiser.add_split_merge_noise(text, percent_err=0.5)
print(noised_text) |