PeachyDinosaur
PeachyDinosaur

Reputation: 47

Python dictionary to json.dumps flask not working can't send response

I'm building the back end for an tensorflow app and basically after I do my classification I want to return the results to the client in JSON format.

So after my classification I get two values a "name" and "%"

imports

import json
from flask import Flask, jsonify, request, Response #import objects from the Flask model
app = Flask(__name__) #define app using Flask

function called by api call

Basically this returns this dictionary in the variable Items

{'moulin de la galette renoir': 0.0080302889, 'les demoiselles d avignon picassso': 0.7823543, 'starry night over the rhone van gogh': 0.01457829, 'wheatfields with crows van gogh': 0.049212866, 'guernica picassso': 0.14582427}

 classify()
     do some code here ...

     # Sort to show labels of first prediction in order of confidence
     top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]

     #items within object
            items = {}
            for node_id in top_k:
                human_string = label_lines[node_id]
                score = predictions[0][node_id]
                #stores human string and score in item
                items[human_string] = score
     return items

api

@app.route('/inception', methods=['POST'])
def inception():
    if 'file' not in request.files:
        return jsonify({'message' : 'failed'})
    file = request.files['file']
    output = classify(file)
    #print just to see the format of the output
    print(output)
    return Response(json.dumps(output),  mimetype='application/json')

This should post back items in json form but it doesn't.

If from classify() I hard code the exact same value as output equal it works.

so:

return {'moulin de la galette renoir': 0.0080302889, 'les demoiselles d avignon picassso': 0.7823543, 'starry night over the rhone van gogh': 0.01457829, 'wheatfields with crows van gogh': 0.049212866, 'guernica picassso': 0.14582427}

Upvotes: 0

Views: 1302

Answers (1)

PeachyDinosaur
PeachyDinosaur

Reputation: 47

Figure it out, basically in tensorflow code which I didn't include my value for score was a numpy float 32 type. Json dumps can't convert this and that's why it wasn't working.

score = float(predictions[0][node_id])

This minor change in the code fixes the issue. A lesson learned in always making sure you know your data types. Thanks for your help guys ^^

Upvotes: 1

Related Questions