import face_recognition
import openpyxl
import os
import math

# Dossier contenant les photos
PHOTOS_FOLDER = "photos"
EXCEL_FILE = "eleves.xlsx"

def angle_between_eyes(landmarks):
    left_eye = landmarks['left_eye']
    right_eye = landmarks['right_eye']

    # Centre de chaque œil
    lx = sum([p[0] for p in left_eye]) / len(left_eye)
    ly = sum([p[1] for p in left_eye]) / len(left_eye)
    rx = sum([p[0] for p in right_eye]) / len(right_eye)
    ry = sum([p[1] for p in right_eye]) / len(right_eye)

    dx = rx - lx
    dy = ry - ly

    angle = math.degrees(math.atan2(dy, dx))
    return angle

def verifier_orientation_photo(nom_photo):
    chemin = os.path.join(PHOTOS_FOLDER, nom_photo)
    if not os.path.isfile(chemin):
        return "❌ Fichier manquant"

    image = face_recognition.load_image_file(chemin)
    visages = face_recognition.face_landmarks(image)

    if not visages:
        return "❌ Aucun visage détecté"

    angle = angle_between_eyes(visages[0])
    if abs(angle) > 10:
        return f"⚠️ Photo mal orientée (angle: {angle:.2f}°)"
    else:
        return f"✅ OK (angle: {angle:.2f}°)"

def lire_excel_et_verifier():
    wb = openpyxl.load_workbook(EXCEL_FILE)
    sheet = wb.active

    col_photo = None
    for i, cell in enumerate(sheet[1], start=1):
        if "photo" in str(cell.value).lower():
            col_photo = i
            break

    if col_photo is None:
        print("Impossible de trouver la colonne 'photo' dans le fichier Excel.")
        return

    for row in sheet.iter_rows(min_row=2):
        nom_photo = row[col_photo - 1].value
        if nom_photo:
            resultat = verifier_orientation_photo(nom_photo)
            print(f"{nom_photo}: {resultat}")

if __name__ == "__main__":
    lire_excel_et_verifier()
