
    55i=!                     >   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Zd dlZd dlZd dlZd dlmZmZ  ej        d          Z e            Ze                    ed	gd	gd	g
           e                    d e	d          d           e                    d          d             Ze                    d           edd           ed           ed          fdededefd            ZdZ G d de          Z  G d de          Z! G d  d!e          Z"	 	 d/d"eded#ed$ed%ed&efd'Z#e                    d(          d)e fd*            Z$e                    d+          d)e!fd,            Z%e                    d-          d)e"fd.            Z&dS )0    )FastAPI
UploadFileFileHTTPExceptionQueryFileResponse)StaticFiles)CORSMiddleware)	BaseModelN)clean_live_textclientzvrs-app*)allow_originsallow_methodsallow_headersz/staticstatic)	directory)name/c                  $   K   t          d          S )zServe the main HTML page.zstatic/index.htmlr         /var/www/html/pixcura-vrs/app.pyrootr      s       +,,,r   z/api/transcribesmartz^(direct|smart)$)regex	radiology.mode	specialtyfilec                   K   t          j        dd          5 }|                                 d{V }|                    |           |j        }ddd           n# 1 swxY w Y   	 	 t          |d          5 }t          j        j        	                    d|dd	          }ddd           n# 1 swxY w Y   nA# t          $ r4}t                              d
|           t          dd|           d}~ww xY wt          |t                    r|nt!          |dd          }	|	                                st          dd          d}
d}| dk    rW	 t%          |	|d          }
nC# t          $ r6}t          |          }d}
t                              d|           Y d}~nd}~ww xY w| |	|
|d	 t'          j        |           S # t*          $ r Y S w xY w# 	 t'          j        |           w # t*          $ r Y w w xY wxY w)z
    mode = "direct"  -> return raw transcript only
    mode = "smart"   -> try to return cleaned transcript using clean_live_text()
                        (falls back to raw if cleaner fails)
    Fz.webm)deletesuffixNrbzgpt-4o-mini-transcribetexten)modelr!   response_formatlanguagezOpenAI transcription error: %si  zTranscription error: )status_codedetail i  zNo text recognized from audio.r   )raw_transcriptr    r*   zclean_live_text failed: %s)r   rawcleanedclean_error)tempfileNamedTemporaryFilereadwriter   openr   audiotranscriptionscreate	Exceptionlogger	exceptionr   
isinstancestrgetattrstripr   osremoveOSError)r   r    r!   tmpdatatmp_pathftranscriptioneraw_textr0   r1   s               r   
transcriberK   %   s      
	$E'	B	B	B cYY[[      		$8              
9	h%%  & ; B B2$*!	 !C ! !                	 	 	=qAAA2q22   	 (s;; 4MM33 	
 ~~ 	7   
  7??	B)#+'!  
  B B B!!ff  !=qAAAAAAAAB &	
 
	Ih 	 	 	D		Ih 	 	 	D	s   7AA #A )B: 9)B."B: .B22B: 5B26B: 9G :
C8/C33C88AG E& %G &
F&0,F!G !F&&	G 0G
GGG<G,+G<,
G96G<8G99G<a  
You are an AI assistant specialized in healthcare documentation for a Voice Reporting System (VRS).

Your role depends on the task:

1. REVIEW (task="review"):
   - Clean and polish the provided medical text
   - Fix grammar, punctuation, and capitalization
   - Ensure proper medical terminology and formatting
   - Preserve ALL medical meaning, findings, diagnoses, and numbers
   - Do NOT add or remove medical information
   - Maintain the original structure and flow

2. MODIFY (task="modify"):
   - Apply the user's natural language instruction to modify the existing text
   - The instruction will describe what change to make (e.g., "add that the patient has diabetes",
     "remove the mention of chest pain", "change the date to January 15th")
   - Make the requested change while preserving the rest of the text
   - Ensure the modified text remains grammatically correct and medically accurate

3. SMART_REPORT (task="smart_report"):
   - Convert the transcription into a structured, professional medical report
   - Format according to the specified specialty's conventions
   - Include appropriate sections (e.g., History, Findings, Impression for radiology)
   - Use proper medical terminology and formatting
   - If a signature is provided, append it at the end
   - Ensure the report is ready for clinical use

