
    >|hU8                         d dl Z d dlmZmZmZmZmZ d dlZd dl	m
Z
mZmZ d dlmZ d dlmZ  ed      Z	 	 	 	 	 	 	 	 d deeej&                  ee   f   d	eeej&                  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j&                  f   d
ededededededeeee      ee   f   fdZdeej&                  ef   deej&                  ef   dej6                  fdZdeej&                  ef   deej&                  ef   dej6                  fdZdeej&                  ef   dej&                  fdZdeej&                  ef   deej&                  ef   dedej6                  fdZd
ededefdZ y)"    N)AnyDictUnionListTuple)representation	detectionmodeling)FacialRecognition)Loggerz deepface/modules/verification.py)module	img1_path	img2_path
model_namedetector_backenddistance_metricenforce_detectionalignexpand_percentagenormalizationsilentreturnc
                    t        j                          }
t        j                  |      }|j                  }t	        | t
              rmt        d | D              st        d      |	du rt        j                  d| d       t        |       |k7  rt        d| d| dt        |        d	      | g}d
g}n	 t        | ||||||      \  }}t	        |t
              rmt        d |D              st        d      |	du rt        j                  d| d       t        |      |k7  rt        d| d| dt        |       d	      |g}d
g}n	 t        |||||||      \  }}d
d
d
d
d
d
d}g }g }t        |      D ]W  \  }}t        |      D ]D  \  }}t        |||      }|j                  |       |j                  ||   xs |||   xs |f       F Y t        ||      }t!        t#        |            }|t%        j&                  |         }t        j                          }||k  ||||||d   |d   dt)        ||
z
  d      d}|S # t        $ r}t        d      |d
}~ww xY w# t        $ r}t        d      |d
}~ww xY w)a   
    Verify if an image pair represents the same person or different persons.

    The verification function converts facial images to vectors and calculates the similarity
    between those vectors. Vectors of images of the same person should exhibit higher similarity
    (or lower distance) than vectors of images of 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  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.

        - '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.

        - 'similarity_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.
    c              3   <   K   | ]  }t        |t                y wN
isinstancefloat.0dims     \/var/www/html/test/engine/venv/lib/python3.12/site-packages/deepface/modules/verification.py	<genexpr>zverify.<locals>.<genexpr>c        ?c:c5)?   zNWhen passing img1_path as a list, ensure that all its items are of type float.FzmYou passed 1st image as pre-calculated embeddings.Please ensure that embeddings have been calculated for the z model.zembeddings of z should have z dimensions, but it has z dimensions inputN)img_pathr   r   r   r   r   r   z$Exception while processing img1_pathc              3   <   K   | ]  }t        |t                y wr   r   r   s     r"   r#   zverify.<locals>.<genexpr>   r$   r%   zNWhen passing img2_path as a list, ensure that all its items are of type float.zmYou passed 2nd image as pre-calculated embeddings.Please ensure that embeddings have been calculated for the z$Exception while processing img2_path)xywhleft_eye	right_eyer      )img1img2   )verifieddistance	thresholdmodelr   similarity_metricfacial_areastime)r8   r
   build_modeloutput_shaper   listall
ValueErrorloggerwarnlen__extract_faces_and_embeddings	enumeratefind_distanceappendfind_thresholdr   minnpargminround)r   r   r   r   r   r   r   r   r   r   ticr5   dimsimg1_embeddingsimg1_facial_areaserrimg2_embeddingsimg2_facial_areasno_facial_area	distancesr7   idximg1_embeddingidyimg2_embeddingr3   r4   tocresp_objs                                r"   verifyrY      s0   V ))+C'33J?ED )T"?Y??`  U?KKNNX\Y`b
 y>T! M$ @"9~..?A 
 %+!F	N1O"%!1"3"3+2.O. )T"?Y??`  U?KKNNX\Y`b
 y>T! M$ @"9~..?A 
 %+!F	N1O"%!1"3"3+2.O. N IL(9 ^#,_#= 	C$^^_UHX&"3'9>;LS;Q;cUcd	 z?;IS^$H		) 45L
))+C 	),,!-a,q/JcCi#	H OY  	NCD#M	NH  	NCD#M	Ns0   4I  I  	I	II	I7&I22I7r&   c           	      0   g }g }t        j                  |      }	|	j                  }
t        j                  | |
|d|||      }|D ]M  }t        j                  |d   ||d||      }|d   d   }|j                  |       |j                  |d          O ||fS )	z
    Extract facial areas and find corresponding embeddings for given image
    Returns:
        embeddings (List[float])
        facial areas (List[dict])
    F)r&   target_sizer   	grayscaler   r   r   faceskip)r&   r   r   r   r   r   r   	embeddingfacial_area)r
   r9   input_shaper	   extract_facesr   	representrD   )r&   r   r   r   r   r   r   
