return predicted results in jsonify
Question:
I am a student and currently working on my project of image classifications in python(FLASK).
i have implemented all the functions and models, and it is working fine as web app. now I want to make an api which results in JSONIFY so I can easily use in mobile app as well.
I have the code listed below
@app.route('/predict', methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
img = request.files['image']
filename = img.filename
path = os.path.join('static/uploads', filename)
img.save(path)
print(filename)
predictions = pipeline_model(path)
return render_template("predict.html", p="uploads/{}".format(filename), pred=predictions)
return render_template("predict.html", p="images/dog.jpg", pred="")
the other pipeline function is:
def pipeline_model(path):
img = image.load_img(path, target_size=(299, 299))
img = image.img_to_array(img)
img = img / 255.0
img = np.expand_dims(img, axis=0)
pred = model.predict(img)
max_preds = []
pred = pred[0]
for i in range(5):
name = labels[pred.argmax()]
per = round(np.amax(pred) * 100, 2)
max_preds.append([name, per])
ele = pred.argmax()
pred = np.delete(pred, ele)
paths = glob('static/uploads/*')
if len(paths) > 5:
for path in paths[:4]:
os.remove(path)
return max_preds
So i want to convert this "return render_template" function in the form of "return jsonify", how can it be implemented so we can use it in mobile apps as well.
Answers:
Based on the user agent, you can send json or HTML(so both app and HTML app can work). Based on your need you can keep both returns or use the only json. In this example, I have used a simple dictionary, if you need help with that let us know.
@app.route("/get_my_prediction",methods=['GET','POST'])
def get_my_predicts():
# print(request.headers) # for debug in case needed
# print(f"request.headers.accept {request.headers.get('Accept')}") # for debug in case needed
data = {"label1": "value 1", "label2": "value2", "label3": 3.6}
data_type, *_ = request.headers.get('Accept').split(",")
if "text/html" in data_type: # this code can be made cleaner based on need
return make_response(str(data),200) # send as html, here you can keep your existing method to render html
else:
return make_response(jsonify(data), 200) # send as a json data
This is What I did and it worked for me to return data in json format.
@app.route('/predict', methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
#code here
predictions = utils.pipeline_model(path)
return jsonify({
"success": True,
"data": predictions
})
I am a student and currently working on my project of image classifications in python(FLASK).
i have implemented all the functions and models, and it is working fine as web app. now I want to make an api which results in JSONIFY so I can easily use in mobile app as well.
I have the code listed below
@app.route('/predict', methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
img = request.files['image']
filename = img.filename
path = os.path.join('static/uploads', filename)
img.save(path)
print(filename)
predictions = pipeline_model(path)
return render_template("predict.html", p="uploads/{}".format(filename), pred=predictions)
return render_template("predict.html", p="images/dog.jpg", pred="")
the other pipeline function is:
def pipeline_model(path):
img = image.load_img(path, target_size=(299, 299))
img = image.img_to_array(img)
img = img / 255.0
img = np.expand_dims(img, axis=0)
pred = model.predict(img)
max_preds = []
pred = pred[0]
for i in range(5):
name = labels[pred.argmax()]
per = round(np.amax(pred) * 100, 2)
max_preds.append([name, per])
ele = pred.argmax()
pred = np.delete(pred, ele)
paths = glob('static/uploads/*')
if len(paths) > 5:
for path in paths[:4]:
os.remove(path)
return max_preds
So i want to convert this "return render_template" function in the form of "return jsonify", how can it be implemented so we can use it in mobile apps as well.
Based on the user agent, you can send json or HTML(so both app and HTML app can work). Based on your need you can keep both returns or use the only json. In this example, I have used a simple dictionary, if you need help with that let us know.
@app.route("/get_my_prediction",methods=['GET','POST'])
def get_my_predicts():
# print(request.headers) # for debug in case needed
# print(f"request.headers.accept {request.headers.get('Accept')}") # for debug in case needed
data = {"label1": "value 1", "label2": "value2", "label3": 3.6}
data_type, *_ = request.headers.get('Accept').split(",")
if "text/html" in data_type: # this code can be made cleaner based on need
return make_response(str(data),200) # send as html, here you can keep your existing method to render html
else:
return make_response(jsonify(data), 200) # send as a json data
This is What I did and it worked for me to return data in json format.
@app.route('/predict', methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
#code here
predictions = utils.pipeline_model(path)
return jsonify({
"success": True,
"data": predictions
})