import image_CNN
import binary_CNN
import tensorflow as tf
sess = tf.InteractiveSession()

width = 64
height = 64
depth = 30
nLabel = 2

# set first data
x = tf.placeholder(tf.float32, shape=[None, width*height*depth]) 
y_ = tf.placeholder(tf.float32, shape=[None, nLabel])  

# weight initialization
def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

#bias initalization
def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

# Convolution and Pooling
def conv3d(x, W):
  return tf.nn.conv3d(x, W, strides=[1, 1, 1, 1, 1], padding='SAME') 
  # set stride = [1, 1, 1, 1, 1]

# max pooling
def max_pool_2x2(x):  
  return tf.nn.max_pool3d(x, ksize=[1, 4, 4, 4, 1], strides=[1, 4, 4, 4, 1], padding='SAME')
  # set stride = [1, 2, 2, 2, 1]


## 1st Convolution
weight_conv1 = weight_variable([5, 5, 5, 1, 32])
bias_conv1 = bias_variable([32])  

x_image = tf.reshape(x, [-1,width,height,depth,1]) # ,1] .. grayscale / ,3].. rgb
print("input size : ")
print(x_image.get_shape) # (?, 256, 256, 30, 1)

#conv-relu-maxpool
h_conv1 = tf.nn.relu(conv3d(x_image, weight_conv1) + bias_conv1)
h_pool1 = max_pool_2x2(h_conv1)  
print("1st Conv-relu-maxpool end, size :")
print(h_conv1.get_shape) # (?, 256, 256, 30, 32)
print(h_pool1.get_shape) # (?, 128, 128, 30, 32)



## 2nd Convolution
weight_conv2 = weight_variable([5, 5, 5, 32, 64]) 
bias_conv2 = bias_variable([64]) 

#conv-relu-maxpool
h_conv2 = tf.nn.relu(conv3d(h_pool1, weight_conv2) + bias_conv2)  
h_pool2 = max_pool_2x2(h_conv2)  # apply max-pool 
print("2nd Conv-relu-maxpool end, size :")
print(h_conv2.get_shape) # (?, 128, 128, 20, 64) 
print(h_pool2.get_shape) # (?, 64, 64, 10, 64)   



# fully-connected layer
weight_fc1 = weight_variable([4*4*2*64, 1024])  # all data set(count) -> 1024
bias_fc1 = bias_variable([1024]) 

h_pool2_flat = tf.reshape(h_pool2, [-1, 4*4*2*64])  # -> all data set(count)
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, weight_fc1) + bias_fc1)  
print("fully-connected end, size : ")
print(h_pool2_flat.get_shape)  # (?, count)
print(h_fc1.get_shape) # (?, 1024) 



# drop_out
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
print("drop_out end, siz : ")
print(h_fc1_drop.get_shape)  # -> output: 1024

# Readout Layer
weight_fc2 = weight_variable([1024, nLabel]) # [1024, 10]
bias_fc2 = bias_variable([nLabel]) # [10]

y_conv = tf.matmul(h_fc1_drop, weight_fc2) + bias_fc2
print('last out_put : ')
print(y_conv.get_shape)  # -> 1024

# initial / train
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
train_step = tf.train.AdamOptimizer(1e-3).minimize(cross_entropy)  # 1e-4
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

#for saving model
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())

for i in range(100):
    batch = image_CNN.get_data_jpeg(sess,'train',10)

    print("batch_end --")

    if i%5 == 0:
        train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
        print("step %d, training accuracy %g"%(i, train_accuracy))
    train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    print("train " + str(i) + "_th end")
    print("----------------------------------------------------------------")

sess = batch[2]

save_path = saver.save(sess, './cnn_3d_model.ckpt')
print(save_path)

testset = image_CNN.get_data_jpeg(sess,'eval',1)

#evalution model
print("test accuracy %g" %accuracy.eval(feed_dict={x: testset[0], y_: testset[1], keep_prob: 1.0}))

