Update main.py
Browse files
main.py
CHANGED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import caption_model
|
3 |
+
from transformers import BertTokenizer
|
4 |
+
import torchvision
|
5 |
+
from PIL import Image
|
6 |
+
from configuration import Config
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
def under_max(image):
|
10 |
+
if image.mode != 'RGB':
|
11 |
+
image = image.convert("RGB")
|
12 |
+
|
13 |
+
shape = np.array(image.size, dtype=np.float)
|
14 |
+
long_dim = max(shape)
|
15 |
+
scale = 299 / long_dim
|
16 |
+
|
17 |
+
new_shape = (shape * scale).astype(int)
|
18 |
+
image = image.resize(new_shape)
|
19 |
+
|
20 |
+
return image
|
21 |
+
|
22 |
+
class Model(object):
|
23 |
+
def __init__(self, gpu=0):
|
24 |
+
config = Config()
|
25 |
+
config.device = 'cuda:{}'.format(gpu)
|
26 |
+
model, _ = caption_model.build_model(config)
|
27 |
+
checkpoint = torch.load('./checkpoint.pth', map_location='cpu')
|
28 |
+
model.load_state_dict(checkpoint['model'])
|
29 |
+
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
30 |
+
start_token = tokenizer.convert_tokens_to_ids(tokenizer._cls_token)
|
31 |
+
end_token = tokenizer.convert_tokens_to_ids(tokenizer._sep_token)
|
32 |
+
|
33 |
+
self.caption = torch.zeros((1, config.max_position_embeddings), dtype=torch.long).to(config.device)
|
34 |
+
self.cap_mask = torch.ones((1, config.max_position_embeddings), dtype=torch.bool).to(config.device)
|
35 |
+
|
36 |
+
self.caption[:, 0] = start_token
|
37 |
+
self.cap_mask[:, 0] = False
|
38 |
+
|
39 |
+
self.val_transform = torchvision.transforms.Compose([
|
40 |
+
torchvision.transforms.Lambda(under_max),
|
41 |
+
torchvision.transforms.ToTensor(),
|
42 |
+
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
|
43 |
+
])
|
44 |
+
model.to(config.device)
|
45 |
+
self.model = model
|
46 |
+
self.config = config
|
47 |
+
self.tokenizer = tokenizer
|
48 |
+
|
49 |
+
def evaluate(self, im):
|
50 |
+
self.model.eval()
|
51 |
+
for i in range(self.config.max_position_embeddings - 1):
|
52 |
+
predictions = self.model(im.to(self.config.device), self.caption.to(self.config.device), self.cap_mask.to(self.config.device))
|
53 |
+
predictions = predictions[:, i, :]
|
54 |
+
predicted_id = torch.argmax(predictions, axis=-1).to(self.config.device)
|
55 |
+
|
56 |
+
if predicted_id[0] == 102:
|
57 |
+
return self.caption
|
58 |
+
|
59 |
+
self.caption[:, i+1] = predicted_id[0]
|
60 |
+
self.cap_mask[:, i+1] = False
|
61 |
+
return caption
|
62 |
+
|
63 |
+
def predict(self, image_path):
|
64 |
+
image = Image.open(image_path)
|
65 |
+
image = self.val_transform(image)
|
66 |
+
image = image.unsqueeze(0)
|
67 |
+
output = self.evaluate(image)
|
68 |
+
return self.tokenizer.decode(output[0].tolist(), skip_special_tokens=True)
|
69 |
+
|
70 |
+
if __name__ == "__main__":
|
71 |
+
model = Model()
|
72 |
+
result = model.predict("./image.jpg")
|
73 |
+
print(result)
|
74 |
+
|