import face_recognition
from PIL import Image, ImageDraw

image_of_bill = face_recognition.load_image_file('./img/know/Bill Gates.jpg')
bill_face_encoding = face_recognition.face_encodings(image_of_bill)[0]

image_of_steve = face_recognition.load_image_file('./img/know/Steve Jobs.jpg')
steve_face_encoding = face_recognition.face_encodings(image_of_steve)[0]

image_of_elon = face_recognition.load_image_file('./img/know/Elon Musk.jpg')
elon_face_encoding = face_recognition.face_encodings(image_of_elon)[0]

image_of_justin = face_recognition.load_image_file('./img/know/Justin Wheeler.jpg')
justin_face_encoding = face_recognition.face_encodings(image_of_justin)[0]

image_of_joey = face_recognition.load_image_file('./img/know/Joey Baugh.jpg')
joey_face_encoding = face_recognition.face_encodings(image_of_joey)[0]

# Create arrzy of encodings and names

known_face_encodings = [
  bill_face_encoding,
  steve_face_encoding,
  elon_face_encoding,
  justin_face_encoding,
  joey_face_encoding
]

known_face_names = [
  'Bill Gates',
  'Steve Jobs',
  'Elon Musk',
  'Justin Wheeler',
  'Joey Baugh'
]

#load test images
test_image = face_recognition.load_image_file('./img/groups/Cohort29_1.jpg')

#find faces in image
face_locations = face_recognition.face_locations(test_image)
face_encodings = face_recognition.face_encodings(test_image, face_locations)

#convert to PIL FORMAT

pil_image = Image.fromarray(test_image)

#Create  imagedraw instance

draw = ImageDraw.Draw(pil_image)

# Loop through faces in test image
for(top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
  matches = face_recognition.compare_faces(known_face_encodings, face_encoding)

  name = "Unknown Person"

  # If match
  if True in matches:
    first_match_index = matches.index(True)
    name = known_face_names[first_match_index]

  # Draw box
  draw.rectangle(((left, top), (right, bottom)), outline=(255,255,0))

  # Draw label
  text_width, text_height = draw.textsize(name)
  draw.rectangle(((left,bottom - text_height - 10), (right, bottom)), fill=(255,255,0), outline=(255,255,0))
  draw.text((left + 6, bottom - text_height - 5), name, fill=(0,0,0))

del draw

# Display image
pil_image.show()

# Save image
pil_image.save('identify.jpg')