o
    mib!                     @   s   d dl Z d dlZd dlmZmZmZmZmZmZ d dl	Z
d dlmZ d dlZd dlmZ d dlmZ ddlmZ ed Zed	 Ze  G d
d dejZdS )    N)AnyDictListLiteralOptionalUnion)	callbacks)	telemetry)StrPath   )patch_tf_keras)autominmaxepochc                       s   e Zd ZdZ							d!ded	ed
edededede	e
ef dee deddf fddZ	d"dedeeeef  ddfddZd"dedeeeef  ddf fddZ	d"dedeee  ddfddZd#ddZedee fdd Z  ZS )$WandbModelCheckpointah  A checkpoint that periodically saves a Keras model or model weights.

    Saved weights are uploaded to W&B as a `wandb.Artifact`.

    Since this callback is subclassed from `tf.keras.callbacks.ModelCheckpoint`, the
    checkpointing logic is taken care of by the parent callback. You can learn more
    here: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint

    This callback is to be used in conjunction with training using `model.fit()` to save
    a model or weights (in a checkpoint file) at some interval. The model checkpoints
    will be logged as W&B Artifacts. You can learn more here:
    https://docs.wandb.ai/guides/artifacts

    This callback provides the following features:
        - Save the model that has achieved "best performance" based on "monitor".
        - Save the model at the end of every epoch regardless of the performance.
        - Save the model at the end of epoch or after a fixed number of training batches.
        - Save only model weights, or save the whole model.
        - Save the model either in SavedModel format or in `.h5` format.

    Args:
        filepath: (Union[str, os.PathLike]) path to save the model file. `filepath`
            can contain named formatting options, which will be filled by the value
            of `epoch` and keys in `logs` (passed in `on_epoch_end`). For example:
            if `filepath` is `model-{epoch:02d}-{val_loss:.2f}`, then the
            model checkpoints will be saved with the epoch number and the
            validation loss in the filename.
        monitor: (str) The metric name to monitor. Default to "val_loss".
        verbose: (int) Verbosity mode, 0 or 1. Mode 0 is silent, and mode 1
            displays messages when the callback takes an action.
        save_best_only: (bool) if `save_best_only=True`, it only saves when the model
            is considered the "best" and the latest best model according to the
            quantity monitored will not be overwritten. If `filepath` doesn't contain
            formatting options like `{epoch}` then `filepath` will be overwritten by
            each new better model locally. The model logged as an artifact will still be
            associated with the correct `monitor`.  Artifacts will be uploaded
            continuously and versioned separately as a new best model is found.
        save_weights_only: (bool) if True, then only the model's weights will be saved.
        mode: (Mode) one of {'auto', 'min', 'max'}. For `val_acc`, this should be `max`,
            for `val_loss` this should be `min`, etc.
        save_freq: (Union[SaveStrategy, int]) `epoch` or integer. When using `'epoch'`,
            the callback saves the model after each epoch. When using an integer, the
            callback saves the model at end of this many batches.
            Note that when monitoring validation metrics such as `val_acc` or `val_loss`,
            save_freq must be set to "epoch" as those metrics are only available at the
            end of an epoch.
        initial_value_threshold: (Optional[float]) Floating point initial "best" value of the metric
            to be monitored.
    val_lossr   Fr   r   Nfilepathmonitorverbosesave_best_onlysave_weights_onlymode	save_freqinitial_value_thresholdkwargsreturnc	                    s   t  jd||||||||d|	 tjd u rtdtjtjd}
d|
j_W d    n1 s2w   Y  || _	| j
rA|   d | _d S )N)r   r   r   r   r   r   r   r   z<You must call `wandb.init()` before `WandbModelCheckpoint()`)runT )super__init__wandbr   Errorr	   contextfeaturekeras_model_checkpointr   r   _check_filepath_is_old_tf_keras_version)selfr   r   r   r   r   r   r   r   r   tel	__class__r   p/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.pyr    G   s.   	


zWandbModelCheckpoint.__init__batchlogsc                 C   s   |  |r?| jr| j| j|d | j| j|d}n| j| j||d | j| j||d}dd| j d| g}| j||d d S d S )Nr   r.   r   r-   r.   latestepoch__batch_aliases)_should_save_on_batchis_old_tf_keras_version_save_model_current_epoch_get_file_path_log_ckpt_as_artifact)r(   r-   r.   r   r5   r   r   r,   on_train_batch_endm   s   
z'WandbModelCheckpoint.on_train_batch_endc                    sb   t  || | jdkr/| jr| j||d}n| j|d |d}dd| g}| j||d d S d S )Nr   r/   r0   r1   r2   r4   )r   on_epoch_endr   r7   r:   r;   )r(   r   r.   r   r5   r*   r   r,   r=      s   
z!WandbModelCheckpoint.on_epoch_endr5   c                 C   s   z?t jdusJ t jdt jj ddd}tj|r!|| ntj|r-|	| nt
d| t j||p:g d W dS  tyI   Y dS w )z&Log model checkpoint as  W&B Artifact.Nrun__modelmodel)typezNo such file or directory r4   )r!   r   Artifactidospathisfileadd_fileisdiradd_dirFileNotFoundErrorlog_artifact
ValueError)r(   r   r5   model_checkpoint_artifactr   r   r,   r;      s   z*WandbModelCheckpoint._log_ckpt_as_artifactc                 C   sV   g }t  | jD ]}|d d ur||d  q
t|dkr)tjddd d S d S )N   r   zWhen using `save_best_only`, ensure that the `filepath` argument contains formatting placeholders like `{epoch:02d}` or `{batch:02d}`. This ensures correct interpretation of the logged artifacts.F)repeat)string	Formatterparser   appendlenr!   termwarn)r(   placeholderstupr   r   r,   r&      s   
z$WandbModelCheckpoint._check_filepathc                 C   sj   | j d u r2ddlm} z|tjj|dk rd| _ W | j S d| _ W | j S  ty1   d| _ Y | j S w | j S )Nr   )parse_versionz2.6.0TF)r'   
wandb.utilrX   tfkeras__version__AttributeError)r(   rX   r   r   r,   r7      s   
z,WandbModelCheckpoint.is_old_tf_keras_version)r   r   FFr   r   N)N)r   N)__name__
__module____qualname____doc__r
   strintboolModer   SaveStrategyr   floatr   r    r   r<   r=   r   r;   r&   propertyr7   __classcell__r   r   r*   r,   r      sd    5
	
'
(


r   )rD   rP   typingr   r   r   r   r   r   
tensorflowrZ   tensorflow.kerasr   r!   wandb.sdk.libr	   wandb.sdk.lib.pathsr
   r[   r   re   rf   ModelCheckpointr   r   r   r   r,   <module>   s     