o
    Ďi                     @  s\   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mZ G dd deZdS )	    )annotationsN)logger)DetectionModel)ObjectPrediction)get_bbox_from_bool_mask$get_coco_segmentation_from_bool_maskc                      sP   e Zd Z fddZdd ZdddZed	d
 ZddggdfdddZ  Z	S )Detectron2DetectionModelc                   s<   t | dd pg }g t|dd| _t j|i | d S )Nrequired_packagestorch
detectron2)getattrlistr	   super__init__)selfargskwargsexisting_packages	__class__ R/home/jeff/fluffinator/venv/lib/python3.10/site-packages/sahi/models/detectron2.pyr      s   z!Detectron2DetectionModel.__init__c              
   C  s  ddl m} ddlm} ddlm} ddlm} | }z|| j	}|
d || || j	|j_W n+ ty` } zt| | j	d urQ|
d || j	 | j|j_W Y d }~nd }~ww | jj|j_| jd urv| j|j_| j|j_||}|| _| jd u rz||jjd }	|	j}
|
| _dd t | jD | _W d S  ty } z2t!"| |jj#d	kr|jj$j%}n|jj&j%}d
d t'|D | _dd t | jD | _W Y d }~d S d }~ww t(| j) | _d S )Nr   )get_cfg)MetadataCatalog)DefaultPredictor)	model_zooTc                 S     i | ]	\}}t ||qS r   str.0indcategory_namer   r   r   
<dictcomp>6       z7Detectron2DetectionModel.load_model.<locals>.<dictcomp>	RetinaNetc                 S  s   g | ]}t |qS r   r   )r    category_idr   r   r   
<listcomp>@   s    z7Detectron2DetectionModel.load_model.<locals>.<listcomp>c                 S  r   r   r   r   r   r   r   r#   A   r$   )*detectron2.configr   detectron2.datar   detectron2.enginer   detectron2.model_zoor   get_config_fileconfig_pathset_new_allowedmerge_from_fileget_checkpoint_urlMODELWEIGHTS	Exceptionprint
model_pathdevicetypeDEVICE
image_sizeINPUTMIN_SIZE_TESTMAX_SIZE_TESTmodelcategory_mappinggetDATASETSTRAINthing_classescategory_names	enumerater   warningMETA_ARCHITECTURE	RETINANETNUM_CLASSES	ROI_HEADSranger   values)r   r   r   r   r   cfgconfig_fileer=   metadatarC   num_categoriesr   r   r   
load_model   sX   









z#Detectron2DetectionModel.load_modelimage
np.ndarrayc                 C  sZ   | j du r	tdt|tjr#| j jdkr#|dddddddf }|  |}|| _dS )a  Prediction is performed using self.model and the prediction result is set to self._original_predictions.

        Args:
            image: np.ndarray
                A numpy array that contains the image to be predicted. 3 channel image should be in RGB order.
        Nz5Model is not loaded, load it by calling .load_model()BGR)r=   RuntimeError
isinstancenpndarrayinput_format_original_predictions)r   rR   prediction_resultr   r   r   perform_inferenceG   s   
	

z*Detectron2DetectionModel.perform_inferencec                 C  s   t | j}|S )zReturns number of categories.)lenr>   )r   rP   r   r   r   rP   [   s   
z'Detectron2DetectionModel.num_categoriesr   Nshift_amount_listlist[list[int]] | Nonefull_shape_listc                   s"  j }t|d tr|g}|durt|d tr|g}|d |du r%dn|d  |d jj}|d j}|d j}z|d j}W n tyK   d}Y nw |j	k}|| }|| }|| }|dure|| }|durz fddt
||||D }	n fddt
|||D }	|	g}
|
_dS )a9  self._original_predictions is converted to a list of prediction.ObjectPrediction and set to
        self._object_prediction_list_per_image.

        Args:
            shift_amount_list: list of list
                To shift the box and mask predictions from sliced image to full sized image, should
                be in the form of List[[shift_x, shift_y],[shift_x, shift_y],...]
            full_shape_list: list of list
                Size of the full image after shifting, should be in the form of
                List[[height, width],[height, width],...]
        r   N	instancesc                   s   g | ]B\}}}}|d u st |   d urt|d u r!| nd |d ur0t|   nd | jt	|  |  dqS N)bboxsegmentationr&   r"   shift_amountscore
full_shape)
r   detachcpunumpyr   tolistr   itemr>   r   )r    boxrg   r&   maskrh   r   rf   r   r   r'      s    
 zeDetectron2DetectionModel._create_object_prediction_list_from_original_predictions.<locals>.<listcomp>c                   sB   g | ]\}}}t | d | jt|  |  dqS rc   )r   rl   rm   r>   r   )r    rn   rg   r&   rp   r   r   r'      s    
)r[   rW   int
pred_boxestensorscorespred_classes
pred_masksAttributeErrorconfidence_thresholdzip!_object_prediction_list_per_image)r   r_   ra   original_predictionsboxesrt   category_idsmaskshigh_confidence_maskobject_prediction_list object_prediction_list_per_imager   rp   r   8_create_object_prediction_list_from_original_predictionsa   s<   





zQDetectron2DetectionModel._create_object_prediction_list_from_original_predictions)rR   rS   )r_   r`   ra   r`   )
__name__
__module____qualname__r   rQ   r]   propertyrP   r   __classcell__r   r   r   r   r      s    
6
r   )
__future__r   rk   rX   sahi.loggerr   sahi.models.baser   sahi.predictionr   sahi.utils.cvr   r   r   r   r   r   r   <module>   s    