Team Ai
Apppublic

jarondon82/ComputerVisionProject

sourceHugging Faceupdated 2y agoView on Hugging Face
1likes
streamlit_app.cpython-310.pyc423 linesDownload Raw Back to __pycache__
1o

2���g���@sddlZddlZddlZddlmZddlmZddl	Z	ddl3Z4ddlZddlZddl
ZddlmZddlZddlmZddlZz5ddlmZdZWneyUdZYnwzddlmZmZmZmZdZ WneyvdZ e�!d	�Ynwd6d�Z"e#dkr�e"�dSdS)
�N)�Image)�BytesIO)�cosine_similarity)�DeepFaceTF)�
compare_faces�compare_faces_embeddings�"generate_comparison_report_english�draw_face_matcheszLFace comparison functions are not available. Please check your installation.c�s\1tjddddd�tj�d�dtjvrdtj_dtjvr!d	tj_d7tjvr*d	tj_tj�dgd��}tj	d
d��}tj	dd��}�d�dd���d�dd���d�dd��dd���fdd�}d d!�}�d����fd"d#�	}d$d%�}d&d'�}d(d)�}d*d+�}	|d,kr�t�8d-�tjd.d/dd0��n|d1k�r�|�}9tj�d2d3d4g�}tjj
d5d6d7dd8d9d:�}tj�d;d<��t�fd=d>�d?D��}
|
d@|
dA|
dBf}tj�dCd�}|d3k�rtjdDgdE�dF�}|du�r�tjt|���tjdG�}t�|tj�}|jt|j�}dHtjv�s10tjj|k�r|tj_|��tj_t�d@�\}}|�t� dI�tjtjjdJddK�Wd�n	1�s8wYt!�!�}�|11tjj|�}�tjj|||�\}}t!�!�|}|�1t� dL�tj|dJddK�t"�#|dd�dd�dddM�f�}tj12||dNdO�ddP�Wd�n	1�s�wY|�r�t� dQ�t�dR�\}}}|�$dS|dT�dU��|�$dVt%|��|�$d5|dW��t�&dX��0|�r�t�'dY�t(|�D]\}}t�'dZ|dA�d[|d\dT����q�nt�'d]�Wd�n	1�s�wY�	n�t�d^d_d`g�}|d_k�rtjdagdb�dF�}|du�r�t)�*�} t+j,�-| dc�}!t.|!dd��}"|"�'|���Wd�n	1�s>wYt� de�t�/|!�|�\}#}$t�0df��r�t�1dg���||!|13|#|$|dd|ddh�	\}%}&}'t� di�t�/|%�t� dj�t�dR�\}(})}*|(�$dk|'dl�|+�r�|)�$dm|'dn�n|)�$dodp�|,�r�|*�$dq|'dr�n|*�$dsdp�t.|%dt��}"|"��}-Wd�n	1�s�wYtj2du|-dvdwdx�zt+�3|!�t+�3|%�t+�4| �t+�4|&�WnYWd�n	1�s�wY�n�t� dy�t�'dz�t�5�}.t�d@�\}}|j0d{|d|�}/|j0d}|d|�}0d~tjv�r8tjj6�r8t�7d�d	tj_6tjj�r�t�7d��t�8dB�}1|1�9��s\t�:d��t�;d��d	tj_�nOz<tjj�r�|1��\}2}3|2�sqt�:d��n!�|14|3|�}�|3|||�\}4}|.j|4dJddK�t!�<d��tjj�sbW|1�=��n|1�=�w�n|d�k�rK|�}15|�\}#}$tj� d��tj�d�d�}+d}5|+�r�tjj
d�dAd�ddAd�d:�}5tj�d�d�},d}6|,�r�tjj
d�dd�ddAd�d:�}6tj�d�d	�}7tjj
d�d6d7dd8d��}tj�d;d<��t�fd�d>�d?D��}
|
d@|
dA|
dBf}tj�d2d3d4g�}|d3k�r0tjdDgdE�dF�}|du�r.tjt|���tjdG�}t�|tj�}|jt|j�}d�tjv�sVtjj>|k�r`|tj_>|��tj_?t�d@�\}}|�t� dI�tjtjj?dJddK�Wd�n	1�s�wY�|16tjj?|�}�tjj?|||�\}}dB}8dB}9|+�s�|,�r��|||#|$|+|,|6|5�\}}8}9|7�r�|||�}|�1t� dL�tj|dJddK�t"�#|dd�dd�dddM�f�}tj17||d�dO�ddP�Wd�n	1�s�wYt� dj�t�dR�\}(})}*|(�$dVt%|��|+�r|)�$do|8�n|)�$dodp�|,�r(|*�$ds|9��n�|*�$dsdp��n{t�'d��t�d^d_d`g�}|d_k�r7t�'d��tjdagdb�dF�}|du�r5t)�*�} t+j,�-| dc�}!t.|!dd��}"|"�'|���Wd�n	1�sxwYt� de�t�/|!�t�0df��r5t�1dg���||!|18|#|$|dd||6|5d��19\}%}&}'t� di�t�/|%�t� dj�t�dR�\}(})}*|(�$dk|'dl�|+�r�|)�$dm|'dn�n|)�$dodp�|,�r�|*�$dq|'dr�n|*�$dsdp�t.|%dt��}"|"��}-Wd�n	1�s�wYtj2du|-d�dwdx�zt+�3|!�t+�3|%�t+�4| �t+�4|&�WnYWd�n	1�s0wY�ntt� d��t�'d��t�5�}.t�d@�\}}|j0d{|d|�}/|j0d}|	d|�}0d�tjv�rntjj@�rnt�7d�d	tj_@tjj�rIt�7d��t�8dB�}1|1�9��s�t�:d��t�;d��d	tj_�nz�t�5�}:|:�dR�\};}<}=dB}>dB}?dB}@dB}Atjj�r=|1��\}2}3|2�s�t�:d��n��|20|3|�}�|3|||�\}4}t%|�}B|>|B7}>dB}8dB}9|+�s�|,�r�|4||#|$|+|,|6|5�\}4}8}9|?|87}?|@|97}@|7�r�||4|�}4|.j|4dJddK�|AdA7}A|AddBk�r3|;�$dV|B�|+�r|<�$do|8�n|<�$dodp�|,�r-|=�$ds|9�n|=�$dsdp�t!�<d��tjj�s�W|1�=��ng|1�=�w�n`|d�k�r�t� d��t�'d��t�&d���
t�21d��Wd�n	1�spwY|�}22t�d@�\}}|�t�'d��tjd�gdE�d�d��}CWd�n	1�s�wY|�t�'d��tjd�gdE�d�d��}DWd�n	1�s�wYtj
d�d6d7dd8d��}tj
d�d�d�d�d�d�d:��tjd�d�d�gd�d��}Ed�}F|Ed�k�r�tA�r�t�;d��tjd�gd��d�d��}Fn|Ed�k�rtA�st�;d��t�7d��d�}Et�d;d<��t�fd�d>�d?D��}
|
d@|
dA|
dBf}|Cdu�r�|Ddu�r�tjt|C���tjdG�}Gt�|Gtj�}Htjt|D���tjdG�}It�|Itj�}J|Cjt|Cj�}K|Djt|Dj�}Ld�tjv�sytjjB|Kk�r�|Ktj_B|H��tj_Cd�tjv�s�tjjD|Lk�r�|Ltj_D|J��tj_E|�tjtjjCdJdd�d��Wd�n	1�s�wY|�tjtjjEdJdd�d��Wd�n	1�s�wY�|23tjjC|�}M�tjjC|M||�\}N}O�|24tjjE|�}P�tjjE|P||�\}Q}Rt� d��t�d@�\}S}T|S�tj|NdJdd�d��t�'d�t%|O����Wd�n	1�	s)wY|T�tj|QdJdd�d��t�'d�t%|R����Wd�n	1�	sOwYt%|O�dBk�	sbt%|R�dBk�	rit�;dš�nBt�1dơ��3|Ed�k�	r�tA�	r�zt�7d�|F���tFtjjC|OtjjE|R|Fdȍ}UWnBtG�	y�}Vz t�:d�t|V����t�7dʡtHtjjC|OtjjE|R�}UWYd}V~Vnd}V~Vww|Ed�k�	r�t�;dˡtHtjjC|OtjjE|R�}UtI|U|O|R�}WtJtjjC|OtjjE|R|U�d̍}Xt� d͡tj|XdJdd�d��t� dϡg�|UD]}Y|YD]}Z��KtL|Zd����25q�	q���rLtM��t%��}[tN��}\tO��}]|[d�k�26r-d�}^d�}_n|[d�k�27r7d�}^d�}_n|[d�k�28rAd�}^d�}_nd�}^d�}_|\d�k�29rOd�}`d�}an|\d�k�30rYd�}`d�}an|\d�k�31rcd�}`d�}and�}`d�}at�dR�\}}}|j$d�|[dW�dڝ|^|_dۍ|j$d�|\dW�dڝ|`|adۍ|�$d�|]dW�dڝ�tM�fd�d>��D��}bt�$d߈�d��|b�d�d�|UD�}ctP�fd�d>�|cD���32r�tPd�d>�|cD���33r�t�Qd�ntPd�d>�|cD���34r�t�7d�nt�;d�nt�:d�t� d�tRjSd�d�\}d}egd���gd�}fgd�}g��fd�d�tTt%��dA�D�}h|ejU|f|h|gd�}i|e�Vd�|e�Wd�|e�Xd��|iD]}j|j�Y�}k|ejZ|j�[�|j�\�d�|kd�t]|k��d�d�d���q(t�^|d�t�&d���
t�'|W�Wd�n	1�sbwYtj2d�|Wd�d�dx�t"�#|Xdd�dd�dddM�f�}lt_�}m|lj`|md�d��|m�a�}ntj2�d|n�d�ddx�Wd�n	1�s�wY|d�k�r�tj�35�d�tj�7�d�dS|�dk�r�t��d�t�36�d�tA�s�t�:�d�t�b�|�}37�d	tjv�r�itj_ct�dg�d38��\}o}p}q|o���t�e�d�tjdDgdE��dd��}rt�f�d
��0t�g�d�}stjd�gd��dB�d�}ttj
�dd6d7dd�d��}ut��d�}vt�h�d�}wWd�n	1�sGwY|w�r�|rdu�r�|s�r�tjt|r���tjdG�}t�|tj�}|�}39�|40||u�d�}�|||u�\}}|�s�t�:�d��nqt%|�dAk�
r�t�;�d�|�
r�t%|�dBk�
r�t%|dB�dk�
r�ti||dB�}x|x�
r||v�
r+|stjjcv�
r+�dtjjc|sv�
r|xD]T}y|y�d}zdM}{t(tjjc|s�d�D]\}}||||zk�r�|}{n�q�|{dBk�
r|y�dtjjc|s�d|{<�q�tjjc|s�d�K|z�tjjc|s�d�K|y�d��q�tjjc|s�ddA7<nvtjjc|s�d}}d�}~|}g|~gdA�d�tjjc|s<|xD](}y|y�d}z|z|~k�
rltjjc|s�d�K|z�tjjc|s�d�K|y�d��
qEtjjc|s�ddA7<n%g}g}�|xD]}y|�K|y�d�|��K|y�d��
q�|�|dA�d�tjjc|s<t�Q�d|s��d���||dBg|u�\}}�tjt�j|tjk��d|s���d��n/t�:�d ��n'ti||dB�}x|x�r�|v�r�|stjjcv�r��dtjjc|sv�rU|xD]T}y|y�d}zdM}{t(tjjc|s�d�D]\}}||||zk�r|}{n�q|{dBk�r*|y�dtjjc|s�d|{<�
q�tjjc|s�d�K|z�tjjc|s�d�K|y�d��
q�tjjc|s�ddA7<nvtjjc|s�d}}d�}~|}g|~gdA�d�tjjc|s<|xD](}y|y�d}z|z|~k�r�tjjc|s�d�K|z�tjjc|s�d�K|y�d��qotjjc|s�ddA7<n%g}g}�|xD]}y|�K|y�d�|��K|y�d��q�|�|dA�d�tjjc|s<t�Q�d|s��d���||dBg|u�\}}�tjt�j|tjk��d|s���d�nt�:�d �t� �d!��d	tjv�r�tjjc�r�g}�tjjc�l�D]2\}�}��d|�v�r.t%|��d�}��d"�-|��d�}ndA}�d�}|��m�ddA�}�|��K|�|�|�|�d#���qdBdln}�|��o|��}�|��p�D]�\}}�t�g�d$��\}}}}�}�|�t�'|��d%�Wd�n	1�szwY|�t�'|��d&�Wd�n	1�s�wY|�t�'|��d'�Wd�n	1�s�wY|��t�'|��d(�Wd�n	1�s�wY|��=tj0�d)�d*|��d%���d+��r|��d%tjjcv�rtjjc|��d%=t�Q�d,|��d%��d-��t�q�Wd�n	1�swY�qSt�0�d.��r��d/tjv�r,d	tj_rtjjr�s�t�;�d0�t�d@�\}}|�!t�0�d1��rZitj_cd	tj_rt�Q�d2�t�q�Wd�n	1�sewY|�t�0�d3��r|d	tj_rt�q�Wd�n	1�s�wYnt�7�d4�Wd�n	1�s�wY|p��ht�e�d5�tjjc�s�t�;�d6��nMtj�d7gdE��d8d��}rtj&�d9d	�d:��Gtj
�d;d�d�d�d��d<d:��tj
�d�d=�d>dd8�d?d:�}utjd�gd���d@d��}ttj�dAg�dB��dCd��}�tj�dDd	�dE�dF�}�Wd�n	1�swY|rdu�r�tjt|r���tjdG�}t�|tj�}�|41||u�}�|||u�\}}|�sPt�:�dG��n�tj|dJ�dH�dI�|��}�t�t%|�dRk�rkt%|�ndR�}�t(|�D�]�\}}ts|||tdȍ}y|ydu�rug}�tjjc�l�D]�\}�}��d|�v�r=g}�t(|��d�D]C\}�}�|��d|�|tk�r�d7}�n�dJ}�ztt|y�dg|�g�dBdB�dK|�}�|��K|��W�q�tu�y�}VzWYd}V~V�q�d}V~Vww|��dLk�r�|��r�tM|��t%|��}�n:d6}�n7|��dMk�r|��rtN|��}�n)d6}�n&|��r,tM�dNd>�t(tv|���D��}�tM�dOd>�tTt%|���D��}�|�|�}�nd6}�|��K|�|�|��d�dP���q�|��d}�ztt|y�dg|�g�dBdB�dK}�|��K|�|�dA�dP��W�q�tu�yt}VzWYd}V~V�q�d}V~Vww|�jw�dQ�dR�d�dS�|\}�}�}�}�}�|��r�|�dBd��k�r�|�dB}�|�d��dTk�r�d}�n|�d��dUk�r��dV}�n�dW}�|��dX��dY|�d��dZ�dڝ}�t�x|�|�|�f|�|�f|�d@�t�y|�|�|�|�d�ftjz�d[|�d@�|��r't%|��dAk�r't(|�dAdR��D]4\}�}��d\|�d@��dY|��dX��dY|�d��dZ�dڝ}�t�y|�|�|�|�|�d@�d]ftjz�d^�d_dA��q�|dR}�|�|��St�$�d`|dA��|��dX�|�d��dZ�dڝ�|��r{t%|��dAk�r{t�'�da�t(|�dAdR��D]\}�}�t�'�db|��dX��dY|�d��dZ�dڝ��q`Wd�n	1�s�wY�qr�dc}�|��r�|��dY|�dBd��dZ�dڝ7}�t�x|�|�|�f|�|�f�ddd@�t�y|�|�|�|�d�ftjz�d[�ddd@�|dR}�|�|��$t�$�d`|dA���dc|��r�|�dBd��dZ�dڝndp�Wd�n	1�s�wY�qrt� �de�tj|�dJddK�Wd�n	1�swY|q���t�e�df�tjjc�s.t�;�d6��n[tj&�d9d	�d:��ktj
�d;d�d�d�d��dg�d<�dh��tj
�d�d=�d>dd8�di�d?�dh�}utjd�gd���dj�d@�dk�}ttj�dAg�dB��dl�dC�dk�}�tj�dmd�dn�dF�}�tj�dod�dp�dF�}�tj
�dqdd�ddA�drd:�}�Wd�n	1�s�wY�dstjv�r�d	tj_{�dttjv�r�itj_|t�d@�\}}|j0�du�dv�dw�dR��dx�}/|j0�dy�dz�d{�dR��dx�}0t�5�}�t�dR�}�|�dB�t�5�}�Wd�n	1�swY|�dA�t�5�}�Wd�n	1�swY|�d@�t�5�}�Wd�n	1�s5wYtjj{�r{t�7�d|�t�8dB�}1|1�9��s[t�:�d}�d	tj_{�n6�zdB}At!�!�}|}�g}�tjj{�r`t!�!�}�|�|�}�|�d7|�k�r�t!�<d���qg|�}�|1��\}2}3|2�s�t�:�d~��n�|AdA7}A|AddBk�r�d|�|}�|��K|��t%|��d�k�r�|��}dB�tM|��t%|��}�|�}|��$�d|��dZ��|��$�d�t]|�t!�!�tj�m�d�|�����d����|42|3|u�}�|3||u�\}�}|AddBk�r|��$�dHt%|��|3��}�t(|�D�]O\}}�d�|��}�ts|3||tdȍ}y|ydu�rYg}�tjjc�l�D]�\}�}��d|�v�r�g}�t(|��d�D]C\}�}�|��d|�|tk�rMd7}�n�dJ}�ztt|y�dg|�g�dBdB�dK|�}�|��K|��W�q<tu�y}VzWYd}V~V�q<d}V~Vww|��dLk�r�tM|��t%|��}�n+|��dMk�r�tN|��}�n tM�d�d>�t(tv|���D��}�tM�d�d>�tTt%|���D��}�|�|�}�|��K|�|��d����q)|��d}�ztt|y�dg|�g�dBdB�dK}�|��K|�|��d���W�q)tu�y�}VzWYd}V~V�q)d}V~Vww|�jw�d��dR�d�dS�|��r�|��r�|�dB}�|�tjj|v�r#gg�d��tjj||�<tjj||����d��K|��dX���d��K|�d��t%��d��d�k�rX��d��}dB���d��}dB�t%��d��dRk�r�i}���d�D]}�|�|�v�rtdB|�|�<|�|�dA7<�qitN|��l��d��dR��d+�dB�	��	f�d�d�tTt%��d���D�}�tM|��t%|��}��	|��d��}�n|�dB}�n	|��r�|�dBnd}�|\}�}�}�}�}�|��r!|�d��k�r!|�d��dTk�r�d}�n|�d��dUk�r�dV}�n�dW}�t�x|�|�|�f|�|�f|�d@�|��r|��dX��dY|�d��dZ�dڝ}�n|��dX�}�t�y|�|�|�|�d�ftjz�d[|�d@��q43t�x|�|�|�f|�|�f�ddd@�|��rD|��r@�d�|�d��dZ�dڝn�dc}�n�dc}�t�y|�|�|�|�d�ftjz�d[�ddd@��q44tjj{�sl|�j|�dJddK�W|1�=�itj_|n'|1�=�itj_|wt�7�d��Wd�dSWd�dSWd�dSWd�dS1�s�wYdSdS(�Nz!Advanced Face & Feature Detectionu👤�wide�expanded)�45page_title�	page_icon�layout�initial_sidebar_statezControls & Settings�original_image�camera_runningF�feature_camera_runningzChoose the app mode)�About�Face Detection�Feature Detection�Comparison Mode�Face Recognitionc46Ss�d}d}g}tj�|�s|�|�tj�|�s|�|�|r6t�dd�|��t�d�t�d�t��z47t	j48�||�}|WSty_}zt�d|���t��WYd}~dSd}~ww)Nz(res10_300x300_ssd_iter_140000.caffemodelzdeploy.prototxt.txtzMissing model files: �, z-Please manually download the following files:a�49            1. Download the model file:50               URL: https://raw.githubusercontent.com/sr6033/face-detection-with-OpenCV-and-DNN/master/res10_300x300_ssd_iter_140000.caffemodel51               Save as: res10_300x300_ssd_iter_140000.caffemodel52               53            2. Download the configuration file:54               URL: https://raw.githubusercontent.com/sr6033/face-detection-with-OpenCV-and-DNN/master/deploy.prototxt.txt55               Save as: deploy.prototxt.txt56            zError loading model: )
�os�path�exists�append�st�error�join�code�stop�cv2�dnnZreadNetFromCaffe�	Exception)Z	modelFileZ57configFile�
missing_files�net�e�r(�[C:\Users\jrondon\Desktop\Empresa\BackupsComputerVision\TestClaude\hf_space\streamlit_app.py�load_face_model;s(58596061	��zmain.<locals>.load_face_modelcSs,t�tjjd�}t�tjjd�}||fS)Nzhaarcascade_eye.xmlzhaarcascade_smile.xml)r"ZCascadeClassifier�dataZhaarcascades)�eye_cascade�
smile_cascader(r(r)�load_feature_modelsbsz!main.<locals>.load_feature_models��?cSs8tj�|ddgd�dd�}|�|�|��}g}|jd}|jd}t|jd�D]p}|dd|df}	|	|kr�t|dd|df|�}62t|dd|d	f|�}t|dd|d63f|�}t|dd|df|�}
tdt	|64|d��}65tdt	||d��}tdt	||d��}tdt	|
|d��}
|�66|67|||
|	g�q)|S)N��?)�,r1)�h�u�{Fr������)r"r#Z
blobFromImageZsetInput�forward�shape�range�int�max�minr)r&�frame�conf_threshold�blob�68detections�bboxesZframe_hZframe_w�i�69confidence�x1�y1�x2�y2r(r(r)�detect_face_dnnjs(707172�zmain.<locals>.detect_face_dnn�r��rc
73Ss�|��}g}|D]>}t|�dkrF|\}}}	}74}||krFt�|||f|	|75f|d�|d�}t�||||dftjd|d�|�|||	|76|g�q||fS)Nr9r6�.2f�77r/)�copy�lenr"�	rectangle�putText�FONT_HERSHEY_SIMPLEXr)
rArDrB�78bbox_color�result_framerEZ	detectionrHrIrJrKrG�labelr(r(r)�process_face_detections�s �z%main.<locals>.process_face_detectionsT�r9c6Ss|��}t�|tj�}	d}79d}|D�]�}|\}
}}}}|	||�|
|�f}|||�|
|�f}||
}||}|�r�|}|t|d�}|	||�|
|�f}|||�|
|�f}|
|d}|	||�|
|�f}|	||�||�f}|||�|
|�f}|||�||�f}|jdk�r�t�|�}tjddd�}|�|�}|j	|dt80d|d	�t|d81�t|d82�ft|d�t|d�fd�} t| �dk�rt| d
d�dd�} | dd�} | D]+\}!}"}#}$|83d7}84t�
||!|"f|!|#|"|$fdd�t�|d|!|"dftjddd�q�n�|jdk�rwt�|�}|�|�}|j	|dt85d|d�t|d�t|d�ft|d�t|d�fd�}%t|%�dk�rwt|%dd�dd�}%|%d}&|86d7}87|&\}!}"}#}$t�
||!|"f|!|#|"|$fdd�t�|d|!|"dftjddd�|jdk�r�t�|�}|�|�}|j	|dt88d|d�t|d�t|d�ft|d�t|d�fd�}'t|'�dk�r�t|'dd�dd�}'|'d}(|89d7}90|(\}!}"}#}$t�
||!|"f|!|#|"|$fdd�t�|d|!|"dftjddd�|�r	|t|d�})|	|)|�|
|�f}*||)|�|
|�f}+|t|d�},|	|,|�|
|�f}-d}.|*jdk�r�t�|*�}*tjddd�}|�|*�}*|j	|*d|t|d�t|d�ft|d�t|d�fd�}/t|/�dk�r�t|/d d�dd�}/|/d\}0}1}2}3|d7}d}.t�
|+|0|1f|0|2|1|3fd!d�t�|+d"|0|1dftjdd!d�|.�s	|-jdk�r	t�|-�}-|�|-�}-|j	|-d#t91d|d�t|d$�t|d%�ft|d&�t|d�fd�}4t|4�dk�r	t|4d'd�dd�}4|4d\}0}1}2}3|1|,|)}5|d7}t�
|+|0|5f|0|2|5|3fd!d�t�|+d"|0|5dftjdd!d�q||92|fS)(Nrg�������?r6�@)�r\)Z	clipLimitZtileGridSizegR���Q�?r5r7g�Q���?�333333�?)�scaleFactorZminNeighbors�minSize�maxSizecS�|d|dS�Nr6r7r(�r'r(r(r)�<lambda>��z6main.<locals>.detect_facial_features.<locals>.<lambda>T��key�reverse�rNrrZEyer9r/g{�G�z�?g{�G�z�?g�?cSrarbr(rcr(r(r)rd�recSrarbr(rcr(r(r)rdreg�������?Fg333333�?g333333�?gffffff�?皙�����?cSrarbr(��sr(r(r)rd/re�rrrNZSmileg�������?g�������?皙�����?�333333�?cSrarbr(rkr(r(r)rdJre)rQr"�cvtColorZCOLOR_BGR2GRAYr>�sizeZequalizeHistZcreateCLAHE�applyZdetectMultiScaler?rR�sortedrSrTrU)6rArEr,r-�detect_eyes�detect_smile�smile_sensitivity�eye_sensitivityrW�gray�	eye_count�smile_count�bboxrHrIrJrK�_Zroi_grayZ	roi_colorZ93face_widthZface_heightZ
upper_face_y1Z
upper_face_y2Zupper_face_roi_grayZupper_face_roi_colorZmid_xZleft_eye_roi_grayZright_eye_roi_grayZleft_eye_roi_colorZright_eye_roi_colorZclaheZ	full_eyes�exZey�ewZehZ	left_eyesZleft_eyeZ94right_eyesZ	right_eyeZ
lower_face_y1Zlower_face_roi_grayZlower_face_roi_colorZalt_lower_face_y1Zalt_lower_face_roi_grayZsmile_detected�smiles�sx�sy�sw�shZ95alt_smilesZadjusted_syr(r(r)�detect_facial_features�s�969798�	""�99100�" 101102�" 103104�" 105106�" �107z$main.<locals>.detect_facial_featuresc108Ss�tsdSz(|\}}}}}|||�||�f}t�|tj�}tj|gd�ddd�}	|	dWStyI}109zt�dt	|110����WYd}111~112dSd}113~114ww)u8115        Detecta atributos faciales como edad, género y emoción usando DeepFace.116        117        Args:118            image: Imagen en formato OpenCV (BGR)119            bbox: Bounding box de la cara [x1, y1, x2, y2, conf]120            121        Returns:122            Diccionario con los atributos detectados123        N)�age�gender�emotionFZopencv)Zimg_path�actionsZenforce_detectionZdetector_backendrz#Error detecting facial attributes: )124�DEEPFACE_AVAILABLEr"rp�
COLOR_BGR2RGBrZanalyzer$rr�str)�imager{rHrIrJrKr|Zface_imgZface_img_rgb�125attributesr'r(r(r)�detect_face_attributesZs$�126��z$main.<locals>.detect_face_attributesc127s�|��}t|�D]�\}}|\}}}}}	tr��||�}128|129r}|130�dd�}|131�dd�}|132�dd���}
|133�di��dd�}|dkrAd}nd}t�|d	|��||d134ftjddd
�t�|d|��||dftjd|d
�t�|d|
��||dftjddd
�qt�|d||d135ftjddd
�t�|d||dftjddd
�qt�|d||d136ftjddd
�t�|d||dftjddd
�q|S)Nr��Unknownr�Zdominant_emotionZWomanr)rNrrNrizAge: �r/)rNrNrr6zGender: �(z	Emotion: �<�rrNrNzAge: UnknownzGender: Unknownz137Age: 25-35)rQ�	enumerater��get�138capitalizer"rTrU)rArErWrFr{rHrIrJrKr|r�r�r�r�Zgender_probZgender_color)r�r(r)�detect_age_gender~sF139140�141�142�143�144�145�146�zmain.<locals>.detect_age_gendercSsBt�}|j|dd�t�|�����}d|�d|�d|�d�}|S)N�JPEG��formatz<a href="data:file/txt;base64,z" download="z">z</a>)r�save�base64�	b64encode�getvalue�decode)�img�filename�text�bufferedZimg_str�hrefr(r(r)�get_image_download_link�s147z%main.<locals>.get_image_download_linkc148$	s�t�|�}149t|150�tj��}t|151�tj��}t|152�tj��}
t��}t	j153�|d�}tjd�}t�
|||
||f�}t|154�tj��}t�d�}t��}d}g}d}d}d}|155��r�|156��\}}|s_n[t��}�|||�}�||||�\}}|t|�7}|s||r��||||||||	�\}} }!|| 7}||!7}|�t��|�|�|�|d7}|�||�|�d|�d|���|157��sV|158��|��|r�t|�t|�}"|�d|"d�d	��|td|�|td|�|td|�d159�}#|||#fS)N�processed_video.mp4Zmp4vrr5zProcessing frame �/z.Processing complete! Average processing time: �.4fzs per frame)�faces�eyesr)r"�VideoCapturer>r�ZCAP_PROP_FRAME_WIDTHZCAP_PROP_FRAME_HEIGHTZCAP_PROP_FPS�tempfile�mkdtemprrrZVideoWriter_fourccZVideoWriterZCAP_PROP_FRAME_COUNTr�progress�empty�isOpened�read�timerRr�writer��release�sumr?)$Z160video_path�face_netr,r-rBrtrurVrvrw�capZframe_widthZframe_height�fps�temp_dirZtemp_output_pathZfourcc�out�frame_count�progress_barZstatus_text�
current_frameZprocessing_timesZtotal_facesZ161total_eyesZtotal_smiles�retrA�162start_timerD�processed_framerEryrzZavg_time�detection_stats)rLr�rYr(r)�
process_video�sj163164165166�167�+�168zmain.<locals>.process_videocS�dtj_dS�NT)r�
session_staterr(r(r(r)�start_camera�zmain.<locals>.start_cameracS�dtj_dtj_dS�NFT)rr�r�camera_stoppedr(r(r(r)�stop_camera�zmain.<locals>.stop_cameracSr�r�)rr�rr(r(r(r)�start_feature_camerar�z"main.<locals>.start_feature_cameracSr�r�)rr�r�feature_camera_stoppedr(r(r(r)�stop_feature_camerar�z!main.<locals>.stop_feature_camerara�169        ## About This App170        171        This application uses OpenCV's Deep Neural Network (DNN) module and Haar Cascade classifiers to detect faces and facial features in images and videos.172        173        ### Features:174        - Face detection using OpenCV DNN175        - Eye and smile detection using Haar Cascades176        - Support for both image and video processing177        - Adjustable confidence threshold178        - Download options for processed media179        - Performance metrics180        181        ### How to use:182        1. Select a mode from the sidebar183        2. Upload an image or video184        3. Adjust settings as needed185        4. View and download the results186        187        ### Technologies Used:188        - Streamlit for the web interface189        - OpenCV for computer vision operations190        - Python for backend processing191        192        ### Models:193        - SSD MobileNet for face detection194        - Haar Cascades for facial features195        z;https://opencv.org/wp-content/uploads/2019/07/detection.gifzSample face detection)�caption�use_container_widthrzSelect Input Typer�VideozConfidence Thresholdgr0g�������?z`Adjust the threshold for face detection confidence (higher = fewer detections but more accurate))�	min_value�	max_value�value�step�helpzBounding Box Colorz#00FF00c3�,�|]}t��d�||d�d�VqdS��#r6�N�r>�lstrip��.0rF�rVr(r)�	<genexpr>S��*zmain.<locals>.<genexpr>)rr6r8r6r5rzShow Processing MetricszUpload an image)Zjpg�jpeg�png)�type)�dtype�file_idzOriginal Image�BGR)�channelsr�zProcessed Image�����zface_detection_result.jpgu📥 Download Processed Image)�unsafe_allow_htmlzProcessing Metricsr7zProcessing Timer�z secondszFaces DetectedrOzDetailed Detection Informationz&Detected faces with confidence scores:zFace #z: Confidence = r8zNo faces detected in the image.zSelect video sourcezUpload videoz196Use webcamzUpload a video)Zmp4ZaviZmovzinput_video.mp4�wbzOriginal Videoz
Process VideozHProcessing video... This may take a while depending on the video length.)rtrurVrwzProcessed VideozDetection SummaryzAvg. Faces per Framer�zAvg. Eyes per Framer�z
Eyes DetectedzN/AzAvg. Smiles per FramerzSmiles Detected�rbu📥 Download Processed Videor�z	video/mp4)rXr+�	file_name�mimezReal-time face detectionz7Click 'Start Camera' to begin real-time face detection.zStart Camera)�on_clickzStop Camerar�z:Camera stopped. Click 'Start Camera' to activate it again.z/Camera activated. Processing real-time video...z\Could not access webcam. Make sure it's connected and not being used by another application.u�⚠️ Note: If you're using this app on Hugging Face Spaces, webcam access is not supported. Try running this app locally for webcam features.z Error reading frame from camera.g{�G�z�?rzFeature Detection OptionszDetect EyeszEye Detection SensitivityrPzGAdjust the sensitivity of eye detection (lower value = more detections)zDetect SmilezSmile Detection Sensitivity�zIAdjust the sensitivity of smile detection (lower value = more detections)zDetect Age/Gender (Demo)zFace Detection Confidence)r�r�r�r�c3r�r�r�r�r�r(r)r�Er��feature_file_idzfeature_detection_result.jpgz!Facial feature detection in videoz8Upload a video to process with facial feature detection.)rtrurVrvrwzfeature_detection_video.mp4z"Real-time facial feature detectionz2Click 'Start Camera' to begin real-time detection.r�zFCamera activated. Processing real-time video with feature detection...rzFace Comparisonz0Upload two images to compare faces between them.u(📌 How to interpret similarity resultsa�	197            ### Facial Similarity Interpretation Guide198            199            The system calculates similarity between faces based on multiple facial features and characteristics.200            201            **Similarity Ranges:**202            - **70-100%**: HIGH Similarity - Very likely to be the same person or identical twins203            - **50-70%**: MEDIUM Similarity - Possible match, requires verification204            - **30-50%**: LOW Similarity - Different people with some similar features205            - **0-30%**: VERY LOW Similarity - Completely different people206            207            **Enhanced Comparison System:**208            The system uses a sophisticated approach that:209            1. Analyzes multiple facial characteristics with advanced precision210            2. Evaluates hair style/color, facial structure, texture patterns, and expressions with improved accuracy211            3. Applies a balanced differentiation between similar and different individuals212            4. Creates a clear gap between similar and different people's scores213            5. Reduces scores for people with different facial structures214            6. Applies penalty factors for critical differences in facial features215            216            **Features Analyzed:**217            - Facial texture patterns (HOG features)218            - Eye region characteristics (highly weighted)219            - Nose bridge features220            - Hair style and color patterns (enhanced detection)221            - Precise facial proportions and structure222            - Texture and edge patterns223            - Facial expressions224            - Critical difference markers (aspect ratio, brightness patterns, texture variance)225            226            **Factors affecting similarity:**227            - Face angle and expression228            - Lighting conditions229            - Age differences230            - Image quality231            - Gender characteristics (with stronger weighting)232            - Critical facial structure differences233            234            **Important note:** This system is designed to provide highly accurate similarity scores that create a clear distinction between different individuals while still recognizing truly similar people. The algorithm now applies multiple reduction factors to ensure that different people receive appropriately low similarity scores. For official identification, always use certified systems.235            zFirst ImagezUpload first image�file1)r�rgzSecond ImagezUpload second image�file2zSimilarity Threshold (%)g�A@g�W@g�F@g@zAMinimum percentage of similarity to consider two faces as a matchzFacial Comparison MethodzHOG (Fast, effective)zEmbeddings (Slow, more precise)zzHOG uses histograms of oriented gradients for quick comparison. Embeddings use deep neural networks for greater precision.)r��VGG-Facez�WARNING: The current version of TensorFlow (2.19) may have incompatibilities with some models. It is recommended to use HOG if you experience problems.zEmbedding model)r�ZFacenetZOpenFaceZArcFacez<Select the neural network model to extract facial embeddingszdThe DeepFace library is not available. Please install with 'pip install deepface' to use embeddings.zUsing HOG method by default.c3r�r�r�r�r�r(r)r��r��file1_id�file2_idzImage 1)r�r�r�zImage 2zDetected FaceszProcessed Image 1zFaces detected: zProcessed Image 2z:Cannot compare: One or both images have no faces detected.zComparing faces...zUsing embedding model: )�236model_namezError using embeddings: z(Automatically switching to HOG method...z3Using HOG method because DeepFace is not available.)�	thresholdzComparison Resultsz>Visual Comparison (red lines indicate matches above threshold)zSimilarity Statistics�237similarity�FZHIGH�normal�2ZMEDIUMZLOW�inversezVERY LOWzAverage Similarity�%)�delta�delta_colorzMaximum SimilarityzMinimum Similarityc3s�|]	}|�krdVqdS�r5Nr(�r�rl��similarity_thresholdr(r)r�?s�zMatches above threshold (z%)cSsg|]}|r|d�qS)rr()r�Z	face_compr(r(r)�238<listcomp>Cszmain.<locals>.<listcomp>c3s �|]}t|d��kVqdS)r�N��float�r��matchrr(r)r�D��cs� �|]}t|d�dkVqdS)r�r�Nrr	r(r(r)r�Erz9CONCLUSION: HIGH similarity matches found between images.csr)r�r�Nrr	r(r(r)r�Grz;CONCLUSION: MEDIUM similarity matches found between images.z8CONCLUSION: LOW similarity matches found between images.z8CONCLUSION: No significant matches found between images.zSimilarity Distribution)rPr8)�figsize)rr�r�r��d)zVery LowZLowZMediumZHigh)�darkred�red�orange�greencs$g|]�t��fdd��D���qS)c3s8�|]}��|kr��dkrnndVqdSrr(r)�binsrFr(r)r�Xs�6z"main.<locals>.<listcomp>.<genexpr>)r�)r�)�all_similaritiesr)rFr)rXs$)�colorzSimilarity LevelzNumber of ComparisonszSimilarity Level Distributionr[rn�center�bottom)�ha�vazView Detailed Reportu📥 Download Comparison Reportzface_comparison_report.txtz239text/plainr�r�u📥 Download Comparison Imagezface_comparison.jpgz240image/jpegz**Eye Detection Settings**z�Adjust the slider to change the sensitivity of eye detection. A higher value will detect more eyes but may generate false positives.rzFace Recognition Systemu�241        Este módulo permite registrar rostros y reconocerlos posteriormente en tiempo real o en imágenes.242        Utiliza embeddings faciales para una identificación precisa.243        zQDeepFace is not available. Please install the library with 'pip install deepface'�
face_database)�
Register Face�Image Recognition�Real-time RecognitionzRegister New FaceZregister_face_imageZface_registration_formz
Person's name)�indexzDetection ConfidencezAdd to existing personr)rBz<No faces detected in the image. Please upload another image.z4Multiple faces detected. The first one will be used.�244embeddings�model�models�	embedding�count)rr!r#z!Face registered successfully for �!zRegistered face: )r�zDFailed to extract embeddings. Please try again with a clearer image.zRegistered Facesr)�Name�Images�245Embeddings�Models)r7r6r6r8r6r%r&r'r(�DeleteZdelete_)rgzDeleted z from the database.zDelete All Registered Faces�confirm_delete_allzSAre you sure you want to delete all registered faces? This action cannot be undone.zYes, delete allz'All registered faces have been deleted.ZCancelz>No faces registered yet. Use the form above to register faces.rz=No faces registered. Please register at least one face first.z Subir imagen para reconocimientoZrecognition_imageuConfiguración avanzada)rzSimilarity threshold (%)u@Porcentaje mínimo de similitud para considerar una coincidenciar]g�������?u8Un valor más alto es más restrictivo pero más precisouWDiferentes modelos pueden dar resultados distintos según las características facialesu/Método de votación para múltiples embeddings)�Promedio�Mejor coincidenciauVotación ponderadauHCómo combinar resultados cuando hay múltiples imágenes de una personazMostrar todas las coincidenciasz4Mostrar las 3 mejores coincidencias para cada rostro)r�r�z&No se detectaron rostros en la imagen.zFaces detected)r�r�g�������?rr+r,cs� �|]\}}||dVqdSrr(�r�rFrlr(r(r)r�rcs��|]}|dVqdSrr(r�r(r(r)r���)�namer�r#cS�|dS�Nr�r(��xr(r(r)rd1�zmain.<locals>.<lambda>rf�P�Ar�)r�rNr1z: z.1fror�r�rj)��r:r:zRostro zOtras coincidencias:z- ZDesconocidormzRecognition ResultrZrealtime_threshold)r�r�r�r�rgr�Zrealtime_confidenceZrealtime_model)rgr�Zrealtime_votingzMostrar porcentaje de confianzaz2Mostrar el porcentaje de similitud junto al nombrezEstabilizar resultadosuFReduce fluctuaciones en la identificación usando un promedio temporaluLímite de FPSz6Limitar los frames por segundo para reducir uso de CPU�recognition_camera_running�recognition_historyuIniciar CámaraZstart_recognition_cameracS�ttjdd�S)Nr;T��setattrrr�r(r(r(r)rd��)rgr�uDetener CámaraZstop_recognition_cameracSr=)Nr;Fr>r(r(r(r)rd�r@u4Cámara activada. Procesando video en tiempo real...utNo se pudo acceder a la cámara. Asegúrese de que esté conectada y no esté siendo utilizada por otra aplicación.u"Error al leer frame de la cámara.ZFPSz
Tiempo activoZcamera_start_timerlZface_csr-rr(r.r(r(r)r�,rcsr/rr(r�r(r(r)r�-r0)r1r�cSr2r3r(r4r(r(r)rd=r6��names�similaritiesrBrCcSr2)Nr5r(r4r(r(r)rd]r6cs(g|]}�d|�kr�d|�qSrAr(r�)�history�stable_namer(r)r`s246247�z
Desconocido: uNHaga clic en 'Iniciar Cámara' para comenzar el reconocimiento en tiempo real.)r/)r/rM)TTrZr9)r/TTrMrZr9)~r�set_page_config�sidebar�titler�rrr�	selectbox�cache_resource�markdownr��radio�slider�color_picker�tuple�checkbox�
file_uploader�np�asarray�	bytearrayr��uint8r"ZimdecodeZIMREAD_COLORr1r�rqr�rQ�columns�	subheaderr�r�	fromarray�metricrR�expanderr�r�r�r�rrr�open�video�button�spinner�download_button�remove�rmdirr�r��infor�r�r�warning�sleepr�r�Zfeature_original_imager�r�r�Zoriginal_image1r�Zoriginal_image2rr$rrr	rrr�r?r@�any�success�plt�subplotsr=�barZ248set_xlabelZ249set_ylabel�	set_titleZ250get_heightr�Zget_xZ	get_widthr>�pyplotrr�r�r!r�tabs�header�form�251text_input�form_submit_buttonZ"extract_face_embeddings_all_modelsrpr��itemsr��pandas�	DataFrame�iterrows�experimental_rerunr*Zextract_face_embeddingsr�252ValueErrorrs�sortrSrTrUr;r<�pop)�Zapp_moder*r.r�r�r�r�r�r�r�r��253input_typerBZbbox_color_rgbZbbox_color_bgrZshow_metricsZfile_bufferZ	raw_bytesr�r�Zcol1Zcol2r�rDZprocessed_imagerEZprocessing_timeZpil_imgZcol3rFr{Zvideo_sourcer��	temp_path�fr,r-Zoutput_pathZ254output_dirr�Zsummary_col1Zsummary_col2Zsummary_col3rtruZvideo_bytesZcamera_placeholderZstart_buttonZstop_buttonr�r�rAr�rwrvZdetect_age_gender_optionryrzZmetrics_placeholderZmetrics_col1Zmetrics_col2Zmetrics_col3Zface_count_totalZeye_count_totalZsmile_count_totalr�Z255face_countr�r�Zcomparison_methodZembedding_modelZ256raw_bytes1�image1Z257raw_bytes2�image2r�r�Zdetections1Zprocessed_image1Zbboxes1Zdetections2Zprocessed_image2Zbboxes2Z	proc_col1Z	proc_col2Zcomparison_resultsr'ZreportZcombined_imageZface_comparisons�compZavg_similarityZmax_similarityZmin_similarityZ	avg_levelZ	avg_color�	max_levelZ	max_colorZmatches_above_thresholdZbest_matches�fig�ax�labels�colorsZ	hist_dataZbarsri�heightZpil_combined_img�bufZbyte_imZtab1Ztab2Ztab3Z
uploaded_fileZperson_nameZmodel_choiceZconfidence_thresholdZadd_to_existingZregister_buttonZembeddings_all_modelsr"r�Z	model_idxr Z
old_embeddingZ	old_modelr!rr|r+r1rbZnum_embeddingsZ258num_images�pd�df�rowZcol4Zcol5Z
voting_methodZshow_all_matchesZresult_imageZ259stats_cols�matchesrC�idxZregistered_embedding�weightr�Zfinal_similarityZweighted_sumZweights_sumrHrIrJrK�260best_matchrrX�jr261Z	sub_label�col_idxZshow_confidenceZstabilize_resultsZ	fps_limitZvideo_placeholderZmetrics_colsZfaces_metricZ262fps_metricZtime_metricZlast_frame_timeZfps_history�current_time�elapsedr�Zavg_fpsrWZface_idZname_countsZstable_similaritiesZstable_similarityr()263rrVrr�rLr�rDrYrrEr)�main s��264265266�267&268<$/[269270�271272273274�275"276��277278$�279���280 281282�283284285�286
287288289��290291292���2935294295296297298299300301302303304305���306307�	�	�	308309310�311�312313"314��315�316317318319�320321�322323324325��326327328���3296330331332333334335336337338339340�341342343��?�344W345346�+347�348���349�350351��352��353�354���355	356��357358�359�360361362363364365��366367 368369370371�372��"���373%��	��&374375�376 "�377378��&379380�381 "�382383��$�384����"���	385���������386�	�	��387��388& 389&��390391392"�� "02393394�.���$395������C396�397�398������:399�400�401402403�404405�406407�4084094104114124134142415&��416417"���418�419"&$$��420�5421�422����d�(��$�����r��__main__)$�	streamlitrr"�numpyrR�PILr�iorr�r�rr��urllib.request�urllib�matplotlib.pyplotrkrg�pickleZsklearn.metrics.pairwiserrrr�Zdeepfacerr��ImportErrorZface_comparisonrrrr	ZFACE_COMPARISON_AVAILABLErcr��__name__r(r(r(r)�<module>s`��423