import cv2
import resnet as r
import numpy as np
import tensorflow as tf
from imutils.object_detection import non_max_suppression
import roslib
import rospy
import sys
from sensor_msgs.msg import Image
from std_msgs.msg import Int16, Float64, String
from cv_bridge import CvBridge



import logging
import os
from nets import resnet_v2
from preprocessing import inception_preprocessing
import time




bbox_list = []

class EmotionClassifier():
    def __init__(self):
        slim = tf.contrib.slim
        CLASSES = ['anger', ' happy ', 'neutral', ' sad ', 'surprise']

        image_size = 160
        checkpoints_dir = 'models/inception_5/'

        logging.basicConfig(filename='result.log', filemode='w', level=logging.INFO)
        self.logger = logging.getLogger('emotion classifier')

        # loading model
        with tf.Graph().as_default():
            self.image = tf.placeholder(tf.uint8, [None, None, 3])
            self.processed_image = inception_preprocessing.preprocess_image(self.image, image_size, image_size, is_training=False)
            self.processed_images = tf.placeholder(tf.float32, [None, image_size, image_size, 3])

            with slim.arg_scope(resnet_v2.resnet_arg_scope()):
                logits, _ = resnet_v2.resnet_v2_50(self.processed_images, num_classes=len(CLASSES), is_training=False)
                self.probs = tf.nn.softmax(logits)

            init_fn = slim.assign_from_checkpoint_fn(
                os.path.join(checkpoints_dir, 'model.ckpt-60000'),
                slim.get_model_variables('resnet_v2_50'))

            config = tf.ConfigProto()
            config.gpu_options.allow_growth = True
            config.allow_soft_placement = True
            self.sess = tf.Session(config=config)
            init_fn(self.sess)




class RosTensorFlow():
    
    def __init__(self):

        self.bridge = CvBridge()

        self._sub1 = rospy.Subscriber('CVsub1', Image, self.callback, queue_size=1, buff_size = 52428800)

        self._pub1 = rospy.Publisher('CVpub1', Image, queue_size=1)

 

        print("1------Initial Entry Point of Emotion Detecting , Starting now ......")

        # ---------------------------------

 	


    def callback(self, image_msg):
        
	face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_alt.xml')

	frame = self.bridge.imgmsg_to_cv2(image_msg, "bgr8")

	faces = face_cascade.detectMultiScale(frame,1.1,5)

	faceBoxes = [cv2.rectangle( frame, (xx,yy), (xx+ww, yy+hh) ,(255,0,0),2 ) for (xx,yy,ww,hh) in faces ]

	msg = self.bridge.cv2_to_imgmsg(frame, "bgr8")

        self._pub1.publish(msg)

        print("1---------------Detecting Loop Ending .............................")

    def main(self):
        rospy.spin()
        print("1------Braking Program by User .................")


if __name__ == "__main__":
    rospy.init_node('rostensorflow')
    tensor = RosTensorFlow()
    tensor.__init__()
    tensor.main()


