
    hЕ                        S SK JrJrJr  S SKJr  S SKrS SKrS SKrS SK	r
S SKrS SKrS SKrS SKr\R                  " \R                   R"                  5        S SKJrJr   S SKrS SKrS SKrSr\" S5        \" \5      r\" \5        S
rSrSq S r!S r"S r#\RI                  SS/S9S 5       r%\RI                  SS/S9S 5       r&\RI                  SS/S9S 5       r'\RI                  SS/S9S 5       r(\RI                  SS/S9S 5       r)\RI                  SS/S9S 5       r*\RI                  SS/S9S  5       r+\RI                  S!S/S9S" 5       r,\RI                  S#S/S9S$ 5       r-\RI                  S%S/S9S& 5       r.\RI                  S'S/S9S( 5       r/\RI                  S)S/S9S* 5       r0\RI                  S+S/S9S, 5       r1\S-:X  a  \Re                  SS.S/9  gg! \ a   rSr\" S\ 35        \" S	5         SrCGNSrCff = f)0    )Flaskrequestjsonify)CORSN)train_face_recognizerpreprocess_faceTu-   ✅ InsightFace libraries loaded successfullyFu"   ⚠️ InsightFace not available: u*   📝 System will continue with OpenCV onlyregistered_facesz/https://api-hris.scrubbed.net/users/getUserInfoc                      [         (       d  g [        c=  [        R                  R	                  5       q[        R                  SSS9  [        S5        g! [         a  n [        SU  35         Sn A gSn A ff = f)	z%Initialize InsightFace model globallyFNr   )  r   )ctx_iddet_sizeu.   ✅ InsightFace model initialized successfullyTu*   ❌ Error initializing InsightFace model: )INSIGHTFACE_AVAILABLEinsightface_modelinsightfaceappFaceAnalysisprepareprint	Exception)es    	server.pyinitialize_insightfacer   %   sm     ! $ + < < >%%Q%DBC :1#>?s   AA 
A5A00A5c                     [         (       d  [        S5        g [        5       (       d  g/ n[        R                  " U5       Vs/ s H  o3R                  S5      (       d  M  UPM     nn[        S[        U5       S35        U H  n[        R                  R                  X5      n[        R                  " U5      nUb\  [        R                  U5      nU(       a0  US   R                  n	UR                  U	5        [        SU 35        M  [        S	U 35        M  [        S
U 35        M     U(       a  U U[        R                  R!                  5       R#                  5       [        U5      S.n
SU  S3n[%        US5       n[&        R(                  " X5        SSS5        [        S[        U5       SU  35        [        SU 35        g[        SU  35        gs  snf ! , (       d  f       NK= f! [*         a  n[        SU 35         SnAgSnAff = f)z/Generate InsightFace embeddings for user imagesu?   ⚠️ InsightFace not available, skipping embedding generationF.jpgu   🔄 Processing z% images for InsightFace embeddings...Nr   u   ✅ Generated embedding for u   ⚠️ No face detected in u   ❌ Could not read image )user_id
embeddings
created_atimage_countinsightface_embeddings_.pklwbu   ✅ Generated z! InsightFace embeddings for user u   💾 Saved embeddings to Tu0   ⚠️ No faces detected in any images for user u-   ❌ Error generating InsightFace embeddings: )r   r   r   oslistdirendswithlenpathjoincv2imreadr   get	embeddingappenddatetimenow	isoformatopenpickledumpr   )r   user_folderr   fimage_filesimg_fileimg_pathimgfacesr+   embedding_dataembedding_filer   s                r   generate_insightface_embeddingsr<   5   s     OP0%''
"$**["9P"9QZZ=Oq"9P [!1 22WXY#Hww||K:H**X&C)--c2 %a 2 2I%%i08
CD7zBC1(<= $   #(&//335??A":	N  7witDNnd+qN. , N3z?"33TU\T]^_-n-=>?DWINOM Q< ,+  =aSABsS   G+ G+ G G&DG+ >G0G+ G+ G+ 
G($G+ +
H5HHc           	          [          SU  3nSS0n[        R                  " XSSS9nUR                  S:X  a  UR	                  5       n[        U 5      UR                  SS	U  35      UR                  S
S5      UR                  SS5      UR                  SS5      US.n[        SU  SUS    SUS    35        U$ [        SU  SUR                   SUR                   35        [        U 5      S	U  3SSSSS.$ ! [        R                  R                   a0  n[        SU  SU 35        [        U 5      S	U  3SSSSS.s SnA$ SnAff = f)z1Fetch employee information from live API endpoint/zContent-Typezapplication/json
   F)headerstimeoutverify   nameUser email 
departmentstatusactive)r   rD   rF   rH   rI   api_responseu#   ✅ Fetched employee info for User : z - u#   ⚠️ API request failed for User z
. Status: z, Response: unknownNu*   ❌ Error fetching employee info for User )
API_ENDPOINTrequestsr*   status_codejsonstrr   text
exceptionsRequestException)r   urlr@   responseresponse_dataemployee_infor   s          r   fetch_employee_inforZ   m   s   ,
ay)!#56<<bO3&$MMOM w<%))&E'2CD&**7B7+//bA'++Hh? -M 7y=QWCXBYY\]jkw]x\yz{   7y
8K_K_J``lmumzmzl{|}w<y) # $  // 	
:7)2aSIJ7|G9% 
 	
	
s$   B5C5 8<C5 5E%D>8E>Ez	/registerPOST)methodsc                    ^^^ [         R                  " 5       n U R                  S5      mU R                  S5      nU R                  SST 35      nU R                  SS5      nU R                  SS5      nT(       a  U(       d  [        SS	05      S
4$ [        R
                  R                  [        T5      m[        R                  " TSS9  [        U5       Hv  u  pVUR                  SS5      u  px[        R                  " U5      n	[        [        R
                  R                  TU S35      S5       n
U
R                  U	5        S S S 5        Mx     [        S5        [        S[!        U5       ST 35        [#        5         [        S5        [        R
                  R%                  S5      (       a  [        S5        O[        S5        [&        (       a6  [        S5        [)        TT5      nU(       a  [        S5        O[        S5        O[        S5        Sn0 n[        R
                  R%                  U5      (       a+  [        US5       n
[*        R,                  " U
5      nS S S 5        UUUS[.        R.                  R1                  5       R3                  5       S.UT'   [        US 5       n
[*        R4                  " XS!S"9  S S S 5        [        S#5        [        S$5        S%S KnS%S KmUUU4S& jnUR;                  US'9nSUl        UR?                  5         [        S(ST S)U S*[!        U5       S+305      $ ! , (       d  f       GMi  = f! , (       d  f       N= f! , (       d  f       N= f),NuserIdimagesuserNamerE   	userEmailrG   userDepartmenterrorzUser ID and images are required  T)exist_ok,   r   r!   zStarting training process...zTraining with  images for user zTraining process finished.face_recognizer.ymlzModel file updated successfullyz,WARNING: Model file not found after trainingu)   🔄 Generating InsightFace embeddings...u.   ✅ InsightFace embedding generation completedu.   ⚠️ InsightFace embedding generation failedu=   📝 InsightFace not available, skipping embedding generationuser_data.jsonrhired)rD   rF   rH   rI   last_updatedw   indentz4Photos kept temporarily for training verification...zBPhotos will be automatically deleted after 5 minutes for security.r   c                     > SS K n U R                  S5        [        R                  R	                  T5      (       a!  TR                  T5        [        ST S35        g g )Nr   i,  zPhotos for user z& deleted after 5 minutes for security.)timesleepr"   r&   existsrmtreer   )rs   shutilr3   r   s    r   delete_photos_later%register.<locals>.delete_photos_later   sH    

377>>+&&MM+&$WI-STU '    )targetmessagez (z) registered successfully with z% images. Photos deleted for security.) r   get_jsonr*   r   r"   r&   r'   FACE_DIRmakedirs	enumeratesplitbase64	b64decoder0   writer   r%   r   ru   r   r<   rQ   loadr-   r.   r/   r2   	threadingrw   Threaddaemonstart)datar_   	user_name
user_emailuser_departmenti
image_dataheaderencodedimage_bytesr4   insightface_successuser_data_file	user_datar   rx   deletion_threadrw   r3   r   s                    @@@r   registerr      s   Dhhx GXXhFuWI%67I+r*Jhh/4O&!BCDcII'',,x1KKKd+"6*$**32&&w/ "'',,{qcJ7>!GGK  ?> + 

()	N3v;-'8	
BC	
&' 
ww~~+,,/0<= 9:=g{SBCBCMN &NI	ww~~n%%.#&!		!I '
 % ))--/99;Ig 
nc	"a		)q) 
# 

@A	
NO V  &&.A&BO!OIwir)<[\_`f\g[h  iN   O  P  Q  QA ?>< '& 
#	"s$   1L.M$M.
L>	
M
M z
/recognizec                  N   [         R                  " 5       n U R                  S5      nU(       d  [        SS05      S4$  UR	                  SS5      u  p#[
        R                  " U5      n[        R                  " U[        R                  5      n[        R                  " U[        R                  5      nUc  [        SS05      S4$ [        R                  " U[        R                  5      n[        R                  " [        R                   R"                  S-   5      nUR%                  US	S
SS9n	['        S[)        U	5       S35        ['        SUR*                   35        [)        U	5      S:X  a  ['        S5        [        SS05      S4$ U	S   u  ppX{X-   2XU-   24   n[-        U5      n [        R.                  R1                  5       nSn[2        R4                  R7                  U5      (       d  [        SS05      S4$ UR9                  U5        UR;                  U5      u  nnSn['        SU SU SU 35        ['        SUU:  a  SOS 35        UU:  Ga  ['        SU SU 35        ['        SU S35        [=        U5      n['        S U 35        SS KnSS K nUR>                  RC                  5       nURE                  S!5      nURE                  S"5      nS#n[2        R4                  R7                  U5      (       a$  [2        RF                  " U5      RH                  S:X  a8  [K        US$S%S&9 nURM                  U5      nURO                  / S'Q5        S S S 5        S(nS)US*    S+U S,3n/ n/ n [K        US-S%S&9 nURQ                  U5      n!U! Hm  n"URS                  U"5        U"R                  S.5      [U        U5      :X  d  M4  U"R                  S/S%5      RW                  U5      (       d  M\  U RS                  U"5        Mo     S S S 5        [Y        S0 U  5       5      n#[Y        S1 U  5       5      n$U#(       d2  S(nS)US*    S+U S,3nURS                  U[U        U5      US*   US'.5        GO
U#(       a8  U$(       d1  S2nS)US*    S+U S33nURS                  U[U        U5      US*   US'.5        OU#(       a  U$(       a  S2nS)US*    S+U S43n[[        []        [)        U5      5      5       Hl  n%UU%   n&U&R                  S.5      [U        U5      :X  d  M(  U&R                  S/S%5      RW                  U5      (       d  MP  U&R                  S55      S2:X  d  Mg  UU&S/'     O$   URS                  U[U        U5      US*   US'.5        [K        US$S%S&9 nUR_                  U/ S'QS69nURa                  5         URc                  U5        S S S 5        S7[e        U5      US*   US8   US9   US:   [g        US;5      UUUS<.
n'['        S=U' 35        [        U'5      $ [        S>S?[g        US;5      S@U SAU 3SB.5      $ ! , (       d  f       GN= f! , (       d  f       GN4= f! , (       d  f       N= f! [h         a%  n([        SSC[U        U(5       305      SD4s S n(A($ S n(A(ff = f! [h         a%  n([        SSE[U        U(5       305      SD4s S n(A($ S n(A(ff = f)FNimagerc   Image data is requiredrd   rf   rg   Invalid image data#haarcascade_frontalface_default.xmlg?   )   r   scaleFactorminNeighborsminSizeu   🔍 Face detection: Found z faces in imageu   📐 Image size: r   u+   ❌ No faces detected - returning 400 errorNo face detectedri   ,Model file not found. Train the model first.   zRecognition attempt - User ID: z, Confidence: z, Threshold: zRecognition result: SUCCESSFAILEDu   ✅ RECOGNITION SUCCESS: User z recognized with confidence u,   🔄 Fetching employee information for User z from live API...u   📋 Employee info result: %Y-%m-%d %H:%M:%S%Y-%m-%dattendance_log.csvrn   rG   newline)	TimestampUser IDz	User NameStatusCheck-inrE   rD    (ID: z) checked in successfullyrk   r   r   c              3   H   #    U  H  oR                  S 5      S:H  v   M     g7f)r   r   Nr*   .0rk   s     r   	<genexpr>!recognize_face.<locals>.<genexpr>S  s     %[]eeHo&C]    "c              3   H   #    U  H  oR                  S 5      S:H  v   M     g7f)r   	Check-outNr   r   s     r   r   r   T  s     &]}!uuX+'E}r   r   z) checked out successfullyz) checkout time updatedr   )
fieldnamesTrF   rH   rI   ro   )
successr   r   r   r   user_status
confidence	timestampattendance_statusr|   u#   📤 Sending response to frontend: FzFace not recognizedzConfidence z >= threshold )r   r|   r   
debug_infoRecognition error:   Image processing error: )5r   r}   r*   r   r   r   r   np
frombufferuint8r(   imdecodeIMREAD_COLORcvtColorCOLOR_BGR2GRAYCascadeClassifierr   haarcascadesdetectMultiScaler   r%   shaper   faceLBPHFaceRecognizer_creater"   r&   ru   readpredictrZ   r-   csvr.   strftimestatst_sizer0   writerwriterow
DictReaderr,   rR   
startswithanyreversedrange
DictWriterwriteheader	writerowsintroundr   ))r   r   r   r   r   nparrr8   grayface_cascader9   xyrn   hface_img
recognizer
model_filer   r   confidence_thresholdrY   r-   r   r.   r   todaylog_filefiler   r   r|   all_recordstoday_recordsreaderrowcheck_in_existscheck_out_existsr   recordrX   r   s)                                            r   recognize_facer      s   D'"J!9:;S@@RX$**32&&w/ k2884ll5#"2"23;G%9:;S@@ ||C!3!34 ,,SXX-B-BEj-jk --dST^f-g+CJ<GH!#))-.u:??@G%7893>> Qxq!%q5()"8,m	K;;=J.J77>>*--)WXY[^^^OOJ'","4"4X">GZ $' 3G9N:,Vcdxcyz{(jCW6W]e(fgh006wi?[\f[ghiDWIM^_` 3G <3M?CD  ''++-LL)<=	Z0/ ww~~h//27783D3L3LPQ3QhR8D!$D!1(WX 9 %/!!-"7!8wiG`a  "(C4 ^^D1F%#**3/779-W=#''+WYBZBeBefkBlBl)005  & 5 #&%[]%["[#&&]}&]#] &(2% %mF&;%<F7)KdeG&&Y3w<fstzf{  HY  (Z  [$-=(3% %mF&;%<F7)KefG&&Y3w<fstzf{  HY  (Z  [$)9(3% %mF&;%<F7)KbcG &eC,<&=>!,Q!::i0CL@VZZP[]_E`EkEklqErErw}  xB  xB  CK  xL  P[  x[2;F;/!	 ? $**sSZ|jwx~j  L]  ,^  _ (C4 ^^D=l^mF&&($$[1 5  $"7|!.v!6"/"8'4\'B#0#:"'
A"6!*):&! ;M?KL}--$4"'
A"6$/
|>J^I_"`	   E 98 54H 546  	KG':3q6(%CDEsJJ	K  X"G/GAx-P#QRTWWWXs   BY5 C Y5 !Y5 'AY :D*Y $%X	%Y .AX 6$X X 3DY 8$Y  Y 76Y -4X2!AY .Y 
XY  
X/*Y 2
Y <Y 
Y2Y-'Y2(Y5 -Y22Y5 5
Z$?ZZ$Z$z/admin/usersGETc                      / n Sn0 n[         R                  R                  U5      (       a+  [        US5       n[        R
                  " U5      nSSS5        UR                  5        H  u  pESnSn[         R                  R                  U5      (       aw  [        US5       nUR                  5       n[        U5       HC  n	U	R                  5       (       d  M  XI;   d  M!  U	R                  S5      S   R                  5       n  O   SSS5        U R                  UUR                  SS5      UR                  S	S
5      UR                  SS
5      SUR                  SS
5      USS.5        GM     U R                  S SS9  [        SU 05      $ ! , (       d  f       GN@= f! , (       d  f       N= f! [         a%  n
[        SS[!        U
5       305      S4s Sn
A
$ Sn
A
ff = f)zIGet all registered users with their details (photos deleted for security)rj   rk   Nr   rf   r   rD   UnknownrF   rG   rH   Trainedrm   Active)r   rD   rF   rH   r   last_modifiedlast_attendancerI   c                     U S   $ )Nr    )r   s    r   <lambda>get_all_users.<locals>.<lambda>  s	    ?!3rz   T)keyreverseusersrc   zError fetching users: r   )r"   r&   ru   r0   rQ   r   items	readlinesr   stripr   r,   r*   sortr   r   rR   )r  r   r   r4   r   	user_infoattendance_filer   linesliner   s              r   get_all_usersr    s   &J *	77>>.))nc*a IIaL	 + #,//"3G2O"Oww~~o../3/1KKME (::<<GO.2jjoa.@.F.F.HO! !0 0 LL"!fi8"w3'mmL"=(!*~r!B#2"	 	 #40 	

3T
B'((; +* 0/,  J#9#a&!BCDcIIJsZ   6F+ FAF+  2FF&FBF+ 
FF+ 
F(	$F+ +
G5GGGz/admin/users/<user_id>DELETEc                     SnSn[         R                  R                  U5      (       a_  [        US5       n[        R
                  " U5      nSSS5        U W;   a.  X@	 Sn[        US5       n[        R                  " XCSS9  SSS5        [         R                  R                  [        U 5      n[         R                  R                  U5      (       a  S	SK	nUR                  U5        SnU(       a5  [        S
U  S35        [        5         [        S5        [        SSU  S305      $ [        SS05      S4$ ! , (       d  f       N= f! , (       d  f       N= f! [         a%  n[        SS[        U5       305      S4s SnA$ SnAff = f)z/Delete a user from the system and retrain modelrj   Frk   NTrn   ro   rp   r   z%Retraining model after deleting user z...zModel retrained successfully.r|   rE   z6 deleted successfully from system and model retrained.rc   zUser not found in system  zError deleting user: r   )r"   r&   ru   r0   rQ   r   r2   r'   r~   rw   rv   r   r   r   r   rR   )r   r   user_deletedr4   r   r3   rw   r   s           r   delete_userr    sN   !I)77>>.))nc*a IIaL	 + )#&#.#.!IIi15 / ggll8W577>>+&&MM+&L9'#FG!#12Iwi7m'noppG%?@A3FF3 +* /.&  I#8Q!ABCSHHIsS   4E D3E +EB"E $E 3
E=E 
EE 
FE?9F?Fz/admin/users/<old_user_id>PUTc                     [         R                  R                  [        U 5      n[         R                  R                  [        W5      n[         R                  R	                  U5      (       d  [        SS05      S4$ [        R                  " 5       nUR                  S5      nU(       d  [        SS05      S4$ [         R                  R                  [        U5      n[         R                  R	                  U5      (       a  [        SS05      S4$ [         R                  " X5        [        SS	U  S
U 305      $ ! [         a%  n[        SS[        U5       305      S4s SnA$ SnAff = f)zUpdate user ID (rename folder)rc   User not foundr  new_user_idzNew user ID is requiredrd   zNew user ID already existsr|   zUser ID updated from z to zError updating user ID: r   N)r"   r&   r'   r~   ru   r   r   r}   r*   renamer   rR   )old_user_id
old_folderr  
new_folderr   r   s         r   update_user_idr    s*   LWW\\(K8
WW\\(K8
ww~~j))G%567<<!hh}-G%>?@#EEWW\\(K8
77>>*%%G%ABCSHH
		*)
 	%:;-tK=#YZ[[ L#;CF8!DEFKKLs1   A:D9 =;D9 9AD9 (D9 9
E(E#E(#E(z/admin/users/<user_id>/imagesc                     [         R                  R                  [        U 5      n[         R                  R	                  U5      (       d  [        SS05      S4$ Sn[         R                  " U5       HS  nUR                  S5      (       d  M  [         R                  " [         R                  R                  X5      5        US-  nMU     [        SSU S	U  305      $ ! [         a%  n[        SS
[        U5       305      S4s SnA$ SnAff = f)z0Delete all images for a user but keep the folderrc   r  r  r   r   rg   r|   zDeleted rh   zError deleting images: r   N)r"   r&   r'   r~   ru   r   r#   r$   remover   rR   )r   r3   deleted_countfilenamer   s        r   delete_user_imagesr"    s    Kggll8W5ww~~k**G%567<< 

;/H  ((		"'',,{=>" 0 	Xm_<MgY#WXYY K#:3q6(!CDEsJJKs+   AC /C AC 
D
%D?D
D
c                     [         R                  R                  [        U 5      n[         R                  R	                  U5      (       d  [        SS05      S4$ / n[         R                  " U5       H  nUR                  S5      (       d  M  [         R                  R                  X5      n[        US5       n[        R                  " UR                  5       5      R                  S5      nUR                  USU 3S.5        S	S	S	5        M     [        S
U05      $ ! , (       d  f       M  = f! [         a%  n[        SS[        U5       305      S4s S	nA$ S	nAff = f)z"Get all images for a specific userrc   r  r  r   rbzutf-8zdata:image/jpeg;base64,)r!  r   Nr_   zError fetching images: r   )r"   r&   r'   r~   ru   r   r#   r$   r0   r   	b64encoder   decoder,   r   rR   )r   r3   r_   r!  
image_pathr4   r   r   s           r   get_user_imagesr(    s"   Kggll8W5ww~~k**G%567<<

;/H  ((WW\\+@
*d+q!'!1!1!&&(!;!B!B7!KJMM$,"9* F#  ,+	 0 &)** ,+  K#:3q6(!CDEsJJKsC   AD- /D- +D- 7ADD- 
D*	%D- -
E7EEEz/attendance/statsc                      SSK n SSKnSSKJn  U R                   R	                  5       R                  S5      nU R                   R	                  5       U R                  " SS9-
  R                  S5      nU R                   R	                  5       U R                  " SS9-
  R                  S5      nSSS/ S.nS	n[        R                  R                  U5      (       Ga  [        US
SS9 nUR                  U5      n	U	 H  n
U
R                  SS5      nU(       d  M   U R                   R                  US5      nUR                  S5      nX:X  a  US==   S-  ss'   X:  a  US==   S-  ss'   X:  a  US==   S-  ss'   [        US   5      S:  a\  US   R                  [        US   5      S-   SU
R                  SS5       3UR                  S5      U
R                  SS5      S.5        M  M     SSS5        [#        U5      $ ! [          a     GM  f = f! , (       d  f       N+= f! [$         a%  n[#        SS['        U5       305      S4s SnA$ SnAff = f)z'Get attendance statistics for dashboardr   N)defaultdictr      )days   )r   thisWeek	thisMonthrecentActivityr   rk   rG   r   r   r   r   rg   r.  r/  r0  r?   rE   r   r   %I:%M %pr   r   )iduserrs   rI   rc   zError getting stats: r   )r-   r   collectionsr*  r.   r   	timedeltar"   r&   ru   r0   r   r*   strptimer%   r,   
ValueErrorr   r   rR   )r-   r   r*  r   week_ago	month_agostatsr   r   r   r   r   dtdate_strr   s                  r   get_attendance_statsr=  -  sH   8I+!!%%'00<%%))+h.@.@a.HHRRS]^&&**,x/A/Ar/JJTTU_`	  	
 (77>>(##hR0D-!C #R 8I y%!)!2!2!;!;IGZ![B'){{:'>H  (0 %g! 3  (3 %j 1Q 6 1  (4 %k 2a 7 2  #5)9#:;b@ %&6 7 > >*-e4D.E*F*J.3CGGIy4Q3R,S,.KK
,C.1ggh
.K	@" !#  A+ " 1B u~  * %$%= 10F  I#8Q!ABCSHHIs[   C$H$ &.HCH(H.H$ 
HHHH
H!H$ $
I.IIIz/test/modelc            
          Sn [         R                  R                  U 5      (       d  [        SS05      S4$ [        R
                  R                  5       nUR                  U 5        Sn/ n[         R                  R                  U5      (       ai  [         R                  " U5       Vs/ s HH  n[         R                  R                  [         R                  R                  X$5      5      (       d  MF  UPMJ     nn/ nSn[         R                  R                  U5      (       aD  [        US5       n[        R                  " U5      n[        UR                  5       5      nSSS5        [        S	[         R                  R!                  U 5      UU[#        U5      [#        U5      :g  S
SS.5      $ s  snf ! , (       d  f       NX= f! [$         a%  n	[        SS['        U	5       305      S4s Sn	A	$ Sn	A	ff = f)zATest if the face recognition model is working and check alignmentri   rc   zModel file not foundrd   r	   rj   rk   NTr   zModel is ready for recognition)model_existsmodel_file_sizefolder_users
json_usersalignment_issuer   rI   zModel test failed: r   )r"   r&   ru   r   r(   r   r   r   r#   isdirr'   r0   rQ   r   listkeysgetsizer%   r   rR   )
r   r   face_dirrA  drB  r   r4   r   r   s
             r   
test_modelrJ  j  s    G*
ww~~j))G%;<=sBBXX779

# &77>>(##')zz(';h';!rww}}RWW\\ZbMf?gA';Lh 
)77>>.))nc*a IIaL	!).."23
 +  !wwz:($"<0C
OC$'6
  	 i +*  G#6s1vh!?@A3FFGsU   4F> A/F> &AF(/F(56F> +0F-AF> (F> -
F;7F> >
G-G("G-(G-z/attendance/datac                      SSK n SSKn/ nSn[        R                  R	                  U5      (       a  [        USSS9 nUR                  U5      nU H  nUR                  SS5      nUR                  SS	5      nUR                  S
S5      n	U(       d  MB   U R                   R                  US5      n
UR                  U
R                  S5      SU 3U
R                  S5      U
R                  S5      SU	S.5        M     SSS5        [        SU05      $ ! [         a     M  f = f! , (       d  f       N,= f! [         a%  n[        SS[        U5       305      S4s SnA$ SnAff = f)z(Get detailed attendance data for reportsr   Nr   rk   rG   r   r   r   r   r   r   r   r   rE   r1  z8h 0m)dater3  checkincheckoutdurationrI   
attendancerc   zError getting attendance data: r   )r-   r   r"   r&   ru   r0   r   r*   r6  r,   r   r7  r   r   rR   )r-   r   attendance_datar   r   r   r   r   r   rI   r;  r   s               r   get_attendance_datarR    sW   $S (77>>(##hR0D-!C #R 8I!ggi;G WWXz:F y%!)!2!2!;!;IGZ![B ,22(*J(?*/y(9+-;;z+B,.KK
,C,3*04  " 10 o677  * %$%+ 104  S#B3q6(!KLMsRRSsZ   ;D3 AD"A$D8D"<D3 
DD"DD""
D0,D3 3
E"=EE"E"z/debug/recognizec                     [         R                  " 5       n U R                  S5      nU(       d  [        SS05      S4$  UR	                  SS5      u  p#[
        R                  " U5      n[        R                  " U[        R                  5      n[        R                  " U[        R                  5      nUc  [        SS05      S4$ [        R                  " U[        R                  5      n[        R                  " [        R                   R"                  S	-   5      nUR%                  US
SSS9n	UR%                  USSSS9n
UR&                  S    SUR&                  S    3[)        U	5      [)        U
5      [)        U	5      S:  a  U	R+                  5       O/ [)        U
5      S:  a  U
R+                  5       O/ S.n[)        U	5      S:X  a  [        SSUS.5      S4$ U	S   u  ppX}X-   2XU-   24   n[-        U5      n [        R.                  R1                  5       nSn[2        R4                  R7                  U5      (       d  [        SS05      S4$ UR9                  U5        UR;                  U5      u  nn/ SQn0 nU H  nUU:  [=        US5      S.USU 3'   M     UR?                  S[A        U5      [=        US5      US.05        [        S[A        U5      [=        US5      US S!.5      $ ! [B         a%  n[        SS"[E        U5       305      S#4s SnA$ SnAff = f! [B         a%  n[        SS$[E        U5       305      S#4s SnA$ SnAff = f)%z7Debug endpoint to test recognition with detailed outputr   rc   r   rd   rf   rg   Nr   r   g?   )r-  r-  r   g333333?   )2   rV  r   r   )
image_sizefaces_detected_sensitivefaces_detected_normalface_locations_sensitiveface_locations_normalFz*No face detected with sensitive parameters)r   r|   r   ri   r   )P   U   Z   _   d   ro   )
recognizedr   
threshold_recognition_results)r   r   threshold_testsTzDebug recognition completed)r   r   r   r   r|   r   r   r   )#r   r}   r*   r   r   r   r   r   r   r   r(   r   r   r   r   r   r   r   r   r   r%   tolistr   r   r   r"   r&   ru   r   r   r   updater   r   rR   )r   r   r   r   r   r   r8   r   r   faces_1faces_2r   r   r   rn   r   r   r   r   r   r   
thresholdsthreshold_results	thresholdr   s                            r   debug_recognitionrl    sS    D'"J!9:;S@@SL$**32&&w/ k2884ll5#"2"23;G%9:;S@@ ||C!3!34 ,,SXX-B-BEj-jk //#TU_g/h//#TU_g/h !YYq\N!CIIaL>:(+G%(\<?L1<L(8RT9<W9IW^^%5r

 w<1 G(  	  qzq!%q5()"8,%	K;;=J.J77>>*--)WXY[^^^OOJ'","4"4X">GZ /J "'	",y"8"'
A"6?!Jyk":; ( %"7|"'
A"6'8(  w<#J2(8    	KG':3q6(%CDEsJJ	K  L#;CF8!DEFKKLs]   BL DL !L 7AK$ 
BK$ $
L.LL	L LL 
M M :M Mz/insightface/embeddingsc            	         [         (       d  [        SSS.5      S4$  / n / n/ n[        R                  " S5       Vs/ s H4  o3R	                  S5      (       d  M  UR                  S5      (       d  M2  UPM6     nn[        S[        U5       S	35        U GH  n [        US
5       n[        R                  " U5      nUS   n[        R                  R                  S5      (       aS  [        SS5       n[        R                  " U5      nUR                  U0 5      n	U	R                  SSU 35      n
SSS5        OSU 3n
US    HD  nU R                  UR!                  5       5        UR                  W
5        UR                  U5        MF     SSS5        [        SW
 SW S35        GM     [        S[        U 5       35        [        SU UU[        U 5      S.5      $ s  snf ! , (       d  f       N= f! , (       d  f       Nl= f! ["         a  n[        SU SU 35         SnAGM  SnAff = f! ["         a1  n[        SU 35        [        S[%        U5      S.5      S4s SnA$ SnAff = f)z1Get all InsightFace embeddings for standalone appFInsightFace not availabler   rc     .r   r    u   🔄 Loading z InsightFace embedding files...r$  r   rj   rk   rD   rE   Nr   u   ✅ Loaded embeddings for r   )   ⚠️ Error loading rL   u   ✅ Total embeddings loaded: T)r   r   namesidscountu)   ❌ Error in get_insightface_embeddings: r   )r   r   r"   r#   r   r$   r   r%   r0   r1   r   r&   ru   rQ   r*   r,   re  r   rR   )all_embeddings	all_namesall_idsr4   embedding_filesr;   r   r   r   r  r   r+   r   s                r   get_insightface_embeddingsr{    sY    ! 0
   	
4	 ')jjoxoF_9`1efeoeopvew1oxc/233RST-N.$/1!;;q>D"9oG ww~~&677!"2C8A(,		!I(1gr(BI(1fgY>O(PI 98
 ',G9$5	 &*,%7	&--i.>.>.@A!((3w/ &8 0& 29+VG9ANO+ .6 	-c..A-BCD((
  	C y 98 0/*  -n-=RsCD  9!=>V
   	s   H) GG0G6 H) G?#AG./>G-AG.G?"5H) H) 
G+'G..
G<	8G??
H&	H!H) !H&&H) )
I$3&II$I$z/insightface/recognizec            
         [         (       d  [        SSS.5      S4$  [        R                  " 5       n U R	                  S5      nU(       d  [        SS05      S4$ UR                  S	S
5      u  p#[        R                  " U5      n[        R                  " U[        R                  5      n[        R                  " U[        R                  5      nUc  [        SSS.5      S4$ [        5       (       d  [        SSS.5      S4$ [        R	                  U5      nU(       d  [        SSS.5      S4$ US   R                   nSn	[#        S5      n
Sn[$        R&                  " S5       Vs/ s H4  oR)                  S5      (       d  M  UR+                  S5      (       d  M2  UPM6     nnU Hv  n [-        US5       n[.        R0                  " U5      n U S   nU S    H9  n[        R2                  R5                  UU-
  5      nUU
:  d  M-  UU:  d  M5  Un
Un	M;     SSS5        Mx     U	(       a*  S
U
-
  n[        SU	[;        US5      S[;        U
S5      S.5      $ [        SSUS .5      S!4$ s  snf ! , (       d  f       M  = f! [6         a  n[9        SU SU 35         SnAM  SnAff = f! [6         a1  n[9        S"U 35        [        S[=        U5      S.5      S4s SnA$ SnAff = f)#z Recognize face using InsightFaceFrn  ro  rp  r   rc   zNo image data providedrd   rf   rg   Nr   z&Failed to initialize InsightFace modelr   r   r   infg333333?rq  r   r    r$  r   r   rs  rL   Tr   r   )r   r   r   methoddistancezNo match found)r   rc   rk  r  u$   ❌ Error in insightface_recognize: )r   r   r   r}   r*   r   r   r   r   r   r   r(   r   r   r   r   r+   floatr"   r#   r   r$   r0   r1   r   linalgnormr   r   r   rR   )r   r   r   r   r   r   r8   r9   face_embedding
best_matchbest_distancerk  r4   rz  r;   r   known_embeddingr  r   r   s                       r   insightface_recognizer  V  s    ! 0
   	
S!XXg&
G%=>?DD %**32&&w/k2884ll5#"2"23; -    &'' A    "%%c* +   
 q++ 
e	 ')jjoxoF_9`1efeoeopvew1ox-N.$/1!;;q>D"9oG+/+=#%99>>.?2R#S#m398L,4M)0J ,>	 0/ .$ ]*J%#J2'!-3    )&  	 = y 0/  -n-=RsCD(  4QC89V
   	s   ;J BJ  J ?+J +6J !I>IIJ $I30A
I!>I!I!I34J J J !
I0	+I3.J 0I33
J=JJ JJ 
K&&KKK__main__i  )debugport)3flaskr   r   r   
flask_corsr   r"   r   r(   numpyr   rQ   r-   rO   urllib3disable_warningsrT   InsecureRequestWarning
livestreamr   r   r   onnxruntimer1   r   r   ImportErrorr   __name__r   r~   rN   r   r   r<   rZ   router   r   r  r  r  r"  r(  r=  rJ  rR  rl  r{  r  runr  rz   r   <module>r     s   ) )  	  
        ++BB C =	8 	
9: Ho S	@   6p.
` ;)TQ *TQl <&*YX +YXv >E7+(J ,(JT #hZ8#I 9#IJ '%9L :L: *XJ?K @K* *UG<K =K. 0:I 1:Ix =5'*"G +"GH w/&S 0&SP x0[L 1[L| $ug6< 7<| #fX6[ 7[z zGG$TG" {  8!	.qc
23	
6778s    G G>G99G>