-
Notifications
You must be signed in to change notification settings - Fork 42
/
demo.py
184 lines (129 loc) · 5.12 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
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
#!/usr/bin/env python
# coding: utf-8
# ## Inverse Cooking: Recipe Generation from Food Images
import torch
import os
from src.args import get_parser
import pickle
from src.model import get_model
from torchvision import transforms
from src.utils.output_utils import prepare_output
from PIL import Image
import time
import sys
import requests
from io import BytesIO
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
urls = []
ids = []
ids.append("hello")
urls.append(sys.argv[1])
# print(urls)
# sys.stdout.flush()
# print(ids)
# print(sys.argv[1])
# -----------------------------------------
data_dir = './data/'
# code will run in gpu if available and if the flag is set to True, else it will run on cpu
use_gpu = False
device = torch.device('cuda' if torch.cuda.is_available() and use_gpu else 'cpu')
map_loc = None if torch.cuda.is_available() and use_gpu else 'cpu'
# print(device)
# print(map_loc)
# code below was used to save vocab files so that they can be loaded without Vocabulary class
# ingrs_vocab = pickle.load(open(os.path.join(data_dir, 'final_recipe1m_vocab_ingrs.pkl'), 'rb'))
# ingrs_vocab = [min(w, key=len) if not isinstance(w, str) else w for w in ingrs_vocab.idx2word.values()]
# vocab = pickle.load(open(os.path.join(data_dir, 'final_recipe1m_vocab_toks.pkl'), 'rb')).idx2word
# pickle.dump(ingrs_vocab, open('../demo/ingr_vocab.pkl', 'wb'))
# pickle.dump(vocab, open('../demo/instr_vocab.pkl', 'wb'))
ingrs_vocab = pickle.load(open(os.path.join(data_dir, 'ingr_vocab.pkl'), 'rb'))
vocab = pickle.load(open(os.path.join(data_dir, 'instr_vocab.pkl'), 'rb'))
ingr_vocab_size = len(ingrs_vocab)
instrs_vocab_size = len(vocab)
output_dim = instrs_vocab_size
t = time.time()
sys.argv = ['']
# del sys
args = get_parser()
args.maxseqlen = 15
args.ingrs_only = False
model = get_model(args, ingr_vocab_size, instrs_vocab_size)
# Load the trained model parameters
model_path = os.path.join(data_dir, 'modelbest.ckpt')
#print(os.path.exists('./data/' + 'modelbest.ckpt'))
#sys.stdout.flush()
# model_path = os.path.join("https://drive.google.com/open?id=1dpSIUZFtl03dvH1midHn67EZKyDzEAvy", "")
#dicty = torch.load(model_path, map_location=torch.device('cpu'))
#import torchvision.models as models
#resnet50 = models.resnet50(pretrained=True)
#print(resnet50)
#print(os.listdir("./.torch/models"))
#os.remove('./.torch/models/resnet50-19c8e357.pth')
#print(os.listdir("./.torch/models"))
dicty = torch.load("file.pt")
#print(type(dicty))
#print(dicty['state_dict'])
# torch.save(dicty, 'file.pt')
#try:
#dicty = torch.load("resnet50-19c8e357.pth")
#print(dicty)
#except:
#os.remove('./.torch/models/resnet50-19c8e357.pth')
model.load_state_dict(dicty) # map_location=map_loc
#print(model.load_state_dict(dicty))
model.to(device)
model.eval()
model.ingrs_only = False
model.recipe_only = False
# print('loaded model')
# print("Elapsed time:", time.time() - t)
transf_list_batch = [transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406),
(0.229, 0.224, 0.225))]
to_input_transf = transforms.Compose(transf_list_batch)
greedy = [True, False, False, False]
beam = [-1, -1, -1, -1]
temperature = 1.0
numgens = 1
# Set ```use_urls = True``` to get recipes for images in ```demo_urls```.
#
# You can also set ```use_urls = False``` and get recipes for images in the path in ```data_dir/test_imgs```.
use_urls = True # set to true to load images from demo_urls instead of those in test_imgs folder
show_anyways = False # if True, it will show the recipe even if it's not valid
final_output = {}
response = requests.get(urls[0])
image = Image.open(BytesIO(response.content))
transf_list = [transforms.Resize(256), transforms.CenterCrop(224)]
transform = transforms.Compose(transf_list)
image_transf = transform(image)
image_tensor = to_input_transf(image_transf).unsqueeze(0).to(device)
# plt.imshow(image_transf)
# plt.axis('off')
# plt.show()
# plt.close()
num_valid = 1
for i in range(numgens):
with torch.no_grad():
outputs = model.sample(image_tensor, greedy=greedy[i],
temperature=temperature, beam=beam[i], true_ingrs=None)
ingr_ids = outputs['ingr_ids'].cpu().numpy()
recipe_ids = outputs['recipe_ids'].cpu().numpy()
outs, valid = prepare_output(recipe_ids[0], ingr_ids[0], ingrs_vocab, vocab)
print(outs['ingrs'])
# print(final_output)
final_output[ids[0]] = outs['ingrs']
# ---------------------------- Retrieving Cuisines ----------------------------
from gensim.models import Word2Vec
import numpy
model = Word2Vec.load("word2vec.model")
clf = pickle.load(open('./trained_models/svc_model_cuisine_100.sav', 'rb'))
# ---------------------------- Calculating total weight for each recipe
recipe_weight = len(outs['ingrs'])
# ---------------------------- Weighting Contribution each Ingredient
print(recipe_weight)
recipe_vector = []
for ingredient in outs['ingrs']:
recipe_vector.append(numpy.array([model[lemmatizer.lemmatize(ingredient.replace("_", " ").lower())]]) * 1)
recipe_vector = numpy.sum(numpy.array(recipe_vector), 0) / recipe_weight
print(clf.predict(recipe_vector))
sys.stdout.flush()