
    >|hT                        d dl Z d dlZd dlZd dlmZmZmZmZmZm	Z	 d dl
Zd dlZd dlZd dlmZmZ d dlmZ d dlmZmZmZmZmZmZmZ d dlmZ  ed      Z ej@                  d	       d
e jB                  d<    ejD                         Z#e#dk(  r* ejH                         jK                  ejL                          ejN                          de(defdZ)	 	 	 	 	 	 	 	 d+dee(ejT                  ee+   f   dee(ejT                  ee+   f   de(de(de(de,de,de-de(de,dee(ef   fdZ.	 	 	 	 	 	 d,dee(ejT                  f   dee/e0f   de,de(de,de-de,deee(ef      fdZ1	 	 	 	 	 	 	 	 	 d-dee(ejT                  f   de(de(de(de,de(de,de-de	e+   de(de,deejd                     fdZ3	 	 	 	 	 	 d.dee(ejT                  f   de(de,de(de,de-de(deee(ef      fd Z4	 	 	 	 	 	 	 	 d/de(de(de(de(d!e,d"ed#e-d$e-ddfd%Z5	 	 	 	 	 	 d0dee(ejT                  f   d&e	ee-e-f      de(de,de,de-d'e,deee(ef      fd(Z6d1d)Z7	 	 	 	 d2dee(ejT                  f   d&e/de(de,de,deejT                  df   fd*Z8y)3    N)AnyDictListTupleUnionOptional)package_utilsfolder_utils)Logger)modelingrepresentationverificationrecognition
demography	detection	streaming)__version__DeepFace)moduleignore3TF_CPP_MIN_LOG_LEVEL   
model_namereturnc                 .    t        j                  |       S )a.  
    This function builds a deepface model
    Args:
        model_name (string): face recognition or facial attribute model
            VGG-Face, Facenet, OpenFace, DeepFace, DeepID for face recognition
            Age, Gender, Emotion, Race for facial attributes
    Returns:
        built_model
    r   )r   build_modelr   s    P/var/www/html/test/engine/venv/lib/python3.12/site-packages/deepface/DeepFace.pyr   r   *   s     :66    	img1_path	img2_pathdetector_backenddistance_metricenforce_detectionalignexpand_percentagenormalizationsilentc
                 @    t        j                  | |||||||||	
      S )a	  
    Verify if an image pair represents the same person or different persons.
    Args:
        img1_path (str or np.ndarray or List[float]): Path to the first image.
            Accepts exact image path as a string, numpy array (BGR), base64 encoded images
            or pre-calculated embeddings.

        img2_path (str or np.ndarray or List[float]): Path to the second image.
            Accepts exact image path as a string, numpy array (BGR), base64 encoded images
            or pre-calculated embeddings.

        model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512,
            OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet (default is VGG-Face).

        detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
            'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8' (default is opencv).

        distance_metric (string): Metric for measuring similarity. Options: 'cosine',
            'euclidean', 'euclidean_l2' (default is cosine).

        enforce_detection (boolean): If no face is detected in an image, raise an exception.
            Set to False to avoid the exception for low-resolution images (default is True).

        align (bool): Flag to enable face alignment (default is True).

        expand_percentage (int): expand detected facial area with a percentage (default is 0).

        normalization (string): Normalize the input image before feeding it to the model.
            Options: base, raw, Facenet, Facenet2018, VGGFace, VGGFace2, ArcFace (default is base)

        silent (boolean): Suppress or allow some log messages for a quieter analysis process
            (default is False).

    Returns:
        result (dict): A dictionary containing verification results with following keys.

        - 'verified' (bool): Indicates whether the images represent the same person (True)
            or different persons (False).

        - 'distance' (float): The distance measure between the face vectors.
            A lower distance indicates higher similarity.

        - 'max_threshold_to_verify' (float): The maximum threshold used for verification.
            If the distance is below this threshold, the images are considered a match.

        - 'model' (str): The chosen face recognition model.

        - 'distance_metric' (str): The chosen similarity metric for measuring distances.

        - 'facial_areas' (dict): Rectangular regions of interest for faces in both images.
            - 'img1': {'x': int, 'y': int, 'w': int, 'h': int}
                    Region of interest for the first image.
            - 'img2': {'x': int, 'y': int, 'w': int, 'h': int}
                    Region of interest for the second image.

        - 'time' (float): Time taken for the verification process in seconds.
    