Always respect medical accuracy and never invent or remove medical information.
c                   .    e Zd ZU eed<   eed<   eed<   dS )ReviewRequestr&   r    targetN__name__
__module____qualname__r>   __annotations__r   r   r   rM   rM      s+         
IIINNNKKKKKr   rM   c                   8    e Zd ZU eed<   eed<   eed<   eed<   dS )ModifyRequestr&   instructionr    rN   NrO   r   r   r   rU   rU      s7         
IIINNNKKKKKr   rU   c                   8    e Zd ZU eed<   eed<   dZedz  ed<   dS )ReportRequestr&   r    N	signature)rP   rQ   rR   r>   rS   rY   r   r   r   rX   rX      s8         
IIINNN IsTz     r   rX   task
input_textrV   rY   returnc                    	 | dk    rd||d}n| dk    rd|||d}n| dk    rd|||d}n|S t           j        j                            ddt          d	d
t          j        |          d	gdd          }|j        d         j        j	        
                                }| dk    r0|r.|
                                r|d|
                                 z  }|S # t          $ r(}t                              d| |           |cY d}~S d}~ww xY w)zACall OpenAI with the appropriate task and return the output text.reviewrZ   r    r[   modifyrZ   r    r[   rV   smart_reportrZ   r    r[   rY   zgpt-4o-minisystem)rolecontentuserg333333?i  )r(   messagestemperature
max_tokensr   z

zAI task error (%s): %sN)r   chatcompletionsr9   AI_SYSTEM_PROMPTjsondumpschoicesmessagerf   r@   r:   r;   r<   )	rZ   r    r[   rV   rY   user_contentresponseoutput_textrI   s	            r   call_ai_taskru      s   28 &( LL X &(*	 LL ^##&&(&	 LL  ;*11!.>??DJ|,D,DEE  2 
 
 &q)19??AA >!!i!IOO4E4E!5)//"3"3555K   14;;;s#   *C B'C 
DD<DDz/api/reviewrequestc                    K   	 t          d| j        | j                  }d|iS # t          $ r.}t                              d|           d| j        icY d}~S d}~ww xY w)zReview and clean medical text.r^   r_   rt   zReview endpoint error: %sN)ru   r    r&   r:   r;   r<   rv   rt   rI   s      r   r^   r^      s      
-"'|
 
 

 {++ - - -4a888w|,,,,,,,-s   $ 
A#AAAz/api/modifyc                    K   	 t          d| j        | j        | j                  }d|iS # t          $ r.}t
                              d|           d| j        icY d}~S d}~ww xY w)z'Modify text based on voice instruction.r`   ra   rt   zModify endpoint error: %sN)ru   r    r&   rV   r:   r;   r<   rx   s      r   r`   r`      s      -"'|+	
 
 
 {++ - - -4a888w|,,,,,,,-   %* 
A"#AA"A"z/api/reportc                    K   	 t          d| j        | j        | j                  }d|iS # t          $ r.}t
                              d|           d| j        icY d}~S d}~ww xY w)z4Generate structured smart report from transcription.rb   rc   rt   zReport endpoint error: %sN)ru   r    r&   rY   r:   r;   r<   rx   s      r   generate_reportr|   
  s      -"'|'	
 
 
 {++ - - -4a888w|,,,,,,,-rz   )NN)'fastapir   r   r   r   r   fastapi.responsesr	   fastapi.staticfilesr
   fastapi.middleware.corsr   pydanticr   r2   rA   loggingrn   live_mode_exampler   r   	getLoggerr;   appadd_middlewaremountgetr   postr>   rK   rm   rM   rU   rX   ru   r^   r`   r|   r   r   r   <module>r      sW   C C C C C C C C C C C C C C * * * * * * + + + + + + 2 2 2 2 2 2        				   5 5 5 5 5 5 5 5 
	9	%	%gii   %%%	     		)[[84448	 D D D - - -
 
g%7888U;''tCyyJ J
JJ J J J Jd B    I       I   ! ! ! ! !I ! ! ! : :
:: : 	:
 : 	: : : :z --- - - - - --- - - - -  --= - - - - - -r   