
    @i.                         d Z ddlZddlZddlmZmZmZmZ ddlZ	ddl
mZ ddlmZ ddlmZ  ej                   e      Z G d d      Zy)	z/Service layer for encapsulating business logic.    N)DictAnyOptionalList)PipelineManager)MemoryStore)PatternEmbedderc                   d   e Zd ZdZdefdZddedee   de	ee
f   fdZd	ed
edede	ee
f   fdZ	 	 ddedededede	ee
f   f
dZde	ee
f   fdZde	ee
f   de	ee
f   fdZde	ee
f   de	ee
f   fdZdedefdZdedede	ee
f   fdZdede	eee   f   de	ee
f   fdZdede	ee
f   fdZy)
WebServicezService layer for web API.managerc                 N    || _         t               | _        t               | _        y)zeInitialize web service.
        
        Args:
            manager: PipelineManager instance
        N)r   r   memoryr	   embedder)selfr   s     C   /home/ubuntu/codebase/yexijia/保研/colocation_mvp/web/services.py__init__zWebService.__init__   s     !m')    Nqueryiteration_roundsreturnc                     	 | j                   j                  ||      }| j                  |      }d|v r|j                  d      |d<   |S # t        $ r }t
        j                  d| d        d}~ww xY w)a  Execute a query and return results.
        
        Args:
            query: Natural language query string
            iteration_rounds: Optional number of iteration rounds (Stage4)
            
        Returns:
            Dictionary containing query results
        )r   extracted_parametersparamszError processing query: Texc_infoN)r   process_query_clean_resultpop	Exceptionloggererrorr   r   r   resultcleaned_resultes         r   	run_queryzWebService.run_query   s    
	\\//HX/YF!//7N%7+9+=+=>T+Ux(!! 	LL3A37$LG	s   AA
 
	A3A..A3
pattern_idpatternfeedbackc                    	 | j                   j                  }| j                  j                  |      }|dk(  r| j                  j                  ||       n0|dk(  r| j                  j                  ||       nt        d|       | j                  j                  |      }t        |j                  dg             }t        |j                  dg             }dd| ||dS # t        $ r }	t        j                  d|	 d	        d
}	~	ww xY w)a,  Add user feedback for a pattern.
        
        Args:
            pattern_id: Pattern identifier
            pattern: Pattern content (list of feature types)
            feedback: "positive" or "negative"
            
        Returns:
            Dictionary with feedback status and counts
        positivenegativezInvalid feedback type: okzFeedback saved: )statusmessagepositive_countnegative_countzError adding feedback: Tr   N)r   stage3_user_idr   encode_patternr   add_positiveadd_negative
ValueErrorget_user_profilelengetr   r    r!   )
r   r'   r(   r)   user_idpattern_vecuser_profiler0   r1   r%   s
             r   add_feedbackzWebService.add_feedback2   s	   	ll11G --66w?K :%((+>Z'((+> #:8*!EFF  ;;77@L !1!1*b!ABN !1!1*b!ABN -hZ8"0"0	   	LL21#6LF	s   CC   	D	)DD	epochslearning_rate
batch_sizemarginc                    	 | j                   j                  sddg ddS | j                   j                  sddg ddS | j                   j                  ddg ddS ddlm} |j                  | j                   j                  j                  j                         |      | j                   j                  _	        | j                   j                  j                  ||| j                   j                  	      }| j                  j                  | j                   j                        }|r<t        |j!                  d
g             }t        |j!                  dg             }	||	z   }
nd}
| j                   j#                  |
||       t%        | j                   d      rTt&        j(                  j+                  | j                   j                        r 	 ddlm} ddl}d}t3        |dd      5 }|j5                  |      }ddd       | j6                  j                  j9                         }j!                  di       j!                  dd      } |||      | j                   _        ddl}|j?                  | j                   j                  d      }| j                   j:                  jA                  |d          | j                   j:                  jC                          tD        jG                  d       dd|j!                  dg       |dS # 1 sw Y   xY w# tH        $ r"}tD        jK                  d|        Y d}~Jd}~ww xY w# tH        $ r4}tD        jM                  d| d        dtO        |      g ddcY d}~S d}~ww xY w)!a?  Run preference model training.
        
        Args:
            epochs: Number of training epochs
            learning_rate: Learning rate
            batch_size: Batch size
            margin: Margin for triplet loss
            
        Returns:
            Dictionary with training status and loss history
        r!   zStage3 is not enabledr   )r.   r/   loss_historyr>   z#Contrastive learning is not enabledNzTrainer is not initialized)lr)r>   r@   	save_pathr+   r,   stage3_model_path)PreferenceEncoderzconfig/config.yamlrutf-8encodingstage3
