Search code examples
pythonapiflaskimage-processingimage-classification

return predicted results in jsonify


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.


Solution

  • 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
        })