-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict.py
More file actions
204 lines (186 loc) · 8.15 KB
/
predict.py
File metadata and controls
204 lines (186 loc) · 8.15 KB
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
import argparse
from utils.helpers import read_lines
from gector.gec_model import GecBERTModel
from tqdm import tqdm
import re
def predict_for_file(
input_file,
output_file,
model,
batch_size=32,
split_chunk=False,
chunk_size=32,
overlap_size=8,
min_words_cut=4
):
test_data = read_lines(input_file)
predictions = []
cnt_corrections = 0
batch = []
for sent in tqdm(test_data):
batch.append(sent.split())
if len(batch) == batch_size:
if split_chunk:
batch, batch_indices = split_chunks(batch, chunk_size, overlap_size)
preds, cnt = model.handle_batch(batch)
preds = merge_chunk([" ".join(x) for x in preds], batch_indices, overlap_size, min_words_cut)
else:
preds, cnt = model.handle_batch(batch)
preds = [" ".join(x) for x in preds]
predictions.extend(preds)
cnt_corrections += cnt
batch = []
if batch:
if split_chunk:
batch, batch_indices = split_chunks(batch, chunk_size, overlap_size)
preds, cnt = model.handle_batch(batch)
preds = merge_chunk([" ".join(x) for x in preds], batch_indices, overlap_size, min_words_cut)
else:
preds, cnt = model.handle_batch(batch)
preds = [" ".join(x) for x in preds]
predictions.extend(preds)
cnt_corrections += cnt
with open(output_file, 'w') as f:
f.write("\n".join(predictions) + '\n')
return cnt_corrections
def split_chunks(batch, chunk_size=32, overlap_size=8):
# return batch pairs of indices
stride = chunk_size - overlap_size
result = []
indices = []
for tokens in batch:
start = len(result)
num_token = len(tokens)
if num_token <= overlap_size:
result.append(tokens)
for i in range(0, num_token - overlap_size, stride):
result.append(tokens[i: i + chunk_size])
indices.append((start, len(result)))
return result, indices
def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4):
head = overlap_size - min_words_cut
tail = min_words_cut
result = []
for (start, end) in indices:
tokens = []
for i in range(start, end):
try:
sub_text = batch[i].strip()
sub_text = re.sub(r'([\.\,\?\:]\s+)+', r'\1', sub_text)
sub_text = re.sub(r'\s+([\.\,\?\:])', r'\1', sub_text)
sub_tokens = sub_text.split()
if i == start:
if i == end - 1:
tokens = sub_tokens
else:
tokens.extend(sub_tokens[:-tail])
elif i == end - 1:
tokens.extend(sub_tokens[head:])
else:
tokens.extend(sub_tokens[head:-tail])
except Exception as e:
print(e)
text = " ".join(tokens)
text = re.sub(r'([\,\.\?\:])', r' \1', text)
result.append(text)
return result
def main(args):
# get all paths
model = GecBERTModel(vocab_path=args.vocab_path,
model_paths=args.model_path,
max_len=args.max_len, min_len=args.min_len,
iterations=args.iteration_count,
min_error_probability=args.min_error_probability,
lowercase_tokens=args.lowercase_tokens,
model_name=args.transformer_model,
special_tokens_fix=args.special_tokens_fix,
log=False,
confidence=args.additional_confidence,
is_ensemble=args.is_ensemble,
weigths=args.weights)
cnt_corrections = predict_for_file(args.input_file, args.output_file, model,
batch_size=args.batch_size, split_chunk=args.split_chunk,
chunk_size=args.chunk_size, overlap_size=args.overlap_size,
min_words_cut=args.min_words_cut)
# evaluate with m2 or ERRANT
print(f"Produced overall corrections: {cnt_corrections}")
if __name__ == '__main__':
# read parameters
parser = argparse.ArgumentParser()
parser.add_argument('--model_path',
help='Path to the model file.', nargs='+',
required=True)
parser.add_argument('--vocab_path',
help='Path to the model file.',
default='data/output_vocabulary' # to use pretrained models
)
parser.add_argument('--input_file',
help='Path to the evalset file',
required=True)
parser.add_argument('--output_file',
help='Path to the output file',
required=True)
parser.add_argument('--max_len',
type=int,
help='The max sentence length'
'(all longer will be truncated)',
default=64)
parser.add_argument('--min_len',
type=int,
help='The minimum sentence length'
'(all longer will be returned w/o changes)',
default=3)
parser.add_argument('--batch_size',
type=int,
help='The size of hidden unit cell.',
default=128)
parser.add_argument('--lowercase_tokens',
action='store_true',
help='Whether to lowercase tokens.',)
parser.add_argument('--transformer_model',
choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert'
'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base',
'vinai/phobert-large', 'xlm-roberta-base'],
help='Name of the transformer model.',
default='roberta')
parser.add_argument('--iteration_count',
type=int,
help='The number of iterations of the model.',
default=5)
parser.add_argument('--additional_confidence',
type=float,
help='How many probability to add to $KEEP token.',
default=0)
parser.add_argument('--min_error_probability',
type=float,
help='Minimum probability for each action to apply. '
'Also, minimum error probability, as described in the paper.',
default=0.0)
parser.add_argument('--special_tokens_fix',
type=int,
help='Whether to fix problem with [CLS], [SEP] tokens tokenization. '
'For reproducing reported results it should be 0 for BERT/XLNet and 1 for RoBERTa.',
default=1)
parser.add_argument('--is_ensemble',
action='store_true',
help='Whether to do ensembling.',)
parser.add_argument('--weights',
help='Used to calculate weighted average', nargs='+',
default=None)
parser.add_argument('--split_chunk',
action='store_true',
help='Whether to use chunk merging or not')
parser.add_argument('--chunk_size',
type=int,
help='Chunk size for chunk merging',
default=32)
parser.add_argument('--overlap_size',
type=int,
help='Overlapped words between two continuous chunks',
default=8)
parser.add_argument('--min_words_cut',
type=int,
help='number of words at the end the first chunk to be removed during merge',
default=4)
args = parser.parse_args()
main(args)