r!   r"   r   r#   r$   r%   r&   r'   r(   r)   )r   verifyr+   s
             r   r,   r,   7   s6    L )'++# r    img_pathactionsc           	      :    t        j                  | ||||||      S )a  
    Analyze facial attributes such as age, gender, emotion, and race in the provided image.
    Args:
        img_path (str or np.ndarray): The exact path to the image, a numpy array in BGR format,
            or a base64 encoded image. If the source image contains multiple faces, the result will
            include information for each detected face.

        actions (tuple): Attributes to analyze. The default is ('age', 'gender', 'emotion', 'race').
            You can exclude some of these attributes from the analysis if needed.

        enforce_detection (boolean): If no face is detected in an image, raise an exception.
            Set to False to avoid the exception for low-resolution images (default is True).

        detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
            'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8' (default is opencv).

        distance_metric (string): Metric for measuring similarity. Options: 'cosine',
            'euclidean', 'euclidean_l2' (default is cosine).

        align (boolean): Perform alignment based on the eye positions (default is True).

        expand_percentage (int): expand detected facial area with a percentage (default is 0).

        silent (boolean): Suppress or allow some log messages for a quieter analysis process
            (default is False).

    Returns:
        results (List[Dict[str, Any]]): A list of dictionaries, where each dictionary represents
           the analysis results for a detected face. Each dictionary in the list contains the
           following keys:

        - 'region' (dict): Represents the rectangular region of the detected face in the image.
            - 'x': x-coordinate of the top-left corner of the face.
            - 'y': y-coordinate of the top-left corner of the face.
            - 'w': Width of the detected face region.
            - 'h': Height of the detected face region.

        - 'age' (float): Estimated age of the detected face.

        - 'face_confidence' (float): Confidence score for the detected face.
            Indicates the reliability of the face detection.

        - 'dominant_gender' (str): The dominant gender in the detected face.
            Either "Man" or "Woman".

        - 'gender' (dict): Confidence scores for each gender category.
            - 'Man': Confidence score for the male gender.
            - 'Woman': Confidence score for the female gender.

        - 'dominant_emotion' (str): The dominant emotion in the detected face.
            Possible values include "sad," "angry," "surprise," "fear," "happy,"
            "disgust," and "neutral"

        - 'emotion' (dict): Confidence scores for each emotion category.
            - 'sad': Confidence score for sadness.
            - 'angry': Confidence score for anger.
            - 'surprise': Confidence score for surprise.
            - 'fear': Confidence score for fear.
            - 'happy': Confidence score for happiness.
            - 'disgust': Confidence score for disgust.
            - 'neutral': Confidence score for neutrality.

        - 'dominant_race' (str): The dominant race in the detected face.
            Possible values include "indian," "asian," "latino hispanic,"
            "black," "middle eastern," and "white."

        - 'race' (dict): Confidence scores for each race category.
            - 'indian': Confidence score for Indian ethnicity.
            - 'asian': Confidence score for Asian ethnicity.
            - 'latino hispanic': Confidence score for Latino/Hispanic ethnicity.
            - 'black': Confidence score for Black ethnicity.
            - 'middle eastern': Confidence score for Middle Eastern ethnicity.
            - 'white': Confidence score for White ethnicity.
    r-   r.   r%   r#   r&   r'   r)   )r   analyzer0   s          r   r1   r1      s-    f +)+ r    db_path	thresholdc                 B    t        j                  | |||||||||	|
      S )a  
    Identify individuals in a database
    Args:
        img_path (str or np.ndarray): The exact path to the image, a numpy array in BGR format,
            or a base64 encoded image. If the source image contains multiple faces, the result will
            include information for each detected face.

        db_path (string): Path to the folder containing image files. All detected faces
            in the database will be considered in the decision-making process.

        model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512,
            OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet (default is VGG-Face).

        distance_metric (string): Metric for measuring similarity. Options: 'cosine',
            'euclidean', 'euclidean_l2' (default is cosine).

        enforce_detection (boolean): If no face is detected in an image, raise an exception.
            Set to False to avoid the exception for low-resolution images (default is True).

        detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
            'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8' (default is opencv).

        align (boolean): Perform alignment based on the eye positions (default is True).

        expand_percentage (int): expand detected facial area with a percentage (default is 0).

        threshold (float): Specify a threshold to determine whether a pair represents the same
            person or different individuals. This threshold is used for comparing distances.
            If left unset, default pre-tuned threshold values will be applied based on the specified
            model name and distance metric (default is None).

        normalization (string): Normalize the input image before feeding it to the model.
            Options: base, raw, Facenet, Facenet2018, VGGFace, VGGFace2, ArcFace (default is base).

        silent (boolean): Suppress or allow some log messages for a quieter analysis process
            (default is False).

    Returns:
        results (List[pd.DataFrame]): A list of pandas dataframes. Each dataframe corresponds
            to the identity information for an individual detected in the source image.
            The DataFrame columns include:

        - 'identity': Identity label of the detected individual.

        - 'target_x', 'target_y', 'target_w', 'target_h': Bounding box coordinates of the
                target face in the database.

        - 'source_x', 'source_y', 'source_w', 'source_h': Bounding box coordinates of the
                detected face in the source image.

        - 'threshold': threshold to determine a pair whether same person or different persons

        - 'distance': Similarity score between the faces based on the
                specified model and distance metric
    r-   r2   r   r$   r%   r#   r&   r'   r3   r(   r)   )r   findr5   s              r   r6   r6      s9    H '+)+# r    c           	      :    t        j                  | ||||||      S )a  
    Represent facial images as multi-dimensional vector embeddings.

    Args:
        img_path (str or np.ndarray): The exact path to the image, a numpy array in BGR format,
            or a base64 encoded image. If the source image contains multiple faces, the result will
            include information for each detected face.

        model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512,
            OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet
            (default is VGG-Face.).

        enforce_detection (boolean): If no face is detected in an image, raise an exception.
            Default is True. Set to False to avoid the exception for low-resolution images
            (default is True).

        detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
            'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8' (default is opencv).

        align (boolean): Perform alignment based on the eye positions (default is True).

        expand_percentage (int): expand detected facial area with a percentage (default is 0).

        normalization (string): Normalize the input image before feeding it to the model.
            Default is base. Options: base, raw, Facenet, Facenet2018, VGGFace, VGGFace2, ArcFace
            (default is base).

    Returns:
        results (List[Dict[str, Any]]): A list of dictionaries, each containing the
            following fields:

        - embedding (List[float]): Multidimensional vector representing facial features.
            The number of dimensions varies based on the reference model
            (e.g., FaceNet returns 128 dimensions, VGG-Face returns 4096 dimensions).

        - facial_area (dict): Detected facial area by face detection in dictionary format.
            Contains 'x' and 'y' as the left-corner point, and 'w' and 'h'
            as the width and height. If `detector_backend` is set to 'skip', it represents
            the full image area and is nonsensical.

        - face_confidence (float): Confidence score of face detection. If `detector_backend` is set
            to 'skip', the confidence will be 0 and is nonsensical.
    r-   r   r%   r#   r&   r'   r(   )r   	representr8   s          r   r9   r9   <  s-    h ##+)+# r    enable_face_analysissourcetime_thresholdframe_thresholdc           
      n    t        |d      }t        |d      }t        j                  | |||||||       y)a  
    Run real time face recognition and facial attribute analysis

    Args:
        db_path (string): Path to the folder containing image files. All detected faces
            in the database will be considered in the decision-making process.

        model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512,
            OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet (default is VGG-Face).

        detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
            'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8' (default is opencv).

        distance_metric (string): Metric for measuring similarity. Options: 'cosine',
            'euclidean', 'euclidean_l2' (default is cosine).

        enable_face_analysis (bool): Flag to enable face analysis (default is True).

        source (Any): The source for the video stream (default is 0, which represents the
            default camera).

        time_threshold (int): The time threshold (in seconds) for face recognition (default is 5).

        frame_threshold (int): The frame threshold for face recognition (default is 5).
    Returns:
        None
       r2   r   r#   r$   r:   r;   r<   r=   N)maxr   analysisr@   s           r   streamrC   {  sC    L +N/1-O)'1%'	r    target_size	grayscalec           
      <    t        j                  | ||||||d      S )a  
    Extract faces from a given image

    Args:
        img_path (str or np.ndarray): Path to the first image. Accepts exact image path
            as a string, numpy array (BGR), or base64 encoded images.

        target_size (tuple): final shape of facial image. black pixels will be
            added to resize the image (default is (224, 224)).

        detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
            'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8' (default is opencv).

        enforce_detection (boolean): If no face is detected in an image, raise an exception.
            Set to False to avoid the exception for low-resolution images (default is True).

        align (bool): Flag to enable face alignment (default is True).

        expand_percentage (int): expand detected facial area with a percentage (default is 0).

        grayscale (boolean): Flag to convert the image to grayscale before
            processing (default is False).

    Returns:
        results (List[Dict[str, Any]]): A list of dictionaries, where each dictionary contains:

        - "face" (np.ndarray): The detected face as a NumPy array.

        - "facial_area" (Dict[str, Any]): The detected face's regions as a dictionary containing:
            - keys 'x', 'y', 'w', 'h' with int values
            - keys 'left_eye', 'right_eye' with a tuple of 2 ints as values

        - "confidence" (float): The confidence score associated with the detected face.
    T)r-   rD   r#   r%   r&   r'   rE   human_readable)r   extract_faces)r-   rD   r#   r%   r&   r'   rE   s          r   rH   rH     s0    X "")++	 	r    c                  ,    ddl } | j                          y)zG
    command line interface function will be offered in this block
    r   N)fireFire)rJ   s    r   clirL     s     IIKr    c                     t         j                  d       t        | ||||d      }d}t        |      dkD  r|d   d   }|S )a  
    Deprecated face detection function. Use extract_faces for same functionality.

    Args:
        img_path (str or np.ndarray): Path to the first image. Accepts exact image path
            as a string, numpy array (BGR), or base64 encoded images.

        target_size (tuple): final shape of facial image. black pixels will be
            added to resize the image (default is (224, 224)).

        detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
            'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8' (default is opencv).

        enforce_detection (boolean): If no face is detected in an image, raise an exception.
            Set to False to avoid the exception for low-resolution images (default is True).

        align (bool): Flag to enable face alignment (default is True).

    Returns:
        img (np.ndarray): detected (and aligned) facial area image as numpy array
    z=Function detectFace is deprecated. Use extract_faces instead.F)r-   rD   r#   r%   r&   rE   Nr   face)loggerwarnrH   len)r-   rD   r#   r%   r&   	face_objsextracted_faces          r   
