o
    mik,                     @   s   d dl mZmZmZmZmZ d dlmZ d dlm	Z	 zd dl
mZ d dlmZmZ W n eyA   d dlmZ d dlmZmZ Y nw d dlmZ d dlZd dlmZ G d	d
 d
Z				ddedee dee deee  dee dee defddZdS )    )AnyCallableDictListOptional)YOLO)BaseTrainer)RANK)	get_flopsget_num_params)ClassificationTrainerN)	telemetryc                   @   s  e Zd ZdZ				d dedee dee deee  dee dee d	dfd
dZ	de
d	dfddZde
d	dfddZde
d	dfddZde
d	dfddZde
d	dfddZde
d	dfddZde
d	dfddZde
d	dfddZed	eeef fddZdS )!WandbCallbacka  An internal YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.

    Usage:
    ```python
    from wandb.integration.yolov8.yolov8 import WandbCallback

    model = YOLO("yolov8n.pt")
    wandb_logger = WandbCallback(
        model,
    )
    for event, callback_fn in wandb_logger.callbacks.items():
        model.add_callback(event, callback_fn)
    ```
    Nyolorun_nameprojecttagsresumekwargsreturnc                 K   s(   || _ || _|| _|| _|| _|| _dS )a  A utility class to manage wandb run and various callbacks for the ultralytics YOLOv8 framework.

        Args:
            yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO`
            run_name, str: The name of the Weights & Biases run, defaults to an auto generated run_name if `trainer.args.name` is not defined.
            project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined.
            tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`.
            resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`.
            **kwargs: Additional arguments to be passed to `wandb.init()`.
        N)r   r   r   r   r   r   )selfr   r   r   r   r   r    r   ]/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/integration/yolov8/yolov8.py__init__"   s   
zWandbCallback.__init__trainerc                 C   s"  t jdu r8t jd| jr| jn|jj| jr| jn|jjpd| jr"| jndgt|j| j	r.| j	ndd| j
| _nt j| _| jdusCJ | jjddd | jjddddd	 | jjd
dddd	 | jjddddd	 | jjddddd	 tjt jd}d|j_W d   dS 1 sw   Y  dS )a'  Starts a new wandb run to track the training process and log to Weights & Biases.

        Args:
            trainer: A task trainer that's inherited from `:class:ultralytics.yolo.engine.trainer.BaseTrainer`
                    that contains the model training and optimization routine.
        NYOLOv8)namer   r   configr   epochT)hiddenztrain/*min)step_metric	step_syncsummaryzval/*z	metrics/*maxzlr/*last)runr   )wandbr&   initr   argsr   r   r   varsr   r   define_metricr   contextfeatureultralytics_yolov8)r   r   telr   r   r   on_pretrain_routine_start<   s<   



"z'WandbCallback.on_pretrain_routine_startc                 C   s8   | j d usJ | j jt|jtt|jdd d S )N   )zmodel/parameterszmodel/GFLOPs)r&   r#   updater   modelroundr
   r   r   r   r   r   on_pretrain_routine_endd   s   z%WandbCallback.on_pretrain_routine_endc                 C   s(   | j dusJ | j d|jd i dS )zJOn train epoch start we only log epoch number to the Weights & Biases run.Nr      )r&   logr   r5   r   r   r   on_train_epoch_startm   s   z"WandbCallback.on_train_epoch_startc                 C   sj   | j dusJ | j i |j|j|jdd|j t|ts3| j ddd |j	dD i dS dS )zFOn train epoch end we log all the metrics to the Weights & Biases run.Ntrain)prefixtrain_batch_imagesc                 S       g | ]}t jt||jd qS )captionr'   Imagestrstem.0
image_pathr   r   r   
<listcomp>       z4WandbCallback.on_train_epoch_end.<locals>.<listcomp>ztrain_batch*.jpg)
r&   r8   metricslabel_loss_itemstlosslr
isinstancer   save_dirglobr5   r   r   r   on_train_epoch_ends   s$   

z WandbCallback.on_train_epoch_endc                    s   | j dusJ  jdkr/ fdddD }|d r|d n|d }|r/| j jdt|di  j jkrM| j jd	 jd id
d  j D  dS dS )z^On fit epoch end we log all the best metrics and model detail to Weights & Biases run summary.Nr   c                    s   g | ]	} j j|qS r   )	validatorspeedget)rE   keyr   r   r   rG      s    z2WandbCallback.on_fit_epoch_end.<locals>.<listcomp>)r7   	inferencer7   zmodel/speed(ms/img)r1   z
best/epochc                 S   s   i | ]
\}}d | |qS )zbest/r   )rE   rT   valr   r   r   
<dictcomp>   s    z2WandbCallback.on_fit_epoch_end.<locals>.<dictcomp>)	r&   r   r#   r2   r4   best_fitnessfitnessrI   items)r   r   speedsrR   r   rU   r   on_fit_epoch_end   s&   



zWandbCallback.on_fit_epoch_endc                 C   s   | j dusJ t|ts/| j dusJ | j dd |jdD dd |jjdD d |j r\| j dus;J | j j	t
|jd| j j d	|jj d
dd|jd  gd dS dS )zgOn train end we log all the media, including plots, images and best model artifact to Weights & Biases.Nc                 S   r=   r>   r@   rD   r   r   r   rG      rH   z.WandbCallback.on_train_end.<locals>.<listcomp>z*.pngc                 S   r=   r>   r@   rD   r   r   r   rG      rH   zval*.jpg)plots
val_imagesr3   _.ptbestepoch_r7   typer   aliases)r&   rM   r   r8   rN   rO   rQ   rb   existslog_artifactrB   r   r)   taskr   r5   r   r   r   on_train_end   s*   



zWandbCallback.on_train_endc                 C   sP   | j dusJ | j jt|jd| j j d|jj ddd|jd  gd dS )	zBOn model save we log the model as an artifact to Weights & Biases.Nr3   r`   ra   r%   rc   r7   rd   )r&   rh   rB   r%   r   r)   ri   r   r5   r   r   r   on_model_save   s   
zWandbCallback.on_model_save_trainerc                 C   s"   | j dusJ | j   d| _ dS )zCOn teardown, we finish the Weights & Biases run and set it to None.N)r&   finish)r   rl   r   r   r   teardown   s   

