
    >|h9                        d dl Z d dlZd dl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 d dlmZ d dlmZ d dlmZmZmZmZ d dlmZ  ed	      Z	 	 	 	 	 	 	 	 	 dd
eee
j6                  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j>                     fdZ dedee   fdZ!	 	 	 	 	 	 	 	 ddee   dede"dededededededeedef      fdZ#y)    N)ListUnionOptionalDictAny)tqdm)Logger)package_utils)representation	detectionmodelingverification)FacialRecognitionzdeepface/modules/recognition.py)moduleimg_pathdb_path
model_namedistance_metricenforce_detectiondetector_backendalignexpand_percentage	thresholdnormalizationsilentreturnc                    t        j                          }t        j                  j                  |      durt	        d      t        j                  |      }|j                  }d| d| d}|j                  dd      j                         }t        j                  j                  ||      }g }g d}t        j                  j                  |      s+t        |d	      5 }t        j                  g |       d
d
d
       t        |d      5 }t        j                  |      }d
d
d
       t!        |      D ]T  \  }}t#        t%        |      t%        |j'                               z
        }t)        |      dkD  sCt	        | d| d|        |D cg c]  }|d   	 }}t+        |      }t)        |      dk(  rt	        d|       d}t#        t%        |      t%        |      z
        }t#        t%        |      t%        |      z
        }g }|D ]V  }|d   }||v r|d   }t-        j.                  |      }||k7  s-t0        j3                  d| d       |j5                  |       X |
sdt)        |      dkD  st)        |      dkD  st)        |      dkD  r:t0        j7                  dt)        |       dt)        |       dt)        |       d       ||z   }||z   }t)        |      dkD  r|D  cg c]  } | d   |vs|  }} d}t)        |      dkD  r|t9        |||||||	|
      z  }d}|rQt        |d	      5 }t        j                  ||       d
d
d
       |
s$t0        j7                  dt)        |       d|        t)        |      dk(  r4|
s0t        j                          }!t0        j7                  d|!|z
   d       g S t;        j<                  |      }"|
du r)t0        j7                  d|  d |"j>                  d    d!       tA        jB                  | ||d|||"      }#g }$|#D ]  }%|%d#   }&|%d$   }'tE        jF                  |&||d%||	&      }(|(d   d'   })|"jI                         }*|'d(   |*d)<   |'d*   |*d+<   |'d,   |*d-<   |'d.   |*d/<   g }+|"jK                         D ]  \  },}-|-d'   }.|.|+j5                  tM        d0             (t)        t#        |)            }/t)        t#        |.            }0|/|0k7  rt	        d1|/ d2|0 d3z   d4z         tO        jP                  |.|)|      }1|+j5                  |1        |xs tO        jR                  ||      }2|2|*d5<   |+|*d6<   |*jU                  d'g7      }*|*|*d6   |2k     }*|*jW                  d6gd8      jY                  d9      }*|$j5                  |*        |
s0t        j                          }!t0        j7                  d|!|z
   d       |$S # 1 sw Y   xY w# 1 sw Y   xY wc c}w c c} w # 1 sw Y   xY w):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'.

        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.

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

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

        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.
            Default is base. Options: base, raw, Facenet, Facenet2018, VGGFace, VGGFace2, ArcFace

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

    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
    TzPassed db_path does not exist!ds__z_v2.pkl- identityhash	embeddingtarget_xtarget_ytarget_wtarget_hwbNrbr   z,-th item does not have some required keys - z.Consider to delete r#   )pathzNo item found in Fr$   zEven though z) represented before, it's replaced later.zFound z newly added image(s), z removed image(s), z replaced image(s).)	employeesr   target_sizer   r   r   r   r   zThere are now z representations in zfind function duration z secondsz
Searching z in z length datastorer   r.   r   	grayscaler   r   r   facefacial_areaskipr   r   r   r   r   r   r%   xsource_xysource_ywsource_whsource_hinfz;Source and target embeddings must have same dimensions but :z. Model structure may changez9 after pickle created. Delete the {file_name} and re-run.r   distance)columns)by	ascending)drop)-timeosr,   isdir
ValueErrorr   build_modelinput_shapereplacelowerjoinexistsopenpickledumpload	enumeratelistsetkeyslen__list_imagesr
   find_hash_of_fileloggerdebugappendinfo__find_bulk_embeddingspd	DataFrameshaper   extract_facesr   	representcopyiterrowsfloatr   find_distancefind_thresholdrC   sort_valuesreset_index)3r   r   r   r   r   r   r   r   r   r   r   ticmodelr.   	file_namedatastore_pathrepresentationsdf_colsficurrent_representationmissing_keysr   pickled_imagesstorage_imagesmust_save_pickle
