
    >|h3{                        d dl Z d dlZd dl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  ed      Zde j$                  d	<   d
ZdZ	 	 	 	 	 	 	 d3defdZdedefdZdej2                  dededededeee   eej2                     f   fdZdeddfdZdej2                  deeeeeef      dej2                  fdZdej2                  deeeeeef      dededej2                  f
dZdeej2                     de dedeej2                     fdZ!	 d4dej2                  ded eeef   d!edeeeeeef      f
d"Z"dej2                  deeeeeef      deej2                     fd#Z#dej2                  d$eej2                     deeeeeef      dededededej2                  fd%Z$dedej2                  deeeeeef      d$eej2                     dej2                  f
d&Z%dej2                  d'ej2                  d(ed)ed*ed+ed,edej2                  fd-Z&dej2                  d.e'd)ed*ed+ed,edej2                  fd/Z(dej2                  d0e d1ed)ed*ed+ed,edej2                  fd2Z)y)5    N)ListTupleOptional)DeepFace)FacialRecognition)Loggerzcommons.realtime)module2TF_CPP_MIN_LOG_LEVELp      r   r   db_pathc           	      8   t        |       t        |      }t        t        j                  g d      | |||      }	d}
d}d}t        j
                         }t        j                  |      }	 |j                         \  }}|snr|j                         }g }|du rt        |||	      }t        ||
      }t        ||
      }t        ||||      }t        |      r|dz   nd}|dkD  xr ||z  dk(  }|rt        ||
      }t        ||||      }t!        |||| |||      }|j                         }
t        j
                         }t"        j%                  d       nK|du rGt        j
                         |z
  |kD  r-d}d}
t        j
                         }t"        j%                  d       t'        |
||      }
t        j(                  d|
|n|
       t        j*                  d      dz  t-        d      k(  rn|j/                          t        j0                          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
    enable_face_analysis
model_name)   r      detected_facer   detector_backenddistance_metricr   NFr   T)imgr   target_size)r   faces_coordinates)r   r   frame_thresholdnum_frames_with_faces   )r   r   r   detected_faces)r   r   r!   r   r   r   r   freezedzfreeze released)r   tictime_thresholdr   r   q)build_demography_modelsbuild_facial_recognition_modelsearch_identitynpzerostimecv2VideoCapturereadcopygrab_facial_areasextract_facial_areashighlight_facial_areascountdown_to_freezelenperform_demography_analysisperform_facial_recognitionloggerinfocountdown_to_releaseimshowwaitKeyordreleasedestroyAllWindows)r   r   r   r   r   sourcer$   r   r   _freezed_imgfreezer   r#   cap	has_framer   raw_imgr   r!   s                       Y/var/www/html/test/engine/venv/lib/python3.12/site-packages/deepface/modules/streaming.pyanalysisrG      s   L 1EF0JGKhh}-)'	A KF
))+C


6
"C
	3 ((*U? 1*:! 2cM^_N(SDUVC%"3 /&;	C BEEVAW$9A$=]^!*Q._3H?3Z^_3_F,L]^ 2)=&7#1	 1&7#1#%5$3) "hhj iikI&t^		c 1N BFK))+CKK)**{Tbc

5!4#+F;;q>D CH,O T KKM    r   returnc                 v    t        j                  |       }t        j                  |  d       |j                  S )aN  
    Build facial recognition model
    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).
    Returns
        input_shape (tuple): input shape of given facial recognitio n model.
    r   z	 is built)r   build_modelr7   r8   input_shape)r   models     rF   r'   r'      s3      (33zJE
KK:,i()rH   r   r   r   c           	      h   d}	 t        j                  | ||||dd      }t        |      dk(  ry	|d   }|j                  d   dk(  ry	|j                  d   }	|	d
   }t        j                  d|        t        j                  |t        t        f|dd      }
t        |
      dk(  r|
d   }|d   }|dz  }|dddddddf   }nt        j                  |      }|j                  d      d   |fS # t        $ r9}d| t        |      v rt        j                  d| d       g }n|Y d}~d}~ww xY w)a  
    Search an identity in facial database.
    Args:
        detected_face (np.ndarray): extracted individual facial image
        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).
    Returns:
        result (tuple): result consisting of following objects
            identified image path (str)
            identified image itself (np.ndarray)
    NFT)img_pathr   r   r   r   enforce_detectionsilentzNo item found in zNo item is found in z6.So, no facial recognition analysis will be performed.r   )NNidentityzHello, )rO   r   r   rP   alignr    facer   /)r   find
