import os
os.environ['HDF5_USE_FILE_LOCKING']='FALSE'
import numpy as np
from keras.models import load_model
from keras.preprocessing import image
import keras.backend as K

def normalize_y_pred(y_pred):
    return K.one_hot(K.argmax(y_pred),y_pred.shape[-1])

def class_true_positive(class_label,y_true,y_pred):
    y_pred=normalize_y_pred(y_pred)
    return K.cast(K.equal(y_true[:,class_label]+y_pred[:,class_label],2),K.floatx())

def class_precision(class_label,y_true,y_pred):
    y_pred=normalize_y_pred(y_pred)
    return K.sum(class_true_positive(class_label,y_true,y_pred))/(K.sum(y_pred[:,class_label])+K.epsilon())

def macro_precision(y_true,y_pred):
    class_count=y_pred.shape[-1]
    return K.sum([class_precision(i,y_true,y_pred) for i in range(class_count)])\
        / K.cast(class_count, K.floatx())


# load and preprocess the image
img=image.load_img('./latest_skibotn.jpg',target_size=(128,128))
im=image.img_to_array(img)
im=np.expand_dims(im,axis=0)
# scale the 8 bit color values to 0-1
im=im/255.

# load the model
model=load_model('./model/resnet50.h5',custom_objects={'macro_precision': macro_precision},compile=False)

# get the probabilities
# *100 is for scale the probabilities 0-1 to 0-100
probs=np.array(model.predict(im)[0])*100
print(probs)

# idx of probs is an alphabetical order of clsses i.e.,
# probs[0] is the probability that the input image belongs to APC class
# probs[1] is the probability that the input image belongs to APM class
# probs[2] is the probability that the input image belongs to ARC class
