"""
# *Import Packages*
"""
import os
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.optimizers import RMSprop

import random
base_dir='../input/defect-imageset'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'valid')
"""
# *Explore the Data*
"""
train_B_MD_Line = os.path.join(train_dir, 'B_MD Line')
train_Bright = os.path.join(train_dir, 'Bright')
train_Coating = os.path.join(train_dir, 'Coating')
train_D_MD_Line = os.path.join(train_dir, 'D_MD Line')
train_Dark = os.path.join(train_dir, 'Dark')
train_Dent = os.path.join(train_dir, 'Dent')
train_Insect = os.path.join(train_dir, 'Insect')
train_Pass_G_Film = os.path.join(train_dir, 'Pass_G_Film')
train_Pass_Glue = os.path.join(train_dir, 'Pass_Glue')
train_Pass_W_Film = os.path.join(train_dir, 'Pass_W_Film')
train_Scratch = os.path.join(train_dir, 'Scratch')
train_Substance = os.path.join(train_dir, 'Substance')
train_Uncoating = os.path.join(train_dir, 'Uncoating')
validation_dir_B_MD_Line = os.path.join(validation_dir, 'B_MD Line')
validation_dir_Bright = os.path.join(validation_dir, 'Bright')
validation_dir_D_MD_Line = os.path.join(validation_dir, 'D_MD Line')
validation_dir_Dark = os.path.join(validation_dir, 'Dark')
validation_dir_Dent = os.path.join(validation_dir, 'Dent_RGH')
validation_dir_Insect = os.path.join(validation_dir, 'Insect')
validation_dir_Pass_G_Film = os.path.join(validation_dir, 'Pass_G_Film')
validation_dir_Pass_Glue = os.path.join(validation_dir, 'Pass_Glue')
validation_dir_Pass_W_Film = os.path.join(validation_dir, 'Pass_W_Film')
validation_dir_Scratch = os.path.join(validation_dir, 'Scratch')
validation_dir_Substance = os.path.join(validation_dir, 'Substance')
validation_dir_Uncoating = os.path.join(train_dir, 'Uncoating')
"""
# *Data Preprocessing*
"""
train_datagen = ImageDataGenerator(rescale=1.0/255,
                                  rotation_range=40,
                                  width_shift_range=0.2,
                                  height_shift_range=0.2,
                                  shear_range=0.2,
                                  zoom_range=0.2,
                                  horizontal_flip=True,
                                  fill_mode='nearest')
test_datagen = ImageDataGenerator(rescale=1.0/255)
train_generator = train_datagen.flow_from_directory(train_dir,batch_size=20,class_mode='categorical',target_size=(150,150))
validation_generator = test_datagen.flow_from_directory(validation_dir,batch_size=20,class_mode='categorical',target_size=(150,150))
"""
# *Building Model*
"""
model=tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu',input_shape=(150,150,3)),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(1024, activation='relu'),
    tf.keras.layers.Dense(1,activation='sigmoid')    
])
model.compile(optimizer=RMSprop(lr=0.001),
              loss='categorical_crossentropy',
              metrics=['acc'])
"""
# *Training*
"""

history=model.fit_generator(train_generator,
                           validation_data=validation_generator,
                           steps_per_epoch=100,
                           epochs=158,
                           validation_steps=50,
                           verbose=1)


model.save("rps.h5")
"""
# *Evaluating Accuracy and Loss for the Model*
"""
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)
plt.figure()


plt.show()