-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess.py
973 lines (842 loc) · 34.4 KB
/
preprocess.py
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
# from transformers import Pipeline
import string
import re
from tqdm import tqdm
import random
class Preprocess:
def __init__(self, main_path, datasets, epochs=1):
self.main_path = main_path
self.DICTIONARY_DIR = main_path + "/dictionary/dictionary.txt"
self.KEYBOARD_ERRORS_DIR = (
main_path + "/dictionary/keyboard_realword_errors.txt"
)
self.SUBSTITUTION_ERRORS_DIR = (
main_path + "/dictionary/substitution_realword_errors.txt"
)
self.HOMOPHONE_ERRORS_DIR = (
main_path + "/dictionary/homophone_realword_errors.txt"
)
self.RAW_DATASET_DIR = main_path + "/raw datasets/total_rawdata.txt"
self.PRUNE_DATA = main_path + "/pruned datasets/total_prunedata.txt"
self.TRAIN_DATASET = main_path + "/train test datasets/train/"
self.TRAIN_FINAL_DATASET = (
main_path + "/train test datasets/train/final_dataset.txt"
)
self.CORRECT_SENTNCES = (
main_path + "/train test datasets/train/correct_sentences.txt"
)
self.METADATA = main_path + "/train test datasets/train/metadata.txt"
self.CORRUPTED_SENTENCES = (
main_path + "/train test datasets/train/corrupted_sentences.txt"
)
self.MASKED_SENTENCES = (
main_path + "/train test datasets/train/masked_sentences.txt"
)
self.TEST_DATASET = main_path + "/train test datasets/test/final_dataset.txt"
self.TEST_DATASET_100 = (
main_path + "/train test datasets/test/final_dataset_100.txt"
)
self.datasets = datasets
self.letters = [
"ا",
"ب",
"پ",
"ت",
"ث",
"ج",
"چ",
"ح",
"خ",
"د",
"ذ",
"ر",
"ز",
"ژ",
"س",
"ش",
"ص",
"ض",
"ط",
"ظ",
"ع",
"غ",
"ف",
"ق",
"ک",
"گ",
"ل",
"م",
"ن",
"و",
"ه",
"ی",
"آ",
]
self.NUMOFLETTERS = len(self.letters)
self.polymorph = {
"ز": ["ذ", "ض", "ظ"],
"ذ": ["ز", "ض", "ظ"],
"ض": ["ز", "ذ", "ظ"],
"ظ": ["ز", "ذ", "ض"],
"س": ["ث", "ص"],
"ث": ["س", "ص"],
"ص": ["س", "ث"],
"ط": ["ت"],
"ت": ["ط"],
"ق": ["غ"],
"غ": ["ق"],
"ه": ["ح"],
"ح": ["ه"],
}
self.keyboard_neighbor = {
"آ": "غتلدذعةأ",
"ا": "غتلدذعةأ",
"ب": "قفلیزرژأ",
"إ": "قفلیزر",
"پ": "ونتدة",
"ت": "اآعهنپد",
"ة": "اآعهنپد",
"ث": "سیقص",
"ج": "چگکح",
"چ": "جگ",
"ح": "مکجخ",
"خ": "هنمح",
"د": "اآتذپة",
"ذ": "اآلدرأ",
"ر": "لبذزإژأ",
"ز": "یبرطإ",
"ژ": "یبطر",
"س": "صثشیظطؤض",
"ش": "ضصسطظ",
"ؤ": "ضصسطظ",
"ص": "ثضیشسؤ",
"ض": "صسشؤ",
"ط": "ظسیزژشؤ",
"ظ": "طشسؤ",
"ع": "غاآتهة",
"غ": "فلاآعأ",
"ف": "قغبلإأ",
"ق": "ثفبیإ",
"ک": "گمحج",
"گ": "چجک",
"ل": "اآبإغفذر",
"أ": "اآبغفذر",
"م": "کنحخو",
"ن": "متخهوپة",
"و": "پنم",
"ه": "عختنة",
"ی": "قثبسإطزژص",
}
print("creating dictionary ...")
self.dictionary = self.__create_dictionary()
print("generating realword error files ...")
# self.__generate_realword_errors_per_token_files()
print("load homophone, keyboard, substitution realword errors ...")
self.homophone_realword_errors = self.__load_homophone_errors()
self.keyboard_realword_errors = self.__load_keyboard_errors()
self.substitution_realword_errors = self.__load_substitution_errors()
print("merging datasets ...")
# self.__merge_files(datasets, self.RAW_DATASET_DIR, True)
print("prune dataset ...")
# self.__prune_dataset()
print("generate test and train dataset ...")
self.__generate_final_dataset_test()
# self.__generate_final_dataset_test_100()
final_datasets = []
for i in range(epochs):
# self.__generate_final_dataset_train(id_=i)
# final_datasets.append(self.TRAIN_DATASET + f"final_dataset_{i}.txt")
pass
# self.__merge_files(final_datasets, self.TRAIN_FINAL_DATASET)
print("generate metadata ...")
# self.__generate_meta_datasets()
def __create_dictionary(self):
dictionary = {}
with open(self.DICTIONARY_DIR, "r", encoding="utf-8") as f:
for idx, word in enumerate(f):
dictionary[word.strip()] = idx
return dictionary
def __split(self, token):
return [char for char in token]
def __manual_replace(self, token, new_char, index):
return token[:index] + new_char + token[index + 1 :]
def __generate_keyboard_errors_per_token(self, token):
keyboard_errors = []
for index, char in enumerate(token):
neighbour_string = self.keyboard_neighbor.get(char, "")
neighbour_list = self.__split(neighbour_string)
for ch in neighbour_list:
new_token = self.__manual_replace(token, ch, index)
if new_token in self.dictionary:
keyboard_errors.append(new_token)
return keyboard_errors
def __generate_substitution_errors_per_token(self, token):
substitution_errors = []
wordLength = len(token)
for indexOfSub in range(0, wordLength - 1):
if token[indexOfSub + 1] == token[indexOfSub]:
continue
new_token = ""
idx = 0
while idx < wordLength:
if idx == indexOfSub:
new_token += token[idx + 1]
elif idx == indexOfSub + 1:
new_token += token[idx - 1]
else:
new_token += token[idx]
idx += 1
if new_token in self.dictionary:
substitution_errors.append(new_token)
return substitution_errors
def __generate_realword_errors_per_token_files(self):
with open(self.KEYBOARD_ERRORS_DIR, "w", encoding="utf-8") as f1, open(
self.SUBSTITUTION_ERRORS_DIR, "w", encoding="utf-8"
) as f2:
for i, word in enumerate(self.dictionary):
keyboard_realword_errors = self.__generate_keyboard_errors_per_token(
word.strip()
)
substitution_realword_errors = (
self.__generate_substitution_errors_per_token(word.strip())
)
line = word.strip() + " "
if len(keyboard_realword_errors) > 0:
for error in keyboard_realword_errors:
line += error + ","
f1.write(line.strip(",") + "\n")
line = word.strip() + " "
if len(substitution_realword_errors) > 0:
for error in substitution_realword_errors:
line += error + ","
f2.write(line.strip(",") + "\n")
def __is_line_in_dataset(self, line):
words = line.strip().split(" ")
for word in words:
if word not in self.dictionary:
return False
return True
def __load_homophone_errors(self):
homophone_realword_errors = {}
with open(self.HOMOPHONE_ERRORS_DIR, "r", encoding="utf-8") as f:
for line in f:
line = f.readline().strip()
word, errors = line.split(" ")
listoferrors = errors.split(",")
listoferrors.append(word)
for err in listoferrors:
temp = [x for x in listoferrors if x != err]
if err in homophone_realword_errors:
homophone_realword_errors[err] += temp
else:
homophone_realword_errors[err] = temp
return homophone_realword_errors
def __load_keyboard_errors(self):
keyboard_realword_errors = {}
with open(self.KEYBOARD_ERRORS_DIR, "r", encoding="utf-8") as f:
for line in f:
word, errors = line.strip().split(" ")
errors = errors.split(",")
if len(errors) > 0:
keyboard_realword_errors[word] = errors
return keyboard_realword_errors
def __load_substitution_errors(self):
substitution_realword_errors = {}
with open(self.SUBSTITUTION_ERRORS_DIR, "r", encoding="utf-8") as f:
for line in f:
word, errors = line.strip().split(" ")
errors = errors.split(",")
if len(errors) > 0:
substitution_realword_errors[word] = errors
return substitution_realword_errors
def __merge_files(self, sources, target, add_nextline=False):
with open(target, "w", encoding="utf-8") as target:
for src in sources:
with open(src, "r", encoding="utf-8") as source:
for line in source:
if add_nextline:
target.write(line + "\n")
else:
target.write(line)
def __prune_dataset(self):
with open(self.RAW_DATASET_DIR, "r", encoding="utf-8") as f1, open(
self.PRUNE_DATA, "w", encoding="utf-8"
) as f2:
for line in tqdm(f1):
# if re.match(".*[۱۲۳۴۵۶۷۸۹]", line) or re.match(".*[a-zA-Z0-9]", line):
# continue
line = re.sub(".*[۱۲۳۴۵۶۷۸۹]", "", line)
line = re.sub(".*[a-zA-Z0-9]", "", line)
line = re.sub(r"\(.*\)", "", line)
line = re.sub(r"-.*-", "", line)
if line.count("(") != line.count(")"):
continue
puctuations = string.punctuation + "»«؟،؛"
for p in puctuations:
if p != "(" and p != ")":
line = line.replace(p, "")
line = line.strip()
length = len(line.split())
if length < 5 or length > 256:
continue
if self.__is_line_in_dataset(line):
f2.write(line + "\n")
def __generate_keyboard_nonrealword_errors_per_line(self, li):
newLine = ""
token = ""
newToken = ""
tokens = li.split(" ")
indices = list(range(0, len(tokens)))
random.shuffle(indices)
for ind in indices:
t = tokens[ind]
if len(t) > 2:
tokenLength = len(t)
newToken = "خالی"
indexOfMisspelled = random.randrange(0, tokenLength)
indexOfAlternative = random.randrange(0, self.NUMOFLETTERS)
newToken = self.__manual_replace(
t, self.letters[indexOfAlternative], indexOfMisspelled
)
while (
newToken in self.dictionary
or t[indexOfMisspelled] == self.letters[indexOfAlternative]
):
indexOfMisspelled = random.randrange(0, tokenLength)
indexOfAlternative = random.randrange(0, self.NUMOFLETTERS)
newToken = self.__manual_replace(
t, self.letters[indexOfAlternative], indexOfMisspelled
)
token = t
tokens[ind] = newToken
newLine = " ".join(tokens)
break
return newLine, token, newToken
def __change_polymorph(self, word):
possibletokens = []
for key, value in self.polymorph.items():
if key in word:
ind = word.find(key)
wordlength = len(word)
random.shuffle(value)
newtoken = ""
for z in range(0, ind):
newtoken += word[z]
newtoken += value[0]
for z in range(ind + 1, wordlength):
newtoken += word[z]
possibletokens.append(newtoken)
random.shuffle(possibletokens)
for p in possibletokens:
if p not in self.dictionary:
return p
return False
def __has_polymorph(self, word):
for key, value in self.polymorph.items():
if key in word:
return True
return False
def __generate_polymorph_nonrealword_per_line(self, li):
newLine = ""
newToken = ""
token = ""
tokens = li.split(" ")
indices = list(range(0, len(tokens)))
random.shuffle(indices)
for ind in indices:
t = tokens[ind]
if len(t) > 2 and self.__has_polymorph(t):
newToken = self.__change_polymorph(t)
if not newToken:
continue
token = t
tokens[ind] = newToken
newLine = " ".join(tokens)
break
return newLine, token, newToken
def __check_substitution_nonrealword_errors(self, token):
possibletokens = []
tokenLength = len(token)
for indexOfSub in range(0, tokenLength - 1):
newtoken = ""
ind = 0
while ind < tokenLength:
if ind == indexOfSub:
newtoken += token[ind + 1]
elif ind == indexOfSub + 1:
newtoken += token[ind - 1]
else:
newtoken += token[ind]
ind += 1
possibletokens.append(newtoken)
random.shuffle(possibletokens)
for p in possibletokens:
if p not in self.dictionary and p != token:
return p
return False
def __generate_substitution_nonrealword_errors_per_line(self, li):
newLine = ""
newToken = ""
token = ""
tokens = li.split(" ")
indices = list(range(0, len(tokens)))
random.shuffle(indices)
for ind in indices:
t = tokens[ind]
if len(t) > 2:
newToken = self.__check_substitution_nonrealword_errors(t)
if newToken is False:
newToken = ""
continue
token = t
tokens[ind] = newToken
newLine = " ".join(tokens)
break
return newLine, token, newToken
def __generate_homophone_realword_errors_per_line(self, li, token):
possibleErrors = self.homophone_realword_errors[token]
random.shuffle(possibleErrors)
for err in possibleErrors:
if token != err:
tokens = li.split(" ")
ind = tokens.index(token)
tokens[ind] = err
replaced = " ".join(tokens)
return replaced, token, err
def __generate_keyboard_realword_errors_per_line(self, li, token):
possibleErrors = self.keyboard_realword_errors[token]
random.shuffle(possibleErrors)
for err in possibleErrors:
if token != err:
tokens = li.split(" ")
ind = tokens.index(token)
tokens[ind] = err
newLine = " ".join(tokens)
return newLine, token, err
def __generate_substitution_realword_errors_per_line(self, li, token):
possibleErrors = self.substitution_realword_errors[token]
random.shuffle(possibleErrors)
for err in possibleErrors:
if token != err:
tokens = li.split(" ")
ind = tokens.index(token)
tokens[ind] = err
newLine = " ".join(tokens)
return newLine, token, err
def __can_be_keyboard_realword_errors(self, li):
listoftokens = li.split(" ")
random.shuffle(listoftokens)
for token in listoftokens:
if len(token) > 2 and token in self.keyboard_realword_errors:
return token
return False
def __can_be_substitution_realword_errors(self, li):
listoftokens = li.split(" ")
random.shuffle(listoftokens)
for token in listoftokens:
if len(token) > 2 and token in self.substitution_realword_errors:
return token
return False
def __can_be_homophone_realword_errors(self, li):
listoftokens = li.strip().split(" ")
random.shuffle(listoftokens)
for token in listoftokens:
if len(token) > 2 and token in self.homophone_realword_errors:
return token
return False
def __generate_final_dataset_test(self):
with open(self.PRUNE_DATA, "r", encoding="utf-8") as f1, open(
self.TEST_DATASET, "w", encoding="utf-8"
) as f2:
total = 0
homophone_realword_error = 0
homophone_realword_correct = 0
substitution_realword_error = 0
substitution_realword_correct = 0
keyboard_realword_error = 0
keyboard_realword_correct = 0
keyboard_nonrealword_error = 0
polymorph_nonrealword_error = 0
substitution_nonrealword_error = 0
for line in f1:
line = line.strip()
newLine = ""
oldToken = ""
newToken = ""
type_ = ""
total += 1
can1 = self.__can_be_homophone_realword_errors(line)
if can1 is not False and random.random() < 0.8:
if random.random() < 0.5:
(
newLine,
oldToken,
newToken,
) = self.__generate_homophone_realword_errors_per_line(
line, can1
)
type_ = "homophone_realword_error"
homophone_realword_error += 1
else:
(
_,
oldToken,
newToken,
) = self.__generate_homophone_realword_errors_per_line(
line, can1
)
newLine = line
type_ = "homophone_realword_correct"
homophone_realword_correct += 1
elif random.random() <= 0.5: # real word error
can5 = self.__can_be_substitution_realword_errors(line)
can6 = self.__can_be_keyboard_realword_errors(line)
i = random.randrange(2, 4)
if i == 2 and can5 is not False:
if random.random() < 0.5 and substitution_realword_error < 5000:
(
newLine,
oldToken,
newToken,
) = self.__generate_substitution_realword_errors_per_line(
line, can5
)
type_ = "substitution_realword_error"
substitution_realword_error += 1
elif substitution_realword_correct < 5000:
(
_,
oldToken,
newToken,
) = self.__generate_substitution_realword_errors_per_line(
line, can5
)
newLine = line
type_ = "substitution_realword_correct"
substitution_realword_correct += 1
elif i == 3 and can6 is not False:
if random.random() < 0.5 and keyboard_realword_error < 5000:
(
newLine,
oldToken,
newToken,
) = self.__generate_keyboard_realword_errors_per_line(
line, can6
)
if newToken is False:
continue
type_ = "keyboard_realword_error"
keyboard_realword_error += 1
elif keyboard_realword_correct < 5000:
(
_,
oldToken,
newToken,
) = self.__generate_keyboard_realword_errors_per_line(
line, can6
)
if newToken is False:
continue
newLine = line
type_ = "keyboard_realword_correct"
keyboard_realword_correct += 1
else: # non real word error
i = random.randrange(1, 4)
if i == 1 and keyboard_nonrealword_error < 5000:
(
newLine,
oldToken,
newToken,
) = self.__generate_keyboard_nonrealword_errors_per_line(line)
type_ = "keyboard_nonrealword_error"
keyboard_nonrealword_error += 1
elif i == 2 and polymorph_nonrealword_error < 5000:
(
newLine,
oldToken,
newToken,
) = self.__generate_polymorph_nonrealword_per_line(line)
type_ = "polymorph_nonrealword_error"
polymorph_nonrealword_error += 1
elif i == 3 and substitution_nonrealword_error < 5000:
(
newLine,
oldToken,
newToken,
) = self.__generate_substitution_nonrealword_errors_per_line(
line
)
type_ = "substitution_nonrealword_error"
substitution_nonrealword_error += 1
if newLine:
f2.write(
newLine.strip()
+ "^"
+ str(type_)
+ "^"
+ str(oldToken)
+ "^"
+ str(newToken)
+ "\n"
)
print("test")
print("total", total)
print("homophone_realword_error", homophone_realword_error)
print("homophone_realword_correct", homophone_realword_correct)
print("keyboard_realword_error", keyboard_realword_error)
print("keyboard_realword_correct", keyboard_realword_correct)
print("substitution_realword_error", substitution_realword_error)
print("substitution_realword_correct", substitution_realword_correct)
print("polymorph_nonrealword_error", polymorph_nonrealword_error)
print("substitution_nonrealword_error", substitution_nonrealword_error)
print("keyboard_nonrealword_error", keyboard_nonrealword_error)
def __generate_final_dataset_train(self, id_=1):
with open(self.PRUNE_DATA, "r", encoding="utf-8") as f1, open(
self.TRAIN_DATASET + f"final_dataset_{id_}.txt", "w", encoding="utf-8"
) as f2:
c0 = 0
c1 = 0
c2 = 0
c3 = 0
c4 = 0
c5 = 0
c6 = 0
c7 = 0
for line in f1:
line = line.strip()
newLine = ""
oldToken = ""
newToken = ""
typeOfError = ""
c0 += 1
can1 = self.__can_be_homophone_realword_errors(line)
if can1 is not False and random.random() < 0.8:
(
newLine,
oldToken,
newToken,
) = self.__generate_homophone_realword_errors_per_line(line, can1)
typeOfError = "homophone_realword_error"
c1 += 1
elif random.random() <= 0.6: # No error
newLine = line
oldToken = "-"
newToken = "-"
typeOfError = "no_error"
c7 += 1
elif random.random() <= 0.5: # real word error
can5 = self.__can_be_substitution_realword_errors(line)
can6 = self.__can_be_keyboard_realword_errors(line)
i = random.randrange(2, 4)
if i == 2 and can5 is not False:
(
newLine,
oldToken,
newToken,
) = self.__generate_substitution_realword_errors_per_line(
line, can5
)
typeOfError = "substitution_realword_error"
c5 += 1
elif i == 3 and can6 is not False:
(
newLine,
oldToken,
newToken,
) = self.__generate_keyboard_realword_errors_per_line(
line, can6
)
if newToken is False:
continue
typeOfError = "keyboard_realword_error"
c6 += 1
else: # non real word error
i = random.randrange(1, 4)
if i == 1:
(
newLine,
oldToken,
newToken,
) = self.__generate_keyboard_nonrealword_errors_per_line(line)
typeOfError = "keyboard_nonrealword_error"
c2 += 1
elif i == 2:
(
newLine,
oldToken,
newToken,
) = self.__generate_polymorph_nonrealword_per_line(line)
typeOfError = "polymorph_nonrealword_error"
c3 += 1
elif i == 3:
(
newLine,
oldToken,
newToken,
) = self.__generate_substitution_nonrealword_errors_per_line(
line
)
typeOfError = "substitution_nonrealword_error"
c4 += 1
if typeOfError:
f2.write(
newLine.strip()
+ "^"
+ str(typeOfError)
+ "^"
+ str(oldToken)
+ "^"
+ str(newToken)
+ "\n"
)
print("train@epoch", id_)
print("total", c0)
print("no_error", c7)
print("homophone_realword_error", c1)
print("keyboard_nonrealword_error", c2)
print("polymorph_nonrealword_error", c3)
print("substitution_nonrealword_error", c4)
print("substitution_realword_error", c5)
print("keyboard_realword_error", c6)
def __generate_final_dataset_test_100(self):
with open(self.PRUNE_DATA, "r", encoding="utf-8") as f1, open(
self.TEST_DATASET_100, "w", encoding="utf-8"
) as f2:
c0 = 0
c1 = 0
c2 = 0
c3 = 0
c4 = 0
c5 = 0
c6 = 0
c7 = 0
for line in f1:
line = line.strip()
newLine = ""
oldToken = ""
newToken = ""
typeOfError = ""
c0 += 1
can1 = self.__can_be_homophone_realword_errors(line)
if can1 is not False and random.random() < 1 and c1 < 17:
(
newLine,
oldToken,
newToken,
) = self.__generate_homophone_realword_errors_per_line(line, can1)
typeOfError = "homophone_realword_error"
c1 += 1
elif random.random() < 0: # No error
newLine = line
oldToken = "-"
newToken = "-"
typeOfError = "no_error"
c7 += 1
elif random.random() <= 0.42: # real word error
can5 = self.__can_be_substitution_realword_errors(line)
can6 = self.__can_be_keyboard_realword_errors(line)
i = random.randrange(2, 4)
if i == 2 and can5 is not False and c5 < 17:
(
newLine,
oldToken,
newToken,
) = self.__generate_substitution_realword_errors_per_line(
line, can5
)
typeOfError = "substitution_realword_error"
c5 += 1
elif i == 3 and can6 is not False and c6 < 17:
(
newLine,
oldToken,
newToken,
) = self.__generate_keyboard_realword_errors_per_line(
line, can6
)
if newToken is False:
continue
typeOfError = "keyboard_realword_error"
c6 += 1
else: # non real word error
i = random.randrange(1, 4)
if i == 1 and c2 < 17:
(
newLine,
oldToken,
newToken,
) = self.__generate_keyboard_nonrealword_errors_per_line(line)
typeOfError = "keyboard_nonrealword_error"
c2 += 1
elif i == 2 and c3 < 16:
(
newLine,
oldToken,
newToken,
) = self.__generate_polymorph_nonrealword_per_line(line)
typeOfError = "polymorph_nonrealword_error"
c3 += 1
elif i == 3 and c4 < 16:
(
newLine,
oldToken,
newToken,
) = self.__generate_substitution_nonrealword_errors_per_line(
line
)
typeOfError = "substitution_nonrealword_error"
c4 += 1
if typeOfError != "":
f2.write(
newLine.strip()
+ "^"
+ str(typeOfError)
+ "^"
+ str(oldToken)
+ "^"
+ str(newToken)
+ "\n"
)
if (
c1 == 17
and c6 == 17
and c5 == 17
and c2 == 17
and c3 == 16
and c4 == 16
):
break
print("test_100")
print("total", c0)
print("no_error", c7)
print("homophone_realword_error", c1)
print("keyboard_nonrealword_error", c2)
print("polymorph_nonrealword_error", c3)
print("substitution_nonrealword_error", c4)
print("substitution_realword_error", c5)
print("keyboard_realword_error", c6)
def __generate_meta_datasets(self):
with open(self.TRAIN_FINAL_DATASET, "r", encoding="utf-8") as f, open(
self.CORRECT_SENTNCES, "w+", encoding="utf-8"
) as f1, open(self.METADATA, "w+", encoding="utf-8") as f2, open(
self.CORRUPTED_SENTENCES, "w+", encoding="utf-8"
) as f3, open(
self.MASKED_SENTENCES, "w+", encoding="utf-8"
) as f4:
for line in f:
tokens = line.strip().split("^")
# print(tokens[3])
f1.write(tokens[0].replace(tokens[3], tokens[2], 1) + "\n")
f2.write(tokens[1] + "," + tokens[2] + "," + tokens[3] + "\n")
f3.write(tokens[0] + "\n")
f4.write(tokens[0].replace(tokens[3], "[MASK]", 1) + "\n")
if __name__ == "__main__":
datasets = []
main_path = input("main path: ")
print("add dataset addresses, otherwise type !q")
while True:
dataset = input()
if "!q" in dataset:
break
datasets.append(dataset)
pre = Preprocess(main_path, datasets)