-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.py
135 lines (124 loc) · 4.45 KB
/
demo.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
"""
Small script for testing on few generic images given the model weights.
In order to minimize the requirements, it runs only on CPU and images are
processed one by one.
"""
import torch
import argparse
import pickle
from argparse import Namespace
from models.End_ExpansionNet_v2 import End_ExpansionNet_v2
from utils.image_utils import preprocess_image
from utils.language_utils import tokens2description
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Demo")
parser.add_argument("--model_dim", type=int, default=512)
parser.add_argument("--N_enc", type=int, default=3)
parser.add_argument("--N_dec", type=int, default=3)
parser.add_argument("--max_seq_len", type=int, default=74)
parser.add_argument(
"--load_path",
type=str,
default="/home/arpitsah/Desktop/Fall-2023/odml/On_Device_Image_Captioning/pretrained_weights/rf_model.pth",
)
parser.add_argument(
"--load_path_vizWiz",
type=str,
default="/home/arpitsah/Desktop/Fall-2023/odml/On_Device_Image_Captioning/vizWiz_Weights/pretrained_weightscheckpoint_2023-10-10-16:26:11_epoch4it1968bs8_xe_.pth",
)
parser.add_argument(
"--image_paths",
type=str,
default=[
"On_Device_Image_Captioning/demo_material/tatin.jpg",
"On_Device_Image_Captioning/demo_material/micheal.jpg",
"On_Device_Image_Captioning/demo_material/napoleon.jpg",
"On_Device_Image_Captioning/demo_material/cat_girl.jpg",
],
nargs="+",
)
parser.add_argument("--beam_size", type=int, default=5)
parser.add_argument("--Vizwiz", type=bool, default=False)
args = parser.parse_args()
drop_args = Namespace(enc=0.0, dec=0.0, enc_input=0.0, dec_input=0.0, other=0.0)
model_args = Namespace(
model_dim=args.model_dim,
N_enc=args.N_enc,
N_dec=args.N_dec,
dropout=0.0,
drop_args=drop_args,
)
with open(
"/home/arpitsah/Desktop/Fall-2023/odml/On_Device_Image_Captioning/demo_material/demo_coco_tokens.pickle",
"rb",
) as f:
coco_tokens = pickle.load(f)
sos_idx = coco_tokens["word2idx_dict"][coco_tokens["sos_str"]]
eos_idx = coco_tokens["word2idx_dict"][coco_tokens["eos_str"]]
print("Dictionary loaded ...")
img_size = 384
model = End_ExpansionNet_v2(
swin_img_size=img_size,
swin_patch_size=4,
swin_in_chans=3,
swin_embed_dim=192,
swin_depths=[2, 2, 18, 2],
swin_num_heads=[6, 12, 24, 48],
swin_window_size=12,
swin_mlp_ratio=4.0,
swin_qkv_bias=True,
swin_qk_scale=None,
swin_drop_rate=0.0,
swin_attn_drop_rate=0.0,
swin_drop_path_rate=0.0,
swin_norm_layer=torch.nn.LayerNorm,
swin_ape=False,
swin_patch_norm=True,
swin_use_checkpoint=False,
final_swin_dim=1536,
d_model=model_args.model_dim,
N_enc=model_args.N_enc,
N_dec=model_args.N_dec,
num_heads=8,
ff=2048,
num_exp_enc_list=[32, 64, 128, 256, 512],
num_exp_dec=16,
output_word2idx=coco_tokens["word2idx_dict"],
output_idx2word=coco_tokens["idx2word_list"],
max_seq_len=args.max_seq_len,
drop_args=model_args.drop_args,
rank="cpu",
)
if not args.Vizwiz:
checkpoint = torch.load(args.load_path)
else:
checkpoint = torch.load(args.load_path_vizWiz)
model.load_state_dict(checkpoint["model_state_dict"])
print("Model loaded ...")
input_images = []
for path in args.image_paths:
input_images.append(preprocess_image(path, img_size))
print("Generating captions ...\n")
for i in range(len(input_images)):
path = args.image_paths[i]
image = input_images[i]
beam_search_kwargs = {
"beam_size": args.beam_size,
"beam_max_seq_len": args.max_seq_len,
"sample_or_max": "max",
"how_many_outputs": 1,
"sos_idx": sos_idx,
"eos_idx": eos_idx,
}
with torch.no_grad():
pred, _ = model(
enc_x=image,
enc_x_num_pads=[0],
mode="beam_search",
**beam_search_kwargs
)
pred = tokens2description(
pred[0][0], coco_tokens["idx2word_list"], sos_idx, eos_idx
)
print(path + " \n\tDescription: " + pred + "\n")
print("Closed.")