ValueErrorstrr7   warnr4   shapeilocr8   extract_facesIDENTIFIED_IMG_SIZEr,   imreadsplit)r   r   r   r   r   target_pathdfserrdf	candidatetarget_objs
target_obj
target_imgs                rF   r(   r(      so   0 Kmm"!-+#
$ 3x1} 
QB	xx{a
IJ'K
KK'+'( (((*=>)K ;1 ^
'
c
1dd
+
ZZ,
S!"%z11W  wi(CH4KK&wi 0H H CI s   C/ /	D18.D,,D1r   c                    | du ryt        j                  d       t        j                  d       t        j                  d       t        j                  d       t        j                  d       t        j                  d	       y)
z
    Build demography analysis models
    Args:
        enable_face_analysis (bool): Flag to enable face analysis (default is True).
    Returns:
        None
    FNAger   zAge model is just builtGenderzGender model is just builtEmotionzEmotion model is just built)r   rK   r7   r8   r   s    rF   r&   r&      s`     u$E*
KK)*H-
KK,-I.
KK-.rH   r   r   c                 d    |D ]*  \  }}}}t        j                  | ||f||z   ||z   fdd       , | S )a  
    Highlight detected faces with rectangles in the given image
    Args:
        img (np.ndarray): image itself
        faces_coordinates (list): list of face coordinates as tuple with x, y, w and h
    Returns:
        img (np.ndarray): image with highlighted facial areas
    C   ro   ro   r    )r,   	rectangle)r   r   xywhs         rF   r2   r2     sH     ( D
1acAq6AE1q5><CD JrH   r   r   c                     |D ]_  \  }}}}t        j                  | t        |||z  z
        t        ||dz  z         t        ||dz  z         ft         j                  ddd       a | S )a  
    Highlight time to freeze in the image's facial areas
    Args:
        img (np.ndarray): image itself
        faces_coordinates (list): list of face coordinates as tuple with x, y, w and h
        frame_threshold (int): how many sequantial frames required with face(s) to freeze
        num_frames_with_faces (int): how many sequantial frames do we have with face(s)
    Returns:
        img (np.ndarray): image with counter values
             ?r      )r,   putTextrY   intFONT_HERSHEY_SIMPLEX)r   r   r   r   rq   rr   rs   rt   s           rF   r3   r3   !  sw      ( 	

1a#8?#JKLQU^SQW-.$$	
	
 JrH   r#   r$   c           	          | | S t        j                          }t        |||z
  z
  dz         }t        j                  | dddd       t        j                  | t        |      dt        j                  ddd       | S )a:  
    Highlight time to release the freezing in the image top left area
    Args:
        img (np.ndarray): image itself
        tic (float): time specifying when freezing started
        time_threshold (int): freeze time threshold
    Returns:
        img (np.ndarray): image with time to release the freezing
    r    )
   r}   )Z   2   rn   i)(   r   r   )r+   rz   r,   rp   ry   rY   r{   )r   r#   r$   toc	time_lefts        rF   r9   r9   >  sw     {

))+CNcCi0145IMM#x<=KKI  		 JrH   r   	thresholdc                     	 t        j                  | ||d      }|D cg c]+  }|d   d   |kD  r|d   d   |d   d   |d   d   |d   d   f- }}|S c c}w #  g cY S xY w)a  
    Find facial area coordinates in the given image
    Args:
        img (np.ndarray): image itself
        detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
            'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8' (default is opencv).
        target_size (tuple): input shape of the facial recognition model.
        threshold (int): threshold for facial area, discard smaller ones
    Returns
        result (list): list of tuple with x, y, w and h coordinates
    r   )rO   r   r   expand_percentagefacial_arears   rq   rr   rt   )r   r]   )r   r   r   r   	face_objsface_objfacess          rF   r0   r0   \  s    **-#
	 &	
 &s+i7 ',',',',		
 	
 	
	s   A 0AA A Ac                     g }|D ]M  \  }}}}| t        |      t        ||z         t        |      t        ||z         f   }|j                  |       O |S )a0  
    Extract facial areas as numpy array from given image
    Args:
        img (np.ndarray): image itself
        faces_coordinates (list): list of facial area coordinates as tuple with
            x, y, w and h values
    Returns:
        detected_faces (list): list of detected facial area images
    )rz   append)r   r   r!   rq   rr   rs   rt   r   s           rF   r1   r1     sg     N' -
1aCFSQZ/Q#a!e*1DDEm,- rH   r!   c           
          t        |      D ]7  \  }\  }}	}
}||   }t        |||||      \  }}|&t        | ||||	|
|      } 9 | S )a  
    Perform facial recognition
    Args:
        img (np.ndarray): image itself
        detected_faces (list): list of extracted detected face images as numpy
        faces_coordinates (list): list of facial area coordinates as tuple with
            x, y, w and h values
        db_path (string): Path to the folder containing image files. All detected faces
            in the database will be considered in the decision-making process.
        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).
        model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512,
            OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet (default is VGG-Face).
    Returns:
        img (np.ndarray): image with identified face informations
    r   )r   rh   labelrq   rr   rs   rt   )	enumerater(   overlay_identified_face)r   r!   r   r   r   r   r   idxrq   rr   rs   rt   r   target_labelrh   s                  rF   r6   r6     s    6 ''89 
\aAq&s+#2'-+!$
 j %!

, JrH   c           
         | du r|S t        |      D ]l  \  }\  }}}}||   }	t        j                  |	dddd      }
t        |
      dk(  r9|
d   }t	        ||d   ||||      }t        ||d	   |d
   dd ||||      }n |S )a  
    Perform demography analysis on given image
    Args:
        enable_face_analysis (bool): Flag to enable face analysis.
        img (np.ndarray): image itself
        faces_coordinates (list): list of face coordinates as tuple with
            x, y, w and h values
        detected_faces (list): list of extracted detected face images as numpy
    Returns:
        img (np.ndarray): image with analyzed demography information
    F)agegenderemotionskipT)rO   actionsr   rP   rQ   r   r   )r   emotion_probasrq   rr   rs   rt   r   dominant_genderr    )r   apparent_ager   rq   rr   rs   rt   )r   r   analyzer4   overlay_emotionoverlay_age_gender)r   r   r   r!   r   rq   rr   rs   rt   r   demographies
demographys               rF   r5   r5     s    " u$
&'89 
\aAq&s+''"0##
 |! "!_
#j6KqTUYZ^_` #E*/015
#
4 JrH   rh   r   rq   rr   rs   rt   c           
         	 |t         z
  dkD  r||z   t         z   | j                  d   k  ri|| |t         z
  |||z   ||z   t         z   f<   | j                         }d}t        j                  | ||z   |f||z   t         z   |dz   fdt        j
                         t        j                  ||| d|z
  d|        t        j                  | |||z   |dz   ft        j                  dt        d       t        j                  | |t        |dz        z   |f|d	t        |d
z        z  z   |t        t         dz        z
  fdd       t        j                  | |d	t        |d
z        z  z   |t        t         dz        z
  f||z   |t        t         dz        z
  fdd       | S ||z   t         z   | j                  d   k  r|t         z
  dkD  r|| ||z   ||z   t         z   |t         z
  |f<   | j                         }d}t        j                  | |t         z
  ||z   dz
  f|||z   fdt        j
                         t        j                  ||| d|z
  d|        t        j                  | ||t         z
  ||z   dz
  ft        j                  dt        d       t        j                  | |t        |dz        z   ||z   f|t        |dz        z   t        |d
