-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_model_bert_article.py
310 lines (246 loc) · 10.4 KB
/
test_model_bert_article.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
from polyleven import levenshtein
from happytransformer import HappyWordPrediction
import pandas as pd
from tqdm import tqdm
import os
import re
"""
Non Real-word:
base on article
Real-word:
base on article
Procedure:
base on article
article:
Y. Hu, X. Jing, Y. Ko, J. T. Rayz, Misspelling correction with pre-trained
contextual language model, in: 2020 ieee 19th international conference
on cognitive informatics cognitive computing (icci* cc), IEEE, pp. 144–149
"""
class TestModel:
def __init__(
self,
main_path="/mnt/disk1/users/naziri",
model_path="HooshvareLab/bert-base-parsbert-uncased",
output_file_name="result",
version=2
):
self.version = version
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.FINAL_DATASET_DIR = (
main_path + "/train test datasets/test/final_dataset_v2.txt"
)
self.OUTPUT_FILE_DIR = (
main_path + "/evaluation results/" + output_file_name + ".csv"
)
print("creating dictionary ...")
self.dictionary = self.__create_dictionary()
print("load homophone, keyboard, substitution realword errors ...")
total_realword_errors = self.__load_homophone_errors({})
total_realword_errors = self.__load_keyboard_errors(total_realword_errors)
self.realword_errors = self.__load_substitution_errors(total_realword_errors)
print("load model ...")
self.model = HappyWordPrediction("BERT", load_path=model_path)
print("evaluation ...")
self.__evaluate()
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 __load_homophone_errors(self, total_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 total_realword_errors:
total_realword_errors[err] += temp
total_realword_errors[err] = list(
set(total_realword_errors[err])
)
else:
total_realword_errors[err] = temp
total_realword_errors[err] = list(
set(total_realword_errors[err])
)
return total_realword_errors
def __load_keyboard_errors(self, total_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:
if word in total_realword_errors:
total_realword_errors[word] += errors
total_realword_errors[word] = list(
set(total_realword_errors[word])
)
else:
total_realword_errors[word] = errors
total_realword_errors[word] = list(
set(total_realword_errors[word])
)
return total_realword_errors
def __load_substitution_errors(self, total_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:
if word in total_realword_errors:
total_realword_errors[word] += errors
total_realword_errors[word] = list(
set(total_realword_errors[word])
)
else:
total_realword_errors[word] = errors
total_realword_errors[word] = list(
set(total_realword_errors[word])
)
return total_realword_errors
def __get_most_similar_token_levenshtein(self, target_word):
def find(myList):
for element in myList:
if element.get("score") > 2:
return myList.index(element)
return len(myList)
list_of_similars = []
for word in self.dictionary:
score = levenshtein(word, target_word)
# freq = word_frequency(word, 'fa')
list_of_similars.append({"word": word, "score": score})
list_of_similars.sort(key=lambda x: x["score"])
indUntil2 = find(list_of_similars)
list_of_similars = list_of_similars[0:indUntil2]
return list_of_similars
def __get_most_similar_token_mix(
self, sentence, target_word, N=500
):
most_levenshtein_score = None
most_similar_word = ""
most_bert_score = 0
if self.version == 2:
targets = self.__get_most_similar_token_levenshtein(target_word)
results = self.model.predict_mask(
sentence.strip(),
targets=[i["word"] for i in targets],
top_k=len(targets),
)
for result in results:
levenshtein_score = levenshtein(result.token, target_word)
if most_bert_score < result.score:
most_levenshtein_score = levenshtein_score
most_bert_score = result.score
most_similar_word = result.token
return most_similar_word, (most_levenshtein_score, most_bert_score)
else:
results = self.model.predict_mask(
sentence.strip(),
top_k=N,
)
for result in results:
levenshtein_score = levenshtein(result.token, target_word)
if most_levenshtein_score == None or (
levenshtein_score < most_levenshtein_score
):
most_levenshtein_score = levenshtein_score
most_bert_score = result.score
most_similar_word = result.token
return most_similar_word, (most_levenshtein_score, most_bert_score)
def __check_sentence(self, sentence, candidate_word):
tokens = sentence.split()
ind = tokens.index(candidate_word)
tokens[ind] = "[MASK]"
detect_is_realword = None
### RealWord
if candidate_word in self.realword_errors:
possiblewords = self.realword_errors[candidate_word]
possiblewords.append(candidate_word)
possiblewords = list(set(possiblewords))
masked_sentence = " ".join(tokens)
(
most_similar_word_mix,
most_score_mix,
) = self.__get_most_similar_token_mix(
masked_sentence,
candidate_word,
)
detect_is_realword = True
### NonRealWord
elif candidate_word not in self.dictionary:
masked_sentence = " ".join(tokens)
(
most_similar_word_mix,
most_score_mix,
) = self.__get_most_similar_token_mix(masked_sentence, candidate_word)
detect_is_realword = False
return pd.DataFrame(
{
"sentence": [sentence],
"is_realword": [detect_is_realword],
"mix_word": [most_similar_word_mix],
"mix_levenshtein_score": [most_score_mix[0]],
"mix_bert_score": [most_score_mix[1]],
}
)
def __evaluate(self):
final_df = None
with open(self.FINAL_DATASET_DIR, "r", encoding="utf-8") as f:
for line in tqdm(f):
(
sentence,
type_,
correct_word,
misspelled_word,
) = line.strip().split("^")
if "correct" in type_:
candidate_word = correct_word
else:
candidate_word = misspelled_word
print(type_)
df = self.__check_sentence(sentence, candidate_word)
os.system("clear")
df["type"] = type_
if "correct" in type_:
df["correct_word"] = correct_word
df["candidate_word"] = correct_word
else:
df["correct_word"] = correct_word
df["candidate_word"] = misspelled_word
if final_df is not None:
final_df = pd.concat([final_df, df], axis=0).copy()
final_df = final_df.reset_index(drop=True)
else:
final_df = df.copy()
final_df.to_csv(self.OUTPUT_FILE_DIR)
if __name__ == "__main__":
main_path = input("main path: ")
model_path = input("model path, otherwise for default click space: ")
output_file_name = input("output file name, otherwise for default click space: ")
version = int(input("version: "))
if model_path and output_file_name:
tm = TestModel(
main_path=main_path,
model_path=model_path,
output_file_name=output_file_name,
version=version
)
elif model_path:
tm = TestModel(main_path=main_path, model_path=model_path, version=version)
elif output_file_name:
tm = TestModel(main_path=main_path, output_file_name=output_file_name, version=version)
else:
tm = TestModel(main_path=main_path, version=version)