
    Oj,                        S r SSKJr  SSKrSSKrSSKJr  SSKJr  SSKJ	r	  SSK
Jr  SSKJr  SS	KJrJr  SS
KJrJrJr   " S S5      rg)z;
service.py

LeafDoctor AI

Business Service Layer

Part 1
    )annotationsN)datetime)Path)func)Session)settings)GeminiClientDiagnosisResult)DiagnosisHistoryProtectionLabelTreatmentMappingc                  "   \ rS rSrSS jr    SS jr    SS jr    SS jr      SS jr          SS jr	\
    SS j5       r    SS	 jr            SS
 jr    SS jr S   SS jjr    SS jrS rSS jrSrg) DiagnosisService   c                D    Xl         [        R                  " 5       U l        g N)dbr	   instancegemini)selfr   s     '/var/www/html/leaf-doctor-v1/service.py__init__DiagnosisService.__init__    s    "++-    c                    [         R                  " 5       R                  S5      n[        R                  " 5       R
                  S S nU SU U 3$ )Nz%Y%m%d%H%M%S   _)r   nowstrftimeuuiduuid4hex)r   	extension	timestamp	random_ids       r   _generate_filename#DiagnosisService._generate_filename*   sT    
 LLN++
	 JJL$$Ra(	 kkk	
r   c                :   [        U5      nUR                  5       (       d  [        U5      eUR                  R	                  5       nU R                  U5      n[        R                  U-  nUR                  R                  SSS9  [        R                  " UU5        U$ )NT)parentsexist_ok)r   existsFileNotFoundErrorsuffixlowerr&   r   upload_pathparentmkdirshutilcopy2)r   
image_pathr#   filenamedestinations        r   
save_imageDiagnosisService.save_image;   s    
 *%
  ""#  %%++-	**

    	
 	   	! 	

 		

 r   c                   U R                   R                  [        5      R                  [        R
                  " [        R                  5      UR                  5       :H  5      R                  5       nUc  [        SU S35      eU$ )NzUnknown label '')	r   queryr   filterr   r.   label_name_enfirst
ValueError)r   labelobjs      r   	get_labelDiagnosisService.get_labelc   s{     GGMM V

#11[[]#
 UW 	 ;!%*  
r   c                    U R                   R                  [        5      R                  [        R                  U:H  [
        R                  " [        R                  5      UR                  5       :H  5      $ r   )r   r;   r   r<   class_idr   r.   crop_en)r   rE   crops      r   get_treatmentsDiagnosisService.get_treatments   sY     GGMM  V ))X5

$,,ZZ\"	
	
r   c                   [        UUR                  UR                  UUR                  U(       a  UR                  OS UR
                  UR                  S9n U R                  R                  U5        U R                  R                  5         U R                  R                  U5        U$ ! [         a    U R                  R                  5         e f = f)N)r4   crop_detectedpredicted_labelrE   
confidencetreatment_idgemini_modelraw_response)r   rG   r@   rM   idmodelrP   r   addcommitrefresh	Exceptionrollback)r   r4   	diagnosis	treatmentrE   historys         r   save_historyDiagnosisService.save_history   s     #!#..%OO ++   #"//)
0	GGKK GGNNGGOOG$N 	GG		s   AB) )&Cc                >    U (       d  g U (       d  g [        U S S9S   $ )Nc                T    U R                   S L U R                  S L U R                  S L 4$ r   )chemicaldosagesms_en)xs    r   <lambda>1DiagnosisService.best_treatment.<locals>.<lambda>   s+    

d"D D r   )keyr   )sorted)
treatmentss    r   best_treatmentDiagnosisService.best_treatment   s/    
 
  	r   c                j   U R                  U5      nU R                  R                  U5      nU R                  UR                  5      nU R                  UR                  UR                  S9nU R                  U5      nU R                  [        U5      UUUR                  S9nU R                  UUUUUS9$ )N)rE   rG   )r4   rX   rY   rE   )rZ   rX   r@   rg   stored_image)r7   r   diagnoserB   r@   rH   rE   rG   rh   r[   str_build_response)r   r4   rk   rX   r@   rg   rY   rZ   s           r   rl   DiagnosisService.diagnose   s     
 KK((
	 OO
 ((^^ ) 


 ''
	 ##<(^^	 $ 
 ##!% $ 
 	
r   c                F   / nU H  nUR                  UR                  UR                  UR                  S.UR                  UR
                  S.UR                  UR                  UR                  UR                  UR                  S.S.5        M     SUR                  [        U5      UR                  UR                  UR                  U(       a  US   R                  OS S.UR                  UR                   S.UR"                  UR$                  S.UR&                  S.US.$ )N)enbn)rQ   rG   problem_typer_   chemical_typer`   smsTr   )rE   rM   rG   problemcategoryrO   )success
history_idimagerX   recommendations)appendrQ   rF   crop_bnproblem_type_enproblem_type_bnr_   rt   r`   ra   sms_bnrm   rE   rM   rG   r=   label_name_bnprimary_category_enprimary_category_bnrR   )r   rZ   rX   r@   rg   rk   r{   items           r   rn    DiagnosisService._build_response&  s)    D"" '' #ll"ll #22"22%
 !%%)%7%7"kk #kk"kk) F !**& "NN'22 $.. & #1--!
  ----	  3333	 !*E$L  /]0
 0	
r   c                    U R                   R                  [        5      R                  [        R                  U:H  5      R                  5       $ r   )r   r;   r   r<   rQ   r>   )r   ry   s     r   get_historyDiagnosisService.get_history  s?     GGMM  V ##z1 UW	
r   c                    U R                   R                  [        5      R                  [        R                  R                  5       5      R                  U5      R                  5       $ r   )r   r;   r   order_by
created_atdesclimitall)r   r   s     r   get_historiesDiagnosisService.get_histories  sL     GGMM  X ++002 U5\SU		
r   c                .   U R                  U5      nUc  g [        UR                  5      nUR                  5       (       a  UR	                  5         U R                  R                  U5        U R                  R                  5         g! [
         a     NBf = f)NFT)	r   r   r4   r+   unlinkrV   r   deleterT   )r   ry   rZ   r4   s       r   delete_historyDiagnosisService.delete_history  s    
 ""
 ?	""J   ""!!# 	w  		s   :B 
BBc                   SnSn U R                   R                  S5         U R                  R	                  5         US:H  =(       a    US:H  UUU R                  R
                  S.$ ! [         a    Sn NSf = f! [         a    Sn NJf = f)N	connectedzSELECT 1disconnected)rx   databaser   rR   )r   executerV   r   test_connectionrR   )r   r   r   s      r   healthDiagnosisService.health  s    	&GGOOJ'	$KK'')  ;. &+% [[&&
 	
  	&%H	&  	$#F	$s"   A& A8 &A54A58BBc                   U R                   R                  [        5      R                  5       nU R                   R                  [        5      R                  5       nU R                   R                  [
        5      R                  5       nUUUS.$ )N)labelsrg   diagnosis_history)r   r;   r   countr   r   )r   total_labelstotal_treatmentstotal_diagnosiss       r   
statisticsDiagnosisService.statistics  s     GGMM UW	 	 GGMM  UW	 	 GGMM  UW	 	 #*!0
 	
r   )r   r   N)r   r   )r#   rm   returnrm   )r4   
str | Pathr   r   )r@   rm   r   r   )rE   intrG   rm   r   list[TreatmentMapping])
r4   rm   rX   r
   rY   TreatmentMapping | NonerE   r   r   r   )rg   r   r   r   )r4   r   r   dict)rZ   r   rX   r
   r@   r   rg   r   rk   r   r   r   )ry   r   r   zDiagnosisHistory | None)2   )r   r   r   zlist[DiagnosisHistory])ry   r   r   bool)r   r   )__name__
__module____qualname____firstlineno__r   r&   r7   rB   rH   r[   staticmethodrh   rl   rn   r   r   r   r   r   __static_attributes__ r   r   r   r      s}   .

 

""" 
"P 
8

 
 
 	
,.. #. +	.
 . 
.f *	  0?
?
 
?
J\
!\
 #\
 	\

 +\
 \
 
\
F

 
!
" 

 
 
  
H!
N
r   r   )__doc__
__future__r   r2   r    r   pathlibr   
sqlalchemyr   sqlalchemy.ormr   configr   r   r	   r
   modelsr   r   r   r   r   r   r   <module>r      s=    #      "  0 t
 t
r   