from reader import read_testing, read_training
from  keras.utils import  to_categorical
import numpy as np
import autokeras as ak
from sklearn.metrics import classification_report, confusion_matrix
emotions_map = [4, 4, 0, 2, 4, 3, 1]

def reading_data():
	print('Reading data...')
	x_test, y_test = read_testing()
	x_train, y_train = read_training()
	print(y_train.shape)

	emotions_count = len(set(emotions_map))
	# y_train = to_categorical(y_train, emotions_count)
	# y_test = to_categorical(y_test, emotions_count)

	x_train = np.array(x_train, 'float32')
	y_train = np.array(y_train, 'float32')
	x_test = np.array(x_test, 'float32')
	y_test = np.array(y_test, 'float32')

	x_train /= 255 #normalize inputs between [0, 1]
	x_test /= 255
	 
	x_train = x_train.reshape(x_train.shape[0], 48, 48, 1)
	x_train = x_train.astype('float32')
	x_test = x_test.reshape(x_test.shape[0], 48, 48, 1)
	x_test = x_test.astype('float32')

	print(x_train.shape[0], 'train samples')
	print(x_test.shape[0], 'test samples')

	return x_train, x_test, y_train, y_test

def create_model(x_train, x_test, y_train, y_test):
	model = ak.ImageClassifier(path="/automodels/", verbose=True)

	#increasing time will increase the accuracy
	model.fit(x_train, y_train, time_limit=60*60*24)
	model.final_fit(x_train, y_train, x_test, y_test, retrain=True)
	score = model.evaluate(x_test, y_test)
	print("accuracy on test set is ",100*score)
	autokeras_predictions = autokeras_model.predict(x_test)
	confusion_matrix(y_test, autokeras_predictions)

	#exporting model
	model.export_autokeras_model('best_auto_keras_model.h5')
	print("done exporting")
	
def main():
	x_train, x_test, y_train, y_test = reading_data()
	create_model(x_train, x_test, y_train, y_test)
	
if __name__ == '__main__': main()