-
Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathdemo_imgs.py
237 lines (205 loc) · 8.56 KB
/
demo_imgs.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
import os
import time
import string
import torch
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.nn.functional as F
import numpy as np
from utils import Averager, TokenLabelConverter
from dataset import hierarchical_dataset, AlignCollateTest, RawDataset
from models import LevOCRModel
from utils import get_args
from levt import utils as utils_levt
from levt.dictionary import Dictionary
from abinet.utils import CharsetMapper
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def generate(
model,
vision_final_pred,
img_feature,
batch_size,
pad,
eos_penalty=0.0,
max_iter=10,
max_ratio=2,
decoding_format=None,
retain_history=True
):
bsz = batch_size
prev_decoder_out = model.module.levt.initialize_output_tokens(vision_final_pred)
prev_output_tokens = prev_decoder_out.output_tokens.clone()
sent_idxs = torch.arange(bsz)
finalized = [[] for _ in range(bsz)]
def finalized_preds(step, prev_out_token, prev_out_score, prev_out_attn):
cutoff = prev_out_token.ne(pad)
tokens = prev_out_token[cutoff]
if prev_out_score is None:
scores, score = None, None
else:
scores = prev_out_score[cutoff]
score = scores.mean()
if prev_out_attn is None:
hypo_attn, alignment = None, None
else:
hypo_attn = prev_out_attn[cutoff]
alignment = hypo_attn.max(dim=1)[1]
return {
"steps": step,
"tokens": tokens,
"positional_scores": scores,
"score": score,
"hypo_attn": hypo_attn,
"alignment": alignment,
}
for step in range(max_iter + 1):
decoder_options = {
"eos_penalty": eos_penalty,
"max_ratio": max_ratio,
"decoding_format": decoding_format,
}
prev_decoder_out = prev_decoder_out._replace(
step=step,
max_step=max_iter + 1,
)
decoder_out = model.module.levt.forward_decoder(
prev_decoder_out, img_feature, **decoder_options
)
# collect finalized sentences
finalized_tokens = decoder_out.output_tokens
finalized_scores = decoder_out.output_scores
finalized_attn = (
None
if (decoder_out.attn is None or decoder_out.attn.size(0) == 0)
else decoder_out.attn
)
finalized_history_tokens = decoder_out.history
for i in range(bsz):
finalized[i] = [
finalized_preds(
step,
finalized_tokens[i],
finalized_scores[i],
None if finalized_attn is None else finalized_attn[i],
)
]
finalized[i][0]["history"] = []
for j in range(len(finalized_history_tokens)):
finalized[i][0]["history"].append(
finalized_preds(
step, finalized_history_tokens[j][i], None, None
)
)
# for next step
prev_decoder_out = decoder_out._replace(
output_tokens=decoder_out.output_tokens,
output_scores=decoder_out.output_scores,
attn=decoder_out.attn
if (decoder_out.attn is not None and decoder_out.attn.size(0) > 0)
else None,
history=decoder_out.history
if decoder_out.history is not None
else None,
)
prev_output_tokens = prev_decoder_out.output_tokens.clone()
return finalized
def test(opt):
opt.eval = True
""" model configuration """
charset = CharsetMapper(opt.dataset_charset_path, max_length=opt.batch_max_length)
opt.num_class = charset.num_classes
print('num_class:', opt.num_class)
indices = charset.char_to_label
src_dict = utils_levt.build_dict(indices)
converter = TokenLabelConverter(src_dict.indices)
opt.num_class = len(converter.character)
if opt.rgb:
opt.input_channel = 3
model = LevOCRModel(opt, src_dict)
model = torch.nn.DataParallel(model).to(device)
model = model.to(device)
# load model
print('loading pretrained model from %s' % opt.saved_model)
model.load_state_dict(torch.load(opt.saved_model, map_location=device))
opt.exp_name = '_'.join(opt.saved_model.split('/')[1:])
# print(model)
""" keep evaluation model and result logs """
os.makedirs(f'./result/{opt.exp_name}', exist_ok=True)
os.system(f'cp {opt.saved_model} ./result/{opt.exp_name}/')
AlignCollate_demo = AlignCollateTest(imgH=opt.imgH, imgW=opt.imgW)
demo_data = RawDataset(root=opt.demo_imgs, opt=opt) # use RawDataset
demo_loader = torch.utils.data.DataLoader(
demo_data, batch_size=opt.batch_size,
shuffle=False,
num_workers=int(opt.workers),
collate_fn=AlignCollate_demo, pin_memory=True)
""" evaluation """
model.eval()
with torch.no_grad():
for image_tensors, image_path_list in demo_loader:
batch_size = image_tensors.size(0)
image = image_tensors.to(device)
out = model.module.vision(image)
pred_logit = out['logits']
features = out['features']
pred_vision = F.log_softmax(pred_logit, dim=-1)
pred_vision_max = pred_vision.max(2)[1]
vision_preds_size = torch.IntTensor([pred_logit.size(1)] * batch_size)
vision_preds_str = converter.decode(pred_vision_max, vision_preds_size, ignore_spec_char=True)
vision_final_pred, _ = converter.encode_levt(vision_preds_str, src_dict, device=device, batch_max_length=pred_vision.size(1))
img_feature_new = model.module.extract_img_feature(features)
preds = generate(model, vision_final_pred, img_feature_new, batch_size, src_dict.pad(), max_iter=int(opt.max_iter))
for i in range(batch_size):
print('=======================================')
print(image_path_list[i])
vision_str = vision_preds_str[i]
for j, hypo in enumerate(preds[i]):
hypo_tokens, hypo_str, alignment = utils_levt.post_process_prediction(
hypo_tokens=hypo["tokens"].int().cpu(),
src_str=vision_str,
alignment=hypo["alignment"],
align_dict=None,
tgt_dict=src_dict,
remove_bpe=opt.post_process,
extra_symbols_to_ignore={src_dict.eos()}
)
hypo_str = hypo_str.replace(" ", "")
hypo_str = hypo_str.replace(",", "")
# print history
print("Visual Prediction:", vision_str)
historys = hypo["history"]
his_result = []
for i,history in enumerate(historys):
step_ = history["steps"]
_, his_str, _ = utils_levt.post_process_prediction(
hypo_tokens=history["tokens"].int().cpu(),
src_str=vision_str,
alignment=history["alignment"],
align_dict=None,
tgt_dict=src_dict,
remove_bpe=opt.post_process,
extra_symbols_to_ignore={src_dict.eos()}
)
his_str = his_str.replace(" ", "")
his_result.append(his_str)
his_result_str = ""
iteration = 0
for index_ in range(0, len(his_result), 3):
iteration += 1
tmp = 'Iteration{}:Del-Plh-Ins {}-{}-{}'.format(str(iteration), his_result[index_], his_result[index_+1], his_result[index_+2])
if his_result_str == '':
his_result_str = tmp
else:
his_result_str += '\n'
his_result_str += tmp
print(his_result_str)
if __name__ == '__main__':
opt = get_args(is_train=False)
""" vocab / character number configuration """
if opt.sensitive:
opt.character = string.printable[:-6] # same with ASTER setting (use 94 char).
cudnn.benchmark = True
cudnn.deterministic = True
opt.num_gpu = torch.cuda.device_count()
opt.saved_model = opt.model_dir
test(opt)