import face_recognition
import cv2
import os

KNOWN_FACES_DIR="known_faces"
UNKNOWN_FACES_DIR="unknown_faces"
TOLEANCE=0.6
FRAME_THICKNESS=4
FONT_THICKNESS=2
MODEL="hog" #hog works faster


print("Loading known faces...")

known_faces=[]
known_names=[]

for name in os.listdir(KNOWN_FACES_DIR):
    for filename in os.listdir(f"{KNOWN_FACES_DIR}/{name}"):
        image = face_recognition.load_image_file(f"{KNOWN_FACES_DIR}/{name}/{filename}")
        encoding = face_recognition.face_encodings(image)[0]
        known_faces.append(encoding)
        known_names.append(name)

print("processing unknown faces...")
for filename in os.listdir(UNKNOWN_FACES_DIR):
    print(filename)
    image=face_recognition.load_image_file(f"{UNKNOWN_FACES_DIR}/{filename}")
    locations = face_recognition.face_locations(image,model=MODEL)
    encodings=face_recognition.face_encodings(image,locations)
    image=cv2.cvtColor(image,cv2.COLOR_RGB2BGR)

    for face_encoding,face_location in zip(encodings,locations):
        results=face_recognition.compare_faces(known_faces,face_encoding,TOLEANCE)
        match=None
        if True in results:
            match=known_names[results.index(True)]
            print(f"Match found: {match}")

            top_left=(face_location[3],face_location[0])
            top_right=(face_location[1],face_location[2])

            color=[0,255,0]
            cv2.rectangle(image,top_left,top_right,FRAME_THICKNESS)

            top_left=(face_location[3],face_location[2])
            top_right=(face_location[1],face_location[2]+22)
            cv2.rectangle(image,top_left,top_right,cv2.FILLED)
            cv2.putText(image,match,(face_location[3]+10,face_location[2]+15),cv2.FONT_HERSHEY_SIMPLEX,2,(200,200,200),FONT_THICKNESS)

    image_resize=cv2.resize(image,None,fx=0.75,fy=0.5,interpolation=cv2.INTER_CUBIC)
    cv2.imshow("window",image_resize)
    cv2.waitKey(10000)
    '''
    if cv2.waitKey(20) & 0xFF == ord('q'):
        break
        '''




















