
    +@h/                        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) d dl*m+Z+ d dl,m-Z-  ede.      Z/e/ja                  dddg      d        Z1e/ja                  ddg      d        Z2e/ja                  ddg      d        Z3e/ja                  ddg      d        Z4d Z5d Z6 e       Z7e/ja                  d dg      d!        Z8e/ja                  d"dg      d#        Z9e/ja                  d$dg      d%        Z:e/ja                  d&dg      d'        Z;y)(    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)check_attire)get_pdf_extractorroutes/GETPOST)methodsc                      t        ddd      S )NzEngine is runningsuccess)messagestatus)r        "/var/www/html/dev/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kr;   s     r&   	<genexpr>ztts_api.<locals>.<genexpr>\   s     6196s   zMissing required fields: z, r-   
elevenlabsstoragelocalDEPLOYMENT_ENVunknownrB   _z./temp/questions_audios/.mp3z./temp/questions_audiosT)exist_okwbr   r!   )r#   filename
local_pathenvironmentttsr1   r2   r3   )r4   r   r5   r   alljoingetlowerr   configosmakedirsr	   text_to_speechopenseekwritereadr7   r8   pathexistsremover9   )r:   rR   required_fieldsr-   rI   
deploy_env	file_name
tts_engineaudio_iofr0   r>   r;   s               @r&   tts_apirj   G   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                         }|j	                  d      }|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-   whisperisozInvalid or missing file_pathsttr!   )r#   
transcriptzFailed to transcribe audio: r1   r2   r3   NzUnexpected error: )r4   r   r5   r   rW   rX   rZ   ra   isfiler
   transcribe_audior7   r8   r9   )r:   r;   rl   r-   rn   
stt_enginerp   r>   s           r&   stt_apirt      sl    IIKE$!G%<=>CCHH[)	(I.446hhuo y 9G%CDEsJJ	 J#44YDJ&#(  
  	&7Ax@"   	  UE")#a&2
   	sM   $D# A1D# .6C% %	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)r4   print)r:   fnNamedurations      r&   r7   r7      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/-rN   r   T)rB   r;   	overwritezhttps://AZURE_STORAGE_ACCOUNTz.blob.core.windows.net/r   zAzure upload failed: N)rZ   getenvr4   strftimer   from_connection_stringget_container_clientr^   upload_blobr8   r9   )rh   rB   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 errorr3   r$   )(rv   r   r   jsonr   r   errorsbase64	b64decodeimagecv2imdecodenp
frombufferuint8IMREAD_COLOR
ValueErrorr8   
proctoringanalyzeFramer   r   analyze
isinstancelistlenfuseEmotions	traceback	print_excdescribeHeadPoseyawpitchrollr   nowr   	isoformatr   dictr9   )requestDatar>   	imageDataframevisionResultsheadPoseDatadominantEmotionanalysisemotionsheadOrientationReadableistTimer0   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)   r3   )
r   r5   rW   r   match_facesr   r8   r   r   r9   )r;   id_image_b64
selfie_b64r=   r>   s        r&   verify_identityr   9  s    /!xx
+XXh'
''jAv /Q()3../s   AA 	B"+BBBz/api/proctor/attire_checkc                      	 t         j                  j                  d      } t        |       }t	        d|i      S # t
        $ r"}t	        dt        |      i      dfcY d }~S d }~ww xY w)Nr   r=   r)   r3   )r   r   rW   r   r   r8   r9   )	image_b64r=   r>   s      r&   handle_attire_checkr   H  s^    /LL$$W-	i(&)** /Q()3../s   69 	A$AA$A$z/api/extract-pdfc                     	 t         j                  j                  d      } | st        ddi      dfS t	               }|j                  |       }t        d|i      S # t        $ r"}t        dt        |      i      dfcY d }~S d }~ww xY w)Nra   r)   zPDF path is requiredr+   r=   r3   )r   argsrW   r   r   extract_textr8   r9   )pdf_path	extractorr=   r>   s       r&   
pdfextractr   R  s    
/<<##F+G%;<=sBB%'	''1&)** /Q()3../s"   /A 'A 	B#B :B B)<r4   rZ   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   services.proctor.attire_checkr   services.extractorr   __name__r   router'   r?   rj   rt   r7   r   r   r   r   r   r   r$   r%   r&   <module>r      s    	 E E       0 '   * * / !   V V 3 6 0	8X	&cE6?+ , j6(+" ,"J j6(+F ,FP j6(+/ ,/b':T L
$vh7<S 8<S| ,vh?/ @/ )F8</ =/  5'2/ 3/r%   