o
    ĎiT.                     @  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mZ d dlmZmZ d d	lmZ eg d
 d dlmZ d dlmZ d dlmZ d dlmZ G dd deZG dd de	ZdS )    )annotations)AnyN)logger)DetectionModel)ObjectPrediction)fix_full_shape_listfix_shift_amount_list)get_bbox_from_bool_mask$get_coco_segmentation_from_bool_mask)check_requirements)torchmmdetmmcvmmengine)DetInferencer)
ConfigType)Compose)	ModelTypec                      sB   e Zd Z						dd  fddZd!d"ddZd#ddZ  ZS )$DetInferencerWrapperNr   nonemodelModelType | str | Noneweights
str | Nonedevicescopepalettestr
image_size
int | NonereturnNonec                   s   || _ t ||||| d S )N)r   super__init__)selfr   r   r   r   r   r   	__class__ M/home/jeff/fluffinator/venv/lib/python3.10/site-packages/sahi/models/mmdet.pyr#      s   	zDetInferencerWrapper.__init__   imageslist[np.ndarray]
batch_sizeintdictc           	   	   C  s\   | j ||d}g g d}|D ]\}}| |}| j|dddddd}|d |d  q|S )a@  
        Emulate DetInferencer(images) without progressbar
        Args:
            images: list of np.ndarray
                A list of numpy array that contains the image to be predicted. 3 channel image should be in RGB order.
            batch_size: int
                Inference batch size. Defaults to 1.
        )r,   )predictionsvisualizationNFT)r0   return_datasampleprint_resultno_save_predpred_out_dirr/   )
preprocessforwardpostprocessextend)	r$   r*   r,   inputsresults_dict_datapredsresultsr'   r'   r(   __call__#   s   	

zDetInferencerWrapper.__call__cfgr   r   c                 C  s   |j jj}d|d v rtdd |d d D |d d< | |d}|dkr*tdd|| d< | |d	}|dkr>td
| jdurM| j| jf|| d< t|S )zInitialize the test pipeline.	meta_keysc                 s  s    | ]	}|d kr|V  qdS )img_idNr'   ).0meta_keyr'   r'   r(   	<genexpr>A   s    z6DetInferencerWrapper._init_pipeline.<locals>.<genexpr>LoadImageFromFilez3LoadImageFromFile is not found in the test pipelinezmmdet.InferencerLoadertypeResizez(Resize is not found in the test pipelineNscale)test_dataloaderdatasetpipelinetuple_get_transform_idx
ValueErrorr   r   )r$   r@   pipeline_cfgload_img_idx
resize_idxr'   r'   r(   _init_pipeline;   s   


z#DetInferencerWrapper._init_pipeline)NNNr   r   N)r   r   r   r   r   r   r   r   r   r   r   r   r    r!   )r)   )r*   r+   r,   r-   r    r.   )r@   r   r    r   )__name__
__module____qualname__r#   r?   rT   __classcell__r'   r'   r%   r(   r      s    r   c                      s   e Zd Z											d/d0 fddZdd Zd1ddZd2d!d"Zed#d$ Zed%d& Z	ed'd( Z
d)d)ggdfd3d-d.Z  ZS )4MmdetDetectionModelN      ?333333?Tr   
model_pathr   r   
Any | Noneconfig_pathr   mask_thresholdfloatconfidence_thresholdcategory_mappingdict | Nonecategory_remappingload_at_initboolr   r   r   r   c                   sX   || _ |
| _t| dd pg }g t|ddd| _t |||||||||	|

 d S )Nrequired_packagesr   r   r   )r   r   getattrlistrg   r"   r#   )r$   r\   r   r^   r   r_   ra   rb   rd   re   r   r   existing_packagesr%   r'   r(   r#   S   s    zMmdetDetectionModel.__init__c                 C  s*   t | j| j| j| j| jd}| | dS )z5Detection model is initialized and set to self.model.)r   r   r   N)r   r^   r\   r   r   r   	set_model)r$   r   r'   r'   r(   
load_modelr   s   zMmdetDetectionModel.load_modelr   c                 C  s.   || _ | jsdd t| jD }|| _dS dS )zySets the underlying MMDetection model.

        Args:
            model: Any
                A MMDetection model
        c                 S  s   i | ]	\}}t ||qS r'   )r   )rD   indcategory_namer'   r'   r(   