z        z
  ||z   t        t         dz        z   fdd       t        j                  | |t        |dz        z   t        |d
z        z
  ||z   t        t         dz        z   f|||z   t        t         dz        z   fdd       | S |t         z
  dkD  r|t         z
  dkD  rv|| |t         z
  ||t         z
  |f<   | j                         }d}t        j                  | |t         z
  |f||dz   fdt        j
                         t        j                  ||| d|z
  d|        t        j                  | ||t         z
  |dz   ft        j                  dt        d       t        j                  | |t        |dz        z   |f|t        |dz        z   t        |d
z        z
  |t        t         dz        z
  fdd       t        j                  | |t        |dz        z   t        |d
z        z
  |t        t         dz        z
  f||t        t         dz        z
  fdd       | S ||z   t         z   | j                  d   k  r||z   t         z   | j                  d   k  r|| ||z   ||z   t         z   ||z   ||z   t         z   f<   | j                         }d}t        j                  | ||z   ||z   dz
  f||z   t         z   ||z   fdt        j
                         t        j                  ||| d|z
  d|        t        j                  | |||z   ||z   dz
  ft        j                  dt        d       t        j                  | |t        |dz        z   ||z   f|t        |dz        z   t        |d
z        z   ||z   t        t         dz        z   fdd       t        j                  | |t        |dz        z   t        |d
z        z   ||z   t        t         dz        z   f||z   ||z   t        t         dz        z   fdd       | S t        j                  d       	 | S # t        $ r)}	t        j                  t!        |	             Y d}	~	| S d}	~	ww xY w)a  
    Overlay the identified face onto image itself
    Args:
        img (np.ndarray): image itself
        target_img (np.ndarray): identified face's image
        label (str): name of the identified face
        x (int): x coordinate of the face on the given image
        y (int): y coordinate of the face on the given image
        w (int): w coordinate of the face on the given image
        h (int): h coordinate of the face on the given image
    Returns:
        img (np.ndarray): image with overlayed identity
    r   r    皙?   .      r   r}         ?rx   r   rv   rn   z/cannot put facial recognition info on the imageN)r^   r[   r/   r,   rp   FILLEDaddWeightedry   r{   
TEXT_COLORlinerz   r7   r8   	ExceptionerrorrY   )
r   rh   r   rq   rr   rs   rt   overlayopacityrc   s
             rF   r   r     s   ,a""Q&1q53F+FST+U
  ''!+AA 3335
 hhjGGMMQ
Q,,a"f5

 OOG KKQB(( HHSQZ#QQU^#Q-@1-D)E%EF HHQQU^#Q-@1-D)E%EFQC 3a 7889l J] U((399Q<7A@S<SVW<W
  AA 333''!+-
 hhjGGMM((!a%"*5AE


 OOG KK((!a%"*5(( HHSQZQ'AE
NSQZ/EC 3a 788 	 HHAE
NSQZ/EC 3a 788 AEC 3a 7889	@ Jk $$q(Q1D-Dq-HLVC''!+Q1D-Dq-HHIhhjGGMM((!,AF

 OOG KK((!b&1(( HHSQZ#AE
NSQZ//!344 	 HHAE
NSQZ//!344 A/!3445	T J} E''#))A,6A++ciil:  AA 333AA 3335
 hhjGGMMQA
#Q,,a!e4

 OOG KKQA
#(( HHSQZQ'AE
NSQZ/EC 3a 788 	 HHAE
NSQZ/EC 3a 788 QA$7!$; <<=	 J KKIJ J  SXJs3   F[ F9[ F[  G[ 6[ 	\ [;;\ r   c           
         t        j                  |j                         ddg      }|j                  dgd      j	                  d      }| j                         }d}||z   t        z   | j                  d	   k  rYt        j                  | ||z   |f||z   t        z   ||z   fd
t        j                         t        j                  ||| d	|z
  d|        n^|t        z
  dkD  rRt        j                  | |t        z
  |f|||z   fd
t        j                         t        j                  ||| d	|z
  d|        |j                         D ]  \  }	}
|
d   }| d}|
d   dz  }d}t        ||z        }||z   t        z   | j                  d	   k  r|dz   |	d	z   dz  z   }||z   }|||z   k  sat        j                  | |||ft        j                  ddd	       t        j                  | ||z   dz   |dz   |	d	z   dz  z   f||z   dz   |z   |dz   |	d	z   dz  z   dz   fdt        j                         |t        z
  dkD  s|dz   |	d	z   dz  z   }|t        z
  }|||z   k  st        j                  | |||ft        j                  ddd	       t        j                  | |t        z
  dz   |dz   |	d	z   dz  z   f|t        z
  dz   |z   |dz   |	d	z   dz  z   dz   fdt        j                          | S )a  
    Overlay the analyzed emotion of face onto image itself
    Args:
        img (np.ndarray): image itself
        emotion_probas (dict): probability of different emotionas dictionary
        x (int): x coordinate of the face on the given image
        y (int): y coordinate of the face on the given image
        w (int): w coordinate of the face on the given image
        h (int): h coordinate of the face on the given image
    Returns:
        img (np.ndarray): image with overlay emotion analsis results
    r   score)columnsF)by	ascendingT)dropr   r    )@   r   r   r    d   #   r   r   r   F         )pd	DataFrameitemssort_valuesreset_indexr/   r^   r[   r,   rp   r   r   iterrowsrz   ry   r{   )r   r   rq   rr   rs   rt   
