o
    mi6                     @   s   d Z ddlmZ ddlmZ ddlmZmZ ddlm	Z	m
Z
 ddlZddlmZ G dd	 d	Zd
ee	e
f dee ddfddZd
ee	e
f ddfddZ			dd
ee	e
f dedededdf
ddZdS )zcatboost init.    )Path)SimpleNamespace)ListUnion)CatBoostClassifierCatBoostRegressorN)	telemetryc                   @   s2   e Zd ZdZddefddZdedefdd	Zd
S )WandbCallbackaV  `WandbCallback` automatically integrates CatBoost with wandb.

    Args:
        - metric_period: (int) if you are passing `metric_period` to your CatBoost model please pass the same value here (default=1).

    Passing `WandbCallback` to CatBoost will:
    - log training and validation metrics at every `metric_period`
    - log iteration at every `metric_period`

    Example:
        ```
        train_pool = Pool(train[features], label=train["label"], cat_features=cat_features)
        test_pool = Pool(test[features], label=test["label"], cat_features=cat_features)

        model = CatBoostRegressor(
            iterations=100,
            loss_function="Cox",
            eval_metric="Cox",
        )

        model.fit(
            train_pool,
            eval_set=test_pool,
            callbacks=[WandbCallback()],
        )
        ```
       metric_periodc                 C   sN   t jd u r
t dt }d|j_W d    n1 sw   Y  || _d S )Nz5You must call `wandb.init()` before `WandbCallback()`T)wandbrunErrorwb_telemetrycontextfeaturecatboost_wandb_callbackr   )selfr   tel r   a/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/integration/catboost/catboost.py__init__*   s   




zWandbCallback.__init__inforeturnc                 C   sr   |j | j dkr7|j D ]\}}| D ]\}}tj| d| |d idd qqtd| j |j i dS )Nr   -Fcommitziteration@metric-period-T)	iterationr   metricsitemsr   log)r   r   datametricmetric_namer!   r   r   r   after_iteration3   s   "zWandbCallback.after_iterationN)r
   )	__name__
__module____qualname____doc__intr   r   boolr%   r   r   r   r   r	      s    	r	   modelaliasesr   c                 C   sj   t jdu r
t ddt jj }tt jjd }| | t j|dd}|t	| t j
||d dS )z(Upload model checkpoint as W&B artifact.N<You must call `wandb.init()` before `_checkpoint_artifact()`model_r,   )nametyper-   )r   r   r   idr   dir
save_modelArtifactadd_filestrlog_artifact)r,   r-   
model_name
model_pathmodel_artifactr   r   r   _checkpoint_artifact?   s   

r=   c                 C   st   t jdu r
t d| jdd}dd t|d |d D }t j|d	d
gd}t jdt jj|d	d
ddidd dS )z-Log feature importance with default settings.Nr.   T)
prettifiedc                 S   s   g | ]\}}||gqS r   r   ).0featfeat_impr   r   r   
<listcomp>^   s    z+_log_feature_importance.<locals>.<listcomp>z
Feature IdImportancesFeature
Importance)r"   columnszFeature Importance)titleFr   )	r   r   r   get_feature_importancezipTabler!   plotbar)r,   feat_dffi_datatabler   r   r   _log_feature_importanceS   s    

rP   TFlog_all_paramssave_model_checkpointlog_feature_importancec                 C   s   t jdu r
t dt| ttfst dt }d|j_	W d   n1 s)w   Y  | 
 }|r:t j| |  t jjd< |  t jjd< |r\|d rSdgnd	g}t| |d
 |rdt|  dS dS )a.  `log_summary` logs useful metrics about catboost model after training is done.

    Args:
        model: it can be CatBoostClassifier or CatBoostRegressor.
        log_all_params: (boolean) if True (default) log the model hyperparameters as W&B config.
        save_model_checkpoint: (boolean) if True saves the model upload as W&B artifacts.
        log_feature_importance: (boolean) if True (default) logs feature importance as W&B bar chart using the default setting of `get_feature_importance`.

    Using this along with `wandb_callback` will:

    - save the hyperparameters as W&B config,
    - log `best_iteration` and `best_score` as `wandb.summary`,
    - save and upload your trained model to Weights & Biases Artifacts (when `save_model_checkpoint = True`)
    - log feature importance plot.

    Example:
        ```python
        train_pool = Pool(train[features], label=train["label"], cat_features=cat_features)
        test_pool = Pool(test[features], label=test["label"], cat_features=cat_features)

        model = CatBoostRegressor(
            iterations=100,
            loss_function="Cox",
            eval_metric="Cox",
        )

        model.fit(
            train_pool,
            eval_set=test_pool,
            callbacks=[WandbCallback()],
        )

        log_summary(model)
        ```
    Nz3You must call `wandb.init()` before `log_summary()`zFModel should be an instance of CatBoostClassifier or CatBoostRegressorTbest_iteration
best_scoreuse_best_modelbestlastr2   )r   r   r   
isinstancer   r   r   r   r   catboost_log_summaryget_all_paramsconfigupdateget_best_iterationsummaryget_best_scorer=   rP   )r,   rQ   rR   rS   r   paramsr-   r   r   r   log_summaryn   s(   
)


rb   )TFT)r)   pathlibr   typesr   typingr   r   catboostr   r   r   wandb.sdk.libr   r   r	   r8   r=   rP   r+   rb   r   r   r   r   <module>   sD    2