new_images
old_imagesreplaced_imagesr#   
alpha_hash	beta_hashreptocdfsource_objsresp_obj
source_obj
source_imgsource_regiontarget_embedding_objtarget_representation	result_df	distancesr   instancesource_representationtarget_dimssource_dimsr?   target_thresholds3                                                      [/var/www/html/test/engine/venv/lib/python3.12/site-packages/deepface/modules/recognition.pyfindr      s   J ))+C 
ww}}WT)9::'33J?E##K j\#3"4G<I!!#r*002IWW\\'95NOG 77>>.).$' 	1KKA	 
nd	# )q ++a.) &/%? !!CL3/E/J/J/L+MMN|q #A, P&&4%57  HWW^nZ0WNW #0N
>a,WI677 c.)C,??@Jc.)C,??@J O"1 -)*5z!+F3
!33H=	"LL<z1Z[\""8,- s:*c*o.ASEY\]E]S_% &Z! "_%&&9;	
 o-Jo-J :*9_3S_T^=^3__ :1 !#-/'	
 		
  .$' 	,1KK+	,KK._)=(>>RS\R]^_ ?q ))+CKK1#)HEF	 
o	&Bj
$rxx{m;LMN )))++K H! 5#
'
"=1-77!/#' 
 !5Q 7 DGGI	 -c 2	* -c 2	* -c 2	* -c 2	*	;;= 	'KAx$,[$9!$,  u.d#89:Kd#89:Kk) Q$Q{m3OPQQR  $11%'<oH X&'	', %`(C(CJP_(`!1	+ )	*NNK=N9	i
37GGH	))j\T)JVV\`Va		"k5#r iik-cCi[ABOM	 	) ) XL `$	, 	,s6   WWW%"W*/W*+W/WW"/W9r,   c                     g }t        j                  |       D ]^  \  }}}|D ]S  }|j                         j                  d      s#t         j                  j                  ||      }|j                  |       U ` |S )z
    List images in a given path
    Args:
        path (str): path's location
    Returns:
        images (list): list of exact image paths
    )z.jpgz.jpegz.png)rE   walkrK   endswithr,   rL   r[   )r,   imagesrr   rp   file
exact_paths          r   rW   rW      sq     F774= *1a 	*Dzz|$$%>?WW\\!T2
j)	**
 M    r-   r.   strc	                    g }	t        | d|      D ]  }
t        j                  |
      }	 t        j                  |
||d|||      }t        |      dk(  r|	j                  |
|dddddd	       ]|D ]T  }|d
   }|d   }t        j                  |||d||      }|d   d   }|	j                  |
|||d   |d   |d   |d   d	       V  |	S # t
        $ r0}t        j                  d|
 dt        |              g }Y d}~d}~ww xY w)a  
    Find embeddings of a list of images

    Args:
        employees (list): list of exact image paths

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

        target_size (tuple): expected input shape of facial recognition model

        detector_backend (str): face detector model name

        enforce_detection (bool): set this to False if you
            want to proceed when you cannot detect any face

        align (bool): enable or disable alignment of image
            before feeding to facial recognition model

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

        normalization (bool): normalization technique

        silent (bool): enable or disable informative logging
    Returns:
        representations (list): pivot list of dict with
            image name, hash, embedding and detected face area's coordinates
    zFinding representations)descdisableFr/   z&Exception while extracting faces from z: Nr   r"   r1   r2   r3   r4   r%   r5   r7   r9   r;   )r   r
   rX   r   ra   rG   rY   errorr   rV   r[   r   rb   )r-   r   r.   r   r   r   r   r   r   rn   employee	file_hashimg_objserrimg_objimg_content
img_regionembedding_objimg_representations                      r   r]   r]   1  sj   P O& :
 "33H=		 ..!'!1"3"3H x=A"" (%!% ! ! ! !
 $ %fo$]3
 . 8 8()&7%+"/! &31%5k%B"&&$, )%7$.sO$.sO$.sO$.sO
G:x U  	LLA(2cRUhZXYH	s   C	D&C??D)	VGG-FacecosineTopencvTr   NbaseF)r   )   r   r   TTr   r   F)$rE   rO   typingr   r   r   r   r   rD   numpynppandasr^   r   deepface.commons.loggerr	   deepface.commonsr
   deepface.modulesr   r   r   r   !deepface.models.FacialRecognitionr   rY   r   ndarrayboolintre   r_   r   rW   tupler]    r   r   <module>r      s   	  3 3     + * N N ?	8	9 !#"$!%HCO$HH H 	H
 H H H H H H H 
",,HV S	 & !#$"eCyee e 	e
 e e e e e 
$ucz
er   