emotion_dfr   r   indexinstancecurrent_emotionemotion_labelemotion_scorefilled_bar_xbar_xtext_location_ytext_location_xs                     rF   r   r     sL    n224y'>RSJ''G9'FRRX\R]J
 hhjGG 	1u""SYYq\1UAJU((!a%0JJ	
 	#q7{AsC 
 	 1	$$$a(AJJJ	
 	#q7{AsC%..0 ?x"9-*+1- )C/L=01q5&&15"f	R'77O!eOQ&!$o6,,# URZR519*:!:;A
U*B%!)r!11A5 $JJ	 $$q("f	R'77O"55O!a%'!$o6,,# //"4B%!)r!11
 //"4u<B%!)r!11A5 $JJg?B JrH   r   r   c           
         t         j                  | d|        t        |       d| }d}|t        z
  t        t        dz        z   dkD  rqt	        j
                  |t        |dz        z   |f|t        |dz        z   t        |dz        z
  |t        t        dz        z
  f|t        |dz        z   t        |dz        z   |t        t        dz        z
  fg      }	t        j                  | |	gd|d	       t        j                  | |t        |dz        z   |t        z
  t        t        dz        z   f||z   t        |dz        z
  |t        t        dz        z
  f|t        j                         t        j                  | ||t        |d
