
    3&}hr+                     b   d dl Z d dlZd dlmZmZmZmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d dlZd dlZd dlZd dlZd d
lmZmZ d dlmZm Z  d dl!m!Z! d dl"m#Z# d dl$m%Z%m&Z&m'Z' d dl(m)Z)  ede*      Z+e+jY                  dddg      d        Z-e+jY                  ddg      d        Z.e+jY                  ddg      d        Z/e+jY                  ddg      d        Z0d Z1d Z2 e       Z3e+jY                  ddg      d        Z4e+jY                  d dg      d!        Z5y)"    N)	Blueprintrequestjsonify	send_filecurrent_app)get_llm)get_tts)get_stt)BlobServiceClient)
Proctoring)BytesIO)DeepFace)	BaseModelValidationError)OptionalList)datetime)timezone)AnalysisRequestAnalysisResponseHeadPose)
fraudCheckroutes/GETPOST)methodsc                      t        ddd      S )NzEngine is runningsuccess)messagestatus)r        #/var/www/html/test/engine/routes.pyindexr%      s    &  r#   z/api/llmc                     t        j                          } 	 t        j                         }|st        ddi      dfS d|vrt        ddi      dfS d|v r
|d   r|d   nd}|d   }t	        |      }|j                  |      }t        | d       t        d	|i      S # t        $ r2}t        | d       t        d
t        |       dd      dfcY d}~S d}~ww xY w)z
    LLM (Language Learning Model) API endpoint
    Purpose: Generates text responses using specified LLM engine
    Input: JSON with required 'prompt' field and optional 'engine' field
    Returns: Generated text response or error message
    errorNo JSON data provided  promptz Missing required field: 'prompt'engineopenaillmresponsezAn error occurred: failedr'   r!     N)	timer   get_jsonr   r   generate_textget_duration	Exceptionstr)startdatar+   r*   
llm_engineresultes          r$   llm_apir=      s    IIKE!0   4;   $,t#3XhHhV_
))&1UE"
F+,, UE"*3q6(3
   	s)   $B B A	B 	C!'CCCz/api/ttsc                     t        j                          } d}	 t        j                         st        ddi      dfS g d}t	        fd|D              s!t        dddj                  |       i      dfS j                  d	      xs d
}j                  dd      j                         }t        j                  j                  dd      }d   }| d| }d| d}t        j                  dd       	 t        |      }|j                        }|dk(  rEt        |d      5 }	|j                  d       |	j!                  |j#                                ddd       d| d||d}
t%        | d       t        |
      S # 1 sw Y   *xY w# t&        $ r=}|r4t        j(                  j+                  |      rt        j,                  |       |d}~ww xY w# t&        $ re}t%        | d       |r4t        j(                  j+                  |      rt        j,                  |       t        t/        |      dd      dfcY d}~S d}~ww xY w)an  
    Text-to-Speech (TTS) API endpoint
    Purpose: Converts text to speech audio and handles storage
    Input: JSON with required fields:
        - text: Text to convert to speech
        - name: Filename for the audio
        - engine: TTS engine to use
        - storage: Storage type (local/azure)
    Returns: Audio file location (local path or Azure URL)
    Nr'   r(   r)   )textnamer+   voicec              3   &   K   | ]  }|v  
 y w)Nr"   ).0kr9   s     r$   	<genexpr>ztts_api.<locals>.<genexpr>Z   s     6196s   zMissing required fields: z, r+   
