import csv
import random
import numpy as np
import emotion_model
import dwdii_transforms

random.seed(20275)

"""
Explanation: DATA622 Final Project
Daniel Dittenhafer
This notebook proceeds with using the trained convolutional neural network to predict emotion for each of the face images in the provided test set as part of the Emotion Detection Form Facial Expressions Kaggle competition.
Import References
End of explanation
"""


imgDimension = []
imgDimension.append(150)
imgDimension.append(150)

"""
Explanation: Definitions
The model was trained on 150x150 images, therefore we will use this size of the test data as well.
End of explanation
"""


testDataPath = "../../facial_expressions/test"

import os
ls  = os.listdir(testDataPath)
len(ls)

testData, fileList = dwdii_transforms.load_test_data(testDataPath, imgResize=imgDimension, verboseFreq=20)

testData.shape

testX = testData.reshape(testData.shape[0], 1, testData.shape[1],testData.shape[2])

"""
Explanation: Load Kaggle Test Data
In this section, the test data is loaded from the previously cloned facial_expressions GitHub repo.
End of explanation
"""


# Load the emotion array for our count in the model definition
emotions = dwdii_transforms.emotionNumerics()
print emotions
print len(emotions)
# Construct the model using our help function
model = emotion_model.emotion_model_jh_v5(len(emotions), verbose=True, 
                                        input_shape=(1,imgDimension[0],imgDimension[1]))

loadWeights = True
if loadWeights:
    #model.load_weights("dwdii-emo-150-jhv5a-Cloud.hdf5")
    #model.load_weights("dwdii-emo-150-jhv5-9tf-Cloud.hdf5")
    model.load_weights("dwdii-emo-150-jhv5-19tf-25e-Cloud.hdf5")

"""
Explanation: Define and Load Trained Model
End of explanation
"""


predictOutput = model.predict(testX, batch_size=32, verbose=1)

# How many predictions?
len(predictOutput)

# Show an example of the prediction output
print predictOutput[0]

np.array(predictOutput[0]).argmax()

numEmo = dwdii_transforms.numericEmotions()
numEmo[2]

fileList[0]

"""
Explanation: Produce Predictions
End of explanation
"""


# For each prediction output, build the row for the CSV and add to our list for saving.
outputData = []
outputData.append(["Image", "Emotion"])
for i in range(len(predictOutput)):
    arPred = np.array(predictOutput[i])
    predictionProb = arPred.max()
    predictionNdx = arPred.argmax()
    predictedEmo = numEmo[predictionNdx]
    fileName = fileList[i]
    outputData.append([fileName,predictedEmo])

print outputData[0:10]

with open('../output/dwdii_predictions-19tf-25e.csv', 'w') as mycsvfile:
    dw = csv.writer(mycsvfile)
    for row in outputData:
        dw.writerow(row)

"""
Explanation: Persist Predictions
In this section we save the prediction results to a file in the prescribed Kaggle competition format.
End of explanation
"""


from scipy import misc
path = testDataPath + "/JayaBhaduri_42.jpg"
img = misc.imread(path)
img = misc.imresize(img, (150, 150))

misc.imsave("test1000.jpg", img)

"""
Explanation: Appendix: Sanity Check Code
I wanted to make sure the resizing didn't cause significant distortion for images which werent' square already. The following code helped with this sanity check.
End of explanation
"""


