-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
279 lines (243 loc) · 9.27 KB
/
__init__.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
from flask import Flask
from flask import request
from flask import jsonify
import tensorflow as tf
import os
import argparse
import requests
import numpy as np
import Image
from StringIO import StringIO
import time
import os.path
import re
import sys
FLAGS = None
app = Flask(__name__)
parser = argparse.ArgumentParser()
# classify_image_graph_def.pb:
# Binary representation of the GraphDef protocol buffer.
# imagenet_synset_to_human_label_map.txt:
# Map from synset ID to a human readable string.
# imagenet_2012_challenge_label_map_proto.pbtxt:
# Text representation of a protocol buffer mapping a label to synset ID.
parser.add_argument(
'--model_dir',
type=str,
default='/home/admin/deepmodel/inception_v1',
help="""\
Path to classify_image_graph_def.pb,
imagenet_synset_to_human_label_map.txt, and
imagenet_2012_challenge_label_map_proto.pbtxt.\
"""
)
parser.add_argument(
'--image_file',
type=str,
default='',
help='Absolute path to image file.'
)
parser.add_argument(
'--num_top_predictions',
type=int,
default=5,
help='Display this many predictions.'
)
FLAGS = parser.parse_args()
class FashionPrediction(object):
'''class for prediction '''
def __init__(self):
with tf.gfile.FastGFile(os.path.join(
FLAGS.model_dir, 'new_v1.pb'), 'rb') as f:
self.graph_def = tf.GraphDef()
self.graph_def.ParseFromString(f.read())
self._ = tf.import_graph_def(graph_def, name='')
self.sess1 = tf.Session()
self.classname = ('men-hoodies',
'women-heels',
'men-suites',
'sneakers',
'men-polo',
'women-sweaters',
'women-trenchcoat'
'backpacks',
'women-jeans',
'men-jeans',
'men-sweaters',
'women-polo',
'men-chinos',
'women-maxi',
'women-tshirts',
'men-messengers',
'women-clutch',
'men-shirts',
'women-blazer',
'women-shorts',
'women-crossbodybags',
'women-wallets',
'men-oxfordshoes',
'women-skirts',
'women-flat',
'men-boots',
'men-tshirts')
print "open Server for Fashion Prediction"
def predict(self, threshold ,url, x= -1 , y = -1, w = -1, h = -1):
try:
response = requests.get(url)
img = Image.open(StringIO(response.content))
if img.mode != 'RGB':
img = img.convert('RGB')
if x!= -1 and y!=-1:
img=img.crop(x,y,x+w,y+h)
resize_image = np.array(img.resize((224, 224), Image.BICUBIC))
normalize_image = (resize_image - 128.0) / 128.0
image_4d = np.expand_dims(normalize_image, axis=0)
#image_array=image_4dTensor.eval(session = sess)
prediction_tensor = self.sess1.graph.get_tensor_by_name(
'final_result:0') # ADDED
t1 = time.time()
predctions = self.sess1.run(
prediction_tensor, {'input:0': image_4d}) # ADDED
predctions = np.squeeze(predctions) # ADDED
delta = time.time() - t1
top_k = predctions.argsort()[-FLAGS.num_top_predictions:][::-1]
return_data = []
for class_index in top_k:
data = {}
#human_string = node_lookup.id_to_string(node_id)
score = predctions[class_index]
data['score'] = score
data['category'] = self.classname[class_index]
#print('%s (score = %.5f)' % (human_string, score))
if score > threshold:
return_data.append(data)
print(' (score = %.5f)' % score)
# print(delta)
return_data = {}
return_data['result'] = 'OK'
return_data['time'] = delta
return return_data
except Exception, e:
return_data = {}
return_data['result'] = 'can not make prediction'
return_data['errorMessage'] = str(e)
return return_data
class FeatureExtraction(object):
'''...'''
def __init__(self):
with tf.gfile.FastGFile(os.path.join(
FLAGS.model_dir, 'v1.pb'), 'rb') as f:
self.graph_def = tf.GraphDef()
self.graph_def.ParseFromString(f.read())
self._ = tf.import_graph_def(graph_def, name='')
self.sess2 = tf.Session()
print "open Server for Feature Extraction"
def calculateFeature(self, url, x= -1 , y = -1, w = -1, h = -1):
try:
response = requests.get(url)
img = Image.open(StringIO(response.content))
if img.mode != 'RGB':
img = img.convert('RGB')
if x!= -1 and y!=-1:
img=img.crop(x,y,x+w,y+h)
resize_image = np.array(img.resize((224, 224), Image.BICUBIC))
normalize_image = (resize_image - 128.0) / 128.0
image_4d = np.expand_dims(normalize_image, axis=0)
#image_array=image_4dTensor.eval(session = sess)
t1 = time.time()
feature_tensor = self.sess2.graph.get_tensor_by_name(
'avgpool0/reshape:0') # ADDED
feature_set = self.sess1.run(
feature_tensor, {'input:0': image_4d}) # ADDED
feature_set = np.squeeze(feature_set) # ADDED
feature_set = feature_set.tolist()
# print type(feature_set)
# print(np.size(feature_set))
# print(feature_set)
delta = time.time() - t1
# print(delta)
return_data = {}
return_data['result'] = 'OK'
return_data['features'] = feature_set
return_data['time'] = delta
return return_data
except Exception, e:
return_data = {}
return_data['result'] = 'ERROR'
return_data['errorMessage'] = str(e)
return return_data
@app.route('/')
def index():
return "Hello World this is Calc Feature server!"
@app.route('/api/getfeature', methods=['POST'])
def create_task():
if not request.json or not 'url' in request.json:
abort(400)
task = calculateFeature(request.json['url'])
return jsonify(task), 201
def calculateFeature(url):
try:
response = requests.get(url)
img = Image.open(StringIO(response.content))
if img.mode != 'RGB':
img = img.convert('RGB')
resize_image = np.array(img.resize((224, 224), Image.BICUBIC))
normalize_image = (resize_image - 128.0) / 128.0
image_4d = np.expand_dims(normalize_image, axis=0)
#image_array=image_4dTensor.eval(session = sess)
t1 = time.time()
feature_tensor = sess.graph.get_tensor_by_name(
'avgpool0/reshape:0') # ADDED
feature_set = sess.run(feature_tensor, {'input:0': image_4d}) # ADDED
feature_set = np.squeeze(feature_set) # ADDED
feature_set = feature_set.tolist()
# print type(feature_set)
# print(np.size(feature_set))
# print(feature_set)
delta = time.time() - t1
# print(delta)
return_data = {}
return_data['result'] = 'OK'
return_data['features'] = feature_set
return_data['time'] = delta
return return_data
except Exception, e:
return_data = {}
return_data['result'] = 'ERROR'
return_data['errorMessage'] = str(e)
return return_data
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# classify_image_graph_def.pb:
# Binary representation of the GraphDef protocol buffer.
# imagenet_synset_to_human_label_map.txt:
# Map from synset ID to a human readable string.
# imagenet_2012_challenge_label_map_proto.pbtxt:
# Text representation of a protocol buffer mapping a label to synset ID.
parser.add_argument(
'--model_dir',
type=str,
default='/home/admin/deepmodel/inception_v1',
help="""\
Path to classify_image_graph_def.pb,
imagenet_synset_to_human_label_map.txt, and
imagenet_2012_challenge_label_map_proto.pbtxt.\
"""
)
parser.add_argument(
'--image_file',
type=str,
default='',
help='Absolute path to image file.'
)
parser.add_argument(
'--num_top_predictions',
type=int,
default=5,
help='Display this many predictions.'
)
FLAGS = parser.parse_args()
# create_graph()
#sess = tf.Session()
print sess
app.run(debug=True, threaded=True)