# USAGE
# python faster_facial_landmarks.py --shape-predictor shape_predictor_68_face_landmarks.dat

# import the necessary packages
from imutils.video import VideoStream
from imutils import face_utils
import argparse
import imutils
import datetime as dt
import logging as log
import time
import dlib
import cv2
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
	help="path to facial landmark predictor")
args = vars(ap.parse_args())

# initialize dlib's face detector (HOG-based) and then create the
# facial landmark predictor
print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])

# initialize the video stream and sleep for a bit, allowing the
# camera sensor to warm up
log.basicConfig(filename='webcam.log',level=log.INFO)
print("[INFO] camera sensor warming up...")
vs = cv2.VideoCapture(0)
anterior = 0
# vs = VideoStream(usePiCamera=True).start() # Raspberry Pi
time.sleep(2.0)

# loop over the frames from the video stream
while True:
	# grab the frame from the threaded video stream, resize it to
	# have a maximum width of 400 pixels, and convert it to
	# grayscale
	(grabbed,frame) = vs.read()
	frame = imutils.resize(frame, width=600)
	gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
 
	# detect faces in the grayscale frame
	rects = detector(gray, 0)

	# check to see if a face was detected, and if so, draw the total
	# number of faces on the frame
	if len(rects) >= 0:
		text = "{} face(s) found".format(len(rects))
		cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX,
			0.5, (0, 0, 255), 2)

	# loop over the face detections
	for rect in rects:
		# compute the bounding box of the face and draw it on the
		# frame
		(bX, bY, bW, bH) = face_utils.rect_to_bb(rect)
		cv2.rectangle(frame, (bX, bY), (bX + bW, bY + bH),
			(255, 0, 0), 1)
	


		# determine the facial landmarks for the face region, then
		# convert the facial landmark (x, y)-coordinates to a NumPy
		# array
		shape = predictor(gray, rect)
		shape = face_utils.shape_to_np(shape)
 
		# loop over the (x, y)-coordinates for the facial landmarks
		# and draw each of them
		for (i, (x, y)) in enumerate(shape):
			cv2.circle(frame, (x, y), 1, (0, 0, 255), -1)
			cv2.putText(frame, str(i + 1), (x - 10, y - 10),
				cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 255, 0), 1)
	if anterior != len(rects) or anterior == len(rects):
      	   	 #anterior = len(rects)
           	 log.info("faces: "+str(len(rects))+" at "+str(dt.datetime.now()))
		
	# show the frame
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF
 
	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		break
fromaddr = "kongun<EMAIL>"
toaddr = ['<EMAIL>'] 
msg = MIMEMultipart()
 
msg['From'] = fromaddr
msg['To'] = ", ".join(toaddr)
msg['Subject'] = "Webcam log"
msg['cc']="hello messages"
 
body = "this is the message and the attachment through the python code"
 
msg.attach(MIMEText(body, 'plain'))
 
filename = "webcam.log"
attachment = open("/home/sabarish/Desktop/facial-landmarks/webcam.log", "rb")
 
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
 
msg.attach(part)
 
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "kongunadu")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
print ("successfully sent email to")

# do a bit of cleanup
cv2.destroyAllWindows()


# USAGE
# python faster_facial_landmarks.py --shape-predictor shape_predictor_68_face_landmarks.dat

# import the necessary packages
from imutils.video import VideoStream
from imutils import face_utils
import argparse
import imutils
import datetime as dt
import logging as log
import time
import dlib
import cv2
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
	help="path to facial landmark predictor")
args = vars(ap.parse_args())

# initialize dlib's face detector (HOG-based) and then create the
# facial landmark predictor
print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])

# initialize the video stream and sleep for a bit, allowing the
# camera sensor to warm up
log.basicConfig(filename='webcam.log',level=log.INFO)
print("[INFO] camera sensor warming up...")
vs = cv2.VideoCapture(0)
anterior = 0
# vs = VideoStream(usePiCamera=True).start() # Raspberry Pi
time.sleep(2.0)

# loop over the frames from the video stream
while True:
	# grab the frame from the threaded video stream, resize it to
	# have a maximum width of 400 pixels, and convert it to
	# grayscale
	(grabbed,frame) = vs.read()
	frame = imutils.resize(frame, width=600)
	gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
 
	# detect faces in the grayscale frame
	rects = detector(gray, 0)

	# check to see if a face was detected, and if so, draw the total
	# number of faces on the frame
	if len(rects) >= 0:
		text = "{} face(s) found".format(len(rects))
		cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX,
			0.5, (0, 0, 255), 2)

	# loop over the face detections
	for rect in rects:
		# compute the bounding box of the face and draw it on the
		# frame
		(bX, bY, bW, bH) = face_utils.rect_to_bb(rect)
		cv2.rectangle(frame, (bX, bY), (bX + bW, bY + bH),
			(255, 0, 0), 1)
	


		# determine the facial landmarks for the face region, then
		# convert the facial landmark (x, y)-coordinates to a NumPy
		# array
		shape = predictor(gray, rect)
		shape = face_utils.shape_to_np(shape)
 
		# loop over the (x, y)-coordinates for the facial landmarks
		# and draw each of them
		for (i, (x, y)) in enumerate(shape):
			cv2.circle(frame, (x, y), 1, (0, 0, 255), -1)
			cv2.putText(frame, str(i + 1), (x - 10, y - 10),
				cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 255, 0), 1)
	if anterior != len(rects) or anterior == len(rects):
      	   	 #anterior = len(rects)
           	 log.info("faces: "+str(len(rects))+" at "+str(dt.datetime.now()))
		
	# show the frame
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF
 
	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		break
fromaddr = "kongun<EMAIL>"
toaddr = ['<EMAIL>'] 
msg = MIMEMultipart()
 
msg['From'] = fromaddr
msg['To'] = ", ".join(toaddr)
msg['Subject'] = "Webcam log"
msg['cc']="hello messages"
 
body = "this is the message and the attachment through the python code"
 
msg.attach(MIMEText(body, 'plain'))
 
filename = "webcam.log"
attachment = open("/home/sabarish/Desktop/facial-landmarks/webcam.log", "rb")
 
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
 
msg.attach(part)
 
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "kongunadu")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
print ("successfully sent email to")

# do a bit of cleanup
cv2.destroyAllWindows()


# USAGE # python faster_facial_landmarks.py --shape-predictor shape_predictor_68_face_landmarks.dat # import the necessary packages # construct the argument parser and parse the arguments # initialize dlib's face detector (HOG-based) and then create the # facial landmark predictor # initialize the video stream and sleep for a bit, allowing the # camera sensor to warm up # vs = VideoStream(usePiCamera=True).start() # Raspberry Pi # loop over the frames from the video stream # grab the frame from the threaded video stream, resize it to # have a maximum width of 400 pixels, and convert it to # grayscale # detect faces in the grayscale frame # check to see if a face was detected, and if so, draw the total # number of faces on the frame # loop over the face detections # compute the bounding box of the face and draw it on the # frame # determine the facial landmarks for the face region, then # convert the facial landmark (x, y)-coordinates to a NumPy # array # loop over the (x, y)-coordinates for the facial landmarks # and draw each of them #anterior = len(rects) # show the frame # if the `q` key was pressed, break from the loop # do a bit of cleanup