parichehr_vn
parichehr_vn

Reputation: 1

Openwhisk invoke action error: "error": "The action did not return a dictionary."

I have a python function that uses the Tensorflow library to image recognition. And I deployed it on IBM Cloud Functions(Openwhisk) through Dockerfile and invoke it from wsk CLI. But when I invoke the function, the following error is displayed:

{
"error": "The action did not return a dictionary."
}

How do I change the output type? Here is the function code:

import boto3
import numpy as np
import os.path
import re
from urllib.request import urlretrieve
import json
from botocore.client import Config
import mimetypes
import os
import requests

SESSION = None
bucket = '---'

def main(event, context):
    global bucket
    global SESSION

    if not os.path.exists('/tmp/imagenet/'):
        os.makedirs('/tmp/imagenet/')

    if SESSION is None:
        downloadFromS3(bucket,'Imagenet/imagenet_2012_challenge_label_map_proto.pbtxt','/tmp/imagenet/imagenet_2012_challenge_label_map_proto.pbtxt')
        downloadFromS3(bucket,'Imagenet/imagenet_synset_to_human_label_map.txt','/tmp/imagenet/imagenet_synset_to_human_label_map.txt')

    strFile = '/tmp/imagenet/inputimage.png'

    if ('queryStringParameters' in event):
        if (event['queryStringParameters'] is not None):
            if ('url' in event['queryStringParameters']):
                urlretrieve(event['queryStringParameters']['url'], strFile)
            else:
                downloadFromS3(bucket,'Imagenet/inputimage.png',strFile)
        else:
            downloadFromS3(bucket,'Imagenet/inputimage.png',strFile)
    else:
        downloadFromS3(bucket,'Imagenet/inputimage.png',strFile)

    strResult = run_inference_on_image(strFile)

    return {
        'statusCode': 200,
        'body': json.dumps(strResult)
    }

def run_inference_on_image(image):
    image_data = tf.gfile.FastGFile(image, 'rb').read()
    global SESSION
    if SESSION is None:
        SESSION = tf.InteractiveSession()
        create_graph()

    softmax_tensor = tf.get_default_graph().get_tensor_by_name('softmax:0')
    predictions = SESSION.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})
    predictions = np.squeeze(predictions)
    top_k = predictions.argsort()[-5:][::-1]

    node_lookup = NodeLookup()
    strResult = '%s (score = %.5f)' % (node_lookup.id_to_string(top_k[0]), predictions[top_k[0]])
    vecStr = []
    for node_id in top_k:
        human_string = node_lookup.id_to_string(node_id)
        score = predictions[node_id]
        vecStr.append('%s (score = %.5f)' % (human_string, score))
    return vecStr

def downloadFromS3(bucket,strKey,strFile):
    s3_client = boto3.client('s3')
    s3_client.download_file(bucket, strKey, strFile)

def getObject(bucket,strKey):
    s3_client = boto3.client('s3')
    s3_response_object = s3_client.get_object(Bucket=bucket, Key=strKey)
    return s3_response_object['Body'].read()  

def create_graph():
    global bucket
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(getObject(bucket,'Imagenet/classify_image_graph_def.pb'))
    _ = tf.import_graph_def(graph_def, name='')

class NodeLookup(object):
    """Converts integer node ID's to human readable labels."""

    def __init__(self,
               label_lookup_path=None,
               uid_lookup_path=None):
        if not label_lookup_path:
            label_lookup_path = os.path.join(
                '/tmp/imagenet/', 'imagenet_2012_challenge_label_map_proto.pbtxt')
        if not uid_lookup_path:
            uid_lookup_path = os.path.join(
                '/tmp/imagenet/', 'imagenet_synset_to_human_label_map.txt')
        self.node_lookup = self.load(label_lookup_path, uid_lookup_path)

    def load(self, label_lookup_path, uid_lookup_path):
        if not tf.gfile.Exists(uid_lookup_path):
            tf.logging.fatal('File does not exist %s', uid_lookup_path)
        if not tf.gfile.Exists(label_lookup_path):
            tf.logging.fatal('File does not exist %s', label_lookup_path)

        # Loads mapping from string UID to human-readable string
        proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
        uid_to_human = {}
        p = re.compile(r'[n\d]*[ \S,]*')
        for line in proto_as_ascii_lines:
            parsed_items = p.findall(line)
            uid = parsed_items[0]
            human_string = parsed_items[2]
            uid_to_human[uid] = human_string

        # Loads mapping from string UID to integer node ID.
        node_id_to_uid = {}
        proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
        for line in proto_as_ascii:
            if line.startswith('  target_class:'):
                target_class = int(line.split(': ')[1])
            if line.startswith('  target_class_string:'):
                target_class_string = line.split(': ')[1]
                node_id_to_uid[target_class] = target_class_string[1:-2]

        # Loads the final mapping of integer node ID to human-readable string
        node_id_to_name = {}
        for key, val in node_id_to_uid.items():
            if val not in uid_to_human:
                tf.logging.fatal('Failed to locate: %s', val)
            name = uid_to_human[val]
            node_id_to_name[key] = name

        return node_id_to_name

    def id_to_string(self, node_id):
        if node_id not in self.node_lookup:
            return ''
        return self.node_lookup[node_id]

Upvotes: 0

Views: 318

Answers (1)

Tremendous Cookie
Tremendous Cookie

Reputation: 1

As the error states, whatever code you have written does not return a dictionary. from my experience with Openwhisk to date, for it to understand what it has to display/compute, the o/p should be in the form of a dict.

So change it to that and you'll be good to go

Upvotes: 0

Related Questions