from flask import Flask, request
import json
import cv2
import base64
import numpy as np
from deepface import DeepFace
import face_recognition as face
import os

app = Flask(__name__)

face_encodings: list = []
face_names: list = []

def init_face() -> None:
    for file in os.scandir("faces"):
        face_name = file.name.split('.')
        face_name = '.'.join(face_name[0:len(face_name)-1])
        face_names.append(face_name)
        face_image = face.load_image_file(file.path)
        face_encodings.append(face.face_encodings(face_image)[0])

init_face()

@app.route('/')
def home() -> str:
    return '<h1>Ching Chong Bing Bong Ding Dong!!</h1>'


@app.route('/process_image', methods=['POST'])
def process_image() -> str:
    print(request.data)
    request_data = json.loads(request.data.decode("utf-8"))
    img_nparr = np.frombuffer(base64.b64decode(request_data['image']), np.uint8)
    img = cv2.imdecode(img_nparr,cv2.IMREAD_COLOR)
    try:
        racist_detector = DeepFace.analyze(img)
        return racist_detector
    except:
        return []

@app.route('/identify_face', methods=['POST'])
def identify_face() -> str:
    request_data = json.loads(request.data.decode("utf-8"))
    target_confidence: float = request_data['target_confidence']
    img_nparr = np.frombuffer(base64.b64decode(request_data['image']), np.uint8)
    img = cv2.imdecode(img_nparr,cv2.IMREAD_COLOR)
    img = cv2.resize(img, (0,0), fx=0.5,fy=0.5)
    img = np.ascontiguousarray(img[:, :, ::-1])
    face_locations = face.face_locations(img)
    face_encodings_img = face.face_encodings(img, face_locations)
    response: list = []
    for face_encoding in face_encodings_img:
        face_distances = face.face_distance(face_encodings, face_encoding)
        index = np.argmin(face_distances)
        confidence = 1-face_distances[index]
        if confidence >= target_confidence:
            response.append({'name':face_names[index],'confidence': confidence})
    return response



if __name__ == '__main__':
    app.run()
