# This is a demo of running face recognition on a Raspberry Pi.
# This program will print out the names of anyone it recognizes to the console.

# To run this, you need a Raspberry Pi 2 (or greater) with face_recognition and
# the picamera[array] module installed.
# You can follow this installation instructions to get your RPi set up:
# https://gist.github.com/ageitgey/1ac8dbe8572f3f533df6269dab35df65

import face_recognition
import picamera
import numpy as np
import serial
from time import sleep
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

# Get a reference to the Raspberry Pi camera.
# If this fails, make sure you have a camera connected to the RPi and that you
# enabled your camera in raspi-config and rebooted first.
camera = picamera.PiCamera()
camera.resolution = (320, 240)
output = np.empty((240, 320, 3), dtype=np.uint8)

# Load a sample picture and learn how to recognize it.
print("Loading known face image(s)")
obama_image = face_recognition.load_image_file("reference.JPG")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]

# Initialize some variables
face_locations = []
face_encodings = []

ser = serial.Serial('/dev/ttyUSB0',9600)
ser.flushInput()
ser.flushOutput()
   
while True:
        passcode = ser.read()
        print("passcode=",passcode)
        if passcode==b'a':
            print("Capturing image.")
            # Grab a single frame of video from the RPi camera as a numpy array
            camera.capture(output, format="rgb")

            # Find all the faces and face encodings in the current frame of video
            face_locations = face_recognition.face_locations(output)
            print("Found {} faces in image.".format(len(face_locations)))
            face_encodings = face_recognition.face_encodings(output, face_locations)

            # Loop over each face found in the frame to see if it's someone we know.
            for face_encoding in face_encodings:
                # See if the face is a match for the known face(s)
                match = face_recognition.compare_faces([obama_face_encoding], face_encoding)
                name = "<Unknown Person>"

                sleep(2)
                camera.capture('/home/pi/Documents/images/image.jpg')
    
                fromaddr = "..."
                toaddr = "..."
 
                msg = MIMEMultipart()
 
                msg['From'] = fromaddr
                msg['To'] = toaddr
                msg['Subject'] = "Box"
     
                body = "Do you know this person?"
     
                msg.attach(MIMEText(body, 'plain'))
 
                filename = "image.jpg"
                attachment = open("/home/pi/Documents/images/image.jpg", "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, "...")
                text = msg.as_string()
                server.sendmail(fromaddr, toaddr, text)
                server.quit()
                sleep(0.5)

                if match[0]:
                    name = "the Owner"
                    ser.write("b".encode())
                print("I see someone named {}!".format(name))
               

