o
    miW                     @   sb  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
mZ d dlmZ d dlmZ d dlZdejded	ed
edee f
ddZ	d'dededededeeeef  f
ddZdedededeeef fddZdedeeef fddZ	d'dededeej deejeejeef f fddZ	d'd ed!eded"edejd#ed$ee dejfd%d&ZdS )(    )AnyDictListOptionalTupleUnionN)tqdm)Results)DetectionPredictor)opsboxresized_image_shapeoriginal_image_shape	ratio_padreturnc                 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   f/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/integration/ultralytics/bbox_utils.py*scale_bounding_box_to_original_image_shape   s
   
r   img_idx
image_pathbatchclass_name_mapc                    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>.       z5get_ground_truth_bbox_annotations.<locals>.<dictcomp>r   zImage: z has no bounding boxes labelsF)repeatNc                    s   g | ]}t  | qS r   )str)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   appendint)r   r   r   r   indicesr!   
cls_labelsclass_name_map_reverser   r   r   datar   r,   r   r-   r   !get_ground_truth_bbox_annotations#   sF   

rH   classes
confidenceclass_id_to_labelc           	      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   )r>   rA   rB   r<   sum)	rI   rJ   rK   confidence_map	class_idxconfidence_valueupdated_confidence_mapr,   confidence_listr   r   r   get_mean_confidence_mapW   s   
rS   resultc                 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   )rC   r+   r$   r   r   r   r(   l   s    zget_boxes.<locals>.<dictcomp>r   r#   r1   r2   r3   r7   rJ   )r8   r9   r:   r;   scorespredictionsbox_dataclass_labels)boxesxywhlongnumpyr"   confnamesr>   rS   ranger<   rB   rC   float)rT   rZ   rI   rJ   rK   mean_confidence_maprX   idxr   r   r   	get_boxesg   s4   
rd   
model_nametablec                 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rZ   rV   rX   )tord   r?   Imageorig_imgadd_datar<   speed)rT   re   rf   rZ   rb   imager   r   r   plot_bbox_predictions   s   
(rp   
dataloaderclass_label_map	predictormax_validation_batchesepochc              
   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descrg   rW   rX   )zground-truthrV   ri   N)r<   dataset
batch_sizemin	enumerater   rj   rp   rH   r?   rk   rn   rm   	TypeError)rq   rr   re   rs   rf   rt   ru   data_idxnum_dataloader_batchesr    r   prediction_resultsprogress_bar_result_iterabler   prediction_resultrL   prediction_box_datarb   ground_truth_datawandb_image
table_rowsr   r   r   !plot_detection_validation_results   s^   






r   )N)typingr   r   r   r   r   r   torch	tqdm.autor   ultralytics.engine.resultsr	   ultralytics.models.yolo.detectr
   ultralytics.utilsr   r?   TensorboolrC   r   r+   rH   ra   rS   rd   Tablerk   rp   r   r   r   r   r   <module>   s     

4

"