<dictcomp>   s    z1MmdetDetectionModel.set_model.<locals>.<dictcomp>N)r   rb   	enumeratecategory_names)r$   r   rb   r'   r'   r(   rk   |   s
   	
zMmdetDetectionModel.set_modelimage
np.ndarrayc                 C  sb   | j du r	tdt|tjr|dddddddf }t|ts%|g}|  |}|d | _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()rB   r/   )r   rP   
isinstancenpndarrayri   _original_predictions)r$   rr   
image_listprediction_resultr'   r'   r(   perform_inference   s   
	

z%MmdetDetectionModel.perform_inferencec                 C  s
   t | jS )zReturns number of categories.)lenrq   )r$   r'   r'   r(   num_categories   s   
z"MmdetDetectionModel.num_categoriesc                 C  s`   dd }| j jd d }|d dkr&|d }|D ]}||d r# d	S qd
S ||d r.d	S d
S )zReturns if model output contains segmentation mask.

        Considers both single dataset and ConcatDataset scenarios.
        c                 S  s   t dd | D S )Nc                 s  s0    | ]}t |totd d | D V  qdS )c                 s  s$    | ]\}}d |v o|du V  qdS )maskTNr'   )rD   keyvaluer'   r'   r(   rF      s   " zZMmdetDetectionModel.has_mask.<locals>.check_pipeline_for_mask.<locals>.<genexpr>.<genexpr>N)rt   r.   anyitems)rD   itemr'   r'   r(   rF      s
    
zPMmdetDetectionModel.has_mask.<locals>.check_pipeline_for_mask.<locals>.<genexpr>)r   )rM   r'   r'   r(   check_pipeline_for_mask   s   z=MmdetDetectionModel.has_mask.<locals>.check_pipeline_for_masktrain_dataloaderrL   rH   ConcatDatasetdatasetsrM   TF)r   r@   )r$   r   dataset_configr   rL   r'   r'   r(   has_mask   s   zMmdetDetectionModel.has_maskc                 C  s"   | j j jd }t|tr|fS |S )Nclasses)r   dataset_metart   r   )r$   r   r'   r'   r(   rq      s   
z"MmdetDetectionModel.category_namesr   shift_amount_listlist[list[int]] | Nonefull_shape_listc                 C  sP  z
ddl m} d}W n ty   d}Y nw | j}| j}t|}t|}g }t|D ]\}}	|| }
|du r8dn|| }|	d }|	d }|	d }| jrO|	d	 }g }t	|}t
|D ]}| jrb|| }|| }|| }|| }|t| }|| jk rzqY| jrd
|v r|r||}ntd|}t|du rqYt|}nd}td|d |d< td|d |d< td|d |d< td|d |d< |durt|d |d |d< t|d |d |d< t|d |d |d< t|d |d |d< |d |d k r|d |d k std|  qYt||||||
|d}|| qY|| q*|| _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   )r}   TFNbboxesscoreslabelsmaskscountszRCan not decode rle mask. Please install pycocotools. ex: 'pip install pycocotools'r)         z'ignoring invalid prediction with bbox: )bboxcategory_idscoresegmentationrn   shift_amount
full_shape)pycocotoolsr}   ImportErrorrw   rb   r   r   rp   r   r{   ranger   ra   decoderP   r	   r
   maxminr   warningr   append!_object_prediction_list_per_image)r$   r   r   
mask_utilscan_decode_rleoriginal_predictionsrb    object_prediction_list_per_image	image_indoriginal_predictionr   r   boxesr   r   r   object_prediction_list	n_detectsir}   r   r   r   rn   	bool_maskr   object_predictionr'   r'   r(   8_create_object_prediction_list_from_original_predictions   s   

$	
zLMmdetDetectionModel._create_object_prediction_list_from_original_predictions)NNNNrZ   r[   NNTNr   )r\   r   r   r]   r^   r   r   r   r_   r`   ra   r`   rb   rc   rd   rc   re   rf   r   r   r   r   )r   r   )rr   rs   )r   r   r   r   )rU   rV   rW   r#   rl   rk   rz   propertyr|   r   rq   r   rX   r'   r'   r%   r(   rY   R   s2    






rY   )
__future__r   typingr   numpyru   sahi.loggerr   sahi.models.baser   sahi.predictionr   sahi.utils.compatibilityr   r   sahi.utils.cvr	   r
   sahi.utils.import_utilsr   mmdet.apis.det_inferencerr   mmdet.utilsr   mmengine.datasetr   mmengine.infer.inferr   r   rY   r'   r'   r'   r(   <module>   s     <