
    Ki!              
       0   d dl  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
mZmZmZ i ddd	d
dddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d,d-d.d/Z e
 ed0       ed1d1d23       eeeef      4      d5        Zd8d6Zy7)9    )*)evaluate_all_metrics)LLMChain)JSONResponse)HTTPException)retrystop_after_attemptwait_exponentialretry_if_exception_typezHeart Rate (BPM)
heart_ratezBreathing Ratebreathing_ratezOxygen Saturationoxygen_saturationzBlood Pressureblood_pressurezStress Levelstress_levelzHeart Variabilityheart_variabilityPRQprqActivityactivitySleepsleepEquilibriumequilibrium
Metabolism
metabolism
Relaxation
relaxationzCardiovascular Agecardiovascular_age
Hemoglobin
hemoglobinCholesterolcholesterolzA1C Riska1c_riskzCholesterol Riskcholesterol_risk	a1c_rangecholesterol_rangewellness_scoreatrial_fibrillationhba1ccardiovascular_bmi)z	A1C RangezCholesterol RangezWellness ScoreAtrial FibrillationHbA1cr+   r,   zCardiovascular BMI      
   )
multiplierminmax)stopwaitr   c                 V    t         t        z  t        z  }|j                  d| i      }|S )z(LLM call with automatic retry on failuredata)input)Promptllmparserinvoke)r6   runnable
llm_outputs      */var/www/welltra_ai_report_api/response.pycall_llm_with_retryr?   &   s,     |f$H~6J    c           	      B   	 t        | d      r| j                         n| }|j                         D ci c]  \  }}|	|| }}}t        |      }g }|j                         D ]  \  }|j	                  i       j	                  dd      }	t        fdt        j                         D        j                  dd      j                               }
|j                  |
 d| d|	 d	       d
k(  s|j                  d| d|	 d	        dj                  |      }t        |      }t        |dd       }|t        |dg       }g }i }|D ]R  }t        |dt        |            }
|||
<   |
j                  d      d   j                         j!                         }|||<   T |j                         D ]  \  }t        fdt        j                         D        d       }
|
s j                  dd      j                         }
|v r|   d   }	d
k(  r|}n|   d   }nd}	d
k(  r|nd}d}|
|v rt        ||
   dd      }nD|
j                  d      d   j                         j!                         }||v rt        ||   dd      }|s$|	dk(  s|	dk(  rd}n|	dk(  s|	dk(  rd}n
|	dk(  rd}nd}|}|j                  |
|	||d        |r\|j	                  d
      }|Id}d |v rt        |d    dd      }|s|d!k\  rd"}n|d#k\  rd$}n
|d%k\  rd&}nd'}d ||d(}|j                  |       |D ]  }|j	                  d      d k(  sd|v s|d= ! t#        d)d)d*d+|d,-      S c c}}w # t$        $ r9}dd l}|j)                          t+        d.|        t-        d/d/d0d1g d,2      d }~ww xY w)3NdictstatusNormalc              3   4   K   | ]  \  }}|k(  s|  y wN .0tkkeys      r>   	<genexpr>zresponse.<locals>.<genexpr>@        I1S!I   _ z: z
 (Status: )r'   zOverall Wellness Score: 
Datametricstitle(r   c              3   4   K   | ]  \  }}|k(  s|  y wrF   rG   rH   s      r>   rM   zresponse.<locals>.<genexpr>_   rN   rO   score    tipOptimalz_This state supports overall physical resilience, so continue with your current wellness habits.HighElevatedzaConsider a gentle adjustment to your daily routine to help bring this closer to a balanced range.Lowz]Prioritizing restorative habits and balanced nutrition can help support a more optimal level.zWMaintaining consistent daily habits will help support long-term stability in this area.)rV   rC   r\   rY   zOverall Wellness Score   zYYour overall wellness is strong. Maintain your current routines to preserve this balance.   u}   Your wellness is on track but has room to improve. Focus on one area—sleep, movement, or stress—to elevate your baseline.   z^Your body is showing signs of strain. Prioritize rest, hydration, and reduced intensity today.ziYour recovery is significantly impaired. Focus on immediate rest and minimizing physical and mental load.)rV   r\   rY      Tz!Get user scan report successfully)ResponseCodeStatusMessagerT   )status_codecontentzError in response function: i  Fz.Internal server error. Please try again later.)rh   detail)hasattrrB   itemsr   getnexttitle_to_keyreplacerV   appendjoinr?   getattrstrsplitstriplowerr   	Exception	traceback	print_excprintr   )r6   
well_score	data_dictrK   vfiltered_dataclinical_evaluationsllm_input_listvaluerC   rV   llm_input_stringllm_response_objmetrics_listformatted_datallm_metrics_mapmetricnorm_keyrY   r\   
norm_titledisplay_scorewellness_valoverall_entryentryery   rL   s                              @r>   responser   2   sn   U
#*4#8DIIKd	 +4//*;M$!Qq}AMM3MB '--/ 	]JC)--c26::8XNFI(:(:(<I3;;WZ\_K`KfKfKhiE!!UG2eWJvha"HI&&%%(@zRXQYYZ&[\	]  99^4 //?@ />"#3YCL  " 	/FFGS[9E%+OE"{{3'*00288:H(.OH%	/ (--/ 0	JCI(:(:(<I4PEC-335 **-c28<**!E05g>E!!$(8!8a C'oe4eR@ #[[-a0668>>@
0!/*"=ubIC X%9)<{Cv%:)=}Cu_yCsC "M!! &	# W0	f (,,-=>L'+>!/2J"KUTVWC #q(y%* ^%*~ J 6)!
 %%m4 $ 	$Eyy!%==(eBS(O	$  #>&	
 	
q ND  
,QC01 #K	
 		

sA   1M 
MMB,M 1IM :M ?M M 	N%4NNN)F)utilsutils.clinical_rangesr   langchain.chainsr   fastapi.responsesr   fastapir   tenacityr   r	   r
   r   ro   
ValueErrorKeyErrorrx   r?   r   rG   r@   r>   <module>r      sP    6 % * ! Y Y& , &	
 N , 
5 
 W = , , . , =  
!" *#$ ,&00.38 	A		QA2	6
!:x"C
D

V
r@   