o
    Wh6                  	   @   s   d Z ddlmZmZmZmZmZ z0ddlZer"dej	ddv s"J ed du s*J ddl
a
et
d	s5J dd
lmZ edZW n eefyM   da
Y nw dedefddZdd Zdd Zdd Zdd Zt
rreeeedZdS i ZdS )az  
MLflow Logging for Ultralytics YOLO.

This module enables MLflow logging for Ultralytics YOLO. It logs metrics, parameters, and model artifacts.
For setting up, a tracking URI should be specified. The logging can be customized using environment variables.

Commands:
    1. To set a project name:
        `export MLFLOW_EXPERIMENT_NAME=<your_experiment_name>` or use the project=<project> argument

    2. To set a run name:
        `export MLFLOW_RUN=<your_run_name>` or use the name=<name> argument

    3. To start a local MLflow server:
        mlflow server --backend-store-uri runs/mlflow
       It will by default start a local server at http://127.0.0.1:5000.
       To specify a different URI, set the MLFLOW_TRACKING_URI environment variable.

    4. To kill all running MLflow server instances:
        ps aux | grep 'mlflow' | grep -v 'grep' | awk '{print $2}' | xargs kill -9
    )LOGGERRUNS_DIRSETTINGSTESTS_RUNNINGcolorstrNtest_mlflowPYTEST_CURRENT_TEST mlflowT__version__)PathzMLflow: xreturnc                 C   s   dd |   D S )zQSanitize dictionary keys by removing parentheses and converting values to floats.c                 S   s*   i | ]\}}| d d ddt|qS )(r	   ))replacefloat).0kv r   V/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/utils/callbacks/mlflow.py
<dictcomp>,   s   * z!sanitize_dict.<locals>.<dictcomp>)items)r   r   r   r   sanitize_dict*   s   r   c              
   C   s:  t jdpttd }tt d|  t	| t jdp&| j
jp&d}t jdp0| j
j}t| t  z=t pDtj|d}tt d|jj d	|  t| rett d
| d tt d tt| j
 W dS  ty } ztt d|  tt d W Y d}~dS d}~ww )a  
    Log training parameters to MLflow at the end of the pretraining routine.

    This function sets up MLflow logging based on environment variables and trainer arguments. It sets the tracking URI,
    experiment name, and run name, then starts the MLflow run if not already active. It finally logs the parameters
    from the trainer.

    Args:
        trainer (ultralytics.engine.trainer.BaseTrainer): The training object with arguments and parameters to log.

    Global:
        mlflow: The imported mlflow module to use for logging.

    Environment Variables:
        MLFLOW_TRACKING_URI: The URI for MLflow tracking. If not set, defaults to 'runs/mlflow'.
        MLFLOW_EXPERIMENT_NAME: The name of the MLflow experiment. If not set, defaults to trainer.args.project.
        MLFLOW_RUN: The name of the MLflow run. If not set, defaults to trainer.args.name.
        MLFLOW_KEEP_RUN_ACTIVE: Boolean indicating whether to keep the MLflow run active after the end of training.
    MLFLOW_TRACKING_URIr
   z tracking uri: MLFLOW_EXPERIMENT_NAMEz/Shared/Ultralytics
MLFLOW_RUN)run_namezlogging run_id(z) to zFview at http://127.0.0.1:5000 with 'mlflow server --backend-store-uri ')disable with 'yolo settings mlflow=False'zFailed to initialize: zNot tracking this runN)osenvirongetstrr   r   debugPREFIXr
   set_tracking_uriargsprojectnameset_experimentautolog
active_run	start_runinforun_idr   is_dir
log_paramsdict	Exceptionwarning)traineruriexperiment_namer   r-   er   r   r   on_pretrain_routine_end/   s&   

r:   c                 C   s:   t rt ji t| jt| j| jdd| jd dS dS )z>Log training metrics at the end of each train epoch to MLflow.train)prefixmetricsstepN)r
   log_metricsr   lrlabel_loss_itemstlossepochr6   r   r   r   on_train_epoch_end[   s   
rF   c                 C   s"   t rt jt| j| jd dS dS )z<Log training metrics at the end of each fit epoch to MLflow.r=   N)r
   r@   r   r>   rD   rE   r   r   r   on_fit_epoch_endg   s   rG   c                 C   s   t sdS t t| jj | jdD ]}|jdv r!t t| qtj	
dd dk}|r8tt d nt   tt d tt d	t   d
t d dS )z/Log model artifacts at the end of the training.N*>   .pt.csv.jpg.png.yamlMLFLOW_KEEP_RUN_ACTIVEFalsetruezCmlflow run still alive, remember to close it using mlflow.end_run()zmlflow run endedzresults logged to 
r    )r
   log_artifactr$   bestparentsave_dirglobsuffixr!   r"   r#   lowerr   r/   r&   end_runr%   get_tracking_uri)r6   fkeep_run_activer   r   r   on_train_endm   s   
r]   )r:   rF   rG   r]   )__doc__ultralytics.utilsr   r   r   r   r   r!   r"   r#   r
   hasattrpathlibr   r&   ImportErrorAssertionErrorr3   r   r:   rF   rG   r]   	callbacksr   r   r   r   <module>   s8   ,