zWandbCallback.teardownc              	   C   s&   | j | j| j| j| j| j| j| jdS )zgProperty contains all the relevant callbacks to add to the YOLO model for the Weights & Biases logging.r0   r6   r9   rP   r]   rj   rk   rn   ro   )r   r   r   r   	callbacks   s   zWandbCallback.callbacksNNNN)__name__
__module____qualname____doc__r   r   rB   r   r   r   r   r0   r6   r9   rP   r]   rj   rk   rn   propertyr   r   rp   r   r   r   r   r      sB    

(	

r   r   r   r   r   r   r   r   c           	      K   sp   t jddd t jddd tdv r1t| f||||d|}|j D ]
\}}| || q$| S t d | S )a  A YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.

    Args:
        yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO`
        run_name, str: The name of the Weights & Biases run, defaults to an auto generated name if `trainer.args.name` is not defined.
        project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined.
        tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`.
        resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`.
        **kwargs: Additional arguments to be passed to `wandb.init()`.

    Usage:
    ```python
    from wandb.integration.yolov8 import add_callbacks as add_wandb_callbacks

    model = YOLO("yolov8n.pt")
    add_wandb_callbacks(
        model,
    )
    model.train(
        data="coco128.yaml",
        epochs=3,
        imgsz=640,
    )
    ```
    a$  The wandb callback is currently in beta and is subject to change based on updates to `ultralytics yolov8`.
        The callback is tested and supported for ultralytics v8.0.43 and above.
        Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.
        F)repeata  This wandb callback is no longer functional and would be deprecated in the near future.
        We recommend you to use the updated callback using `from wandb.integration.ultralytics import add_wandb_callback`.
        The updated callback is tested and supported for ultralytics 8.0.167 and above.
        You can refer to https://docs.wandb.ai/guides/integrations/ultralytics for the updated documentation.
        Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.
        )r   )r   r   r   r   zThe RANK of the process to add the callbacks was neither 0 or -1.No Weights & Biases callbacks were added to this instance of the YOLO model.)r'   termwarnr	   r   rp   r[   add_callback	termerror)	r   r   r   r   r   r   wandb_loggereventcallback_fnr   r   r   add_callbacks   s.   !
r   rq   )typingr   r   r   r   r   ultralytics.yolo.engine.modelr   ultralytics.yolo.engine.trainerr   ultralytics.yolo.utilsr	   "ultralytics.yolo.utils.torch_utilsr
   r   ModuleNotFoundErrorultralytics.utilsultralytics.utils.torch_utils"ultralytics.yolo.v8.classify.trainr   r'   wandb.sdk.libr   r   rB   r   r   r   r   r   <module>   sD     O