detectFacerT     sT    8 KKOP)+I N
9~"1f-r    )VGG-FaceopencvcosineTTr   baseF))emotionagegenderraceTrV   Tr   F)	rU   rW   TrV   Tr   NrX   F)rU   TrV   Tr   rX   ) rU   rV   rW   Tr      r^   )   r`   rV   TTr   F)r   N)r_   rV   TT)9oswarningsloggingtypingr   r   r   r   r   r   numpynppandaspd
tensorflowtfdeepface.commonsr	   r
   deepface.commons.loggerr   deepface.modulesr   r   r   r   r   r   r   deepfacer   rO   filterwarningsenvironget_tf_major_version
tf_version
get_loggersetLevelERRORinitialize_folderstrr   ndarrayfloatboolintr,   tuplelistr1   	DataFramer6   r9   rC   rH   rL   rT    r    r   <module>r      s   	   : :    9 *   !	z	"
    !%(

! "/]//1
?BMMOW]]+     
7C 
7C 
7  !$#"QS"**d5k12QS"**d5k12Q Q 	Q
 Q Q Q Q Q Q 
#s(^Ql #G"$[CO$[5$;[ [ 	[
 [ [ [ 
$sCx.[B !#"$!%PCO$PP P 	P
 P P P P P P P 
",,Pj !"$<CO$<< < 	<
 < < < 
$sCx.<@  $#!%222 2 	2
 2 2 2 2 
2n .8$"5CO$5%S/*5 5 	5
 5 5 5 
$sCx.5p $$"(CO$(( ( 	(
 ( 2::t(r    