a
    yf[                  	   @   s   d dl mZmZ d dlmZ z6er&J ed du s6J d dlZeedsLJ i ZW n e	e
fyl   dZY n0 dd
dZdddZdd Zdd Zdd Zdd Zdd Zereeeedn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, optional): Title for the plot; defaults to 'Precision Recall Curve'.
        x_title (str, optional): Label for the x-axis; defaults to 'Recall'.
        y_title (str, optional): 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)Z	dataframe)fieldsstring_fields)pandasZ	DataFrameroundwbZ
plot_tableTable)
r   r   classesr   x_titley_titler   dfr   r    r   Z/var/www/html/django/DPS/env/lib/python3.9/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 }|rtjtt	||||gd}tj
|tjj||||di nvd	gt| }t|D ]>\}}||
 ||	|
| | ||| gt|
  qt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 CxN, where C is the number of classes.
        names (list, optional): Names of the classes corresponding to the y-axis data; length C. Defaults to [].
        id (str, optional): Unique identifier for the logged data in wandb. Defaults to 'precision-recall'.
        title (str, optional): Title for the visualization plot. Defaults to 'Precision Recall Curve'.
        x_title (str, optional): Label for the x-axis. Defaults to 'Recall'.
        y_title (str, optional): Label for the y-axis. Defaults to 'Precision'.
        num_x (int, optional): Number of interpolated data points for visualization. Defaults to 100.
        only_mean (bool, optional): Flag to indicate if only the mean curve should be plotted. Defaults to True.

    Note:
        The function leverages the '_custom_table' function to generate the actual visualization.
    r   N   )Zaxisr   )datacolumns)r   meanF)commit)numpyZlinspacer   tolistZinterpr"   r   r   listziprunlogZplotlinelen	enumerateextendr   )r   r   namesidr   r   r   Znum_xZ	only_meannpZx_newZx_logZy_logtabler   iyir   r   r   _plot_curve/   s    ""
r4   c                 C   sX   |    D ]F\}}|d }t||krtjj|jtt	|i|d |t|< qdS )z_Logs plots from the input dictionary if they haven't been logged already at the specified step.	timestampstepN)
copyitems_processed_plotsgetr   r(   r)   stemZImagestr)plotsr7   nameparamsr5   r   r   r   
_log_plotse   s
     rA   c                 C   s,   t jp&t j| jjpd| jjt| jd dS )z0Initiate and start project if module is present.ZYOLOv8)projectr?   configN)r   r(   initargsrB   r?   varstrainerr   r   r   on_pretrain_routine_startn   s    rI   c                 C   sj   t jj| j| jd d t| j| jd d t| jj| jd d | jdkrft jjt| | jd d dS )zCLogs training metrics and model information at the end of an epoch.   r6   r   N)	r   r(   r)   metricsepochrA   r>   	validatorr   rG   r   r   r   on_fit_epoch_ends   s
    
rN   c                 C   s\   t jj| j| jdd| jd d t jj| j| jd d | jdkrXt| j| jd d dS )z>Log metrics and save images at the end of each training epoch.train)prefixrJ   r6   N)	r   r(   r)   Zlabel_loss_itemsZtlossrL   lrrA   r>   rG   r   r   r   on_train_epoch_end|   s    "
rR   c              
   C   s   t | jj| jd d t | j| jd d tjddtjj dd}| j	 rl|
| j tjj|dgd t| jjj| jjjD ]>\}}|\}}}}t||t| jjj d	| |||d
 qtj  dS )z6Save the best model as an artifact at end of training.rJ   r6   modelZrun__model)typer?   best)aliaseszcurves/)r.   r/   r   r   r   N)rA   rM   r>   rL   r   ZArtifactr(   r/   rV   existsZadd_fileZlog_artifactr'   rK   ZcurvesZcurves_resultsr4   r&   r.   valuesfinish)rH   artZ
curve_nameZcurve_valuesr   r   r   r   r   r   r   on_train_end   s$    
	r\   )rI   rR   rN   r\   )r   r   r	   )Nr   r   r   r	   r   F)Zultralytics.utilsr   r   Zultralytics.utils.torch_utilsr   r   r   hasattrr:   ImportErrorAssertionErrorr   r4   rA   rI   rN   rR   r\   	callbacksr   r   r   r   <module>   s@   

        
6		