
    &`iS1                         d dl Z d dl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 erd dlmZ d dlmZ  e j        e          Z G d d	          ZdS )
    N)deepcopy)TYPE_CHECKINGDictOptional)version)flatten_dict)RunMlflowClientc                      e Zd ZdZd Zd$dZ	 	 	 	 	 	 	 d%dee         dee         dee         d	ee         d
ee         dee         defdZ	de
de
fdZ	 	 	 d&dee         dee
         deddfdZ	 d'dee         dee
         ddfdZdedefdZd(dZd$de
dee         fdZd$de
dee         fdZd$d edee         fd!Zd'd"ee         fd#ZdS ))_MLflowLoggerUtilzUtil class for setting up and logging to MLflow.

    Use this util for any library that needs MLflow logging/tracking logic
    such as Ray Tune or Ray Train.
    c                 *    dd l }|| _        d | _        d S )Nr   )mlflow_mlflowexperiment_id)selfr   s     l/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/air/_internal/mlflow.py__init__z_MLflowLoggerUtil.__init__   s     !    Nc                     | j         }| j                            d           t          | j        |          }t	                      }|j                            |           || _         ||_         |S )Nr   )r   __dict__popr   r   update)r   memor   	dict_copycopied_objects        r   __deepcopy__z_MLflowLoggerUtil.__deepcopy__   sg    ,)$$$T]D11	)++%%i000 'r   Ttracking_uriregistry_urir   experiment_nametracking_tokenartifact_locationcreate_experiment_if_not_existsc                 d   |r|t           j        d<   | j                            |           | j                            |           ||nt           j                            d          }|Tddlm} 	 | j                            |           t          
                    d| d           || _        dS # |$ r Y nw xY w||nt           j                            d	          }|_| j                            |
          rDt          
                    d| d           | j                            |          j        | _        dS |rB|r@t          
                    d|            | j                            ||          | _        dS |rt          d| d          t          d| d| d          )a  
        Sets up MLflow.

        Sets the Mlflow tracking uri & token, and registry URI. Also sets
        the MLflow experiment that the logger should use, and possibly
        creates new experiment if it does not exist.

        Args:
            tracking_uri: The tracking URI for the MLflow tracking
                server.
            registry_uri: The registry URI for the MLflow model registry.
            experiment_id: The id of an already existing MLflow
                experiment to use for logging. If None is passed in
                here and the MFLOW_EXPERIMENT_ID is not set, or the
                experiment with this id does not exist,
                ``experiment_name`` will be used instead. This argument takes
                precedence over ``experiment_name`` if both are passed in.
            experiment_name: The experiment name to use for logging.
                If None is passed in here, the MLFLOW_EXPERIMENT_NAME environment
                variable is used to determine the experiment name.
                If the experiment with the name already exists with MLflow,
                it will be reused. If not, a new experiment will be created
                with the provided name if
                ``create_experiment_if_not_exists`` is set to True.
            artifact_location: The location to store run artifacts.
                If not provided, MLFlow picks an appropriate default.
                Ignored if experiment already exists.
            tracking_token: Tracking token used to authenticate with MLflow.
            create_experiment_if_not_exists: Whether to create an
                experiment with the provided name if it does not already
                exist. Defaults to True.

        Returns:
            Whether setup is successful.
        MLFLOW_TRACKING_TOKENNMLFLOW_EXPERIMENT_IDr   MlflowException)r   zExperiment with provided id z( exists. Setting that as the experiment.MLFLOW_EXPERIMENT_NAME)namezExperiment with provided name zBExisting experiment not found. Creating new experiment with name: )r*   r"   z,Experiment with the provided experiment_id: zZ does not exist and no experiment_name provided. At least one of these has to be provided.z or experiment_name: zV does not exist. Please create an MLflow experiment and provide either its id or name.)osenvironr   set_tracking_uriset_registry_urigetmlflow.exceptionsr(   get_experimentloggerdebugr   get_experiment_by_namecreate_experiment
ValueError)	r   r   r   r   r    r!   r"   r#   r(   s	            r   setup_mlflowz_MLflowLoggerUtil.setup_mlflow)   sz   Z  	A2@BJ./%%l333%%l333
 ( M 677 	
 $999999	++-+HHH>= > > >   &3""    * O 899 	
 &4<+N+N  ,O ,
 ,
& LL: : : :   "&!D!D" "  F  	> 	LL;)8; ;   "&!?!?$8I "@ " "D F* 	- - - -   * * *"* * *  s   2A B4 4B<;B<dict_to_logreturnc                     i }|                                 D ]_\  }}	 t          |          }|||<   # t          t          f$ r1 t                              d                    ||                     Y \w xY w|S )a  Parses provided dict to convert all values to float.

        MLflow can only log metrics that are floats. This does not apply to
        logging parameters or artifacts.

        Args:
            dict_to_log: The dictionary containing the metrics to log.

        Returns:
            A dictionary containing the metrics to log with all values being
                converted to floats, or skipped if not able to be converted.
        zMCannot log key {} with value {} since the value cannot be converted to float.)itemsfloatr6   	TypeErrorr2   r3   format)r   r8   new_dictkeyvalues        r   _parse_dictz_MLflowLoggerUtil._parse_dict   s     %++-- 		 		JCe %	*   ::@&e:L:L    s   2?A43A4Frun_nametags
set_activer	   c                 X   ddl }ddlm} |i }|r|                     ||          S |                                 }t          j        |j                  t          j        d          k    r|                    || j	        |          }n!|||<   |                    | j	        |          }|S )aM  Starts a new run and possibly sets it as the active run.

        Args:
            tags: Tags to set for the new run.
            set_active: Whether to set the new run as the active run.
                If an active run already exists, then that run is returned.

        Returns:
            The newly created MLflow run.
        r   N)MLFLOW_RUN_NAME)rC   rD   z1.30.0rC   r   rD   )r   rD   )
r   mlflow.utils.mlflow_tagsrG   _start_active_run_get_clientr   parse__version__
create_runr   )r   rC   rD   rE   r   rG   clientruns           r   	start_runz_MLflowLoggerUtil.start_run   s      	<<<<<<<D 	H))8$)GGG!!## =+,,h0G0GGG##!1C$ $  CC %-D!##$2D4#PPC
r   c                     | j                                         }|r|S | j                             || j        |          S )zStarts a run and sets it as the active run if one does not exist.

        If an active run already exists, then returns it.
        rH   )r   
active_runrQ   r   )r   rC   rD   rS   s       r   rJ   z#_MLflowLoggerUtil._start_active_run   sN     \,,..
 	|%%T-?d & 
 
 	
r   run_idc                 b    ddl m} 	 | j                            |           dS # |$ r Y dS w xY w)z)Check if run with the provided id exists.r   r'   )rT   TF)r0   r(   r   get_run)r   rT   r(   s      r   _run_existsz_MLflowLoggerUtil._run_exists   sY    555555	L   ///4 	 	 	55	s   % ..r   c                     | j                                         }| j                                         }ddlm}  |||          S )z@Returns an ml.tracking.MlflowClient instance to use for logging.r   r
   )r   r   )r   get_tracking_uriget_registry_urimlflow.trackingr   )r   r   r   r   s       r   rK   z_MLflowLoggerUtil._get_client   sO    |4466|4466000000|LQQQQr   params_to_logc                 N   t          |          }|r]|                     |          rH|                                 }|                                D ]\  }}|                    |||           dS |                                D ]!\  }}| j                            ||           "dS )a  Logs the provided parameters to the run specified by run_id.

        If no ``run_id`` is passed in, then logs to the current active run.
        If there is not active run, then creates a new run and sets it as
        the active run.

        Args:
            params_to_log: Dictionary of parameters to log.
            run_id (Optional[str]): The ID of the run to log to.
        )rT   r@   rA   )r@   rA   N)r   rW   rK   r;   	log_paramr   )r   r\   rT   rO   r@   rA   s         r   
log_paramsz_MLflowLoggerUtil.log_params  s     %]33 	=d&&v.. 	=%%''F+1133 F F
U  Cu EEEEF F ,1133 = =
U&&3e&<<<<= =r   metrics_to_logc                 |   t          |          }|                     |          }|r^|                     |          rI|                                 }|                                D ]\  }}|                    ||||           dS |                                D ]"\  }}| j                            |||           #dS )a|  Logs the provided metrics to the run specified by run_id.


        If no ``run_id`` is passed in, then logs to the current active run.
        If there is not active run, then creates a new run and sets it as
        the active run.

        Args:
            metrics_to_log: Dictionary of metrics to log.
            run_id (Optional[str]): The ID of the run to log to.
        )rT   r@   rA   step)r@   rA   rb   N)r   rB   rW   rK   r;   
log_metricr   )r   rb   r`   rT   rO   r@   rA   s          r   log_metricsz_MLflowLoggerUtil.log_metrics  s     &n55)).99 	Id&&v.. 	I%%''F,2244 R R
U!!SD!QQQQR R -2244 I I
U''Cu4'HHHHI Ir   dirc                     |rB|                      |          r-|                                 }|                    ||           dS | j                            |           dS )a  Saves directory as artifact to the run specified by run_id.

        If no ``run_id`` is passed in, then saves to the current active run.
        If there is not active run, then creates a new run and sets it as
        the active run.

        Args:
            dir: Path to directory containing the files to save.
            run_id (Optional[str]): The ID of the run to log to.
        )rT   	local_dir)rg   N)rW   rK   log_artifactsr   )r   re   rT   rO   s       r   save_artifactsz _MLflowLoggerUtil.save_artifacts/  sp      	6d&&v.. 	6%%''F  # >>>>>L&&&55555r   statusc                 D   |r|                      |          rm| j                                        r'| j                                        j        j        |k    s-|                                 }|                    ||           dS | j                            |           dS )a2  Terminates the run specified by run_id.

        If no ``run_id`` is passed in, then terminates the
        active run if one exists.

        Args:
            status (Optional[str]): The status to set when terminating the run.
            run_id (Optional[str]): The ID of the run to terminate.

        )rT   rj   )rj   N)rW   r   rS   inforT   rK   set_terminatedend_run)r   rj   rT   rO   s       r   rn   z_MLflowLoggerUtil.end_run@  s     	0  ((	0 ''))		0
 L++--29VCC %%''F!!!?????L   /////r   )N)NNNNNNT)NNF)NN)r9   r   )__name__
__module____qualname____doc__r   r   r   strboolr7   r   rB   rQ   rJ   rW   rK   r_   rd   ri   rn    r   r   r   r      su        " " "	 	 	 	 '+&*'+)-(,+/04s ssms sms  }	s
 "#s !s $C=s *.s s s sjt     : #'# 	$ $3-$ tn$ 	$
 
$ $ $ $N FJ
 
 
4<TN
	
 
 
 
# $    R R R R= = =hsm = = = =,I I Ihsm I I I I06 6# 6x} 6 6 6 6"0 0hsm 0 0 0 0 0 0r   r   )loggingr+   copyr   typingr   r   r   	packagingr   ray._private.dictr   mlflow.entitiesr	   r[   r   	getLoggerro   r2   r   ru   r   r   <module>r}      s     				       0 0 0 0 0 0 0 0 0 0       * * * * * * -######,,,,,,		8	$	$E0 E0 E0 E0 E0 E0 E0 E0 E0 E0r   