embeddingsr7   r5   r[   img_objsimg_objimg_embedding_objimg_embeddings                  r"   rA   rA      s     JL'33J?E##K&&)++H  4*44V_!/#'
 *!,[9-(GM234 |##    source_representationtest_representationc                    t        | t              rt        j                  |       } t        |t              rt        j                  |      }t        j                  t        j
                  |       |      }t        j                  t        j                  | |             }t        j                  t        j                  ||            }d|t        j                  |      t        j                  |      z  z  z
  S )a  
    Find cosine distance between two given vectors
    Args:
        source_representation (np.ndarray or list): 1st vector
        test_representation (np.ndarray or list): 2nd vector
    Returns
        distance (np.float64): calculated cosine distance
    r.   )	r   r;   rG   arraymatmul	transposesummultiplysqrt)rj   rk   abcs        r"   find_cosine_distancerv     s     '. ")> ?%t, hh':;
		",,457JKA
r{{02GHIA
r{{.0CDEARWWQZ"''!*,-..ri   c                     t        | t              rt        j                  |       } t        |t              rt        j                  |      }| |z
  }t        j                  t        j
                  ||            }t        j                  |      }|S )a
  
    Find euclidean distance between two given vectors
    Args:
        source_representation (np.ndarray or list): 1st vector
        test_representation (np.ndarray or list): 2nd vector
    Returns
        distance (np.float64): calculated euclidean distance
    )r   r;   rG   rm   rp   rq   rr   )rj   rk   euclidean_distances      r"   find_euclidean_distancery     sx     '. ")> ?%t, hh':;.1DD,>@R ST!34ri   r(   c           	          t        | t              rt        j                  |       } | t        j                  t        j
                  t        j                  | |                   z  S )z
    Normalize input vector with l2
    Args:
        x (np.ndarray or list): given vector
    Returns:
        y (np.ndarray): l2 normalized vector
    )r   r;   rG   rm   rr   rp   rq   )r(   s    r"   l2_normalizer{   /  sC     !THHQKrwwrvvbkk!Q/0111ri   alpha_embeddingbeta_embeddingc                     |dk(  rt        | |      }|S |dk(  rt        | |      }|S |dk(  r t        t        |       t        |            }|S t        d|      )a%  
    Wrapper to find distance between vectors according to the given distance metric
    Args:
        source_representation (np.ndarray or list): 1st vector
        test_representation (np.ndarray or list): 2nd vector
    Returns
        distance (np.float64): calculated cosine distance
    cosine	euclideaneuclidean_l2z!Invalid distance_metric passed - )rv   ry   r{   r=   )r|   r}   r   r3   s       r"   rC   rC   <  sv     ("'H O 
K	'*?NK O 
N	**)<+G

 O <oNNri   c                     dddd}ddddddddd	d
ddddddddddddddddddddddddddddddd
}|j                  | |      j                  |d      }|S )aE  
    Retrieve pre-tuned threshold values for a model and distance metric pair
    Args:
        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 (str): distance metric name. Options are cosine, euclidean
            and euclidean_l2.
    Returns:
        threshold (float): threshold value for that model name and distance metric
            pair. Distances less than this threshold will be classified same person.
    g?g?g      ?)r   r   r   g(\?gQ?
   g?g333333?g(\7@gp=
ף?g@gGz?gQ?g333333?g`"?g+w%@gzG?g?gq=
ףp?@   g{Gz?gQ?-   g(\?g?g{GA@g?)
VGG-FaceFacenet
Facenet512ArcFaceDlibSFaceOpenFaceDeepFaceDeepIDGhostFaceNet)get)r   r   base_threshold
thresholdsr4   s        r"   rE   rE   V  s     !%4NN
  

 #TJ!%E4P"tLc3G!N#$M#"dK"TJ#'eTRJ$ z>:>>PSTIri   )r   opencvr   TTr   baseF)r   r   TTr   r   )!r8   typingr   r   r   r   r   numpyrG   deepface.modulesr   r	   r
   !deepface.models.FacialRecognitionr   deepface.commons.loggerr   r>   strndarrayr   boolintrY   dictrA   r;   float64rv   ry   r{   rC   rE    ri   r"   <module>r      s    0 0  A @ ? *	9	: !$#"}S"**d5k12}S"**d5k12} } 	}
 } } } } } } 
#s(^}D !$".$CO$.$.$ .$ 	.$
 .$ .$ .$ 4Ud4j().$b/ T!12/INrzz[_O_I`/ZZ/. T!12INrzz[_O_I`ZZ.
2E"**d*+ 
2

 
22::t+,"**d*+  ZZ	4#s #S #U #ri   