Wednesday, November 8, 2017

Setting up Your Web App with Flask

With Python Flask, you can easily setup a web application that is interactive. In this tutorial, we will build a simple deep neural network server that will classify the given image into one of the 1000 categories. When done, your app will look like




Let's create a folder where all your web app files will reside.
$ mkdir ~/web_app
$ cd ~/web_app

Install Flas, Keras and OpenCV modules
$ pip install flask keras opencv-python

Next, create two more folders as below
$ mkdir templates uploads

Create server.py and copy the code below:
from flask import Flask, render_template, request, send_from_directory
import os
import urllib
from keras.models import load_model
from keras.applications import resnet50
from keras.applications.imagenet_utils import preprocess_input, decode_predictions
import cv2
import numpy as np
app = Flask(__name__)
PORT = '8888'
UPLOAD = 'uploads'
@app.route('/')
def index():
return render_template("index.html",
title='ResNet50 Classification Demo')
@app.route('/download', methods=['POST'])
def download_image():
address = request.form['address']
filename = os.path.join(UPLOAD, address.split('/')[-1])
with open(filename, 'wb') as f:
f.write(urllib.urlopen(address).read())
return predict(filename)
@app.route('/upload', methods=['POST'])
def upload_image():
f = request.files['image']
filename = os.path.join(UPLOAD, f.filename)
f.save(filename)
return predict(filename)
@app.route('/' + UPLOAD + '/<path:path>')
def serve_files(path):
return send_from_directory(UPLOAD, path)
def predict(filename):
img = cv2.imread(filename)
img = cv2.resize(img, (224,224))[...,::-1]
img = np.expand_dims(img, axis=0).astype(np.float32)
x_batch = preprocess_input(img)
pred = model.predict(x_batch)
decode_result = decode_predictions(pred)[0]
result = []
for r in decode_result:
result.append({'name':r[1], 'prob':r[2]*100})
return render_template('predict.html',
filename=filename,
predictions=result)
if __name__ == "__main__":
os.environ["CUDA_VISIBLE_DEVICES"] = ""
model = resnet50.ResNet50(include_top=True, weights='imagenet')
app.run(host='0.0.0.0', port=PORT)
view raw server.py hosted with ❤ by GitHub

Create templates/index.html file and copy the code below:

<!DOCTYPE html>
<html>
<head>
{% if title %}
<title>{{ title }}</title>
{% else %}
<title>Classification Demo</title>
{% endif %}
</head>
<body>
<form action="/download" method="POST">
<fieldset>
<legend>Image URL</legend>
<input type="text" name="address"
value="http://cdn2-www.cattime.com/assets/uploads/gallery/ragdoll/ragdoll-cats-kittens-2.jpg" size="100"><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<br><br>
<form action="/upload" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload Image</legend>
<input type="file" name="image">
<input type="submit" value="Upload your image" class="btn btn-primary">
</fieldset>
</form>
</body>
</html>
view raw index.html hosted with ❤ by GitHub

Create templates/predict.html file and copy the code below:

<!DOCTYPE html>
<html>
<head>
{% if title %}
<title>{{ title }}</title>
{% else %}
<title>Classification Demo</title>
{% endif %}
</head>
<body>
<img src={{ filename }} width="224" height="224">
<br>
{% for pred in predictions %}
{{ pred.name }} : {{ pred.prob }}
<br>
{% endfor %}
<br>
</body>
</html>
view raw predict.html hosted with ❤ by GitHub

That's it! Your web app will classify a given image---either uploaded directly from the client or using the web url---using ResNet50 pre-trained network.

To run the server, run
$ python server.py

While the server is running, you can browse to http://SERVER_IP:8888 to view the web app, where of course SERVER_IP must be replaced with the server's actual IP address.

No comments:

Post a Comment