hidden_dim   )	input_dimrM   cpu)map_locationmodel_state_dictz(Preference model reloaded after trainingz#Failed to reload preference model: r-   zTraining completed successfullylosszError during training: Tr   )(r   stage3_enabledstage3_use_contrastivetrainertorch.optimoptimAdammodel
parameters	optimizertrainrF   r   r7   r2   r8   r9   _save_training_historyhasattrospathexistsembedding.encoderrG   yamlopen	safe_loadr    get_sentence_embedding_dimensionpreference_modeltorchloadload_state_dictevalr    infor   warningr!   str)r   r>   r?   r@   rA   rX   historyr<   r0   r1   total_feedbackrG   rd   config_pathfconfigrO   rM   ri   
checkpointr%   s                        r   run_trainingzWebService.run_trainingZ   s   Y	<<..%6$&	  <<66%D$&	  ||##+%;$&	  (-2ZZ$$**557  .8 .DLL  * ll**00%,,88 1 G  ;;778S8STL!$\%5%5j"%E!F!$\%5%5j"%E!F!/.!@!" LL//P t||%89bggnnT\\MkMk>lNC"6Kk3AQ!%!2 B $ 3 3 T T VI!'Hb!9!=!=lC!PJ4E"+#-5DLL1
 !!&DLL,J,JY^!_JLL11AA*M_B`aLL11668KK JK
 < 'FB 7 	 # BA ! NNN%H#LMMN  	LL21#6LF!q6 "	 	sq   L< L< L< E1L< L %L7C3L *L< LL 	L9L4/L< 4L99L< <	M9)M4.M94M9c                 ,   ddl }ddl}d}|j                  j                  |      sdg iS 	 t	        |dd      5 }|j                  |      }ddd       |S # 1 sw Y   S xY w# t        $ r(}t        j                  d| d	
       dg icY d}~S d}~ww xY w)zuGet training history from logs.
        
        Returns:
            Dictionary containing training history
        r   Nzlogs/training_history.json	trainingsrH   rI   rJ   z Error reading training history: Tr   )	jsonr`   ra   rb   re   rj   r   r    r!   )r   ry   r`   history_pathrs   datar%   s          r   get_training_historyzWebService.get_training_history   s     	3ww~~l+$$	%lC':ayy| ;K ;K 	%LL;A3?$LO$$	%s:   A" A	A" AA" A" "	B+BBBr#   c                 4   i }|j                         D ]  \  }}t        |t        j                        r|j	                         ||<   4t        |t
              r| j                  |      ||<   Yt        |t              r| j                  |      ||<   ~|||<    |S )zClean result dictionary, converting numpy arrays to lists.
        
        Args:
            result: Raw result dictionary
            
        Returns:
            Cleaned result dictionary
        	items
isinstancenpndarraytolistdict_clean_dictlist_clean_list)r   r#   cleanedkeyvalues        r   r   zWebService._clean_result   s      ,,.JC%,$||~E4(#//6E4(#//6$ ) r   dc                 4   i }|j                         D ]  \  }}t        |t        j                        r|j	                         ||<   4t        |t
              r| j                  |      ||<   Yt        |t              r| j                  |      ||<   ~|||<    |S )zRecursively clean dictionary.r~   )r   r   r   kvs        r   r   zWebService._clean_dict   s    GGIDAq!RZZ(XXZ
At$!--a0
At$!--a0

  r   lc                 r   g }|D ]  }t        |t        j                        r |j                  |j	                                =t        |t
              r!|j                  | j                  |             nt        |t              r!|j                  | j                  |             |j                  |        |S )zRecursively clean list.)	r   r   r   appendr   r   r   r   r   )r   r   r   items       r   r   zWebService._clean_list   s    D$

+t{{}-D$'t//56D$'t//56t$  r   c                     	 | j                   j                  ||      }| j                  |      }|S # t        $ r }t        j                  d| d        d}~ww xY w)a
  Start an interactive iteration session (Stage4).
        
        Args:
            query: User query
            iteration_rounds: Number of iteration rounds
            
        Returns:
            Dictionary containing session_id and first round results
        zError starting iteration: Tr   N)r   start_iterationr   r   r    r!   r"   s         r   r   zWebService.start_iteration  s_    	\\11%9IJF!//7N!! 	LL5aS9DLI	   .1 	AAA
session_idc                     	 | j                   j                  ||      }| j                  |      }|S # t        $ r }t        j                  d| d        d}~ww xY w)a6  Process feedback, train model, and return next iteration round (Stage4).
        
        Args:
            session_id: Iteration session ID
            feedback: Dictionary with 'positive' and 'negative' pattern lists
            
        Returns:
            Dictionary containing next round results
        zError in next iteration: Tr   N)r   next_iterationr   r   r    r!   )r   r   r)   r#   r$   r%   s         r   r   zWebService.next_iteration  s^    	\\00XFF!//7N!! 	LL4QC84LH	r   c                     	 | j                   j                  |      }| j                  |      }|S # t        $ r }t        j                  d| d        d}~ww xY w)zGet final results after all iterations (Stage4).
        
        Args:
            session_id: Iteration session ID
            
        Returns:
            Dictionary containing final results and explanation
        zError finalizing iteration: Tr   N)r   finalize_iterationr   r   r    r!   )r   r   r#   r$   r%   s        r   r   zWebService.finalize_iteration,  s\    	\\44Z@F!//7N!! 	LL7s;dLK	s   -0 	AAA)N)
   gMbP?    g333333?)__name__
__module____qualname____doc__r   r   ro   r   intr   r   r&   r   r=   floatrv   r|   r   r   r   r   r   r   r    r   r   r   r      s   $* *s hsm tTWY\T\~ ,&s &T &S &TRUWZRZ^ &P EJ:=f3 fE f #f27fBFsCx.fP%d38n %*DcN tCH~ *T#s(^ S#X T d S C DcN $ S$s)^8L QUVY[^V^Q_ $S T#s(^ r   r   )r   loggingr`   typingr   r   r   r   numpyr   controller.managerr   memory.storer   learning.embedderr	   	getLoggerr   r    r   r   r   r   <module>r      s>    5  	 , ,  . $ -			8	$l lr   