def get_inference()

in iot-blog/image-classification-connector-and-feedback/part_1/beverageclassifier.py [0:0]


def get_inference(image_filename):
    logging.info('Invoking Greengrass ML Inference Service')
    
    with open(image_filename, 'rb') as image_file:
        image = image_file.read()

    try:
        response = ml_client.invoke_inference_service(
            AlgoType='image-classification',
            ServiceName="beverage-classifier",
            ContentType='image/jpeg',
            Body=image
        )
    except ml.GreengrassInferenceException as e:
        logging.info('Inference exception {}("{}")'.format(e.__class__.__name__, e))
        raise
    except ml.GreengrassDependencyException as e:
        logging.info('Dependency exception {}("{}")'.format(e.__class__.__name__, e))
        raise

    inference = response['Body'].read()
    inference = inference[1:-1]
    predictions = np.fromstring(inference, dtype=np.float, sep=',')

    logging.info("Received the following predictions from beverage-classifier model:" + str(predictions))

    # Get the prediction that has the highest confidence
    prediction_confidence = predictions.max()

    # The indicies of the inference result will match our CATEGORIES
    # array. Find the index of the highest prediction confidence,
    # and index into the CATEGORIES array to find the category name.
    predicted_category = CATEGORIES[predictions.argmax()]

    return predicted_category, prediction_confidence