-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
329 lines (253 loc) · 9.98 KB
/
main.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
import json
import os.path
import re
import time
import errant
import pandas as pd
import torch
from annotated_text import annotated_text
from bs4 import BeautifulSoup
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from gramformer import Gramformer
from pydantic import BaseModel
from transformers import AutoModelForSeq2SeqLM
from transformers import AutoTokenizer
import datetime
annotator = errant.load('en')
PATH = os.path.abspath('models/gf.pth')
print("Loading models...")
app = FastAPI()
class Sentences(BaseModel):
sentences: list
origins = [
'https://8249-218-2-231-114.jp.ngrok.io/',
"http://localhost",
"http://localhost:3000",
"http://127.0.0.1:8000",
"https://trans-grammer-frontend.vercel.app/"
]
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
device = "cpu"
correction_model_tag = "prithivida/grammar_error_correcter_v1"
correction_tokenizer = AutoTokenizer.from_pretrained(correction_model_tag)
correction_model = AutoModelForSeq2SeqLM.from_pretrained(correction_model_tag)
influent_sentences = [
"I is dog."
]
def set_seed(seed):
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
print("Models loaded !")
gf = Gramformer(models=1, use_gpu=False) # 1=corrector, 2=detector
try:
torch.save(gf, PATH)
gf_inference = torch.load(PATH)
except:
print('Torch Save Error')
@app.get("/")
def read_root():
return {"Gramformer !"}
# @app.get("/{correct}")
# def get_correction(input_sentence):
# set_seed(1212)
# scored_corrected_sentence = correct(input_sentence)
# return {"scored_corrected_sentence": scored_corrected_sentence}
@app.post("/sentence")
def get_corrected_sentence(sentences: Sentences):
sentence_list = sentences.sentences
# print(sentence_list)
set_seed(1212)
scored_corrected_sentence = correct_sentence(sentence_list)
sent_list = list(scored_corrected_sentence)
highlighted_sentences = show_highlights(sentence_list[0], sent_list[0])
return json.dumps({'corrected_sentence': highlighted_sentences})
def correct_sentence(input_sentence):
for influent_sentence in input_sentence:
"""
Correct influent_sentences
"""
corrected_sentences = gf.correct(influent_sentence, max_candidates=3)
# print("[Input] ", influent_sentence)
# for corrected_sentence in corrected_sentences:
# print("[Correction] ",corrected_sentence)
# print("[Edits] ", gf.highlight(influent_sentence, corrected_sentence))
return corrected_sentences
def correct(input_sentence, max_candidates=1):
correction_prefix = "gec: "
input_sentence = correction_prefix + input_sentence
input_ids = correction_tokenizer.encode(input_sentence, return_tensors='pt')
input_ids = input_ids.to(device)
preds = correction_model.generate(
input_ids,
do_sample=True,
max_length=128,
top_k=50,
top_p=0.95,
# num_beams=7,
early_stopping=True,
num_return_sequences=max_candidates)
corrected = set()
for pred in preds:
corrected.add(correction_tokenizer.decode(pred, skip_special_tokens=True).strip())
corrected = list(corrected)
return (corrected[0], 0) # Corrected Sentence, Dummy score
def show_highlights(input_text, corrected_sentence):
try:
strikeout = lambda x: '\u0336'.join(x) + '\u0336'
highlight_text = highlight(input_text, corrected_sentence)
color_map = {'d': '#faa', 'a': '#afa', 'span': '#fea'}
tokens = re.split(r'(<[das]\s.*?<\/[das]>)', highlight_text)
# print(tokens)
annotations = [] # ['Sorry i ', ('forgot', 'VERB:TENSE', '#fea'), ' how to write. ', ('Tomorrow', 'SPELL', '#fea'), ' i ', ('remember.', 'VERB', '#fea'), '']
for token in tokens:
soup = BeautifulSoup(token, 'html.parser')
tags = soup.findAll()
if tags:
_tag = tags[0].name
_type = tags[0]['type']
_text = tags[0]['edit']
_desc = tags[0]['desc']
_color = color_map[_tag]
if _tag == 'd':
_text = strikeout(tags[0].text)
annotations.append((_text, _type, _desc))
else:
annotations.append(token)
annotated_text(*annotations)
print(highlight_text)
return highlight_text
except Exception as e:
print('Some error occured!' + str(e))
def show_edits(input_text, corrected_sentence):
try:
edits = get_edits(input_text, corrected_sentence)
df = pd.DataFrame(edits, columns=['type', 'original word', 'original start', 'original end', 'correct word',
'correct start', 'correct end'])
df = df.set_index('type')
except Exception as e:
print('Some error occured!' + str(e))
def description(orig, edit, edit_type):
descriptions = {
"DET": 'The article %s may be incorrect. You may consider changing it to agree with the beginning sound of the following word and use %s' % (
orig, edit),
"NOUN": 'Consider changing %s to %s' % (
orig, edit),
"SPELL": 'The word %s is wrongly spelt. Correct it to %s' % (
orig, edit),
"PUNCT": 'The article %s may be incorrect. You may consider changing it to agree with the beginning sound of the following word and use %s' % (
orig, edit),
"OTHER": 'Consider changing %s to %s' % (
orig, edit),
"ORTH": '%s may be incorrect. Consider changing to %s' % (
orig, edit),
"VERB:FORM": 'The verb %s may be incorrect. Consider changing to %s' % (
orig, edit),
"NOUN:NUM": '%s may not agree in number with other words in this phrase. Consider changing to %s' % (
orig, edit),
"VERB:TENSE": 'The verb tense %s may be incorrect. Consider changing to %s' % (
orig, edit),
"VERB:SVA": 'The verb %s may be incorrect. Consider changing to %s' % (
orig, edit),
}
desc = descriptions[edit_type]
return desc
def highlight(orig, cor):
edits = _get_edits(orig, cor)
orig_tokens = orig.split()
ignore_indexes = []
for edit in edits:
edit_type = edit[0]
edit_str_start = edit[1]
edit_spos = edit[2]
edit_epos = edit[3]
edit_str_end = edit[4]
# if no_of_tokens(edit_str_start) > 1 ==> excluding the first token, mark all other tokens for deletion
for i in range(edit_spos + 1, edit_epos):
ignore_indexes.append(i)
if edit_str_start == "":
if edit_spos - 1 >= 0:
new_edit_str = orig_tokens[edit_spos - 1]
edit_spos -= 1
else:
new_edit_str = orig_tokens[edit_spos + 1]
edit_spos += 1
if edit_type == "PUNCT":
timestamp = str(datetime.datetime.timestamp(datetime.datetime.now())).replace('.', '-') + edit_type
st = "<a id=" + timestamp + " " + "type='" + edit_type + "' edit='" + \
edit_str_end + "'>" + new_edit_str + "</a>"
else:
timestamp = str(datetime.datetime.timestamp(datetime.datetime.now())).replace('.', '-') + edit_type
st = "<a id=" + timestamp + " " + "type='" + edit_type + "' edit='" + new_edit_str + \
" " + edit_str_end + "'>" + new_edit_str + "</a>"
orig_tokens[edit_spos] = st
elif edit_str_end == "":
timestamp = str(datetime.datetime.timestamp(datetime.datetime.now())).replace('.', '-') + edit_type
st = "<d id=" + timestamp + " " + "type='" + edit_type + "' edit=''>" + edit_str_start + "</d>"
orig_tokens[edit_spos] = st
else:
timestamp = str(datetime.datetime.timestamp(datetime.datetime.now())).replace('.', '-') + edit_type
edit_desc = description(edit_str_start, edit_str_end, edit_type)
st = "<span id=" + timestamp + " type='" + edit_type + "' desc='" + edit_desc + "' edit='" + \
str(edit_str_end) + "'>" + edit_str_start + "</span>"
orig_tokens[edit_spos] = st
for i in sorted(ignore_indexes, reverse=True):
print(i)
del (orig_tokens[i])
return (" ".join(orig_tokens))
def _get_edits(orig, cor):
orig = annotator.parse(orig)
cor = annotator.parse(cor)
alignment = annotator.align(orig, cor)
edits = annotator.merge(alignment)
if len(edits) == 0:
return []
edit_annotations = []
for e in edits:
e = annotator.classify(e)
edit_annotations.append((e.type[2:], e.o_str, e.o_start, e.o_end, e.c_str, e.c_start, e.c_end))
if len(edit_annotations) > 0:
return edit_annotations
else:
return []
def get_edits(orig, cor):
return _get_edits(orig, cor)
# def set_seed(seed):
# torch.manual_seed(seed)
# if torch.cuda.is_available():
# torch.cuda.manual_seed_all(seed)
#
# set_seed(1212)
#
#
# gf = Gramformer(models = 1, use_gpu=False) # 1=corrector, 2=detector
#
#
#
# influent_sentences = [
# "He are moving here.",
# "I am doing fine. How is you?",
# "How is they?",
# "Matt like fish",
# "the collection of letters was original used by the ancient Romans",
# "We enjoys horror movies",
# "Anna and Mike is going skiing",
# "I walk to the store and I bought milk",
# " We all eat the fish and then made dessert",
# "I will eat fish for dinner and drink milk",
# "what be the reason for everyone leave the company",
# ]
#
# for influent_sentence in influent_sentences:
# corrected_sentences = gf.correct(influent_sentence, max_candidates=1)
# print("[Input] ", influent_sentence)
# for corrected_sentence in corrected_sentences:
# print("[Correction] ",corrected_sentence)
# print("-" *100)