o
    xiK                     @  s   d dl m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
 d dlmZ d dlZd:ddZ	d;d<ddZd=d"d#Zd>d'd(Z	d;d?d-d.Z	d;d@d8d9ZdS )A    )annotations)AnyN)tqdm)Results)DetectionPredictor)opsboxtorch.Tensorresized_image_shapetupleoriginal_image_shape	ratio_padboolreturn	list[int]c                 C  s:   |\}}t j| ||d} t || ||} t | } |  S )a4  YOLOv8 resizes images during training and the label values are normalized based on this resized shape.

    This function rescales the bounding box labels to the original
    image shape.

    Reference: https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/utils/callbacks/comet.py#L105
    )hw)r   
xywhn2xyxyscale_boxes	xyxy2xywhtolist)r   r
   r   r   resized_image_heightresized_image_width r   \/home/ubuntu/.local/lib/python3.10/site-packages/wandb/integration/ultralytics/bbox_utils.py*scale_bounding_box_to_original_image_shape   s
   
r   img_idxint
image_pathstrbatchdictclass_name_maplist[dict[str, Any]]c                   sP  |d | k}|d | }t |d | r |d | d }ng }dd   D }t |dkr>tjd| d	d
d dS t |d | rR|d | d }ng } r_ fdd|D }|d |  }|d |  }	|d |  }
g }t||D ]-\}}t||	||
}|t	|d t	|d gt	|d t	|d dd|| |d qx|S )zdGet ground truth bounding box annotation data in the form required for `wandb.Image` overlay system.	batch_idxbboxescls   c                 S  s   i | ]\}}||qS r   r   .0kvr   r   r   
<dictcomp>0       z5get_ground_truth_bbox_annotations.<locals>.<dictcomp>r   zImage: z has no bounding boxes labelsF)repeatNc                   s   g | ]}t  | qS r   )r   )r)   labelr"   r   r   
<listcomp>>   s    z5get_ground_truth_bbox_annotations.<locals>.<listcomp>	ori_shaperesized_shaper         middlewidthheightpixel)positiondomainclass_idbox_caption)
lensqueezer   itemswandbtermwarnzipr   appendr   )r   r   r    r"   indicesr%   
cls_labelsclass_name_map_reverser   r
   r   datar   r/   r   r0   r   !get_ground_truth_bbox_annotations%   sF   

rJ   classeslist
confidenceclass_id_to_labeldict[str, float]c           	      C  s|   dd |  D }t| |D ]\}}|||  | qi }|  D ]\}}t|dkr7t|t| ||< q"d||< q"|S )zOGet Mean-confidence map from the predictions to be logged into a `wandb.Table`.c                 S  s   i | ]\}}|g qS r   r   )r)   _r+   r   r   r   r,   ]   r-   z+get_mean_confidence_map.<locals>.<dictcomp>r   )rA   rD   rE   r?   sum)	rK   rM   rN   confidence_map	class_idxconfidence_valueupdated_confidence_mapr/   confidence_listr   r   r   get_mean_confidence_mapY   s   
rW   resultr   tuple[dict, dict]c                 C  s   | j j  }| j j  }| j j }dd | j D }t|||}g }t	t
|D ];}|t|| d t|| d gt|| d t|| d ddt|| |t||  d	t|| id
 q.d||di}||fS )z\Convert an ultralytics prediction result into metadata for the `wandb.Image` overlay system.c                 S  s   i | ]\}}t |t|qS r   )r   r   r(   r   r   r   r,   n   s    zget_boxes.<locals>.<dictcomp>r   r'   r4   r5   r6   r:   rM   )r;   r<   r=   r>   scorespredictionsbox_dataclass_labels)boxesxywhlongnumpyr&   confnamesrA   rW   ranger?   rE   r   float)rX   r_   rK   rM   rN   mean_confidence_mapr]   idxr   r   r   	get_boxesi   s4   
ri   
model_nametablewandb.Table | None,wandb.Table | tuple[wandb.Image, dict, dict]c                 C  sx   |  d} t| \}}tj| jdddddddf |d}|dur5|||t|d d || j |S ||d |fS )zxPlot the images with the W&B overlay system.

    The `wandb.Image` is either added to a `wandb.Table` or returned.
    cpuNr_   r[   r]   )tori   rB   Imageorig_imgadd_datar?   speed)rX   rj   rk   r_   rg   imager   r   r   plot_bbox_predictions   s   
(rw   
dataloaderr   class_label_map	predictorr   wandb.Tablemax_validation_batchesepoch
int | Nonec              
   C  s:  d}t | j| j }t||}t| D ]\}	}
||
d }tt|t |d|	d  d| d}|D ]^\}}|d}t||\}}}zDt||
d | |
|}t	j
|
d | ||d|d	 |dd
d}||	|||jg}|durv|g| n|}|g| }|j|  |d7 }W q2 ty   Y q2w |	d |kr |S q|S )z#Plot validation results in a table.r   im_filez$Generating Visualizations for batch-r'   /)totaldescrn   r\   r]   )zground-truthr[   rp   N)r?   dataset
batch_sizemin	enumerater   rq   rw   rJ   rB   rr   ru   rt   	TypeError)rx   ry   rj   rz   rk   r|   r}   data_idxnum_dataloader_batchesr$   r    prediction_resultsprogress_bar_result_iterabler   prediction_resultrP   prediction_box_datarg   ground_truth_datawandb_image
table_rowsr   r   r   !plot_detection_validation_results   s^   






r   )
r   r	   r
   r   r   r   r   r   r   r   )N)
r   r   r   r   r    r!   r"   r!   r   r#   )rK   rL   rM   rL   rN   r!   r   rO   )rX   r   r   rY   )rX   r   rj   r   rk   rl   r   rm   )rx   r   ry   r!   rj   r   rz   r   rk   r{   r|   r   r}   r~   r   r{   )
__future__r   typingr   torch	tqdm.autor   ultralytics.engine.resultsr   ultralytics.models.yolo.detectr   ultralytics.utilsr   rB   r   rJ   rW   ri   rw   r   r   r   r   r   <module>   s"    

4
"