1

I am trying to print a dictionary on the HTML from a flask application and it's not allowing me to do so throwing the below error. I was able to successfully return the string (https://github.com/upendrak/Disease_Predictor) but when I changed the code to return the dictionary (code below), it is throwing an error. I was thinking it has something to do with the js which I am not much familiar.

Here is the error that I am getting

TypeError: 'list' object is not callable
The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a list.

Here are the two relevant functions in my app.py script

def model_predict(img_path, model):
    img = image.load_img(img_path, target_size=(224, 224))

    # Preprocessing the image
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = x/255

    predictions = model.predict(x)
    pred_5 = np.argsort(predictions)[0][-5:]
    top_5 = {}
    labels_dict = {'Apple Scab': 0, 'Apple Black rot': 1, 'Apple Cedar rust': 2, 'Apple healthy': 3}
    for i in pred_5:
        rank = predictions[0][i]
        for kee, val in labels_dict.items():
            if i == val:
                top_5[kee] = rank

    sorted_x2 = sorted(top_5.items(), key=operator.itemgetter(1), reverse=True)
    return sorted_x2

@app.route('/predict', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']

        # Save the file to ./uploads
        basepath = os.path.dirname(__file__)
        file_path = os.path.join(
            basepath, 'uploads', secure_filename(f.filename))
        f.save(file_path)

        result = model_predict(file_path, model)
        return result

    return None

Here is my js file - https://github.com/upendrak/Disease_Predictor/blob/master/static/js/main.js

upendra
  • 2,141
  • 9
  • 39
  • 64

1 Answers1

1

Use [jsonify()][1] to pass your data. It serializes the data to JSON and hence, returns the JSON response. Instead of just returning return result, do return jsonify(result).

Updated Code:

def model_predict(img_path, model):
    img = image.load_img(img_path, target_size=(224, 224))

    # Preprocessing the image
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = x/255

    predictions = model.predict(x)
    pred_5 = np.argsort(predictions)[0][-5:]
    top_5 = {}
    labels_dict = {'Apple Scab': 0, 'Apple Black rot': 1, 'Apple Cedar rust': 2, 'Apple healthy': 3}
    for i in pred_5:
        rank = predictions[0][i]
        for kee, val in labels_dict.items():
            if i == val:
                top_5[kee] = rank

    sorted_x2 = sorted(top_5.items(), key=operator.itemgetter(1), reverse=True)
    return sorted_x2

@app.route('/predict', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']

        # Save the file to ./uploads
        basepath = os.path.dirname(__file__)
        file_path = os.path.join(
            basepath, 'uploads', secure_filename(f.filename))
        f.save(file_path)

        result = model_predict(file_path, model)
        return jsonify(result)

    return None
  • It didn't work. I got this error `TypeError: Object of type 'float32' is not JSON serializable `. Do you think I also need to change anything in here - https://github.com/upendrak/Disease_Predictor/blob/f79942d9827be5be5351fff91be4aaa12d4620a8/static/js/main.js#L35-L48 – upendra Jun 16 '19 at 04:08
  • Never mind. After I converted the floats to integers, it worked. Thanks – upendra Jun 16 '19 at 04:34
  • Can you share the sample output – kanav Malhotra Jun 16 '19 at 04:38
  • You might be using numpy floats object in a list, if that's the case convert all numpy floats to python float using float(var). – kanav Malhotra Jun 16 '19 at 04:42
  • Oh, I see. I will work on it. Here is the output - https://i.postimg.cc/Bnyc7B25/predict-output.png. Currently, it's rough but I will work on it to make it look better. – upendra Jun 16 '19 at 05:12