This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
app.py
executable file
·311 lines (245 loc) · 9.27 KB
/
app.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/env python
#
# Copyright 2018 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import collections
import json
import logging
import os
import requests
import signal
import time
import threading
from tornado import httpserver, ioloop, web
from tornado.options import define, options, parse_command_line
import numpy
from PIL import Image
modelEndpoint = os.environ.get("MODEL_ENDPOINT")
# Command Line Options
define("port", default=8088, help="Port the web app will run on")
# define("ml-endpoint", default="http://0.0.0.0:5000/predict",
# help="The Image Caption Generator REST endpoint")
define("ml-endpoint", default=modelEndpoint,
help="The Image Caption Generator REST endpoint")
# Setup Logging
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"),
format='%(levelname)s: %(message)s')
# Global variables
static_img_path = "static/img/images/"
temp_img_prefix = "MAX-"
image_captions = collections.OrderedDict()
VALID_EXT = ['png', 'jpg', 'jpeg', 'gif']
FASHION_LIST = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
class MainHandler(web.RequestHandler):
def get(self):
self.render("index.html", image_captions=image_captions)
class DetailHandler(web.RequestHandler):
def get(self):
image = self.get_argument('image', None)
if not image:
self.set_status(400)
return self.finish("400: Missing image parameter")
if image not in image_captions:
self.set_status(404)
return self.finish("404: Image not found")
self.render("detail-snippet.html", image=image,
predictions=image_captions[image])
class CleanupHandler(web.RequestHandler):
def get(self):
self.render("cleanup.html")
def delete(self):
clean_up()
class UploadHandler(web.RequestHandler):
def post(self):
finish_ret = []
new_files = self.request.files['file']
for file_des in new_files:
file_name = temp_img_prefix + file_des['filename']
if valid_file_ext(file_name):
rel_path = static_img_path + file_name
output_file = open(rel_path, 'wb')
output_file.write(file_des['body'])
output_file.close()
caption = run_ml(rel_path)
finish_ret.append({
"file_name": rel_path,
"caption": caption[0]['caption']
})
if not finish_ret:
self.send_error(400)
return
sort_image_captions()
self.finish(json.dumps(finish_ret))
def valid_file_ext(filename):
return '.' in filename and filename.split('.', 1)[1].lower() in VALID_EXT
# Runs ML on given image
def run_ml(img_path):
image = preprocess_object(img_path)
# Run curl command to send json to seldon
features = [str(i+1) for i in range(0, 784)]
req = {"data": {"names": features, "ndarray": image}}
results = requests.post(ml_endpoint, json=req)
request_results = results.json()
# Run postprocessing and retrieve results from returned json
return_json = request_results['data']['ndarray']
results = postprocess(return_json)
cap_json = postpostprocess(results)
print(cap_json)
caption = cap_json['predictions']
image_captions[img_path] = caption
return caption
# preprocess and post processing images
def preprocess_object(image_path, target_shape=(28, 28)):
"""
image_path: File path to image
target_shape: Shape that the model is expecting images to be in
by default the expected shape is (28,28)
returns: An array containing the raw data from the image at
'image_path' resized to 'target_shape'
"""
image = read_image(image_path, target_shape)
# Changes the image from a 1d array of size 784 to 2d of 28x28
feature_list = []
row = []
for x in range(0, 28):
range1 = 28 * x
row = []
for vals in range(0, 28):
pixel = image[range1 + vals]
row.append([pixel])
feature_list.append(row)
return [feature_list]
def read_image(image_path, target_shape):
"""
image_path: File path to image
target_shape: Shape that the model is expecting images to be in
by default the expected shape is (28,28)
returns: Returns a list of pixel values stored in 'L' mode
(black and white 8bit pixels)
"""
image = Image.open(image_path)
image = image.resize(target_shape)
# Force image to be stored in 'L' mode (Black and White 8bit pixels)
image = image.convert('L')
raw = list(image.getdata())
return raw
def postprocess(results):
"""
results: List of results where each result is a list of confidences
in the image being predicted being of a certain class
returns: A list of 2-tuples where each 2-tuple corresponds to a result
and is a 2-tuple where the second element is a list of sorted
confidence values (from max to min) and the first element is
the argsorted list of classes corresponding to the confidences
"""
post_results = []
for result in results:
argsort_rev = numpy.argsort(result)[::-1]
result_rev_sort = sorted(result)[::-1]
post_results.append((argsort_rev, result_rev_sort))
return post_results
def postpostprocess(post_results):
"""
post_results: An array of confidences that the image is of the class
with the same key as the index of the confidence value
"""
FASHION_LIST = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
cap_array = []
for i in range(0, 3):
cap_array.append({"index": i,
"caption": FASHION_LIST[post_results[0][0][i]],
"probability": str(round(post_results[0][1][i]*100,
4))})
cap_json = {'predictions': cap_array}
return cap_json
def sort_image_captions():
global image_captions
image_captions = collections.OrderedDict(
sorted(image_captions.items(), key=lambda t: t[0].lower()))
# Gets list of images with relative paths from static dir
def get_image_list():
image_list = sorted(os.listdir(static_img_path))
rel_img_list = [static_img_path + s for s in image_list]
return rel_img_list
# Run all static images through ML
def prepare_metadata():
threads = []
rel_img_list = get_image_list()
for img in rel_img_list:
t = threading.Thread(target=run_ml, args=(img,))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
sort_image_captions()
# Deletes all files uploaded through the GUI and removes them from the dict
def clean_up():
img_list = get_image_list()
for img_file in img_list:
if img_file.startswith(static_img_path + temp_img_prefix):
os.remove(img_file)
image_captions.pop(img_file)
def signal_handler(sig, frame):
ioloop.IOLoop.current().add_callback_from_signal(shutdown)
def shutdown():
logging.info("Cleaning up image files")
clean_up()
logging.info("Stopping web server")
server.stop()
ioloop.IOLoop.current().stop()
def make_app():
handlers = [
(r"/", MainHandler),
(r"/upload", UploadHandler),
(r"/cleanup", CleanupHandler),
(r"/detail", DetailHandler)
]
configs = {
'static_path': 'static',
'template_path': 'templates'
}
return web.Application(handlers, **configs)
def main():
parse_command_line()
global ml_endpoint
ml_endpoint = options.ml_endpoint
# if '/model/predict' not in options.ml_endpoint:
# ml_endpoint = options.ml_endpoint + "/model/predict"
logging.info("Connecting to ML endpoint at %s", ml_endpoint)
# try:
# requests.get(ml_endpoint)
# except requests.exceptions.ConnectionError:
# logging.error(
# "Cannot connect to the Image Caption Generator REST endpoint at "
# + options.ml_endpoint)
# raise SystemExit
logging.info("Starting web server")
app = make_app()
global server
server = httpserver.HTTPServer(app)
server.listen(options.port)
signal.signal(signal.SIGINT, signal_handler)
logging.info("Preparing ML metadata (this may take some time)")
start = time.time()
prepare_metadata()
end = time.time()
logging.info("Metadata prepared in %s seconds", end - start)
logging.info("Use Ctrl+C to stop web server")
ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()