how do I set up html with text and images for flask app?

Issue

I have a flask app, which looks like:

@app.route("/predict", methods=["GET","POST"])
def predict():    
    if request.method == "POST":        
        if request.files:
            raw_data = request.files['image'].read()         
            finalNumpyArray=np.array(json.loads(raw_data), dtype = 'uint8')
            processed_image = preprocess_image(finalNumpyArray)
            processed_image1 = preprocess_image1(finalNumpyArray)    
            prediction = model.predict(processed_image).tolist()
            f1 = plt.imshow(processed_image1, interpolation='none')
            f1.show()

            response = {
                'prediction': {
                    'Center': prediction[0][0],
                    'Donut': prediction[0][1],
                    'Edge-Loc': prediction[0][2],
                    'Edge-Ring': prediction[0][3],
                    'Loc': prediction[0][4],
                    'Random': prediction[0][5],
                    'Scratch': prediction[0][6],
                    'None': prediction[0][7],
                }
            }


            return jsonify(response)
    return render_template("predict.html")

The first predict page shows the "predict.html" page, where you can upload an image to get it predicted by the model I have loaded in the app. Once uploaded, the second page comes up, with the jsonify(response).

I’d like to change the jsonify(response) to an html that has a nice readout for the "response" variable, and that also shows the f1 figure, plt.imshow(…). The figure looks like this.

plt.imshow(…)

Solution

You can use render_template to render a Jinja2 template.

Have a look at the Flask documentation here.

In essence you would replace your return jsonify(response) with something like this:

return render_template('your_template.html', prediction=response['prediction'])

Now your Jinja2 template would have the prediction dictionary available in the prediction template variable.

For the f1 image you would need to save this first to disk somehow (e.g. using plt.imsave(), see here) and then pass the path to the file also to the render_template call so that you can use it in an <img /> tag in your template.

Answered By – yvesonline

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published