z        z   |t        t        dz        z
  ft        j                  ddd       | S ||z   t        z   t        t        dz        z
  | j                  d   k  rt	        j
                  |t        |dz        z   ||z   f|t        |dz        z   t        |dz        z
  ||z   t        t        dz        z   f|t        |dz        z   t        |dz        z   ||z   t        t        dz        z   fg      }	t        j                  | |	gd|d	       t        j                  | |t        |dz        z   ||z   t        t        dz        z   f||z   t        |dz        z
  ||z   t        z   t        t        dz        z
  f|t        j                         t        j                  | ||t        |d
z        z   ||z   t        t        dz        z   ft        j                  ddd       | S )a  
    Overlay the analyzed age and gender of face onto image itself
    Args:
        img (np.ndarray): image itself
        apparent_age (float): analyzed apparent age
        gender (str): analyzed gender
        x (int): x coordinate of the face on the given image
        y (int): y coordinate of the face on the given image
        w (int): w coordinate of the face on the given image
        h (int): h coordinate of the face on the given image
    Returns:
        img (np.ndarray): image with overlay age and gender analsis results
    z years old r   r   r   r   rx   r}   r   rU   g      @g @r    )r   o   r   rw   )r7   debugrz   r^   r)   arrayr,   drawContoursrp   r   ry   r{   r[   )
r   r   r   rq   rr   rs   rt   analysis_reportinfo_box_colortriangle_coordinatess
             rF   r   r   e  s     LLL>VH56\*+1VH5O#N 	%81%<!==A!xxSQZ#AE
NSR[0/!344
 AE
NSR[0/!344
 
 	!"	
 	CAJ''#.AA.E*FF USQZS)<q)@%A!ABJJ		
 	QWq3':S'@#AAB$$	
p J[ 
Q$	$s+>+B'C	CciiPQl	R!xxSQZQ'AE
NSR[0EC 3a 788
 AE
NSR[0EC 3a 788
 
 	!"	
 	QU^QUS)<q)@%AABAAE
"A++c2E2I.JJ JJ		
 	QWq1us+>+D'EEF$$	
 JrH   )zVGG-FaceopencvcosineTr   r   r   )   )*osr+   typingr   r   r   numpyr)   pandasr   r,   deepfacer   !deepface.models.FacialRecognitionr   deepface.commons.loggerr   r7   environr^   r   rY   rG   tupler'   ndarrayr(   boolr&   rz   r2   r3   floatr9   r0   r1   r6   r5   r   dictr   r    rH   rF   <module>r      s$   	  ( (   
  ? *	)	* &)

! "  

 BBJs u N2::N2N2 N2 	N2
 N2 8C=(2::../N2b/$ /4 /$	(,U3S#3E-F(GZZ"	E#sC"456  	
 ZZ:	"**	$);>bjj> \_"	"'*"9>sCx"UX"	%S#s"
#$"J	(,U3S#3E-F(G	"**&1	1$1 E#sC"4561 	1
 1 1 1 ZZ1h--	- E#sC"456- $	-
 ZZ-`x	x

x x 	x
 x x x ZZxvo	o%)o.1o69o>AoFIoZZodq	q#(q25q:=qBEqJMqRUqZZqrH   