elevenlabsstoragelocalDEPLOYMENT_ENVunknownr@   _z./temp/questions_audios/.mp3z./temp/questions_audiosT)exist_okwbr   r   )r!   filename
local_pathenvironmentttsr/   r0   r1   )r2   r   r3   r   alljoingetlowerr   configosmakedirsr	   text_to_speechopenseekwritereadr5   r6   pathexistsremover7   )r8   rP   required_fieldsr+   rG   
deploy_env	file_name
tts_engineaudio_iofr.   r<   r9   s               @r$   tts_apirh   E   s3    IIKEJ9!G%<=>CC =6o664TYY5O4PQ   (#3|((9g.446 !''++,<iH
L	!l!I;/	/	{$?

-=	 J!006H '!*d+ -qMM!$GGHMMO,-
 $(k.()	H &8$$- -  	bggnnZ8		*%G	
  UE""''..4IIj!V
   	s`   $G 8G 7A>G 6-F	 #1E=(F	 =FF	 		G8G

GG 	I AH;5I ;I z/api/sttc                     t        j                          } 	 t        j                         }|st        ddi      dfS |j	                  d      }|j	                  dd      j                         }|rt        j                  j                  |      st        ddi      dfS 	 t        |      }|j                  |      }t        | d       t        d	|d
      S # t        $ r2}t        | d       t        dt        |       dd      dfcY d}~S d}~ww xY w# t        $ r2}t        | d       t        dt        |       dd      dfcY d}~S d}~ww xY w)a/  
    Speech-to-Text (STT) API endpoint
    Purpose: Converts audio file at given path to text using specified STT engine
    Input: JSON with fields:
        - file_path: Path to the audio file on server
        - engine: STT engine to use (default: whisper)
    Returns: JSON with transcribed text
    r'   zNo JSON body providedr)   	file_pathr+   whisperzInvalid or missing file_pathsttr   )r!   
transcriptzFailed to transcribe audio: r/   r0   r1   NzUnexpected error: )r2   r   r3   r   rU   rV   rX   r_   isfiler
   transcribe_audior5   r6   r7   )r8   r9   rj   r+   
stt_enginerm   r<   s          r$   stt_apirq      s]    IIKE#!G%<=>CCHH[)	(I.446 y 9G%CDEsJJ	 J#44Y?J&#(  
  	&7Ax@"   	  UE")#a&2
   	sM   $D A D 5C 	D'D	DD 	DD 	E'EEEc                 Z    t        j                          | z
  }t        d| d|dd       |S )a	  
    Utility function to measure and log execution time
    Purpose: Calculates and prints the duration of API calls
    Parameters:
        - start: Start time of the function
        - fnName: Name of the function being timed
    Returns: Duration in seconds
    z	Function z took z.2fz seconds)r2   print)r8   fnNamedurations      r$   r5   r5      s2     yy{U"H	IfXVHS>
:;Or#   c                    	 t        j                  d      }t        j                  d      }t        j                  d      }d| d| d}t	        j
                  |      }|j                  |      }| j                  d       |j                  || d	      }d
t        j                  d       d| d| }	|	|fS # t        $ r}
t        dt        |
             d}
~
ww xY w)a  
    Azure Blob Storage upload handler
    Purpose: Uploads audio files to Azure Blob Storage
    Parameters:
        - audio_io: BytesIO object containing audio data
        - name: Base name for the blob file
    Returns: Tuple of (blob_url, blob_name)
    Required Environment Variables:
        - AZURE_STORAGE_CONNECTION_STRING
        - AZURE_CONTAINER_NAME
        - AZURE_STORAGE_ACCOUNT
    AZURE_STORAGE_CONNECTION_STRINGAZURE_CONTAINER_NAMEz%Y%m%d-%H%M%Sztts/-rL   r   T)r@   r9   	overwritezhttps://AZURE_STORAGE_ACCOUNTz.blob.core.windows.net/r   zAzure upload failed: N)rX   getenvr2   strftimer   from_connection_stringget_container_clientr\   upload_blobr6   r7   )rf   r@   connection_stringcontainer_name	timestamp	blob_nameblob_service_clientcontainer_clientblob_clientblob_urlr<   s              r$   upload_to_azurer      s    :II&GH#9: MM/2	4&)D1	 0FFGXY.CCNS 	a&22 3 
 bii(?@AAXYgXhhijsitu"" :/Ax899:s   B4B7 7	C CCz/api/proctor/analyzec                     t        d       	 t        di t        j                  } 	 t        j                  | j                        }t        j                  t        j                  |t        j                        t        j                        }|t!        d      	 	 t$        j'                  |      }|d   rt)        di |d   nd }d }	 t+        j,                  |d	gd
d      }t/        |t0              r+t3        |      dkD  r|d   d	   }t$        j5                  |      }d}	|r5t$        j;                  |j<                  |j>                  |j@                        }	tC        jD                  tG        d            jI                         }
tK        |d   |d   ||g |
      }|jM                         }|	|d<   t        |      S # t        $ r(}t        d|j                         d      dfcY d }~S d }~ww xY w# t"        $ r t        ddi      dfcY S w xY w#  t7        j8                          Y xY w# t"        $ r7}t7        j8                          t        dtO        |      d      dfcY d }~S d }~ww xY w)Nzcalling analyze endpointzInvalid request format)r'   detailsr)   zDecoded image is Noner'   zInvalid base64 image	head_poseemotionFopencv)img_pathactionsenforce_detectiondetector_backendr   zNot detectedzAsia/Kolkataface_detectedpeople_count)r   r   r   dominant_emotionflagsr   head_orientation_readablezInternal server errorr1   r"   )(rs   r   r   jsonr   r   errorsbase64	b64decodeimagecv2imdecodenp
frombufferuint8IMREAD_COLOR
ValueErrorr6   
proctoringanalyzeFramer   r   analyze
isinstancelistlenfuseEmotions	traceback	print_excdescribeHeadPoseyawpitchrollr   nowr   	isoformatr   dictr7   )requestDatar<   	imageDataframevisionResultsheadPoseDatadominantEmotionanalysisemotionsheadOrientationReadableistTimer.   payloads                r$   r   r      sH   	
$%X%55?$$[%6%67	R]]9bhh?AQAQR=455 
-S"//6AN{A[x=-"<=ae	"''""'!)	H (D)c(ma.?#A;y1","9"9("C #1&0&A&A  ""!!'# ,,x78BBD#'8&~6",
 --//F+,wi  X!9ahhjQRTWWWX  ?!7893>>?$	"!6  S!8SVLMsRRSsg   F9 A2G- ,H' AH BH' 9	G*G%G*%G*-HHH$!H' '	I'0,I"I'"I'z/api/proctor/verify_identityc                  6   	 t        j                         } | j                  d      }| j                  d      }t        j                  ||      }t        |      S # t        $ r6}t        j                          t        dt        |      i      dfcY d }~S d }~ww xY w)Nid_imageselfier'   r1   )
r   r3   rU   r   match_facesr   r6   r   r   r7   )r9   id_image_b64
selfie_b64r;   r<   s        r$   verify_identityr   6  s    /!xx
+XXh'
''jAv /Q()3../s   AA 	B"+BBB)6r2   rX   flaskr   r   r   r   r   services.llmr   services.ttsr	   services.sttr
   azure.storage.blobr   services.proctorr   ior   deepfacer   r   r   numpyr   r   pydanticr   r   typingr   r   r   pytzr   services.proctor.models.modelsr   r   r   services.proctor.fraud_checkr   __name__r   router%   r=   rh   rq   r5   r   r   r   r   r"   r#   r$   <module>r      s<    	 E E       0 '   * * / !   V V 3	8X	&cE6?+ , j6(+" ,"J j6(+F ,FP j6(+. ,.`':T L
$vh7<S 8<S| ,vh?/ @/r#   