o
    WhS                  	   @   s   d dl mZmZ d dlmZ zerJ ed du sJ d dlZeeds&J i ZW n e	e
fy6   dZY nw dd
dZ								dddZdd Zdd Zdd Zdd Zdd ZergeeeedZdS i ZdS )    )SETTINGSTESTS_RUNNING)model_info_for_loggerswandbTN__version__Precision Recall CurveRecall	Precisionc           
      C   sR   ddl }|||| dd}dddd}|||d	}	tjd
tj|d||	dS )a  
    Create and log a custom metric visualization to wandb.plot.pr_curve.

    This function crafts a custom metric visualization that mimics the behavior of the default wandb precision-recall
    curve while allowing for enhanced customization. The visual metric is useful for monitoring model performance across
    different classes.

    Args:
        x (list): Values for the x-axis; expected to have length N.
        y (list): Corresponding values for the y-axis; also expected to have length N.
        classes (list): Labels identifying the class of each point; length N.
        title (str): Title for the plot; defaults to 'Precision Recall Curve'.
        x_title (str): Label for the x-axis; defaults to 'Recall'.
        y_title (str): Label for the y-axis; defaults to 'Precision'.

    Returns:
        (wandb.Object): A wandb object suitable for logging, showcasing the crafted metric visualization.
    r   N)classyx   r   r   r
   )r   r   r
   )titlezx-axis-titlezy-axis-titlezwandb/area-under-curve/v0)	dataframe)fieldsstring_fields)pandas	DataFrameroundwb
plot_tableTable)
r   r   classesr   x_titley_titler   dfr   r    r   R/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/utils/callbacks/wb.py_custom_table   s   r   precision-recalld   Fc	              	   C   s  ddl }	|du r
g }|	| d | d |d}
|
 }|	|
| |	j|ddd }|rOtjtt	||||gd}tj
|tjj||||di dS d	gt| }t|D ]\}}||
 ||	|
| | ||| gt|
  qZtj|t||||||id
d dS )a  
    Log a metric curve visualization.

    This function generates a metric curve based on input data and logs the visualization to wandb.
    The curve can represent aggregated data (mean) or individual class data, depending on the 'only_mean' flag.

    Args:
        x (np.ndarray): Data points for the x-axis with length N.
        y (np.ndarray): Corresponding data points for the y-axis with shape (C, N), where C is the number of classes.
        names (list): Names of the classes corresponding to the y-axis data; length C.
        id (str): Unique identifier for the logged data in wandb.
        title (str): Title for the visualization plot.
        x_title (str): Label for the x-axis.
        y_title (str): Label for the y-axis.
        num_x (int): Number of interpolated data points for visualization.
        only_mean (bool): Flag to indicate if only the mean curve should be plotted.

    Notes:
        The function leverages the '_custom_table' function to generate the actual visualization.
    r   N   )axisr   )datacolumns)r   meanF)commit)numpylinspacer   tolistinterpr&   r   r   listziprunlogplotlinelen	enumerateextendr   )r   r   namesidr   r   r   num_x	only_meannpx_newx_logy_logtabler   iyir   r   r   _plot_curve/   s   "$
$r@   c                 C   sX   |    D ]#\}}|d }t||kr)tjj|jtt	|i|d |t|< qdS )a  
    Log plots to WandB at a specific step if they haven't been logged already.

    This function checks each plot in the input dictionary against previously processed plots and logs
    new or updated plots to WandB at the specified step.

    Args:
        plots (dict): Dictionary of plots to log, where keys are plot names and values are dictionaries
            containing plot metadata including timestamps.
        step (int): The step/epoch at which to log the plots in the WandB run.

    Notes:
        - The function uses a shallow copy of the plots dictionary to prevent modification during iteration
        - Plots are identified by their stem name (filename without extension)
        - Each plot is logged as a WandB Image object
    	timestampstepN)
copyitems_processed_plotsgetr   r.   r/   stemImagestr)plotsrC   nameparamsrA   r   r   r   
_log_plotse   s    rN   c                 C   sP   t js&t j| jjrt| jjddndt| jjddt| jd dS dS )z6Initiate and start wandb project if module is present./-Ultralytics)projectrL   configN)	r   r.   initargsrR   rJ   replacerL   varstrainerr   r   r   on_pretrain_routine_start}   s   
rZ   c                 C   sn   t jj| j| jd d t| j| jd d t| jj| jd d | jdkr5t jjt| | jd d dS dS )zBLog training metrics and model information at the end of an epoch.   rB   r   N)	r   r.   r/   metricsepochrN   rK   	validatorr   rX   r   r   r   on_fit_epoch_end   s   
r_   c                 C   s`   t jj| j| jdd| jd d t jj| j| jd d | jdkr.t| j| jd d dS dS )z>Log metrics and save images at the end of each training epoch.train)prefixr[   rB   N)	r   r.   r/   label_loss_itemstlossr]   lrrN   rK   rX   r   r   r   on_train_epoch_end   s
   "
re   c              
   C   s   t | jj| jd d t | j| jd d tjddtjj dd}| j	 r6|
| j tjj|dgd | jjrlt| jjd	rlt| jjj| jjjD ]\}}|\}}}}t||t| jjj d
| |||d qLtj  dS )zNSave the best model as an artifact and log final plots at the end of training.r[   rB   modelrun__model)typerL   best)aliasescurves_resultszcurves/)r5   r6   r   r   r   N)rN   r^   rK   r]   r   Artifactr.   r6   rj   existsadd_filelog_artifactrU   hasattrr\   r-   curvesrl   r@   r,   r5   valuesfinish)rY   art
curve_namecurve_valuesr   r   r   r   r   r   r   on_train_end   s&   
	rx   )rZ   re   r_   rx   )r   r   r	   )Nr   r   r   r	   r    F)ultralytics.utilsr   r   ultralytics.utils.torch_utilsr   r   r   rq   rF   ImportErrorAssertionErrorr   r@   rN   rZ   r_   re   rx   	callbacksr   r   r   r   <module>   sF   
 
6
	